{"text": "#include <cmath>\n#include <functional>\n#include <iostream>\n#include <vector>\n#include <catch2/catch.hpp>\n#include <Eigen/Dense>\n#include \"nelder_mead.h\"\n\nTEST_CASE(\"Test Nelder-Mead Optimization\", \"[Helpers][Optimization]\") {\n\n  SECTION(\"Test ability to optimize Rosenbrock function\") {\n    optimization::NelderMead optimizer(1e-6);\n\n    std::function<double(const std::vector<double>&)> rosenbrock =\n        [](const std::vector<double> &points) -> double {\n      double a = 1.0, b = 100.0;\n      return std::pow(a - points[0], 2) +\n             b * std::pow(points[1] - points[0] * points[0], 2);\n    };\n\n    std::vector<double> initial_point = {-10.0, -1.0};\n    double delta = 0.1;\n\n    auto calced_min_location =\n        optimizer.minimize(initial_point, delta, rosenbrock);\n\n    REQUIRE(optimizer.get_minimum() + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_min_location[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_min_location[1] == Approx(1.0).epsilon(0.01));\n  }\n\n  SECTION(\"Test ability to optimize Rosenbrock function\") {\n    optimization::NelderMead optimizer(1e-6);\n\n    std::function<double(const std::vector<double>&)> rosenbrock =\n        [](const std::vector<double> &points) -> double {\n      double a = 1.0, b = 100.0;\n      return std::pow(a - points[0], 2) +\n             b * std::pow(points[1] - points[0] * points[0], 2);\n    };\n\n    std::vector<double> initial_point = {1000.0, -2000.0};\n    std::vector<double> delta = {0.1, 0.2};\n\n    auto calced_min_location =\n        optimizer.minimize(initial_point, delta, rosenbrock);\n\n    REQUIRE(optimizer.get_minimum() + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_min_location[0] == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_min_location[1] == Approx(1.0).epsilon(0.01));\n  }\n}\n", "meta": {"hexsha": "45ab0d4f74d3f43bb741240b85a56dc63fc912cf", "size": 1780, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/optimization_tests.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "test/optimization_tests.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "test/optimization_tests.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 33.5849056604, "max_line_length": 72, "alphanum_fraction": 0.6359550562, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6999816735830003}}
{"text": "#include \"QuinticPolynomial.h\"\n\n#include <Eigen/LU>\n#include <cmath>\n\nusing namespace Eigen;\n\nQuinticPolynomial::QuinticPolynomial(double xs, double vxs, double axs,\n        double xe, double vxe, double axe, double t):\n        a0(xs), a1(vxs) {\n    a2 = axs / 2.0;\n    Matrix3d A;\n    Vector3d B;\n    A << pow(t, 3), pow(t, 4), pow(t, 5), 3 * pow(t, 2),\n    4 * pow(t, 3), 5 * pow(t, 4), 6 * t, 12 * pow(t, 2),\n    20 * pow(t, 3);\n    B << xe - a0 - a1 * t - a2 * pow(t, 2), vxe - a1 - 2 * a2 * t,\n    axe - 2 * a2;\n    Matrix3d A_inv = A.inverse();\n    Vector3d x = A_inv * B;\n    a3 = x[0];\n    a4 = x[1];\n    a5 = x[2];\n}\n\ndouble QuinticPolynomial::calc_point(double t) {\n    return a0 + a1 * t + a2 * pow(t, 2) + a3 * pow(t, 3) +\n    a4 * pow(t, 4) + a5 * pow(t, 5);\n}\n\ndouble QuinticPolynomial::calc_first_derivative(double t) {\n    return a1 + 2 * a2 * t + 3 * a3 * pow(t, 2) + 4 * a4 * pow(t, 3) +\n    5 * a5 * pow(t, 4);\n}\n\ndouble QuinticPolynomial::calc_second_derivative(double t) {\n    return 2 * a2 + 6 * a3 * t + 12 * a4 * pow(t, 2) + 20 * a5 * pow(t, 3);\n}\n\ndouble QuinticPolynomial::calc_third_derivative(double t) {\n    return 6 * a3 + 24 * a4 * t + 60 * a5 * pow(t, 2);\n}", "meta": {"hexsha": "5f5c16a5643727c6c3f4c4b5da1925a79ebba3cc", "size": 1189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_stars_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_stars_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T16:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:56:27.000Z", "max_issues_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_issues_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_issues_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-05-16T11:57:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T07:54:17.000Z", "max_forks_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_forks_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_forks_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2020-04-28T06:02:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:13:23.000Z", "avg_line_length": 28.3095238095, "max_line_length": 75, "alphanum_fraction": 0.5449957948, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6999709165182003}}
{"text": "/*\n DepSpawn: Data Dependent Spawn library\n Copyright (C) 2012-2021 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna\n \n Distributed under the MIT License. (See accompanying file LICENSE)\n*/\n\n///\n/// \\author   Carlos H. Gonzalez  <cgonzalezv@udc.es>\n/// \\author   Basilio B. Fraguela <basilio.fraguela@udc.es>\n///\n\n#include <cstdlib>\n#include <iostream>\n#include <chrono>\n#include <blitz/array.h>\n#include \"depspawn/depspawn.h\"\n#include \"common_io.cpp\"  // This is only for serializing parallel prints\n\nusing namespace depspawn;\nusing namespace blitz;\n\ntypedef float Type;\n\n\n#define N 1000\n\nint CHUNKS;\n\nArray<Type , 2> result(N,N), a(N, N), b(N,N);\n\n//template<typename Type> //IT DOES NOT WORK WITH A TEMPLATED FUNCTION; AND IT SHOULD!\nvoid mxm(Array<Type , 2>& result, const Array<Type , 2>& a, const Array<Type , 2>& b)\n{\n  const int nrows = result.rows();\n  const int ncols = result.cols();\n  const int kdim = a.cols();\n  \n  for(int i = 0; i < nrows; i++) {\n    for(int j = 0; j < ncols; j++) {\n      Type f = (Type)0;\n      for(int k = 0; k < kdim; k++)\n\tf += a(i, k) * b(k, j);\n      result(i, j) = f;\n    }\n  }\n}\n\nbool test()\n{\n  const Type *ap = a.data();\n  const Type *bp = b.data();\n  const Type *rp = result.data();\n  \n  for (int i = 0; i < N; i++) {\n    for(int j = 0; j < N; j++) {\n      Type f = (Type)0;\n      for(int k = 0; k < N; k++)\n\tf += ap[i * N + k] * bp[k * N + j];\n      if (f != rp[i * N + j])\n\treturn false;\n    }\n  }\n  \n  return true;\n}\n\nint main(int argc, char **argv)\n{ int i, j;\n  \n  CHUNKS = (argc == 1) ? 4 : atoi(argv[1]);\n\n  for (i = 0; i < N; i++) {\n    for( j = 0; j < N; j++) {\n      result(i, j) = (Type)0;\n      a(i, j) = i + j;\n      b(i, j) = (i > j) ? i - j : j - i;\n    }\n  }\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t0 = std::chrono::high_resolution_clock::now();\n  \n  mxm(result, a, b);\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t1 = std::chrono::high_resolution_clock::now();\n  \n  //matrix - vector product using CHUNKS chunks\n  for(i = 0; i < N; i += N / CHUNKS) {\n    int limi = (i + N / CHUNKS) >= N ? N : (i + N / CHUNKS);\n    Range rows(i, limi - 1);\n    for(j = 0; j < N; j += N / CHUNKS) {\n      int limj = (j + N / CHUNKS) >= N ? N : (j + N / CHUNKS);\n      Range cols(j, limj - 1);\n      spawn(mxm, result(rows, cols), a(rows, Range::all()), b(Range::all(), cols));\n    }\n  }\n \n  wait_for_all();\n  \n  std::chrono::time_point<std::chrono::high_resolution_clock> t2 = std::chrono::high_resolution_clock::now();\n  \n  double serial_time = std::chrono::duration<double>(t1-t0).count();\n  double parallel_time = std::chrono::duration<double>(t2-t1).count();\n  \n  std::cout << \"Serial time: \" << serial_time << \"s.  Parallel time: \" << parallel_time << \"s.\\n\";\n  std::cout << \"Speedup (using \" << CHUNKS << \" X \" << CHUNKS << \" chunks): \" <<  (serial_time / parallel_time) << std::endl;\n  \n  const bool test_ok = test();\n  \n  std::cout << \"TEST \" << (test_ok ? \"SUCCESSFUL\" : \"UNSUCCESSFUL\") << std::endl;\n  \n  return !test_ok;\n}\n", "meta": {"hexsha": "084952f7fb27e25b0427a46bde611cc21c220e5f", "size": 3040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/mxm.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": "tests/mxm.cpp", "max_issues_repo_name": "fraguela/depspawn", "max_issues_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/mxm.cpp", "max_forks_repo_name": "fraguela/depspawn", "max_forks_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 125, "alphanum_fraction": 0.5723684211, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6999548080591087}}
{"text": "/*\n *  Distributed under our modified Boost Software License.\n *  Version 1.0 (see accompanying file LICENSE)\n */\n/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/. */\n/**\n *  @file       Robot.cpp\n *  @author     Lydia Zoghbi, Ari Kupferberg, Ryan Bates\n *  @copyright  Copyright ARL 2019\n *  @date       10/19/2019\n *  @version    1.0\n *\n *  @brief      Definitions for Robot.hpp \n *\n */\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/SVD>\n#include <math.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include \"Robot.hpp\"\n#include <RobotPosition.hpp>\n#include <RobotPath.hpp>\n#include <Point.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nRobot::Robot(const Point& startingPos): initialEEPosition(startingPos) {\n}\n\nboost::numeric::ublas::matrix<double> Robot::computeATransform(std::vector<double> dhRow) {\n\n  // Initializing parameters\n  double a = dhRow[0];\n  double alpha = dhRow[1];\n  double d = dhRow[2];\n  double theta = dhRow[3];\n  boost::numeric::ublas::matrix<double> aTransform(4, 4);\n\n  // Initialize 'A' matrix variables\n  std::vector<double> aTerms = {cos(theta), -sin(theta)*cos(alpha),\n     sin(theta)*sin(alpha), a*cos(theta), sin(theta), cos(theta)*cos(alpha),\n     -cos(theta)*sin(alpha), a*sin(theta), 0, sin(alpha), cos(alpha), d, 0,\n     0, 0, 1};\n\n  int i = 0;\n  int j = 0;\n\n  // Populate the A transformation matrix\n  for (auto& term: aTerms) {\n    aTransform(i, j) = term;\n    j++;\n    if (j == 4) {\n      i++;\n      j = 0;\n    }\n  }\n  return aTransform;\n}\n\nstd::vector<Point> Robot::computeFk(std::vector<double> jointAngles) {\n  int i = 0;\n  for (auto& element : jointAngles) {\n    dhParams[i][3] = element + dhParams[i][3];\n    i++;\n  }\n\n  // Initialize Matrices\n  boost::numeric::ublas::matrix<double> aTransform(4, 4);\n  boost::numeric::ublas::matrix<double> tTransform(4, 4);\n  boost::numeric::ublas::matrix<double> previousTransform(4, 4);\n  boost::numeric::ublas::identity_matrix<double> identity(4, 4);\n  previousTransform = identity;\n\n  // Loop through A matrices to get T matrices\n  std::vector<boost::numeric::ublas::matrix<double>> tTransforms;\n  for (auto& row : dhParams) {\n    aTransform = computeATransform(row);\n      tTransform = prod(previousTransform, aTransform);\n      previousTransform = tTransform;\n      tTransforms.push_back(tTransform);\n  }\n\n  // Pull points from T matrices\n  Point initialPoint(0.0, 0.0, 0.0);\n  std::vector<Point> points = {initialPoint};\n  for (auto& p : tTransforms) {\n     Point point(p(0, 3), p(1, 3), p(2, 3));\n     points.push_back(point);\n  }\n  return points;\n}\n\nboost::numeric::ublas::vector<double> Robot::crossProduct(boost::numeric::ublas::vector<double> vector1, boost::numeric::ublas::vector<double> vector2) {\n\n  // Cross product function because there was no easy way to get it done through Boost\n  boost::numeric::ublas::vector<double> resultVector(3);\n  resultVector(0) = vector1(1)*vector2(2)-vector1(2)*vector2(1);\n  resultVector(1) = vector1(2)*vector2(0)-vector1(0)*vector2(2);\n  resultVector(2) = vector1(0)*vector2(1)-vector1(1)*vector2(0);\n  return resultVector;\n}\n\nstd::vector<boost::numeric::ublas::matrix<double>> Robot::computeTransformationMatrices(std::vector<double> jointAngles) {\n\n int i = 0;\n  for (auto& element : jointAngles) {\n    dhParams[i][3] = element + dhParams[i][3];\n    i++;\n  }\n\n  // Initialize Matrices\n  boost::numeric::ublas::matrix<double> aTransform(4, 4);\n  boost::numeric::ublas::matrix<double> tTransform(4, 4);\n  boost::numeric::ublas::matrix<double> previousTransform(4, 4);\n  boost::numeric::ublas::identity_matrix<double> identity(4, 4);\n  previousTransform = identity;\n\n  // Loop through A matrices to get T matrices\n  std::vector<boost::numeric::ublas::matrix<double>> tTransforms;\n  tTransforms.push_back(identity);\n  for (auto& row : dhParams) {\n    aTransform = computeATransform(row);\n    tTransform = prod(previousTransform, aTransform);\n    previousTransform = tTransform;\n    tTransforms.push_back(tTransform);\n  }\n return tTransforms;\n}\n\nboost::numeric::ublas::matrix<double> Robot::computeJacobian(RobotPosition robotPosition, std::vector<boost::numeric::ublas::matrix<double>> tTransforms) {\n\n  // Get all the joint positions in Point\n  std::vector<Point> joints = robotPosition.getJoints();\n  boost::numeric::ublas::vector<double> zAxes(3);\n  zAxes(0) = 0;\n  zAxes(1) = 0;\n  zAxes(2) = 1;\n\n  // Initialize some parameteres\n  boost::numeric::ublas::matrix<double> jacobian(6,6);\n  std::vector<double> iterator = {0, 1, 2};\n  boost::numeric::ublas::matrix<double> trans(3,3);\n\n  int index = 0;\n  Point robotEEPosition = joints[6];\n  joints.pop_back();\n\n  // Loop through the joints to compute the Jacobian\n  for (auto& joint : joints) {\n    Point robotJointPosition = joint;\n    double differenceInX = robotEEPosition.getX() - robotJointPosition.getX();\n    double differenceInY = robotEEPosition.getY() - robotJointPosition.getY();\n    double differenceInZ = robotEEPosition.getZ() - robotJointPosition.getZ();\n    boost::numeric::ublas::vector<double> differenceVector(3);\n    differenceVector(0) = differenceInX;\n    differenceVector(1) = differenceInY;\n    differenceVector(2) = differenceInZ;\n\n    trans(0,0) = tTransforms[index](0,0); trans(0,1) = tTransforms[index](0,1);\n    trans(0,2) = tTransforms[index](0,2); trans(1,0) = tTransforms[index](1,0);\n    trans(1,1) = tTransforms[index](1,1); trans(1,2) = tTransforms[index](1,2);\n    trans(2,0) = tTransforms[index](2,0); trans(2,1) = tTransforms[index](2,1);\n    trans(2,2) = tTransforms[index](2,2);\n    boost::numeric::ublas::vector<double> transformedZAxes = prod(trans,zAxes);\n    boost::numeric::ublas::vector<double> crossProductVector = crossProduct(transformedZAxes, differenceVector);\n\n    // Populate the Jacobian's columns iteratively\n    for (auto& element : iterator) {\n      jacobian(element, index) = crossProductVector(element);\n      jacobian(element+3, index) = transformedZAxes(element);\n    }\n    index++;\n  }\n  return jacobian;\n}\n\n// https://gist.github.com/javidcf/25066cf85e71105d57b6 used as reference\nboost::numeric::ublas::matrix<double> Robot::penroseInverseMatrix(boost::numeric::ublas::matrix<double> mat) {\n  boost::numeric::ublas::matrix<double> result(mat.size1(), mat.size2());\n\n  Eigen::MatrixXd convertedInput(mat.size1(), mat.size2());\n\n  // Convert from boost matrix to eigen matrix\n  // we permit ourselves to use int for loops\n  // because the indexing is useful for referencing between datatypes\n  for (unsigned int rowIndex = 0; rowIndex < mat.size1(); rowIndex++) {\n    for (unsigned int columnIndex = 0; columnIndex < mat.size2(); columnIndex++) {\n      convertedInput(rowIndex, columnIndex) = mat(rowIndex, columnIndex);\n    }\n  }\n\n  // Now for the actual math\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(convertedInput, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  // We can safely use adjoint instead of transpose because this is a real matrix\n  Eigen::MatrixXd sigma = svd.singularValues().asDiagonal();\n\n  double tolerance = 0.001;\n  // Take the reciprocal of each element, if possible,\n  // as per https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse\n  // We only hit the diagonal, since this is a diagonal matrix.\n  // We allow this loop type because the indexing is useful.\n  for (int i = 0; i < sigma.rows(); i++) {\n    if (fabs(sigma(i, i)) < tolerance) {\n      sigma(i, i) = 0;\n    } else {\n      sigma(i, i) = 1 / sigma(i, i);\n    }\n  }\n\n  Eigen::MatrixXd sigmaTransposed = sigma.transpose();\n  Eigen::MatrixXd eigenResult = svd.matrixV() * sigmaTransposed * svd.matrixU().adjoint();\n\n  // Convert eigen matrix to boost matrix\n  // We permit ourselves to use int for loops\n  // because the indexing is useful for referencing between datatypes\n  for (unsigned int rowIndex = 0; rowIndex < mat.size1(); rowIndex++) {\n    for (unsigned int columnIndex = 0; columnIndex < mat.size2(); columnIndex++) {\n      result(rowIndex, columnIndex) = static_cast<double>(eigenResult(rowIndex, columnIndex));\n    }\n  }\n  return result;\n}\n\nstd::vector<RobotPosition> Robot::computeIK(Point targetPoint, Environment environment) {\n\n  // Initialize the angles vector theta\n  std::vector<RobotPosition> allRobotPositions;\n  boost::numeric::ublas::vector<double> velocity(6);\n  boost::numeric::ublas::vector<double> theta(6);\n  theta(0) = initialJointAngles[0]; theta(1) = initialJointAngles[1]; theta(2) = initialJointAngles[2];\n  theta(3) = initialJointAngles[3]; theta(4) = initialJointAngles[4]; theta(5) = initialJointAngles[5];\n\n  std::vector<double> jointAngles = initialJointAngles;\n\n  std::vector<Point> robotJointPosition = computeFk(jointAngles);\n  Point eePosition = robotJointPosition.back();\n  PathPlanner pathPlanner;\n  std::vector<Point> getPath = pathPlanner.findStraightPath(eePosition, targetPoint);\n\n  double eeX; double eeY; double eeZ;\n  double targetX; double targetY; double targetZ;\n  double norm;\n  int counter = 0;\n\n  for(auto& pathPoints:getPath) {\n\n    // Extact each point from a discretized path to find joint angles\n    robotJointPosition = computeFk(jointAngles);\n    eePosition = robotJointPosition.back();\n    eeX = eePosition.getX(); eeY = eePosition.getY(); eeZ = eePosition.getZ();\n    targetX = pathPoints.getX(); targetY = pathPoints.getY(); targetZ = pathPoints.getZ();\n    velocity(0) = targetX - eeX; velocity(1) = targetY - eeY; velocity(2) = targetZ - eeZ;\n    velocity(3) = 0.0; velocity(4) = 0.0; velocity(5) = 0.0;\n    norm = norm_2(velocity);\n    counter++;\n\n    // Loop through each point to compute the inverse kinematics using the pseudo-inverse Jacobian\n    while (norm > 0.01) {\n\n      robotJointPosition = computeFk(jointAngles);\n      RobotPosition robotPosition(robotJointPosition, jointAngles);\n      std::vector<boost::numeric::ublas::matrix<double>> tTrans = computeTransformationMatrices(jointAngles);\n      boost::numeric::ublas::matrix<double> jacobian = computeJacobian(robotPosition, tTrans);\n      boost::numeric::ublas::matrix<double> pseudoInverse = penroseInverseMatrix(jacobian);\n      Point eePosition = robotJointPosition.back();\n\n      eeX = eePosition.getX(); eeY = eePosition.getY(); eeZ = eePosition.getZ();\n      targetX = pathPoints.getX(); targetY = pathPoints.getY(); targetZ = pathPoints.getZ();\n      velocity(0) = targetX - eeX; velocity(1) = targetY - eeY; velocity(2) = targetZ - eeZ;\n      velocity(3) = 0.0; velocity(4) = 0.0; velocity(5) = 0.0;\n      norm = norm_2(velocity);\n\n      boost::numeric::ublas::vector<double> deltaTheta = prod(pseudoInverse, velocity);\n      theta = theta + 0.0000001*deltaTheta;\n      jointAngles[0] = theta(0); jointAngles[1] = theta(1); jointAngles[2] = theta(2);\n      jointAngles[3] = theta(3); jointAngles[4] = theta(4); jointAngles[5] = theta(5);\n\n    }\n\n    RobotPosition robotPosition(robotJointPosition, jointAngles);\n\n    // Check for any collision\n    if (robotPosition.checkCollision(environment)) {\n      allRobotPositions.push_back(robotPosition);\n    } else {break;}\n  }\n\nreturn allRobotPositions;\n\n}\n\n", "meta": {"hexsha": "656585756f8b85b34f8ec3143fb5432f52d69d36", "size": 11176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/Robot.cpp", "max_stars_repo_name": "akupferb/808xmidterm", "max_stars_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "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": "app/Robot.cpp", "max_issues_repo_name": "akupferb/808xmidterm", "max_issues_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "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": "app/Robot.cpp", "max_forks_repo_name": "akupferb/808xmidterm", "max_forks_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-13T22:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-13T22:46:15.000Z", "avg_line_length": 37.6296296296, "max_line_length": 155, "alphanum_fraction": 0.6913922691, "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6999434759866942}}
{"text": "#include \"common.h\"\n#include <cmath>\n#include <ctime>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n\nboost::random::mt19937 rng(time(0));\nboost::random::uniform_01<float_type> dist01;\n\n// calculate digamma(x+n) - digamma(x) = \\sum 1/(x+k), k=0,1,...n-1\nfloat_type digammaDiff(float_type x, int n)\n{\n    float_type ret = 0.0;\n\n    for (int i = n - 1; i >= 0; i--) {\n        ret += 1.0/(x + i);\n    }\n\n    return ret;\n}\n\nfloat_type GegenbauerDAlphaAt0(int n, float_type x)\n{\n    if (n <= 0) {\n        return 0.0;\n    } else if (n == 1) {\n        return 2 * x;\n    } else if (n == 2) {\n        return 2 * x * x - 1;\n    }\n\n    // for -1 < x < 1 it actually equals \n    // return 2 * cos(n * acos(x)) / n;\n\n    float_type a = 2 * x, b = 2 * x * x - 1;\n    float_type c;\n    for (int i = 3; i <= n; i++) {\n        c = (2 * (i - 1) * x * b - (i - 2) * a) / i;\n        a = b; \n        b = c;\n    }\n\n    return c;\n}\n\nbool IsInteger(float_type n)\n{\n    return std::abs(n - floor(n + EPS)) < EPS;\n}\n\nfloat_type random(float_type min, float_type max)\n{\n    return min + (max - min) * dist01(rng);\n}\n\nint randomint(int min, int max)\n{\n    boost::random::uniform_int_distribution<int> dist(min,max);\n    return dist(rng);\n}\n\ncpx_t RandomComplex(float_type maxNorm)\n{\n    float_type r = random(0.0, maxNorm);\n    float_type theta = random(0.0, 2 * acos(-1.0));\n    return cpx_t(r * cos(theta), r * sin(theta));\n}\n\nstd::string NowToString()\n{\n    time_t rawtime;\n    struct tm * timeinfo;\n    char buffer[80];\n\n    time (&rawtime);\n    timeinfo = localtime(&rawtime);\n\n    strftime(buffer,sizeof(buffer),\"%Y-%m-%d %I:%M:%S\",timeinfo);\n    return std::string(buffer);\n}\n", "meta": {"hexsha": "6ca27edf72d75bff7b02e5e984933be9bf3886f1", "size": 1745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common.cpp", "max_stars_repo_name": "gaolichen/cftbtsp", "max_stars_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common.cpp", "max_issues_repo_name": "gaolichen/cftbtsp", "max_issues_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.cpp", "max_forks_repo_name": "gaolichen/cftbtsp", "max_forks_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2804878049, "max_line_length": 67, "alphanum_fraction": 0.5713467049, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278695464501, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6998587861974556}}
{"text": "//\n//  seqols.cpp\n//\n//\n// Created by Jose V. Alcala Burgos on 7/30/13.\n//  Copyright [2013] Jose V. Alcala Burgos\n//\n//\n\n#include \"base/seqols.h\"\n\n// System\n#include <armadillo>\n\n#include <iostream>\n#include <cmath>\n\nusing namespace arma;\nusing namespace std;\n\nvoid SeqOls::useObservations(mat X, mat Y  // A n x p matrix with n responses,\n                                           // one response per row\n                             ) {\n    if (X.size() != Y.size()) {\n        cout << \" The predictor/response matrices should have the same size\";\n        cout << endl;\n    }\n\n    n = X.n_rows;\n    p = X.n_cols;\n    X = join_rows(X, ones(n, 1));\n    P = inv((X.t()) * X);\n    B = P * (X.t() * Y);\n    G = inv(B.rows(0, p - 1));\n}\n\nvoid SeqOls::addObservation(mat x,\n                            mat y\n                            ) {\n    if (x.size() != y.size()) {\n        cout << \" The predictor/response matrices should have the same size\";\n        cout << endl;\n    }\n\n    if (x.n_cols != p) {\n        cout << \" The new observation should have \" << p << \"columns\" << endl;\n    }\n\n    if (x.n_rows != 1) {\n        cout << \" Add only ONE observation. \" << endl;\n    }\n\n    n = n + 1;\n    x = join_rows(x, ones(1, 1));\n    double alpha;\n    alpha = as_scalar((1.0 / (1.0 + x * P * x.t())));\n    mat u = P * x.t();\n    u = u.rows(0, p - 1);\n    u = alpha * u;\n    mat v = y - x * B;\n    v = v.t();\n    B = B + alpha * (P * x.t() * (y - x * B));\n    P = P - alpha * (P * x.t() * x * P.t());\n    double beta;\n    beta = as_scalar(1.0 / (1.0 + v.t() * G * u));\n    G = G - beta * (G * u * v.t() * G);\n}\n\n// Prints the Ols estimator\nvoid SeqOls::printEstimator() {\n    B.print(\" B_estimator : \");\n    G.print(\"G_estimator (Hessian inverse):\");\n}\n\n// Tests that the inverse of the first p rows of B is equal to G.\nvoid SeqOls::testInverse() {\n    double tolerance = 0.00000001;\n    mat error = (B.rows(0, p - 1) * G - eye<mat>(p, p));\n    if (norm(error, 2) < tolerance) {\n        cout << \"The inverse of the estimator is correct.\" << endl;\n    } else {\n        cout << \"The inverse of the estimator is incorrect.\" << endl;\n    }\n}\n", "meta": {"hexsha": "59b9b59a9a1b1c976ed32ee2158753d2b897ec22", "size": 2129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/seqols.cpp", "max_stars_repo_name": "vidalalcala/sopt-ols", "max_stars_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_stars_repo_licenses": ["MIT"], "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/seqols.cpp", "max_issues_repo_name": "vidalalcala/sopt-ols", "max_issues_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_issues_repo_licenses": ["MIT"], "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/seqols.cpp", "max_forks_repo_name": "vidalalcala/sopt-ols", "max_forks_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_forks_repo_licenses": ["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.0470588235, "max_line_length": 78, "alphanum_fraction": 0.4922498826, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6998587782514756}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/math/math_eigen_system_decomposition.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <cmath>\n\nusing namespace OpenTissue;\n\ntemplate<typename vector3_type,typename matrix3x3_type>\nvoid eigen_value_decomposition_test(vector3_type d,matrix3x3_type R)\n{\n  using std::fabs;\n\n  typedef typename vector3_type::value_type    real_type;\n  typedef typename vector3_type::value_traits  value_traits;\n\n  real_type tol = 0.0001;\n\n  vector3_type r1 = vector3_type(R(0,0),R(1,0),R(2,0));\n  vector3_type r2 = vector3_type(R(0,1),R(1,1),R(2,1));\n  vector3_type r3 = vector3_type(R(0,2),R(1,2),R(2,2));\n  real_type    d0 = d(0);\n  real_type    d1 = d(1);\n  real_type    d2 = d(2);\n\n  matrix3x3_type D = diag(d);\n  matrix3x3_type A = R*D*trans(R);\n  BOOST_CHECK( is_symmetric(A,tol) );\n\n  matrix3x3_type V;\n  OpenTissue::math::eigen(A, V, d);\n\n  vector3_type e1 = vector3_type(V(0,0),V(1,0),V(2,0));\n  vector3_type e2 = vector3_type(V(0,1),V(1,1),V(2,1));\n  vector3_type e3 = vector3_type(V(0,2),V(1,2),V(2,2));\n\n  real_type determinant = det(V);\n  BOOST_CHECK_CLOSE( fabs( determinant ), value_traits::one(), tol );\n\n  real_type epsilon = 10e-7;\n\n  matrix3x3_type Itest = trans(V)*V;\n\n  BOOST_CHECK_CLOSE( Itest(0,0), value_traits::one() , tol );\n  BOOST_CHECK_CLOSE( Itest(1,1), value_traits::one() , tol );\n  BOOST_CHECK_CLOSE( Itest(2,2), value_traits::one() , tol );\n  //--- The check close versin behaves strange when rhs is exactly\n  //--- zero?, so I use the check-version instead...\n  //BOOST_CHECK_CLOSE(      Itest(0,1) , value_traits::zero(), tol );\n  //BOOST_CHECK_CLOSE(      Itest(0,2) , value_traits::zero(), tol );\n  //BOOST_CHECK_CLOSE(      Itest(1,0) , value_traits::zero(), tol );\n  //BOOST_CHECK_CLOSE(      Itest(1,2) , value_traits::zero(), tol );\n  //BOOST_CHECK_CLOSE(      Itest(2,0) , value_traits::zero(), tol );\n  //BOOST_CHECK_CLOSE(      Itest(2,1) , value_traits::zero(), tol );\n  BOOST_CHECK( fabs(Itest(0,1))<epsilon );\n  BOOST_CHECK( fabs(Itest(0,2))<epsilon );\n  BOOST_CHECK( fabs(Itest(1,0))<epsilon );\n  BOOST_CHECK( fabs(Itest(1,2))<epsilon );\n  BOOST_CHECK( fabs(Itest(2,0))<epsilon );\n  BOOST_CHECK( fabs(Itest(2,1))<epsilon );\n\n  matrix3x3_type Atest = A - V*diag(d)*trans(V);\n\n  BOOST_CHECK( fabs(Atest(0,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(0,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(0,2))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(1,2))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,0))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,1))<epsilon );\n  BOOST_CHECK( fabs(Atest(2,2))<epsilon );\n\n  bool match1 = fabs( d0 - d(0) ) < epsilon &&  \n                fabs( d1 - d(1) ) < epsilon &&\n                fabs( d2 - d(2) ) < epsilon ;\n\n  bool match2 = fabs( d0 - d(0) )< epsilon &&\n                fabs( d1 - d(2) )< epsilon &&\n                fabs( d2 - d(1) )< epsilon ;\n\n  bool match3 = fabs( d0 - d(1) )< epsilon &&\n                fabs( d1 - d(0) )< epsilon &&\n                fabs( d2 - d(2) )< epsilon ;\n\n  bool match4 = fabs( d0 - d(1) )< epsilon &&\n                fabs( d1 - d(2) )< epsilon &&\n                fabs( d2 - d(0) )< epsilon ;\n\n  bool match5 = fabs( d0 - d(2) )< epsilon &&\n                fabs( d1 - d(0) )< epsilon &&\n                fabs( d2 - d(1) )< epsilon ;\n\n  bool match6 = fabs( d0 - d(2) )< epsilon &&\n                fabs( d1 - d(1) )< epsilon &&\n                fabs( d2 - d(0) )< epsilon ;\n\n  BOOST_CHECK( match1 || match2 || match3 || match4 || match5 || match6 );\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_eigen);\n\n  BOOST_AUTO_TEST_CASE(random_testing)\n  {\n    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n    typedef math_types::vector3_type                         vector3_type;\n    typedef math_types::matrix3x3_type                       matrix3x3_type;\n    typedef math_types::real_type                            real_type;\n\n    matrix3x3_type R;\n    vector3_type d;\n\n    for(int i= 0;i<100;++i)\n    {\n      //--- non-negative eigen-values\n      random(d,0,1);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- non-positive eigen-values\n      random(d,-1,0);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      random(d,0,1);\n      d(0) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      random(d,0,1);\n      d(1) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- one zero eigen-values\n      random(d,0,1);\n      d(2) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      random(d,0,1);\n      d(0) = 0;\n      d(1) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      random(d,0,1);\n      d(0) = 0;\n      d(2) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- two zero eigen-values\n      random(d,0,1);\n      d(1) = 0;\n      d(2) = 0;\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- three zero eigen-values\n      d.clear();\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 3\n      random(d,0,1);\n      d(1) = d(0);\n      d(2) = d(0);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      random(d,0,1);\n      d(1) = d(0);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      random(d,0,1);\n      d(2) = d(0);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n\n      //--- multiplicity of 2\n      random(d,0,1);\n      d(2) = d(1);\n      random(R);\n      R = ortonormalize(R);\n      eigen_value_decomposition_test(d,R);\n    }\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "9147e986432f6580e578214c02385ca5010044cb", "size": 6660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/eigen/src/unit_eigen.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/eigen/src/unit_eigen.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/eigen/src/unit_eigen.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 29.865470852, "max_line_length": 78, "alphanum_fraction": 0.5987987988, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6997915044898383}}
{"text": "\r\n#include <NTL/HNF.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n// This implements a variation of an algorithm in\r\n// [P. Domich, R. Kannan and L. Trotter, Math. Oper. Research 12:50-59, 1987].\r\n// I started with the description in Henri Cohen's book, but had to modify\r\n// that because Cohen does not actually keep the numbers reduced modulo\r\n// the determinant, which leads to larger than necessary numbers.\r\n// This modifiaction was put in place in v3.9b.\r\n\r\nstatic\r\nvoid EuclUpdate(vec_ZZ& u, vec_ZZ& v, \r\n                const ZZ& a, const ZZ& b, const ZZ& c, const ZZ& d,\r\n                const ZZ& M)\r\n\r\n{\r\n   long m = u.length(); \r\n   long i;\r\n\r\n   ZZ M1;\r\n   RightShift(M1, M, 1);\r\n\r\n   ZZ t1, t2, t3;\r\n\r\n   for (i = 1; i <= m; i++) {\r\n      mul(t1, u(i), a);\r\n      mul(t2, v(i), b);\r\n      add(t1, t1, t2);\r\n      rem(t1, t1, M);\r\n      if (t1 > M1)\r\n         sub(t1, t1, M);\r\n\r\n      t3 = t1;\r\n\r\n      mul(t1, u(i), c);\r\n      mul(t2, v(i), d);\r\n      add(t1, t1, t2);\r\n      rem(t1, t1, M);\r\n      if (t1 > M1)\r\n         sub(t1, t1, M);\r\n\r\n      u(i) = t3;\r\n      v(i) = t1;\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nvoid FixDiag(vec_ZZ& u, const ZZ& a, const vec_ZZ& v, const ZZ& M, long m)\r\n{\r\n   long i;\r\n   ZZ t1;\r\n\r\n   for (i = 1; i <= m; i++) {\r\n      mul(t1, a, v(i));\r\n      rem(u(i), t1, M);\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nvoid ReduceW(vec_ZZ& u, const ZZ& a, const vec_ZZ& v, const ZZ& M, long m)\r\n{\r\n   long i;\r\n   ZZ t1, t2;\r\n\r\n   for (i = 1; i <= m; i++) {\r\n      mul(t1, a, v(i));\r\n      sub(t2, u(i), t1);\r\n      rem(u(i), t2, M);\r\n   }\r\n}\r\n   \r\n\r\n\r\nvoid HNF(mat_ZZ& W, const mat_ZZ& A_in, const ZZ& D_in)\r\n{\r\n   mat_ZZ A = A_in;\r\n\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   ZZ D = D_in;\r\n   if (D < 0)\r\n      negate(D, D);\r\n\r\n   if (n == 0 || m == 0 || D == 0)\r\n      LogicError(\"HNF: bad input\");\r\n\r\n   W.SetDims(m, m);\r\n   clear(W);\r\n\r\n   long i, j, k;\r\n   ZZ d, u, v, c1, c2;\r\n\r\n   k = n;\r\n\r\n   for (i = m; i >= 1; i--) {\r\n      for (j = k-1; j >= 1; j--) {\r\n         if (A(j, i) != 0) {\r\n            XGCD(d, u, v, A(k, i), A(j, i));\r\n            div(c1, A(k, i), d);\r\n            div(c2, A(j, i), d);\r\n            negate(c2, c2);\r\n            EuclUpdate(A(j), A(k), c1, c2, v, u, D);\r\n         }\r\n      }\r\n\r\n      XGCD(d, u, v, A(k, i), D);\r\n      FixDiag(W(i), u, A(k), D, i);\r\n      if (W(i, i) == 0) W(i, i) = D;\r\n\r\n      for (j = i+1; j <= m; j++) {\r\n         div(c1, W(j, i), W(i, i));\r\n         ReduceW(W(j), c1, W(i), D, i);\r\n      }\r\n\r\n      div(D, D, d);\r\n      k--;\r\n   }\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "0c3affdfd256b52dfaec4dfa46f1716236140252", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/HNF.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": "WinNTL-8_1_2/src/HNF.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": "WinNTL-8_1_2/src/HNF.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": 19.5891472868, "max_line_length": 79, "alphanum_fraction": 0.4309457855, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6997915034317642}}
{"text": "#include <Core/Core.h>\n#include <Eigen/Eigen.h>\n#include \"Sundials.h\"\n#include \"Mooring.h\"\n\n\nnamespace Upp {\n\n\nMooringStatus Catenary(double rho_m, double rho_m3, double rho_water, double moorlen, double BL,\n\t\t\t  double xanchorvessel, double zanchor, double zvessel, \n\t\t\t  double &Fhanchorvessel, double &Fvanchor, double &Fvvessel, \n\t\t\t  double &xonfloor, Vector<double> &x, Vector<double> &z, int num) {\n\tif (zanchor < 0 && zvessel < 0)\n\t\tthrow Exc(\"Catenary. Anchor and vessel z positions have to be positive\");\n\tif (xanchorvessel < 0)\n\t\tthrow Exc(\"Catenary. x distance between anchor and vessel has to be positive\");\n\t\n\tconst double g = 9.81;       \t\t\n\n\tdouble lmb = rho_m*(rho_m3 - rho_water)/rho_m3;\n\t\n  \tBuffer<double> udata(1, 1);\t\n\tSolveNonLinearEquationsSun(udata, 1, [&](const double y[], double residuals[])->bool {\n\t\tdouble Blimit = y[0];\n\t\tresiduals[0] =  sqrt(zanchor*(zanchor + 2*Blimit)) + sqrt(zvessel*(zvessel + 2*Blimit)) - moorlen; \n\t\treturn true;\n\t});\n\tdouble Blimit = udata[0];\n\n    double xanchorvessel_limit = Blimit*(acosh(zanchor/Blimit + 1) + acosh(zvessel/Blimit + 1));\n\t\n\tdouble delta = xanchorvessel/(num - 1);\n\tx.SetCount(num);\n\tz.SetCount(num);\n\t\n\tMooringStatus status;\n\t\n\tif (xanchorvessel < moorlen - zanchor - zvessel) {\t\t\t\t\n\t\tstatus = LOOSE_ON_FLOOR;\n\t\t\n\t\tif (!IsNull(rho_m)) {\n\t        Fhanchorvessel = 0;\n\t        Fvanchor = lmb*g*zanchor;\n\t        Fvvessel = lmb*g*zvessel;\n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n\t\t\n     \txonfloor = xanchorvessel;\n     \t\n\t\tx.SetCount(4);\n\t\tz.SetCount(4);\n\t\tx[0] = 0;\t\t\t\tz[0] = zanchor;\n\t\tx[1] = 0;\t\t\t\tz[1] = 0;\n\t\tx[2] = xanchorvessel;\tz[2] = 0;\n\t\tx[3] = xanchorvessel;\tz[3] = zvessel;\n\t} else if (xanchorvessel < xanchorvessel_limit) {\n        status = CATENARY_ON_FLOOR;\n\t\n\t  \tBuffer<int> consdata(1, 2);\t\t// B > 0\n\t  \t\n\t  \tBuffer<double> udata(1, Blimit/2.);\t\n\t\tSolveNonLinearEquationsSun(udata, 1, [&](const double y[], double residuals[])->bool {\n\t\t\tdouble B = y[0];\n\t\t\tresiduals[0] = xanchorvessel - B*acosh(zanchor/B + 1) - B*acosh(zvessel/B + 1) + sqrt(zanchor*(zanchor + 2*B)) + sqrt(zvessel*(zvessel + 2*B)) - moorlen; \n\t\t\treturn true;\n\t\t}, consdata);\t\t\n\t\tdouble B = udata[0];\n\n        double xcatanchor = B*acosh(zanchor/B + 1);\n        double xcatvessel = B*acosh(zvessel/B + 1);\n\t\txonfloor = xanchorvessel - xcatanchor - xcatvessel;\n\n\t\tif (!IsNull(rho_m)) {\n\t        Fhanchorvessel = lmb*g*B;        \n\t        Fvanchor = Fhanchorvessel*sinh(xcatanchor/B); \n\t        Fvvessel = Fhanchorvessel*sinh(xcatvessel/B); \n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n        \n        for (int i = 0; i < x.size(); ++i) {\n            x[i] = i*delta;\n            if (x[i] < xcatanchor)\n        \t\tz[i] = B*(cosh((xcatanchor - x[i])/B) - 1);\n            else if (x[i] > (xanchorvessel - xcatvessel))\n                z[i] = B*(cosh((max(0., x[i] - (xanchorvessel - xcatvessel)))/B) - 1);\n            else\n                z[i] = 0;\n        }\n    } else if (xanchorvessel < sqrt(sqr(moorlen) - sqr(zvessel - zanchor))) {\n        status = CATENARY;\n        \n\t\tint neq = 2;\n        double deltaz = zvessel - zanchor;\n\n\t  \tBuffer<double> udata(neq);\n\t  \tBuffer<int> consdata(2);\n\t  \tconsdata[0] = 2;\t\t\t// B > 0\n\t  \tconsdata[1] = 0;\n\t  \t\n\t  \tdouble x1_0, B_0, x1, B;\n\t  \tbool done = false;\n\t  \tfor (x1_0 = 0; x1_0 < abs(xanchorvessel) && !done; x1_0 += abs(xanchorvessel)/4) {\n\t  \t\tfor (B_0 = abs(Blimit); B_0 < 10*B_0 && !done; B_0 += 5*abs(Blimit)/4) {\t\t\n\t\t  \t\tudata[0] = B_0;\t\n\t\t  \t\tudata[1] = x1_0;\n\t\t\t\tSolveNonLinearEquationsSun(udata, neq, [&](const double y[], double residuals[])->bool {\n\t\t\t\t\tdouble B = y[0];\n\t\t\t\t\tdouble x1 = y[1];\n\t\t\t\t\t\n\t\t\t\t\tresiduals[0] = B*(sinh((x1 + xanchorvessel)/B) - sinh(x1/B)) - moorlen;\n\t\t\t\t\tresiduals[1] = B*(cosh((x1 + xanchorvessel)/B) - cosh(x1/B)) - deltaz;\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}, consdata);\n\t\t\t\tB = udata[0];\n\t\t\t\tx1 = udata[1];\t\t\n\t\t\t\tif (abs((x1 + xanchorvessel)/B) < 3)\n\t\t\t\t\tdone = true;\n\t  \t\t}\n\t  \t}\n\t  \tif (!done) \n\t\t\tthrow Exc(\"Catenary. Solving problem\");\n\n\t\tif (!IsNull(rho_m)) {\n\t        Fhanchorvessel = lmb*g*abs(B);    \n\t        Fvanchor = -Fhanchorvessel*sinh(x1/B);  \t\t\t\n\t        Fvvessel = Fhanchorvessel*sinh((x1 + xanchorvessel)/B);  \t\n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n\t\t\n        xonfloor = 0;\n        \n        for (int i = 0; i < x.size(); ++i) {\n            x[i] = i*delta;\n        \tz[i] = B*(cosh((x[i] + x1)/B) - 1) - B*(cosh(x1/B) - 1) + zanchor;\n        }\n    } else {\n\t\tstatus = BROKEN;\n\t\tif (!IsNull(rho_m)) \n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = xonfloor = 0;\n\t\telse\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = xonfloor = Null;\n\t\t\n\t\tx.Clear();\n\t\tz.Clear();\n    }\n    \n\tif (!IsNull(BL))    \n    \tif (max(sqrt(sqr(Fhanchorvessel) + sqr(Fvanchor)), sqrt(sqr(Fhanchorvessel) + sqr(Fvvessel))) >= BL)\n        \tstatus = BL_EXCEDEED;\n    \n\treturn status;\n}\n\nMooringStatus Catenary(double rho_m, double rho_m3, double rho_water, double moorlen, double BL,\n\t\t\t  double xanchorvessel, double zanchor, double zvessel, \n\t\t\t  double &Fhanchorvessel, double &Fvanchor, double &Fvvessel, double &xonfloor) {\n\tVector<double> x, z;\n\t\t\t\t      \n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 0);\t\t\t\t      \n}\n\nMooringStatus Catenary(double moorlen, double xanchorvessel, double zanchor, double zvessel, double &xonfloor,\n\t\t\t\tVector<double> &x, Vector<double> &z, int num) {\n\tdouble rho_m = Null,  rho_m3 = Null, rho_water = Null, BL = Null, Fhanchorvessel, Fvanchor, Fvvessel;\t\t      \n\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, num);\n}\n\nMooringStatus Catenary(double moorlen, double xanchorvessel, double zanchor, double zvessel, double &xonfloor) {\n\tdouble rho_m = Null,  rho_m3 = Null, rho_water = Null, BL = Null, Fhanchorvessel, Fvanchor, Fvvessel;\t\t      \n\tVector<double> x, z;\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 0);\n}\n\n\nbool CatenaryGetLen0(double xonfloor, double xanchorvessel, double zanchor, double zvessel, \n\t\t\t\t\tdouble &moorlen) {\n\tif (xonfloor >= xanchorvessel) {\n\t\tmoorlen = xanchorvessel + 2*(xonfloor - xanchorvessel) + zanchor + zvessel;\n\t\treturn false;\n\t} \n\t\n\tBuffer<int> consdata(2, 2);\t\t// B > 0 && moorlen > 0\n  \tBuffer<double> udata(2);\t\n  \tudata[0] = 1;\n  \tudata[1] = sqrt(sqr(xanchorvessel) + sqr(zanchor - zvessel));\n\tSolveNonLinearEquationsSun(udata, 2, [&](const double y[], double residuals[])->bool {\n\t\tdouble B = y[0];\n\t\tdouble moorlen = y[1];\n\t\tresiduals[0] = xanchorvessel - B*acosh(zanchor/B + 1) - B*acosh(zvessel/B + 1) + sqrt(zanchor*(zanchor + 2*B)) + sqrt(zvessel*(zvessel + 2*B)) - moorlen; \n    \tdouble xcatanchor = B*acosh(zanchor/B + 1);\n    \tdouble xcatvessel = B*acosh(zvessel/B + 1);\n\t\tresiduals[1] = xanchorvessel - xcatanchor - xcatvessel - xonfloor;\n\t\treturn true;\n\t}, consdata);\t\t\n\t//double B = udata[0];\n\tmoorlen = udata[1];\n\n\treturn true;\n\t\t\t\t\t}\n\nMooringStatus CatenaryGetLen(double xonfloor, double xanchorvessel, double zanchor, double zvessel, \n\t\t\tdouble &moorlen) {\n\tif (!CatenaryGetLen0(xonfloor, xanchorvessel, zanchor, zvessel, moorlen))\n\t\treturn LOOSE_ON_FLOOR;\n\t\n\treturn Catenary(moorlen, xanchorvessel, zanchor, zvessel, xonfloor);\n}\n\nMooringStatus CatenaryGetLen(double rho_m, double rho_m3, double rho_water, double xonfloor, \n\t\t\tdouble BL, double xanchorvessel, double zanchor, double zvessel, \n\t\t\tdouble &Fhanchorvessel, double &Fvanchor, double &Fvvessel, double &moorlen) {\n\tif (!CatenaryGetLen0(xonfloor, xanchorvessel, zanchor, zvessel, moorlen))\n\t\treturn LOOSE_ON_FLOOR;\n\t\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, zanchor, zvessel, \n\t\t\t\t\tFhanchorvessel, Fvanchor, Fvvessel, xonfloor);\n}\n\nconst char *MooringStatusStr(MooringStatus status) {\n\tconst char *str[5] = {\"loose on floor\", \"catenary on floor\", \"catenary\", \n\t\t\t\t\t\t \"line length exceeded\", \"break load exdeeded\"};\n\tASSERT(int(status) < 5);\n\treturn str[int(status)];\n}\n\nbool IsOK(MooringStatus status) { \n\treturn status < BROKEN;\n}\n\n}", "meta": {"hexsha": "ee38705258508f5706e34b3dae762f214a184cdc", "size": 8178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/Mooring.cpp", "max_stars_repo_name": "XOULID/Anboto", "max_stars_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STEM4U/Mooring.cpp", "max_issues_repo_name": "XOULID/Anboto", "max_issues_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STEM4U/Mooring.cpp", "max_forks_repo_name": "XOULID/Anboto", "max_forks_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "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.6525423729, "max_line_length": 157, "alphanum_fraction": 0.6312056738, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.699791490279279}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\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\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.h\"\n\nnamespace tudat\n{\n\nnamespace unit_tests\n{\n\nusing namespace tudat::gravitation;\n\n\n//! Function to get theoretical values of zonal gravity field coefficient of ellipsoid of revolution\ndouble getZonalTermForEllipsoidOfRevolution(\n        const double axisA, const double axisC, const double referenceRadius, const int degree )\n{\n    double zonalTerm = 0.0;\n    if( degree % 2 == 0 )\n    {\n        zonalTerm = 3.0 / std::pow( referenceRadius, degree ) *\n                std::pow( axisA * axisA - axisC * axisC, degree / 2 ) *\n                std::pow( -1.0, degree / 2 ) /\n                ( ( static_cast< double >( degree ) + 1.0 ) *\n                  ( static_cast< double >( degree ) + 3.0 ) );\n    }\n\n    return zonalTerm;\n}\n\nBOOST_AUTO_TEST_SUITE( test_tri_axial_ellipsoid_gravity )\n\n//! Test gravity field coefficients of homogeneous triaxial ellipsoid\nBOOST_AUTO_TEST_CASE( testTriAxialEllipsoidGravity )\n{\n    double axisA = 26.8E3;\n    double axisB = 22.4E3;\n    double axisC = 18.4E3;\n\n    // Compute coefficients\n    std::pair< Eigen::MatrixXd, Eigen::MatrixXd > sphericalHarmonicCoefficients =\n            createTriAxialEllipsoidSphericalHarmonicCoefficients( axisA, axisB, axisC, 4, 4 );\n    double referenceRadius = calculateTriAxialEllipsoidReferenceRadius( axisA, axisB, axisC );\n\n    // Compute expected low-degree coefficients\n    double expectedC20 = 1.0 / ( 5.0 * referenceRadius * referenceRadius ) *\n            ( axisC * axisC - ( axisA * axisA + axisB * axisB ) / 2.0 );\n    double expectedC22 = 1.0 / ( 20.0 * referenceRadius * referenceRadius ) *\n            ( axisA * axisA - axisB * axisB );\n    double expectedC40 = 15.0 / 7.0 * ( expectedC20 * expectedC20 +\n                                        2.0 * expectedC22 * expectedC22 );\n    double expectedC42 = 5.0 / 7.0 * ( expectedC20 * expectedC22 );\n    double expectedC44 = 5.0 / 28.0 * ( expectedC22 * expectedC22 );\n\n    BOOST_CHECK_CLOSE_FRACTION(\n                expectedC20, sphericalHarmonicCoefficients.first( 2, 0 ),\n                2.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION(\n                expectedC22, sphericalHarmonicCoefficients.first( 2, 2 ),\n                2.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION(\n                expectedC40, sphericalHarmonicCoefficients.first( 4, 0 ),\n                2.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION(\n                expectedC42, sphericalHarmonicCoefficients.first( 4, 2 ),\n                2.0 * std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE_FRACTION(\n                expectedC44, sphericalHarmonicCoefficients.first( 4, 4 ),\n                2.0 * std::numeric_limits< double >::epsilon( ) );\n\n    // Check whether C-coefficients with odd degree or order, and all S-coefficients, are zero.\n    for( unsigned int i = 0; i < 5; i++ )\n    {\n        for( unsigned int j = 0; j < 5; j++ )\n        {\n            if( ( i % 2 != 0 ) || ( j % 2 ) != 0 )\n            {\n                BOOST_CHECK_EQUAL( sphericalHarmonicCoefficients.first( i, j ), 0.0 );\n            }\n            BOOST_CHECK_EQUAL( sphericalHarmonicCoefficients.second( i, j ), 0.0 );\n\n        }\n    }\n\n    // Compute gravity field coefficients for ellipsoid of revolution\n    axisB = axisA;\n    referenceRadius = calculateTriAxialEllipsoidReferenceRadius( axisA, axisB, axisC );\n    sphericalHarmonicCoefficients = createTriAxialEllipsoidSphericalHarmonicCoefficients( axisA, axisB, axisC, 20, 1 );\n\n    // Check computation against theoretical values.\n    for( int i = 2; i < 21; i += 2 )\n    {\n        BOOST_CHECK_CLOSE_FRACTION(\n                    sphericalHarmonicCoefficients.first( i, 0 ),\n                    getZonalTermForEllipsoidOfRevolution( axisA, axisC, referenceRadius, i ),\n                    2.0 * std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n}\n\n}\n\n", "meta": {"hexsha": "336bff9ce2fc01a4113ce8491a5195e62fa39905", "size": 4540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/UnitTests/unitTestTriAxialEllipsoidGravity.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "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/Astrodynamics/Gravitation/UnitTests/unitTestTriAxialEllipsoidGravity.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "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/Astrodynamics/Gravitation/UnitTests/unitTestTriAxialEllipsoidGravity.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "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": 37.8333333333, "max_line_length": 119, "alphanum_fraction": 0.6352422907, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657921, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6997163008687332}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Advancing_front_surface_reconstruction.h>\n#include <CGAL/tuple.h>\n#include <boost/lexical_cast.hpp>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef K::Point_3  Point_3;\n\ntypedef std::array<std::size_t,3> Facet;\n\nnamespace std {\n  std::ostream&\n  operator<<(std::ostream& os, const Facet& f)\n  {\n    os << \"3 \" << f[0] << \" \" << f[1] << \" \" << f[2];\n    return os;\n  }\n}\n\nstruct Perimeter {\n\n  double bound;\n\n  Perimeter(double bound)\n    : bound(bound)\n  {}\n\n  template <typename AdvancingFront, typename Cell_handle>\n  double operator() (const AdvancingFront& adv, Cell_handle& c,\n                     const int& index) const\n  {\n    // bound == 0 is better than bound < infinity\n    // as it avoids the distance computations\n    if(bound == 0){\n      return adv.smallest_radius_delaunay_sphere (c, index);\n    }\n\n    // If perimeter > bound, return infinity so that facet is not used\n    double d  = 0;\n    d = sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n                              c->vertex((index+2)%4)->point()));\n    if(d>bound) return adv.infinity();\n    d += sqrt(squared_distance(c->vertex((index+2)%4)->point(),\n                               c->vertex((index+3)%4)->point()));\n    if(d>bound) return adv.infinity();\n    d += sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n                               c->vertex((index+3)%4)->point()));\n    if(d>bound) return adv.infinity();\n\n    // Otherwise, return usual priority value: smallest radius of\n    // delaunay sphere\n    return adv.smallest_radius_delaunay_sphere (c, index);\n  }\n};\n\nint main(int argc, char* argv[])\n{\n  std::ifstream in((argc>1)?argv[1]:\"data/half.xyz\");\n  double per = (argc>2)?boost::lexical_cast<double>(argv[2]):0;\n  std::vector<Point_3> points;\n  std::vector<Facet> facets;\n\n  std::copy(std::istream_iterator<Point_3>(in),\n            std::istream_iterator<Point_3>(),\n            std::back_inserter(points));\n\n  Perimeter perimeter(per);\n  CGAL::advancing_front_surface_reconstruction(points.begin(),\n                                               points.end(),\n                                               std::back_inserter(facets),\n                                               perimeter);\n\n  std::cout << \"OFF\\n\" << points.size() << \" \" << facets.size() << \" 0\\n\";\n  std::copy(points.begin(),\n            points.end(),\n            std::ostream_iterator<Point_3>(std::cout, \"\\n\"));\n  std::copy(facets.begin(),\n            facets.end(),\n            std::ostream_iterator<Facet>(std::cout, \"\\n\"));\n\n  return 0;\n}\n", "meta": {"hexsha": "f3b259d80e47d61b8b315d02a5236ab6a8737085", "size": 2637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Advancing_front_surface_reconstruction/reconstruction_fct.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/Advancing_front_surface_reconstruction/reconstruction_fct.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/Advancing_front_surface_reconstruction/reconstruction_fct.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": 30.6627906977, "max_line_length": 74, "alphanum_fraction": 0.5798255593, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6996766868909073}}
{"text": "#ifndef CANNON_MATH_FUNC_ROSENBROCK_H\n#define CANNON_MATH_FUNC_ROSENBROCK_H \n\n/*!\n * \\file cannon/math/func/rosenbrock.hpp\n * \\brief File containing Rosenbrock function and gradient definitions.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace math {\n\n    /*!\n     * \\brief Compute the value of the Rosenbrock function at the input point.\n     * See https://en.wikipedia.org/wiki/Rosenbrock_function\n     *\n     * \\param x The point at which to evaluate the Rosenbrock function.\n     *\n     * \\returns The value of the Rosenbrock function at the input point.\n     */\n    double rosenbrock(const Vector2d& x);\n\n    /*!\n     * \\brief Compute the gradient of the Rosenbrock function at the input point.\n     *\n     * \\param x The point at which to compute the gradient.\n     *\n     * \\returns Rosenbrock function gradient at the input point.\n     */\n    Vector2d rosenbrock_grad(const Vector2d& x);\n\n  } // namespace math\n} // namespace cannon\n\n\n#endif /* ifndef CANNON_MATH_FUNC_ROSENBROCK_H */\n", "meta": {"hexsha": "0ba09451e33248b0ef335be5cd749ffac82415f7", "size": 1028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/func/rosenbrock.hpp", "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": "cannon/math/func/rosenbrock.hpp", "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": "cannon/math/func/rosenbrock.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7, "max_line_length": 81, "alphanum_fraction": 0.6974708171, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6995374036024845}}
{"text": "#include \"problemes.h\"\n#include \"numerique.h\"\n#include \"puissance.h\"\n\n#include <boost/algorithm/string.hpp>\n\nENREGISTRER_PROBLEME(162, \"Hexadecimal numbers\") {\n    // In the hexadecimal number system numbers are represented using 16 different digits:\n    //\n    //                           0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F\n    //\n    // The hexadecimal number AF when written in the decimal number system equals 10x16+15=175.\n    //\n    // In the 3-digit hexadecimal numbers 10A, 1A0, A10, and A01 the digits 0,1 and A are all present.\n    // Like numbers written in base ten we write hexadecimal numbers without leading zeroes.\n    //\n    // How many hexadecimal numbers containing at most sixteen hexadecimal digits exist with all of the digits 0,1, and\n    // A present at least once?\n    // Give your answer as a hexadecimal number.\n    //\n    // (A,B,C,D,E and F in upper case, without any leading or trailing code that marks the number as hexadecimal and\n    // without leading zeroes , e.g. 1A3F and not: 1a3f and not 0x1a3f and not $1A3F and not #1A3F and not 0000001A3F)\n    uint128_t resultat = 0;\n    for (size_t n = 3; n < 17; ++n) {\n        resultat += 15 * puissance::puissance<uint128_t>(16, n - 1);\n        resultat += 41 * puissance::puissance<uint128_t>(14, n - 1);\n        resultat -= 43 * puissance::puissance<uint128_t>(15, n - 1);\n        resultat -= puissance::puissance<uint128_t>(13, n);\n    }\n\n    std::ostringstream oss;\n    oss << std::hex << resultat;\n\n    std::string str = oss.str();\n    boost::to_upper(str);\n\n    return str;\n}\n", "meta": {"hexsha": "965918f1ea7ec54ea8dc19b9027ddef5d1bfcbd0", "size": 1560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme162.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/probleme162.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/probleme162.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": 40.0, "max_line_length": 119, "alphanum_fraction": 0.65, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6995266848691656}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2009\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_LinearLeastSquares3_hpp__\n#define __Thea_Algorithms_LinearLeastSquares3_hpp__\n\n#include \"../Common.hpp\"\n#include \"../Array.hpp\"\n#include \"../Line3.hpp\"\n#include \"../MatVec.hpp\"\n#include \"../Plane3.hpp\"\n#include \"CentroidN.hpp\"\n#include \"Iterators.hpp\"\n#include \"PointTraitsN.hpp\"\n#include <Eigen/Eigenvalues>\n\nnamespace Thea {\nnamespace Algorithms {\n\n/** Fitting linear models to 3D data by minimizing sum-of-squared-errors. */\ntemplate <typename T, typename Enable = void>\nclass /* THEA_API */ LinearLeastSquares3\n{\n  public:\n    /**\n     * Linear least-squares fitting of a line to a set of 3D objects. InputIterator must dereference to type T or pointer-to-T.\n     *\n     * @param begin The first object in the set.\n     * @param end One position beyond the last object in the set.\n     * @param line Used to return the best-fit line.\n     * @param centroid If non-null, used to return the centroid of the objects, which is computed in the process of finding the\n     *   best-fit line.\n     *\n     * @return The sum of squared fitting errors.\n     */\n    template <typename InputIterator>\n    static double fitLine(InputIterator begin, InputIterator end, Line3 & line, Vector3 * centroid = nullptr);\n\n    /**\n     * Linear least-squares fitting of a plane to a set of 3D objects. InputIterator must dereference to type T or pointer-to-T.\n     *\n     * @param begin The first object in the set.\n     * @param end One position beyond the last object in the set.\n     * @param plane Used to return the best-fit plane.\n     * @param centroid If non-null, used to return the centroid of the objects, which is computed in the process of finding\n     *   the best-fit plane.\n     *\n     * @return The fitting quality: 0 (worst) to 1 (perfect).\n     */\n    template <typename InputIterator>\n    static double fitPlane(InputIterator begin, InputIterator end, Plane3 & plane, Vector3 * centroid = nullptr);\n\n}; // class LinearLeastSquares3\n\n// Fitting linear models to sets of objects that map to single points in 3-space.\ntemplate <typename T>\nclass LinearLeastSquares3<T, typename std::enable_if< IsNonReferencedPointN<T, 3>::value >::type>\n{\n  public:\n    template <typename InputIterator>\n    static double fitLine(InputIterator begin, InputIterator end, Line3 & line, Vector3 * centroid = nullptr)\n    {\n      Vector3d center;\n      Matrix3d cov = covMatrix(begin, end, center);\n\n      double sum = 0;\n      for (auto iter = makeRefIterator(begin); iter != makeRefIterator(end); ++iter)\n      {\n        Vector3d diff = PointTraitsN<T, 3>::getPosition(*iter).template cast<double>() - center;\n        sum += (diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);\n      }\n\n      Matrix3d m = sum * Matrix3d::Identity() - cov;\n      Eigen::SelfAdjointEigenSolver<Matrix3d> eigensolver;\n      if (eigensolver.computeDirect(m).info() != Eigen::Success)\n        throw Error(\"LinearLeastSquares3: Could not eigensolve matrix\");\n\n      // Eigenvalues are in increasing order\n      line = Line3::fromPointAndDirection(center.cast<Real>(), eigensolver.eigenvectors().col(0).cast<Real>());\n      if (centroid) *centroid = center.cast<Real>();\n      return eigensolver.eigenvalues()[0];\n    }\n\n    template <typename InputIterator>\n    static double fitPlane(InputIterator begin, InputIterator end, Plane3 & plane, Vector3 * centroid = nullptr)\n    {\n      Vector3d center;\n      Matrix3d cov = covMatrix(begin, end, center);\n\n      Eigen::SelfAdjointEigenSolver<Matrix3d> eigensolver;\n      if (eigensolver.computeDirect(cov).info() != Eigen::Success)\n        throw Error(\"LinearLeastSquares3: Could not eigensolve covariance matrix\");\n\n      // Eigenvalues are non-negative (covariance matrix is non-negative definite) and in increasing order\n      plane = Plane3::fromPointAndNormal(center.cast<Real>(), eigensolver.eigenvectors().col(0).cast<Real>());\n      if (centroid) *centroid = center.cast<Real>();\n      return eigensolver.eigenvalues()[0];\n    }\n\n  private:\n    /** Compute the covariance matrix between the coordinates of a set of 3D points. */\n    template <typename InputIterator>\n    static Matrix3d covMatrix(InputIterator begin, InputIterator end, Vector3d & centroid)\n    {\n      centroid = CentroidN<T, 3>::compute(begin, end).template cast<double>();\n\n      Matrix3d m = Matrix3d::Zero();\n      for (auto iter = makeRefIterator(begin); iter != makeRefIterator(end); ++iter)\n      {\n        Vector3d diff = PointTraitsN<T, 3>::getPosition(*iter).template cast<double>() - centroid;\n        m += diff * diff.transpose();  // outer product\n      }\n\n      return m;\n    }\n\n}; // class LinearLeastSquares3<Point3>\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "9adfd3bda0e43fa1f13cd16ccab389b68c0599fe", "size": 5244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 39.1343283582, "max_line_length": 128, "alphanum_fraction": 0.6702898551, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6994738900649674}}
{"text": "#include \"rotation.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <iostream>\n\nnamespace cpt {\n\nEigen::Matrix3f get_angle_axis_rotation_matrix(const Eigen::Vector3f& angleAxis) {\n    return Eigen::AngleAxisf(angleAxis.norm(), angleAxis.normalized()).toRotationMatrix();\n}\n\nEigen::Matrix3f get_euler_xyz_rotation_matrix(const Eigen::Vector3f& xyz) {\n    return get_angle_axis_rotation_matrix(xyz(2) * Eigen::Vector3f::UnitZ()) *\n        get_angle_axis_rotation_matrix(xyz(1) * Eigen::Vector3f::UnitY()) *\n        get_angle_axis_rotation_matrix(xyz(0) * Eigen::Vector3f::UnitX());\n}\n\nvoid decompose_scale_rotation(const Eigen::Matrix3f& rotScaleMat, Eigen::Matrix3f& rot, Eigen::Vector3f& scale)\n{\n    scale = rotScaleMat.colwise().norm();\n    rot = rotScaleMat.array().rowwise() / scale.transpose().array();\n\n    if (rot.determinant() < 0.f) {\n        scale *= -1.f;\n        rot *= -1.f;\n    }\n}\n\n}\n", "meta": {"hexsha": "05314a00d4e969315f3c3bd9668fc77d9527f72b", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/math/rotation.cpp", "max_stars_repo_name": "b3h47pte/cuda-path-tracing", "max_stars_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_stars_repo_licenses": ["MIT"], "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/math/rotation.cpp", "max_issues_repo_name": "b3h47pte/cuda-path-tracing", "max_issues_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_issues_repo_licenses": ["MIT"], "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/math/rotation.cpp", "max_forks_repo_name": "b3h47pte/cuda-path-tracing", "max_forks_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_forks_repo_licenses": ["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.53125, "max_line_length": 111, "alphanum_fraction": 0.6976998905, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868804, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6994738765222726}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\n#include <util/util.hpp>\n\nenum ActivationFunction { None = 0, Tanh = 1, ReLU = 2, LeakyReLU = 3 };\n\nclass Layer {\npublic:\n  Layer(Eigen::MatrixXd weight, Eigen::MatrixXd bias,\n        ActivationFunction act_fn);\n  virtual ~Layer();\n  Eigen::MatrixXd GetOutput(const Eigen::MatrixXd &input);\n  int GetNumInput() { return num_input_; }\n  int GetNumOutput() { return num_output_; }\n  Eigen::MatrixXd GetWeight() { return weight_; }\n  Eigen::MatrixXd GetBias() { return bias_; }\n  ActivationFunction GetActivationFunction() { return act_fn_; }\n\nprivate:\n  Eigen::MatrixXd weight_;\n  Eigen::MatrixXd bias_;\n  int num_input_;\n  int num_output_;\n  ActivationFunction act_fn_;\n};\n\nclass MLPModel {\npublic:\n  MLPModel(std::vector<Layer> layers);\n  MLPModel(const YAML::Node &node);\n\n  virtual ~MLPModel();\n\n  std::vector<Layer> GetLayers() { return layers_; }\n  Eigen::MatrixXd GetOutput(const Eigen::MatrixXd &input);\n  Eigen::MatrixXd GetOutput(const Eigen::MatrixXd &input, int idx);\n\n  int GetNumInput() { return num_input_; }\n  int GetNumOutput() { return num_output_; }\n  void PrintInfo();\n\nprivate:\n  void Initialize_(std::vector<Layer> layers);\n  int num_input_;\n  int num_output_;\n  int num_layer_;\n  std::vector<Layer> layers_;\n};\n", "meta": {"hexsha": "1fb3740abd7c1177d76fc3852a780a6c6726bcc0", "size": 1308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util/mlp_model.hpp", "max_stars_repo_name": "MaxxWilson/ASE389Project", "max_stars_repo_head_hexsha": "13c3c72887e27fbed2eef63c1e27b4a185036a39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-05-31T10:55:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:09:37.000Z", "max_issues_repo_path": "util/mlp_model.hpp", "max_issues_repo_name": "MaxxWilson/ASE389Project", "max_issues_repo_head_hexsha": "13c3c72887e27fbed2eef63c1e27b4a185036a39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-10-01T22:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T02:34:33.000Z", "max_forks_repo_path": "util/mlp_model.hpp", "max_forks_repo_name": "MaxxWilson/ASE389Project", "max_forks_repo_head_hexsha": "13c3c72887e27fbed2eef63c1e27b4a185036a39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T00:53:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:29:07.000Z", "avg_line_length": 24.679245283, "max_line_length": 72, "alphanum_fraction": 0.7125382263, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6994348219744237}}
{"text": "//\n//  LR.hpp\n//  LR-x\n//\n//  Created by zhuangqh on 2017/6/16.\n//  Copyright \u00a9 2017\u5e74 zhuangqh. All rights reserved.\n//\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace LR {\n\n  using Eigen::VectorXd;\n  using Eigen::MatrixXd;\n\n  class LogisticRegression {\n  private:\n    double alpha;\n    double lambda;\n    double epsilon;\n    int maxIter;\n\n    VectorXd theta;\n\n    long m;\n    long n;\n\n    bool verbose;\n\n    void regularize(VectorXd &);\n  public:\n    LogisticRegression(double alpha, int maxIter, double lambda, bool verbose=false, double epsilon=1e-5)\n        : alpha(alpha), maxIter(maxIter), lambda(lambda), epsilon(epsilon), verbose(verbose) {}\n\n    void fit_vec(std::pair<MatrixXd, VectorXd>);\n\n    void fit_naive(std::pair<MatrixXd, VectorXd>);\n\n    void fit_parallel(std::pair<MatrixXd, VectorXd>);\n\n    VectorXd predict(MatrixXd);\n  };\n\n}\n", "meta": {"hexsha": "2f07d694bd48cd269c5845ef68da6f4c48d02175", "size": 848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "LR.hpp", "max_stars_repo_name": "zhuangqh/LR-x", "max_stars_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LR.hpp", "max_issues_repo_name": "zhuangqh/LR-x", "max_issues_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LR.hpp", "max_forks_repo_name": "zhuangqh/LR-x", "max_forks_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_forks_repo_licenses": ["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.0425531915, "max_line_length": 105, "alphanum_fraction": 0.6639150943, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.6993505872177408}}
{"text": "// A simple quickref for Eigen. Add anything that's missing.\n// Main author: Keir Mierle\n\n#include <Eigen/Dense>\n\nMatrix<double, 3, 3> A;               // Fixed rows and cols. Same as Matrix3d.\nMatrix<double, 3, Dynamic> B;         // Fixed rows, dynamic cols.\nMatrix<double, Dynamic, Dynamic> C;   // Full dynamic. Same as MatrixXd.\nMatrix<double, 3, 3, RowMajor> E;     // Row major; default is column-major.\nMatrix3f P, Q, R;                     // 3x3 float matrix.\nVector3f x, y, z;                     // 3x1 float matrix.\nRowVector3f a, b, c;                  // 1x3 float matrix.\nVectorXd v;                           // Dynamic column vector of doubles\ndouble s;\n\n// Basic usage\n// Eigen          // Matlab           // comments\nx.size()          // length(x)        // vector size\nC.rows()          // size(C,1)        // number of rows\nC.cols()          // size(C,2)        // number of columns\nx(i)              // x(i+1)           // Matlab is 1-based\nC(i,j)            // C(i+1,j+1)       //\n\nA.resize(4, 4);   // Runtime error if assertions are on.\nB.resize(4, 9);   // Runtime error if assertions are on.\nA.resize(3, 3);   // Ok; size didn't change.\nB.resize(3, 9);   // Ok; only dynamic cols changed.\n\nA << 1, 2, 3,     // Initialize A. The elements can also be\n     4, 5, 6,     // matrices, which are stacked along cols\n     7, 8, 9;     // and then the rows are stacked.\nB << A, A, A;     // B is three horizontally stacked A's.\nA.fill(10);       // Fill A with all 10's.\n\n// Eigen                            // Matlab\nMatrixXd::Identity(rows,cols)       // eye(rows,cols)\nC.setIdentity(rows,cols)            // C = eye(rows,cols)\nMatrixXd::Zero(rows,cols)           // zeros(rows,cols)\nC.setZero(rows,cols)                // C = ones(rows,cols)\nMatrixXd::Ones(rows,cols)           // ones(rows,cols)\nC.setOnes(rows,cols)                // C = ones(rows,cols)\nMatrixXd::Random(rows,cols)         // rand(rows,cols)*2-1        // MatrixXd::Random returns uniform random numbers in (-1, 1).\nC.setRandom(rows,cols)              // C = rand(rows,cols)*2-1\nVectorXd::LinSpaced(size,low,high)   // linspace(low,high,size)'\nv.setLinSpaced(size,low,high)        // v = linspace(low,high,size)'\n\n\n// Matrix slicing and blocks. All expressions listed here are read/write.\n// Templated size versions are faster. Note that Matlab is 1-based (a size N\n// vector is x(1)...x(N)).\n// Eigen                           // Matlab\nx.head(n)                          // x(1:n)\nx.head<n>()                        // x(1:n)\nx.tail(n)                          // x(end - n + 1: end)\nx.tail<n>()                        // x(end - n + 1: end)\nx.segment(i, n)                    // x(i+1 : i+n)\nx.segment<n>(i)                    // x(i+1 : i+n)\nP.block(i, j, rows, cols)          // P(i+1 : i+rows, j+1 : j+cols)\nP.block<rows, cols>(i, j)          // P(i+1 : i+rows, j+1 : j+cols)\nP.row(i)                           // P(i+1, :)\nP.col(j)                           // P(:, j+1)\nP.leftCols<cols>()                 // P(:, 1:cols)\nP.leftCols(cols)                   // P(:, 1:cols)\nP.middleCols<cols>(j)              // P(:, j+1:j+cols)\nP.middleCols(j, cols)              // P(:, j+1:j+cols)\nP.rightCols<cols>()                // P(:, end-cols+1:end)\nP.rightCols(cols)                  // P(:, end-cols+1:end)\nP.topRows<rows>()                  // P(1:rows, :)\nP.topRows(rows)                    // P(1:rows, :)\nP.middleRows<rows>(i)              // P(:, i+1:i+rows)\nP.middleRows(i, rows)              // P(:, i+1:i+rows)\nP.bottomRows<rows>()               // P(:, end-rows+1:end)\nP.bottomRows(rows)                 // P(:, end-rows+1:end)\nP.topLeftCorner(rows, cols)        // P(1:rows, 1:cols)\nP.topRightCorner(rows, cols)       // P(1:rows, end-cols+1:end)\nP.bottomLeftCorner(rows, cols)     // P(end-rows+1:end, 1:cols)\nP.bottomRightCorner(rows, cols)    // P(end-rows+1:end, end-cols+1:end)\nP.topLeftCorner<rows,cols>()       // P(1:rows, 1:cols)\nP.topRightCorner<rows,cols>()      // P(1:rows, end-cols+1:end)\nP.bottomLeftCorner<rows,cols>()    // P(end-rows+1:end, 1:cols)\nP.bottomRightCorner<rows,cols>()   // P(end-rows+1:end, end-cols+1:end)\n\n// Of particular note is Eigen's swap function which is highly optimized.\n// Eigen                           // Matlab\nR.row(i) = P.col(j);               // R(i, :) = P(:, i)\nR.col(j1).swap(mat1.col(j2));      // R(:, [j1 j2]) = R(:, [j2, j1])\n\n// Views, transpose, etc; all read-write except for .adjoint().\n// Eigen                           // Matlab\nR.adjoint()                        // R'\nR.transpose()                      // R.' or conj(R')\nR.diagonal()                       // diag(R)\nx.asDiagonal()                     // diag(x)\nR.transpose().colwise().reverse(); // rot90(R)\nR.conjugate()                      // conj(R)\n\n// All the same as Matlab, but matlab doesn't have *= style operators.\n// Matrix-vector.  Matrix-matrix.   Matrix-scalar.\ny  = M*x;          R  = P*Q;        R  = P*s;\na  = b*M;          R  = P - Q;      R  = s*P;\na *= M;            R  = P + Q;      R  = P/s;\n                   R *= Q;          R  = s*P;\n                   R += Q;          R *= s;\n                   R -= Q;          R /= s;\n\n// Vectorized operations on each element independently\n// Eigen                  // Matlab\nR = P.cwiseProduct(Q);    // R = P .* Q\nR = P.array() * s.array();// R = P .* s\nR = P.cwiseQuotient(Q);   // R = P ./ Q\nR = P.array() / Q.array();// R = P ./ Q\nR = P.array() + s.array();// R = P + s\nR = P.array() - s.array();// R = P - s\nR.array() += s;           // R = R + s\nR.array() -= s;           // R = R - s\nR.array() < Q.array();    // R < Q\nR.array() <= Q.array();   // R <= Q\nR.cwiseInverse();         // 1 ./ P\nR.array().inverse();      // 1 ./ P\nR.array().sin()           // sin(P)\nR.array().cos()           // cos(P)\nR.array().pow(s)          // P .^ s\nR.array().square()        // P .^ 2\nR.array().cube()          // P .^ 3\nR.cwiseSqrt()             // sqrt(P)\nR.array().sqrt()          // sqrt(P)\nR.array().exp()           // exp(P)\nR.array().log()           // log(P)\nR.cwiseMax(P)             // max(R, P)\nR.array().max(P.array())  // max(R, P)\nR.cwiseMin(P)             // min(R, P)\nR.array().min(P.array())  // min(R, P)\nR.cwiseAbs()              // abs(P)\nR.array().abs()           // abs(P)\nR.cwiseAbs2()             // abs(P.^2)\nR.array().abs2()          // abs(P.^2)\n(R.array() < s).select(P,Q);  // (R < s ? P : Q)\n\n// Reductions.\nint r, c;\n// Eigen                  // Matlab\nR.minCoeff()              // min(R(:))\nR.maxCoeff()              // max(R(:))\ns = R.minCoeff(&r, &c)    // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);\ns = R.maxCoeff(&r, &c)    // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);\nR.sum()                   // sum(R(:))\nR.colwise().sum()         // sum(R)\nR.rowwise().sum()         // sum(R, 2) or sum(R')'\nR.prod()                  // prod(R(:))\nR.colwise().prod()        // prod(R)\nR.rowwise().prod()        // prod(R, 2) or prod(R')'\nR.trace()                 // trace(R)\nR.all()                   // all(R(:))\nR.colwise().all()         // all(R)\nR.rowwise().all()         // all(R, 2)\nR.any()                   // any(R(:))\nR.colwise().any()         // any(R)\nR.rowwise().any()         // any(R, 2)\n\n// Dot products, norms, etc.\n// Eigen                  // Matlab\nx.norm()                  // norm(x).    Note that norm(R) doesn't work in Eigen.\nx.squaredNorm()           // dot(x, x)   Note the equivalence is not true for complex\nx.dot(y)                  // dot(x, y)\nx.cross(y)                // cross(x, y) Requires #include <Eigen/Geometry>\n\n//// Type conversion\n// Eigen                           // Matlab\nA.cast<double>();                  // double(A)\nA.cast<float>();                   // single(A)\nA.cast<int>();                     // int32(A)\nA.real();                          // real(A)\nA.imag();                          // imag(A)\n// if the original type equals destination type, no work is done\n\n// Note that for most operations Eigen requires all operands to have the same type:\nMatrixXf F = MatrixXf::Zero(3,3);\nA += F;                // illegal in Eigen. In Matlab A = A+F is allowed\nA += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)\n\n// Eigen can map existing memory into Eigen matrices.\nfloat array[3];\nVector3f::Map(array).fill(10);            // create a temporary Map over array and sets entries to 10\nint data[4] = {1, 2, 3, 4};\nMatrix2i mat2x2(data);                    // copies data into mat2x2\nMatrix2i::Map(data) = 2*mat2x2;           // overwrite elements of data with 2*mat2x2\nMatrixXi::Map(data, 2, 2) += mat2x2;      // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)\n\n// Solve Ax = b. Result stored in x. Matlab: x = A \\ b.\nx = A.ldlt().solve(b));  // A sym. p.s.d.    #include <Eigen/Cholesky>\nx = A.llt() .solve(b));  // A sym. p.d.      #include <Eigen/Cholesky>\nx = A.lu()  .solve(b));  // Stable and fast. #include <Eigen/LU>\nx = A.qr()  .solve(b));  // No pivoting.     #include <Eigen/QR>\nx = A.svd() .solve(b));  // Stable, slowest. #include <Eigen/SVD>\n// .ldlt() -> .matrixL() and .matrixD()\n// .llt()  -> .matrixL()\n// .lu()   -> .matrixL() and .matrixU()\n// .qr()   -> .matrixQ() and .matrixR()\n// .svd()  -> .matrixU(), .singularValues(), and .matrixV()\n\n// Eigenvalue problems\n// Eigen                          // Matlab\nA.eigenvalues();                  // eig(A);\nEigenSolver<Matrix3d> eig(A);     // [vec val] = eig(A)\neig.eigenvalues();                // diag(val)\neig.eigenvectors();               // vec\n// For self-adjoint matrices use SelfAdjointEigenSolver<>\n", "meta": {"hexsha": "a755c302168a23917adb5f4b3c47d2a76c5a8463", "size": 9644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_stars_repo_name": "KerryWu16/src", "max_stars_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-17T11:07:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T09:35:11.000Z", "max_issues_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_issues_repo_name": "KerryWu16/src", "max_issues_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_forks_repo_name": "KerryWu16/src", "max_forks_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-19T07:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T07:41:48.000Z", "avg_line_length": 46.3653846154, "max_line_length": 133, "alphanum_fraction": 0.4813355454, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.699350583606021}}
{"text": "/*\nCopyright (C) 2015-present CompatibL\n\nPerformance test results and finance-specific examples are available at:\n\nhttp://www.tapescript.org\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\nhttp://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#ifndef cl_tape_examples_impl_polynomial_regression_hpp\n#define cl_tape_examples_impl_polynomial_regression_hpp\n\n#define CL_BASE_SERIALIZER_OPEN\n#include <cl/tape/tape.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace cl\n{\n    // Class for polynomial regression calculation.\n    class polynomial_regression\n    {\n    private:\n        // Order of polynomial regression.\n        const int order_;\n        // Size of matrixes m = order + 1.\n        const int m_;\n\n        // Input data vectors.\n        const tobject data_x_;\n        const tobject data_y_;\n\n        // Intermediate regression struuctures:\n        // Vectors of powers of x from 0 to 2 * (order + 1).\n        std::vector<tobject> x_power_;\n        // Matrix X * X^T\n        std::vector<std::vector<tobject>> mat_X_XT_;\n        // Inverse matrix (X * X^T)^-1\n        std::vector<std::vector<tobject>> mat_X_XT_inv_;\n        // Vector X^T * y.\n        std::vector<tobject> vec_XT_y_;\n\n        // Regression coefficients and their derivatives.\n        std::vector<tobject> coef_;\n\n        // Status of calculation.\n        bool is_coef_calculated;\n        bool is_estim_calculated;\n\n    public:\n        // Construct using provided data and order of polynomial regression.\n        polynomial_regression(tobject& x, tobject& y, int order) : data_x_(x), data_y_(y), order_(order), m_(order + 1)\n        {\n            is_coef_calculated = false;\n            is_estim_calculated = false;\n        }\n\n        // Calculate polynomial regression coefficients.\n        std::vector<tobject> calculate_coefficients()\n        {\n            // Create vectors of powers of x from 0 to 2m.\n            x_power_.resize(2 * m_);\n            x_power_[0] = 1 + data_x_ - data_x_;\n            std::vector<tobject> x_power_sum_vec(2 * m_);\n            x_power_sum_vec[0] = tapescript::sum_vec(x_power_[0]);\n            for (int i = 1; i < 2 * m_; i++)\n            {\n                x_power_[i] = x_power_[i - 1] * data_x_;\n                x_power_sum_vec[i] = tapescript::sum_vec(x_power_[i]);\n            }\n\n            // Calculate matrix X * X^T.\n            mat_X_XT_.resize(m_);\n            for (int i = 0; i < m_; i++)\n                mat_X_XT_[i].resize(m_);\n\n            // Calculate lower triangular matrix elements.\n            for (int i = 0; i < m_; i++)\n                for (int j = 0; j <= i; j++)\n                    mat_X_XT_[i][j] = x_power_sum_vec[i + j];\n\n            // Calculate the rest of matrix elements using symmetry.\n            for (int i = 0; i < m_; i++)\n                for (int j = i + 1; j < m_; j++)\n                    mat_X_XT_[i][j] = mat_X_XT_[j][i];\n\n            // Calculate inverse matrix (X * X^T)^-1.\n            mat_X_XT_inv_ = invert_sym_matrix_boost(mat_X_XT_);\n\n            // Calculate vector X^T * y.\n            vec_XT_y_.resize(m_);\n            for (int i = 0; i < m_; i++)\n                vec_XT_y_[i] = tapescript::sum_vec(x_power_[i] * data_y_);\n\n            // Calculate regression coefficients.\n            coef_.resize(m_);\n            for (int i = 0; i < m_; i++)\n            {\n                coef_[i] = 0;\n                for (int j = 0; j < m_; j++)\n                    coef_[i] += mat_X_XT_inv_[i][j] * vec_XT_y_[j];\n            }\n\n            is_coef_calculated = true;\n            return coef_;\n        }\n\n        // Calculate polynomial regression coefficients.\n        tobject calculate_estimation()\n        {\n            if (!is_coef_calculated)\n                throw std::runtime_error(\"Regression coefficients are not calculated.\");\n            tobject estim_y = tobject(0);\n            for (int i = 0; i < m_; i++)\n                estim_y += coef_[i] * x_power_[i];\n            is_estim_calculated = true;\n            return estim_y;\n        }\n\n        // Calculate polynomial regression coefficients derivatives w.r.t data points (y).\n        std::vector<std::vector<double>> calculate_coefficients_derivatives()\n        {\n            if (!is_coef_calculated)\n                throw std::runtime_error(\"Regression coefficients are not calculated.\");\n            std::vector<std::vector<double>> d_coef_d_y(m_);\n            std::vector<tvalue> x_power_tvalue(m_);\n            for (int i = 0; i < m_; i++)\n                x_power_tvalue[i] = (tvalue)x_power_[i];\n            int npoints = x_power_tvalue[0].size();\n            for (int i = 0; i < m_; i++)\n            {\n                d_coef_d_y[i].resize(npoints);\n                for (int j = 0; j < npoints; j++)\n                    for (int k = 0; k < m_; k++)\n                        d_coef_d_y[i][j] += ((tvalue)mat_X_XT_inv_[i][k]).scalar_value_ * x_power_tvalue[k].element_at(j);\n            }\n            return d_coef_d_y;\n        }\n\n        // Calculate polynomial regression coefficients derivatives w.r.t data points (y).\n        std::vector<std::vector<double>> calculate_estimation_derivatives()\n        {\n            std::vector<std::vector<double>> d_coef_d_y = calculate_coefficients_derivatives();\n            std::vector<tvalue> x_power_tvalue(m_);\n            for (int i = 0; i < m_; i++)\n                x_power_tvalue[i] = (tvalue)x_power_[i];\n            int npoints = x_power_tvalue[0].size();\n            std::vector<std::vector<double>> estim_y_deriv(npoints);\n            for (int i = 0; i < npoints; i++)\n            {\n                estim_y_deriv[i].resize(npoints);\n                for (int j = 0; j < npoints; j++)\n                    for (int k = 0; k < m_; k++)\n                        estim_y_deriv[i][j] += d_coef_d_y[k][i] * x_power_tvalue[k].element_at(j);\n            }\n            return estim_y_deriv;\n        }\n\n        // Invert symmetric matrix using Cholesky decomposition from the Boost library.\n        // This template method works with both element_type = tobject and element_type = tdouble.\n        template<typename element_type>\n        static std::vector<std::vector<element_type>> invert_sym_matrix_boost(const std::vector<std::vector<element_type>>& mat)\n        {\n            // Matrix size.\n            int m = mat.size();\n            boost::numeric::ublas::matrix<element_type> input(m, m);\n            for (int i = 0; i < m; i++)\n                for (int j = 0; j < m; j++)\n                    input.operator ()(i, j) = mat[i][j];\n            // Create a permutation matrix for the LU-factorization\n            boost::numeric::ublas::permutation_matrix<std::size_t> pm(m);\n            // Perform LU-factorization\n            if(boost::numeric::ublas::lu_factorize(input, pm))\n                throw std::runtime_error(\"Singular matrix\");\n            // Create identity matrix of for inverse\n            boost::numeric::ublas::matrix<element_type> inverse(m, m);\n            inverse.assign(boost::numeric::ublas::identity_matrix<element_type>(m));\n            boost::numeric::ublas::lu_substitute(input, pm, inverse);\n            std::vector<std::vector<element_type>> mat_inv = mat;\n            for (int i = 0; i < m; i++)\n                for (int j = 0; j < m; j++)\n                    mat_inv[i][j] = inverse(i, j);\n            return mat_inv;\n        }\n    };\n}\n\n#endif // cl_tape_examples_impl_polynomial_regression_hpp\n", "meta": {"hexsha": "f2820a9576aef761497c20e756f89f9cdf62e925", "size": 7898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 39.2935323383, "max_line_length": 128, "alphanum_fraction": 0.566599139, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6992823567261756}}
{"text": "/** @file\n * @brief NPDE ZienkiewiczZhuEstimator\n * @author Erick Schulz\n * @date 25/07/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\n#include \"zienkiewiczzhuestimator.h\"\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n// Lehrfem++ includes\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\nusing namespace ZienkiewiczZhuEstimator;\n\nint main(int /*argc*/, const char ** /*argv*/) {\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"PROBLEM - ZienkiewiczZhuEstimator \" << std::endl;\n  progress_bar progress{std::clog, 70u, \"Computing\"};\n  double progress_pourcentage;\n  // Tools and data\n  int N_meshes = 4;             // num. of meshes\n  Eigen::VectorXd approx_sol;   // basis ceoff expansion of scalar approx sol\n  Eigen::VectorXd approx_grad;  // basis ceoff expansion of approx grad\n  Eigen::VectorXd L2errors(N_meshes);     // L2 errors of scalar approx sol\n  Eigen::VectorXd H1errors(N_meshes);     // H1 errors of scalar approx sol\n  Eigen::VectorXd errors_grad(N_meshes);  // deviation of grad (delta error)\n  Eigen::VectorXd errors_diff(N_meshes);  // error difference (epsilon error)\n  Eigen::VectorXd mesh_sizes(N_meshes);\n  Eigen::VectorXd interpolated_uExact;\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space_p;\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p;\n\n  // Analytic solution\n  auto uExact = [](coord_t x) -> double {\n    return (0.2 / (M_PI * M_PI)) * sin(M_PI * x[0]) * sin(2 * M_PI * x[1]);\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_uExact{uExact};\n  auto grad_uExact = [](coord_t x) -> Eigen::Vector2d {\n    return Eigen::Vector2d(\n        (0.2 / M_PI) * cos(M_PI * x[0]) * sin(2 * M_PI * x[1]),\n        (0.4 / M_PI) * sin(M_PI * x[0]) * cos(2 * M_PI * x[1]));\n  };\n  lf::mesh::utils::MeshFunctionGlobal mf_grad_uExact{grad_uExact};\n\n  for (int i = 0; i < N_meshes; i++) {  // for each mesh\n    std::string idx_str = std::to_string(i);\n    // Load mesh into a Lehrfem++ object\n    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    const lf::io::GmshReader reader(\n        std::move(mesh_factory),\n        CURRENT_SOURCE_DIR \"/../meshes/unitsquare\" + idx_str + \".msh\");\n    mesh_p = reader.mesh();\n    mesh_sizes[i] = getMeshSize(mesh_p);\n    fe_space_p =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n    // Obtain reference to scalar dofh\n    const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n    // Produce a dof handler for the vector-valued finite element space\n    lf::assemble::UniformFEDofHandler vec_dofh(\n        mesh_p, {{lf::base::RefEl::kPoint(), 2},\n                 {lf::base::RefEl::kSegment(), 0},\n                 {lf::base::RefEl::kTria(), 0},\n                 {lf::base::RefEl::kQuad(), 0}});\n\n    LF_VERIFY_MSG(2 * dofh.NumDofs() == vec_dofh.NumDofs(),\n                  \"Number of degrees of freedom mismatch!\");\n\n    // Solve Poisson BVP with essential BCs\n    approx_sol = solveBVP(fe_space_p);\n    // Compute L2 and H1 errors\n    auto mf_approx_sol = lf::fe::MeshFunctionFE(fe_space_p, approx_sol);\n    L2errors[i] = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::uscalfe::squaredNorm(mf_uExact - mf_approx_sol), 2));\n    auto mf_approx_grad_sol =\n        lf::fe::MeshFunctionGradFE(fe_space_p, approx_sol);\n    H1errors[i] = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::uscalfe::squaredNorm(mf_grad_uExact - mf_approx_grad_sol),\n        2));\n\n    // Solve gradient VP and compute L2 deviation\n    approx_grad = solveGradVP(fe_space_p, approx_sol, vec_dofh);\n    // approx_grad = computeLumpedProjection(dofh, approx_sol, vec_dofh);\n    // Compute deviation error (delta error)\n    errors_grad[i] =\n        computeL2Deviation(dofh, approx_sol, vec_dofh, approx_grad);\n\n    // Compute difference error (epsilon error)\n    errors_diff[i] = std::abs(H1errors[i] - errors_grad[i]);\n\n    progress_pourcentage = ((double)i + 1.0) / N_meshes * 100.0;\n    progress.write(progress_pourcentage / 100.0);\n  }\n\n  // Computing rates of convergence of approx solutions to BVP and gradient VP\n  double ratesL2[N_meshes - 1];\n  double ratesH1[N_meshes - 1];\n  double rates_grad[N_meshes - 1];\n  double rates_diff[N_meshes - 1];\n  double log_denum;\n  for (int k = 0; k < N_meshes - 1; k++) {\n    log_denum = log(mesh_sizes[k] / mesh_sizes[k + 1]);\n    ratesL2[k] = log(L2errors[k] / L2errors[k + 1]) / log_denum;\n    ratesH1[k] = log(H1errors[k] / H1errors[k + 1]) / log_denum;\n    rates_grad[k] = log(errors_grad[k] / errors_grad[k + 1]) / log_denum;\n    rates_diff[k] = log(errors_diff[k] / errors_diff[k + 1]) / log_denum;\n  }\n\n  std::cout << \"\\n Done.\" << std::endl;\n  std::cout << \"Outputing results.\" << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"*********************************************************\"\n            << std::endl;\n  std::cout << \"      ERRORS AND CONVERGENCE RATES FOR PROBLEM        \"\n            << std::endl;\n  std::cout << \"             ZIENKIEWICZ ZHU ESTIMATOR                   \"\n            << std::endl;\n  std::cout << \"*********************************************************\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"    L2 errors of approximate scalar solutions to the     \"\n            << std::endl;\n  std::cout << \"   Poisson Problem with essential boundary conditions    \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| L2 error\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << L2errors[k];\n    if (k > 0) {\n      std::cout << \"\\t \\t|\" << ratesL2[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"    H1 errors of approximate scalar solutions to the     \"\n            << std::endl;\n  std::cout << \"   Poisson Problem with essential boundary conditions    \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| H1 error\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << H1errors[k];\n    if (k > 0) {\n      std::cout << \"\\t \\t|\" << ratesH1[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"      Convergence rates of the approximate gradients     \"\n            << std::endl;\n  std::cout << \"                     (delta error)                       \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| delta\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << errors_grad[k];\n    if (k > 0) {\n      std::cout << \"\\t\\t|\" << rates_grad[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  std::cout << \"      Difference error between the H1 error of the       \"\n            << std::endl;\n  std::cout << \"   approximate solution to the BVP and the deviation     \"\n            << std::endl;\n  std::cout << \"                    (epsilon error)                      \"\n            << std::endl;\n  std::cout << \"--------------------- RESULTS ---------------------------\"\n            << std::endl;\n  std::cout << \"Iteration\"\n            << \"\\t| epsilon\"\n            << \"\\t\\t| rates\" << std::endl;\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n  for (int k = 0; k < N_meshes; k++) {\n    std::cout << k << \"\\t\"\n              << \"\\t|\" << errors_diff[k];\n    if (k > 0) {\n      std::cout << \"\\t \\t|\" << rates_diff[k - 1];\n    }\n    std::cout << \"\\n\";\n  }\n  std::cout << \"---------------------------------------------------------\"\n            << std::endl;\n\n  // Output results for epsilon and delta errors to csv file\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::string errors_file_name_delta = \"delta_errors.csv\";\n  std::ofstream file_delta(errors_file_name_delta.c_str());\n  if (file_delta.is_open()) {\n    file_delta << errors_grad.format(CSVFormat);\n  }\n  std::string errors_file_name_epsilon = \"epsilon_errors.csv\";\n  std::ofstream file_epsilon(errors_file_name_epsilon.c_str());\n  if (file_epsilon.is_open()) {\n    file_epsilon << errors_diff.format(CSVFormat);\n  }\n\n  std::cout << \"\\n The delta and epsilon errors were written to:\" << std::endl;\n  std::cout << \">> delta_errors.csv and epsilon_errors.csv\\n\" << std::endl;\n\n  // Save approximate solution in VTK format\n  // Output results to vtk file\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  lf::io::VtkWriter vtk_writer(mesh_p, \"ZienkiewiczZhuEstimator_solution.vtk\");\n  // Write nodal data taking the values of the discrete solution at the\n  // vertices\n  auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 2);\n  for (int global_idx = 0; global_idx < N_dofs; global_idx++) {\n    nodal_data->operator()(dofh.Entity(global_idx)) = approx_sol[global_idx];\n  };\n  vtk_writer.WritePointData(\"ZienkiewiczZhuEstimator_solution\", *nodal_data);\n\n  std::cout << \"\\n The ZienkiewiczZhuEstimator_solution was written to:\"\n            << std::endl;\n  std::cout << \">> ZienkiewiczZhuEstimator_solution.vtk\\n\" << std::endl;\n\n}  // main\n", "meta": {"hexsha": "363b68875865eeed949c42195812bae851e45c0a", "size": 10885, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_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/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_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/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_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": 40.1660516605, "max_line_length": 79, "alphanum_fraction": 0.5257694074, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6992823530940874}}
{"text": "// Modified from NetKet source for YANNQ Project\n// <Chae-Yeun Park>(chae.yeun.park@gmail.com)\n// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\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#ifndef YANNQ_ACTIVATIONS_HPP\n#define YANNQ_ACTIVATIONS_HPP\n\n#include <Eigen/Dense>\n#include <complex>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <Utilities/type_traits.hpp>\n#include <Utilities/Utility.hpp>\n\n#include <nlohmann/json.hpp>\n\nnamespace yannq {\n\n/**\n  Abstract class for Activations.\n*/\nnamespace activation\n{\ntemplate<typename T>\nclass Identity \n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\t// A = Z\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tA.noalias() = Z;\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Z\n\t// J = dA / dZ = I\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  {\n\t\tG.noalias() = F;\n\t}\n\n\tstd::string name() const {\n\t\treturn \"Identity\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\n\ntemplate<typename T>\nclass LnCosh \n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\t// A = Lncosh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tfor (int i = 0; i < A.size(); ++i) {\n\t\t\tA(i) = logCosh(Z(i));\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Lncosh(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  {\n\t\tG.array() = F.array() * Z.array().tanh();\n\t}\n\n\tstd::string name() const {\n\t\treturn \"LnCosh\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate<typename T>\nclass Tanh \n{\npublic:\t\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t<Scalar>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\nprivate:\n\tRealScalar constant_;\n\npublic:\n\n\texplicit Tanh(const RealScalar constant = 1.0) //constant*tanh(z/constant)\n\t\t: constant_{constant}\n\t{\n\t}\n\n\t// A = a*Tanh(Z/a)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tA.array() = constant_ * (Z.array() / constant_).tanh();\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = a*Tanh(Z/a)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  {\n\t\tG.array() = F.array() * (1. - A.array() * A.array() / (constant_*constant_));\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Tanh\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(constant_);\n\t}\n};\n\ntemplate<typename T>\nclass WeakTanh\n{\npublic:\t\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t<Scalar>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\nprivate:\n\npublic:\n\n\texplicit WeakTanh() //x - tanh(x)/2\n\t{\n\t}\n\n\t// A = a*Tanh(Z/a)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tA.array() = Z.array();\n\t\tA.array() -= Z.array().tanh()/2.0;\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Tanh(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  {\n\t\tEigen::Array<T, Eigen::Dynamic, 1> tanh = Z.array().tanh();\n\t\tG.array() = F.array() * (1.0 +  tanh * tanh)/2.0;\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"WeakTanh\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\n\ntemplate<typename T>\nclass Sigmoid\n{\n\tstatic_assert(!is_complex_type<T>::value, \"Sigmoid now only supports real parameters\");\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\t// A = Sigmoid(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tA.array() = Z.array().exp();\n\t\tA.array().inverse();\n\t\tA.array() += 1.;\n\t\tA.array().inverse();\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Sigmoid(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,\n\t\t\tVectorConstRef /*F*/,\n\t\t\tVectorRef G) const  {\n\t\tG.array() = (1. - A.array() ) * A.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Sigmoid\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate<typename T, typename Enable = void>\nclass ReLU;\n\n//for complex T\ntemplate<typename T>\nclass ReLU<T, typename std::enable_if<is_complex_type<T>::value>::type > \n{\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t<Scalar>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\tconstexpr static RealScalar theta1_ = 3*M_PI/4;\n\tconstexpr static RealScalar theta2_ = -M_PI/4;\n\n\t// A = ReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : 0.0;\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = ReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : 0.0;\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"ReLU\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n//For real T\ntemplate<typename T>\nclass ReLU<T, typename std::enable_if<!is_complex_type<T>::value>::type >\n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\t// A = ReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) = std::max(Z(i), T{0.0});\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = ReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = Z(i)>0?F(i):T{0.0};\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"ReLU\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate<typename T, typename Enable = void>\nclass LeakyReLU;\n\n//for complex T\ntemplate<typename T>\nclass LeakyReLU<T, typename std::enable_if<is_complex_type<T>::value>::type>\n{\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t<Scalar>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\tconstexpr static RealScalar theta1_ = 3*M_PI/4;\n\tconstexpr static RealScalar theta2_ = -M_PI/4;\n\tRealScalar negativeSlope_;\n\n\tLeakyReLU(const RealScalar negativeSlope = 0.1)\n\t\t: negativeSlope_{negativeSlope}\n\t{\n\t}\n\n\t// A = LeakyReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : negativeSlope_*Z(i);\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = LeakyReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : negativeSlope_*F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyReLU\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(negativeSlope_);\n\t}\n};\n\n//For real T\ntemplate<typename T>\nclass LeakyReLU<T, typename std::enable_if<!is_complex_type<T>::value>::type>\n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\t\n\tScalar negativeSlope_;\n\n\tLeakyReLU(const Scalar negativeSlope = 0.1)\n\t\t: negativeSlope_{negativeSlope}\n\t{\n\t}\n\t// A = LeakyReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) = Z(i)>0?Z(i):T{negativeSlope_*Z(i)};\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = LeakyReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const  \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = Z(i)>0?F(i):T{negativeSlope_*F(i)};\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyReLU\";\n\t}\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(negativeSlope_);\n\t}\n};\n\n\n//For real T\ntemplate<typename T>\nclass HardTanh\n{\npublic:\n\tstatic_assert(!is_complex_type<T>::value, \"T must be a real type for HardTanh\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\t\n\tHardTanh()\n\t{\n\t}\n\n\t// A = hardtanh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tA(i) = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = hardtanh(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))>1.0?0.0:F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"HardTanh\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate<typename T>\nclass SoftShrink\n{\npublic:\n\tstatic_assert(!is_complex_type<T>::value, \"T must be a real type for SoftShrink\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\t\n\tSoftShrink()\n\t{\n\t}\n\n\t// A = softshrink(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tA(i) = abs(Z(i))<1.0?0.0:(Z(i)-copysign(1.0,Z(i)));\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = softshrink(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))<1.0?0.0:F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"SoftShrink\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n\n};\n\ntemplate<typename T>\nclass LeakyHardTanh\n{\npublic:\n\tstatic_assert(!is_complex_type<T>::value, \"T must be a real type for LeakyHardTanh\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\tScalar outsideSlope_;\n\t\n\tLeakyHardTanh(Scalar outsideSlope = 0.01)\n\t\t: outsideSlope_{outsideSlope}\n\t{\n\t}\n\n\t// A = leakyhardtanh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tT val = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);\n\t\t\tval += abs(Z(i))<1.0?0.0:outsideSlope_*(Z(i)-copysign(1.0,Z(i)));\n\t\t\tA(i) = val;\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = leakyhardtanh(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const  \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))>1.0?outsideSlope_*F(i):F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyHardTanh\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(outsideSlope_);\n\t}\n};\n\n\ntemplate<typename T>\nclass SoftSign\n{\npublic:\n\tstatic_assert(!is_complex_type<T>::value, \"T must be a real type for SoftSign\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\t\n\tSoftSign()\n\t{\n\t}\n\n\t// A = softsign(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  \n\t{\n\t\tA.array() = Z.array()/(Z.array().abs()+1.0);\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = softsign(Z)\n\t// J = dA / dZ = I\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const  \n\t{\n\t\tG.array() = (1.0+Z.array().abs()).square().inverse()*F.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"SoftSign\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate<typename T>\nclass Cos\n{\nprivate:\n\tT a_;\npublic:\n\tstatic_assert(!is_complex_type<T>::value, \"T must be a real type for Cos\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\t\n\tCos(T a = 1.0)\n\t\t: a_{a}\n\t{\n\t}\n\n\t// A = cos(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const  \n\t{\n\t\tA.array() = a_*cos(Z.array()*M_PI/a_);\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = a*cos(\\pi Z/a)\n\t// J = dA / dZ = \\pi sin(\\pi Z/ a)\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const  \n\t{\n\t\tG.array() = -M_PI*sin(M_PI*Z.array()/a_)*F.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Cos\";\n\t}\n\n\ttemplate<class Archive>\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(a_);\n\t}\n};\n}//namsepace activation\n\n}// namespace yannq\n\n#endif\n", "meta": {"hexsha": "2e0d9f7efabdb0d9f3defaf2bb48089937efd734", "size": 14850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/layers/activations.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "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": "Yannq/Machines/layers/activations.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "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": "Yannq/Machines/layers/activations.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "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.8382352941, "max_line_length": 90, "alphanum_fraction": 0.6422895623, "num_tokens": 4619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6992409165079084}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <string>\n \nusing Eigen::MatrixXd;\nusing namespace Eigen;\nusing namespace std;\n \nint main()\n{\n  string name = \"Juan pablo mallarino \\n github.com\";\n  int n = 0, m = 0;\n  // Bloque de codigo que lee el archivo y determina filas y columnas\n  MatrixXd A(n,m);\n  // Bloque de codigo que carga el archivo a la matriz\n  MatrixXd m = MatrixXd::Random(10,10); // # reales PSEUDO-aleatorios entre -1 y 1\n  cout << \"Checkpoint 1: \\n\" << m << endl;\n  cout << \"Determinant of m:\\n\" << m.determinant() << endl;\n  MatrixXd u_m = m.inverse();\n  cout << \"Inverse of m:\\n\" << u_m << endl;\n  cout << \"Test de valicez m^-1*m:\\n\" << u_m*m << endl;\n  // No existe tal cosa como exactitud en computacion -> decimales\n  // el cero en precision doble (double) -> 10^-15\n  // -> es un reto!\n  // LISP + Mathematica\n  m = (m + MatrixXd::Constant(10,10,1.2)) * 50; // # reales aleatorios entre 10 y 110\n  cout << \"Checkpoint 2: m =\\n\" << m << endl; // endl hace flush...\n  VectorXd v(10);\n  v << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;\n  cout << \"Checkpoint 3: v =\" << v << endl;\n  cout << \"m * v =\" << endl << m * v << endl;\n  cout << \"terminando... \"<<name<<endl;\n  return 0;\n}", "meta": {"hexsha": "b298b220cbab1bc5e9586e3953ad0051416b5472", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejercicios/semana5/matrix2.cpp", "max_stars_repo_name": "lschinchilla/FISI2028-202120", "max_stars_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "ejercicios/semana5/matrix2.cpp", "max_issues_repo_name": "lschinchilla/FISI2028-202120", "max_issues_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "ejercicios/semana5/matrix2.cpp", "max_forks_repo_name": "lschinchilla/FISI2028-202120", "max_forks_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 35.1176470588, "max_line_length": 85, "alphanum_fraction": 0.6030150754, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7490872019117029, "lm_q1q2_score": 0.6992210744122583}}
{"text": "#include <Eigen/Dense>\n\n#include <iostream>\n#include <iomanip>\n\n#include <cmath>\n\n//! \\brief One step of autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z). Steps of size h.\n//! \\tparam StateType type of solution space y and initial data y0\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] h size of the step\n//! \\param[in] gamma parameter\n//! \\return next step z1\ntemplate <class StateType>\nStateType sdirkStep(const StateType & z0, double h, double gamma) {\n    // TODO: implement one step of SDIRK method\n}\n\n//! \\brief Solve autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z), with N equidistant steps\n//! \\tparam StateType type of solution space z = [y,y']! and initial data z0 = [y(0), y'(0)]\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] N number of equidistant steps\n//! \\param[in] T final time of simulation\n//! \\param[in] gamma parameter\n//! \\return vector containing each step of z_k (y and y')\ntemplate <class StateType>\nstd::vector<StateType> sdirkSolve(const StateType & z0, unsigned int N, double T, double gamma) {\n    // TODO: implement solution with SDIRK method\n}\n\nint main() {\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    std::vector<int> N = {20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240};\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.) * ( 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    // TODO: compute solution and output error/approximate order\n}\n", "meta": {"hexsha": "09f47763b6961a85e84f95ecef9f784fa7ee64a9", "size": 1926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/sdirk_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/PS14/templates_ps14/sdirk_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/PS14/templates_ps14/sdirk_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": 37.0384615385, "max_line_length": 97, "alphanum_fraction": 0.6100726895, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.6991592036778402}}
{"text": "#include <unistd.h>\n#include <Eigen/Dense>\n#include <string>\n#include <fstream>\n#include \"common.h\"\n\n#define TINYEXR_IMPLEMENTATION\n#include \"tinyexr.h\"\n\nusing namespace std;\n\n\nfloat L(float cosTheta, float rough, float f0, int s)\n{\n\tif (rough == 0) return schlick(cosTheta, f0);\n\tcosTheta = std::max(cosTheta, 0.001f); // avoid issues at exact grazing\n\n\tfloat sinTheta = std::sqrt(1 - sqr(cosTheta));\n\tVector3 incoming(sinTheta, 0, cosTheta);\n\tfloat alpha = sqr(rough);\n\tMicrofacetLobe lobe(alpha, f0, incoming);\n\tfloat total = 0;\n\n\tfor (int i = 0; i < s; i++)\n\t\tfor (int j = 0; j < s; j++)\n\t\t{\n\t\t\t// stratified sampling\n\t\t\tfloat r1 = (randf() + i) / s;\n\t\t\tfloat r2 = (randf() + j) / s;\n\t\t\tVector3 dir;\n\t\t\tfloat weight;\n\t\t\tbool ok = lobe.sample(r1, r2, dir, weight);\n\t\t\tif (!ok) continue;\n\t\t\ttotal += weight;\n\t\t}\n\n\ttotal /= s * s;\n\treturn total;\n}\n\nfloat T(int i, const FloatImage& img)\n{\n\t// computing the hemispherical integral in solid angle measure:\n\t// I = 1/pi * int[f(cos theta) * cos theta d omega]\n\n\t// this is turned into spherical coordinates, resulting in:\n\t// I = 2 int[f(cos theta) * cos theta * sin theta d theta] from 0 to pi/2\n\n\t// substitute t := cos theta, obtaining\n\t// I = 2 int[f(t) * t dt]  from 0 to 1\n\t// compute the latter using trapezoid rule\n\n\tint n = img.cols();\n\tfloat total = 0;\n\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfloat t = float(j) / (n - 1);\n\t\tfloat w = j == 0 || j == n-1 ? 0.5f : 1;\n\t\ttotal += 2 * t * img(i, j) * w / (n - 1);\n\t}\n\n\treturn total;\n}\n\nvoid writeExr(FloatImage& img, string filename)\n{\n\tint m = img.rows(), n = img.cols();\n\tColorImage tmp(m, n);\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t\ttmp(i, j) = Color::Constant(img(i, j));\n\tSaveEXR((float*) &tmp(0,0), n, m, 3, 1, filename.c_str(), 0);\n}\n\nint main(int argc, char** argv)\n{\n\tint s = 100;  // use s^2 stratified samples\n\tint n = 256;  // result table size n x n\n\tfloat f0 = 0; // Schlick Fresnel normal incidence\n\n\tint tmp;\n\twhile ((tmp = getopt(argc, argv, \"n:s:f:\")) != -1)\n\t{\n\t\tswitch (tmp)\n\t\t{\n\t\t\tcase 'n': n = atoi(optarg); break;\n\t\t\tcase 's': s = atoi(optarg); break;\n\t\t\tcase 'f': f0 = atof(optarg); break;\n\t\t}\n\t}\n\n\tFloatImage Limg(n, n);\n\n\t#pragma omp parallel for\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tfloat rough = float(i) / (n - 1);\n\t\t\tfloat cosTheta = float(j) / (n - 1);\n\t\t\tLimg(i, j) = L(cosTheta, rough, f0, s);\n\t\t}\n\n\tFloatImage Timg(1, n);\n\tfor (int i = 0; i < n; i++) Timg(0, i) = T(i, Limg);\n\n\twriteExr(Limg, \"L.exr\");\n\twriteExr(Timg, \"T.exr\");\n\treturn 0;\n}\n\n", "meta": {"hexsha": "4bdc8487f00695731b046323e5eb757ba6e8ff46", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aps.cpp", "max_stars_repo_name": "miloshasan/aps", "max_stars_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aps.cpp", "max_issues_repo_name": "miloshasan/aps", "max_issues_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aps.cpp", "max_forks_repo_name": "miloshasan/aps", "max_forks_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_forks_repo_licenses": ["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.5625, "max_line_length": 74, "alphanum_fraction": 0.5856747131, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6991556816715239}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\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#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\ntemplate<class T>\nclass func {\npublic:\n  typedef T real_t;\n  func(real_t t) : t_(t) {}\n  real_t operator()(real_t x, real_t xc) const {\n    using std::abs; using std::cos; using std::log;\n    if (x < t_ && xc > 0) {\n      return cos(2 * x) * log(abs(2 * sin(xc / 2) * sin((t_ + x) / 2)));\n    } else if (x > t_ && xc < 0) {\n      return cos(2 * x) * log(abs(2 * sin(-xc / 2) * sin((t_ + x) / 2)));\n    } else {\n      real_t s = abs(cos(x) - cos(t_));\n      return s > 0 ? cos(2 * x) * log(s) : real_t(0);\n    }\n  }\n  real_t result() const {\n    using std::cos;\n    return -boost::math::constants::pi<real_t>() * cos(2 * t_) / 2;\n  }\nprivate:\n  real_t t_;\n};\n\nint main() {\n  using std::abs; using std::sqrt;\n  typedef double real_t;\n  const real_t pi = boost::math::constants::pi<real_t>();\n\n  boost::math::quadrature::tanh_sinh<real_t> integrator;\n  real_t termination = sqrt(std::numeric_limits<real_t>::epsilon());\n  \n  real_t t = pi / 8;\n  func<real_t> f(t);\n  real_t error, L1;\n  size_t levels;\n  real_t q1 = integrator.integrate(f, 0, t, termination, &error, &L1, &levels);\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"lower part: \" << q1 << std::endl\n            << \"estimated error: \" << error << std::endl\n            << \"L1 * error: \" << L1 * error << std::endl\n            << \"levels: \" << levels << std::endl;\n  real_t q2 = integrator.integrate(f, t, pi, termination, &error, &L1, &levels);\n  std::cout << \"upper part: \" << q2 << std::endl\n            << \"estimated error: \" << error << std::endl\n            << \"L1 * error: \" << L1 * error << std::endl\n            << \"levels: \" << levels << std::endl;\n  std::cout << \"result: \" << (q1 + q2) << std::endl\n            << \"real error: \" << abs(q1 + q2 - f.result()) << std::endl;\n}\n", "meta": {"hexsha": "41964491125f74938aab56bf1b7f2bf7a74ea9d3", "size": 2337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tanh_sinh/example2.cpp", "max_stars_repo_name": "wistaria/boost-examples", "max_stars_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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": "tanh_sinh/example2.cpp", "max_issues_repo_name": "wistaria/boost-examples", "max_issues_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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": "tanh_sinh/example2.cpp", "max_forks_repo_name": "wistaria/boost-examples", "max_forks_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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": 35.4090909091, "max_line_length": 90, "alphanum_fraction": 0.5353016688, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6990561692576199}}
{"text": "//\n//  neuralnetwork.h\n//  NeuralNetwork\n//\n//  Created by Nikhil Joshi on 10/15/14.\n//  Copyright (c) 2014 Nikhil Joshi. All rights reserved.\n//\n\n#ifndef __NeuralNetwork__neuralnetwork__\n#define __NeuralNetwork__neuralnetwork__\n\n#define EIGEN_DEFAULT_TO_ROW_MAJOR\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <ctime>\n#include <vector>\n#include <initializer_list>\n\n#include \"utility/utility.hpp\"\n#include \"utility/functionalitysuite.hpp\"\n\nnamespace NNetwork {\n    \n    class Network {\n    public:\n        // constructor\n        Network(std::vector<unsigned int>&& topology) {\n            _topology =  Eigen::toEigen(topology);\n            initialize();\n        }\n        \n        Network(std::initializer_list<unsigned int>& ls)\n        : Network(std::vector<unsigned int>(ls))\n        {\n        }\n        \n        // Destructor\n        ~Network(){\n            for (int i = 0; i < _numLayers; i++)\n                delete _functions[i];\n        }\n        \n        \n        // member functions\n        // Setters/Getters\n        // network topology\n        void setTopology(const std::vector<unsigned int>& topology);\n        void setTopology(const std::initializer_list<unsigned int>& topology);\n        std::vector<unsigned int> getTopology(void)  const      { return Eigen::toStdVector(_topology); }\n        size_t numInputs(void)   const                          { return _numInputs; }\n        size_t numOutputs(void)  const                          { return _numOutputs; }\n        size_t numLayers(void)   const                          { return _numLayers; }\n        // weights\n        std::vector<std::vector<double>> getWeightsAfterLayer(const unsigned int layer) const;\n        Eigen::MatrixXd getWeightsAfterLayerEigen(const unsigned int layer) const;\n        void printWeights(void) const;\n        void setRandomWeights(void);\n        void setRandomWeightsForLayer(unsigned int layer);\n        void setWeightsAfterLayer(const unsigned int layer, const std::vector<std::vector<double>>& weights);\n        void setWeightsAfterLayer(const unsigned int layer, const Eigen::Ref<const Eigen::MatrixXd>& weights);\n\n        // activation function\n        void setFunctionalityAtLayer(const unsigned int layer, FunctionalitySuite& suit);\n        // make it a softmax output\n        void setSoftmaxAtOutputLayer(void);\n        bool isSoftmaxAtOutputLayer(void)                      { return _isSoftmax; }\n        \n        \n        // Train the network on given examples\n        // Data is assumed given in standard format :\n        // One row = one (training) example n input/feature columns followed by m output/label columns\n        double train(const char* dataFileName, const double regularizer,\n                     const bool verbose = true);\n        double train(const Eigen::MatrixXd& data, const double regularizer,\n                     const bool verbose = true);\n        \n        // Predict\n        unsigned int predict(const std::vector<double>& input);\n        \n        \n        // Test methods\n        friend bool isValidNetworkImplementation(Network& testNet);\n \n        \n    private:\n\n        Eigen::VectorXu _topology;\n        std::vector<Eigen::MatrixXd> _weights;\n        std::vector<FunctionalitySuite*> _functions;\n        size_t _numInputs, _numOutputs, _numLayers;\n        bool _isSoftmax;\n        \n        // Member functions\n        // initializers\n        void initialize(void);\n        void scaleWeightVectors(void);\n        void setupDefaultNetwork(void);\n        \n        // Process input to produce output\n        void processInput(const Eigen::Ref<const Eigen::VectorXd>& input,\n                          std::vector<Eigen::VectorXd>& inputs,\n                          std::vector<Eigen::VectorXd>& activations);\n        // Calculate loss for the given input - label pair\n        double calculateLoss(const Eigen::Ref<const Eigen::MatrixXd>& data,\n                             const double regularizer = 0);\n        double calculateLoss(const Eigen::Ref<const Eigen::VectorXd>& input,\n                             const Eigen::Ref<const Eigen::VectorXd>& label,\n                             const double regularizer = 0);\n        \n        // Calculate Error Delta by back Propagation\n        void unregularizedLossAndWeightCorrectionsForExample(const Eigen::Ref<const Eigen::VectorXd>& input,\n                                                             const Eigen::Ref<const Eigen::VectorXd>& label,\n                                                             double& loss,\n                                                             std::vector<Eigen::MatrixXd>& weightCorrections);\n        void lossAndWeightCorrections(const Eigen::Ref<const Eigen::MatrixXd>& data,\n                                      const double regularizer,\n                                      double& loss,\n                                      std::vector<Eigen::MatrixXd>& weightCorrections);\n    };\n    \n\n    // Network implementation checks\n    bool isValidNetworkImplementation(Network& testNet);\n    \n    \n    // include implementation file\n#include \"network.ipp\"\n    \n}\n\n\n#endif /* defined(__NeuralNetwork__neuralnetwork__) */\n", "meta": {"hexsha": "4f221edb33abe9ff0f0f82b9aac07f774392b609", "size": 5154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NeuralNetwork/network.hpp", "max_stars_repo_name": "nikhiljjoshi/neuralNetwork", "max_stars_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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": "NeuralNetwork/network.hpp", "max_issues_repo_name": "nikhiljjoshi/neuralNetwork", "max_issues_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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": "NeuralNetwork/network.hpp", "max_forks_repo_name": "nikhiljjoshi/neuralNetwork", "max_forks_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "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": 38.4626865672, "max_line_length": 110, "alphanum_fraction": 0.5871168025, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6989508628357679}}
{"text": "#ifndef MPI_PI_PI_INCLUDED\n#define MPI_PI_PI_INCLUDED\n\n#include \"../include/common.hpp\"\n#include \"../include/random.hpp\"\n#include <boost/mpi.hpp>\n#include <boost/multiprecision/number.hpp>\n\nnamespace mpi_pi {\n\nnamespace area_integral {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  common::Division division(comm, terms);\n  Number nterms = terms;\n  Number delta = Number(1) / nterms;\n  Number local_sum = 0;\n  Number fxdx = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number ni = i;\n    Number x = ni / nterms;\n    Number x1 = (ni + Number(1)) / nterms;\n    Number fxdx1 = delta / (x1 * x1 + Number(1));\n    if (i == division.first) {\n      fxdx = delta / (x * x + Number(1));\n    }\n    local_sum += (fxdx + fxdx1) / Number(2);\n    fxdx = fxdx1;\n  }\n  local_sum *= Number(4);\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace area_integral\n\nnamespace power_series {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  common::Division division(comm, terms);\n  Number local_sum = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number ni = i;\n    Number term = Number(1) / (Number(2) * ni + Number(1));\n    if (i % 2 == 1)\n      term = -term;\n    local_sum += term;\n  }\n  local_sum *= Number(4);\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace power_series\n\nnamespace improved_power_series {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  using boost::multiprecision::pow;\n  using std::pow;\n\n  common::Division division(comm, terms);\n  Number local_sum = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number ni = i;\n    Number x = ni * Number(2) + Number(1);\n    Number term5 = Number(4) / (x * pow(Number(5), x));\n    Number term239 = Number(-1) / (x * pow(Number(239), x));\n    if (i % 2 == 1) {\n      term5 = -term5;\n      term239 = -term239;\n    }\n    local_sum += term5 + term239;\n  }\n  local_sum *= Number(4);\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace improved_power_series\n\nnamespace monte_carlo {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  common::Division division(comm, terms);\n  random::MinimunStandardEngine random_engine(comm, root);\n  std::uniform_real_distribution<double> dist(-1.0, 1.0);\n  std::size_t local_hit = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    auto x = dist(random_engine);\n    auto y = dist(random_engine);\n    if ((x * x + y * y) <= 1.0)\n      local_hit += 1;\n  }\n  std::size_t total_hit = 0;\n  boost::mpi::reduce(comm, local_hit, total_hit, std::plus<std::size_t>(),\n                     root);\n  Number result = 0;\n  if (comm.rank() == root) {\n    result = Number(total_hit) * Number(4) / Number(terms);\n  }\n  return result;\n}\n\n} // namespace monte_carlo\n\nnamespace monte_carlo_integral {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  common::Division division(comm, terms);\n  random::MinimunStandardEngine random_engine(comm, root);\n  std::uniform_real_distribution<double> dist(0, 1.0);\n  std::size_t local_hit = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    auto x = dist(random_engine);\n    auto y = dist(random_engine);\n    double fx = 1.0 / (1.0 + x * x);\n    if (y <= fx)\n      local_hit += 1;\n  }\n  std::size_t total_hit = 0;\n  boost::mpi::reduce(comm, local_hit, total_hit, std::plus<std::size_t>(),\n                     root);\n  Number result = 0;\n  if (comm.rank() == root) {\n    result = Number(total_hit) * Number(4) / Number(terms);\n  }\n  return result;\n}\n\n} // namespace monte_carlo_integral\n\nnamespace random_integral {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  common::Division division(comm, terms);\n  random::MinimunStandardEngine random_engine(comm, root);\n  std::uniform_real_distribution<double> dist(0, 1.0);\n  Number nterms = terms;\n  Number delta = Number(1) / nterms;\n  Number local_sum = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number x = dist(random_engine);\n    Number x1 = x + delta;\n    Number fxdx = delta / (x * x + Number(1));\n    Number fxdx1 = delta / (x1 * x1 + Number(1));\n    local_sum += (fxdx + fxdx1) / Number(2);\n  }\n  local_sum *= Number(4);\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace random_integral\n\nnamespace borwein1987 {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  using boost::multiprecision::pow;\n  using boost::multiprecision::sqrt;\n  using std::pow;\n  using std::sqrt;\n\n  if (comm.rank() == root) {\n    std::cerr << \"borwein1987 is an iterative method, will not run parallelized\"\n              << std::endl;\n  }\n  Number x = sqrt(Number(2.0));\n  Number p = Number(2) + sqrt(Number(2.0));\n  Number y = pow(Number(2.0), Number(1.0) / Number(4.0));\n  for (std::size_t i = 0; i != terms; ++i) {\n    x = Number(0.5) * (sqrt(x) + Number(1) / sqrt(x));\n    p *= (x + Number(1)) / (y + Number(1));\n    y = (y * sqrt(x) + Number(1) / sqrt(x)) / (y + Number(1));\n  }\n  return p;\n}\n\n} // namespace borwein1987\n\nnamespace yasumasa2002 {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  using boost::multiprecision::pow;\n  using std::pow;\n\n  common::Division division(comm, terms);\n  Number local_sum = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number ni = i;\n    Number x = ni * Number(2) + Number(1);\n    Number term49 = Number(12) / (x * pow(Number(49), x));\n    Number term57 = Number(32) / (x * pow(Number(57), x));\n    Number term239 = Number(-5) / (x * pow(Number(239), x));\n    Number term110443 = Number(12) / (x * pow(Number(110443), x));\n    if (i % 2 == 1) {\n      term49 = -term49;\n      term57 = -term57;\n      term239 = -term239;\n      term110443 = -term110443;\n    }\n    local_sum += term49 + term57 + term239 + term110443;\n  }\n  local_sum *= Number(4);\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace yasumasa2002\n\nnamespace chudnovsky {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  using boost::multiprecision::pow;\n  using boost::multiprecision::sqrt;\n  using std::pow;\n  using std::sqrt;\n\n  if (comm.rank() == root) {\n    std::cerr << \"this implementation of chudnovsky is iterative, will not run \"\n                 \"parallelized\"\n              << std::endl;\n  }\n\n  Number K = 6;\n  Number M = 1;\n  Number L = 13591409;\n  Number X = 1;\n  Number x_multiplier = -pow(Number(640320), 3);\n  Number sum = 13591409;\n  for (std::size_t k = 0; k != terms; ++k) {\n    M = (pow(K, Number(3)) - Number(16) * K) * M /\n        pow(k + Number(1), Number(3));\n    L += 545140134;\n    X *= x_multiplier;\n    sum += M * L / X;\n    K += 12;\n  }\n  Number result = Number(426880) * sqrt(Number(10005)) / sum;\n  return result;\n}\n\n} // namespace chudnovsky\n\nnamespace bbp {\n\ntemplate <typename Number>\nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n  using boost::multiprecision::pow;\n  using std::pow;\n\n  common::Division division(comm, terms);\n  Number local_sum = 0;\n  for (std::size_t i = division.first; i != division.last; ++i) {\n    Number ni = Number(i);\n    Number ni8 = Number(8) * ni;\n    Number t1 = Number(4) / (ni8 + Number(1));\n    Number t2 = Number(-2) / (ni8 + Number(4));\n    Number t3 = Number(-1) / (ni8 + Number(5));\n    Number t4 = Number(-1) / (ni8 + Number(6));\n    Number term = (t1 + t2 + t3 + t4) / pow(Number(16), ni);\n    local_sum += term;\n  }\n  Number result = 0;\n  boost::mpi::reduce(comm, local_sum, result, std::plus<Number>(), root);\n  return result;\n}\n\n} // namespace bbp\n\n} // namespace mpi_pi\n\n#endif", "meta": {"hexsha": "fa2e6b0fe0d158f254279ee1f01c8f1be3d2c9c0", "size": 8329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pi.hpp", "max_stars_repo_name": "linyinfeng/mpi-pi", "max_stars_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_stars_repo_licenses": ["MIT"], "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/pi.hpp", "max_issues_repo_name": "linyinfeng/mpi-pi", "max_issues_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_issues_repo_licenses": ["MIT"], "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/pi.hpp", "max_forks_repo_name": "linyinfeng/mpi-pi", "max_forks_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_forks_repo_licenses": ["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.0209059233, "max_line_length": 80, "alphanum_fraction": 0.6276863969, "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6988598512200584}}
{"text": "/**\n * @file sdirk.cc\n * @brief NPDE homework SDIRK code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"sdirk.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"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  // TO DO (13-3.f): compute one timestep of the ODE\n#if SOLUTION\n  // Matrix A for evaluation of f\n  Eigen::Matrix2d A;\n  A << 0., 1., -1., -1.;\n  // Reuse factorization\n  auto A_lu = (Eigen::Matrix2d::Identity() - h * gamma * A).partialPivLu();\n  Eigen::Vector2d az = A * z0;\n\n  // Increments\n  Eigen::Vector2d k1 = A_lu.solve(az);\n  Eigen::Vector2d k2 = A_lu.solve(az + h * (1 - 2 * gamma) * A * k1);\n\n  // Next step\n  res = z0 + h * 0.5 * (k1 + k2);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return res;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector<Eigen::Vector2d> sdirkSolve(const Eigen::Vector2d &z0,\n                                        unsigned int N, double T,\n                                        double gamma) {\n  // Solution vector\n  std::vector<Eigen::Vector2d> res(N + 1);\n  // TO DO (13-3.g): solve the ODE with uniform timesteps using the SDIRK method\n#if SOLUTION\n  // Equidistant step size\n  const double h = T / N;\n  // Push initial data\n  res.at(0) = z0;\n  // Main loop\n  for (unsigned int i = 1; i <= N; ++i) {\n    res.at(i) = sdirkStep(res.at(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  // TO DO (13-3.g) 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 N(10);\n  N << 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) << \"n\" << std::setw(15) << \"maxerr\"\n            << std::setw(15) << \"rate\" << std::endl;\n  // Loop over all meshes\n  for (unsigned int i = 0; i < N.size(); ++i) {\n    int n = N(i);\n    // Get solution\n    auto sol = sdirkSolve(z0, n, 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) << n << 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  // Eigen::VectorXd Neig(N.data());\n  // Eigen::VectorXd erreig (err.data());\n  Eigen::VectorXd coeffs = polyfit(N.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": "c25bcb83929e9fb0ce15a4c81d3df907de27ed1c", "size": 3487, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/SDIRK/mastersolution/sdirk.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": "developers/SDIRK/mastersolution/sdirk.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": "developers/SDIRK/mastersolution/sdirk.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": 26.4166666667, "max_line_length": 80, "alphanum_fraction": 0.5468884428, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.6988370714300821}}
{"text": "//\n// hough3dlines.cpp\n//     Main program implementing the iterative Hough transform\n//\n// Author:  Tilman Schramke, Christoph Dalitz\n// Date:    2020-01-15\n// License: see License-BSD2\n//\n\n#include \"vector3d.h\"\n#include \"pointcloud.h\"\n#include \"hough.h\"\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXf;\nusing namespace std;\n\n// usage message\nconst char* usage = \"Usage:\\n\"\n  \"\\though3dlines [options] <infile>\\n\"\n  \"Options (defaults in brackets):\\n\"\n  \"\\t-o <outfile>   write results to <outfile> [stdout]\\n\"\n  \"\\t-dx <dx>       step width in x'y'-plane [0]\\n\"\n  \"\\t               when <dx>=0, it is set to 1/64 of total width\\n\"\n  \"\\t-nlines <nl>   maximum number of lines returned [0]\\n\"\n  \"\\t               when <nl>=0, all lines are returned\\n\"\n  \"\\t-minvotes <nv> only lines with at least <nv> points are returned [0]\\n\"\n  \"\\t-gnuplot       print result as a gnuplot command\\n\"\n  \"\\t-raw           print plot data in easily machine-parsable format\\n\"\n  \"\\t-delim <char>  use <char> as field delimiter in input file [,]\\n\"\n  \"\\t-v             be verbose and print Hough space size to stdout\\n\"\n  \"\\t-vv            be even more verbose and print Hough lines (before LSQ)\\n\"\n  \"Version:\\n\"\n  \"\\t1.2 from 2020-01-15\\n\";\n\n//--------------------------------------------------------------------\n// utility functions\n//--------------------------------------------------------------------\n\n//\n// orthogonal least squares fit with libeigen\n// rc = largest eigenvalue\n//\ndouble orthogonal_LSQ(const PointCloud &pc, Vector3d* a, Vector3d* b){\n  double rc = 0.0;\n\n  // anchor point is mean value\n  *a = pc.meanValue();\n\n  // copy points to libeigen matrix\n  Eigen::MatrixXf points = Eigen::MatrixXf::Constant(pc.points.size(), 3, 0);\n  for (int i = 0; i < points.rows(); i++) {\n    points(i,0) = pc.points.at(i).x;\n    points(i,1) = pc.points.at(i).y;\n    points(i,2) = pc.points.at(i).z;\n  }\n\n  // compute scatter matrix ...\n  MatrixXf centered = points.rowwise() - points.colwise().mean();\n  MatrixXf scatter = (centered.adjoint() * centered);\n\n  // ... and its eigenvalues and eigenvectors\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(scatter);\n  Eigen::MatrixXf eigvecs = eig.eigenvectors();\n\n  // we need eigenvector to largest eigenvalue\n  // libeigen yields it as LAST column\n  b->x = eigvecs(0,2); b->y = eigvecs(1,2); b->z = eigvecs(2,2);\n  rc = eig.eigenvalues()(2);\n\n  return (rc);\n}\n\n\n//--------------------------------------------------------------------\n// main program\n//--------------------------------------------------------------------\n\nint main(int argc, char ** argv) {\n\n  // default values for command line options\n  double opt_dx = 0.0;\n  int opt_nlines = 0;\n  int opt_minvotes = 0;\n  enum Outformat { format_normal, format_gnuplot, format_raw };\n  Outformat opt_outformat = format_normal;\n  char opt_delim = ',';\n  int opt_verbose = 0;\n  char* infile_name = NULL;\n  char* outfile_name = NULL;\n\n  // number of icosahedron subdivisions for direction discretization\n  int granularity = 4;\n  int num_directions[7] = {12, 21, 81, 321, 1281, 5121, 20481};\n\n  // IO files\n  //FILE* infile = NULL;\n  FILE* outfile = stdout;\n\n  // bounding box of point cloud\n  Vector3d minP, maxP, minPshifted, maxPshifted;\n  // diagonal length of point cloud\n  double d;\n\n  // parse command line\n  for (int i=1; i<argc; i++) {\n    if (0 == strcmp(argv[i], \"-o\")) {\n      i++;\n      if (i<argc) outfile_name = argv[i];\n    }\n    else if (0 == strcmp(argv[i], \"-dx\")) {\n      i++;\n      if (i<argc) opt_dx = atof(argv[i]);\n    }\n    else if (0 == strcmp(argv[i], \"-nlines\")) {\n      i++;\n      if (i<argc) opt_nlines = atoi(argv[i]);\n    }\n    else if (0 == strcmp(argv[i], \"-minvotes\")) {\n      i++;\n      if (i<argc) opt_minvotes = atoi(argv[i]);\n    }\n    else if (0 == strcmp(argv[i], \"-gnuplot\")) {\n      opt_outformat = format_gnuplot;\n    }\n    else if (0 == strcmp(argv[i], \"-raw\")) {\n      opt_outformat = format_raw;\n    }\n    else if (0 == strcmp(argv[i], \"-delim\")) {\n      i++;\n      if (i<argc) opt_delim = argv[i][0];\n    }\n    else if (0 == strcmp(argv[i], \"-v\")) {\n      opt_verbose = 1;\n    }\n    else if (0 == strcmp(argv[i], \"-vv\")) {\n      opt_verbose = 2;\n    }\n\n    else if (argv[i][0] == '-') {\n      fprintf(stderr, \"%s\", usage);\n      return 1;\n    }\n    else {\n      infile_name = argv[i];\n    }\n  }\n\n  // plausibilty checks\n  if (!infile_name) {\n    fprintf(stderr, \"Error: no infile given!\\n%s\", usage);\n    return 1;\n  }\n  if (opt_dx < 0){\n    fprintf(stderr, \"Error: dx < 0!\\n%s\", usage);\n    return 1;\n  }\n  if (opt_nlines < 0){\n    fprintf(stderr, \"Error: nlines < 0!\\n%s\", usage);\n    return 1;\n  }\n  if (opt_minvotes < 0){\n    fprintf(stderr, \"Error: minvotes < 0!\\n%s\", usage);\n    return 1;\n  }\n  if (opt_minvotes < 2){\n    opt_minvotes = 2;\n  }\n\n  // open in/out files\n  if (outfile_name) {\n    outfile = fopen(outfile_name, \"w\");\n    if (!outfile) {\n      fprintf(stderr, \"Error: cannot open outfile '%s'!\\n\", outfile_name);\n      return 1;\n    }\n  }\n\n  // read point cloud from file\n  PointCloud X;\n  int errorcode = X.readFromFile(infile_name, opt_delim);\n  if (2 == errorcode) {\n    fprintf(stderr, \"Error: wrong file format of infile '%s'!\\n\", infile_name);\n    return 1;\n  }\n  else if (0 != errorcode) {\n    fprintf(stderr, \"Error: cannot read infile '%s'!\\n\", infile_name);\n    return 1;\n  }\n  if (X.points.size() < 2) {\n    fprintf(stderr, \"Error: point cloud has less than two points\\n\");\n    return 1;\n  }\n\n  // center cloud and compute new bounding box\n  X.getMinMax3D(&minP, &maxP);\n  d = (maxP-minP).norm();\n  if (d == 0.0) {\n    fprintf(stderr, \"Error: all points in point cloud identical\\n\");\n    return 1;\n  }\n  X.shiftToOrigin();\n  X.getMinMax3D(&minPshifted, &maxPshifted);\n\n  // estimate size of Hough space\n  if (opt_dx == 0.0) {\n    opt_dx = d / 64.0;\n  }\n  else if (opt_dx >= d) {\n    fprintf(stderr, \"Error: dx too large\\n\");\n    return 1;\n  }\n  double num_x = floor(d / opt_dx + 0.5);\n  double num_cells = num_x * num_x * num_directions[granularity];\n  if (opt_verbose) {\n    printf(\"info: x'y' value range is %f in %.0f steps of width dx=%f\\n\",\n           d, num_x, opt_dx);\n    printf(\"info: Hough space has %.0f cells taking %.2f MB memory space\\n\",\n           num_cells, num_cells * sizeof(unsigned int) / 1000000.0);\n  }\n#ifdef WEBDEMO\n  if (num_cells > 1E8) {\n    fprintf(stderr, \"Error: program was compiled in WEBDEMO mode, \"\n            \"which does not permit %.0f cells in Hough space\\n\", num_cells);\n    return 2;\n  }\n#endif\n\n  // first Hough transform\n  Hough* hough;\n  try {\n    hough = new Hough(minPshifted, maxPshifted, opt_dx, granularity);\n  } catch (const std::exception &e) {\n    fprintf(stderr, \"Error: cannot allocate memory for %.0f Hough cells\"\n            \" (%.2f MB)\\n\", num_cells, \n            (double(num_cells) / 1000000.0) * sizeof(unsigned int));\n    return 2;\n  }\n  hough->add(X);\n\n  // print header info if necessary\n  if (opt_outformat == format_gnuplot) {\n    fprintf(outfile, \"set datafile separator '%c'\\n\"\n            \"set parametric\\n\"\n            \"set xrange [%f:%f]\\n\"\n            \"set yrange [%f:%f]\\n\"\n            \"set zrange [%f:%f]\\n\"\n            \"set urange [%f:%f]\\n\"\n            \"splot '%s' using 1:2:3 with points palette\",\n            opt_delim,\n            minP.x, maxP.x, minP.y, maxP.y, minP.z, maxP.z,\n            -d, d, infile_name);\n  }\n  else if (opt_outformat == format_raw) {\n    fprintf(outfile, \"%f %f %f %f %f %f\\n%f %f\\n\",\n            minP.x, maxP.x, minP.y, maxP.y, minP.z, maxP.z, -d, d);\n  }\n  \n  // iterative Hough transform\n  // (Algorithm 1 in IPOL paper)\n  PointCloud Y;\t// points close to line\n  double rc;\n  unsigned int nvotes;\n  int nlines = 0;\n  do {\n    Vector3d a; // anchor point of line\n    Vector3d b; // direction of line\n\n    hough->subtract(Y); // do it here to save one call\n\n    nvotes = hough->getLine(&a, &b);\n    if (opt_verbose > 1) {\n      Vector3d p = a + X.shift;\n      printf(\"info: highest number of Hough votes is %i for the following \"\n             \"line:\\ninfo: a=(%f,%f,%f), b=(%f,%f,%f)\\n\",\n             nvotes, p.x, p.y, p.z, b.x, b.y, b.z);\n    }\n\n    X.pointsCloseToLine(a, b, opt_dx, &Y);\n\n    rc = orthogonal_LSQ(Y, &a, &b);\n    if (rc==0.0) break;\n\n    X.pointsCloseToLine(a, b, opt_dx, &Y);\n    nvotes = Y.points.size();\n    if (nvotes < (unsigned int)opt_minvotes) break;\n\n    rc = orthogonal_LSQ(Y, &a, &b);\n    if (rc==0.0) break;\n\n    a = a + X.shift;\n\n    nlines++;\n    if (opt_outformat == format_normal) {\n      fprintf(outfile, \"npoints=%lu, a=(%f,%f,%f), b=(%f,%f,%f)\\n\",\n              Y.points.size(), a.x, a.y, a.z, b.x, b.y, b.z);\n    }\n    else if (opt_outformat == format_gnuplot) {\n      fputs(\", \\\\\\n    \", outfile);\n      fprintf(outfile, \"%f + u * %f, %f + u * %f, %f + u * %f \"\n              \"with lines notitle lc rgb 'black'\",\n              a.x, b.x, a.y, b.y, a.z, b.z);\n    }\n    else {\n      fprintf(outfile, \"%f %f %f %f %f %f %lu\\n\",\n              a.x, a.y, a.z, b.x, b.y, b.z, Y.points.size());\n    }\n\n    X.removePoints(Y);\n\n  } while ((X.points.size() > 1) && \n           ((opt_nlines == 0) || (opt_nlines > nlines)));\n\n  // final newline in gnuplot command\n  if (opt_outformat == format_gnuplot)\n    fputs(\"\\n\", outfile);\n  \n  // clean up\n  delete hough;\n  if (outfile_name) fclose(outfile);\n\n  return 0;\n}\n", "meta": {"hexsha": "912eedab04b43a0e48aa840195b5be3b1e57f1c6", "size": 9381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hough3dlines.cpp", "max_stars_repo_name": "estebanrdo/hough-3d-lines", "max_stars_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T14:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T09:14:27.000Z", "max_issues_repo_path": "hough3dlines.cpp", "max_issues_repo_name": "estebanrdo/hough-3d-lines", "max_issues_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hough3dlines.cpp", "max_forks_repo_name": "estebanrdo/hough-3d-lines", "max_forks_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T10:35:43.000Z", "avg_line_length": 28.5136778116, "max_line_length": 79, "alphanum_fraction": 0.5630529794, "num_tokens": 2908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.6988370634449442}}
{"text": "#include \"triangle.hpp\"\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include <boost/format.hpp>\n\n#include \"base-types.hpp\"\n\nnamespace\n{\n  bool areValidVertices(const yakovlev::point_t vertices[3]);\n}\n\nyakovlev::Triangle::Triangle(\n    const point_t & vertice1,\n    const point_t & vertice2,\n    const point_t & vertice3,\n    double rotation\n) :\n  vertices_{ vertice1, vertice2, vertice3 },\n  pos_{ (vertice1.x + vertice2.x + vertice3.x) / 3.0, (vertice1.y + vertice2.y + vertice3.y) / 3.0 }\n{\n  if (!areValidVertices(vertices_)) {\n    throw std::invalid_argument{ \"Triangle must not be degenerate\" };\n  }\n  rotate(rotation);\n}\n\nbool yakovlev::Triangle::operator==(const Triangle & other) const noexcept\n{\n  for (const point_t & vert : vertices_) {\n    bool hasEqual = false;\n    for (const point_t & othervert : other.vertices_) {\n      if (vert == othervert) {\n        hasEqual = true;\n      }\n    }\n    if (!hasEqual) {\n      return false;\n    }\n  }\n  return true;\n}\n\nbool yakovlev::Triangle::operator!=(const Triangle & other) const noexcept\n{\n  return !(*this == other);\n}\n\nyakovlev::point_t yakovlev::Triangle::getCenter() const noexcept\n{\n  return pos_;\n}\n\ndouble yakovlev::Triangle::getArea() const noexcept\n{\n  return std::abs(vertices_[0].x * (vertices_[1].y - vertices_[2].y)\n        + vertices_[1].x * (vertices_[2].y - vertices_[0].y)\n        + vertices_[2].x * (vertices_[0].y - vertices_[1].y))\n      / 2.0;\n}\n\nyakovlev::rectangle_t yakovlev::Triangle::getFrameRect() const noexcept\n{\n  double maxX = vertices_[0].x, maxY = vertices_[0].y;\n  double minX = vertices_[0].x, minY = vertices_[0].y;\n  for (int i = 1; i < 3; ++i) {\n    minX = std::min(vertices_[i].x, minX);\n    maxX = std::max(vertices_[i].x, maxX);\n    minY = std::min(vertices_[i].y, minY);\n    maxY = std::max(vertices_[i].y, maxY);\n  }\n  \n  double width = maxX - minX, height = maxY - minY;\n  return { width, height, { minX + (width / 2.0), minY + (height / 2.0) } };\n}\n\nvoid yakovlev::Triangle::move(const point_t & pos) noexcept\n{\n  move(pos.x - pos_.x, pos.y - pos_.y);\n}\n\nvoid yakovlev::Triangle::move(double x, double y) noexcept\n{\n  for (point_t &vert : vertices_) {\n    vert.x += x;\n    vert.y += y;\n  }\n  pos_.x += x;\n  pos_.y += y;\n}\n\nvoid yakovlev::Triangle::rotate(double rotation) noexcept\n{\n  double rad = rotation * M_PI / 180.0;\n  double rotSin = sin(rad);\n  double rotCos = cos(rad);\n  for (point_t & vert : vertices_) {\n    point_t local = { vert.x - pos_.x, vert.y - pos_.y };\n    vert = {\n        pos_.x + local.x * rotCos - local.y * rotSin,\n        pos_.y + local.x * rotSin + local.y * rotCos\n    };\n  }\n}\n\nvoid yakovlev::Triangle::scale(double coef)\n{\n  if (coef <= 0.0) {\n    throw std::invalid_argument{ (boost::format(\"Invalid rectangle scale coefficient %1% - can not be negative or zero\") % coef ).str() };\n  }\n  for (point_t & vert : vertices_) {\n    vert = {\n        pos_.x + (vert.x - pos_.x) * coef,\n        pos_.y + (vert.y - pos_.y) * coef\n    };\n  }\n}\n\nvoid yakovlev::Triangle::print(std::ostream & os) const\n{\n  os << \"Triangle with verticies on \" << vertices_[0] << \", \" << vertices_[1]\n      << \", \" << vertices_[2] << '\\n';\n}\n\nnamespace\n{\n  bool areValidVertices(const yakovlev::point_t vertices[3])\n  {\n    double sides[3] = { \n        yakovlev::getDistanceBetweenPoints(vertices[0], vertices[1]),\n        yakovlev::getDistanceBetweenPoints(vertices[1], vertices[2]),\n        yakovlev::getDistanceBetweenPoints(vertices[0], vertices[2])\n    };\n    return ((sides[0] + sides[1]) > sides[2]) \n        && ((sides[0] + sides[2]) > sides[1]) \n        && ((sides[1] + sides[2]) > sides[0]); \n  }\n}\n", "meta": {"hexsha": "6449f6b0e54102d646b45fb79e4de5f18aeff433", "size": 3629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_stars_repo_name": "NekoSilverFox/CPP", "max_stars_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T20:57:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T06:24:41.000Z", "max_issues_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_issues_repo_name": "NekoSilverFox/CPP", "max_issues_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T14:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T16:25:33.000Z", "max_forks_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_forks_repo_name": "NekoSilverFox/CPP", "max_forks_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T17:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:48:23.000Z", "avg_line_length": 25.5563380282, "max_line_length": 138, "alphanum_fraction": 0.612565445, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6988000771980137}}
{"text": "// ===========================================================================\n// Imagine++ Libraries\n// Copyright (C) Imagine\n// For detailed information: http://imagine.enpc.fr/software\n// ===========================================================================\n\n#include \"Imagine/LinAlg/MyEigen.h\"\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n// Eigen value decomposition of packed symmetric matrix\ntemplate <typename T>\nvoid subSymEigenValues(int *n,T *ap,T *w,T *z,int *info) \n{\n  T *t= new T [(*n)*(*n)];\n  symToMatrix(*n,ap,t);\n  Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (t,*n,*n,OuterStride<>(*n));\n   Eigen::JacobiSVD<Matrix<T, Dynamic, Dynamic> > svd (AMap, ComputeFullU | ComputeFullV);\n   Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > zMap (z,*n,*n,OuterStride<>(*n));\n   Map<Matrix<T, Dynamic, 1>, 0, InnerStride<0> > wMap (w, *n);\n   wMap=svd.singularValues();\n   zMap=svd.matrixU();\n   Matrix<T, Dynamic, Dynamic> v=svd.matrixV();\n   *info=1-AMap.isApprox(zMap * wMap.asDiagonal() * v.adjoint());\n   for (int i=0;i<*n;i++){\n     if (v.col(i).isApprox(-zMap.col(i)))\n     {\n       wMap(i)=-wMap(i);\n     }\n   };\n   delete[] t;\n}\n\nvoid symEigenValues(int *n, double *ap, double *w, double *z, int* info) { subSymEigenValues<double>(n, ap, w, z, info); }\nvoid symEigenValues(int *n, float *ap, float *w, float *z, int* info) { subSymEigenValues<float>(n, ap, w, z, info); }\n\n", "meta": {"hexsha": "b739446788a6e0594d4cbbe808ebcf7898508650", "size": 1414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Imagine/LinAlg/src/MyEigen5.cpp", "max_stars_repo_name": "Ethiy/imagine-pp", "max_stars_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "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": "Imagine/LinAlg/src/MyEigen5.cpp", "max_issues_repo_name": "Ethiy/imagine-pp", "max_issues_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "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": "Imagine/LinAlg/src/MyEigen5.cpp", "max_forks_repo_name": "Ethiy/imagine-pp", "max_forks_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "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.2162162162, "max_line_length": 122, "alphanum_fraction": 0.5693069307, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6986425887108174}}
{"text": "/*\n *  trajectory_factory.hpp\n *\n *  Author(s): Tamas D. Nagy\n *\tCreated on: 2016-10-25\n *\n *  Static class to generate simple trajectories\n *  built of any corresponding data type.\n *\n */\n\n#ifndef DVRK_TRAJECTORY_FACTORY_HPP_\n#define DVRK_TRAJECTORY_FACTORY_HPP_\n\n#include <iostream>\n#include <vector>\n#include <ros/ros.h>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry> \n#include \"irob_utils/trajectory.hpp\"\n#include \"irob_utils/utils.hpp\"\n#include \"irob_utils/tool_pose.hpp\"\n\n\nnamespace saf {\n\nclass TrajectoryFactory\n{\n\nprivate:\n  TrajectoryFactory() {}\npublic:\n\n\n  /**\n   *\tUniform ramp between x1 and x2.\n   */\n  static Trajectory<double> uniformRamp(int N,\n                                        double x1=0.0, double x2=1.0)\n  {\n    Trajectory<double> v;\n    for (int i = 0; i < N; i++)\n    {\n      v.addPoint(interpolate(((double)i)/(N-1), x1, x2));\n    }\n    return v;\n  }\n\n\n  /**\n   *\tAccelerating ramp between x1 and x2.\n   *\tFor decceleration: acceleratingRamp(N, x2, x1).reverse().\n   */\n  static Trajectory<double> acceleratingRamp(int N,\n                                             double x1=0.0, double x2=1.0)\n  {\n    Trajectory<double> v, steps;\n    double maxStep = (2.0*(x2-x1))/N;\n    steps = uniformRamp(N, 0.0, maxStep);\n\n    double a = x1;\n    for (int i = 0; i < N; i++)\n    {\n      a += steps[i];\n      v.addPoint(interpolate(a, x1, x2));\n    }\n    return v;\n  }\n\n\n  /**\n   *\tSmooth ramp between x1 and x2.\n   */\n  static Trajectory<double> smoothenedRamp(int Nfull, int Nacc, int Ndecc,\n                                           double x1=0.0, double x2=1.0)\n  {\n    Trajectory<double> v, stepsAcc, stepsDecc;\n\n    if (Nfull < Nacc || Nfull < Ndecc)\n      throw std::runtime_error(\"Trajectory Nacc > Nfull\");\n\n    double accRatio = ((double)Nacc) / Nfull;\n    double deccRatio = ((double)Ndecc) / Nfull;\n    double maxStep = (x2-x1)/(Nfull-((Nacc+Ndecc)/2.0));\n    stepsAcc = uniformRamp(Nacc, 0.0, maxStep);\n    stepsDecc = uniformRamp(Ndecc, maxStep, 0.0);\n\n    double a = x1;\n    for (int i = 0; i < Nacc; i++)\n    {\n      a += stepsAcc[i];\n      v.addPoint(interpolate(a, x1, x2));\n    }\n\n    for (int i = 0; i < Nfull-(Nacc + Ndecc); i++)\n    {\n      a += maxStep;\n      v.addPoint(interpolate(a, x1, x2));\n    }\n\n    for (int i = 0; i < Ndecc; i++)\n    {\n      a += stepsDecc[i];\n      v.addPoint(interpolate(a, x1, x2));\n    }\n    return v;\n  }\n\n\n  /**\n   * Linear trajectory between start and end, with constant speed.\n   */\n  template <class P>\n  static Trajectory<P> linearTrajectory(P start,P end,\n                                        double speed, double dt)\n  {\n    Trajectory<P> tr(dt);\n    double stepSize = speed * dt;\n    int N = (int)round(distanceEuler(start, end) / stepSize)+1;\n    Trajectory<double> ramp = uniformRamp(N);\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      tr.addPoint(interpolate(ramp[i], start, end));\n    }\n    return tr;\n  }\n\n  /**\n   *\tSmoothly accelerationg trajectory between 2 points.\n   */\n  template <class P>\n  static Trajectory<P> linearTrajectoryWithSmoothAcceleration(\n      P start,\n      P end,\n      double speed,\n      double acc,\n      double dt)\n  {\n    Trajectory<P> tr(dt);\n    double s_full = distanceEuler(start, end);\n    if (s_full < 0.00001)\n      return tr;\n\n    double t_acc = speed / acc;\n    double s_acc = 0.5 * acc * t_acc * t_acc;\n\n    double t_full = (2.0 * t_acc) + ((s_full-(2.0 * s_acc)) / speed);\n\n    int N_full = (int)round(t_full / dt)+1;\n    int N_acc = (int)round(t_acc / dt)+1;\n\n    Trajectory<double> ramp = smoothenedRamp(N_full, N_acc, N_acc);\n\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      tr.addPoint(interpolate(ramp[i], start, end));\n    }\n    return tr;\n  }\n\n\n  /**\n     *\tSmoothly accelerationg trajectory between 2 points with waypoints.\n     */\n  template <class P>\n  static Trajectory<P> linearTrajectoryWithSmoothAcceleration(\n      P start,\n      std::vector<P> waypoints,\n      P end,\n      double speed,\n      double acc,\n      double dt)\n  {\n    if (waypoints.empty())\n      return linearTrajectoryWithSmoothAcceleration(\n            start, end, speed, acc, dt);\n    Trajectory<P> tr(dt);\n\n    // To first waypoints\n    double s_full = distanceEuler(start,  waypoints[0]);\n    double t_acc = speed / acc;\n    double s_acc = 0.5 * acc * t_acc * t_acc;\n    double t_full = t_acc + ((s_full-s_acc) / speed);\n\n    int N_full = (int)round(t_full / dt)+1;\n    int N_acc = (int)round(t_acc / dt)+1;\n    Trajectory<double> acc_ramp = smoothenedRamp(N_full, N_acc, 0);\n\n    for (int i = 0; i < acc_ramp.size(); i++)\n    {\n      tr.addPoint(interpolate(acc_ramp[i], start, waypoints[0]));\n    }\n\n    // Between waypoints\n    for(typename std::vector<P>::size_type i = 0;\n        i < waypoints.size()-1; i++)\n    {\n      s_full = distanceEuler(waypoints[i],waypoints[i+1]);\n      t_full = s_full / speed;\n\n      N_full = (int)round(t_full / dt)+1;\n      Trajectory<double> ramp = uniformRamp(N_full);\n      for (int j = 0; j < ramp.size(); j++)\n      {\n        tr.addPoint(interpolate(ramp[j],\n                                waypoints[i],\n                                waypoints[i+1]));\n      }\n    }\n\n    // To endpoint\n    s_full = distanceEuler(waypoints.back(), end);\n    t_acc = speed / acc;\n    s_acc = 0.5 * acc * t_acc * t_acc;\n    t_full = t_acc + ((s_full-s_acc) / speed);\n\n    N_full = (int)round(t_full / dt)+1;\n    N_acc = (int)round(t_acc / dt)+1;\n\n    Trajectory<double> decc_ramp = smoothenedRamp(N_full, 0, N_acc);\n    for (int i = 0; i < decc_ramp.size(); i++)\n    {\n      tr.addPoint(interpolate(decc_ramp[i],\n                              waypoints.back(),\n                              end));\n    }\n\n    return tr;\n  }\n\n\n  /**\n   * Horizontal circular trajectory around center.\n   */\n  static Trajectory<Eigen::Vector3d> circleTrajectoryHorizontal(\n      Eigen::Vector3d start,\n      double toAngle, Eigen::Vector3d center,\n      double T, double dt)\n  {\n    Trajectory<Eigen::Vector3d> tr(dt);\n    int N = (int)round(T / dt)+1;\n    Trajectory<double> ramp = uniformRamp(N, 0.0, toAngle);\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      Eigen::Vector3d p = start-center;\n      Eigen::Vector3d p1(p.x()*cos(ramp[i])-p.y()*sin(ramp[i]),\n                         p.y()*cos(ramp[i])+p.x()*sin(ramp[i]), p.z());\n      Eigen::Vector3d p2 = p1+center;\n      tr.addPoint(p2);\n    }\n    return tr;\n  }\n\n\n  /**\n   * Horizontal circular trajectory around center.\n   */\n  static Trajectory<ToolPose> circleTrajectoryHorizontal(\n      ToolPose start,\n      double toAngle, Eigen::Vector3d center,\n      double T, double dt)\n  {\n    Trajectory<ToolPose> tr(dt);\n    int N = (int)round(T / dt)+1;\n    Trajectory<double> ramp = uniformRamp(N, 0.0, toAngle);\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      Eigen::Vector3d p = start.transform.translation()-center;\n      Eigen::Vector3d p1(p.x()*cos(ramp[i])-p.y()*sin(ramp[i]),\n                         p.y()*cos(ramp[i])+p.x()*sin(ramp[i]), p.z());\n      Eigen::Vector3d p2 = p1+center;\n      ToolPose po2(p2, Eigen::Quaterniond(start.transform.rotation()), start.jaw);\n      tr.addPoint(po2);\n    }\n    return tr;\n  }\n\n\n  /**\n   * Vertical circular trajectory around center in Y plane.\n   */\n  static Trajectory<Eigen::Vector3d> circleTrajectoryVerticalY(\n      Eigen::Vector3d start,\n      double toAngle, Eigen::Vector3d center,\n      double T, double dt)\n  {\n    Trajectory<Eigen::Vector3d> tr(dt);\n    int N = (int)round(T / dt)+1;\n    Trajectory<double> ramp = uniformRamp(N, 0.0, toAngle);\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      Eigen::Vector3d p = start-center;\n      Eigen::Vector3d p1(p.x(),\n                         p.y()*cos(ramp[i])+p.z()*sin(ramp[i]), p.z()*cos(ramp[i])-p.y()*sin(ramp[i]));\n      Eigen::Vector3d p2 = p1+center;\n      tr.addPoint(p2);\n    }\n    return tr;\n  }\n\n\n  /**\n   * Vertical circular trajectory around center in X plane.\n   */\n  static Trajectory<Eigen::Vector3d> circleTrajectoryVerticalX(\n      Eigen::Vector3d start,\n      double toAngle, Eigen::Vector3d center,\n      double T, double dt)\n  {\n    Trajectory<Eigen::Vector3d> tr(dt);\n    int N = (int)round(T / dt)+1;\n    Trajectory<double> ramp = uniformRamp(N, 0.0, toAngle);\n    for (int i = 0; i < ramp.size(); i++)\n    {\n      Eigen::Vector3d p = start-center;\n      Eigen::Vector3d p1(p.x()*cos(ramp[i])+p.z()*sin(ramp[i]),\n                         p.y(), p.z()*cos(ramp[i])-p.x()*sin(ramp[i]));\n      Eigen::Vector3d p2 = p1+center;\n      tr.addPoint(p2);\n    }\n    return tr;\n  }\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "5df761be236ae18537532931d744304e05d0bf60", "size": 8534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 25.8606060606, "max_line_length": 103, "alphanum_fraction": 0.5701898289, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6986271654969143}}
{"text": "#ifndef DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n#define DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n\n// C++ standard library headers\n#include <cstddef>    // for std::size_t\n#include <functional> // for std::function\n\n// Eigen linear algebra library headers\n#include <Eigen/Core>\n\n// Project-specific headers\n#include \"QuadraticLineSearcher.hpp\"\n\nnamespace dznl {\n\n    enum class StepType { NONE, GRAD, BFGS };\n\n    template <typename T>\n    class BFGSOptimizer {\n    private: // ========================================== INTERNAL TYPE ALIASES\n        typedef std::function<T(const T *)> objective_function_t;\n        typedef std::function<void(T *, const T *)> objective_gradient_t;\n\n        typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXT;\n        typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXT;\n\n    private: // =============================================== MEMBER VARIABLES\n        const std::size_t n;\n        const objective_function_t f;\n        const objective_gradient_t g;\n\n        VectorXT x;\n        T fx;\n        VectorXT gx;\n        VectorXT dg;\n\n        T step_size;\n        VectorXT step_dir;\n        VectorXT grad_dir;\n        MatrixXT hess_inv;\n\n        VectorXT temp;\n        std::size_t iter_count;\n        StepType last_step_type;\n\n    public: // ===================================================== CONSTRUCTOR\n        BFGSOptimizer(std::size_t num_dimensions,\n                      const objective_function_t &objective_function,\n                      const objective_gradient_t &objective_gradient)\n                : n(num_dimensions),\n                  f(objective_function),\n                  g(objective_gradient),\n                  x(n),\n                  fx(0),\n                  gx(n),\n                  dg(n),\n                  step_size(0),\n                  step_dir(n),\n                  grad_dir(n),\n                  hess_inv(n, n),\n                  temp(n),\n                  iter_count(0),\n                  last_step_type(StepType::NONE) {\n            hess_inv.setIdentity();\n        }\n\n    public: // ======================================================= ACCESSORS\n        const VectorXT &get_current_point() { return x; }\n\n        T get_current_objective_value() { return fx; }\n\n        const VectorXT &get_current_gradient() { return gx; }\n\n        std::size_t get_iteration_count() { return iter_count; }\n\n        T get_last_step_size() { return step_size; }\n\n        StepType get_last_step_type() { return last_step_type; }\n\n    public: // ======================================================== MUTATORS\n        void set_current_point(const VectorXT &p) {\n            x = p;\n            fx = f(p.data());\n            g(gx.data(), p.data());\n        }\n\n        void set_iteration_count(std::size_t k) { iter_count = k; }\n\n        void set_step_size(const T &h) { step_size = h; }\n\n    private: // ==================================== OPTIMIZATION HELPER METHODS\n        void reset_hessian() { hess_inv.setIdentity(); }\n\n        void update_inverse_hessian() {\n            temp = hess_inv.template selfadjointView<Eigen::Upper>() * dg;\n            const T lambda = step_size * dg.dot(step_dir);\n            const T sigma = (lambda + dg.dot(temp)) / (lambda * lambda);\n            temp -= (step_size * lambda * sigma / 2) * step_dir;\n            hess_inv.template selfadjointView<Eigen::Upper>().rankUpdate(\n                    temp, step_dir, -step_size / lambda);\n        }\n\n        T competitive_line_search() {\n            dznl::QuadraticLineSearcher<T> grad_searcher(f, x, grad_dir);\n            grad_searcher.search(step_size);\n            dznl::QuadraticLineSearcher<T> bfgs_searcher(f, x, step_dir);\n            bfgs_searcher.search(step_size);\n            if (grad_searcher.get_best_objective_value() <\n                bfgs_searcher.get_best_objective_value()) {\n                last_step_type = StepType::GRAD;\n                step_dir = grad_dir;\n                reset_hessian();\n                fx = grad_searcher.get_best_objective_value();\n                return grad_searcher.get_best_step_size();\n            } else {\n                last_step_type = StepType::BFGS;\n                fx = bfgs_searcher.get_best_objective_value();\n                return bfgs_searcher.get_best_step_size();\n            }\n        }\n\n    public: // ============================================ OPTIMIZATION METHODS\n        bool step() {\n            grad_dir = -gx.normalized();\n            step_dir =\n                    -(hess_inv.template selfadjointView<Eigen::Upper>() * gx);\n            step_dir.normalize();\n            const T new_step_size = competitive_line_search();\n            if (new_step_size == 0) { return false; }\n            ++iter_count;\n            step_size = new_step_size;\n            x += step_size * step_dir;\n            g(temp.data(), x.data());\n            dg = temp - gx;\n            gx.swap(temp);\n            update_inverse_hessian();\n            return true;\n        }\n\n    }; // class BFGSOptimizer\n\n} // namespace dznl\n\n#endif // DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n", "meta": {"hexsha": "daf65c1237d2c0603dd285f6ce910cfed155403a", "size": 5049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_stars_repo_name": "dzhang314/dznl", "max_stars_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_issues_repo_name": "dzhang314/dznl", "max_issues_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_forks_repo_name": "dzhang314/dznl", "max_forks_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_forks_repo_licenses": ["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.8206896552, "max_line_length": 80, "alphanum_fraction": 0.5284214696, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127610972518}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2016 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__Eigen__convolution__hpp_INCLUDED_\n#define _mitrax__Eigen__convolution__hpp_INCLUDED_\n\n#include <Eigen/Core>\n\n\nnamespace Eigen{\n\n\n\ttemplate < typename DerivedM, typename DerivedK >\n\tinline auto convolution(\n\t\tMatrixBase< DerivedM > const& m,\n\t\tMatrixBase< DerivedK > const& k\n\t){\n\t\tusing ScalarK = typename DerivedK::Scalar;\n\n\t\tusing ResultType = Matrix< ScalarK, Eigen::Dynamic, Eigen::Dynamic >;\n\n\t\tint kr = k.rows();\n\t\tint kc = k.cols();\n\n\t\tint res_r = m.rows() - kr + 1;\n\t\tint res_c = m.cols() - kc + 1;\n\n\t\tResultType res(res_r, res_c);\n\n\t\tfor(int my = 0; my < res_r; ++my){\n\t\t\tfor(int mx = 0; mx < res_c; ++mx){\n\t\t\t\tScalarK b = 0;\n\n\t\t\t\tfor(int ky = 0; ky < kr; ++ky){\n\t\t\t\t\tfor(int kx = 0; kx < kc; ++kx){\n\t\t\t\t\t\tb += m(my + ky, mx + kx) * k(ky, kx);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tres.coeffRef(my, mx) = b;\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\ttemplate < typename DerivedM, typename DerivedKC, typename DerivedKR >\n\tinline auto convolution(\n\t\tMatrixBase< DerivedM > const& m,\n\t\tMatrixBase< DerivedKC > const& vc,\n\t\tMatrixBase< DerivedKR > const& vr\n\t){\n\t\treturn convolution(convolution(m, vr), vc);\n\t}\n\n}\n\n\n#endif\n", "meta": {"hexsha": "cbda56c21ac67fccd92976e95511b5e7c57e7b92", "size": 1505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1538461538, "max_line_length": 79, "alphanum_fraction": 0.5813953488, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127610972518}}
{"text": "\n#include <iostream>\n#include <cstdlib>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv)\n{\n\tint mag_data_counter = 1000;\n\tFILE * fp;\n\tdouble mag_x, mag_y, mag_z;\n\n\tMatrixXd mat_D(mag_data_counter, 9);\n\tMatrixXd mat_DT;\n\tfp = fopen(\"magdata\", \"r\");\n\n\tfor (int i = 0; i < mag_data_counter; i++)\n\t{\n\n\t\tfscanf(fp, \"%lf %lf %lf\\n\", &mag_x, &mag_y, &mag_z);\n\t\tmat_D(i, 0) = mag_x * mag_x;\n\t\tmat_D(i, 1) = mag_y * mag_y;\n\t\tmat_D(i, 2) = mag_z * mag_z;\n\t\tmat_D(i, 3) = 2 * mag_x * mag_y;\n\t\tmat_D(i, 4) = 2 * mag_x * mag_z;\n\t\tmat_D(i, 5) = 2 * mag_y * mag_z;\n\t\tmat_D(i, 6) = 2 * mag_x;\n\t\tmat_D(i, 7) = 2 * mag_y;\n\t\tmat_D(i, 8) = 2 * mag_z;\n\t}\n\tfclose(fp);\n\tmat_DT = mat_D.transpose();\n\n\tMatrixXd mat_Ones = MatrixXd::Ones(mag_data_counter, 1);\n\n\tMatrixXd mat_Result =  (mat_DT * mat_D).inverse() * (mat_DT * mat_Ones);\n\n\tMatrix<double, 4, 4>  mat_A_4x4;\n\n\tmat_A_4x4(0, 0) = mat_Result(0, 0);\n\tmat_A_4x4(0, 1) = mat_Result(3, 0);\n\tmat_A_4x4(0, 2) = mat_Result(4, 0);\n\tmat_A_4x4(0, 3) = mat_Result(6, 0);\n\n\tmat_A_4x4(1, 0) = mat_Result(3, 0);\n\tmat_A_4x4(1, 1) = mat_Result(1, 0);\n\tmat_A_4x4(1, 2) = mat_Result(5, 0);\n\tmat_A_4x4(1, 3) = mat_Result(7, 0);\n\n\tmat_A_4x4(2, 0) = mat_Result(4, 0);\n\tmat_A_4x4(2, 1) = mat_Result(5, 0);\n\tmat_A_4x4(2, 2) = mat_Result(2, 0);\n\tmat_A_4x4(2, 3) = mat_Result(8, 0);\n\n\tmat_A_4x4(3, 0) = mat_Result(6, 0);\n\tmat_A_4x4(3, 1) = mat_Result(7, 0);\n\tmat_A_4x4(3, 2) = mat_Result(8, 0);\n\tmat_A_4x4(3, 3) = -1.0;\n\n\n\tMatrixXd mat_Center = -((mat_A_4x4.block(0, 0, 3, 3)).inverse() * mat_Result.block(6, 0, 3, 1));\n\n\tMatrix<double, 4, 4>  mat_T_4x4;\n\tmat_T_4x4.setIdentity();\n\tmat_T_4x4.block(3, 0, 1, 3) = mat_Center.transpose();\n\n\tMatrixXd mat_R = mat_T_4x4 * mat_A_4x4 * mat_T_4x4.transpose();\n\n\tEigenSolver<MatrixXd> eig(mat_R.block(0, 0, 3, 3) / -mat_R(3, 3));\n\t//mat_T_4x4(3,0)=mat_Center()\n\tMatrixXd mat_Eigval(3, 1) ;\n\tMatrixXd mat_Evecs(3, 3) ;\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tmat_Evecs(i, j) = (eig.eigenvectors())(i, j).real();\n\t\t}\n\t}\n\tmat_Eigval(0, 0) = (eig.eigenvalues())(0, 0).real();\n\tmat_Eigval(1, 0) = (eig.eigenvalues())(1, 0).real();\n\tmat_Eigval(2, 0) = (eig.eigenvalues())(2, 0).real();\n\tMatrixXd mat_Radii = (1.0 / mat_Eigval.array()).cwiseSqrt();\n\tMatrixXd mat_Scale = MatrixXd::Identity(3, 3) ;\n\tmat_Scale(0, 0) = mat_Radii(0, 0);\n\tmat_Scale(1, 1) = mat_Radii(1, 0);\n\tmat_Scale(2, 2) = mat_Radii(2, 0);\n\tdouble min_Radii = mat_Radii.minCoeff();\n\n\tmat_Scale = mat_Scale.inverse().array() * min_Radii;\n\tMatrixXd mat_Correct = mat_Evecs * mat_Scale * mat_Evecs.transpose();\n\n\n\tcout << \"The Ellipsoid center is:\" << endl << mat_Center << endl;\n\tcout << \"The Ellipsoid radii is:\" << endl << mat_Radii << endl;\n\tcout << \"The scale matrix  is:\" << endl << mat_Scale << endl;\n\tcout << \"The correct matrix  is:\" << endl << mat_Correct << endl;\n\n}", "meta": {"hexsha": "0fdc01a6587d8805621135e52d2cfc3f64bf7338", "size": 2894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_stars_repo_name": "mfkiwl/RTIMULib2", "max_stars_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T10:15:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T12:17:29.000Z", "max_issues_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_issues_repo_name": "mfkiwl/RTIMULib2", "max_issues_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T03:58:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T14:53:58.000Z", "max_forks_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_forks_repo_name": "mfkiwl/RTIMULib2", "max_forks_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T13:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T04:50:39.000Z", "avg_line_length": 27.8269230769, "max_line_length": 97, "alphanum_fraction": 0.6264685556, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899295134923, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6985747406438644}}
{"text": "#ifndef PROPAGATION_HPP\n#define PROPAGATION_HPP\n\n#include <opencv2/core.hpp>\n\n#include <Eigen/Dense>\n\n#include \"../utility/activation.hpp\"\n\n/*! \\file propagation.hpp\n    \\brief collection of propagation algorithms\n*/\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup ml\n *  @{\n */\nnamespace ml{\n\n/**\n *@brief forward propagation of neural network, this function\\n\n *Assume this is a three layers neural network, this function\\n\n *will compute the output of the layer 2\n *@param input The input of the neurals(input of layer 2)\n *@param weight The weight of the input\n *@param bias bias of the input\n *@param output The output of the neurals(output of layer 2).\\n\n * After computation, output.rows == weight.rows && output.cols == input.cols\n *@param func unary functor which apply the activation on\\n\n * the output\n *@pre input, weight and bias cannot be empty, the type of the\\n\n * input, weight, bias and output should be double(CV_64F).\\n\n * weight.cols == input.rows && bias.rows == weight.rows\n */\ntemplate<typename UnaryFunc = sigmoid>\nvoid forward_propagation(cv::Mat const &input,\n                         cv::Mat const &weight,\n                         cv::Mat const &bias,\n                         cv::Mat &output,\n                         UnaryFunc func = UnaryFunc())\n{\n    if(!input.empty() && !weight.empty() &&\n            !bias.empty()){\n        //output = weight * input;\n        cv::gemm(weight, input, 1.0, cv::Mat(),\n                 0.0, output);\n        for(int i = 0; i != output.cols; ++i){\n            output.col(i) += bias;\n        }\n        func(output);\n    }\n}\n\n/**\n *@brief forward propagation of neural network, this function\\n\n *Assume this is a three layers neural network, this function\\n\n *will compute the output of the layer 2\n *@param input The input of the neurals(input of layer 2)\n *@param weight The weight of the input\n *@param bias bias of the input\n *@param output The output of the neurals(output of layer 2).\\n\n * After computation, output.rows == weight.rows && output.cols == input.cols\n *@param func unary functor which apply the activation on\\n\n * the output\n *@pre input, weight and bias cannot be empty.\\n\n * weight.cols == input.rows && bias.rows == weight.rows\n */\ntemplate<typename Derived1,\n         typename Derived2,\n         typename Derived3,\n         typename Derived4,\n         typename UnaryFunc = sigmoid>\nvoid forward_propagation(Eigen::MatrixBase<Derived1> const &input,\n                         Eigen::MatrixBase<Derived2> const &weight,\n                         Eigen::MatrixBase<Derived3> const &bias,\n                         Eigen::MatrixBase<Derived4> &output,\n                         bool no_overlap = true,\n                         UnaryFunc func = UnaryFunc())\n{\n    static_assert(std::is_same<Derived1::Scalar, Derived2::Scalar>::value &&\n                  std::is_same<Derived2::Scalar, Derived3::Scalar>::value &&\n                  std::is_same<Derived4::Scalar, Derived4::Scalar>::value,\n                  \"Data type of matrix input, weight, bias and output should be the same\");\n\n    if(input.rows() != 0 && weight.rows() != 0 &&\n            bias.rows() != 0){        \n        if(no_overlap){\n            output.noalias() = weight * input;\n        }else{\n            output = weight * input;\n        }\n\n        using Scalar = typename Derived3::Scalar;\n        using MatType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n        using Mapper = Eigen::Map<const MatType, Eigen::Aligned>;\n        Mapper Map(&bias(0, 0), bias.size());\n        output.colwise() += Map;\n        func(output);\n    }\n}\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // PROPAGATION_HPP\n\n", "meta": {"hexsha": "7ce6c903ac620a6a025f732d29d0252c0170cb45", "size": 3694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/deep_learning/propagation.hpp", "max_stars_repo_name": "stereomatchingkiss/ocv_libs", "max_stars_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-12-17T05:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T02:59:29.000Z", "max_issues_repo_path": "ml/deep_learning/propagation.hpp", "max_issues_repo_name": "stereomatchingkiss/ocv_libs", "max_issues_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "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": "ml/deep_learning/propagation.hpp", "max_forks_repo_name": "stereomatchingkiss/ocv_libs", "max_forks_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-05-10T11:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T17:06:06.000Z", "avg_line_length": 32.4035087719, "max_line_length": 91, "alphanum_fraction": 0.60584732, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6985120173113334}}
{"text": "#include <iostream>\n#include <g2o/core/g2o_core_api.h>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n// vertex: 3d vector\nclass CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  // override the reset function\n  virtual void setToOriginImpl() override {\n    _estimate << 0, 0, 0;\n  }\n\n  // override the plus operator, just plain vector addition\n  virtual void oplusImpl(const double *update) override {\n    _estimate += Eigen::Vector3d(update);\n  }\n\n  // the dummy read/write function\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n};\n\n// edge: 1D error term, connected to exactly one vertex\nclass CurveFittingEdge : public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  CurveFittingEdge(double x) : BaseUnaryEdge(), _x(x) {}\n\n  // define the error term computation\n  virtual void computeError() override {\n    const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);\n    const Eigen::Vector3d abc = v->estimate();\n    _error(0, 0) = _measurement - std::exp(abc(0, 0) * _x * _x + abc(1, 0) * _x + abc(2, 0));\n  }\n\n  // the jacobian\n  virtual void linearizeOplus() override {\n    const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);\n    const Eigen::Vector3d abc = v->estimate();\n    double y = exp(abc[0] * _x * _x + abc[1] * _x + abc[2]);\n    _jacobianOplusXi[0] = -_x * _x * y;\n    _jacobianOplusXi[1] = -_x * y;\n    _jacobianOplusXi[2] = -y;\n  }\n\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n\npublic:\n  double _x;  // x data, note y is given in _measurement\n};\n\nint main(int argc, char **argv) {\n  double ar = 1.0, br = 2.0, cr = 1.0;         // ground\u2212truth values\n  double ae = 2.0, be = -1.0, ce = 5.0;        // initial estimation\n  int N = 100;                                 // num of data points\n  double w_sigma = 1.0;                        // sigma of the noise\n  double inv_sigma = 1.0 / w_sigma;\n  cv::RNG rng;                                 // Random number generator\n\n  vector<double> x_data, y_data;      // the data\n  for (int i = 0; i < N; i++) {\n    double x = i / 100.0;\n    x_data.push_back(x);\n    y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma));\n  }\n\n  // set g2o\n  // Each error term optimizer has a dimension of 3, and the error value has a dimension of 1.\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType;\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // linear solver\n\n  // choose the optimizatoin method from GN, LM, DogLeg\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;   // graph optimizer\n  optimizer.setAlgorithm(solver);   // set the algorithm\n  optimizer.setVerbose(true);       // print the results\n\n  // add vertex\n  CurveFittingVertex *v = new CurveFittingVertex();\n  v->setEstimate(Eigen::Vector3d(ae, be, ce));\n  v->setId(0);\n  optimizer.addVertex(v);\n\n  // add edges\n  for (int i = 0; i < N; i++) {\n    CurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);\n    edge->setId(i);\n    edge->setVertex(0, v);                // connect to the vertex\n    edge->setMeasurement(y_data[i]);      // measurement\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() * 1 / (w_sigma * w_sigma)); // set the information matrix\n    optimizer.addEdge(edge);\n  }\n\n  // carry out the optimization\n  cout << \"start optimization\" << endl;\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n  // print the results\n  Eigen::Vector3d abc_estimate = v->estimate();\n  cout << \"estimated model: \" << abc_estimate.transpose() << endl;\n\n  return 0;\n}", "meta": {"hexsha": "a29ca6d589536a0b3058da5ed124fe5bf6c027b7", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/g2oCurveFitting.cpp", "max_stars_repo_name": "SNU-SF4/slambook2", "max_stars_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_stars_repo_licenses": ["MIT"], "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/g2oCurveFitting.cpp", "max_issues_repo_name": "SNU-SF4/slambook2", "max_issues_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_issues_repo_licenses": ["MIT"], "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/g2oCurveFitting.cpp", "max_forks_repo_name": "SNU-SF4/slambook2", "max_forks_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_forks_repo_licenses": ["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.8976377953, "max_line_length": 122, "alphanum_fraction": 0.6711998245, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.698510416808155}}
{"text": "#ifndef POLYNOMIALS_HPP\n#define POLYNOMIALS_HPP\n\n#include <vector>\n#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nclass Polynomial {\npublic:\n    Polynomial() {}\n    Polynomial(const Polynomial& orig);\n    Polynomial(const vector<double> &coeffs);\n    ~Polynomial() {}\n    \n    void set_coeffs(const vector<double> &coeffs);\n    vector<double> get_coeffs() const;\n\n    void polyfit(const Eigen::VectorXd &xvals,\n                 const Eigen::VectorXd &yvals,\n                 const int order);\n    void polyfit(const vector<double> &xvals,\n                 const vector<double> &yvals,\n                 const int order);\n\n    double polyeval(const double x) const;\n    double polyeval_d(const double x) const;\n    double polyeval_dd(const double x) const;\n    double polyeval_ddd(const double x) const;\n    vector<double> polyeval(const vector<double> &x) const;\n    vector<double> polyeval_d(const vector<double> &x) const;\n    vector<double> polyeval_dd(const vector<double> &x) const;\n    vector<double> polyeval_ddd(const vector<double> &x) const;\n\nprivate:\n    double polyeval(const double x,\n                    const vector<double> &coeffs) const;\n    vector<double> polyeval(const vector<double> &x,\n                            const vector<double> &coeffs) const;    \n    vector<double> _coeffs;\n    vector<double> _coeffs_d;\n    vector<double> _coeffs_dd;\n    vector<double> _coeffs_ddd;\n};\n\n#endif // POLYNOMIALS_HPP\n\n", "meta": {"hexsha": "b3a784758c9f2621b35578fad3ad0e8ffab9ec41", "size": 1487, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomials.hpp", "max_stars_repo_name": "da-phil/SDC-Path-Planning", "max_stars_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:27:54.000Z", "max_issues_repo_path": "src/polynomials.hpp", "max_issues_repo_name": "da-phil/SDC-Path-Planning", "max_issues_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_issues_repo_licenses": ["MIT"], "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/polynomials.hpp", "max_forks_repo_name": "da-phil/SDC-Path-Planning", "max_forks_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_forks_repo_licenses": ["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.5961538462, "max_line_length": 68, "alphanum_fraction": 0.661062542, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8006919949619792, "lm_q1q2_score": 0.6984815650454697}}
{"text": "/*\n * oper_matrix.cpp\n *\n *  Created on: 2017. 6. 6.\n *      Author: cho\n */\n\n#include <random>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n//#include \"io.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/// number of data\nconst unsigned int N = 5;\n\nint main() {\n\tcout << \"==== START \" << endl;\n\trandom_device rd;     // seed, rd()\n\tmt19937_64 gen(4);    // random number generator\n\n\tublas::vector<double> t (N); // time vector, sec\n\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = i+1;\n\tcout << \"t(\"<<N<<\") = \" << t << endl;\n\n\tuniform_int_distribution<int> dis_y( 0, 10 );\n\tublas::vector<double> y (N); // measured value\n\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\tcout << \"y(\"<<N<<\") = \" << y << endl;\n\n\t//const double m_init[N][N] = { {1, 2}, {3, 4} };\n\tublas::matrix<double> m( N, N );\n\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t\tm (i, j) = i*2 + j + 1;\n\t\t\t//m(i,j) = m_init[i][j];\n\tm(N-1,N-1) = 3;\n\tcout << \"matrix = \" << m << endl;\n\n\tcout << \"\\n==== standard operation : +, -, *(scalar), /(scalar) \" << endl;\n\t{\n\t\tcout << \"t+y = \" << t+y << endl;\n\t\tcout << \"t-y = \" << t-y << endl;\n\t\tcout << \"2*t = \" << 2*t << endl;\n\t\tcout << \"t*3 = \" << t*3 << endl;\n\t\tcout << \"t/2 = \" << t/3 << endl;\n\t\tcout << \"-t  = \" << -t << endl;\n\t}\n\n\tcout << \"\\n==== inner, outer and other products \" << endl;\n\t{\n\t\tcout << \"inner_prod(t, y) = \" << inner_prod( t, y ) << endl;\n\t\tcout << \"inner_prod(y, t) = \" << inner_prod( y, t ) << endl;\n\t\tcout << \"outer_prod(t, y) = \" << outer_prod( t, y ) << endl;\n\t\tcout << \"outer_prod(y, t) = \" << outer_prod( y, t ) << endl;\n\t\tcout << \"element_prod(t, y) = \" << element_prod(t, y) << endl;\n\t\tcout << \"element_prod(y, t) = \" << element_prod(y, t) << endl;\n\t\tcout << \"element_div(t, y)  = \" << element_div(t, y) << endl;\n\t\tcout << \"element_div(y, t)  = \" << element_div(y, t) << endl;\n\t\tcout << \"prod(m, t)  = \" << prod(m, t) << endl;\n\t\tcout << \"prod(t, m)  = \" << prod(t, m) << endl;\n\t\tcout << \"prec_prod(t, m)  = \" << prec_prod(t, m) << endl;\n\t\tcout << \"prec_prod(m, t)  = \" << prec_prod(m, t) << endl;\n\t}\n\n\tcout << \"\\n==== transformations \" << endl;\n\t{\n\t\tcout << \"trans(m) = \" << ublas::trans(m) << endl;\n\t}\n\n\tcout << \"\\n==== triangular matrix \" << endl;\n\t{\n\t\tauto L  = ublas::triangular_adaptor<ublas::matrix<double>, ublas::lower> (m);\n\t\tauto SL = ublas::triangular_adaptor<ublas::matrix<double>, ublas::strict_lower> (m);\n\t\tauto UL = ublas::triangular_adaptor<ublas::matrix<double>, ublas::unit_lower> (m);\n\t\tcout << \"lower        L  = \" << L << endl;\n\t\tcout << \"strict lower SL = \" << SL << endl;\n\t\tcout << \"unit lower   UL = \" << UL << endl;\n\n\t\tauto U =  ublas::triangular_adaptor<ublas::matrix<double>, ublas::upper> (m);\n\t\tauto SU = ublas::triangular_adaptor<ublas::matrix<double>, ublas::strict_upper> (m);\n\t\tauto UU = ublas::triangular_adaptor<ublas::matrix<double>, ublas::unit_upper> (m);\n\t\tcout << \"upper        U  = \" << U << endl;\n\t\tcout << \"strict upper SU = \" << SU << endl;\n\t\tcout << \"unit upper   UU = \" << UU << endl;\n\n\t\tcout << \"prod( U, m ) = \" << prod(U, m) << endl;\n\n\t\tublas::vector<double> x(m.size1());\n\t\tublas::vector<double> b(m.size1(), 1);\n\t\tcout << \"inplace_solve(UL, b, ) : b = \" << b << endl;\n\t\tinplace_solve( UL, b, ublas::unit_lower_tag() );\n\t\tcout << \"inplace_solve(UL, b, ) : b = \" << b << endl;\n\t\tcout << \"prod( UL, b ) = \" << prod( UL, b ) << endl;\n\t}\n\n\tcout << \"\\n==== pumutation matrix \" << endl;\n\t{\n\t\tublas::permutation_matrix<size_t> pm(N);\n\t\tpm(0) = 1;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t\tpm(0) = 0; pm(1) = 0;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t\tpm(0) = 0; pm(1) = 1; pm(2) = 0;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t}\n\n\tcout << \"\\n==== LU factorization\" << endl;\n\t{\n\t\tublas::matrix<double> A(m);\n\t\tublas::permutation_matrix<double> pm(N);\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tbool singular = ublas::lu_factorize( A, pm);\n\t\tcout << \"-- return = \" << singular << endl;\n\t\tcout << \"-- A  = \" << A << endl;\n\t\tcout << \"-- pm = \" << pm << endl;\n\n\t\tauto L = ublas::triangular_adaptor<ublas::matrix<double>, ublas::unit_lower>(A);\n\t\tcout << \"-- L = \" << L << endl;\n\t\tauto U = ublas::triangular_adaptor<ublas::matrix<double>, ublas::upper>(A);\n\t\tcout << \"-- U = \" << U << endl;\n\t\tcout << \"-- LU = \" << prod(L,U) << endl;\n\t\tublas::matrix<double> pmA( m ); // pmA means pm*A, at first init as m\n\t\tswap_rows(pm, pmA);\n\t\tcout << \"-- swap_rows(pm,A) = \" << pmA << endl;\n\n\t\tcout << \"-- solve Lz = b -------------\" << endl;\n\t\tublas::vector<double> b( N ); b(0) = 1; b(1) = 2; b(2) = 3;\n\t\tublas::vector<double> z( b );\n\t\tcout << \"-- L \" << L << endl;\n\t\tcout << \"-- b \" << b << endl;\n\t\tublas::inplace_solve( A, z, ublas::unit_lower_tag() );\n\t\tcout << \"-- z = \" << z << endl;\n\t\tcout << \"-- confirm Lz = \" << prod( L, z ) << endl;\n\n\t\tcout << \"-- solve Ux = z -------------\" << endl;\n\t\tublas::vector<double> x( z );\n\t\tcout << \"-- U \" << U << endl;\n\t\tcout << \"-- z \" << z << endl;\n\t\tinplace_solve( A, x, ublas::upper_tag() );\n\t\tcout << \"-- x = \" << x << endl;\n\t\tcout << \"-- confirm Ux = \" << prod( U, x ) << endl;\n\t}\n\n\tcout << \"==== END \" << endl;\n}\n", "meta": {"hexsha": "bda7363d360c1808e9ee524cbe49726de2c86bfd", "size": 5526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_ublas/oper_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/oper_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/oper_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": 34.7547169811, "max_line_length": 86, "alphanum_fraction": 0.5200868621, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6982486178861433}}
{"text": "#ifndef MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n#define MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n\n#include <Eigen/Core>\n#include <functional>\n#include <iostream>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        /// \\brief Run the backtracking line search.\n        ///\n        /// \\details The algorithm is described in the book (Algorithm 3.1: Backtracking Line Search).\n        ///\n        /// This algorithm tries to find an appropriate step size that satisfies the Armijo condition (i.e., the\n        /// safficient decreasing condition). This algorithm runs faster than the line search algorithm for the strong\n        /// Wolfe conditions, but it does not guarantee the curvature condition, which is required to stabilize the\n        /// overall optimization.\n        inline double RunBacktrackingLineSearch(const std::function<double(const Eigen::VectorXd&)>& f,\n                                                const Eigen::VectorXd&                               grad,\n                                                const Eigen::VectorXd&                               x,\n                                                const Eigen::VectorXd&                               p,\n                                                const double                                         alpha_init,\n                                                const double                                         rho,\n                                                const double                                         c = 1e-04)\n        {\n            constexpr unsigned int max_num_iters = 50;\n\n            assert(p.size() == x.size());\n\n            double alpha = alpha_init;\n\n            for (int iter = 0; iter < max_num_iters; ++iter)\n            {\n                // Equation 3.4\n                const bool armijo_condition = f(x + alpha * p) <= f(x) + c * alpha * grad.transpose() * p;\n\n                if (armijo_condition)\n                {\n                    return alpha;\n                }\n\n                alpha *= rho;\n            }\n\n            std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n            return alpha;\n        }\n\n        /// \\brief Run the backtracking line search with bound constraints\n        ///\n        /// \\details This function should be slightly slower than the unbounded one since it evaluates bound conditions\n        /// every step.\n        ///\n        /// \\param lower_bound Lower bound of the search space. It can also be a zero-sized vector when there is no\n        /// lower bound condition.\n        ///\n        /// \\param upper_bound Upper bound of the search space. It can also be a zero-sized vector when there is no\n        /// upper bound condition.\n        inline double RunBacktrackingBoundedLineSearch(const std::function<double(const Eigen::VectorXd&)>& f,\n                                                       const Eigen::VectorXd&                               grad,\n                                                       const Eigen::VectorXd&                               x,\n                                                       const Eigen::VectorXd&                               p,\n                                                       const Eigen::VectorXd&                               lower_bound,\n                                                       const Eigen::VectorXd&                               upper_bound,\n                                                       const double                                         alpha_init,\n                                                       const double                                         rho,\n                                                       const double                                         c = 1e-04)\n        {\n            constexpr unsigned int max_num_iters = 50;\n\n            assert(p.size() == x.size());\n\n            double alpha = alpha_init;\n\n            for (int iter = 0; iter < max_num_iters; ++iter)\n            {\n                const Eigen::VectorXd x_new = x + alpha * p;\n\n                // Equation 3.4\n                const bool armijo_condition = f(x_new) <= f(x) + c * alpha * grad.transpose() * p;\n\n                // Bound conditions\n                const bool lower_bound_condition = lower_bound.size() == 0 || (x_new - lower_bound).minCoeff() >= 0.0;\n                const bool upper_bound_condition = upper_bound.size() == 0 || (upper_bound - x_new).minCoeff() >= 0.0;\n\n                if (armijo_condition && lower_bound_condition && upper_bound_condition)\n                {\n                    return alpha;\n                }\n\n                alpha *= rho;\n            }\n\n            std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n            return alpha;\n        }\n    } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n", "meta": {"hexsha": "687042cded4ee473c3b3017783194088cee4dcb7", "size": 4898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/backtracking-line-search.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/backtracking-line-search.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/backtracking-line-search.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": 47.5533980583, "max_line_length": 120, "alphanum_fraction": 0.4501837485, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6981715195229788}}
{"text": "#include <yaml-cpp/yaml.h>\n\n#include <Eigen/Dense>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <chrono>\n#include <iostream>\n#include <vector>\n\n#include \"NumpySaver.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef double type;\n\nconst char* divider = \"#####################################################\";\n\n// copied from https://gist.github.com/lorenzoriano/5414671\ntemplate <typename T>\nstd::vector<T> linspace(T start, T end, size_t N) {\n  T h = (end - start) / static_cast<T>(N - 1);\n  std::vector<T> xs(N);\n  typename std::vector<T>::iterator x;\n  T val;\n  for (x = xs.begin(), val = start; x != xs.end(); ++x, val += h) *x = val;\n  return xs;\n}\n\nSparseMatrix<type> get_5_point_schroedinger_matrix(\n    double xmin, double xmax, unsigned int N,\n    function<double(double)> potential) {\n  // cout << \"Hello from the Beginning of building the matrix\" << endl;\n  SparseMatrix<type> mat(N, N);\n  mat.reserve(5 * N - 6);\n\n  double h = (xmax - xmin) / N;\n  double prefac = 1. / 12. / h / h;\n\n  double x = xmin;\n  for (unsigned int i = 0; i < N; i++, x += h) {\n    if (i >= 2) mat.insert(i, i - 2) = prefac;\n    if (i >= 1) mat.insert(i, i - 1) = -prefac * 16;\n    mat.insert(i, i) = prefac * 30 + potential(x);\n    if (i < N - 1) mat.insert(i, i + 1) = -prefac * 16;\n    if (i < N - 2) mat.insert(i, i + 2) = prefac;\n  }\n  // cout << \"Hello from the End of building the matrix\" << endl;\n\n  return mat;\n}\n\ndouble harmonic_oszi_potential(double x) { return x * x; }\ndouble disturbed_harmonic_oszi_potential(double x, double c1, double c2) {\n  return x * x + c1 * exp(-x * x * c2);\n}\n\nfunction<double(double)> get_potential(YAML::Node potential_conf) {\n  auto pot_name = potential_conf[\"name\"].as<string>();\n\n  if (pot_name == \"harmonic\") {\n    return harmonic_oszi_potential;\n  } else if (pot_name == \"disturbed\") {\n    double c1 = potential_conf[\"c1\"].as<double>();\n    double c2 = potential_conf[\"c2\"].as<double>();\n    return bind(disturbed_harmonic_oszi_potential, std::placeholders::_1, c1,\n                c2);\n  } else {\n    throw runtime_error(\n        \"Potential needs to be either 'harmonic' or 'disturbed'!\");\n  }\n}\n\ntemplate <typename T>\nvector<T> get_values(YAML::Node& node) {\n  auto type = node.Type();\n  // single value\n  if (type == YAML::NodeType::Scalar) {\n    vector<T> ret = {node.as<T>()};\n    return ret;\n  } else if (type == YAML::NodeType::Sequence) {\n    return node.as<vector<T>>();\n  } else if (type == YAML::NodeType::Map) {\n    auto start = node[\"start\"].as<T>();\n    auto end = node[\"end\"].as<T>();\n    auto N = node[\"N\"].as<size_t>();\n    return linspace<T>(start, end, N);\n  } else {\n    throw std::runtime_error(\n        \"Range node must either be list, scalar or a map defining \"\n        \"'start','end' and 'N'.\");\n  }\n}\n\ntuple<VectorXd, type, unsigned int> eigenvector_inverse_power_iteration(\n    SparseMatrix<type>& matrix, VectorXd& start_vector, double shift = 0,\n    double tol = 1e-4, unsigned int max_iterations = 10000) {\n  // apply shift\n  // cout << \"Matrix=\\n\" << matrix;\n  SparseMatrix<type> mat(matrix.rows(), matrix.cols());\n  mat.setIdentity();\n  mat = matrix - shift * mat;\n  // cout << \"Shifted Matrix\\n\" << mat;\n\n  // first do the (sparse) LU decomposition\n  Eigen::SparseLU<Eigen::SparseMatrix<type>, Eigen::COLAMDOrdering<int>> solver;\n  solver.analyzePattern(mat);\n  solver.factorize(mat);\n\n  // now the iteration\n  VectorXd y_now(start_vector);\n  VectorXd y_last;\n\n  // not the best init value, but should work ok\n  type lambda_now = numeric_limits<type>::max();\n  type lambda_last;\n\n  // keep track of iterations\n  unsigned int i = 0;\n\n  do {\n    // normalize vector\n    y_now.normalize();\n    y_last = y_now;\n\n    // iteration\n    y_now = solver.solve(y_last);\n\n    // calculate eigenvector\n    lambda_last = lambda_now;\n    lambda_now = 1 / (y_last.dot(y_now)) + shift;\n\n  } while ((abs(lambda_last - lambda_now) > tol) && i++ < max_iterations);\n\n  return {y_now, lambda_now, i};\n}\n\nvoid test_inverse_power_iteration(YAML::Node& test_configs) {\n  auto size = test_configs.size();\n  for (std::size_t i = 0; i < size; i++) {\n    auto conf = test_configs[i];\n\n    auto N = conf[\"dim\"].as<int>();\n    auto max_iteartions = conf[\"max_iter\"].as<unsigned int>();\n    auto tol = conf[\"tol\"].as<double>();\n\n    MatrixXd matrix = MatrixXd::Random(N, N);\n    matrix = matrix.selfadjointView<Eigen::Lower>();\n    VectorXd start_vector = VectorXd::Random(N);\n    SparseMatrix<type> sparse_view = matrix.sparseView();\n\n    cout << divider << \"# Test Power Iteration \" << i + 1 << \"/\" << size << endl\n         << divider;\n    cout << \"Matrix=\\n\" << matrix;\n    cout << \"\\nStart vector=\\n\" << start_vector;\n    cout << \"\\nTolerance=\" << tol << endl << endl;\n\n    YAML::Node shift_node = conf[\"shift\"];\n    auto shifts = get_values<double>(shift_node);\n\n    // Eigen solution for comparison:\n    EigenSolver<MatrixXd> es(matrix);\n    cout << \"Eigen-Eigenvalues:\" << endl << es.eigenvalues() << endl;\n    cout << \"Eigen-Eigenvectors:\" << endl << es.eigenvectors() << endl << endl;\n\n    for (auto& shift : shifts) {\n      cout << divider << \"Shift=\" << shift << endl;\n\n      auto [eigenvector, eigenvalue, iterations] =\n          eigenvector_inverse_power_iteration(sparse_view, start_vector, shift,\n                                              tol, max_iteartions);\n      cout << \"Iterations needed to reach tolerance: \" << iterations << endl;\n      cout << \"Inverse power Iteration eigenvector is:\\n\" << eigenvector;\n      cout << \"\\nInverse power Iteration eigenvalue is:\\n\" << eigenvalue;\n      if (iterations >= max_iteartions)\n        cerr\n            << \"\\nWarning! Exceeded maximum number of iterations! Solution did \"\n               \"not converge!\"\n            << endl;\n      cout << endl;\n    }\n    cout << endl;\n  }\n}\n\nvoid test_harmonic(YAML::Node& test_configs) {\n  auto size = test_configs.size();\n  for (std::size_t i = 0; i < size; i++) {\n    cout << divider << \"\\n# Test Harmonic Oscillator \" << i + 1 << \"/\" << size\n         << endl\n         << divider << endl\n         << endl;\n    auto conf = test_configs[i];\n\n    auto N = conf[\"N\"].as<size_t>();\n    auto max_iteartions = conf[\"max_iter\"].as<unsigned int>();\n    auto tol = conf[\"tol\"].as<double>();\n    auto xmin = conf[\"xmin\"].as<double>();\n    auto xmax = conf[\"xmax\"].as<double>();\n\n    function<double(double)> pot = get_potential(conf[\"potential\"]);\n    auto matrix = get_5_point_schroedinger_matrix(xmin, xmax, N, pot);\n\n    bool has_name = false;\n    string file_name;\n    if (conf[\"name\"]) {\n      has_name = true;\n      file_name = \"build/output/\" + conf[\"name\"].as<string>() + \".npy\";\n      cout << \"Name to save to: \" << file_name << endl;\n    }\n\n    NumpySaver saver(file_name);\n\n    if (has_name) {\n      VectorXd x_space(N);\n      VectorXd pot_space(N);\n      double h = (xmax - xmin) / N;\n\n      double x = xmin;\n      for (size_t i = 0; i < N; i++, x += h) {\n        x_space[i] = x;\n        pot_space[i] = pot(x);\n      }\n\n      saver << \"x\" << x_space << \"pot\" << pot_space;\n    }\n\n    VectorXd start_vector = VectorXd::Ones(N);\n\n    YAML::Node shift_node = conf[\"shift\"];\n    auto shifts = get_values<double>(shift_node);\n\n    cout << \"Tolerance=\" << tol << endl;\n\n    // Eigen solution for comparison:\n    SelfAdjointEigenSolver<SparseMatrix<type>> es(matrix);\n    if (N < 10) {\n      cout << \"Eigen-Eigenvalues:\" << endl << es.eigenvalues() << endl;\n      cout << \"Eigen-Eigenvectors:\" << endl\n           << es.eigenvectors() << endl\n           << endl;\n      cout << \"Matrix=\\n\" << matrix << endl;\n      cout << \"Start vector=\\n\" << start_vector << endl;\n    }\n\n    for (auto& shift : shifts) {\n      cout << divider << \"Shift=\" << shift << endl;\n\n      auto [eigenvector, eigenvalue, iterations] =\n          eigenvector_inverse_power_iteration(matrix, start_vector, shift, tol,\n                                              max_iteartions);\n\n      if (has_name) saver << \"ev\" << eigenvector;\n\n      cout << \"Iterations=\" << iterations << endl;\n\n      if (N < 10)\n        cout << \"Inverse power Iteration eigenvector = \\n\"\n             << eigenvector << endl;\n\n      cout << \"Inverse power Iteration eigenvalue = \" << eigenvalue << endl;\n\n      if (iterations >= max_iteartions)\n        cerr << \"Warning! Exceeded maximum number of iterations! Solution did \"\n                \"not converge!\"\n             << endl;\n\n      cout << endl;\n    }\n    cout << endl;\n  }\n}\n\nvoid run_tests() {\n  cout << divider << divider << \"## RUNNING TESTS\\n\"\n       << divider << divider << endl\n       << endl;\n\n  YAML::Node config = YAML::LoadFile(\"test.yaml\");\n\n  auto config_power_iter = config[\"inverse_iteration\"];\n  test_inverse_power_iteration(config_power_iter);\n\n  auto config_harmonic = config[\"harmonic\"];\n  test_harmonic(config_harmonic);\n}\n\nvoid run_program() {\n  YAML::Node configs = YAML::LoadFile(\"config.yaml\");\n  auto size = configs.size();\n\n  for (std::size_t i = 0; i < size; i++) {\n    cout << divider << divider << \"\\n# Running Simulation  \" << i + 1 << \"/\"\n         << size << endl\n         << divider << divider << endl;\n    auto conf = configs[i];\n\n    auto N = conf[\"N\"].as<size_t>();\n    auto max_iteartions = conf[\"max_iter\"].as<unsigned int>();\n    auto tol = conf[\"tol\"].as<double>();\n    auto xmin = conf[\"xmin\"].as<double>();\n    auto xmax = conf[\"xmax\"].as<double>();\n\n    function<double(double)> pot = get_potential(conf[\"potential\"]);\n    auto matrix = get_5_point_schroedinger_matrix(xmin, xmax, N, pot);\n    VectorXd start_vector = VectorXd::Ones(N);\n\n    bool has_name = false;\n    string file_name;\n    if (conf[\"name\"]) {\n      has_name = true;\n      file_name = \"build/output/\" + conf[\"name\"].as<string>() + \".npy\";\n      cout << \"Save to:\\t\" << file_name << endl;\n    }\n\n    NumpySaver saver(file_name);\n\n    if (has_name) {\n      VectorXd x_space(N);\n      VectorXd pot_space(N);\n      double h = (xmax - xmin) / N;\n\n      double x = xmin;\n      for (size_t i = 0; i < N; i++, x += h) {\n        x_space[i] = x;\n        pot_space[i] = pot(x);\n      }\n\n      saver << \"x\" << x_space << \"pot\" << pot_space;\n    }\n\n    YAML::Node shift_node = conf[\"shift\"];\n    auto shifts = get_values<double>(shift_node);\n\n    cout << \"N=\\t\\t\" << N << endl;\n    cout << \"Tolerance=\\t\" << tol << endl;\n    cout << \"xmin=\\t\\t\" << xmin << endl;\n    cout << \"xmax=\\t\\t\" << xmax << endl;\n    cout << \"function=\\t\" << conf[\"potential\"][\"name\"] << endl << endl;\n\n    // to time the methods\n    chrono::steady_clock::time_point start;\n    chrono::duration<double> elapsed_seconds;\n\n    // Eigen solution for comparison:\n    if (N <= 1000) {\n      start = chrono::steady_clock::now();\n\n      SelfAdjointEigenSolver<SparseMatrix<type>> es(matrix);\n      auto ev_ref = es.eigenvalues();\n\n      elapsed_seconds = chrono::steady_clock::now() - start;\n      cout << \"Eigen::SelfAdjointEigenSolver<SparseMatrix> took \"\n           << elapsed_seconds.count() * 1e3 << \"ms\" << endl;\n\n      cout << \"eigenvalues=\" << ev_ref(seq(0, shifts.size())).transpose()\n           << endl\n           << endl;\n\n      auto evec_ref = es.eigenvectors();\n\n      if (has_name)\n        NumpySaver(\"build/output/\" + conf[\"name\"].as<string>() +\n                   \"_reference.npy\")\n            << evec_ref;\n\n      if (N < 10) {\n        cout << \"Eigen-Eigenvalues:\" << endl << ev_ref << endl;\n        cout << \"Eigen-Eigenvectors:\" << endl << evec_ref << endl << endl;\n        cout << \"Matrix=\\n\" << matrix << endl;\n        cout << \"Start vector=\\n\" << start_vector << endl;\n      }\n    } else {\n      cout << \"Not going to test SelfAdjointEigenSolver, since it would take \"\n              \"too long.\"\n           << endl;\n    }\n\n    start = std::chrono::steady_clock::now();\n    for (auto& shift : shifts) {\n      cout << divider << \"\\nShift=\\t\\t\" << shift << endl;\n\n      auto [eigenvector, eigenvalue, iterations] =\n          eigenvector_inverse_power_iteration(matrix, start_vector, shift, tol,\n                                              max_iteartions);\n\n      elapsed_seconds = chrono::steady_clock::now() - start;\n\n      if (has_name) saver << \"ev\" << eigenvector;\n\n      cout << \"elapsed time=\\t\" << elapsed_seconds.count() * 1e3 << \"ms\"\n           << endl;\n\n      cout << \"Iterations=\\t\" << iterations << endl;\n      if (N < 10)\n        cout << \"Inverse power Iteration eigenvector = \\n\"\n             << eigenvector << endl;\n\n      cout << \"eigenvalue=\\t\" << eigenvalue << endl;\n\n      if (iterations >= max_iteartions)\n        cerr << \"Warning! Exceeded maximum number of iterations! Solution did \"\n                \"not converge!\"\n             << endl;\n    }\n    cout << endl;\n  }\n}\n\nint main(int argc, char const* argv[]) {\n  // uncomment this to run the test\n  // run_tests();\n  run_program();\n  return 0;\n}\n", "meta": {"hexsha": "69962b63220b9885603358819bad436f8ba9200a", "size": 12779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project02-Eigenvalues/eigenvalues.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": "Project02-Eigenvalues/eigenvalues.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": "Project02-Eigenvalues/eigenvalues.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": 30.6450839329, "max_line_length": 80, "alphanum_fraction": 0.5816574067, "num_tokens": 3463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.6980093069257037}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n//[transform_sqrt_example\n\n#include <vector>\n#include <algorithm>\n\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/functional/math.hpp>\n\nnamespace compute = boost::compute;\n\nint main()\n{\n    // get default device and setup context\n    compute::device device = compute::system::default_device();\n    compute::context context(device);\n    compute::command_queue queue(context, device);\n\n    // generate random data on the host\n    std::vector<float> host_vector(10000);\n    std::generate(host_vector.begin(), host_vector.end(), rand);\n\n    // create a vector on the device\n    compute::vector<float> device_vector(host_vector.size(), context);\n\n    // transfer data from the host to the device\n    compute::copy(\n        host_vector.begin(), host_vector.end(), device_vector.begin(), queue\n    );\n\n    // calculate the square-root of each element in-place\n    compute::transform(\n        device_vector.begin(),\n        device_vector.end(),\n        device_vector.begin(),\n        compute::sqrt<float>(),\n        queue\n    );\n\n    // copy values back to the host\n    compute::copy(\n        device_vector.begin(), device_vector.end(), host_vector.begin(), queue\n    );\n\n    return 0;\n}\n\n//]\n", "meta": {"hexsha": "e77f41aeeaeb151a630e56dacebec31cab054e41", "size": 1697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/transform_sqrt.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "example/transform_sqrt.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/transform_sqrt.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.7627118644, "max_line_length": 79, "alphanum_fraction": 0.6193282263, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6979870435600991}}
{"text": "// TODO : Dimention Agnosticism\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometry.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace bg = boost::geometry;\nnamespace ublas = boost::numeric::ublas;\n\n// Make vector from 2 points\ntemplate<typename Point>\nublas::vector<double> make_vector(const Point& a, const Point& b)\n{\n\tublas::vector<double> v(2);\n\tv[0] = bg::get<0>(b) - bg::get<0>(a);\n\tv[1] = bg::get<1>(b) - bg::get<1>(a);\n\treturn v;\n}\n\n// Calculate cos from 2 vectors\ndouble cos_from_vecs(const ublas::vector<double>& v1, \n\t\t\t\t\t const ublas::vector<double>& v2) {\n\treturn ublas::inner_prod(v1, v2)/(ublas::norm_2(v1)*ublas::norm_2(v2));\n}\n\n// Calculate cos from 3 points\ntemplate<typename Point>\ndouble cos_from_dots(const Point& a, const Point& b, const Point& c) {\n\treturn cos_from_vecs(make_vector(b,a), make_vector(b,c));\n}\n\ntemplate<typename MultiPoint>\nvoid convex_hull(const MultiPoint& in, MultiPoint& out) {\n\n\ttypedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\n\tpoint_t min_coordinate;\n\n\tbool flag = false;\n\n\t// TODO : Remove points which cannot be a part of a convex hull\n\tfor (const auto &point : in) {\n\t\tif (!flag) {\n\t\t\tbg::set<0>(min_coordinate, bg::get<0>(point));\n\t\t\tbg::set<1>(min_coordinate, bg::get<1>(point));\n\t\t\tflag = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (bg::get<0>(point) < bg::get<0>(min_coordinate) || \n\t\t\t\t(bg::get<0>(point) == bg::get<0>(min_coordinate) &&\n\t\t\t\t bg::get<1>(point) < bg::get<1>(min_coordinate))) {\n\t\t\t\n\t\t\tbg::set<0>(min_coordinate, bg::get<0>(point));\n\t\t\tbg::set<1>(min_coordinate, bg::get<1>(point));\n\t\t}\n\t}\n\t\n\tpoint_t B(bg::get<0>(min_coordinate), bg::get<1>(min_coordinate)-1.0);\t// Before\n\tpoint_t S(bg::get<0>(min_coordinate), bg::get<1>(min_coordinate));\t// Start\n\tpoint_t T;\t// To\n\n\tbg::append(out, S);\n\n\twhile(1) {\n\t\tdouble min_cos_value = 1.0;\n\t\tpoint_t p;\n\t\tfor (const auto &point : in) {\n\t\t\tbg::set<0>(T, bg::get<0>(point));\n\t\t\tbg::set<1>(T, bg::get<1>(point));\n\n\t\t\tif (bg::get<0>(S)==bg::get<0>(T) && bg::get<1>(S)==bg::get<1>(T)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble cos_value = cos_from_dots(B,S,T);\n\n\t\t\tif (cos_value < min_cos_value) {\n\t\t\t\tmin_cos_value = cos_value;\n\t\t\t\tbg::set<0>(p, bg::get<0>(T));\n\t\t\t\tbg::set<1>(p, bg::get<1>(T));\n\t\t\t}\n\t\t}\n\t\tbg::append(out, p);\n\t\tif (bg::get<0>(p)==bg::get<0>(min_coordinate) &&\n\t\t\tbg::get<1>(p)==bg::get<1>(min_coordinate)) {\n\t\t\t// Break because Pi+1 == P0 \n\t\t\tbreak;\n\t\t}\n\n\t\t// B = S\n\t\tbg::set<0>(B, bg::get<0>(S));\n\t\tbg::set<1>(B, bg::get<1>(S));\n\n\t\t// S = p\n\t\tbg::set<0>(S, bg::get<0>(p));\n\t\tbg::set<1>(S, bg::get<1>(p));\n\t}\n}\n\n\n\n", "meta": {"hexsha": "37eae7193f487d9559a0945510664a7982a96232", "size": 2553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "convex_hull.hpp", "max_stars_repo_name": "rika77/boost", "max_stars_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T00:17:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T00:17:47.000Z", "max_issues_repo_path": "convex_hull.hpp", "max_issues_repo_name": "rika77/convex_hull_with_boost", "max_issues_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convex_hull.hpp", "max_forks_repo_name": "rika77/convex_hull_with_boost", "max_forks_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_forks_repo_licenses": ["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.2772277228, "max_line_length": 81, "alphanum_fraction": 0.6153544849, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6979870412896301}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\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 explicit Forward Euler scheme\n//!\n//! @param vertices the list of vertices that build the triangular mesh\n//! @param triangles the list of indices that represent the triangular mesh\n//! @param u0 the initial data\n//! @param gamma the parameter gamma (has to do with the boundary conditions)\n//! @param m number of timesteps to perform\n//! @returns a pair which contains as first parameter the solution at time = 1,\n//!          and second parameter the energy evolving over time.\nstd::pair<Eigen::VectorXd, std::vector<double>> radiativeTimeEvolutionExplicit(const Eigen::MatrixXd &vertices,\n                                                                               const Eigen::MatrixXi &triangles,\n                                                                               const Eigen::VectorXd &u0,\n                                                                               const double           gamma,\n                                                                               const int              m) {\n\tstd::vector<double> energy;\n\tEigen::VectorXd     u(u0.size());\n\tu = u0;\n\n\tdouble dt = 1.0 / m;\n\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 and solvers\n\tSparseMatrix M = assembleMassMatrix(vertices, triangles);\n\tSparseMatrix A = assembleStiffnessMatrix(vertices, triangles);\n\tSparseMatrix B = assembleBoundaryMatrix(vertices, edges, gamma);\n\tA += B;\n\n\tEigen::SimplicialLDLT<SparseMatrix> 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\t// (write your solution here)\n\tfor (int timestep = 0; timestep < m; ++timestep) {\n\t\t// Step the solution forward in time\n\t\t// (write your solution here)\n\t\tu += SolverM.solve(-1.0 * dt * A * u).eval();\n\n\t\tenergy.push_back(u.sum() / u.rows());\n\t}\n\n\treturn std::make_pair(u, energy);\n}\n", "meta": {"hexsha": "fda557867a736ad373b7591c381ac0c49cf1cd40", "size": 2229, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/time_evolution_explicit.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_explicit.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_explicit.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.7796610169, "max_line_length": 112, "alphanum_fraction": 0.6173171826, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6979499093450098}}
{"text": "/*\n * @Description: utils for ceres residual block analytic Jacobians\n * @Author: Ge Yao\n * @Date: 2020-11-29 15:47:49\n */\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <sophus/so3.hpp>\n\nnamespace sliding_window {\n\nEigen::Matrix3d JacobianRInv(const Eigen::Vector3d &w) {\n    Eigen::Matrix3d J_r_inv = Eigen::Matrix3d::Identity();\n\n    double theta = w.norm();\n\n    if ( theta > 1e-5 ) {\n        Eigen::Vector3d k = w.normalized();\n        Eigen::Matrix3d K = Sophus::SO3d::hat(k);\n        \n        J_r_inv = J_r_inv \n                  + 0.5 * K\n                  + (1.0 - (1.0 + std::cos(theta)) * theta / (2.0 * std::sin(theta))) * K * K;\n    }\n\n    return J_r_inv;\n}\n\n} // namespace sliding_window\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_", "meta": {"hexsha": "92dfdb5826f14dc400df6e486a2e4fce33a46112", "size": 916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 25.4444444444, "max_line_length": 94, "alphanum_fraction": 0.6517467249, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6979499071931902}}
{"text": "/*\n ISC License\n\n Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder\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 <stdio.h>\n#include <stdlib.h>\n#include \"gaussMarkovCheck.h\"\n#include <Eigen/Dense>\n#include \"utilities/avsEigenSupport.h\"\n#include \"utilities/gauss_markov.h\"\n#include <iostream>\n\n\nuint64_t testGaussMarkov()\n{\n    uint64_t failures = 0;\n    uint64_t seedIn = 1000;\n    Eigen::Matrix2d propIn;\n    propIn << 1,1,0,1;\n    Eigen::Matrix2d covar;\n    covar << 1500,0,0,1.5;\n    Eigen::Vector2d bounds;\n    bounds << 1e-15, 1e-15; //small but non-zero required for \"white\" noise\n    GaussMarkov errorModel;\n    errorModel = GaussMarkov(2);\n    errorModel.setRNGSeed(seedIn);\n    errorModel.setPropMatrix(propIn);\n    errorModel.setNoiseMatrix(covar);\n    errorModel.setUpperBounds(bounds);\n    uint64_t numPts = 100000;\n    \n    Eigen::MatrixXd noiseOut;\n    noiseOut.resize(2, numPts);\n    \n    for(uint64_t i = 0; i < numPts; i++){\n        errorModel.computeNextState();\n        noiseOut.block(0, i, 2, 1) = errorModel.getCurrentState();\n    }\n    \n    //Test if the std deviation is what we asked for\n    Eigen::Vector2d stds = calculateSD(noiseOut, numPts);\n    Eigen::Vector2d stdsIn;\n    stdsIn(0) = covar(0,0) / 1.5;\n    stdsIn(1) = covar(1,1) / 1.5;\n    failures += (stdsIn(0) - stds(0))/(stdsIn(0)) > 0.1 ? 1 : 0;\n    failures += (stdsIn(1) - stds(1))/(stdsIn(1)) > 0.1 ? 1 : 0;\n    \n    //Test if the mean is zero\n    Eigen::Vector2d means = noiseOut.rowwise().mean();\n    Eigen::Vector2d meansIn;\n    meansIn << 0, 0;\n    failures += fabs(meansIn(0) - means(0)) > 5 ? 1 : 0;\n    failures += fabs(meansIn(1) - means(1)) > .05 ? 1 : 0;\n    seedIn = 1500;\n    propIn << 1,0,0,1;\n    covar << 1.5,0,0,0.015;\n    bounds << 10., 0.1;\n    errorModel = GaussMarkov(2);\n    errorModel.setRNGSeed(seedIn);\n    errorModel.setPropMatrix(propIn);\n    errorModel.setNoiseMatrix(covar);\n    errorModel.setUpperBounds(bounds);\n    \n    Eigen::Vector2d maxOut;\n    maxOut.fill(0.0);\n    Eigen::Vector2d minOut;\n    minOut.fill(0.0);\n    \n    numPts = 1e6;\n    \n    noiseOut.resize(2,numPts);\n    \n    for(uint64_t i = 0; i < numPts; i++){\n        errorModel.computeNextState();\n        noiseOut.block(0, i, 2, 1) = errorModel.getCurrentState();\n        if (noiseOut(0,i) > maxOut(0)){\n            maxOut(0) = noiseOut(0,i);\n        }\n        if (noiseOut(0,i) < minOut(0)){\n            minOut(0) = noiseOut(0,i);\n        }\n        if (noiseOut(1,i) > maxOut(1)){\n            maxOut(1) = noiseOut(1,i);\n        }\n        if (noiseOut(1,i) < minOut(1)){\n            minOut(1) = noiseOut(1,i);\n        }\n    }\n    \n    //Test the bounds\n    failures += fabs(12.481655180914322 - maxOut(0)) / 12.481655180914322 > 5e-1 ? 1 : 0;\n    failures += fabs(0.12052269089286843 - maxOut(1)) / 0.12052269089286843 > 5e-1 ? 1 : 0;\n    failures += fabs(-12.230618182796439 - minOut(0)) / -12.230618182796439 > 5e-1 ? 1 : 0;\n    failures += fabs(-0.12055787311661936 - minOut(1)) / -0.12055787311661936 > 5e-1 ? 1 : 0;\n\n    return failures;\n    \n}\n\nEigen::Vector2d calculateSD(Eigen::MatrixXd dat, uint64_t numPts)\n{\n    \n    Eigen::Vector2d sum = dat.rowwise().sum();\n    \n    Eigen::Vector2d means = sum / numPts;\n    Eigen::MatrixXd mean;\n    mean.resize(2, numPts);\n    mean.block(0, 0, 1, numPts).fill(means(0) / numPts);\n    mean.block(1, 0, 1, numPts).fill(means(1) / numPts);\n    \n    Eigen::MatrixXd resid = dat - mean;\n    resid = resid.cwiseProduct(resid);\n    Eigen::MatrixXd stnd = resid.rowwise().sum();\n    stnd = stnd / numPts;\n    stnd = stnd.array().sqrt().matrix();\n\n    return stnd;\n}\n\n\n\n", "meta": {"hexsha": "d6103a6293a2d7a1610c8795051968f17f0084be", "size": 4306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/utilitiesSelfCheck/gaussMarkovCheck.cpp", "max_stars_repo_name": "ian-cooke/basilisk_mag", "max_stars_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "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/simulation/utilitiesSelfCheck/gaussMarkovCheck.cpp", "max_issues_repo_name": "ian-cooke/basilisk_mag", "max_issues_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-13T20:52:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-13T20:52:22.000Z", "max_forks_repo_path": "src/simulation/utilitiesSelfCheck/gaussMarkovCheck.cpp", "max_forks_repo_name": "ian-cooke/basilisk_mag", "max_forks_repo_head_hexsha": "a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14", "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": 31.4306569343, "max_line_length": 93, "alphanum_fraction": 0.6346957733, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.697949907031134}}
{"text": "/**\n * @file visual_ekf.hpp\n * @author Ziyou Zhang (ziyou.zhang@outlook.com)\n * @brief Design of visual-based EKF estimation of dynamic object state.\n * @version 0.1\n * @date 2020-09-18\n * \n * @copyright Copyright (c) 2020\n * \n */\n\n#ifndef VISUAL_EKF_HPP_\n#define VISUAL_EKF_HPP_\n\n#include <ros/ros.h>\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <fstream>\n\nstruct ObjectState\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    double mass;\n    double timestamp;                            // Time stamp in seconds.\n    Eigen::Vector3d r_W;                         // The position relative to the W frame.\n    Eigen::Quaterniond q_WO;                     // The quaternion of rotation W-O.\n    Eigen::Vector3d v_O;                         // The velocity expressed in object frame.\n    Eigen::Vector3d omega_O;                     // The angular velocity expressed in object frame.\n    Eigen::Matrix<double, 3, 3> inertia;         //The moment of inertia.\n    Eigen::Matrix<double, 3, 3> inertia_inverse; // The inverse of moment of inertia, stored for better efficiency.\n\n    ObjectState()\n    {\n        inertia << 0.5 / 12, 0, 0,\n            0, 0.5 / 12, 0,\n            0, 0, 0.5 / 12;\n\n        inertia_inverse = inertia.inverse();\n    }\n};\n\nstruct ObjectStateDerivative\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    double timestamp;            // Time stamp in seconds.\n    Eigen::Vector3d r_W_dot;     // The position relative to the W frame.\n    Eigen::Quaterniond q_WO_dot; // The quaternion of rotation W-O.\n    Eigen::Vector3d v_O_dot;     // The velocity expressed in object frame.\n    Eigen::Vector3d omega_O_dot; // The angular velocity expressed in object frame.\n};\n\nstruct ApriltagMeasurement\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    double timestamp;        // Time stamp in seconds.\n    Eigen::Vector3d r_W;     // The position relative to the W frame.\n    Eigen::Quaterniond q_WO; // The quaternion of rotation W-O.\n};\n\nclass VisualEKF\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    VisualEKF();\n    ~VisualEKF();\n\n    /**\n     * @brief The initialisation state.\n     * \n     * @return true if initialised\n     * @return false if not initialised\n     */\n    bool isInitialsed();\n\n    /**\n     * @brief Initialise the EKF with the initial state.\n     * \n     * @param initialState Initial object state.\n     * @return true if successfully executed.\n     */\n    bool initialise(const ObjectState initialState);\n\n    /**\n     * @brief The predict step in EKF.\n     * \n     * @param dt The time difference.\n     * @param fromState The previous state.\n     * @param toState The predicted state.\n     * @return true if successfully executed.\n     */\n    bool predict(const double dt,\n                 const ObjectState &fromState,\n                 ObjectState &toState);\n\n    /**\n     * @brief The update step in EKF.\n     * \n     * @param apriltagMeasurement The apriltag measurement (pose and oritation of the object).\n     * @return true if successfully executed.\n     */\n    bool update(const ApriltagMeasurement apriltagMeasurement);\n\n    /**\n     * @brief The state transition using trapezoidal numerical integration.\n     * \n     * @param object_state_k_minues_1 The state at previous step.\n     * @param object_state_1 The resulting state after trapezoidal numerical integration.\n     * @param dt The time difference.\n     * @param jacobian The jacobian matrix to be calculated.\n     * @return true if successfully executed.\n     */\n    bool stateTransition(const ObjectState &object_state_k_minues_1,\n                         ObjectState &object_state_1,\n                         const double dt,\n                         Eigen::Matrix<double, 13, 13> &jacobian);\n\n    /**\n     * @brief Calculate the derivatives based on the motion model.\n     * \n     * @param state The object state.\n     * @return ObjectStateDerivative The object state derivatives.\n     */\n    ObjectStateDerivative calcStateDerivative(const ObjectState &state);\n\n    /**\n     * @brief Calculate the jacobian matrix.\n     * \n     * @param state The object state.\n     * @param dt The time difference.\n     * @param jacobian The jacobian matrix to be calculated.\n     * @return true if successfully executed.\n     */\n    bool calcJacobian(const ObjectState &state,\n                      const double &dt,\n                      Eigen::Matrix<double, 13, 13> &jacobian);\n\nprivate:\n    // The object states.\n    ObjectState x_;\n    ObjectState x_predicted_;\n    ObjectState x_temp_;\n\n    // The initialsation information.\n    bool initialised = false;\n\n    // The error matrix and jacobian matrix.\n    Eigen::Matrix<double, 13, 13> P_;\n    Eigen::Matrix<double, 13, 13> jacobian;\n\n    // Process noise params.\n    double sigma_c_r_W = 0.2;     // m, location error\n    double sigma_c_q_WO = 0.4;    // N/A, for quoternion error\n    double sigma_c_v_O = 3;     // m/s, velocity error\n    double sigma_c_omega_O = 10; // rad/s, amgular velocity error\n\n    //Measurement noise params.\n    double sigma_z_r_W = 0.02;  // m, pose measurement error\n    double sigma_z_q_WO = 0.02; // N/A, quaternion measurement error\n\n    friend class PoseDetector;\n};\n\n#endif // VISUAL_EKF_HPP_", "meta": {"hexsha": "48364d9ec8fbaa068468cd237ba44201afdb0132", "size": 5161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/visual_ekf.hpp", "max_stars_repo_name": "ZiyouZhang/rotors_datmo", "max_stars_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T23:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T06:34:30.000Z", "max_issues_repo_path": "include/visual_ekf.hpp", "max_issues_repo_name": "ZiyouZhang/rotors_datmo", "max_issues_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_issues_repo_licenses": ["MIT"], "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/visual_ekf.hpp", "max_forks_repo_name": "ZiyouZhang/rotors_datmo", "max_forks_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_forks_repo_licenses": ["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.4695121951, "max_line_length": 115, "alphanum_fraction": 0.6365045534, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6979499024033824}}
{"text": "// \u4ee5\u4e0b\u4ee3\u7801\u53c2\u8003\n// Eigen\u63d0\u53d6block\uff1ahttps://blog.csdn.net/jiahao62/article/details/80655542\n// Eigen\u63d0\u53d6block:https://www.cnblogs.com/newneul/p/8306430.html\n// \u6c42\u89e3Ax=b\uff1ahttps://www.cnblogs.com/newneul/p/8306442.html\n\n#include <iostream>\nusing namespace std;\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\n#define EQUATION_NUM 3\n#define VARIABLE_NUM 3\n\nint main( int argc, char** argv )\n{\n    // Eigen\u63d0\u53d6block\n    Eigen::Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN = Eigen::MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );\n    cout << \"before assign \\n\" << matrix_NN.block(0, 0, 3, 3) << endl;\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Identity();\n    matrix_NN.block(0, 0, 3, 3) = matrix_33;\n    cout << \"after assign \\n\"  << matrix_NN.block(0, 0, 3, 3) << endl;\n\n    //-------------------------------------------------------------------------------------\n    // \u6c42\u89e3Ax=b\n    Eigen::Matrix<double, EQUATION_NUM, VARIABLE_NUM> A = Eigen::MatrixXd::Random(EQUATION_NUM, VARIABLE_NUM);\n    Eigen::Matrix<double, EQUATION_NUM, 1> b = Eigen::MatrixXd::Random(EQUATION_NUM, 1);\n    // \u6d4b\u8bd5\u7528\u4f8b\n    A << 10,3,1,2,-10,3,1,3,10;\n    b << 14,-5,14;\n    // \u8bbe\u7f6e\u89e3\u53d8\u91cf\n    Eigen::Matrix<double, VARIABLE_NUM, 1> x;\n\n    clock_t time_stt = clock(); // \u8ba1\u65f6\n    \n    // \u65b9\u6cd5\u4e00\uff1a\u76f4\u63a5\u6c42\u9006\uff0c\u9002\u7528\u6761\u4ef6\uff1a\u65b9\u9635\n    x = A.inverse()*b;\n    cout <<\"time use in normal inverse is \"   << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << \"ms\"<< endl;\n    \n\t  // \u65b9\u6cd5\u4e8c\uff1aQR\u5206\u89e3\uff0c\u9002\u7528\u6761\u4ef6\uff1a\u65b9\u9635\u548c\u975e\u65b9\u9635\n    // \u5f53\u65b9\u7a0b\u7ec4\u6709\u89e3\u65f6\u7684\u51fa\u7684\u662f\u771f\u89e3\uff0c\u82e5\u65b9\u7a0b\u7ec4\u65e0\u89e3\u5f97\u51fa\u7684\u662f\u8fd1\u4f3c\u89e3\n    time_stt = clock();\n    x = A.colPivHouseholderQr().solve(b);\n    cout << \"x^T = \" << x.transpose() <<endl;\n    cout <<\"time use in Qr decomposition is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    // \u65b9\u6cd5\u4e09\uff1a\u6700\u5c0f\u4e8c\u4e58\u6cd5\uff0c\u9002\u7528\u6761\u4ef6\uff1a\u65b9\u9635\u548c\u975e\u65b9\u9635\n    // \u65b9\u7a0b\u7ec4\u6709\u89e3\u65f6\u5f97\u51fa\u771f\u89e3\uff0c\u5426\u5219\u662f\u6700\u5c0f\u4e8c\u4e58\u89e3(\u5728\u6c42\u89e3\u8fc7\u7a0b\u4e2d\u53ef\u4ee5\u7528QR\u5206\u89e3 \u5206\u89e3\u6700\u5c0f\u4e8c\u6210\u7684\u7cfb\u6570\u77e9\u9635)\n    time_stt = clock();\n    x = (A.transpose() * A ).inverse() * (A.transpose() * b);\n    cout << \"x^T = \" << x.transpose() <<endl;\n    cout <<\"time use in least square is \"     << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    // \u65b9\u6cd5\u56db\uff1aLU\u5206\u89e3\u6cd5\uff0c\u9002\u7528\u6761\u4ef6\uff1a\u65b9\u9635\n    // \u6ee1\u8db3\u5206\u89e3\u7684\u6761\u4ef6\u624d\u884c\n    time_stt = clock();\n    x = A.lu().solve(b);\n    cout << \"x^T = \" << x.transpose() <<endl;\n    cout <<\"time use in LU decomposition is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    // \u65b9\u6cd5\u4e94\uff1aCholesky\u5206\u89e3\u6cd5\uff0c\u9002\u7528\u6761\u4ef6\uff1a\u65b9\u9635\n    // \u7ed3\u679c\u4e0e\u5176\u4ed6\u7684\u65b9\u6cd5\u5dee\u597d\u591a\uff0c\u5982\u6b64\u7b80\u5355\u7684\u4e5f\u9519\u4e86\u3002\u3002\n    time_stt = clock();\n    x = A.llt().solve(b);\n    cout << \"x^T = \" << x.transpose() <<endl;\n    cout <<\"time use in Cholesky decomposition is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    // \u65b9\u6cd5\u516d\uff1aJacobi\u8fed\u4ee3\u6cd5\uff0c\u6316\u5751\u5f85\u8865\u5145\u3002\u3002\n\n\n    //-------------------------------------------------------------------------------------\n    // \u5750\u6807\u53d8\u6362\n    Eigen::Quaterniond q1(0.35, 0.2,  0.3, 0.1);\n    cout << \"quaternion 1 = \\n\" << q1.coeffs() << endl;\n    Eigen::Quaterniond q2(-0.5, 0.4, -0.1, 0.2);\n    cout << \"quaternion 2 = \\n\" << q2.coeffs() << endl;\n    q1.normalize(); // remember to normalize\n    q2.normalize();\n    cout << \"normalized quaternion 1 = \\n\" << q1.coeffs() << endl;\n    cout << \"normalized quaternion 2 = \\n\" << q2.coeffs() << endl;\n    Eigen::Vector3d t1(0.3, 0.1, 0.1), t2(-0.1, 0.5, 0.3);\n    \n    // \u6ce8\u610f\u4e0b\u6807\uff0cT1w\u8868\u793aworld to 1\uff01\n    Eigen::Isometry3d T1w(q1); // \u521d\u59cb\u5316\u65b9\u6cd5\u4e00\n    // Eigen::Isometry3d T1w(q1.toRotationMatrix()); // \u521d\u59cb\u5316\u65b9\u6cd5\u4e8c\n    // Eigen::Isometry3d T1w = Eigen::Isometry3d::Identity(); \n    // T1w.rotate(q1.toRotationMatrix()); // \u521d\u59cb\u5316\u65b9\u6cd5\u4e09\n    T1w.pretranslate(t1);\n    cout << \"Transform matrix 1 = \\n\" << T1w.matrix() <<endl;\n    // world to 2\n    Eigen::Isometry3d T2w(q2);\n    T2w.pretranslate(t2);\n    cout << \"Transform matrix 2 = \\n\" << T2w.matrix() <<endl;\n\n    Eigen::Vector3d p1(0.5, 0, 0.2);\n    // first from 1 to world, then world to 2\n    Eigen::Vector3d p2 = T2w * T1w.inverse() * p1; \n    cout << \"coordinate in camera 2 is \\n\" << p2.transpose() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "38c44db4ba730b5e8455effe31d020b53194109d", "size": 3879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/homework/homework.cpp", "max_stars_repo_name": "billamiable/slambook", "max_stars_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:27:43.000Z", "max_issues_repo_path": "ch3/homework/homework.cpp", "max_issues_repo_name": "billamiable/slambook", "max_issues_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_issues_repo_licenses": ["MIT"], "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/homework/homework.cpp", "max_forks_repo_name": "billamiable/slambook", "max_forks_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T11:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T02:59:20.000Z", "avg_line_length": 37.6601941748, "max_line_length": 120, "alphanum_fraction": 0.5764372261, "num_tokens": 1457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6979294351588866}}
{"text": "#include <iostream>\n#include <vector>\n//#include <cstdint>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\nclass Poly1d\n{\n    protected:\n         std::vector<double> coefficients_;\n    public:\n        //============================================================================\n        // Method Description:\n        Poly1d() = default;\n\n        //============================================================================\n        // Method Description:\n        std::vector<double> getCoeffs()\n        {\n            return coefficients_;\n        }\n\n        void init (const std::vector<double>& inValues)\n        {\n            // std::vector<double> coefficients_;\n            for (auto value : inValues)\n            {\n                coefficients_.push_back(value);\n            }\n        }\n            \n        std::vector<double> evaluate (std::vector<double> inValues)\n        {\n            std::vector<double> result;\n            \n            for (int i = 0; i < inValues.size(); i++)\n            {\n                double polyValue = 0.0;\n                int power = inValues.size() - 1;\n                for (auto coeff : coefficients_)\n                {\n                    polyValue += coeff * pow(inValues[i], power);\n                    power--;\n                }\n                result.push_back(polyValue);\n            }\n            \n            return result;\n        }\n            \n        void fit (std::vector<double> &x_data, std::vector<double> &y_data, std::vector<double> &coeff, int order)\n        {\n            Eigen::MatrixXd W(x_data.size(), order + 1); \n            Eigen::VectorXd I = Eigen::VectorXd::Map(&y_data.front(), y_data.size());\n            Eigen::VectorXd result;\n\n            assert(x_data.size() == y_data.size());\n            assert(x_data.size() >= order + 1);\n\n            for(std::size_t i = 0; i < x_data.size(); ++i)\n            {\n                for (std::size_t j = 0; j < order + 1; ++j)\n                {\n                    W(i, j) = std::pow(x_data.at(i), j);\n                }\n            }\n\n//            std::cout<< W << std::endl;\n\n            result = W.householderQr().solve(I);\n            coeff.resize(order + 1);\n\n            for(std::size_t k = 0; k < order + 1; k++)\n            {\n                coeff[k] = result[k];\n            }\n        }\n};\n\n", "meta": {"hexsha": "ae3b9c529b4ca6e9f44bec785f256fa82b701314", "size": 2324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/poly1d.cpp", "max_stars_repo_name": "anva-kn/ramanflow", "max_stars_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/poly1d.cpp", "max_issues_repo_name": "anva-kn/ramanflow", "max_issues_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-05T06:40:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T07:18:18.000Z", "max_forks_repo_path": "utils/poly1d.cpp", "max_forks_repo_name": "anva-kn/ramanflow", "max_forks_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_forks_repo_licenses": ["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.6913580247, "max_line_length": 114, "alphanum_fraction": 0.4083476764, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6978188906985098}}
{"text": "#include <iostream>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50>> Precise_Decimal;\n\n/*\n    Solves two conic sections equations simultaneously.\n\n    It is used to find the intersection points of two conic sections.\n\n    An arbitrary conic section (equation) is of the following form:\n\n    Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0\n\n    where A, B, C, D, and E are arbitrary coefficients, and F is an arbitrary constant.\n\n    - by Melwyn Francis Carlo <carlo.melwyn@outlook.com>\n\n    - Written for LibreCAD software.\n*/\nRS_VectorSolutions RS_Math::simultaneousQuadraticSolverFull(const std::vector<std::vector<double>>& input_conicSections)\n{\n    RS_VectorSolutions intersectionPoints;\n\n    if (input_conicSections.size() != 2) return intersectionPoints;\n\n    if ((input_conicSections[0].size() == 3) || (input_conicSections[1].size() == 3))\n    {\n        return simultaneousQuadraticSolverMixed(input_conicSections);\n    }\n\n    if ((input_conicSections[0].size() != 6) || (input_conicSections[1].size() != 6))\n    {\n        return intersectionPoints;\n    }\n\n    std::vector<std::vector<double>> conicSections = input_conicSections;\n\n    for (int i = 0; i < 2; i++)\n    {\n        unsigned int max_orderOfMagnitudeFactor = 0;\n\n        for (int j = 0; j < 6; j++)\n        {\n            if (std::fabs(conicSections[i][j]) < RS_TOLERANCE15)\n            {\n                conicSections[i][j] = 0.0;\n            }\n\n            if (conicSections[i][j] < 1.0)\n            {\n                const unsigned int orderOfMagnitudeFactor = (unsigned int) std::trunc(std::fabs(std::log10(conicSections[i][j]))) + 1;\n\n                if (orderOfMagnitudeFactor > max_orderOfMagnitudeFactor)\n                {\n                    max_orderOfMagnitudeFactor = orderOfMagnitudeFactor;\n                }\n            }\n        }\n\n        for (int j = 0; j < 6; j++)\n        {\n            const double orderOfMagnitude = std::pow(10, max_orderOfMagnitudeFactor);\n\n            conicSections[i][j] = std::trunc(conicSections[i][j] * orderOfMagnitude * 1.0E+10) * 1.0E-10;\n        }\n    }\n\n    const Precise_Decimal a1 = conicSections[0][0];\n    const Precise_Decimal b1 = conicSections[0][1];\n    const Precise_Decimal c1 = conicSections[0][2];\n    const Precise_Decimal d1 = conicSections[0][3];\n    const Precise_Decimal e1 = conicSections[0][4];\n    const Precise_Decimal f1 = conicSections[0][5];\n\n    const Precise_Decimal a2 = conicSections[1][0];\n    const Precise_Decimal b2 = conicSections[1][1];\n    const Precise_Decimal c2 = conicSections[1][2];\n    const Precise_Decimal d2 = conicSections[1][3];\n    const Precise_Decimal e2 = conicSections[1][4];\n    const Precise_Decimal f2 = conicSections[1][5];\n\n    if ((a1 == 0.0) || (a2 == 0.0) || (c1 == 0.0) || (c2 == 0.0)) return intersectionPoints;\n\n    const Precise_Decimal a1_sq = a1 * a1;\n    const Precise_Decimal b1_sq = b1 * b1;\n    const Precise_Decimal c1_sq = c1 * c1;\n    const Precise_Decimal d1_sq = d1 * d1;\n    const Precise_Decimal e1_sq = e1 * e1;\n    const Precise_Decimal f1_sq = f1 * f1;\n\n    const Precise_Decimal a2_sq = a2 * a2;\n    const Precise_Decimal b2_sq = b2 * b2;\n    const Precise_Decimal c2_sq = c2 * c2;\n    const Precise_Decimal d2_sq = d2 * d2;\n    const Precise_Decimal e2_sq = e2 * e2;\n    const Precise_Decimal f2_sq = f2 * f2;\n\n    const Precise_Decimal c1_cu = c1_sq * c1;\n\n    std::vector<double> x_n_terms(5, 0.0);\n\n    /* The x^4 term. */\n    x_n_terms[4] = ((a1_sq * c1 * c2_sq)  + (a2_sq * c1_cu)  - (2.0 * a1 * a2 * c1_sq * c2) \n                 + (a2 * b1_sq * c1 * c2) - (a2 * b1 * b2 * c1_sq)  \n                 + (a1 * b2_sq * c1_sq)  - (a1 * b1 * b2 * c1 * c2)).convert_to<double>();\n\n    /* The x^3 term. */\n    x_n_terms[3] = ((2.0 * a1 * c1 * c2_sq * d1) + (2.0 * a2 * c1_cu * d2) - (2.0 * a1 * c1_sq * c2 * d2) - (2.0 * a2 * c1_sq * c2 * d1) \n                 + (2.0 * a2 * b1 * c1 * c2 * e1) + (b1_sq * c1 * c2 * d2) - (a2 * b1 * c1_sq * e2) - (a2 * b2 * c1_sq * e1) - (b1 * b2 * c1_sq * d2) \n                 + (2.0 * a1 * b2 * c1_sq * e2) + (b2_sq * c1_sq * d1) - (a1 * b1 * c1 * c2 * e2) - (a1 * b2 * c1 * c2 * e1) - (b1 * b2 * c1 * c2 * d1)).convert_to<double>();\n\n    /* The x^2 term. */\n    x_n_terms[2] = ((2.0 * a1 * c1 * c2_sq * f1) + (2.0 * a2 * c1_cu * f2) + (c1_cu * d2_sq)  + (c1 * c2_sq * d1_sq)  - (2.0 * a1 * c1_sq * c2 * f2) - (2.0 * a2 * c1_sq * c2 * f1) - (2.0 * c1_sq * c2 * d1 * d2) \n                 + (a2 * c1 * c2 * e1_sq)  + (2.0 * b1 * c1 * c2 * d2 * e1) + (b1_sq * c1 * c2 * f2) - (a2 * c1_sq * e1 * e2) - (b1 * b2 * c1_sq * f2) - (b1 * c1_sq * d2 * e2) - (b2 * c1_sq * d2 * e1) \n                 + (a1 * c1_sq * e2_sq)  + (b2_sq * c1_sq * f1) + (2.0 * b2 * c1_sq * d1 * e2) - (a1 * c1 * c2 * e1 * e2) - (b1 * b2 * c1 * c2 * f1) - (b1 * c1 * c2 * d1 * e2) - (b2 * c1 * c2 * d1 * e1)).convert_to<double>();\n\n    /* The x term. */\n    x_n_terms[1] = ((2.0 * c1_cu * d2 * f2) + (2.0 * c1 * c2_sq * d1 * f1) - (2.0 * c1_sq * c2 * d1 * f2) - (2.0 * c1_sq * c2 * d2 * f1) \n                 + (2.0 * b1 * c1 * c2 * e1 * f2) + (c1 * c2 * d2 * e1_sq)  - (b1 * c1_sq * e2 * f2) - (b2 * c1_sq * e1 * f2) - (c1_sq * d2 * e1 * e2) \n                 + (c1_sq * d1 * e2_sq)  + (2.0 * b2 * c1_sq * e2 * f1) - (b1 * c1 * c2 * e2 * f1) - (b2 * c1 * c2 * e1 * f1) - (c1 * c2 * d1 * e1 * e2)).convert_to<double>();\n\n    /* The constant term. */\n    x_n_terms[0] = ((c1_cu * f2_sq)  + (c1 * c2_sq * f1_sq)  - (2.0 * c1_sq * c2 * f1 * f2) \n                 + (c1 * c2 * e1_sq * f2) - (c1_sq * e1 * e2 * f2) \n                 + (c1_sq * e2_sq * f1) - (c1 * c2 * e1 * e2 * f1)).convert_to<double>();\n\n    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n    {\n        DEBUG_HEADER\n        std::cout << std::endl << std::endl \n                  << \" (\" << x_n_terms[4] << \")x^4 + \" \n                  <<  \"(\" << x_n_terms[3] << \")x^3 + \" \n                  <<  \"(\" << x_n_terms[2] << \")x^2 + \" \n                  <<  \"(\" << x_n_terms[1] << \")x + \" \n                  <<  \"(\" << x_n_terms[0] << \") = 0\" \n                  << std::endl << std::endl;\n\n        const double a = x_n_terms[4];\n        const double b = x_n_terms[3];\n        const double c = x_n_terms[2];\n        const double d = x_n_terms[1];\n        const double e = x_n_terms[0];\n\n        const double a_sq = a * a;\n        const double b_sq = b * b;\n        const double c_sq = c * c;\n        const double d_sq = d * d;\n        const double e_sq = e * e;\n\n        const double a_cu = a * a * a;\n        const double b_cu = b * b * b;\n        const double c_cu = c * c * c;\n        const double d_cu = d * d * d;\n        const double e_cu = e * e * e;\n\n        std::cout << \" Discriminant (Delta) = \" \n                  << (256.0 * a_cu * e_cu) - (192.0 * a_sq * b * d * e_sq) - (128.0 * a_sq * c_sq * e_sq) \n                   + (144.0 * a_sq * c * d_sq * e) - (27.0 * a_sq * d_cu * d) + (144.0 * a * b_sq * c * e_sq) \n                   - (6.0 * a * b_sq * d_sq * e) - (80.0 * a * b * c_sq * d * e) + (18.0 * a * b * c * d_cu) \n                   + (16.0 * a * c_cu * c * e) - (4.0 * a * c_cu * d_sq) - (27.0 * b_cu * b * e_sq) \n                   + (18.0 * b_cu * c * d * e) - (4.0 * b_cu * d_cu) - (4.0 * b_sq * c_cu * e) + (b_sq * c_sq * d_sq) \n                  << std::endl << std::endl;\n\n        std::cout << \" P Factor = \" \n                  << (8.0 * a * c) - (3.0 * b_sq) \n                  << std::endl << std::endl;\n\n        std::cout << \" D Factor = \" \n                  << (64.0 * a_cu * e) - (16.0 * a_sq * c_sq) + (16.0 * a * b_sq * c) - (16.0 * a_sq * b * d) - (3 * b_cu * b) \n                  << std::endl << std::endl;\n    }\n\n\tstd::vector<double> rootsAbscissae = quarticSolverFull(x_n_terms);\n\n    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n    {\n        std::cout << \" Number of quartic roots = \" << rootsAbscissae.size() \n                  << std::endl << std::endl;\n    }\n\n    for (double& rootX : rootsAbscissae)\n    {\n        const Precise_Decimal rootXPrecise = rootX;\n\n        const Precise_Decimal sqrtTerm1 = boost::multiprecision::trunc(((((b1 * rootXPrecise) + e1) * ((b1 * rootXPrecise) + e1)) \n                                        - (4.0 * c1 * ((a1 * rootXPrecise * rootXPrecise) + (d1 * rootXPrecise) + f1))) * 1.0E+4) * 1.0E-4;\n\n        const Precise_Decimal sqrtTerm2 = boost::multiprecision::trunc(((((b2 * rootXPrecise) + e2) * ((b2 * rootXPrecise) + e2)) \n                                        - (4.0 * c2 * ((a2 * rootXPrecise * rootXPrecise) + (d2 * rootXPrecise) + f2))) * 1.0E+4) * 1.0E-4;\n\n        if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n        {\n            std::cout << \" RootX square root terms : \" \n                      << sqrtTerm1 << \", \" << sqrtTerm2 \n                      << std::endl << std::endl;\n        }\n\n        if ((sqrtTerm1 < 0.0) || (sqrtTerm2 < 0.0)) continue;\n\n        const Precise_Decimal numeratorTerm1 = (-b1 * rootXPrecise) - e1;\n        const Precise_Decimal numeratorTerm2 = (-b2 * rootXPrecise) - e2;\n\n        const Precise_Decimal denominatorTerm1 = 2.0 * c1;\n        const Precise_Decimal denominatorTerm2 = 2.0 * c2;\n\n        const RS_Vector conic_1_points[2] = \n        {\n            RS_Vector(rootX, ((numeratorTerm1 + boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to<double>()), \n            RS_Vector(rootX, ((numeratorTerm1 - boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to<double>()) \n        };\n\n        const RS_Vector conic_2_points[2] = \n        {\n            RS_Vector(rootX, ((numeratorTerm2 + boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to<double>()), \n            RS_Vector(rootX, ((numeratorTerm2 - boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to<double>()) \n        };\n\n        if (((fabs(conic_1_points[0].x - conic_2_points[0].x) < 1.0E-4) \n        &&   (fabs(conic_1_points[0].y - conic_2_points[0].y) < 1.0E-4)) \n        ||  ((fabs(conic_1_points[0].x - conic_2_points[1].x) < 1.0E-4) \n        &&   (fabs(conic_1_points[0].y - conic_2_points[1].y) < 1.0E-4)))\n        {\n            intersectionPoints.push_back(conic_1_points[0]);\n        }\n\n\n        if (((fabs(conic_1_points[1].x - conic_2_points[0].x) < 1.0E-4) \n        &&   (fabs(conic_1_points[1].y - conic_2_points[0].y) < 1.0E-4)) \n        ||  ((fabs(conic_1_points[1].x - conic_2_points[1].x) < 1.0E-4) \n        &&   (fabs(conic_1_points[1].y - conic_2_points[1].y) < 1.0E-4)))\n        {\n            intersectionPoints.push_back(conic_1_points[1]);\n        }\n\n        if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n        {\n            std::cout << \" Available roots : \" << std::endl \n                      << \" 1.1. \" << conic_1_points[0] << std::endl \n                      << \" 1.2. \" << conic_1_points[1] << std::endl \n                      << \" 2.1. \" << conic_2_points[0] << std::endl \n                      << \" 2.2. \" << conic_2_points[1] << std::endl << std::endl;\n\n            std::cout << \" Chosen root : \" << intersectionPoints [intersectionPoints.size() - 1] \n                      << std::endl << std::endl;\n        }\n    }\n\n    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n    {\n        std::cout << \" Number of intersection points = \" << intersectionPoints.size() \n                  << std::endl << std::endl;\n    }\n\n    return intersectionPoints;\n}\n\n", "meta": {"hexsha": "eaa9dbb171deacd49dd0ddaa6a9553878e493219", "size": 11412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPP/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_stars_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_stars_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_stars_repo_licenses": ["MIT"], "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/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_issues_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_issues_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_issues_repo_licenses": ["MIT"], "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/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_forks_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_forks_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_forks_repo_licenses": ["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.0617760618, "max_line_length": 225, "alphanum_fraction": 0.5171749036, "num_tokens": 4050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6977784326908261}}
{"text": "//\n// Created by alex on 26/05/20.\n//\n\n#include <cmath>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n#include <fstream>\n#include \"Utils.h\"\n\nusing namespace std;\n\nvector<vector<int>> Utils::loadGEucSpace(const string &file_path) {\n    auto vertices = readVList(file_path);\n    int n = vertices.size();\n    vector<vector<int>> D(n, vector<int>(n));\n\n    for (size_t i = 0; i < n; ++i) {\n        for (size_t j = i + 1; j < n; ++j) {\n\n            auto v1 = vertices[i];\n            auto v2 = vertices[j];\n\n            // computing euclidean distance\n            vector<float> subtracted;\n            subtracted.reserve(v1.size());\n            transform(v1.begin(), v1.end(), v2.begin(), back_inserter(subtracted),\n                           [](float a, float b) { return pow(a - b, 2); });\n            double d = sqrt(accumulate(subtracted.begin(), subtracted.end(), 0.0));\n            D[j][i] = D[i][j] = (int)(d+0.5);\n        }\n    }\n    return D;\n}\n\nstd::vector<std::vector<float>> Utils::readVList(const std::string &file_path) {\n\n    std::vector<std::vector<float>> vertices;\n    std::string line;\n    std::ifstream file(file_path);\n\n    if (file.is_open()) {\n\n        getline(file, line);\n        boost::trim_right(line);\n        boost::trim_left(line);\n\n        std::vector<std::string> line_vec;\n        boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n        if (line_vec.size() != 1 && line_vec.size() != 3) {\n            std::cerr << \"Error in line \" << line << std::endl;\n            throw;\n        }\n\n        std::vector<float> xy(2);\n        if (line_vec.size() == 1) {\n            int n = stoi(line);\n            vertices.reserve(n);\n        } else {\n            std::transform(line_vec.begin() + 1, line_vec.end(), xy.begin(),\n                           [](std::string const &val) { return stof(val); });\n            vertices.push_back(xy);\n        }\n\n        while (getline(file, line)) {\n            boost::trim_right(line);\n            boost::trim_left(line);\n            boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n            if (line_vec.size() != 3) {\n                std::cerr << \"Error in line \" << line << std::endl;\n                throw;\n            }\n\n            std::transform(line_vec.begin() + 1, line_vec.end(), xy.begin(),\n                           [](std::string const &val) { return stof(val); });\n            vertices.push_back(xy);\n        }\n        file.close();\n    } else {\n        std::cerr << \"Unable to open file\" << std::endl;\n    }\n    return vertices;\n}\n\nstd::vector<std::vector<float>> Utils::loadGMetricSpace(int n, const std::string &file_path) {\n    std::vector<std::vector<float>> G(n, std::vector<float>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            G[i][j] = i != j ? +INFINITY : 0;\n        }\n    }\n\n    std::string line;\n    std::ifstream file(file_path);\n\n    if (file.is_open()) {\n\n        std::vector<std::string> line_vec;\n        while (getline(file, line)) {\n            boost::trim_right(line);\n            boost::trim_left(line);\n            boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n            if (line_vec.size() != 3) {\n                std::cerr << \"Error in line \" << line << std::endl;\n                throw;\n            }\n\n            int v1 = stoi(line_vec[0]) - 1;\n            int v2 = stoi(line_vec[1]) - 1;\n            float w = stof(line_vec[2]);\n\n            G[v1][v2] = w;\n            G[v2][v1] = w;\n        }\n        file.close();\n    } else {\n        std::cerr << \"Unable to open file\" << std::endl;\n    }\n    floydWarshall(G);\n    return G;\n}\n\nvoid Utils::floydWarshall(std::vector<std::vector<float>> &G) {\n    int n = G.size();\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            for (int l = 0; l < n; ++l) {\n                float cost = (G[i][j] == +INFINITY || G[i][l] == +INFINITY) ?\n                             +INFINITY : G[i][j] + G[i][l];\n                if (cost < G[j][l]) {\n                    G[j][l] = cost;\n                }\n            }\n        }\n    }\n}\n\nfloat Utils::stdDev(std::vector<int> &items, float average) {\n    float std = 0;\n    for (float item : items) {\n        std += pow(item - average, 2);\n    }\n    int n = items.size() > 2 ? items.size() - 1 : items.size();\n    return sqrt(std / n);\n}\n\nbool Utils::save(std::string &output_path, std::string &content) {\n    std::ofstream output_file(output_path);\n//    output_file.write(&content, content.size());\n    output_file << content;\n    output_file.close();\n    return true;\n}\n", "meta": {"hexsha": "cbdaf5da47d492c0aa525cac1d1079b07debfde6", "size": 4608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/Utils.cpp", "max_stars_repo_name": "alex-cornejo/ckc-heuristic", "max_stars_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T17:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T14:20:22.000Z", "max_issues_repo_path": "src/util/Utils.cpp", "max_issues_repo_name": "alex-cornejo/ckc-heuristic", "max_issues_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_issues_repo_licenses": ["MIT"], "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/Utils.cpp", "max_forks_repo_name": "alex-cornejo/ckc-heuristic", "max_forks_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8, "max_line_length": 94, "alphanum_fraction": 0.4928385417, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6977468615575466}}
{"text": "#include <armadillo>\n#include \"zeroSumGame.h\"\n#include \"gurobi_c++.h\"\n\nusing namespace arma;\nusing namespace std;\n\n\nbool ZeroSumGame::solveGame(const Mat<double> &payoffMat, double &gameValue, Col<double> &p, Col<double> &q, double diffThreshold, bool checkNonnegative)\n{\n    double maximumGain = 0;\n    double minimumLoss = 0;\n    if(!maximizePayoff(payoffMat,maximumGain,p,checkNonnegative)) return false;\n    if(!minimizePayoff(payoffMat,minimumLoss,q,checkNonnegative)) return false;\n    \n    Col<double> absValues(2);\n    absValues(0) = abs(maximumGain);\n    absValues(1) = abs(minimumLoss);\n    \n    double abs_gain_loss_diff = abs(maximumGain-minimumLoss);\n    double diff_portion = abs_gain_loss_diff/max(absValues);\n    if (diff_portion < diffThreshold) {\n        gameValue = (maximumGain+minimumLoss)/2;\n        return true;\n    }\n    return false;\n}\n\nbool ZeroSumGame::maximizePayoff(const Mat<double> &payoffMat, double &maximumGain, Col<double> &p, bool checkNonnegative)\n{\n    if (checkNonnegative==true) {\n        double minValuePayoffMat = min(min(payoffMat));\n        if (minValuePayoffMat <= 0) {\n            cout << \"all elements of the payoffMat must be positive!\" << endl;\n            throw 2;\n        }\n    }\n    \n    int numRows = payoffMat.n_rows;\n    int numCols = payoffMat.n_cols;\n    \n    bool success = false;\n    GRBEnv* env = 0;\n    try{\n    env = new GRBEnv();\n    GRBModel model = GRBModel(*env);\n    /* No solving information printed */\n    model.getEnv().set(GRB_IntParam_OutputFlag, 0);\n    /* Add varialbe to the model */\n    /* first NULL means low bound is 0.0 and seconde NULL means up bound is infinite by default */\n    GRBVar* vars = model.addVars(NULL,NULL,NULL,NULL,NULL,numRows);\n    model.update();\n    \n    /* Populate payoffMat matrix */\n    for (int j = 0; j < numCols; j++) {\n        GRBLinExpr lhs = 0;\n        for (int i = 0; i < numRows; i++)\n            if(payoffMat(i,j) != 0)\n                lhs += payoffMat(i,j)*vars[i];\n        model.addConstr(lhs,GRB_GREATER_EQUAL,1.0);\n    }\n    \n    GRBLinExpr obj = 0;\n    \n    for (int i = 0; i<numRows; i++)\n        obj += 1.0*vars[i];\n\n    model.setObjective(obj,GRB_MINIMIZE);\n    model.update();\n    model.optimize();\n    \n    if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {\n        maximumGain = 1.0/model.get(GRB_DoubleAttr_ObjVal);\n        p = zeros< Col<double> >(numRows);\n        for (int i = 0; i < numRows; i++)\n            p(i) = vars[i].get(GRB_DoubleAttr_X)*maximumGain;\n        success = true;\n    }\n        \n    //cout << \"maximum gain:\" << maximumGain << endl;\n    delete [] vars;\n        \n    }catch(GRBException e) {\n        cout << \"Error code = \" << e.getErrorCode() << endl;\n        cout << e.getMessage() << endl;\n    } catch(...) {\n        cout << \"Exception during optimization\" << endl;\n    }\n    delete env;\n    return success;\n}\n\nbool ZeroSumGame::minimizePayoff(const Mat<double> &payoffMat, double &minimumLoss, Col<double> &q, bool checkNonnegative)\n{\n    if (checkNonnegative==true) {\n        double minValuePayoffMat = min(min(payoffMat));\n        if (minValuePayoffMat <= 0) {\n            cout << \"all elements of the payoffMat must be positive!\" << endl;\n            throw 2;\n        }\n    }\n    int numRows = payoffMat.n_rows;\n    int numCols = payoffMat.n_cols;\n    \n    bool success = false;\n    GRBEnv* env = 0;\n    try{\n        env = new GRBEnv();\n        GRBModel model = GRBModel(*env);\n        /* No solving information printed */\n        model.getEnv().set(GRB_IntParam_OutputFlag, 0);\n        /* Add varialbe to the model */\n        /* first NULL means low bound is 0.0 and seconde NULL means up bound is infinite by default */\n        GRBVar* vars = model.addVars(NULL,NULL,NULL,NULL,NULL,numCols);\n        model.update();\n        \n        /* Populate A matrix */\n        for (int i = 0; i < numRows; i++) {\n            GRBLinExpr lhs = 0;\n            for (int j = 0; j < numCols; j++)\n                if(payoffMat(i,j) != 0)\n                    lhs += payoffMat(i,j)*vars[j];\n            model.addConstr(lhs,GRB_LESS_EQUAL,1.0);\n        }\n        \n        GRBLinExpr obj = 0;\n        \n        for (int j = 0; j<numCols; j++)\n            obj += 1.0*vars[j];\n        \n        model.setObjective(obj,GRB_MAXIMIZE);\n        model.update();\n        model.optimize();\n        \n        if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {\n            minimumLoss = 1.0/model.get(GRB_DoubleAttr_ObjVal);\n            q = zeros< Col<double> >(numCols);\n            for (int j = 0; j < numCols; j++)\n                q(j) = vars[j].get(GRB_DoubleAttr_X)*minimumLoss;\n            success = true;\n        }\n        \n        //cout << \"minimum loss:\" << minimumLoss << endl;\n        \n        delete [] vars;\n        \n    }catch(GRBException e) {\n        cout << \"Error code = \" << e.getErrorCode() << endl;\n        cout << e.getMessage() << endl;\n    } catch(...) {\n        cout << \"Exception during optimization\" << endl;\n    }\n    delete env;\n    return success;\n}\n", "meta": {"hexsha": "791a8c32e97376cb5b199ed357daddd6e98409e8", "size": 5002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gurobi_C++/src/ZeroSumGame.cpp", "max_stars_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_stars_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "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": "gurobi_C++/src/ZeroSumGame.cpp", "max_issues_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_issues_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "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": "gurobi_C++/src/ZeroSumGame.cpp", "max_forks_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_forks_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "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": 32.0641025641, "max_line_length": 153, "alphanum_fraction": 0.5757696921, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6977466387547238}}
{"text": "#include <iostream>\n#include <vector>\n#include <functional>\n#include <cmath>\n#include <Eigen/Dense>\n\n#include \"Derivative.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing Eigen::Derivative;\n\nusing std::function;\nusing std::vector;\n\ntypedef function<double(VectorXd)> FuncDV;\ntypedef function<VectorXd(VectorXd)> FuncVV;\ntypedef function<MatrixXd(VectorXd)> FuncMV;\n\nMatrixXd MakePositiveSemidefinite(MatrixXd mat, int dim){\n    double left = 0, right = std::max(-mat.minCoeff(), .0) + 1;\n    while(right - left >= 1e-4){\n        double mid = (left+right)/2;\n        auto test = mat + mid*MatrixXd::Identity(dim, dim);\n        // From https://stackoverflow.com/questions/35227131/eigen-check-if-matrix-is-positive-semi-definite\n\n        Eigen::LLT<Eigen::MatrixXd> lltOfA(test);\n        if(lltOfA.info() == Eigen::NumericalIssue)\n            left = mid;\n        else\n            right = mid;\n    }\n    return mat + right*MatrixXd::Identity(dim, dim);\n}\n\nVectorXd doIPM(\n    FuncDV F, FuncVV DelF, FuncMV LaplaceF,\n    FuncVV H, FuncMV DelH, vector<FuncMV> LaplaceH,\n    int dimX, int dimH, VectorXd initX\n){\n    double mu = 0.0001;\n\n    std::function<bool(VectorXd)> feasible = [dimH](VectorXd _f){\n        for(int lx = 0;lx < dimH;lx++)\n            if(_f[lx] < 0)\n                return false;\n        return true; \n    };\n\n    std::function<double(VectorXd, VectorXd, VectorXd)> \n        L = [mu, F, H, dimH](VectorXd x, VectorXd y, VectorXd w){\n        double barrier = 0;\n        for(int lx = 0;lx < dimH;lx++)\n            barrier += log(w[lx]);\n        return F(x) - mu*barrier - y.transpose()*(H(x) - w);\n    };\n\n    VectorXd x = initX, y, w = H(initX);\n\n    { \n        MatrixXd A = DelH(x).transpose();\n        MatrixXd invA = A.completeOrthogonalDecomposition().pseudoInverse();\n        y = invA*DelF(x);\n    }\n    \n    for(;;){\n        VectorXd h = H(x), e = VectorXd::Ones(dimH);\n        MatrixXd W = w.asDiagonal(), invY = y.asDiagonal().inverse();\n\n        MatrixXd Hess = LaplaceF(x);\n        for(int lx = 0;lx < dimH;lx++)\n            Hess -= y[lx]*LaplaceH[lx](x);\n\n        // Find ~H = H + lambda * I\n        Hess = MakePositiveSemidefinite(Hess, dimX);\n\n        MatrixXd A = DelH(x);\n        MatrixXd M1(dimX + dimH, dimX + dimH);\n\n        M1 << -Hess, A.transpose(),\n                  A, W*invY       ;\n\n        VectorXd V1(dimX + dimH);\n        \n        V1 << DelF(x) - A.transpose()*y,\n                  - h + mu*invY*e      ;\n\n        VectorXd dxy = M1.inverse()*V1;\n        VectorXd dx, dy, dw;\n\n        dx = dxy.head(dimX);\n        dy = dxy.tail(dimH);\n        dw = invY*mu*e - W*e - invY*W*dy;\n\n        x += dx, y += dy, w += dw;\n\n        if(dx.norm() <= 0.001)\n            break;\n    }\n\n    return x;\n}\n\n// Solve : min  obj_f\n//         sub  con_hs >= 0 \n\nVectorXd Derivative_IPM(Derivative obj_f, vector<Derivative> con_hs, VectorXd start_guess){\n    int x_size = start_guess.size(), h_size = con_hs.size();\n\n    vector<Derivative> v1w(x_size);\n    vector< vector<Derivative> > v2w(x_size, v1w);\n\n    vector<Derivative> f_gradient = v1w;\n    vector< vector<Derivative> > f_hess = v2w;\n\n    vector< vector<Derivative> > hs_gradient(h_size, v1w);\n    vector< vector< vector<Derivative> > > hs_hess(h_size, v2w);\n\n    // Prebuild differiential function\n    \n    for(int lx = 0;lx < x_size;lx++)\n        f_gradient[lx] = obj_f.diffPartial(lx);\n\n    for(int lx = 0;lx < x_size;lx++)\n        for(int ly = 0;ly < x_size;ly++)\n            f_hess[lx][ly] = f_gradient[lx].diffPartial(ly);\n    \n    for(int lh = 0;lh < h_size;lh++){\n        for(int lx = 0;lx < x_size;lx++)\n            hs_gradient[lh][lx] = con_hs[lh].diffPartial(lx);\n\n        for(int lx = 0;lx < x_size;lx++)\n            for(int ly = 0;ly < x_size;ly++)\n                hs_hess[lh][lx][ly] = hs_gradient[lh][lx].diffPartial(ly);\n    }\n\n    FuncDV F = [obj_f](VectorXd x){\n        return obj_f(x);\n    };\n\n    FuncVV DelF = [f_gradient, x_size](VectorXd x){\n        VectorXd ret(x_size);\n        for(int lx = 0;lx < x_size;lx++)\n            ret[lx] = f_gradient[lx](x);\n        return ret;\n    };\n\n    FuncMV LaplaceF = [f_hess, x_size](VectorXd x){ \n        MatrixXd ret(x_size, x_size);\n        for(int lx = 0;lx < x_size;lx++)\n            for(int ly = 0;ly < x_size;ly++)\n                ret(lx, ly) = f_hess[lx][ly](x);\n        return ret; \n    };\n\n    FuncVV H = [con_hs, h_size](VectorXd x){\n        VectorXd ret(h_size);\n        for(int lx = 0;lx < h_size;lx++)\n            ret[lx] = con_hs[lx](x);\n        return ret;\n    };\n\n    FuncMV DelH = [hs_gradient, h_size, x_size](VectorXd x){\n        MatrixXd A(h_size, x_size);\n        for(int lh = 0;lh < h_size;lh++)\n            for(int lx = 0;lx < x_size;lx++)\n                A(lh, lx) = hs_gradient[lh][lx](x);\n        return A;\n    };\n    \n    vector<FuncMV> LaplaceH(h_size);\n    \n    for(int lh = 0;lh < h_size;lh++){\n        LaplaceH[lh] = [hs_hess, lh, x_size](VectorXd x){\n            MatrixXd ret(x_size, x_size);\n            for(int lx = 0;lx < x_size;lx++)\n                for(int ly = 0;ly < x_size;ly++)\n                    ret(lx, ly) = hs_hess[lh][lx][ly](x);\n            return ret;\n        };\n    };\n \n    return doIPM(F, DelF, LaplaceF, H, DelH, LaplaceH, start_guess.size(), con_hs.size(), start_guess); \n}\n\nint main(){\n    // Reference : http://www.princeton.edu/~rvdb/tex/talks/MLSS_LaPalma/LaPalma3.pdf\n    // Solve : min  x+y\n    //         sub  xx + yy >= 1 \n    //              x >= 0 \n    //              y >= 0 \n\n    Derivative par_x = Derivative::Variable(0), par_y = Derivative::Variable(1);\n    Derivative obj_f = par_x + par_y;\n\n    Derivative con_h1 = par_x*par_x + par_y*par_y - 1,\n               con_h2 = par_x,\n               con_h3 = par_y;\n\n    // Multiple initial value\n    VectorXd x(2);\n    \n    x << 1, 1;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n    x << 1, 2;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n    x << 2, 1;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n    \n    x << 4, -1;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n    x << -1, 4;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n    x << 0.2, 0.7;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n    x << 0.5, 0.5;\n    std::cout << \"x initial as \" << x.transpose() << std::endl;\n    std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "55ee171f3727f76c71ad3e290159f3a536dca781", "size": 7026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/interior-point-method.cpp", "max_stars_repo_name": "mudream4869/eigen-derivative", "max_stars_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_stars_repo_licenses": ["MIT"], "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/interior-point-method.cpp", "max_issues_repo_name": "mudream4869/eigen-derivative", "max_issues_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_issues_repo_licenses": ["MIT"], "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/interior-point-method.cpp", "max_forks_repo_name": "mudream4869/eigen-derivative", "max_forks_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_forks_repo_licenses": ["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.1545064378, "max_line_length": 108, "alphanum_fraction": 0.5461144321, "num_tokens": 2214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6976485146247153}}
{"text": "#ifndef TRIUMF_SRIM_PDF_HPP\n#define TRIUMF_SRIM_PDF_HPP\n\n#include <boost/math/constants/constants.hpp>\n// #include <boost/math/distributions/lognormal.hpp>\n// #include <boost/math/distributions/skew_normal.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\n#include <boost/math/special_functions/beta.hpp>\n\n#include <cmath>\n\n// TRIUMF: Canada's accelerator centre\nnamespace triumf {\n\n// Stopping and Range of Ions in Matter (SRIM)\nnamespace srim {\n\n// probability density functions (PDF)\nnamespace pdf {\n\n/// see Eq. (5.6) in Md Masrur Hossain's MSc thesis, UBC, 2006, p. 52.\ntemplate <typename T> T custom(T x, T alpha, T beta, T sigma, T x_max, T N) {\n  T y = x / x_max;\n  return y < 0.0 or y > 1.0 ? 0.0\n                            : N * std::pow(y, alpha) * std::pow(1.0 - y, beta) *\n                                  std::exp(-std::pow((x - x_max) / sigma, 2));\n}\n\n/// see Eq. (5.6) in Md Masrur Hossain's MSc thesis, UBC, 2006, p. 52.\ntemplate <typename T> T custom(const T *x, const T *par) {\n  // parameters\n  T alpha = par[0];\n  T beta = par[1];\n  T sigma = par[2];\n  T x_max = par[3];\n  T N = par[4];\n  T y = *x / x_max;\n\n  // ensure function is always properly normalized!\n  boost::math::quadrature::tanh_sinh<T> integrator;\n  auto integrand = [&](T z) { return custom(z, alpha, beta, sigma, x_max, N); };\n  T I = integrator.integrate(integrand, 0.0, x_max);\n\n  // return the normalized function\n  return custom(*x, alpha, beta, sigma, x_max, N) / I;\n}\n\n/// beta distribution - x in [0, 1]\ntemplate <typename T> T _beta(T x, T alpha, T beta) {\n  if ((x < 0.0) or (x > 1.0)) {\n    return 0.0;\n  } else {\n    return std::pow(x, alpha - 1.0) * std::pow(1.0 - x, beta - 1.0) /\n           boost::math::beta<T, T>(alpha, beta);\n  }\n}\n\n/// modified beta distribution - x in [0, x_max]\ntemplate <typename T> T modified_beta(T x, T alpha, T beta, T x_max) {\n  T y = x / x_max;\n  return _beta<T>(y, alpha, beta) / x_max;\n}\n\n/// modified beta distribution - x in [0, x_max]\n/// interface for ROOT TF1\ntemplate <typename T> T modified_beta(const T *x, const T *par) {\n  T alpha = par[0];\n  T beta = par[1];\n  T x_max = par[2];\n  return modified_beta<T>(*x, alpha, beta, x_max);\n}\n\n} // namespace pdf\n\n} // namespace srim\n\n} // namespace triumf\n\n#endif // TRIUMF_SRIM_PDF_HPP\n", "meta": {"hexsha": "128cfc3cef818f52de6f8b0e51f679981248c63e", "size": 2276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/srim/pdf.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/srim/pdf.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/srim/pdf.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.0987654321, "max_line_length": 80, "alphanum_fraction": 0.6234622144, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6976485114702979}}
{"text": "#include <rct_optimizations/validation/homography_validation.h>\n#include <Eigen/Dense>\n#include <rct_optimizations/types.h>\n\nnamespace rct_optimizations\n{\nEigen::VectorXd calculateHomographyError(const Correspondence2D3D::Set &correspondences,\n                                         const CorrespondenceSampler &correspondence_sampler)\n{\n  /* There is a 3x3 homography matrix, H, that can transform a point from one plane onto a different plane\n   * | u | = k * | H00 H01 H02 | * | x |\n   * | v |       | H10 H11 H12 |   | y |\n   * | 1 |       | H20 H12  1  |   | 1 |\n   *\n   * In our case we have 2 sets of known corresponding planar points: points on the planar target, and points in the image plane\n   * Therefore, there is some matrix, H, which can transform target points into the image plane.\n   * If the target points and camera points actually match, we should be able to:\n   *   1. Calculate H for a subset of corresponding points\n   *   2. Transform the remaining target points by H to obtain estimates of their locations in the image plane\n   *   3. Compare the calculated estimations to the actual image points to make sure they are very close. If they are not close, we know that the correspondences are not valid\n   *\n   * The matrix H has 8 unique values.\n   * These 8 values of the homography matrix can be solved for, given a set of (at least) 8 corresponding planar vectors, by rearranging the above equations:\n   *\n   * A * H = b, where\n   * H = inv(A) * b\n   *   - A is matrix (size 2*n x 8), where n is the number of corresponding vectors\n   *   - H is a vector (size 8 x 1) of the unknown elements of the homography matrix\n   *   - B is a vector (size 2*n x 1) representing the elements of one set of planar vectors\n   *\n   *                  A               *              H    =    b\n   * |-x0 -y0  -1   0    0    0   u0*x0   u0*y0 | * | H00 | = | -u0 |\n   * | 0   0   0  -x0   -y0  -1   v0*x0   v0*y0 | * | H01 | = | -v0 |\n   *                              ...\n   * |-x7 -y7  -1   0    0    0   u7*x7   u7*y7 | * | H20 | = | -u7 |\n   * | 0   0   0  -x7   -y7  -1   v7*x7   v7*y7 | * | H21 | = | -v7 |\n   *\n   */\n\n  // Select the points that we want to use to create the H matrix\n  std::vector<std::size_t> sample_correspondence_indices = correspondence_sampler\n                                                             .getSampleCorrespondenceIndices();\n  std::size_t n_samples = sample_correspondence_indices.size();\n\n  // Ensure that there are enough points for testing outside of the sampled set\n  if (correspondences.size() < 2 * n_samples)\n  {\n    std::stringstream ss;\n    ss << \"Correspondences size is not more than 2x sample size (\" << correspondences.size()\n       << \" correspondences vs. \" << n_samples << \")\";\n    throw std::runtime_error(ss.str());\n  }\n\n  // Create the A and b matrices\n  Eigen::MatrixXd A(2 * n_samples, 8);\n  Eigen::MatrixXd b(2 * n_samples, 1);\n\n  // Fill the A and B matrices with data from the selected correspondences\n  for (std::size_t i = 0; i < n_samples; ++i)\n  {\n    std::size_t corr_idx = sample_correspondence_indices.at(i);\n    const Correspondence2D3D &corr = correspondences.at(corr_idx);\n\n    //assign A row-th row:\n    const double x = corr.in_target.x();\n    const double y = corr.in_target.y();\n    const double u = corr.in_image.x();\n    const double v = corr.in_image.y();\n    A.row(2 * i) << -x, -y, -1.0, 0.0, 0.0, 0.0, u * x, u * y;\n    A.row(2 * i + 1) << 0.0, 0.0, 0.0, -x, -y, -1.0, v * x, v * y;\n\n    b.block<2, 1>(2 * i, 0) = -1.0 * corr.in_image;\n  }\n\n  // Create the homography matrix\n  Eigen::Matrix<double, 3, 3, Eigen::RowMajor> H = Eigen::Matrix3d::Ones();\n\n  // Map the elements of the H matrix into a column vector and solve for the first 8\n  {\n    Eigen::Map<Eigen::VectorXd> hv(H.data(), 9);\n    hv.head<8>() = A.fullPivLu().solve(b);\n  }\n\n  // Estimate the image locations of all the target observations and compare to the actual image locations\n  Eigen::VectorXd error(correspondences.size());\n  for (std::size_t i = 0; i < correspondences.size(); ++i)\n  {\n    const Correspondence2D3D &corr = correspondences[i];\n\n    // Calculate the scaling factor\n    double ki = 1.0 / (H(2, 0) * corr.in_target.x() + H(2, 1) * corr.in_target.y() + 1.0);\n\n    // Replace the z-element of the point with 1\n    Eigen::Vector3d xy(corr.in_target);\n    xy(2) = 1.0;\n\n    // Estimate the point in the image plane\n    Eigen::Vector3d in_image_estimate = ki * H * xy;\n\n    // Calculate the error\n    Eigen::Vector2d image_error = corr.in_image - in_image_estimate.head<2>();\n    error(i) = image_error.norm();\n  }\n\n  return error;\n}\n\n} // namespace rct_optimizations\n\n", "meta": {"hexsha": "b6a349b1af8d959a0d6e3e60f95d58ac17a83e80", "size": 4651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_stars_repo_name": "jaberkebile/robot_cal_tools", "max_stars_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "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": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_issues_repo_name": "jaberkebile/robot_cal_tools", "max_issues_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "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": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_forks_repo_name": "jaberkebile/robot_cal_tools", "max_forks_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "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": 42.2818181818, "max_line_length": 175, "alphanum_fraction": 0.6196516878, "num_tokens": 1398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6976485102571586}}
{"text": "#ifndef LINEAR_ELASTICITY_HPP\n#define LINEAR_ELASTICITY_HPP\n\n#include \"C0_triangles.hpp\"\n#include \"Galerkin/Galerkin.hpp\"\n#include \"mesh_traits.hpp\"\n#include \"SymSparse.hpp\"\n\nusing Galerkin::get;\n\n#include <Eigen/Core>\n\n#include <exception>\n\nnamespace Elasticity\n{\n\nnamespace TwoD\n{\n\ntemplate <class Element, class U, class V>\nEigen::Matrix2d pair_stiffness_integral(const Element &el, const U &u, const V &v,\n    double lambda, double mu)\n{\n    auto uxvx = el.integrate(el.template partial<0>(u) * el.template partial<0>(v));\n    auto uxvy = el.integrate(el.template partial<0>(u) * el.template partial<1>(v));\n    auto uyvy = el.integrate(el.template partial<1>(u) * el.template partial<1>(v));\n    auto uyvx = el.integrate(el.template partial<1>(u) * el.template partial<0>(v));\n\n    Eigen::Matrix2d K;\n    K(0, 0) = (lambda + 2*mu) * uxvx + mu * uyvy;\n    K(1, 0) = lambda * uyvx + mu * uxvy;\n    K(0, 1) = lambda * uxvy + mu * uyvx;\n    K(1, 1) = (lambda + 2*mu) * uyvy + mu * uxvx;\n\n    return K;\n}\n\ntemplate <class Element>\nconstexpr size_t basis_size = Element::basis.size();\n\ntemplate <auto I, auto J, class Element>\nvoid add_contribution(const Element &el, double lambda, double mu,\n                      Eigen::Matrix<double, 2*basis_size<Element>, 2*basis_size<Element>> &K)\n{\n    constexpr auto u = get<I>(Element::basis);\n    constexpr auto v = get<J>(Element::basis);\n    auto local_K = pair_stiffness_integral(el, u, v, lambda, mu);\n    auto row = I*2;\n    auto col = J*2;\n    K.block(row, col, 2, 2) = local_K;\n    K.block(col, row, 2, 2) = local_K.transpose();\n}\n\ntemplate <class Element>\nEigen::Matrix<double, 2*basis_size<Element>, 2*basis_size<Element>>\nelement_stiffness_matrix(const Element &el, double lambda, double mu)\n{\n    Eigen::Matrix<double, 2*basis_size<Element>, 2*basis_size<Element>> K;\n    Galerkin::static_for<0, basis_size<Element>, 1>(\n        [&](auto I)\n        {\n            Galerkin::static_for<I(), basis_size<Element>, 1>(\n                [&](auto J)\n                {\n                    add_contribution<I(), J()>(el, lambda, mu, K);\n                }\n            );\n        }\n    );\n    return K;\n}\n\ntemplate <class Mesh>\nauto instantiate_element(const Mesh &mesh, size_t which)\n{\n    constexpr int order = msh::element_order<Mesh>;\n    const auto &el = mesh.element(which);\n    return fem::c0::C0Triangle<order>(\n        mesh.coord(el.control_nodes[0]),\n        mesh.coord(el.control_nodes[1]),\n        mesh.coord(el.control_nodes[2])\n    );\n}\n\nconstexpr auto lame_parameters(double E, double nu) noexcept\n{\n    double lambda = E * nu / ((1+nu) * (1-nu));\n    double mu     = E / (2 * (1+nu));\n    return std::make_pair(lambda, mu);\n}\n\ntemplate <class Mesh>\nauto assemble_stiffness(const Mesh &mesh, double E, double nu)\n{\n    SymSparse::SymmetricSparseMatrix<double, 2 * msh::max_node_adjacencies<Mesh>> K(mesh.num_nodes() * 2);\n    auto [lambda, mu] = lame_parameters(E, nu);\n\n    for (size_t i = 0; i < mesh.num_elements(); ++i)\n    {\n        const auto &el_info = mesh.element(i);\n        const auto nn = el_info.node_numbers();\n        const auto el = instantiate_element(mesh, i);\n        const auto local_K = element_stiffness_matrix(el, lambda, mu);\n        for (size_t j = 0; j < nn.size(); ++j)\n        {\n            for (size_t k = j; k < nn.size(); ++k)\n            {\n                K.insert_entry(nn[j]*2, nn[k]*2, local_K(2*j, 2*k));\n                if (k != j)\n                {\n                    K.insert_entry(nn[j]*2+1, nn[k]*2, local_K(2*j+1, 2*k));\n                }\n                K.insert_entry(nn[j]*2, nn[k]*2+1, local_K(2*j, 2*k+1));\n                K.insert_entry(nn[j]*2+1, nn[k]*2+1, local_K(2*j+1, 2*k+1));\n            }\n        }\n    }\n    return K;\n}\n\ntemplate <class Mesh>\nusing StiffnessType = decltype(assemble_stiffness(std::declval<const Mesh &>(), 1.0, 1.0));\n\n/*\n * Add a homogeneous Dirichlet condition on the boundary segment of the mesh\n * indexed by `which`. K is the stiffness matrix obtained from `assemble_stiffness`,\n * and `rhs` is the forcing vector.\n */\ntemplate <class Mesh, class RHS>\nvoid impose_homogeneous_condition(const Mesh &mesh, StiffnessType<Mesh> &K, RHS &rhs, size_t which,\n                                  double scale = 1.0)\n{\n    std::vector<size_t> adjacent;\n    adjacent.reserve(2 * msh::max_node_adjacencies<Mesh>);\n    const auto &boundary = mesh.boundary(which);\n\n    for (auto n: boundary.nodes)\n    {\n        adjacent.clear();\n        // Get all of the adjacent DOFs to this one; since there are two components\n        // of displacement there are 2 degrees of freedom (2*n, 2*n+1) corresponding\n        // to each node.\n        for (auto n2: mesh.adjacent_nodes(n))\n        {\n            adjacent.push_back(2*n2);\n            adjacent.push_back(2*n2+1);\n        }\n        K.eliminate_dof(2*n, 0.0, scale, rhs, adjacent);\n        K.eliminate_dof(2*n+1, 0.0, scale, rhs, adjacent);\n    }\n}\n\ntemplate <class Mesh>\nvoid impose_homogeneous_condition(\n    const Mesh &mesh, StiffnessType<Mesh> &K, size_t which, double scale = 1.0)\n{\n    std::vector<size_t> adjacent;\n    adjacent.reserve(2 * msh::max_node_adjacencies<Mesh>);\n    const auto &boundary = mesh.boundary(which);\n\n    for (auto n : boundary.nodes)\n    {\n        adjacent.clear();\n        // Get all of the adjacent DOFs to this one; since there are two components\n        // of displacement there are 2 degrees of freedom (2*n, 2*n+1) corresponding\n        // to each node.\n        for (auto n2 : mesh.adjacent_nodes(n))\n        {\n            adjacent.push_back(2 * n2);\n            adjacent.push_back(2 * n2 + 1);\n        }\n        K.eliminate_dof(2 * n, 0.0, scale, adjacent);\n        K.eliminate_dof(2 * n + 1, 0.0, scale, adjacent);\n    }\n}\n\nstruct OutOfBoundsIndex : public std::exception\n{\n    const char *msg;\n    OutOfBoundsIndex(const char *m) : msg(m) {}\n    const char *what() const noexcept\n    {\n        return msg;\n    }\n};\n\ntemplate <class Mesh, class RHS, class Vector>\nvoid impose_dirichlet_condition(const Mesh &mesh, StiffnessType<Mesh> &K, RHS &rhs, size_t which,\n                                const Vector &value, double scale = 1.0)\n{\n    std::vector<size_t> adjacent;\n    adjacent.reserve(2 * msh::max_node_adjacencies<Mesh>);\n    const auto &boundary = mesh.boundary(which);\n\n    if (value.size() != 2*boundary.nodes.size())\n    {\n        throw OutOfBoundsIndex(\"Vector given for Dirichlet condition has wrong number of values\");\n    }\n\n    size_t i = 0;\n    for (auto n: boundary.nodes)\n    {\n        adjacent.clear();\n        for (auto n2: mesh.adjacent_nodes(n))\n        {\n            adjacent.push_back(2*n2);\n            adjacent.push_back(2*n2+1);\n        }\n        K.eliminate_dof(2*n, value[2*i], scale, rhs, adjacent);\n        K.eliminate_dof(2*n+1, value[2*i+1], scale, rhs, adjacent);\n        i += 1;\n    }\n}\n\ntemplate <class Force, class RHS>\nvoid add_point_force(const Force &force, size_t node, RHS &F)\n{\n    if (2*node+1 > F.size())\n    {\n        throw OutOfBoundsIndex(\"Node is out of bounds for given forcing vector\");\n    }\n    F[2*node] += force[0];\n    F[2*node+1] += force[1];\n}\n\ntemplate <class T, class RHS, int N, class IndexContainer, int... Options>\nvoid add_point_forces(const Eigen::Matrix<T, 2, N, Options...> &force, const IndexContainer &nodes,\n                      RHS &F)\n{\n    static_assert(sizeof...(Options) == 3);\n    size_t col = 0;\n    for (size_t n: nodes)\n    {\n        add_point_force(force.col(col), n, F);\n        col += 1;\n    }\n}\n\n} // namespace 2D\n\n} // namespace Elasticity\n\n#endif // LINEAR_ELASTICITY_HPP\n", "meta": {"hexsha": "307f895d2da05bf5a869182ba79dfabe525f8bb0", "size": 7566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "2d.hpp", "max_stars_repo_name": "slmcbane/Le-TO", "max_stars_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2d.hpp", "max_issues_repo_name": "slmcbane/Le-TO", "max_issues_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2d.hpp", "max_forks_repo_name": "slmcbane/Le-TO", "max_forks_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_forks_repo_licenses": ["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.8816326531, "max_line_length": 106, "alphanum_fraction": 0.6037536347, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6975771930285403}}
{"text": "// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT License. See LICENSE in the project root for license information.\n\n#include <pch.h>\n#include <Eigen_Z.h>\n\n////////////////////////////////////////////////////////////////////////////////\n// File: jacobi_cyclic_method.c                                               //\n// Routines:                                                                  //\n//    Jacobi_Cyclic_Method                                                    //\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n//  void Jacobi_Cyclic_Method                                                 //\n//            (double eigenvalues[], double *eigenvectors, double *A, int n)  //\n//                                                                            //\n//  Description:                                                              //\n//     Find the eigenvalues and eigenvectors of a symmetric n x n matrix A    //\n//     using the Jacobi method. Upon return, the input matrix A will have     //\n//     been modified.                                                         //\n//     The Jacobi procedure for finding the eigenvalues and eigenvectors of a //\n//     symmetric matrix A is based on finding a similarity transformation     //\n//     which diagonalizes A.  The similarity transformation is given by a     //\n//     product of a sequence of orthogonal (rotation) matrices each of which  //\n//     annihilates an off-diagonal element and its transpose.  The rotation   //\n//     effects only the rows and columns containing the off-diagonal element  //\n//     and its transpose, i.e. if a[i][j] is an off-diagonal element, then    //\n//     the orthogonal transformation rotates rows a[i][] and a[j][], and      //\n//     equivalently it rotates columns a[][i] and a[][j], so that a[i][j] = 0 //\n//     and a[j][i] = 0.                                                       //\n//     The cyclic Jacobi method considers the off-diagonal elements in the    //\n//     following order: (0,1),(0,2),...,(0,n-1),(1,2),...,(n-2,n-1).  If the  //\n//     the magnitude of the off-diagonal element is greater than a treshold,  //\n//     then a rotation is performed to annihilate that off-diagnonal element. //\n//     The process described above is called a sweep.  After a sweep has been //\n//     completed, the threshold is lowered and another sweep is performed     //\n//     with the new threshold. This process is completed until the final      //\n//     sweep is performed with the final threshold.                           //\n//     The orthogonal transformation which annihilates the matrix element     //\n//     a[k][m], k != m, is Q = q[i][j], where q[i][j] = 0 if i != j, i,j != k //\n//     i,j != m and q[i][j] = 1 if i = j, i,j != k, i,j != m, q[k][k] =       //\n//     q[m][m] = cos(phi), q[k][m] = -sin(phi), and q[m][k] = sin(phi), where //\n//     the angle phi is determined by requiring a[k][m] -> 0.  This condition //\n//     on the angle phi is equivalent to                                      //\n//               cot(2 phi) = 0.5 * (a[k][k] - a[m][m]) / a[k][m]             //\n//     Since tan(2 phi) = 2 tan(phi) / (1.0 - tan(phi)^2),                    //\n//               tan(phi)^2 + 2cot(2 phi) * tan(phi) - 1 = 0.                 //\n//     Solving for tan(phi), choosing the solution with smallest magnitude,   //\n//       tan(phi) = - cot(2 phi) + sgn(cot(2 phi)) sqrt(cot(2phi)^2 + 1).     //\n//     Then cos(phi)^2 = 1 / (1 + tan(phi)^2) and sin(phi)^2 = 1 - cos(phi)^2 //\n//     Finally by taking the sqrts and assigning the sign to the sin the same //\n//     as that of the tan, the orthogonal transformation Q is determined.     //\n//     Let A\" be the matrix obtained from the matrix A by applying the        //\n//     similarity transformation Q, since Q is orthogonal, A\" = Q'AQ, where Q'//\n//     is the transpose of Q (which is the same as the inverse of Q).  Then   //\n//         a\"[i][j] = Q'[i][p] a[p][q] Q[q][j] = Q[p][i] a[p][q] Q[q][j],     //\n//     where repeated indices are summed over.                                //\n//     If i is not equal to either k or m, then Q[i][j] is the Kronecker      //\n//     delta.   So if both i and j are not equal to either k or m,            //\n//                                a\"[i][j] = a[i][j].                         //\n//     If i = k, j = k,                                                       //\n//        a\"[k][k] =                                                          //\n//           a[k][k]*cos(phi)^2 + a[k][m]*sin(2 phi) + a[m][m]*sin(phi)^2     //\n//     If i = k, j = m,                                                       //\n//        a\"[k][m] = a\"[m][k] = 0 =                                           //\n//           a[k][m]*cos(2 phi) + 0.5 * (a[m][m] - a[k][k])*sin(2 phi)        //\n//     If i = k, j != k or m,                                                 //\n//        a\"[k][j] = a\"[j][k] = a[k][j] * cos(phi) + a[m][j] * sin(phi)       //\n//     If i = m, j = k, a\"[m][k] = 0                                          //\n//     If i = m, j = m,                                                       //\n//        a\"[m][m] =                                                          //\n//           a[m][m]*cos(phi)^2 - a[k][m]*sin(2 phi) + a[k][k]*sin(phi)^2     //\n//     If i= m, j != k or m,                                                  //\n//        a\"[m][j] = a\"[j][m] = a[m][j] * cos(phi) - a[k][j] * sin(phi)       //\n//                                                                            //\n//     If X is the matrix of normalized eigenvectors stored so that the ith   //\n//     column corresponds to the ith eigenvalue, then AX = X Lamda, where     //\n//     Lambda is the diagonal matrix with the ith eigenvalue stored at        //\n//     Lambda[i][i], i.e. X'AX = Lambda and X is orthogonal, the eigenvectors //\n//     are normalized and orthogonal.  So, X = Q1 Q2 ... Qs, where Qi is      //\n//     the ith orthogonal matrix,  i.e. X can be recursively approximated by  //\n//     the recursion relation X\" = X Q, where Q is the orthogonal matrix and  //\n//     the initial estimate for X is the identity matrix.                     //\n//     If j = k, then x\"[i][k] = x[i][k] * cos(phi) + x[i][m] * sin(phi),     //\n//     if j = m, then x\"[i][m] = x[i][m] * cos(phi) - x[i][k] * sin(phi), and //\n//     if j != k and j != m, then x\"[i][j] = x[i][j].                         //\n//                                                                            //\n//  Arguments:                                                                //\n//     double  eigenvalues                                                    //\n//        Array of dimension n, which upon return contains the eigenvalues of //\n//        the matrix A.                                                       //\n//     double* eigenvectors                                                   //\n//        Matrix of eigenvectors, the ith column of which contains an         //\n//        eigenvector corresponding to the ith eigenvalue in the array        //\n//        eigenvalues.                                                        //\n//     double* A                                                              //\n//        Pointer to the first element of the symmetric n x n matrix A. The   //\n//        input matrix A is modified during the process.                      //\n//     int     n                                                              //\n//        The dimension of the array eigenvalues, number of columns and rows  //\n//        of the matrices eigenvectors and A.                                 //\n//                                                                            //\n//  Return Values:                                                            //\n//     Function is of type void.                                              //\n//                                                                            //\n//  Example:                                                                  //\n//     #define N                                                              //\n//     double A[N][N], double eigenvalues[N], double eigenvectors[N][N]       //\n//                                                                            //\n//     (your code to initialize the matrix A )                                //\n//                                                                            //\n//     Jacobi_Cyclic_Method(eigenvalues, (double*)eigenvectors,               //\n//                                                          (double *) A, N); //\n////////////////////////////////////////////////////////////////////////////////\n//                                                                            //\n\n#define VAL_FLT_EPSILON     2.2204460492503131e-016f//1.0e-4f//1.192092896e-07F        /* smallest such that 1.0+FLT_EPSILON != 1.0 */\n\nvoid Jacobi_Cyclic_Method(float eigenvalues[], float *eigenvectors,float *A, int n)\n{\n   int i, j, k, m;\n   float *pAk, *pAm, *p_r, *p_e;\n   double threshold_norm;\n   double threshold;\n   double tan_phi, sin_phi, cos_phi, tan2_phi, sin2_phi, cos2_phi;\n   double sin_2phi, cos_2phi, cot_2phi;\n   double dum1;\n   double dum2;\n   double dum3;\n   double max;\n\n\t\t\t\t  // Take care of trivial cases\n\n   if ( n < 1) return;\n   if ( n == 1) {\n\t  eigenvalues[0] = *A;\n\t  *eigenvectors = 1.f;\n\t  return;\n   }\n\n\t\t  // Initialize the eigenvalues to the identity matrix.\n\n   for (p_e = eigenvectors, i = 0; i < n; i++)\n\t  for (j = 0; j < n; p_e++, j++)\n\t\t if (i == j) *p_e = 1.f; else *p_e = 0.f;\n  \n\t\t\t// Calculate the threshold and threshold_norm.\n \n   for (threshold = 0.f, pAk = A, i = 0; i < ( n - 1 ); pAk += n, i++) \n\t  for (j = i + 1; j < n; j++) threshold += *(pAk + j) * *(pAk + j);\n   threshold = sqrt(threshold + threshold);\n   threshold_norm = threshold * VAL_FLT_EPSILON;\n   max = threshold + 1.f;\n   while (threshold > threshold_norm)\n   {\n//   for (int il=0; il<100; il++) {\n\t  threshold /= 10.f;\n\t  if (max < threshold)\n\t\t  continue;\n\t  max = 0.f;\n\t  for (pAk = A, k = 0; k < (n-1); pAk += n, k++) {\n\t\t for (pAm = pAk + n, m = k + 1; m < n; pAm += n, m++) {\n\t\t\tdouble fabspAkpm=fabs(*(pAk + m));\n\t\t\tif ( fabspAkpm < threshold )\n\t\t\t\tcontinue;\n\n\t\t\t\t // Calculate the sin and cos of the rotation angle which\n\t\t\t\t // annihilates A[k][m].\n\n\t\t\tcot_2phi = 0.5f * ( *(pAk + k) - *(pAm + m) ) / *(pAk + m);\n\t\t\tdum1 = sqrt( cot_2phi * cot_2phi + 1.f);\n\t\t\tif (cot_2phi < 0.f) dum1 = -dum1;\n\t\t\ttan_phi = -cot_2phi + dum1;\n\t\t\ttan2_phi = tan_phi * tan_phi;\n\t\t\tsin2_phi = tan2_phi / (1.f + tan2_phi);\n\t\t\tcos2_phi = 1.f - sin2_phi;\n\t\t\tsin_phi = sqrt(sin2_phi);\n\t\t\tif (tan_phi < 0.f) sin_phi = - sin_phi;\n\t\t\tcos_phi = sqrt(cos2_phi); \n\t\t\tsin_2phi = 2.f * sin_phi * cos_phi;\n\t\t\tcos_2phi = cos2_phi - sin2_phi;\n\n\t\t\t\t\t // Rotate columns k and m for both the matrix A \n\t\t\t\t\t //     and the matrix of eigenvectors.\n\n\t\t\tp_r = A;\n\t\t\tdum1 = *(pAk + k);\n\t\t\tdum2 = *(pAm + m);\n\t\t\tdum3 = *(pAk + m);\n\t\t\t*(pAk + k) = dum1 * cos2_phi + dum2 * sin2_phi + dum3 * sin_2phi;\n\t\t\t*(pAm + m) = dum1 * sin2_phi + dum2 * cos2_phi - dum3 * sin_2phi;\n\t\t\t*(pAk + m) = 0.f;\n\t\t\t*(pAm + k) = 0.f;\n\t\t\tfor (i = 0; i < n; p_r += n, i++) {\n\t\t\t   if ( (i == k) || (i == m) ) continue;\n\t\t\t   if ( i < k ) dum1 = *(p_r + k); else dum1 = *(pAk + i);\n\t\t\t   if ( i < m ) dum2 = *(p_r + m); else dum2 = *(pAm + i);\n\t\t\t   dum3 = dum1 * cos_phi + dum2 * sin_phi;\n\t\t\t   if ( i < k ) *(p_r + k) = dum3; else *(pAk + i) = dum3;\n\t\t\t   dum3 = - dum1 * sin_phi + dum2 * cos_phi;\n\t\t\t   if ( i < m ) *(p_r + m) = dum3; else *(pAm + i) = dum3;\n\t\t\t}\n\t\t\tfor (p_e = eigenvectors, i = 0; i < n; p_e += n, i++) {\n\t\t\t   dum1 = *(p_e + k);\n\t\t\t   dum2 = *(p_e + m);\n\t\t\t   *(p_e + k) = dum1 * cos_phi + dum2 * sin_phi;\n\t\t\t   *(p_e + m) = - dum1 * sin_phi + dum2 * cos_phi;\n\t\t\t}\n\t\t }\n\t\t for (i = 0; i < n; i++)\n\t\t\tif ( i == k ) continue;\n\t\t\telse if ( max < fabs(*(pAk + i))) max = fabs(*(pAk + i));\n\t  }\n   }\n   for (pAk = A, k = 0; k < n; pAk += n, k++) eigenvalues[k] = *(pAk + k); \n}\n\nvoid GenericEigen3D(const Vec3f *vectors,S32 nbvectors,Vec3f eigenvectors[3],Float eigenvalues[3])\n{\n\tint\t\ti;\n\n\tif (nbvectors<1)\n\t\treturn;\n\n\tVec3f\tBaryCentre=VEC4F_NULL;\n\n\t// Calculate mean (barycentre)\n\tfor (i=0; i<nbvectors; i++)\n\t{\n\t\tBaryCentre+=vectors[i];\n\t}\n\n\tBaryCentre/=(Float)nbvectors;\n\n\tFloat\tMatCovariance[3][3];\n\t// Compute cloud point directing vector\n\t// 1st compute covariance matrix\n\tfor (int x=0; x<3; x++)\n\t{\n\t\tfor (int y=0; y<3; y++)\n\t\t{\n\t\t\tFloat\ttotalcovariance=0.f;\n\t\t\tfor (i=0; i<nbvectors; i++)\n\t\t\t{\n\t\t\t\tFloat\tvalx=(Float)(((Float*)&vectors[i])[x]);\n\t\t\t\tFloat\tvaly=(Float)(((Float*)&vectors[i])[y]);\n\t\t\t\tvalx-=((Float*)&BaryCentre)[x];\n\t\t\t\tvaly-=((Float*)&BaryCentre)[y];\n\t\t\t\tFloat\tcovariance=valx*valy;\n\t\t\t\ttotalcovariance+=covariance;\n\t\t\t}\n\t\t\tFloat\tcovariance=totalcovariance/nbvectors;\n\t\t\tMatCovariance[x][y]=covariance;\n\t\t}\n\t}\n\t// Compute EigenVectors\n\tJacobi_Cyclic_Method(eigenvalues,(float *)eigenvectors,(Float*)&MatCovariance,3);\n\t\n\tSwap(eigenvectors[0].y, eigenvectors[1].x);\n\tSwap(eigenvectors[0].z, eigenvectors[2].x);\n\tSwap(eigenvectors[1].z, eigenvectors[2].y);\n}\n", "meta": {"hexsha": "6ccfcb85a5fb88a080d83ac303eef8e8ab580777", "size": 13282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SpatialUnderstanding/Src/Engine/Eigen_Z.cpp", "max_stars_repo_name": "ScriptBox99/MixedRealityToolkit", "max_stars_repo_head_hexsha": "9c9e6557263001bcbc48b8396c84ac840eff7c4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 300.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T12:57:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T00:31:29.000Z", "max_issues_repo_path": "SpatialUnderstanding/Src/Engine/Eigen_Z.cpp", "max_issues_repo_name": "ScriptBox99/MixedRealityToolkit", "max_issues_repo_head_hexsha": "9c9e6557263001bcbc48b8396c84ac840eff7c4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 84.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T11:03:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T22:59:59.000Z", "max_forks_repo_path": "SpatialUnderstanding/Src/Engine/Eigen_Z.cpp", "max_forks_repo_name": "ScriptBox99/MixedRealityToolkit", "max_forks_repo_head_hexsha": "9c9e6557263001bcbc48b8396c84ac840eff7c4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2017-08-12T03:51:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-06T03:36:26.000Z", "avg_line_length": 50.6946564885, "max_line_length": 134, "alphanum_fraction": 0.4384881795, "num_tokens": 3568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6975354066543161}}
{"text": "/**\n * @date Thu July 19 12:27:15 2012 +0200\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * @brief This file provides a class to process images with a weighted\n *        Gaussian kernel (Used by the Self Quotient Image)\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <boost/format.hpp>\n#include <stdexcept>\n#include <bob.ip.base/IntegralImage.h>\n#include <bob.ip.base/WeightedGaussian.h>\n\n\nbob::ip::base::WeightedGaussian::WeightedGaussian(\n  const size_t radius_y, const size_t radius_x,\n  const double sigma_y, const double sigma_x,\n  const bob::sp::Extrapolation::BorderType border_type\n):\n  m_radius_y(radius_y),\n  m_radius_x(radius_x),\n  m_sigma_y(sigma_y),\n  m_sigma_x(sigma_x),\n  m_conv_border(border_type)\n{\n  computeKernel();\n}\n\n\nbob::ip::base::WeightedGaussian::WeightedGaussian(const WeightedGaussian& other)\n:\n  m_radius_y(other.m_radius_y),\n  m_radius_x(other.m_radius_x),\n  m_sigma_y(other.m_sigma_y),\n  m_sigma_x(other.m_sigma_x),\n  m_conv_border(other.m_conv_border)\n{\n  computeKernel();\n}\n\n\nvoid bob::ip::base::WeightedGaussian::computeKernel()\n{\n  m_kernel.resize(2 * m_radius_y + 1, 2 * m_radius_x + 1);\n  m_kernel_weighted.resize(2 * m_radius_y + 1, 2 * m_radius_x + 1);\n  // Computes the kernel\n  const double inv_sigma_y = 1.0 / (m_sigma_y*m_sigma_y);\n  const double inv_sigma_x = 1.0 / (m_sigma_x*m_sigma_x);\n  for (int i = -(int)m_radius_y; i <= (int)m_radius_y; ++i)\n    for (int j = -(int)m_radius_x; j <= (int)m_radius_x; ++j)\n      m_kernel(i + (int)m_radius_y, j + (int)m_radius_x) =\n        exp( -0.5 * (inv_sigma_y * (i * i) + inv_sigma_x * (j * j)));\n  // Normalizes the kernel\n  m_kernel /= blitz::sum(m_kernel);\n}\n\nvoid bob::ip::base::WeightedGaussian::reset(\n  const size_t radius_y, const size_t radius_x,\n  const double sigma_y, const double sigma_x,\n  const bob::sp::Extrapolation::BorderType border_type\n){\n  m_radius_y = radius_y;\n  m_radius_x = radius_x;\n  m_sigma_y = sigma_y;\n  m_sigma_x = sigma_x;\n  m_conv_border = border_type;\n  computeKernel();\n}\n\nbob::ip::base::WeightedGaussian& bob::ip::base::WeightedGaussian::operator=(const bob::ip::base::WeightedGaussian& other)\n{\n  if (this != &other)\n  {\n    m_radius_y = other.m_radius_y;\n    m_radius_x = other.m_radius_x;\n    m_sigma_y = other.m_sigma_y;\n    m_sigma_x = other.m_sigma_x;\n    m_conv_border = other.m_conv_border;\n    computeKernel();\n  }\n  return *this;\n}\n\nbool bob::ip::base::WeightedGaussian::operator==(const bob::ip::base::WeightedGaussian& b) const\n{\n  return (this->m_radius_y == b.m_radius_y && this->m_radius_x == b.m_radius_x &&\n          this->m_sigma_y == b.m_sigma_y && this->m_sigma_x == b.m_sigma_x &&\n          this->m_conv_border == b.m_conv_border);\n}\n\nbool bob::ip::base::WeightedGaussian::operator!=(const bob::ip::base::WeightedGaussian& b) const\n{\n  return !(this->operator==(b));\n}\n\nvoid bob::ip::base::WeightedGaussian::filter_(const blitz::Array<double,2>& src, blitz::Array<double,2>& dst)\n{\n  // Checks input\n  bob::core::array::assertZeroBase(src);\n  bob::core::array::assertZeroBase(dst);\n  bob::core::array::assertSameShape(src, dst);\n  if(src.extent(0)<m_kernel.extent(0)) {\n    boost::format m(\"The convolutional kernel has the first dimension larger than the corresponding one of the array to process (%d > %d). Our convolution code does not allows. You could try to revert the order of the two arrays.\");\n    m % src.extent(0) % m_kernel.extent(0);\n    throw std::runtime_error(m.str());\n  }\n  if(src.extent(1)<m_kernel.extent(1)) {\n    boost::format m(\"The convolutional kernel has the second dimension larger than the corresponding one of the array to process (%d > %d). Our convolution code does not allows. You could try to revert the order of the two arrays.\");\n    m % src.extent(1) % m_kernel.extent(1);\n    throw std::runtime_error(m.str());\n  }\n\n  // 1/ Extrapolation of src\n  // Resize temporary extrapolated src array\n  blitz::TinyVector<int,2> shape = src.shape();\n  shape(0) += 2 * (int)m_radius_y;\n  shape(1) += 2 * (int)m_radius_x;\n  m_src_extra.resize(shape);\n\n  // Extrapolate\n  if(m_conv_border == bob::sp::Extrapolation::Zero)\n    bob::sp::extrapolateZero(src, m_src_extra);\n  else if(m_conv_border == bob::sp::Extrapolation::NearestNeighbour)\n    bob::sp::extrapolateNearest(src, m_src_extra);\n  else if(m_conv_border == bob::sp::Extrapolation::Circular)\n    bob::sp::extrapolateCircular(src, m_src_extra);\n  else\n    bob::sp::extrapolateMirror(src, m_src_extra);\n\n  // 2/ Integral image then mean values\n  shape += 1;\n  m_src_integral.resize(shape);\n  bob::ip::base::integral(m_src_extra, m_src_integral, true);\n\n  // 3/ Convolution\n  double n_elem = m_kernel.numElements();\n  for(int y=0; y<src.extent(0); ++y)\n    for(int x=0; x<src.extent(1); ++x)\n    {\n      // Computes the threshold associated to the current location\n      // Integral image is used to speed up the process\n      blitz::Array<double,2> src_slice = m_src_extra(\n        blitz::Range(y,y+2*(int)m_radius_y), blitz::Range(x,x+2*(int)m_radius_x));\n      double threshold = (m_src_integral(y,x) +\n          m_src_integral(y+2*(int)m_radius_y+1,x+2*(int)m_radius_x+1) -\n          m_src_integral(y,x+2*(int)m_radius_x+1) -\n          m_src_integral(y+2*(int)m_radius_y+1,x)\n        ) / n_elem;\n      // Computes the weighted Gaussian kernel at this location\n      // a/ M1 is the set of pixels whose values are above the threshold\n      if( blitz::sum(src_slice >= threshold) >= n_elem/2.)\n        m_kernel_weighted = blitz::where(src_slice >= threshold, m_kernel, 0.);\n      // b/ M1 is the set of pixels whose values are below the threshold\n      else\n        m_kernel_weighted = blitz::where(src_slice < threshold, m_kernel, 0.);\n      // Normalizes the kernel\n      m_kernel_weighted /= blitz::sum(m_kernel_weighted);\n      // Convolves: This is indeed not a real convolution but a multiplication,\n      // as it seems that the authors aim at exclusively using the M1 part\n      dst(y,x) = blitz::sum(src_slice * m_kernel_weighted);\n    }\n}\n\n", "meta": {"hexsha": "1d547cd952eec672f186b3fdf073ec4de194f7ca", "size": 6026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/ip/base/cpp/WeightedGaussian.cpp", "max_stars_repo_name": "bioidiap/bob.ip.base", "max_stars_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-10-30T10:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T05:33:33.000Z", "max_issues_repo_path": "bob/ip/base/cpp/WeightedGaussian.cpp", "max_issues_repo_name": "bioidiap/bob.ip.base", "max_issues_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T18:00:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-24T08:18:05.000Z", "max_forks_repo_path": "bob/ip/base/cpp/WeightedGaussian.cpp", "max_forks_repo_name": "bioidiap/bob.ip.base", "max_forks_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-07-16T14:57:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-15T09:23:28.000Z", "avg_line_length": 36.3012048193, "max_line_length": 233, "alphanum_fraction": 0.6893461666, "num_tokens": 1731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6975354025187078}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <avatar_locomanipulation/helpers/IOUtilities.hpp>\n#include <iostream>\n#include <vector>\n\nenum ActivationFunction { None = 0, Tanh = 1, ReLU = 2, LeakyReLU = 3, Sigmoid = 4};\n\nclass Layer {\n   public:\n    Layer(Eigen::MatrixXd weight, Eigen::MatrixXd bias,\n          ActivationFunction act_fn);\n    virtual ~Layer();\n    Eigen::MatrixXd GetOutput(const Eigen::MatrixXd& input);\n    int GetNumInput() { return num_input_; }\n    int GetNumOutput() { return num_output_; }\n    Eigen::MatrixXd GetWeight() { return weight_; }\n    Eigen::MatrixXd GetBias() { return bias_; }\n    ActivationFunction GetActivationFunction() { return act_fn_; }\n\n   private:\n    Eigen::MatrixXd weight_;\n    Eigen::MatrixXd bias_;\n    int num_input_;\n    int num_output_;\n    ActivationFunction act_fn_;\n};\n\nclass NeuralNetModel {\n   public:\n    NeuralNetModel(std::vector<Layer> layers);\n    NeuralNetModel(std::vector<Layer> layers, Eigen::VectorXd logstd);\n    NeuralNetModel(const myYAML::Node& node, bool b_stochastic);\n\n    virtual ~NeuralNetModel();\n\n    std::vector<Layer> GetLayers() { return layers_; }\n    Eigen::MatrixXd GetOutput(const Eigen::MatrixXd& input);\n    Eigen::MatrixXd GetOutput(const Eigen::MatrixXd& input, int idx);\n    void GetOutput(const Eigen::MatrixXd& _input,\n                   const Eigen::VectorXd& _lb,\n                   const Eigen::VectorXd& _ub,\n                   Eigen::MatrixXd& _output,\n                   Eigen::MatrixXd& _mean,\n                   Eigen::VectorXd& _neglogp);\n\n    int GetNumInput() { return num_input_; }\n    int GetNumOutput() { return num_output_; }\n    void PrintInfo();\n\n    Eigen::MatrixXd CropMatrix(Eigen::MatrixXd value, Eigen::MatrixXd min,\n                               Eigen::MatrixXd max, std::string source);\n\n   private:\n    void Initialize_(std::vector<Layer> layers, bool b_stoch = false,\n                     Eigen::VectorXd logstd = Eigen::VectorXd::Zero(1));\n    int num_input_;\n    int num_output_;\n    int num_layer_;\n    std::vector<Layer> layers_;\n    bool b_stochastic_;\n    Eigen::VectorXd logstd_;\n    Eigen::VectorXd std_;\n};\n", "meta": {"hexsha": "9be1866322758ab0acb252f5efccc5608d620abb", "size": 2138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/NeuralNetModel.hpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "include/avatar_locomanipulation/helpers/NeuralNetModel.hpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "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/avatar_locomanipulation/helpers/NeuralNetModel.hpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 32.3939393939, "max_line_length": 84, "alphanum_fraction": 0.6552853134, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6972559593827165}}
{"text": "// Example implementation of an objective function class for linear regression\n// and usage of the L-BFGS optimizer.\n// \n// Compilation:\n// g++ example.cpp -o example -O3 -larmadillo\n\n\n#include <iostream>\n#include <armadillo>\n#include <ensmallen.hpp>\n\n\nclass LinearRegressionFunction\n{\n  public:\n  \n  LinearRegressionFunction(arma::mat& X, arma::vec& y) : X(X), y(y) { }\n  \n  double EvaluateWithGradient(const arma::mat& theta, arma::mat& gradient)\n  {\n    const arma::vec tmp = X.t() * theta - y;\n    gradient = 2 * X * tmp;\n    return arma::dot(tmp,tmp);\n  }\n  \n  private:\n  \n  const arma::mat& X;\n  const arma::vec& y;\n};\n\n\nint main(int argc, char** argv)\n{\n  if (argc < 3)\n  {\n    std::cout << \"usage: \" << argv[0] << \" n_dims n_points\" << std::endl;\n    return -1;\n  }\n  \n  int n_dims   = atoi(argv[1]);\n  int n_points = atoi(argv[2]);\n  \n  // generate noisy dataset with a slight linear pattern\n  arma::mat X(n_dims, n_points, arma::fill::randu);\n  arma::vec y(        n_points, arma::fill::randu);\n  \n  for (size_t i = 0; i < n_points; ++i)\n  {\n    double a = arma::randu();\n    X(1, i) += a;\n    y(i)    += a;\n  }\n  \n  LinearRegressionFunction lrf(X, y);\n  \n  // create a Limited-memory BFGS optimizer object with default parameters\n  ens::L_BFGS opt;\n  opt.MaxIterations() = 10;\n  \n  // initial point (uniform random)\n  arma::vec theta(n_dims, arma::fill::randu);\n  \n  opt.Optimize(lrf, theta);\n  \n  // theta now contains the optimized parameters\n  theta.print(\"theta:\");\n  \n  return 0;\n}\n", "meta": {"hexsha": "264f137bd065720338b65fa43b77eff47a7ef45c", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "ElianeBriand/ensmallen", "max_stars_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_stars_repo_licenses": ["BSL-1.0", "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": "example.cpp", "max_issues_repo_name": "ElianeBriand/ensmallen", "max_issues_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_issues_repo_licenses": ["BSL-1.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": "example.cpp", "max_forks_repo_name": "ElianeBriand/ensmallen", "max_forks_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-16T16:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T16:21:59.000Z", "avg_line_length": 21.0985915493, "max_line_length": 78, "alphanum_fraction": 0.6194926569, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.697255956398453}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org/libs/test for the library home page.\r\n\r\n//[example_code\r\n#define BOOST_TEST_MODULE dataset_example68\r\n#include <boost/test/included/unit_test.hpp>\r\n#include <boost/test/data/test_case.hpp>\r\n#include <boost/test/data/monomorphic.hpp>\r\n#include <sstream>\r\n\r\nnamespace bdata = boost::unit_test::data;\r\n\r\n// Dataset generating a Fibonacci sequence\r\nclass fibonacci_dataset : public bdata::monomorphic::dataset<int>\r\n{\r\npublic:\r\n  // Samples type is int\r\n  typedef int data_type;\r\n  enum { arity = 1 };\r\n\r\nprivate:\r\n  typedef bdata::monomorphic::dataset<int> base;\r\n  \r\n  struct iterator : base::iterator\r\n  {\r\n    typedef bdata::monomorphic::traits<int>::ref_type ref_type;\r\n    int a;\r\n    int b; // b is the output\r\n    \r\n    iterator() : a(0), b(0) \r\n    {}\r\n    \r\n    ref_type operator*()\r\n    {\r\n      return b;\r\n    }\r\n    \r\n    virtual void operator++()\r\n    {\r\n      a = a + b;\r\n      std::swap(a, b);\r\n      \r\n      if(!b)\r\n        b = 1;\r\n    }\r\n  };\r\n  \r\npublic:\r\n  fibonacci_dataset()\r\n  {}\r\n  \r\n  // size is infinite\r\n  bdata::size_t size() const\r\n  {\r\n    return bdata::BOOST_TEST_DS_INFINITE_SIZE;\r\n  }\r\n  \r\n  // iterator\r\n  virtual iter_ptr begin() const\r\n  { \r\n    return boost::make_shared<iterator>(); \r\n  }\r\n};\r\n\r\nnamespace boost { namespace unit_test { namespace data { namespace monomorphic {\r\n  // registering fibonacci_dataset as a proper dataset\r\n  template <>\r\n  struct is_dataset<fibonacci_dataset> : boost::mpl::true_ {};\r\n}}}}\r\n\r\n// Creating a test-driven dataset \r\nBOOST_DATA_TEST_CASE( \r\n  test1, \r\n  fibonacci_dataset() ^ bdata::xrange(10),\r\n  fib_sample, index)\r\n{\r\n  std::cout << \"test 1: \" \r\n    << fib_sample \r\n    << \" / index: \" << index\r\n    << std::endl;\r\n  BOOST_TEST(fib_sample <= 13);\r\n}\r\n//]\r\n", "meta": {"hexsha": "d249c07eff908bbc1e4dc5841f77e0a73b4ffa02", "size": 1967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/examples/dataset_example68.run-fail.cpp", "max_stars_repo_name": "fineshift/boost", "max_stars_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "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/test/doc/examples/dataset_example68.run-fail.cpp", "max_issues_repo_name": "fineshift/boost", "max_issues_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "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/test/doc/examples/dataset_example68.run-fail.cpp", "max_forks_repo_name": "fineshift/boost", "max_forks_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3522727273, "max_line_length": 81, "alphanum_fraction": 0.6202338587, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6972017600800936}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include <array>\n#include \"/Users/drewlewis/software/install/tiledarray/sparse_new_summa_debug/include/tiledarray.h\"\n\nusing Tensor = TiledArray::Tensor<double>;\nusing Perm = TiledArray::Permutation;\nusing Range = TiledArray::Range;\nusing Matrix =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\ntemplate <typename... Args>\nTiledArray::Range make_range(Args... args) {\n    return TiledArray::Range(args...);\n}\n\nTensor vectors(Tensor const &a) {\n    auto const &size = a.range().size();\n    Eigen::Map<const Matrix> map(a.data(), size[0], size[1] * size[2]);\n\n    Eigen::JacobiSVD<Matrix> svd(map,\n                                 Eigen::ComputeThinU | Eigen::ComputeThinV);\n    auto const &vals = svd.singularValues();\n\n    auto rank = 0;\n    for (auto i = 0; i < vals.size(); ++i) {\n        if (1e-12 < vals[i]) {\n            ++rank;\n        }\n    }\n\n    auto matrixU = svd.matrixU().leftCols(rank);\n    Tensor U{Range(matrixU.rows(), matrixU.cols())};\n\n    for (auto i = 0; i < matrixU.size(); ++i) {\n        U[i] = *(matrixU.data() + i);\n    }\n\n    return U;\n}\n\nTensor Kron(Tensor const &a, Tensor const &b) {\n    auto const &asize = a.range().size();\n    auto const &bsize = b.range().size();\n    const auto ab0 = asize[0] * bsize[0];\n    const auto ab1 = asize[1] * bsize[1];\n\n    Tensor out(Range(ab0, ab1));\n\n    Eigen::Map<Matrix> outm(out.data(), ab0, ab1);\n    Eigen::Map<const Matrix> am(a.data(), asize[0], asize[1]);\n    Eigen::Map<const Matrix> bm(b.data(), bsize[0], bsize[1]);\n\n    outm = Matrix::Zero(ab0, ab1);\n    std::cout << \"outm = \\n\" << outm << std::endl;\n\n    auto row_start = 0;\n    for (auto i = 0; i < am.rows(); ++i) {\n        auto col_start = 0;\n        for (auto j = 0; j < am.cols(); ++j) {\n            outm.block(row_start, col_start, bsize[0], bsize[1]) = am(i, j) * bm;\n            col_start += bsize[1];\n        }\n        row_start += bsize[0];\n        std::cout << \"outm = \\n\" << std::endl;\n    }\n\n    return out;\n}\n\nTensor FormS(Tensor const &U1, Tensor const &A, Tensor const &K) {\n    auto const &usize = U1.range().size();\n    auto const &asize = A.range().size();\n    auto const &ksize = K.range().size();\n    Eigen::Map<const Matrix> um(U1.data(), usize[0], usize[1]);\n    Eigen::Map<const Matrix> am(A.data(), asize[0], asize[1] * asize[2]);\n    Eigen::Map<const Matrix> km(K.data(), ksize[0], ksize[1]);\n\n    Matrix outtemp(usize[1], asize[1] * asize[2]);\n    outtemp = um.transpose() * am;\n\n    Tensor out{Range(usize[1], asize[1], asize[2])};\n    Eigen::Map<Matrix> outm(out.data(), usize[1], asize[1] * asize[2]);\n    outm = outtemp * km;\n    return out;\n}\n\nTensor FormA(Tensor const &U1, Tensor const &S, Tensor const &K) {\n    auto const &usize = U1.range().size();\n    auto const &ssize = S.range().size();\n    auto const &ksize = K.range().size();\n    Eigen::Map<const Matrix> um(U1.data(), usize[0], usize[1]);\n    Eigen::Map<const Matrix> sm(S.data(), ssize[0], ssize[1] * ssize[2]);\n    Eigen::Map<const Matrix> km(K.data(), ksize[0], ksize[1]);\n\n    Matrix outtemp(usize[0], ssize[1] * ssize[2]);\n    outtemp = um * sm;\n    std::cout << outtemp << std::endl;\n\n    Tensor out{Range(usize[0], ssize[1], ssize[2])};\n    Eigen::Map<Matrix> outm(out.data(), usize[0], ssize[1] * ssize[2]);\n    outm = outtemp * km.transpose();\n    return out;\n}\n\nint main(int argc, char **argv) {\n    auto tensor = Tensor{make_range(3, 2, 2)};\n    for (auto i = 1; i <= 12; ++i) {\n        tensor[i - 1] = i;\n    }\n    auto u1 = vectors(tensor);\n    auto u2 = vectors(Tensor{tensor, Perm{1, 0, 2}});\n    auto u3 = vectors(Tensor{tensor, Perm{2, 1, 0}});\n\n    std::cout << tensor << std::endl;\n    std::cout << u1 << std::endl;\n    std::cout << u2 << std::endl;\n    std::cout << u3 << std::endl;\n\n    auto K = Kron(u3,u2);\n    std::cout << \"K = \\n\" << K << std::endl;\n    auto S = FormS(u1, tensor, K);\n    std::cout << \"S = \\n\" << S << std::endl;\n    auto Tapprox = FormA(u1, S, K);\n    std::cout << \"Aapprox = \\n\" << Tapprox << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "ddcf337f2de894bb5849a490ed80a48ffde920ae", "size": 4079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_tests/hosvd/hosvd.cpp", "max_stars_repo_name": "calewis/SmallProjectsAndDev", "max_stars_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_tests/hosvd/hosvd.cpp", "max_issues_repo_name": "calewis/SmallProjectsAndDev", "max_issues_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_tests/hosvd/hosvd.cpp", "max_forks_repo_name": "calewis/SmallProjectsAndDev", "max_forks_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_forks_repo_licenses": ["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.3769230769, "max_line_length": 99, "alphanum_fraction": 0.5685216965, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6972017505987161}}
{"text": "\n// Adapted from:\n// * http://www.stanford.edu/~acoates/quaternion.h\n// * http://www.euclideanspace.com/maths/geometry/rotations/conversions\n\n#pragma once\n\n#include \"vector-2.hpp\"\n#include \"vector-3.hpp\"\n#include \"vector-4.hpp\"\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nnamespace perceive\n{\n#pragma pack(push, 1)\ntemplate<typename T> class QuaternionT\n{\n public:\n   using value_type = T;\n\n   T x, y, z, w;\n\n   QuaternionT() noexcept\n       : x(0.0)\n       , y(0.0)\n       , z(0.0)\n       , w(1.0)\n   {}\n\n   QuaternionT(const Vector3T<T>& v, T w_) noexcept\n       : x(v.x)\n       , y(v.y)\n       , z(v.z)\n       , w(w_)\n   {}\n\n   QuaternionT(const Vector4T<T>& v) noexcept { from_axis_angle(v); }\n\n   QuaternionT(const T array[4]) noexcept\n   {\n      x = array[0];\n      y = array[1];\n      z = array[2];\n      w = array[3];\n   }\n\n   QuaternionT(T x_, T y_, T z_, T w_) noexcept\n       : x(x_)\n       , y(y_)\n       , z(z_)\n       , w(w_)\n   {}\n\n   QuaternionT(const Vector3T<T>& a, const Vector3T<T>& b) noexcept\n   {\n      *this = between_vectors(a, b);\n   }\n\n   bool operator==(const QuaternionT& rhs) const noexcept\n   {\n      const auto o       = this->normalised();\n      const auto p       = rhs.normalised();\n      const auto cos_phi = p.x * o.x + p.y * o.y + p.z * o.z + p.w * o.w;\n      return fabs(cos_phi) > 1.0 - 1e-9;\n   }\n\n   bool operator!=(const QuaternionT& rhs) const noexcept\n   {\n      return !(*this == rhs);\n   }\n\n   static inline QuaternionT identity() noexcept\n   {\n      return QuaternionT(0.0, 0.0, 0.0, 1.0);\n   }\n\n   static QuaternionT nan() noexcept\n   {\n      constexpr T val = T(NAN);\n      return QuaternionT(val, val, val, val);\n   }\n\n   // Create from between vectors\n   static inline QuaternionT between_vectors(const Vector3T<T>& a,\n                                             const Vector3T<T>& b) noexcept\n   {\n      auto u     = a.normalised();\n      auto v     = b.normalised();\n      auto n     = cross(u, v);\n      auto cos_t = dot(u, v);\n      if(cos_t < (1e-6 - 1.0)) {\n         // 180 degree rotation... about arbitrary axis\n         Vector3T<T> axis;\n         axis = cross(Vector3T<T>(1, 0, 0), u);\n         if(axis.quadrance() < 1e-3) axis = cross(Vector3T<T>(0, 1, 0), u);\n         axis.normalise();\n         return QuaternionT(axis, 0);\n      } else if(cos_t >= 1.0 - 1e-6) {\n         return QuaternionT(0, 0, 0, 1);\n      }\n      QuaternionT q(n, 1.0 + cos_t);\n      q.normalise();\n      return q;\n   }\n\n   // Create from between rotations: r * a = b\n   static inline QuaternionT between_rotations(const QuaternionT<T>& a,\n                                               const QuaternionT<T>& b) noexcept\n   {\n      return b * a.conjugate();\n   }\n\n   Vector3T<T>& complex() noexcept\n   {\n      return *(reinterpret_cast<Vector3T<T>*>(this));\n   }\n   const Vector3T<T>& complex() const noexcept\n   {\n      return *(reinterpret_cast<const Vector3T<T>*>(this));\n   }\n   T& real() noexcept { return w; }\n   const T& real() const noexcept { return w; }\n   QuaternionT conjugate() const noexcept { return QuaternionT(-x, -y, -z, w); }\n\n   QuaternionT inverse() const noexcept { return conjugate().normalised(); }\n   QuaternionT& invert() const noexcept\n   {\n      x = -x;\n      y = -y;\n      z = -z;\n      return normalise();\n   }\n\n   T quadrance() const noexcept { return x * x + y * y + z * z + w * w; }\n   T norm() const noexcept { return std::sqrt(quadrance()); }\n\n   QuaternionT normalised(T epsilon = T(1e-9)) const noexcept\n   {\n      QuaternionT ret(*this);\n      ret.normalise(epsilon);\n      return ret;\n   }\n\n   QuaternionT& normalise(T epsilon = T(1e-9)) noexcept\n   {\n      auto mag2 = quadrance();\n      if(std::fabs(mag2 - T(1.0)) > epsilon) {\n         auto inv = T(1.0) / T(std::sqrt(mag2));\n         x *= inv;\n         y *= inv;\n         z *= inv;\n         w *= inv;\n      }\n      return *this;\n   }\n\n   unsigned size() const noexcept { return 4; }\n\n   T* copy_to(T a[4]) const noexcept\n   {\n      a[0] = x;\n      a[1] = y;\n      a[2] = z;\n      a[3] = w;\n      return a;\n   }\n\n   T* ptr() noexcept { return &x; }\n   const T* ptr() const noexcept { return &x; }\n   T& operator[](int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator[](int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   T& operator()(int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator()(int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   static void product(const QuaternionT<T>& a,\n                       const QuaternionT<T>& b,\n                       QuaternionT<T>& c) noexcept\n   {\n      c.x = a.y * b.z - a.z * b.y + a.x * b.w + a.w * b.x;\n      c.y = a.z * b.x - a.x * b.z + a.y * b.w + a.w * b.y;\n      c.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;\n      c.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n   }\n\n   QuaternionT<T> operator*(const QuaternionT<T>& rhs) const noexcept\n   {\n      QuaternionT<T> q;\n      product(*this, rhs, q);\n      return q;\n   }\n   QuaternionT<T>& operator*=(const QuaternionT<T>& rhs) noexcept\n   {\n      *this = *this * rhs;\n      return *this;\n   }\n\n   QuaternionT<T> operator*(T s) const noexcept\n   {\n      auto q = *this;\n      q *= s;\n      return q;\n   }\n   QuaternionT<T>& operator*=(T s) noexcept\n   {\n      x *= s;\n      y *= s;\n      z *= s;\n      w *= s;\n      return *this;\n   }\n   QuaternionT<T> operator/(T s) const noexcept { return *this * T(1.0) /= s; }\n   QuaternionT<T>& operator/=(T s) noexcept { return *this *= T(1.0) / s; }\n\n   QuaternionT<T> operator+(const QuaternionT<T>& o) const noexcept\n   {\n      auto q = *this;\n      q += o;\n      return q;\n   }\n   QuaternionT<T>& operator+=(const QuaternionT<T>& o) noexcept\n   {\n      x += o.x;\n      y += o.y;\n      z += o.z;\n      w += o.w;\n      return *this;\n   }\n   QuaternionT<T> operator-(const QuaternionT<T>& o) const noexcept\n   {\n      auto q = *this;\n      q -= o;\n      return q;\n   }\n   QuaternionT<T>& operator-=(const QuaternionT<T>& o) noexcept\n   {\n      x -= o.x;\n      y -= o.y;\n      z -= o.z;\n      w -= o.w;\n      return *this;\n   }\n\n   // Same as rotation-maxtrix3x3 * v\n   Vector3T<T> rotate(const Vector3T<T>& v) const noexcept\n   {\n      return (((*this) * QuaternionT(v, 0)) * inverse()).complex();\n   }\n\n   Vector3T<T> inverse_rotate(const Vector3T<T>& v) const noexcept\n   {\n      return conjugate().rotate(v);\n   }\n\n   Vector3T<T> apply(const Vector3T<T>& v) const noexcept { return rotate(v); }\n   Vector3T<T> inverse_apply(const Vector3T<T>& v) const noexcept\n   {\n      return inverse_rotate(v);\n   }\n\n   // -- spherical-axis-angle\n   Vector3T<T> to_spherical_axis_angle() const noexcept\n   {\n      Vector3T<T> a;\n      auto aa = to_axis_angle();\n      a.x     = std::acos(aa.z);        // inclination\n      a.y     = std::atan2(aa.y, aa.x); // azimuth\n      a.z     = aa.w;                   // theta\n      return a;\n   }\n\n   QuaternionT<T>& from_spherical_axis_angle(const Vector3T<T>& a) noexcept\n   {\n      // a(inclination, azimuth, amount-of-rotation)\n      const T half_theta     = T(0.5) * a.z;\n      const T sin_half_theta = std::sin(half_theta);\n      x                      = std::sin(a.x) * std::cos(a.y) * sin_half_theta;\n      y                      = std::sin(a.x) * std::sin(a.y) * sin_half_theta;\n      z                      = std::cos(a.x) * sin_half_theta;\n      w                      = std::cos(half_theta);\n      return *this;\n   }\n\n   QuaternionT& from_axis_angle(const Vector3T<T>& a,\n                                const double theta) noexcept\n   {\n      const T sin_t = std::sin(0.5 * theta);\n      const T cos_t = std::cos(0.5 * theta);\n      auto b        = a.normalised();\n      x             = b.x * sin_t;\n      y             = b.y * sin_t;\n      z             = b.z * sin_t;\n      w             = cos_t;\n      normalise();\n      return *this;\n   }\n\n   QuaternionT& from_axis_angle(const Vector4T<T>& a) noexcept\n   {\n      return from_axis_angle(a.xyz(), a.d());\n   }\n\n   Vector4T<T> to_axis_angle() const noexcept\n   {\n      if(!is_finite()) return Vector4T<T>::nan();\n      auto mag = quadrance();\n      if(std::fabs(mag) < T(1e-9)) return Vector4T<T>(1, 0, 0, 0);\n      T n_inv = T(1.0) / std::sqrt(mag);\n\n      Vector4T<T> a;\n      if(std::fabs(w - T(1.0)) < T(1e-9)) {\n         // There is no rotation, so set the axis\n         // to an arbitrary value, and theta to 0\n         a = Vector4T<T>(1, 0, 0, 0);\n      } else {\n         auto ww = w * n_inv;\n         T theta = T(2.0) * std::acos(ww); // angle of rotation\n         T s_inv = T(1.0) / std::sqrt(T(1.0) - ww * ww);\n         a.xyz() = complex() * s_inv * n_inv;\n         a.w     = T(2.0) * std::acos(ww);\n      }\n      return a;\n   }\n\n   T theta() const noexcept { return to_axis_angle().w; }\n   Vector3T<T> axis() const noexcept { return to_axis_angle().xyz(); }\n\n   void set_theta(T f) noexcept { from_axis_angle(axis(), f); }\n   void set_axis(const Vector3T<T>& a) noexcept { from_axis_angle(a, theta()); }\n\n   bool is_nan() const noexcept\n   {\n      return std::isnan(x) || std::isnan(y) || std::isnan(z) || std::isnan(w);\n   }\n   bool is_finite() const noexcept\n   {\n      return std::isfinite(x) && std::isfinite(y) && std::isfinite(z)\n             && std::isfinite(w);\n   }\n   bool is_unit_quaternion(T epsilon = 1e-9) const noexcept\n   {\n      return is_finite() && fabs(quadrance() - 1.0) < epsilon;\n   }\n\n   // -- String shim --\n   std::string to_string(const char* fmt = \"[{}, {}, {}, {}]\") const\n   {\n      return format(fmt, x, y, z, w);\n   }\n   std::string to_str() const { return to_string(\"[{}, {}, {}, {}]\"); }\n\n   void print(const char* msg = NULL, bool newline = true) const\n   {\n      printf(\"{}{}{}{}\",\n             (msg == NULL ? \"\" : msg),\n             (msg == NULL ? \"\" : \" \"),\n             to_string().c_str(),\n             (newline ? \"\\n\" : \"\"));\n      fflush(stdout);\n   }\n\n   std::string to_readable_str() const\n   {\n      auto aa = to_axis_angle();\n      return format(\"aa = [{:7.5f}, {:7.5f}, {:7.5f}], theta = {:7.3f} degrees\",\n                    aa(0),\n                    aa(1),\n                    aa(2),\n                    to_degrees(aa(3)));\n   }\n};\n#pragma pack(pop)\n\n// Scalar multiplication\ntemplate<typename T> QuaternionT<T> operator*(float a, const QuaternionT<T>& v)\n{\n   return v * a;\n}\ntemplate<typename T> QuaternionT<T> operator/(float a, const QuaternionT<T>& v)\n{\n   return v / a;\n}\ntemplate<typename T> QuaternionT<T> operator*(double a, const QuaternionT<T>& v)\n{\n   return v * a;\n}\ntemplate<typename T> QuaternionT<T> operator/(double a, const QuaternionT<T>& v)\n{\n   return v / a;\n}\n\n// ------------------- String shim\ntemplate<typename T> std::string str(const QuaternionT<T>& v)\n{\n   return v.to_string();\n}\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const QuaternionT<T>& v)\n{\n   out << v.to_string();\n   return out;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "577f89b79abff065598c6f8401818cec05b9fbf5", "size": 11134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/quaternion.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/geometry/quaternion.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/geometry/quaternion.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": 25.6543778802, "max_line_length": 80, "alphanum_fraction": 0.523890785, "num_tokens": 3284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6972017473019031}}
{"text": "#include \"drake/common/polynomial.h\"\n\n#include <cmath>\n#include <cstddef>\n#include <map>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/symbolic.h\"\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/common/test_utilities/expect_no_throw.h\"\n#include \"drake/common/test_utilities/random_polynomial_matrix.h\"\n\nusing Eigen::VectorXd;\nusing std::default_random_engine;\nusing std::map;\nusing std::runtime_error;\nusing std::uniform_int_distribution;\nusing std::uniform_real_distribution;\nusing std::vector;\n\nnamespace drake {\nnamespace {\n\nusing std::pow;\n\ntemplate <typename T>\nvoid testIntegralAndDerivative() {\n  VectorXd coefficients = VectorXd::Random(5);\n  Polynomial<T> poly(coefficients);\n\n  EXPECT_TRUE(CompareMatrices(poly.GetCoefficients(),\n                              poly.Derivative(0).GetCoefficients(), 1e-14,\n                              MatrixCompareType::absolute));\n\n  const T x{1.32};\n  Polynomial<T> first_derivative = poly.Derivative(1);\n  EXPECT_NEAR(poly.EvaluateUnivariate(x, 1),\n              first_derivative.EvaluateUnivariate(x), 1e-14);\n\n  Polynomial<T> third_derivative = poly.Derivative(3);\n  EXPECT_NEAR(poly.EvaluateUnivariate(x, 3),\n              third_derivative.EvaluateUnivariate(x), 1e-14);\n\n  Polynomial<T> third_derivative_check =\n      poly.Derivative().Derivative().Derivative();\n\n  EXPECT_TRUE(CompareMatrices(third_derivative.GetCoefficients(),\n                              third_derivative_check.GetCoefficients(), 1e-14,\n                              MatrixCompareType::absolute));\n\n  Polynomial<T> tenth_derivative = poly.Derivative(10);\n\n  EXPECT_TRUE(CompareMatrices(tenth_derivative.GetCoefficients(),\n                              VectorXd::Zero(1), 1e-14,\n                              MatrixCompareType::absolute));\n\n  Polynomial<T> integral = poly.Integral(0.0);\n  Polynomial<T> poly_back = integral.Derivative();\n\n  EXPECT_TRUE(CompareMatrices(poly_back.GetCoefficients(),\n                              poly.GetCoefficients(), 1e-14,\n                              MatrixCompareType::absolute));\n}\n\ntemplate <typename T>\nvoid testOperators() {\n  int max_num_coefficients = 6;\n  int num_tests = 10;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n  uniform_real_distribution<double> uniform;\n\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeff1 = VectorXd::Random(int_distribution(generator));\n    Polynomial<T> poly1(coeff1);\n\n    VectorXd coeff2 = VectorXd::Random(int_distribution(generator));\n    Polynomial<T> poly2(coeff2);\n\n    double scalar = uniform(generator);\n\n    Polynomial<T> sum = poly1 + poly2;\n    Polynomial<T> difference = poly2 - poly1;\n    Polynomial<T> product = poly1 * poly2;\n    Polynomial<T> poly1_plus_scalar = poly1 + scalar;\n    Polynomial<T> poly1_minus_scalar = poly1 - scalar;\n    Polynomial<T> poly1_scaled = poly1 * scalar;\n    Polynomial<T> poly1_div = poly1 / scalar;\n    Polynomial<T> poly1_times_poly1 = poly1;\n    const Polynomial<T> pow_poly1_3{pow(poly1, 3)};\n    const Polynomial<T> pow_poly1_4{pow(poly1, 4)};\n    const Polynomial<T> pow_poly1_10{pow(poly1, 10)};\n    poly1_times_poly1 *= poly1_times_poly1;\n\n    double t = uniform(generator);\n    EXPECT_NEAR(sum.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) + poly2.EvaluateUnivariate(t),\n                1e-8);\n    EXPECT_NEAR(difference.EvaluateUnivariate(t),\n                poly2.EvaluateUnivariate(t) - poly1.EvaluateUnivariate(t),\n                1e-8);\n    EXPECT_NEAR(product.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) * poly2.EvaluateUnivariate(t),\n                1e-8);\n    EXPECT_NEAR(poly1_plus_scalar.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) + scalar, 1e-8);\n    EXPECT_NEAR(poly1_minus_scalar.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) - scalar, 1e-8);\n    EXPECT_NEAR(poly1_scaled.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) * scalar, 1e-8);\n    EXPECT_NEAR(poly1_div.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) / scalar, 1e-8);\n    EXPECT_NEAR(poly1_times_poly1.EvaluateUnivariate(t),\n                poly1.EvaluateUnivariate(t) * poly1.EvaluateUnivariate(t),\n                1e-8);\n    EXPECT_NEAR(pow_poly1_3.EvaluateUnivariate(t),\n                pow(poly1.EvaluateUnivariate(t), 3), 1e-8);\n    EXPECT_NEAR(pow_poly1_4.EvaluateUnivariate(t),\n                pow(poly1.EvaluateUnivariate(t), 4), 1e-8);\n    EXPECT_NEAR(pow_poly1_10.EvaluateUnivariate(t),\n                pow(poly1.EvaluateUnivariate(t), 10), 1e-8);\n    EXPECT_NEAR(pow_poly1_3.EvaluateUnivariate(t) *\n                    pow_poly1_4.EvaluateUnivariate(t) *\n                    pow_poly1_3.EvaluateUnivariate(t),\n                pow_poly1_10.EvaluateUnivariate(t), 1e-8);\n\n    // Check the '==' operator.\n    EXPECT_TRUE(poly1 + poly2 == sum);\n    EXPECT_FALSE(poly1 == sum);\n  }\n}\n\ntemplate <typename T>\nvoid testRoots() {\n  int max_num_coefficients = 6;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n\n  int num_tests = 50;\n  for (int i = 0; i < num_tests; ++i) {\n    VectorXd coeffs = VectorXd::Random(int_distribution(generator));\n    Polynomial<T> poly(coeffs);\n    auto roots = poly.Roots();\n    EXPECT_EQ(roots.rows(), poly.GetDegree());\n    for (int k = 0; k < roots.size(); k++) {\n      auto value = poly.EvaluateUnivariate(roots[k]);\n      EXPECT_NEAR(std::abs(value), 0.0, 1e-8);\n    }\n  }\n}\n\nvoid testEvalType() {\n  int max_num_coefficients = 6;\n  default_random_engine generator;\n  std::uniform_int_distribution<> int_distribution(1, max_num_coefficients);\n  VectorXd coeffs = VectorXd::Random(int_distribution(generator));\n  Polynomial<double> poly(coeffs);\n\n  auto valueIntInput = poly.EvaluateUnivariate(1);\n  EXPECT_EQ(typeid(decltype(valueIntInput)), typeid(double));\n\n  auto valueComplexInput =\n      poly.EvaluateUnivariate(std::complex<double>(1.0, 2.0));\n  EXPECT_EQ(typeid(decltype(valueComplexInput)), typeid(std::complex<double>));\n}\n\ntemplate <typename T>\nvoid testPolynomialMatrix() {\n  int max_matrix_rows_cols = 7;\n  int num_coefficients = 6;\n  default_random_engine generator;\n\n  uniform_int_distribution<> matrix_size_distribution(1, max_matrix_rows_cols);\n  int rows_A = matrix_size_distribution(generator);\n  int cols_A = matrix_size_distribution(generator);\n  int rows_B = cols_A;\n  int cols_B = matrix_size_distribution(generator);\n\n  auto A = test::RandomPolynomialMatrix<T>(num_coefficients,\n                                                         rows_A, cols_A);\n  auto B = test::RandomPolynomialMatrix<T>(num_coefficients,\n                                                         rows_B, cols_B);\n  auto C = test::RandomPolynomialMatrix<T>(num_coefficients,\n                                                         rows_A, cols_A);\n  auto product = A * B;\n  auto sum = A + C;\n\n  uniform_real_distribution<double> uniform;\n  for (int row = 0; row < A.rows(); ++row) {\n    for (int col = 0; col < A.cols(); ++col) {\n      double t = uniform(generator);\n      EXPECT_NEAR(sum(row, col).evaluateUnivariate(t),\n                  A(row, col).evaluateUnivariate(t) +\n                  C(row, col).evaluateUnivariate(t), 1e-8);\n\n      double expected_product = 0.0;\n      for (int i = 0; i < A.cols(); ++i) {\n        expected_product += A(row, i).evaluateUnivariate(t) *\n                            B(i, col).evaluateUnivariate(t);\n      }\n      EXPECT_NEAR(product(row, col).evaluateUnivariate(t),\n                  expected_product, 1e-8);\n    }\n  }\n\n  C.setZero();  // this was a problem before\n}\n\nGTEST_TEST(PolynomialTest, IntegralAndDerivative) {\n  testIntegralAndDerivative<double>();\n}\n\nGTEST_TEST(PolynomialTest, TestMakeMonomialsUnique) {\n  Eigen::Vector2d coefficients(1, 2);\n  Polynomial<double> poly(coefficients);\n  const auto poly_squared = poly * poly;\n  EXPECT_EQ(poly_squared.GetNumberOfCoefficients(), 3);\n}\n\nGTEST_TEST(PolynomialTest, Operators) { testOperators<double>(); }\n\nGTEST_TEST(PolynomialTest, Roots) { testRoots<double>(); }\n\nGTEST_TEST(PolynomialTest, EvalType) { testEvalType(); }\n\nGTEST_TEST(PolynomialTest, IsAffine) {\n  Polynomiald x(\"x\");\n  Polynomiald y(\"y\");\n\n  EXPECT_TRUE(x.IsAffine());\n  EXPECT_TRUE(y.IsAffine());\n  EXPECT_TRUE((2 + x).IsAffine());\n  EXPECT_TRUE((2 * x).IsAffine());\n  EXPECT_FALSE((x * x).IsAffine());\n  EXPECT_FALSE((x * y).IsAffine());\n  EXPECT_TRUE((x + y).IsAffine());\n  EXPECT_TRUE((2 + x + y).IsAffine());\n  EXPECT_TRUE((2 + (2 * x) + y).IsAffine());\n  EXPECT_FALSE((2 + (y * x) + y).IsAffine());\n}\n\nGTEST_TEST(PolynomialTest, VariableIdGeneration) {\n  // Probe the outer edge cases of variable ID generation.\n\n  // There is no documented maximum ID, but empirically it is 2325.  What we\n  // really care about here is just that there is some value below which it\n  // succeeds and above which it fails.\n  static const int kMaxId = 2325;\n\n  DRAKE_EXPECT_NO_THROW(Polynomial<double>(\"x\", kMaxId));\n  DRAKE_EXPECT_NO_THROW(Polynomial<double>(\"zzzz\", 1));\n  DRAKE_EXPECT_NO_THROW(Polynomial<double>(\"zzzz\", kMaxId));\n  EXPECT_THROW(Polynomial<double>(\"!\"),\n               std::runtime_error);  // Illegal character.\n  EXPECT_THROW(Polynomial<double>(\"zzzz@\"),\n               std::runtime_error);  // Illegal length.\n  EXPECT_THROW(Polynomial<double>(\"z\", 0),\n               std::runtime_error);  // Illegal ID.\n  EXPECT_THROW(Polynomial<double>(\"z\", kMaxId + 1),\n               std::runtime_error);  // Illegal ID.\n\n  // Test that ID generation round-trips correctly.\n  std::stringstream test_stream;\n  test_stream << Polynomial<double>(\"x\", 1);\n  std::string result;\n  test_stream >> result;\n  EXPECT_EQ(result, \"x1\");\n}\n\nGTEST_TEST(PolynomialTest, GetVariables) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald::VarType x_var = x.GetSimpleVariable();\n  Polynomiald y = Polynomiald(\"y\");\n  Polynomiald::VarType y_var = y.GetSimpleVariable();\n  Polynomiald z = Polynomiald(\"z\");\n  Polynomiald::VarType z_var = z.GetSimpleVariable();\n\n  EXPECT_TRUE(x.GetVariables().count(x_var));\n  EXPECT_FALSE(x.GetVariables().count(y_var));\n\n  EXPECT_FALSE(Polynomiald().GetVariables().count(x_var));\n\n  EXPECT_TRUE((x + x).GetVariables().count(x_var));\n\n  EXPECT_TRUE((x + y).GetVariables().count(x_var));\n  EXPECT_TRUE((x + y).GetVariables().count(y_var));\n\n  EXPECT_TRUE((x * y * y + z).GetVariables().count(x_var));\n  EXPECT_TRUE((x * y * y + z).GetVariables().count(y_var));\n  EXPECT_TRUE((x * y * y + z).GetVariables().count(z_var));\n\n  EXPECT_FALSE(x.Derivative().GetVariables().count(x_var));\n}\n\nGTEST_TEST(PolynomialTest, Simplification) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n\n  {  // Test duplicate monomials.\n    std::stringstream test_stream;\n    test_stream << ((x * y) + (x * y));\n    std::string result;\n    test_stream >> result;\n    EXPECT_EQ(result, \"(2)*x1*y1\");\n  }\n\n  {  // Test monomials that are duplicates under commutativity.\n    std::stringstream test_stream;\n    test_stream << ((x * y) + (y * x));\n    std::string result;\n    test_stream >> result;\n    EXPECT_EQ(result, \"(2)*x1*y1\");\n  }\n}\n\nGTEST_TEST(PolynomialTest, MonomialFactor) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n\n  // \"m_\" prefix denotes monomial.\n  Polynomiald::Monomial m_one = Polynomiald(1).GetMonomials()[0];\n  Polynomiald::Monomial m_two = Polynomiald(2).GetMonomials()[0];\n  Polynomiald::Monomial m_x = x.GetMonomials()[0];\n  Polynomiald::Monomial m_y = y.GetMonomials()[0];\n  Polynomiald::Monomial m_2x = (x * 2).GetMonomials()[0];\n  Polynomiald::Monomial m_x2 = (x * x).GetMonomials()[0];\n  Polynomiald::Monomial m_x2y = (x * x * y).GetMonomials()[0];\n\n  // Expect failures\n  EXPECT_EQ(m_x.Factor(m_y).coefficient, 0);\n  EXPECT_EQ(m_x.Factor(m_x2).coefficient, 0);\n\n  // Expect successes\n  EXPECT_EQ(m_x.Factor(m_x), m_one);\n  EXPECT_EQ(m_2x.Factor(m_x), m_two);\n  EXPECT_EQ(m_x2.Factor(m_x), m_x);\n  EXPECT_EQ(m_x2y.Factor(m_x2), m_y);\n  EXPECT_EQ(m_x2y.Factor(m_y), m_x2);\n}\n\nGTEST_TEST(PolynomialTest, MultivariateValue) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n  const Polynomiald p{x * x + 2 * x * y + y * y + 2};\n  const Polynomiald pow_p_2{pow(p, 2)};\n  const Polynomiald pow_p_3{pow(p, 3)};\n  const Polynomiald pow_p_7{pow(p, 7)};\n  const std::map<Polynomiald::VarType, double> eval_point = {\n    {x.GetSimpleVariable(), 1},\n    {y.GetSimpleVariable(), 2}};\n  EXPECT_EQ((x * x + y).EvaluateMultivariate(eval_point), 3);\n  EXPECT_EQ((2 * x * x + y).EvaluateMultivariate(eval_point), 4);\n  EXPECT_EQ((x * x + 2 * y).EvaluateMultivariate(eval_point), 5);\n  EXPECT_EQ((x * x + x * y).EvaluateMultivariate(eval_point), 3);\n  EXPECT_NEAR(pow_p_2.EvaluateMultivariate(eval_point),\n              pow(p.EvaluateMultivariate(eval_point), 2), 1e-8);\n  EXPECT_NEAR(pow_p_3.EvaluateMultivariate(eval_point),\n              pow(p.EvaluateMultivariate(eval_point), 3), 1e-8);\n  EXPECT_NEAR(pow_p_7.EvaluateMultivariate(eval_point),\n              pow(p.EvaluateMultivariate(eval_point), 7), 1e-8);\n  EXPECT_NEAR((pow_p_2 * pow_p_3 * pow_p_2).EvaluateMultivariate(eval_point),\n              pow_p_7.EvaluateMultivariate(eval_point), 1e-8);\n}\n\nGTEST_TEST(PolynomialTest, Conversion) {\n  // Confirm that these conversions compile okay.\n  Polynomial<double> x(1.0);\n  Polynomial<double> y = 2.0;\n  Polynomial<double> z = 3;\n}\n\nGTEST_TEST(PolynomialTest, EvaluatePartial) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n  Polynomiald dut = (5 * x * x * x) + (3 * x * y) + (2 * y) + 1;\n\n  const std::map<Polynomiald::VarType, double> eval_point_null;\n  const std::map<Polynomiald::VarType, double> eval_point_x = {\n    {x.GetSimpleVariable(), 7}};\n  const std::map<Polynomiald::VarType, double> eval_point_y = {\n    {y.GetSimpleVariable(), 11}};\n  const std::map<Polynomiald::VarType, double> eval_point_xy = {\n    {x.GetSimpleVariable(), 7},\n    {y.GetSimpleVariable(), 11}};\n\n  // Test a couple of straightforward explicit cases.\n  EXPECT_EQ(dut.EvaluatePartial(eval_point_null).GetMonomials(),\n            dut.GetMonomials());\n  // TODO(#2216) These fail due to a known drake bug:\n#if 0\n  EXPECT_EQ(dut.evaluatePartial(eval_point_x).getMonomials(),\n            ((23 * y) + 1716).getMonomials());\n  EXPECT_EQ(dut.evaluatePartial(eval_point_y).getMonomials(),\n            ((5 * x * x * x) + (33 * x) + 23).getMonomials());\n#endif\n\n  // Test that every order of partial and then complete evaluation gives the\n  // same answer.\n  const double expected_result = dut.EvaluateMultivariate(eval_point_xy);\n  EXPECT_EQ(\n      dut.EvaluatePartial(eval_point_null).EvaluateMultivariate(eval_point_xy),\n      expected_result);\n  EXPECT_EQ(\n      dut.EvaluatePartial(eval_point_xy).EvaluateMultivariate(eval_point_null),\n      expected_result);\n  EXPECT_EQ(\n      dut.EvaluatePartial(eval_point_x).EvaluateMultivariate(eval_point_y),\n      expected_result);\n  EXPECT_EQ(\n      dut.EvaluatePartial(eval_point_y).EvaluateMultivariate(eval_point_x),\n      expected_result);\n\n  // Test that zeroing out one term gives a sensible result.\n  EXPECT_EQ(dut.EvaluatePartial(\n      std::map<Polynomiald::VarType, double>{{x.GetSimpleVariable(), 0}}),\n            (2 * y) + 1);\n  EXPECT_EQ(dut.EvaluatePartial(\n      std::map<Polynomiald::VarType, double>{{y.GetSimpleVariable(), 0}}),\n            (5 * x * x * x) + 1);\n}\n\nGTEST_TEST(PolynomialTest, FromExpression) {\n  using symbolic::Environment;\n  using symbolic::Expression;\n  using symbolic::Variable;\n\n  const Variable x{\"x\"};\n  const Variable y{\"y\"};\n  const Variable z{\"z\"};\n  Environment env{{x, 1.0}, {y, 2.0}, {z, 3.0}};\n  const map<Polynomiald::VarType, double> eval_point{\n      {x.get_id(), env[x]}, {y.get_id(), env[y]}, {z.get_id(), env[z]}};\n\n  const Expression e0{42.0};\n  const Expression e1{pow(x, 2)};\n  const Expression e2{3 + x + y + z};\n  const Expression e3{1 + pow(x, 2) + pow(y, 2)};\n  const Expression e4{pow(x, 2) * pow(y, 2)};\n  const Expression e5{pow(x + y + z, 3)};\n  const Expression e6{pow(x + y + z, 3) / 10};\n  const Expression e7{-pow(y, 3)};\n  const Expression e8{pow(pow(x, 3), 1.0 / 3)};\n\n  EXPECT_NEAR(\n      e0.Evaluate(env),\n      Polynomial<double>::FromExpression(e0).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e1.Evaluate(env),\n      Polynomial<double>::FromExpression(e1).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e2.Evaluate(env),\n      Polynomial<double>::FromExpression(e2).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e3.Evaluate(env),\n      Polynomial<double>::FromExpression(e3).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e4.Evaluate(env),\n      Polynomial<double>::FromExpression(e4).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e5.Evaluate(env),\n      Polynomial<double>::FromExpression(e5).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e6.Evaluate(env),\n      Polynomial<double>::FromExpression(e6).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e7.Evaluate(env),\n      Polynomial<double>::FromExpression(e7).EvaluateMultivariate(eval_point),\n      1e-8);\n  EXPECT_NEAR(\n      e8.Evaluate(env),\n      Polynomial<double>::FromExpression(e8).EvaluateMultivariate(eval_point),\n      1e-8);\n\n  const vector<Expression> test_vec{\n      log(x),\n      abs(x),\n      exp(x),\n      sqrt(x),\n      sin(x),\n      cos(x),\n      tan(x),\n      asin(x),\n      acos(x),\n      atan(x),\n      atan2(x, y),\n      sinh(x),\n      cosh(x),\n      tanh(x),\n      min(x, y),\n      max(x, y),\n      ceil(x),\n      floor(x),\n      if_then_else(x > y, x, y),\n      Expression::NaN(),\n      symbolic::uninterpreted_function(\"uf\", {x, y})};\n  for (const Expression& e : test_vec) {\n    EXPECT_FALSE(e.is_polynomial());\n    EXPECT_THROW(Polynomial<double>::FromExpression(e), runtime_error);\n  }\n}\n\ntemplate <typename T>\nvoid TestScalarType() {\n  Eigen::Vector3d coeffs(1., 2., 3.);\n  const Polynomial<T> p(coeffs);\n  EXPECT_NEAR(ExtractDoubleOrThrow(p.EvaluateUnivariate(0.0)), coeffs(0),\n              1e-14);\n\n  EXPECT_THROW(p.Roots(), std::runtime_error);\n  EXPECT_TRUE(static_cast<bool>(p.CoefficientsAlmostEqual(p, 1e-14)));\n\n  Polynomial<T> x(\"x\", 1);\n  Polynomial<T> y(\"y\", 1);\n  const std::map<Polynomiald::VarType, double> eval_point = {\n    {x.GetSimpleVariable(), 1},\n    {y.GetSimpleVariable(), 2}};\n  EXPECT_NEAR(\n      ExtractDoubleOrThrow((x * x + y).EvaluateMultivariate(eval_point)), 3,\n      1e-14);\n}\n\nGTEST_TEST(PolynomialTest, ScalarTypes) {\n  TestScalarType<AutoDiffXd>();\n  TestScalarType<symbolic::Expression>();\n\n  // Checks that we can create an instance, Polynomial<T>(0). `Scalar(0)` (where\n  // Scalar = Polynomial<T>) is a common pattern in Eigen internals and we want\n  // to make sure that we can build these instances.\n  const Polynomial<double> p_double(0);\n  const Polynomial<AutoDiffXd> p_autodiffxd(0);\n  const Polynomial<symbolic::Expression> p_symbolic(0);\n}\n\nGTEST_TEST(PolynomialTest, CoefficientsAlmostEqualTest) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n\n  EXPECT_FALSE(x.CoefficientsAlmostEqual(y));\n  EXPECT_TRUE((x + y).CoefficientsAlmostEqual(y + x));\n\n  EXPECT_TRUE((x + x * x + 3 * pow(x, 3))\n                  .CoefficientsAlmostEqual(3 * pow(x, 3) + x + x * x));\n\n  // Test relative and absolute tolerance.\n  EXPECT_TRUE(\n      (100 * x).CoefficientsAlmostEqual(99 * x, 0.1, ToleranceType::kRelative));\n  EXPECT_FALSE(\n      (100 * x).CoefficientsAlmostEqual(99 * x, 0.1, ToleranceType::kAbsolute));\n  EXPECT_FALSE((0.01 * x).CoefficientsAlmostEqual(0.02 * x, 0.1,\n                                                  ToleranceType::kRelative));\n  EXPECT_TRUE((0.01 * x).CoefficientsAlmostEqual(0.02 * x, 0.1,\n                                                 ToleranceType::kAbsolute));\n\n  // Test missing monomials.\n  EXPECT_FALSE((x + y + 0.01 * x * x).CoefficientsAlmostEqual(x + y));\n  EXPECT_FALSE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x));\n  // Missing monomials is ok only for absolute tolerance.\n  EXPECT_TRUE(\n      (x + y + 0.01 * x * x)\n          .CoefficientsAlmostEqual(x + y, 0.02, ToleranceType::kAbsolute));\n  EXPECT_TRUE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x, 0.02,\n                                              ToleranceType::kAbsolute));\n  EXPECT_FALSE(\n      (x + y + 0.01 * x * x)\n          .CoefficientsAlmostEqual(x + y, 0.02, ToleranceType::kRelative));\n  EXPECT_FALSE((x + y).CoefficientsAlmostEqual(x + y + 0.01 * x * x, 0.02,\n                                               ToleranceType::kRelative));\n}\n\nGTEST_TEST(PolynomialTest, SubsitutionTest) {\n  Polynomiald x = Polynomiald(\"x\");\n  Polynomiald y = Polynomiald(\"y\");\n\n  Polynomiald::VarType xvar = x.GetSimpleVariable();\n  Polynomiald::VarType yvar = y.GetSimpleVariable();\n\n  EXPECT_TRUE(x.Substitute(xvar, y).CoefficientsAlmostEqual(y));\n\n  Polynomiald p1 = x + 3 * x * x + 3 * y;\n  EXPECT_TRUE(\n      p1.Substitute(xvar, 1 + x)\n          .CoefficientsAlmostEqual(1 + x + 3 * (1 + x) * (1 + x) + 3 * y));\n  EXPECT_TRUE(p1.Substitute(yvar, 1 + x)\n                  .CoefficientsAlmostEqual(3 + 4 * x + 3 * x * x));\n  EXPECT_TRUE(p1.Substitute(xvar, x * x)\n                  .CoefficientsAlmostEqual(x * x + 3 * pow(x, 4) + 3 * y));\n}\n\n}  // anonymous namespace\n}  // namespace drake\n", "meta": {"hexsha": "6b38c13d0680e014c21eba5e16869259a834dbea", "size": 21513, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/test/polynomial_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "common/test/polynomial_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "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": "common/test/polynomial_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 35.6766169154, "max_line_length": 80, "alphanum_fraction": 0.6578812811, "num_tokens": 5782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6970802677908864}}
{"text": "// neural_network.cpp example program using posit arithmetic for a neural network simulation\n//\n// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#include \"common.hpp\"\n// include the posit number system\n#include <universal/posit/posit>\n#define MTL_WITH_INITLIST 1\n#include <boost/numeric/mtl/mtl.hpp>\n\n#undef NOW\n#ifdef NOW\ntemplate<size_t nbits, size_t es>\nsw::unum::posit<nbits, es> Sigmoid_(sw::unum::posit<nbits, es>& x, bool derivative = false) {\n\tif (derivative) return x*(1-x);\n\treturn (1);\n}\n\n\ntemplate<typename Scalar>\nScalar sigmoid(Scalar x) {\n\treturn (1.0f / (1.0f + exp(-x)));\n}\n\ntemplate<typename Vector, typename Scalar>\nScalar f_theta(Scalar x, Scalar b, const Vector& V, const Vector& W) {\n\tdouble result = b;\n\tfor (int i = 0; i < N; ++i) {\n\t\tresult += V[i] * sigmoid(c[i] + W[i] * x);\n\t}\n\treturn result;\n}\n\ntemplate<typename Vector, typename Scalar>\nvoid train(Scalar x, Scalar y, Vector& W, Vector& V, Vector& c) {\n\tfor (int i = 0; i < size(W); ++i) {\n\t\tW[i] = W[i] - epsilon * 2 * (f_theta(x) - y) * V[i] * x *\n\t\t\t(1 - sigmoid(c[i] + W[i] * x)) * sigmoid(c[i] + W[i] * x);\n\t}\n\tfor (int i = 0; i < size(V); ++i) {\n\t\tV[i] = V[i] - epsilon * 2 * (f_theta(x) - y) * sigmoid(c[i] + W[i] * x);\n\t}\n\tb = b - epsilon * 2 * (f_theta(x) - y);\n\tfor (int i = 0; i < size(c); ++i) {\n\t\tc[i] = c[i] - epsilon * 2 * (f_theta(x) - y) * V[i] *\n\t\t\t(1 - sigmoid(c[i] + W[i] * x)) * sigmoid(c[i] + W[i] * x);\n\t}\n}\n\n// Multi-Level Perceptron\n// one input layer\n// one hidden layer with NrOfNeurons. \n// A \\(sigmoid\\\\) function as activation function\n// one output layer\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\n\tusing Scalar = float;\n\tusing Matrix = mtl::dense2D<Scalar>;\n\tusing Vector = mtl::dense_vector<Scalar>;\n\tusing Pair   = std::pair<Scalar, Scalar>;\n\tusing VoP    = mtl::dense_vector<Pair>;\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n\tMatrix X = {\n\t\t{0,0,1},\n\t\t{0,1,1},\n\t\t{1,0,1},\n\t\t{1,1,1}\n\t};\n#endif\n\n\tconstexpr int NrOfTrainingSamples = 20;\n\tconstexpr int NrOfNeurons = 5;\n\tconstexpr float epsilon = 0.05f;\n\tconstexpr int epoch = 50000;\n\n\tVector c(NrOfNeurons), W(NrOfNeurons), V(NrOfNeurons);\n\tc = W = V = 0;\n\tScalar b = 0;\n\n\t// fill initial state with random values\n\tsrand((unsigned int)time(NULL));\n\tfor (int i = 0; i < NrOfNeurons; i++) {\n\t\tW[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t\tV[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t\tc[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t}\n\tVoP trainingSet(NrOfTrainingSamples);\n\n\tfor (int i = 0; i < NrOfTrainingSamples; i++) {\n\t\ttrainingSet[i] = make_pair(i * 2 * m_pi / NrOfTrainingSamples, sin(i * m_2_pi / NrOfTrainingSamples));\n\t}\n\n\t// train for epoch number of cycles\n\tfor (int k = 0; k < epoch; ++k) {\n\t\tfor (int i = 0; i < NrOfTrainingSamples; i++) {\n\t\t\tauto x = trainingSet[i].first;\n\t\t\tauto y = trainingSet[i].second;\n\t\t\ttrain(x,y, W, V, c);\n\t\t}\n\t\tstd::cout << k << \"\\r\";\n\t}\n\n\t// Plot the results\n\tint nrVisualSamples = 1000;\n\tVector x(nrVisualSamples);\n\tVector y1(nrVisualSamples), y2(nrVisualSamples);\n\n\tauto scaling_factor = m_2pi / nrVisualSamples;\n\tfor (int i = 0; i < nrVisualSamples; i++) {\n\t\tx[i] =  i * scaling_factor;\n\t\ty1[i] = sin(i * scaling_factor);\n\t\ty2[i] = f_theta(Scalar(i * scaling_factor), b, V, W);\n\t}\n\n\tFILE * gp = _popen(\"gnuplot\", \"w\");\n\tfprintf(gp, \"set terminal wxt size 600,400 \\n\");\n\tfprintf(gp, \"set grid \\n\");\n\tfprintf(gp, \"set title '%s' \\n\", \"f(x) = sin (x)\");\n\tfprintf(gp, \"set style line 1 lt 3 pt 7 ps 0.1 lc rgb 'green' lw 1 \\n\");\n\tfprintf(gp, \"set style line 2 lt 3 pt 7 ps 0.1 lc rgb 'red' lw 1 \\n\");\n\tfprintf(gp, \"plot '-' w p ls 1, '-' w p ls 2 \\n\");\n\n\t// Exact f(x) = sin(x) -> Green Graph\n\tfor (int k = 0; k < nrVisualSamples; ++k) {\n\t\tfprintf(gp, \"%f %f \\n\", x[k], y1[k]);\n\t}\n\tfprintf(gp, \"e\\n\");\n\n\t//Neural Network Approximate f(x) = sin(x) -> Red Graph\n\tfor (int k = 0; k < nrVisualSamples; ++k) {\n\t\tfprintf(gp, \"%f %f \\n\", x[k], y2[k]);\n\t}\n\tfprintf(gp, \"e\\n\");\n\n\tfflush(gp);\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\n#else\nint main() {}\n#endif\n", "meta": {"hexsha": "9315fadf769e1a1ccc204fe543a4480b26acc00c", "size": 4949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/mlp/neural_network.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": "applications/mlp/neural_network.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": "applications/mlp/neural_network.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": 27.9604519774, "max_line_length": 106, "alphanum_fraction": 0.6280056577, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6970523655492106}}
{"text": "#pragma once\n#ifndef CALC_TVALUE_FP_HPP\n#define CALC_TVALUE_FP_HPP\n\n//#include <NTL/matrix.h>\n#include <NTL/lzz_p.h>\n#include <NTL/mat_lzz_p.h>\n#include \"combination.hpp\"\n\nint calc_tvalue(NTL::Mat<NTL::zz_p> array[], int dim, int max_tvalue)\n{\n    using namespace std;\n    using namespace NTL;\n\n    uint32_t s = dim;\n    uint32_t m = array[0].NumRows();\n    Combination index(s);\n    int t = 0;\n    for (; t <= max_tvalue; t++) {\n        index.reset(m - t);\n#if defined(DEBUG)\n        cout << \"t = \" << dec << t << endl;\n#endif\n        //vector<uint32_t> v;\n        bool pass = true;\n        for (;;) {\n            Mat<zz_p> v;\n            v.SetDims(m - t, m);\n#if defined(DEBUG)\n            index.print(cout);\n#endif\n            int vrow = 0;\n            for (uint32_t i = 0; i < s; ++i) {\n                for (int j = 0; j < index[i]; ++j) {\n                    v[vrow++] = array[i][j];\n                }\n            }\n            if (gauss(v) != m-t) {\n                pass = false;\n                break;\n            }\n            bool hasNext = index.next();\n            if (!hasNext) {\n                break;\n            }\n        }\n        if (pass) {\n            return t;\n        }\n    }\n    return -1;\n}\n\n#endif // CALC_TVALUE_FP_HPP\n", "meta": {"hexsha": "084a33b7a14216592f69b2c2b0c0f10b65c89862", "size": 1244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/calc_tvalue_fp.hpp", "max_stars_repo_name": "MSaito/ntl-test1", "max_stars_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_stars_repo_licenses": ["MIT"], "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/calc_tvalue_fp.hpp", "max_issues_repo_name": "MSaito/ntl-test1", "max_issues_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_issues_repo_licenses": ["MIT"], "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/calc_tvalue_fp.hpp", "max_forks_repo_name": "MSaito/ntl-test1", "max_forks_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_forks_repo_licenses": ["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.6181818182, "max_line_length": 69, "alphanum_fraction": 0.4557877814, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6968161087780733}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <armadillo>\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n#include \"Sampling_functions.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace arma;\nusing namespace boost;\n\n//boost::random::mt19937 gen(0);\nboost::random::mt19937 gen(time(0));\n//distributions\ndouble runif(double lower, double higher)\n{\n\tboost::random::uniform_real_distribution<> dist(lower, higher);\n\treturn dist(gen);\n}\n\ndouble rnorm(double mean, double sd)\n{\n\tboost::random::normal_distribution<> dist(mean, sd);\n\treturn dist(gen);\n}\n\ndouble rgamma(double alpha, double beta)\n{\n\n\tboost::math::gamma_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rbeta(double alpha, double beta)\n{\n\n\tboost::math::beta_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rinvchisq(double df, double scale)\n{\n\n\tboost::math::inverse_chi_squared_distribution<> dist(df, scale);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\nint rbernoulli(double p)\n{\n\tstd::bernoulli_distribution dist(p);\n\treturn dist(gen);\n}\n\n//switch between armadillo and eigen\nEigen::MatrixXd cast_eigen(arma::mat arma_A)\n{\n\tEigen::MatrixXd eigen_B = Eigen::Map<Eigen::MatrixXd>(arma_A.memptr(),\n\t\t\tarma_A.n_rows,\n\t\t\tarma_A.n_cols);\n\n\treturn eigen_B;\n}\n\narma::mat cast_arma(Eigen::MatrixXd& eigen_A)\n{\n\tarma::mat arma_B = arma::mat(eigen_A.data(), eigen_A.rows(), eigen_A.cols(),false, false);\n\treturn arma_B;\n}\n\n\n//sampling functions\ndouble sample_hyper(const MatrixXd& w1_M1_sample, const MatrixXd& WI_m, double b0_m, const VectorXd& mu0_m, int df_m,VectorXd& mu_m,MatrixXd& lambda_m)\n{\n\t//Sample from individual or SNP hyperparams (equation 14)\n\tint N = w1_M1_sample.rows();\n\tint num_feat=w1_M1_sample.cols();\n\tVectorXd u_bar(num_feat);\n\tMatrixXd S_bar(num_feat,num_feat);\n\n\tu_bar = w1_M1_sample.colwise().mean().transpose();\n\t//covariance to correlation\n\tS_bar = (w1_M1_sample.transpose()*w1_M1_sample)/N;\n\n\t//Gaussian-Wishard sampling\n\t//1.sample lambda from wishard distribution (lambda_m or lambda_u)\n\t//2.sample mu (mu_m or mu_u) from multivariate normal distribution with mean mu_0 (mu_temp) and variance (lambda*Lambda)^-1\n\n\t//Wishard-covariance matrix\n\tMatrixXd WI_post(num_feat,num_feat);\n\tWI_post = WI_m.inverse() + N*S_bar+((N*b0_m)/(b0_m+N))*((mu0_m - u_bar)*(mu0_m - u_bar).transpose());\n\n\t//WI_post = (WI_post + WI_post.transpose())/2;\n\n\tWI_post=WI_post.inverse();\n\n\t//Wishard-degrees of freedom\n\tint df_mpost = df_m+N;\n\n\t//Wishard draw, using the armadillo function. So I cast to an armadillo matrix, draw wishart then cast back to eigen matrix.\n\t//should just code the wishart function.\n\tmat arma_lambda =cast_arma(WI_post);\n\tmat W = wishrnd(arma_lambda, df_mpost);\n\tlambda_m=cast_eigen(W);\n\n\t//multivariate normal mean\n\tVectorXd mu_temp(num_feat);\n\tmu_temp = (b0_m*mu0_m + N*u_bar)/(b0_m+N);\n\n\t//Multivariate normal with mean mu_temp and cholesky decomposed covariance lam\n\tMatrixXd lam = (((b0_m+N)*lambda_m).inverse());\n\n\tlam=lam.llt().matrixU();\n\tlam.transposeInPlace();\n\n\tMatrixXd normV(num_feat,1);\n\tfor (int i=0;i<num_feat;i++){\n\t\tnormV(i,0)=rnorm(0,1);\n\t}\n\n\tmu_m = lam*normV+mu_temp;\n\n\treturn 0;\n}\n\ndouble sample_ind (double Xglobalmean,const MatrixXd& w1_M1_sample, MatrixXd& w1_P1_sample, const MatrixXd& X,int num_p,int num_feat,const MatrixXd& lambda_u,const VectorXd& mu_u,const VectorXd& alpha)\n{\n\t//random shuffling of individuals.\n\tstd::vector<int> I;\n\tfor (int i=0; i<num_p; ++i) {\n\t\tI.push_back(i);\n\t}\n\n\tstd::random_shuffle(I.begin(), I.end());\n\n\t// Gibbs updates over individual latent vectors given hyperparams.\n\t// Infer posterior distribution over individual latent vectors (equation 11).\n\tMatrixXd covarprod = w1_P1_sample.transpose()*w1_P1_sample;\n\tMatrixXd lambda_mu_prod=lambda_u*mu_u;\n\n\tfor (int i=0;i<num_p;i++){\n\t\t//observed data row\n\t\tVectorXd rr = X.row(I[i]).array();\n\t\t//equation 12\n\t\tMatrixXd covar = alpha[i]*covarprod+lambda_u;\n\t\tcovar=covar.inverse();\n\t\t//equation 13\n\t\tVectorXd mean_u = covar * (alpha[i]*(w1_M1_sample.transpose()*rr)+lambda_mu_prod);\n\t\t//multivariate normal with mean mean_u and cholesky decomposed variance lam\n\t\tMatrixXd lam = covar.llt().matrixU();\n\t\tlam.transposeInPlace();\n\n\t\tMatrixXd normV(num_feat,1);\n\t\tfor (int j=0;j<num_feat;j++){\n\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t}\n\n\t\tw1_P1_sample.row(I[i]) = (lam*normV+mean_u).transpose();\n\n\t}\n\n\treturn 0;\n}\n\ndouble sample_SNP (double Xglobalmean,const MatrixXd& w1_P1_sample, MatrixXd& w1_M1_sample, const MatrixXd& X,int num_m,int num_feat,const MatrixXd& lambda_m,const VectorXd& mu_m,double alpha)\n{\n\t//random shuffling of markers.\n\tstd::vector<int> I;\n\tfor (int i=0; i<num_m; ++i) {\n\t\tI.push_back(i);\n\t}\n\n\tstd::random_shuffle(I.begin(), I.end());\n\t//equation 12\n\tMatrixXd covar = ((alpha*(w1_P1_sample.transpose()*w1_P1_sample)+lambda_m));\n\tcovar=covar.inverse();\n\tMatrixXd lam = covar.llt().matrixU();\n\tlam.transposeInPlace();\n\tMatrixXd lambda_mu_prod=lambda_m*mu_m;\n\n\tfor (int i=0;i<num_m;i++){\n\t\t//observed data column\n\t\tVectorXd rr = X.col(I[i]).array();\n\n\t\t//equation 13\n\t\tVectorXd mean_m = covar * (alpha*(w1_P1_sample.transpose()*rr)+lambda_mu_prod);\n\t\t//multivariate normal with mean mean_m and cholesky decomposed variance lam\n\t\tMatrixXd normV(num_feat,1);\n\t\tfor (int j=0;j<num_feat;j++){\n\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t}\n\t\tw1_M1_sample.row(I[i]) = (lam*normV+mean_m).transpose();\n\t}\n\n\treturn 0;\n}\n\ndouble sample_ind_missing (double Xglobalmean,const MatrixXd& w1_M1_sample, MatrixXd& w1_P1_sample,const MatrixXd& Indicator, const MatrixXd& X,int num_p,int num_m,int num_feat,const MatrixXd& lambda_u,const VectorXd& mu_u,const VectorXd& alpha)\n{\n\t//random shuffling of individuals.\n\tstd::vector<int> I;\n\tfor (int i=0; i<num_p; ++i) {\n\t\tI.push_back(i);\n\t}\n\n\tstd::random_shuffle(I.begin(), I.end());\n\n\t// Gibbs updates over individual latent vectors given hyperparams.\n\t// Infer posterior distribution over individual latent vectors (equation 11).\n\n\n\tfor (int i=0;i<num_p;i++){\n\t\t//observed data row\n\t\tVectorXd rr = X.row(I[i]).array();\n\t\t//equation 12\n\t\tMatrixXd covarprod(num_feat,num_feat);\n\t\tVectorXd obsprod(num_feat);\n\t\tMatrixXd lambda_mu_prod=lambda_u*mu_u;\n\n\t\tcovarprod.setZero();\n\t\tobsprod.setZero();\n\t\tfor (int j=0;j<num_m;j++){\n\t\t\tcovarprod=covarprod + (w1_M1_sample.row(j).transpose()*w1_M1_sample.row(j))*Indicator(i,j);\n\t\t\tobsprod=obsprod + (w1_M1_sample.row(j).transpose()*rr[j])*Indicator(i,j);\n\t\t}\n\n\t\tMatrixXd covar = alpha[i]*covarprod+lambda_u;\n\t\tcovar=covar.inverse();\n\t\t//equation 13\n\t\tVectorXd mean_u = covar * (alpha[i]*obsprod+lambda_mu_prod);\n\t\t//multivariate normal with mean mean_u and cholesky decomposed variance lam\n\t\tMatrixXd lam = covar.llt().matrixU();\n\t\tlam.transposeInPlace();\n\n\t\tMatrixXd normV(num_feat,1);\n\t\tfor (int j=0;j<num_feat;j++){\n\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t}\n\n\t\tw1_P1_sample.row(I[i]) = (lam*normV+mean_u).transpose();\n\n\t}\n\n\treturn 0;\n}\n\ndouble sample_SNP_missing (double Xglobalmean,const MatrixXd& w1_P1_sample, MatrixXd& w1_M1_sample, const MatrixXd& Indicator,const MatrixXd& X,int num_p,int num_m,int num_feat,const MatrixXd& lambda_m,const VectorXd& mu_m,double alpha)\n{\n\t//random shuffling of markers.\n\tstd::vector<int> I;\n\tfor (int i=0; i<num_m; ++i) {\n\t\tI.push_back(i);\n\t}\n\n\tstd::random_shuffle(I.begin(), I.end());\n\n\n\tfor (int i=0;i<num_m;i++){\n\t\t//observed data column\n\t\tVectorXd rr = X.col(I[i]).array();\n\t\t//equation 12\n\t\tMatrixXd covarprod(num_feat,num_feat);\n\t\tVectorXd obsprod(num_feat);\n\t\tMatrixXd lambda_mu_prod=lambda_m*mu_m;\n\n\t\tcovarprod.setZero();\n\t\tobsprod.setZero();\n\t\tfor (int j=0;j<num_p;j++){\n\t\t\tcovarprod=covarprod + (w1_P1_sample.row(j).transpose()*w1_P1_sample.row(j))*Indicator(j,i);\n\t\t\tobsprod=obsprod + (w1_P1_sample.row(j).transpose()*rr[j])*Indicator(j,i);\n\t\t}\n\n\t\tMatrixXd covar = alpha*covarprod+lambda_m;\n\t\tcovar=covar.inverse();\n\n\t\t//equation 13\n\t\tVectorXd mean_m= covar * (alpha*obsprod+lambda_mu_prod);\n\t\t//multivariate normal with mean mean_m and cholesky decomposed variance lam\n\t\tMatrixXd lam = covar.llt().matrixU();\n\t\tlam.transposeInPlace();\n\n\t\tMatrixXd normV(num_feat,1);\n\t\tfor (int j=0;j<num_feat;j++){\n\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t}\n\t\tw1_M1_sample.row(I[i]) = (lam*normV+mean_m).transpose();\n\t}\n\n\treturn 0;\n}\n\ndouble sample_ind_SNP (MatrixXd& w1_M1_sample, MatrixXd& w1_P1_sample, const MatrixXd& X,int num_p,int num_m,int num_feat,const MatrixXd& lambda_u,const VectorXd& mu_u,const MatrixXd& lambda_m,const VectorXd& mu_m,double alpha)\n{\n\t//random shuffling of individuals.\n\tstd::vector<int> I;\n\tfor (int i=0; i<num_p; ++i) {\n\t\tI.push_back(i);\n\t}\n\tstd::vector<int> J;\n\tfor (int i=0; i<num_m; ++i) {\n\t\tJ.push_back(i);\n\t}\n\n\tstd::random_shuffle(I.begin(), I.end());\n\tstd::random_shuffle(J.begin(), J.end());\n\n\t// Gibbs updates over individual latent vectors given hyperparams.\n\t// Infer posterior distribution over individual latent vectors (equation 11).\n\tint upd_row=0;\n\tint upd_col=0;\n\tint i=0;\n\twhile (i<num_p+num_m){\n\n\t\tif(upd_row<num_p){\n\t\t\t//observed data row\n\t\t\tVectorXd rr = X.row(I[upd_row]);\n\t\t\t//equation 12\n\t\t\tMatrixXd covar = ((alpha*(w1_M1_sample.transpose()*w1_M1_sample)+lambda_u));\n\t\t\tcovar=covar.inverse();\n\t\t\t//equation 13\n\t\t\tVectorXd mean_u = covar * (alpha*w1_M1_sample.transpose()*rr+lambda_u*mu_u);\n\t\t\t//multivariate normal with mean mean_u and cholesky decomposed variance lam\n\t\t\tMatrixXd lam = covar.llt().matrixU();\n\t\t\tlam.transposeInPlace();\n\n\t\t\tMatrixXd normV(num_feat,1);\n\t\t\tfor (int j=0;j<num_feat;j++){\n\t\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t\t}\n\n\t\t\tw1_P1_sample.row(I[upd_row]) = (lam*normV+mean_u).transpose();\n\t\t\tupd_row=upd_row+1;\n\t\t\ti=i+1;\n\t\t}\n\n\t\tif(upd_col<num_m){\n\t\t\t//observed data column\n\t\t\tVectorXd rr = X.col(J[upd_col]);\n\t\t\t//equation 12\n\t\t\tMatrixXd covar = ((alpha*(w1_P1_sample.transpose()*w1_P1_sample)+lambda_m));\n\t\t\tcovar=covar.inverse();\n\t\t\t//equation 13\n\t\t\tVectorXd mean_m = covar * (alpha*w1_P1_sample.transpose()*rr+lambda_m*mu_m);\n\t\t\t//multivariate normal with mean mean_m and cholesky decomposed variance lam\n\t\t\tMatrixXd lam = covar.llt().matrixU();\n\t\t\tlam.transposeInPlace();\n\n\t\t\tMatrixXd normV(num_feat,1);\n\t\t\tfor (int j=0;j<num_feat;j++){\n\t\t\t\tnormV(j,0)=rnorm(0,1);\n\t\t\t}\n\t\t\tw1_M1_sample.row(J[upd_col]) = (lam*normV+mean_m).transpose();\n\t\t\tupd_col=upd_col+1;\n\t\t\ti=i+1;\n\t\t}\n\n\t}\n\n\treturn 0;\n}\n\n\ndouble sample_residual_variance_gamma(const MatrixXd& epsilon)\n{\n\tint N=epsilon.rows()*epsilon.cols();\n\tdouble res=epsilon.squaredNorm();\n\tdouble sigma2=1/rgamma((N-1)/2,1/(0.5*res));\n\t//cout<<\"residual info\"<<endl;\n\t//cout<<N<<\"\\t\"<<res<<\"\\t\"<<sigma2<<endl;\n\treturn sigma2;\n}\n\ndouble sample_residual_row_variance_gamma(const MatrixXd& epsilon, VectorXd& alpha)\n{\n\tint N=epsilon.rows();\n\tint M=epsilon.cols();\n\tdouble res=0;\n\tfor (int i=0;i<N;i++){\n\tres=epsilon.row(i).squaredNorm();\n\talpha[i]=1/rgamma((M-1)/2,1/(0.5*res));\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "71a8129a42e0a591a4db0f2ed537c01f74d8171a", "size": 10807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sampling_functions.cpp", "max_stars_repo_name": "kousathanas/BayesFactors", "max_stars_repo_head_hexsha": "197bbb7d7458a33391f84e08dec3cffe57470ece", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-05T03:25:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T03:25:22.000Z", "max_issues_repo_path": "Sampling_functions.cpp", "max_issues_repo_name": "kousathanas/BayesFactors", "max_issues_repo_head_hexsha": "197bbb7d7458a33391f84e08dec3cffe57470ece", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sampling_functions.cpp", "max_forks_repo_name": "kousathanas/BayesFactors", "max_forks_repo_head_hexsha": "197bbb7d7458a33391f84e08dec3cffe57470ece", "max_forks_repo_licenses": ["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.7102564103, "max_line_length": 245, "alphanum_fraction": 0.7084297215, "num_tokens": 3333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6967788695779992}}
{"text": "#include <iostream>\n#include <ctime>\n#include <Eigen/Core>  // Eigen \u90e8\u5206\n#include <Eigen/Dense> // \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\nusing namespace std;\n\n#define MATRIX_SIZE 50\n\n/********************************************\n * \u672c\u7a0b\u5e8f\u6f14\u793aEigen\u7684\u57fa\u672c\u7c7b\u578b\u7684\u4f7f\u7528\n * *****************************************/\n\nint main(int argc, char** argv)\n{\n    Eigen::Matrix<float,2,3> matrix_23;\n    Eigen::Vector3d v_3d;\n    Eigen::Matrix<float,3,1> vd_3d;\n\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n    Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> matrix_dynamic;\n    Eigen::MatrixXd matrix_x;\n\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    cout<< matrix_23<<endl;\n\n    for(int i=0; i<2; i++)\n    {\n        for(int j=0; j<3; j++)\n            cout<<matrix_23(i,j)<<\"\\t\";\n        cout<<endl;\n    }\n    \n    v_3d << 3, 2, 1;\n    vd_3d << 4, 5, 6;\n    Eigen::Matrix<double,2,1> result = matrix_23.cast<double>() * v_3d;\n    cout << result << endl;\n\n    // Eigen::Matrix<double,2,1> result2 = matrix_23 * vd_3d;\n    // cout << result2 << endl;\n\n    // \u56db\u5219\u8fd0\u7b97\u76f4\u63a5\u7528+-*/\n    // \u4e0b\u9762\u4e3a\u5176\u4ed6\u77e9\u9635\u8fd0\u7b97\n    matrix_33  = Eigen::Matrix3d::Random();\n    cout << matrix_33 << 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 << matrix_33.inverse() << endl;\n    cout << matrix_33.determinant() << endl;\n\n    // \u7279\u5f81\u503c\n    //\u5b9e\u5bf9\u79f0\u77e9\u9635\u53ef\u4ee5\u4fdd\u8bc1\u5bf9\u89d2\u5316\u6210\u529f\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver\n        (matrix_33.transpose()*matrix_33);\n    cout << \"Eigen values = \\n\"<< eigen_solver.eigenvalues()<<endl;\n    cout << \"Eigen vectors = \\n\"<< eigen_solver.eigenvectors()<<endl;\n\n    // \u89e3\u65b9\u7a0b\n    // \u6c42\u89e3matrix_NN * x = v_Nd\u8fd9\u4e2a\u65b9\u7a0b\n    // N \u7531\u524d\u9762\u7684\u5b8f\u5b9a\u4e49\n    // \u76f4\u63a5\u6c42\u89e3\u6700\u76f4\u63a5,\u4f46\u662f\u6c42\u9006\u8fd0\u7b97\u91cf\u5927\n    \n    Eigen::Matrix<double,MATRIX_SIZE,MATRIX_SIZE> matrix_NN;\n    matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE,MATRIX_SIZE);\n    Eigen::Matrix<double,MATRIX_SIZE,1> v_Nd;\n    v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE,1);\n\n    clock_t time_stt = clock(); // start\n    \n\n    // \u76f4\u63a5\u6c42\u9006\n    Eigen::Matrix<double,MATRIX_SIZE,1> x = matrix_NN.inverse()*v_Nd;\n    cout << \"time use in normal inverse is \" << 1000*(clock()-time_stt)/\n        (double)CLOCKS_PER_SEC << \"ms\" <<endl;\n\n    // \u901a\u5e38\u7528\u77e9\u9635\u5206\u89e3\u7684\u65b9\u5f0f\u6c42\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout << \"time use in Qr decomposition is \" << 1000*(clock()-time_stt)/\n        (double)CLOCKS_PER_SEC << \"ms\" <<endl;\n\n    return 0;\n\n}\n", "meta": {"hexsha": "158843b2650cc809f7e249f2c56a7002e786db3a", "size": 2435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_stars_repo_name": "Teeerry/learning-slam", "max_stars_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_issues_repo_name": "Teeerry/learning-slam", "max_issues_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useEigen/eigenMatrix.cpp", "max_forks_repo_name": "Teeerry/learning-slam", "max_forks_repo_head_hexsha": "064196e03c0fa52e3e7153aabd854922f79ccd8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9885057471, "max_line_length": 74, "alphanum_fraction": 0.5880903491, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6967749898840447}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    double           array[][3]= {{1., 0., 3.}, {4., 0., 6.}, {7., 0., 9.}, {0., 0., 0.}};\n    dense2D<double>  A(array), B2, B3;\n\n    // Creating a compression (reordering) matrix from a vector (or an array respectively)\n    int non_zero_rows[]= {0, 1, 2}, non_zero_columns[]= {0, 2};\n    // To be sure, we give the number of columns for a consistent size!\n    mat::traits::reorder<>::type RR= mat::reorder(non_zero_rows, 4), RC= mat::reorder(non_zero_columns);\n    std::cout << \"A =\\n\" << A << \"\\nRR =\\n\" << RR << \"\\nRC =\\n\" << RC;    \n\n    // Compress rows\n    B2= RR * A;\n    std::cout << \"\\nRR * A, i.e. compress row of A =\\n\" << B2;\n    \n    // Compress columns\n    B3= B2 * trans(RC);\n    std::cout << \"\\nB2 * trans(RC), i.e. compress columns of B2 =\\n\" << B3;\n    \n    // Decompress rows\n    dense2D<double>  C1(trans(RR) * B3);\n    std::cout << \"\\ntrans(RR) * B3, i.e. row decompression of B3 =\\n\" << C1;\n\n    // Decompress columns\n    dense2D<double>  C2(C1 * RC);\n    std::cout << \"\\nC1 * RC, i.e. column decompression of C1 (should be A) =\\n\" << C2;\n\n    return 0;\n}\n", "meta": {"hexsha": "087e5bfd741b961a039356558135ae0c3ce9e300", "size": 1187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/reorder3.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/examples/reorder3.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/examples/reorder3.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": 33.9142857143, "max_line_length": 104, "alphanum_fraction": 0.5543386689, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6967393578633362}}
{"text": "#include <iostream>\n#include <tuple>\n#include <Eigen/Dense>\n#include \"linear_algebra_addon.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_cocg_rq(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n// only for complex-symmetric matrix\n// Gu et al 2016, arXiv, Block variants of COCG and COCR methods\n// for solving complex symmetric linear systems with multiple right-hand sides\n\n  double Bnorm= B.norm();\n  MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n\n  MatrixXcd Q;\n  MatrixXcd xi;\n  tie(Q,xi)= qr_reduced(B-A*X);\n  MatrixXcd S= Q;\n\n  for(int k= 0; k < itermax; ++k){\n      MatrixXcd AS= A*S;\n      MatrixXcd alpha= (S.transpose()*AS).fullPivLu().solve(Q.transpose()*Q);\n      X= X+S*alpha*xi;\n      MatrixXcd Qnew;\n      MatrixXcd tau;\n      tie(Qnew,tau)= qr_reduced(Q-AS*alpha);\n      xi= tau*xi;\n      double err= xi.norm()/Bnorm;\n      cout << \"bl_cocg_rq: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n      if(err < tol) break;\n      MatrixXcd beta= (Q.transpose()*Q).fullPivLu().solve(tau.transpose()*Qnew.transpose()*Qnew);\n      Q= Qnew;\n      S= Q+S*beta;\n  }\n\n  if((A*X-B).norm()/Bnorm > 10*tol){\n      cerr << \"bl_cocg_rq did not converge to solution within error tolerance !\" << endl;\n     // exit(EXIT_FAILURE);\n  }\n\n  return X;\n}\n", "meta": {"hexsha": "d1c86ed450a125d97a66f17039902d203033d0c2", "size": 1338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_cocg_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_cocg_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_cocg_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.7333333333, "max_line_length": 99, "alphanum_fraction": 0.6382660688, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6966301992577538}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\nusing namespace mtl;\n\ntypedef dense2D<double> Matrix;\n// using Matrix= dense2D<double>; // C++11\n\ndense_vector<double> unit_vector(unsigned k, unsigned n)\n{\n    dense_vector<double>  e_k(n, 0.0);\n    e_k[k]= 1.0;\n\n    // for (unsigned i= 0; i < n; ++i)\n    // \t   e_k[k]= static_cast<double>(i == k);\n    // for (unsigned i= 0; i < n; ++i)\n    // \t   e_k[k]= i == k; \n\n    return e_k;\n}\n\n\nMatrix inverse_upper(const Matrix& U)\n{\n    const unsigned n= num_rows(U);\n    Matrix Inv(n, n);\n    Inv= 0.0;\n    for (unsigned k= 0; k < n; k++) { \n\tirange  r(0,k+1);\n\tInv[r][k]= upper_trisolve(U[r][r], unit_vector(k, k+1));\n    }\n    return Inv;\n}\n\nMatrix inverse_lower(const Matrix& L)\n{\n    Matrix T(trans(L));\n    return Matrix(trans(inverse_upper(T)));\n}\n\n\nMatrix inverse(const Matrix& A)\n{\n    const unsigned n= num_rows(A);\n    if (num_cols(A) != n)\n\tthrow \"Matrix must be square\";\n\n    Matrix Inv(n, n);\n\n    Matrix LU(A); // Kopie von A\n    dense_vector<unsigned>  Pv(n);\n    lu(LU, Pv);\n    compressed2D<unsigned> P(permutation(Pv));\n    Matrix I(mat::identity(n, n)), L(I + strict_lower(LU)), U(upper(LU));\n    Inv= inverse_upper(U) * inverse_lower(L) * P;\n\n    return Inv;\n}\n\n\nint main (int argc, char* argv[]) \n{\n    const unsigned size= 3;\n    const double   eps= 0.001; // C++11: constexpr double   eps= 0.001; \n    Matrix   A(size, size);\n    A= 4, 1, 2,\n       1, 5, 3,\n       2, 6, 9;\n\n    cout << \"A ist\\n\" << A;\n\n    Matrix LU(A); // Kopie von A\n    dense_vector<unsigned>  Pv(size);\n    lu(LU, Pv);\n    Matrix P(permutation(Pv));\n\n    cout << \"LU ist\\n\" << LU;\n    cout << \"Permutation vector is \" << Pv << \"\\nPermutationsmatrix ist\\n\" << P;\n\n    Matrix I(mat::identity(size, size)), L(I + strict_lower(LU)), U(upper(LU));\n    cout << \"L ist\\n\" << L << \"U ist\\n\" << U;\n\n    Matrix UI(inverse_upper(U));\n    cout << \"Inverse von U ist\\n\" << UI << \"UI * U ist\\n\" << Matrix(UI * U);\n    assert(one_norm(Matrix(UI * U - I)) < eps);\n\n    Matrix LI(inverse_lower(L));\n    cout << \"Inverse von L ist\\n\" << LI << \"LI * L ist\\n\" << Matrix(LI * L);\n    assert(one_norm(Matrix(LI * L - I)) < eps);\n\n\n    Matrix AI(UI * LI * P);\n    cout << \"Inverse von A ist\\n\" << AI << \"AI * A ist\\n\" << Matrix(AI * A);\n    assert(one_norm(Matrix(AI * A - I)) < eps);\n    \n    Matrix A_inverse(inverse(A));\n    cout << \"Inverse von A ist\\n\" << A_inverse << \"A_inverse * A ist\\n\" << Matrix(A_inverse * A);\n    assert(one_norm(Matrix(A_inverse * A - I)) < eps);\n\n    return 0 ;\n}\n", "meta": {"hexsha": "baa969a34426b88000832c7a22e7585421cd03f5", "size": 2562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_stars_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_stars_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-09-15T12:23:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:31:26.000Z", "max_issues_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_issues_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_issues_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-07T06:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T07:55:32.000Z", "max_forks_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_forks_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_forks_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-29T02:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T08:52:22.000Z", "avg_line_length": 24.6346153846, "max_line_length": 97, "alphanum_fraction": 0.5671350507, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6966301803473822}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// math::logit_shift.hpp                                                     //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. 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_STATISTICS_DETAIL_MATH_FUNCTION_LOGIT_SHIFT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_MATH_FUNCTION_LOGIT_SHIFT_HPP_ER_2009\n#include <boost/statistics/detail/math/function/log_shift.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace math{\n\n    // The t>0 is an adjustment which preventsa numerical error at p = 0 and \n    // p = 1 causes numerical error\n    template<typename T>\n    T logit_shift(const T& p,const T& t){\n        // log(p/(1-p)) = log(p)-log(1-p)\n        return log_shift(p,t) - boost::math::log1p(t - p);\n    }\n\n}// math\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "aa0c93e1a5a7e4ebc9d2d7649da588b478aa2409", "size": 1179, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/math/boost/statistics/detail/math/function/logit_shift.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/math/boost/statistics/detail/math/function/logit_shift.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/math/boost/statistics/detail/math/function/logit_shift.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": 39.3, "max_line_length": 79, "alphanum_fraction": 0.5131467345, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037363973294, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6965920465950041}}
{"text": "#include \"triangulation.h\"\n\n#include \"defines.h\"\n\n#include <Eigen/SVD>\n\n// \u0418\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u043c DLT \u043c\u0435\u0442\u043e\u0434, \u0441\u043e\u0441\u0442\u0430\u0432\u043b\u044f\u0435\u043c \u0441\u0438\u0441\u0442\u0435\u043c\u0443 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439. \u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043f\u043e\u0445\u043e\u0436\u0430 \u043d\u0430 \u0441\u0438\u0441\u0442\u0435\u043c\u0443 \u0434\u043b\u044f \u0433\u043e\u043c\u043e\u0433\u0440\u0430\u0444\u0438\u0438, \u0442\u0430\u043c \u043f\u0430\u0440\u044b \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439 \u043f\u043e\u043b\u0443\u0447\u0430\u043b\u0438\u0441\u044c \u0438\u0437 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0439 \u0432\u0438\u0434\u0430 x (cross) Hx = 0, \u0430 \u0437\u0434\u0435\u0441\u044c \u0431\u0443\u0434\u0435\u0442 x (cross) PX = 0\n// (\u0441\u043c. Hartley & Zisserman p.312)\ncv::Vec4d phg::triangulatePoint(const cv::Matx34d *Ps, const cv::Vec3d *ms, int count)\n{\n    using mat = Eigen::MatrixXd;\n    using vec = Eigen::VectorXd;\n\n    mat A(2 * count, 4);\n\n    for (int i = 0; i < count; ++i) {\n\n        const matrix34d &P = Ps[i];\n        const vector3d &m = ms[i];\n\n        double x = m[0];\n        double y = m[1];\n        double z = m[2];\n\n        auto p0 = P.row(0);\n        auto p1 = P.row(1);\n        auto p2 = P.row(2);\n\n        auto row0 = x * p2 - z * p0;\n        auto row1 = y * p2 - z * p1;\n\n        A.row(i * 2 + 0) << row0(0), row0(1), row0(2), row0(3);\n        A.row(i * 2 + 1) << row1(0), row1(1), row1(2), row1(3);\n    }\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::VectorXd null_space = svd.matrixV().col(3);\n\n    vector4d result;\n    for (int i = 0; i < 4; ++i) {\n        result(i) = null_space(i);\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "7492480e0002dafff07da7d71b1e1fdaa22e9c53", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/triangulation.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/triangulation.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/triangulation.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6956521739, "max_line_length": 193, "alphanum_fraction": 0.5602605863, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6965920410336649}}
{"text": "//=============================================================================\n// Daniel J. Greenhoe\n// normed linear space R^2\n//=============================================================================\n//=====================================\n// headers\n//=====================================\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <vector>\n#include <complex>\n#include <Eigen/Dense>\n#include \"r1.h\"\n#include \"r2.h\"\n#include \"r2op.h\"\n\n//-----------------------------------------------------------------------------\n//! List value of opair\n//! \\param[in]  str1 : string to print before the sequence\n//! \\param[in]  str2 : string to print after the sequence\n//! \\param[out] ptr  : output string\n//-----------------------------------------------------------------------------\nvoid opair::list(const char *str1, const char *str2, FILE *ptr) const\n{\n  if( strlen(str1)>0 ) fprintf(ptr,\"%s\",str1);\n  fprintf(ptr,\"(%9.6lf,%9.6lf)\",getx(),gety());\n  if( strlen(str2)>0 ) fprintf(ptr,\"%s\",str2);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief polar rotation coordinate <theta> of opair point (x,y)\n//! \\returns Return value is in the half open interval [0:2pi), \n//!          -1 on error\n//-----------------------------------------------------------------------------\ndouble vectR2::theta(void) const\n{\n  const double x = getx();\n  const double y = gety();\n  if(x==0){\n    if(     y == 0 ) return -1           ;\n    else if(y > 0  ) return  1 * M_PI / 2;\n    else             return  3 * M_PI / 2;\n  }\n  if(y==0){\n    if(     x>0    ) return 0;\n    else             return M_PI;\n  }\n  if( x>0 && y>0 ) return        atan( y/x); // 1st quadrant\n  if( x>0 && y<0 ) return 2*M_PI-atan(-y/x); // 4th quadrant\n  if( x<0 && y>0 ) return   M_PI-atan(-y/x); // 2nd quadrant\n  if( x<0 && y<0 ) return   M_PI+atan( y/x); // 3rd quadrant\n  else             return -1;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator to rotate vector R2 [x,y] counter-clockwise by <phi> radians\n//! \\param[in]  phi: angle to rotate vector by\n//-----------------------------------------------------------------------------\nvoid vectR2::operator&=(const double phi)\n{\n  vectR2  p(getx(),gety());\n  p = p & phi;\n  put(p.getx(),p.gety());\n}\n\n//=====================================\n// seqR2\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR1 to 0s\n//! \\param[in]  M: Length of sequence\n//-----------------------------------------------------------------------------\nseqR2::seqR2(const long M)\n{\n  N  = M;\n  xy = new vectR2[N];\n  clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief constructor initializing seqR1 to u\n//! \\param[in]  M: Length of sequence\n//! \\param[in]  u: Initialization value\n//-----------------------------------------------------------------------------\nseqR2::seqR2(long M, double u)\n{\n  long n;\n  N=M;\n  xy = new vectR2[N];\n  for(n=0; n<N; n++)\n  {\n    xy[n].put(u,u);\n  }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the sequence with a value 0\n//-----------------------------------------------------------------------------\nvoid seqR2::clear(void)\n{\n  for( long n=0; n<N; n++ ) xy[n].clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the sequence with a value <u>\n//-----------------------------------------------------------------------------\nvoid seqR2::fill(double u)\n{\n  long n;\n  for(n=0; n<N; n++) xy[n].put(u,u);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the sequence with (x_0, x_1, x_2, ...)\n//!        where x_n = x_{n-1} + (dx,dy)\n//-----------------------------------------------------------------------------\nvoid seqR2::inc(double x0, double y0,double dx, double dy)\n{\n  for( long n=0; n<N; n++ )\n  {\n    xy[n].put(x0,y0);\n    x0 += dx;\n    y0 += dy;\n  }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Put an order pair (u,v) into the sequence x at location n\n//-----------------------------------------------------------------------------\nint seqR2::put(long n, double u, double v)\n{\n  int retval=0;\n  if(n>=N){\n    fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n    retval=-1;\n    }\n  else xy[n].put(u,v);\n  return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Put an R2 vector xyz into the sequence x at location n\n//-----------------------------------------------------------------------------\nint seqR2::put(long n, vectR2 xya)\n{\n  int retval=0;\n  if(n>=N){\n    fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n    retval=-1;\n    }\n  else xy[n]=xya;\n  return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! Get a single value from the sequence x at location n\n//-----------------------------------------------------------------------------\nvectR2 seqR2::get(const long n) const\n{\n  vectR2 xya(0,0);\n  if(n<N)xya=xy[n];\n  else   fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n  return xya;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Get a single value from the sequence x element x at location n\n//-----------------------------------------------------------------------------\ndouble seqR2::getx(const long n) const\n{\n  double u=0;\n  if(n<N)u=xy[n].getx();\n  else   fprintf(stderr,\"n=%ld larger than x seqR1 size N=%ld\\n\",n,N);\n  return u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Get a single value from the sequence x element y at location n\n//-----------------------------------------------------------------------------\ndouble seqR2::gety(const long n) const\n{\n  double u=0;\n  if(n<N)u=xy[n].gety();\n  else   fprintf(stderr,\"n=%ld larger than y seqR1 size N=%ld\\n\",n,N);\n  return u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief List contents of sequence\n//-----------------------------------------------------------------------------\nvoid seqR2::list(const long start, const long end, const char *str1, const char *str2, FILE *ptr) const\n{\n  long n,m;\n  vectR2 x;\n  if(strlen(str1)>0)fprintf(ptr,\"%s\",str1);\n  for(n=start,m=1; n<=end; n++,m++){\n    x=get(n);\n    fprintf(ptr,\"  \");\n    x.list(ptr);\n    if(m%3==0)fprintf(ptr,\"\\n\");\n    }\n  if(strlen(str2)>0)fprintf(ptr,\"%s\",str2);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief List contents of seqC1 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR2::list1(void) const\n{\n  long n,m;\n  for(n=0,m=1; n<N; n++,m++){\n    printf(\"(%2.0lf,%2.0lf)   \",getx(n),gety(n));\n    if(m%5==0)printf(\"\\n\");\n    }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief List contents of seqC1 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR2::list1(long start, long end) const\n{\n  long n,m;\n  for(n=start,m=1; n<=end; n++,m++){\n    printf(\"(%2.0lf,%2.0lf)   \",getx(n),gety(n));\n    if(m%50==0)printf(\"\\n\");\n    else if(m%10==0)printf(\" \");\n    }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the largest pair of values in the sequence as measured by norm()\n//-----------------------------------------------------------------------------\ndouble seqR2::norm(const long n) const\n{\n  vectR2 xya=get(n);\n  return xya.norm();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the largest pair of values in the sequence as measured by norm()\n//-----------------------------------------------------------------------------\nvectR2 seqR2::max(const int verbose) const\n{\n  long n;\n  double maxnorm=0;\n  long   maxn=0;\n  vectR2  maxpair;\n  for(n=0; n<N; n++)if(norm(n)>maxnorm){maxnorm=norm(n); maxn=n;}\n  maxpair=get(maxn);\n  if(verbose)\n  {\n    for(n=0; n<N; n++)\n    {\n      if(norm(n)>=(maxnorm*0.999))\n        printf(\"max=(%lf,%lf) at n=%ld\\n\",maxpair.getx(),maxpair.gety(),n);\n    }\n  }\n  return maxpair;\n}\n\n//=====================================\n// external operations\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return p+q\n//-----------------------------------------------------------------------------\nvectR2 operator+(const vectR2 p, const vectR2 q)\n{\n  const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n  const Eigen::Map< const Eigen::Vector2d > b( q.getdata() );\n  const Eigen::Vector2d c = a + b;\n  const vectR2 r( c(0), c(1) );\n  return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return p-q\n//-----------------------------------------------------------------------------\nvectR2 operator-(const vectR2 p, const vectR2 q)\n{\n  const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n  const Eigen::Map< const Eigen::Vector2d > b( q.getdata() );\n  const Eigen::Vector2d c = a - b;\n  const vectR2 r( c(0), c(1) );\n  return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return -p\n//-----------------------------------------------------------------------------\nvectR2 operator-(const vectR2 p)\n{\n  const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n  const Eigen::Vector2d b = -a;\n  const vectR2 c( b(0), b(1) );\n  return c;\n}\n\n//-----------------------------------------------------------------------------\n//!  \\brief operator: return <p> rotated counter-clockwise by <phi> radians\n//!  \\details\n//!    https://stackoverflow.com/questions/17036818/\n//!    https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html\n//!    https://stackoverflow.com/questions/28722899/\n//-----------------------------------------------------------------------------\nvectR2 operator&(const vectR2 p, const double phi)\n{\n  double cosphi, sinphi;\n  if(phi==0){ cosphi = 1;        sinphi = 0;        }\n  else      { cosphi = cos(phi); sinphi = sin(phi); }\n  const std::vector<double> rr = { cosphi, -sinphi, \n                                   sinphi,  cosphi  };\n  const Eigen::Matrix<double, 2, 2, Eigen::RowMajor> R(rr.data()); \n//printf(\"     _                    _\\n\");\n//printf(\"R = | %9.6lf %9.6lf  |\\n\", R(0,0), R(0,1) );\n//printf(\"    |_%9.6lf %9.6lf _|\\n\", R(1,0), R(1,1) );\n//const Eigen::Map< const Eigen::Vector2d > x( p.pairxy.data() );\n  const Eigen::Map< const Eigen::Vector2d > x( p.getdata() );\n  const Eigen::Vector2d y = R * x;\n  const vectR2 q( y(0), y(1) );\n  return q;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the angle theta in radians between the two vectors induced by\n//!        the points <p> and <q> in the plane R^2\n//! \\returns On SUCCESS return theta in the closed interval [0:M_PI];\n//!          On ERROR   exit with value EXIT_FAILURE\n//-----------------------------------------------------------------------------\ndouble pqtheta(const vectR2 p, const vectR2 q)\n{\n  const double rp=p.mag(), rq=q.mag();\n  double y;\n  if(rp==0) return -1;\n  if(rq==0) return -2;\n  y = (p^q)/(rp*rq);\n  if( y > +1.0 )\n  {\n    if(y-1 < 1e-13 ) y = 1.0;\n    else{\n      fprintf(stderr,\"\\nERROR using pqtheta(vectR2 p, vectR2 q): (p^q)/(rp*rq)=%.12lf>+1\\n\",y);\n      exit(EXIT_FAILURE);\n      }\n  }\n  if(y<(-1.0))\n  {\n    if(y+1> -1e-13 ) y = -1.0;\n    else{\n      fprintf(stderr,\"\\nERROR using pqtheta(vectR2 p, vectR2 q): (p^q)/(rp*rq)=%.12lf<-1\\n\",y);\n      exit(EXIT_FAILURE);\n      }\n  }\n  const double theta = acos(y);\n  return theta;\n}\n\n", "meta": {"hexsha": "7d520f2b45b97c4b2996d5b0b33d21abe713a79f", "size": 12033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "r2.cpp", "max_stars_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_stars_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r2.cpp", "max_issues_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_issues_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r2.cpp", "max_forks_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_forks_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_forks_repo_licenses": ["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.5181058496, "max_line_length": 103, "alphanum_fraction": 0.3928363667, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6965621286735617}}
{"text": "#include <cmath>\n#include \"../matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\n#ifdef WITH_EIGEN\n  #include <Eigen/Dense>\n#endif\n\ntypedef std::vector<std::vector<double>> nested_vectors;\n\ntemplate <typename Matrix>\nvoid get_data(Matrix& x, Matrix& y, Matrix& z) {\n  // check the sizes\n  const unsigned ncols = x.cols(),\n                 nrows = x.rows();\n  assert(ncols == y.cols() && ncols == z.cols());\n  assert(nrows == y.rows() && nrows == z.rows());\n\n  // write data\n  const double a = -5,\n               b = 5;\n  const double col_incr = (b - a) / ncols,\n               row_incr = (b - a) / nrows;\n  for (unsigned i = 0; i < nrows; ++i) {\n    for (unsigned j = 0; j < ncols; ++j) {\n      x(i, j) = i;\n      y(i, j) = j;\n      z(i, j) = ::std::sin(::std::hypot(a + i * col_incr, a + j * row_incr));\n    }\n  }\n}\n\ntemplate <>\nvoid get_data(nested_vectors& x, nested_vectors& y, nested_vectors& z) {\n    for (double i = -5; i <= 5;  i += 0.25) {\n        std::vector<double> x_row, y_row, z_row;\n        for (double j = -5; j <= 5; j += 0.25) {\n            x_row.push_back(i);\n            y_row.push_back(j);\n            z_row.push_back(::std::sin(::std::hypot(i, j)));\n        }\n        x.push_back(x_row);\n        y.push_back(y_row);\n        z.push_back(z_row);\n    }\n}\n\n\nint main() {\n    std::vector<std::vector<double>> x, y, z;\n    get_data(x, y, z);\n    plt::plot_surface(x, y, z);\n    plt::show();\n\n    #ifdef WITH_EIGEN\n      const unsigned n = 100;  // resolution of hypot function\n      Eigen::MatrixXd X(n,n), Y(n,n), Z(n,n);\n      get_data(X, Y, Z);\n      plt::plot_surface(X, Y,   Z);\n      plt::show();\n    #endif\n}\n", "meta": {"hexsha": "d597708cc066f108f333915ed2a2f27b410bf4aa", "size": 1630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation_code/src/matplotlib-cpp/examples/surface.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/surface.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/surface.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": 25.873015873, "max_line_length": 77, "alphanum_fraction": 0.5319018405, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6965621260602517}}
{"text": "#include <Eigen/SVD> // Eigen is required\n\ntemplate<int R, int C>\nstatic inline void pseudoInverse(float A[], float B[])\n{\n\ttypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor | Eigen::AutoAlign, R, C> t_A;\n\n\tt_A mA(R, C);\n\n\tfor (int i = 0; i < R; i++)\n\t{\n\t\tfor (int j = 0; j < C; j++)\n\t\t{\n\t\t\tmA(i, j) = A[i + j * R];\n\t\t}\n\t}\n\n\tEigen::JacobiSVD<t_A, Eigen::ColPivHouseholderQRPreconditioner> svd(mA, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\tauto U = svd.matrixU();\n\tauto S = svd.singularValues();\n\tauto V = svd.matrixV();\n\n\tfloat Vt[C * C];\n\n\tfor (int i = 0; i < C; i++)\n\t{\n\t\tfloat s = S(i);\n\n\t\tif (s != 0.f)\n\t\t\ts = 1.f / s;\n\n\t\tfor (int j = 0; j < C; j++)\n\t\t{\n\t\t\tVt[j * C + i] = V(j, i) * s;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < C; i++)\n\t{\n\t\tfor (int j = 0; j < R; j++)\n\t\t{\n\t\t\tfloat v = 0.f;\n\n\t\t\tfor (int k = 0; k < C; k++)\n\t\t\t{\n\t\t\t\tv += Vt[i * C + k] * U(j, k);\n\t\t\t}\n\n\t\t\tB[i * R + j] = v;\n\t\t}\n\t}\n}\n\nvoid svd_routine_49_2(float A[], float B[])\n{\n\tpseudoInverse<49, 2>(A, B);\n}\n\nvoid svd_routine_121_8(float A[], float B[])\n{\n\tpseudoInverse<121, 8>(A, B);\n}\n", "meta": {"hexsha": "618a0db1a757a19ead6ab94446511b1d913e241c", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_stars_repo_name": "pps83/playrix", "max_stars_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_issues_repo_name": "pps83/playrix", "max_issues_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_forks_repo_name": "pps83/playrix", "max_forks_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.84375, "max_line_length": 116, "alphanum_fraction": 0.5222634508, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6964691348198766}}
{"text": "/**\n * @author      : adamlamson (adamlamson@LamsonMacbookPro)\n * @file        : two_step_prob\n * @created     : Wednesday Jan 29, 2020 14:05:35 MST\n */\n\n#ifndef TWO_STEP_PROB_HPP\n\n#define TWO_STEP_PROB_HPP\n#include <boost/math/tools/roots.hpp>\n#include <cassert>\n#include <cmath>\n\n// Solve the for the time that maximizes the probability of two events occuring\ntemplate <class T>\nclass MaxTimeOfTwoStepProbFunctor {\n  public:\n    // Constructor just stores values find root of function.\n    MaxTimeOfTwoStepProbFunctor(T const &rate1, T const &rate2,\n                                T const &total_time)\n        : k_ab(rate1), k_bc(rate2), tot_time(total_time) {}\n\n    T operator()(T const &t) {\n        T fx = k_ab * (exp(k_bc * (tot_time - t)) - 1.) -\n               k_bc * (exp(k_ab * t) - 1.);\n        return fx;\n    }\n\n  private:\n    T k_ab;\n    T k_bc;\n    T tot_time;\n};\n\ntemplate <class T>\nT max_time_of_two_step_prob(T const &rate1, T const &rate2,\n                            T const &total_time) {\n\n    T guess = .5 * total_time;\n    T factor = 2; // How big steps to take when searching.\n\n    const boost::uintmax_t maxit = 20; // Limit to maximum iterations.\n    boost::uintmax_t it =\n        maxit; // Initally our chosen max iterations, but updated with actual.\n    bool is_rising =\n        false; // So if guess is too low, then try increasing guess.\n    int digits = std::numeric_limits<T>::digits; // Maximum possible binary\n                                                 // digits accuracy for type T.\n    // Some fraction of digits is used to control how accurate o try to make the\n    // result.\n    int get_digits =\n        digits - 3; // We have to have a non-zero interval at each step, so\n                    // maximum accuracy is digits - 1.  But we also have to\n                    // allow for inaccuracy in f(x), otherwise the last few\n                    // iterations just thrash around.\n    boost::math::tools::eps_tolerance<T> rel_tol(\n        get_digits); // Set the tolerance.\n    std::pair<T, T> t = boost::math::tools::bracket_and_solve_root(\n        MaxTimeOfTwoStepProbFunctor<T>(rate1, rate2, total_time), guess, factor,\n        is_rising, rel_tol, it);\n    return t.first + (t.second - t.first) * .5;\n};\n\ntemplate <class T>\nT two_step_prob(T const &rate1, T const &rate2, T const &total_time,\n                T const &t) {\n    assert(total_time >= t);\n    T prob = (1. - exp(-1. * rate1 * t)) *\n             (1. - exp(-1. * rate2 * (total_time - t)));\n    return prob;\n};\n\ntemplate <class T>\nT two_step_max_prob(T const &rate1, T const &rate2, T const &total_time) {\n    T t_max = max_time_of_two_step_prob(rate1, rate2, total_time);\n    T prob = two_step_prob(rate1, rate2, total_time, t_max);\n    return prob;\n};\n\n#endif /* end of include guard TWO_STEP_PROB_HPP */\n\n", "meta": {"hexsha": "f3f5e7617a6bfebba4fc566bff08a058608a5c84", "size": 2814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KMC/two_step_prob.hpp", "max_stars_repo_name": "lamsoa729/KMC", "max_stars_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-15T22:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T22:06:52.000Z", "max_issues_repo_path": "KMC/two_step_prob.hpp", "max_issues_repo_name": "lamsoa729/KMC", "max_issues_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T17:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T15:59:17.000Z", "max_forks_repo_path": "KMC/two_step_prob.hpp", "max_forks_repo_name": "lamsoa729/KMC", "max_forks_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T20:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T20:17:58.000Z", "avg_line_length": 34.3170731707, "max_line_length": 80, "alphanum_fraction": 0.6112295665, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.696380397258486}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n\nusing Eigen::MatrixXd;\ntypedef Eigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> ArrayXXd;\ntypedef Eigen::Array<double,Eigen::Dynamic,1> ArrayXd;\nint main(int argc, char const *argv[]) {\n  Eigen::Matrix<double,2,2> Q;\n  Q(0,0) = 2.0;\n  Q(1,0) = 3.0;\n  Q(0,1) = 4.0;\n  Q(1,1) = 5.0;\n  ArrayXXd A_a = Q.array();\n  std::cout << A_a.inverse() << std::endl;\n  /* code */\n  return 0;\n}\n", "meta": {"hexsha": "ebe6e70eebae960758b694b5b1c1534222956ce3", "size": 454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/test_inverse.cpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "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/deprecated/test_inverse.cpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "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/deprecated/test_inverse.cpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["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.7, "max_line_length": 68, "alphanum_fraction": 0.6365638767, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789749258714, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6963484578625245}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/DistanceFuncs.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass MDS\n{\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n\n  void process(RealMatrixView in, RealMatrixView out, index distance, index k)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    auto     dist = static_cast<DistanceFuncs::Distance>(distance);\n    MatrixXd input = asEigen<Matrix>(in);\n    index    n = input.rows();\n    MatrixXd D = MatrixXd::Zero(n, n);\n    MatrixXd I = MatrixXd::Identity(n, n);\n    MatrixXd ones = MatrixXd::Ones(n, n);\n    for (index i = 0; i < n; i++)\n    {\n      for (index j = 0; j < n; j++)\n      { D(i, j) = DistanceFuncs::map()[dist](input.row(i), input.row(j)); }\n    }\n    MatrixXd J = I - ones / n;\n    D = -0.5 * J * D * J;\n    BDCSVD<MatrixXd> svd(D, ComputeThinV | ComputeThinU);\n    MatrixXd         U = svd.matrixU();\n    ArrayXd          s = svd.singularValues().segment(0, k);\n    MatrixXd         result =\n        U.block(0, 0, U.rows(), k).array().rowwise() * s.transpose();\n    out <<= asFluid(result);\n  }\n};\n}// namespace algorithm\n}// namespace fluid\n", "meta": {"hexsha": "60a6630c0d5789e4754e1037f15f2b71a728125f", "size": 1710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/MDS.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/MDS.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/MDS.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": 30.0, "max_line_length": 78, "alphanum_fraction": 0.6584795322, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897492587141, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6963484470783049}}
{"text": "#pragma once\n#include <iostream>\n#include <random>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#define EPSILON 1e-6f\n#define DELTA 1e-4f\n#define PI 3.14159265358979323846f\n#define PI_INV 0.31830988618f\n\n\nnamespace mathext {\n    std::default_random_engine random_generator;\n\n    std::vector<float> unif(float a, float b, int N = 1)\n    {\n        std::vector<float> res;\n        std::uniform_real_distribution<float> dis(a, b);\n\n        for (int i = 0; i < N; i++) {\n            res.push_back(dis(random_generator));\n        }\n        return res;\n    }\n\n    Eigen::Vector2f disk(float r)\n    {\n        std::vector<float> u = unif(0.0f, 1.0f, 2);\n\n        return Eigen::Vector2f(r * sqrt(u[0]), 2 * PI * u[1]);\n    }\n\n    Eigen::Matrix3f rot_from_two_vectors(Eigen::Vector3f src, Eigen::Vector3f des)\n    {\n        return Eigen::Quaternionf::FromTwoVectors(src, des).toRotationMatrix();\n    }\n\n    Eigen::Matrix3f rot_align_normal(Eigen::Vector3f n)\n    {\n        return rot_from_two_vectors(Eigen::Vector3f(0.0f, 0.0f, 1.0f), n);\n    }\n\n    Eigen::Vector3f reflect(Eigen::Vector3f v1, Eigen::Vector3f n)\n    {\n        return 2 * n.dot(v1) * n - v1;\n    }\n\n    Eigen::Vector3f refract(Eigen::Vector3f v1, Eigen::Vector3f n, float ior = 1.0f)\n    {\n        float cos_theta_i = v1.dot(n); \n        float eta = 1 / ior;\n        if (cos_theta_i < 0) {\n            eta = 1 / eta;\n            n *= -1;\n            cos_theta_i *= -1;\n        }\n        float c = sqrt(1 - eta * eta * (1 - cos_theta_i * cos_theta_i));\n        return c < 0 ? Eigen::Vector3f(0, 0, 0) : (eta * (-v1) + (eta * cos_theta_i - c) * n);\n    }\n\n    float power_heuristic(int n_f, float p_f, int n_g, float p_g, float beta = 2)\n    {\n        float c_f = (float)n_f * p_f, c_g = (float)n_g * p_g;\n        return pow(c_f, beta) / (pow(c_f, beta) + pow(c_g, beta));\n    }\n}\n", "meta": {"hexsha": "084ead4fa3bda6b5f4084ee3f87ec345a745513a", "size": 1857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "global_illumination/head/mathext.hpp", "max_stars_repo_name": "yuehaowang/learn_openGL", "max_stars_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-05T15:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T06:33:38.000Z", "max_issues_repo_path": "global_illumination/head/mathext.hpp", "max_issues_repo_name": "yuehaowang/lets_CG", "max_issues_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "global_illumination/head/mathext.hpp", "max_forks_repo_name": "yuehaowang/lets_CG", "max_forks_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 94, "alphanum_fraction": 0.577275175, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6962967975110155}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main(int argc, char **argv) \n{\n  // exploit namespaces to shorten code\n  using namespace boost::numeric::ublas;\n  using std::cout; \n  using std::endl;\n\n  // declare three 3x3 matrices of complex<long double> elements\n  matrix<std::complex<long double> > m(3, 3), n(3, 3), o(3, 3);\n\n  // iterate over 3x3 matrix entries\n  // r : row index\n  // c : column index\n  for (unsigned r = 0; r < m.size1(); r++) {\n    for (unsigned c = 0; c < m.size2(); c++) {\n      // enumerated matrix entries\n      m(r,c) = 3 * r + c;\n\n      // complex numbers designating rows and cols\n      n(r,c) = r + c * 1i;\n\n      // elementwise square of n\n      o(r,c) = std::pow(n(r,c), 2);\n    }\n  }\n\n  // print to screen as demonstration\n  cout << \"m:\" << endl;\n  cout << m << endl;\n  cout << endl << \"n:\" << endl;\n  cout << n << endl;\n  cout << endl << \"o:\" << endl;\n  cout << n << endl;\n  cout << endl << \"m + n:\" << endl;\n  cout << m + n << endl;\n  cout << endl << \"m * n:\" << endl;\n  cout << prod(m, n) << endl;\n  cout << endl << \"n * n - o:\" << endl;\n  cout << prod(n, n) - o << endl;\n}\n", "meta": {"hexsha": "78469c1bd5dc0f62a0dccb918258cb30cc8819fc", "size": 1150, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/boost_matrix.cc", "max_stars_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_stars_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_stars_repo_licenses": ["MIT"], "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/blas/boost_matrix.cc", "max_issues_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_issues_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_issues_repo_licenses": ["MIT"], "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/blas/boost_matrix.cc", "max_forks_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_forks_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_forks_repo_licenses": ["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.1363636364, "max_line_length": 64, "alphanum_fraction": 0.54, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6962967919633317}}
{"text": "//####### Test module for physical constants ##################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/constants\"\n\n#include <cmath>\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include \"phys_constants.h\"\n#include \"math_constants.h\"\n\nusing namespace picsar::multi_physics::phys;\nusing namespace picsar::multi_physics::math;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-14;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-7;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n// ------------- Tests --------------\n\n// ***Test physical constants\n\ntemplate<typename RealType>\nvoid test_case_const_phys()\n{\n    const auto exp_electron_mass =\n        static_cast<RealType>(9.1093837015e-31);\n    const auto exp_elementary_charge =\n        static_cast<RealType>(1.602176634e-19);\n    const auto exp_light_speed =\n        static_cast<RealType>(299792458.);\n    const auto exp_reduced_plank =\n        static_cast<RealType>(1.054571817e-34);\n    const auto exp_vacuum_permittivity =\n        static_cast<RealType>(8.8541878128e-12);\n    const auto exp_vacuum_permeability =\n        static_cast<RealType>(1.25663706212e-6);\n    const auto exp_fine_structure =\n        static_cast<RealType>(0.0072973525693);\n    const auto exp_eV =\n        static_cast<RealType>(1.602176634e-19);\n    const auto exp_KeV =\n        static_cast<RealType>(1.602176634e-16);\n    const auto exp_MeV =\n        static_cast<RealType>(1.602176634e-13);\n    const auto exp_GeV =\n        static_cast<RealType>(1.602176634e-10);\n    const auto exp_sqrt_4_pi_fine_structure =\n            static_cast<RealType>(sqrt(\n                4.0*pi<double>*fine_structure<double>));\n    const auto exp_classical_electron_radius =\n        static_cast<RealType>(2.81794032620493e-15);\n    const auto exp_schwinger_field =\n        static_cast<RealType>(1.32328547494817e18);\n    const auto exp_tau_e =\n        static_cast<RealType>(9.39963715232933e-24);\n\n    BOOST_CHECK_SMALL(\n        (electron_mass<RealType>-exp_electron_mass)/exp_electron_mass,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (elementary_charge<RealType>-exp_elementary_charge)/exp_elementary_charge,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (light_speed<RealType>-exp_light_speed)/exp_light_speed,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (reduced_plank<RealType>-exp_reduced_plank)/exp_reduced_plank,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (vacuum_permittivity<RealType>-exp_vacuum_permittivity)/exp_vacuum_permittivity,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (vacuum_permeability<RealType>-exp_vacuum_permeability)/exp_vacuum_permeability,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (fine_structure<RealType>-exp_fine_structure)/exp_fine_structure,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (eV<RealType>-exp_eV)/exp_eV,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (KeV<RealType>-exp_KeV)/exp_KeV,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (MeV<RealType>-exp_MeV)/exp_MeV,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (GeV<RealType>-exp_GeV)/exp_GeV,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n            (sqrt_4_pi_fine_structure<RealType>-exp_sqrt_4_pi_fine_structure)/\n            exp_sqrt_4_pi_fine_structure, tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (classical_electron_radius<RealType>-exp_classical_electron_radius)/exp_classical_electron_radius,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (schwinger_field<RealType>-exp_schwinger_field)/exp_schwinger_field,\n        tolerance<RealType>());\n\n    BOOST_CHECK_SMALL(\n        (tau_e<RealType>-exp_tau_e)/exp_tau_e,\n        tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( picsar_const_phys )\n{\n    test_case_const_phys<double>();\n    test_case_const_phys<float>();\n}\n\n// *******************************\n", "meta": {"hexsha": "efa238dc778af86ae4538e017e33c6831ae60b84", "size": 4292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_picsar_phys_constants.cpp", "max_stars_repo_name": "LDAmorim/picsar", "max_stars_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_picsar_phys_constants.cpp", "max_issues_repo_name": "LDAmorim/picsar", "max_issues_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_picsar_phys_constants.cpp", "max_forks_repo_name": "LDAmorim/picsar", "max_forks_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4397163121, "max_line_length": 106, "alphanum_fraction": 0.6943150047, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7981867681382279, "lm_q1q2_score": 0.6962961290393171}}
{"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"grad_shape.hpp\"\n#include \"integrate.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n\n//----------------H1Begin----------------\n//! Computes the H^1 differences between\n//! u1 (considered as coefficients for Quadratic FEM) and u2grad.\ndouble computeH1Difference(const Eigen::MatrixXd &vertices,\n                           const Eigen::MatrixXi &dofs,\n                           const Eigen::VectorXd &u1,\n                           const std::function<Eigen::Vector2d(double, double)> &u2grad) {\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\t\tEigen::Matrix2d elementMap          = coordinateTransform.inverse().transpose();\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\tEigen::Vector2d approximate_grad = Eigen::Vector2d(0, 0);\n\t\t\tfor (int j = 0; j < 6; ++j) {\n\t\t\t\tapproximate_grad += u1(idSet(j)) * elementMap * gradientShapefun(j, x, y);\n\t\t\t}\n\t\t\tEigen::Vector2d diff = u2grad(transformedPoint.x(), transformedPoint.y()) - approximate_grad;\n\n\t\t\treturn diff.dot(diff) * volumeFactor;\n\t\t};\n\n\t\terror += integrate(f);\n\t}\n\n\treturn std::sqrt(error);\n}\n//----------------H1End----------------\n", "meta": {"hexsha": "2711c1e3cb796a17581cb8f8aa2b9ff9c6658c42", "size": 1691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/H1_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/H1_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/H1_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": 34.5102040816, "max_line_length": 98, "alphanum_fraction": 0.6221170905, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6962681211491213}}
{"text": "// 2.62     Nov 10, 05  hyperparameter autosearch: observations weighted by inverse stddev\n// 3.02     Sep 01, 11  watch for denormal or infinite limits during autosearch\n// MAS      Jan 02, 15  changed first step direction if hyperparameter is very small\n\n#define  _USE_MATH_DEFINES\n#include <cmath>\n#include <stdexcept>\n#include <limits>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\n//#include \"tnt_array2d.h\"\n//#include \"tnt_array2d_utils.h\"\n//#include \"jama_lu.h\"\n//\n//#include \"logging.h\"\n\n#include \"HParSearch.h\"\n\n//observations weighted by inverse stddev\nQuadrCoefs QuadrLogFit( const map<double,UniModalSearch::MS> & y_by_x )\n{\n    unsigned n = y_by_x.size();\n\n    //prepare for case weights: inverse of stddev; beware of zero stddev\n    double minstddev=numeric_limits<double>::max();\n    for (map<double,UniModalSearch::MS>::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end(); itr++) {\n        if (0 < itr->second.s && itr->second.s < minstddev) {\n        \tminstddev = itr->second.s;\n        }\n    }\n    const double zeroadjust = minstddev<numeric_limits<double>::max() ? 100.0/minstddev //non-zeroes present\n        : 1.0; //all weights will be equal\n\n    Eigen::MatrixXd X( n, 3 ); //nRows, nCols\n    Eigen::MatrixXd XTW( 3, n ); //nRows, nCols\n    Eigen::VectorXd Y( n );\n    int i = 0;\n    for (map<double,UniModalSearch::MS>::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end();\n        itr++, i++) {\n        double weight = itr->second.s>0 ? 1/itr->second.s : zeroadjust;\n        X(i,0) = XTW(0,i) = 1.0;\n        X(i,1) = XTW(1,i) = log( itr->first );\n        X(i,2) = XTW(2,i) = log( itr->first ) * log( itr->first );\n        for (int j=0; j < 3; j++) { //for no weighting, just skip this\n            XTW(j,i) *= weight;\n        }\n        Y(i) = itr->second.m;\n    }\n\n    Eigen::MatrixXd XTX =  XTW * X;\n    Eigen::VectorXd XTY = XTW * Y;\n    Eigen::VectorXd b_hat = XTX.fullPivLu().solve(XTY);\n\n    // TODO Check numerical accuracy and throw error\n\n    QuadrCoefs ret;\n    ret.c0 = b_hat(0);\n    ret.c1 = b_hat(1);\n    ret.c2 = b_hat(2);\n    return ret;\n}\n\nStepValue UniModalSearch::step() //recommend: do/not next step, and the next x value\n{\n    StepValue ret(true,0,0);\n    switch( y_by_x.size() ) {\n    case 0: ret.second = 1; break;\n    case 1:\n        if (y_by_x.begin()->first < m_first_cut)\n            ret.second = y_by_x.begin()->first * m_stdstep;\n        else\n            ret.second = y_by_x.begin()->first / m_stdstep;\n            //we divide here because step with more penalty is safer numerically\n        break;\n    case 2:\n        if( y_by_x.begin()->second.m > y_by_x.rbegin()->second.m )\n            ret.second = y_by_x.begin()->first / m_stdstep;\n        else\n            ret.second = y_by_x.rbegin()->first * m_stdstep;\n        break;\n    default: // 3 or more\n\t\tif( y_by_x.begin()->first==best->first ) {  //max is at the left - move to the left\n            ret.second = best->first / m_stdstep;\n\t\t\tif( !(best->first > numeric_limits<double>::denorm_min()) ) { //inf or nan\n\t\t\t\tret.first = false;\n\t\t\t    ret.expected = best->second.m;\n\t\t\t}\n\t\t}else if( y_by_x.rbegin()->first==best->first ) { //max is at the right - move to the right\n            ret.second = best->first * m_stdstep;\n\t\t\tif( !(best->first < numeric_limits<double>::infinity()) ) { //inf or nan\n\t\t\t\tret.first = false;\n\t\t\t    ret.expected = best->second.m;\n\t\t\t}\n\t\t}else { //max is 'bracketed'\n            QuadrCoefs coefs = QuadrLogFit( y_by_x );\n            double log_argmax = - coefs.c1 / coefs.c2 / 2;\n            double expected_max = - coefs.c1*coefs.c1 / coefs.c2 / 4 + coefs.c0;\n\n\t\t\tdouble maxval = best->second.m;\n            if( 0==maxval )  ret.first=false;\n            else if( (expected_max-maxval)/fabs(maxval) < m_stop_by_y )  ret.first=false;\n            else if( fabs(log_argmax-log(best->first)) < m_stop_by_x )  ret.first=false;\n            //double deriv = 2*coefs.c2*best->first + coefs.c1;    cout<<\"\\nderiv  \"<<deriv;\n            //ret.first = fabs(deriv) > stop_by_y;\n\n            ret.second = exp( log_argmax );\n            ret.expected = expected_max;\n            //map<double,double>::const_iterator left = best; left--;\n            //map<double,double>::const_iterator right = best; right++;\n//            std::cout\n//            //Log(6)\n//            <<\"\\nSearch step \"<<ret.second<<\" stop_by_y \"<<((expected_max-maxval)/fabs(maxval))\n//                <<\" stop_by_x \"<<(fabs(log_argmax-log(best->first))) << endl;\n        }\n    }\n    return ret;\n}\n\n//void UniModalSearch::dump(std::ostream& stream) const {\n//    int i = 0;\n//    for (map<double,UniModalSearch::MS>::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end();\n//        itr++, i++) {\n//    \tstream << \"search[ \" << itr->first << \" ] = \" << itr->second << std::endl;\n//    }\n//}\n\n\nstd::ostream& operator<< (std::ostream& stream, const UniModalSearch& search) {\n//\tsearch.dump(stream);\n\n    for (map<double,UniModalSearch::MS>::const_iterator itr=search.y_by_x.begin(); itr!=search.y_by_x.end();\n        itr++) {\n    \tstream << \"search[ \" << itr->first << \" ] = \" << itr->second.m\n    \t\t\t<< \"(\" << itr->second.s << \")\" << std::endl;\n    }\n\n\treturn stream;\n}\n\n#ifdef UNITTEST_\n#include <iostream>\nvoid main() {\n    map<double,double> y_by_x;\n    //example llkl.d001145.b prepared in R\n    y_by_x[ 2.000000e+04 ] = -408.199;\n    y_by_x[ 2.002884e+03 ] = -328.581;\n    y_by_x[ 2.000000e+02 ] = -281.788;\n    y_by_x[ 2.002884e+01 ] = -229.966;\n    y_by_x[ 2.000000e+00 ] = -184.908;\n    y_by_x[ 2.002884e-01 ] = -150.792;\n    y_by_x[ 2.000000e-02 ] = -132.081;\n    y_by_x[ 2.002884e-03 ] = -127.708;\n    y_by_x[ 2.000000e-04 ] = -146.397;\n    y_by_x[ 2.002884e-05 ] = -183.208;\n    QuadrCoefs c = QuadrLogFit( y_by_x );\n    //R results:\n    // (Intercept)     logvar2      logvar\n    // -171.030466   -1.186039  -12.662184\n    cout<<\"c0=\"<<c.c0<<\"  c1=\"<<c.c1<<\"  c2=\"<<c.c2<<endl;\n\n    UniModalSearch s;\n    for( map<double,double>::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end(); itr++ )\n        s.tried( itr->first, itr->second );\n    //R result: 0.004805411\n    cout<<\"step=\"<<s.step().second<<endl;\n}\n#endif //UNITTEST_\n\n\n/*\n    Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, Rutgers University, New Brunswick, NJ, USA.\n\n    Permission is hereby granted, free of charge, to any person obtaining\n    a copy of this software and associated documentation files (the\n    \"Software\"), to deal in the Software without restriction, including\n    without limitation the rights to use, copy, modify, merge, publish,\n    distribute, sublicense, and/or sell copies of the Software, and to\n    permit persons to whom the Software is furnished to do so, subject to\n    the following conditions:\n\n    The above copyright notice and this permission notice shall be\n    included in all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n    ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n\n    Except as contained in this notice, the name(s) of the above\n    copyright holders, DIMACS, and the software authors shall not be used\n    in advertising or otherwise to promote the sale, use or other\n    dealings in this Software without prior written authorization.\n*/\n", "meta": {"hexsha": "cc921d19f4b971eca109520d7533bc1ec3517ca0", "size": 7615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/HParSearch.cpp", "max_stars_repo_name": "cran/Cyclops", "max_stars_repo_head_hexsha": "081ae5868cdc63cf1918a0c17828f101ff1de14f", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-01-16T07:41:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T09:15:37.000Z", "max_issues_repo_path": "src/utils/HParSearch.cpp", "max_issues_repo_name": "cran/Cyclops", "max_issues_repo_head_hexsha": "081ae5868cdc63cf1918a0c17828f101ff1de14f", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T18:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:21:10.000Z", "max_forks_repo_path": "src/utils/HParSearch.cpp", "max_forks_repo_name": "cran/Cyclops", "max_forks_repo_head_hexsha": "081ae5868cdc63cf1918a0c17828f101ff1de14f", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T18:17:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T20:22:33.000Z", "avg_line_length": 37.8855721393, "max_line_length": 108, "alphanum_fraction": 0.6182534471, "num_tokens": 2207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6962681049223244}}
{"text": "#include <vector> /* std::vector */\n#include <utility> /* std::pair */\n#include <algorithm> /* std::lower_bound, std::sort */\n\n#include \"XYParser.hpp\"\n\n#include <boost/range/combine.hpp> /* boost::combine */\ntemplate<typename U = double>\nclass Interpolator {\n    std::vector<std::pair<U, U>> _table;\n    const U INF = static_cast<U>(1e100);\n\n    U _lower_bound = -INF;\n    U _upper_bound = INF;\n\n    void init(const std::vector<U> &x, const std::vector<U> &y)\n    {\n        // taken from here: https://stackoverflow.com/a/8513803/2289030\n        for(auto tup : boost::combine(x, y)) {\n            U x, y;\n            boost::tie(x, y) = tup;\n\n            _table.push_back(std::make_pair(x, y));\n        }\n\n        std::sort(_table.begin(), _table.end());\n    }\n\n    void init(const std::vector<U> &x, const std::vector<U> &y, std::pair<U, U> bounds)\n    {\n        init(x, y);\n        set_bounds(bounds);\n    }\n    \n    void copy(const Interpolator &other)\n    {\n        _table = other._table;\n        _lower_bound = other._lower_bound;\n        _upper_bound = other._upper_bound;    \n    }\npublic:\n    U get(U x)\n    {\n        // taken from here: https://stackoverflow.com/a/11675205/2289030\n        // Assumes that \"table\" is sorted by .first\n\n        // Check if x is out of bound\n        if (x > _table.back().first) return _upper_bound;\n        if (x < _table[0].first) return _lower_bound;\n\n        typename std::vector<std::pair<U, U>>::iterator it, it2;\n        // INFINITY is defined in math.h in the glibc implementation\n        it = std::lower_bound(_table.begin(), _table.end(), std::make_pair(x, -INF));\n        // Corner case\n        if (it == _table.begin()) return it->second;\n        it2 = it;\n        --it2;\n        return it2->second + ((it->second - it2->second)\n                                *(x - it2->first)/(it->first - it2->first));\n    }\n\n    void set_bounds(const std::pair<U, U> &bounds)\n    {\n        _lower_bound = bounds.first;\n        _upper_bound = bounds.second;\n    }\n\n    U interpolate(U x)\n    {\n        return get(x);\n    }\n\n    Interpolator(const std::vector<U> &x, const std::vector<U> &y)\n    {\n        init(x, y);\n    }\n\n    Interpolator(const std::vector<U> &x, const std::vector<U> &y\n            , std::pair<U,U> bounds)\n    {\n        init(x, y, bounds);\n    }\n\n    Interpolator(const std::string &filename)\n    {\n        std::vector<U> x, y;\n        load_xy_data<U>(filename, x, y);\n        \n        init(x, y);\n    }\n\n    Interpolator() {};\n\n    Interpolator(const Interpolator &other)\n    {\n        copy(other);\n    }\n\n    Interpolator& operator=(const Interpolator &rhs)\n    {\n        copy(rhs);\n        return *this;\n    }\n\n};\n", "meta": {"hexsha": "1d7797af6e87e0c379a6bf880fa616dd221c783f", "size": 2676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Interpolator.cpp", "max_stars_repo_name": "ijustlovemath/chase-icing", "max_stars_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_stars_repo_licenses": ["MIT"], "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/Interpolator.cpp", "max_issues_repo_name": "ijustlovemath/chase-icing", "max_issues_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_issues_repo_licenses": ["MIT"], "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/Interpolator.cpp", "max_forks_repo_name": "ijustlovemath/chase-icing", "max_forks_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_forks_repo_licenses": ["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.2452830189, "max_line_length": 87, "alphanum_fraction": 0.5467115097, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.6962289752365988}}
{"text": "#include <iomanip>\n#include <memory>\n#include <vector>\n\n#include <Eigen/Core>\n#include <aslam/common/memory.h>\n#include <eigen-checks/gtest.h>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include \"maplab-common/global-coordinate-tools.h\"\n#include \"maplab-common/test/testing-entrypoint.h\"\n#include \"maplab-common/test/testing-predicates.h\"\n\nnamespace common {\n\nTEST(GlobalCoordinateToolsTest, testLlhToEcefAndBack) {\n  // Zurich coordinates in longitude, latitude, height.\n  const double latitude_degree = 47.3666700;\n  const double longitude_degree = 8.5500000;\n  // Height above WGS84 ellipsoid.\n  const double height_meter = 429.0;\n  const Eigen::Vector3d llh(latitude_degree, longitude_degree, height_meter);\n\n  // Conversion from LLH to ECEF coordinates.\n  Eigen::Vector3d ecef;\n\n  common::llhToEcef(llh, &ecef);\n\n  // Conversion from ECEF back to LLH coordinates using iterative method.\n  Eigen::Vector3d llh_back_transformed_iterative;\n  common::ecefToLlhIterative(ecef, &llh_back_transformed_iterative);\n  EXPECT_NEAR_EIGEN(llh, llh_back_transformed_iterative, 1.0e-5);\n\n  // Conversion from ECEF back to LLH coordinates using closed method.\n  Eigen::Vector3d llh_back_transformed_closed;\n  common::ecefToLlh(ecef, &llh_back_transformed_closed);\n  EXPECT_NEAR_EIGEN(llh, llh_back_transformed_closed, 1.0e-5);\n}\n\nTEST(GlobalCoordinateToolsTest, testEcefToNedAndBack) {\n  // Zurich coordinates in longitude, latitude, height.\n  const double latitude_degree = 47.3666700;\n  const double longitude_degree = 8.5500000;\n  // Height above WGS84 ellipsoid.\n  const double height_meter = 429.0;\n  const Eigen::Vector3d llh(latitude_degree, longitude_degree, height_meter);\n\n  // Conversion from LLH to ECEF coordinates.\n  Eigen::Vector3d ecef;\n  common::llhToEcef(llh, &ecef);\n\n  // Conversion from ECEF to NED coordinates.\n  const Eigen::Vector3d offset(10.0, 50.0, 20.0);\n  const Eigen::Vector3d origin_ecef(ecef + offset);\n  Eigen::Vector3d north_east_down;\n  common::ecefToNed(ecef, origin_ecef, &north_east_down);\n\n  // Conversion from NED back to ECEF coordinates.\n  Eigen::Vector3d ecef_back_transformed;\n  common::nedToEcef(north_east_down, origin_ecef, &ecef_back_transformed);\n\n  EXPECT_NEAR_EIGEN(ecef, ecef_back_transformed, 1.0e-12);\n}\n}  // namespace common\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "afd7bae9fdede6aa83b0be2439de6c3507abe04e", "size": 2307, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/maplab-common/test/test_global-coordinate-tools.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "common/maplab-common/test/test_global-coordinate-tools.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "common/maplab-common/test/test_global-coordinate-tools.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 33.9264705882, "max_line_length": 77, "alphanum_fraction": 0.774165583, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.696137423734877}}
{"text": "#include <iostream>\n#include <armadillo>\n#define PRINT 1\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  // User input\n  arma::mat input;\n  input << 1 << 3 << 2 << 4 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << endr\n        << 5 << 7 << 6 << 8 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << endr;\n  input = input.t();\n\n  size_t size = 4; // input channels\n  size_t upscale_factor = 2;\n  size_t height = 2;\n  size_t width = 2;\n\n  // Forward()\n  size_t batchSize = input.n_cols;\n  size_t size_out = size / std::pow(upscale_factor, 2); // output channels\n  size_t output_height = height * upscale_factor;\n  size_t output_width = width * upscale_factor;\n\n  arma::mat output;\n  output.zeros(output_height * output_width * size_out, batchSize );\n\n  for(size_t n = 0; n < batchSize; n++)\n  {\n    arma::mat inputImage = input.col(n);\n    arma::mat outputImage = output.col(n);\n    arma::cube inputTemp(const_cast<arma::mat&>(inputImage).memptr(), height, width, size, false, false);\n    arma::cube outputTemp(const_cast<arma::mat&>(outputImage).memptr(), output_height, output_width, size_out, false, false);\n\n    for (size_t c = 0; c < size_out ; c++)\n    {\n      for (size_t h = 0; h < output_height; h++)\n      {\n        for (size_t w = 0; w < output_width; w++)\n        {\n          size_t height_index = h / upscale_factor;\n          size_t width_index = w / upscale_factor;\n          size_t channel_index = (upscale_factor * (h % upscale_factor)) + (w % upscale_factor) + (c * std::pow(upscale_factor, 2));\n          outputTemp(w, h, c) = inputTemp(width_index, height_index, channel_index);\n        }\n      }\n    }\n\n    output.col(n) = outputImage;\n\n    if(PRINT)\n    {\n      cout << \"Image \" << n << \" calculations: \" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"INPUT for Pixel Shuffle: \" << endl;\n      cout << inputTemp << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"OUTPUT from Pixel Shuffle: \" << endl;\n      cout << outputTemp << endl;\n      cout << \"-----------------------------------\" << endl;\n    }\n\n  }\n\n  // this is gy for Pixel Shuffle layer simulated as a tensor filled with an arbitrary sequence of values.\n  arma::mat gy;\n  gy << 1 << 5 << 9 << 13 << 2 << 6 << 10 << 14 << 3 << 7 << 11 << 15 << 4 << 8 << 12 << 16 << endr\n    << 17 << 21 << 25 << 29 << 18 << 22 << 26 << 30 << 19 << 23 << 27 << 31 << 20 << 24 << 28 << 32 << endr;\n  gy = gy.t();\n\n  // Backward()\n  arma::mat g;\n  g.zeros(arma::size(input));\n\n  for(size_t n = 0; n < batchSize; n++)\n  {\n    arma::mat gyImage = gy.col(n);\n    arma::mat gImage = g.col(n);\n    arma::cube gyTemp(const_cast<arma::mat&>(gyImage).memptr(), output_height, output_width, size_out, false, false);\n    arma::cube gTemp(const_cast<arma::mat&>(gImage).memptr(), height, width, size, false, false);\n\n    for (size_t c = 0; c < size_out ; c++)\n    {\n      for (size_t h = 0; h < output_height; h++)\n      {\n        for (size_t w = 0; w < output_width; w++)\n        {\n          size_t height_index = h / upscale_factor;\n          size_t width_index = w / upscale_factor;\n          size_t channel_index = (upscale_factor * (h % upscale_factor)) + (w % upscale_factor) + (c * std::pow(upscale_factor, 2));\n          gTemp(width_index, height_index, channel_index) = gyTemp(w, h, c);\n        }\n      }\n    }\n\n    g.col(n) = gImage;\n\n    if (PRINT)\n    {\n      cout << \"Image \" << n << \" calculations: \" << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"Hypothetical gy for Pixel Shuffle: \" << endl;\n      cout << gyTemp << endl;\n      cout << \"-----------------------------------\" << endl;\n      cout << \"g for Pixel Shuffle: \" << endl;\n      cout << gTemp << endl;\n      cout << \"-----------------------------------\" << endl;\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "db301d12803dde7b47a7c566e326d7667395a9e3", "size": 3920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pixel_shuffle/test.cpp", "max_stars_repo_name": "iamshnoo/mlpack-testing", "max_stars_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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": "pixel_shuffle/test.cpp", "max_issues_repo_name": "iamshnoo/mlpack-testing", "max_issues_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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": "pixel_shuffle/test.cpp", "max_forks_repo_name": "iamshnoo/mlpack-testing", "max_forks_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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.7931034483, "max_line_length": 132, "alphanum_fraction": 0.5130102041, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.696137421194878}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <cmath>\n#include <string>\n#include <fstream>\n#include <bits/stdc++.h>\n\ntemplate <typename T>\nvoid print(T x)\n{\n    std::ofstream output;\n    output.open(\"output/output.txt\", std::ios_base::app); // std::ofstream::trunc);\n    std::cout << x << std::endl;\n    output.close();\n}\n\ndouble trapezRule(Eigen::VectorXd function(Eigen::VectorXd), double x_min, double x_max, double h)\n{\n    double result = 100;\n    double old_result = 0;\n    int iterator = 0;\n\n    do\n    {\n        h = h / 2;\n        iterator++;\n        Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x_max - x_min) / h + 1, x_min, x_max);\n        Eigen::VectorXd f = function(deltaX);\n        Eigen::VectorXd result_vec = f * h;\n        old_result = result;\n        result = 0.5 * (result_vec(0) + result_vec(result_vec.size() - 1)) + result_vec(Eigen::seq(1, result_vec.size() - 2)).sum();\n\n    } while ((abs(result - old_result) > 1e-6) & (iterator <= 30));\n    print(\"Iterationen:\");\n    print(iterator);\n    return result;\n}\n\nEigen::VectorXd f1a(Eigen::VectorXd x)\n{\n    return Eigen::exp(x.array()) / x.array();\n}\n\nEigen::VectorXd f1b(Eigen::VectorXd x)\n{\n    return Eigen::exp(-x.array()) / Eigen::sqrt(x.array());\n}\n\nEigen::VectorXd f1c(Eigen::VectorXd x)\n{\n    return Eigen::sin(x.array()) / x.array(); //sin(x) / x;\n}\n\ndouble f3a(double x)\n{\n    return (x * x) - 2;\n}\n\ndouble bisection(double function(double), double a, double b, double c)\n{\n    if ((a < b) & (b < c) & (function(b) < function(a)) & (function(b) < function(c)))\n    {\n        int iteration = 0;\n        do\n        {\n            iteration++;\n\n            if (abs(b - a) > abs(c - b))\n            {\n                double a_new = a;\n                double b_new = (a + b) / 2;\n                double c_new = b;\n                if (function(b_new) < function(c_new))\n                {\n                    a = a_new;\n                    b = b_new;\n                    c = c_new;\n                }\n                else\n                {\n                    a = b_new;\n                    b = c_new;\n                    c = c;\n                }\n            }\n            else\n            {\n                double a_new = b;\n                double b_new = (b + c) / 2;\n                double c_new = c;\n                if (function(b_new) < function(a_new))\n                {\n                    a = a_new;\n                    b = b_new;\n                    c = c_new;\n                }\n                else\n                {\n                    a = a;\n                    b = a_new;\n                    c = b_new;\n                }\n            }\n        } while ((abs(a - c) > 1e-9) & (iteration < 100));\n        print(\"Iterationen: \");\n        print(iteration);\n        print(\"a - c = \");\n        print(abs(a - c));\n    }\n    else\n    {\n        print(\"First requirement of bisection is not fullfiled.\");\n    }\n    return a;\n}\n\ndouble fDot(double function(double), double x0)\n{\n    double deltaX = (x0 + 1) / 1000;\n    // Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x(x.size()-1) -x(0) ) / diff_x + 1, x(0), x(x.size()-1));\n    return (function(x0 + deltaX) - function(x0 - deltaX)) / (2 * deltaX);\n}\n\ndouble fDDot(double function(double), double x0)\n{\n    double deltaX = (x0 + 1) / 1000;\n    // Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x(x.size()-1) -x(0) ) / diff_x + 1, x(0), x(x.size()-1));\n    return (function(x0 + deltaX) - 2 * function(x0) + function(x0 - deltaX)) / (deltaX * deltaX);\n}\n\ndouble newton(double function(double), double x0)\n{\n    double x_new = x0;\n    double x_old = 0;\n    double iteration = 0;\n    do\n    {\n        iteration++;\n        x_old = x_new;\n        x_new = x_old - fDot(function, x_old) / fDDot(function, x_old);\n    } while ((abs(x_new - x_old) > 1e-9) & (iteration < 100));\n    print(\"Iterationen: \");\n    print(iteration);\n    print(\"x_new - x_old = \");\n    print(abs(x_new - x_old));\n    return x_new;\n}\n\nint main()\n{\n    for (int m = 3; m < 5; m++)\n    {\n        int j = pow(2, m);\n        int N = 10;\n        int l = N;\n        std::complex<double> complex_(0.0, 1.0);\n        Eigen::VectorXcd F_j(j);\n        Eigen::VectorXcd f_l(l);\n        Eigen::MatrixXcd omega(j, l);\n\n        for (int i = 0; i < l; i++)\n        {\n            f_l(i) = std::sqrt(1 + i);\n        }\n\n        for (int i = 0; i < l; i++)\n        {\n            for (int k = 0; k < j; k++)\n            {\n                omega(k, i) = std::exp(k * i / N * 2 * M_PI * complex_);\n            }\n        }\n\n        F_j = omega * f_l;\n        Eigen::VectorXd F_j_real = F_j.real();\n        print(F_j_real);\n    }\n\n    // // Ex. 1\n    // // a)\n\n    // print(\"Exercise a): \");\n    // double zero = 1e-6;\n    // print(\"Zero is:\");\n    // print(zero);\n    // double i1 = trapezRule(f1a, -1, -zero, 0.5) + trapezRule(f1a, zero, 1, 0.5);\n    // print(\"Result I1: \");\n    // print(i1);\n\n    // // b) see WolframAlpha for x_max\n    // print(\"Exercise b): \");\n    // double infty = 100.;\n    // print(\"Infinity is:\");\n    // print(infty);\n    // double epsilon = 0.001;\n    // print(\"Epsilon is:\");\n    // print(epsilon);\n    // zero = 1e-11;\n    // print(\"Zero is:\");\n    // print(zero);\n    // double i2 = trapezRule(f1b, zero, epsilon, 0.0005) + trapezRule(f1b, epsilon, infty, 0.5);\n    // print(\"Result I2: \");\n    // print(i2);\n\n    // // c)\n    // print(\"Exercise c): \");\n    // infty = 1000000.;\n    // print(\"Infinity is:\");\n    // print(infty);\n    // zero = 1e-6;\n    // print(\"Zero is:\");\n    // print(zero);\n    // double i3 = trapezRule(f1c, -infty, -zero, 0.5) + trapezRule(f1c, zero, infty, 0.5);\n    // print(\"Result I3: \");\n    // print(i3);\n\n    // // Ex. 3\n    // // a)\n    // double a = -0.5;\n    // double b = -0.1;\n    // double c = 2.0;\n    // double result_bisec = bisection(f3a, a, b, c);\n\n    // // b)\n    // double x0 = 1;\n    // double result_newton = newton(f3a, x0);\n    // print(\"Bisec - Newton:\");\n    // print(abs(result_bisec - result_newton));\n\n    return 0;\n}", "meta": {"hexsha": "ef98a1ab5d995b5dbaa6ca00fbcb648b8f11b9c3", "size": 6000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt5/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": "Blatt5/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": "Blatt5/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": 25.974025974, "max_line_length": 132, "alphanum_fraction": 0.4735, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6960191539764263}}
{"text": "/*\n  Solves the one-particle Schrodinger equation\n  for a potential specified in function\n  potential(). This example is for the harmonic oscillator in 3d\n*/\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <armadillo>\n\nusing namespace  std;\nusing namespace  arma;\n\ndouble potential(double);\nvoid output(double, double, int, vec& );\n\n\n// Begin of main program   \n\nint main(int argc, char* argv[])\n{\n  int       i, j, Dim, lOrbital;\n  double    RMin, RMax, Step, DiagConst, NondiagConst, OrbitalFactor; \n  // With spherical coordinates RMin = 0 always\n  RMin = 0.0;\n\n  RMax = 8.0;  lOrbital = 0;  Dim =2000;  \n  mat Hamiltonian = zeros<mat>(Dim,Dim);\n  // Integration step length\n  Step    = RMax/ Dim;\n  DiagConst = 2.0 / (Step*Step);\n  NondiagConst =  -1.0 / (Step*Step);\n  OrbitalFactor = lOrbital * (lOrbital + 1.0);\n  \n  // local memory for r and the potential w[r] \n  vec r(Dim); vec w(Dim);\n  for(i = 0; i < Dim; i++) {\n    r(i) = RMin + (i+1) * Step;\n    w(i) = potential(r(i)) + OrbitalFactor/(r(i) * r(i));\n  }\n\n\n  // Setting up tridiagonal matrix and brute diagonalization using Armadillo\n  Hamiltonian(0,0) = DiagConst + w(0);\n  Hamiltonian(0,1) = NondiagConst;\n  for(i = 1; i < Dim-1; i++) {\n    Hamiltonian(i,i-1)    = NondiagConst;\n    Hamiltonian(i,i)    = DiagConst + w(i);\n    Hamiltonian(i,i+1)    = NondiagConst;\n  }\n  Hamiltonian(Dim-1,Dim-2) = NondiagConst;\n  Hamiltonian(Dim-1,Dim-1) = DiagConst + w(Dim-1);\n  // diagonalize and obtain eigenvalues\n  \n\n\n\n\n  vec Eigval(Dim);\n  eig_sym(Eigval, Hamiltonian);\n  output(RMin , RMax, Dim, Eigval);\n\n  return 0;\n}  //  end of main function\n\n\n/*\n  The function potential()\n  calculates and return the value of the \n  potential for a given argument x.\n  The potential here is for the hydrogen atom\n*/        \n\ndouble potential(double x)\n{\n  return x*x;\n\n} // End: function potential()  \n\n\nvoid output(double RMin , double RMax, int Dim, vec& d)\n{\n  int i;\n  cout << \"RESULTS:\" << endl;\n  cout << setiosflags(ios::showpoint | ios::uppercase);\n  cout <<\"Rmin = \" << setw(15) << setprecision(8) << RMin << endl;  \n  cout <<\"Rmax = \" << setw(15) << setprecision(8) << RMax << endl;  \n  cout <<\"Number of steps = \" << setw(15) << Dim << endl;  \n  cout << \"Five lowest eigenvalues:\" << endl;\n  for(i = 0; i < 5; i++) {\n    cout << setw(15) << setprecision(8) << d[i] << endl;\n  }\n}  // end of function output         \n\n//   vec q1 = randu<vec>(100);\n", "meta": {"hexsha": "70278b9ce22a2a37eb0c23d5e5b6f73c5e52a523", "size": 2442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.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": 25.175257732, "max_line_length": 76, "alphanum_fraction": 0.6216216216, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6959726147109772}}
{"text": "/*\n\n\u3000\n\u3000\n\u3000\n*/\n\n#include <boost/math/special_functions/next.hpp>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include \"Functions.hpp\"\n\nint main()\n{\n\t/* 2.5.1 */\n\t// a) Test the classify function with following values:\n\tdouble val = std::numeric_limits<double>::max();\n\tstd::cout << \"For val = numeric_limits<double>::max(): \" << std::endl;\n\tstd::cout << \"val classification: \" << Classify(val) << std::endl;\n\tstd::cout << \"2.0 * val classification: \" << Classify(2.0 * val) << std::endl;\n\tstd::cout << \"3.1415 + val classification: \" << Classify(3.1415 + val) << std::endl;\n\tdouble val2 = std::numeric_limits<double>::min() - 3.1415;\n\tstd::cout << \"For val2 = numeric_limits<double>::min(): \" << std::endl;\n\tstd::cout << \"val2 classification: \" << Classify(val2) << std::endl;\n\tstd::cout << \"val2 / 2.0 classification: \" << Classify(val2 / 2.0) << std::endl;\n\tstd::cout << \"DBL_MIN / 2.0 classification: \" << Classify(DBL_MIN / 2.0) << std::endl;\n\t// b) Test std::isfinite, std::isinf, std::isnan, std::isnormal on values:\n\tdouble factor = 2.0; \n\tval = factor*std::numeric_limits<double>::max();\n\tstd::cout << \"For val = 2.0 * numeric_limits<double>::max()\" << std::endl;\n\n\tstd::cout << \"val classifications: \" << std::endl;\n\tstd::cout << \"\\t isfinite(val): \" << std::isfinite(val) << std::endl;\n\tstd::cout << \"\\t isfinite(val): \" << std::isinf(val) << std::endl;\n\tstd::cout << \"\\t isfinite(val): \" << std::isnan(val) << std::endl;\n\tstd::cout << \"\\t isfinite(val): \" << std::isnormal(val) << std::endl;\n\n\tstd::cout << \"val - val classification: \" << std::endl;\n\tstd::cout << \"\\t isfinite(val - val): \" << std::isfinite(val - val) << std::endl;\n\tstd::cout << \"\\t isfinite(val - val): \" << std::isinf(val - val) << std::endl;\n\tstd::cout << \"\\t isfinite(val - val): \" << std::isnan(val - val) << std::endl;\n\tstd::cout << \"\\t isfinite(val - val): \" << std::isnormal(val - val) << std::endl;\n\n\tstd::cout << \"sqrt(-1.0) classification: \" << std::endl;\n\tstd::cout << \"\\t isfinite(sqrt(-1.0)): \" << std::isfinite(std::sqrt(-1.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(sqrt(-1.0)): \" << std::isinf(std::sqrt(-1.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(sqrt(-1.0)): \" << std::isnan(std::sqrt(-1.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(sqrt(-1.0)): \" << std::isnormal(std::sqrt(-1.0)) << std::endl;\n\n\tstd::cout << \"log(0.0) classification: \" << std::endl;\n\tstd::cout << \"\\t isfinite(log(0.0)): \" << std::isfinite(std::log(0.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(log(0.0)): \" << std::isinf(std::log(0.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(log(0.0)): \" << std::isnan(std::log(0.0)) << std::endl;\n\tstd::cout << \"\\t isfinite(log(0.0)): \" << std::isnormal(std::log(0.0)) << std::endl;\n\n\tstd::cout << \"exp(val) classification: \" << std::endl;\n\tstd::cout << \"\\t isfinite(exp(val)): \" << std::isfinite(std::exp(val)) << std::endl;\n\tstd::cout << \"\\t isfinite(exp(val)): \" << std::isinf(std::exp(val)) << std::endl;\n\tstd::cout << \"\\t isfinite(exp(val)): \" << std::isnan(std::exp(val)) << std::endl;\n\tstd::cout << \"\\t isfinite(exp(val)): \" << std::isnormal(std::exp(val)) << std::endl;\n\n\t/* 2.5.2 */\n\t// b) Compare FindEpsilon outputs to std::numeric_limits<>::epsilon() outputs:\n\tdouble epsilon1 = FindEpsilon<double>();\n\tstd::cout << \"FindEpsilon<double>() == numeric_limits<double>::epsilon(): \" << ((epsilon1 == std::numeric_limits<double>::epsilon())? \"True\": \"False\") << std::endl;\n\tint epsilon2 = FindEpsilon<int>();\n\tstd::cout << \"FindEpsilon<int>() == numeric_limits<int>::epsilon(): \" << ((epsilon2 == std::numeric_limits<int>::epsilon()) ? \"True\" : \"False\") << std::endl;\n\tfloat epsilon3 = FindEpsilon<float>();\n\tstd::cout << \"FindEpsilon<float>() == numeric_limits<float>::epsilon(): \" << ((epsilon3 == std::numeric_limits<float>::epsilon()) ? \"True\" : \"False\") << std::endl;\n\n\t/* 2.5.3 */\n\t// Experiment with the Boost C++ math toolkit:\n\t// Test float_distance:\n\tdouble a = 0.1; double b =\n\t\ta + std::numeric_limits<double>::min();\n\tstd::cout << \"Distance between 0.1 and 0.1 + numeric_limits<double>::min(): \" << boost::math::float_distance(a, b) << std::endl;\n\ta = 1.0; b = 0.0;\n\tstd::cout << \"Distance between 1.0 and 0.0: \" << boost::math::float_distance(a, b) << std::endl;\n\t// Test float_next:\n\tunsigned long long steps = 0;\n\ttry\n\t{\n\t\t// Will throw exception in float_next if std::numeric_limits<double>::max() minus any number is used as an input, thus need to use literal:\n\t\tb = 1.797693134862315805e+308 - std::numeric_limits<double>::min();\n\t\twhile(true)\n\t\t{\n\t\t\tb = boost::math::float_next(b);\n\t\t\tsteps++;\n\t\t}\n\t}\n\tcatch (std::overflow_error& err)\n\t{\n\t\tstd::cout << \"Overflow exception caught:\" << std::endl;\n\t\tstd::cout << err.what() << std::endl;\n\t\tstd::cout << \"Steps between numeric_limits<double>::max() - 10 and numeric_limits<double>::max(): \" << steps << std::endl;\n\t}\n\t// Test float_prior:\n\tsteps = 0;\n\ttry\n\t{\n\t\tb = std::numeric_limits<double>::min() + 1.0;\n\t\twhile (true)\n\t\t{\n\t\t\tb = boost::math::float_prior(b);\n\t\t\tsteps++;\n\t\t}\n\t}\n\tcatch (std::underflow_error& err)\n\t{\n\t\tstd::cout << \"Underflow exception caught: \" << std::endl;\n\t\tstd::cout << err.what() << std::endl;\n\t\tstd::cout << \"Steps between ... \" << steps << std::endl;\n\t}\n\t// Test boost::nextafter():\n\tstd::cout << \"nextafter(): \" << std::nextafter(a, b) << std::endl;\n\tsystem(\"pause\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "ffea4200c8f08147f742497b0522a99ce5670966", "size": 5309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Advanced C++ Course/Benjamin Rutan HW 2 Submission/2.5+2.6/Main.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": "Advanced C++ Course/Benjamin Rutan HW 2 Submission/2.5+2.6/Main.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": "Advanced C++ Course/Benjamin Rutan HW 2 Submission/2.5+2.6/Main.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": 43.8760330579, "max_line_length": 165, "alphanum_fraction": 0.5997362969, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.6959472030866035}}
{"text": "#ifndef UTIL_H\n#define UTIL_H\n#include <cmath>\n#include <cassert>\n#include <boost/operators.hpp>\n\ntemplate<class T> class Maybe {\n    T value;\n    bool has_value;\npublic:\n    Maybe() : value(), has_value(false) {}\n    Maybe(T val) : value(val), has_value(true) {}\n\n    operator bool() {\n        return has_value;\n    }\n\n    T val() {\n        assert(has_value);\n        return value;\n    }\n};\n\nvoid log(const char* s) {\n    printf(\"%s\\n\", s);\n    fflush(stdout);\n}\n\ninline double sq(double val) {\n    return val*val;\n}\n\nconst double EPS = 1e-6;\n\ninline bool almost_zero(double val) {\n    return fabs(val) < EPS;\n}\n\nstruct Vector : boost::additive<Vector>, boost::multiplicative2<Vector, double>, boost::equality_comparable<Vector> {\n    double coord[3];\n    Vector() : coord{0, 0, 0} {}\n    Vector(double x, double y, double z) : coord{x, y, z} {}\n\n    double length() const {\n        return sqrt(sq(coord[0]) + sq(coord[1]) + sq(coord[2]));\n    }\n\n    bool operator==(const Vector& other) {\n        for (int i = 0; i < 3; ++i) {\n            if (fabs(coord[i] - other.coord[i]) > EPS) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    Vector& operator+=(const Vector& other) {\n        for (int i = 0; i < 3; ++i) {\n            coord[i] += other.coord[i];\n        }\n        return *this;\n    }\n\n    Vector& operator-=(const Vector& other) {\n        for (int i = 0; i < 3; ++i) {\n            coord[i] -= other.coord[i];\n        }\n        return *this;\n    }\n\n    Vector& operator*=(double factor) {\n        for (int i = 0; i < 3; ++i) {\n            coord[i] *= factor;\n        }\n        return *this;\n    }\n\n    Vector& operator/=(double factor) {\n        for (int i = 0; i < 3; ++i) {\n            coord[i] /= factor;\n        }\n        return *this;\n    }\n\n    Vector normalized() const {\n        return *this / length();\n    }\n\n    friend Vector operator*(Vector a, Vector b) {\n        return Vector(a.coord[0]*b.coord[0], a.coord[1]*b.coord[1], a.coord[2]*b.coord[2]);\n    }\n\n    friend double dot(Vector a, Vector b) {\n        double ans = 0;\n        for (int i = 0; i < 3; ++i) {\n            ans += a.coord[i]*b.coord[i];\n        }\n        return ans;\n    }\n\n    friend Vector vec(Vector a, Vector b) {\n        return Vector(a.coord[1]*b.coord[2]-a.coord[2]*b.coord[1], -(a.coord[0]*b.coord[2]-a.coord[2]*b.coord[0]), a.coord[0]*b.coord[1]-a.coord[1]*b.coord[0]);\n    }\n\n    friend double angle(Vector a, Vector b) {\n        return dot(a, b) / a.length() / b.length();\n    }\n};\n\ninline double sq(Vector v) {\n    return dot(v, v);\n}\n\ntypedef Vector Point;\n\n#endif\n", "meta": {"hexsha": "7e73a91cd3acb7dac70c42bcde7270166d4c5e0c", "size": 2602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util.hpp", "max_stars_repo_name": "nzinov/ray-tracer", "max_stars_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util.hpp", "max_issues_repo_name": "nzinov/ray-tracer", "max_issues_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-21T11:53:07.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-21T11:53:55.000Z", "max_forks_repo_path": "util.hpp", "max_forks_repo_name": "nzinov/ray-tracer", "max_forks_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_forks_repo_licenses": ["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.2393162393, "max_line_length": 160, "alphanum_fraction": 0.5196003075, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6959320723424813}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <ctime>\n\nusing namespace Eigen;\n\ntemplate <class Matrix>\n\n// The function arrowmatvec computes the product the desired product directly as A*A*x\nvoid arrowmatvec(const Matrix & d, const Matrix & a, const Matrix & x, Matrix & y)\n{\n    // Here, we choose a MATLAB style implementation using block construction\n    // you can also use loops\n    // If you are interested you can compare both implementation and see if and how they differ\n    int n=d.size();\n    VectorXd dcut= d.head(n-1);\n    VectorXd acut = a.head(n-1);\n    MatrixXd ddiag=dcut.asDiagonal();\n    MatrixXd A(n,n);\n    MatrixXd D = dcut.asDiagonal();\n    // If you do not create the temporary matrix D, you will get an error: D must be casted to MatrixXd\n    A << D, a.head(n-1), acut.transpose(), d(n-1);\n    \n    y=A*A*x;\n}\n\n// We test the function arrowmatvec with 5 dimensional random vectors.\n\nint main(void)\n{\n//     srand((unsigned int) time(0));\n    VectorXd a=VectorXd::Random(5);\n    VectorXd d=VectorXd::Random(5);\n    VectorXd x=VectorXd::Random(5);\n    VectorXd y;\n    \n    arrowmatvec(d,a,x,y);\n    std::cout << \"A*A*x = \" << y << std::endl;\n}\n", "meta": {"hexsha": "6a9f393775a462725038d456af2adefdc837640f", "size": 1173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS1/solutions_ps1/C++/arrowmatvec.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++/arrowmatvec.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++/arrowmatvec.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.325, "max_line_length": 103, "alphanum_fraction": 0.6615515772, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6959200056820851}}
{"text": "/**\n * \\file SinusGeneratorFilter.cpp\n */\n\n#include <ATK/Tools/SinusGeneratorFilter.h>\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  SinusGeneratorFilter<DataType_>::SinusGeneratorFilter()\n  :Parent(0, 2)\n  {\n  }\n  \n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_frequency(DataType_ frequency)\n  {\n    if(frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency must be strictly positive\");\n    }\n    this->frequency = frequency;\n    this->frequ_cos = std::cos(2 * boost::math::constants::pi<DataType_>() * frequency / output_sampling_rate);\n    this->frequ_sin = std::sin(2 * boost::math::constants::pi<DataType_>() * frequency / output_sampling_rate);\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_frequency() const\n  {\n    return frequency;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_volume(DataType_ volume)\n  {\n    this->volume = volume;\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_volume() const\n  {\n    return volume;\n  }\n  \n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_offset(DataType_ offset)\n  {\n    this->offset = offset;\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_offset() const\n  {\n    return offset;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::full_setup()\n  {\n    Parent::full_setup();\n    cos = 1;\n    sin = 0;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    DataType* ATK_RESTRICT output_cos = outputs[0];\n    DataType* ATK_RESTRICT output_sin = outputs[1];\n\n    for(gsl::index i = 0; i < size; ++i)\n    {\n      auto new_cos = cos * frequ_cos - sin * frequ_sin;\n      auto new_sin = cos * frequ_sin + sin * frequ_cos;\n      auto norm = (new_cos * new_cos + new_sin * new_sin);\n\n      cos = new_cos / norm;\n      sin = new_sin / norm;\n\n      output_cos[i] = volume * cos + offset;\n      output_sin[i] = volume * sin + offset;\n    }\n  }\n  \n#if ATK_ENABLE_INSTANTIATION\n  template class SinusGeneratorFilter<float>;\n#endif\n  template class SinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "0810bc980d0d8917ec69ba998c585e614885aaf7", "size": 2288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 24.3404255319, "max_line_length": 111, "alphanum_fraction": 0.6896853147, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6957488344712136}}
{"text": "\ufeff#define BOOST_TEST_MODULE School test\n#include <boost/test/unit_test.hpp>\n#include \"Sum.h\"\n#include \"Variable.h\"\n\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\n\nBOOST_AUTO_TEST_CASE(P_474)\n{\n\tstd::cout\n\t\t<< std::endl\n\t\t<< \"No 474 Equations\"\n\t\t<< std::endl;\n\n\tDECL_VA(x);\n\tstd::cout << \"x+318=645\t\tx=\" << (x + 318 - 645)(x) << std::endl;\n\n\tDECL_VA(y);\n\tstd::cout << \"870-y=187\t\ty=\" << (870-y-187)(y) << std::endl;\n\n\tDECL_VA(z);\n\tstd::cout << \"z-234=356\t\tz=\" << (z-234-356)(z) << std::endl;\n\n\n}\n\n\nBOOST_AUTO_TEST_CASE(N456)\n{\n\tstd::cout\n\t\t<< std::endl\n\t\t<< \n\t\t\"\u2116456\"\n\t\t<< std::endl;\n\n\tDECL_VA(all);\n\tDECL_VA(soldfirst);\n\tDECL_VA(soldsecond);\n\tDECL_VA(free);\n\n\t// \u0423\u0441\u044c\u043e\u0433\u043e = \u041f\u0440\u043e\u0434\u0430\u043b\u0438\u0421\u043f\u043e\u0447\u0430\u0442\u043a\u0443 + \u041f\u0440\u043e\u0434\u0430\u043b\u0438\u041f\u043e\u0442\u0456\u043c + \u0412\u0456\u043b\u044c\u043d\u0438\u0445\u041c\u0456\u0441\u0446\u044c\n\t// (\u041f\u0440\u043e\u0434\u0430\u043b\u0438\u0421\u043f\u043e\u0447\u0430\u0442\u043a\u0443 + \u041f\u0440\u043e\u0434\u0430\u043b\u0438\u041f\u043e\u0442\u0456\u043c + \u0412\u0456\u043b\u044c\u043d\u0438\u0445\u041c\u0456\u0441\u0446\u044c) - \u0423\u0441\u044c\u043e\u0433\u043e == 0\n\tauto formula = (soldfirst + soldsecond + free) - all;\n\tstd::cout << \"formula: \" << formula.str() << \" = 0\" << std::endl;\n\n\tformula.eval({\n\t\t{ all, 586 },\n\t\t{ soldfirst, 29 },\n\t\t{ soldsecond, 459 }\n\t\t});\n\tstd::cout << \"evaluated: \" << formula.str() << \" = 0\" << std::endl;\n\n\tauto root = formula(free);\n\tstd::cout << \"x = \" << root << std::endl;\n\n\tformula.eval({ { free, root } });\n\tstd::cout << \"check: \" << formula << \" = 0\" << std::endl;\n\tBOOST_TEST(formula == 0);\n}\n\nBOOST_AUTO_TEST_CASE(N_451_3)\n{\n\tstd::cout\n\t\t<< std::endl\n\t\t<< \"451_3\"\n\t\t<< std::endl;\n\n\tDECL_VA(S);\n\tDECL_VA(P);\n\tDECL_VA(x);\n\n\tauto formula = (P + x) - S; // S = P+x\n\tstd::cout << \"formula: \" << formula.str() << \" = 0\" << std::endl;\n\n\tformula.eval({\n\t\t{ S, 235 },\n\t\t{ P, 127 }\n\t\t});\n\tstd::cout << \"evaluated: \" << formula.str() << \" = 0\" << std::endl;\n\n\tauto root = formula(x);\n\tstd::cout << \"x = \" << root << std::endl;\n\n\tformula.eval({ { x, root } });\n\tstd::cout << \"check: \" << formula << \" = 0\" << std::endl;\n\tBOOST_TEST(formula == 0);\n}\n\nBOOST_AUTO_TEST_CASE(P_465_358)\n{\n\tstd::cout\n\t\t<< std::endl\n\t\t<< \"Primer: 465-358=\" << 586-459\n\t\t<< std::endl;\n}\n\nBOOST_AUTO_TEST_CASE(Perimeter)\n{\n    std::cout\n        << std::endl\n        << \"perimeter\"\n        << std::endl;\n    \n    DECL_VA(x);\n    DECL_VA(P);\n    DECL_VA(a);\n    DECL_VA(b);\n\n    auto formula = (a+b)*2 - P;\n    std::cout <<\"formula: \" << formula.str() << \" = 0\" << std::endl;\n    \n    formula.eval({\n        { P, 20 },\n        { a, x },\n        { b, 6 }\n    });\n    std::cout <<\"evaluated: \" << formula.str() << \" = 0\" << std::endl;\n    \n    auto root = formula(x);\n    std::cout <<\"x = \" << root << std::endl;\n    \n    BOOST_TEST(root == 4);\n    \n    formula.eval({ { x, root }});\n    std::cout << \"check: \" << formula << \" = 0\" << std::endl;\n    BOOST_TEST(formula == 0);\n}\n\n", "meta": {"hexsha": "b70055e5834d0d05d223f3cf5baae193074eb4cd", "size": 2616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/SchoolTasks.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-08-13T18:46:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T14:18:10.000Z", "max_issues_repo_path": "omnn/math/test/SchoolTasks.cpp", "max_issues_repo_name": "SergMariaDB/openmind", "max_issues_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2017-11-26T12:42:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T09:38:33.000Z", "max_forks_repo_path": "omnn/math/test/SchoolTasks.cpp", "max_forks_repo_name": "SergMariaDB/openmind", "max_forks_repo_head_hexsha": "98ad7f1c2c5c02d41418c7f9af25876342270d25", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-08-28T07:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T19:59:55.000Z", "avg_line_length": 19.8181818182, "max_line_length": 70, "alphanum_fraction": 0.5332568807, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7634837743174789, "lm_q1q2_score": 0.695670918556902}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n    const Eigen::MatrixXd &vertices,\n    std::function<double(const Eigen::Vector2d &)> f) {\n  // Number of nodes of the element: triangles = 3, rectangles = 4\n  const int num_nodes = vertices.cols();\n  // Vector for returning element vector\n  Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n  //====================\n  // Your code goes here\n  //====================\n \n  Eigen::MatrixXd midpoints(2,num_nodes);\n  \n  double area;\n  switch(num_nodes){\n    case 3: {\n      area = 0.5*(vertices(0,1)-vertices(0,0)*(vertices(1,2)-vertices(1,0))-\n                  vertices(0,2)-vertices(0,0)*(vertices(1,1)-vertices(1,0))\n              );\n      midpoints<<\n        vertices(0,0)+vertices(0,1),\n        vertices(0,1)+vertices(0,2),\n        vertices(0,2)+vertices(0,0),\n        vertices(1,0)+vertices(1,1),\n        vertices(1,1)+vertices(1,2),\n        vertices(1,2)+vertices(1,0);\n      break;\n    }\n    case 4: {\n      area = (vertices(0,1)-vertices(0,0))*(vertices(1,3)-vertices(1,0));\n      midpoints<<\n        vertices(0,0)+vertices(0,1),\n        vertices(0,1)+vertices(0,2),\n        vertices(0,2)+vertices(0,3),\n        vertices(0,3)+vertices(0,0),\n        vertices(1,0)+vertices(1,1),\n        vertices(1,1)+vertices(1,2),\n        vertices(1,2)+vertices(1,3),\n        vertices(1,3)+vertices(1,0);\n      break;\n    }\n  }\n  midpoints *= 0.5;\n\n  Eigen::VectorXd fvals = Eigen::VectorXd::Zero(num_nodes);\n  for (int i=0;i<num_nodes;i++){\n    fvals[i] = f(midpoints.col(i));\n  }\n\n  for (int i=0;i<num_nodes;i++){\n    elem_vec[i%num_nodes] += 0.5*fvals[i];\n    elem_vec[(i+1)%num_nodes] += 0.5*fvals[i];\n  }\n  elem_vec *= area/(double)num_nodes;\n  return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace\n\nEigen::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": "a4264332c79f0a4b1fb937aa490e72c01aa40af9", "size": 2726, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_stars_repo_licenses": ["MIT"], "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": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_issues_repo_licenses": ["MIT"], "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": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_forks_repo_licenses": ["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.26, "max_line_length": 76, "alphanum_fraction": 0.6291269259, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6956626611653807}}
{"text": "/*\n * Copyright Nick Thompson, 2017\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <random>\n#include <iostream>\n#include <boost/type_index.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/array.hpp>\n#include \"math_unit_test.hpp\"\n\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::math::chebyshev_t;\nusing boost::math::chebyshev_t_prime;\nusing boost::math::chebyshev_u;\n\ntemplate<class Real>\nvoid test_polynomials()\n{\n    std::cout << \"Testing explicit polynomial representations of the Chebyshev polynomials on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n\n    Real x = -2;\n    Real tol = 32*std::numeric_limits<Real>::epsilon();\n    while (x < 2)\n    {\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(0, x), Real(1), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(1, x), x, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(2, x), 2*x*x - 1, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(3, x), x*(4*x*x-3), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(4, x), 8*x*x*(x*x - 1) + 1, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t(5, x), x*(16*x*x*x*x - 20*x*x + 5), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n\n    x = -2;\n    while (x < 2)\n    {\n        CHECK_MOLLIFIED_CLOSE(chebyshev_u(0, x), Real(1), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_u(1, x), 2*x, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_u(2, x), 4*x*x - 1, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_u(3, x), 4*x*(2*x*x - 1), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n}\n\n\ntemplate<class Real>\nvoid test_derivatives()\n{\n    std::cout << \"Testing explicit polynomial representations of the Chebyshev polynomial derivatives on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n\n    Real x = -2;\n    Real tol = 4*std::numeric_limits<Real>::epsilon();\n    while (x < 2)\n    {\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t_prime(0, x), Real(0), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t_prime(1, x), Real(1), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t_prime(2, x), 4*x, tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t_prime(3, x), 3*(4*x*x - 1), tol);\n        CHECK_MOLLIFIED_CLOSE(chebyshev_t_prime(4, x), 16*x*(2*x*x - 1), tol);\n        // This one makes the tolerance have to grow too large; the Chebyshev recurrence is more stable than naive polynomial evaluation anyway.\n        //BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(5, x), 5*(4*x*x*(4*x*x - 3) + 1), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n}\n\ntemplate<class Real>\nvoid test_clenshaw_recurrence()\n{\n    using boost::math::chebyshev_clenshaw_recurrence;\n    boost::array<Real, 5> c0 = { {2, 0, 0, 0, 0} };\n    // Check the size = 1 case:\n    boost::array<Real, 1> c01 = { {2} };\n    // Check the size = 2 case:\n    boost::array<Real, 2> c02 = { {2, 0} };\n    boost::array<Real, 4> c1 = { {0, 1, 0, 0} };\n    boost::array<Real, 4> c2 = { {0, 0, 1, 0} };\n    boost::array<Real, 5> c3 = { {0, 0, 0, 1, 0} };\n    boost::array<Real, 5> c4 = { {0, 0, 0, 0, 1} };\n    boost::array<Real, 6> c5 = { {0, 0, 0, 0, 0, 1} };\n    boost::array<Real, 7> c6 = { {0, 0, 0, 0, 0, 0, 1} };\n\n    Real x = -1;\n    // It's not clear from this test which one is more accurate; higher precision cast testing is required, and is done elsewhere:\n    int ulps = 50;\n    while (x <= 1)\n    {\n        Real y = chebyshev_clenshaw_recurrence(c0.data(), c0.size(), x);\n        Real expected = chebyshev_t(0, x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c0.data(), c0.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        y = chebyshev_clenshaw_recurrence(c01.data(), c01.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c01.data(), c01.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        y = chebyshev_clenshaw_recurrence(c02.data(), c02.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c02.data(), c02.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(1,x);\n        y = chebyshev_clenshaw_recurrence(c1.data(), c1.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c1.data(), c1.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(2, x);\n        y = chebyshev_clenshaw_recurrence(c2.data(), c2.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c2.data(), c2.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(3, x);\n        y = chebyshev_clenshaw_recurrence(c3.data(), c3.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c3.data(), c3.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(4, x);\n        y = chebyshev_clenshaw_recurrence(c4.data(), c4.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c4.data(), c4.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(5, x);\n        y = chebyshev_clenshaw_recurrence(c5.data(), c5.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c5.data(), c5.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        expected = chebyshev_t(6, x);\n        y = chebyshev_clenshaw_recurrence(c6.data(), c6.size(), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n        y = chebyshev_clenshaw_recurrence(c6.data(), c6.size(), Real(-1), Real(1), x);\n        CHECK_ULP_CLOSE(expected, y, ulps);\n\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\ntemplate<typename Real>\nvoid test_translated_clenshaw_recurrence()\n{\n    using boost::math::chebyshev_clenshaw_recurrence;\n    std::mt19937_64 mt(123242);\n    std::uniform_real_distribution<Real> dis(-1,1);\n\n    std::vector<Real> c(32);\n    for (auto & d : c) {\n        d = dis(mt);\n    }\n    int samples = 0;\n    while (samples++ < 250) {\n        Real x = dis(mt);\n        Real expected = chebyshev_clenshaw_recurrence(c.data(), c.size(), x);\n        // The computed value, in this case, should actually be better, since it has more information to use.\n        // In any case, this test doesn't show Reinch's modification to the Clenshaw recurrence is better;\n        // it shows they are doing roughly the same thing.\n        Real computed = chebyshev_clenshaw_recurrence(c.data(), c.size(), Real(-1), Real(1), x);\n        if (!CHECK_ULP_CLOSE(expected, computed, 1000)) {\n            std::cerr << \"  Problem occured at x = \" << x << \"\\n\";\n        }\n    }\n}\n\nint main()\n{\n    test_polynomials<float>();\n    test_polynomials<double>();\n    test_polynomials<long double>();\n    test_polynomials<cpp_bin_float_quad>();\n\n    test_derivatives<float>();\n    test_derivatives<double>();\n    test_derivatives<long double>();\n    test_derivatives<cpp_bin_float_quad>();\n\n    test_clenshaw_recurrence<float>();\n    test_clenshaw_recurrence<double>();\n    test_clenshaw_recurrence<long double>();\n\n    test_translated_clenshaw_recurrence<double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "90982d68a6d17583e67ee8500e16f63b0607bdd4", "size": 7603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/chebyshev_test.cpp", "max_stars_repo_name": "armdevvel/boost", "max_stars_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "libs/math/test/chebyshev_test.cpp", "max_issues_repo_name": "armdevvel/boost", "max_issues_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "libs/math/test/chebyshev_test.cpp", "max_forks_repo_name": "armdevvel/boost", "max_forks_repo_head_hexsha": "30d0930951181ef5bc5aad2231ebac8575db0720", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 39.3937823834, "max_line_length": 172, "alphanum_fraction": 0.6314612653, "num_tokens": 2407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.69566265844585}}
{"text": "/**\n * 2D Data builder class definition\n */\n\n#pragma once\n\n#define _USE_MATH_DEFINES\n\n#include <Eigen/Dense>\n#include <math.h>\n\nnamespace DeepLearningFramework {\n/**\n * Build Data class\n *\n * generateDiscSet: generate 2D data with label 1 inside a circle, otherwise 0\n */\nclass DataBuilder2D {\npublic:\n  DataBuilder2D() = delete;\n  ~DataBuilder2D() = delete;\n\n  /**\n   * generateDiscSet static method\n   *\n   * Generate features in [0.f; 1.f] and labels in function of radius value\n   * One-hot encoded labels [0, 1] inside radius, otherwise [1, 0]\n   *\n   * @param[out] labels one-hot encoded labels, [0, 1] inside radius otherwise\n   * [1, 0]\n   * @param[out] features random number in range [0.f, 1.f]\n   * @param[in] samplesCount number of samples to generate.\n   * @param[in] discRadius radius of the circle in range [0.f, 1.f].\n   */\n  static void generateDiscSet(Eigen::MatrixXf &labels,\n                              Eigen::MatrixXf &features, uint32_t samplesCount,\n                              float discRadius);\n};\n}; // namespace DeepLearningFramework\n", "meta": {"hexsha": "5eb3bb601ae80024b1d132608d50f64717099357", "size": 1065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Data/DataBuilder2D.hpp", "max_stars_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_stars_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_stars_repo_licenses": ["MIT"], "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/Data/DataBuilder2D.hpp", "max_issues_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_issues_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_issues_repo_licenses": ["MIT"], "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/Data/DataBuilder2D.hpp", "max_forks_repo_name": "Apiquet/DeepLearningFrameworkFromScratchCpp", "max_forks_repo_head_hexsha": "63a6cd57f8f50e75ac7eb9bd5d7ea79ed5253c71", "max_forks_repo_licenses": ["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.625, "max_line_length": 79, "alphanum_fraction": 0.6563380282, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8006919949619793, "lm_q1q2_score": 0.695662644742537}}
{"text": "#include <eigen3/Eigen/Core>\n#include <Eigen/LU>\n#include <vector>\n\n#include \"nntree/dataset.h\"\n\nnamespace nntree {\n    namespace core {\n\n// TODO(equivalence1) memory leaks here, but we will rewrite it anyways\n        void LeastSquares(Tensor<double>& x, Tensor<double>& y, Tensor<double>& res) {\n            namespace E = Eigen;\n\n            assert(x.Ndim() == 2);\n            assert(y.Ndim() == 2);\n\n            E::Map<E::MatrixXd, 0, E::Stride<E::Dynamic, E::Dynamic>>\n                mxX_t(x.Data(),\n                      x.Ncols(),\n                      x.Nrows(),\n                      E::Stride<E::Dynamic, E::Dynamic>(x.Strides()[0] / sizeof(double),\n                                                        x.Strides()[1] / sizeof(double)));\n            auto mxX = mxX_t.transpose();\n            E::Map<E::MatrixXd, 0, E::Stride<E::Dynamic, E::Dynamic>>\n                mxY_t(y.Data(),\n                      y.Ncols(),\n                      y.Nrows(),\n                      E::Stride<E::Dynamic, E::Dynamic>(y.Strides()[0] / sizeof(double),\n                                                        y.Strides()[1] / sizeof(double)));\n            auto mxY = mxY_t.transpose();\n\n            auto solution = (mxX.transpose() * mxX).inverse() * mxX.transpose() * mxY;\n            auto solution_t = solution.transpose();\n\n            auto result = new double[solution_t.rows() * solution_t.cols()];\n            assert(result != nullptr);\n            E::Map<E::MatrixXd> resultMap(result, solution_t.rows(), solution_t.cols());\n            resultMap = solution_t;\n\n            std::vector<uint64_t> shape({(uint64_t) solution.rows(),\n                                         (uint64_t) solution.cols()});\n            std::vector<uint64_t> strides({(uint64_t) resultMap.outerStride() * sizeof(double),\n                                           (uint64_t) resultMap.innerStride() * sizeof(double)});\n            res.FromMem(resultMap.data(), shape, strides, true);\n        }\n\n// TODO(equivalence1) reference is not const\n        void LeastSquares(core::DataSet<double, double>& ds, Tensor<double>& res) {\n            auto& x = ds.GetInput();\n            auto& y = ds.GetOutput();\n            assert(y.Nrows() == x.Nrows());\n            LeastSquares(x, y, res);\n        }\n\n    }\n}\n", "meta": {"hexsha": "1d62aa12fbdeaa6838a63a59b99ad95a6b06d927", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nn_trees/src/least_squares.cpp", "max_stars_repo_name": "equivalence1/ml_lib", "max_stars_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-15T09:40:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-15T09:40:43.000Z", "max_issues_repo_path": "cpp/nn_trees/src/least_squares.cpp", "max_issues_repo_name": "equivalence1/ml_lib", "max_issues_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "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": "cpp/nn_trees/src/least_squares.cpp", "max_forks_repo_name": "equivalence1/ml_lib", "max_forks_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-29T10:17:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-03T20:33:31.000Z", "avg_line_length": 39.9824561404, "max_line_length": 97, "alphanum_fraction": 0.4927599824, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642806, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6956062905382703}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef DLTV_PROBLEM_HPP_\n#define DLTV_PROBLEM_HPP_\n\n#include <Eigen/Dense>\n#include <cstdint>\n\ntemplate<std::size_t _nPts = 100>\nstruct DltvOcpDi\n{\n  static_assert(_nPts > 1, \"Number of trajectory points must be > 1.\");\n\n  // Must be defined\n  constexpr static std::size_t nPts = _nPts;\n  constexpr static std::size_t nx = 2;\n  constexpr static std::size_t nu = 1;\n\n  // Time step\n  constexpr static double dt = 0.01;\n\n  // Custom types\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using input_t = Eigen::Matrix<double, nu, 1>;\n  using A_t = Eigen::Matrix<double, nx, nx>;\n  using B_t = Eigen::Matrix<double, nx, nu>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n\n  // Constants\n  const A_t A = (A_t() << 1., 0.01, 0., 1.).finished();\n  const B_t B = (B_t() << 5.0e-5, 0.01).finished();\n  const state_t E = (state_t() << 0., 0.).finished();\n  const Q_t Q = (Q_t() << 10., 0., 0., 0.1 ).finished();\n  const R_t R = (R_t() << 0.01).finished();\n  const Q_t QT = (Q_t() << 1., 0., 0., 1.).finished();\n\n  void get_x0(Eigen::Ref<state_t> x0) const\n  {\n    x0 << 1., 0.;\n  }\n\n  void get_T(std::size_t k, double & t) const\n  {\n    t = static_cast<double>(k) * dt;\n  }\n\n  void get_state_lb(std::size_t, Eigen::Ref<state_t> state_lb) const\n  {\n    state_lb <<\n      -1000.,\n      -0.5;\n  }\n\n  void get_state_ub(std::size_t, Eigen::Ref<state_t> state_ub) const\n  {\n    state_ub <<\n      1000.,\n      0.5;\n  }\n\n  void get_input_lb(std::size_t, Eigen::Ref<input_t> input_lb) const\n  {\n    input_lb << -1;\n  }\n\n  void get_input_ub(std::size_t, Eigen::Ref<input_t> input_ub) const\n  {\n    input_ub << 1;\n  }\n\n  const A_t & get_A(std::size_t) const\n  {\n    return A;\n  }\n\n  const B_t & get_B(std::size_t) const\n  {\n    return B;\n  }\n\n  const state_t & get_E(std::size_t) const\n  {\n    return E;\n  }\n\n  const Q_t & get_Q(std::size_t) const\n  {\n    return Q;\n  }\n\n  const R_t & get_R(std::size_t) const\n  {\n    return R;\n  }\n\n  const Q_t & get_QT() const\n  {\n    return QT;\n  }\n\n  state_t get_xldot(double) const {return state_t::Zero();}\n};\n\n#endif  // DLTV_PROBLEM_HPP_\n", "meta": {"hexsha": "4f3776b9965cf28d682e1966810c6d9ea7890fe1", "size": 2211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/dltv_problem.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/dltv_problem.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "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/dltv_problem.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["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.4722222222, "max_line_length": 71, "alphanum_fraction": 0.6110357304, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6956062791736446}}
{"text": "/**\n * @file matode_main.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n#include <iomanip>\n#include <iostream>\n\n#include \"matode.h\"\n\nint main(int /*argc*/, char** /*argv*/) {\n  /* SAM_LISTING_BEGIN_6 */\n  double h = 0.01;  // stepsize\n  Eigen::Vector3d norms;\n  // Build M\n  Eigen::Matrix3d M;\n  M << 8, 1, 6, 3, 5, 7, 9, 9, 2;\n  // Build A\n  Eigen::Matrix3d A;\n  A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n  Eigen::MatrixXd I = Eigen::Matrix3d::Identity();\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_6 */\n  return 0;\n}\n", "meta": {"hexsha": "1d59d27af15b5724d8ffcbf4d82216d9a80961dc", "size": 623, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/templates/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": "homeworks/MatODE/templates/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": "homeworks/MatODE/templates/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": 20.7666666667, "max_line_length": 50, "alphanum_fraction": 0.5537720706, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6955981651181865}}
{"text": "#include \"spectral_clustering.h\"\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\n//these functions are defined later in this file\nvoid repair_clusters(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXi& sF, Eigen::VectorXi& sFC);\nstd::vector<std::vector<int> > spectral_clustering(const Eigen::MatrixXd& A, int K);\nstd::vector<std::vector<int> > kmeans_cluster(const Eigen::MatrixXd& data, int K);\n\n/*\nSpectral clustering of the faces\n- use similarity matrix and face connectivity to determine the clusters\n\nInput:\n\nK: number of clusters\nV, F: the mesh\nsimilarity: a |F|*|F| symmetric matrix\n\nOutput:\n\nsF: A face index matrix of size |F|*3. Faces in the same cluster are in consecutive rows of sF\nsFC: A K*1 vector. Each element indicates the size of each cluster stored in sF\n*/\n\nvoid spectral_clustering\n(int K, const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, const Eigen::MatrixXd& similarity,\n Eigen::MatrixXi& sF, Eigen::VectorXi& sFC)\n{\n\n\t//Requirements\n\t// - similar faces are clustered together based on the similarity matrix\n\t// - faces in a cluster must be contiguous and form a single connected component\n\n\n  //dummy segmentation, replace the following code\n  int cluster_size=F.rows()/K;\n  sFC=Eigen::VectorXi::Constant(K,cluster_size);\n  sFC[K-1]=F.rows()-cluster_size*(K-1);\n  sF=F;\n\n  //YOUR CODE HERE\n\n  //make sure that faces in the same cluster are connected\n  repair_clusters(V,F,sF,sFC);\n}\n\n\n/// repair clusters so that each cluster contains a compact connected component\nvoid repair_clusters\n(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXi& sF, Eigen::VectorXi& sFC)\n{\n  //YOUR CODE HERE\n}\n\n/**\n* Spectral clustering into K clusters\n*\n* @param A \t\tthe affinity matrix\n* @param K    the number of clusters\n*\n* @return\t\t   ordered set of data row indices for each cluster\n*/\n\nstd::vector<std::vector<int> > spectral_clustering(const Eigen::MatrixXd& A, int K)\n{\n\t// compute normalized laplacian\n  // using Ng, Jordan and Weiss, \"On Spectral Clustering: Analysis and an Algorithm\", NIPS 2002\n  Eigen::VectorXd S=A.colwise().sum().array().pow(-0.5);\n  Eigen::MatrixXd D=S.asDiagonal();\n  Eigen::MatrixXd I=Eigen::MatrixXd::Identity(A.rows(),A.cols());\n  Eigen::MatrixXd L = I - (D* A *D);\n\n  //solve, eigenvalues are sorted in increasing order\n  cout<<\"- Solving Eigen Decomposition\"<<endl;\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(L);\n\tEigen::VectorXd E = es.eigenvalues();\n\tEigen::MatrixXd V = es.eigenvectors();\n\n  // keep only the k-principal components (Eigen's eigenvectors are colwise)\n  V = V.block(0,1,V.rows(),K);\n\n  //normalize V\n  Eigen::VectorXd norm = V.array().pow(2).matrix().rowwise().sum();\n  for (unsigned int k = 0; k < K; ++k) V.col(k) = V.col(k).array() / norm.array();\n\n  return kmeans_cluster(V, K);\n}\n\n/**\n * kmeans clustering\n * based on kmeans matlab script by Ian T Nabney (1996-2001)\n *\n * @param data \taffinity matrix\n * @oaram ncentres\tnumber of clusters\n * @return\t\tordered set of data row indices for each cluster\n * \t\t\t    \t(order is based on distance to cluster centre)\n */\nstd::vector<std::vector<int> >\nkmeans_cluster(const Eigen::MatrixXd& data, int ncentres)\n{\n  std::srand(std::time(nullptr));\n  //std::srand(0); //use this to debug so you get the same results\n\n\tint ndims = data.cols();\n\tint ndata = data.rows();\n\n\tEigen::MatrixXd centres = Eigen::MatrixXd::Zero(ncentres, ndims);\n\tEigen::MatrixXd old_centres;\n\n\tstd::vector<int> rands;\n\tfor (int i=0; i < ncentres; i++)\n  {\n\t\t//randomly initialise centers\n\t\tbool flag;\n\t\tdo {\n\t\t\tflag = false;\n\t\t\tint randIndex = std::rand()%ndata;\n\t\t\t//make sure same row not chosen twice\n\t\t\tfor (unsigned int j=0; j < rands.size(); ++j) {\n\t\t\t\tif (randIndex == rands[j]) {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!flag) {\n\t\t\t\tcentres.row(i) = data.row(randIndex);\n\t\t\t\trands.push_back(randIndex);\n\t\t\t}\n\t\t} while (flag);\n\t}\n\tEigen::MatrixXd id = Eigen::MatrixXd::Identity(ncentres, ncentres);\n\t//maps vectors to centres.\n\tEigen::MatrixXd post(ndata, ncentres);\n\n\tEigen::VectorXd minvals(ndata);\n\n\tdouble old_e = 0;\n\tint niters = 100;\n\tfor (int n=0; n < niters; n++) {\n\t\t//Save old centres to check for termination\n\t\told_centres = centres;\n\n\t\t// Calculate posteriors based on existing centres\n\t\tEigen::MatrixXd d2(ndata, ncentres);\n\t\tfor (int j = 0; j < ncentres; j++) {\n\t\t\tfor (int k=0; k < ndata; k++) {\n\t\t\t\td2(k,j) = (data.row(k)-centres.row(j)).squaredNorm();\n\t\t\t}\n\t\t}\n\n\t\tint r,c;\n\t\t// Assign each point to nearest centre\n\t\tfor (int k=0; k < ndata; k++) {\n\t\t\t//get centre index (c)\n\t\t\tminvals[k] = d2.row(k).minCoeff(&r, &c);\n\t\t\t//set centre\n\t\t\tpost.row(k) = id.row(c);\n\t\t}\n\n\t\tEigen::VectorXd num_points = post.colwise().sum();\n\t\t// Adjust the centres based on new posteriors\n\t\tfor (int j = 0; j < ncentres; j++) {\n\t\t\tif (num_points[j] > 0) {\n\t\t\t\tEigen::MatrixXd s = Eigen::MatrixXd::Zero(1,ndims);\n\t\t\t\tfor (int k=0; k<ndata; k++) {\n\t\t\t\t\tif (post(k,j) == 1) {\n\t\t\t\t\t\ts += data.row(k);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcentres.row(j) = s / num_points[j];\n\t\t\t}\n\t\t}\n\n\t\t// Error value is total squared distance from cluster centres\n\t\tdouble e = minvals.sum();\n\t\tdouble ediff = fabs(old_e - e);\n\t\tdouble cdiff = (centres-old_centres).array().abs().maxCoeff();\n\t\t//std::cout << \"Cycle \" << n << \" Error \" << e << \" Movement \" << cdiff << \", \" << ediff << std::endl;\n\n\t\tif (n > 1) {\n\t\t\t//Test for termination\n\t\t\tif (cdiff < 0.0000000001 && ediff < 0.0000000001) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\told_e = e;\n\t}\n\n\t//------- finished kmeans ---------\n\n\t//find the item closest to the centre for each cluster\n\tstd::vector<std::vector<int> > clustered_items;\n\tfor (int j=0; j < ncentres; j++) {\n\t\t//put data into map (multimap because minvals[k] could be the same for multiple units)\n\t\tstd::multimap<double,int> cluster;\n\t\tfor (int k=0; k < ndata; k++) {\n\t\t\tif (post(k,j) == 1) {\n\t\t\t\tcluster.insert(std::make_pair(minvals[k], k));\n\t\t\t}\n\t\t}\n\t\t//extract data from map\n\t\tstd::vector<int> units;\n\t\t//the map will be sorted based on the key (the minval) so just loop through it\n\t\t//to get set of data indices sorted on the minval\n\t\tfor (std::multimap<double,int>::iterator it = cluster.begin(); it != cluster.end(); it++) {\n\t\t\tunits.push_back(it->second);\n\t\t}\n\n\t\tclustered_items.push_back(units);\n\t}\n\t//return the ordered set of item indices for each cluster centre\n\treturn clustered_items;\n}\n", "meta": {"hexsha": "4098e4adef62f62c3e1381a6d4faec1de28b024f", "size": 6343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spectral_clustering.cpp", "max_stars_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_stars_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-03-25T22:47:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T06:07:50.000Z", "max_issues_repo_path": "src/spectral_clustering.cpp", "max_issues_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_issues_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "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/spectral_clustering.cpp", "max_forks_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_forks_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-01T13:33:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T13:33:46.000Z", "avg_line_length": 29.0963302752, "max_line_length": 116, "alphanum_fraction": 0.6635661359, "num_tokens": 1878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6955981584132603}}
{"text": "#include <graphlab.hpp>\n#include <string>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <numeric>\n#include <limits>\n#include <graphlab/engine/warp_engine.hpp> \n#include <graphlab/engine/warp_parfor_all_vertices.hpp> \n#include <unsupported/Eigen/MatrixFunctions>\n\n#include <Eigen/Dense>\n\nint verbose;\nstd::vector<double> Hleft;\n//#include <functional>\n\n/*\n\n  Total Subgraph Centrality.\n\n  For a graph G with adjacency matrix A, TSC(G) = exp(A)*b, where 1 is\n  the ones vector.\n\n\n  We're going to implement this with an Arnoldi solver, following Saad\n  (1992).\n\n  The algorithm works like this:\n  Choose a maximum iteration m.  Then make matrices V and H:\n  b = ones(A.nodecount)\n  V[0] = b/||b||\n  for j in 0..m:\n      w = A*V[j]\n      for i in 0..j:\n         H[i,j] = (w,V[i])\n\t w = w - H[i,j] * V[i]\n      H[j+1,j] = ||w||\n      V[j+1] =w/||w||\n\n  Then TSC = exp(A)*b ~= (V * exp(H) / ||b||)[:,0].  Stop when\n  successive approximations converge, or we run out of steps.  \n\n  We still have that matrix exponential, but it's small and dense, and\n  there's an implementation in Eigen. \n  \n\n  \n*/\n\nclass node {\npublic: \nstd::vector<double> V;\ndouble w;\n  double TSC;\n  double prev;\n  node(): w(0.0),TSC(0.0),prev(0.0){};\n  void load(graphlab::iarchive& infile) {\n    infile>>V>>w>>TSC>>prev;\n  }\n  void save(graphlab::oarchive& outfile) const {\n    outfile<<V<<w<<TSC<<prev;\n  }\n  \n  \n};\n\nclass edge {\npublic:\n  double weight;\n  edge(): weight(1.0) {} ;\n  edge(double weight) : weight(weight) {};\n  \n\n  void save(graphlab::oarchive& outfile) const {\n    outfile<<weight; \n  }\n  \n  void load(graphlab::iarchive& infile) {\n    infile>>weight; \n  }\n  \n  \n};\n\n\ntypedef node vertex_data_type;\ntypedef edge edge_data_type;\ntypedef graphlab::distributed_graph<vertex_data_type, edge_data_type> graph_type; \ntypedef graphlab::warp::warp_engine<graph_type> engine_type; \n\n\n// This is just a little class to be used to find the maximum change in TSC values. \nclass max_finder{\npublic:\n  double data;\n  max_finder& operator+=(const max_finder& other){\n    if (this->data <other.data){\n      this->data = other.data;\n    }\n    return *this;\n  }\n  \n  max_finder(): data(std::numeric_limits<double>::max()) {};\n  max_finder(double x): data(x) {};\n  void load(graphlab::iarchive& infile) {\n    infile>>data;\n  }\n  void save(graphlab::oarchive& outfile) const {\n    outfile<<data;\n  }\n\n\n};\n  \n\n \n\n// These three functions compute the A*w step of the\n// Arnoldi iteration. \ndouble arnoldi_map(graph_type::edge_type e, \n\t\t   graph_type::vertex_type v){\n  return v.data().V.back();\n\n}\nvoid arnoldi_combine(double& v1, const double& v2) {\n  v1 += v2;\n}\nvoid AVj_to_w(graph_type::vertex_type& v) {\n  v.data().w = graphlab::warp::map_reduce_neighborhood(v, \n\t\t\t\t\t\t       graphlab::IN_EDGES,\n\t\t\t\t\t\t       arnoldi_map,\n\t\t\t\t\t\t       arnoldi_combine);\n  return;\n}\n\n// Pushes the current w onto the V matrix\nvoid w_to_v(graph_type::vertex_type& v){\n  v.data().V.push_back(v.data().w);\n}\n// Scales w by a constant factor.  This is meant to be called through transform_vertices \n// with a boost::bind to take care of the argument list\nvoid scale_w(graph_type::vertex_type& v, double scale_factor){\n  v.data().w /= scale_factor;\n}\n\n// Dumps the TSC to stdout\nvoid print_TSC(graph_type::vertex_type& v){\n  std::cout<<v.id()<<\" \" <<v.data().TSC<<std::endl;\n}\n\n// For debugging.\nvoid print_w(graph_type::vertex_type& v){\n  std::cout<<v.id()<<\" \" <<v.data().w<<\" \"<<v.data().V.size()<<\" \"<<v.data().V.back()<<std::endl;\n}\n\n\n// Make initial vector if we want a column from exp(A)\nvoid initialize_column(graph_type::vertex_type& v, int i,int m) {\n  if (v.id()==i){\n    v.data().w = 1.0;\n  } else{\n    v.data().w = 0.0;\n  }\n  v.data().V.reserve(m);\n\n}\n// Make initial vector if we want the TSC\nvoid initialize_TSC(graph_type::vertex_type& v, int m) {\n  v.data().w = 1.0/sqrt((double)m);\n  v.data().V.reserve(m);\n}\n\n// ||w||**2\ndouble sum_w(const graph_type::vertex_type&  v){\n  return v.data().w*v.data().w; \n}\n\n// w*V[i].  Call via boost::bind to select the i.\ndouble w_dot_V(const graph_type::vertex_type&  v, int i){\n  return v.data().w * v.data().V[i];\n}\n\n// w - (h,w)*V[i].  Call via boost::bind to set i, hdot. \nvoid w_minus_hdot(graph_type::vertex_type& v, int i, double hdot) {\n  v.data().w -= hdot * v.data().V[i];\n}\n\n\n// TSC = V*Hleft\nvoid accumulate_hleft(graph_type::vertex_type&v){\n  v.data().prev = v.data().TSC;\n  v.data().TSC = 0;\n  for(int j=0;j<Hleft.size();j++){\n    v.data().TSC += v.data().V[j] * Hleft[j];\n  }\n  if (verbose){\n    if (v.id()<10){\n      std::cout<<\"TSC \"<<v.id()<<\" \"<<Hleft.size()<<\" \"<<v.data().TSC<<\" \"<<v.data().prev<< \" \"<<(v.data().TSC-v.data().prev)/(1e-15+v.data().TSC) <<std::endl;\n    }\n  }\n  return;\n}\n\n// sum ((TSC-prevTSC)/TSC)\ndouble total_error(const graph_type::vertex_type& v){\n  return fabs((v.data().TSC-v.data().prev)/(1e-15+v.data().TSC));\n}\n\n// max ((TSC-prevTSC)/TSC)\nmax_finder max_error(const graph_type::vertex_type& v){\n  return max_finder(fabs((v.data().TSC-v.data().prev)/(1e-15+v.data().TSC)));\n}\n\n\n\nint main(int argc, char** argv) {\n  graphlab::command_line_options clopts(\"Total Subgraph Centrality\");\n  graphlab::distributed_control dc;\n  std::string infile;\n  std::string format = \"tsv\";\n  int verbose=0;\n  int m=100;\n  int column = -1;\n  clopts.attach_option(\"graph\",infile,\"Input graph.\");\n  clopts.attach_option(\"format\",format,\"Input format. Default tsv.\");\n  clopts.attach_option(\"m\",m,\"Maximum number of orthogonal vectors to approximate with. Default 100.\");\n  clopts.attach_option(\"column\",column,\"Column of exponential to calculate (instead of row-sum)\");\n  clopts.attach_option(\"verbose\",verbose,\"Verbosity level.\");\n  if(!clopts.parse(argc, argv)) {\n    dc.cout() << \"Error in parsing command line arguments.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  if (infile==\"\"){\n    dc.cout() <<\"ERROR: Must specify --graph! \\n\";\n    return EXIT_FAILURE;\n  }\n  graph_type graph(dc,clopts);\n  graph.load_format(infile, format);\n  graph.finalize();\n  if (m>graph.num_vertices()) {\n    m = graph.num_vertices();\n  }\n  engine_type engine(dc,graph,clopts);\n\n  engine.signal_all();\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(m+1,m+1);\n  Hleft.resize(m);\n  for(int i=0;i<m;i++) { Hleft[i] = 0.0;}\n  double beta;\n  if (column>=0) {\n    if (column>graph.num_vertices()){\n      column = 0;\n    }\n    graph.transform_vertices(boost::bind(initialize_column,_1,column,m));\n    beta = 1.0;\n  } else {\n    graph.transform_vertices(boost::bind(initialize_TSC,_1,m));\n    beta = sqrt(m);\n  }\n\n\n  // The first column of V is just w\n  graph.transform_vertices(w_to_v);\n\n\n  for(int j=0;j<m;j++) {\n    graphlab::warp::parfor_all_vertices(graph,AVj_to_w);\n    // We should be able to move this loop inside the map-reduce and transform steps\n    for(int i=0;i<=j;i++) {\n      H(i,j)= graph.map_reduce_vertices<double>(boost::bind(w_dot_V,_1,i));\n      graph.transform_vertices(boost::bind(w_minus_hdot,_1,i,H(i,j)));\n    }\n    H(j+1,j)= sqrt(graph.map_reduce_vertices<double>(sum_w));\n    // If we're in this case, it means we have a spanning set and we shouldn't\n    // prep for the next iteration.  Otherwise, make the data we'll need next time.\n    if ( ( !std::isnan(H(j+1,j))) && (H(j+1,j) > 0) ) {\n      graph.transform_vertices(boost::bind(scale_w, _1, H(j+1,j)));\n      graph.transform_vertices(w_to_v); \n    }\n\n    if (j>0) {\n      // Have we converged? \n      Eigen::MatrixXd EH(H);\n      EH = EH.exp();\n      Hleft.resize(j+1);\n      \n      for(int i=0;i<=j;i++) { Hleft[i] = EH(i,0) * beta;}\n      graph.transform_vertices(accumulate_hleft);\n      if (j>1) {\n \tmax_finder largest_error= graph.map_reduce_vertices<max_finder>(max_error);\n\tdouble all_error = graph.map_reduce_vertices<double>(total_error);\n\tif (verbose){\n\t  std::cerr<<\"ARNOLDI STEP FINISHED \"<<j<<std::endl;\n\t  std::cout<<\"MAX ERROR: \"<<largest_error.data<<\" TOTAL ERROR: \"<<all_error<<std::endl;\n\t}\n\tif (largest_error.data < 1e-15) { break; };\n\tif (all_error < 1e-15){  break; }\n      }\n    }\n    // If we know we are in the last iteration, break\n    if (std::isnan(H(j+1,j))){ break;}\n    if (fabs(H(j+1,j))<1e-15){ break;}\n\n \n  }\n  graph.transform_vertices(print_TSC);\n\n\n}\n", "meta": {"hexsha": "4291c697be49ccf76e1e1dfe0a3a8aea62d823bc", "size": 8186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graph_analytics/TSC.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 333.0, "max_stars_repo_stars_event_min_datetime": "2016-07-29T19:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:40:34.000Z", "max_issues_repo_path": "toolkits/graph_analytics/TSC.cpp", "max_issues_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_issues_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-09-15T00:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T07:51:07.000Z", "max_forks_repo_path": "toolkits/graph_analytics/TSC.cpp", "max_forks_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_forks_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 163.0, "max_forks_repo_forks_event_min_datetime": "2016-07-29T19:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:15:24.000Z", "avg_line_length": 26.3215434084, "max_line_length": 159, "alphanum_fraction": 0.6379183973, "num_tokens": 2438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.695519729962897}}
{"text": "\n/******************************************************************************\n\n  Basic N-dimensional topology.\n\n  Copyright (c) 2013\n  Dzmitry Hlindzich <hlindzich@gmail.com>\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions\n  are met:\n  1.  Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\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  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n  SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n#define TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n\n#include <vector>\n#include <utility>\n#include <set>\n#include <boost/static_assert.hpp>\n\n#include \"bo/core/vector.hpp\"\n\nnamespace bo {\nnamespace math {\n\n// Basic N-dimensional hyperrectangle (N-orthotope) geometry.\ntemplate <typename RealType, std::size_t N>\nclass OrthotopeTopology\n{\nprivate:\n    BOOST_STATIC_ASSERT(N > 0);\n\npublic:\n    typedef Vector<RealType, N> Point;\n    typedef std::pair<Point, Point> Edge;\n    typedef std::vector<Edge> Edges;\n\n    // Returns all the edges of a unit N-orthotope.\n    static Edges edges()\n    {\n        // Initialize the source of the edge traverse.\n        PointSet in_vertices;\n        in_vertices.insert(Point(0));\n\n        // Traverse the edges.\n        Edges e;\n        traverse_edges(in_vertices, e);\n\n        return e;\n    }\n\n    // Returns the number of edges in a N-orthotope.\n    static std::size_t edge_count()\n    {\n        return (1 << (N - 1)) * N;\n    }\n\n    // Returns the number of vertices in a N-orthotope.\n    static std::size_t vertex_count()\n    {\n        return 1 << N;\n    }\n\n    // Returns the number of facets ((N-1)-dimensional faces) in a N-othotope.\n    static std::size_t facet_count()\n    {\n        return 2 * N;\n    }\n\nprivate:\n\n    typedef std::set<Point> PointSet;\n\n    // Recursively traverses the edges of a N-orthotope starting from the given set\n    // of vertices in ascending order and pushes the edges into the given container.\n    static void traverse_edges(const PointSet &in_vertices, Edges &edges)\n    {\n        if (in_vertices.size() == 1 && *in_vertices.begin() == Point(1))\n            return;\n\n        PointSet out_vertices;\n\n        for (typename PointSet::const_iterator it = in_vertices.begin(); it != in_vertices.end(); ++it)\n        {\n            Point edge_begin = *it;\n\n            // Find all adjacent vertices for the current one.\n            for (std::size_t k = 0; k < N; ++k)\n            {\n                if (edge_begin[k] == 1)\n                    continue;\n\n                // An adjacent vertex differs only in one dimension.\n                Point edge_end = edge_begin;\n                edge_end[k] = 1;\n\n                // Insert the edge into the collection.\n                edges.push_back(Edge(edge_begin, edge_end));\n\n                // Save the end vertex.\n                out_vertices.insert(edge_end);\n            }\n        }\n\n        traverse_edges(out_vertices, edges);\n    }\n\n};\n\n} // namespace math\n} // namespace bo\n\n#endif // TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n", "meta": {"hexsha": "ce773fb05db98f034b218933260d96811775d110", "size": 4166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/math/topology.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/math/topology.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "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": "Bo/math/topology.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0895522388, "max_line_length": 103, "alphanum_fraction": 0.6437830053, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6955197234204524}}
{"text": "// Copyright 2020, Madhur Chauhan\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This is an example to calculate Reciprocal Fibonacci Constant (A079586 in the OEIS)\n// compile with flags: -std=c++11 -lmpfr\n\n//[fibonacci_eg\n\n#include <boost/math/special_functions/fibonacci.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <iomanip>\n#include <iostream>\n\nint main() {\n    using Real = boost::multiprecision::mpfr_float_1000;\n    boost::math::fibonacci_generator<Real> gen;\n    gen.set(1); // start producing values from 1st fibonacci number\n    Real ans = 0;\n    const int ITR = 1000;\n    for (int i = 0; i < ITR; ++i) {\n        ans += 1.0 / gen();\n    }\n    std::cout << std::setprecision(1000) << \"Reciprocal fibonacci constant after \"\n              << ITR << \" iterations is: \" << ans << std::endl;\n}\n\n//]\n", "meta": {"hexsha": "7c6405c52b4ba052d8b675feaef14e8b8886ebfa", "size": 962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/reciprocal_fibonacci_constant.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/reciprocal_fibonacci_constant.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/reciprocal_fibonacci_constant.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": 30.0625, "max_line_length": 86, "alphanum_fraction": 0.6715176715, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6955197166234861}}
{"text": "#include \"LogisticRegression.h\"\n#include \"TrainingType.h\"\n#include <armadillo>\n#include <assert.h>\n#include <iostream>\n#include <math.h>\n\nusing namespace arma;\n\nLogisticRegression::LogisticRegression(mat &x, vec &y, double regPara)\n    : x{x}, y{y}, regPara{regPara}, trained{false} {\n  assert(x.n_rows == y.n_rows);\n\n  // Create bias column and append at the end of  x\n  mat bias = ones<mat>(this->ExampleNumber(), 1);\n  this->x.insert_cols(0, bias);\n}\n\nLogisticRegression::~LogisticRegression() {}\n\nvoid LogisticRegression::AddData(mat &extraX, vec &extraY) {\n  assert(extraX.n_rows == extraY.n_rows);\n  // Add 1 because x has a bias column\n  assert((extraX.n_cols + 1) == this->x.n_cols);\n\n  this->trained = false;\n  // Add Bias column to latest added input\n  mat bias = ones<mat>(extraX.n_rows, 1);\n  mat inputX = extraX;\n  inputX.insert_cols(0, bias);\n  this->x.insert_rows(this->x.n_rows, inputX);\n  this->y.insert_rows(this->y.n_rows, extraY);\n}\n\nvoid LogisticRegression::Train(TrainingType Type, double alpha,\n                               unsigned int iters) {\n  /*if (Type == normalEquation) {\n    this->NormalEquation();\n  } else*/\n  if (Type == gradientDescent) {\n    this->GradientDescent(alpha, iters);\n  } else {\n    std::cerr << \"Invalid training type\" << std::endl;\n  }\n}\n\nuword LogisticRegression::ExampleNumber() { return this->x.n_rows; }\n\ndouble LogisticRegression::Probablity(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  double prob = (input.t() * this->theta).eval()(0, 0);\n  return prob;\n}\n\ndouble LogisticRegression::Predict(vec &x) {\n  double prob = this->Probablity(x);\n  if (prob >= probabilityThreshold) {\n    return 1;\n  } else {\n    return 0;\n  }\n}\n\narma::mat LogisticRegression::SigmoidFunction(arma::mat inputX) {\n  //--     1      --//\n  //-- ---------- --//\n  //-- 1 + e^(-inpuX) --//\n  return 1 / (1 + exp(-inputX));\n}\n\ndouble LogisticRegression::SelfCost() { return this->Cost(this->x); }\n\ndouble LogisticRegression::Cost(mat &inputX) {\n  this->InitializeTheta();\n  //--                    h = g(X Theta)                   --//\n  //--J(Theta) = 1/m * (-y^T log(h) - (1-y)^T log(1-h)) +lambda/2m theta^2--//\n  assert(inputX.n_cols == this->theta.n_rows);\n  vec h = this->SigmoidFunction(inputX * this->theta);\n  vec ve = (-this->y.t() * log(h)) - ((1 - y).t() * log(1 - h));\n  vec thetaWithoutFirst = this->theta;\n  thetaWithoutFirst[0] = 0;\n\n  return (1 / (float)this->ExampleNumber() * ve +\n          this->regPara / (double)this->ExampleNumber() * 2 *\n              thetaWithoutFirst.t() * thetaWithoutFirst)\n      .eval()(0, 0);\n}\n\nvec LogisticRegression::CostDerivative() {\n  vec h = this->SigmoidFunction(this->x * this->theta);\n  vec deriv = this->x.t() * (h - this->y);\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\nvoid LogisticRegression::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 LogisticRegression::InitializeTheta() {\n  if (this->trained != true || this->theta.n_rows != this->x.n_cols) {\n    // Initialize Theta\n    this->theta = zeros<vec>(this->x.n_cols);\n  }\n}\n", "meta": {"hexsha": "26feb79aa6e3ac1087073e3444ebfc5a0308b92f", "size": 3498, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LinearModel/LogisticRegression.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/LogisticRegression.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/LogisticRegression.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": 29.3949579832, "max_line_length": 78, "alphanum_fraction": 0.6255002859, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6954940098258949}}
{"text": "#include <iostream>\n#include <numeric>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"FEM/FEM1DApp.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\n#include <numeric>\n\nusing Linear = PolynomialFEMApp<1>;\nusing Quadratic = PolynomialFEMApp<2>;\n\nclass FEM1DVisualizer :public Visualizer\n{\nprotected:\n\n\tvoid evaluate()\n\t{\n\t\tint segement_ = segemnt;\n\n\t\tif (segement_ % 2 != 0)\n\t\t{\n\t\t\tsegement_ += 1;\n\t\t}\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  2 * cos(1 - x) * cos(x) + 2 * sin(1 - x) * sin(x); };\n\t\tauto d = [this](Float x) {return 1; };\n\t\tauto b = [](Float x) {return 0;\t};\n\t\tauto c = [](Float x) {return 0; };\n\n\t\tInterval interval(0.0, 1.0);\n\n\t\tinterval.SetPartitionCount(segement_);\n\n\t\tStaticFEM1DMG mg_linear(rhs, d, b, c, interval);\n\t\tLinear cg_linear(rhs, d, b, c, interval);\n\t\tmg_linear.evaluate();\n\t\tcg_linear.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tcg_val[i] = cg_linear.Value(1.0 / (Length - 1) * i);\n\t\t\tmg_val[i] = mg_linear.Value(1.0 / (Length - 1) * i);\n\n\t\t\tcg_diff[i] = cg_val[i] - precise_val[i];\n\t\t\tmg_diff[i] = mg_val[i] - precise_val[i];\n\t\t}\n\t}\n\n\tvoid Control_UI();\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tbool updated = true;\n\tint segemnt = 16;\n\tfloat epsilon = 1E-7;\n\n\tvoid error(std::vector<float>& ref, std::vector<float>& eval, Float& L_1, Float& L_2, Float& L_inf)\n\t{\n\t\tassert(ref.size() == eval.size());\n\n\t\tstd::vector<Float> minus(ref.size());\n\n\t\tfor (int i = 0; i < ref.size(); ++i)\n\t\t{\n\t\t\tminus[i] = abs(ref[i] - eval[i]);\n\t\t}\n\n\t\tL_inf = *std::max_element(minus.begin(), minus.end(), [](Float a, Float b) {return a < b; });\n\t\tL_2 = sqrt(std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a * a; }) / Float(ref.size()));\n\t\tL_1 = std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a; }) / Float(ref.size());\n\t}\n\npublic:\n\tvoid CalcAccurateRst()\n\t{\n\t\tFloat h = 1.0 / (Length - 1);\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = i * h;\n\n\t\t\tauto accurate_func = [this](Float x) {return sin(x) * sin(1 - x); };\n\n\t\t\tprecise_val[i] = accurate_func(xs[i]);\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\t//std::cout << \"Segmentations: \" << segemnt << std::endl;\n\t\t\tevaluate();\n\n\t\t\terror(precise_val, mg_val, L1, L2, L_inf);\n\n\t\t\tusing std::cout;\n\t\t\tusing std::endl;\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 / linear_L1.back()) << '&' << L2 << '&' << -log2(L2 / mg_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / mg_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tpointcount.push_back(segemnt);\n\t\t\tmg_L1.push_back(L1);\n\t\t\tmg_L2.push_back(L2);\n\t\t\tmg_Linf.push_back(L_inf);\n\t\t\terror(precise_val, cg_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 / cg_L1.back()) << '&' << L2 << '&' << -log2(L2 / cg_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / cg_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tcg_L1.push_back(L1);\n\t\t\tcg_L2.push_back(L2);\n\t\t\tcg_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 = 10001;\n\n\tstd::vector<float> xs = std::vector<float>(Length);\n\tstd::vector<float> precise_val = std::vector<float>(Length);\n\tstd::vector<float> cg_val = std::vector<float>(Length);\n\tstd::vector<float> mg_val = std::vector<float>(Length);\n\tstd::vector<float> cg_diff = std::vector<float>(Length);\n\tstd::vector<float> mg_diff = std::vector<float>(Length);\n\n\tstd::vector<float> pointcount;\n\tstd::vector<float> mg_L1;\n\tstd::vector<float> mg_L2;\n\tstd::vector<float> mg_Linf;\n\n\tstd::vector<float> cg_L1;\n\tstd::vector<float> cg_L2;\n\tstd::vector<float> cg_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, 3, 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}\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 Conjugate Gradient\", &xs[0], &cg_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Multigrid\", &xs[0], &mg_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 Multigrid\", &xs[0], &mg_diff[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM diff Conjugate Gradient\", &xs[0], &cg_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(\"Multigrid L1    Error\", &pointcount[0], &mg_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Multigrid L2    Error\", &pointcount[0], &mg_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Multigrid L_inf Error\", &pointcount[0], &mg_Linf[0], pointcount.size());\n\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L1    Error\", &pointcount[0], &cg_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L2    Error\", &pointcount[0], &cg_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L_inf Error\", &pointcount[0], &cg_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": "69e7c95749bc0c86321b4a505ac134c02d225f4a", "size": 6696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/FEM/FEM1DApp/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/FEM1DApp/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/FEM1DApp/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": 29.6283185841, "max_line_length": 201, "alphanum_fraction": 0.598864994, "num_tokens": 2339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6954666280044367}}
{"text": "#include <Eigen/Dense>\nextern \"C\"\n{\n#include \"induct.h\"\n}\n\n//#include <cmath>\n\n\n/*Starts by applying QR decomposition using the householder transform and then applies \nSVD to obtain the recompressed U and V matrices.\nThe Eigen Library is used to assist in computing QR and SVD.*/\nint SVD_QR(double **U, double **V, int m, int n, int rank, double tol)\n{\n\tusing namespace Eigen;\n\n\tMatrixXd U2(m, rank);\n\tMatrixXd V2(n, rank);\n\tMatrixXd Q_u(m, rank);\n\tMatrixXd R_u(rank, rank);\n\tMatrixXd Q_v(n, rank);\n\tMatrixXd R_v(rank, rank);\n\n\tint new_rank = 0;\n\n\tfor (int i = 0; i < rank; i++)\n\t{\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\tU2(j, i) = U[i][j];\n\t\t}\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tV2(j, i) = V[i][j];\n\t\t}\n\t}\n\n\tHouseholderQR<MatrixXd> qr(U2);\n\tQ_u = qr.householderQ()* MatrixXd::Identity(m, rank);\n\n\tR_u = Q_u.transpose()*U2;\n\n\tHouseholderQR<MatrixXd> qr2(V2);\n\t//Q_v = V2.colPivHouseholderQr().householderQ().setLength(V2.colPivHouseholderQr().nonzeroPivots());\n\tQ_v = qr2.householderQ()*MatrixXd::Identity(n, rank);\n\n\t//R_v = V2.colPivHouseholderQr().matrixR().topLeftCorner(rank, rank).template triangularView<Upper>();\n\tR_v = Q_v.transpose()*V2;\n\n\tJacobiSVD<MatrixXd> svd(R_u*R_v.transpose(), ComputeFullU | ComputeFullV);\n\t//BDCSVD<MatrixXd> svd(R_u.block(0, 0, rank, rank)*R_v.transpose().block(0, 0, rank, rank), ComputeFullU | ComputeFullV);\n\n\n\tfor (int i = 0; i < rank; i++)\n\t{\n\t\tif (svd.singularValues()(i) >= tol*svd.singularValues()(0))\n\t\t{\n\t\t\t++new_rank;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int j = 0; j < m; j++)\n\t\t\t{\n\t\t\t\tU[i][j] = 0;\n\t\t\t}\n\t\t\tfor (int j = 0; j < n; j++)\n\t\t\t{\n\t\t\t\tV[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble temp_U = 0;\n\tdouble temp_V = 0;\n\tMatrixXd U_temp(new_rank, new_rank);\n\n\n\tfor (int i = 0; i < new_rank; i++)\n\t{\n\t\tfor (int j = 0; j < new_rank; j++)\n\t\t{\n\t\t\tU_temp(i, j) = svd.matrixU()(j, i)*svd.singularValues()(i);//check\n\t\t}\n\t}\n\n\n\n\tfor (int i = 0; i < m; i++)\n\t{\n\t\tfor (int k = 0; k < new_rank; k++)\n\t\t{\n\n\t\t\tfor (int j = 0; j < new_rank; j++)\n\t\t\t{\n\t\t\t\ttemp_U += Q_u(i, j)*U_temp(k, j);\n\t\t\t}\n\t\t\tU[k][i] = temp_U;\n\t\t\ttemp_U = 0;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int k = 0; k < new_rank; k++)\n\t\t{\n\n\t\t\tfor (int j = 0; j < new_rank; j++)\n\t\t\t{\n\t\t\t\ttemp_V += Q_v(i, j)*svd.matrixV()(j, k);\n\t\t\t}\n\t\t\tV[k][i] = temp_V;\n\t\t\ttemp_V = 0;\n\t\t}\n\t}\n\treturn new_rank;\n}\n", "meta": {"hexsha": "3d5c332f83aa14a0c0b81598a965d2ba12187ddf", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SVD.cpp", "max_stars_repo_name": "Bnel13/FastHenry-ACA-", "max_stars_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-03T10:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T14:20:00.000Z", "max_issues_repo_path": "src/SVD.cpp", "max_issues_repo_name": "Bnel13/FastHenry-ACA-", "max_issues_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_issues_repo_licenses": ["MIT"], "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/SVD.cpp", "max_forks_repo_name": "Bnel13/FastHenry-ACA-", "max_forks_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T15:51:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T13:06:28.000Z", "avg_line_length": 19.4786324786, "max_line_length": 122, "alphanum_fraction": 0.5778850373, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6954591461868188}}
{"text": "//! [nbody-all]\n#include <chrono>\n#include <vector>\n#include <iostream>\n#include <cmath>\n\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/sqrt.hpp>\n\n#include <boost/simd/memory/allocator.hpp>\n\ntypedef float T;\nnamespace bs = boost::simd;\nusing pack_t = bs::pack<T>;\n\nstruct particles\n{\n  std::vector<T, bs::allocator<T>> x, y, z, m, vx, vy, vz;\n  std::size_t size_;\n\n  particles(std::size_t size) : size_(size)\n                              , x(size + pack_t::static_size)\n                              , y(size + pack_t::static_size)\n                              , z(size + pack_t::static_size)\n                              , m(size + pack_t::static_size)\n                              , vx(size + pack_t::static_size)\n                              , vy(size + pack_t::static_size)\n                              , vz(size + pack_t::static_size)\n  {}\n\n  std::size_t size() const {return size_;}\n};\n\n//! [nbody-simd]\nvoid nbody_step(particles & ps)\n{\n  pack_t grav_con {6.67408e-11};\n  pack_t epsilon {0.00125f};\n  for(std::size_t i = 0 ; i <ps.size() ; i += pack_t::static_size)\n  {\n    pack_t ax{0};\n    pack_t ay{0};\n    pack_t az{0};\n\n    pack_t pix{&ps.x[i]};\n    pack_t piy{&ps.y[i]};\n    pack_t piz{&ps.z[i]};\n\n    pack_t pim {&ps.m[ i ]};\n\n    for(std::size_t j = i + 1 ; j <ps.size() ; ++j)\n    {\n      auto pjx = bs::load<pack_t>(&ps.x[ j ]);\n      auto pjy = bs::load<pack_t>(&ps.y[ j ]);\n      auto pjz = bs::load<pack_t>(&ps.z[ j ]);\n\n      auto dx = pjx - pix;\n      auto dy = pjy - piy;\n      auto dz = pjz - piz;\n\n      auto inorm = grav_con / bs::sqrt(dx * dx + dy * dy + dz * dz + epsilon);\n      auto inorm3 = inorm * inorm *inorm;\n\n      auto fi = bs::load<pack_t>(&ps.m[ j ]) * inorm3;\n      auto fj = pim * inorm3;\n\n      ax += dx * fi;\n      ay += dy * fi;\n      az += dz * fi;\n\n      auto pjvx = bs::load<pack_t>(&ps.vx[ j ]);\n      pjvx -= dx * fj;\n      bs::store(pjvx, &ps.vx[ j ]);\n      auto pjvy = bs::load<pack_t>(&ps.vy[ j ]);\n      pjvy -= dy * fj;\n      bs::store(pjvy, &ps.vy[ j ]);\n      auto pjvz = bs::load<pack_t>(&ps.vz[ j ]);\n      pjvz -= dz * fj;\n      bs::store(pjvz, &ps.vz[ j ]);\n    }\n\n    pack_t pivx {&ps.vx[ i ]};\n    pack_t pivy {&ps.vy[ i ]};\n    pack_t pivz {&ps.vz[ i ]};\n\n    pivx += ax;\n    pivy += ay;\n    pivz += az;\n\n    pix += pivx;\n    piy += pivy;\n    piz += pivz;\n\n    bs::aligned_store(pivx, &ps.vx[ i ]);\n    bs::aligned_store(pivy, &ps.vy[ i ]);\n    bs::aligned_store(pivz, &ps.vz[ i ]);\n\n    bs::aligned_store(pix, &ps.x[ i ]);\n    bs::aligned_store(piy, &ps.y[ i ]);\n    bs::aligned_store(piz, &ps.z[ i ]);\n  }\n}\n//! [nbody-simd]\n\n//! [nbody-scalar]\nvoid nbody_step_scalar(particles & ps)\n{\n  T epsilon = 0.00125f;\n  for(std::size_t i = 0 ; i <ps.size() ; ++i)\n  {\n    T ax{0};\n    T ay{0};\n    T az{0};\n\n    T pix = ps.x[ i ];\n    T piy = ps.y[ i ];\n    T piz = ps.z[ i ];\n\n    T pim = ps.m[ i ];\n\n    for(std::size_t j = i + 1 ; j <ps.size() ; ++j)\n    {\n      T pjx = ps.x[ j ];\n      T pjy = ps.y[ j ];\n      T pjz = ps.z[ j ];\n\n      T dx = pjx - pix;\n      T dy = pjy - piy;\n      T dz = pjz - piz;\n\n      T inorm = 6.667408e-11 / std::sqrt(dx * dx + dy * dy + dz * dz + epsilon);\n\n      T fi = ps.m[ j ] * inorm * inorm * inorm;\n      T fj = pim * inorm * inorm * inorm;\n\n      ax += dx * fi;\n      ay += dy * fi;\n      az += dz * fi;\n\n      ps.vx[ j ] -= dx * fj;\n      ps.vy[ j ] -= dy * fj;\n      ps.vz[ j ] -= dz * fj;\n    }\n\n    T pivx = ps.vx[ i ];\n    T pivy = ps.vy[ i ];\n    T pivz = ps.vz[ i ];\n\n    pivx += ax;\n    pivy += ay;\n    pivz += az;\n\n    pix += pivx;\n    piy += pivy;\n    piz += pivz;\n\n    ps.vx[ i ] = pivx;\n    ps.vy[ i ] = pivy;\n    ps.vz[ i ] = pivz;\n\n    ps.x[ i ]  = pix;\n    ps.y[ i ]  = piy;\n    ps.z[ i ]  = piz;\n  }\n}\n//! [nbody-scalar]\n\nint main(int argc, char * argv[])\n{\n  std::size_t size  = 4096\n    , steps = 10;\n\n  if(argc != 3)\n  {\n    std::cerr <<\"E: Incorrect number of arguments, using \" <<size <<\" particles and \" <<steps <<\" steps.\" <<std::endl;\n  }\n  else {\n    size  = std::stoll(argv[ 1 ], 0, 10);\n    steps = std::stoll(argv[ 2 ], 0, 10);\n  }\n\n  particles ps_scalar(size);\n  particles ps_simd(size);\n\n  for(std::size_t i = 0 ; i <size ; ++i)\n  {\n    ps_scalar.x[ i ] = (0.5f + i - size / 2) * 10.0f;\n    ps_scalar.y[ i ] = 0.0f;\n    ps_scalar.z[ i ] = 0.0f;\n    ps_scalar.m[ i ] = 1.0f;\n    ps_simd.x[ i ] = (0.5f + i - size / 2) * 10.0f;\n    ps_simd.y[ i ] = 0.0f;\n    ps_simd.z[ i ] = 0.0f;\n    ps_simd.m[ i ] = 1.0f;\n  }\n\n  auto start = std::chrono::system_clock::now();\n\n  for(std::size_t step = 0 ; step <steps ; ++step)\n  {\n    nbody_step_scalar(ps_scalar);\n  }\n\n  auto stop = std::chrono::system_clock::now();\n\n  auto duration = stop - start;\n\n  std::cout <<\" Time scalar: \" <<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() <<std::endl;\n\n  start = std::chrono::system_clock::now();\n\n  for(std::size_t step = 0 ; step <steps ; ++step)\n  {\n    nbody_step(ps_simd);\n  }\n\n  stop = std::chrono::system_clock::now();\n\n  duration = stop - start;\n\n  std::cout <<\" Time SIMD: \" <<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() <<std::endl;\n\n  if(size < 64)\n  {\n    for(std::size_t i = 0 ; i <ps_scalar.size() ; ++i)\n    {\n      std::cout <<\"(\" <<ps_scalar.x[ i ] <<\", \" <<ps_scalar.y[ i ] << \", \" <<ps_scalar.z[ i ] <<\")\" <<std::endl;\n      std::cout <<\"(\" <<ps_simd.x[ i ] <<\", \" <<ps_simd.y[ i ] << \", \" <<ps_simd.z[ i ] <<\")\" <<std::endl;\n    }\n  }\n  return 0;\n}\n//! [nbody-all]\n", "meta": {"hexsha": "5ec34528703d6f9c88a48bef0a4a26573bb7206c", "size": 5564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/nbody-struct-soa-bs.cpp", "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": "doc/examples/nbody-struct-soa-bs.cpp", "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": "doc/examples/nbody-struct-soa-bs.cpp", "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": 23.5762711864, "max_line_length": 118, "alphanum_fraction": 0.4958662832, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6953398577406101}}
{"text": "#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <iostream>\n#include <chrono>\n#include <cstdlib>\n\n/*\nThis code is entirely based on the examples from Eigen. \nThis file simply creates dynamic sized symmetric positive definite matrices and calls Eigen/Cholesky and times the calls. \nEigen can use MKL if installed, but for the purposes of this test, MKL was not used as MKL was tested separately already. \nIf using Eigen in a real-life project, you may want to use Eigen with MKL. \nSee instruction on Eigen's website: https://eigen.tuxfamily.org/dox/TopicUsingIntelMKL.html\n*/\n\n\nusing namespace Eigen;\nnamespace cn = std::chrono;\ncn::time_point<cn::high_resolution_clock> startTimer()\n{\n\treturn cn::high_resolution_clock::now();\n}\n\ndouble endTimer(cn::time_point<cn::high_resolution_clock> t1)\n{\n\tauto t2 = cn::high_resolution_clock::now();\n\tcn::duration<double> diff = t2 - t1;\n\treturn diff.count() * 1000;\n}\n\nMatrixXf genRandomPosDefMatrix(int size)\n{\n\tsrand(111970);\n\t// Generate random matrix\n\tMatrixXf M(size, size);\n\tfor (int i = 0; i < size; i++)\n\t\tfor (int j = 0; j < size; j++)\n\t\t\tM(i, j) = (float)rand() / RAND_MAX;\n\t// prod = M^T M to guarantee positive-definite\n\tMatrixXf MT = M.transpose();\n\tMatrixXf prod(size, size);\n\tprod = MT * M;\n\treturn prod;\n}\n\nint main(int argc, const char * argv[])\n{\n\tint numRuns = 10;\n\tfor(int mSize = 4; mSize <= 4096; mSize *= 2)\n\t{\n\t\tMatrixXf A = genRandomPosDefMatrix(mSize);\n\t\tMatrixXf L(mSize,mSize);\n\n\t\t//Warm up run\n\t\tL = A.ldlt().matrixL(); \n\n\t\tauto t1 = startTimer();\t\n\t\tfor(int i = 0; i < numRuns; i++)\n\t\t\tL = A.llt().matrixL(); \n\t\tauto time1 = endTimer(t1)/numRuns;\n\t\t//std::cout << \"The Cholesky factor L is\" << std::endl << L << std::endl;\n\t\tstd::cout << mSize << \"\\t\\t\" << time1 << \" ms\"<< std::endl;\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "e95c3e563bf4ae8c180b13f4a5b8ae919d796778", "size": 1804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_Eigen/testEigen.cpp", "max_stars_repo_name": "pashminacameron/cholesky_benchmarking", "max_stars_repo_head_hexsha": "3c3c3d03799f1193995ef41306f0d5684e66f4b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-04T10:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-04T10:45:06.000Z", "max_issues_repo_path": "cpp_Eigen/testEigen.cpp", "max_issues_repo_name": "pashminacameron/cholesky_benchmarking", "max_issues_repo_head_hexsha": "3c3c3d03799f1193995ef41306f0d5684e66f4b7", "max_issues_repo_licenses": ["MIT"], "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_Eigen/testEigen.cpp", "max_forks_repo_name": "pashminacameron/cholesky_benchmarking", "max_forks_repo_head_hexsha": "3c3c3d03799f1193995ef41306f0d5684e66f4b7", "max_forks_repo_licenses": ["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.9253731343, "max_line_length": 122, "alphanum_fraction": 0.6807095344, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6952675895257319}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n// Eigen \u51e0\u4f55\u6a21\u5757\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <chrono>\nusing namespace std::chrono;\nusing namespace std;\n\n\n\n/****************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86 Eigen \u51e0\u4f55\u6a21\u5757\u7684\u4f7f\u7528\u65b9\u6cd5\n****************************/\n\n// TO-DO: \u641e\u6e05\u695a\u56db\u5143\u6570\u7684\u987a\u5e8f\u95ee\u9898\uff0c\u660e\u5929\u53bb\u586b\u4e0b\u3002\n\nint main ( int argc, char** argv )\n{\n    // Eigen/Geometry \u6a21\u5757\u63d0\u4f9b\u4e86\u5404\u79cd\u65cb\u8f6c\u548c\u5e73\u79fb\u7684\u8868\u793a\n    // 3D \u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u4f7f\u7528 Matrix3d \u6216 Matrix3f\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    // \u65cb\u8f6c\u5411\u91cf\u4f7f\u7528 AngleAxis, \u5b83\u5e95\u5c42\u4e0d\u76f4\u63a5\u662fMatrix\uff0c\u4f46\u8fd0\u7b97\u53ef\u4ee5\u5f53\u4f5c\u77e9\u9635\uff08\u56e0\u4e3a\u91cd\u8f7d\u4e86\u8fd0\u7b97\u7b26\uff09\n    // \u6784\u9020\u51fd\u6570\u521d\u59cb\u5316\n    Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) );     //\u6cbf Z \u8f74\u65cb\u8f6c 45 \u5ea6\n    // \u4fdd\u7559\u4e09\u4f4d\u5c0f\u6570\uff01\n    cout .precision(3);\n    // \u5c06\u65cb\u8f6c\u5411\u91cf\u7528\u77e9\u9635\u7684\u5f62\u5f0f\u8868\u5f81\u51fa\u6765\n    cout<<\"rotation matrix =\\n\"<<rotation_vector.matrix() <<endl;                //\u7528matrix()\u8f6c\u6362\u6210\u77e9\u9635\n    // \u5c06\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\u8f6c\u6362\u6210\u65cb\u8f6c\u77e9\u9635\u5f62\u5f0f\n    cout<<\"rotation matrix =\\n\"<<rotation_vector.toRotationMatrix() <<endl;\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    \n    // \u5b9a\u4e49\u4e86\u4e00\u4e2a\u5f85\u65cb\u8f6c\u7684\u5411\u91cf\n    Eigen::Vector3d v ( 1,0,0 );\n    // \u8fd9\u91cc\u5e94\u8be5\u662f\u91cd\u8f7d<<\u7684\u65f6\u5019\u5b58\u5728\u987a\u5e8f\u7684\u95ee\u9898\uff0c\u56e0\u6b64\u9700\u8981\u52a0\u4e0atranspose\u6765\u6b63\u786e\u663e\u793a\u60f3\u8981\u5c55\u793a\u7684\u5185\u5bb9\n    cout<<\"(1,0,0) before rotation = \"<<v.transpose()<<endl;\n    // \u7528 AngleAxis \u53ef\u4ee5\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    // \u91cc\u9762\u5e94\u8be5\u662f\u91cd\u8f7d\u4e86*\u8fd0\u7b97\u7b26\n    Eigen::Vector3d v_rotated = rotation_vector * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n    // \u6216\u8005\u7528\u65cb\u8f6c\u77e9\u9635\uff0c\u6548\u679c\u4e00\u6837\uff0c\u540c\u7406\u91cd\u8f7d\n    v_rotated = rotation_matrix * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    // \u6b27\u62c9\u89d2: \u53ef\u4ee5\u5c06\u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u8f6c\u6362\u6210\u6b27\u62c9\u89d2\n    // \u8fd9\u91cc\u76842,1,0\u5206\u522b\u4ee3\u6307ZYX\uff0c\u8868\u793a\u5148\u540e\u4ee5\u8fd9\u4e09\u4e2a\u4e3a\u8f74\u65cb\u8f6c\n    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles ( 2,1,0 ); // ZYX\u987a\u5e8f\uff0c\u5373roll pitch yaw\u987a\u5e8f\n    cout<<\"yaw pitch roll = \"<<euler_angles.transpose()<<endl;\n\n    // \u6b27\u5f0f\u53d8\u6362\uff0c\u5305\u62ec\u4e86\u65cb\u8f6c\u4e0e\u5e73\u79fb\n    // \u6b27\u6c0f\u53d8\u6362\u77e9\u9635\u4f7f\u7528 Eigen::Isometry\uff08\u7b49\u8ddd\uff09\n    Eigen::Isometry3d T=Eigen::Isometry3d::Identity();    // \u867d\u7136\u79f0\u4e3a3d\uff0c\u5b9e\u8d28\u4e0a\u662f4\uff0a4\u7684\u77e9\u9635\n    // \u901a\u8fc7\u8c03\u7528\u6210\u5458\u51fd\u6570\u7684\u65b9\u5f0f\u6765\u8d4b\u503c\n    T.rotate ( rotation_vector );                         // \u6309\u7167rotation_vector\u8fdb\u884c\u65cb\u8f6c\n    // pretranslate\u51fd\u6570\u7528\u4e8einital position setting\n    // Applies on the right the translation matrix represented by the vector\n    T.pretranslate ( Eigen::Vector3d ( 1,3,4 ) );         // \u628a\u5e73\u79fb\u5411\u91cf\u8bbe\u6210(1,3,4)\n    cout << \"Transform matrix = \\n\" << T.matrix() <<endl;\n\n    Eigen::Matrix3d rotation_T = T.rotation();\n    cout<<\"---- T ---- rotation matrix  =\\n\"<<rotation_T <<endl;\n    \n    Eigen::Quaterniond q_T = Eigen::Quaterniond ( rotation_T );\n    cout<<\"---- T ---- quaternion = \\n\"<<q_T.coeffs() <<endl;\n\n    Eigen::Vector3d translation_T = T.translation();\n    cout<<\"---- T ---- translation = \\n\"<<translation_T.transpose() <<endl;\n    \n\n    // \u7528\u53d8\u6362\u77e9\u9635\u8fdb\u884c\u5750\u6807\u53d8\u6362\uff0cv\u662f\uff081\uff0c0\uff0c0\uff09\n    Eigen::Vector3d v_transformed = T*v;                              // \u76f8\u5f53\u4e8eR*v+t\uff0c\u7406\u89e3\uff01\n    cout<<\"v tranformed = \"<<v_transformed.transpose()<<endl;         // \u7ed3\u679c\u6b63\u786e\n\n    // \u5bf9\u4e8e\u4eff\u5c04\u548c\u5c04\u5f71\u53d8\u6362\uff0c\u4f7f\u7528 Eigen::Affine3d \u548c Eigen::Projective3d \u5373\u53ef\uff0c\u7565\n\n    // \u56db\u5143\u6570\n    // \u53ef\u4ee5\u76f4\u63a5\u628aAngleAxis\u8d4b\u503c\u7ed9\u56db\u5143\u6570\uff0c\u53cd\u4e4b\u4ea6\u7136\uff0c\u4e5f\u5c31\u662f\u7528\u89d2\u8f74\u8f6c\u6210\u56db\u5143\u6570\n    Eigen::Quaterniond q = Eigen::Quaterniond ( rotation_vector );\n    cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;   // \u8bf7\u6ce8\u610fcoeffs\u7684\u987a\u5e8f\u662f(x,y,z,w),w\u4e3a\u5b9e\u90e8\uff0c\u524d\u4e09\u8005\u4e3a\u865a\u90e8\uff0c\u987a\u5e8f\u4e0d\u4e00\u6837\n\n    Eigen::Quaterniond q1(0.924, 0, 0, 0.383); // \u8d4b\u503c\u7684\u65f6\u5019\u662fw,x,y,z\n    cout<<\"quaternion1 = \\n\"<<q1.coeffs() <<endl;\n\n    // \u4e5f\u53ef\u4ee5\u628a\u65cb\u8f6c\u77e9\u9635\u8d4b\u7ed9\u5b83\uff0c\u7ed3\u679c\u4e00\u6837\uff01\n    Eigen::Quaterniond q2 = Eigen::Quaterniond ( rotation_matrix );\n    cout<<\"quaternion = \\n\"<<q2.coeffs() <<endl;\n\n    cout<<\"--- rotation matrix =\\n\"<<q2.toRotationMatrix() <<endl;\n\n    // \u4f7f\u7528\u56db\u5143\u6570\u65cb\u8f6c\u4e00\u4e2a\u5411\u91cf\uff0c\u4f7f\u7528\u91cd\u8f7d\u7684\u4e58\u6cd5\u5373\u53ef\n    v_rotated = q*v; // \u6ce8\u610f\u6570\u5b66\u4e0a\u662fqvq^{-1}\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl; //\u7ed3\u679c\u6b63\u786e\n\n    auto t0 = std::chrono::high_resolution_clock::now();\n    Eigen::Quaterniond quat = Eigen::Quaterniond ( T.rotation() );\n    Eigen::Vector3d pos = T.translation();\n    std::cout <<\"time is \" << std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::high_resolution_clock::now() - t0).count()<< '\\n';\n\n\n    Eigen::Matrix4d T_m = Eigen::Matrix4d::Identity(); \n    T_m.block<3, 3>(0, 0) = rotation_matrix;\n    T_m.block<3, 1>(0, 3) = Eigen::Vector3d ( 1,3,4 );\n    cout << \"Transform matrix = \\n\" << T_m <<endl;\n    cout << \"Rotation matrix= \\n\" << T_m.block<3, 3>(0, 0) << endl;\n    cout << \"Translation matrix= \\n\" << T_m.block<3, 1>(0, 3) << endl;\n\n    // Test if Quaterniond only takes normalized rotation matrix\n    cout << \"Rotation matrix= \\n\" << rotation_matrix << endl;\n    rotation_matrix *= 2.0;\n    cout << \"Rotation matrix= \\n\" << rotation_matrix << endl;\n    double scale = std::sqrt((rotation_matrix.transpose() * rotation_matrix)(0, 0));\n    Eigen::Matrix3d ret = (1. / scale) * rotation_matrix;\n    Eigen::Matrix3d rotation_matrix_quat = Eigen::Quaterniond ( ret ).normalized().toRotationMatrix();;\n    cout << \"Rotation matrix= \\n\" << rotation_matrix_quat << endl;\n    \n\n    return 0;\n}\n", "meta": {"hexsha": "54bbeae036f66a22b5e184ad6ac019f6d6d10525", "size": 4722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "billamiable/slambook", "max_stars_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:27:43.000Z", "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "billamiable/slambook", "max_issues_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "billamiable/slambook", "max_forks_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T11:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T02:59:20.000Z", "avg_line_length": 38.3902439024, "max_line_length": 147, "alphanum_fraction": 0.6249470563, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6951179328012274}}
{"text": "#pragma once\n\n#include <armadillo>\n#include \"../guia2/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(-v)) - 1;\n}\n\nvec winnerTakesAll(const vec& v)\n{\n\tif (v.n_elem == 1)\n\t\t// Si la red tiene una sola salida, aplicar la funci\u00f3n signo\n\t\treturn v(0) >= 0 ? vec{1} : vec{-1};\n\telse {\n\t\tvec result = v;\n\t\t// Si la red tiene varias salidas, asignarle +1 a \"la que gan\u00f3\"\n\t\t// y -1 a las dem\u00e1s.\n\t\tconst double maximo = max(result);\n\n\t\tresult.transform([maximo](double val) {\n            // Comparaci\u00f3n de igualdad de n\u00fameros de coma flotante\n            if (abs(val - maximo) < 1e-9)\n                return 1;\n            else\n                return -1;\n\t\t});\n\n\t\treturn result;\n\t}\n}\n\nvector<vec> salidaMulticapa(const vector<mat>& pesos,\n                            const vec& patron)\n{\n\tvector<vec> ySalidas;\n\n\t// Calculo de la salida para la primer capa\n\t{\n\t\tconst vec v = pesos[0] * join_vert(vec{-1}, patron); // agrega entrada correspondiente al sesgo\n\t\tySalidas.push_back(sigmoid(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\tconst vec v = pesos[i] * join_vert(vec{-1}, ySalidas[i - 1]); // agrega entrada correspondiente al sesgo\n\t\tySalidas.push_back(sigmoid(v));                               // TODO: ver qu\u00e9 valor le pasamos como par\u00e1metro\n\t\t                                                              // a la sigmoidea\n\t}\n\n\treturn ySalidas;\n}\n\ndouble errorCuadraticoMulticapa(const vector<mat>& pesos,\n                                const mat& patrones,\n                                const mat& salidaDeseada)\n{\n\tdouble errorCuadraticoTotal = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\t\tconst vec salidaRed = ySalidas.back();\n\n\t\tconst double errorCuadraticoPatron = sum(pow(salidaDeseada.row(n).t() - salidaRed, 2));\n\t\terrorCuadraticoTotal += errorCuadraticoPatron;\n\t}\n\n\treturn errorCuadraticoTotal;\n}\n\ndouble errorClasificacionMulticapa(const vector<mat>& pesos,\n                                   const mat& patrones,\n                                   const mat& salidaDeseada)\n{\n\tint errores = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\n\t\tconst vec salidaRed = winnerTakesAll(ySalidas.back()); // fija los valores en -1 o 1.\n\n\t\tif (any(salidaRed.t() != salidaDeseada.row(n)))\n\t\t\t++errores;\n\t}\n\n\tdouble tasaError = static_cast<double>(errores) / patrones.n_rows * 100;\n\n\treturn tasaError;\n}\n\ndouble errorClasificacionMulticapa(const vector<mat>& pesos,\n                                   const mat& datos)\n{\n\tconst int nEntradas = pesos.front().n_cols - 1;\n\tconst int nSalidas = pesos.back().n_rows;\n\tif (nEntradas + nSalidas != int(datos.n_cols))\n\t\tthrow runtime_error(\"Est\u00e1n mal calculados el n\u00famero de entradas y salidas\");\n\n\treturn errorClasificacionMulticapa(pesos,\n\t                                   datos.head_cols(nEntradas),\n\t                                   datos.tail_cols(nSalidas));\n}\n\npair<vector<mat>, double> epocaMulticapa(const mat& patrones,\n                                         const mat& salidaDeseada,\n                                         double tasaAprendizaje,\n                                         double inercia,\n                                         vector<mat> pesos)\n{\n\t//Entrenamiento\n\tvector<mat> deltaWOld;\n\tfor (unsigned int i = 0; i < pesos.size(); ++i)\n\t\tdeltaWOld.push_back(zeros(size(pesos[i])));\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\t// Calcular las salidas para cada capa\n\t\tconst vector<vec> ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\n\t\t// Calculo del error\n\t\tconst vec error = salidaDeseada.row(n).t() - ySalidas.back();\n\n\t\t// Calculo retropropagacion\n\t\t// Calculo de gradiente error local instantaneo\n\t\tvector<vec> delta;\n\t\t// Tenemos tantos vectores de deltas como capas\n\t\tdelta.resize(ySalidas.size());\n\n\t\t// Delta de ultima capa\n\t\tdelta[delta.size() - 1] = error\n\t\t                          % (1 + ySalidas.back())\n\t\t                          % (1 - ySalidas.back());\n\t\t// Deltas de las capas anteriores\n\t\tfor (int i = ySalidas.size() - 2; i >= 0; --i) {\n\t\t\t// No participan los pesos correspondientes al sesgo en el c\u00e1lculo de los deltas\n\t\t\tconst mat pesosAux = pesos[i + 1].tail_cols(pesos[i + 1].n_cols - 1);\n\t\t\tdelta[i] = (pesosAux.t() * delta[i + 1])\n\t\t\t           % (1 + ySalidas[i])\n\t\t\t           % (1 - ySalidas[i]);\n\t\t}\n\n        // Actualizacion de pesos de todas las capas menos la primera.\n        // Si la red tiene una sola capa, no se entra ac\u00e1.\n\t\tfor (int i = pesos.size() - 1; i >= 1; --i) {\n\t\t\tconst mat deltaWnuevo = tasaAprendizaje\n\t\t\t                            * delta[i]\n\t\t\t                            * join_horiz(vec{-1}, ySalidas[i - 1].t())\n\t\t\t                        + inercia * deltaWOld[i];\n\t\t\tpesos[i] += deltaWnuevo;\n\t\t\tdeltaWOld[i] = deltaWnuevo;\n\t\t}\n\n\t\t// Actualizaci\u00f3n de pesos de la primer capa\n\t\tconst mat deltaW = tasaAprendizaje\n\t\t                       * delta[0]\n\t\t                       * join_horiz(vec{-1}, patrones.row(n))\n\t\t                   + inercia * deltaWOld[0];\n\t\tpesos[0] += deltaW;\n\t\tdeltaWOld[0] = deltaW;\n\t}\n\n\t// Calculo de Tasa de error\n\tdouble tasaError = errorClasificacionMulticapa(pesos, patrones, salidaDeseada);\n\n\treturn {pesos, tasaError};\n} // fin funcion Epoca\n\ntuple<vector<mat>, vec, vec, int> entrenarMulticapa(const EstructuraCapasRed& estructura,\n                                                    const mat& datos,\n                                                    int nEpocas,\n                                                    double tasaAprendizaje,\n                                                    double inercia,\n                                                    double toleranciaErrorClasificacion,\n                                                    long long semilla = -1)\n{\n\tconst int nSalidas = estructura(estructura.n_elem - 1);\n\tconst int nEntradas = datos.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\tconst mat salidaDeseada = datos.tail_cols(nSalidas);\n\t// Extender la matriz de patrones con la entrada correspondiente al umbral\n\tconst mat patrones = datos.head_cols(nEntradas);\n\n\t// Inicializar pesos y tasa de error\n\tvector<mat> pesos;\n\n#pragma omp critical(inicializarPesos)\n\t{\n\t\tif (semilla != -1)\n\t\t\tarma_rng::set_seed(semilla);\n\n\t\t// La primer matriz matriz de pesos tiene tantas filas como neuronas en la primer capa\n\t\t// y tantas columnas como componentes tiene la entrada, m\u00e1s la entrada correspondiente\n\t\t// al sesgo.\n\t\tpesos.push_back(randu(estructura(0), nEntradas + 1) - 0.5);\n\n\t\tfor (int i = 1; i < nCapas; ++i) {\n\t\t\t// Las siguientes matrices de pesos tienen tantas filas como neuronas en dicha capa\n\t\t\t// y tantas columnas como entradas a esa capa, que van a ser las salidas de\n\t\t\t// la capa anterior mas la entrada correspondiente al sesgo.\n\t\t\t// Las salidas de la capa anterior es igual al nro de neuronas en la capa anterior.\n\t\t\tpesos.push_back(randu(estructura(i), estructura(i - 1) + 1) - 0.5);\n\t\t}\n\t}\n\n\tdouble tasaError = 100;\n\tvec erroresClasificacion;\n\tvec erroresCuadraticos;\n\n\t// Ciclo de las epocas\n\tint epoca = 1;\n\tfor (; epoca <= nEpocas; ++epoca) {\n\t\t// Ciclo para una \u00e9poca\n\t\ttie(pesos, tasaError) = epocaMulticapa(patrones,\n\t\t                                       salidaDeseada,\n\t\t                                       tasaAprendizaje,\n\t\t                                       inercia,\n\t\t                                       pesos);\n\n\t\terroresClasificacion.insert_rows(erroresClasificacion.n_elem, vec{tasaError});\n\t\tconst double errorCuadratico = errorCuadraticoMulticapa(pesos, patrones, salidaDeseada);\n\t\terroresCuadraticos.insert_rows(epoca - 1, vec{errorCuadratico});\n\n\t\tif (tasaError <= toleranciaErrorClasificacion)\n\t\t\tbreak;\n\t}\n\t// Fin ciclo (epocas)\n\n\t// Si el bucle anterior no cort\u00f3 por tolerancia de error,\n\t// el for va a incrementar la variable una vez de m\u00e1s.\n\tif (epoca > nEpocas)\n\t\tepoca = nEpocas;\n\n\treturn make_tuple(pesos, erroresClasificacion, erroresCuadraticos, epoca);\n}\n\nstruct ParametrosMulticapa {\n\tEstructuraCapasRed estructuraRed;\n\tint nEpocas;\n\tdouble tasaAprendizaje;\n\tdouble inercia;\n\tdouble toleranciaError;\n};\n}\n\nistream& operator>>(istream& is, ic::ParametrosMulticapa& parametros)\n{\n\t// Formato:\n\t// estructura: [3 2 1]\n\t// n_epocas: 200\n\t// tasa_entrenamiento: 0.1\n\t// inercia: 0.5\n\t// parametro_sigmoidea: 1\n\t// tolerancia_error: 5\n\tstring str;\n\n\t// No chequeamos si la etiqueta de cada l\u00ednea est\u00e1 bien o no. No nos importa\n\tis >> str >> parametros.estructuraRed\n\t    >> str >> parametros.nEpocas\n\t    >> str >> parametros.tasaAprendizaje\n\t    >> str >> parametros.inercia\n\t    >> str >> parametros.toleranciaError;\n\n\t// Control b\u00e1sico de valores de par\u00e1metros\n\tif (parametros.nEpocas <= 0\n\t    || parametros.tasaAprendizaje <= 0\n\t    || parametros.toleranciaError <= 0\n\t    || parametros.toleranciaError >= 100)\n\t\tis.clear(ios::failbit);\n\n\treturn is;\n}\n", "meta": {"hexsha": "314593e87e52766fdf1c0cfd39ffd2f9de4faa6b", "size": 9156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/multicapa.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": "guia1/multicapa.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": "guia1/multicapa.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": 32.8172043011, "max_line_length": 112, "alphanum_fraction": 0.6032110092, "num_tokens": 2546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6951179311602962}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <CGAL/barycenter.h>\n#include <CGAL/Simple_cartesian.h>\n#include <boost/iterator/transform_iterator.hpp>\n\n// Typedefs.\nusing Kernel   = CGAL::Simple_cartesian<double>;\nusing Point_2  = Kernel::Point_2;\nusing VectorXd = Eigen::VectorXd;\nusing MatrixXd = Eigen::MatrixXd;\n\nusing Output_iterator =\n  std::back_insert_iterator< std::vector<double> >;\n\nint main() {\n\n  // Create a set of vertices.\n  const std::vector<Point_2> vertices = {\n    Point_2(0.0, 0.0), Point_2(0.75, 0.25), Point_2(0.5, 0.5), Point_2(0.4, -0.2) };\n\n  // Create a set of query points.\n  const std::vector<Point_2> queries = {\n    Point_2(0.2, 0.2), Point_2(0.3, 0.3), Point_2(0.4, 0.4) };\n\n  // Create a lambda function with affine coordinates.\n  // This implementation is based on the following paper:\n  // S. Waldron. Affine generalized barycentric coordinates.\n  // Jaen Journal on Approximation, 3(2):209-226, 2011.\n  // This function is a model of the `AnalyticWeights_2` concept.\n  const auto affine = [&](\n    const Point_2& query,\n    Output_iterator coordinates) {\n\n    const std::size_t n = vertices.size();\n    const auto lambda = [](const Point_2& p){ return std::make_pair(p, 1.0); };\n    const Point_2 b = CGAL::barycenter(\n      boost::make_transform_iterator(vertices.begin(), lambda),\n      boost::make_transform_iterator(vertices.end()  , lambda), Kernel());\n\n    MatrixXd V(2, n);\n    for (std::size_t i = 0; i < n; ++i) {\n      V(0, i) = vertices[i].x() - b.x();\n      V(1, i) = vertices[i].y() - b.y();\n    }\n\n    const auto A   = V.adjoint();\n    const auto mat = V * A;\n    const auto inv = mat.inverse();\n\n    Point_2 diff; VectorXd vec(2);\n    for (std::size_t i = 0; i < n; ++i) {\n      const double x = query.x() - b.x();\n      const double y = query.y() - b.y();\n      diff = Point_2(x, y);\n\n      vec(0) = V(0, i);\n      vec(1) = V(1, i);\n      const auto res = inv * vec;\n\n      *(coordinates++) =\n        diff.x() * res(0) + diff.y() * res(1) + 1.0 / double(n);\n    }\n  };\n\n  // Compute affine coordinates for all query points.\n  std::cout << std::endl << \"affine coordinates (all queries): \" << std::endl << std::endl;\n\n  std::vector<double> coordinates;\n  coordinates.reserve(4);\n  for (const auto& query : queries) {\n    coordinates.clear();\n    affine(query, std::back_inserter(coordinates));\n    for (std::size_t i = 0; i < coordinates.size() - 1; ++i) {\n      std::cout << coordinates[i] << \", \";\n    }\n    std::cout << coordinates[coordinates.size() - 1] << std::endl;\n  }\n  std::cout << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "abf8c9391853b705daebb3bb04a6334375035fa3", "size": 2587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.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": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.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": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 31.1686746988, "max_line_length": 91, "alphanum_fraction": 0.6134518748, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6950680694778688}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <tuple>\n#include <stdbool.h>\n#include <bitset>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\n\nint main(void) {\n    int ab, bc, ca;\n    cin >> ab;\n    cin >> bc;\n    cin >> ca;\n\n    // \u30d8\u30ed\u30f3\u306e\u516c\u5f0f   \n    auto s = (ab + bc + ca) / 2;\n    auto ans = sqrt(s * (s - ab) * (s - bc) * (s - ca));\n\n    cout << ans << endl; \n\n    return 0;\n}", "meta": {"hexsha": "696042fdfdbe732a4e0f1a738d89c3f139de1a6d", "size": 519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc116/a/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc116/a/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc116/a/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["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.3, "max_line_length": 56, "alphanum_fraction": 0.5857418112, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6950420926529816}}
{"text": "#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\nint main()\n{\n        // scaling \u77e9\u9635\u4e3a\u4e00\u4e2a\u5bf9\u89d2\u9635\n        //2 0\n        //0 1\n        Matrix<float, 2, 2> t = Scaling(2.0f, 1.0f);\n        std::cout << t.matrix() << std::endl;\n\n        Affine3f aux(Affine3f::Identity());\n\n        cout << aux.affine().matrix() << endl;  // aux\u662f\u4e00\u4e2a\u9f50\u6b21\u77e9\u9635\uff0c\u91c7\u7528.affine()\u5ffd\u7565\u4e86\u6700\u540e\u4e00\u884c\n\n        cout  << aux.matrix()<<endl;\n\n        Transform<double, 3, Affine> Affine_transform;     // \u4eff\u5c04\n        Affine_transform.setIdentity();\n        Transform<double, 3, Isometry> Isometry_transform;   //\u7b49\u8ddd\n        Transform<double, 3, Projective> Projective_transform; // \u5c04\u5f71\u53d8\u6362\n        Affine_transform.prerotate(AngleAxisd(3.14,Vector3d::UnitX()));\n\n\n}", "meta": {"hexsha": "d1341dc9678a698ce00ba38ced57fbdf14e69e88", "size": 742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_stars_repo_name": "Yihua-Ni/Tools", "max_stars_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_issues_repo_name": "Yihua-Ni/Tools", "max_issues_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_forks_repo_name": "Yihua-Ni/Tools", "max_forks_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_forks_repo_licenses": ["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.4814814815, "max_line_length": 80, "alphanum_fraction": 0.6051212938, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6950005065119135}}
{"text": "// #include <omi_for_c.h>\n#include <Eigen/Eigen>\n\nvoid CalcElaStiffMat(\tEigen::Ref<Eigen::Matrix<double, 6,6>> C, \n\t\t\t\t\t\tconst double &G, \n\t\t\t\t\t\tconst double &LAMBDA)\n{\n    C = Eigen::Matrix<double, 6,6>::Zero();\n    // Kelvin Voigt\n    for (int i = 0; i < 3; i++)\n    {\n\t\tC(i,i) += 2*G;\n        C(i+3,i+3) += G;\n        for (int j = 0; j < 3; j++)\n        {\n            C(i,j) += LAMBDA;\n\n        }   \n    } \n}\n\nextern \"C\" void umat(double *stress, double *statev, double *ddsdde, double *sse, double *spd,\n\t\tdouble *scd, double *rpl, double *ddsddt, double *drplde, double *drpldt,\n\t\tdouble *stran, double *dstran, double *time, double *dtime, double *temp,\n\t\tdouble *dtemp, double *predef, double *dpred, char *cmname, int *ndi,\n\t\tint *nshr, int *ntens, int *nstatv, double *props, int *nprops, \n\t\tdouble *coords, double *drot, double *pnewdt, double *celent, double *dfgrd0, \n\t\tdouble *dfgrd1, int *noel, int *npt, int *layer, int *kspt, \n\t\tint *kstep, int *kinc, short cmname_len)\n{\n\tdouble E = props[0]; //210000\n\tdouble NU = props[1]; //0.3\n\tdouble G = E/2.0/(1.0 + NU); //80769,23\n\tdouble LAMBDA = 2.0*G*NU/(1.0 - 2.0*NU);//121153,85\n\tdouble eps [6];\n\tdouble eps_trace;\n\n// Update strain\n\tfor (int i = 0; i < 6; i++)\n\t{\n\t\teps[i] = stran[i] + dstran[i];\t\n\t}\n\t\n\teps_trace = eps[0] + eps[1] + eps[2];\n\n//Calculation of the stress\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\tstress[i] = LAMBDA*eps_trace + 2.0*G*eps[i];\n\t\tstress[i+3] = G*eps[i+3];\n\t}\n\n// Calc Isotropic elastic stiffness matrix through Eigen \n// (unnessary but informative)\n\tEigen::Matrix<double, 6,6> C;\n\tCalcElaStiffMat(C, G, LAMBDA);\n\n//\tIsotropic elastic stiffness matrix ddsdde as a 36x1-Vector\n//  But first it`s Initialization\n\tfor (int i = 0; i < 6; i++)\n\t{\n\t\tfor(int j = 0; j< 6; j++)\n\t\t{\n\t\t\tddsdde[6*i+j] = 0.0; \n\t\t}\n\t}\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\tddsdde[6*i+0] \t\t\t= C(0,i);\n\t\tddsdde[6*i+1] \t\t\t= C(1,i);\n\t\tddsdde[6*i+2] \t\t\t= C(2,i);\n\t\tddsdde[6*(i+3)+(i+3)] \t= C(i+3, i+3);\n\t}\n}\n", "meta": {"hexsha": "306e27380b8a0ddfce82d86359eb2aeac36b1dff", "size": 1953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "umat.cpp", "max_stars_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_stars_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T01:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:52:16.000Z", "max_issues_repo_path": "umat.cpp", "max_issues_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_issues_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "umat.cpp", "max_forks_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_forks_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-18T07:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T05:00:04.000Z", "avg_line_length": 26.04, "max_line_length": 94, "alphanum_fraction": 0.5729646697, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6950004969950099}}
{"text": "#include <cmath>\n#include <algorithm>\n\n#include <sims/linkmodel.h>\n#include <sims/cholesky.h>\n#include <sims/svd.h>\n#include <sims/qr.h>\n#include <sims/ostr.h>\n#include <Eigen/Eigenvalues>\n\n\nstd::vector<double> compute_link_distance(const std::vector<sims::Optics::CLink> &links) {\n    std::vector<double> l_distance{};\n\n    for (const auto &link : links) {\n        l_distance.emplace_back(sims::math::distance_pathloss(link));\n    }\n\n    return l_distance;\n}\n\n\nsims::linalg::vecvec<double>\nsims::linkmodel::nearest_SPD(const sims::linalg::vecvec<double> &matrix) {\n    auto svd_res = sims::svd::svd(matrix, 20);\n\n    auto h = std::get<2>(svd_res) * std::get<0>(svd_res) * sims::linalg::transpose(std::get<2>(svd_res));\n    auto spd = (matrix + h) / 2.0;\n\n    uint32_t scalar = 1;\n    uint32_t multiplier = 1;\n    while (!sims::cholesky::is_positive_definite(spd)) {\n        auto eigen = sims::linalg::eig(spd, 30);\n        auto min_eig = eigen.values.back();\n\n        spd = spd + (-min_eig * sims::math::next_power_of_2(scalar) +\n                     (std::numeric_limits<double>::epsilon() * std::abs(min_eig))) *\n                    sims::linalg::identity(spd.size());\n\n        scalar++;\n\n    }\n\n    return spd;\n}\n\n\nsims::linalg::Eigen calc_eigen(const sims::linalg::vecvec<double> &matrix) {\n    auto s = matrix.size();\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x(s, s);\n    ::std::vector<double> values(s);\n    sims::linalg::vecvec<double> vectors;\n    vectors.resize(s, ::std::vector<double>(s));\n\n    for (auto row = 0; row < s; ++row) {\n        for (auto column = 0; column < s; ++column) {\n            x(row, column) = matrix[row][column];\n        }\n    }\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> es;\n    es.compute(x);\n\n    auto ve = es.eigenvectors();\n    auto va = es.eigenvalues();\n\n    for (auto row = 0; row < s; ++row) {\n        for (auto column = 0; column < s; ++column) {\n            vectors[row][column] = ve(row, column);\n        }\n    }\n    for (auto row = 0; row < s; ++row) {\n        values[row] = va(row);\n    }\n\n    std::sort(std::begin(values), std::end(values));\n    return sims::linalg::Eigen{vectors, values, 0, 0};\n}\n\nsims::linalg::vecvec<double> sims::linkmodel::near_pd(const sims::linalg::vecvec<double> &matrix) {\n    auto x = matrix;\n\n    while (true) {\n        auto y = x;\n        //auto eigen = sims::linalg::eig(x, 10);\n        //auto eigen = sims::qr::qr_algorithm(x);\n        auto eigen = calc_eigen(x);\n        auto q = eigen.vectors;\n        auto d = eigen.values;\n\n        std::vector<int> p;\n        auto eigen_tolerance = 1e-06 * d.front();\n        for (auto i = 0; i < d.size(); ++i) {\n            if (d[i] > eigen_tolerance)\n                p.emplace_back(i);\n        }\n\n        std::sort(p.begin(), p.end());\n        q = sims::linalg::slice_column_from_index_list(q, p);\n        auto q_t = q;\n\n        for (auto i = 0; i < p.size(); ++i) {\n            for (auto &row : q)\n                row[i] = row[i] * d[i];\n        }\n\n        x = sims::linalg::crossprod(sims::linalg::transpose(q), q_t);\n        x = sims::linalg::diag(x, 1.0);\n\n        auto diff = y - x;\n        auto conv = sims::linalg::infinity_norm(diff) / sims::linalg::infinity_norm(y);\n\n        if (conv <= 1e-07) {\n            return x;\n        }\n    }\n}\n\n\nstd::vector<double> compute_link_fading(const std::vector<sims::Optics::CLink> &links, double time = 0.0) {\n    auto corr = sims::math::generate_correlation_matrix(links);\n    /*if (!sims::cholesky::is_positive_definite(corr)) {\n        std::cout << \"ensuring spd\" << std::endl;\n        corr = sims::linkmodel::near_pd(corr);\n    }\n\n    if (!sims::cholesky::is_positive_definite(corr)) {\n        std::cout << \"near PD failed\" << std::endl;\n    }*/\n\n    auto std_deviation = std::pow(STANDARD_DEVIATION, 2);\n    auto sigma = std_deviation * corr;\n\n    /*if (!sims::cholesky::is_positive_definite(sigma)) {\n        std::cout << \"ensuring spd\" << std::endl;\n        sigma = sims::linkmodel::nearest_SPD(sigma);\n    }*/\n\n    auto autocorrelation_matrix = sims::cholesky::cholesky(sigma);\n\n    auto l_fading = autocorrelation_matrix * sims::math::generate_gaussian_vector(0.0, 1.0, links.size());\n    return common::is_equal(time, 0.0) ? l_fading : l_fading * time;\n}\n\n\nstd::vector<double>\nsims::linkmodel::compute_spatial_correlation(const std::vector<sims::Optics::CLink> &links, double time) {\n    return compute_link_fading(links, time);\n\n}\n\nstd::vector<double> sims::linkmodel::compute_temporal_correlation(const std::vector<sims::Optics::CLink> &links,\n                                                                    const double time, const double delta_time) {\n    /* TODO: Compute the temporal coefficient */\n    auto d_t = 1_km;\n    auto d_r = 1_km;\n\n    auto temporal_coefficient = std::exp(-(std::log(2) * ((d_t + d_r) / 20)));\n\n    /* compute l_fading */\n    auto l_fading = compute_link_fading(links, time);\n\n    return sqrt(1 - temporal_coefficient) + l_fading * temporal_coefficient;\n}\n\n::std::vector<double> sims::linkmodel::compute(const std::vector<sims::Optics::CLink> &links, double time) {\n    return compute_link_distance(links);// + compute_link_fading(links, time); /* TODO: + temporal*/\n}", "meta": {"hexsha": "bb12c71fdba2505391c24290fd3e416fc5b5bb11", "size": 5248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linkmodel.cpp", "max_stars_repo_name": "Joklost/sims", "max_stars_repo_head_hexsha": "36e9929fb7a3360d4de812b19d66eea542d993a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-22T12:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-22T12:24:44.000Z", "max_issues_repo_path": "src/linkmodel.cpp", "max_issues_repo_name": "Joklost/sims", "max_issues_repo_head_hexsha": "36e9929fb7a3360d4de812b19d66eea542d993a1", "max_issues_repo_licenses": ["MIT"], "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/linkmodel.cpp", "max_forks_repo_name": "Joklost/sims", "max_forks_repo_head_hexsha": "36e9929fb7a3360d4de812b19d66eea542d993a1", "max_forks_repo_licenses": ["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.2380952381, "max_line_length": 113, "alphanum_fraction": 0.5943216463, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966686936261, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6949150875738402}}
{"text": "/**\n * @file gradientflow.h\n * @brief NPDE homework GradientFlow code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"gradientflow.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <vector>\n\nnamespace GradientFlow {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::MatrixXd ButcherMatrix() {\n  Eigen::MatrixXd A(6, 5);\n  // clang-format off\n  A <<       0.25,          0.,       0.,       0.,   0.,\n    0.5,        0.25,       0.,       0.,   0.,\n    17./50.,     -1./25.,     0.25,       0.,   0.,\n    371./1360., -137./2720., 15./544.,     0.25,   0.,\n    25./24.,    -49./48., 125./16., -85./12., 0.25,\n    25./24.,    -49./48., 125./16., -85./12., 0.25;\n  // clang-format on\n  return A;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector<Eigen::VectorXd> SolveGradientFlow(const Eigen::VectorXd &d,\n                                               double lambda,\n                                               const Eigen::VectorXd &y0,\n                                               double T, unsigned int M) {\n  // initialize solution vector\n  std::vector<Eigen::VectorXd> sol(M + 1, Eigen::VectorXd::Zero(y0.size()));\n\n#if SOLUTION\n  // Define the right hand side of the ODE y' = f(y), and the Jacobian of f.\n  auto f = [d, lambda](const Eigen::VectorXd &y) {\n    Eigen::VectorXd val =\n        -2. * std::cos(y.squaredNorm()) * y - 2. * lambda * d.dot(y) * d;\n    return val;\n  };\n  auto df = [d, lambda](const Eigen::VectorXd &y) {\n    int dim = y.size();\n    Eigen::MatrixXd term1 = 4. * std::sin(y.squaredNorm()) * y * y.transpose();\n    Eigen::MatrixXd term2 =\n        -2. * std::cos(y.squaredNorm()) * Eigen::MatrixXd::Identity(dim, dim);\n    Eigen::MatrixXd term3 = -2. * lambda * d * d.transpose();\n    Eigen::MatrixXd dfval = term1 + term2 + term3;\n    return dfval;\n  };\n\n  // Split the interval [0,T] into M intervals of size h.\n  double h = T / M;\n  Eigen::VectorXd y = y0;\n  sol[0] = y;\n  // Evolve up to time T:\n  for (int i = 1; i <= M; i++) {\n    y = DiscEvolSDIRK(f, df, y, h);\n    sol[i] = y;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return sol;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace GradientFlow\n", "meta": {"hexsha": "adaa63fe475d515dfcd7b25d770ea2a08b3e4143", "size": 2239, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/GradientFlow/mastersolution/gradientflow.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/GradientFlow/mastersolution/gradientflow.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/GradientFlow/mastersolution/gradientflow.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": 29.4605263158, "max_line_length": 79, "alphanum_fraction": 0.5270209915, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.6949147325037214}}
{"text": "/*******************************************************************************\n *\n * File Name: H01indexedCSVdatabaseAlgorithms.hpp\n * Author: Richard Bruce Baxter - Copyright (c) 2021 Baxter AI (baxterai.com)\n * License: MIT License\n * Project: H01LocalConnectome\n * Requirements: see H01indexedCSVdatabase.hpp\n * Compilation: see H01indexedCSVdatabase.hpp\n * Usage: see H01indexedCSVdatabase.hpp\n * Description: H01 indexed CSV database algorithms\n * Comments:\n * /\n *******************************************************************************/\n\n#ifndef HEADER_H01indexedCSVdatabaseAlgorithms\n#define HEADER_H01indexedCSVdatabaseAlgorithms\n\n#include \"H01indexedCSVdatabase.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#ifdef INDEXED_CSV_DATABASE_ALGORITHMS\n\n//https://gist.github.com/chrisengelsma/108f7ab0a746323beaaf7d6634cf4add\n/**\n * PURPOSE:\n *\n *\tPolynomial Regression aims to fit a non-linear relationship to a set of\n *\tpoints. It approximates this by solving a series of linear equations using \n *\ta least-squares approach.\n *\n *\tWe can model the expected value y as an nth degree polynomial, yielding\n *\tthe general polynomial regression model:\n *\n *\ty = a0 + a1 * x + a2 * x^2 + ... + an * x^n\n *\n * LICENSE:\n *\n * MIT License\n * \n * Copyright (c) 2020 Chris Engelsma\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 * @author Chris Engelsma\n */\n#include <vector>\n#include <stdlib.h>\n#include <cmath>\n#include <stdexcept>\n#include \"SHAREDvars.hpp\"\n\nclass H01indexedCSVdatabaseAlgorithmsFit\n{\npublic:\n\n\tH01indexedCSVdatabaseAlgorithmsFit(void);\n\t~H01indexedCSVdatabaseAlgorithmsFit(void);\n\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_2D_POLY_REGRESSION\n\tdouble calculatePoly(int xx);\n\t#endif\n\n\tlong connectionNeuronID;\n\tint estSynapseType;\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_2D_POLY_REGRESSION\n\tdouble a;\n\tdouble b;\n\tdouble c;\n\t#endif\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_3D_LINEAR_REGRESSION\n\tvec origin;\n\tvec axis;\n\t#endif\n};\n\t\t\ntemplate <class TYPE>\nclass PolynomialRegression {\n\tpublic:\n\n\t\tPolynomialRegression();\n\t\tvirtual ~PolynomialRegression(){};\n\n\t\tbool fitIt(\n\t\t\tconst std::vector<TYPE> & x,\n\t\t\tconst std::vector<TYPE> & y,\n\t\t\tconst int & order,\n\t\t\tstd::vector<TYPE> &\tcoeffs);\n};\n\ntemplate <class TYPE>\nPolynomialRegression<TYPE>::PolynomialRegression() {};\n\ntemplate <class TYPE>\nbool PolynomialRegression<TYPE>::fitIt( \n\tconst std::vector<TYPE> & x,\n\tconst std::vector<TYPE> & y,\n\tconst int & order,\n\tstd::vector<TYPE> & coeffs)\n{\n\t// The size of xValues and yValues should be same\n\tif (x.size() != y.size()) {\n\t\tthrow std::runtime_error( \"The size of x & y arrays are different\" );\n\t\treturn false;\n\t}\n\t// The size of xValues and yValues cannot be 0, should not happen\n\tif (x.size() == 0 || y.size() == 0) {\n\t\tthrow std::runtime_error( \"The size of x or y arrays is 0\" );\n\t\treturn false;\n\t}\n\t\n\tsize_t N = x.size();\n\tint n = order;\n\tint np1 = n + 1;\n\tint np2 = n + 2;\n\tint tnp1 = 2 * n + 1;\n\tTYPE tmp;\n\n\t// X = vector that stores values of sigma(xi^2n)\n\tstd::vector<TYPE> X(tnp1);\n\tfor (int i = 0; i < tnp1; ++i) {\n\t\tX[i] = 0;\n\t\tfor (int j = 0; j < N; ++j)\n\t\t\tX[i] += (TYPE)pow(x[j], i);\n\t}\n\n\t// a = vector to store final coefficients.\n\tstd::vector<TYPE> a(np1);\n\n\t// B = normal augmented matrix that stores the equations.\n\tstd::vector<std::vector<TYPE> > B(np1, std::vector<TYPE> (np2, 0));\n\n\tfor (int i = 0; i <= n; ++i) \n\t\tfor (int j = 0; j <= n; ++j) \n\t\t\tB[i][j] = X[i + j];\n\n\t// Y = vector to store values of sigma(xi^n * yi)\n\tstd::vector<TYPE> Y(np1);\n\tfor (int i = 0; i < np1; ++i) {\n\t\tY[i] = (TYPE)0;\n\t\tfor (int j = 0; j < N; ++j) {\n\t\t\tY[i] += (TYPE)pow(x[j], i)*y[j];\n\t\t}\n\t}\n\n\t// Load values of Y as last column of B\n\tfor (int i = 0; i <= n; ++i) \n\t\tB[i][np1] = Y[i];\n\n\tn += 1;\n\tint nm1 = n-1;\n\n\t// Pivotisation of the B matrix.\n\tfor (int i = 0; i < n; ++i) \n\t\tfor (int k = i+1; k < n; ++k) \n\t\t\tif (B[i][i] < B[k][i]) \n\t\t\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\t\t\ttmp = B[i][j];\n\t\t\t\t\tB[i][j] = B[k][j];\n\t\t\t\t\tB[k][j] = tmp;\n\t\t\t\t}\n\n\t// Performs the Gaussian elimination.\n\t// (1) Make all elements below the pivot equals to zero\n\t//\t\t or eliminate the variable.\n\tfor (int i=0; i<nm1; ++i)\n\t\tfor (int k =i+1; k<n; ++k) {\n\t\t\tTYPE t = B[k][i] / B[i][i];\n\t\t\tfor (int j=0; j<=n; ++j)\n\t\t\t\tB[k][j] -= t*B[i][j];\t\t\t\t // (1)\n\t\t}\n\n\t// Back substitution.\n\t// (1) Set the variable as the rhs of last equation\n\t// (2) Subtract all lhs values except the target coefficient.\n\t// (3) Divide rhs by coefficient of variable being calculated.\n\tfor (int i=nm1; i >= 0; --i) {\n\t\ta[i] = B[i][n];\t\t\t\t\t\t\t\t\t // (1)\n\t\tfor (int j = 0; j<n; ++j)\n\t\t\tif (j != i)\n\t\t\t\ta[i] -= B[i][j] * a[j];\t\t\t // (2)\n\t\ta[i] /= B[i][i];\t\t\t\t\t\t\t\t\t// (3)\n\t}\n\n\tcoeffs.resize(a.size());\n\tfor (size_t i = 0; i < a.size(); ++i) \n\t\tcoeffs[i] = a[i];\n\n\treturn true;\n}\n\n\n//https://gist.github.com/ialhashim/0a2554076a6cf32831ca (ialhashim/fitting3D.cpp)\n\ntemplate<class Vector3>\nstd::pair < Vector3, Vector3 > best_line_from_points(const std::vector<Vector3> & c)\n{\n\t//copy coordinates to matrix in Eigen format\n\tsize_t num_atoms = c.size();\n\tEigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > centers(num_atoms, 3);\n\tfor (size_t i = 0; i < num_atoms; ++i) centers.row(i) = c[i];\n\n\tVector3 origin = centers.colwise().mean();\n\tEigen::MatrixXd centered = centers.rowwise() - origin.transpose();\n\tEigen::MatrixXd cov = centered.adjoint() * centered;\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eig(cov);\n\tVector3 axis = eig.eigenvectors().col(2).normalized();\n\n\treturn std::make_pair(origin, axis);\n}\n\n\n\n#endif\n\n#endif\n", "meta": {"hexsha": "9f215b43c4701b5f24f9348a96c303c920e44c4d", "size": 6617, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_stars_repo_name": "baxterai/H01localConnectome", "max_stars_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_issues_repo_name": "baxterai/H01localConnectome", "max_issues_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_forks_repo_name": "baxterai/H01localConnectome", "max_forks_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_forks_repo_licenses": ["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.2777777778, "max_line_length": 85, "alphanum_fraction": 0.6527127097, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6948992182504082}}
{"text": "/*\n\t1/2^n hyperspace.\n*/\n\n#ifndef __NVAR_HALFSPACE__\n#define __NVAR_HALFSPACE__\n\n#include <vector>\n#include <cmath>\n#include <stdexcept>\n#include <Eigen/Dense>\n\nnamespace sisl {\n\ttemplate<int N, class I=double>\n\tclass halfspace{\n\tpublic:\n\t\thalfspace(const Eigen::Matrix<I, Dynamic, Dynamic> &M) {\n\t\t\tthis->T = M;\n\t\t\tthis->Tinv = M.inverse();\n\t\t}\n\n\t\tbool in_halfspace(std::vector<I> x) {\n\t\t\tEigen::Matrix<I, Dynamic, 1> v(x.size());\n\t\t\tfor(int i=0; i < x.size(); i++) v(i,0) = x[i];\n\n\t\t\tv = Tinv * v; \n\t\t\tfor(int i=0; i < x.size(); i++) \n\t\t\t\tif(v(i) < (I)0)\n\t\t\t\t\treturn false;\n\t\t\treturn true;\n\n\t\t}\n\tprivate:\n\t\tEigen::Matrix<I, Dynamic, Dynamic> T, Tinv;\n\t};\n}\n\n#endif //__NVAR_HALFSPACE__", "meta": {"hexsha": "495479d867bb6b232311cd17cc2ee2381f0e60ab", "size": 687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sisl/halfspace.hpp", "max_stars_repo_name": "jjh13/dual-marching", "max_stars_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "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/sisl/halfspace.hpp", "max_issues_repo_name": "jjh13/dual-marching", "max_issues_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-05-05T04:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-08T14:57:25.000Z", "max_forks_repo_path": "include/sisl/halfspace.hpp", "max_forks_repo_name": "jjh13/dual-marching", "max_forks_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "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": 18.0789473684, "max_line_length": 58, "alphanum_fraction": 0.6128093159, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067276593032, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6947765330688958}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Example of tikhonov class with blurred sine test problem.\n */\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <unordered_map>\n#include <vector>\n\n#include <Eigen/Core>\n#include <pybind11/embed.h>\n#include <pybind11/stl.h>\n\n#include \"num_collect/regularization/explicit_l_curve.h\"\n#include \"num_collect/regularization/tikhonov.h\"\n#include \"num_prob_collect/regularization/blur_sine.h\"\n\nauto main() -> int {\n    constexpr int prec = 15;\n    std::cout << std::setprecision(prec);\n\n    using coeff_type = Eigen::MatrixXd;\n    using data_type = Eigen::VectorXd;\n    static constexpr num_collect::index_type solution_size = 60;\n    static constexpr num_collect::index_type data_size = 60;\n    constexpr double error_rate = 0.01;\n\n    // create test problem\n    const auto prob =\n        num_prob_collect::regularization::blur_sine(data_size, solution_size);\n    std::mt19937 engine;  // NOLINT\n    std::normal_distribution<double> dist{0.0,\n        std::sqrt(prob.data().squaredNorm() /\n            static_cast<double>(prob.data().size()) * error_rate)};\n    auto data_with_error = prob.data();\n    for (num_collect::index_type i = 0; i < data_with_error.size(); ++i) {\n        data_with_error(i) += dist(engine);\n    }\n\n    // solve\n    using solver_type =\n        num_collect::regularization::tikhonov<coeff_type, data_type>;\n    solver_type tikhonov;\n    tikhonov.compute(prob.coeff(), data_with_error);\n\n    using searcher_type =\n        num_collect::regularization::explicit_l_curve<solver_type>;\n    searcher_type searcher{tikhonov};\n    searcher.search();\n    Eigen::VectorXd solution;\n    searcher.solve(solution);\n    std::cout << \"Optimal parameter: \" << searcher.opt_param() << std::endl;\n    std::cout << \"Error rate: \"\n              << (solution - prob.solution()).squaredNorm() /\n            prob.solution().squaredNorm()\n              << std::endl;\n\n    // plot graphs\n    std::vector<double> param_list;\n    std::vector<std::string> type_list;\n    std::vector<double> value_list;\n    const auto [min_param, max_param] = tikhonov.param_search_region();\n    constexpr std::size_t num_samples = 101;\n    for (std::size_t i = 0; i < num_samples; ++i) {\n        const double rate =\n            static_cast<double>(i) / static_cast<double>(num_samples - 1);\n        const double param = min_param * std::pow(max_param / min_param, rate);\n\n        const double residual_norm = tikhonov.residual_norm(param);\n        param_list.push_back(param);\n        type_list.emplace_back(\"residual norm\");\n        value_list.push_back(residual_norm);\n\n        const double regularization_term = tikhonov.regularization_term(param);\n        param_list.push_back(param);\n        type_list.emplace_back(\"regularization term\");\n        value_list.push_back(regularization_term);\n\n        const double curvature_value = tikhonov.l_curve_curvature(param);\n        param_list.push_back(param);\n        type_list.emplace_back(\"curvature\");\n        value_list.push_back(curvature_value);\n\n        tikhonov.solve(param, solution);\n        const double error = (solution - prob.solution()).squaredNorm() /\n            prob.solution().squaredNorm();\n        param_list.push_back(param);\n        type_list.emplace_back(\"error rate\");\n        value_list.push_back(error);\n    }\n\n    pybind11::scoped_interpreter interpreter;\n    auto pd = pybind11::module::import(\"pandas\");\n    auto px = pybind11::module::import(\"plotly.express\");\n\n    std::unordered_map<std::string, pybind11::object> data;\n    data.try_emplace(\"param\", pybind11::cast(param_list));\n    data.try_emplace(\"type\", pybind11::cast(type_list));\n    data.try_emplace(\"value\", pybind11::cast(value_list));\n\n    auto fig = px.attr(\"line\")(pybind11::arg(\"data_frame\") = data,\n        pybind11::arg(\"x\") = \"param\", pybind11::arg(\"y\") = \"value\",\n        pybind11::arg(\"color\") = \"type\", pybind11::arg(\"log_x\") = true,\n        pybind11::arg(\"log_y\") = true);\n\n    fig.attr(\"write_html\")(\"blur_sine_tikhonov_norms.html\");\n    fig.attr(\"write_image\")(\"blur_sine_tikhonov_norms.png\");\n}\n", "meta": {"hexsha": "ea91162da2c0052594819793abcde819b183ae58", "size": 4675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4, "max_line_length": 79, "alphanum_fraction": 0.6793582888, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.694705728642979}}
{"text": "// faces_angles.cpp\n/*\n * Calculates all angles between crystal grids\n * (C) 2006 olegabr. All rights reserved.\n*/\n\n#include <iostream>\nusing std::cout; using std::endl;\n\n#include <cmath>\nusing std::sqrt;\n\n#include <vector>\nusing std::vector;\n\n#include <map>\nusing std::multimap;\n\n#include <utility>\nusing std::pair; using std::make_pair;\n\n#include <boost/array.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <point3d.h>\ntypedef point3d face_t;\n\ntypedef boost::array<face_t, 19> hkl_array;\n\nstruct face_pair\n{\n\tface_t face1;\n\tface_t face2;\n\tfriend bool operator == (face_pair const& lh, face_pair const& rh) {\n\t\treturn\n\t\t\tlh.face1 == rh.face1 &&\n\t\t\tlh.face2 == rh.face2;\n\t}\n\tfriend bool operator != (face_pair const& lh, face_pair const& rh) {\n\t\treturn !(lh == rh);\n\t}\n};\n\nstruct face_triple\n{\n\tface_t face1;\n\tface_t face2;\n\tface_t face3;\n};\n\nnamespace {\n\tdouble calc_angle(face_t const& face1, face_t const& face2)\n\t{\n\t\tdouble dCosAngle = face1 * face2 / (norm(face1) * norm(face2));\n\t\tdouble dAngleRadians = std::acos(dCosAngle);\n\t\tdouble dAngleDegrees = 180.0 - 180.0 * dAngleRadians / 3.14159265358979323F;\n\t\treturn dAngleDegrees;\n\t}\n\n\tvoid print_faces(hkl_array const& arrHKL)\n\t{\n\t\thkl_array::const_iterator iHKL = arrHKL.begin();\n\t\thkl_array::const_iterator hklEnd = arrHKL.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\thkl_array::const_iterator jHKL = iHKL;\n\t\t\tfor (++jHKL; jHKL != hklEnd; ++jHKL) {\n\t\t\t\tcout\n\t\t\t\t\t<< iHKL->x << iHKL->y << iHKL->z\n\t\t\t\t\t<< '\\t'\n\t\t\t\t\t<< jHKL->x << jHKL->y << jHKL->z\n\t\t\t\t\t<< '\\t'\n\t\t\t\t\t<< calc_angle(*iHKL, *jHKL) << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tvector< face_pair >\n\tcalc_faces(hkl_array const& arrHKL, double dAngle12, double dAngleErrorMin, double dAngleErrorMax)\n\t{\n\t\tmultimap< double/*angle error*/, face_pair > mapFaces;\n\n\t\thkl_array::const_iterator iHKL = arrHKL.begin();\n\t\thkl_array::const_iterator hklEnd = arrHKL.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\thkl_array::const_iterator jHKL = iHKL;\n\t\t\tfor (++jHKL; jHKL != hklEnd; ++jHKL) {\n\t\t\t\tdouble dAngle = calc_angle(*iHKL, *jHKL);\n\t\t\t\tdouble dAngleDelta = fabs(dAngle - dAngle12);\n\t\t\t\tif (dAngleDelta >= dAngleErrorMin && dAngleDelta <= dAngleErrorMax) {\n\t\t\t\t\tface_pair pr;\n\t\t\t\t\tpr.face1 = *iHKL;\n\t\t\t\t\tpr.face2 = *jHKL;\n\t\t\t\t\tmapFaces.insert(make_pair(dAngleDelta, pr));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvector< face_pair > vecFaces;\n\t\tvecFaces.reserve(mapFaces.size());\n\n\t\tmultimap< double, face_pair >::const_iterator iterMap = mapFaces.begin();\n\t\tmultimap< double, face_pair >::const_iterator iterMapEnd = mapFaces.end();\n\t\tfor(; iterMap != iterMapEnd; ++iterMap) {\n\t\t\tvecFaces.push_back(iterMap->second);\n\t\t}\n\n\t\treturn vecFaces;\n\t}\n\n\tvoid print_faces_pairs(vector< face_pair > const& vecFaces, double dAngle12)\n\t{\n\t\tvector< face_pair >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_pair >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tdouble dAngle = calc_angle(f1, f2);\n\t\t\tdouble dErr = fabs(dAngle - dAngle12);\n\t\t\tdErr = dErr >= 0.01 ? dErr : 0.0;\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(hkl_array const& arrHKL, double dAngle12, double dAngleErrorMin, double dAngleErrorMax)\n\t{\n\t\tvector< face_pair > vecFaces;\n\t\tvecFaces = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\t\tif (!vecFaces.empty()) {\n\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\tprint_faces_pairs(vecFaces, dAngle12);\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_triples(vector< face_triple > const& vecFaces, double dAngle12, double dAngle23)\n\t{\n\t\tvector< face_triple >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_triple >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tface_t f3 = iHKL->face3;\n\t\t\tdouble dAngle1 = calc_angle(f1, f2);\n\t\t\tdouble dAngle2 = calc_angle(f2, f3);\n\t\t\tdouble dAngle3 = calc_angle(f3, f1);\n\n\t\t\tdouble dErr1 = fabs(dAngle1 - dAngle12);\n\t\t\tdErr1 = dErr1 >= 0.01 ? dErr1 : 0.0;\n\n\t\t\tdouble dErr2 = fabs(dAngle2 - dAngle23);\n\t\t\tdErr2 = dErr2 >= 0.01 ? dErr2 : 0.0;\n\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f3.x << f3.y << f3.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle3\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(\n\t\thkl_array const& arrHKL,\n\t\tdouble dAngle12,\n\t\tdouble dAngle23,\n\t\tdouble dAngleErrorMin, double dAngleErrorMax\n\t)\n\t{\n\t\tvector< face_pair > vecFaces12;\n\t\tvecFaces12 = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\n\t\tvector< face_pair > vecFaces23;\n\t\tvecFaces23 = calc_faces(arrHKL, dAngle23, dAngleErrorMin, dAngleErrorMax);\n\n\t\tif (!vecFaces12.empty() && !vecFaces23.empty()) {\n\t\t\tvector<face_triple> vecFaceTriples;\n\n\t\t\tvector< face_pair >::const_iterator iterFacePair12 = vecFaces12.begin();\n\t\t\tvector< face_pair >::const_iterator iterFacePair12End = vecFaces12.end();\n\t\t\tfor (; iterFacePair12 != iterFacePair12End; ++iterFacePair12) {\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23 = vecFaces23.begin();\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23End = vecFaces23.end();\n\t\t\t\tfor (; iterFacePair23 != iterFacePair23End; ++iterFacePair23) {\n\t\t\t\t\tif (*iterFacePair12 != *iterFacePair23) {\n\t\t\t\t\t\tif (iterFacePair12->face1 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face1 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\tprint_faces_triples(vecFaceTriples, dAngle12, dAngle23);\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_triples(vector< face_triple > const& vecFaces, double dAngle12, double dAngle23, double dAngle31)\n\t{\n\t\tvector< face_triple >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_triple >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tface_t f3 = iHKL->face3;\n\t\t\tdouble dAngle1 = calc_angle(f1, f2);\n\t\t\tdouble dAngle2 = calc_angle(f2, f3);\n\t\t\tdouble dAngle3 = calc_angle(f3, f1);\n\n\t\t\tdouble dErr1 = fabs(dAngle1 - dAngle12);\n\t\t\tdErr1 = dErr1 >= 0.01 ? dErr1 : 0.0;\n\n\t\t\tdouble dErr2 = fabs(dAngle2 - dAngle23);\n\t\t\tdErr2 = dErr2 >= 0.01 ? dErr2 : 0.0;\n\n\t\t\tdouble dErr3 = fabs(dAngle3 - dAngle31);\n\t\t\tdErr3 = dErr3 >= 0.01 ? dErr3 : 0.0;\n\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f3.x << f3.y << f3.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle3\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr3\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(\n\t\thkl_array const& arrHKL,\n\t\tdouble dAngle12,\n\t\tdouble dAngle23,\n\t\tdouble dAngle31,\n\t\tdouble dAngleErrorMin, double dAngleErrorMax\n\t)\n\t{\n\t\tvector< face_pair > vecFaces12;\n\t\tvecFaces12 = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\n\t\tvector< face_pair > vecFaces23;\n\t\tvecFaces23 = calc_faces(arrHKL, dAngle23, dAngleErrorMin, dAngleErrorMax);\n\n\t\tif (!vecFaces12.empty() && !vecFaces23.empty()) {\n\t\t\tvector<face_triple> vecFaceTriples;\n\n\t\t\tvector< face_pair >::const_iterator iterFacePair12 = vecFaces12.begin();\n\t\t\tvector< face_pair >::const_iterator iterFacePair12End = vecFaces12.end();\n\t\t\tfor (; iterFacePair12 != iterFacePair12End; ++iterFacePair12) {\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23 = vecFaces23.begin();\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23End = vecFaces23.end();\n\t\t\t\tfor (; iterFacePair23 != iterFacePair23End; ++iterFacePair23) {\n\t\t\t\t\tif (*iterFacePair12 != *iterFacePair23) {\n\t\t\t\t\t\tif (iterFacePair12->face1 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face2, iterFacePair23->face2);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face1 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face2, iterFacePair23->face1);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face1, iterFacePair23->face2);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face1, iterFacePair23->face1);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!vecFaceTriples.empty()) {\n\t\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\t\tprint_faces_triples(vecFaceTriples, dAngle12, dAngle23, dAngle31);\n\t\t\t\tcout << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid usage()\n\t{\n\t\tcout\n\t\t\t<< \"up to 3 angles between 3 faces (in degrees):\\n\"\n\t\t\t   \"f1 f2 f3 => angle12 [angle23 [angle31]]\"\n\t\t\t<< endl;\n\t}\n}\n\nusing std::fixed;\n\nint main(int argc, char* argv[])\ntry {\n\thkl_array arrHKL =\n\t{\n\t\tface_t(1.0, 1.0, 1.0),\n\n\t\tface_t(1.0, 1.0, 0.0),\n\t\tface_t(1.0, 0.0, 1.0),\n\t\tface_t(0.0, 1.0, 1.0),\n\n\t\tface_t(1.0, 0.0, 0.0),\n\t\tface_t(0.0, 0.0, 1.0),\n\t\tface_t(0.0, 1.0, 0.0),\n\n\t\tface_t(1.0, 1.0, 2.0),\n\t\tface_t(2.0, 1.0, 1.0),\n\t\tface_t(1.0, 2.0, 1.0),\n\n\t\tface_t(2.0, 1.0, 0.0),\n\t\tface_t(1.0, 2.0, 0.0),\n\t\tface_t(1.0, 0.0, 2.0),\n\t\tface_t(2.0, 0.0, 1.0),\n\t\tface_t(0.0, 2.0, 1.0),\n\t\tface_t(0.0, 1.0, 2.0),\n\n\t\tface_t(1.0, 2.0, 2.0),\n\t\tface_t(2.0, 1.0, 2.0),\n\t\tface_t(2.0, 2.0, 1.0)\n\t};\n\n\t//cout.precision(2);\n\t//cout << fixed;\n\n\tswitch(argc) {\n\t\tcase 1 :\n\t\t\tprint_faces(arrHKL);\n\t\t\tbreak;\n\t\tcase 2 : // angle12 in degrees\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast<double>(argv[1]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 0.0, 1.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 1.0, 2.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 2.0, 3.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 3.0, 4.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 4.0, 5.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3 : // angle12 angle23\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast<double>(argv[1]);\n\t\t\t\tdouble dAngle23 = boost::lexical_cast<double>(argv[2]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 0.0, 5.0);\n\t\t\t\t////print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 0.0, 1.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 1.0, 2.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 2.0, 3.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 3.0, 4.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 4.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4 : // angle12 angle23 angle31\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast<double>(argv[1]);\n\t\t\t\tdouble dAngle23 = boost::lexical_cast<double>(argv[2]);\n\t\t\t\tdouble dAngle31 = boost::lexical_cast<double>(argv[3]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 0.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 0.0, 1.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 1.0, 2.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 2.0, 3.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 3.0, 4.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 4.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\tusage();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\ncatch (std::exception &e) {\n\tcout << e.what() << endl;\n\treturn 1;\n}\ncatch (...) {\n\tcout << \"Unknown exception occured.\" << endl;\n\treturn 1;\n}\n", "meta": {"hexsha": "52bebdbfa2be0842d6caa0912bea49a6ec013c5a", "size": 14134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "faces_angles/faces_angles.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "faces_angles/faces_angles.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "faces_angles/faces_angles.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 30.3956989247, "max_line_length": 125, "alphanum_fraction": 0.6448988255, "num_tokens": 4943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6947057110723989}}
{"text": "#pragma once\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n\nclass HomographyModel {\n public:\n  HomographyModel(const Eigen::Matrix3d& matrix);\n  HomographyModel();\n  cv::Point2f operator()(const cv::Point2f& p) const;\n  void print() const;\n  void operator=(const HomographyModel& o);\n  HomographyModel inverse();\n  cv::Mat toMat();\n private:\n  Eigen::Matrix3d _matrix;\n};", "meta": {"hexsha": "c046003020499b11477827fd7eb5b45b8eef45de", "size": 379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/homography/homography_model.hpp", "max_stars_repo_name": "matheuscarius/project-inf573", "max_stars_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_stars_repo_licenses": ["MIT"], "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/homography/homography_model.hpp", "max_issues_repo_name": "matheuscarius/project-inf573", "max_issues_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_issues_repo_licenses": ["MIT"], "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/homography/homography_model.hpp", "max_forks_repo_name": "matheuscarius/project-inf573", "max_forks_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_forks_repo_licenses": ["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.2941176471, "max_line_length": 53, "alphanum_fraction": 0.7203166227, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.7634837689358858, "lm_q1q2_score": 0.694699222890081}}
{"text": "// The MIT License \n// (c) 2019 Daniel Williams\n\n#include <memory>\n#include <string>\n#include <iostream>\n\n#include <Eigen/Geometry>\n\n#include \"geometry/cell_value.hpp\"\n#include \"geometry/sample.hpp\"\n\nusing std::cerr;\nusing std::endl;\nusing std::make_unique;\nusing std::string;\nusing std::unique_ptr;\n\nusing Eigen::Vector2d;\n\n\nnamespace terrain::geometry {\n\ncell_value_t interpolate_linear(const Eigen::Vector2d& to, const Sample& s1, const Sample& s2){\n    if(s1.at.isApprox(s2.at)){\n        return s1.is;\n    }\n\n    // distances from query point to each interpolation point\n    const double dist1 = (s1.at - to).norm();\n    const double dist2 = (s2.at - to).norm();\n\n    // If the point is farther than from a point than the distance between the two interpolation points, \n    //     return the value at one of the end-points.\n    // This is not perfect, but it's a reasonable heuristic.\n    // ... in particular, it will return odd values at large distances\n    // ... arguably, this should return a NAN value instead -- for not-applicable\n    const double dist12 = (s1.at - s2.at).norm();\n    if(dist12 < dist1){\n        return s2.is;\n    }else if( dist12 < dist2){\n        return s1.is;\n    }\n\n    const double combined_distance = dist1 + dist2;\n    const double normdist1 = 1 - dist1 / combined_distance;\n    const double normdist2 = 1 - dist2 / combined_distance;\n    const double interp_value = (normdist1*s1.is + normdist2*s2.is);\n\n    return round(interp_value);\n}\n\ncell_value_t interpolate_bilinear(  const Eigen::Vector2d& to, \n                                    const Sample& ne,\n                                    const Sample& nw,\n                                    const Sample& sw,\n                                    const Sample& se)\n{\n    // cerr << \"    ==>>  to:    @\" << to[0] << \", \" << to[1] << endl;\n    // cerr << \"        - NE:     \" << ne.at[0] << \", \" << ne.at[1] << \" = \" << (int)ne.is << endl;\n    // cerr << \"        - NW:     \" << nw.at[0] << \", \" << nw.at[1] << \" = \" << (int)nw.is << endl;\n    // cerr << \"        - SW:     \" << sw.at[0] << \", \" << sw.at[1] << \" = \" << (int)sw.is << endl;\n    // cerr << \"        - SE:     \" << se.at[0] << \", \" << se.at[1] << \" = \" << (int)se.is << endl;\n\n    // not necessary ?\n    // // test for degenerate cases:\n    // if( &sx == &sd ){\n    //     // top or bottom border\n    //     return interpolate_linear(to, {to[0], xn.at[1]}, xn);\n    // }else if( &sy  == &sd ){\n    //     // left or right border\n    //     return interpolate_linear({yn[0], to[1]}, yn);\n    // }\n\n    // calculate full bilinear interpolation:\n    const Eigen::Vector2d upper_point = {to[0], (nw.at[1] + ne.at[1])/2};\n    const Sample upper_sample = { upper_point,\n                                  interpolate_linear(upper_point, nw, ne)};\n\n\n    const Eigen::Vector2d lower_point = {to[0], (sw.at[1] + se.at[1])/2};\n    const Sample lower_sample = { lower_point,\n                                interpolate_linear(lower_point, sw, se) };\n\n    // cerr << \"        ::Upper:    \" << upper_point[0] << \", \" << upper_point[1] << \" = \" << (int)upper_sample.is << endl;\n    // cerr << \"        ::Lower:    \" << lower_point[0] << \", \" << lower_point[1] << \" = \" << (int)lower_sample.is << endl;\n\n    return interpolate_linear(to, upper_sample, lower_sample);\n}\n\n} // namespace terrain::geometry\n", "meta": {"hexsha": "4539e45359d8969e143a2f07c8addf3d936c7df6", "size": 3339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/interpolate.cpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "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/geometry/interpolate.cpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "src/geometry/interpolate.cpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["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.2934782609, "max_line_length": 123, "alphanum_fraction": 0.5438754118, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6945918767650768}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"../src/utils.h\"\n\n// Use either Eigen or Diospyros RQ routine.\n#ifdef DIOS\n#include \"dios_rq_decomposition.h\"\nstatic const char *BACKEND = \"Dios\";\n#else\n#include \"rq_decomposition.h\"\nstatic const char *BACKEND = \"Eigen\";\n#endif\n\nusing namespace theia;\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\n\n// Copied from `util.cc` in Theia! --AS\n// Projects a 3x3 matrix to the rotation matrix in SO3 space with the closest\n// Frobenius norm. For a matrix with an SVD decomposition M = USV, the nearest\n// rotation matrix is R = UV'.\nMatrix3f ProjectToRotationMatrix(const Matrix3f& matrix) {\n  Eigen::JacobiSVD<Matrix3f> svd(matrix,\n                                 Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Matrix3f rotation_mat = svd.matrixU() * (svd.matrixV().transpose());\n\n  // The above projection will give a matrix with a determinant +1 or -1. Valid\n  // rotation matrices have a determinant of +1.\n  if (rotation_mat.determinant() < 0) {\n    rotation_mat *= -1.0;\n  }\n\n  return rotation_mat;\n}\n\n// Used as the projection matrix type.\ntypedef Eigen::Matrix<float, 3, 4> Matrix3x4f;\n\n// Generate a calibration matrix from some parameters.\nvoid IntrinsicsToCalibrationMatrix(const float focal_length,\n                                   const float skew,\n                                   const float aspect_ratio,\n                                   const float principal_point_x,\n                                   const float principal_point_y,\n                                   Matrix3f* calibration_matrix) {\n  *calibration_matrix <<\n      focal_length, skew, principal_point_x,\n      0, focal_length * aspect_ratio, principal_point_y,\n      0, 0, 1.0;\n}\n\n// Generate a projection matrix from a rotation and position.\nbool ComposeProjectionMatrix(const Matrix3f& calibration_matrix,\n                             const Vector3f& rotation,\n                             const Vector3f& position,\n                             Matrix3x4f* pmatrix) {\n  const double rotation_angle = rotation.norm();\n  if (rotation_angle == 0) {\n    pmatrix->block<3, 3>(0, 0) = Matrix3f::Identity();\n  } else {\n    pmatrix->block<3, 3>(0, 0) = Eigen::AngleAxisf(\n        rotation_angle, rotation / rotation_angle).toRotationMatrix();\n  }\n\n  pmatrix->col(3) = - (pmatrix->block<3, 3>(0, 0) *  position);\n  *pmatrix = calibration_matrix * (*pmatrix);\n  return true;\n}\n\nbool DecomposeProjectionMatrix(const Matrix3x4f pmatrix,\n                               Eigen::Matrix3f* calibration_matrix,\n                               Eigen::Vector3f* rotation,\n                               Eigen::Vector3f* position) {\n\n#ifdef DIOS\n  RQDecomposition rq(pmatrix.block<3, 3>(0, 0));\n#else\n  RQDecomposition<Eigen::Matrix3f> rq(pmatrix.block<3, 3>(0, 0));\n#endif\n\n  Eigen::Matrix3f rotation_matrix = ProjectToRotationMatrix(rq.matrixQ());\n\n  const float k_det = rq.matrixR().determinant();\n  if (k_det == 0) {\n    return false;\n  }\n\n  Eigen::Matrix3f& kmatrix = *calibration_matrix;\n  if (k_det > 0) {\n    kmatrix = rq.matrixR();\n  } else {\n    kmatrix = -rq.matrixR();\n  }\n\n  // Fix the matrix such that all internal parameters are greater than 0.\n  for (int i = 0; i < 3; ++i) {\n    if (kmatrix(i, i) < 0) {\n      kmatrix.col(i) *= -1.0;\n      rotation_matrix.row(i) *= -1.0;\n    }\n  }\n\n  // Solve for t.\n  const Eigen::Vector3f t =\n      kmatrix.triangularView<Eigen::Upper>().solve(pmatrix.col(3));\n\n  // c = - R' * t, and flip the sign according to k_det;\n  if (k_det > 0) {\n    *position = - rotation_matrix.transpose() * t;\n  } else {\n    *position = rotation_matrix.transpose() * t;\n  }\n\n  const Eigen::AngleAxisf rotation_aa(rotation_matrix);\n  *rotation = rotation_aa.angle() * rotation_aa.axis();\n\n  return true;\n}\n\nint main() {\n  int time = 0;\n\n  // Create a projection matrix from \"raw materials.\"\n  Matrix3f in_calibration;\n  IntrinsicsToCalibrationMatrix(0.3, 0.2, 0.4, 0.5, 0.6, &in_calibration);\n  Vector3f in_rotation;\n  in_rotation << 0.3, 0.7, 0.2;\n  Vector3f in_position;\n  in_position << 0.9, 0.1, 0.6;\n  Matrix3x4f random_pmatrix;\n  ComposeProjectionMatrix(in_calibration, in_rotation, in_position, &random_pmatrix);\n\n  Matrix3f calibration_matrix;\n  Vector3f rotation, position;\n\n  start_cycle_timing;\n  bool success = DecomposeProjectionMatrix(random_pmatrix,\n                                           &calibration_matrix,\n                                           &rotation,\n                                           &position);\n  stop_cycle_timing;\n  time = get_time();\n  printf(\"DecomposeProjectionMatrix - %s: %d cycles\\n\", BACKEND, time);\n\n  std::cout << \"Input:\" << std::endl << random_pmatrix << std::endl;\n  std::cout << \"Rotation:\" << std::endl << rotation << std::endl;\n  std::cout << \"Position:\" << std::endl << position << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "3da8043300d87268af8baa5ea6dff79601260989", "size": 4837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_stars_repo_name": "sgpthomas/diospyros", "max_stars_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-16T22:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T04:17:19.000Z", "max_issues_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_issues_repo_name": "sgpthomas/diospyros", "max_issues_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T15:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T19:48:43.000Z", "max_forks_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_forks_repo_name": "sgpthomas/diospyros", "max_forks_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T20:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T20:35:15.000Z", "avg_line_length": 32.0331125828, "max_line_length": 85, "alphanum_fraction": 0.6222865412, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6945918651904204}}
{"text": "#pragma once\n#include <iostream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <unordered_map>\n#include <boost/algorithm/string.hpp>\n#include <xtensor/xarray.hpp>\n#include <xtensor/xmath.hpp>\n\nusing namespace std;\n\ndouble compute_probability_from_distance(const double distance, const bool left_tail) {\n\tdouble prob;\n\tif (left_tail) {\n\t\tprob = (double) 1.0 - distance;\n\t} else {\n\t\tprob = distance;\n\t}\n\tif (isnan(prob)) {\n\t\tthrow runtime_error(\"compute_probability_from_distance: NaN values encountered\");\n\t}\n\treturn prob;\n}\n\nxt::xarray<double> compute_probabilities_from_distance(const vector<double>& distances, const bool left_tail) {\n\txt::xarray<double> probabilities = xt::zeros<double>({distances.size()});\n\tfor (int i = 0; i < distances.size(); ++i) {\n\t\tprobabilities[i] = compute_probability_from_distance(distances[i], left_tail);\n\t}\n\treturn probabilities;\n}\n\nxt::xarray<double> compute_baseline_probabilities(const xt::xarray<double>& probabilities) {\n\txt::xarray<double> baseline = xt::zeros<double>({probabilities.size()});\n\tdouble mean = xt::mean(probabilities)();\n\tfor (int j = 0; j < probabilities.size(); ++j) {\n\t\tbaseline[j] = mean;\n\t}\n\treturn baseline;\n}\n\nclass GeneProbabilies {\n\tvector<string> keys;\n\tunordered_map<string, size_t> lookup;\n\txt::xarray<double> probabilities;\n\txt::xarray<double> random_probabilities;\n\n\tpublic:\n\t\tGeneProbabilies(istream& is, const string& tail) :keys{}, lookup{} {\n\t\t\tif (tail != \"left\" && tail != \"right\") {\n\t\t\t\tthrow runtime_error(\n\t\t\t\t\t\"GeneProbabilies: tail argument must be one of left, right \"\n\t\t\t\t\t\"but got: \" + tail\n\t\t\t\t);\n\t\t\t}\n\t\t\tstring line;\n\t\t\tint i = 0;\n\t\t\tvector<double> distances;\n\t\t\twhile (getline(is, line)) {\n\t\t\t\tif (i == 0 || line.empty()) {\n\t\t\t\t\t++i;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvector<string> elements;\n\t\t\t\tboost::split(elements, line, boost::is_any_of(\",\"));\n\t\t\t\tif (elements.size() != 2) {\n\t\t\t\t\tthrow runtime_error(\n\t\t\t\t\t\t\"GeneProbabilies: 2 columns expected \"\n\t\t\t\t\t\t\"but got: \" + to_string(elements.size())\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tstring key = elements[0];\n\t\t\t\tkeys.push_back(key);\n\t\t\t\tlookup[key] = i-1;\n\n\t\t\t\tdouble distance = stod(elements[1]);\n\t\t\t\tdistances.push_back(distance);\n\t\t\t\t++i;\n\t\t\t}\n\n\t\t\tif (distances.empty()) {\n\t\t\t\tthrow runtime_error(\"GeneProbabilies: no data\");\n\t\t\t}\n\n\t\t\tprobabilities = compute_probabilities_from_distance(distances, tail == \"left\");\t\n\t\t\trandom_probabilities = compute_baseline_probabilities(probabilities);\n\t\t}\n\n\t\tdouble operator[](const string& id) {\n\t\t\treturn probabilities[lookup[id]];\n\t\t}\n\n\t\tdouble Get(const string& id, const bool random = false) {\n\t\t\tif (!random) {\n\t\t\t\treturn probabilities[lookup[id]];\n\t\t\t} else {\n\t\t\t\treturn random_probabilities[lookup[id]];\n\t\t\t}\n\t\t}\n\n\t\tsize_t IndexOf(const string& id) {\n\t\t\treturn lookup[id];\n\t\t}\n\n\t\tvector<string>& Keys() {\n\t\t\treturn keys;\n\t\t}\n\n\t\txt::xarray<double>& Values() {\n\t\t\treturn probabilities;\n\t\t}\n\n\t\txt::xarray<double>& RandomValues() {\n\t\t\treturn random_probabilities;\n\t\t}\n\n\t\tsize_t size() {\n\t\t\treturn lookup.size();\n\t\t}\n};\n\nxt::xarray<double> make_uniform_prior(const size_t n_elements) {\n\treturn xt::ones<double>({n_elements}) / n_elements;\n}\n\nxt::xarray<double> make_uniform_prior(const size_t n_rows, const size_t n_cols) {\n\treturn xt::ones<double>({n_rows, n_cols}) / n_cols;\n}\n\ndouble normalize_probability(const double& probability, const size_t& n_elements) {\n\treturn exp(log(probability) / n_elements);\n}\n", "meta": {"hexsha": "e301d51bf7d1c011b5a2826f322e82c6a6fe04d3", "size": 3383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/probability/probability_util.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/probability/probability_util.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/probability/probability_util.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2462686567, "max_line_length": 111, "alphanum_fraction": 0.6783919598, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6944231755247322}}
{"text": "#include \"utils.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <vector>\n#include <cmath>\n#include <iostream>\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\n//return f s.t. q^f<M<=q^(f+1)\nunsigned long get_f(unsigned long q, unsigned long M);\nvector<unsigned long> generate_primes(unsigned long MAX);\n\nstring PminusOneFactorizer_step1_cppfunc(string s, unsigned long M){\n    Bint n(s);\n    Bint A(\"2\");\n    if(n%A==0){\n        return A.str();\n    }\n    for(unsigned long p : generate_primes(M)){\n        unsigned long f = get_f(p, M);\n        Bint Mp = pow(Bint(p), f);\n        A = powm(A, Mp, n);\n    }\n    Bint retval = gcd(A-1, n);\n    return retval.str();\n}\n\nstring PminusOneFactorizer_step2_cppfunc(string s, unsigned long M, unsigned long L){\n    Bint n(s);\n    Bint A(\"2\");\n    if(n%A==0){\n        return A.str();\n    }\n    for(unsigned long p : generate_primes(L)){\n        if(p<M){\n            unsigned long f = get_f(p, M);\n            Bint Mp = pow(Bint(p), f);\n            A = powm(A, Mp, n);\n        }\n        else{\n            Bint AK = powm(A, p, n);\n            Bint candidate = gcd(AK-1, n);\n            if(1<candidate and candidate<n){\n                return candidate.str();\n            }\n        }\n    }\n    return \"1\";\n}\n\n\nunsigned long get_f(unsigned long q, unsigned long M){\n    unsigned long f = log(M)/log(q);\n    if(pow(q,f)==M){\n        return f-1;\n    }\n    else{\n        assert(pow(q,f)<M and M<=pow(q,f+1));\n        return f;\n    }\n}\n\nvector<unsigned long> generate_primes(unsigned long MAX){ // we have to make this more smart...\n    vector<bool> v(MAX+1, true);\n    v.at(0) = false;\n    v.at(1) = false;\n    vector<unsigned long> retval;\n    retval.clear();\n    unsigned long sqrt_MAX = (unsigned long)sqrt(MAX);\n    for(unsigned long i=2;i<=MAX;i++){\n        if(!v.at(i)){\n            continue;\n        }   \n        retval.push_back(i);\n        if(i>sqrt_MAX+1){continue;}\n        for(unsigned long k=2;k*i<=MAX;k++){\n            v.at(k*i) = false;\n        }\n    }\n    return retval;\n}", "meta": {"hexsha": "85d7b2e993096a504a983882d8d836e125d69e3a", "size": 2094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PminusOneFactorizer_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/PminusOneFactorizer_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/PminusOneFactorizer_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": 25.2289156627, "max_line_length": 95, "alphanum_fraction": 0.553008596, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6944231732419998}}
{"text": "//==============================================================================\r\n//         Copyright 2011-2014     Karsten Ahnert\r\n//         Copyright 2011-2014     Mario Mulansky\r\n//         Copyright 2014          LRI    UMR 8623 CNRS/Univ Paris Sud XI\r\n//         Copyright 2014          NumScale SAS\r\n//\r\n//          Distributed under the Boost Software License, Version 1.0.\r\n//                 See accompanying file LICENSE.txt or copy at\r\n//                     http://www.boost.org/LICENSE_1_0.txt\r\n//==============================================================================\r\n\r\n#include <iostream>\r\n#include <utility>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\n#ifndef M_PI //not there on windows\r\n#define M_PI 3.141592653589793 //...\r\n#endif\r\n\r\n#include <boost/random.hpp>\r\n#include <boost/dispatch/meta/as_integer.hpp>\r\n\r\n#include <nt2/include/functions/cos.hpp>\r\n#include <nt2/include/functions/sin.hpp>\r\n#include <nt2/include/functions/atan2.hpp>\r\n#include <nt2/table.hpp>\r\n#include <nt2/include/functions/zeros.hpp>\r\n#include <nt2/include/functions/sum.hpp>\r\n#include <nt2/include/functions/mean.hpp>\r\n#include <nt2/arithmetic/include/functions/hypot.hpp>\r\n#include <nt2/include/functions/tie.hpp>\r\n\r\n#include <boost/numeric/odeint/external/nt2/nt2_algebra_dispatcher.hpp>\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntemplate <typename container_type, typename T>\r\npair< T, T > calc_mean_field( const container_type &x )\r\n\r\n{\r\n  T cos_sum = 0.0 , sin_sum = 0.0;\r\n\r\n  nt2::tie(cos_sum,sin_sum) = nt2::tie(nt2::mean( nt2::cos(x) ), nt2::mean( nt2::sin(x) ));\r\n\r\n  T K = nt2::hypot(sin_sum,cos_sum);\r\n  T Theta = nt2::atan2( sin_sum , cos_sum );\r\n\r\n  return make_pair( K , Theta );\r\n}\r\n\r\ntemplate <typename container_type, typename T>\r\nstruct phase_ensemble\r\n{\r\n  typedef typename boost::dispatch::meta::as_integer<T,unsigned>::type int_type;\r\n  container_type m_omega;\r\n  T m_epsilon;\r\n\r\n  phase_ensemble( const int_type n , T g = 1.0 , T epsilon = 1.0 )\r\n  : m_epsilon( epsilon )\r\n  {\r\n    m_omega = nt2::zeros(nt2::of_size(n), nt2::meta::as_<T>());\r\n    create_frequencies( g );\r\n  }\r\n\r\n  void create_frequencies( T g )\r\n  {\r\n    boost::mt19937 rng;\r\n    boost::cauchy_distribution<> cauchy( 0.0 , g );\r\n    boost::variate_generator< boost::mt19937&, boost::cauchy_distribution<> > gen( rng , cauchy );\r\n    generate( m_omega.begin() , m_omega.end() , gen );\r\n}\r\n\r\n  void set_epsilon( T epsilon ) { m_epsilon = epsilon; }\r\n\r\n  T get_epsilon( void ) const { return m_epsilon; }\r\n\r\n  void operator()( const container_type &x , container_type &dxdt , T ) const\r\n  {\r\n    pair< T, T > mean = calc_mean_field<container_type,T>( x );\r\n    dxdt = m_omega +  m_epsilon * mean.first * nt2::sin( mean.second - x );\r\n  }\r\n};\r\n\r\ntemplate<typename T>\r\nstruct statistics_observer\r\n{\r\n    typedef typename boost::dispatch::meta::as_integer<T,unsigned>::type int_type;\r\n    T m_K_mean;\r\n    int_type m_count;\r\n\r\n    statistics_observer( void )\r\n    : m_K_mean( 0.0 ) , m_count( 0 ) { }\r\n\r\n    template< class State >\r\n    void operator()( const State &x , T t )\r\n    {\r\n        pair< T, T > mean = calc_mean_field<State,T>( x );\r\n        m_K_mean += mean.first;\r\n        ++m_count;\r\n    }\r\n\r\n    T get_K_mean( void ) const { return ( m_count != 0 ) ? m_K_mean / T( m_count ) : 0.0 ; }\r\n\r\n    void reset( void ) { m_K_mean = 0.0; m_count = 0; }\r\n};\r\n\r\ntemplate<typename T>\r\nstruct test_ode_table\r\n{\r\n  typedef nt2::table<T> array_type;\r\n  typedef void experiment_is_immutable;\r\n\r\n  typedef typename boost::dispatch::meta::as_integer<T,unsigned>::type int_type;\r\n\r\n  test_ode_table ( )\r\n                 : size_(16384), ensemble( size_ , 1.0 ), unif( 0.0 , 2.0 * M_PI ), gen( rng , unif ), obs()\r\n  {\r\n    x.resize(nt2::of_size(size_));\r\n  }\r\n\r\n  void operator()()\r\n  {\r\n    for( T epsilon = 0.0 ; epsilon < 5.0 ; epsilon += 0.1 )\r\n    {\r\n      ensemble.set_epsilon( epsilon );\r\n      obs.reset();\r\n\r\n      // start with random initial conditions\r\n      generate( x.begin() , x.end() , gen );\r\n      // calculate some transients steps\r\n      integrate_const( runge_kutta4< array_type, T >() , boost::ref( ensemble ) , x , T(0.0) , T(10.0) , dt );\r\n\r\n      // integrate and compute the statistics\r\n      integrate_const( runge_kutta4< array_type, T >() , boost::ref( ensemble ) , x , T(0.0) , T(100.0) , dt , boost::ref( obs ) );\r\n      cout << epsilon << \"\\t\" << obs.get_K_mean() << endl;\r\n    }\r\n  }\r\n\r\n  friend std::ostream& operator<<(std::ostream& os, test_ode_table<T> const& p)\r\n  {\r\n    return os << \"(\" << p.size() << \")\";\r\n  }\r\n\r\n  std::size_t size() const { return size_; }\r\n\r\n  private:\r\n    std::size_t size_;\r\n    phase_ensemble<array_type,T> ensemble;\r\n    boost::uniform_real<> unif;\r\n    array_type x;\r\n    boost::mt19937 rng;\r\n    boost::variate_generator< boost::mt19937&, boost::uniform_real<> > gen;\r\n    statistics_observer<T> obs;\r\n\r\n    static const T dt = 0.1;\r\n};\r\n\r\nint main()\r\n{\r\n  std::cout<< \" With T = [double] \\n\";\r\n  test_ode_table<double> test_double;\r\n  test_double();\r\n\r\n  std::cout<< \" With T = [float] \\n\";\r\n  test_ode_table<float> test_float;\r\n  test_float();\r\n}\r\n", "meta": {"hexsha": "99d307e74f74495014390d34970b0dbdc2c64566", "size": 5130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/nt2/phase_oscillator_ensemble.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/numeric/odeint/examples/nt2/phase_oscillator_ensemble.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/nt2/phase_oscillator_ensemble.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": 30.0, "max_line_length": 132, "alphanum_fraction": 0.5992202729, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6942542400604111}}
{"text": "//\n// SpecialFunctions.hpp\n//\n// Copyright (c) 2020 Shion Hosoda\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n#include<iostream>\n#include<Eigen/Dense>\n#include<Eigen/Core>\n#include <unsupported/Eigen/SpecialFunctions>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include\"utils.hpp\"\n\n\ndouble normalLogPdf(const Eigen::VectorXd &y, const Eigen::VectorXd &mu, double sigma2);\n\ndouble normalLogPdf(const Eigen::VectorXd &y, const Eigen::VectorXd &mu, const Eigen::MatrixXd &covMatrix);\n\ndouble normalPdf(const Eigen::VectorXd &y, const Eigen::VectorXd &mu, double sigma2);\n\ndouble normalPdf(const Eigen::VectorXd &y, const Eigen::VectorXd &mu, const Eigen::MatrixXd &covMatrix);\n", "meta": {"hexsha": "1f00780991b42324a1f060d3d06220989549fbbf", "size": 796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/SpecialFunctions.hpp", "max_stars_repo_name": "shion-h/Umibato", "max_stars_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-30T06:02:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T17:02:22.000Z", "max_issues_repo_path": "src/include/SpecialFunctions.hpp", "max_issues_repo_name": "shion-h/Umibato", "max_issues_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "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/include/SpecialFunctions.hpp", "max_forks_repo_name": "shion-h/Umibato", "max_forks_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T16:37:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T16:37:21.000Z", "avg_line_length": 31.84, "max_line_length": 107, "alphanum_fraction": 0.7638190955, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6942542264992458}}
{"text": "#include <iostream>\n\n#include <Eigen/Core>\n#include <catch2/catch.hpp>\n\n#include <finitediff.hpp>\n\nusing namespace fd;\n\nTEST_CASE(\"Test finite difference jacobian of linear\", \"[jacobian]\")\n{\n    int n = GENERATE(1, 2, 4, 10, 100);\n\n    // f(x) = Ax\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(n, n);\n\n    const auto f = [&](const Eigen::VectorXd x) -> Eigen::VectorXd {\n        return A * x;\n    };\n\n    Eigen::VectorXd x = Eigen::VectorXd::Random(n);\n\n    Eigen::MatrixXd jac = A;\n\n    AccuracyOrder accuracy = GENERATE(SECOND, FOURTH, SIXTH, EIGHTH);\n\n    Eigen::MatrixXd fjac;\n    finite_jacobian(x, f, fjac, accuracy);\n\n    CHECK(compare_jacobian(jac, fjac));\n}\n\nTEST_CASE(\"Test finite difference jacobian of trig\", \"[jacobian]\")\n{\n    int n = GENERATE(1, 2, 4, 10, 100);\n\n    const auto f = [&](const Eigen::VectorXd x) -> Eigen::VectorXd {\n        return x.array().sin();\n    };\n\n    Eigen::VectorXd x = Eigen::VectorXd::Random(n);\n\n    Eigen::MatrixXd jac = x.array().cos().matrix().asDiagonal();\n\n    AccuracyOrder accuracy = GENERATE(SECOND, FOURTH, SIXTH, EIGHTH);\n\n    Eigen::MatrixXd fjac;\n    finite_jacobian(x, f, fjac, accuracy);\n\n    CHECK(compare_jacobian(jac, fjac));\n}\n", "meta": {"hexsha": "37331dc24394e81ddc4f55c487c2190cadab253c", "size": 1192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_jacobian.cpp", "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": "tests/test_jacobian.cpp", "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": "tests/test_jacobian.cpp", "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": 22.9230769231, "max_line_length": 69, "alphanum_fraction": 0.6342281879, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6942436330840289}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2016, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\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#ifndef BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n\r\n#include <boost/geometry/core/coordinate_system.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n\r\n//#include <boost/geometry/arithmetic/arithmetic.hpp>\r\n#include <boost/geometry/arithmetic/cross_product.hpp>\r\n#include <boost/geometry/arithmetic/dot_product.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n\r\nnamespace boost { namespace geometry {\r\n    \r\nnamespace formula {\r\n\r\ntemplate <typename T>\r\nstruct result_spherical\r\n{\r\n    result_spherical()\r\n        : azimuth(0)\r\n        , reverse_azimuth(0)\r\n    {}\r\n\r\n    T azimuth;\r\n    T reverse_azimuth;\r\n};\r\n\r\ntemplate <typename T>\r\nstatic inline void sph_to_cart3d(T const& lon, T const& lat, T & x, T & y, T & z)\r\n{\r\n    T const cos_lat = cos(lat);\r\n    x = cos_lat * cos(lon);\r\n    y = cos_lat * sin(lon);\r\n    z = sin(lat);\r\n}\r\n\r\ntemplate <typename Point3d, typename PointSph>\r\nstatic inline Point3d sph_to_cart3d(PointSph const& point_sph)\r\n{\r\n    typedef typename coordinate_type<Point3d>::type calc_t;\r\n\r\n    calc_t const lon = get_as_radian<0>(point_sph);\r\n    calc_t const lat = get_as_radian<1>(point_sph);\r\n    calc_t x, y, z;\r\n    sph_to_cart3d(lon, lat, x, y, z);\r\n\r\n    Point3d res;\r\n    set<0>(res, x);\r\n    set<1>(res, y);\r\n    set<2>(res, z);\r\n\r\n    return res;\r\n}\r\n\r\ntemplate <typename T>\r\nstatic inline void cart3d_to_sph(T const& x, T const& y, T const& z, T & lon, T & lat)\r\n{\r\n    lon = atan2(y, x);\r\n    lat = asin(z);\r\n}\r\n\r\ntemplate <typename PointSph, typename Point3d>\r\nstatic inline PointSph cart3d_to_sph(Point3d const& point_3d)\r\n{\r\n    typedef typename coordinate_type<PointSph>::type coord_t;\r\n    typedef typename coordinate_type<Point3d>::type calc_t;\r\n\r\n    calc_t const x = get<0>(point_3d);\r\n    calc_t const y = get<1>(point_3d);\r\n    calc_t const z = get<2>(point_3d);\r\n    calc_t lonr, latr;\r\n    cart3d_to_sph(x, y, z, lonr, latr);\r\n\r\n    PointSph res;\r\n    set_from_radian<0>(res, lonr);\r\n    set_from_radian<1>(res, latr);\r\n\r\n    coord_t lon = get<0>(res);\r\n    coord_t lat = get<1>(res);\r\n\r\n    math::normalize_spheroidal_coordinates\r\n        <\r\n            typename coordinate_system<PointSph>::type::units,\r\n            coord_t\r\n        >(lon, lat);\r\n\r\n    set<0>(res, lon);\r\n    set<1>(res, lat);\r\n\r\n    return res;\r\n}\r\n\r\n// -1 right\r\n// 1 left\r\n// 0 on\r\ntemplate <typename Point3d1, typename Point3d2>\r\nstatic inline int sph_side_value(Point3d1 const& norm, Point3d2 const& pt)\r\n{\r\n    typedef typename select_coordinate_type<Point3d1, Point3d2>::type calc_t;\r\n    calc_t c0 = 0;\r\n    calc_t d = dot_product(norm, pt);\r\n    return math::equals(d, c0) ? 0\r\n        : d > c0 ? 1\r\n        : -1; // d < 0\r\n}\r\n\r\ntemplate <typename CT, bool ReverseAzimuth, typename T1, typename T2>\r\nstatic inline result_spherical<CT> spherical_azimuth(T1 const& lon1,\r\n                                                     T1 const& lat1,\r\n                                                     T2 const& lon2,\r\n                                                     T2 const& lat2)\r\n{\r\n    typedef result_spherical<CT> result_type;\r\n    result_type result;\r\n\r\n    // http://williams.best.vwh.net/avform.htm#Crs\r\n    // https://en.wikipedia.org/wiki/Great-circle_navigation\r\n    CT dlon = lon2 - lon1;\r\n\r\n    // An optimization which should kick in often for Boxes\r\n    //if ( math::equals(dlon, ReturnType(0)) )\r\n    //if ( get<0>(p1) == get<0>(p2) )\r\n    //{\r\n    //    return - sin(get_as_radian<1>(p1)) * cos_p2lat);\r\n    //}\r\n\r\n    CT const cos_dlon = cos(dlon);\r\n    CT const sin_dlon = sin(dlon);\r\n    CT const cos_lat1 = cos(lat1);\r\n    CT const cos_lat2 = cos(lat2);\r\n    CT const sin_lat1 = sin(lat1);\r\n    CT const sin_lat2 = sin(lat2);\r\n\r\n    {\r\n        // \"An alternative formula, not requiring the pre-computation of d\"\r\n        // In the formula below dlon is used as \"d\"\r\n        CT const y = sin_dlon * cos_lat2;\r\n        CT const x = cos_lat1 * sin_lat2 - sin_lat1 * cos_lat2 * cos_dlon;\r\n        result.azimuth = atan2(y, x);\r\n    }\r\n\r\n    if (ReverseAzimuth)\r\n    {\r\n        CT const y = sin_dlon * cos_lat1;\r\n        CT const x = sin_lat2 * cos_lat1 * cos_dlon - cos_lat2 * sin_lat1;\r\n        result.reverse_azimuth = atan2(y, x);\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\ntemplate <typename ReturnType, typename T1, typename T2>\r\ninline ReturnType spherical_azimuth(T1 const& lon1, T1 const& lat1,\r\n                                    T2 const& lon2, T2 const& lat2)\r\n{\r\n    return spherical_azimuth<ReturnType, false>(lon1, lat1, lon2, lat2).azimuth;\r\n}\r\n\r\ntemplate <typename T>\r\ninline T spherical_azimuth(T const& lon1, T const& lat1, T const& lon2, T const& lat2)\r\n{\r\n    return spherical_azimuth<T, false>(lon1, lat1, lon2, lat2).azimuth;\r\n}\r\n\r\ntemplate <typename T>\r\ninline int azimuth_side_value(T const& azi_a1_p, T const& azi_a1_a2)\r\n{\r\n    T const pi = math::pi<T>();\r\n    T const two_pi = math::two_pi<T>();\r\n\r\n    // instead of the formula from XTD\r\n    //calc_t a_diff = asin(sin(azi_a1_p - azi_a1_a2));\r\n\r\n    T a_diff = azi_a1_p - azi_a1_a2;\r\n    // normalize, angle in [-pi, pi]\r\n    while (a_diff > pi)\r\n        a_diff -= two_pi;\r\n    while (a_diff < -pi)\r\n        a_diff += two_pi;\r\n\r\n    // NOTE: in general it shouldn't be required to support the pi/-pi case\r\n    // because in non-cartesian systems it makes sense to check the side\r\n    // only \"between\" the endpoints.\r\n    // However currently the winding strategy calls the side strategy\r\n    // for vertical segments to check if the point is \"between the endpoints.\r\n    // This could be avoided since the side strategy is not required for that\r\n    // because meridian is the shortest path. So a difference of\r\n    // longitudes would be sufficient (of course normalized to [-pi, pi]).\r\n\r\n    // NOTE: with the above said, the pi/-pi check is temporary\r\n    // however in case if this was required\r\n    // the geodesics on ellipsoid aren't \"symmetrical\"\r\n    // therefore instead of comparing a_diff to pi and -pi\r\n    // one should probably use inverse azimuths and compare\r\n    // the difference to 0 as well\r\n\r\n    // positive azimuth is on the right side\r\n    return math::equals(a_diff, 0)\r\n        || math::equals(a_diff, pi)\r\n        || math::equals(a_diff, -pi) ? 0\r\n        : a_diff > 0 ? -1 // right\r\n        : 1; // left\r\n}\r\n\r\n} // namespace formula\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n", "meta": {"hexsha": "0f3e75e9e0a1c64f96368387413df51b8d35dc71", "size": 7057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T00:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T01:52:56.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "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": "2021-12-11T00:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:39:01.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T01:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-13T13:36:36.000Z", "avg_line_length": 31.3644444444, "max_line_length": 87, "alphanum_fraction": 0.6332719286, "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6942285997831397}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2018 - 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\n// This Miller-Rabin primality test is loosely based on\n// an adaptation of some code from Boost.Multiprecision.\n// The Boost.Multiprecision code can be found here:\n// https://www.boost.org/doc/libs/1_76_0/libs/multiprecision/doc/html/boost_multiprecision/tut/primetest.html\n\n#include <ctime>\n#include <random>\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n\n#if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <boost/multiprecision/uintwide_t_backend.hpp>\n\n#include <examples/example_uintwide_t.h>\n\nbool math::wide_integer::example008a_miller_rabin_prime()\n{\n  using wide_integer_type = boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<512U>,\n                                                          boost::multiprecision::et_off>;\n\n  boost::random::mt11213b base_gen(static_cast<typename boost::random::mt11213b::result_type>(std::clock()));\n\n  boost::random::independent_bits_engine<boost::random::mt11213b,\n                                         std::numeric_limits<wide_integer_type>::digits,\n                                         wide_integer_type>\n  gen(base_gen);\n\n  using random_engine2_type =\n    std::linear_congruential_engine<std::uint32_t, UINT32_C(48271), UINT32_C(0), UINT32_C(2147483647)>;\n\n  random_engine2_type gen2(static_cast<typename random_engine2_type::result_type>(std::clock()));\n\n  wide_integer_type p0;\n  wide_integer_type p1;\n\n  for(;;)\n  {\n    p0 = gen();\n\n    const bool miller_rabin_result = boost::multiprecision::miller_rabin_test(p0, 25U, gen2);\n\n    if(miller_rabin_result)\n    {\n      break;\n    }\n  }\n\n  for(;;)\n  {\n    p1 = gen();\n\n    const bool miller_rabin_result = boost::multiprecision::miller_rabin_test(p1, 25U, gen2);\n\n    if(miller_rabin_result)\n    {\n      break;\n    }\n  }\n\n  const wide_integer_type gd = gcd(p0, p1);\n\n  const bool result_is_ok = (   (p0 != 0U)\n                             && (p1 != 0U)\n                             && (p0 != p1)\n                             && (gd == 1U));\n\n  return result_is_ok;\n}\n\n// Enable this if you would like to activate this main() as a standalone example.\n#if 0\n\n#include <iomanip>\n#include <iostream>\n\nint main()\n{\n  const bool result_is_ok = wide_integer::example008a_miller_rabin_prime();\n\n  std::cout << \"result_is_ok: \" << std::boolalpha << result_is_ok << std::endl;\n}\n\n#endif\n\n#if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n#pragma GCC diagnostic pop\n#endif\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "387cf7181920a16aa8400fd7204256578d0b297f", "size": 3318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example008a_miller_rabin_prime.cpp", "max_stars_repo_name": "ckormanyos/wide-integer", "max_stars_repo_head_hexsha": "9f8167346c72d6375daf4114be63ac268af420cd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2018-10-14T19:14:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:29:18.000Z", "max_issues_repo_path": "examples/example008a_miller_rabin_prime.cpp", "max_issues_repo_name": "ckormanyos/wide-integer", "max_issues_repo_head_hexsha": "9f8167346c72d6375daf4114be63ac268af420cd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 152.0, "max_issues_repo_issues_event_min_datetime": "2019-05-31T07:36:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:12:30.000Z", "max_forks_repo_path": "examples/example008a_miller_rabin_prime.cpp", "max_forks_repo_name": "ckormanyos/wide-integer", "max_forks_repo_head_hexsha": "9f8167346c72d6375daf4114be63ac268af420cd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-10-14T20:50:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T01:23:24.000Z", "avg_line_length": 29.3628318584, "max_line_length": 109, "alphanum_fraction": 0.6404460518, "num_tokens": 782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702031, "lm_q2_score": 0.7577943712746407, "lm_q1q2_score": 0.6942227121199401}}
{"text": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <sstream>\n#include <unordered_map>\n#include <map>\n#include <limits>\nusing namespace std;\n\ntypedef boost::multiprecision::checked_cpp_int bigint;\n\nnamespace std {\n  template<> struct hash<bigint> {\n    size_t operator()(const bigint& x) const {\n      auto mask = bigint(numeric_limits<size_t>::max());\n      return size_t(bigint(x & mask));\n    }\n  };\n} // namespace std\n\n// Solve h = g^x [mod p], using a meet-in-the-middle attack\nint main(int argc, char** argv) {\n  if (argc <= 4) {\n    cerr << \"Not enough arguments, usage: ./middle p g h xmax\\n\"\n         << \"computes (x) s.t. h = g^x [mod p] | 0 < x < xmax\" << endl;\n  }\n\n  // read in the parameters of the problem\n  auto p = bigint(), g = bigint(), h = bigint();\n  auto xmax = uint64_t();\n  istringstream(argv[1]) >> p;\n  istringstream(argv[2]) >> g;\n  istringstream(argv[3]) >> h;\n  istringstream(argv[4]) >> xmax;\n  cerr << \"# p=\" << p << \"\\n# g=\" << g << \"\\n# h=\" << h << \"\\n# xmax=\" << xmax << endl;\n\n  // solve it\n  const auto b = uint64_t(sqrt(xmax));\n  const auto gb = powm(g, b, p);\n  cerr << \"# b=\" << b << \"\\n# gb=\" << gb << endl;\n\n  // // build a table of the lefts\n  auto lefts = unordered_map<bigint, uint64_t>();\n  for (uint64_t x1 = 0; x1 <= b; ++x1) {\n    auto gx1 = bigint(powm(g, x1, p));\n    auto lhs = (h * bigint(powm(gx1, p-2, p))) % p;\n    // cerr << lhs << endl;\n    lefts.insert(make_pair(lhs, x1));\n  }\n  // // search for a matching right\n  for (uint64_t x0 = 0; x0 <= b; ++x0) {\n    auto rhs = powm(gb, x0, p);\n    auto it = lefts.find(rhs);\n    if (it != lefts.end()) {\n      auto x1 = it->second;\n      auto x = x0 * b + x1;\n      cout << x << endl;\n      cerr << \"# Check: \" << (powm(g, x, p) == h ? \"OK\" : \"Not OK\") << endl;\n      return 0;\n    }\n  }\n  cerr << \"# No solution found\" << endl;\n  return 1;\n}\n", "meta": {"hexsha": "e96b717ef71bfe24f30cafe0fdc01d431dbd0d29", "size": 1865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crypto-013/pa5/middle.cpp", "max_stars_repo_name": "DouglasOrr/Snippets", "max_stars_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crypto-013/pa5/middle.cpp", "max_issues_repo_name": "DouglasOrr/Snippets", "max_issues_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-11T18:07:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T18:07:19.000Z", "max_forks_repo_path": "crypto-013/pa5/middle.cpp", "max_forks_repo_name": "DouglasOrr/Snippets", "max_forks_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_forks_repo_licenses": ["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.140625, "max_line_length": 87, "alphanum_fraction": 0.5544235925, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6942227019019015}}
{"text": "//\tObjective: To implement the option class that is defined in the header file: CashOrNothingOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n#include \"CashOrNothingOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble CashOrNothingOption::CallPrice() const\r\n{\r\n\treturn ::CashOrNothingCallPrice(S, K, cr, T, r, sig, b, type);\r\n}\r\n\r\ndouble CashOrNothingOption::PutPrice() const\r\n{\r\n\treturn ::CashOrNothingPutPrice(S, K, cr, T, r, sig, b, type);\r\n}\r\n\r\n\r\nvoid CashOrNothingOption::init()\t\t\t\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 1;\r\n\tcr = 10;\r\n\tr = 0.08;\r\n\tsig = 0.25;\r\n\tK = 100;\r\n\tS = 100;\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 CashOrNothingOption::copy(const CashOrNothingOption& option)\r\n{\r\n\tcr = option.cr;\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\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\nCashOrNothingOption::CashOrNothingOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nCashOrNothingOption::CashOrNothingOption(const CashOrNothingOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nCashOrNothingOption::CashOrNothingOption(const double& S1, const double& K1, const double& cr1, const double& T1, const double& r1, const double& sig1,\r\n\tconst double& b1, const string type1) : Option(), S(S1), K(K1), cr(cr1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nCashOrNothingOption::~CashOrNothingOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nCashOrNothingOption& CashOrNothingOption::operator = (const CashOrNothingOption& 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 CashOrNothingOption::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 CashOrNothingOption::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 CashOrNothingCallPrice(const double S, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d = (log(S / K) + (b - (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (cr * exp(-r * T) * cdf(standard_normal, d));\r\n}\r\n\r\ndouble CashOrNothingPutPrice(const double S, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d = (log(S / K) + (b - (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (cr * exp(-r * T) * cdf(standard_normal, -d));\r\n}\r\n\r\n", "meta": {"hexsha": "c154b3dec47eee0cad55f072bbc17256d8add8c2", "size": 3035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CashOrNothingOption.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": "CashOrNothingOption.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": "CashOrNothingOption.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": 25.0826446281, "max_line_length": 164, "alphanum_fraction": 0.6550247117, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6942214306210317}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <numeric>\n\n#include \"LinearCodeGenerator.h\"\n#include \"Math.h\"\n#include <gurobi_c++.h>\n\ntemplate<class T, class I1, class I2>\nT hamming_distance(uint32_t size, I1 b1, I2 b2)\n{\n\treturn std::inner_product(b1, b1 + size, b2, T{},\n\t\tstd::plus<T>(), std::not_equal_to<T>());\n}\n\nint getMinHammingDistance(const int q, const int k, const arma::s32_mat &G)\n{\n\tauto language = Math::generateLanguage(q, k);\n\tlanguage.erase(language.begin());\n\n\tstd::vector<arma::s32_vec> codes;\n\tcodes.reserve(language.size());\n\tfor (const auto& word : language)\n\t{\n\t\tcodes.push_back(Math::encode(word, G, q));\n\t}\n\n\tauto minDistance = std::numeric_limits<int>::max();\n\tfor (auto& codeword : codes)\n\t{\n\t\tfor (auto& codeword2 : codes)\n\t\t{\n\t\t\tconst auto distance = hamming_distance<int>(codeword.size(), codeword.begin(), codeword2.begin());\n\t\t\tif (distance > 0 && distance < minDistance)\n\t\t\t{\n\t\t\t\tminDistance = distance;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn minDistance;\n}\n\nint main()\n{\n\t/* Parameters */\n\tconstexpr int q = 7;\n\tconstexpr int k = 3;\n\tconstexpr int b = 3;\n\n\tstd::cout << \"###### Linear Code Creator ######\" << std::endl << std::endl;\n\tstd::cout << \"q = \" << q << std::endl << \"k = \" << k << std::endl << \"b = \" << b << std::endl;\n\n\tconst LinearCodeGenerator linCodeGenerator(q, k, b);\n\n\ttry\n\t{\n\t\tconst auto linCode = linCodeGenerator.generateCode();\n\n\t\tstd::cout << \"We have now following code\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tstd::cout << \"[n,k,d]_q\" << std::endl;\n\t\tstd::cout << \"[\" << linCode.n << \",\" << linCode.k << \",\" << linCode.d << \"]_\" << linCode.q << \"\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\t\tstd::cout << \"Generatormatrix G\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tlinCode.G.raw_print();\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\t\tstd::cout << \"Proof Hamming Distance\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tconst int minDistance = getMinHammingDistance(q, k, linCode.G);\n\t\tstd::cout << minDistance << \" = calculated distance\" << std::endl;\n\t\tstd::cout << linCode.d << \" = should be the distance\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\t}\n\tcatch (const GRBException& e) {\n\t\tstd::cout << \"Error code = \" << e.getErrorCode() << std::endl;\n\t\tstd::cout << e.getMessage() << std::endl;\n\t}\n\tcatch (...) {\n\t\tstd::cout << \"Exception during optimization\" << std::endl;\n\t}\n\n\tstd::cout << \"Press any key to exit...\";\n\tstd::cin.get();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "206d695cf026d8d3c4debaa33ed031716c9a710e", "size": 2762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lin-code-gen/main.cpp", "max_stars_repo_name": "ZeraPain/Coding-Theory", "max_stars_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "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": "lin-code-gen/main.cpp", "max_issues_repo_name": "ZeraPain/Coding-Theory", "max_issues_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "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": "lin-code-gen/main.cpp", "max_forks_repo_name": "ZeraPain/Coding-Theory", "max_forks_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T06:02:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-01T06:02:28.000Z", "avg_line_length": 30.3516483516, "max_line_length": 112, "alphanum_fraction": 0.5347574222, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6941480445288825}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_BestFitPlane.h\"\r\n\r\n#include <assert.h>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Dense>\r\n#include <Eigen/SVD>\r\n\r\nnamespace {\r\n\r\nEigen::Vector3f ComputeCentroid(const Eigen::MatrixXf& V)\r\n{\r\n\tassert(V.rows() == 3);\r\n\r\n\tEigen::Vector3f c(0.0f, 0.0f, 0.0f);\r\n\r\n\tfor (int i = 0; i < V.cols(); ++i) {\r\n\t\tc += V.col(i);\r\n\t}\r\n\r\n\tif (V.cols() != 0) {\r\n\t\tfloat sc = (1.0f / V.cols());\r\n\t\tc *= sc;\r\n\t}\r\n\r\n\treturn c;\r\n}\r\n\r\n\r\n} // namespace\r\n\r\nvoid Geomlib::BestFitPlane(\r\n\tconst Urho3D::Vector<Urho3D::Vector3>& point_cloud,\r\n\tUrho3D::Vector3& point,\r\n\tUrho3D::Vector3& normal\r\n)\r\n{\r\n\tusing Urho3D::Vector3;\r\n\r\n\tint num_vertices = (int)point_cloud.Size();\r\n\tif (num_vertices <= 0) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tEigen::MatrixXf V(3, num_vertices);\r\n\tfor (int i = 0; i < num_vertices; ++i) {\r\n\t\tVector3 vec = point_cloud[i];\r\n\t\tV.col(i) = Eigen::Vector3f(vec.x_, vec.y_, vec.z_);\r\n\t}\r\n\r\n\tEigen::Vector3f c = ComputeCentroid(V);\r\n\r\n\tEigen::MatrixXf NV = V;\r\n\tfor (int i = 0; i < NV.cols(); ++i) {\r\n\t\tNV.col(i) -= c;\r\n\t}\r\n\r\n\tEigen::JacobiSVD<Eigen::MatrixXf> svd(NV, Eigen::DecompositionOptions::ComputeThinU);\r\n\r\n\tEigen::MatrixXf U = svd.matrixU();\r\n\tassert(U.rows() == 3 && U.cols() == 3);\r\n\r\n\tnormal = Vector3(U(0, 2), U(1, 2), U(2, 2));\r\n\tpoint = Vector3(c(0), c(1), c(2));\r\n}\r\n\r\nvoid Geomlib::BestFitPlane(\r\n\tconst Urho3D::VariantVector& vertex_list,\r\n\tUrho3D::Vector3& point,\r\n\tUrho3D::Vector3& normal\r\n)\r\n{\r\n\tusing Urho3D::Vector;\r\n\tusing Urho3D::Vector3;\r\n\r\n\tVector<Vector3> point_cloud;\r\n\tfor (int i = 0; i < vertex_list.Size(); ++i) {\r\n\t\tpoint_cloud.Push(vertex_list[i].GetVector3());\r\n\t}\r\n\r\n\tBestFitPlane(point_cloud, point, normal);\r\n}\r\n", "meta": {"hexsha": "b1e5b66aa7f5066795f25e01dfdfe551f8c306d9", "size": 2796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 26.6285714286, "max_line_length": 87, "alphanum_fraction": 0.662732475, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6940902642395762}}
{"text": "/*\n * generate_data.cpp\n * Date: 2016-02-26\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n * Copyright: Karsten Ahnert\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#include \"generate_data.hpp\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n\n#include <iostream>\n#include <cmath>\n#include <cassert>\n\nnamespace dynsys {\n    \nusing stepper_type = boost::numeric::odeint::runge_kutta4< state_type > ;\n    \n    \ndata_type generate_data( void )\n{\n    data_type data;\n    state_type x {{ 10.0 , 10.0 , 10.0 }};\n    state_type dxdt;\n    double dt = 0.1;\n    stepper_type stepper;\n    for( double t = 0.0 ; t<100.0 ; t+= dt )\n    {\n        lorenz( x , dxdt , t );\n        data.first.push_back( x );\n        data.second.push_back( dxdt );\n        stepper.do_step( lorenz , x , dxdt , t , dt );\n    }\n    return data;\n}\n\nvoid plot_data( data_type const& data , std::ostream& out )\n{\n    for( size_t i=0 ; i<data.first.size() ; ++i )\n    {\n        state_type const& x = data.first[i];\n        state_type const& dxdt = data.second[i];\n        out << x[0] << \" \" << x[1] << \" \" << x[2] << \" \" << dxdt[0] << \" \" << dxdt[1] << \" \" << dxdt[2] << \"\\n\";\n    }\n}\n\nnorm_type normalize_data( state_container& data )\n{\n    norm_type means;\n    for( size_t j=0 ; j<dim ; ++j )\n    {\n        means[j].first = means[j].second = 0.0;\n    }\n    \n    for( size_t i=0 ; i<data.size() ; ++i )\n    {\n        assert( data[i].size() == dim );\n        for( size_t j=0 ; j<dim ; ++j )\n        {\n            means[j].first += data[i][j];\n            means[j].second += data[i][j] * data[i][j];\n        }\n    }\n    double len = double( data.size() );\n    for( size_t j=0 ; j<dim ; ++j )\n    {\n        double mean = means[j].first / len;\n        double sqmean = means[j].second / len;\n        means[j].first = mean;\n        means[j].second = std::sqrt( sqmean - mean * mean );\n    }\n    for( size_t i=0 ; i<data.size() ; ++i )\n    {\n        for( size_t j=0 ; j<dim ; ++j )\n        {\n            data[i][j] = ( data[i][j] - means[j].first ) / means[j].second;\n        }\n    }\n    \n    return means;\n}\n\n\n} // namespace dynsys", "meta": {"hexsha": "347843f778e093fbe65c8a311d7c299293e94f7a", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dynamical_system/generate_data.cpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "examples/dynamical_system/generate_data.cpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "examples/dynamical_system/generate_data.cpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 25.3222222222, "max_line_length": 112, "alphanum_fraction": 0.5414655551, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6940902494504272}}
{"text": "//c\r\n#include <ctime>\r\n//c++\r\n#include <iostream>\r\n#include <stdexcept>\r\n//eigen\r\n#include <Eigen/Dense>\r\n\r\ndouble test_eigensolver_values(int b, int e, int s){\r\n\ttypedef Eigen::MatrixXf MatType;\r\n\tdouble sum=0;\r\n\tfor(int i=b; i<=e; i+=s){\r\n\t\tclock_t start_=std::clock();\r\n\t\tMatType mat=MatType::Random(i,i);\r\n\t\tEigen::EigenSolver<MatType> solver(mat);\r\n\t\tsum+=solver.eigenvalues()[0].real();\r\n\t\tclock_t stop_=std::clock();\r\n\t\tconst double time=((double)(stop_-start_))/CLOCKS_PER_SEC;\r\n\t\tstd::cout<<\"time[\"<<i<<\"] = \"<<time<<\"\\n\";\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\ndouble test_selfadjointeigensolver_values(int b, int e, int s){\r\n\ttypedef Eigen::MatrixXf MatType;\r\n\tdouble sum=0;\r\n\tfor(int i=b; i<=e; i+=s){\r\n\t\tclock_t start_=std::clock();\r\n\t\tMatType mat=MatType::Random(i,i);\r\n\t\tEigen::SelfAdjointEigenSolver<MatType> solver(mat);\r\n\t\tsum+=solver.eigenvalues()[0];\r\n\t\tclock_t stop_=std::clock();\r\n\t\tconst double time=((double)(stop_-start_))/CLOCKS_PER_SEC;\r\n\t\tstd::cout<<\"time[\"<<i<<\"] = \"<<time<<\"\\n\";\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\ndouble test_selfadjointeigensolver_rank(int b, int e, int s){\r\n\ttypedef Eigen::MatrixXf MatType;\r\n\tdouble sum=0;\r\n\tfor(int i=b; i<=e; i+=s){\r\n\t\tclock_t start_=std::clock();\r\n\t\tMatType mat=MatType::Random(i,i);\r\n\t\t//Eigen::FullPivLU<MatType> solver(mat);\r\n\t\tEigen::FullPivHouseholderQR<MatType> solver(mat);\r\n\t\tsum+=solver.rank();\r\n\t\tclock_t stop_=std::clock();\r\n\t\tconst double time=((double)(stop_-start_))/CLOCKS_PER_SEC;\r\n\t\tstd::cout<<\"time[\"<<i<<\"] = \"<<time<<\"\\n\";\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\nint main(int argc, char* argv[]){\r\n\t\r\n\ttest_eigensolver_values(1,1001,100);\r\n\ttest_selfadjointeigensolver_values(1,1001,100);\r\n\t//test_selfadjointeigensolver_rank(1,1001,100);\r\n\t\r\n\treturn 0;\r\n}", "meta": {"hexsha": "a3a794408b16cc45c5a2098dc56bee287cf02450", "size": 1705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/test_unit_eigen.cpp", "max_stars_repo_name": "markdellostritto/AtomNN", "max_stars_repo_head_hexsha": "763aa2ca12916638fcca14d5bddafe1112d603cd", "max_stars_repo_licenses": ["MIT"], "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/test_unit_eigen.cpp", "max_issues_repo_name": "markdellostritto/AtomNN", "max_issues_repo_head_hexsha": "763aa2ca12916638fcca14d5bddafe1112d603cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_unit_eigen.cpp", "max_forks_repo_name": "markdellostritto/AtomNN", "max_forks_repo_head_hexsha": "763aa2ca12916638fcca14d5bddafe1112d603cd", "max_forks_repo_licenses": ["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.5, "max_line_length": 64, "alphanum_fraction": 0.6557184751, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6939809882679234}}
{"text": "#ifndef newton_raphson_hpp\n#define newton_raphson_hpp 3141592\n\n#include \"constants.hpp\"\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n\nusing namespace boost::numeric::ublas;\n\ntemplate<class T>\nbool InvertMatrix (const matrix<T>& input, matrix<T>& inverse) {\n  typedef permutation_matrix<std::size_t> pmatrix;\n  matrix<T> A(input);\n  pmatrix pm(A.size1());\n  int res = lu_factorize(A,pm);\n  if( res != 0 ) return false;\n  inverse.assign(identity_matrix<T>(A.size1()));\n  lu_substitute(A, pm, inverse);\n  return true;\n}\n\ntemplate<typename U, typename V>void newton_raphson(U & F,V & J,vector<double>& x0,double tol){\n  double res = norm_1(F(x0));\n  //std::cout << \"F(x0):\" << F(x0) << std::endl;\n  int size = x0.size();\n  matrix<double> A;\n  matrix<double> inverse(size,size);\n  inverse = set_zero(inverse);\n  std::cout << \"Residu:\" << res << std::endl;\n  while(res > tol){\n    A = J(x0);\n    std::cout<< \"A: \" << A << std::endl;\n    InvertMatrix(A, inverse);\n    // //std::cout << \"Inverse size \" << inverse.size1() << \" \" << inverse.size2() << std::endl;\n    // x0 = x0 - prod(inverse,F(x0));\n    // res = norm_1(F(x0));\n    // std::cout << \"Residu: \"<< res << std::endl;\n    // std::cout << \"Solution: \"<< x0 << std::endl;\n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "2d9417157efbba77697409e7d743bec0cb38070d", "size": 1377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/newton_raphson.hpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "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/deprecated/newton_raphson.hpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "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/deprecated/newton_raphson.hpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["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.6875, "max_line_length": 96, "alphanum_fraction": 0.6332607117, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.693882285012374}}
{"text": "#pragma once\n\n#include <iostream>\n#include <random>\n\n#include <Eigen/Cholesky>\n#include <Eigen/SVD>\n\n#include \"km_utils/types.hpp\"\n\nnamespace km\n{\nnamespace math\n{\ntemplate <typename Scalar_t, int vector_size>\nconstexpr Scalar_t multivariateNormalProb(\n    types::Vec<Scalar_t, vector_size> const &x,\n    types::Vec<Scalar_t, vector_size> const &mean,\n    types::SquareMat<Scalar_t, vector_size> const &cov_inverse,\n    Scalar_t const normal_pdf_constant)\n{\n  types::Vec<Scalar_t, vector_size> const dx = x - mean;\n  Scalar_t const normal_pdf_exponent =\n      Scalar_t{-0.5} * (dx.transpose() * cov_inverse * dx).value();\n  return normal_pdf_constant * std::exp(normal_pdf_exponent);\n}\n\ntemplate <typename Scalar_t, int vector_size>\nconstexpr Scalar_t multivariateNormalProb(\n    types::Vec<Scalar_t, vector_size> const &dx,\n    types::SquareMat<Scalar_t, vector_size> const &cov_inverse,\n    Scalar_t const normal_pdf_constant)\n{\n  Scalar_t const normal_pdf_exponent =\n      Scalar_t{-0.5} * (dx.transpose() * cov_inverse * dx).value();\n  return normal_pdf_constant * std::exp(normal_pdf_exponent);\n}\n\ntemplate <typename Scalar_t, int vector_size>\nconstexpr Scalar_t multivariateNormalProb(\n    types::Vec<Scalar_t, vector_size> const &x,\n    types::Vec<Scalar_t, vector_size> const &mean,\n    types::SquareMat<Scalar_t, vector_size> const &cov_inverse)\n{\n  Scalar_t const normal_pdf_constant =\n      std::sqrt((cov_inverse / Scalar_t{2 * M_PI}).determinant());\n  return multivariateNormalProb(x, mean, cov_inverse, normal_pdf_constant);\n}\n\ntemplate <typename Derived>\nconstexpr auto getNormalPDFConstant(\n    Eigen::MatrixBase<Derived> const &cov_inverse)\n{\n  using Scalar = typename Eigen::internal::traits<Derived>::Scalar;\n  return std::sqrt((cov_inverse / Scalar{2 * M_PI}).determinant());\n}\n\ntemplate <typename Scalar_t, int mat_size>\nconstexpr std::vector<Scalar_t> getNormalPDFConstant(\n    types::vector_aligned<types::SquareMat<Scalar_t, mat_size>> const\n        &vec_cov_inverse)\n{\n  std::vector<Scalar_t> ret;\n  ret.reserve(vec_cov_inverse.size());\n  for(auto const &M : vec_cov_inverse)\n    ret.push_back(getNormalPDFConstant(M));\n  return ret;\n}\n\n/**\n * Calculate the matrix square root of a positive (semi-)definite matrix.\n *\n * @param mat The input matrix.\n * @param semidefinite_mat Indicates whether the input is a semidefinite matrix.\n *\n * @return The matrix square root of the input mat.\n */\ntemplate <typename Derived>\nconstexpr typename Derived::PlainObject matrixSquareRoot(\n    Eigen::MatrixBase<Derived> const &mat, bool semidefinite_mat = false)\n{\n  constexpr auto M = Derived::RowsAtCompileTime;\n  constexpr auto N = Derived::ColsAtCompileTime;\n  static_assert(M == N, \"Only valid for a square matrix\");\n  if constexpr(M == 0 || N == 0)\n    return Derived::PlainObject::Zero(mat.rows(), mat.cols());\n  else\n  {\n    if(!semidefinite_mat)\n    {\n      Eigen::LLT<typename Derived::PlainObject> cov_chol{mat};\n      if(cov_chol.info() == Eigen::Success)\n        return cov_chol.matrixL();\n    }\n    Eigen::LDLT<typename Derived::PlainObject> cov_chol{mat};\n    if(cov_chol.info() == Eigen::Success)\n    {\n      typename Derived::PlainObject const L = cov_chol.matrixL();\n      auto const P = cov_chol.transpositionsP();\n      auto const D_sqrt =\n          cov_chol.vectorD().array().sqrt().matrix().asDiagonal();\n      return P.transpose() * L * D_sqrt;\n    }\n    return Derived::PlainObject::Zero(mat.rows(), mat.cols());\n  }\n}\n\ntemplate <typename Vec, typename Cov>\ntypes::vector_aligned<Vec> randomSamplesGaussian(Vec const &mean,\n                                                 Cov const &covariance_sqrt,\n                                                 unsigned int n,\n                                                 std::random_device &rd)\n{\n  std::mt19937 rng{rd()};\n  std::normal_distribution<> dist;\n\n  types::vector_aligned<Vec> ret;\n  ret.reserve(n);\n  for(unsigned int i = 0; i < n; ++i)\n  {\n    Vec z = Vec::Zero(mean.size());\n    for(unsigned int j = 0; j < mean.size(); ++j)\n      z(j) = dist(rng);\n    ret.push_back(mean + covariance_sqrt * z);\n  }\n  return ret;\n}\n\ntemplate <typename Derived>\nconstexpr typename Derived::PlainObject pseudoInverse(\n    Eigen::MatrixBase<Derived> const &m)\n{\n  // JacobiSVD: thin U and V are only available when your matrix has a dynamic\n  // number of columns.\n  constexpr auto flags = (Derived::ColsAtCompileTime == Eigen::Dynamic) ?\n                             (Eigen::ComputeThinU | Eigen::ComputeThinV) :\n                             (Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::JacobiSVD<typename Derived::PlainObject> m_svd(m, flags);\n  // std::cout << \"singular values: \" << m_svd.singularValues().transpose()\n  //           << \"\\n\";\n  return m_svd.solve(Derived::PlainObject::Identity(m.rows(), m.rows()));\n}\n\ntemplate <unsigned int num_repeat, typename Derived>\nconstexpr auto blockDiagonalMatrix(Eigen::EigenBase<Derived> const &X)\n{\n  using Scalar = typename Eigen::internal::traits<Derived>::Scalar;\n  constexpr auto M = Eigen::internal::traits<Derived>::RowsAtCompileTime;\n  constexpr auto N = Eigen::internal::traits<Derived>::ColsAtCompileTime;\n\n  auto const in_rows = (M == Eigen::Dynamic) ? X.rows() : M;\n  auto const in_cols = (N == Eigen::Dynamic) ? X.cols() : N;\n  auto const out_rows = num_repeat * in_rows;\n  auto const out_cols = num_repeat * in_cols;\n  constexpr auto out_template_rows =\n      (M == Eigen::Dynamic) ? Eigen::Dynamic : out_rows;\n  constexpr auto out_template_cols =\n      (N == Eigen::Dynamic) ? Eigen::Dynamic : out_cols;\n\n  auto ret = Eigen::Matrix<Scalar, out_template_rows, out_template_cols>::Zero(\n                 out_rows, out_cols)\n                 .eval();\n\n  if constexpr(M != Eigen::Dynamic && N != Eigen::Dynamic)\n  {\n    for(unsigned int i = 0; i < num_repeat; ++i)\n      ret.template block<M, N>(i * M, i * N) = X;\n  }\n  else\n  {\n    for(unsigned int i = 0; i < num_repeat; ++i)\n      ret.block(i * in_rows, i * in_cols, in_rows, in_cols) = X;\n  }\n  return ret;\n}\n\ntemplate <typename Derived>\nconstexpr auto blockDiagonalMatrix(Eigen::EigenBase<Derived> const &X,\n                                   unsigned int const num_repeat)\n{\n  using Scalar = typename Eigen::internal::traits<Derived>::Scalar;\n  constexpr auto M = Eigen::internal::traits<Derived>::RowsAtCompileTime;\n  constexpr auto N = Eigen::internal::traits<Derived>::ColsAtCompileTime;\n\n  auto const in_rows = X.rows();\n  auto const in_cols = X.cols();\n\n  auto ret = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>::Zero(\n                 num_repeat * in_rows, num_repeat * in_cols)\n                 .eval();\n\n  if constexpr(M != Eigen::Dynamic && N != Eigen::Dynamic)\n  {\n    for(unsigned int i = 0; i < num_repeat; ++i)\n      ret.template block<M, N>(i * M, i * N) = X;\n  }\n  else\n  {\n    for(unsigned int i = 0; i < num_repeat; ++i)\n      ret.block(i * in_rows, i * in_cols, in_rows, in_cols) = X;\n  }\n  return ret;\n}\n\ntemplate <typename T>\nconstexpr T square(T p)\n{\n  return p * p;\n}\n\n// From https://stackoverflow.com/a/33454406\ntemplate <typename T>\nconstexpr T powInt(T x, unsigned int n)\n{\n  if(n == 0)\n    return T{1};\n  else if(n == 1)\n    return x;\n  else if(n == 2)\n    return x * x;\n\n  auto y = x * x;\n  n -= 2;\n  while(n > 1)\n  {\n    if(n % 2 == 1)\n      y *= x;\n    x *= x;\n    n /= 2;\n  }\n  return x * y;\n}\n\n/**\n * @brief Normalize the given angle in radians to (-PI, PI]\n *\n * @param[in] x angle in radians\n *\n * @return normalized angle in the range (-PI, PI]\n */\ntemplate <typename Scalar_t>\nconstexpr Scalar_t normalize_angle(Scalar_t x)\n{\n  constexpr Scalar_t pi = M_PI, two_pi = 2 * M_PI;\n  return x - (std::ceil((x + pi) / two_pi) - Scalar_t{1}) * two_pi;\n}\n} // namespace math\n} // namespace km\n", "meta": {"hexsha": "335664970ee6d622f7835c0c0aaea40152794b5b", "size": 7731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/km_utils/math.hpp", "max_stars_repo_name": "kartikmohta/km_utils", "max_stars_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T23:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-26T23:21:22.000Z", "max_issues_repo_path": "include/km_utils/math.hpp", "max_issues_repo_name": "kartikmohta/km_utils", "max_issues_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "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/km_utils/math.hpp", "max_forks_repo_name": "kartikmohta/km_utils", "max_forks_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "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.0481927711, "max_line_length": 80, "alphanum_fraction": 0.656706765, "num_tokens": 2009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.693695914257856}}
{"text": "//\n// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/strong_components.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nusing namespace std;\n\nint dijkstra(const weighted_graph &G, int s, int k) {\n  int n = boost::num_vertices(G);\n  std::vector<int> dist_map(n);\n\n  boost::dijkstra_shortest_paths(G, s,\n    boost::distance_map(boost::make_iterator_property_map(\n      dist_map.begin(), boost::get(boost::vertex_index, G))));\n  int min_dist = dist_map[0];\n  for(int i = 1; i < k; i++) {\n    min_dist = min(min_dist, dist_map[i]);\n  }\n  return min_dist;\n}\n\n\nvoid testcase() {\n  int n; cin >> n;\n  int m; cin >> m;\n  int k; cin >> k;\n  int T; cin >> T;\n  vector<int> tele_nodes(T);\n  for(int i = 0; i < T; i++) {\n    cin >> tele_nodes[i];\n  }\n  weighted_graph G(n);\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 c; cin >> c;\n    e = boost::add_edge(v, u, G).first; weights[e] = c; // flipped edges!\n  }\n  // scc_map[i]: index of SCC containing i-th vertex\n  vector<int> scc_map(n); // exterior property map\n  // nscc: total number of SCCs\n  int nscc = boost::strong_components(G,\n      boost::make_iterator_property_map(scc_map.begin(),\n      boost::get(boost::vertex_index, G)));\n  \n  vector<int> size_scc(nscc);\n  for(int i = 0; i < T; i++) {\n    size_scc[scc_map[tele_nodes[i]]]++;\n  }\n  \n  \n  for(int i = 0; i < T; i++) {\n      int u = tele_nodes[i];\n      int scc = scc_map[u];\n      int size_this_scc = size_scc[scc] - 1;\n      e = boost::add_edge(u, n + scc, G).first;\n      weights[e] = size_this_scc;\n      e = boost::add_edge(n + scc, u, G).first;\n      weights[e] = 0;\n  }\n  \n  int min_dist_to_warehouse = dijkstra(G, n - 1, k);\n  if(min_dist_to_warehouse <= 1e6) {\n    cout << min_dist_to_warehouse << endl;\n  } else {\n    cout << \"no\" << endl;\n  }\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": "d07555915527d7c8a55487e3e53b8e7af775043a", "size": 2515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week06-potw-planet_express/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/week06-potw-planet_express/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/week06-potw-planet_express/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": 27.6373626374, "max_line_length": 87, "alphanum_fraction": 0.6310139165, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6936493724979871}}
{"text": "\n#include <thread>\n#include <complex>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#define lapack_complex_float  std::complex<float>\n#define lapack_complex_double std::complex<double>\n\n#ifdef OpenBLAS_AVAILABLE\n#include <cblas.h>\n#include <openblas_config.h>\n#endif\n\n\n#ifdef MKL_AVAILABLE\n#include <mkl_service.h>\n#include <mkl.h>\n#endif\n\n#if __has_include(<mkl_lapacke.h>)\n#include <mkl_lapacke.h>\n#elif __has_include(<lapacke.h>)\n#include <lapacke.h>\n#endif\n\n#include <Eigen/Core>\n#include <general/nmspc_tensor_omp.h>\n#include <h5pp/h5pp.h>\n#include <math/class_eigsolver.h>\n\nint eig_dsyevd(double *matrix2eigvecs, double * eigvals, int L){\n    //These nice values are inspired from armadillo. The prefactors give good performance.\n    int lwork  = 2 * (1 + 6*L + 2*(L*L));\n    int liwork = 3 * (3 + 5*L);\n    std::cout << \" lwork  = \" << lwork << std::endl;\n    std::cout << \" liwork = \" << liwork << std::endl;\n\n    int info   = 0;\n    std::vector<double> work  ( lwork );\n    std::vector<int   > iwork ( liwork );\n    char jobz = 'V';\n    info = LAPACKE_dsyevd_work(LAPACK_COL_MAJOR,jobz,'L',L,\n                               matrix2eigvecs,\n                               L,\n                               eigvals,\n                               work.data(),\n                               lwork,\n                               iwork.data(),\n                               liwork);\n    return info;\n}\n\nstd::tuple<Eigen::VectorXd,Eigen::MatrixXd, int> eig_dsyevd(const double* matrix, int L){\n//    using namespace eigutils::eigSetting;\n    Eigen::VectorXd eigvals(L);\n    Eigen::MatrixXd eigvecs(L,L);\n    std::copy(matrix, matrix + L*L, eigvecs.data());\n    int info = eig_dsyevd(eigvecs.data(),eigvals.data(), L);\n\n    return std::make_tuple(eigvals,eigvecs,info);\n}\n\n\nint main(){\n\n    #ifdef _OPENMP\n        omp_set_num_threads(std::thread::hardware_concurrency());\n        Eigen::setNbThreads(std::thread::hardware_concurrency());\n        std::cout << \"Using Eigen  with \" << Eigen::nbThreads() << \" threads\" << std::endl;\n        std::cout << \"Using OpenMP with \" << omp_get_max_threads() << \" threads\" << std::endl;\n\n        #ifdef OpenBLAS_AVAILABLE\n        openblas_set_num_threads(std::thread::hardware_concurrency());\n                    std::cout << OPENBLAS_VERSION\n                              << \" compiled with parallel mode \" << openblas_get_parallel()\n                              << \" for target \" << openblas_get_corename()\n                              << \" with config \" << openblas_get_config()\n                              << \" with multithread threshold \" << OPENBLAS_GEMM_MULTITHREAD_THRESHOLD\n                              << \". Running with \" << openblas_get_num_threads() << \" thread(s)\" << std::endl;\n        #endif\n\n        #ifdef MKL_AVAILABLE\n        mkl_set_num_threads(std::thread::hardware_concurrency());\n        std::cout << \"Using Intel MKL with \" << mkl_get_max_threads() << \" threads\" << std::endl;\n        #endif\n    #endif\n\n\n\n    Eigen::MatrixXd H_localA1, H_localA2;\n    Eigen::MatrixXd H_localB1, H_localB2;\n\n    Eigen::MatrixXd eigvecsA1, eigvecsA2;\n    Eigen::MatrixXd eigvecsB1, eigvecsB2;\n    Eigen::MatrixXd eigvalsA1, eigvalsA2;\n    Eigen::MatrixXd eigvalsB1, eigvalsB2;\n    Eigen::VectorXcd thetaA1, thetaA2;\n    Eigen::VectorXcd thetaB1, thetaB2;\n\n    Eigen::VectorXd overlapsA1, overlapsA2;\n    Eigen::VectorXd overlapsB1, overlapsB2;\n\n    h5pp::File fileA1(std::string(TEST_MATRIX_DIR) + \"/lapacke_matrix-1A.h5\", h5pp::FilePermission::READONLY);\n    h5pp::File fileA2(std::string(TEST_MATRIX_DIR) + \"/lapacke_matrix-2A.h5\", h5pp::FilePermission::READONLY);\n    h5pp::File fileB1(std::string(TEST_MATRIX_DIR) + \"/lapacke_matrix-1B.h5\", h5pp::FilePermission::READONLY);\n    h5pp::File fileB2(std::string(TEST_MATRIX_DIR) + \"/lapacke_matrix-2B.h5\", h5pp::FilePermission::READONLY);\n    fileA1.readDataset(H_localA1,\"matrix\");\n    fileA2.readDataset(H_localA2,\"matrix\");\n    fileB1.readDataset(H_localB1,\"matrix\");\n    fileB2.readDataset(H_localB2,\"matrix\");\n\n    fileA1.readDataset(eigvecsA1,\"eigvecs\");\n    fileA2.readDataset(eigvecsA2,\"eigvecs\");\n    fileB1.readDataset(eigvecsB1,\"eigvecs\");\n    fileB2.readDataset(eigvecsB2,\"eigvecs\");\n\n    fileA1.readDataset(eigvalsA1,\"eigvals\");\n    fileA2.readDataset(eigvalsA2,\"eigvals\");\n    fileB1.readDataset(eigvalsB1,\"eigvals\");\n    fileB2.readDataset(eigvalsB2,\"eigvals\");\n\n    fileA1.readDataset(thetaA1,\"theta\");\n    fileA2.readDataset(thetaA2,\"theta\");\n    fileB1.readDataset(thetaB1,\"theta\");\n    fileB2.readDataset(thetaB2,\"theta\");\n\n    fileA1.readDataset(overlapsA1,\"overlaps\");\n    fileA2.readDataset(overlapsA2,\"overlaps\");\n    fileB1.readDataset(overlapsB1,\"overlaps\");\n    fileB2.readDataset(overlapsB2,\"overlaps\");\n    using namespace eigutils::eigSetting;\n\n    class_eigsolver solverA;\n    class_eigsolver solverB;\n\n    [[maybe_unused]] auto [eigvalsA1_lapacke,eigvecsA1_lapacke,infoA1] = eig_dsyevd(H_localA1.data(),H_localA1.rows());\n    [[maybe_unused]] auto [eigvalsB1_lapacke,eigvecsB1_lapacke,infoB1] = eig_dsyevd(H_localB1.data(),H_localB1.rows());\n\n    solverA.eig<Type::REAL, Form::SYMMETRIC>(H_localA1,true,false);\n    solverB.eig<Type::REAL, Form::SYMMETRIC>(H_localB1,true,false);\n    Eigen::VectorXd eigvalsA1_eig           = Eigen::Map<const Eigen::VectorXd> (solverA.solution.get_eigvals<Form::SYMMETRIC>().data()            ,solverA.solution.meta.cols);\n    Eigen::MatrixXd eigvecsA1_eig           = Eigen::Map<const Eigen::MatrixXd> (solverA.solution.get_eigvecs<Type::REAL, Form::SYMMETRIC>().data(),solverA.solution.meta.rows,solverA.solution.meta.cols);\n    Eigen::VectorXd eigvalsB1_eig           = Eigen::Map<const Eigen::VectorXd> (solverB.solution.get_eigvals<Form::SYMMETRIC>().data()            ,solverB.solution.meta.cols);\n    Eigen::MatrixXd eigvecsB1_eig           = Eigen::Map<const Eigen::MatrixXd> (solverB.solution.get_eigvecs<Type::REAL, Form::SYMMETRIC>().data(),solverB.solution.meta.rows,solverB.solution.meta.cols);\n\n    Eigen::VectorXd overlapsA1_read         = (thetaA1.adjoint() * eigvecsA1).cwiseAbs();\n    Eigen::VectorXd overlapsA1_lapacke      = (thetaA1.adjoint() * eigvecsA1_lapacke).cwiseAbs();\n    Eigen::VectorXd overlapsA1_eig          = (thetaA1.adjoint() * eigvecsA1_eig).cwiseAbs();\n    Eigen::VectorXd overlapsB1_read         = (thetaB1.adjoint() * eigvecsB1).cwiseAbs();\n    Eigen::VectorXd overlapsB1_lapacke      = (thetaB1.adjoint() * eigvecsB1_lapacke).cwiseAbs();\n    Eigen::VectorXd overlapsB1_eig          = (thetaB1.adjoint() * eigvecsB1_eig).cwiseAbs();\n\n\n    double max_overlapA1_read        = overlapsA1_read    .maxCoeff();\n    double max_overlapA1_lapacke     = overlapsA1_lapacke .maxCoeff();\n    double max_overlapA1_eig         = overlapsA1_eig     .maxCoeff();\n    double max_overlapB1_read        = overlapsB1_read    .maxCoeff();\n    double max_overlapB1_lapacke     = overlapsB1_lapacke .maxCoeff();\n    double max_overlapB1_eig         = overlapsB1_eig     .maxCoeff();\n\n\n    auto overlap_A1A1_eig     =     (eigvecsA1.adjoint() * eigvecsA1_eig    ).diagonal().cwiseAbs().mean();\n    auto overlap_A1B1_eig     =     (eigvecsA1.adjoint() * eigvecsB1_eig    ).diagonal().cwiseAbs().mean();\n    auto overlap_A1A1_lapacke =     (eigvecsA1.adjoint() * eigvecsA1_lapacke).diagonal().cwiseAbs().mean();\n    auto overlap_A1B1_lapacke =     (eigvecsA1.adjoint() * eigvecsB1_lapacke).diagonal().cwiseAbs().mean();\n\n    [[maybe_unused]] auto [eigvalsA2_lapacke,eigvecsA2_lapacke,infoA2] = eig_dsyevd(H_localA2.data(),H_localA2.rows());\n    [[maybe_unused]] auto [eigvalsB2_lapacke,eigvecsB2_lapacke,infoB2] = eig_dsyevd(H_localB2.data(),H_localB2.rows());\n    solverA.eig<Type::REAL, Form::SYMMETRIC>(H_localA2,true,false);\n    solverB.eig<Type::REAL, Form::SYMMETRIC>(H_localB2,true,false);\n    Eigen::VectorXd eigvalsA2_eig           = Eigen::Map<const Eigen::VectorXd> (solverA.solution.get_eigvals<Form::SYMMETRIC>().data()            ,solverA.solution.meta.cols);\n    Eigen::MatrixXd eigvecsA2_eig           = Eigen::Map<const Eigen::MatrixXd> (solverA.solution.get_eigvecs<Type::REAL, Form::SYMMETRIC>().data(),solverA.solution.meta.rows,solverA.solution.meta.cols);\n    Eigen::VectorXd eigvalsB2_eig           = Eigen::Map<const Eigen::VectorXd> (solverB.solution.get_eigvals<Form::SYMMETRIC>().data()            ,solverB.solution.meta.cols);\n    Eigen::MatrixXd eigvecsB2_eig           = Eigen::Map<const Eigen::MatrixXd> (solverB.solution.get_eigvecs<Type::REAL, Form::SYMMETRIC>().data(),solverB.solution.meta.rows,solverB.solution.meta.cols);\n\n    Eigen::VectorXd overlapsA2_read         = (thetaA2.adjoint() * eigvecsA2).cwiseAbs();\n    Eigen::VectorXd overlapsA2_lapacke      = (thetaA2.adjoint() * eigvecsA2_lapacke).cwiseAbs();\n    Eigen::VectorXd overlapsA2_eig          = (thetaA2.adjoint() * eigvecsA2_eig).cwiseAbs();\n    Eigen::VectorXd overlapsB2_read         = (thetaB2.adjoint() * eigvecsB2).cwiseAbs();\n    Eigen::VectorXd overlapsB2_lapacke      = (thetaB2.adjoint() * eigvecsB2_lapacke).cwiseAbs();\n    Eigen::VectorXd overlapsB2_eig          = (thetaB2.adjoint() * eigvecsB2_eig).cwiseAbs();\n\n\n    double max_overlapA2_read        = overlapsA2_read    .maxCoeff();\n    double max_overlapA2_lapacke     = overlapsA2_lapacke .maxCoeff();\n    double max_overlapA2_eig         = overlapsA2_eig     .maxCoeff();\n    double max_overlapB2_read        = overlapsB2_read    .maxCoeff();\n    double max_overlapB2_lapacke     = overlapsB2_lapacke .maxCoeff();\n    double max_overlapB2_eig         = overlapsB2_eig     .maxCoeff();\n\n    auto overlap_A2A2_eig     =  (eigvecsA2.adjoint() * eigvecsA2_eig    ).diagonal().cwiseAbs().mean();\n    auto overlap_A2B2_eig     =  (eigvecsA2.adjoint() * eigvecsB2_eig    ).diagonal().cwiseAbs().mean();\n    auto overlap_A2A2_lapacke =  (eigvecsA2.adjoint() * eigvecsA2_lapacke).diagonal().cwiseAbs().mean();\n    auto overlap_A2B2_lapacke =  (eigvecsA2.adjoint() * eigvecsB2_lapacke).diagonal().cwiseAbs().mean();\n\n\n\n\n    std::cout << std::setprecision(16);\n    std::cout << \"H_localA1         vs H_localB1           diff   =   \" << std::boolalpha << (H_localA1.array() - H_localB1.array()).cwiseAbs().sum() << std::endl;\n    std::cout << \"thetaA1           vs thetaB1             diff   =   \" << std::boolalpha << (thetaA1.array()   - thetaB1.array()).cwiseAbs().sum() << std::endl;\n    std::cout << \"<thetaA1          |  thetaB1 >            diff  =   \" << std::boolalpha << (thetaA1.adjoint() * thetaB1).cwiseAbs().sum() << std::endl;\n    std::cout << \"overlapsA1        vs overlapsB1          diff   =   \" << std::boolalpha << (overlapsA1.array()- overlapsB1.array()).cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvecsA1_read    vs eigvecsA1_lapacke   diff   =   \" << std::boolalpha << (eigvecsA1.adjoint()         * eigvecsA1_lapacke).diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB1_read    vs eigvecsB1_lapacke   diff   =   \" << std::boolalpha << (eigvecsB1.adjoint()         * eigvecsB1_lapacke).diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsA1_read    vs eigvecsA1_solver    diff   =   \" << std::boolalpha << (eigvecsA1.adjoint()         * eigvecsA1_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB1_read    vs eigvecsB1_solver    diff   =   \" << std::boolalpha << (eigvecsB1.adjoint()         * eigvecsB1_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsA1_lapacke vs eigvecsA1_solver    diff   =   \" << std::boolalpha << (eigvecsA1_lapacke.adjoint() * eigvecsA1_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB1_lapacke vs eigvecsB1_solver    diff   =   \" << std::boolalpha << (eigvecsB1_lapacke.adjoint() * eigvecsB1_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvalsA1_read    vs eigvalsA1_lapacke   diff   =   \" << std::boolalpha << (eigvalsA1.array()           - eigvalsA1_lapacke .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB1_read    vs eigvalsB1_lapacke   diff   =   \" << std::boolalpha << (eigvalsB1.array()           - eigvalsB1_lapacke .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsA1_read    vs eigvalsA1_solver    diff   =   \" << std::boolalpha << (eigvalsA1.array()           - eigvalsA1_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB1_read    vs eigvalsB1_solver    diff   =   \" << std::boolalpha << (eigvalsB1.array()           - eigvalsB1_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsA1_lapacke vs eigvalsA1_solver    diff   =   \" << std::boolalpha << (eigvalsA1_lapacke.array()   - eigvalsA1_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB1_lapacke vs eigvalsB1_solver    diff   =   \" << std::boolalpha << (eigvalsB1_lapacke.array()   - eigvalsB1_eig     .array())  .cwiseAbs().sum() << std::endl;\n\n\n    std::cout << \"max_overlapA1_read     =  \" << max_overlapA1_read     << std::endl;\n    std::cout << \"max_overlapA1_lapacke  =  \" << max_overlapA1_lapacke  << std::endl;\n    std::cout << \"max_overlapA1_eig      =  \" << max_overlapA1_eig      << std::endl;\n    std::cout << \"max_overlapB1_read     =  \" << max_overlapB1_read     << std::endl;\n    std::cout << \"max_overlapB1_lapacke  =  \" << max_overlapB1_lapacke  << std::endl;\n    std::cout << \"max_overlapB1_eig      =  \" << max_overlapB1_eig      << std::endl;\n\n    std::cout << \"overlap_A1A1_eig       =  \" << overlap_A1A1_eig       << std::endl;\n    std::cout << \"overlap_A1B1_eig       =  \" << overlap_A1B1_eig       << std::endl;\n    std::cout << \"overlap_A1A1_lapacke   =  \" << overlap_A1A1_lapacke   << std::endl;\n    std::cout << \"overlap_A1B1_lapacke   =  \" << overlap_A1B1_lapacke   << std::endl;\n\n\n\n    std::cout << \"H_localA2         vs H_localB2           diff   =   \" << std::boolalpha << (H_localA2.array() - H_localB2.array()).cwiseAbs().sum() << std::endl;\n    std::cout << \"thetaA2           vs thetaB2             diff   =   \" << std::boolalpha << (thetaA2.array()   - thetaB2.array()).cwiseAbs().sum() << std::endl;\n    std::cout << \"<thetaA2          |  thetaB2 >            diff  =   \" << std::boolalpha << (thetaA2.adjoint() * thetaB2).cwiseAbs().sum() << std::endl;\n    std::cout << \"overlapsA2        vs overlapsB2          diff   =   \" << std::boolalpha << (overlapsA2.array()- overlapsB2.array()).cwiseAbs().sum() << std::endl;\n\n    std::cout << \"eigvecsA2_read    vs eigvecsA2_lapacke   diff   =   \" << std::boolalpha << (eigvecsA2.adjoint()         * eigvecsA2_lapacke).diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB2_read    vs eigvecsB2_lapacke   diff   =   \" << std::boolalpha << (eigvecsB2.adjoint()         * eigvecsB2_lapacke).diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsA2_read    vs eigvecsA2_solver    diff   =   \" << std::boolalpha << (eigvecsA2.adjoint()         * eigvecsA2_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB2_read    vs eigvecsB2_solver    diff   =   \" << std::boolalpha << (eigvecsB2.adjoint()         * eigvecsB2_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsA2_lapacke vs eigvecsA2_solver    diff   =   \" << std::boolalpha << (eigvecsA2_lapacke.adjoint() * eigvecsA2_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvecsB2_lapacke vs eigvecsB2_solver    diff   =   \" << std::boolalpha << (eigvecsB2_lapacke.adjoint() * eigvecsB2_eig)    .diagonal().cwiseAbs().mean() << std::endl;\n    std::cout << \"eigvalsA2_read    vs eigvalsA2_lapacke   diff   =   \" << std::boolalpha << (eigvalsA2.array()           - eigvalsA2_lapacke .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB2_read    vs eigvalsB2_lapacke   diff   =   \" << std::boolalpha << (eigvalsB2.array()           - eigvalsB2_lapacke .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsA2_read    vs eigvalsA2_solver    diff   =   \" << std::boolalpha << (eigvalsA2.array()           - eigvalsA2_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB2_read    vs eigvalsB2_solver    diff   =   \" << std::boolalpha << (eigvalsB2.array()           - eigvalsB2_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsA2_lapacke vs eigvalsA2_solver    diff   =   \" << std::boolalpha << (eigvalsA2_lapacke.array()   - eigvalsA2_eig     .array())  .cwiseAbs().sum() << std::endl;\n    std::cout << \"eigvalsB2_lapacke vs eigvalsB2_solver    diff   =   \" << std::boolalpha << (eigvalsB2_lapacke.array()   - eigvalsB2_eig     .array())  .cwiseAbs().sum() << std::endl;\n\n\n    std::cout << \"max_overlapA2_read     =  \" << max_overlapA2_read     << std::endl;\n    std::cout << \"max_overlapA2_lapacke  =  \" << max_overlapA2_lapacke  << std::endl;\n    std::cout << \"max_overlapA2_eig      =  \" << max_overlapA2_eig      << std::endl;\n    std::cout << \"max_overlapB2_read     =  \" << max_overlapB2_read     << std::endl;\n    std::cout << \"max_overlapB2_lapacke  =  \" << max_overlapB2_lapacke  << std::endl;\n    std::cout << \"max_overlapB2_eig      =  \" << max_overlapB2_eig      << std::endl;\n\n    std::cout << \"overlap_A2A2_eig       =  \" << overlap_A2A2_eig       << std::endl;\n    std::cout << \"overlap_A2B2_eig       =  \" << overlap_A2B2_eig       << std::endl;\n    std::cout << \"overlap_A2A2_lapacke   =  \" << overlap_A2A2_lapacke   << std::endl;\n    std::cout << \"overlap_A2B2_lapacke   =  \" << overlap_A2B2_lapacke   << std::endl;\n\n    if(std::abs(overlap_A1A1_eig     - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A1A1_eig     : \" + std::to_string(overlap_A1A1_eig     ));\n    if(std::abs(overlap_A1B1_eig     - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A1B1_eig     : \" + std::to_string(overlap_A1B1_eig     ));\n    if(std::abs(overlap_A1A1_lapacke - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A1A1_lapacke : \" + std::to_string(overlap_A1A1_lapacke ));\n    if(std::abs(overlap_A1B1_lapacke - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A1B1_lapacke : \" + std::to_string(overlap_A1B1_lapacke ));\n\n\n\n    if(std::abs(overlap_A2A2_eig     - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A2A2_eig     : \" + std::to_string(overlap_A2A2_eig     ));\n    if(std::abs(overlap_A2B2_eig     - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A2B2_eig     : \" + std::to_string(overlap_A2B2_eig     ));\n    if(std::abs(overlap_A2A2_lapacke - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A2A2_lapacke : \" + std::to_string(overlap_A2A2_lapacke ));\n    if(std::abs(overlap_A2B2_lapacke - 1) > 1e-10 ) throw std::runtime_error(\"overlap_A2B2_lapacke : \" + std::to_string(overlap_A2B2_lapacke ));\n\n\n//    std::cout << \"theta * eigvecsA2         = \\n\" << std::fixed << (thetaA2.adjoint() * eigvecsA2).cwiseAbs().transpose() << std::endl;\n\n\n}", "meta": {"hexsha": "9874dd5bb359d02f7604b50d7fd5fbdedae91a5c", "size": 18774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/old_tests/eigsolver.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "tests/old_tests/eigsolver.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/old_tests/eigsolver.cpp", "max_forks_repo_name": "DavidAce/DMRG", "max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z", "avg_line_length": 66.8113879004, "max_line_length": 203, "alphanum_fraction": 0.6369447108, "num_tokens": 6125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6936493717793927}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestRotation3D\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <cmath>\n#include \"minimath/matrix.hpp\"\n#include \"minimath/matrix_ops.hpp\"\n#include \"minimath/rotation3d.hpp\"\n#include \"minimath/point3d.hpp\"\n#include \"minimath/geom3d_ops.hpp\"\n#include \"TestRotation3DUtils.h\"\n#include \"Defines.h\"\n\n\nusing namespace minimath;\n\nBOOST_AUTO_TEST_SUITE(TestRotation3D)\n\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  rotation3d<double> rot1, rot2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n  BOOST_CHECK(rotation3d<double>() == rotation3d<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  rotation3d<double> rot1;\n  rotation3d<double> rot2(rot1);\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  rotation3d<double> rot1, rot2;\n  rot2 = rot1;\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testNullRotation)\n{\n  rotation3d<double> rot;\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45X)\n{\n  rotation3d<double> rot = rotation3dx<double>(PI/4.); // 45 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., cos45, cos45));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -cos45, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90X)\n{\n  rotation3d<double> rot = rotation3dx<double>(PI/2.); // 90 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180X)\n{\n  rotation3d<double> rot = rotation3dx<double>(PI); // 180 degree rotation about X\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Y)\n{\n  rotation3d<double> rot = rotation3dy<double> (PI/4.); // 45 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0., -cos45));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Y)\n{\n  rotation3d<double> rot = rotation3dy<double> (PI/2.); // 90 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Y)\n{\n  rotation3d<double> rot = rotation3dy<double> (PI); // 180 degree rotation about X\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Z)\n{\n  rotation3d<double> rot = rotation3dz<double>(PI/4.); // 45 degree rotation about Z\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, cos45, 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(-cos45, cos45, 0));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0, 0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Z)\n{\n  rotation3d<double> rot = rotation3dz<double>(PI/2.); // 90 degree rotation about Z\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Z)\n{\n  rotation3d<double> rot = rotation3dz<double>(PI); // 180 degree rotation about Z\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  BOOST_CHECK(TestUtils::testInverseRotation3D<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInverseRotation3D<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInverseRotation3D<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  BOOST_CHECK(TestUtils::testInvertRotation3D<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInvertRotation3D<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInvertRotation3D<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_CASE(testFindTransformationRotX)\n{\n  TestUtils::testFindTransformationAxisRot<rotation3dx<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testFindTransformationRotY)\n{\n  TestUtils::testFindTransformationAxisRot<rotation3dy<double> >();\n}\n\nBOOST_AUTO_TEST_CASE(testFindTransformationRotZ)\n{\n  TestUtils::testFindTransformationAxisRot<rotation3dz<double> >();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3c640fff18ec6b3f1426b4cc89398083f9a1c705", "size": 5412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestRotation3D.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestRotation3D.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestRotation3D.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 25.4084507042, "max_line_length": 85, "alphanum_fraction": 0.7110125647, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6936493114969862}}
{"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    least squares optimization routines from the dlib C++ Library.\n\n    This example program will demonstrate how these routines can be used for data fitting.\n    In particular, we will generate a set of data and then use the least squares  \n    routines to infer the parameters of the model which generated the data.\n*/\n\n\n#include <dlib/optimization.h>\n#include <iostream>\n#include <vector>\n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\ntypedef matrix<double,1,1> input_vector;\ntypedef matrix<double,2,1> parameter_vector;\ntypedef std::vector<std::pair<input_vector, double> > data_samples;\n\nconst double sqrt2pi = std::sqrt(2*pi);\nconst double sqrtpi = std::sqrt(pi);\n// ----------------------------------------------------------------------------------------\n\n// We will use this function to generate data.  It represents a function of 2 variables\n// and 3 parameters.   The least squares procedure will be used to infer the values of \n// the 3 parameters based on a set of input/output pairs.\ndouble model (\n    const input_vector& input,\n    const parameter_vector& params\n)\n{\n    const double a = params(0);\n    const double b = params(1);\n\n    const double x = input(0);\n\n    /*\n               /               2 \\\n               |   (a - log(x))  |\n    sqrt(2) exp| - ------------- |\n               |           2     |\n               \\        2 b      /\n    ------------------------------\n            b x sqrt(pi) 2\n     */\n\n    const double logx = log(x);\n    const double nominator = sqrt_2 * exp(- ((a - logx)*(a - logx))/(2*b*b));\n    const double denominator = b * x * sqrtpi * 2;\n    double out = nominator/denominator;\n    return out;\n\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the \"residual\" for a least squares problem.   It takes an input/output\n// pair and compares it to the output of our model and returns the amount of error.  The idea\n// is to find the set of parameters which makes the residual small on all the data pairs.\ndouble residual (\n    const std::pair<input_vector, double>& data,\n    const parameter_vector& params\n)\n{\n    return model(data.first, params) - data.second;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the derivative of the residual() function with respect to the parameters.\nparameter_vector residual_derivative (\n    const std::pair<input_vector, double>& data,\n    const parameter_vector& params\n)\n{\n    /*\n    wrt a (mean)\n             /               2 \\\n             |   (a - log(x))  |\n  sqrt(2) exp| - ------------- | (2 a - 2 log(x))\n             |           2     |\n             \\        2 b      /\n- -----------------------------------------------\n                   3\n                  b  x sqrt(pi) 4\n\n\n           /               2 \\                            /               2 \\\n           |   (a - log(x))  |             2              |   (a - log(x))  |\nsqrt(2) exp| - ------------- | (a - log(x))    sqrt(2) exp| - ------------- |\n           |           2     |                            |           2     |\n           \\        2 b      /                            \\        2 b      /\n-------------------------------------------- - ------------------------------\n                4                                       2\n               b  x sqrt(pi) 2                         b  x sqrt(pi) 2\n    */\n    parameter_vector der;\n\n    const double a = params(0);\n    const double b = params(1);\n\n    const double x = data.first(0);\n    const double logx = log(x);\n    const double a_logxsq = (a - logx)*(a - logx);\n    const double sqb = b*b;\n    const double exp_fraction = sqrt_2 * exp(- a_logxsq/(2*sqb));\n\n    const double numeratorA = exp_fraction * (2 * a - 2 * logx);\n    const double denominatorA = b*sqb * x * sqrtpi * 4;\n\n    const double numeratorB = exp_fraction * a_logxsq;\n    const double denominatorB = sqb*sqb * x * sqrtpi * 2;\n\n    der(0) = -numeratorA/denominatorA;\n    der(1) = numeratorB/denominatorB - exp_fraction/(sqb * x * sqrtpi * 2);\n\n    return der;\n}\n\n// ----------------------------------------------------------------------------------------\n\nbool read_inputfile(std::string filename, data_samples& DS, double& maxYPos, std::string& errmsg){\n    bool out = false;\n    std::ifstream datafile(filename.c_str());\n    if (!datafile.good()) {\n        errmsg = \"Can't open the file\" + filename;\n    }\n    else{\n        std::string line;\n        double y;\n        double max_y = 0;\n        double x = 1;\n        input_vector input;\n        while (getline(datafile, line)){\n            if (line.size() > 0){\n                std::istringstream inp(line.c_str());\n                inp >> y;\n                input(0) = x;\n                DS.push_back(make_pair(input, y));\n                if (y > max_y){\n                    max_y = y;\n                    maxYPos = x;\n                }\n                x = x + 1.0;\n            }\n        }\n        out = true;\n    }\n    return out;\n}\n\nint main(int argc, char* argv[])\n{\n    if (argc == 1){\n        std::cout << \"No input file!\" << std::endl;\n        return 0;\n    }\n\n    std::string infile = argv[1];\n    data_samples DS;\n    double maxYpos = 1;\n    std::string msg;\n    bool tf = read_inputfile(infile, DS ,maxYpos,msg);\n\n    parameter_vector params;\n    params(0) = log(maxYpos);\n    params(1) = 0.3;\n    try\n    {\n        // randomly pick a set of parameters to use in this example\n//        const parameter_vector params = 10*randm(3,1);\n//        cout << \"params: \" << trans(params) << endl;\n\n\n        // Now let's generate a bunch of input/output pairs according to our model.\n//        std::vector<std::pair<input_vector, double> > data_samples;\n//        input_vector input;\n//        for (int i = 0; i < 1000; ++i)\n//        {\n//            input = 10*randm(2,1);\n//            const double output = model(input, params);\n//\n//            // save the pair\n//            data_samples.push_back(make_pair(input, output));\n//        }\n\n        // Before we do anything, let's make sure that our derivative function defined above matches\n        // the approximate derivative computed using central differences (via derivative()).  \n        // If this value is big then it means we probably typed the derivative function incorrectly.\n        //cout << \"derivative error: \" << length(residual_derivative(DS[18], params) -\n        //                                       derivative(residual)(DS[18], params) ) << endl;\n\n\n\n\n\n        // Now let's use the solve_least_squares_lm() routine to figure out what the\n        // parameters are based on just the data_samples.\n        parameter_vector x;\n        x = params;\n\n        //cout << \"Use Levenberg-Marquardt\" << endl;\n        // Use the Levenberg-Marquardt method to determine the parameters which\n        // minimize the sum of all squared residuals.\n        solve_least_squares_lm(objective_delta_stop_strategy(1e-7),\n                               residual,\n                               residual_derivative,\n                               DS,\n                               x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        //cout << \"inferred parameters: \"<< trans(x) << endl;\n        //cout << \"solution error:      \"<< length(x - params) << endl;\n        //cout << endl;\n        cout << trans(x) << endl;\n\n\n        /*\n\n        x = params;\n        cout << \"Use Levenberg-Marquardt, approximate derivatives\" << endl;\n        // If we didn't create the residual_derivative function then we could\n        // have used this method which numerically approximates the derivatives for you.\n        solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \n                               residual,\n                               derivative(residual),\n                               DS,\n                               x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        cout << \"inferred parameters: \"<< trans(x) << endl;\n        cout << \"solution error:      \"<< length(x - params) << endl;\n        cout << endl;\n\n\n\n\n        x = params;\n        cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << endl;\n        // This version of the solver uses a method which is appropriate for problems\n        // where the residuals don't go to zero at the solution.  So in these cases\n        // it may provide a better answer.\n        solve_least_squares(objective_delta_stop_strategy(1e-7).be_verbose(), \n                            residual,\n                            residual_derivative,\n                            DS,\n                            x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        cout << \"inferred parameters: \"<< trans(x) << endl;\n        cout << \"solution error:      \"<< length(x - params) << endl;\n        */\n\n    }\n    catch (std::exception& e)\n    {\n        cout << e.what() << endl;\n    }\n}\n", "meta": {"hexsha": "a48de070d614b93c8fe4f45e1bd53554fcc3d36e", "size": 9285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lgnrmfit.cpp", "max_stars_repo_name": "giorgk/lgnrmfit", "max_stars_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lgnrmfit.cpp", "max_issues_repo_name": "giorgk/lgnrmfit", "max_issues_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lgnrmfit.cpp", "max_forks_repo_name": "giorgk/lgnrmfit", "max_forks_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_forks_repo_licenses": ["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.7752808989, "max_line_length": 100, "alphanum_fraction": 0.5018847604, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6934917322296218}}
{"text": "#include \"average_case_relative_error.hpp\"\n#include \"average_case_error.hpp\"\n#include \"cudd_helpers.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace abo::error_metrics {\n    std::pair<boost::multiprecision::cpp_dec_float_100, boost::multiprecision::cpp_dec_float_100>\n            average_relative_value(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &g) {\n\n        BDD zero_so_far = mgr.bddOne();\n\n        boost::multiprecision::cpp_dec_float_100 min_average_result = 0;\n        boost::multiprecision::cpp_dec_float_100 max_average_result = 0;\n        std::vector<BDD> max_one = abo::util::bdd_max_one(mgr, g);\n        for (int i = int(g.size())-1;i>=0;i--) {\n            std::vector<BDD> partial_result;\n            partial_result.reserve(max_one.size());\n            BDD modifier = zero_so_far & max_one[i];\n            for (const BDD &b : f) {\n                partial_result.push_back(b & modifier);\n            }\n            auto average = average_value(partial_result);\n            min_average_result += average  / (std::pow(2.0, i + 1) - 1);\n            max_average_result += average  / std::pow(2.0, i);\n\n            zero_so_far &= !max_one[i];\n        }\n\n        return {min_average_result, max_average_result};\n    }\n\n    std::pair<boost::multiprecision::cpp_dec_float_100, boost::multiprecision::cpp_dec_float_100>\n            average_relative_error_bounds(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                                          const util::NumberRepresentation num_rep) {\n\n        std::vector<BDD> absolute_difference = abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n        return average_relative_value(mgr, absolute_difference, abo::util::abs(mgr, f));\n    }\n\n    boost::multiprecision::cpp_dec_float_100 average_relative_error_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                                                                        const NumberRepresentation num_rep) {\n\n        ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);\n        ADD respective_diff = diff.Divide(abo::util::bdd_forest_to_add(mgr, abo::util::abs(mgr, f)).Maximum(mgr.addOne()));\n        std::vector<std::pair<double, unsigned long>> terminal_values = abo::util::add_terminal_values(respective_diff);\n\n        boost::multiprecision::cpp_dec_float_100 sum = 0;\n        boost::multiprecision::uint256_t path_sum = 0;\n        for (auto p : terminal_values) {\n            boost::multiprecision::cpp_dec_float_100 value(p.first);\n            sum += value * p.second;\n            path_sum += p.second;\n        }\n        return boost::multiprecision::cpp_dec_float_100(sum) /\n                boost::multiprecision::cpp_dec_float_100(path_sum);\n    }\n\n    boost::multiprecision::cpp_dec_float_100 average_relative_error_symbolic_division(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat,\n                                                                                      unsigned int num_extra_bits, const NumberRepresentation num_rep) {\n\n        std::vector<BDD> absolute_difference = abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n\n        std::vector<BDD> no_zero = abo::util::bdd_max_one(mgr, abo::util::abs(mgr, f));\n        std::vector<BDD> divided = abo::util::bdd_divide(mgr, absolute_difference, no_zero, num_extra_bits);\n\n        return average_value(divided) / std::pow(2.0, num_extra_bits);\n    }\n\n}\n", "meta": {"hexsha": "8b344f78eb762ceb7ec3c508f29fd7f7cb7378ea", "size": 3489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_stars_repo_name": "andreaswendler/abo", "max_stars_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_stars_repo_licenses": ["MIT"], "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/error_metrics/average_case_relative_error.cpp", "max_issues_repo_name": "andreaswendler/abo", "max_issues_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_issues_repo_licenses": ["MIT"], "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/error_metrics/average_case_relative_error.cpp", "max_forks_repo_name": "andreaswendler/abo", "max_forks_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_forks_repo_licenses": ["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.8428571429, "max_line_length": 160, "alphanum_fraction": 0.633992548, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6934917255246059}}
{"text": "/*\n * libcluster -- A collection of hierarchical Bayesian clustering algorithms.\n * Copyright (C) 2013 Daniel M. Steinberg (daniel.m.steinberg@gmail.com)\n *\n * This file is part of libcluster.\n *\n * libcluster is free software: you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation, either version 3 of the License, or (at your option)\n * any later version.\n *\n * libcluster is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with libcluster. If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"probutils.h\"\n#include <boost/math/special_functions.hpp>\n\n\n//\n// Namespaces\n//\n\n\nusing namespace std;\nusing namespace Eigen;\n\n\n//\n// Local Constants\n//\n\n\nconst double EIGCONTHRESH = 1.0e-8f;\nconst int    MAXITER      = 100;\n\n\n//\n// Public Functions\n//\n\n\nRowVectorXd probutils::mean (const MatrixXd& X)\n{\n  return X.colwise().sum()/X.rows();\n}\n\n\nRowVectorXd probutils::mean (const vector<MatrixXd>& X)\n{\n  const int J = X.size(),\n            D = X[0].cols();\n  int N = 0;\n  RowVectorXd mean = RowVectorXd::Zero(D);\n\n  for (int j = 0; j < J; ++j)\n  {\n    if (X[j].cols() != D)\n      throw invalid_argument(\"X dimensions are inconsistent between groups!\");\n\n    mean += X[j].colwise().sum();\n    N    += X[j].rows();\n  }\n  return mean / N;\n}\n\n\nRowVectorXd probutils::stdev (const MatrixXd& X)\n{\n  RowVectorXd meanX = mean(X);\n  return ((X.rowwise() - meanX).array().square().colwise().sum()\n          / (X.rows()-1)).sqrt();\n}\n\n\nMatrixXd probutils::cov (const MatrixXd& X)\n{\n  if (X.rows() <= 1)\n    throw invalid_argument(\"Insufficient no. of observations.\");\n\n  MatrixXd X_mu = X.rowwise() - probutils::mean(X); // X - mu\n  return (X_mu.transpose()*X_mu)/(X.rows()-1);      // (X-mu)'*(X-mu)/(N-1)\n}\n\n\nMatrixXd probutils::cov (const vector<MatrixXd>& X)\n{\n  const int J = X.size(),\n            D = X[0].cols();\n  int N = 0;\n  const RowVectorXd mean = probutils::mean(X);\n  MatrixXd cov = MatrixXd::Zero(D, D),\n           X_mu;\n\n  for (int j = 0; j < J; ++j)\n  {\n    if (X[j].rows() <= 1)\n      throw invalid_argument(\"Insufficient no. of observations.\");\n    X_mu = X[j].rowwise() - mean;\n    N   += X[j].rows();\n    cov.noalias() += (X_mu.transpose() * X_mu); // (X_j-mu)'*(X_j-mu)\n  }\n\n  return cov / (N-1);\n}\n\n\nVectorXd probutils::mahaldist (\n    const MatrixXd& X,\n    const RowVectorXd& mu,\n    const MatrixXd& A\n    )\n{\n  // Check for same number of dimensions, D\n  if((X.cols() != mu.cols()) || (X.cols() != A.cols()))\n    throw invalid_argument(\"Arguments do not have the same dimensionality\");\n\n  // Check if A is square\n  if (A.rows() != A.cols())\n    throw invalid_argument(\"Matrix A must be square!\");\n\n  // Decompose A\n  LDLT<MatrixXd> Aldl(A);\n\n  // Check if A is PD\n  if ((Aldl.vectorD().array() <= 0).any() == true)\n    throw invalid_argument(\"Matrix A is not positive definite\");\n\n  // Do the Mahalanobis distance for each sample (N times)\n  MatrixXd X_mu = (X.rowwise() - mu).transpose();\n  return ((X_mu.array() * (Aldl.solve(X_mu)).array())\n          .colwise().sum()).transpose();\n}\n\n\nVectorXd probutils::logsumexp (const MatrixXd& X)\n{\n  const VectorXd mx = X.rowwise().maxCoeff(); // Get max of each row\n\n  // Perform the sum(exp(x - mx)) part\n  ArrayXd se = ((X.colwise() - mx).array().exp()).rowwise().sum();\n\n  // return total log(sum(exp(x))) - hoping for return value optimisation\n  return (se.log()).matrix() + mx;\n}\n\n\ndouble probutils::eigpower (const MatrixXd& A, VectorXd& eigvec)\n{\n  // Check if A is square\n  if (A.rows() != A.cols())\n    throw invalid_argument(\"Matrix A must be square!\");\n\n  // Check if A is a scalar\n  if (A.rows() == 1)\n  {\n    eigvec.setOnes(1);\n    return A(0,0);\n  }\n\n  // Initialise working vectors\n  VectorXd v = VectorXd::LinSpaced(A.rows(), -1, 1);\n  VectorXd oeigvec(A.rows());\n\n  // Initialise eigenvalue and eigenvectors etc\n  double eigval = v.norm();\n  double vdist = numeric_limits<double>::infinity();\n  eigvec = v/eigval;\n\n  // Loop until eigenvector converges or we reach max iterations\n  for (int i=0; (vdist>EIGCONTHRESH) && (i<MAXITER); ++i)\n  {\n    oeigvec = eigvec;\n    v.noalias() = A * oeigvec;\n    eigval = v.norm();\n    eigvec = v/eigval;\n    vdist = (eigvec - oeigvec).norm();\n  }\n\n  return eigval;\n}\n\n\ndouble probutils::logdet (const MatrixXd& A)\n{\n  // Check if A is square\n  if (A.rows() != A.cols())\n    throw invalid_argument(\"Matrix A must be square!\");\n\n  VectorXd d = A.ldlt().vectorD();  // Get the diagonal from a Cholesky decomp.\n\n  // Check if A is PD\n  if ((d.array() <= 0).any() == true)\n    throw domain_error(\"Matrix A is not positive definite.\");\n\n  return (d.array().log()).sum();   // ln(det(A)) = sum(log(d))\n}\n\n\nMatrixXd probutils::mxdigamma (const MatrixXd& X)\n{\n  const int I = X.rows(),\n            J = X.cols();\n  MatrixXd result(I, J);\n\n  for (int i = 0; i < I; ++i)\n    for (int j = 0; j < J; ++j)\n      result(i,j) = boost::math::digamma(X(i, j));\n\n  return result;\n}\n\n\nMatrixXd probutils::mxlgamma (const MatrixXd& X)\n{\n  const int I = X.rows(),\n            J = X.cols();\n  MatrixXd result(I, J);\n\n  for (int i = 0; i < I; ++i)\n    for (int j = 0; j < J; ++j)\n      result(i, j) = boost::math::lgamma(X(i, j));\n\n  return result;\n}\n", "meta": {"hexsha": "6a32e4499296eac7dbb91185bdd4820c190fcd35", "size": 5510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/LibCluster/src/probutils.cpp", "max_stars_repo_name": "mfkiwl/ICE", "max_stars_repo_head_hexsha": "e660d031bb1bcea664db1de4946fd8781be5b627", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-10-12T01:22:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T23:28:26.000Z", "max_issues_repo_path": "3rdparty/LibCluster/src/probutils.cpp", "max_issues_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_issues_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/LibCluster/src/probutils.cpp", "max_forks_repo_name": "wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation", "max_forks_repo_head_hexsha": "2f1ff054b7c5059da80bb3b2f80c05861a02cc36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2019-11-05T01:50:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:23:44.000Z", "avg_line_length": 23.8528138528, "max_line_length": 79, "alphanum_fraction": 0.6181488203, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.693486048901551}}
{"text": "#ifndef PDC_gauss_hh_included\n#define PDC_gauss_hh_included\n\n#include <dlib/optimization.h>\n#include <iostream>\n#include <vector>\n\n#include \"../classes/structs.hh\"\n\ntypedef dlib::matrix<double,2,1> input_vector;\ntypedef dlib::matrix<double,3,1> parameter_vector;\n\n// ----------------------------------------------------------------------------------------\n\n// We will use this function to generate data.  It represents a function of 2 variables\n// and 3 parameters.   The least squares procedure will be used to infer the values of\n// the 3 parameters based on a set of input/output pairs.\ndouble model (\n    const input_vector& input,\n    const parameter_vector& params\n)\n{\n    const double p0 = params(0);\n    const double p1 = params(1);\n    const double p2 = params(2);\n\n    const double i0 = input(0);\n    const double i1 = input(1);\n\n    const double temp = p0*i0 + p1*i1 + p2;\n\n    return temp*temp;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the \"residual\" for a least squares problem.   It takes an input/output\n// pair and compares it to the output of our model and returns the amount of error.  The idea\n// is to find the set of parameters which makes the residual small on all the data pairs.\ndouble residual (\n    const std::pair<input_vector, double>& data,\n    const parameter_vector& params\n)\n{\n    return model(data.first, params) - data.second;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the derivative of the residual() function with respect to the parameters.\nparameter_vector residual_derivative (\n    const std::pair<input_vector, double>& data,\n    const parameter_vector& params\n)\n{\n    parameter_vector der;\n\n    const double p0 = params(0);\n    const double p1 = params(1);\n    const double p2 = params(2);\n\n    const double i0 = data.first(0);\n    const double i1 = data.first(1);\n\n    const double temp = p0*i0 + p1*i1 + p2;\n\n    der(0) = i0*2*temp;\n    der(1) = i1*2*temp;\n    der(2) = 2*temp;\n\n    return der;\n}\n\nPDC::gaussParameter fitGauss(std::vector<double>& xVals, std::vector<double>& yValsData, PDC::gaussParameter initialParams) {\n    try {\n        // randomly pick a set of parameters to use in this example\n        const parameter_vector params = 10*dlib::randm(3,1);\n        std::cout << \"params: \" << trans(params) << std::endl;\n\n\n        // Now let's generate a bunch of input/output pairs according to our model.\n        std::vector<std::pair<input_vector, double> > data_samples;\n        input_vector input;\n        for (int i = 0; i < 1000; ++i)\n        {\n            input = 10*dlib::randm(2,1);\n            const double output = model(input, params);\n\n            // save the pair\n            data_samples.push_back(std::make_pair(input, output));\n        }\n\n        // Before we do anything, let's make sure that our derivative function defined above matches\n        // the approximate derivative computed using central differences (via derivative()).\n        // If this value is big then it means we probably typed the derivative function incorrectly.\n        std::cout << \"derivative error: \" << length(residual_derivative(data_samples[0], params) -\n                                               derivative(residual)(data_samples[0], params) ) << std::endl;\n\n\n\n\n\n        // Now let's use the solve_least_squares_lm() routine to figure out what the\n        // parameters are based on just the data_samples.\n        parameter_vector x;\n        x = 1;\n\n        std::cout << \"Use Levenberg-Marquardt\" << std::endl;\n        // Use the Levenberg-Marquardt method to determine the parameters which\n        // minimize the sum of all squared residuals.\n        dlib::solve_least_squares_lm(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n                               residual,\n                               residual_derivative,\n                               data_samples,\n                               x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n        std::cout << \"solution error:      \"<< length(x - params) << std::endl;\n        std::cout << std::endl;\n\n\n\n\n        x = 1;\n        std::cout << \"Use Levenberg-Marquardt, approximate derivatives\" << std::endl;\n        // If we didn't create the residual_derivative function then we could\n        // have used this method which numerically approximates the derivatives for you.\n        dlib::solve_least_squares_lm(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n                               residual,\n                               derivative(residual),\n                               data_samples,\n                               x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n        std::cout << \"solution error:      \"<< length(x - params) << std::endl;\n        std::cout << std::endl;\n\n\n\n\n        x = 1;\n        std::cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << std::endl;\n        // This version of the solver uses a method which is appropriate for problems\n        // where the residuals don't go to zero at the solution.  So in these cases\n        // it may provide a better answer.\n        dlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n                            residual,\n                            residual_derivative,\n                            data_samples,\n                            x);\n\n        // Now x contains the solution.  If everything worked it will be equal to params.\n        std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n        std::cout << \"solution error:      \"<< length(x - params) << std::endl;\n\n    }\n    catch (std::exception& e) {\n        std::cout << \"Error while fitting: \" << e.what() << std::endl;\n    }\n}\n\n#endif /* PDC_gauss_hh_included */\n", "meta": {"hexsha": "aa0ea180167d804b0e2f9c2c84bc92e078af79c0", "size": 6053, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/util/fit_gauss.hh", "max_stars_repo_name": "ClundXIII/timepix-data-crunching", "max_stars_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "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/util/fit_gauss.hh", "max_issues_repo_name": "ClundXIII/timepix-data-crunching", "max_issues_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "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/util/fit_gauss.hh", "max_forks_repo_name": "ClundXIII/timepix-data-crunching", "max_forks_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "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.6848484848, "max_line_length": 125, "alphanum_fraction": 0.5833471006, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6934535086556761}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Tridiagonalization<MatrixXf> tri;\nMatrixXf X = MatrixXf::Random(4,4);\nMatrixXf A = X + X.transpose();\ntri.compute(A);\ncout << \"The matrix T in the tridiagonal decomposition of A is: \" << endl;\ncout << tri.matrixT() << endl;\ntri.compute(2*A); // re-use tri to compute eigenvalues of 2A\ncout << \"The matrix T in the tridiagonal decomposition of 2A is: \" << endl;\ncout << tri.matrixT() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "aaf3c19b5aa3ddafa20f35a0558466aba4d57920", "size": 612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Tridiagonalization_compute.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Tridiagonalization_compute.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Tridiagonalization_compute.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 22.6666666667, "max_line_length": 75, "alphanum_fraction": 0.7026143791, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252812, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6933745064209996}}
{"text": "#include <iostream>\n#include <cmath>\n#include <string>\n#include <random>\n#include <chrono>\n#include <fstream>\n#include <tuple>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/SparseExtra>\n#include \"block_iterative_solvers.hpp\"\n#include \"linear_algebra_addon.hpp\"\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::chrono;\n\nint main(int argc, char *argv[]){\n\n    double tol= 1e-8;\n    int itermax= 1000;\n\n    std::srand((unsigned int) time(0));\n    int L=atoi(argv[1]); // dimension of matrix A\n\n    MatrixXcd A;\n\n\n    switch (argc)\n    {\n    case 2:\n        {\n        // load A from a file in matrix market format .mtx\n        cout << \"please enter filename for A (.mtx): \" ;\n        string matfname;\n        cin >> matfname;\n        SparseMatrix<complex<double>> mat;\n        //Matrix collections is available in   http://www.cise.ufl.edu/research/sparse/matrices/\n        if(!loadMarket(mat,matfname)){\n            cerr << \"can't open file\" << matfname << endl;\n            exit(EXIT_FAILURE);\n        }\n        cout << \"A was loaded from \" <<  matfname << endl;\n        A= MatrixXcd(mat);\n\n        break;\n        }\n    case 3:\n        {\n        // Set A as a random matrix\n        int n=atoi(argv[2]); // number of RHS vector\n        A= MatrixXcd::Random(n,n);\n        A= A.transpose()*A; // complex-symmetric\n        cout << \"A is a \" << n << \" x \" << n << \" square random matrix\" << endl;\n        break;\n        }\n    default:\n        {\n\n        break;\n        }\n    }\n\n    MatrixXcd B= MatrixXcd::Random(A.rows(),L);\n\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_cocg_rq ...\" << endl;\n            MatrixXcd X= bl_cocg_rq(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n        cout << \" bl_cocg_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_cocg_rq computation time= \" << duration_cast<seconds>((end - start)).count()  << \" sec\" << endl << endl<< endl;\n    }\n\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_bicg_rq ...\" << endl;\n            MatrixXcd X= bl_bicg_rq(A, B, tol, itermax); // applicable to general matrix A but needs A.adjoint()\n        cout << \" bl_bicg_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_bicg_rq computation time= \" << duration_cast<seconds>((end - start)).count() << \" sec\" << endl << endl<< endl;\n    }\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_bicr_rq ...\" << endl;\n            MatrixXcd X= bl_bicr_rq(A, B, tol, itermax); // applicable to general matrix A but needs A.adjoint()\n        cout << \" bl_bicr_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_bicr_rq computation time= \" << duration_cast<seconds>((end - start)).count() << \" sec\" << endl << endl<< endl;\n    }\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_bicgstab_rq ...\" << endl;\n            MatrixXcd X= bl_bicgstab_rq(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n        cout << \" bl_bicgstab_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_bicgstab_rq computation time= \" << duration_cast<seconds>((end - start)).count() << \" sec\" << endl << endl<< endl;\n    }\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_bicgstab ...\" << endl;\n            MatrixXcd X= bl_bicgstab(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n        cout << \" bl_bicgstab relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_bicgstab computation time= \" << duration_cast<seconds>((end - start)).count() << \" sec\" << endl << endl<< endl;\n    }\n\n    {\n        time_point<steady_clock> start= steady_clock::now();\n        cout << \"solving AX=B using bl_bicggr ...\" << endl;\n            MatrixXcd X= bl_bicggr(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n        cout << \" bl_bicggr relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n        auto end= steady_clock::now();\n        cout << \"bl_bicggr computation time= \" << duration_cast<seconds>((end - start)).count() << \" sec\" << endl << endl<< endl;\n    }\n\n\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "1085584672ccf39873a2aec322f0a09c7b136832", "size": 4619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "block_iterative_solvers_test.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": "block_iterative_solvers_test.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": "block_iterative_solvers_test.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": 35.8062015504, "max_line_length": 134, "alphanum_fraction": 0.5780471964, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.693306805734782}}
{"text": "#include <iostream>\n#include <ctime>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\nint main(int argc, char** argv) {\n    Eigen::Matrix<float,2,3> matrix_23;\n    Eigen::Vector3d v_3d;//Matrix<double,3,1>\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();//Matrix<double,3,3>\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_dynamic;\n    Eigen::MatrixXd matric_x;\n\n    matrix_23<<1,2,3,4,5,6;\n    cout<<matrix_23<<endl;\n\n    for (int i = 0; i < 1 ; i++)\n        for (int j = 0; j < 2 ; j++)\n            cout<<matrix_23(i,j)<<endl;\n\n    v_3d<<3,2,1;\n    Eigen::Matrix<double,2,1> result=matrix_23.cast<double>()*v_3d; //cast \u8f6c\u6362\u7c7b\u578b\n    cout<<result<<endl;\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<<matrix_33.inverse()<<endl;\n    cout<<matrix_33.determinant()<<endl;\n\n    //\u7279\u5f81\u503c\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver (matrix_33);\n    cout<< \"Eigen values = \"<<eigen_solver.eigenvalues() <<endl;\n    cout<< \"Eigen vectors = \"<<eigen_solver.eigenvectors() <<endl;\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    //\u8ba1\u65f6\n    clock_t time_stt=clock();\n    Eigen::Matrix<double,MATRIX_SIZE,1> x=matrix_NN.inverse()*v_Nd;\n    cout<<\"time use in normal inverse is \"<<1000*(clock()-time_stt)/(double)CLOCKS_PER_SEC<<\"ms\"<<endl;\n\n    time_stt=clock();\n    x =matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout<<\"time use in Qr composition is \"<<1000*(clock()-time_stt)/(double)CLOCKS_PER_SEC<<\"ms\"<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "561e09030c8091ab0799ac4650ed68a47dcb904b", "size": 1868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3_Eigen/eigenMatrix.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3_Eigen/eigenMatrix.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3_Eigen/eigenMatrix.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2068965517, "max_line_length": 103, "alphanum_fraction": 0.658993576, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6933068039764526}}
{"text": "/********************************************************************\r\n * Implements multivariate regression analysis in an attempt to learn\r\n * the weight/hypothesis coefficients for a system of eqations.\r\n * Created: Jun 17 2020 \r\n * Author: Ethan Patterson\r\n *******************************************************************/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <Eigen/Dense> // Linear Algebra library. Don't forget to add path to Makefile.\r\n\r\n#include \"HousingData.h\" // For reading data files.\r\n\r\n#ifndef ITR\r\n#define ITR 2000\r\n#endif\r\n\r\n#ifndef ALPHA\r\n#define ALPHA 0.01\r\n#endif\r\n\r\n// Made for convinance of managing \r\n// the max and min values of the data.\r\nstruct Tuple{\r\n    float x;\r\n    float y;\r\n};\r\n\r\nvoid loadData(Eigen::MatrixXf &X, Eigen::VectorXf &Y, std::ifstream &fp){\r\n    int r = 0;\r\n    HousingData data;\r\n    // Read data line by line and sotre it into X matrix.\r\n    while (fp >> data){\r\n        // Again this could be put into an array.\r\n        // See HousingData.h for why it is currently structered this way.\r\n        //X(r,0) = 1; // Dummy value.\r\n        X(r,0) = std::stof(data.crim, NULL);\r\n        X(r,1) = std::stof(data.zn, NULL);\r\n        X(r,2) = std::stof(data.indus, NULL);\r\n        X(r,3) = std::stof(data.chas, NULL);\r\n        X(r,4) = std::stof(data.nox, NULL);\r\n        X(r,5) = std::stof(data.rm, NULL);\r\n        X(r,6) = std::stof(data.age, NULL);\r\n        X(r,7) = std::stof(data.dis, NULL);\r\n        X(r,8) = std::stof(data.rad, NULL);\r\n        X(r,9) = std::stof(data.tax, NULL);\r\n        X(r,10) = std::stof(data.ptratio, NULL);\r\n        X(r,11) = std::stof(data.B, NULL);\r\n        X(r,12) = std::stof(data.lstat, NULL);\r\n\r\n        Y(r) = std::stof(data.medv, NULL); // Values of interest.\r\n        r++;\r\n    }\r\n\r\n    fp.clear();\r\n    fp.seekg(0, fp.beg);// Reset to head of file. \r\n}\r\n/**\r\n * @param fp is a file pointer.\r\n * Function gets the number of rows in a file.\r\n */\r\nint getFileRowCount(std::ifstream &fp){\r\n    int num_of_rows = 0;\r\n    std::string rows;\r\n    while (std::getline( fp, rows ))\r\n        num_of_rows++;\r\n    \r\n    fp.clear();\r\n    fp.seekg(0, fp.beg); // Reset to head of file.\r\n    return num_of_rows;\r\n}\r\n\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param W Learned vector of weight coefficients\r\n * @param Y Vector of Response Variables.\r\n * Measures the Sum Squared Error of the learned weights.\r\n */\r\nfloat leastSquares(Eigen::MatrixXf &X, Eigen::VectorXf &W, Eigen::VectorXf &Y){\r\n    Eigen::VectorXf e( Y.size() );\r\n    e = (Y - X*W);\r\n    for (int i = 0; i < e.size(); i++)\r\n        e[i] = e[i]*e[i]/Y.size();\r\n\r\n    return (float)e.sum();\r\n}\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param W Learned vector of weight coefficients, hypothosis.\r\n * @param Y Vector of Response Variables.\r\n * @param alpha The learning rate to apply.\r\n * @param iter The number of iterations to complete.\r\n * Use batch gradient descent to minimize the cost/error of the system.\r\n * Returns the cost history of the system over iterations.\r\n */\r\nfloat* BGD(Eigen::MatrixXf &X, Eigen::VectorXf &W, Eigen::VectorXf &Y, float alpha, int itr, const Tuple &maxmin){\r\n    Eigen::VectorXf Hypo ( Y.size() );\r\n    Eigen::VectorXf Loss ( Y.size() );\r\n    Eigen::VectorXf Gradient ( Y.size() );\r\n    float* costHistory = new float[itr];\r\n\r\n    float cost = 0.0;\r\n    for (int i = 0; i < itr; i++){\r\n        Hypo = X*W;\r\n        Loss = Hypo - Y;\r\n        Gradient = (X.transpose() * Loss) / Y.size();\r\n        W = W - alpha * Gradient;\r\n        cost = leastSquares(X, W, Y);\r\n        costHistory[i] = cost*(maxmin.x - maxmin.y) + maxmin.y;\r\n    }\r\n    return costHistory;\r\n}\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param Y Vector of Response Variables.\r\n * Nomralize the data between 0 and 1.\r\n * Returns a tuple of the max and min value.\r\n * Max is the x component and min is the y.\r\n */\r\nTuple normalize(Eigen::MatrixXf &X, Eigen::VectorXf &Y){\r\n    float max_x, max_y, max;\r\n    float min_x, min_y, min;\r\n    Tuple maxmin;\r\n\r\n    Eigen::MatrixXf::Index maxRow,maxCol;\r\n    Eigen::MatrixXf::Index minRow,minCol;\r\n\r\n    max_x = X.maxCoeff(&maxRow, &maxCol);\r\n    max_y = Y.maxCoeff(&maxRow, &maxCol);\r\n\r\n    min_x = X.minCoeff(&minRow, &minCol);\r\n    min_y = Y.minCoeff(&minRow, &minCol);\r\n    \r\n    if (max_x < max_y)\r\n        max = max_y;\r\n    else\r\n        max = max_x;\r\n\r\n    if (min_x < min_y)\r\n        min = min_x;\r\n    else\r\n        min = min_y;\r\n\r\n    for (int i = 0; i < X.rows(); i++){\r\n        for (int j = 0; j < X.cols(); j++){\r\n            X(i,j) = (X(i,j) - min) / (max - min);\r\n        }\r\n    }\r\n    \r\n    for (int i = 0; i < Y.rows(); i++)\r\n        Y(i) = (Y(i) - min) / (max - min);\r\n        \r\n    maxmin.x = max;\r\n    maxmin.y = min;\r\n\r\n    return maxmin;\r\n}\r\n/**\r\n * @param cost Dynamic array of cost history.\r\n * @param W Learned vector of weight coefficients, hypothesis.\r\n * @param Y Vector of Response Variables.\r\n * Saves data produced such as the cost history, weights/hypotheses, and normalization min max.\r\n */\r\nvoid saveData(float *cost, const Tuple &maxmin, Eigen::VectorXf &W){\r\n    std::ofstream weights(\"weights.csv\");\r\n    std::ofstream norm(\"normalize.csv\");\r\n    std::ofstream costHistory(\"cost_history.csv\");\r\n\r\n    if (weights.is_open()){\r\n        for (int i = 0; i < W.size()-1; i++)\r\n            weights << W(i) << \",\";\r\n        weights << W(W.size()-1);\r\n    }\r\n    weights.close();\r\n\r\n    if (norm.is_open()){\r\n        norm << \"max\" << \",\" << maxmin.x << \"\\n\";\r\n        norm << \"min\" << \",\" << maxmin.y << \"\\n\";  \r\n    }\r\n    norm.close();\r\n\r\n    if(costHistory.is_open()){\r\n        for (int i = 0; i < ITR; i++)\r\n            if ( i % 2 ) // No need to see cost at every step.\r\n                costHistory << i << \",\" << cost[i] << \"\\n\";\r\n    }\r\n    costHistory.close();\r\n}\r\n\r\nint main()\r\n{\r\n    // Files in training and testing data.\r\n    std::ifstream fp_train(\"./data/data/housing_train.csv\");\r\n    std::ifstream fp_test(\"./data/data/housing_test.csv\");\r\n\r\n    // Build maxtix for traning and testing data.\r\n    Eigen::MatrixXf X(getFileRowCount(fp_train), COL_SIZE);\r\n    Eigen::MatrixXf X_test(getFileRowCount(fp_test), COL_SIZE);\r\n    \r\n    // Build Vectors for target variables and weight/hypotheses.\r\n    Eigen::VectorXf Y( X.rows() );\r\n    Eigen::VectorXf Y_test( X_test.rows() );\r\n    Eigen::VectorXf W ( X.cols() );// Size is the number of features/dimensions.\r\n\r\n    Tuple maxmin; // Used to keep track of max and min value during normalization.\r\n    float *costHistory; // Pointer for array to cost history.\r\n\r\n    // Load data into matrices and vectors.\r\n    loadData(X, Y, fp_train);\r\n    loadData(X_test, Y_test, fp_test);\r\n    fp_train.close(); // Don't need this anymore, data is now in the matrix.\r\n    fp_test.close();\r\n\r\n    // Set all initial weight/hypothesis values to 0.\r\n    W = Eigen::VectorXf::Ones( X.cols() ) * 0;\r\n    \r\n    normalize(X, Y); // Normalize data.\r\n    maxmin = normalize(X_test, Y_test); // Keep max and min values for future data sets.\r\n    std::cout << \"Max: \" << maxmin.x << \" Min: \" << maxmin.y << std::endl;\r\n\r\n    // Run batch gradient descent.\r\n    costHistory = BGD(X, W, Y, ALPHA, ITR, maxmin);\r\n    std::cout << \"SSE for training set: \" << leastSquares(X, W, Y) *\r\n     (maxmin.x - maxmin.y) + maxmin.y << std::endl;\r\n    std::cout << \"SSE for testing set: \" << leastSquares(X_test, W, Y_test) *\r\n     (maxmin.x - maxmin.y) + maxmin.y << std::endl;\r\n\r\n    saveData(costHistory, maxmin, W);\r\n    delete costHistory;\r\n\r\n    return 0;\r\n}", "meta": {"hexsha": "cbd755591ea7c73227a84b1c7e478d49b8e72c90", "size": 7545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression.cpp", "max_stars_repo_name": "boxman888/LinearRegression", "max_stars_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T06:15:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T06:15:08.000Z", "max_issues_repo_path": "regression.cpp", "max_issues_repo_name": "boxman888/LinearRegression", "max_issues_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "boxman888/LinearRegression", "max_forks_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_forks_repo_licenses": ["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.5215517241, "max_line_length": 115, "alphanum_fraction": 0.5676607025, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6932968234115391}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\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\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE linalg_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/eigenio_matrixmarket.h\"\n#include \"votca/tools/linalg.h\"\n\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(linalg_test)\n\nBOOST_AUTO_TEST_CASE(linalg_constrained_qrsolve_test) {\n\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(3);\n  b(0) = 11;\n  b(1) = -3;\n  b(2) = 8;\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3, 3);\n  A(0, 0) = 1;\n  A(0, 1) = 1;\n  A(0, 2) = 1;\n  A(1, 0) = 1;\n  A(1, 1) = -1;\n  A(2, 1) = 1;\n  A(2, 2) = 1;\n\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(1, 3);\n  B(0, 1) = -1;\n  B(0, 2) = 3;\n  Eigen::VectorXd x = linalg_constrained_qrsolve(A, b, B);\n  Eigen::VectorXd x_ref = Eigen::VectorXd::Zero(3);\n  x_ref(0) = 3;\n  x_ref(1) = 6;\n  x_ref(2) = 2;\n\n  bool equal = x_ref.isApprox(x, 1e-7);\n\n  if (!equal) {\n    std::cout << \"result\" << std::endl;\n    std::cout << x << std::endl;\n    std::cout << \"ref\" << std::endl;\n    std::cout << x_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal, true);\n}\n\nBOOST_AUTO_TEST_CASE(linalg_mkl_test) {\n\n  votca::Index nmax = 10;\n\n  Eigen::MatrixXd H = EigenIO_MatrixMarket::ReadMatrix(\n      std::string(TOOLS_TEST_DATA_FOLDER) + \"/linalg/H.mm\");\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(H);\n  Eigen::MatrixXd V_ref = es.eigenvectors().block(0, 0, H.rows(), nmax);\n  Eigen::VectorXd E_ref = es.eigenvalues().segment(0, nmax);\n\n  EigenSystem result = linalg_eigenvalues(H, nmax);\n  bool check_energy = E_ref.isApprox(result.eigenvalues(), 0.0001);\n\n  bool check_vector =\n      result.eigenvectors().cwiseAbs().isApprox(V_ref.cwiseAbs(), 0.0001);\n\n  if (!check_vector || !check_energy) {\n    std::cout << \"E_ref\" << std::endl;\n    std::cout << E_ref << std::endl;\n    std::cout << \"E\" << std::endl;\n    std::cout << result.eigenvalues() << std::endl;\n    std::cout << \"V_ref\" << std::endl;\n    std::cout << V_ref << std::endl;\n    std::cout << \"V\" << std::endl;\n    std::cout << result.eigenvectors() << std::endl;\n  }\n\n  BOOST_CHECK_EQUAL(check_energy, 1);\n  BOOST_CHECK_EQUAL(check_vector, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "ab1c033d0cf57004398048e893181f0e86f3107a", "size": 2842, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_linalg.cc", "max_stars_repo_name": "MrTheodor/tools", "max_stars_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "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/tests/test_linalg.cc", "max_issues_repo_name": "MrTheodor/tools", "max_issues_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "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/tests/test_linalg.cc", "max_forks_repo_name": "MrTheodor/tools", "max_forks_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "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": 27.3269230769, "max_line_length": 75, "alphanum_fraction": 0.6586910626, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6932046107533071}}
{"text": "#include \"case.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\nCase1::Case1(const Ref<const MatrixXd> &matM, const Ref<const MatrixXd> &matD,\n             const Ref<const MatrixXd> &matK)\n\n    : ndim_(matM.cols()), matM_(matM), matD_(matD), matK_(matK),\n      matC_(ndim_ * 2, ndim_ * 2), matG_(ndim_ * 2, ndim_ * 2),\n      alphas(ndim_ * 2), betas(ndim_ * 2) {\n  MatrixXd mzero = MatrixXd::Zero(ndim_, ndim_);\n  MatrixXd mone = MatrixXd::Identity(ndim_, ndim_);\n  matC_ << -matD_, -matK_, mone, mzero;\n  matG_ << matM_, mzero, mzero, mone;\n\n  GeneralizedEigenSolver<MatrixXd> ges(matC_, matG_, false);\n  alphas = ges.alphas();\n  betas = ges.betas();\n}\n", "meta": {"hexsha": "e3d62d6c5fb8b4e286afbc8e070af9724584d87e", "size": 688, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/case.cc", "max_stars_repo_name": "pan3rock/QuadEigsSOAR", "max_stars_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/case.cc", "max_issues_repo_name": "pan3rock/QuadEigsSOAR", "max_issues_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_issues_repo_licenses": ["MIT"], "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/case.cc", "max_forks_repo_name": "pan3rock/QuadEigsSOAR", "max_forks_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 78, "alphanum_fraction": 0.6569767442, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.69315649777489}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2005, 2008 Klaus Spanderen\nCopyright (C) 2007 StatPro Italia srl\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n// Based on batesmodel.cpp file from test-suite.\n\n\n#ifndef cl_adjoint_bates_model_impl_hpp\n#define cl_adjoint_bates_model_impl_hpp\n#pragma once\n\n\n#include \"adjointbatesmodeltest.hpp\"\n#include \"utilities.hpp\"\n#include \"adjointtestutilities.hpp\"\n#include \"adjointtestbase.hpp\"\n#include <ql/time/calendars/target.hpp>\n#include <ql/processes/batesprocess.hpp>\n#include <ql/processes/merton76process.hpp>\n#include <ql/instruments/europeanoption.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/pricingengines/vanilla/batesengine.hpp>\n#include <ql/pricingengines/vanilla/jumpdiffusionengine.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/mceuropeanhestonengine.hpp>\n#include <ql/pricingengines/vanilla/fdbatesvanillaengine.hpp>\n#include <ql/models/equity/batesmodel.hpp>\n#include <ql/models/equity/hestonmodelhelper.hpp>\n#include <ql/time/period.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\n// Based on QuantLib\\test-suite\\batesmodel.cpp file\n\n#define OUTPUT_FOLDER_NAME \"AdjointBates\"\n\n/*!\nAdjointBatesModelsTest is tested using adjoint differentiation for the class BatesProcess.\n\nThe Bates model (1996) combines the Merton and Heston approaches and proposes a model\nwith stochastic volatility and jumps governed by:\n\\f[\n\\begin{array}{rcl}\ndS(t)  &=& (r-d-\\lambda m) S dt +\\sqrt{v} S dW_1 + (\\exp^J - 1) S dN \\\\\ndv(t)  &=& \\kappa (\\theta - v) dt + \\sigma \\sqrt{v} dW_2 \\\\\ndW_1 dW_2 &=& \\rho dt \\\\\n\\omega(J) &=& \\frac{1}{\\sqrt{2\\pi \\delta^2}}\n\\exp\\left[-\\frac{(J-\\nu)^2}{2\\delta^2}\\right]\n\\end{array}\n\\f]\nHere:\n\\f$ S(t) \\f$                    is an asset (underlying) price,\n\\f$ v(t) \\f$                    is volatility,\n\\f$ J \\f$ and \\f$ \\omega(J) \\f$ are a jump size and its PDF\n\\f$ r \\f$                       is a risk-free (domestic) interest rate,\n\\f$ d \\f$                       is a dividend (foreign interest) rate,\n\\f$ m \\f$                       is an average jump amplitude\n\\f$ \\sigma \\f$                  is a volatility of volatility,\n\\f$ \\kappa \\f$                  is a mean-reverting rate,\n\\f$ \\theta \\f$                  is a long-term variance,\n\\f$ \\rho \\f$                    is correlation between price and variance (Wiener processes \\f$ dW_1 \\f$ and \\f$ dW_2 \\f$),\n\\f$ \\lambda \\f$, \\f$ \\nu \\f$, \\f$ \\delta \\f$ are jump intensity, mean and volatility for the Merton jump-diffusion, respectively.\n\nReferences:\nA. Sepp, Pricing European-Style Options under Jump Diffusion\nProcesses with Stochastic Volatility: Applications of Fourier\nTransform (<http://math.ut.ee/~spartak/papers/stochjumpvols.pdf>)\n\nIn this test, the dependence of the NPV of a portfolio consisted of several options\non option strike prices is calculated using adjoint and finite difference differentiation.\nIn addition, the NPV is checked with the Black formula\n(the parameters of the Bates model are chosen to produce results identical to the Black formula).\n*/\n\nnamespace {\n    enum\n    {\n#if defined CL_GRAPH_GEN\n        // Number of points for dependency plots.\n        pointNo = 100,\n        // Number of points for performance plot.\n        iterNo = 30,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#else\n        // Number of points for dependency plots.\n        pointNo = 0,\n        // Number of points for performance plot.\n        iterNo = 0,\n        // Step for portfolio size for performance testing .\n        step = 1,\n#endif\n        // Defines performance accuracy. Its value is a minimum number\n        // of calling of O(1) complexity methods per one performance test.\n        iterNumFactor = 0,\n    };\n\n    // This structure contains all constant variables\n    // Parameters of the Bates model are chosen to produce results identical to the Black formula\n    // (based on BatesModelTest::testAnalyticVsBlack() from QuantLib\\test-suite\\batesmodel.cpp)\n    struct CommonVars\n    {\n        CommonVars()\n        : settlementDate_(Date(1, September, 2005))\n        , exerciseDate_(settlementDate_ + 6 * Months)\n        , riskfreeRate_(0.10)\n        , dividentRate_(0.04)\n        , spotPrice_(30.0)\n        , volatility_(0.05)\n        , kappa_(5.0)\n        , theta_(0.05)\n        , sigma_(1.0e-4)\n        , rho_(0.0)\n        , lambda_(0.0001)\n        , nu_(0.0)\n        , delta_(0.0001)\n        , exercise_(boost::make_shared<EuropeanExercise>(exerciseDate_))\n        , strikePrice_(18.0)\n        {\n        }\n\n        // global data\n        const Date settlementDate_;\n        const Date exerciseDate_;\n        const Real riskfreeRate_;\n        const Real dividentRate_;\n        const Real spotPrice_;\n        const Real volatility_;\n        // Bates model specific data\n        const Real kappa_;\n        const Real theta_;\n        const Real sigma_;\n        const Real rho_;\n        const Real lambda_;\n        const Real nu_;\n        const Real delta_;\n        // variables and objects needed for calculations\n        boost::shared_ptr<Exercise> exercise_;\n        const Real strikePrice_;\n        Handle<YieldTermStructure> riskFreeTS_;\n    };\n\n    // This structure contains all constant variables from CommonVars + strike price\n    // In addition it provides methods for calcualtions\n    struct BatesData\n        : public CommonVars\n    {\n        explicit BatesData()\n        : CommonVars()\n        {\n        }\n\n        // Provides payoffs that are different only by their strike price\n        boost::shared_ptr<StrikedTypePayoff> makePayoff(Rate strikePrice)\n        {\n            boost::shared_ptr<StrikedTypePayoff> payoff(\n                new PlainVanillaPayoff(Option::Put, strikePrice));\n            return payoff;\n        }\n\n        // Calculate forward price for given divident rate\n        Real CalculateForwardPrice(Real dividentRate)\n        {\n            Settings::instance().evaluationDate() = settlementDate_;\n            DayCounter dayCounter = ActualActual();\n            Handle<Quote> s0(boost::make_shared<SimpleQuote>(spotPrice_));\n            Real yearFraction = dayCounter.yearFraction(settlementDate_, exerciseDate_);\n            Real forwardPrice = s0->value()*std::exp((riskfreeRate_ - dividentRate)*yearFraction);\n            return forwardPrice;\n        }\n\n        // Provides options that are different only by their strike price\n        boost::shared_ptr<VanillaOption> makeOptionForStrikePrice(Real strikePrice)\n        {\n            Settings::instance().evaluationDate() = settlementDate_;\n            DayCounter dayCounter = ActualActual();\n\n            boost::shared_ptr<StrikedTypePayoff> payoff = makePayoff(strikePrice);\n            boost::shared_ptr<VanillaOption> option(new VanillaOption(payoff, exercise_));\n            Handle<Quote> s0(boost::make_shared<SimpleQuote>(spotPrice_));\n\n            Handle<YieldTermStructure> riskFreeTS(flatRate(riskfreeRate_, dayCounter));\n            Handle<YieldTermStructure> dividendTS(flatRate(dividentRate_, dayCounter));\n            boost::shared_ptr<BatesProcess> process(\n                new BatesProcess(riskFreeTS, dividendTS, s0, volatility_,\n                kappa_, theta_, sigma_, rho_, lambda_, nu_, delta_));\n\n            boost::shared_ptr<PricingEngine> engine(new BatesEngine(\n                boost::shared_ptr<BatesModel>(new BatesModel(process)), 64));\n\n            option->setPricingEngine(engine);\n\n            return option;\n        }\n\n        // Returns net present value (NPV) of option with given fixed rate strike and other\n        // parameters determined from class instance.\n        Real optionNPVForStrikePrice(Real strikePrice)\n        {\n            auto option = makeOptionForStrikePrice(strikePrice);\n            return option->NPV();\n        }\n\n        // Black-Scholes result (for cross check)\n        Real optionNPVForStrikePrice_BS(Real strikePrice)\n        {\n            Settings::instance().evaluationDate() = settlementDate_;\n            DayCounter dayCounter = ActualActual();\n            Real yearFraction = dayCounter.yearFraction(settlementDate_, exerciseDate_);\n            boost::shared_ptr<StrikedTypePayoff> payoff = makePayoff(strikePrice);\n            Real forwardPrice = CalculateForwardPrice(dividentRate_);\n            Real NPV = blackFormula(payoff->optionType(), payoff->strike(),\n                forwardPrice, std::sqrt(volatility_*yearFraction)) *\n                std::exp(-1 * riskfreeRate_*yearFraction);\n            return NPV;\n        }\n\n        // Provides options that are different only by the divident rate\n        boost::shared_ptr<VanillaOption> makeOptionForDividentRate(Real dividentRate)\n        {\n            Settings::instance().evaluationDate() = settlementDate_;\n            DayCounter dayCounter = ActualActual();\n\n            boost::shared_ptr<StrikedTypePayoff> payoff = makePayoff(strikePrice_);\n            boost::shared_ptr<VanillaOption> option(new VanillaOption(payoff, exercise_));\n            Handle<Quote> s0(boost::make_shared<SimpleQuote>(spotPrice_));\n\n            Handle<YieldTermStructure> riskFreeTS(flatRate(riskfreeRate_, dayCounter));\n            Handle<YieldTermStructure> dividendTS(flatRate(dividentRate, dayCounter));\n            boost::shared_ptr<BatesProcess> process(\n                new BatesProcess(riskFreeTS, dividendTS, s0, volatility_,\n                kappa_, theta_, sigma_, rho_, lambda_, nu_, delta_));\n\n            boost::shared_ptr<PricingEngine> engine(new BatesEngine(\n                boost::shared_ptr<BatesModel>(new BatesModel(process)), 64));\n\n            option->setPricingEngine(engine);\n\n            return option;\n        }\n\n        // Returns net present value (NPV) of option with given fixed rate strike and other\n        // parameters determined from class instance.\n        Real optionNPVForDividentRate(Real dividentRate)\n        {\n            auto option = makeOptionForDividentRate(dividentRate);\n            return option->NPV();\n        }\n\n        // Black-Scholes result (for cross check)\n        Real optionNPVForDividentRate_BS(Real dividentRate)\n        {\n            Settings::instance().evaluationDate() = settlementDate_;\n            DayCounter dayCounter = ActualActual();\n            Real yearFraction = dayCounter.yearFraction(settlementDate_, exerciseDate_);\n            boost::shared_ptr<StrikedTypePayoff> payoff = makePayoff(strikePrice_);\n            Real forwardPrice = CalculateForwardPrice(dividentRate);\n            Real NPV = blackFormula(payoff->optionType(), payoff->strike(),\n                forwardPrice, std::sqrt(volatility_*yearFraction)) *\n                std::exp(-1*riskfreeRate_*yearFraction);\n            return NPV;\n        }\n    };\n\n    // Struct for graphics recording of NPV dependence on anything\n    // (taken from adjointbermudanswaptionimpl.hpp)\n    struct NPVonSmth\n    {\n        static std::deque<std::string > get_columns()\n        {\n            static std::deque<std::string > columns =\n            {\n                \"Independent variable\", \"\"\n            };\n\n            return columns;\n        }\n\n        template <typename stream_type>\n        friend inline stream_type&\n            operator << (stream_type& stm, NPVonSmth& v)\n        {\n                stm << v.var_\n                    << \";\" << v.sensitivity_\n                    << std::endl;\n                return stm;\n            }\n\n        Real var_;\n        Real sensitivity_;\n    };\n\n    // Bates test structure (dependence on strike rate)\n    struct BatesTestStrikePrice\n        : public cl::AdjointTest<BatesTestStrikePrice>\n    {\n        // Create test with a portfolio given by the sum of size options with strike prices in the range:\n        //                                                    data_->strikePrice_ + 0.5 * i, 0 < i < size\n        BatesTestStrikePrice(Size size, BatesData* data, cl::tape_empty_test_output* logger = nullptr)\n        : AdjointTest()\n        , size_(size)\n        , data_(data)\n        , strikes_(size)\n        , NPV_(size)\n        , totalNPV_()\n        {\n            setLogger(logger);\n\n            for (Size i = 0; i < size_; i++)\n            {\n                strikes_[i] = data_->strikePrice_ + 0.5 * i;\n            }\n        }\n\n        // Do tape recording for adjoint calculation\n        void recordTape()\n        {\n            cl::Independent(strikes_);\n            calculateTotalNPV();\n            f_ = std::make_unique<cl::tape_function<double>>(strikes_, totalNPV_);\n        }\n\n        // Calculates price of  each option and portfolio (the sum)\n        Real calculateTotalNPV()\n        {\n            totalNPV_.resize(1, 0);\n            NPV_.resize(size_);\n            for (Size i = 0; i < size_; i++)\n            {\n                NPV_[i] = data_->optionNPVForStrikePrice(strikes_[i]);\n                totalNPV_.front() += NPV_[i];\n            }\n            return totalNPV_.front();\n        }\n\n        // Calculates price of  each option and portfolio (the sum) using Black formula (for cross check)\n        Real calculateTotalNPV_BS()\n        {\n            Real sum = 0.0;\n            for (Size i = 0; i < size_; i++)\n            {\n                sum += data_->optionNPVForStrikePrice_BS(strikes_[i]);\n            }\n            return sum;\n        }\n\n        // Check with BS formula\n        bool CheckBatesVsBlack()\n        {\n            Real calculated = this->calculateTotalNPV();\n            Real expected = this->calculateTotalNPV_BS();\n            Real maxabs = std::max(std::abs(calculated), std::abs(expected));\n            Real tol = std::max(this->relativeTol() * maxabs, this->absTol());\n            return (std::abs(expected - calculated) < tol);\n        }\n\n        // Calculates derivatives using finite difference method\n        void calcAnalytical()\n        {\n            const Real diff = 1e-6;\n            Real h = diff * data_->strikePrice_;  // shift for finite diff. method\n            analyticalResults_.resize(size_);\n            for (Size i = 0; i < size_; i++)\n            {\n                analyticalResults_[i] = (data_->optionNPVForStrikePrice(strikes_[i] + h)\n                    - data_->optionNPVForStrikePrice(strikes_[i] - h)) / (2 * h);\n            }\n        }\n\n        // get relative tolerance\n        double relativeTol() const { return 1e-5; }\n\n        // get absolute tolerance\n        double absTol() const { return 1e-7; }\n\n        // get number of independent variables\n        Size indepVarNumber() { return size_; }\n\n        Size size_;\n        BatesData* data_;\n        std::vector<cl::tape_double> strikes_;\n        std::vector<Real> NPV_;\n        std::vector<cl::tape_double> totalNPV_;\n    };\n\n\n    // Bates test structure (dependence on divident rate)\n    struct BatesTestDividentRate\n        : public cl::AdjointTest<BatesTestDividentRate>\n    {\n        // Create test with a portfolio given by the sum of options on assets with divident rates in the range:\n        //                                                    data_->dividentRate_ + 0.01 * i, 0 < i < size\n        BatesTestDividentRate(Size size, BatesData* data, cl::tape_empty_test_output* logger = nullptr)\n        : AdjointTest()\n        , size_(size)\n        , data_(data)\n        , dividents_(size)\n        , NPV_(size)\n        , totalNPV_()\n        {\n            setLogger(logger);\n\n            for (Size i = 0; i < size_; i++)\n            {\n                dividents_[i] = data_->dividentRate_ + 0.005 * i;\n            }\n        }\n\n        // Do tape recording for adjoint calculation\n        void recordTape()\n        {\n            cl::Independent(dividents_);\n            calculateTotalNPV();\n            f_ = std::make_unique<cl::tape_function<double>>(dividents_, totalNPV_);\n        }\n\n        // Calculates price of  each option and portfolio (the sum)\n        Real calculateTotalNPV()\n        {\n            totalNPV_.resize(1, 0);\n            NPV_.resize(size_);\n            for (Size i = 0; i < size_; i++)\n            {\n                NPV_[i] = data_->optionNPVForDividentRate(dividents_[i]);\n                totalNPV_.front() += NPV_[i];\n            }\n            return totalNPV_.front();\n        }\n\n        // Calculates price of each option and portfolio (the sum) using Black formula (for cross check)\n        Real calculateTotalNPV_BS()\n        {\n            Real sum = 0.0;\n            for (Size i = 0; i < size_; i++)\n            {\n                sum += data_->optionNPVForDividentRate_BS(dividents_[i]);\n            }\n            return sum;\n        }\n\n        // Check with BS formula\n        bool CheckBatesVsBlack()\n        {\n            Real calculated = this->calculateTotalNPV();\n            Real expected = this->calculateTotalNPV_BS();\n            Real maxabs = std::max(std::abs(calculated), std::abs(expected));\n            Real tol = std::max(this->relativeTol() * maxabs, this->absTol());\n            return (std::abs(expected - calculated) < tol);\n        }\n\n        // Calculates derivatives using finite difference method\n        void calcAnalytical()\n        {\n            const Real diff = 1e-4;\n            Real h = diff * data_->dividentRate_;  // shift for finite diff. method\n            analyticalResults_.resize(size_);\n            for (Size i = 0; i < size_; i++)\n            {\n                analyticalResults_[i] = (data_->optionNPVForDividentRate(dividents_[i] + h)\n                    - data_->optionNPVForDividentRate(dividents_[i] - h)) / (2 * h);\n            }\n        }\n\n        // get relative tolerance\n        double relativeTol() const { return 1e-5; }\n\n        // get absolute tolerance\n        double absTol() const { return 1e-7; }\n\n        // get number of independent variables\n        Size indepVarNumber() { return size_; }\n\n        Size size_;\n        BatesData* data_;\n        std::vector<cl::tape_double> dividents_;\n        std::vector<Real> NPV_;\n        std::vector<cl::tape_double> totalNPV_;\n    };\n\n    // BatesData structure extended for making plots with dependence on the divident rate\n    struct TestDataDividentRate\n        : public BatesData\n    {\n        explicit TestDataDividentRate()\n        : outPerform_(OUTPUT_FOLDER_NAME \"//\" + std::string(\"DividentRate\"), {\n            { \"title\", \"Bates NPV differentiation performance with respect to divident rate\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Time (s)\" }\n            , { \"xlabel\", \"Number of divident rates\" }\n            , { \"line_box_width\", \"-5\" }\n            , { \"cleanlog\", \"true\" }\n            , { \"smooth\", \"default\" }\n        })\n            , outAdjoint_(OUTPUT_FOLDER_NAME \"//\" + std::string(\"DividentRate\"), {\n                { \"title\", \"Bates NPV adjoint differentiation with respect to fixed divident rate\" }\n            , { \"filename\", \"Adjoint\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Time (s)\" }\n            , { \"xlabel\", \"Number of divident rates\" }\n            , { \"cleanlog\", \"false\" }\n            , { \"smooth\", \"default\" }\n        })\n            , outSize_(OUTPUT_FOLDER_NAME \"//\" + std::string(\"DividentRate\"), {\n                { \"title\", \"Tape size dependence on number of divident rates\" }\n            , { \"filename\", \"TapeSize\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"ylabel\", \"Memory (MB)\" }\n            , { \"cleanlog\", \"false\" }\n        })\n            , out_(OUTPUT_FOLDER_NAME \"//\" + std::string(\"DividentRate\") + \"//output\", {\n                { \"filename\", \"NPVonDividentRate\" }\n            , { \"not_clear\", \"Not\" }\n            , { \"title\", \"Option NPV dependence on fixed divident rate\" }\n            , { \"ylabel\", \"Option NPV\" }\n            , { \"xlabel\", \"Divident rate\" }\n            , { \"cleanlog\", \"false\" }\n        })\n        { }\n\n        // main method to produce output\n        bool makeOutput()\n        {\n            bool ok = true;\n            if (pointNo > 0)\n            {\n                ok &= recordDependencePlot(pointNo);\n                ok &= cl::recordPerformance(*this, iterNo, step);\n            }\n            return ok;\n        }\n\n        std::shared_ptr<BatesTestDividentRate> getTest(size_t size)\n        {\n            return std::make_shared<BatesTestDividentRate>(size, this, &outPerform_);\n        }\n\n        // Makes graphics for divident sensitivity dependence\n        bool recordDependencePlot(size_t pointNo)\n        {\n            bool ok = true;\n            std::vector<NPVonSmth> outData(pointNo);\n            auto test = getTest(pointNo);\n            test->recordTape();\n            for (Size i = 0; i < pointNo; i++)\n            {\n                outData[i] = { test->dividents_[i], test->NPV_[i] };\n            }\n            out_ << outData;\n            return ok;\n        }\n\n        cl::tape_empty_test_output outPerform_;\n        cl::tape_empty_test_output outAdjoint_;\n        cl::tape_empty_test_output outSize_;\n        cl::tape_empty_test_output out_;\n    }; \n}\n\n\n#endif\n", "meta": {"hexsha": "d928c21ffb3fda783cf1112c3c58d2d5d9afc082", "size": 21901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointbatesmodelimpl.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointbatesmodelimpl.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointbatesmodelimpl.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 37.4376068376, "max_line_length": 129, "alphanum_fraction": 0.5954522625, "num_tokens": 5176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6931342833585287}}
{"text": "#include \"matrix.h\"\n#include \"mex.h\"\n\n\n#include <iostream>\n#include <math.h>\n#include <chrono>\n#include <random>\n#include <vector>\n#include <Eigen\\Dense>\n#include <Eigen\\SVD>\n\n\n#include \"estimator.h\"\n#include \"prosac.h\"\n#include \"mlesac.h\"\n#include \"ransac.h\"\n\nusing namespace std;\nusing namespace theia;\nusing namespace Eigen;\n\n// Structure for a 2-D point\nstruct Point\n{\n\tdouble x;\n\tdouble y;\n\tPoint() {}\n\tPoint(double _x, double _y) : x(_x), y(_y) {}\n\tPoint(const Point& p)\n\t{\n\t\tx = p.x;\n\t\ty = p.y;\n\t}\n};\n\n// A pair of points that correspond to each other. These two points are two keypoints in to separate images that have been matched to each other\nstruct Correspondence\n{\n\tPoint p1;\n\tPoint p2;\n\tCorrespondence() {}\n\tCorrespondence(double x1, double y1, double x2, double y2)\n\t{\n\t\tp1.x = x1;\n\t\tp1.y = y1;\n\t\tp2.x = x2;\n\t\tp2.y = y2;\n\t}\n\tCorrespondence(Point& _p1, Point& _p2) : p1(_p1), p2(_p2) {}\n\tCorrespondence(const Correspondence& other) : p1(other.p1), p2(other.p2) { }\n};\n\n// Homography matrix is a 3-by-3 matrix which is the model we are trying to estimate\nstruct Homography\n{\n\tdouble Matrix[9];\n\tHomography() {}\n\tHomography(const Homography& other)\n\t{\n\t\tfor (size_t i = 0; i < 9; i++)\n\t\t{\n\t\t\tMatrix[i] = other.Matrix[i];\n\t\t}\n\t}\n};\n\n// This is the estimator class for estimating a homography matrix between two images. A model estimation method and error calculation method are implemented\nclass HomographyEstimator : public Estimator < Correspondence, Homography >\n{\npublic:\n\tHomographyEstimator() {}\n\t~HomographyEstimator() {}\n\n\n\n\tint SampleSize() const { return 4; }\n\tbool EstimateModel(const vector<Correspondence>& data, vector<Homography>* models) const\n\t{\n\t\tHomography model;\n\n\t\t//calculate homography -- see gc_lecture_notes pp. 17-19\n\t\tMatrixXd Q = MatrixXd::Zero(2 * data.size(), 9);\n\t\tfor (size_t i = 0; i < data.size(); i++)\n\t\t{\n\t\t\tQ(i, 0) = data[i].p2.x;\n\t\t\tQ(i, 1) = data[i].p2.y;\n\t\t\tQ(i, 2) = 1.0;\n\t\t\tQ(i, 6) = -1 * data[i].p2.x * data[i].p1.x;\n\t\t\tQ(i, 7) = -1 * data[i].p2.y * data[i].p1.x;\n\t\t\tQ(i, 8) = -1 * data[i].p1.x;\n\n\t\t\tQ(i + data.size(), 3) = data[i].p2.x;\n\t\t\tQ(i + data.size(), 4) = data[i].p2.y;\n\t\t\tQ(i + data.size(), 5) = 1.0;\n\t\t\tQ(i + data.size(), 6) = -1.0 * data[i].p2.x * data[i].p1.y;\n\t\t\tQ(i + data.size(), 7) = -1.0 * data[i].p2.y * data[i].p1.y;\n\t\t\tQ(i + data.size(), 8) = -1.0 * data[i].p1.y;\n\t\t}\n\n\t\tMatrixXd qtq = Q.transpose() * Q;\n\t\tJacobiSVD<MatrixXd> svd(qtq, ComputeThinV);\n\t\tsvd.computeV();\n\t\tMatrixXd minEigenVector = svd.matrixV().col(8);\n\t\tfor (size_t i = 0; i < 9; i++)\n\t\t{\n\t\t\tmodel.Matrix[i] = minEigenVector(i);\n\t\t}\n\t\tmodels->push_back(model);\n\t\treturn true;\n\t}\n\n\tdouble Error(const Correspondence& correspondence, const Homography& model) const\n\t{\n\t\t// calculate reporojection error\n\t\tdouble projectionPointZ = model.Matrix[6] * correspondence.p1.x + model.Matrix[7] * correspondence.p1.y + model.Matrix[8];\n\t\tdouble projectionPointX = (model.Matrix[0] * correspondence.p1.x + model.Matrix[1] * correspondence.p1.y + model.Matrix[2]) / projectionPointZ;\n\t\tdouble projectionPointY = (model.Matrix[3] * correspondence.p1.x + model.Matrix[4] * correspondence.p1.y + model.Matrix[5]) / projectionPointZ;\n\n\t\treturn (double) (fabs(projectionPointX - correspondence.p2.x) + fabs(projectionPointY - correspondence.p2.y));\n\t}\n};\n\n// This is the entry point from MATLAB to this routine\n// plhs and prhs represent a pointer to the left hand side (output) and a pointer to the right hand side (input) respectively\n// matlab function signature: H = homography_estimator(points1, points2, 'mode')\n// H -> 9-by-9 homography matrix as output\n// points1 -> n-by-2 matrix, coordinates of the keypoints of the first image\n// points2 -> n-by-2 matrix, coordinates of the keypoints of the second image\n// 'mode' -> {'ransac', 'prosac', 'mlesac'}\nvoid mexFunction(int nlhs, mxArray *plhs [], int nrhs, const mxArray*prhs [])\n{\n\tif (nlhs != 1)\n\t{\n\t\tmexPrintf(\"Only one output expected\\n\");\n\t\treturn;\n\t}\n\tif (nrhs != 3)\n\t{\n\t\tmexPrintf(\"Only three inputs expected\\n\");\n\t\treturn;\n\t}\n\n\tconst mwSize *dims1, *dims2;\n\tchar* modeStr;\n\tdouble *points1, *points2;\n\n\n\tdims1 = mxGetDimensions(prhs[0]);\n\tdims2 = mxGetDimensions(prhs[1]);\n\n\tint dim1y = (int) dims1[0]; int dim1x = (int) dims1[1];\n\tint dim2y = (int) dims2[0]; int dim2x = (int) dims2[1];\n\n\tif (dim1x != dim2x || dim1y != dim2y)\n\t{\n\t\tmexPrintf(\"Error! two input points arrays must be of the same size\\n\");\n\t\treturn;\n\t}\n\n\tif (dim1x != 2 || dim2x != 2)\n\t{\n\t\tmexPrintf(\"Error! Points must be 2-D!\\n\");\n\t\treturn;\n\t}\n\n\tmodeStr = mxArrayToString(prhs[2]);\n\n\tif (!modeStr || mxGetDimensions(prhs[2])[0] != 1)\n\t{\n\t\tmexPrintf(\"Error! Last argument must be an string!\\n\");\n\t\treturn;\n\t}\n\n\tmexPrintf(\"string:\\n%s\\n\", modeStr);\n\tvector<Correspondence> correspondences(dim1y);\n\tpoints1 = mxGetPr(prhs[0]);\n\tpoints2 = mxGetPr(prhs[1]);\n\tfor (size_t j = 0; j < dim1y; j++)\n\t{\n\t\t/*Correspondence corr;\n\t\tcorr.p1.x = points1[j];\n\t\tcorr.p2.x = points2[j];\n\t\tcorr.p1.y = points1[dim1y + j];\n\t\tcorr.p2.y = points2[dim1y + j];*/\n\t\tcorrespondences[j] = Correspondence(points1[j], points1[dim1y + j], points2[j], points2[dim1y + j]);\n\t}\n\tHomography homographyModel;\n\tRansacParameters params;\n\tparams.error_thresh = 0.5;\n\tHomographyEstimator homographyEstimator;\n\tSampleConsensusEstimator<HomographyEstimator> *sacEstimator;\n\t// RANSAC mode\n\tif (!strcmp(\"ransac\", modeStr))\n\t{\n\t\tsacEstimator = new Ransac<HomographyEstimator>(params, homographyEstimator);\n\t}\n\t// MLESAC mode\n\telse if (!strcmp(\"mlesac\", modeStr))\n\t{\n\t\tsacEstimator = new Mlesac<HomographyEstimator>(params, homographyEstimator);\n\t}\n\t// PROSAC mode\n\telse if (!strcmp(\"prosac\", modeStr))\n\t{\n\t\tsacEstimator = new Prosac<HomographyEstimator>(params, homographyEstimator);\n\t}\n\t// Unknown mode\n\telse\n\t{\n\t\tmexPrintf(\"Error! unknown estimation mode selected!\\n\");\n\t\treturn;\n\t}\n\n\n\tsacEstimator->Initialize();\n\tRansacSummary summary;\n\tsacEstimator->Estimate(correspondences, &homographyModel, &summary);\n\n\tauto outArray = mxCreateDoubleMatrix(3, 3, mxREAL);\n\tdouble *outp = mxGetPr(outArray);\n\t// Copy the estimated homography matrix to the output matrix, note the difference between matrix's column-wise arrays vs. C's row-wise arrays convention\n\tauto lastElement = homographyModel.Matrix[8];\n\tfor (size_t i = 0; i < 3; i++)\n\t{\n\t\tfor (size_t j = 0; j < 3; j++)\n\t\t{\n\t\t\toutp[i * 3 + j] = homographyModel.Matrix[j * 3 + i] / lastElement;\n\t\t}\n\t}\n\n\tplhs[0] = outArray;\n}\n", "meta": {"hexsha": "c98077c0766c237bb8ffac5179cf2d0d11867eb7", "size": 6388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homography_estimator.cpp", "max_stars_repo_name": "erfannoury/sac", "max_stars_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-19T12:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T08:19:24.000Z", "max_issues_repo_path": "homography_estimator.cpp", "max_issues_repo_name": "erfannoury/sac", "max_issues_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homography_estimator.cpp", "max_forks_repo_name": "erfannoury/sac", "max_forks_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_forks_repo_licenses": ["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.2991452991, "max_line_length": 156, "alphanum_fraction": 0.6693800877, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894270096563}}
{"text": "#include <plll.hpp>\n#include <Eigen/Dense>\n#include <random>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <numeric>\n#include <fstream>\n#include <algorithm>\n#include <chrono>\n#include <cstdlib>\n#include <ctime>\n#include <cmath>\n#include <regex>\n\nusing namespace std;\n//namespace plt = matplotlibcpp;\ntemplate <class T>\nusing Matrix = vector<vector<T>>;\nusing sec_type = std::chrono::microseconds;\nusing _type = float;\nconstexpr double _c = 0.9;\n\nstruct matrix_with_det\n{\n    int det;\n    Matrix<int> mat;\n};\n\ntemplate <typename T>\nvoid getCofactor(Matrix<T> &A, Matrix<T> &temp, int p, int q, int n)\n{\n    int i = 0, j = 0;\n\n    // Looping for each element of the matrix\n    for (int row = 0; row < n; row++)\n    {\n        for (int col = 0; col < n; col++)\n        {\n            //  Copying into temporary matrix only those element\n            //  which are not in given row and column\n            if (row != p && col != q)\n            {\n                temp[i][j++] = A[row][col];\n\n                // Row is filled, so increase row index and\n                // reset col index\n                if (j == n - 1)\n                {\n                    j = 0;\n                    i++;\n                }\n            }\n        }\n    }\n}\n/* Recursive function for finding determinant of matrix.\n   n is current dimension of A[][]. */\ntemplate <typename T>\nT determinant(Matrix<T> &A, int n)\n{\n\n    //  Base case : if matrix contains single element\n    if (n == 1)\n        return A[0][0];\n    T D = 0;                            // Initialize result\n    Matrix<T> temp(n, vector<T>(n, 0)); // To store cofactors\n\n    float sign = 1; // To store sign multiplier\n\n    // Iterate for each element of first row\n    for (int f = 0; f < n; f++)\n    {\n        // Getting Cofactor of A[0][f]\n        getCofactor(A, temp, 0, f, n);\n        D += sign * A[0][f] * determinant(temp, n - 1);\n\n        // terms are to be added with alternate sign\n        sign = -sign;\n    }\n\n    return D;\n}\n\n// Function to get adjoint of A[N][N] in adj[N][N].\nvoid adjoint(Matrix<_type> &A, Matrix<_type> &adj)\n{\n    int n = A.size();\n    if (n == 1)\n    {\n        adj[0][0] = 1;\n        return;\n    }\n\n    // temp is used to store cofactors of A[][]\n    _type sign = 1;\n    Matrix<_type> temp(n, vector<_type>(n, 0));\n\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            // Get cofactor of A[i][j]\n            getCofactor(A, temp, i, j, n);\n\n            // sign of adj[j][i] positive if sum of row\n            // and column indexes is even.\n            sign = ((i + j) % 2 == 0) ? 1 : -1;\n\n            // Interchanging rows and columns to get the\n            // transpose of the cofactor matrix\n            adj[j][i] = (sign) * (determinant(temp, n - 1));\n        }\n    }\n}\n\n// Function to calculate and store inverse, returns false if\n// matrix is singular\nbool inverse(Matrix<_type> &A, Matrix<_type> &inverse)\n{\n    // Find determinant of A[][]\n    int det = determinant(A, A.size());\n    //_type det = 6;\n    if (det == 0)\n    {\n        cout << \"Singular matrix, can't find its inverse\";\n        return false;\n    }\n\n    // Find adjoint\n    Matrix<_type> adj;\n    for (int i = 0; i < A.size(); i++)\n    {\n        adj.push_back(vector<_type>());\n        for (int j = 0; j < A.size(); j++)\n            adj[i].push_back(0);\n    }\n    adjoint(A, adj);\n\n    // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\"\n    for (int i = 0; i < A.size(); i++)\n        for (int j = 0; j < A.size(); j++)\n            inverse[i][j] = adj[i][j] / float(det);\n\n    return true;\n}\n\ntemplate <typename T, typename T2>\ndouble dotProduct(const vector<T> &v1, const vector<T2> &v2)\n{\n    double ret = 0;\n    for (int i = 0; i < v1.size(); ++i)\n        ret += (v1.at(i) * v2.at(i));\n    return ret;\n}\n\ntemplate <typename T>\nvector<T> operator*(const double &c, const vector<T> &v)\n{\n    vector<T> ret = v;\n    for (auto &d : ret)\n        d *= c;\n    return ret;\n}\n\nvector<_type> operator*(Matrix<_type> &M, const vector<_type> &v)\n{\n    int n = v.size();\n    vector<_type> res(n, 0);\n    for (size_t i = 0; i < n; i++)\n    {\n        for (size_t j = 0; j < n; j++)\n        {\n            res[i] += M[j][i] * v[j];\n        }\n    }\n    return res;\n}\ntemplate <typename T, typename T2>\nvector<T2> subtract(const vector<T> &v1, const vector<T2> &v2)\n{\n    vector<T2> ret(v1.size());\n    for (int i = 0; i < v1.size(); ++i)\n        ret[i] = (v1[i] - v2[i]);\n    return ret;\n}\ntemplate <typename T, typename T2>\nvector<T> operator-(const vector<T> &v1, const vector<T2> &v2)\n{\n    vector<T> ret(v1.size());\n    for (int i = 0; i < v1.size(); ++i)\n        ret[i] = v1[i] - v2[i];\n    return ret;\n}\ntemplate <typename T>\nvector<T> inverse(const vector<T> &v1)\n{\n    vector<T> ret(v1.size());\n    for (int i = 0; i < v1.size(); ++i)\n        ret[i] = -v1[i];\n    return ret;\n}\ntemplate <typename T>\nbool operator==(const vector<T> &v1, const vector<T> &v2)\n{\n    if (v1.size() == v2.size())\n    {\n        if (v1.size())\n        {\n            if (v1[0] == v2[0])\n            {\n                if (v1[0] == 0)\n                {\n                    int sign = 0;\n                    for (int i = 1; i < v1.size(); i++)\n                    {\n                        if (v1[i] == 0 && v2[i] == 0)\n                            continue;\n                        if (sign == 0)\n                        {\n                            if (v1[i] == v2[i])\n                                sign = 1;\n                            else if (v1[i] == -v2[i])\n                                sign = -1;\n                            else\n                                return false;\n                        }\n                        else if (v1[i] != sign * v2[i])\n                        {\n                            return false;\n                        }\n                    }\n                }\n                else\n                {\n                    for (int i = 1; i < v1.size(); i++)\n                    {\n                        if (v1[i] != v2[i])\n                        {\n                            return false;\n                        }\n                    }\n                }\n                return true;\n            }\n            if (v1[0] == -v2[0])\n            {\n                for (int i = 1; i < v1.size(); i++)\n                {\n                    if (v1[i] != -v2[i])\n                    {\n                        return false;\n                    }\n                }\n                return true;\n            }\n            return false;\n        }\n        else\n            return true;\n    }\n    else\n        return false;\n}\ntemplate <typename T>\nvector<T> operator+(const vector<T> &v1, const vector<T> &v2)\n{\n    vector<T> ret(v1.size());\n    for (int i = 0; i < v1.size(); ++i)\n        ret[i] = (v1.at(i) + v2.at(i));\n    return ret;\n}\nvector<_type> roundV(vector<_type> a)\n{\n    for (size_t i = 0; i < a.size(); i++)\n    {\n        a[i] = round(a[i]);\n    }\n    return a;\n}\n\nvector<_type> proj(const vector<_type> &v1, const vector<_type> &v2)\n{\n    vector<_type> proj = (dotProduct(v1, v2) / dotProduct(v1, v1)) * v1;\n    return proj;\n}\n\nvector<_type> proj(const vector<_type> &v1, const vector<int> &v2)\n{\n    vector<_type> proj = (dotProduct(v1, v2) / dotProduct(v1, v1)) * v1;\n    return proj;\n}\n\nMatrix<_type> gSchmidt(const Matrix<int> &vspace)\n{\n    Matrix<_type> uspace(vspace.size(), vector<_type>(vspace[0].size()));\n    for (int i = 0; i < vspace[0].size(); i++)\n    {\n        uspace[0][i] = vspace[0][i];\n    }\n    for (int i = 1; i < vspace.size(); ++i)\n    {\n        for (int j = 0; j < i; ++j)\n        {\n            uspace.at(i) = subtract(vspace.at(i), proj(uspace.at(j), vspace.at(i)));\n        }\n    }\n    return uspace;\n}\nMatrix<_type> gSchmidt(const Matrix<_type> &vspace, int limit)\n{\n    Matrix<_type> uspace;\n    for (int i = 0; i <= limit; ++i)\n    {\n        uspace.push_back(vspace.at(i));\n        for (int j = 0; j < i; ++j)\n        {\n            uspace.at(i) = uspace.at(i) - proj(uspace.at(j), vspace.at(i));\n        }\n    }\n    return uspace;\n}\ntemplate <typename T>\nvoid printVS(const Matrix<T> &vspace)\n{\n    for (auto &v : vspace)\n    {\n        cout << '|';\n        for (auto &d : v)\n            cout << d << ' ';\n        cout << \"|\\n\";\n    }\n}\ntemplate <typename T>\nvoid printVS(const Matrix<T> &vspace, ostream &file)\n{\n    file << '[';\n    for (auto &v : vspace)\n    {\n        file << '[';\n        for (auto &d : v)\n            file << d << ' ';\n        file << \"]\\n\";\n    }\n    file << \"]\\n\";\n}\ntemplate <typename T>\nvoid printVec(const vector<T> &v)\n{\n    cout << endl;\n    cout << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n    for (auto &d : v)\n        cout << d << ' ';\n    cout << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n}\ntemplate <typename T>\nvoid printVec(const vector<T> &v, ostream &file)\n{\n    file << endl;\n    file << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n    for (auto &d : v)\n        file << d << ' ';\n    file << endl\n         << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n}\ntemplate <typename T>\nfloat mu(int k1, int k2, Matrix<T> *m, Matrix<_type> *gsm)\n{\n    T init = 0;\n    vector<T> *a = &m->at(k1);\n    vector<_type> *b = &gsm->at(k2);\n    return std::inner_product(a->begin(), a->end(), b->begin(), init) /\n           std::inner_product(b->begin(), b->end(), b->begin(), init);\n}\ntemplate <typename T, typename T2>\nfloat mu(vector<T> &a, vector<T2> &b)\n{\n    float init = 0.0;\n    double d = std::inner_product(a.begin(), a.end(), b.begin(), init);\n    double dd = std::inner_product(b.begin(), b.end(), b.begin(), init);\n    return d / dd;\n}\ntemplate <typename T>\ndouble squaredLengthOfVector(vector<T> *v)\n{\n    return std::inner_product(v->begin(), v->end(), v->begin(), 0.0);\n}\ntemplate <typename T>\ndouble squaredLengthOfVector(vector<T> &v)\n{\n    return std::inner_product(v.begin(), v.end(), v.begin(), 0.0);\n}\n\nint KabatianskyLevenshteinC(Matrix<int> &M)\n{\n    float angle = 1;\n    for (int i = 0; i < M.size(); i++)\n    {\n        auto v1 = M[i];\n        for (int j = i + 1; j < M.size(); j++)\n        {\n            auto v2 = M[j];\n            float t = dotProduct(v1, v2) / (sqrt(squaredLengthOfVector(&v1)) *\n                                            sqrt(squaredLengthOfVector(&v2)));\n            angle = fmin(angle, t);\n        }\n    }\n    return fmax((int)(-1.0 / 2.0 * log(1 - cos(angle)) - 0.099), 1);\n}\n\nvector<int> lll_reduce(vector<_type> &gsreducing, vector<int> &target,\n                       vector<int> &reducing)\n{\n    vector<int> t = target - round(mu(target, gsreducing)) * reducing;\n    return t;\n}\n\nvoid LLL(Matrix<int> &B, ostream &o)\n{\n    bool cont;\n    Matrix<_type> gramSmidt;\n    int iter = 0;\n    do\n    {\n        iter++;\n        gramSmidt = gSchmidt(B);\n        cont = false;\n        for (int i = 1; i < B.size(); i++)\n        {\n            for (int j = 0; j < i; j++)\n            {\n                B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n            }\n        }\n        for (int i = 1; i < B.size() && !cont; i++)\n        {\n            float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n            float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n            float mu1 = mu(i, i - 1, &B, &gramSmidt);\n            if (a2 < (_c - mu1 * mu1) * a1)\n            {\n                B.at(i - 1).swap(B.at(i));\n                cont = true;\n            }\n        }\n    } while (cont);\n    o << \"lll iter : \" << iter << \"|\\n\";\n}\n\nvoid LLL(Matrix<int> &B)\n{\n    bool cont;\n    Matrix<_type> gramSmidt;\n    int iter = 0;\n    do\n    {\n        iter++;\n        gramSmidt = gSchmidt(B);\n        cont = false;\n        for (int i = 1; i < B.size(); i++)\n        {\n            for (int j = 0; j < i; j++)\n            {\n                B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n            }\n            float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n            float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n            float mu1 = mu(i, i - 1, &B, &gramSmidt);\n            if (a2 < (_c - mu1 * mu1) * a1)\n            {\n                B.at(i - 1).swap(B.at(i));\n                i--;\n                cont = true;\n            }\n        }\n    } while (cont);\n}\n// opera 918\nvoid LLL2(Matrix<int> &B)\n{\n    bool cont;\n    Matrix<_type> gramSmidt;\n    int iter = 0;\n    do\n    {\n        iter++;\n        gramSmidt = gSchmidt(B);\n        cont = false;\n        for (int i = 1; i < B.size(); i++)\n        {\n            for (int j = i - 1; j > 0; j--)\n            {\n                B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n            }\n            float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n            float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n            float mu1 = mu(i, i - 1, &B, &gramSmidt);\n            if (a2 < (_c - mu1 * mu1) * a1)\n            {\n                B.at(i - 1).swap(B.at(i));\n                i--;\n                cont = true;\n            }\n        }\n    } while (cont);\n}\nvoid preparePlot(Matrix<_type> res, Matrix<_type> og)\n{\n    map<_type, _type> m;\n    vector<_type> x, y, z;\n    int maxSize = 20;\n    if (res.size() == 2)\n    {\n        vector<_type> bounds = 2 * og[0] + 2 * og[1];\n        int boundX = bounds[0];\n        int boundY = bounds[1];\n        for (int i = -maxSize; i < maxSize; i++)\n        {\n            for (int j = -maxSize; j < maxSize; j++)\n            {\n                vector<_type> t = i * res.at(0) + j * res.at(1);\n                if (-boundX < t[0] < boundX && -boundY < t[1] < boundY)\n                {\n                    x.push_back(t.at(0));\n                    y.push_back(t.at(1));\n                }\n            }\n        }\n        //plt::plot(x, y, \".\");\n    }\n    if (res.size() == 3)\n    {\n        vector<_type> bounds = 2 * og[0] + 2 * og[1];\n        int boundX = bounds[0];\n        int boundY = bounds[1];\n        int boundZ = bounds[2];\n        for (int i = -maxSize; i < maxSize; i++)\n        {\n            for (int j = -maxSize; j < maxSize; j++)\n                for (int k = -maxSize; k < maxSize; j++)\n                {\n                    vector<_type> t = i * res.at(0) + j * res.at(1) + k * res.at(2);\n                    if (-boundX < t[0] < boundX && -boundY < t[1] < boundY)\n                    {\n                        x.push_back(t.at(0));\n                        y.push_back(t.at(1));\n                        z.push_back(t.at(2));\n                    }\n                }\n        }\n    }\n    /*plt::plot({ 0 }, { 0 }, \"bo\");\n    plt::plot({ res.at(0).at(0) }, { res.at(0).at(1) }, \"r+\");\n    plt::plot({ res.at(1).at(0) }, { res.at(1).at(1) }, \"r+\");\n    plt::plot({ og.at(0).at(0) }, { og.at(0).at(1) }, \"g*\");\n    plt::plot({ og.at(1).at(0) }, { og.at(1).at(1) }, \"g*\");*/\n}\n//https://tel.archives-ouvertes.fr/tel-01245066v2/document\nvector<int> kleinSample(Matrix<int> &B, Matrix<_type> &GSO, float deviation, vector<int> &c)\n{\n    vector<int> v(c.size(), 0);\n    std::random_device mch;\n    std::default_random_engine generator(mch());\n\n    double d, z;\n    for (int i = B.size() - 1; i >= 0; i--)\n    {\n        double length = squaredLengthOfVector(GSO.at(i));\n        d = dotProduct(c, GSO.at(i)) / length;\n        double sigma = deviation / sqrt(length);\n        std::normal_distribution<double> distribution(d, 1);\n        z = round(distribution(generator));\n        //std::cout << z << \" \" ;\n        c = c - z * B[i];\n        v = v + z * B[i];\n    }\n    //std::cout << std::endl;\n    return v;\n}\n\n// todo discover\nvector<_type> sample_gaussian(Matrix<_type> &B)\n{\n    vector<_type> a;\n    a = (5 - rand() % 10) * B.back();\n    for (auto b : B)\n        a = a + (5 - rand() % 10) * b;\n    return a;\n}\n\nbool reduce(vector<int> &p, Matrix<int> &L, vector<double> &lengths)\n{\n    double s = squaredLengthOfVector(p);\n    for (size_t i = 0; i < L.size(); i++)\n    {\n        if (s >= lengths[i])\n        {\n            auto diff = p - L[i];\n            double s2 = squaredLengthOfVector(diff);\n            if (s2 < s)\n            {\n                p = diff;\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nvector<int> gauss_reduce(vector<int> &v_new, Matrix<int> &L, Matrix<int> &S, vector<double> &lengths)\n{\n    bool cont = true;\n    while (cont)\n    {\n        auto same = std::find_if(L.begin(), L.end(), [&v_new](vector<int> &v) { return v_new == v; });\n        if (same != L.end())\n        {\n            return vector<int>(v_new.size());\n        }\n        // 2 \u0440\u0430\u0437\u0430 \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044f \u0440\u0430\u0437\u043d\u0438\u0446\u0430, \u043c\u043e\u0436\u043d\u043e \u0441\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c \u0438 \u0441\u0440\u0430\u0432\u043d\u0438\u0442\u044c \u0441 \u043c\u0438\u043d\u0438\u043c\u0443\u043c\u043e\u043c\n        cont = reduce(v_new, L, lengths);\n    }\n    auto it = L.begin();\n    auto it2 = lengths.begin();\n    int i = 0;\n    vector<int> a(v_new.size());\n    while (it != L.end())\n    {\n        double v_new_length = squaredLengthOfVector(&v_new);\n        vector<int> v = *it;\n        if (lengths[i] > v_new_length)\n        {\n            a = v - v_new;\n            if (squaredLengthOfVector(a) <= lengths[i])\n            {\n                S.push_back(a);\n                it = L.erase(it);\n                it2 = lengths.erase(it2);\n            }\n            else\n            {\n                ++it;\n                ++it2, ++i;\n            }\n        }\n        else\n        {\n            ++it;\n            ++it2, ++i;\n        }\n    }\n    return v_new;\n}\n// https://cseweb.ucsd.edu/~daniele/papers/Sieve.pdf\n// c= 1000\nvector<int> gaussSieve(Matrix<int> &B, float bound, ostream &o)\n{\n    Matrix<int> L, S;\n    vector<int> v_new;\n    Matrix<_type> gramSmidt = gSchmidt(B);\n    vector<double> squarelengthsVector;\n    int K = 0, iter = 0;\n    //int c = KabatianskyLevenshteinC(B);\n    map<int, int> _map;\n\n    size_t max_number_of_collistions = 200;\n    do\n    {\n        _map.insert(make_pair(iter, K));\n\n        iter++;\n        if (S.size() > 0)\n        {\n            v_new = S.back();\n            S.pop_back();\n        }\n        else\n        {\n            vector<int> a(B[0].size(), 0);\n            v_new = kleinSample(B, gramSmidt, 1, a);\n        }\n        v_new = gauss_reduce(v_new, L, S, squarelengthsVector);\n        if (!v_new.size() ||\n            std::count(v_new.begin(), v_new.end(), 0) == v_new.size())\n        {\n            K++;\n        }\n        else if (sqrt(squaredLengthOfVector(v_new)) < bound)\n        {\n            o << \"early exit gauss iter : \" << iter << \"|\\n\";\n            return v_new;\n        }\n        else\n        {\n            L.push_back(v_new);\n            squarelengthsVector.push_back(squaredLengthOfVector(v_new));\n        }\n        max_number_of_collistions = std::max(max_number_of_collistions, L.size());\n    } while (10 * K < max_number_of_collistions + 2000 || L.size() == 0);\n    vector<int> shortestVector = L[0];\n    int _a = 0, count = 0;\n    for (int i = 1; i < L.size(); i++)\n    {\n        if (sqrt(squaredLengthOfVector(L[i])) <= bound)\n        {\n            count++;\n        }\n        if (squaredLengthOfVector(shortestVector) > squaredLengthOfVector(L[i]))\n        {\n            shortestVector = L[i];\n            _a = i;\n        }\n    }\n    cout << \"count \" << count << endl;\n    cout << \"gauss at : \" << _map.at(_a) << endl;\n    o << \"gauss iter : \" << iter << \"|\\n\";\n    return shortestVector;\n}\n\nvector<_type> randomInBall(const int dimm, float r)\n{\n    vector<_type> randVector(dimm);\n    for (int i = 0; i < dimm; i++)\n    {\n        randVector[i] = (rand() % (int)(r + 1));\n    }\n    return (r * (rand() / double(RAND_MAX)) / sqrt(squaredLengthOfVector(randVector))) * randVector;\n}\n//https://crypto.stackexchange.com/questions/29661/how-to-find-the-value-of-a-vector-modulo-a-basis-in-lattice-based-cryptography/29701#29701\nvector<_type> mod(vector<_type> vec, Matrix<_type> m)\n{\n    Matrix<_type> r(m.size(), vector<_type>(m.size(), 0));\n    inverse(m, r);\n    return m * roundV(r * vec);\n}\n\nvoid ListReduce(vector<int> &p, Matrix<int> &L, vector<double> &lengths)\n{\n    bool cont = true;\n    while (cont)\n    {\n        auto same = std::find(L.begin(), L.end(), p);\n        if (same != L.end())\n        {\n            p = vector<int>(p.size());\n            return;\n        }\n        if (!reduce(p, L, lengths))\n            return;\n        /*auto f = std::find_if(L.begin(), L.end(), [&p](vector<int>& v) {\n            return squaredLengthOfVector(&p) >= squaredLengthOfVector(&v) && squaredLengthOfVector(&(p - v)) < squaredLengthOfVector(&p);\n            });\n        if (f == L.end()) return;\n        p = p - *f;*/\n    }\n}\n//https://math.stackexchange.com/questions/396382/what-does-this-dollar-sign-over-arrow-in-function-mapping-mean\n//https://eprint.iacr.org/2014/714.pdf\nvector<int> ListSieve(Matrix<int> &B, float bound, ostream &o)\n{\n    Matrix<int> L;\n    Matrix<_type> gramSmidt = gSchmidt(B);\n    vector<int> a(B[0].size(), 0);\n    vector<double> lengths;\n    map<int, int> _map;\n    size_t max_number_of_collistions = 200;\n    int iter = 0;\n    for (int i = 0, k = 0; 10*i < max_number_of_collistions + 2000 || L.size() == 0; k++)\n    {\n        iter++;\n        vector<int> v = kleinSample(B, gramSmidt, 1, a);\n        ListReduce(v, L, lengths);\n        bool isZero = true;\n        for (auto in : v)\n        {\n            if (in != 0)\n            {\n                isZero = false;\n                break;\n            }\n        }\n        _map.insert(make_pair(k, i));\n        if (isZero)\n        {\n            i++;\n        }\n        else if (sqrt(squaredLengthOfVector(v)) < bound)\n        {\n            o << \"early list iter : \" << iter << \"|\\n\";\n            return v;\n        }\n        else\n        {\n            L.push_back(v);\n            lengths.push_back(squaredLengthOfVector(v));\n        }\n        max_number_of_collistions = std::max(max_number_of_collistions, L.size());\n\n    }\n    vector<int> shortestVector = L[0];\n    int _a = 0, count = 0;\n    for (int i = 1; i < L.size(); i++)\n    {\n        if (sqrt(squaredLengthOfVector(L[i])) <= bound)\n        {\n            count++;\n        }\n        if (squaredLengthOfVector(shortestVector) > squaredLengthOfVector(L[i]))\n        {\n            shortestVector = L[i];\n            _a = i;\n        }\n    }\n    cout << \"count \" << count << endl;\n    cout << \"list at : \" << _map.at(_a) << endl;\n    o << \"list iter : \" << iter << \"|\\n\";\n    return shortestVector;\n}\n\nvector<int> sumVectorsWithCoeff(Matrix<int> &matrix, vector<int> &c)\n{\n    vector<int> a(c.size(), 0);\n    for (size_t i = 0; i < c.size(); i++)\n    {\n        a = a + c[i] * matrix[i];\n    }\n    return a;\n}\n\nbool checkifBiggerByEachCoordinate(vector<int> &a, vector<int> &b)\n{\n    for (size_t i = 0; i < a.size(); i++)\n    {\n        if (abs(a[i]) > abs(b[i]))\n            return false;\n    }\n    return true;\n}\n\nvector<int> LLLenumerate(Matrix<int> &matrix, ofstream &myfile)\n{\n    Matrix<int> enumeration;\n    int n = matrix.size();\n    int lim = pow(2, n * (n - 1) / 4.0);\n    vector<int> c(n, 0);\n    c[0] = 1;\n    vector<int> shortest = sumVectorsWithCoeff(matrix, c);\n    auto shortestL = squaredLengthOfVector(shortest);\n    long long tmpL;\n    vector<int> tmp;\n    tmp = sumVectorsWithCoeff(matrix, c);\n    if (!checkifBiggerByEachCoordinate(shortest, tmp))\n    {\n        tmpL = squaredLengthOfVector(tmp);\n        if (tmpL > 0 && shortestL > tmpL)\n        {\n            shortestL = tmpL;\n            shortest = tmp;\n        }\n    }\n    for (int i = 0; i < n;)\n    {\n        int &a = c[i];\n        if (a == -lim)\n        {\n            for (int j = 0; j < i; j++)\n                c[j] = -lim;\n            a++;\n            i = 0;\n            tmp = sumVectorsWithCoeff(matrix, c);\n            if (!checkifBiggerByEachCoordinate(shortest, tmp))\n            {\n                tmpL = squaredLengthOfVector(tmp);\n                if (tmpL > 0 && shortestL > tmpL)\n                {\n                    shortestL = tmpL;\n                    shortest = tmp;\n                }\n            }\n            // for (auto &bb : c)\n            //     cout << bb;\n            // cout << endl;\n            // // enumeration.push_back(sumVectorsWithCoeff(matrix, c));\n        }\n        else if (a < lim)\n        {\n            a++;\n            if (a == lim)\n                i++;\n            else\n                i = 0;\n            tmp = sumVectorsWithCoeff(matrix, c);\n            if (!checkifBiggerByEachCoordinate(shortest, tmp))\n            {\n                tmpL = squaredLengthOfVector(tmp);\n                if (tmpL > 0 && shortestL > tmpL)\n                {\n                    shortestL = tmpL;\n                    shortest = tmp;\n                }\n            }\n            // for (auto &bb : c)\n            //     cout << bb;\n            // cout << endl;\n            // // enumeration.push_back(sumVectorsWithCoeff(matrix, c));\n        }\n        else if (a == lim)\n        {\n            i++;\n        }\n    }\n    return shortest;\n}\n\n//https://web.eecs.umich.edu/~cpeikert/pubs/lattice-survey.pdf\nMatrix<int> generateLattice(int dimm, int diff, int iter, bool print, ofstream &file)\n{\n    Matrix<int> m(dimm, vector<int>(dimm, 0));\n\n    file << \"---------------------------------------------\\n\\n\"\n         << \"dimm: \" << dimm << \" iter: \" << iter << \" diff: \" << diff << \"|\\n\";\n    int summ = 0;\n    srand(time(0));\n    file << '[';\n    for (auto &v : m)\n    {\n        file << '[';\n        for (auto &el : v)\n        {\n            float f = rand();\n            el = f / RAND_MAX * (float)diff * 3;\n            summ += el;\n            file << el << ' ';\n        }\n        file << \"]\\n\";\n    }\n    file << \"]\\n\";\n    file << \" summ: \" << summ << \"\\n\\n\";\n    return m;\n}\n//void preprocessVoronoi(Matrix<int>& B)\n//{\n//    LLL(B);\n//}\n//\n//vector<int> findRelevantHelper(Matrix<int>& B, int p, int n)\n//{\n//    vector<int> res(B.size(), 0);\n//    for (size_t i = 0; i < n; i++)\n//    {\n//        if (p & 1)\n//        {\n//            res = res - B[i];\n//        }\n//        p = p >> 1;\n//    }\n//    for (auto& b : res)\n//        b = b / 2;\n//    return res;\n//}\n//\n//vector<int> CVPP2V(vector<int>& t, Matrix<vector<int>>& Voronoi) {\n//    int i = 0;\n//    vector<int> t0(t.size()), ti(t.size());\n//    while (find_if(Voronoi.begin(), Voronoi.end(), [&ti](auto& v) {\n//        return v[0] == ti\n//    }) == Voronoi.end()) {\n//        float tmp = mu(ti, Voronoi[0][0]);\n//        int maxi = 0;\n//        for (size_t j = 1; j < Voronoi.size(); j++)\n//        {\n//            if (tmp < mu(ti,Voronoi[j][0])) {\n//                maxi = j;\n//            }\n//        }\n//        ti = ti - ti;\n//        i++;\n//    }\n//\n//    return t0 - ti;\n//}\n//vector<int> CVPP(vector<int>& t, Matrix<int>& B, Matrix<vector<int>>& Voronoi) {\n//    vector<int> res(t.size(), 0), tp;\n//    for (auto& v : B) {\n//        res = res + mu(t, v) * v;\n//    }\n//    // not sure about this\n//    int p = 0;\n//    while(true) {\n//        p++;\n//        if (squaredLengthOfVector(t) < (squaredLengthOfVector(pow(2, p) * Voronoi[0][0]))) {\n//            break;\n//        }\n//    }\n//\n//    for (int i = p - 1; i > 0; i--) {\n//        tp = tp - CVPP2V(tp, pow(2, i - 1) * Voronoi);\n//    }\n//    return res - tp;\n//}\n//\n//vector<int> rankReduceCVP(const vector<int>& t, Matrix<int>& B, Matrix<vector<int>>& Voronoi, int H) {\n//    vector<int> res(t.size(), 0), v, closest, tmp;\n//    int h = mu(t, B.at(Voronoi.size()));\n//    float length, tmplength;\n//    int i = h - H + 1;\n//    res = CVPP(t - h * B.at(Voronoi.size()), Voronoi.back());\n//    length = squaredLengthOfVector(res);\n//    i++;\n//    // todo is it correct?\n//    for (; abs(i - h) < H; i++) {\n//        v = CVPP(t - i * B.at(Voronoi.size()), Voronoi.back());\n//        tmp = v - t;\n//        tmplength = squaredLengthOfVector(tmp);\n//        if (tmplength < length) {\n//            length = tmplength;\n//            res = tmp;\n//        }\n//    }\n//    return res;\n//}\n//\n//Matrix<vector<int>> findRelevant(Matrix<int>& B, Matrix<vector<int>>& Voronoi, int H)\n//{\n//    Matrix<vector<int>> res;\n//    vector<int> t, c;\n//    int l = pow(2, B.size());\n//    // p - \u0432\u0435\u043a\u0442\u043e\u0440 \u0438\u0437 \u043d\u0435\u043b\u0435\u0439 \u0438 1\n//    for (int p = 1; p < l; p++)\n//    {\n//        t = findRelevantHelper(B, p, B.size());\n//        c = rankReduceCVP(t, B, Voronoi, H);\n//        t = 2 * (t - c);\n//        c = inverse(t);\n//        res.push_back({ t, c });\n//    }\n//    return res;\n//}\n//void removeNonRelevant(Matrix<vector<int>>& res)\n//{\n//    for (size_t i = 0; i < res.size(); i++)\n//    {\n//        for (size_t j = 0; j < res.size(); j++)\n//        {\n//            if (i != j && squaredLengthOfVector(res[j][0] - 0.5 * res[i][0]) <= squaredLengthOfVector(0.5 * res[i][0])) {\n//                // debug whats in it\n//                res.erase(res.begin() + i);\n//            }\n//        }\n//\n//    }\n//\n//}\n//\n//Matrix<vector<int>> computeVcell(Matrix<int>& B, Matrix<vector<int>>& Voronoi, int H)\n//{\n//    Matrix<vector<int>> res = findRelevant(B, Voronoi, H);\n//    removeNonRelevant(res);\n//    return res;\n//}\n//// https://cseweb.ucsd.edu/~pvoulgar/files/voronoi_full.pdf\n//void basicVoronoiCell(Matrix<int>& B)\n//{\n//    preprocessVoronoi(B);\n//    Matrix<vector<int>> Voronoi(1);\n//    Matrix<int> newB;\n//    Voronoi[0] = { B[0], inverse(B[0]) };\n//    for (int i = 1; i < B.size(); i++)\n//    {\n//        for (size_t j = 0; j < i; j++)\n//        {\n//            newB.push_back(B[j]);\n//        }\n//        // nedd to remake to vec of vec of vec\n//        Voronoi = computeVcell(newB, Voronoi, pow(2, 0.5 * i));\n//    }\n//}\n// void printShortestVector(const plll::linalg::math_matrix<plll::arithmetic::Integer> & A,\n//                          unsigned index, const plll::arithmetic::Integer & sqnorm)\n// {\n//     std::cout << \"The currently shortest vector is \" << A.row(index)\n//               << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n// }\n// void printShortestVector_LI(const plll::linalg::math_matrix<plll::arithmetic::NInt<long> > & A,\n//                             unsigned index, const plll::arithmetic::NInt<long> & sqnorm)\n// {\n//     std::cout << \"The currently shortest vector is \" << A.row(index)\n//               << \" with squared norm \" << sqnorm << \" (NInt<long>)\\n\";\n// }\n\nplll::LatticeReduction::MinCallbackFunction_LI f_LI(ostream &file, vector<int> &r)\n{\n    return [&r, &file](const plll::linalg::math_matrix<plll::arithmetic::NInt<long>> &A,\n                       unsigned index, const plll::arithmetic::NInt<long> &sqnorm) {\n        auto i = A.row(index).enumerate();\n        int iter = 0;\n        while (i.has_current())\n        {\n            r[iter++] = plll::arithmetic::convert<int>(i.current());\n            i.next();\n        }\n        file << \"The currently shortest vector is \" << A.row(index)\n             << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n    };\n}\n\nplll::LatticeReduction::MinCallbackFunction f(ostream &file, vector<int> &r)\n{\n    return [&r, &file](const plll::linalg::math_matrix<plll::arithmetic::Integer> &A,\n                       unsigned index, const plll::arithmetic::Integer &sqnorm) {\n        auto i = A.row(index).enumerate();\n        int iter = 0;\n        while (i.has_current())\n        {\n            r[iter++] = plll::arithmetic::convert<int>(i.current());\n            i.next();\n        }\n        file << \"The currently shortest vector is \" << A.row(index)\n             << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n    };\n}\nvector<int> shortestVectorByVoronoi(Matrix<int> &B, int dimm, ostream &file)\n{\n    cout << \"mat\";\n    vector<int> res(dimm);\n    cout << \"mat\";\n    plll::linalg::base_matrix<plll::arithmetic::Integer> mat(dimm, dimm);\n    cout << \"mat\";\n\n    plll::linalg::base_matrix<plll::arithmetic::Integer>::Enumerator iterr = mat.enumerate();\n    cout << \"mat\";\n\n    int i = 0, x, y;\n    while (iterr.has_current())\n    {\n        x = i / dimm;\n        y = i % dimm;\n        iterr.current() = plll::arithmetic::Integer(B[x][y]);\n        iterr.next();\n        i++;\n    }\n    cout << mat << endl;\n    plll::LatticeReduction lr;\n    //cin >> mat;\n    plll::linalg::math_matrix<plll::arithmetic::Integer> A(mat);\n    lr.setLattice(A);\n    lr.setSVPMode(plll::LatticeReduction::SVP_VoronoiCellSVP);\n    cout << \"mat\";\n\n    lr.setMinCallbackFunction(f(file, res), f_LI(file, res));\n    lr.svp();\n    file << \"voronoi res \" << lr.getLattice() << endl\n         << endl;\n    mat = lr.getLattice();\n    iterr = mat.enumerate();\n    for (int i = 0; i < dimm; i++)\n    {\n        res[i] = plll::arithmetic::convert<int>(iterr.current());\n        iterr.next();\n    }\n    return res;\n}\n\nmatrix_with_det readFromFile(ifstream &myfile)\n{\n    matrix_with_det res;\n    string line;\n    std::regex e(\"det.*\");\n    getline(myfile, line);\n    // cout << line << endl;\n    // while (!regex_match(line, e))\n    // {\n        if (myfile.eof())\n        {\n            res.det = 0;\n            return res;\n        }\n    //     getline(myfile, line);\n    //     cout << line << \"k\" << endl;\n    // }\n    std::regex e2(\"\\\\d+\");\n    std::smatch sm;\n\n    // std::regex_search(line, sm, e2);\n    int det = 3;\n    // line = sm.suffix().str();\n    // cout << \"\\ndet \" << det;\n    // std::regex_search(line, sm, e2);\n    int dimm = 3;\n   \n    // std::regex_search(line, sm, e2);\n    // int det = stoi(sm.str());\n    // line = sm.suffix().str();\n    // cout << \"\\ndet \" << det;\n    // std::regex_search(line, sm, e2);\n    // int dimm = stoi(sm.str());\n   \n    Matrix<int> matr(dimm, vector<int>(dimm));\n    cout << \"\\ndimm \" << dimm;\n\n    for (int i = 0; i < dimm; i++)\n    {\n        getline(myfile, line);\n        int j = 0;\n        while (std::regex_search(line, sm, e2))\n        {\n            matr[i][j++] = stoi(sm.str());\n            line = sm.suffix().str();\n        }\n        cout << endl;\n    }\n    printVS(matr);\n    res.det = det;\n    res.mat = matr;\n    return res;\n}\n\nvoid printResVector(vector<int> &v, string method, ostream &o)\n{\n    o << endl\n      << method << \" size: \" << sqrt(squaredLengthOfVector(v)) << endl\n      << \"[ \";\n    for (auto &a : v)\n    {\n        o << a << \" \";\n    }\n    o << \"] \" << endl;\n}\n\nint main()\n{\n\n    ofstream myfile;\n\n    ifstream datafile;\n    myfile.open(\"example.txt\");\n\n    datafile.open(\"det3.txt\");\n    matrix_with_det md = readFromFile(datafile);\n    cout << md.det;\n\n    while (md.det != 0)\n    {\n        cout << \"det\" << md.det;\n\n        Matrix<int> matrix = md.mat;\n        Matrix<int> matrix2 = matrix;\n        Matrix<int> matrix3 = matrix;\n        Matrix<int> original(matrix2);\n        Matrix<float> gramSmidt = gSchmidt(matrix);\n\n        cout << \"starting voronoi\" << endl;\n        auto t1 = std::chrono::high_resolution_clock::now();\n        int dimm = matrix.size();\n        cout << \"t\";\n        auto vector_voronoi = shortestVectorByVoronoi(matrix, matrix.size(), myfile);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        auto duration = std::chrono::duration_cast<sec_type>(t2 - t1).count();\n        myfile << \"voronoi duration \" << duration << endl;\n        myfile << \"\\n\\n\";\n\n        float bound = 1;\n        // bound = 1;\n        cout << \"starting gauss\" << endl;\n        t1 = std::chrono::high_resolution_clock::now();\n        vector<int> sv = gaussSieve(matrix2, bound, myfile);\n        t2 = std::chrono::high_resolution_clock::now();\n        duration = std::chrono::duration_cast<sec_type>(t2 - t1).count();\n        myfile << \"gauss duration: \" << duration << endl;\n        myfile << \"\\n\\n\";\n        cout << \"f\\n\\n\";\n\n        cout << \"starting list\" << endl;\n        t1 = std::chrono::high_resolution_clock::now();\n        vector<int> v3 = ListSieve(matrix3, bound, myfile);\n        // auto vector_voronoi = v3;\n        t2 = std::chrono::high_resolution_clock::now();\n        duration = std::chrono::duration_cast<sec_type>(t2 - t1).count();\n        myfile << \"list duration: \" << duration << endl;\n\n        bound = 1.01 * (sqrt(dimm)) * pow(abs(md.det), 1.0 / dimm);\n        myfile << \"bound \" << bound << endl;\n        t1 = std::chrono::high_resolution_clock::now();\n        vector<int> gauss_with_bound = gaussSieve(matrix2, bound, myfile);\n        t2 = std::chrono::high_resolution_clock::now();\n        duration = std::chrono::duration_cast<sec_type>(t2 - t1).count();\n        myfile << \"gauss with bound duration: \" << duration << endl;\n        myfile << \"\\n\\n\";\n        cout << \"f\\n\\n\";\n\n        cout << \"starting bound list\" << endl;\n        t1 = std::chrono::high_resolution_clock::now();\n        vector<int> list_with_bound = ListSieve(matrix3, bound, myfile);\n        // auto vector_voronoi = v3;\n        t2 = std::chrono::high_resolution_clock::now();\n        duration = std::chrono::duration_cast<sec_type>(t2 - t1).count();\n        myfile << \"list with bound duration: \" << duration;\n\n        if (squaredLengthOfVector(list_with_bound) != squaredLengthOfVector(gauss_with_bound))\n        {\n            myfile << \"found different norms of vectors\";\n            printResVector(list_with_bound, \"list with bound\", myfile);\n            printResVector(gauss_with_bound, \"gauss with bound\", myfile);\n        }\n        else\n        {\n            myfile << endl\n                   << \"shortest with bound norm\" << (long)squaredLengthOfVector(gauss_with_bound) << endl;\n            printVec(gauss_with_bound, myfile);\n        }\n\n        if (squaredLengthOfVector(vector_voronoi) != squaredLengthOfVector(sv) || squaredLengthOfVector(sv) != squaredLengthOfVector(vector_voronoi))\n        {\n            myfile << \"found different norms of vectors\";\n\n            printResVector(vector_voronoi, \"voronoi\", myfile);\n            printResVector(sv, \"gauss\", myfile);\n            printResVector(v3, \"list\", myfile);\n        }\n        else\n        {\n            myfile << endl\n                   << \"shortest with norm\" << (long)squaredLengthOfVector(sv) << endl;\n            printVec(sv, myfile);\n        }\n        myfile << \"---------------------------------------------------------------------\\n\\n\";\n        md = readFromFile(datafile);\n    }\n\n    // myfile << dimm << \" \" << diff << \" \" << iter << endl;\n\n    //         }\n    //     }\n    // }\n    // }\n    // catch (exception e)\n    // {\n    //     cout << e.what();\n    // }\n    myfile.close();\n    return 0;\n}", "meta": {"hexsha": "d4d47317a6708c87d55d4c67b28fa6b7b9932f12", "size": 37968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "svp/src/svp2.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "svp/src/svp2.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svp/src/svp2.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["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.2921013413, "max_line_length": 149, "alphanum_fraction": 0.473820059, "num_tokens": 10938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894270096561}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\nusing namespace std; \n#include <boost/timer.hpp>\n\n// for sophus \n#include <sophus/se3.h>\nusing Sophus::SE3;\n\n// for eigen \n#include <Eigen/Core>\n#include <Eigen/Geometry>\nusing namespace Eigen;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nusing namespace cv;\n\n/**********************************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86\u5355\u76ee\u76f8\u673a\u5728\u5df2\u77e5\u8f68\u8ff9\u4e0b\u7684\u7a20\u5bc6\u6df1\u5ea6\u4f30\u8ba1\n* \u4f7f\u7528\u6781\u7ebf\u641c\u7d22 + NCC \u5339\u914d\u7684\u65b9\u5f0f\uff0c\u4e0e\u4e66\u672c\u7684 13.2 \u8282\u5bf9\u5e94\n* \u8bf7\u6ce8\u610f\u672c\u7a0b\u5e8f\u5e76\u4e0d\u5b8c\u7f8e\uff0c\u4f60\u5b8c\u5168\u53ef\u4ee5\u6539\u8fdb\u5b83\u2014\u2014\u6211\u5176\u5b9e\u5728\u6545\u610f\u66b4\u9732\u4e00\u4e9b\u95ee\u9898\u3002\n***********************************************/\n\n\n\n// ------------------------------------------------------------------\n// parameters \nconst int boarder = 20; \t// \u8fb9\u7f18\u5bbd\u5ea6\nconst int width = 640;  \t// \u5bbd\u5ea6 \nconst int height = 480;  \t// \u9ad8\u5ea6\nconst double fx = 481.2f;\t// \u76f8\u673a\u5185\u53c2\nconst double fy = -480.0f;\nconst double cx = 319.5f;\nconst double cy = 239.5f;\nconst int ncc_window_size = 2;\t// NCC \u53d6\u7684\u7a97\u53e3\u534a\u5bbd\u5ea6\nconst int ncc_area = (2*ncc_window_size+1)*(2*ncc_window_size+1); // NCC\u7a97\u53e3\u9762\u79ef\nconst double min_cov = 0.1;\t// \u6536\u655b\u5224\u5b9a\uff1a\u6700\u5c0f\u65b9\u5dee\nconst double max_cov = 10;\t// \u53d1\u6563\u5224\u5b9a\uff1a\u6700\u5927\u65b9\u5dee\n\n// ------------------------------------------------------------------\n// \u91cd\u8981\u7684\u51fd\u6570 \n// \u4ece REMODE \u6570\u636e\u96c6\u8bfb\u53d6\u6570\u636e  \nbool readDatasetFiles( \n    const string& path, \n    vector<string>& color_image_files, \n    vector<SE3>& poses \n);\n\n// \u6839\u636e\u65b0\u7684\u56fe\u50cf\u66f4\u65b0\u6df1\u5ea6\u4f30\u8ba1\nbool update( \n    const Mat& ref, \n    const Mat& curr, \n    const SE3& T_C_R, \n    Mat& depth, \n    Mat& depth_cov \n);\n\n// \u6781\u7ebf\u641c\u7d22 \nbool epipolarSearch( \n    const Mat& ref, \n    const Mat& curr, \n    const SE3& T_C_R, \n    const Vector2d& pt_ref, \n    const double& depth_mu, \n    const double& depth_cov,\n    Vector2d& pt_curr\n);\n\n// \u66f4\u65b0\u6df1\u5ea6\u6ee4\u6ce2\u5668 \nbool updateDepthFilter( \n    const Vector2d& pt_ref, \n    const Vector2d& pt_curr, \n    const SE3& T_C_R, \n    Mat& depth, \n    Mat& depth_cov\n);\n\n// \u8ba1\u7b97 NCC \u8bc4\u5206 \ndouble NCC( const Mat& ref, const Mat& curr, const Vector2d& pt_ref, const Vector2d& pt_curr );\n\n// \u53cc\u7ebf\u6027\u7070\u5ea6\u63d2\u503c \ninline double getBilinearInterpolatedValue( const Mat& img, const Vector2d& pt ) {\n    uchar* d = & img.data[ int(pt(1,0))*img.step+int(pt(0,0)) ];\n    double xx = pt(0,0) - floor(pt(0,0)); \n    double yy = pt(1,0) - floor(pt(1,0));\n    return  (( 1-xx ) * ( 1-yy ) * double(d[0]) +\n            xx* ( 1-yy ) * double(d[1]) +\n            ( 1-xx ) *yy* double(d[img.step]) +\n            xx*yy*double(d[img.step+1]))/255.0;\n}\n\n// ------------------------------------------------------------------\n// \u4e00\u4e9b\u5c0f\u5de5\u5177 \n// \u663e\u793a\u4f30\u8ba1\u7684\u6df1\u5ea6\u56fe \nbool plotDepth( const Mat& depth );\n\n// \u50cf\u7d20\u5230\u76f8\u673a\u5750\u6807\u7cfb \ninline Vector3d px2cam ( const Vector2d px ) {\n    return Vector3d ( \n        (px(0,0) - cx)/fx,\n        (px(1,0) - cy)/fy, \n        1\n    );\n}\n\n// \u76f8\u673a\u5750\u6807\u7cfb\u5230\u50cf\u7d20 \ninline Vector2d cam2px ( const Vector3d p_cam ) {\n    return Vector2d (\n        p_cam(0,0)*fx/p_cam(2,0) + cx, \n        p_cam(1,0)*fy/p_cam(2,0) + cy \n    );\n}\n\n// \u68c0\u6d4b\u4e00\u4e2a\u70b9\u662f\u5426\u5728\u56fe\u50cf\u8fb9\u6846\u5185\ninline bool inside( const Vector2d& pt ) {\n    return pt(0,0) >= boarder && pt(1,0)>=boarder \n        && pt(0,0)+boarder<width && pt(1,0)+boarder<=height;\n}\n\n// \u663e\u793a\u6781\u7ebf\u5339\u914d \nvoid showEpipolarMatch( const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_curr );\n\n// \u663e\u793a\u6781\u7ebf \nvoid showEpipolarLine( const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_min_curr, const Vector2d& px_max_curr );\n// ------------------------------------------------------------------\n\n\nint main( int argc, char** argv )\n{\n    if ( argc != 2 )\n    {\n        cout<<\"Usage: dense_mapping path_to_test_dataset\"<<endl;\n        return -1;\n    }\n    \n    // \u4ece\u6570\u636e\u96c6\u8bfb\u53d6\u6570\u636e\n    vector<string> color_image_files; \n    vector<SE3> poses_TWC;\n    bool ret = readDatasetFiles( argv[1], color_image_files, poses_TWC );\n    if ( ret==false )\n    {\n        cout<<\"Reading image files failed!\"<<endl;\n        return -1; \n    }\n    cout<<\"read total \"<<color_image_files.size()<<\" files.\"<<endl;\n    \n    // \u7b2c\u4e00\u5f20\u56fe\n    Mat ref = imread( color_image_files[0], 0 );                // gray-scale image \n    SE3 pose_ref_TWC = poses_TWC[0];\n    double init_depth   = 3.0;    // \u6df1\u5ea6\u521d\u59cb\u503c\n    double init_cov2    = 3.0;    // \u65b9\u5dee\u521d\u59cb\u503c \n    Mat depth( height, width, CV_64F, init_depth );             // \u6df1\u5ea6\u56fe\n    Mat depth_cov( height, width, CV_64F, init_cov2 );          // \u6df1\u5ea6\u56fe\u65b9\u5dee \n    \n    for ( int index=1; index<color_image_files.size(); index++ )\n    {\n        cout<<\"*** loop \"<<index<<\" ***\"<<endl;\n        Mat curr = imread( color_image_files[index], 0 );       \n        if (curr.data == nullptr) continue;\n        SE3 pose_curr_TWC = poses_TWC[index];\n        SE3 pose_T_C_R = pose_curr_TWC.inverse() * pose_ref_TWC; // \u5750\u6807\u8f6c\u6362\u5173\u7cfb\uff1a T_C_W * T_W_R = T_C_R \n        update( ref, curr, pose_T_C_R, depth, depth_cov );\n        plotDepth( depth );\n        imshow(\"image\", curr);\n        waitKey(1);\n    }\n    \n    cout<<\"estimation returns, saving depth map ...\"<<endl;\n    imwrite( \"depth.png\", depth );\n    cout<<\"done.\"<<endl;\n    \n    return 0;\n}\n\nbool readDatasetFiles(\n    const string& path, \n    vector< string >& color_image_files, \n    std::vector<SE3>& poses\n)\n{\n    ifstream fin( path+\"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if ( !fin ) return false;\n    \n    while ( !fin.eof() )\n    {\n\t\t// \u6570\u636e\u683c\u5f0f\uff1a\u56fe\u50cf\u6587\u4ef6\u540d tx, ty, tz, qx, qy, qz, qw \uff0c\u6ce8\u610f\u662f TWC \u800c\u975e TCW\n        string image; \n        fin>>image; \n        double data[7];\n        for ( double& d:data ) fin>>d;\n        \n        color_image_files.push_back( path+string(\"/images/\")+image );\n        poses.push_back(\n            SE3( Quaterniond(data[6], data[3], data[4], data[5]), \n                 Vector3d(data[0], data[1], data[2]))\n        );\n        if ( !fin.good() ) break;\n    }\n    return true;\n}\n\n// \u5bf9\u6574\u4e2a\u6df1\u5ea6\u56fe\u8fdb\u884c\u66f4\u65b0\nbool update(const Mat& ref, const Mat& curr, const SE3& T_C_R, Mat& depth, Mat& depth_cov )\n{\n#pragma omp parallel for\n    for ( int x=boarder; x<width-boarder; x++ )\n#pragma omp parallel for\n        for ( int y=boarder; y<height-boarder; y++ )\n        {\n\t\t\t// \u904d\u5386\u6bcf\u4e2a\u50cf\u7d20\n            if ( depth_cov.ptr<double>(y)[x] < min_cov || depth_cov.ptr<double>(y)[x] > max_cov ) // \u6df1\u5ea6\u5df2\u6536\u655b\u6216\u53d1\u6563\n                continue;\n            // \u5728\u6781\u7ebf\u4e0a\u641c\u7d22 (x,y) \u7684\u5339\u914d \n            Vector2d pt_curr; \n            bool ret = epipolarSearch ( \n                ref, \n                curr, \n                T_C_R, \n                Vector2d(x,y), \n                depth.ptr<double>(y)[x], \n                sqrt(depth_cov.ptr<double>(y)[x]),\n                pt_curr\n            );\n            \n            if ( ret == false ) // \u5339\u914d\u5931\u8d25\n                continue; \n            \n\t\t\t// \u53d6\u6d88\u8be5\u6ce8\u91ca\u4ee5\u663e\u793a\u5339\u914d\n            // showEpipolarMatch( ref, curr, Vector2d(x,y), pt_curr );\n            \n            // \u5339\u914d\u6210\u529f\uff0c\u66f4\u65b0\u6df1\u5ea6\u56fe \n            updateDepthFilter( Vector2d(x,y), pt_curr, T_C_R, depth, depth_cov );\n        }\n}\n\n// \u6781\u7ebf\u641c\u7d22\n// \u65b9\u6cd5\u89c1\u4e66 13.2 13.3 \u4e24\u8282\nbool epipolarSearch(\n    const Mat& ref, const Mat& curr, \n    const SE3& T_C_R, const Vector2d& pt_ref, \n    const double& depth_mu, const double& depth_cov, \n    Vector2d& pt_curr )\n{\n    Vector3d f_ref = px2cam( pt_ref );\n    f_ref.normalize();\n    Vector3d P_ref = f_ref*depth_mu;\t// \u53c2\u8003\u5e27\u7684 P \u5411\u91cf\n    \n    Vector2d px_mean_curr = cam2px( T_C_R*P_ref ); // \u6309\u6df1\u5ea6\u5747\u503c\u6295\u5f71\u7684\u50cf\u7d20\n    double d_min = depth_mu-3*depth_cov, d_max = depth_mu+3*depth_cov;\n    if ( d_min<0.1 ) d_min = 0.1;\n    Vector2d px_min_curr = cam2px( T_C_R*(f_ref*d_min) );\t// \u6309\u6700\u5c0f\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n    Vector2d px_max_curr = cam2px( T_C_R*(f_ref*d_max) );\t// \u6309\u6700\u5927\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n    \n    Vector2d epipolar_line = px_max_curr - px_min_curr;\t// \u6781\u7ebf\uff08\u7ebf\u6bb5\u5f62\u5f0f\uff09\n    Vector2d epipolar_direction = epipolar_line;\t\t// \u6781\u7ebf\u65b9\u5411 \n    epipolar_direction.normalize();\n    double half_length = 0.5*epipolar_line.norm();\t// \u6781\u7ebf\u7ebf\u6bb5\u7684\u534a\u957f\u5ea6\n    if ( half_length>100 ) half_length = 100;   // \u6211\u4eec\u4e0d\u5e0c\u671b\u641c\u7d22\u592a\u591a\u4e1c\u897f \n    \n\t// \u53d6\u6d88\u6b64\u53e5\u6ce8\u91ca\u4ee5\u663e\u793a\u6781\u7ebf\uff08\u7ebf\u6bb5\uff09\n    // showEpipolarLine( ref, curr, pt_ref, px_min_curr, px_max_curr );\n    \n    // \u5728\u6781\u7ebf\u4e0a\u641c\u7d22\uff0c\u4ee5\u6df1\u5ea6\u5747\u503c\u70b9\u4e3a\u4e2d\u5fc3\uff0c\u5de6\u53f3\u5404\u53d6\u534a\u957f\u5ea6\n    double best_ncc = -1.0;\n    Vector2d best_px_curr; \n    for ( double l=-half_length; l<=half_length; l+=0.7 )  // l+=sqrt(2) \n    {\n        Vector2d px_curr = px_mean_curr + l*epipolar_direction;  // \u5f85\u5339\u914d\u70b9\n        if ( !inside(px_curr) )\n            continue; \n        // \u8ba1\u7b97\u5f85\u5339\u914d\u70b9\u4e0e\u53c2\u8003\u5e27\u7684 NCC\n        double ncc = NCC( ref, curr, pt_ref, px_curr );\n        if ( ncc>best_ncc )\n        {\n            best_ncc = ncc; \n            best_px_curr = px_curr;\n        }\n    }\n    if ( best_ncc < 0.85f )      // \u53ea\u76f8\u4fe1 NCC \u5f88\u9ad8\u7684\u5339\u914d\n        return false; \n    pt_curr = best_px_curr;\n    return true;\n}\n\ndouble NCC (\n    const Mat& ref, const Mat& curr, \n    const Vector2d& pt_ref, const Vector2d& pt_curr\n)\n{\n    // \u96f6\u5747\u503c-\u5f52\u4e00\u5316\u4e92\u76f8\u5173\n    // \u5148\u7b97\u5747\u503c\n    double mean_ref = 0, mean_curr = 0;\n    vector<double> values_ref, values_curr; // \u53c2\u8003\u5e27\u548c\u5f53\u524d\u5e27\u7684\u5747\u503c\n    for ( int x=-ncc_window_size; x<=ncc_window_size; x++ )\n        for ( int y=-ncc_window_size; y<=ncc_window_size; y++ )\n        {\n            double value_ref = double(ref.ptr<uchar>( int(y+pt_ref(1,0)) )[ int(x+pt_ref(0,0)) ])/255.0;\n            mean_ref += value_ref;\n            \n            double value_curr = getBilinearInterpolatedValue( curr, pt_curr+Vector2d(x,y) );\n            mean_curr += value_curr;\n            \n            values_ref.push_back(value_ref);\n            values_curr.push_back(value_curr);\n        }\n        \n    mean_ref /= ncc_area;\n    mean_curr /= ncc_area;\n    \n\t// \u8ba1\u7b97 Zero mean NCC\n    double numerator = 0, demoniator1 = 0, demoniator2 = 0;\n    for ( int i=0; i<values_ref.size(); i++ )\n    {\n        double n = (values_ref[i]-mean_ref) * (values_curr[i]-mean_curr);\n        numerator += n;\n        demoniator1 += (values_ref[i]-mean_ref)*(values_ref[i]-mean_ref);\n        demoniator2 += (values_curr[i]-mean_curr)*(values_curr[i]-mean_curr);\n    }\n    return numerator / sqrt( demoniator1*demoniator2+1e-10 );   // \u9632\u6b62\u5206\u6bcd\u51fa\u73b0\u96f6\n}\n\nbool updateDepthFilter(\n    const Vector2d& pt_ref, \n    const Vector2d& pt_curr, \n    const SE3& T_C_R,\n    Mat& depth, \n    Mat& depth_cov\n)\n{\n    // \u6211\u662f\u4e00\u53ea\u55b5\n    // \u4e0d\u77e5\u9053\u8fd9\u6bb5\u8fd8\u6709\u6ca1\u6709\u4eba\u770b\n    // \u7528\u4e09\u89d2\u5316\u8ba1\u7b97\u6df1\u5ea6\n    SE3 T_R_C = T_C_R.inverse();\n    Vector3d f_ref = px2cam( pt_ref );\n    f_ref.normalize();\n    Vector3d f_curr = px2cam( pt_curr );\n    f_curr.normalize();\n    \n    // \u65b9\u7a0b\n    // d_ref * f_ref = d_cur * ( R_RC * f_cur ) + t_RC\n    // => [ f_ref^T f_ref, -f_ref^T f_cur ] [d_ref] = [f_ref^T t]\n    //    [ f_cur^T f_ref, -f_cur^T f_cur ] [d_cur] = [f_cur^T t]\n    // \u4e8c\u9636\u65b9\u7a0b\u7528\u514b\u83b1\u9ed8\u6cd5\u5219\u6c42\u89e3\u5e76\u89e3\u4e4b\n    Vector3d t = T_R_C.translation();\n    Vector3d f2 = T_R_C.rotation_matrix() * f_curr; \n    Vector2d b = Vector2d ( t.dot ( f_ref ), t.dot ( f2 ) );\n    double A[4];\n    A[0] = f_ref.dot ( f_ref );\n    A[2] = f_ref.dot ( f2 );\n    A[1] = -A[2];\n    A[3] = - f2.dot ( f2 );\n    double d = A[0]*A[3]-A[1]*A[2];\n    Vector2d lambdavec = \n        Vector2d (  A[3] * b ( 0,0 ) - A[1] * b ( 1,0 ),\n                    -A[2] * b ( 0,0 ) + A[0] * b ( 1,0 )) /d;\n    Vector3d xm = lambdavec ( 0,0 ) * f_ref;\n    Vector3d xn = t + lambdavec ( 1,0 ) * f2;\n    Vector3d d_esti = ( xm+xn ) / 2.0;  // \u4e09\u89d2\u5316\u7b97\u5f97\u7684\u6df1\u5ea6\u5411\u91cf\n    double depth_estimation = d_esti.norm();   // \u6df1\u5ea6\u503c\n    \n    // \u8ba1\u7b97\u4e0d\u786e\u5b9a\u6027\uff08\u4ee5\u4e00\u4e2a\u50cf\u7d20\u4e3a\u8bef\u5dee\uff09\n    Vector3d p = f_ref*depth_estimation;\n    Vector3d a = p - t; \n    double t_norm = t.norm();\n    double a_norm = a.norm();\n    double alpha = acos( f_ref.dot(t)/t_norm );\n    double beta = acos( -a.dot(t)/(a_norm*t_norm));\n    double beta_prime = beta + atan(1/fx);\n    double gamma = M_PI - alpha - beta_prime;\n    double p_prime = t_norm * sin(beta_prime) / sin(gamma);\n    double d_cov = p_prime - depth_estimation; \n    double d_cov2 = d_cov*d_cov;\n    \n    // \u9ad8\u65af\u878d\u5408\n    double mu = depth.ptr<double>( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ];\n    double sigma2 = depth_cov.ptr<double>( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ];\n    \n    double mu_fuse = (d_cov2*mu+sigma2*depth_estimation) / ( sigma2+d_cov2);\n    double sigma_fuse2 = ( sigma2 * d_cov2 ) / ( sigma2 + d_cov2 );\n    \n    depth.ptr<double>( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ] = mu_fuse; \n    depth_cov.ptr<double>( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ] = sigma_fuse2;\n    \n    return true;\n}\n\n// \u540e\u9762\u8fd9\u4e9b\u592a\u7b80\u5355\u6211\u5c31\u4e0d\u6ce8\u91ca\u4e86\uff08\u5176\u5b9e\u662f\u56e0\u4e3a\u61d2\uff09\nbool plotDepth(const Mat& depth)\n{\n    imshow( \"depth\", depth*0.4 );\n    waitKey(1);\n}\n\nvoid showEpipolarMatch(const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_curr)\n{\n    Mat ref_show, curr_show;\n    cv::cvtColor( ref, ref_show, CV_GRAY2BGR );\n    cv::cvtColor( curr, curr_show, CV_GRAY2BGR );\n    \n    cv::circle( ref_show, cv::Point2f(px_ref(0,0), px_ref(1,0)), 5, cv::Scalar(0,0,250), 2);\n    cv::circle( curr_show, cv::Point2f(px_curr(0,0), px_curr(1,0)), 5, cv::Scalar(0,0,250), 2);\n    \n    imshow(\"ref\", ref_show );\n    imshow(\"curr\", curr_show );\n    waitKey(1);\n}\n\nvoid showEpipolarLine(const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_min_curr, const Vector2d& px_max_curr)\n{\n\n    Mat ref_show, curr_show;\n    cv::cvtColor( ref, ref_show, CV_GRAY2BGR );\n    cv::cvtColor( curr, curr_show, CV_GRAY2BGR );\n    \n    cv::circle( ref_show, cv::Point2f(px_ref(0,0), px_ref(1,0)), 5, cv::Scalar(0,255,0), 2);\n    cv::circle( curr_show, cv::Point2f(px_min_curr(0,0), px_min_curr(1,0)), 5, cv::Scalar(0,255,0), 2);\n    cv::circle( curr_show, cv::Point2f(px_max_curr(0,0), px_max_curr(1,0)), 5, cv::Scalar(0,255,0), 2);\n    cv::line( curr_show, Point2f(px_min_curr(0,0), px_min_curr(1,0)), Point2f(px_max_curr(0,0), px_max_curr(1,0)), Scalar(0,255,0), 1);\n    \n    imshow(\"ref\", ref_show );\n    imshow(\"curr\", curr_show );\n    waitKey(1);\n}\n\n", "meta": {"hexsha": "9cdc2e3387a96236e31c1659effb0e5141e6174b", "size": 13276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_stars_repo_name": "renzhuli/SLAM", "max_stars_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T06:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T14:00:36.000Z", "max_issues_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_issues_repo_name": "renzhuli/SLAM", "max_issues_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_forks_repo_name": "renzhuli/SLAM", "max_forks_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T16:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T04:02:23.000Z", "avg_line_length": 30.9463869464, "max_line_length": 139, "alphanum_fraction": 0.5720849654, "num_tokens": 4723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6930890639445418}}
{"text": "#include <ceres/ceres.h>\n#include <ceres/gradient_checker.h>\n#include <Eigen/Core>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"wave/optimization/ceres/local_params/spherical_parameterization.hpp\"\n#include \"wave/wave_test.hpp\"\n#include \"wave/utils/math.hpp\"\n#include \"wave/geometry_og/transformation.hpp\"\n\nnamespace {\n\nclass TestSpherical : public ceres::SizedCostFunction<3, 3> {\n private:\n    const double *const normal;\n\n public:\n    virtual ~TestSpherical() {};\n\n    TestSpherical(const double *const normal) : normal(normal) {}\n\n    virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n        // Want to align the optimization parameter with the normal, error is a - b\n\n        residuals[0] = -normal[0] + parameters[0][0];\n        residuals[1] = -normal[1] + parameters[0][1];\n        residuals[2] = -normal[2] + parameters[0][2];\n\n        if (jacobians) {\n            Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> J(jacobians[0]);\n            J.setIdentity();\n        }\n        return true;\n    }\n};\n\n}\n\nnamespace wave {\n\nTEST(easy_cost_function, alignment) {\n    Vec3 normal;\n    normal << -1, 2, 4;\n    normal.normalize();\n\n    Vec3 initial;\n    initial.setRandom();\n    initial.normalize();\n\n    ceres::Problem problem;\n    ceres::CostFunction *cost = new TestSpherical(normal.data());\n    problem.AddResidualBlock(cost, nullptr, initial.data());\n\n    ceres::LocalParameterization *spherical = new SphericalParameterization();\n    problem.SetParameterization(initial.data(), spherical);\n\n    ceres::Solver::Options options;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.FullReport();\n\n    EXPECT_LT((initial - normal).norm(), 1e-6);\n    EXPECT_NEAR(initial.norm(), 1.0, 1e-6);\n}\n\n}", "meta": {"hexsha": "951e5f3cd4db6a1f804fb4b31bd0db1c37cc40f8", "size": 1825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/tests/ceres/spherical_param_test.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_optimization/tests/ceres/spherical_param_test.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_optimization/tests/ceres/spherical_param_test.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 27.6515151515, "max_line_length": 105, "alphanum_fraction": 0.6706849315, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6930890415931221}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// monomials_horner::policy::power2divfact.hpp                              //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\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_MONOMIALS_HORNER_POLICY_MULTI_POWER2DIVFACT_HPP_ER_2009\n#define BOOST_MONOMIALS_HORNER_POLICY_MULTI_POWER2DIVFACT_HPP_ER_2009\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace boost{\nnamespace monomials_horner{\n\n    // (a,b,c) --> 2^{a+b+c}/(a! b! c!)\n    struct multi_power2divfact{\n        typedef double                      result_type;\n        typedef double                      first_argument_type;\n        typedef unsigned                    second_argument_type;\n        multi_power2divfact(){}\n        result_type operator()(\n            first_argument_type a1,\n            second_argument_type a2\n        )const{\n            result_type d = std::pow(2.0,static_cast<result_type>(a2));\n            result_type f = math::factorial<result_type>(a2);\n            result_type r = d/f;\n            return a1 * static_cast<result_type>(r);\n        }\n        static result_type initial_value;\n    };\n    multi_power2divfact::result_type multi_power2divfact::initial_value\n        = static_cast<result_type>(1);\n\n}// monomials_horner\n}// boost\n\n#endif\n", "meta": {"hexsha": "e84cd0021d99fddddd97cc6a67cea5953326a00d", "size": 1716, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "monomials_horner/boost/monomials_horner/policy/multi_power2divfact.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "monomials_horner/boost/monomials_horner/policy/multi_power2divfact.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "monomials_horner/boost/monomials_horner/policy/multi_power2divfact.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9, "max_line_length": 78, "alphanum_fraction": 0.5285547786, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299653388752, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6930779465913077}}
{"text": "// C++ includes\n#include <iostream>\nusing namespace std;\n\n// Eigen includes\n#include <Eigen/Core>\nusing namespace Eigen;\n\n// autodiff include\n#include <autodiff/reverse.hpp>\n#include <autodiff/reverse/eigen.hpp>\nusing namespace autodiff;\n\n// The scalar function for which the gradient is needed\nvar f(const VectorXvar& x)\n{\n    return sqrt(x.cwiseProduct(x).sum()); // sqrt(sum([x(i) * x(i) for i = 1:5]))\n}\n\nint main()\n{\n    VectorXvar x(5);     // the input vector x with 5 variables\n    x << 1, 2, 3, 4, 5;  // x = [1, 2, 3, 4, 5]\n\n    var u = f(x);  // the output variable u\n\n    VectorXd g;  // the gradient vector to be computed in method `hessian`\n    MatrixXd H = hessian(u, x, g);  // evaluate the Hessian matrix H and the gradient vector g of u\n\n    cout << \"u = \" << u << endl;    // print the evaluated output variable u\n    cout << \"g = \\n\" << g << endl;  // print the evaluated gradient vector of u\n    cout << \"H = \\n\" << H << endl;  // print the evaluated Hessian matrix of u\n}\n", "meta": {"hexsha": "1f066a20b54d38ebfe32a4df93dac97d3608e87b", "size": 994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/autodiff/examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_stars_repo_name": "Speech-VINO/Speech-Analysis", "max_stars_repo_head_hexsha": "e95083c4709f3ba7bcc89006ff4623d73475dacd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T16:38:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T16:38:48.000Z", "max_issues_repo_path": "examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 29.2352941176, "max_line_length": 99, "alphanum_fraction": 0.6287726358, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6930779346815342}}
{"text": "#include \"forward_kinematics.h\"\n#include <iostream>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <bitset>\n#include <string>\n#include <utility>\n//perform the forward kinematics of the robot to figure out where you are\nwsState* fk (configState* c)\n{\n  double theta0 = tick_to_radians(c->theta[0]);\n  double theta1 = tick_to_radians(c->theta[1]);\n  double theta2 = tick_to_radians(c->theta[2]);\n  double theta3 = tick_to_radians(c->theta[3]);\n  double theta4 = tick_to_radians(c->theta[4]);\n  /*  Eigen::Matrix4d T_01 = DH(M_PI/2 , 0, 26.5, theta0);\n  Eigen::Matrix4d T_12 = DH(0, 150, 0 , M_PI/2+theta1);\n  Eigen::Matrix4d T_23 = DH(0, 150, 0, theta2);\n  Eigen::Matrix4d T_34 = DH(-M_PI/2, 0, 0, M_PI/2+theta3);\n  Eigen::Matrix4d T_45 = DH(0,0,116.525, theta4);\n\n  Eigen::Matrix4d T_05 = T_01*T_12*T_23*T_34*T_45;\n\n  wsState* outstate = new wsState;\n  outstate->x = T_05(0,3);\n  outstate->y = T_05(1,3);\n  outstate->z = T_05(2,3);\n  outstate->alpha = tick_to_radians(c->theta[0]+c->theta[1]+\n      c->theta[2]+c->theta[3]+c->theta[4]);\n  //TODO calculate angles based on rotation matrix\n  */\n  double c0 = cos(theta0);\n  double s0 = sin(theta0);\n  double c1 = cos(theta1);\n  double s1 = sin(theta1);\n  double c12 = cos(theta1+theta2);\n  double s12 = sin(theta1+theta2);\n  double c123 = cos(theta1+theta2+theta3);\n  double s123 = sin(theta1+theta2+theta3);\n\n  wsState* outstate = new wsState;\n  outstate->x = c0*(150*(c1+c12) + 116.525*s123);\n  outstate->y = s0*(150*(c1+c12) + 116.525*s123);\n  outstate->z = 150*(s12+s1) - 116.525*c123 + 26.5;\n  outstate->alpha = theta1+ theta2+ theta3;\n\n  return outstate;\n\n}//end forward_kinematics\n\nEigen::Matrix4d DH(double alpha,double a,double d,double theta)\n{\n  Eigen::Matrix4d T;\n  T << cos(theta),sin(theta)*cos(alpha),-sin(theta)*sin(alpha),a*cos(theta),\n    sin(theta), cos(theta)*cos(alpha), -cos(theta)*sin(alpha),a*sin(theta),\n    0,sin(alpha),cos(alpha),d,\n    0,0,0,1;\n  return T;\n}\n\n\n//calculate Euclidean ndistance between two states\ndouble distance(wsState* s1,wsState* s2)\n{\n  return (pow(s1->x - s2->x,2)+pow(s1->y-s2->y,2)+pow(s1->z-s2->z,2)+pow(s1->alpha-s2->alpha,2));\n}\n\nconfigState* clone_configstate(configState* c){\n\n  configState* clone = new configState;\n  clone->theta[0] = c->theta[0];\n  clone->theta[1] = c->theta[1];\n  clone->theta[2] = c->theta[2];\n  clone->theta[3] = c->theta[3];\n  clone->theta[4] = c->theta[4];\n  return clone;\n}\n\ndouble tick_to_radians(int i){\n  return (M_PI/100)*i;\n}\n\nwsState* create_wsstate(){\n   return (wsState*)malloc(sizeof(struct wsState));\n}\n\nconfigState* create_configstate(){\n  return (configState*)malloc(sizeof(struct configState));\n}\n\nvisData* create_visdata(){\n  return (visData*)malloc(sizeof(struct visData));\n}\n\nvoid deallocate_wsstate(wsState* w){\n  if(w != 0)\n    free(w);\n}\n\nvoid deallocate_configstate(configState* c){\n  if(c != 0)\n    free(c);\n}\n\nvoid deallocate_visdata(visData* v){\n  if(v != 0)\n    free(v);\n}\n\nvoid wsstate_tostring(wsState* w){\n    printf(\"Work Space State: x:%f, y:%f, z:%f\\n\",\n      w->x, w->y, w->z);\n}\n\nvoid configstate_tostring(configState* c){\n  printf(\"Theta1: %i, Theta2: %i, Theta3: %i, Theta4: %i, Theta5: %i\\n\"\n      , c->theta[0], c->theta[1],c->theta[2], c->theta[3], c->theta[4]);\n}\n", "meta": {"hexsha": "5df27efc23f3ecd124a83beb07e5e36d31d514f2", "size": 3260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armplanning_test/forward_kinematics.cpp", "max_stars_repo_name": "Boberito25/ButlerBot", "max_stars_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "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": "armplanning_test/forward_kinematics.cpp", "max_issues_repo_name": "Boberito25/ButlerBot", "max_issues_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-06-08T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T19:55:40.000Z", "max_forks_repo_path": "armplanning_test/forward_kinematics.cpp", "max_forks_repo_name": "Boberito25/ButlerBot", "max_forks_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "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.1666666667, "max_line_length": 97, "alphanum_fraction": 0.6567484663, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6930779346815342}}
{"text": "//Neural network in C++\n// Author: Sethu Iyer \n//Sigmoid is used because the sigmoid function assumes \n//minimal structure and reflects our general state of ignorance about the underlying model.\n\n//This code implements simple 3 layer feed forward neural network with no regularization.\n// we use fast sigmoid approximation to speed up the calculation.\n\n#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nclass Neural_Network\n{\n   private:\n    //define the architecture of the network\n    int inputLayerSize = 2;\n    int  outputLayerSize = 1;\n    int hiddenLayerSize = 3;\n\n    // activation function and the weights\n    arma::mat W1,W2;\n    arma::mat z2,a2;\n    arma::mat z3,a3;\n    arma::mat delta3,delta2;\n    arma::mat dJdW1, djdW2;\n\n  public:\n       Neural_Network()\n     {\n          //fills in random weights\n        W1.randu(2,3);\n        W2.randu(3,1);\n    }\n\n      //helper functions\n        static double sigmoid(double x)\n    {\n      return x / (1 + abs(x));\n    }\n    static double sigmoidPrime(double x)\n    {\n      double f = sigmoid(x);\n      return f * (1-f);\n    }\n\n\n    //forwarding function.\n    arma::mat forward(arma::mat X)\n    {\n        z2 = X * W1;\n        a2 = z2;\n        a2.transform(*sigmoid);\n        z3 = a2 * W2;\n        a3 = z3;\n        a3.transform(*sigmoid);\n        return a3;\n    }\n\n    //cost function\n    double costFunction(mat X,mat y)\n    {\n      mat yHat = forward(X);\n\n      double cost = 0;\n      for(int i = 0; i < outputLayerSize; i++)\n      {\n        cost =  cost + (yHat[i] - y[i])*(yHat[i] - y[i]);\n      }\n      cost = cost / 2;\n      return cost;\n\n    }\n\n    //derivative of cost function \n    //backpropogation of errors can be understood in this code\n    void computeGradients(mat X, mat y)\n    {\n\n      mat yHat = forward(X);\n      mat z = z3;\n      z.transform(*sigmoidPrime);\n      delta3 = (yHat - y.t()) % z;\n      djdW2 = a2.t() * delta3;\n\n      z = z2;\n      z.transform(*sigmoidPrime);\n      delta2 = delta3 * W2.t()*z;\n      dJdW1 = X.t() * delta2;\n\n    }\n\n    //alpha is our learning rate\n    void gradientDescent(mat X,mat y,double alpha,int numIter)\n    {\n      int i;\n      mat transdj1,transdj2;\n      for(i=0;i<numIter;i++)\n      {\n        computeGradients(X,y);\n        transdj1 = dJdW1;\n        transdj1.transform([=] (double x) { return x * alpha;});\n        W1 = W1 - transdj1;\n    transdj2 = djdW2;\n        transdj2.transform([=] (double x ) { return x *alpha;});\n        W2 = W2 - transdj2;\n      }\n    }\n};\n\nint main()\n{\n\n    mat X = {{0.3,1},{0.5,0.2},{1,0.4}};\n    mat y = {0.75,0.82,0.93};\n    Neural_Network nn;\n    cout<<\"Initial Cost: \"<<nn.costFunction(X,y)<<endl;\n    nn.gradientDescent(X,y,0.01,400);\n    cout<<\"After 400 Iterations: \"<<nn.costFunction(X,y)<<endl;\n    nn.gradientDescent(X,y,0.01,400);\n    cout<<\"After 800 Iterations: \"<<nn.costFunction(X,y)<<endl;\n    return 0;\n}", "meta": {"hexsha": "622e95218c8839a18cfce8f7ff4338b33b28d243", "size": 2899, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3-Layer Neural Network in C++/neuralnet.cpp", "max_stars_repo_name": "sethuiyer/mlhub", "max_stars_repo_head_hexsha": "6be271c0070a0c0bb90dd92aceb344e7415bb1db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2016-12-28T16:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-22T16:39:29.000Z", "max_issues_repo_path": "3-Layer Neural Network in C++/neuralnet.cpp", "max_issues_repo_name": "sethuiyer/mlhub", "max_issues_repo_head_hexsha": "6be271c0070a0c0bb90dd92aceb344e7415bb1db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-03-24T17:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:04:58.000Z", "max_forks_repo_path": "3-Layer Neural Network in C++/neuralnet.cpp", "max_forks_repo_name": "sethuiyer/mlhub", "max_forks_repo_head_hexsha": "6be271c0070a0c0bb90dd92aceb344e7415bb1db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-01-17T09:45:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T07:19:39.000Z", "avg_line_length": 23.192, "max_line_length": 91, "alphanum_fraction": 0.5708865126, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6930141649169633}}
{"text": "//\n// Created by \u9ad8\u7fd4 on 2017/12/15.\n//\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv) {\n    double ar = 1.0, br = 2.0, cr = 1.0;         // \u771f\u5b9e\u53c2\u6570\u503c\n    double ae = 2.0, be = -1.0, ce = 5.0;        // \u4f30\u8ba1\u53c2\u6570\u503c\n    int N = 100;                                 // \u6570\u636e\u70b9\n    double w_sigma = 1.0;                        // \u566a\u58f0Sigma\u503c\n    cv::RNG rng;                                 // OpenCV\u968f\u673a\u6570\u4ea7\u751f\u5668\n\n    vector<double> x_data, y_data;      // \u6570\u636e\n    for (int i = 0; i < N; i++) {\n        double x = i / 100.0;\n        x_data.push_back(x);\n        y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma));\n    }\n\n    // \u5f00\u59cbGauss-Newton\u8fed\u4ee3\n    int iterations = 100;    // \u8fed\u4ee3\u6b21\u6570\n    double cost = 0, lastCost = 0;  // \u672c\u6b21\u8fed\u4ee3\u7684cost\u548c\u4e0a\u4e00\u6b21\u8fed\u4ee3\u7684cost\n\n    for (int iter = 0; iter < iterations; iter++) {\n\n        Matrix3d H = Matrix3d::Zero();             // Hessian = J^T J in Gauss-Newton\n        Vector3d b = Vector3d::Zero();             // bias\n        cost = 0;\n\n        for (int i = 0; i < N; i++) {\n            double xi = x_data[i], yi = y_data[i];  // \u7b2ci\u4e2a\u6570\u636e\u70b9\n            // start your code here\n            double error = 0 ; // \u7b2ci\u4e2a\u6570\u636e\u70b9\u7684\u8ba1\u7b97\u8bef\u5dee\n            // \u586b\u5199\u8ba1\u7b97error\u7684\u8868\u8fbe\u5f0f\n            error = yi- exp(ae * xi * xi + be * xi + ce);\n            Vector3d J; // \u96c5\u53ef\u6bd4\u77e9\u9635\n            J[0] = -exp(ae * xi * xi + be * xi + ce)*xi*xi;  // de/da\n            J[1] = -exp(ae * xi * xi + be * xi + ce)*xi;  // de/db\n            J[2] = -exp(ae * xi * xi + be * xi + ce);  // de/dc\n\n            H += J * J.transpose(); // GN\u8fd1\u4f3c\u7684H\n            b += -error * J;\n            // end your code here\n\n            cost += error * error;\n        }\n\n        // \u6c42\u89e3\u7ebf\u6027\u65b9\u7a0b Hx=b\uff0c\u5efa\u8bae\u7528ldlt\n \t// start your code here\n        Vector3d dx;\n        dx = H.ldlt().solve(b);\n\t// end your code here\n\n        if (isnan(dx[0])) {\n            cout << \"result is nan!\" << endl;\n            break;\n        }\n\n        if (iter > 0 && cost > lastCost) {\n            // \u8bef\u5dee\u589e\u957f\u4e86\uff0c\u8bf4\u660e\u8fd1\u4f3c\u7684\u4e0d\u591f\u597d\n            cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n            break;\n        }\n\n        // \u66f4\u65b0abc\u4f30\u8ba1\u503c\n        ae += dx[0];\n        be += dx[1];\n        ce += dx[2];\n\n        lastCost = cost;\n\n        cout << \"total cost: \" << cost << endl;\n    }\n\n    cout << \"estimated abc = \" << ae << \", \" << be << \", \" << ce << endl;\n    return 0;\n}", "meta": {"hexsha": "9cdd996cd290050c53181c5c32653bf87b3385bb", "size": 2410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4/gaussnewton.cpp", "max_stars_repo_name": "Yvon-Shong/SLAM", "max_stars_repo_head_hexsha": "4f633e71e13e1b3482255bc5abc38446a56beebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:25:08.000Z", "max_issues_repo_path": "SLAM14Lectures-master/4/gaussnewton.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T11:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T18:40:41.000Z", "max_forks_repo_path": "SLAM14Lectures-master/4/gaussnewton.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T16:30:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T11:37:37.000Z", "avg_line_length": 29.0361445783, "max_line_length": 85, "alphanum_fraction": 0.4369294606, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6930141568162483}}
{"text": "#include <armadillo>\n#include <cstring>\n#include <iostream>\n\nusing namespace std;\nusing namespace arma;\n\n/*  ----------------- useful help functions --------------  */\n\nstruct MyVec\n{\n    double *data;\n    size_t n;\n};\n\nstruct MyMat\n{\n    double *data;\n    size_t num_rows, num_cols;\n};\n\nextern \"C\" void freeMyVec(MyVec &vec)\n{\n    delete[] vec.data;\n    memset((void *)&vec, 0, sizeof(vec));\n}\n\nextern \"C\" void freeMyMat(MyMat &mat)\n{\n    delete[] mat.data;\n    memset((void *)&mat, 0, sizeof(mat));\n}\n\nstruct HuberCovResult\n{\n    MyVec means;\n    MyMat cov;\n};\n\nextern \"C\" void freeHuberCovResult(const HuberCovResult &result)\n{\n    delete[] result.means.data;\n    delete[] result.cov.data;\n    memset((void *)&result, 0, sizeof(result));\n}\n\n              /* --------------------------------- */    \n/*------------ Tuning-Free Huber Regression Funtions ---------------*/\n              /* --------------------------------- */ \n\nint sgn(const double x)\n{\n    return (x > 0) - (x < 0);\n}\n\ndouble f1(const double x, const arma::vec &resSq, const int n, const double rhs)\n{\n    return arma::mean(arma::min(resSq / x, arma::ones(n))) - rhs;\n}\n\ndouble rootf1(const arma::vec &resSq, const int n, const double rhs, double low, double up, const double tol = 0.001, const int maxIte = 500)\n{\n    int ite = 1;\n    while (ite <= maxIte && up - low > tol)\n    {\n        double mid = 0.5 * (up + low);\n        double val = f1(mid, resSq, n, rhs);\n        if (val < 0)\n        {\n            up = mid;\n        }\n        else\n        {\n            low = mid;\n        }\n        ite++;\n    }\n    return 0.5 * (low + up);\n}\n\ndouble f2(const double x, const arma::vec &resSq, const int N, const double rhs)\n{\n    return arma::mean(arma::min(resSq / x, arma::ones(N))) - rhs;\n}\n\ndouble rootf2(const arma::vec &resSq, const int n, const int d, const int N, const double rhs, double low, double up, const double tol = 0.001,\n              const int maxIte = 500)\n{\n    int ite = 0;\n    while (ite <= maxIte && up - low > tol)\n    {\n        double mid = 0.5 * (up + low);\n        double val = f2(mid, resSq, N, rhs);\n        if (val < 0)\n        {\n            up = mid;\n        }\n        else\n        {\n            low = mid;\n        }\n        ite++;\n    }\n    return 0.5 * (low + up);\n}\n\ndouble g1(const double x, const arma::vec &resSq, const int n, const double rhs)\n{\n    return arma::mean(arma::min(resSq / x, arma::ones(n))) - rhs;\n}\n\ndouble rootg1(const arma::vec &resSq, const int n, const double rhs, double low, double up, const double tol = 0.001, const int maxIte = 500)\n{\n    int ite = 0;\n    while (ite <= maxIte && up - low > tol)\n    {\n        double mid = 0.5 * (up + low);\n        double val = g1(mid, resSq, n, rhs);\n        if (val < 0)\n        {\n            up = mid;\n        }\n        else\n        {\n            low = mid;\n        }\n        ite++;\n    }\n    return 0.5 * (low + up);\n}\n\ndouble huberDer(const arma::vec &res, const double tau, const int n)\n{\n    double rst = 0.0;\n    for (int i = 0; i < n; i++)\n    {\n        double cur = res(i);\n        rst -= std::abs(cur) <= tau ? cur : tau * sgn(cur);\n    }\n    return rst / n;\n}\n\nextern \"C\" double huberMean(MyVec _X, const double tol = 0.001, const int iteMax = 500)\n{\n    arma::vec X(_X.data, _X.n);\n    int n = X.n_rows;\n    double rhs = std::log(n) / n;\n    double mx = arma::mean(X);\n    X -= mx;\n    double tau = arma::stddev(X) * std::sqrt((long double)n / std::log(n));\n    double derOld = huberDer(X, tau, n);\n    double mu = -derOld, muDiff = -derOld;\n    arma::vec res = X - mu;\n    arma::vec resSq = arma::square(res);\n    tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n    double derNew = huberDer(res, tau, n);\n    double derDiff = derNew - derOld;\n    int ite = 1;\n    while (std::abs(derNew) > tol && ite <= iteMax)\n    {\n        double alpha = 1.0;\n        double cross = muDiff * derDiff;\n        if (cross > 0)\n        {\n            double a1 = cross / derDiff * derDiff;\n            double a2 = muDiff * muDiff / cross;\n            alpha = std::min(std::min(a1, a2), 100.0);\n        }\n        derOld = derNew;\n        muDiff = -alpha * derNew;\n        mu += muDiff;\n        res = X - mu;\n        resSq = arma::square(res);\n        tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n        derNew = huberDer(res, tau, n);\n        derDiff = derNew - derOld;\n        ite++;\n    }\n    return mu + mx;\n}\n\ndouble _huberMean(arma::vec X, const double tol = 0.001, const int iteMax = 500)\n{\n    int n = X.n_rows;\n    double rhs = std::log(n) / n;\n    double mx = arma::mean(X);\n    X -= mx;\n    double tau = arma::stddev(X) * std::sqrt((long double)n / std::log(n));\n    double derOld = huberDer(X, tau, n);\n    double mu = -derOld, muDiff = -derOld;\n    arma::vec res = X - mu;\n    arma::vec resSq = arma::square(res);\n    tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n    double derNew = huberDer(res, tau, n);\n    double derDiff = derNew - derOld;\n    int ite = 1;\n    while (std::abs(derNew) > tol && ite <= iteMax)\n    {\n        double alpha = 1.0;\n        double cross = muDiff * derDiff;\n        if (cross > 0)\n        {\n            double a1 = cross / derDiff * derDiff;\n            double a2 = muDiff * muDiff / cross;\n            alpha = std::min(std::min(a1, a2), 100.0);\n        }\n        derOld = derNew;\n        muDiff = -alpha * derNew;\n        mu += muDiff;\n        res = X - mu;\n        resSq = arma::square(res);\n        tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n        derNew = huberDer(res, tau, n);\n        derDiff = derNew - derOld;\n        ite++;\n    }\n    return mu + mx;\n}\n\ndouble hMeanCov(const arma::vec &Z, const int n, const int d, const int N, double rhs, const double epsilon = 0.0001, const int iteMax = 500)\n{\n    double muOld = 0;\n    double muNew = arma::mean(Z);\n    double tau = arma::stddev(Z) * std::sqrt((long double)n / (2 * std::log(d) + std::log(n)));\n    int iteNum = 0;\n    arma::vec res(n), resSq(n), w(n);\n    while ((std::abs(muNew - muOld) > epsilon) && iteNum < iteMax)\n    {\n        muOld = muNew;\n        res = Z - muOld;\n        resSq = arma::square(res);\n        tau = std::sqrt((long double)rootf2(resSq, n, d, N, rhs, arma::min(resSq), arma::accu(resSq)));\n        w = arma::min(tau / arma::abs(res), arma::ones(N));\n        muNew = arma::as_scalar(Z.t() * w) / arma::accu(w);\n        iteNum++;\n    }\n    return muNew;\n}\n\nextern \"C\" HuberCovResult huberCov(const MyMat &_X)\n{\n    const arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n    const int n = X.n_rows;\n    const int p = X.n_cols;\n\n    double rhs2 = (2 * std::log(p) + std::log(n)) / n;\n    arma::vec mu(p);\n    arma::mat sigmaHat(p, p);\n    for (int j = 0; j < p; j++)\n    {\n        mu(j) = _huberMean(X.col(j), n);\n        double theta = _huberMean(arma::square(X.col(j)), n);\n        double temp = mu(j) * mu(j);\n        if (theta > temp)\n        {\n            theta -= temp;\n        }\n        sigmaHat(j, j) = theta;\n    }\n    int N = n * (n - 1) >> 1;\n    arma::mat Y(N, p);\n    for (int i = 0, k = 0; i < n - 1; i++)\n    {\n        for (int j = i + 1; j < n; j++)\n        {\n            Y.row(k++) = X.row(i) - X.row(j);\n        }\n    }\n    for (int i = 0; i < p - 1; i++)\n    {\n        for (int j = i + 1; j < p; j++)\n        {\n            sigmaHat(i, j) = sigmaHat(j, i) = hMeanCov(0.5 * Y.col(i) % Y.col(j), n, p, N, rhs2);\n        }\n    }\n\n    HuberCovResult result;\n\n    result.means.data = new double[mu.size()];\n    result.means.n = mu.size();\n    memcpy(result.means.data, mu.memptr(), mu.size() * sizeof(double));\n\n    result.cov.data = new double[sigmaHat.n_rows * sigmaHat.n_cols];\n    result.cov.num_rows = sigmaHat.n_rows;\n    result.cov.num_cols = sigmaHat.n_cols;\n    memcpy(result.cov.data, sigmaHat.memptr(), sigmaHat.n_rows * sigmaHat.n_cols * sizeof(double));\n\n    return result;\n}\n\ndouble mad(const arma::vec &x)\n{\n    return 1.482602 * arma::median(arma::abs(x - arma::median(x)));\n}\n\narma::mat standardize(arma::mat X, const arma::rowvec &mx, const arma::vec &sx, const int p)\n{\n    for (int i = 0; i < p; i++)\n    {\n        X.col(i) = (X.col(i) - mx(i)) / sx(i);\n    }\n    return X;\n}\n\nvoid updateHuber(const arma::mat &Z, const arma::vec &res, arma::vec &der, arma::vec &grad, const int n, const double tau, const double n1)\n{\n    for (int i = 0; i < n; i++)\n    {\n        double cur = res(i);\n        if (std::abs(cur) <= tau)\n        {\n            der(i) = -cur;\n        }\n        else\n        {\n            der(i) = -tau * sgn(cur);\n        }\n    }\n    grad = n1 * Z.t() * der;\n}\n\nextern \"C\" MyVec adaHuberReg(MyMat _X, MyVec _Y, const double tol = 0.0001, const int iteMax = 5000)\n{\n    arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n    arma::vec Y(_Y.data, _Y.n);\n    int n = X.n_rows;\n    int p = X.n_cols;\n    const double n1 = 1.0 / n;\n    double rhs = n1 * (p + std::log(n * p));\n    arma::rowvec mx = arma::mean(X, 0);\n    arma::vec sx = arma::stddev(X, 0, 0).t();\n    double my = arma::mean(Y);\n    arma::mat Z = arma::join_rows(arma::ones(n), standardize(X, mx, sx, p));\n    Y -= my;\n    double tau = 1.345 * mad(Y);\n    arma::vec der(n);\n    arma::vec gradOld(p + 1), gradNew(p + 1);\n    updateHuber(Z, Y, der, gradOld, n, tau, n1);\n    arma::vec beta = -gradOld, betaDiff = -gradOld;\n    arma::vec res = Y - Z * beta;\n    arma::vec resSq = arma::square(res);\n    tau = std::sqrt((long double)rootg1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n    updateHuber(Z, res, der, gradNew, n, tau, n1);\n    arma::vec gradDiff = gradNew - gradOld;\n    int ite = 1;\n    while (arma::norm(gradNew, \"inf\") > tol && ite <= iteMax)\n    {\n        double alpha = 1.0;\n        double cross = arma::as_scalar(betaDiff.t() * gradDiff);\n        if (cross > 0)\n        {\n            double a1 = cross / arma::as_scalar(gradDiff.t() * gradDiff);\n            double a2 = arma::as_scalar(betaDiff.t() * betaDiff) / cross;\n            alpha = std::min(std::min(a1, a2), 100.0);\n        }\n        gradOld = gradNew;\n        betaDiff = -alpha * gradNew;\n        beta += betaDiff;\n        res -= Z * betaDiff;\n        resSq = arma::square(res);\n        tau = std::sqrt((long double)rootg1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n        updateHuber(Z, res, der, gradNew, n, tau, n1);\n        gradDiff = gradNew - gradOld;\n        ite++;\n    }\n    beta.rows(1, p) /= sx;\n    beta(0) = _huberMean(Y + my - X * beta.rows(1, p));\n\n    MyVec result;\n    result.data = new double[n];\n    result.n = n;\n    memcpy(result.data, beta.memptr(), n * sizeof(double));\n    return result;\n}\n\nextern \"C\" MyVec huberReg(MyMat _X, MyVec _Y, const double tol = 0.0001, const double constTau = 1.345, const int iteMax = 5000)\n{\n    arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n    arma::vec Y(_Y.data, _Y.n);\n    int n = X.n_rows;\n    int p = X.n_cols;\n    const double n1 = 1.0 / n;\n    arma::rowvec mx = arma::mean(X, 0);\n    arma::vec sx = arma::stddev(X, 0, 0).t();\n    double my = arma::mean(Y);\n    arma::mat Z = arma::join_rows(arma::ones(n), standardize(X, mx, sx, p));\n    Y -= my;\n    double tau = constTau * mad(Y);\n    arma::vec der(n);\n    arma::vec gradOld(p + 1), gradNew(p + 1);\n    updateHuber(Z, Y, der, gradOld, n, tau, n1);\n    arma::vec beta = -gradOld, betaDiff = -gradOld;\n    arma::vec res = Y - Z * beta;\n    tau = constTau * mad(res);\n    updateHuber(Z, res, der, gradNew, n, tau, n1);\n    arma::vec gradDiff = gradNew - gradOld;\n    int ite = 1;\n    while (arma::norm(gradNew, \"inf\") > tol && ite <= iteMax)\n    {\n        double alpha = 1.0;\n        double cross = arma::as_scalar(betaDiff.t() * gradDiff);\n        if (cross > 0)\n        {\n            double a1 = cross / arma::as_scalar(gradDiff.t() * gradDiff);\n            double a2 = arma::as_scalar(betaDiff.t() * betaDiff) / cross;\n            alpha = std::min(std::min(a1, a2), 100.0);\n        }\n        gradOld = gradNew;\n        betaDiff = -alpha * gradNew;\n        beta += betaDiff;\n        res -= Z * betaDiff;\n        tau = constTau * mad(res);\n        updateHuber(Z, res, der, gradNew, n, tau, n1);\n        gradDiff = gradNew - gradOld;\n        ite++;\n    }\n    beta.rows(1, p) /= sx;\n    beta(0) = _huberMean(Y + my - X * beta.rows(1, p), n);\n\n    MyVec result;\n    result.data = new double[n];\n    result.n = n;\n    memcpy(result.data, beta.memptr(), n * sizeof(double));\n    return result;\n}\n\n              /* - */    \n/*------------ LASSO ------------*/\n              /* - */ \n\narma::vec softThresh(const arma::vec& x, const arma::vec& lambda)\n{\n  return arma::sign(x) % arma::max(arma::abs(x) - lambda, arma::zeros(x.size()));\n}\n\narma::vec cmptLambda(const arma::vec& beta, const double lambda)\n{\n  arma::vec rst = lambda * arma::ones(beta.size());\n  rst(0) = 0;\n  return rst;\n}\n\ndouble loss(const arma::vec& Y, const arma::vec& Ynew, const std::string lossType, const double tau)\n{\n  double rst = 0;\n  if (lossType == \"l2\") {\n    rst = arma::mean(arma::square(Y - Ynew)) / 2;\n  } else if (lossType == \"Huber\") {\n    arma::vec res = Y - Ynew;\n    for (int i = 0; i < Y.size(); i++) {\n      if (std::abs(res(i)) <= tau) {\n        rst += res(i) * res(i) / 2;\n      } else {\n        rst += tau * std::abs(res(i)) - tau * tau / 2;\n      }\n    }\n    rst /= Y.size();\n  }\n  return rst;\n}\n\narma::vec gradLoss(const arma::mat& X, const arma::vec& Y, const arma::vec& beta,\n                   const std::string lossType, const double tau)\n{\n  arma::vec res = Y - X * beta;\n  arma::vec rst = arma::zeros(beta.size());\n  if (lossType == \"l2\") {\n    rst = -1 * (res.t() * X).t();\n  } else if (lossType == \"Huber\") {\n    for (int i = 0; i < Y.size(); i++) {\n      if (std::abs(res(i)) <= tau) {\n        rst -= res(i) * X.row(i).t();\n      } else {\n        rst -= tau * sgn(res(i)) * X.row(i).t();\n      }\n    }\n  }\n  return rst / Y.size();\n}\n\narma::vec updateBeta(const arma::mat& X, const arma::vec& Y, arma::vec beta, const double phi,\n                     const arma::vec& Lambda, const std::string lossType, const double tau)\n{\n  arma::vec first = beta - gradLoss(X, Y, beta, lossType, tau) / phi;\n  arma::vec second = Lambda / phi;\n  return softThresh(first, second);\n}\n\ndouble cmptPsi(const arma::mat& X, const arma::vec& Y, const arma::vec& betaNew,\n               const arma::vec& beta, const double phi, const std::string lossType,\n               const double tau) \n{\n  arma::vec diff = betaNew - beta;\n  double rst = loss(Y, X * beta, lossType, tau)\n    + arma::as_scalar((gradLoss(X, Y, beta, lossType, tau)).t() * diff)\n    + phi * arma::as_scalar(diff.t() * diff) / 2;\n    return rst;\n}\n\nRcpp::List LAMM(const arma::mat& X, const arma::vec& Y, const arma::vec& Lambda, arma::vec beta,\n                const double phi, const std::string lossType, const double tau, \n                const double gamma) \n{\n  double phiNew = phi;\n  arma::vec betaNew = arma::vec();\n  double FVal, PsiVal;\n  while (true) {\n    betaNew = updateBeta(X, Y, beta, phiNew, Lambda, lossType, tau);\n    FVal = loss(Y, X * betaNew, lossType, tau);\n    PsiVal = cmptPsi(X, Y, betaNew, beta, phiNew, lossType, tau);\n    if (FVal <= PsiVal) {\n      break;\n    }\n    phiNew *= gamma;\n  }\n  return Rcpp::List::create(Rcpp::Named(\"beta\") = betaNew, Rcpp::Named(\"phi\") = phiNew);\n}\n\narma::vec lasso(const arma::mat& X, const arma::vec& Y, const double lambda,\n                const double phi0 = 0.001, const double gamma = 1.5, \n                const double epsilon_c = 0.001, const int iteMax = 500) \n{\n  int d = X.n_cols - 1;\n  arma::vec beta = arma::zeros(d + 1);\n  arma::vec betaNew = arma::zeros(d + 1);\n  arma::vec Lambda = cmptLambda(beta, lambda);\n  double phi = phi0;\n  int ite = 0;\n  Rcpp::List listLAMM;\n  while (ite < iteMax) {\n    ite++;\n    listLAMM = LAMM(X, Y, Lambda, beta, phi, \"l2\", 1, gamma);\n    betaNew = Rcpp::as<arma::vec>(listLAMM[\"beta\"]);\n    phi = listLAMM[\"phi\"];\n    phi = std::max(phi0, phi / gamma);\n    if (arma::norm(betaNew - beta, \"inf\") <= epsilon_c) {\n      break;\n    }\n    beta = betaNew;\n  }\n  return betaNew;\n}\n\nRcpp::List huberLasso(const arma::mat& X, const arma::vec& Y, const double lambda,\n                      double tau = -1, const double constTau = 1.345, const double phi0 = 0.001, \n                      const double gamma = 1.5, const double epsilon_c = 0.001, \n                      const int iteMax = 500) \n{\n  int n = X.n_rows;\n  int d = X.n_cols - 1;\n  arma::vec beta = arma::zeros(d + 1);\n  arma::vec betaNew = arma::zeros(d + 1);\n  arma::vec Lambda = cmptLambda(beta, lambda);\n  double mad;\n  if (tau <= 0) {\n    arma::vec betaLasso = lasso(X, Y, lambda, phi0, gamma, epsilon_c, iteMax);\n    arma::vec res = Y - X * betaLasso;\n    mad = arma::median(arma::abs(res - arma::median(res))) / 0.6744898;\n    tau = constTau * mad;\n  }\n  double phi = phi0;\n  int ite = 0;\n  Rcpp::List listLAMM;\n  arma::vec res(n);\n  while (ite < iteMax) {\n    ite++;\n    listLAMM = LAMM(X, Y, Lambda, beta, phi, \"Huber\", tau, gamma);\n    betaNew = Rcpp::as<arma::vec>(listLAMM[\"beta\"]);\n    phi = listLAMM[\"phi\"];\n    phi = std::max(phi0, phi / gamma);\n    if (arma::norm(betaNew - beta, \"inf\") <= epsilon_c) {\n      break;\n    }\n    beta = betaNew;\n    res = Y - X * beta;\n    mad = arma::median(arma::abs(res - arma::median(res))) / 0.6744898;\n    tau = constTau * mad;\n  }\n  return Rcpp::List::create(Rcpp::Named(\"beta\") = betaNew, Rcpp::Named(\"tau\") = tau,\n                            Rcpp::Named(\"iteration\") = ite);\n}\n\narma::uvec getIndex(const int n, const int low, const int up) \n{\n  arma::vec seq = arma::regspace(0, n - 1);\n  return arma::find(seq >= low && seq <= up);\n}\n\narma::uvec getIndexComp(const int n, const int low, const int up)\n{\n  arma::vec seq = arma::regspace(0, n - 1);\n  return arma::find(seq < low || seq > up);\n}\n\ndouble pairPred(const arma::mat& X, const arma::vec& Y, const arma::vec& beta)\n{\n  int n = X.n_rows;\n  int d = X.n_cols - 1;\n  int m = n * (n - 1) >> 1;\n  arma::mat pairX(m, d + 1);\n  arma::vec pairY(m);\n  int k = 0;\n  for (int i = 0; i < n; i++) {\n    for (int j = i + 1; j < n; j++) {\n      pairX.row(k) = X.row(i) - X.row(j);\n      pairY(k++) = Y(i) - Y(j);\n    }\n  }\n  arma::vec predY = pairX * beta;\n  return arma::accu(arma::square(pairY - predY));\n}\n\nRcpp::List cvHuberLasso(const arma::mat& X, const arma::vec& Y,\n                        Rcpp::Nullable<Rcpp::NumericVector> lSeq = R_NilValue, int nlambda = 30,\n                        const double constTau = 2.5, const double phi0 = 0.001, \n                        const double gamma = 1.5, const double epsilon_c = 0.001, \n                        const int iteMax = 500, int nfolds = 3) \n{\n  int n = X.n_rows;\n  int d = X.n_cols;\n  arma::mat Z(n, d + 1);\n  Z.cols(1, d) = X;\n  Z.col(0) = arma::ones(n);\n  arma::vec lambdaSeq = arma::vec();\n  if (lSeq.isNotNull()) {\n    lambdaSeq = Rcpp::as<arma::vec>(lSeq);\n    nlambda = lambdaSeq.size();\n  } else {\n    double lambdaMax = arma::max(arma::abs(Y.t() * Z)) / n;\n    double lambdaMin = 0.01 * lambdaMax;\n    lambdaSeq = arma::exp(arma::linspace(std::log((long double)lambdaMin),\n                                   std::log((long double)lambdaMax), nlambda));\n  }\n  if (nfolds > 10 || nfolds > n) {\n    nfolds = n < 10 ? n : 10;\n  }\n  int size = n / nfolds;\n  arma::vec mse = arma::zeros(nlambda);\n  int low, up;\n  arma::uvec idx, idxComp;\n  Rcpp::List hLassoList;\n  arma::vec thetaHat(d + 1);\n  for (int i = 0; i < nlambda; i++) {\n    for (int j = 0; j < nfolds; j++) {\n      low = j * size;\n      up = (j == (nfolds - 1)) ? (n - 1) : ((j + 1) * size - 1);\n      idx = getIndex(n, low, up);\n      idxComp = getIndexComp(n, low, up);\n      hLassoList = huberLasso(Z.rows(idxComp), Y.rows(idxComp), lambdaSeq(i), -1, constTau, phi0, \n                              gamma, epsilon_c, iteMax);\n      thetaHat = Rcpp::as<arma::vec>(hLassoList[\"beta\"]);\n      mse(i) += pairPred(Z.rows(idx), Y.rows(idx), thetaHat);\n    }\n  }\n  arma::uword cvIdx = mse.index_min();\n  hLassoList = huberLasso(Z, Y, lambdaSeq(cvIdx), -1, constTau, phi0, gamma, epsilon_c, iteMax);\n  arma::vec theta = Rcpp::as<arma::vec>(hLassoList[\"beta\"]);\n  Rcpp::List listMean = huberMean(Y - Z.cols(1, d) * theta.rows(1, d));\n  theta(0) = listMean[\"mu\"];\n  return Rcpp::List::create(Rcpp::Named(\"theta\") = theta, Rcpp::Named(\"lambdaSeq\") = lambdaSeq,\n                            Rcpp::Named(\"lambdaMin\") = lambdaSeq(cvIdx), \n                            Rcpp::Named(\"tauCoef\") = hLassoList[\"tau\"], \n                            Rcpp::Named(\"tauItcp\") = listMean[\"tau\"], \n                            Rcpp::Named(\"iteCoef\") = hLassoList[\"iteration\"],\n                            Rcpp::Named(\"iteItcp\") = listMean[\"iteration\"]);\n}\n\n              /* ------------------------------------ */    \n/*------------ Alternating Gradient Descent Functions ------------*/\n              /* ------------------------------------ */ \n\ndouble LnVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n    return (arma::accu(arma::sqrt(tau * tau + arma::square(Y - mu)) - tau) / (z * std::sqrt(n)) + z * tau / std::sqrt(n)) / n;\n}\n\ndouble gradientMuVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n    return -(1 / std::sqrt(n)) * arma::accu((Y - mu) / (z * arma::sqrt(tau * tau + arma::square(Y - mu)))) / n;\n}\n\ndouble gradientTauVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n    return (1 / std::sqrt(n)) * arma::accu(tau / (z * arma::sqrt(tau * tau + arma::square(Y - mu)))) / n - (std::sqrt(n) / z - z / std::sqrt(n)) / n;\n}\n\nextern \"C\" double agd(MyVec _Y, double epsilon = 1e-5, int iteMax = 5000)\n{\n    arma::vec Y(_Y.data, _Y.n);\n    int n = Y.n_elem;\n    double eta1 = 1.0;\n    double eta2 = std::sqrt(n);\n    double muOld = std::numeric_limits<double>::infinity();\n    double muNew = arma::mean(Y);\n    double tauOld = std::numeric_limits<double>::infinity();\n    double delta = 0.05;\n    double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n    double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n    int iteNum = 0;\n    double LMuOld = std::numeric_limits<double>::infinity();\n    double LMuNew = LnVal(Y, muNew, tauNew, n, z);\n\n    while (((LMuOld - LMuNew > 1e-10) && std::abs(muOld - muNew) > epsilon) && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n    {\n        muOld = muNew;\n        tauOld = tauNew;\n        LMuOld = LMuNew;\n\n        double gradientLnTauVal = gradientTauVal(Y, muOld, tauOld, n, z);\n        tauNew = tauOld - eta2 * gradientLnTauVal;\n\n        double gradientLnMuVal = gradientMuVal(Y, muOld, tauNew, n, z);\n        muNew = muOld - eta1 * gradientLnMuVal;\n        LMuNew = LnVal(Y, muNew, tauNew, n, z);\n        iteNum += 1;\n    }\n    return muNew;\n}\n\nextern \"C\" double agdBB(MyVec _Y, double epsilon = 1e-5, int iteMax = 5000)\n{\n    arma::vec Y(_Y.data, _Y.n);\n    int n = Y.n_elem;\n    double eta1 = 1.0;\n    double eta2 = std::sqrt(n);\n    double muOld = std::numeric_limits<double>::infinity();\n    double muNew = arma::mean(Y);\n    double tauOld = std::numeric_limits<double>::infinity();\n    double delta = 0.05;\n    double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n    double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n    int iteNum = 0;\n\n    double stepSizeTau = eta2;\n    double stepSizeMu = eta1;\n\n    double LMuOld = std::numeric_limits<double>::infinity();\n    double LMuNew = LnVal(Y, muNew, tauNew, n, z);\n\n    double lastTauTilde;\n    double lastGradTau;\n    double lastMuTilde;\n    double lastGradMu;\n\n    while (((LMuOld - LMuNew) > epsilon * epsilon && std::abs(muOld - muNew) > epsilon) && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n    {\n        LMuOld = LMuNew;\n        muOld = muNew;\n        tauOld = tauNew;\n\n        double gradTau = gradientTauVal(Y, muOld, tauOld, n, z);\n        if (iteNum > 0)\n        {\n            double sTau = tauOld - lastTauTilde;\n            double yTau = gradTau - lastGradTau;\n            stepSizeTau = std::max(eta2, std::min(std::min((sTau * yTau) / (yTau * yTau), (sTau * sTau) / std::max(0.000001, sTau * yTau)), 1e3));\n        }\n        lastGradTau = gradTau;\n        lastTauTilde = tauOld;\n\n        tauNew = std::max(1.35, tauOld - stepSizeTau * (gradientTauVal(Y, muOld, tauOld, n, z)));\n\n        double gradMu = gradientMuVal(Y, muOld, tauNew, n, z);\n        if (iteNum > 0)\n        {\n            double sMu = muOld - lastMuTilde;\n            double yMu = gradMu - lastGradMu;\n            stepSizeMu = std::max(eta1, std::min(std::min((sMu * yMu) / (yMu * yMu), (sMu * sMu) / std::max(0.000001, sMu * yMu)), 1e3));\n        }\n        lastGradMu = gradMu;\n        lastMuTilde = muOld;\n\n        muNew = muOld - stepSizeMu * (gradientMuVal(Y, muOld, tauNew, n, z));\n        LMuNew = LnVal(Y, muNew, tauNew, n, z);\n        iteNum += 1;\n    }\n    return muNew;\n}\n\n\nextern \"C\" double agdBacktracking(MyVec _Y, double s1 = 1.0, double gamma1 = 0.5, double beta1 = 0.8, double s2 = 1.0, \n                                  double gamma2 = 0.5, double beta2 = 0.8, double epsilon = 1e-5, int iteMax = 5000)\n{    \n    arma::vec Y(_Y.data, _Y.n);\n    int n = Y.n_elem;\n    double muOld = std::numeric_limits<double>::infinity();\n    double muNew = arma::mean(Y);\n    double tauOld = std::numeric_limits<double>::infinity();\n    double delta = 0.05;\n    double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n    double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n    int iteNum = 0;\n\n    while (std::abs(muOld - muNew) > epsilon && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n    {\n        muOld = muNew;\n        tauOld = tauNew;\n        double LTauOld = LnVal(Y, muOld, tauOld, n, z);\n        double gradientLnTauVal = gradientTauVal(Y, muOld, tauOld, n, z);\n\n        /*backtracking for eta2*/\n        double eta2 = s2;\n        tauNew = tauOld - eta2*gradientLnTauVal;\n        double LTauNew = LnVal(Y, muOld, tauNew, n ,z);\n        \n        while (LTauNew > LTauOld + gamma2*eta2*gradientLnTauVal)\n        {\n            eta2 = beta2*eta2;\n            tauNew = tauOld - eta2*gradientLnTauVal;\n            LTauNew = LnVal(Y, muOld, tauNew, n ,z);\n            gradientLnTauVal = gradientTauVal(Y, muOld, tauNew, n, z);\n        }\n        \n        double LMuOld = LTauNew;\n        double gradientLnMuVal = gradientMuVal(Y, muOld, tauNew, n, z);\n        \n        /*backtracking for eta1*/\n        double eta1 = s1;\n        muNew = muOld - eta1*gradientLnMuVal;\n        double LMuNew = LnVal(Y, muNew, tauNew, n ,z);\n        \n        while (LMuNew > LMuOld + gamma1*eta1*gradientLnMuVal)\n        {\n            eta1 = beta1*eta1;\n            muNew = muOld - eta1*gradientLnMuVal;\n            LMuNew = LnVal(Y, muNew, tauNew, n ,z);\n            gradientLnMuVal = gradientMuVal(Y, muNew, tauNew, n, z);\n        }\n        iteNum += 1;\n    }\n    return muNew;\n}\n", "meta": {"hexsha": "e70822e3864013050b9a44a19eb34e43a6ee59bc", "size": 26934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/pyAutoAdaptiveRobustRegression.cpp", "max_stars_repo_name": "YichiZhang-Oxford/auto-adaptive-robust-regression", "max_stars_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T14:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T14:15:32.000Z", "max_issues_repo_path": "cpp/pyAutoAdaptiveRobustRegression.cpp", "max_issues_repo_name": "YichiZhang-Oxford/pyAutoAdaptiveRobustRegression", "max_issues_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_issues_repo_licenses": ["MIT"], "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/pyAutoAdaptiveRobustRegression.cpp", "max_forks_repo_name": "YichiZhang-Oxford/pyAutoAdaptiveRobustRegression", "max_forks_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_forks_repo_licenses": ["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.3337334934, "max_line_length": 149, "alphanum_fraction": 0.5406920621, "num_tokens": 8693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6928802874152487}}
{"text": "/**\n * @file    pose_estimation_3d3d.cpp\n * @version v1.0.0\n * @date    Nov,6 2017\n * @author  jacob.lin\n */\n\n#include <iostream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector<cv::KeyPoint>&, std::vector<cv::KeyPoint>&, std::vector<cv::DMatch>&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\n/*  */\nvoid pose_estimation_3d3d(const std::vector<cv::Point3f>&, const std::vector<cv::Point3f>&, cv::Mat&, cv::Mat&);\n\n/*  */\nvoid bundleAdjustment(const std::vector<cv::Point3f>&, const std::vector<cv::Point3f>&, cv::Mat&, cv::Mat&);\n\n/* g2o edge */\nclass EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3Expmap>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    EdgeProjectXYZRGBDPoseOnly(const Eigen::Vector3d& point) : _point(point) {}\n    \n    virtual void computeError()\n    {\n        const g2o::VertexSE3Expmap* pose = static_cast<const g2o::VertexSE3Expmap*>(_vertices[0]);\n        // measurement is p, point is p'\n        _error = _measurement - pose->estimate().map(_point);\n    }\n    \n    virtual void linearizeOplus()\n    {\n        g2o::VertexSE3Expmap* pose = static_cast<g2o::VertexSE3Expmap *>(_vertices[0]);\n        g2o::SE3Quat T(pose->estimate());\n        Eigen::Vector3d xyz_trans = T.map(_point);\n        \n        double x = xyz_trans[0];\n        double y = xyz_trans[1];\n        double z = xyz_trans[2];\n        \n        _jacobianOplusXi(0, 0) = 0;\n        _jacobianOplusXi(0, 1) = -z;\n        _jacobianOplusXi(0, 2) = y;\n        _jacobianOplusXi(0, 3) = -1;\n        _jacobianOplusXi(0, 4) = 0;\n        _jacobianOplusXi(0, 5) = 0;\n        \n        _jacobianOplusXi(1, 0) = z;\n        _jacobianOplusXi(1, 1) = 0;\n        _jacobianOplusXi(1, 2) = -x;\n        _jacobianOplusXi(1, 3) = 0;\n        _jacobianOplusXi(1, 4) = -1;\n        _jacobianOplusXi(1, 5) = 0;\n        \n        _jacobianOplusXi(2, 0) = -y;\n        _jacobianOplusXi(2, 1) = x;\n        _jacobianOplusXi(2, 2) = 0;\n        _jacobianOplusXi(2, 3) = 0;\n        _jacobianOplusXi(2, 4) = 0;\n        _jacobianOplusXi(2, 5) = -1;\n    }\n    \n    bool read(std::istream& in) {}\n    bool write(std::ostream & out) const {}\n    \nprotected:\n    Eigen::Vector3d _point;\n};\n\nint main(int argc, char** argv)\n{\n    if (argc != 5) {\n        cout << \"usage: pose_estimation_3d3d img1 img2 depth1 depth2.\" << endl;\n        return 1;\n    }\n    \n    //-- 1st, read photo\n    cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n    if (img_1.empty() || img_2.empty()) {\n        cerr << \"img1 or img2 is empty.\" << endl;\n        return 1;\n    }\n    \n    //-- 2nd, find the two photo feature matches points\n    std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n    std::vector<cv::DMatch> matches;\n    find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n    cout << \"feature matches points total is \" << matches.size() << endl;\n    \n    //-- 3rd, create 3 dimensions point correspondences\n    cv::Mat depth1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);      // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    cv::Mat depth2 = cv::imread(argv[4], CV_LOAD_IMAGE_UNCHANGED);\n    if (depth1.empty() || depth2.empty()) {\n        cerr << \"depth1 or depth2 is empty.\" << endl;\n        return 1;\n    }\n    \n    cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    std::vector<cv::Point3f> pts1, pts2;\n    \n    for (cv::DMatch m : matches) {\n        ushort d1 = depth1.ptr<unsigned short>((int)keypoints_1[m.queryIdx].pt.y)[(int)keypoints_1[m.queryIdx].pt.x];\n        ushort d2 = depth2.ptr<unsigned short>((int)keypoints_2[m.trainIdx].pt.y)[(int)keypoints_2[m.trainIdx].pt.x];\n        if (d1 == 0 || d2 == 0) {\n            continue;\n        }\n        cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n        cv::Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);\n        float dd1 = float(d1) / 5000.0;\n        float dd2 = float(d2) / 5000.0;\n        pts1.push_back(cv::Point3f(p1.x * dd1, p1.y * dd1, dd1));\n        pts2.push_back(cv::Point3f(p2.x * dd2, p2.y * dd2, dd2));\n    }\n    cout << \"3d-3d pairs: \" << pts1.size() << endl;\n    \n    cv::Mat R, t;\n    pose_estimation_3d3d(pts1, pts2, R, t);\n    cout << \"ICP vid SVD results: \" << endl;\n    cout << \"R = \" << R << endl;\n    cout << \"t = \" << t << endl;\n    cout << \"R_inv = \" << R.t() << endl;\n    cout << \"t_inv = \" << -R.t() * t << endl;\n    \n    cout << \"calling bundle adjustment. \\r\\n\";\n    \n    bundleAdjustment(pts1, pts2, R, t);\n    \n    // verify p1 = R*p2 + t\n    for (int i = 0; i < 5; i ++) {\n        cout << \"p1 = \" << pts1[i] << endl;\n        cout << \"p2 = \" << pts2[i] << endl;\n        cout << \"R*p2 + t = \" << R * (Mat_<double>(3, 1) << pts2[i].x, pts2[i].y, pts2[i].z) + t << endl;\n        cout << endl;\n    }\n    \n    return 0;\n}\n\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector<cv::KeyPoint>& keypoints_1, std::vector<cv::KeyPoint>& keypoints_2, std::vector<cv::DMatch>& matches)\n{\n    //-- Initialize\n    cv::Mat descriptors_1, descriptors_2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    \n    //-- 1st: detect Oriented FAST KeyPoint \n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    \n    //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    \n    //-- 3rd: \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    std::vector<cv::DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    \n    //-- 4th: \u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist = 10000, max_dist = 0;\n    \n    /* \u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb */\n    for (int i = 0; i < descriptors_1.rows; i++) {\n        double dist = match[i].distance;\n        if (dist < min_dist) {\n            min_dist = dist;\n        }\n        if (dist > max_dist) {\n            max_dist = dist;\n        }\n    }\n    \n    printf(\"-- Max distance : %f \\r\\n\", max_dist);\n    printf(\"-- Min distance : %f \\r\\n\", min_dist);\n    \n    // \u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for (int i = 0; i < descriptors_2.rows; i ++) {\n        if (match[i].distance <= max(2*min_dist, 30.0)) {\n            matches.push_back(match[i]);\n        }\n    }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n    return cv::Point2d\n        (\n            (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n            (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n        );\n}\n\nvoid pose_estimation_3d3d(const std::vector<cv::Point3f>& pts1, const std::vector<cv::Point3f>& pts2, cv::Mat& R, cv::Mat& t)\n{\n    // center of mass\n    cv::Point3f p1, p2;\n    int N = pts1.size();\n    for (int i = 0; i < N; i ++) {\n        p1 += pts1[i];\n        p2 += pts2[i];\n    }\n    p1 = cv::Point3f(Vec3f(p1) / N);\n    p2 = cv::Point3f(Vec3f(p2) / N);\n    \n    // remove the center\n    std::vector<cv::Point3f> q1(N), q2(N);\n    for (int i = 0; i < N; i ++) {\n        q1[i] = pts1[i] - p1;\n        q2[i] = pts2[i] - p2;\n    }\n    \n    // compute q1*q2^T\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < N; i ++) {\n        W += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n    }\n    cout << \"W = \" << W << endl;\n    \n    // SVD on W\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n\n    // \u5229\u7528SVD\u6c42\u89e33D-3D\u53d8\u6362\uff0c\u9700\u8981U\u548cV\u7684\u884c\u5217\u5f0f\u540c\u53f7\u3002\u6362\u8a00\u4e4b\uff0c\u65cb\u8f6c\u77e9\u9635\u7684\u884c\u5217\u5f0f\u53ea\u80fd\u4e3a1\uff0c\u4e0d\u80fd\u4e3a-1\n    if (U.determinant() * V.determinant() < 0) {\n        for (int x = 0; x < 3; ++x) {\n            U(x, 2) *= -1;\n        }\n    }\n    cout << \"U = \" << U << endl;\n    cout << \"V = \" << V << endl;\n    \n    \n    Eigen::Matrix3d R_ = U * (V.transpose());\n    Eigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n    \n    // convert to cv::mat\n    R = (cv::Mat_<double>(3, 3) <<\n        R_(0, 0), R_(0, 1), R_(0, 2),\n        R_(1, 0), R_(1, 1), R_(1, 2),\n        R_(2, 0), R_(2, 1), R_(2, 2)\n    );\n    t = (cv::Mat_<double>(3, 1) << t_(0, 0), t_(1, 0), t_(2, 0));\n}\n\nvoid bundleAdjustment(const std::vector<cv::Point3f>& pts1, const std::vector<cv::Point3f>& pts2, cv::Mat& R, cv::Mat& t)\n{\n    // Initialize g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> Block;   // pose\u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linear_solver = new g2o::LinearSolverEigen<Block::PoseMatrixType>();   // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block((std::unique_ptr<Block::LinearSolverType>) linear_solver);\n    g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton((std::unique_ptr<Block>) solver_ptr);\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    \n    // vertex \n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();    // camera pose\n    pose->setId(0);\n    pose->setEstimate(g2o::SE3Quat(Eigen::Matrix3d::Identity(), Eigen::Vector3d(0, 0, 0)));\n    optimizer.addVertex(pose);\n    \n    // edges\n    int index = 1;\n    std::vector<EdgeProjectXYZRGBDPoseOnly*> edges;\n    for (size_t i = 0; i < pts1.size(); i ++) {\n        EdgeProjectXYZRGBDPoseOnly* edge = new EdgeProjectXYZRGBDPoseOnly(Eigen::Vector3d(pts2[i].x, pts2[i].y, pts2[i].z));\n        edge->setId(index);\n        edge->setVertex(0, dynamic_cast<g2o::VertexSE3Expmap*>(pose));\n        edge->setMeasurement(Eigen::Vector3d(pts1[i].x, pts1[i].y, pts1[i].z));\n        edge->setInformation(Eigen::Matrix3d::Identity() * 1e4);\n        optimizer.addEdge(edge);\n        index ++;\n        edges.push_back(edge);\n    }\n    \n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> (t2 - t1);\n    cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << \"\\r\\n\";\n    \n    cout << endl << \"after optimization: \" << endl;\n    cout << \"T = \" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "74056cf2e28a9b4ea296265d3f5278da79a20f38", "size": 11313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d.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_estimation_3d3d/src/pose_estimation_3d3d.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_estimation_3d3d/src/pose_estimation_3d3d.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": 34.1782477341, "max_line_length": 183, "alphanum_fraction": 0.5927693804, "num_tokens": 3891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6928802831901788}}
{"text": "#include <cassert>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"expsum/exponential_sum.hpp\"\n#include \"expsum/kernel_functions/sph_bessel_kernel.hpp\"\n// #include \"expsum/fitting/fast_esprit.hpp\"\n#include <boost/math/special_functions/bessel.hpp>\n\nusing size_type   = arma::uword;\nusing expsum_type = expsum::exponential_sum<double, std::complex<double>>;\n\ntemplate <typename F, typename Vec>\nvoid make_sample(F f, double xmin, double xmax, Vec& result)\n{\n    auto np = result.n_elem;\n    auto h  = (xmax - xmin) / (np - 1);\n    for (size_type n = 0; n < np; ++n)\n    {\n        result(n) = f(xmin + n * h);\n    }\n\n    return;\n}\n\n// expsum_type sph_bessel_kernel(int l, double xmax, size_type N, size_type L,\n//                               size_type M, double eps)\n// {\n//     using esprit_type = expsum::fast_esprit<double>;\n//     using vector_type = arma::Col<double>;\n\n//     vector_type exact(N);\n//     make_sample([=](double x) { return boost::math::sph_bessel(l, x); }, 0.0,\n//                 xmax, exact);\n//     auto delta = xmax / (N - 1);\n\n//     esprit_type esprit(N, L, M);\n\n//     esprit.fit(exact, 0.0, delta, eps);\n//     expsum_type ret(esprit.exponents(), esprit.weights());\n\n//     ret.remove_small_terms(eps / 100.0);\n\n//     return ret;\n// }\n\nexpsum_type sph_bessel_kernel(int l, double xmax, double eps)\n{\n    // using vector_type = arma::Col<double>;\n    expsum::sph_bessel_kernel<double> body;\n    body.compute(l, xmax, eps);\n\n    expsum_type ret(body.exponents(), body.weights());\n\n    return ret;\n}\n\nvoid sph_bessel_kernel_error(int l, double xmax, size_type n_samples,\n                             const expsum_type& ret)\n{\n    using vector_type = arma::Col<double>;\n\n    vector_type x(arma::linspace<vector_type>(0.0, xmax, n_samples));\n    vector_type exact(n_samples), approx(n_samples);\n\n    for (size_type i = 0; i < n_samples; ++i)\n    {\n        exact(i)    = boost::math::sph_bessel(l, x(i));\n        approx(i)   = ret(x(i));\n        auto abserr = std::abs(exact(i) - approx(i));\n        std::cout << std::setw(24) << x(i) << std::setw(24) << exact(i)\n                  << std::setw(24) << approx(i) << std::setw(24) << abserr\n                  << '\\n';\n    }\n\n    vector_type abserr(arma::abs(exact - approx));\n\n    size_type imax = abserr.index_max();\n\n    std::cout << \"\\n  abs. error in interval [0,\" << xmax << \"]\\n\"\n              << \"    maximum : \" << abserr(imax) << '\\n'\n              << \"    averaged: \" << arma::sum(abserr) / n_samples << '\\n';\n}\n\nint main()\n{\n    std::cout.precision(15);\n    std::cout.setf(std::ios::scientific);\n\n    const int lmax = 2;\n\n    size_type N = 100001; // # of sampling points\n    // size_type L = N / 2;       // window length\n    // size_type M = 1000;        // max # of terms\n    double xmax = 1.0e12;\n    double eps  = 1.0e-12;\n\n    expsum_type ret;\n\n    std::cout\n        << \"# Approximation of spherical Bessel function by exponential sum\\n\";\n\n    // for (int l = 0; l <= lmax; ++l)\n    // {\n    //     std::cout << \"\\n# --- order \" << l << '\\n';\n    //     ret = sph_bessel_kernel(l, xmax, eps);\n    //     ret.print(std::cout);\n\n    //     sph_bessel_kernel_error(l, 10.0, N, ret);\n    //     sph_bessel_kernel_error(l, 1.0e8, N, ret);\n    // }\n\n    // for (int l = 0; l <= lmax; ++l)\n    // {\n    //     std::cout << \"\\n# --- order \" << l << '\\n';\n    //     sph_bessel_kernel(l, xmax, eps);\n    // }\n\n    std::cout << \"\\n# --- order \" << lmax << '\\n';\n    ret = sph_bessel_kernel(1, xmax, eps);\n    ret.print(std::cout);\n    std::cout << \"sum weights: \" << arma::sum(ret.weight()) << std::endl;\n    sph_bessel_kernel_error(1, 1.0, 100001, ret);\n    // sph_bessel_kernel_error(1, xmax, N, ret);\n\n    return 0;\n}\n", "meta": {"hexsha": "6f68a738623d6904ef273792c472dc6d4be7c9ef", "size": 3739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/sph_bessel_kernel.cpp", "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": "example/sph_bessel_kernel.cpp", "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": "example/sph_bessel_kernel.cpp", "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": 28.7615384615, "max_line_length": 80, "alphanum_fraction": 0.5629847553, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.692718157335282}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MODULE test_cubic_b_spline\n\n#include <random>\n#include <functional>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::math::constants::third;\nusing boost::math::constants::half;\n\ntemplate<class Real>\nvoid test_b3_spline()\n{\n    std::cout << \"Testing evaluation of spline basis functions on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    // Outside the support:\n    Real eps = std::numeric_limits<Real>::epsilon();\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline<Real>(2.5), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline<Real>(-2.5), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_prime<Real>(2.5), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_prime<Real>(-2.5), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_double_prime<Real>(2.5), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_double_prime<Real>(-2.5), (Real) 0);\n\n\n    // On the boundary of support:\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline<Real>(2), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline<Real>(-2), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_prime<Real>(2), (Real) 0);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_prime<Real>(-2), (Real) 0);\n\n    // Special values:\n    BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline<Real>(-1), third<Real>()*half<Real>(), eps);\n    BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline<Real>( 1), third<Real>()*half<Real>(), eps);\n    BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline<Real>(0), 2*third<Real>(), eps);\n\n    BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline_prime<Real>(-1), half<Real>(), eps);\n    BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline_prime<Real>( 1), -half<Real>(), eps);\n    BOOST_CHECK_SMALL(boost::math::interpolators::detail::b3_spline_prime<Real>(0), eps);\n\n    // Properties: B3 is an even function, B3' is an odd function.\n    for (size_t i = 1; i < 200; ++i)\n    {\n        Real arg = i*0.01;\n        BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline<Real>(arg), boost::math::interpolators::detail::b3_spline<Real>(arg), eps);\n        BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline_prime<Real>(-arg), -boost::math::interpolators::detail::b3_spline_prime<Real>(arg), eps);\n        BOOST_CHECK_CLOSE(boost::math::interpolators::detail::b3_spline_double_prime<Real>(-arg), boost::math::interpolators::detail::b3_spline_double_prime<Real>(arg), eps);\n    }\n\n}\n/*\n * This test ensures that the interpolant s(x_j) = f(x_j) at all grid points.\n */\ntemplate<class Real>\nvoid test_interpolation_condition()\n{\n    using std::sqrt;\n    std::cout << \"Testing interpolation condition for cubic b splines on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    boost::random::uniform_real_distribution<Real> dis(1, 10);\n    std::vector<Real> v(5000);\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = dis(gen);\n    }\n\n    Real step = 0.01;\n    Real a = 5;\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), a, step);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real y = spline(i*step + a);\n        // This seems like a very large tolerance, but I don't know of any other interpolators\n        // that will be able to do much better on random data.\n        BOOST_CHECK_CLOSE(y, v[i], 10000*sqrt(std::numeric_limits<Real>::epsilon()));\n    }\n\n}\n\n\ntemplate<class Real>\nvoid test_constant_function()\n{\n    std::cout << \"Testing that constants are interpolated correctly by cubic b splines on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::vector<Real> v(500);\n    Real constant = 50.2;\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 50.2;\n    }\n\n    Real step = 0.02;\n    Real a = 5;\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), a, step);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        // Do not test at interpolation point; we already know it works there:\n        Real y = spline(i*step + a + 0.001);\n        BOOST_CHECK_CLOSE(y, constant, 10*std::numeric_limits<Real>::epsilon());\n        Real y_prime = spline.prime(i*step + a + 0.002);\n        BOOST_CHECK_SMALL(y_prime, 5000*std::numeric_limits<Real>::epsilon());\n        Real y_double_prime = spline.double_prime(i*step + a + 0.002);\n        BOOST_CHECK_SMALL(y_double_prime, 5000*std::numeric_limits<Real>::epsilon());\n\n    }\n\n    // Test that correctly specified left and right-derivatives work properly:\n    spline = boost::math::interpolators::cardinal_cubic_b_spline<Real>(v.data(), v.size(), a, step, 0, 0);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real y = spline(i*step + a + 0.002);\n        BOOST_CHECK_CLOSE(y, constant, std::numeric_limits<Real>::epsilon());\n        Real y_prime = spline.prime(i*step + a + 0.002);\n        BOOST_CHECK_SMALL(y_prime, std::numeric_limits<Real>::epsilon());\n    }\n\n    //\n    // Again with iterator constructor:\n    //\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline2(v.begin(), v.end(), a, step);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n       // Do not test at interpolation point; we already know it works there:\n       Real y = spline2(i*step + a + 0.001);\n       BOOST_CHECK_CLOSE(y, constant, 10 * std::numeric_limits<Real>::epsilon());\n       Real y_prime = spline2.prime(i*step + a + 0.002);\n       BOOST_CHECK_SMALL(y_prime, 5000 * std::numeric_limits<Real>::epsilon());\n    }\n\n    // Test that correctly specified left and right-derivatives work properly:\n    spline2 = boost::math::interpolators::cardinal_cubic_b_spline<Real>(v.begin(), v.end(), a, step, 0, 0);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n       Real y = spline2(i*step + a + 0.002);\n       BOOST_CHECK_CLOSE(y, constant, std::numeric_limits<Real>::epsilon());\n       Real y_prime = spline2.prime(i*step + a + 0.002);\n       BOOST_CHECK_SMALL(y_prime, std::numeric_limits<Real>::epsilon());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_affine_function()\n{\n    using std::sqrt;\n    std::cout << \"Testing that affine functions are interpolated correctly by cubic b splines on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::vector<Real> v(500);\n    Real a = 10;\n    Real b = 8;\n    Real step = 0.005;\n\n    auto f = [a, b](Real x) { return a*x + b; };\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = f(i*step);\n    }\n\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), 0, step);\n\n    for (size_t i = 0; i < v.size() - 1; ++i)\n    {\n        Real arg = i*step + 0.0001;\n        Real y = spline(arg);\n        BOOST_CHECK_CLOSE(y, f(arg), sqrt(std::numeric_limits<Real>::epsilon()));\n        Real y_prime = spline.prime(arg);\n        BOOST_CHECK_CLOSE(y_prime, a, 100*sqrt(std::numeric_limits<Real>::epsilon()));\n    }\n\n    // Test that correctly specified left and right-derivatives work properly:\n    spline = boost::math::interpolators::cardinal_cubic_b_spline<Real>(v.data(), v.size(), 0, step, a, a);\n\n    for (size_t i = 0; i < v.size() - 1; ++i)\n    {\n        Real arg = i*step + 0.0001;\n        Real y = spline(arg);\n        BOOST_CHECK_CLOSE(y, f(arg), sqrt(std::numeric_limits<Real>::epsilon()));\n        Real y_prime = spline.prime(arg);\n        BOOST_CHECK_CLOSE(y_prime, a, 100*sqrt(std::numeric_limits<Real>::epsilon()));\n    }\n}\n\n\ntemplate<class Real>\nvoid test_quadratic_function()\n{\n    using std::sqrt;\n    std::cout << \"Testing that quadratic functions are interpolated correctly by cubic b splines on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::vector<Real> v(500);\n    Real a = 1.2;\n    Real b = -3.4;\n    Real c = -8.6;\n    Real step = 0.01;\n\n    auto f = [a, b, c](Real x) { return a*x*x + b*x + c; };\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = f(i*step);\n    }\n\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), 0, step);\n\n    for (size_t i = 0; i < v.size() -1; ++i)\n    {\n        Real arg = i*step + 0.001;\n        Real y = spline(arg);\n        BOOST_CHECK_CLOSE(y, f(arg), 0.1);\n        Real y_prime = spline.prime(arg);\n        BOOST_CHECK_CLOSE(y_prime, 2*a*arg + b, 2.0);\n    }\n}\n\n\ntemplate<class Real>\nvoid test_trig_function()\n{\n    std::cout << \"Testing that sine functions are interpolated correctly by cubic b splines on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::mt19937 gen;\n    std::vector<Real> v(500);\n    Real x0 = 1;\n    Real step = 0.125;\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = sin(x0 + step * i);\n    }\n\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), x0, step);\n\n    boost::random::uniform_real_distribution<Real> absissa(x0, x0 + 499 * step);\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real x = absissa(gen);\n        Real y = spline(x);\n        BOOST_CHECK_CLOSE(y, sin(x), 1.0);\n        auto y_prime = spline.prime(x);\n        BOOST_CHECK_CLOSE(y_prime, cos(x), 2.0);\n    }\n}\n\ntemplate<class Real>\nvoid test_copy_move()\n{\n    std::cout << \"Testing that copy/move operation succeed on cubic b spline\\n\";\n    std::vector<Real> v(500);\n    Real x0 = 1;\n    Real step = 0.125;\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = sin(x0 + step * i);\n    }\n\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), x0, step);\n\n\n    // Default constructor should compile so that splines can be member variables:\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> d;\n    d = boost::math::interpolators::cardinal_cubic_b_spline<Real>(v.data(), v.size(), x0, step);\n    BOOST_CHECK_CLOSE(d(x0), sin(x0), 0.01);\n    // Passing to lambda should compile:\n    auto f = [=](Real x) { return d(x); };\n    // Make sure this variable is used.\n    BOOST_CHECK_CLOSE(f(x0), sin(x0), 0.01);\n\n    // Move operations should compile.\n    auto s = std::move(spline);\n\n    // Copy operations should compile:\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> c = d;\n    BOOST_CHECK_CLOSE(c(x0), sin(x0), 0.01);\n\n    // Test with std::bind:\n    auto h = std::bind(&boost::math::interpolators::cardinal_cubic_b_spline<double>::operator(), &s, std::placeholders::_1);\n    BOOST_CHECK_CLOSE(h(x0), sin(x0), 0.01);\n}\n\ntemplate<class Real>\nvoid test_outside_interval()\n{\n    std::cout << \"Testing that the spline can be evaluated outside the interpolation interval\\n\";\n    std::vector<Real> v(400);\n    Real x0 = 1;\n    Real step = 0.125;\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = sin(x0 + step * i);\n    }\n\n    boost::math::interpolators::cardinal_cubic_b_spline<Real> spline(v.data(), v.size(), x0, step);\n\n    // There's no test here; it simply does it's best to be an extrapolator.\n    //\n    std::ostream cnull(0);\n    cnull << spline(0);\n    cnull << spline(2000);\n}\n\nBOOST_AUTO_TEST_CASE(test_cubic_b_spline)\n{\n    test_b3_spline<float>();\n    test_b3_spline<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_b3_spline<long double>();\n#endif\n    test_b3_spline<cpp_bin_float_50>();\n\n    test_interpolation_condition<float>();\n    test_interpolation_condition<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_interpolation_condition<long double>();\n#endif\n    test_interpolation_condition<cpp_bin_float_50>();\n\n    test_constant_function<float>();\n    test_constant_function<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_constant_function<long double>();\n#endif\n    test_constant_function<cpp_bin_float_50>();\n\n    test_affine_function<float>();\n    test_affine_function<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_affine_function<long double>();\n#endif\n    test_affine_function<cpp_bin_float_50>();\n\n    test_quadratic_function<float>();\n    test_quadratic_function<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_quadratic_function<long double>();\n#endif\n    test_affine_function<cpp_bin_float_50>();\n\n    test_trig_function<float>();\n    test_trig_function<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_trig_function<long double>();\n#endif\n    test_trig_function<cpp_bin_float_50>();\n\n    test_copy_move<double>();\n    test_outside_interval<double>();\n}\n", "meta": {"hexsha": "28b3cf302dcd6f31a86c6cc27a8e28e613028209", "size": 13316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cardinal_cubic_b_spline_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/cardinal_cubic_b_spline_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/cardinal_cubic_b_spline_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 36.5824175824, "max_line_length": 174, "alphanum_fraction": 0.6565785521, "num_tokens": 3740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6926977493795374}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#include <iostream>\r\n\r\n#include <boost/compute/function.hpp>\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/algorithm/count_if.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n#include <boost/compute/iterator/buffer_iterator.hpp>\r\n#include <boost/compute/random/default_random_engine.hpp>\r\n#include <boost/compute/types/fundamental.hpp>\r\n\r\nnamespace compute = boost::compute;\r\n\r\nint main()\r\n{\r\n    // get default device and setup context\r\n    compute::device gpu = compute::system::default_device();\r\n    compute::context context(gpu);\r\n    compute::command_queue queue(context, gpu);\r\n\r\n    std::cout << \"device: \" << gpu.name() << std::endl;\r\n\r\n    using compute::uint_;\r\n    using compute::uint2_;\r\n\r\n    // ten million random points\r\n    size_t n = 10000000;\r\n\r\n    // generate random numbers\r\n    compute::default_random_engine rng(queue);\r\n    compute::vector<uint_> vector(n * 2, context);\r\n    rng.generate(vector.begin(), vector.end(), queue);\r\n\r\n    // function returing true if the point is within the unit circle\r\n    BOOST_COMPUTE_FUNCTION(bool, is_in_unit_circle, (const uint2_ point),\r\n    {\r\n        const float x = point.x / (float) UINT_MAX - 1;\r\n        const float y = point.y / (float) UINT_MAX - 1;\r\n\r\n        return (x*x + y*y) < 1.0f;\r\n    });\r\n\r\n    // iterate over vector<uint> as vector<uint2>\r\n    compute::buffer_iterator<uint2_> start =\r\n        compute::make_buffer_iterator<uint2_>(vector.get_buffer(), 0);\r\n    compute::buffer_iterator<uint2_> end =\r\n        compute::make_buffer_iterator<uint2_>(vector.get_buffer(), vector.size() / 2);\r\n\r\n    // count number of random points within the unit circle\r\n    size_t count = compute::count_if(start, end, is_in_unit_circle, queue);\r\n\r\n    // print out values\r\n    float count_f = static_cast<float>(count);\r\n    std::cout << \"count: \" << count << \" / \" << n << std::endl;\r\n    std::cout << \"ratio: \" << count_f / float(n) << std::endl;\r\n    std::cout << \"pi = \" << (count_f / float(n)) * 4.0f << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "0f9e3d3e0260da161eac8f2aec1688c3f0a4234e", "size": 2476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/compute/example/monte_carlo.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/compute/example/monte_carlo.cpp", "max_issues_repo_name": "nxplatform/nx-mobile", "max_issues_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty-cpp/boost_1_62_0/libs/compute/example/monte_carlo.cpp", "max_forks_repo_name": "nxplatform/nx-mobile", "max_forks_repo_head_hexsha": "0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5", "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": 35.884057971, "max_line_length": 87, "alphanum_fraction": 0.6122778675, "num_tokens": 581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888478, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.6925647429665419}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2014 Soumyajit De\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 <iostream>\n#include <tesseract/regression/LeastSquares.hpp>\n#include <Eigen/Eigen>\n\nusing namespace tesseract;\nusing namespace Eigen;\nusing namespace std;\n\ntemplate <class Matrix, class Vector>\nvoid test_svd(const Matrix& A, const Vector& b, Vector& x)\n{\n\tLeastSquares<double, LS_SVD> ls;\n\tls.solve(A, b, x);\n//\tcout << \"beta = \" << endl << x << endl;\n//\tcout << \"residual = \" << b-A*x << endl;\n}\n\ntemplate <class Matrix, class Vector>\nvoid test_qr(const Matrix& A, const Vector& b, Vector& x)\n{\n\tLeastSquares<double, LS_QR> ls;\n\tls.solve(A, b, x);\n//\tcout << \"beta = \" << endl << x << endl;\n//\tcout << \"residual = \" << b-A*x << endl;\n}\n\ntemplate <class Matrix, class Vector>\nvoid test_normal(Matrix& A, Vector& b, Vector& x)\n{\n\tLeastSquares<double, LS_NORMAL> ls;\n\tls.solve(A, b, x);\n//\tcout << \"beta = \" << endl << x << endl;\n//\tcout << \"residual = \" << b-A*x << endl;\n}\n\nint main(int argc, char** argv)\n{\n\tMatrixXd A = MatrixXd::Random(3, 2);\n\tVectorXd b = VectorXd::Random(3);\n\tVectorXd res = VectorXd::Zero(2);\n\n//\tcout << \"A = \" << endl << A << endl;\n//\tcout << \"b = \" << endl << b << endl;\n\n\ttest_svd(A, b, res);\n\ttest_qr(A, b, res);\n\ttest_normal(A, b, res);\n\n\tMap<MatrixXd> map_A(A.data(), A.rows(), A.cols());\n\tMap<VectorXd> map_b(b.data(), b.rows());\n\tMap<VectorXd> map_res(res.data(), res.rows());\n\n\ttest_svd(map_A, map_b, map_res);\n\ttest_qr(map_A, map_b, map_res);\n\ttest_normal(map_A, map_b, map_res);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "12c86393c3d0f452d54155a4d530bc4108db9490", "size": 2583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sanity/unit/LeastSquares_unittest.cpp", "max_stars_repo_name": "lambday/tesseract", "max_stars_repo_head_hexsha": "b38cf14545940f3b227285a19d40907260f057e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T08:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-24T08:34:04.000Z", "max_issues_repo_path": "sanity/unit/LeastSquares_unittest.cpp", "max_issues_repo_name": "lambday/tesseract", "max_issues_repo_head_hexsha": "b38cf14545940f3b227285a19d40907260f057e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sanity/unit/LeastSquares_unittest.cpp", "max_forks_repo_name": "lambday/tesseract", "max_forks_repo_head_hexsha": "b38cf14545940f3b227285a19d40907260f057e6", "max_forks_repo_licenses": ["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.1204819277, "max_line_length": 81, "alphanum_fraction": 0.683313976, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8128673269042768, "lm_q1q2_score": 0.6925246090066792}}
{"text": "\ufeff#include <iostream>\n\n#include <Eigen/Dense>\n\nint main (int argc, char *argv[]){\n    Eigen::MatrixXf m(2, 2);\n    m << 1, 2, 3, 4;\n    Eigen::VectorXf v(2);\n    v << -1, 1;\n    auto r = m * v;\n    std::cout << r(0) << \" \" << r(1) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "7929d2df90c8c7d951a94b06632add817f22d23e", "size": 260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example.01/main.cpp", "max_stars_repo_name": "AndreyBuyanov/EigenExample", "max_stars_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_stars_repo_licenses": ["MIT"], "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.01/main.cpp", "max_issues_repo_name": "AndreyBuyanov/EigenExample", "max_issues_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_issues_repo_licenses": ["MIT"], "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.01/main.cpp", "max_forks_repo_name": "AndreyBuyanov/EigenExample", "max_forks_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 50, "alphanum_fraction": 0.4807692308, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.692378925173398}}
{"text": "#include <ctime>\n#include <fftw3.h>\n#include <string>\n#include <algorithm>\n#include <iostream>\n#include <random>\n#include <math.h>\n#include <vtkNew.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkDoubleArray.h>\n#include <vtkPoints.h>\n#include <vtkCellArray.h>\n#include <vtkIdList.h>\n#include <Eigen/Dense>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include \"shtns.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned,K> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds> Delaunay;\ntypedef Delaunay::Face_circulator Face_circulator;\ntypedef Delaunay::Face_handle Face_handle;\ntypedef Delaunay::Point Point;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\n\nint main(){\n\n    // Read the polydata\n    vtkNew<vtkPolyDataReader> reader;\n    reader->SetFileName(\"T7.vtk\");\n    reader->Update();\n    auto pointCloud = reader->GetOutput();\n    int N = pointCloud->GetNumberOfPoints();\n\n    //**********************************************************************//\n    //SHTns: Generate quadrature points\n    int lmax = std::floor( sqrt(N) - 1 );\n    int mmax = lmax, nlat = 0, nphi = 0, mres = 1;\n    shtns_cfg shtns;\n    shtns_verbose(1);\n    shtns_norm norm = static_cast<shtns_norm>(SHT_REAL_NORM | SHT_NO_CS_PHASE);\n    shtns = shtns_create(lmax, mmax, mres, norm );\n    shtns_type flags = static_cast<shtns_type>( sht_gauss | SHT_NATIVE_LAYOUT);\n    shtns_set_grid_auto(shtns, flags, 1e-14, 1, &nlat, &nphi );\n    int NLM = shtns->nlm;\n    int numQ = nphi*nlat;\n\n    // Memory allocation\n    double_t *f;\n    f = static_cast<double_t*>(\n\t    fftw_malloc( NSPAT_ALLOC(shtns)*sizeof(double_t) ));\n    std::complex<double_t> *Slm;\n    Slm = static_cast<std::complex<double_t>*>(\n\t    fftw_malloc( NLM*sizeof(std::complex<double_t>) ));\n    // Memory initialization\n    for( auto lm = 0; lm < NLM; ++lm){\n\tSlm[lm] = 0.0;\n    }\n\n    // Calculate the quad point Q0\n    Eigen::Matrix3Xd Q0(3,numQ);\n    for( auto ip = 0; ip < nphi; ++ip){\n\tfor( auto it = 0; it < nlat; ++it){\n\t    auto phi = ip*M_PI*2/nphi;\n\t    Q0.col(it + ip*nlat) << shtns->st[it]*std::cos(phi),\n\t\tshtns->st[it]*std::sin(phi), shtns->ct[it];\n\t}\n    }\n\n    //************************* Some handy functions ***********************//\n\n    // A lambda function to write a Eigen::Matrix3Xd to VTK file\n    auto writeMatToVTK =\n\t[](Eigen::Matrix3Xd M, std::string file, bool Proj = false){\n\t    vtkNew<vtkPoints> pts;\n\t    vtkNew<vtkCellArray> verts;\n\t    for( auto b = 0; b < M.cols(); ++b ){\n\t\tdouble x, y, z;\n\t\tx = M(0,b);\n\t\ty = M(1,b);\n\t\tz = Proj? 0.0 : M(2,b);\n\t\tpts->InsertNextPoint(x, y, z);\n\t\tverts->InsertNextCell( 1 );\n\t\tverts->InsertCellPoint( b );\n\t    }\n\t    vtkNew<vtkPolyData> poly;\n\t    poly->SetPoints( pts );\n\t    poly->SetVerts( verts );\n\t    vtkNew<vtkPolyDataWriter> wr;\n\t    wr->SetInputData( poly );\n\t    wr->SetFileName( file.c_str() );\n\t    wr->Write();\n\t};\n\n    //**********************************************************************//\n    clock_t t = clock();\n\n    for( auto z = 0; z < 1000; ++z ){\n\t// Copy the point coordinates into a matrix\n\tEigen::Map<Eigen::Matrix3Xd> points((double_t*)pointCloud->GetPoints()\n\t\t->GetData()->GetVoidPointer(0),3,N);\n\n\t// Project points to unit sphere\n\tpoints.colwise().normalize();\n\n\t// Reset the center of the sphere to origin by translating\n\tVector3d center = points.rowwise().mean();\n\tpoints = points.colwise() - center;\n\n\t// Write original points to VTK\n\t//writeMatToVTK( points, \"BasePoints.vtk\" );\n\n\t// Rotate all points so that the point in 0th column is along z-axis\n\tVector3d c = points.col(0);\n\tdouble_t cos_t = c(2);\n\tdouble_t sin_t = std::sqrt( 1 - cos_t*cos_t );\n\tVector3d axis;\n\taxis << c(1), -c(0), 0.;\n\tMatrix3d rotMat, axis_cross, outer;\n\taxis_cross << 0. , -axis(2), axis(1),\n\t\t   axis(2), 0., -axis(0),\n\t\t   -axis(1), axis(0), 0.;\n\n\touter.noalias() = axis*axis.transpose();\n\n\trotMat = cos_t*Matrix3d::Identity() + sin_t*axis_cross + (1-cos_t)*outer;\n\tMatrix3Xd rPts(3,N);\n\trPts = rotMat*points; // The points on a sphere rotated\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( rPts, \"RotBasePoints.vtk\" );\n\n\t// Calculate the stereographic projections\n\tVector3d p0;\n\tMap3Xd l0( &(rPts(0,1)), 3, N-1 );\n\tMatrix3Xd l(3,N-1), proj(3,N-1);\n\tp0 << 0,0,-1; // Point on the plane of projection\n\tc = rPts.col(0); // The point from which we are projecting\n\tl = (l0.colwise() - c).colwise().normalized(); // directions of projections\n\tfor( auto j=0; j < N-1; ++j ){\n\t    proj.col(j) = ((p0(2) - l0(2,j))/l(2,j))*l.col(j) + l0.col(j);\n\t}\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( proj, \"ProjBasePoints.vtk\", true );\n\n\t// Insert the projected points in a CGAL vertex_with_info vector\n\tstd::vector< std::pair< Point, unsigned> > verts;\n\tfor( auto j=0; j < N-1; ++j ){\n\t    verts.push_back(std::make_pair(Point(proj(0,j),proj(1,j)),j+1));\n\t}\n\n\tDelaunay dt( verts.begin(), verts.end() );\n\n\t/*\n\t// Write the triangulation to file\n\tvtkNew<vtkCellArray> sphereTri;\n\tfor( auto fc = dt.all_faces_begin(); fc != dt.all_faces_end(); ++fc ){\n\tsphereTri->InsertNextCell(3);\n\tfor( auto zz = 2; zz >= 0; --zz ){\n\tauto vid = dt.is_infinite( fc->vertex( zz ) )? 0 :\n\tfc->vertex(zz)->info();\n\tsphereTri->InsertCellPoint(vid);\n\t}\n\t}\n\tpointCloud->SetPolys( sphereTri );\n\tvtkNew<vtkPolyDataWriter> wr;\n\twr->SetInputData( pointCloud );\n\twr->SetFileName( \"Sphere.vtk\" );\n\twr->Write();\n\t*/\n\n\t// Create the input scalar field f(theta,phi)\n\tstd::complex<double_t> Qlm[NLM];\n\tfor(auto pp = 0; pp < NLM; ++pp)\n\t    Qlm[pp] = 0.0;\n\tQlm[ LM(shtns, 0, 0) ] = std::complex<double_t>(0,0);\n\tQlm[ LM(shtns, 1, 0) ] = std::complex<double_t>(2,0);\n\tQlm[ LM(shtns, 1, 1) ] = std::complex<double_t>(0,3);\n\tQlm[ LM(shtns, 7, 7) ] = std::complex<double_t>(7,0);\n\n\tEigen::VectorXd finput(N);\n\tfor(auto i = 0; i < N; ++i){\n\t    Eigen::Vector3d q;\n\t    q = points.col(i);\n\t    double_t x = q(0);\n\t    double_t y = q(1);\n\t    double_t z = q(2);\n\t    auto phi = std::atan2(y,x);\n\t    finput(i) = SH_to_point(shtns, Qlm, z, phi);\n\t}\n\n\t//Now we need to first identify which triangles each of the quadrature\n\t//points belongs to. For this, we need the coordinates of the points\n\tEigen::Matrix3Xd Qr(3,numQ);// Rotated quadrature points\n\tEigen::Matrix3Xd Qsp(3,numQ);// StereoProjection of quadrature points\n\n\n\t// Write Quadrature points to VTK file\n\t//writeMatToVTK( Q0, \"QuadPointsOrig.vtk\" );\n\n\t// Now we need to rotate and project the quadrature points\n\t// p0 is already defined as the z = -1 plane\n\t// c is the point from which we are projecting (calculated earlier)\n\tQr = rotMat*Q0; // Rotate the quadrature points\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( Qr, \"RotQuadPoints.vtk\" );\n\n\tEigen::Matrix3Xd lQ(3,numQ);\n\tlQ = (Qr.colwise() - c).colwise().normalized();//projn dirn unit vectors\n\tfor( auto j=0; j < numQ; ++j ){\n\t    Qsp.col(j) = ((p0(2) - Qr(2,j))/lQ(2,j))*lQ.col(j) + Qr.col(j);\n\t}\n\n\t// Write Stereographic projections of quadrature points to VTK file\n\t//writeMatToVTK( Qsp, \"ProjQuadPoints.vtk\", true );\n\n\t//Finally let's try to locate these points in the Triangulation and\n\t//interpolate it as per the weights\n\tEigen::Map<Eigen::VectorXd> fquad(f,numQ);\n\tauto interpolate = [&points, &Q0, &finput, &fquad](const size_t i,\n\t\tconst size_t j, const size_t k, const size_t q){\n\t    Eigen::Vector3d v0 = points.col(i);\n\t    Eigen::Vector3d v1 = points.col(j);\n\t    Eigen::Vector3d v2 = points.col(k);\n\t    Eigen::Vector3d qp = Q0.col(q);\n\t    auto A0 = ((v1-qp).cross((v2-qp))).norm();\n\t    auto A1 = ((v2-qp).cross((v0-qp))).norm();\n\t    auto A2 = ((v0-qp).cross((v1-qp))).norm();\n\t    auto A = A0 + A1 + A2;\n\t    fquad(q) = (A0/A)*finput(i) + (A1/A)*finput(j) + (A2/A)*finput(k);\n\t};\n\tfor( auto j=0; j < numQ; ++j ){\n\t    auto query = Point( Qsp(0,j), Qsp(1,j) );\n\t    Delaunay::Locate_type lt;\n\t    int li;\n\t    Face_handle face = dt.locate( query, lt, li );\n\t    switch(lt){\n\t\tcase Delaunay::FACE:\n\t\t    {\n\t\t\tauto id0 = face->vertex(0)->info();\n\t\t\tauto id1 = face->vertex(1)->info();\n\t\t\tauto id2 = face->vertex(2)->info();\n\t\t\tinterpolate( id0, id1, id2, j );\n\t\t\tbreak;\n\t\t    }\n\t\tcase Delaunay::EDGE:\n\t\t    {\n\t\t\tauto id1 = face->vertex( (li + 1)%3 )->info();\n\t\t\tauto id2 = face->vertex( (li + 2)%3 )->info();\n\t\t\tEigen::Vector3d v1, v2, qp;\n\t\t\tv1 = points.col(id1);\n\t\t\tv2 = points.col(id2);\n\t\t\tqp = Q0.col(j);\n\t\t\tdouble_t ratio = (qp - v1).norm()/(qp - v2).norm();\n\t\t\tfquad(j) = (finput(id1) + ratio*finput(id2))/(1 + ratio);\n\t\t\tbreak;\n\t\t    }\n\t\tcase Delaunay::VERTEX:\n\t\t    fquad(j) = finput( face->vertex( li )->info() );\n\t\t    break;\n\t\tcase Delaunay::OUTSIDE_CONVEX_HULL:\n\t\t    {\n\t\t\tEigen::Vector3d v0, v1, v2;\n\t\t\tauto id0 = dt.is_infinite(face->vertex(0))?\n\t\t\t    0 : face->vertex(0)->info();\n\t\t\tauto id1 = dt.is_infinite(face->vertex(1))?\n\t\t\t    0 : face->vertex(1)->info();\n\t\t\tauto id2 = dt.is_infinite(face->vertex(2))?\n\t\t\t    0 : face->vertex(2)->info();\n\t\t\tinterpolate( id0, id1, id2, j );\n\t\t\tbreak;\n\t\t    }\n\t\tdefault:\n\t\t    std::cout<< \"Point \" << j << \" not found!\" << std::endl;\n\t    }\n\t}\n\n\t/*\n\t   std::cout<< \"Print interpolated values and actual values...\"<<std::endl;\n\t   Eigen::VectorXd direct(numQ);\n\t   for(auto i = 0; i < numQ; ++i){\n\t   Eigen::Vector3d q;\n\t   q = Q0.col(i);\n\t   double_t x = q(0);\n\t   double_t y = q(1);\n\t   double_t z = q(2);\n\t   auto phi = std::atan2(y,x);\n\t   direct(i) = SH_to_point(shtns, Qlm, z, phi);\n\t   std::cout<< fquad(i) << \" \" << direct(i) << std::endl;\n\t   }\n\t   */\n\n\t// Now time for spherical harmonic analysis -- find the coefficients flm\n\tspat_to_SH(shtns, f, Slm);\n\n\t/*\n\t   std::cout<< \"Printing the coefficients...\" << std::endl;\n\t// Print the spherical harmonic coefficients\n\tfor( auto l = 0; l <= lmax; ++l ){\n\tfor( auto m = -l; m <= l; ++m ){\n\tstd::complex<double_t> flm;\n\tif( m < 0){\n\tauto factor = (-m%2 == 0)? 1.0 : -1.0;\n\tflm = factor*std::conj(Slm[ LM(shtns,l,-m) ]);\n\t}\n\telse{\n\tflm = Slm[ LM(shtns,l,m) ];\n\t}\n\tstd::cout<< l << \" \" << m << \" \" << flm << std::endl;\n\t}\n\t}\n\t*/\n    }\n    std::cout<< \"Time for 1000 steps = \" \n\t<< ((float)(clock() - t))/CLOCKS_PER_SEC << std::endl;\n    for( auto lm = 0; lm < NLM; ++lm){\n\tstd::cout<< Slm[ lm ] << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "f8f15c17d2265a6efc3799060cb01448cca3d8c3", "size": 10502, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "TestSHTNS.cxx", "max_stars_repo_name": "amit112amit/ops-spherical-harmonics", "max_stars_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T13:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T13:42:53.000Z", "max_issues_repo_path": "TestSHTNS.cxx", "max_issues_repo_name": "amit112amit/ops-spherical-harmonics", "max_issues_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestSHTNS.cxx", "max_forks_repo_name": "amit112amit/ops-spherical-harmonics", "max_forks_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_forks_repo_licenses": ["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.6325301205, "max_line_length": 79, "alphanum_fraction": 0.6140735098, "num_tokens": 3508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6923194928175932}}
{"text": "// -*- coding: utf-8 -*-\n\n#define _USE_MATH_DEFINES\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <chrono>\n#include <assert.h>\n\ndouble slp_laplace(const Eigen::Vector2d &xm, const Eigen::Vector2d &ym, const Eigen::Vector2d &y1,\n\t\t   const Eigen::Vector2d &y2, const double &hy, const Eigen::Vector2d &yn){\n//  Eigen::Vector2d ym;\n  Eigen::Vector2d rr1;\n  Eigen::Vector2d rr2;\n  double r1;\n  double r2;\n  Eigen::Vector2d yt;\n  double uk1, uk2, uk3, uk4, uk5;\n  constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0));\n\n//  ym = 0.5*(y1 + y2);\n\n  if((xm - ym).squaredNorm() < 1.0e-8){\n    return hy*(1.0 - std::log(hy*0.5))*arctwopi;\n  }\n  else{\n    rr1 = xm - y1;\n    rr2 = xm - y2;\n    r1 = rr1.norm();\n    r2 = rr2.norm();\n    yt(0) = -yn(1);\n    yt(1) = yn(0);\n\n    uk1 = rr1.dot(yn);\n    uk2 = rr1.dot(yt);\n    uk3 = rr2.dot(yn);\n    uk4 = rr2.dot(yt);\n    uk5 = std::atan2(uk3, uk4) - std::atan2(uk1, uk2);\n    return (uk4*std::log(r2) - uk2*std::log(r1) + hy - uk1*uk5)*arctwopi;\n//    std::cout << \"tes3 \" << std::endl; //dbg\n  }\n}\n\ndouble dlp_laplace(const Eigen::Vector2d &xm, const Eigen::Vector2d &ym, const Eigen::Vector2d &y1,\n\t\t   const Eigen::Vector2d &y2, const double &hy, const Eigen::Vector2d &yn,\n\t\t   const int &exterior){\n\n//  Eigen::Vector2d ym;\n  Eigen::Vector2d rr1;\n  Eigen::Vector2d rr2;\n  double r1;\n  double r2;\n  Eigen::Vector2d yt;\n  double uk1, uk2, uk3, uk4;\n  constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0));\n\n  //  ym = 0.5*(y1 + y2);\n\n  if((xm - ym).squaredNorm() < 1.0e-8){\n    if(exterior == 0){\n      return 0.5;\n    }else if(exterior == 1){\n      return -0.5;\n    }else{\n      assert(false);\n    }\n  }\n  else{\n    rr1 = xm - y1;\n    rr2 = xm - y2;\n    r1 = rr1.norm();\n    r2 = rr2.norm();\n    yt(0) = -yn(1);\n    yt(1) = yn(0);\n\n    uk1 = rr1.dot(yn);\n    uk2 = rr1.dot(yt);\n    uk3 = rr2.dot(yn);\n    uk4 = rr2.dot(yt);\n    return arctwopi*(std::atan2(uk3, uk4) - std::atan2(uk1, uk2));\n  }\n}\n\nint main(){\n  int n;\n  double rad;\n  std::ifstream fr(\"input\");\n  fr >> n >> rad;\n  std::cout << \"n \" << n << std::endl;\n  std::cout << \"rad \" << rad << std::endl;\n\n  Eigen::MatrixXd x = Eigen::MatrixXd::Zero(2, n);\n  Eigen::MatrixXd xn = Eigen::MatrixXd::Zero(2, n);\n  Eigen::MatrixXi edge = Eigen::MatrixXi::Zero(2, n);\n  Eigen::VectorXd hs = Eigen::VectorXd::Zero(n);\n  Eigen::MatrixXd slp = Eigen::MatrixXd::Zero(n, n);\n  Eigen::MatrixXd dlp = Eigen::MatrixXd::Zero(n, n);\n  Eigen::VectorXd u = Eigen::VectorXd::Zero(n);\n  Eigen::VectorXd kai = Eigen::VectorXd::Zero(n);\n  Eigen::VectorXd xm = Eigen::VectorXd::Zero(2);\n  Eigen::VectorXd ym = Eigen::VectorXd::Zero(2);\n\n  constexpr double pi = std::acos(-1.0);\n\n  int i;\n  int j;\n  double th;\n  int i0;\n  int i1;\n  int j0;\n  int j1;\n  int exterior = 0;\n\n  for(i = 0; i < n; i++){\n    th = 2.0*pi*(i + 1.5)/n;\n    x(0, i) = rad*cos(th);\n    x(1, i) = rad*sin(th);\n    edge(0, i) = i;\n    edge(1, i) = (i + 1) % n;\n  }\n\n  Eigen::Vector2d rr1; //dbg\n  Eigen::Vector2d rr2; //dbg\n  double r1; //dbg\n  double r2; //dbg\n  Eigen::Vector2d yt; //dbg\n  double uk1, uk2, uk3, uk4, uk5; //dbg\n  constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0)); //dbg\n\n  for(i = 0; i < n; i++){\n    i0 = edge(0, i);\n    i1 = edge(1, i);\n    xm = 0.5*(x.col(i0) + x.col(i1));\n\n    if((i0 >= 0 && i0 < n) && (i1 >= 0 && i1 < n)){\n      xn(0, i) = x(1, i1) - x(1, i0);\n      xn(1, i) = x(0, i0) - x(0, i1);\n\n      hs(i) = std::sqrt(std::pow(xn(0, i), 2.0) + std::pow(xn(1, i), 2.0));\n\n      xn(0, i) = xn(0, i)/hs(i);\n      xn(1, i) = xn(1, i)/hs(i);\n    }\n    else{\n      assert(false);\n    }\n    // x**3*y - x*y**3\n    u(i) = std::pow(xm(0), 3.0)*xm(1) - xm(0)*std::pow(xm(1), 3.0);\n\n    // (3x**2*y - y**3)nx + (x**3 - 3xy**2)ny\n    kai(i) = (3.0*std::pow(xm(0), 2.0)*xm(1) - std::pow(xm(1), 3.0))*xn(0, i)\n      + (std::pow(xm(0), 3.0) - 3.0*xm(0)*std::pow(xm(1), 2.0))*xn(1, i);\n  }\n\n  for(j = 0; j < n; j++){\n     j0 = edge(0, j);\n     j1 = edge(1, j);\n     ym = 0.5*(x.col(j0) + x.col(j1));\n     for(i = 0; i < n; i++){\n       i0 = edge(0, i);\n       i1 = edge(1, i);\n       xm = 0.5*(x.col(i0) + x.col(i1));\n\n       slp(i, j) = slp_laplace(xm, ym, x.col(j0), x.col(j1), hs(j), xn.col(j));\n       dlp(i, j) = dlp_laplace(xm, ym, x.col(j0), x.col(j1), hs(j), xn.col(j), exterior);\n     }\n  }\n\n  u = slp.partialPivLu().solve(dlp*u);\n\n  std::cout << \"relative error \" << std::sqrt(((u - kai).dot(u - kai))/kai.dot(kai)) << std::endl;\n}\n", "meta": {"hexsha": "4fff57c1b7897b0518071d1e7c4bf8324033afce", "size": 4452, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/2d_laplace", "max_stars_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_stars_repo_licenses": ["MIT"], "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.cc", "max_issues_repo_name": "ya-mat/2d_laplace", "max_issues_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_issues_repo_licenses": ["MIT"], "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/2d_laplace", "max_forks_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_forks_repo_licenses": ["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.5862068966, "max_line_length": 99, "alphanum_fraction": 0.524034142, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6921885996226141}}
{"text": "\n#include <UnitTest++/UnitTest++.h>\n#include <stdexcept>\n#include \"../misc_math.h\"\n#include <iostream>\n#include <boost/math/distributions/poisson.hpp>\n#include <limits>\n#include <boost/math/distributions/hypergeometric.hpp>\n\nusing namespace coela;\nusing namespace std;\n\nSUITE(misc_math)\n{\n    using namespace misc_math;\n\n    TEST(Notify_Suite_Has_Been_Run) {\n        cout << \"*** \\\"misc_math\\\" unit tests running ***\" <<endl;\n    }\n\n    TEST(integer_factorial) {\n        CHECK_EQUAL(1ul, integer_factorial(0));\n        CHECK_EQUAL(1ul, integer_factorial(1));\n        CHECK_EQUAL(2ul, integer_factorial(2));\n        CHECK_EQUAL(6ul, integer_factorial(3));\n        CHECK_EQUAL(24ul, integer_factorial(4));\n\n//        cout<<\"Unsigned long max: \" << numeric_limits<unsigned long>::max() <<endl;\n//\n//        double max_int_fac =1;\n//        while (approx_factorial_double(max_int_fac) < numeric_limits<unsigned long>::max())\n//            max_int_fac++;\n//\n//        cout<<\"Implies max input for integer_factorial:\"<<max_int_fac<<endl;\n\n    }\n\n    TEST(boost_poisson_dist_function) {\n        boost::math::poisson_distribution<> p(0.2);\n        CHECK_CLOSE(0.81873 , boost::math::pdf(p, 0), 0.001);\n        CHECK_CLOSE(0.16375 , boost::math::pdf(p, 1), 0.001);\n        CHECK_CLOSE(0.01637 , boost::math::pdf(p, 2), 0.001);\n    }\n}", "meta": {"hexsha": "d29b187e39b79d53578841621865e367a87e73d4", "size": 1325, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_utility/src/unit_tests/lucky_math_unit_tests.cc", "max_stars_repo_name": "timstaley/coelacanth", "max_stars_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:08:45.000Z", "max_issues_repo_path": "coela_utility/src/unit_tests/lucky_math_unit_tests.cc", "max_issues_repo_name": "timstaley/coelacanth", "max_issues_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "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": "coela_utility/src/unit_tests/lucky_math_unit_tests.cc", "max_forks_repo_name": "timstaley/coelacanth", "max_forks_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "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.1136363636, "max_line_length": 93, "alphanum_fraction": 0.6475471698, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088004, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6921213573804983}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>\n\n#include <Eigen/Dense>\n#include <array>\n#include <scicpp/core.hpp>\n#include <scicpp/linalg.hpp>\n\nint main() {\n    Eigen::Matrix<double, 4, 2> A;\n    A << 0., 1., //\n        1., 1.,  //\n        2., 1.,  //\n        3., 1.;\n\n    const std::array b{-1., 0.2, 0.9, 2.1};\n    const auto x = scicpp::linalg::lstsq(A, b);\n    scicpp::print(x);\n}", "meta": {"hexsha": "705a02085709211ff7b7b93c900f5953434ec828", "size": 447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/doc/linalg_lstsq.cpp", "max_stars_repo_name": "tvanderbruggen/SciCpp", "max_stars_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T09:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:58:05.000Z", "max_issues_repo_path": "examples/doc/linalg_lstsq.cpp", "max_issues_repo_name": "tvanderbruggen/SciCpp", "max_issues_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_issues_repo_licenses": ["MIT"], "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/doc/linalg_lstsq.cpp", "max_forks_repo_name": "tvanderbruggen/SciCpp", "max_forks_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_forks_repo_licenses": ["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.5263157895, "max_line_length": 76, "alphanum_fraction": 0.5659955257, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6921213475064647}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\n#include <type_traits>\nusing namespace std;\n\n#include <boost/math/constants/constants.hpp>\nusing namespace boost::math;\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n    cout << setprecision(64);\n\n    auto a = float_constants::pi * 2 * 2;\n    cout << \"area \\t\\t= \" << a << endl;\n\n    using namespace double_constants;\n\n    auto x = root_two * root_three;\n    cout << \"root 2 * 3 \\t= \" << x << endl;\n\n    cout << \"root pi \\t= \" << root_pi << endl;\n    cout << \"pi pow e \\t= \" << pi_pow_e << endl;\n}\n\n//////////////////////////////////////////\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nvoid case2()\n{\n    using namespace constants;\n\n    typedef decltype(pi<float>) pi_t;\n    assert(is_function<pi_t>::value);\n\n    assert(pi<float>() == float_constants::pi);\n    assert(pi<double>() == double_constants::pi);\n\n    typedef boost::multiprecision::cpp_dec_float_100 float_100;\n    cout << setprecision(100)\n         << pi<float_100>() << endl;\n}\n\nint main()\n{\n    case1();\n    case2();\n}\n\n\n", "meta": {"hexsha": "d345868e2ef2de0431faed622d25f2980ea83948", "size": 1070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/math_constants.cpp", "max_stars_repo_name": "xujungp02/boost_guide", "max_stars_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 355.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T12:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:15:00.000Z", "max_issues_repo_path": "math/math_constants.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-04T18:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-09T02:38:12.000Z", "max_forks_repo_path": "math/math_constants.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 202.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T16:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:55:48.000Z", "avg_line_length": 20.1886792453, "max_line_length": 63, "alphanum_fraction": 0.5682242991, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6920782682940181}}
{"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_EULER_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Euler Euler (function template)\n\n  Generates an approximation of the Euler-Mascheroni constant.\n\n  @headerref{<boost/simd/constant/euler.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Euler();\n      @endcode\n\n  2.  @code\n      template<typename T> T Euler( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T evaluating to the Euler-Mascheroni constant defined as:\n  \\f$\\gamma = \\lim_{n \\rightarrow \\infty } \\left( 1+ \\frac{1}{2} + ... + \\frac{1}{n} - \\ln(n) \\right)\\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(0.57721566490153286060651209008240243104215933593992359)`\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/euler.hpp>\n#include <boost/simd/constant/simd/euler.hpp>\n\n#endif\n", "meta": {"hexsha": "450309bb5d577da23bf488a60ad1ae3d1f73d58c", "size": 1650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/euler.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/euler.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/euler.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": 31.7307692308, "max_line_length": 105, "alphanum_fraction": 0.5454545455, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6920255623956549}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <cmath>\n#include <boost/core/demangle.hpp>\n#include <boost/math/special_functions/gegenbauer.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing std::abs;\nusing boost::math::gegenbauer;\nusing boost::math::gegenbauer_derivative;\n\ntemplate<class Real>\nvoid test_parity()\n{\n    std::mt19937 gen(323723);\n    std::uniform_real_distribution<Real> xdis(-1, +1);\n    std::uniform_real_distribution<Real> lambdadis(-0.5, 1);\n\n    for(unsigned n = 0; n < 50; ++n) {\n        unsigned calls = 50;\n        unsigned i = 0;\n        while(i++ < calls) {\n            Real x = xdis(gen);\n            Real lambda = lambdadis(gen);\n            if (n & 1) {\n                CHECK_ULP_CLOSE(gegenbauer(n, lambda, -x), -gegenbauer(n, lambda, x), 0);\n            }\n            else {\n                CHECK_ULP_CLOSE(gegenbauer(n, lambda, -x), gegenbauer(n, lambda, x), 0);\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_quadratic()\n{\n    Real lambda = 1/Real(4);\n    auto c2 = [&](Real x) { return -lambda + 2*lambda*(1+lambda)*x*x; };\n\n    Real x = -1;\n    Real h = 1/Real(256);\n    while (x < 1) {\n        Real expected = c2(x);\n        Real computed = gegenbauer(2, lambda, x);\n        CHECK_ULP_CLOSE(expected, computed, 0);\n        x += h;\n    }\n}\n\ntemplate<class Real>\nvoid test_cubic()\n{\n    Real lambda = 1/Real(4);\n    auto c3 = [&](Real x) { return lambda*(1+lambda)*x*(-2 + 4*(2+lambda)*x*x/3); };\n\n    Real x = -1;\n    Real h = 1/Real(256);\n    while (x < 1) {\n        Real expected = c3(x);\n        Real computed = gegenbauer(3, lambda, x);\n        CHECK_ULP_CLOSE(expected, computed, 4);\n        x += h;\n    }\n}\n\ntemplate<class Real>\nvoid test_derivative()\n{\n    Real lambda = 0.5;\n    auto c3_prime = [&](Real x) { return 2*lambda*(lambda+1)*(-1 + 2*(lambda+2)*x*x); };\n    auto c3_double_prime = [&](Real x) { return 8*lambda*(lambda+1)*(lambda+2)*x; };\n    Real x = -1;\n    Real h = 1/Real(256);\n    while (x < 1) {\n        Real expected = c3_prime(x);\n        Real computed = gegenbauer_derivative(3, lambda, x, 1);\n        CHECK_ULP_CLOSE(expected, computed, 1);\n\n        expected = c3_double_prime(x);\n        computed = gegenbauer_derivative(3, lambda, x, 2);\n        CHECK_ULP_CLOSE(expected, computed, 1);\n\n        x += h;\n    }\n\n}\n\n\n\nint main()\n{\n    test_parity<float>();\n    test_parity<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_parity<long double>();\n#endif\n\n    test_quadratic<float>();\n    test_quadratic<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_quadratic<long double>();\n#endif\n\n    test_cubic<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_cubic<long double>();\n#endif\n\n    test_derivative<float>();\n    test_derivative<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_derivative<long double>();\n#endif\n\n#ifdef BOOST_HAS_FLOAT128\n    test_quadratic<boost::multiprecision::float128>();\n    test_cubic<boost::multiprecision::float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "aa684cea8f2b970ae4be4edee5cdd0183d213dc6", "size": 3416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gegenbauer_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/gegenbauer_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/gegenbauer_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 25.3037037037, "max_line_length": 89, "alphanum_fraction": 0.6267564403, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6920132703298424}}
{"text": "#include \"physics.hpp\"\n\n#include <Eigen/Geometry>\n\nphysics::physics()\n{\n\tthis->generator = std::mt19937_64(std::random_device{}());\n\n}\n\nphysics::~physics()\n{\n\n}\n\nvoid physics::step(double delta_t)\n{\n\ttotal_time += delta_t;\n\n\t// TODO: collision detection\n\t#pragma omp parallel for\n\tfor(int i = 0; i < obj_count; i++)\n\t{\n\t\t// Euler\n\t\t//a[current][i] = accel(x[current][i], i);\n\t\t//v[next][i] = a[current][i] * delta_t + v[current][i];\n\t\t//x[next][i] = v[next][i] * delta_t + x[current][i];\n\n\t\t// RK4 integration, see doc/grav_sim.tex\n\t\t// this is about 4x worse than Euler\n\t\tEigen::Vector3d xk1 = x[current][i];\n\t\tEigen::Vector3d vk1 = v[current][i];\n\t\tEigen::Vector3d ak1 = accel(xk1, i);\n\n\t\tEigen::Vector3d xk2 = x[current][i] + 0.5 * vk1 * delta_t;\n\t\tEigen::Vector3d vk2 = v[current][i] + 0.5 * ak1 * delta_t;\n\t\tEigen::Vector3d ak2 = accel(xk2, i);\n\n\t\tEigen::Vector3d xk3 = x[current][i] + 0.5 * vk2 * delta_t;\n\t\tEigen::Vector3d vk3 = v[current][i] + 0.5 * ak2 * delta_t;\n\t\tEigen::Vector3d ak3 = accel(xk3, i);\n\n\t\tEigen::Vector3d xk4 = x[current][i] + vk3 * delta_t;\n\t\tEigen::Vector3d vk4 = v[current][i] + ak3 * delta_t;\n\t\tEigen::Vector3d ak4 = accel(xk4, i);\n\n\t\tv[next][i] = v[current][i] + (delta_t / 6.0) *\n\t\t\t\t(ak1 + 2 * ak2 + 2 * ak3 + ak4);\n\t\tx[next][i] = x[current][i] + (delta_t / 6.0) *\n\t\t\t\t(vk1 + 2 * vk2 + 2 * vk3 + vk4);\n\t}\n\n\tcurrent = current ? 0 : 1;\n\tnext = next ? 0 : 1;\n}\n\nEigen::Vector3d physics::accel(Eigen::Vector3d x_i, uint16_t skip_index)\n{\n\tEigen::Vector3d a(0.0, 0.0, 0.0);\n\tfor(uint16_t j = 0; j < obj_count; j++)\n\t{\n\t\tif(skip_index == j)\n\t\t\tcontinue;\n\n\t\tEigen::Vector3d r = x[current][j] - x_i;\n\t\ta += G * m[j] * r.normalized() / r.squaredNorm();\n\t}\n\treturn a;\n}\n\nvoid physics::init(uint16_t obj_count)\n{\n\tthis->obj_count = obj_count;\n\n\tcurrent = 0;\n\tnext = 1;\n\ttotal_time = 0.0;\n\n\tx[0].resize(obj_count);\n\tx[1].resize(obj_count);\n\tv[0].resize(obj_count);\n\tv[1].resize(obj_count);\n\ta[0].resize(obj_count);\n\ta[1].resize(obj_count);\n\tr.resize(obj_count);\n\tm.resize(obj_count);\n\n\t// for now hard code some values\n\tmass_range[0] = 5e7;\n\tmass_range[1] = 1e8;\n\tradius_range[0] = 0.05;\n\tradius_range[1] = 0.25;\n\t//distance_range[0] = -radius_range[0] * 15.0;\n\t//distance_range[1] = radius_range[0] * 15.0;\n\tdistance_range[0] = -4.0;\n\tdistance_range[1] = 4.0;\n\n\t// random init stuff\n\tstd::uniform_real_distribution<double> dist_m(mass_range[0],\n\t\tmass_range[1]);\n\tstd::uniform_real_distribution<double> dist_r(radius_range[0],\n\t\tradius_range[1]);\n\tstd::uniform_real_distribution<double> dist_d(distance_range[0],\n\t\tdistance_range[1]);\n\n\tfor(uint16_t i = 0; i < obj_count; i++)\n\t{\n\t\tr[i] = dist_r(generator);\n\t\tm[i] = dist_m(generator);\n\n\t\t// TODO: detect and avoid collisions here\n\t\tbool collision = true;\n\t\twhile(collision)\n\t\t{\n\t\t\t// generate a new point\n\t\t\tx[0][i] = Eigen::Vector3d(dist_d(generator),\n\t\t\t\t\t\t\t\t\tdist_d(generator),\n\t\t\t\t\t\t\t\t\tdist_d(generator));\n\n\t\t\t// look for a collision\n\t\t\tcollision = false;\n\t\t\tfor(uint16_t j = 0; j < i; j++)\n\t\t\t{\n\t\t\t\tif(i == j)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// direction unit vector\n\t\t\t\tEigen::Vector3d ji_uv = (x[0][i] - x[0][j]).normalized();\n\n\t\t\t\t// position plus radius in the direction of the other object\n\t\t\t\tEigen::Vector3d ji_r = x[0][j] + ji_uv * r[j];\n\n\t\t\t\tdouble distance_j = (x[0][i] - ji_r).norm();\n\t\t\t\t// if radius > distance to j object then collision\n\t\t\t\tif(r[i] > distance_j)\n\t\t\t\t{\n\t\t\t\t\tcollision = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tv[0][i] = Eigen::Vector3d(0.0, 0.0, 0.0);\n\t\ta[0][i] = Eigen::Vector3d(0.0, 0.0, 0.0);\n\t}\n}\n\nvoid physics::deinit()\n{\n\t// TODO: should we really use swap to force a deallocation and is this the\n\t// right way to do it?\n\n\tstd::vector<Eigen::Vector3d> n0, n1;\n\tx[0].clear();\n\tx[1].clear();\n\tx[0].swap(n0);\n\tx[1].swap(n1);\n\n\tstd::vector<Eigen::Vector3d> n2, n3;\n\tv[0].clear();\n\tv[1].clear();\n\tv[0].swap(n2);\n\tv[1].swap(n3);\n\n\tstd::vector<Eigen::Vector3d> n4, n5;\n\ta[0].clear();\n\ta[1].clear();\n\ta[0].swap(n4);\n\ta[1].swap(n5);\n\n\tstd::vector<double> n6;\n\tr.clear();\n\tr.swap(n6);\n\n\tstd::vector<double> n7;\n\tm.clear();\n\tm.swap(n7);\n}\n\n\n", "meta": {"hexsha": "5716422e1b92b4e91ad01476f6276b7bcfdb2107", "size": 4028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "phy/physics.cpp", "max_stars_repo_name": "foxfire256/grav_sim", "max_stars_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "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": "phy/physics.cpp", "max_issues_repo_name": "foxfire256/grav_sim", "max_issues_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "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": "phy/physics.cpp", "max_forks_repo_name": "foxfire256/grav_sim", "max_forks_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "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.2541436464, "max_line_length": 75, "alphanum_fraction": 0.6112214499, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6920132703298424}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <gnuplot-iostream.h>\n#include \"../config.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\npair<vec, double> entrenarPerceptron(const mat& patrones,\n                                     const vec& salidaDeseada,\n                                     int nEpocas,\n                                     double tasaAprendizaje,\n                                     double tolerancia,\n                                     string tituloGrafica);\ndouble errorPerceptron(const vec& pesos,\n                   const mat& patrones,\n                   const vec& salidaDeseada);\n\nint main()\n{\n    arma_rng::set_seed_random();\n\n    mat datos;\n    datos.load(config::sourceDir + \"/guia1/icgtp1datos/OR_trn.csv\");\n    mat patronesEntOR = datos.head_cols(2);\n    vec salidaDeseadaEntOR = datos.tail_cols(1);\n    datos.load(config::sourceDir + \"/guia1/icgtp1datos/OR_tst.csv\");\n    mat patronesPruebaOR = datos.head_cols(2);\n    vec salidaDeseadaPruebaOR = datos.tail_cols(1);\n\n    // OR\n    // Entrenar la red graficando resultados intermedios (la recta)\n    vec pesos;\n    tie(pesos, ignore) = entrenarPerceptron(patronesEntOR,\n                                            salidaDeseadaEntOR,\n                                            100,\n                                            0.1,\n                                            5,\n                                            \"OR\");\n    double tasaError = errorPerceptron(pesos, patronesPruebaOR, salidaDeseadaPruebaOR);\n    cout << \"tasa de error del OR : \" << tasaError << endl;\n\n    // XOR\n    // Entrenar la red graficando resultados intermedios (la recta)\n    // Prueba\n    datos.load(config::sourceDir + \"/guia1/icgtp1datos/XOR_trn.csv\");\n    mat patronesEntXOR = datos.head_cols(2);\n    vec salidaDeseadaEntXOR = datos.tail_cols(1);\n    datos.load(config::sourceDir + \"/guia1/icgtp1datos/XOR_tst.csv\");\n    mat patronesPruebaXOR = datos.head_cols(2);\n    vec salidaDeseadaPruebaXOR = datos.tail_cols(1);\n\n    tie(pesos, ignore) = entrenarPerceptron(patronesEntXOR,\n                                            salidaDeseadaEntXOR,\n                                            100,\n                                            0.4,\n                                            30,\n                                            \"XOR\");\n    tasaError = errorPerceptron(pesos, patronesPruebaXOR, salidaDeseadaPruebaXOR);\n    cout << \"tasa de error del XOR : \" << tasaError << endl;\n\n    return 0;\n}\n\nnamespace ic {\nint sign(double numero)\n{\n    if (numero >= 0)\n        return 1;\n    else\n        return -1;\n}\n}\n\npair<vec, double> entrenarPerceptron(const mat& patrones,\n                                     const vec& salidaDeseada,\n                                     int nEpocas,\n                                     double tasaAprendizaje,\n                                     double tolerancia,\n                                     string tituloGrafica)\n{\n    // Inicializar pesos y tasa de error\n    vec pesos = randu<vec>(patrones.n_cols + 1) - 0.5;\n    double tasaError = 0;\n\n    // Extender las matrices de patrones con la entrada correspondiente al umbral\n    const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);\n\n    // Separar patrones de entrenamiento en casos verdaderos y falsos\n    // para graficarlos en colores distintos\n    const mat verdaderos = patrones.rows(find(salidaDeseada == 1));\n    const mat falsos = patrones.rows(find(salidaDeseada == -1));\n\n    // Objeto para graficar\n    Gnuplot gp;\n    // Caracter usado para dejar de graficar\n    const char caracterSalteo = 's';\n    char caracter = ' ';\n\n    // Ciclo de las epocas\n    for (int epoca = 1; epoca <= nEpocas; ++epoca) {\n        // Ciclo para una \u00e9poca\n        for (unsigned int i = 0; i < patrones.n_rows; ++i) {\n            double z = dot(patronesExt.row(i), pesos);\n            int y = ic::sign(z);\n\n            if (caracter != caracterSalteo) {\n                cout << \"Patr\u00f3n que entr\u00f3: \" << patrones.row(i)\n                     << \"Salida para ese patr\u00f3n: \" << y << '\\n'\n                     << \"Salida deseada: \" << salidaDeseada(i) << endl;\n\n                caracter = getchar();\n            }\n\n            // Actualizar pesos\n            // Tener en cuenta el orden en que colocamos la salida por la direccion del gradiente.\n            pesos += tasaAprendizaje * 0.5 * (salidaDeseada(i) - y) * patronesExt.row(i).t();\n\n            // Graficar recta\n            double pendiente = -pesos(1) / pesos(2);\n            double ordenadaOrigen = pesos(0) / pesos(2);\n            mat puntosRecta = {{-2, -2 * pendiente + ordenadaOrigen},\n                               {2, 2 * pendiente + ordenadaOrigen}};\n\n            if (caracter != caracterSalteo) {\n                gp << \"set title '\" << tituloGrafica << \"' font ',13'\\n\"\n                   << \"set xlabel 'x_1'\\n\"\n                   << \"set ylabel 'x_2'\\n\"\n                   << \"set grid\\n\"\n                   << \"unset key\\n\"\n                   << \"plot \" << gp.file1d(verdaderos) << \"with points, \"\n                   << gp.file1d(falsos) << \"with points, \"\n                   << gp.file1d(puntosRecta) << \"with lines\" << endl;\n            }\n        }\n        // Fin ciclo (\u00e9poca)\n\n        // Parte de validaci\u00f3n - C\u00e1lculo de la tasa de error para ver si dejamos de entrenar\n        int errores = 0;\n\n        for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n            double z = dot(patronesExt.row(i), pesos);\n            int y = ic::sign(z);\n\n            if (y != salidaDeseada(i))\n                ++errores;\n        }\n\n        tasaError = static_cast<double>(errores) / patrones.n_rows * 100;\n        if (tasaError < tolerancia)\n            break;\n    }\n    // Fin ciclo (epocas)\n\n    return {pesos, tasaError};\n}\n\ndouble errorPerceptron(const vec& pesos,\n                   const mat& patrones,\n                   const vec& salidaDeseada)\n{\n    // Se extiende la matriz de patrones con la entrada correspondiente al umbral\n    const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);\n\n    int errores = 0;\n\n    for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n        double z = dot(patronesExt.row(i), pesos);\n        int y = ic::sign(z);\n\n        if (y != salidaDeseada(i))\n            ++errores;\n    }\n\n    double tasaError = static_cast<double>(errores) / patronesExt.n_rows * 100;\n\n    return tasaError;\n}\n", "meta": {"hexsha": "1daeb8a58c4dc8cdac36dca52cf6509a8926856b", "size": 6405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/ejercicio1.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": "guia1/ejercicio1.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": "guia1/ejercicio1.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": 35.782122905, "max_line_length": 98, "alphanum_fraction": 0.5245901639, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6919426162475755}}
{"text": "#include \"DarkART/Special_Functions.hpp\"\n\n#include <algorithm>\n#include <iostream>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_sf_coulomb.h>\n#include <gsl/gsl_sf_coupling.h>\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\n#include \"arb_hypgeom.h\"\n\nnamespace DarkART\n{\n// using namespace std::complex_literals;\n\n// 1. Gaunt coefficients\ndouble Gaunt_Coefficient(int j1, int j2, int j3, int m1, int m2, int m3)\n{\n\treturn sqrt((2.0 * j1 + 1.0) * (2.0 * j2 + 1.0) * (2.0 * j3 + 1.0)) / sqrt(4.0 * M_PI) * gsl_sf_coupling_3j(2 * j1, 2 * j2, 2 * j3, 0, 0, 0) * gsl_sf_coupling_3j(2 * j1, 2 * j2, 2 * j3, 2 * m1, 2 * m2, 2 * m3);\n}\n\n// 2. Spherical Bessel function j_L\ndouble Spherical_Bessel_jL_arb(int L, double x)\n{\n\tdouble prefactor = sqrt(M_PI / 2.0 / x);\n\tdouble result;\n\tslong prec;\n\tarb_t J_arb, x_arb, n_arb;\n\tarb_init(J_arb);\n\tarb_init(x_arb);\n\tarb_init(n_arb);\n\tarb_set_d(x_arb, x);\n\tarb_set_d(n_arb, 1.0 * L + 0.5);\n\tfor(prec = 80;; prec *= 2)\n\t{\n\t\tarb_hypgeom_bessel_j(J_arb, n_arb, x_arb, prec);\n\t\tif(arb_rel_accuracy_bits(J_arb) >= 53)\n\t\t{\n\t\t\tresult = arf_get_d(arb_midref(J_arb), ARF_RND_NEAR);\n\t\t\tbreak;\n\t\t}\n\t\telse if(prec > 10000)\n\t\t{\n\t\t\tresult = NAN;\n\t\t\tbreak;\n\t\t}\n\t}\n\tarb_clear(J_arb);\n\tarb_clear(n_arb);\n\tarb_clear(x_arb);\n\treturn prefactor * result;\n}\n\ndouble Spherical_Bessel_jL(int L, double x)\n{\n\tif(L < 10)\n\t\treturn gsl_sf_bessel_jl(L, x);\n\telse\n\t\treturn Spherical_Bessel_jL_arb(L, x);\n}\n\n// 3. Coulomb wave\ndouble Coulomb_Wave_ARB(int L, double eta, double rho)\n{\n\tdouble result;\n\tslong prec;\n\tarb_t F, l, eta_2, rho_2;\n\tarb_init(F);\n\tarb_init(l);\n\tarb_init(eta_2);\n\tarb_init(rho_2);\n\tarb_set_d(l, L);\n\tarb_set_d(eta_2, eta);\n\tarb_set_d(rho_2, rho);\n\tfor(prec = 80;; prec *= 2)\n\t{\n\t\tarb_hypgeom_coulomb(F, NULL, l, eta_2, rho_2, prec);\n\t\tif(arb_rel_accuracy_bits(F) >= 53)\n\t\t{\n\t\t\tresult = arf_get_d(arb_midref(F), ARF_RND_NEAR);\n\t\t\tbreak;\n\t\t}\n\t\telse if(prec > 10000)\n\t\t{\n\t\t\tresult = NAN;\n\t\t\tbreak;\n\t\t}\n\t}\n\tarb_clear(F);\n\tarb_clear(eta_2);\n\tarb_clear(rho_2);\n\tarb_clear(l);\n\treturn result;\n}\n\ndouble Coulomb_Wave_GSL(int L, double eta, double rho, int& status)\n{\n\tdouble fc_array[1];\n\tdouble F_exponent[1];\n\tstatus = gsl_sf_coulomb_wave_F_array(L, 0, eta, rho, fc_array, F_exponent);\n\treturn fc_array[0];\n}\n\ndouble Coulomb_Wave(int L, double eta, double rho)\n{\n\tint status;\n\tdouble cw = Coulomb_Wave_GSL(L, eta, rho, status);\n\tif(status != 0 || std::isnan(cw))\n\t\tcw = Coulomb_Wave_ARB(L, eta, rho);\n\treturn cw;\n}\n\n}\t// namespace DarkART", "meta": {"hexsha": "d46530d3a6bf1c63901c1a4ae6112cbec91504a7", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Special_Functions.cpp", "max_stars_repo_name": "temken/DarkART", "max_stars_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-15T13:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T13:58:28.000Z", "max_issues_repo_path": "src/Special_Functions.cpp", "max_issues_repo_name": "temken/DarkART", "max_issues_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_issues_repo_licenses": ["MIT"], "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/Special_Functions.cpp", "max_forks_repo_name": "temken/DarkART", "max_forks_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_forks_repo_licenses": ["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.5948275862, "max_line_length": 211, "alphanum_fraction": 0.6758483034, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6919419125917671}}
{"text": "#include <iostream>\n// #include <Eigen/Eigenvalues>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include \"include/parser.h\"\n// using namespace Spectra;\n\nint main()\n{\n    std::string S_file, M_file, L_file;\n    S_file = \"../assets/S_soc-karate.mtx\";\n    M_file = \"../assets/M_web-edu.csv\";\n    L_file = \"../assets/L_tech-internet-as.mtx\";\n\n    // Eigen::MatrixXd S_mat = Eigen::MatrixXd::Zero(10, 10);\n    // for(int i=0; i<10; i++){\n    //     for(int j=0; j<10; j++){\n    //         S_mat(i, j) = 1;\n    //     }\n    // }\n\n    // Eigen::MatrixXd S_mat = parser::readMTXFiletoDense(L_file);\n    Eigen::MatrixXd S_mat = parser::readCSVFiletoDense(M_file);\n    // std::cout << S_mat << \"\\n\";\n    Eigen::EigenSolver<Eigen::MatrixXd> es(S_mat, false);\n    std::cout << \"The eigenvalues of the 10x10 matrix of ones are:\" \n     << std::endl << es.eigenvalues() << std::endl;\n\n    // // Eigen::SparseMatrix<double> * d = new Eigen::SparseMatrix<double>(data);\n    // Eigen::SparseMatrix<double> M_mat = parser::readCSVFile(M_file);\n    // Eigen::SparseMatrix<double> L_mat = parser::readMTXFile(L_file);\n\n    // Spectra::SparseGenMatProd<double> XS_op(XS_mat);\n    // Spectra::SparseSymMatProd<double> S_op(S_mat);\n    // Spectra::SparseSymMatProd<double> M_op(M_mat);\n    // Spectra::SparseSymMatProd<double> L_op(L_mat);\n\n    // Construct eigen solver object, requesting the largest three eigenvalues\n    // Spectra::GenEigsSolver<Spectra::SparseGenMatProd<double>> XS_eigs(XS_op, 8, 10);\n    // Spectra::SymEigsSolver<Spectra::SparseSymMatProd<double>> S_eigs(S_op, 33, 34);\n    // Spectra::SymEigsSolver<Spectra::SparseSymMatProd<double>> M_eigs(M_op, 3, 6);\n    // Spectra::SymEigsSolver<Spectra::SparseSymMatProd<double>> L_eigs(L_op, 3, 6);\n\n    // Initialize and compute\n    // XS_eigs.init(); \n    // S_eigs.init();\n    // M_eigs.init();\n    // L_eigs.init();\n\n    // int XS_nconv = XS_eigs.compute(Spectra::SortRule::LargestReal);\n    // int S_nconv = S_eigs.compute(Spectra::SortRule::LargestMagn);\n    // int M_nconv = M_eigs.compute(Spectra::SortRule::LargestMagn);\n    // int L_nconv = L_eigs.compute(Spectra::SortRule::LargestMagn);\n\n    // Retrieve results\n    // Eigen::VectorXcd evalues;\n\n    // std::cout << XS_mat;\n    // std::cout << \"\\nX Small : \" << XS_mat.nonZeros()<< \"\\n\\n\";\n    // std::cout << XS_eigs.eigenvectors() << \"\\n\";\n    // if (XS_eigs.info() == Spectra::CompInfo::Successful)\n    //     evalues = XS_eigs.eigenvalues();\n    // std::cout << \"Eigenvalues found for XS :\\n\"\n    //           << evalues << std::endl;\n\n    // std::cout << \"\\nSmall : \" << S_mat.nonZeros() / 2 << \"\\n\";\n    // std::cout << S_eigs.eigenvectors() << \"\\n\";\n    // if (S_eigs.info() == Spectra::CompInfo::Successful)\n    //     evalues = S_eigs.eigenvalues();\n    // std::cout << \"Eigenvalues found for S :\\n\"\n    //           << evalues << std::endl;\n\n    // std::cout << \"\\nMedium : \" << M_mat.nonZeros() / 2 << \"\\n\";\n    // if (M_eigs.info() == Spectra::CompInfo::Successful)\n    //     evalues = M_eigs.eigenvalues();\n    // std::cout << \"Eigenvalues found for M :\\n\"\n    //           << evalues << std::endl;\n\n    // std::cout << \"\\nLarge : \" << L_mat.nonZeros() / 2 << \"\\n\";\n    // if (L_eigs.info() == Spectra::CompInfo::Successful)\n    //     evalues = L_eigs.eigenvalues();\n    // std::cout << \"Eigenvalues found for L :\\n\"\n    //           << evalues << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "9e931b8d567944d5b745cd509a28bb8d8baa54e9", "size": 3508, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp-src/main.cc", "max_stars_repo_name": "appmonster007/project-megraphs", "max_stars_repo_head_hexsha": "7e32af817f49804a17dbfd729e5afaef50fa95f7", "max_stars_repo_licenses": ["MIT"], "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/main.cc", "max_issues_repo_name": "appmonster007/project-megraphs", "max_issues_repo_head_hexsha": "7e32af817f49804a17dbfd729e5afaef50fa95f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-09-05T05:41:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T07:12:49.000Z", "max_forks_repo_path": "cpp-src/main.cc", "max_forks_repo_name": "appmonster007/project-megraphs", "max_forks_repo_head_hexsha": "7e32af817f49804a17dbfd729e5afaef50fa95f7", "max_forks_repo_licenses": ["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.8636363636, "max_line_length": 87, "alphanum_fraction": 0.608608894, "num_tokens": 1087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6919419021217896}}
{"text": "/*\n * prime_utils.cpp: Function definitions for working with primes. The following\n * methods are defined here:\n *     - Miller-Rabin probabilistic primality test, with an iterative tester\n *       method\n *     - Modular addition, which is used by modular multiplication\n *     - Modular multiplication and exponentiation, which are used by the\n *       Miller-Rabin test\n *     - Sieve of Atkin\n *     - Integer square root, which is used by the Sieve\n *\n * Version:     1.0.0\n * License:     MIT License (see LICENSE.txt for more details)\n * Author:      Joshua Morrison (MrM21632)\n * Last Edited: 2/6/2018, 1:20am\n */\n\n#include <cstdlib>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include \"prime_utils.h\"\n\n\nuint64_t isqrt(uint64_t n) {\n    // Base Case: if n < 2, then sqrt(n) = n.\n    if (n < 2) return n;\n    \n    // We calculate a \"small\" and \"large\" candidate for our return value:\n    //     1. s, which is equal to 2 * isqrt(n / 4), is the small candidate.\n    //     2. l, which is equal to one larger than s, is the large candidate.\n    uint64_t s = isqrt(n >> 2) << 1;\n    uint64_t l = s + 1;\n    \n    if (l*l > n)\n        return s;\n    else\n        return l;\n}\n\n\nuint64_t mod_add(uint64_t a, uint64_t b, uint64_t n) {\n    return ((a % n) + (b % n)) % n;\n}\n\n\nuint64_t mod_mult(uint64_t a, uint64_t b, uint64_t n) {\n    uint64_t r = 0;  // Remainder\n    \n    // If a is larger than the modulus, we need to reduce it in order to avoid\n    // integer overflow.\n    if (a >= n) a %= n;\n    \n    // Perform modular addition on r until the multiplier is 0.\n    while (b > 0) {\n        if (b & 1)\n            r = mod_add(r, a, n);\n        \n        a = (a * 2) % n;\n        b >>= 1;\n    }\n    \n    // (a * b) mod n == ((a mod n) * (b mod n)) mod n. At this point, we have\n    // calculated r = (a mod n) * (b mod n), so we now need to reduce r by mod\n    // n, then return that result.\n    return r % n;\n}\n\n\nuint64_t mod_pow(uint64_t a, uint64_t b, uint64_t n) {\n    uint64_t r = 1;  // Remainder\n    \n    // If a is larger than the modulus, we need to reduce it in order to avoid\n    // integer overflow.\n    if (a >= n) a %= n;\n    \n    // Perform modular multiplication on both the remainder and the base, until\n    // our exponent is 0.\n    while (b > 0) {\n        if (b & 1)\n            r = mod_mult(r, a, n);\n        \n        a = mod_mult(a, a, n);\n        b >>= 1;\n    }\n    \n    return r;\n}\n\n\nbool miller_rabin(uint64_t n, uint64_t d) {\n    boost::random::random_device rd;\n    boost::random::mt19937 mt(rd());\n    boost::random::uniform_int_distribution<uint64_t> dist(2, n-2);\n    \n    uint64_t a = dist(mt);\n    uint64_t x = mod_pow(a, d, n);\n    \n    // Base Case: if a^d mod n is 1 or n-1, then we already know n is prime, so\n    // we can return true.\n    if (x == 1 || x == n-1)\n        return true;\n    \n    // Perform modular multiplication on x until d is equal to n-1.\n    while (d != (n - 1)) {\n        x = mod_mult(x, x, n);\n        d <<= 1;\n        \n        if (x == 1) return false;\n        if (x == (n - 1)) return true;\n    }\n    \n    // If we reach this point, we can safely say that n is not prime, so we\n    // return false.\n    return false;\n}\n\n\nbool is_prime(uint64_t n, uint64_t k) {\n    // Base cases\n    if (n <= 1) return false;\n    if (n <= 3) return true;\n    if (!(n & 1)) return false;\n    \n    // At this point, we know n is odd and greater than 1. Now, our goal is to\n    // find an integer d such that n-1 = d * 2^r, where r >= 1. The loop divides\n    // d by 2 until it is no longer even - at that point, we will have the value\n    // we desire.\n    uint64_t d = n - 1;\n    while (!(d & 1))\n        d >>= 1;\n    \n    // Call miller_rabin(n, d) k times. If any of the tests fail, we know that n\n    // is not prime, so we return false.\n    for (uint64_t i = 0; i < k; ++i) {\n        if (!miller_rabin(n, d))\n            return false;\n    }\n    \n    // If we reach this point, we can safely assume (NOT guarantee!) n is prime,\n    // so we return true.\n    return true;\n}\n\n\nbool *sieve_of_atkin(uint64_t n) {\n    bool *data = new bool[n + 1]();\n    data[2] = true;\n    data[3] = true;\n    uint64_t lim = isqrt(n);\n    \n    // This loop runs for all x in [1, lim].\n    for (uint64_t x = 1; x <= lim; ++x) {\n        // This loop runs for all y in [1, lim].\n        // \n        // k is prime if any of the following are true:\n        //     1. For k = 4*x^2 + y^2, k is prime iff k mod 12 = 1 or 5.\n        //     2. For k = 3*x^2 + y^2, k is prime iff k mod 12 = 7.\n        //     3. For k = 3*x^2 - y^2, k is prime iff k mod 12 = 11.\n        // All of these also assume that k is not greater than n, and for the\n        // third case, that k is not negative (i.e., that x > y).\n        for (uint64_t y = 1; y <= lim; ++y) {\n            uint64_t k = (4*x*x) + (y*y);\n            if ((k <= n) && ((k % 12 == 1) || (k % 12 == 5)))\n                data[k] = !data[k];\n            \n            k = (3*x*x) + (y*y);\n            if ((k <= n) && (k % 12 == 7))\n                data[k] = !data[k];\n            \n            k = (3*x*x) - (y*y);\n            if ((x > y) && (k <= n) && (k % 12 == 11))\n                data[k] = !data[k];\n        }\n    }\n    \n    // This loop runs for all j in [5, lim].\n    // \n    // We perform one last loop through the array. If j is prime, then we mark\n    // all multiples of its square as composite, a la the standard Sieve of\n    // Eratosthenes.\n    for (uint64_t j = 5; j <= lim; ++j) {\n        if (data[j]) {\n            for (uint64_t k = j*j; k <= n; k += j*j)\n                data[k] = false;\n        }\n    }\n    \n    return data;\n}\n", "meta": {"hexsha": "95273a467815072971a649109aa36011ca1d4dbb", "size": 5709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "factor/prime_utils.cpp", "max_stars_repo_name": "MrM21632/WinUtils", "max_stars_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "factor/prime_utils.cpp", "max_issues_repo_name": "MrM21632/WinUtils", "max_issues_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factor/prime_utils.cpp", "max_forks_repo_name": "MrM21632/WinUtils", "max_forks_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.890052356, "max_line_length": 80, "alphanum_fraction": 0.5274128569, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.691863893358926}}
{"text": "#include <metaSMT/frontend/QF_BV.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <string>\n\nusing namespace std;\nusing namespace metaSMT;\nusing namespace metaSMT::logic;\nusing namespace metaSMT::logic::QF_BV;\nnamespace proto = boost::proto;\nusing boost::dynamic_bitset;\n\nBOOST_FIXTURE_TEST_SUITE(QF_BV, Solver_Fixture )\n\nBOOST_AUTO_TEST_CASE( negative_t )\n{\n   const char w = 32;\n\n   bitvector x = new_bitvector(w);\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal(bvsint(-1, w), x) );\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   int xd = read_value(ctx, x);\n   BOOST_CHECK_EQUAL(xd, -1);\n}\n\nBOOST_AUTO_TEST_CASE( negative_multiply_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, equal( x, bvmul( bvsint(1, w), bvsint(-1, w) ) ) ); \n\n  BOOST_REQUIRE( solve(ctx) );\n\n  signed char xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL( (int) xd, (int)-1 );\n}\n\nBOOST_AUTO_TEST_CASE( simple_sat )\n{\n  BOOST_REQUIRE( solve(ctx) );\n  // sat\n  assertion( ctx, equal(bit1,bit1));\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, equal(bit1, bvuint(1,1)) );\n  BOOST_REQUIRE( solve(ctx) );\n  assertion( ctx, equal(bit1, bvsint(-1,1)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, equal(bit1, bvbin(\"1\")) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  // unsat\n  assumption( ctx, equal(bit1, bit0) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, equal(bit1, bvuint(0,1)) );\n  BOOST_REQUIRE( !solve(ctx) );\n  assumption( ctx, equal(bit1, bvsint(0,1)) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, equal(bit1, bvbin(\"0\")) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n}\n\nBOOST_AUTO_TEST_CASE( incremental )\n{\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(bit0, bit1));\n  BOOST_REQUIRE( !solve(ctx) );\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( equal_t )\n{\n  bitvector x = new_bitvector(1);\n  bitvector y = new_bitvector(1);\n  // equal\n  assumption( ctx, equal(x, x));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(x, x));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(x, bit1));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(x, bit0));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(x, y));\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal(bit1, bvnot(bit0)) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal(bit0, bvnot(bit1)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal(bit0, bvnot(bvnot(bit0))) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal(bit1, bvnot(bvnot(bit1))) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  // nequal\n  assumption( ctx, equal(bit1, bit0));\n  BOOST_REQUIRE( !solve(ctx) );\n  assumption( ctx, equal(bit0, bit1));\n  BOOST_REQUIRE( !solve(ctx) );\n  assumption( ctx, equal(x, bvnot(x)));\n  BOOST_REQUIRE( !solve(ctx) );\n  assumption( ctx, equal(bvnot(x), x));\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( nequal_t )\n{\n  bitvector x = new_bitvector(1);\n  bitvector y = new_bitvector(1);\n  // equal\n  assumption( ctx, nequal(x, x));\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, nequal(bit1, bvnot(bit0)) );\n  BOOST_REQUIRE( !solve(ctx) );\n  assumption( ctx, nequal(bit0, bvnot(bit1)) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, nequal(bit0, bvnot(bvnot(bit0))) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, nequal(bit1, bvnot(bvnot(bit1))) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, nequal(x, y));\n  BOOST_REQUIRE( solve(ctx) );\n\n  // nequal\n  assumption( ctx, nequal(x, bit1));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal(x, bit0));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal(bit1, bit0));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal(bit0, bit1));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal(x, bvnot(x)));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal(bvnot(x), x));\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bin_constant_t )\n{\n\n  assumption(ctx, equal( bvbin(\"0\"), bvuint(0, 1) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"1\"), bvuint(1, 1) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"0000\"), bvuint(0, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"0011\"), bvuint(3, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"1010\"), bvuint(10, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"1111\"), bvuint(15, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"11111111\"), bvuint(255,8) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, nequal( bvbin(\"11111111\"), bvuint(255,8) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption(ctx, equal( bvbin(\"11110000\"), bvuint(240,8) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, nequal( bvbin(\"11110000\"), bvuint(240,8) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  bitvector x = new_bitvector(8);\n\n  assumption(ctx, equal( x,  bvbin(\"10100011\") ) );\n  BOOST_REQUIRE( solve(ctx) );\n  unsigned u = read_value(ctx, x);\n  BOOST_REQUIRE_EQUAL( u, 163u);\n  assumption(ctx, nequal( bvbin(\"10100011\"), bvuint(163,8) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( hex_constant_t )\n{\n\n  assumption(ctx, equal( bvhex(\"0\"), bvuint(0, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"1\"), bvuint(1, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"2\"), bvuint(2, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"3\"), bvuint(3, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"4\"), bvuint(4, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"5\"), bvuint(5, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"6\"), bvuint(6, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"7\"), bvuint(7, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"8\"), bvuint(8, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"9\"), bvuint(9, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"a\"), bvuint(10, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"A\"), bvuint(10, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"b\"), bvuint(11, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"B\"), bvuint(11, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"c\"), bvuint(12, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"C\"), bvuint(12, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"d\"), bvuint(13, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"D\"), bvuint(13, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"e\"), bvuint(14, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"E\"), bvuint(14, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"f\"), bvuint(15, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, equal( bvhex(\"F\"), bvuint(15, 4) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n\n\n\n  bitvector x = new_bitvector(8);\n  assumption(ctx, equal( bvhex(\"FF\"), bvbin(\"11111111\") ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, nequal( bvhex(\"FF\"), bvbin(\"11111111\") ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption(ctx, equal( bvhex(\"F0\"), bvuint(240,8) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, nequal( bvhex(\"F0\"), bvuint(240,8) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n\n  assumption(ctx, equal( x,  bvhex(\"A3\") ) );\n  BOOST_REQUIRE( solve(ctx) );\n  unsigned u = read_value(ctx, x);\n  BOOST_REQUIRE_EQUAL( u, 163u);\n  assumption(ctx, nequal( bvhex(\"A3\"), bvuint(163,8) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( read_value_eq_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(1);\n  bitvector y = new_bitvector(1);\n\n  assertion( ctx, equal(x, y) );\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  // bool value\n  bool xb = read_value (ctx, x);\n  bool yb = read_value (ctx, y);\n\n  BOOST_CHECK_EQUAL( xb, yb );\n\n  // vector bool\n  vector<bool> xvb = read_value(ctx, x);\n  vector<bool> yvb = read_value(ctx, y);\n\n  BOOST_CHECK( xvb.size() == 1u );\n  BOOST_CHECK( yvb.size() == 1u );\n  BOOST_CHECK_EQUAL( xvb.at(0), yvb.at(0) );\n\n  // vector tribool\n  vector<tribool> xvt = read_value(ctx, x);\n  vector<tribool> yvt = read_value(ctx, y);\n \n  BOOST_CHECK_EQUAL( xvt.size(), 1u );\n  BOOST_CHECK_EQUAL( yvt.size(), 1u );\n  BOOST_CHECK_EQUAL( xvt.at(0), yvt.at(0) );\n  \n  // dynamic_bitset\n  dynamic_bitset<> xd = read_value(ctx, x);\n  dynamic_bitset<> yd = read_value(ctx, y);\n  BOOST_CHECK_EQUAL( xd.size(), 1u );\n  BOOST_CHECK_EQUAL( yd.size(), 1u );\n  BOOST_CHECK_EQUAL( xd[0], yvt[0] );\n\n  // string\n  string xs = read_value(ctx, x);\n  string ys = read_value(ctx, y);\n  BOOST_CHECK_EQUAL( xs, ys );\n}\n\nBOOST_AUTO_TEST_CASE( read_value_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(1);\n  bitvector y = new_bitvector(1);\n\n  assertion( ctx, nequal(x, y) );\n  // add some constraints so that it will not be optimized away\n  assertion( ctx, equal(equal(x,x),equal(y,y)) );\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  // bool value\n  bool xb = read_value (ctx, x);\n  bool yb = read_value (ctx, y);\n\n  BOOST_CHECK_NE( xb, yb );\n\n  // vector bool\n  vector<bool> xvb = read_value(ctx, x);\n  vector<bool> yvb = read_value(ctx, y);\n\n  BOOST_CHECK_EQUAL( xvb.size(), 1u );\n  BOOST_CHECK_EQUAL( yvb.size(), 1u );\n  BOOST_CHECK_NE( xvb.at(0), yvb.at(0) );\n\n  // vector tribool\n  vector<tribool> xvt = read_value(ctx, x);\n  vector<tribool> yvt = read_value(ctx, y);\n \n  BOOST_CHECK_EQUAL( xvt.size(), 1u );\n  BOOST_CHECK_EQUAL( yvt.size(), 1u );\n  BOOST_CHECK_NE( xvt.at(0), yvt.at(0) );\n\n  // dynamic_bitset\n  dynamic_bitset<> xd = read_value(ctx, x);\n  dynamic_bitset<> yd = read_value(ctx, y);\n  BOOST_CHECK_EQUAL( xd.size(), 1u );\n  BOOST_CHECK_EQUAL( yd.size(), 1u );\n  BOOST_CHECK_NE( xd[0], yvt[0] );\n\n  // string\n  string xs = read_value(ctx, x);\n  string ys = read_value(ctx, y);\n  BOOST_CHECK_NE( xs, ys );\n}\n\nBOOST_AUTO_TEST_CASE( bvand_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(2);\n  bitvector y = new_bitvector(2);\n  bitvector z = new_bitvector(2);\n  short xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvand(x,y), z) );\n  assumption( ctx, equal( z, bvbin(\"01\")) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( (xd&yd), zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvneg_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(8);\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvneg(bvneg(x)), x) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, nequal( bvneg(bvneg(x)), x) );\n  BOOST_REQUIRE( !solve(ctx) );\n  \n  assumption( ctx, equal( bvneg(x), bvadd(bvnot(x), bvuint(1,8))) );\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, nequal( bvneg(x), bvadd(bvnot(x), bvuint(1,8))) );\n  BOOST_REQUIRE( !solve(ctx) );\n  \n  \n  assumption(ctx, equal( bvneg( bvuint(87, 8)), bvsint(-87, 8)));\n  BOOST_REQUIRE( solve(ctx) );\n  assumption(ctx, nequal( bvneg( bvuint(87, 8)), bvsint(-87, 8)));\n  BOOST_REQUIRE( !solve(ctx) );\n\n\n}\n\nBOOST_AUTO_TEST_CASE( bvnand_t )\n{\n  using namespace boost::logic;\n\n  const unsigned w = sizeof(short)*8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  dynamic_bitset<> xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvnand(x,y), z) );\n  assumption( ctx, equal( z, bvuint(1, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( ~(xd&yd), zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvor_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(2);\n  bitvector y = new_bitvector(2);\n  bitvector z = new_bitvector(2);\n  dynamic_bitset<> xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvor(x,y), z) );\n  assumption( ctx, equal( z, bvbin(\"01\")) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( (xd|yd), zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvxor_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(2);\n  bitvector y = new_bitvector(2);\n  bitvector z = new_bitvector(2);\n  dynamic_bitset<> xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvxor(x,y), z) );\n  assumption( ctx, equal( z, bvbin(\"10\")) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( (xd^yd), zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvnor_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(2);\n  bitvector y = new_bitvector(2);\n  bitvector z = new_bitvector(2);\n  dynamic_bitset<> xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvnor(x,y), z) );\n  assumption( ctx, equal( z, bvbin(\"10\")) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( ~(xd|yd), zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvxnor_t )\n{\n  using namespace boost::logic;\n\n  bitvector x = new_bitvector(2);\n  bitvector y = new_bitvector(2);\n  bitvector z = new_bitvector(2);\n  dynamic_bitset<> xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvxnor(x,y), z) );\n  assumption( ctx, equal( z, bvbin(\"10\")) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_CHECK_EQUAL( (~xd^yd), zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvadd_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvadd(x,y), z) );\n  assumption( ctx, equal( z, bvuint(135, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  unsigned char r = xd+yd;\n\n  BOOST_REQUIRE_EQUAL( 135, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvsub_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd, r;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvsub(x,y), z) );\n  assumption( ctx, equal( z, bvuint(135, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  r = xd-yd;\n  BOOST_REQUIRE_EQUAL( 135, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n\n}\n\nBOOST_AUTO_TEST_CASE( bvsub_2 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n\n  unsigned xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvadd(bvsub(x,y),y), x) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_EQUAL( (xd-yd)+yd, xd );\n\n  assumption( ctx, nequal( bvadd(bvsub(x,y),y), x) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvmul_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvmul(x,y), z) );\n  assumption( ctx, equal( z, bvuint(135, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  unsigned char r = xd*yd;\n\n  BOOST_REQUIRE_EQUAL( 135, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvudiv_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvudiv(x,y), z) );\n  assumption( ctx, nequal( bvuint(0,w), y) );\n  assumption( ctx, equal( z, bvuint(7, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( 7, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvudiv_250_1 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal( bvudiv(x,y), z) );\n  assumption( ctx, equal( bvuint(1,w), y) );\n  assumption( ctx, equal( bvuint(250,w), x) );\n  BOOST_REQUIRE( solve(ctx) );\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd/yd;\n\n  BOOST_CHECK_EQUAL( (unsigned)r, (unsigned)zd);\n}\n\n\nBOOST_AUTO_TEST_CASE( bvudiv_2 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n  \n  assumption( ctx, equal( bvudiv(x,y), z) );\n  \n  assumption( ctx, nequal( bvuint(0,w), y) );\n // assumption( ctx, equal( bvuint(7,w), x) );\n  assumption( ctx, nequal( bvuint(0,w), y) );\n//  assumption( ctx, equal( bvuint(35,w), y) );\n  //assumption( ctx, equal( bvuint(2,w), y) );\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd/yd;\n\n  //BOOST_REQUIRE_EQUAL( 7, zd);\n  \n  BOOST_CHECK_EQUAL( (unsigned)r, (unsigned)zd);\n}\n\n\nBOOST_AUTO_TEST_CASE( bvudiv_3 )\n{\n  using namespace boost::logic;\n\n  const char w = 6;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n  assumption( ctx, equal( bvudiv(x,y), z) );\n  assumption( ctx, nequal( bvuint(0,w), y) );\n  BOOST_REQUIRE( solve(ctx) );\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd/yd;\n\n  BOOST_CHECK_EQUAL( (unsigned)r, (unsigned)zd);\n}\n\n\nBOOST_AUTO_TEST_CASE( bvsdiv_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  signed char xd, yd, zd, r;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvsdiv(x,y), z) );\n  assumption( ctx, nequal( bvsint(0,w), y) );\n  assumption( ctx, equal( z, bvsint(7, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( 7, zd);\n  BOOST_CHECK_EQUAL( static_cast<int>(r), static_cast<int>(zd) );\n\n  assumption( ctx, equal( bvsdiv(x,y), z) );\n  assumption( ctx, nequal( bvsint(0,w), y) );\n  assumption( ctx, equal( z, bvsint(-7, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( -7, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvsdiv_39_5 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  signed char xd, yd, zd, r;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion ( ctx, equal( bvsdiv(x,y), z) );\n\n  assumption( ctx, equal( bvsint(39, w), x) );\n  assumption( ctx, equal( bvsint( 5, w), y) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  r = xd/yd;\n\n\n  BOOST_CHECK_EQUAL(  5, static_cast<int>(yd) );\n  BOOST_CHECK_EQUAL( 39, static_cast<int>(xd) );\n\n  BOOST_REQUIRE_EQUAL( 7, static_cast<int>(r ) );\n  BOOST_REQUIRE_EQUAL( 7, static_cast<int>(zd) );\n  BOOST_CHECK_EQUAL( static_cast<int>(r), static_cast<int>(zd) );\n\n  assumption( ctx, equal( bvsint(-39, w), x) );\n  assumption( ctx, equal( bvsint( -5, w), y) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( 7, zd);\n  BOOST_CHECK_EQUAL( static_cast<int>(r), static_cast<int>(zd) );\n\n  assumption( ctx, equal( bvsint(39,w), x) );\n  assumption( ctx, equal( bvsint(-5, w), y) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( -7, static_cast<int>(zd));\n  BOOST_CHECK_EQUAL( static_cast<int>(r), static_cast<int>(zd) );\n\n  assumption( ctx, equal( bvsint(-39,w), x) );\n  assumption( ctx, equal( bvsint(5, w), y) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  r = xd/yd;\n\n  BOOST_REQUIRE_EQUAL( -7, zd);\n  BOOST_CHECK_EQUAL( static_cast<int>(r), static_cast<int>(zd) );\n}\n\n\nBOOST_AUTO_TEST_CASE( bvurem_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvurem(x,y), z) );\n  assumption( ctx, nequal( bvuint(0,w), y) );\n  assumption( ctx, equal( z, bvuint(17, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd%yd;\n\n  BOOST_REQUIRE_EQUAL( 17, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvsrem_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  signed char xd, yd, zd, rd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal(x, bvuint(3,w)) );\n  assumption( ctx, equal(y, bvuint(2,w)) );\n  assumption( ctx, equal(z, bvuint(1,w)) );\n  assumption( ctx, equal(bvsrem(x, y), z) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  rd = xd % yd;\n  BOOST_REQUIRE_EQUAL(zd, rd);\n\n  assumption( ctx, equal(x, bvuint(-1,w)) );\n  assumption( ctx, equal(y, bvuint(2,w)) );\n  assumption( ctx, equal(z, bvuint(-1,w)) );\n  assumption( ctx, equal(bvsrem(x, y), z) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  rd = xd % yd;\n  BOOST_REQUIRE_EQUAL(zd, rd);\n}\n\nBOOST_AUTO_TEST_CASE( bvurem_2 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n  unsigned char xd, yd, zd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvurem(x,y), z) );\n  assumption( ctx, nequal( bvuint(0,w), y) );\n  assumption( ctx, equal( z, bvuint(17, w)) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  zd = read_value(ctx, z);\n\n  BOOST_REQUIRE_NE( yd, 0);\n  unsigned char r = xd%yd;\n\n  BOOST_REQUIRE_EQUAL( 17, zd);\n  BOOST_CHECK_EQUAL( r, zd);\n}\n\nBOOST_AUTO_TEST_CASE( bvcomp_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvcomp(x,y), bit1) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_EQUAL(xd, yd);\n\n  assumption( ctx, equal( bvcomp(x,y), bit0) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_NE(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvslt_2 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  signed char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvslt(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_LT(xd, yd);\n\n  assumption( ctx, Not( bvslt(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_GE(xd, yd);\n}\n\n\n\n\n\nBOOST_AUTO_TEST_CASE( bvslt_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  signed char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvslt(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_LT(xd, yd);\n\n  assumption( ctx, Not( bvslt(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_GE(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvsgt_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  signed char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvsgt(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_GT(xd, yd);\n\n  assumption( ctx, Not( bvsgt(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_LE(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvsle_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  signed char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvsle(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_LE(xd, yd);\n\n  assumption( ctx, Not( bvsle(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_GT(xd, yd);\n}\n\n\nBOOST_AUTO_TEST_CASE( bvsge_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  signed char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvsge(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_GE(xd, yd);\n\n  assumption( ctx, Not( bvsge(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_LT(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvult_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  unsigned char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvult(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  //printf(\"%u %u\\n\",xd, yd);\n  BOOST_CHECK_LT(xd, yd);\n\n  assumption( ctx, Not( bvult(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_GE(xd, yd);\n  //printf(\"%u %u\\n\",xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvult_all )\n{\n  using namespace boost::logic;\n\n  const char w = 4;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  unsigned xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, bvult(x,y) );\n  \n  unsigned limit = 257;\n  \n  while( solve(ctx) ) {\n    if( --limit == 0) break;\n    xd = read_value(ctx, x);\n    yd = read_value(ctx, y);\n    //printf(\"%u %u\\n\",xd, yd);\n    BOOST_REQUIRE_LT(xd, yd);\n  \n    assertion( ctx, Nand( equal(x, bvuint(xd,w)), equal(y, bvuint(yd, w)) ) );\n  \n  }\n}\n\nBOOST_AUTO_TEST_CASE( bvugt_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  unsigned char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvugt(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_GT(xd, yd);\n\n  assumption( ctx, Not( bvugt(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_LE(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvule_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  unsigned char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvule(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_LE(xd, yd);\n\n  assumption( ctx, Not( bvule(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_GT(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( bvule_70 )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(70,w), bvuint(70,w)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(70,w), bvuint(70,w)) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(69,w), bvuint(70,w)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(69,w), bvuint(70,w)) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(71,w), bvuint(70,w)) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(71,w), bvuint(70,w)) ) );\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvule_1 )\n{\n  using namespace boost::logic;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvule( bit1, bit1) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bit1,bit1) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bit0, bit1) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bit0, bit1) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bit1, bit0) );\n  BOOST_REQUIRE( !solve(ctx) );\n  \n  assumption( ctx, Not(bvule( bit1, bit0) ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvule( bit0, bit0) );\n  BOOST_REQUIRE( solve(ctx) );\n  \n  assumption( ctx, Not(bvule( bit0, bit0) ));\n  BOOST_REQUIRE( !solve(ctx) );\n  \n}\n\nBOOST_AUTO_TEST_CASE( bvule_2 )\n{\n  using namespace boost::logic;\n\n  const char w = 2;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(2,w), bvuint(2,w)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(2,w), bvuint(2,w)) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(1,w), bvuint(2,w)) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(1,w), bvuint(2,w)) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, bvule( bvuint(3,w), bvuint(2,w)) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  assumption( ctx, Not(bvule( bvuint(3,w), bvuint(2,w)) ) );\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvuge_t )\n{\n  using namespace boost::logic;\n\n  const char w = 8;\n\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  unsigned char xd, yd;\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, bvuge(x,y) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n\n  BOOST_CHECK_GE(xd, yd);\n\n  assumption( ctx, Not( bvuge(x,y) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  yd = read_value(ctx, y);\n  BOOST_CHECK_LT(xd, yd);\n}\n\nBOOST_AUTO_TEST_CASE( predicate_bvslt )\n{\n   const char w = 8;\n\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n   predicate p = new_variable();\n   predicate q = new_variable();\n   bool pd;\n   bool qd;\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal(p, bvslt(x,y)) );\n   assertion( ctx, equal(p, True) );\n   BOOST_REQUIRE( solve(ctx) );\n\n   pd = read_value(ctx, p);\n\n   BOOST_CHECK_EQUAL(pd, true);\n\n   assertion( ctx, equal(q, Not( bvslt(x,y) ) ) );\n   BOOST_REQUIRE( solve(ctx) );\n\n   qd = read_value(ctx, q);\n\n   BOOST_CHECK_EQUAL(qd, false);\n}\n\nBOOST_AUTO_TEST_CASE( uninitialized_readt )\n{\n   const char w = 8;\n\n   bitvector x = new_bitvector(w);\n   signed char xd;\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   xd = read_value(ctx, x);\n\n   BOOST_CHECK_EQUAL(xd, xd);\n}\n\n/**\n * this tests triggers an invalid optimization\n * is SWORD, the constrained is preprocessed,\n * found to constant true and replaced with\n * true. Therefore no assignment for the \n * variables is generated.\n */\nBOOST_AUTO_TEST_CASE( keeps_tiny_assertions )\n{\n   const char w = 32;\n\n   bitvector retval = new_bitvector(w);\n   assertion( ctx, equal(retval, retval));\n\n   BOOST_REQUIRE( solve(ctx) );\n   \n   bitvector tmp0 = new_bitvector(w);\n   assertion( ctx, equal(tmp0, tmp0));\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   bitvector x = new_bitvector(w);\n   assertion( ctx, equal(x, x));\n\n   assertion( ctx, equal(bvuint(3, w), x));\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   bitvector tmp1 = new_bitvector(w);\n   assertion( ctx, equal(tmp1, x));\n\n   assertion( ctx, equal(tmp1, tmp0));\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   unsigned xd = read_value(ctx, x);\n   unsigned tmp0d = read_value(ctx, tmp0);\n   unsigned tmp1d = read_value(ctx, tmp1);\n\n   BOOST_CHECK_EQUAL(xd, 3u);\n   BOOST_CHECK_EQUAL(tmp0d, 3u);\n   BOOST_CHECK_EQUAL(tmp1d, 3u);\n}\n\nBOOST_AUTO_TEST_CASE( keeps_small_assertions )\n{\n   const char w = 32;\n\n   bitvector tmp0   = new_bitvector(w);\n   bitvector tmp1   = new_bitvector(w);\n   bitvector x      = new_bitvector(w);\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, And(And( equal(bvuint(3, w), x),\n                   equal(tmp1, tmp0)),\n                   equal(tmp1, x)));\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   unsigned xd = read_value(ctx, x);\n   unsigned tmp0d = read_value(ctx, tmp0);\n   unsigned tmp1d = read_value(ctx, tmp1);\n\n   BOOST_CHECK_EQUAL(xd, 3u);\n   BOOST_CHECK_EQUAL(tmp0d, 3u);\n   BOOST_CHECK_EQUAL(tmp1d, 3u);\n}\n\nBOOST_AUTO_TEST_CASE( negative_multiply_t2 )\n{\n   using namespace boost::logic;\n\n   const unsigned w = 8;\n\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n   bitvector z = new_bitvector(w);\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal( y, bvsint( -1, w) ));\n   assertion( ctx, equal( z, bvsint(  1, w) ));\n   assertion( ctx, equal( x, bvmul (  z, y) ));\n   BOOST_REQUIRE( solve(ctx) );\n\n   signed char xd = read_value(ctx, x);\n   signed char yd = read_value(ctx, y);\n   signed char zd = read_value(ctx, z);\n   BOOST_CHECK_EQUAL( yd, -1 );\n   BOOST_CHECK_EQUAL( zd,  1 );\n   BOOST_CHECK_EQUAL( xd, -1 );\n}\n\nBOOST_AUTO_TEST_CASE( ite_t )\n{\n   using namespace boost::logic;\n\n   const unsigned w = 8;\n\n   predicate c = new_variable();\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n   bitvector z = new_bitvector(w);\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal( x, Ite( c, y, z) ));\n\n   assumption( ctx, c);\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   bool b = read_value(ctx, c);\n   int xd = read_value(ctx, x);\n   int yd = read_value(ctx, y);\n   int zd = read_value(ctx, z);\n\n   BOOST_CHECK_EQUAL( b, true );\n   BOOST_CHECK_EQUAL( xd, yd );\n   \n   assumption( ctx, Not(c) );\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   b  = read_value(ctx, c);\n   xd = read_value(ctx, x);\n   yd = read_value(ctx, y);\n   zd = read_value(ctx, z);\n\n   BOOST_CHECK_EQUAL( b, false );\n   BOOST_CHECK_EQUAL( xd, zd );\n}\n\nBOOST_AUTO_TEST_CASE( concat_extract_x )\n{\n   const unsigned w = 8;\n\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal( x, extract( 7, 0, concat(x, y) )) );\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, nequal( x, extract( 7, 0, concat(x, y) )) );\n\n   BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( concat_extract_y )\n{\n   const unsigned w = 8;\n\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n   assertion( ctx, equal( y, extract( 15, 8, concat(x, y) )) );\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, nequal( y, extract( 15, 8, concat(x, y) )) );\n\n   BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvshl_t )\n{\n  const unsigned w = 128u;\n\n  bitvector x = new_bitvector(w);\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, equal( bvmul(x, bvuint(2,w)), bvshl(x, bvuint(2,w))) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assertion( ctx, nequal( bvmul(x, bvuint(2,w)), bvshl(x, bvuint(2,w))) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvshl_all )\n{\n  const unsigned w = 16;\n  bitvector x = new_bitvector(w);\n  bitvector y = new_bitvector(w);\n  bitvector z = new_bitvector(w);\n\n  const unsigned xlimit = 256;\n  const unsigned ylimit = w;\n  BOOST_REQUIRE( solve(ctx) );\n  assertion(ctx, equal( z, bvshl( x, y)) );\n  assertion(ctx, bvult(x,bvuint(xlimit,w)));\n  assertion(ctx, bvult(y,bvuint(ylimit,w)));\n  \n  unsigned limit = xlimit*ylimit+1;\n\n  while( solve(ctx) ) {\n    if( --limit == 0) break;\n    unsigned xd = read_value(ctx, x);\n    unsigned yd = read_value(ctx, y);\n    unsigned zd = read_value(ctx,z);\n\n    //printf(\"before shifting: %d %u %u %u\\n\",limit, xd, yd, zd);\n    \n    unsigned shifted = (xd << yd) %(1ul << w);\n\n    //printf(\"after shifting: %d %u %u %u\\n\",limit, xd, yd, zd);\n\n    //std::cout << \"x: \" <<read_value(ctx,x) << std::endl;\n    //std::cout << \"y: \" <<read_value(ctx,y) << std::endl;\n    //std::cout << \"z: \" <<read_value(ctx,z) << std::endl;\n    BOOST_REQUIRE_EQUAL(shifted, zd);\n\n    //printf(\"test: %d %u %u %u\\n\",limit, xd, yd, zd);\n\n    assertion( ctx, Nand( equal(x, bvuint(xd,w)), equal(y, bvuint(yd, w)) ) );\n    \n  }\n  BOOST_REQUIRE_EQUAL(limit,1u);\n}\n\nBOOST_AUTO_TEST_CASE( bvshl_128_30 )\n{\n   const unsigned w = 32;\n   bitvector x = new_bitvector(w);\n   bitvector y = new_bitvector(w);\n   bitvector z = new_bitvector(w);\n\n   BOOST_REQUIRE( solve(ctx) );\n\n   assumption(ctx, equal( z, bvshl( x, y)) );\n   assumption(ctx, equal(x, bvuint(128,w)));\n   assumption(ctx, equal(y, bvuint( 30,w)));\n   assumption(ctx, equal(z, bvuint(  0,w)));\n   BOOST_REQUIRE( solve(ctx) );\n\n   assumption(ctx, nequal( z, bvshl( x, y)) );\n   assumption(ctx, equal(x, bvuint(128,w)));\n   assumption(ctx, equal(y, bvuint( 30,w)));\n   assumption(ctx, equal(z, bvuint(  0,w)));\n   BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvshr_t )\n{\n  const unsigned w = 128u;\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, equal( bvuint(1,w), bvshr(bvuint(8,w), bvuint(3, w))) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  assumption( ctx, nequal( bvuint(1,w), bvshr(bvuint(8,w), bvuint(3, w))) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvashr_t )\n{\n   const unsigned w = 32;\n   bitvector x = new_bitvector(w);\n   BOOST_REQUIRE( solve(ctx) );\n\n   assumption( ctx, equal( bvsint(-1,w), bvashr(bvsint(-1,w), x)) );\n   BOOST_REQUIRE( solve(ctx) );\n\n   assumption( ctx, nequal( bvsint(-1,w), bvashr(bvsint(-1,w), x)) );\n   BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( zero_extend_t )\n{\n   const unsigned w = 8;\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal( zero_extend(w, bvuint(255,w)), bvuint(255,2*w)));\n   BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( sign_extend_t )\n{\n   const unsigned w = 8;\n   BOOST_REQUIRE( solve(ctx) );\n\n   assertion( ctx, equal( sign_extend(w, bvsint(-1,w)), bvsint(-1,2*w)));\n   BOOST_REQUIRE( solve(ctx) );\n}\n\n\nBOOST_AUTO_TEST_CASE( evaluate_concat )\n{\n  const unsigned w = 8;\n  BOOST_REQUIRE( solve(ctx) );\n\n  bitvector x = new_bitvector(w);\n  bitvector x2 = new_bitvector(2*w);\n\n  ContextType::result_type cc = evaluate( ctx, concat(x,x) );\n\n  metaSMT::assertion( ctx, metaSMT::logic::equal( x2, cc) );\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( read_value_constant )\n{\n  const unsigned w = 32;\n  bitvector x = new_bitvector(w);\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( x, bvuint(13,w) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  unsigned i = read_value(ctx, x);\n  BOOST_CHECK_EQUAL( i, 13u);\n  \n  std::string s = read_value(ctx, x);\n  BOOST_CHECK_EQUAL( s, \"00000000000000000000000000001101\");\n\n}\n\nBOOST_AUTO_TEST_CASE( bvint_t )\n{\n  const unsigned w = 32;\n\n  BOOST_REQUIRE( solve(ctx) );\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(13,w), bvint(13u,w) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::nequal( bvuint(13,w), bvint(13u,w) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n  \n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(13,w), bvint(13,w) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::nequal( bvsint(13,w), bvint(13,w) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-13,w), bvint(-13,w) ) );\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::nequal( bvsint(-13,w), bvint(-13,w) ) );\n  BOOST_REQUIRE( !solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvuint_t )\n{\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(123,8),\n    bvbin(\"01111011\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(0x5F55,16),\n    bvbin(\"01011111\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n  \n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(0x555F55F5,32),\n    bvbin(\"01010101\" \"01011111\" \"01010101\" \"11110101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n  \n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(0x555F55555F55F555ul,64),\n    bvbin(\"01010101\" \"01011111\" \"01010101\" \"01010101\"\n          \"01011111\" \"01010101\" \"11110101\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvuint(0xF5555F555555F555ul,128),\n    bvbin(\"00000000\" \"00000000\" \"00000000\" \"00000000\"\n          \"00000000\" \"00000000\" \"00000000\" \"00000000\"\n          \"11110101\" \"01010101\" \"01011111\" \"01010101\"\n          \"01010101\" \"01010101\" \"11110101\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( bvsint_t )\n{\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(123,8),\n    bvbin(\"01111011\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(0x5F55,16),\n    bvbin(\"01011111\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n  \n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(0x555F55F5,32),\n    bvbin(\"01010101\" \"01011111\" \"01010101\" \"11110101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(0x555F55555F55F555ul,64),\n    bvbin(\"01010101\" \"01011111\" \"01010101\" \"01010101\"\n          \"01011111\" \"01010101\" \"11110101\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(0xF5555F555555F555ul,128),\n    bvbin(\"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11110101\" \"01010101\" \"01011111\" \"01010101\"\n          \"01010101\" \"01010101\" \"11110101\" \"01010101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-123,8),\n    bvbin(\"10000101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-123,16),\n    bvbin(\"11111111\" \"10000101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-123,32),\n    bvbin(\"11111111\" \"11111111\" \"11111111\" \"10000101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-123,64),\n    bvbin(\"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11111111\" \"11111111\" \"11111111\" \"10000101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n\n  metaSMT::assumption( ctx, metaSMT::logic::equal( bvsint(-123,128),\n    bvbin(\"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11111111\" \"11111111\" \"11111111\" \"11111111\"\n          \"11111111\" \"11111111\" \"11111111\" \"10000101\")\n  ));\n  BOOST_REQUIRE( solve(ctx) );\n}\n\nBOOST_AUTO_TEST_CASE( variable_equality )\n{\n  unsigned const width = 8;\n  bitvector x = new_bitvector(width);\n  bitvector y = new_bitvector(width);\n\n  bool cmp = (x == x);\n  BOOST_CHECK( cmp );\n\n  cmp = (x == y);\n  BOOST_CHECK( !cmp );\n\n  cmp = (y == x);\n  BOOST_CHECK( !cmp );\n}\n\nBOOST_AUTO_TEST_CASE( constant_64bit )\n{\n  unsigned const w = 64;\n  unsigned long const value = std::numeric_limits<unsigned long>::max();\n  bitvector x = new_bitvector(w);\n\n  assumption(ctx, equal(x, bvuint(value, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  unsigned long xd = read_value(ctx, x);\n  std::string xs = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value);\n  BOOST_CHECK_EQUAL(xs, \"1111111111111111111111111111111111111111111111111111111111111111\");\n\n  assumption(ctx, equal(x, bvuint(value-123, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value-123);\n}\n\nBOOST_AUTO_TEST_CASE( constant_69bit )\n{\n  bitvector x = new_bitvector(69);\n\n  const std::string longconst (\"001111001110010101010100000000000000000000000000000000000000000000000\");\n  assumption(ctx, equal( x,  bvbin(longconst) ) );\n  BOOST_REQUIRE( solve(ctx) );\n  std::string longval = read_value(ctx, x);\n  BOOST_REQUIRE_EQUAL( longconst, longval);\n}\n\nBOOST_AUTO_TEST_CASE( signed_constant_64bit )\n{\n  unsigned const w = 64;\n  long value = std::numeric_limits<long>::max();\n  bitvector x = new_bitvector(w);\n\n  assumption(ctx, equal(x, bvsint(value, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  std::string xs = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xs, \"0111111111111111111111111111111111111111111111111111111111111111\");\n\n  long xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value);\n\n  assumption(ctx, equal(x, bvsint(value-123, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value-123);\n\n  value = std::numeric_limits<long>::min();\n\n  assumption(ctx, equal(x, bvsint(value, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value);\n\n  assumption(ctx, equal(x, bvsint(value+123, w)));\n  BOOST_REQUIRE( solve(ctx) );\n\n  xd = read_value(ctx, x);\n  BOOST_CHECK_EQUAL(xd, value+123);\n\n}\n\n\nBOOST_AUTO_TEST_CASE(extended_concat) {\n\n\n  // b[..] == b\n  bitvector b_1   = new_bitvector(8);\n  bitvector b_0_1 = new_bitvector(4);\n  bitvector b_1_1 = new_bitvector(4);\n  assertion(ctx, equal( concat( b_1_1, b_0_1), b_1) );\n\n  bitvector a_1   = new_bitvector(8);\n  bitvector a_0_1 = new_bitvector(4);\n  bitvector a_1_1 = new_bitvector(4);\n\n  // a[..] == a\n  assertion(ctx, equal( concat( a_1_1, a_0_1), a_1) );\n\n  bitvector z_1   = new_bitvector(16);\n  bitvector z_0_1 = new_bitvector(4);\n  bitvector z_1_1 = new_bitvector(4);\n  bitvector z_2_1 = new_bitvector(4);\n  bitvector z_3_1 = new_bitvector(4);\n\n  // z[..] == z\n  assertion(ctx, equal(\n    concat( z_3_1,\n    concat( z_2_1,\n    concat( z_1_1,\n            z_0_1))),\n    z_1\n  ));\n\n  bitvector buf_3_o_0_1 = new_bitvector(4);\n  bitvector buf_3_o_1_1 = new_bitvector(4);\n  bitvector buf_3_o_2_1 = new_bitvector(4);\n  bitvector buf_3_o_3_1 = new_bitvector(4);\n\n  // (a[..],b[..]) == buf\n  assertion(ctx, equal(\n\n    concat( a_1_1,\n    concat( a_0_1,\n    concat( b_1_1,\n            b_0_1))),\n\n    concat( buf_3_o_3_1,\n    concat( buf_3_o_2_1,\n    concat( buf_3_o_1_1,\n            buf_3_o_0_1)))\n  ));\n\n  // buf[..] == z[..]\n  assertion(ctx, equal(\n\n    concat( buf_3_o_3_1,\n    concat( buf_3_o_2_1,\n    concat( buf_3_o_1_1,\n            buf_3_o_0_1))),\n\n    concat( z_3_1,\n    concat( z_2_1,\n    concat( z_1_1,\n            z_0_1)))\n\n  ));\n\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  // a = 00\n  // b = 00\n  assumption(ctx, equal(a_1, bvbin(\"00000000\")));\n  assumption(ctx, equal(b_1, bvbin(\"00000000\")));\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  std::string av = read_value(ctx, a_1);\n  std::string bv = read_value(ctx, b_1);\n  std::string zv = read_value(ctx, z_1);\n\n  BOOST_REQUIRE_EQUAL( av, \"00000000\" );\n  BOOST_REQUIRE_EQUAL( bv, \"00000000\" );\n  BOOST_REQUIRE_EQUAL( zv, \"0000000000000000\" );\n\n\n  // a = 00\n  // b = 01\n  assumption(ctx, equal(a_1, bvbin(\"00000000\")));\n  assumption(ctx, equal(b_1, bvbin(\"00000001\")));\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  std::string av2 = read_value(ctx, a_1);\n  std::string bv2 = read_value(ctx, b_1);\n  std::string zv2 = read_value(ctx, z_1);\n\n  BOOST_REQUIRE_EQUAL( av2, \"00000000\" );\n  BOOST_REQUIRE_EQUAL( bv2, \"00000001\" );\n  BOOST_REQUIRE_EQUAL( zv2, \"0000000000000001\" );\n\n\n  // a = 01\n  // b = 00\n  assumption(ctx, equal(a_1, bvbin(\"00000001\")));\n  assumption(ctx, equal(b_1, bvbin(\"00000000\")));\n\n  BOOST_REQUIRE( solve(ctx) );\n\n  std::string av3 = read_value(ctx, a_1);\n  std::string bv3 = read_value(ctx, b_1);\n  std::string zv3 = read_value(ctx, z_1);\n\n  BOOST_REQUIRE_EQUAL( av3, \"00000001\" );\n  BOOST_REQUIRE_EQUAL( bv3, \"00000000\" );\n  BOOST_REQUIRE_EQUAL( zv3, \"0000000100000000\" );\n}\n\nBOOST_AUTO_TEST_SUITE_END() //QF_BV\n\n//  vim: ft=cpp:ts=2:sw=2:expandtab\n", "meta": {"hexsha": "613661a666439b6a233afaaf7bd6a8a50f9d689a", "size": 48791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_QF_BV.cpp", "max_stars_repo_name": "finnhaedicke/metaSMT", "max_stars_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:55:58.000Z", "max_issues_repo_path": "tests/test_QF_BV.cpp", "max_issues_repo_name": "finnhaedicke/metaSMT", "max_issues_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T14:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T07:59:34.000Z", "max_forks_repo_path": "tests/test_QF_BV.cpp", "max_forks_repo_name": "finnhaedicke/metaSMT", "max_forks_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T18:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T12:44:12.000Z", "avg_line_length": 23.559150169, "max_line_length": 104, "alphanum_fraction": 0.6454264106, "num_tokens": 15735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.691863893358926}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_MATRIX_HOUSEHOLDER_INCLUDE\n#define MTL_MATRIX_HOUSEHOLDER_INCLUDE\n\n#include <cmath>\n#include <cassert>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace vector {\n\n\n/// Computes Householder vector v and scalar b for vector \\p y \n/** such that identity_matrix(size(y))-b*v*v' projects the vector y \n    to a positive multiple of the first unit vector. **/\ntemplate <typename Vector>\nstd::pair<typename mtl::vector::dense_vector<typename Collection<Vector>::value_type, parameters<> >, typename Collection<Vector>::value_type>\ninline householder(Vector& y)\n{\n    vampir_trace<2004> tracer;\n    assert(size(y) > 0);\n    typedef typename  Collection<Vector>::value_type   value_type;\n    // typedef typename  Collection<Vector>::size_type    size_type;\n    const value_type  zero= math::zero(y[0]), one= math::one(y[0]);\n\n    Vector            v(y);\n    v[0]= one;\n    irange            tail(1, imax); \n    value_type        s( dot(v[tail], v[tail]) ), b, v0;\n\n    //evaluation of v and b\n    if (s == zero)\n        b= zero;\n    else {\n\tvalue_type mu= sqrt(y[0] * y[0] + s);\n\tv0= v[0]= y[0] <= zero ? y[0] - mu : -s / (y[0] + mu); // complex < zero????\n\tb= 2 * v0 * v0 / (s + v0 * v0);                        // 2* complex???????\n\tv/= v0;                                                // normalization of the first entry\n    }\n  \n    return std::make_pair(v,b);\n}\n\n/// Computes Householder vector for vector \\p y \n/** More stable Householder transformation, also for non-square matrices. **/\ntemplate <typename Vector>\ntypename mtl::vector::dense_vector<typename Collection<Vector>::value_type, parameters<> >\ninline householder_s(Vector& y)\n{\n    vampir_trace<2005> tracer;\n    typedef typename  Collection<Vector>::value_type   value_type;\n    const value_type  zero= math::zero(y[0]);\n\n    Vector            u(y);\n    value_type        nu(sqrt( dot(u, u) )), s;\n\n    if (nu != zero){\n\tif(u[0] < 0){\n\t\ts= -1;\n\t} else {\n\t\ts= 1; \n\t}\n\tu[0]= u[0] + s * nu;\n\tu/= sqrt( dot(u, u) );\n    }\n\n    return u;\n}\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_HOUSEHOLDER_INCLUDE\n\n", "meta": {"hexsha": "d435b2b75b9ee32e806bce971b92eda43e751f41", "size": 2741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "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/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["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.1208791209, "max_line_length": 142, "alphanum_fraction": 0.6395476104, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6917657969214323}}
{"text": "#pragma once\n#include <string>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_bind.hpp>\n\n\nusing namespace boost::spirit::qi;\nusing namespace std;\nusing namespace boost::spirit;\n\n\ntemplate <typename Iterator, typename NumType>\nstruct CalcGrammar : public grammar<Iterator, NumType(), space_type>\n{\n\tCalcGrammar() : CalcGrammar::base_type(exp_)\n\t{\n\t\treal_parser<NumType, real_policies<NumType> > rp_;\n\t\tfactor_ = rp_[_val = _1]\n\t\t\t| ('-' >> factor_)[_val = -_1]\n\t\t\t| ('+' >> factor_)[_val = _1]\n\t\t\t| ('(' >> exp_[_val = _1] >> ')');\n\n\t\tterm_ = factor_[_val = _1] >>\n\t\t\t*(('*' >> factor_[_val *= _1])\n\t\t\t| ('/' >> factor_[_val /= _1]));\n\n\t\texp_ = term_[_val = _1] >>\n\t\t\t*(('+' >> term_[_val += _1])\n\t\t\t| ('-' >> term_[_val -= _1]));\n\t}\n\ttypedef rule<Iterator, NumType(), space_type> rule_t;\n\trule_t factor_, term_, exp_;\n};\n\n\ntemplate<class _NumType = double>\nclass Calculator\n{\npublic:\n\tCalculator(void){}\n\tvirtual ~Calculator(void){}\npublic:\n\ttypedef _NumType NumType;\npublic:\n\t_NumType calc(const std::string& input);\n\t_NumType calc(const std::string& input,bool& isSuccessed,const char*& lastErr);\n\tconst char* getLastErr(){ return lastErr_.c_str(); }\nprotected:\n\tCalcGrammar<std::string::const_iterator, _NumType> gram_;\n\tstd::string lastErr_;\n};\ntemplate<class _NumType>\n_NumType Calculator<_NumType>::calc(const std::string& input)\n{\n\tbool isSuccess;\n\tconst char* lastErr = nullptr;\n\treturn calc(input, isSuccess, lastErr);\n}\n\ntemplate<class _NumType>\n_NumType Calculator<_NumType>::calc(const std::string& input, bool& isSuccessed, const char*& lastErr)\n{\n\t_NumType val = 0;\n\tstd::string::const_iterator startPos = input.begin();\n\tauto r = phrase_parse(startPos, input.end(), gram_, space, val);\n\tif (r && startPos == input.end())\n\t{\n\t\tlastErr_.clear();\n\t\tisSuccessed = true;\n\t\tlastErr = \"\";\n\t\treturn val;\n\t}\n\telse\n\t{\n\t\tint num = input.end() - startPos;\n\t\tlastErr_ = std::string(num, '-') + \"^\";\n\t\tisSuccessed = false;\n\t\tlastErr = lastErr_.c_str();\n\t}\n}\n\nint main()\n{\n\tCalculator<> calc;\n\tstd::string input;\n\tprintf(\"input here\\n\");\n\twhile (true)\n\t{\n\t\tgetline(cin,input);\n\t\tif (input == \"\")\n\t\t\tbreak;\n\t\tint val = calc.calc(input.c_str());\n\t\tif (calc.getLastErr()[0] != 0)\n\t\t\tprintf(\"%s\\nWrong\\n\\n\", calc.getLastErr());\n\t\telse\n\t\t\tprintf(\"%d\\n\\n\", val);\n\t}\n}\n", "meta": {"hexsha": "de173a794f0bbd44a57408dbdb528e48dceaaf3c", "size": 2395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calulator.cpp", "max_stars_repo_name": "Remilia-Scarlet/red", "max_stars_repo_head_hexsha": "93b739931d801df685d8c07608e40651f8e31707", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "calulator.cpp", "max_issues_repo_name": "Remilia-Scarlet/red", "max_issues_repo_head_hexsha": "93b739931d801df685d8c07608e40651f8e31707", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calulator.cpp", "max_forks_repo_name": "Remilia-Scarlet/red", "max_forks_repo_head_hexsha": "93b739931d801df685d8c07608e40651f8e31707", "max_forks_repo_licenses": ["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.7128712871, "max_line_length": 102, "alphanum_fraction": 0.6638830898, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6917657952084427}}
{"text": "//\n// Copyright (c) 2019 CNRS\n//\n\n#ifndef __pinocchio_math_rotation_hpp__\n#define __pinocchio_math_rotation_hpp__\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/math/matrix.hpp\"\n#include <Eigen/Core>\n\nnamespace pinocchio\n{\n  ///\n  /// \\brief Computes a rotation matrix from a vector and values of sin and cos\n  ///        orientations values.\n  ///\n  /// \\remarks This code is issue from Eigen::AxisAngle::toRotationMatrix\n  ///\n  template<typename Vector3, typename Scalar, typename Matrix3>\n  void toRotationMatrix(const Eigen::MatrixBase<Vector3> & axis,\n                        const Scalar & cos_value, const Scalar & sin_value,\n                        const Eigen::MatrixBase<Matrix3> & res)\n  {\n    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3,3);\n    EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3,3,3);\n    \n    assert(isUnitary(axis) && \"The axis is not unitary.\");\n    \n    Matrix3 & res_ = PINOCCHIO_EIGEN_CONST_CAST(Matrix3,res);\n    Vector3 sin_axis  = sin_value * axis;\n    Vector3 cos1_axis = (Scalar(1)-cos_value) * axis;\n    \n    Scalar tmp;\n    tmp = cos1_axis.x() * axis.y();\n    res_.coeffRef(0,1) = tmp - sin_axis.z();\n    res_.coeffRef(1,0) = tmp + sin_axis.z();\n    \n    tmp = cos1_axis.x() * axis.z();\n    res_.coeffRef(0,2) = tmp + sin_axis.y();\n    res_.coeffRef(2,0) = tmp - sin_axis.y();\n    \n    tmp = cos1_axis.y() * axis.z();\n    res_.coeffRef(1,2) = tmp - sin_axis.x();\n    res_.coeffRef(2,1) = tmp + sin_axis.x();\n    \n    res_.diagonal() = (cos1_axis.cwiseProduct(axis)).array() + cos_value;\n  }\n}\n\n#endif //#ifndef __pinocchio_math_rotation_hpp__\n\n", "meta": {"hexsha": "0a7c014c197909228ea947a23e77daf1a9d539c6", "size": 1593, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/rotation.hpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "src/math/rotation.hpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/rotation.hpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 30.0566037736, "max_line_length": 79, "alphanum_fraction": 0.6534839925, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6917085314355036}}
{"text": "// test_root.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestRootFunctions)\n    \n    BOOST_AUTO_TEST_CASE(test_root_bisection)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = 0.0f;\n        result = Numerary::root(sin, -3, 3, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing log function\n        expected_result = 1;\n        expected_answer = 1.0f;\n        result = Numerary::root(log, 0, 3, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_root_secant)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = 0.0f;\n        result = Numerary::root(sin, -3, 3, &answer, \"secant\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing cos function\n        expected_result = 0;\n        result = Numerary::root(cos, -3, 3, &answer, \"secant\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "28c43a4d048067c61ca0024acb96e4c44f178cf3", "size": 1637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_root.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_root.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_root.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 27.2833333333, "max_line_length": 71, "alphanum_fraction": 0.6194257789, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6917085206844465}}
{"text": "\r\n\r\n#include <NTL/FFT.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\nFFTTablesType FFTTables;\r\n// a truly GLOBAL variable, shared among all threads\r\n\r\n\r\n\r\nlong IsFFTPrime(long n, long& w)\r\n{\r\n   long  m, x, y, z;\r\n   long j, k;\r\n\r\n\r\n   if (n <= 1 || n >= NTL_SP_BOUND) return 0;\r\n\r\n   if (n % 2 == 0) return 0;\r\n\r\n   if (n % 3 == 0) return 0;\r\n\r\n   if (n % 5 == 0) return 0;\r\n\r\n   if (n % 7 == 0) return 0;\r\n   \r\n   m = n - 1;\r\n   k = 0;\r\n   while ((m & 1) == 0) {\r\n      m = m >> 1;\r\n      k++;\r\n   }\r\n\r\n   for (;;) {\r\n      x = RandomBnd(n);\r\n\r\n      if (x == 0) continue;\r\n      z = PowerMod(x, m, n);\r\n      if (z == 1) continue;\r\n\r\n      x = z;\r\n      j = 0;\r\n      do {\r\n         y = z;\r\n         z = MulMod(y, y, n);\r\n         j++;\r\n      } while (j != k && z != 1);\r\n\r\n      if (z != 1 || y !=  n-1) return 0;\r\n\r\n      if (j == k) \r\n         break;\r\n   }\r\n\r\n   /* x^{2^k} = 1 mod n, x^{2^{k-1}} = -1 mod n */\r\n\r\n   long TrialBound;\r\n\r\n   TrialBound = m >> k;\r\n   if (TrialBound > 0) {\r\n      if (!ProbPrime(n, 5)) return 0;\r\n   \r\n      /* we have to do trial division by special numbers */\r\n   \r\n      TrialBound = SqrRoot(TrialBound);\r\n   \r\n      long a, b;\r\n   \r\n      for (a = 1; a <= TrialBound; a++) {\r\n         b = (a << k) + 1;\r\n         if (n % b == 0) return 0; \r\n      }\r\n   }\r\n\r\n   /* n is an FFT prime */\r\n\r\n   for (j = NTL_FFTMaxRoot; j < k; j++)\r\n      x = MulMod(x, x, n);\r\n\r\n   w = x;\r\n   return 1;\r\n}\r\n\r\n\r\nstatic\r\nvoid NextFFTPrime(long& q, long& w, long index)\r\n{\r\n   static long m = NTL_FFTMaxRootBnd + 1;\r\n   static long k = 0;\r\n   // m and k are truly GLOBAL variables, shared among\r\n   // all threads.  Access is protected by a critical section\r\n   // guarding FFTTables\r\n\r\n   static long last_index = -1;\r\n   static long last_m = 0;\r\n   static long last_k = 0;\r\n\r\n   if (index == last_index) {\r\n      // roll back m and k...part of a simple error recovery\r\n      // strategy if an exception was thrown in the last \r\n      // invocation of UseFFTPrime...probably of academic \r\n      // interest only\r\n\r\n      m = last_m;\r\n      k = last_k;\r\n   }\r\n   else {\r\n      last_index = index;\r\n      last_m = m;\r\n      last_k = k;\r\n   }\r\n\r\n   long t, cand;\r\n\r\n   for (;;) {\r\n      if (k == 0) {\r\n         m--;\r\n         if (m < 5) ResourceError(\"ran out of FFT primes\");\r\n         k = 1L << (NTL_SP_NBITS-m-2);\r\n      }\r\n\r\n      k--;\r\n\r\n      cand = (1L << (NTL_SP_NBITS-1)) + (k << (m+1)) + (1L << m) + 1;\r\n\r\n      if (!IsFFTPrime(cand, t)) continue;\r\n      q = cand;\r\n      w = t;\r\n      return;\r\n   }\r\n}\r\n\r\n\r\nlong CalcMaxRoot(long p)\r\n{\r\n   p = p-1;\r\n   long k = 0;\r\n   while ((p & 1) == 0) {\r\n      p = p >> 1;\r\n      k++;\r\n   }\r\n\r\n   if (k > NTL_FFTMaxRoot)\r\n      return NTL_FFTMaxRoot;\r\n   else\r\n      return k; \r\n}\r\n\r\n\r\nvoid InitFFTPrimeInfo(FFTPrimeInfo& info, long q, long w, bool bigtab)\r\n{\r\n   double qinv = 1/((double) q);\r\n\r\n   long mr = CalcMaxRoot(q);\r\n\r\n   info.q = q;\r\n   info.qinv = qinv;\r\n   info.zz_p_context = 0;\r\n\r\n\r\n   info.RootTable.SetLength(mr+1);\r\n   info.RootInvTable.SetLength(mr+1);\r\n   info.TwoInvTable.SetLength(mr+1);\r\n   info.TwoInvPreconTable.SetLength(mr+1);\r\n\r\n   long *rt = &info.RootTable[0];\r\n   long *rit = &info.RootInvTable[0];\r\n   long *tit = &info.TwoInvTable[0];\r\n   mulmod_precon_t *tipt = &info.TwoInvPreconTable[0];\r\n\r\n   long j;\r\n   long t;\r\n\r\n   rt[mr] = w;\r\n   for (j = mr-1; j >= 0; j--)\r\n      rt[j] = MulMod(rt[j+1], rt[j+1], q);\r\n\r\n   rit[mr] = InvMod(w, q);\r\n   for (j = mr-1; j >= 0; j--)\r\n      rit[j] = MulMod(rit[j+1], rit[j+1], q);\r\n\r\n   t = InvMod(2, q);\r\n   tit[0] = 1;\r\n   for (j = 1; j <= mr; j++)\r\n      tit[j] = MulMod(tit[j-1], t, q);\r\n\r\n   for (j = 0; j <= mr; j++)\r\n      tipt[j] = PrepMulModPrecon(tit[j], q, qinv);\r\n\r\n   if (bigtab)\r\n      info.bigtab.make();\r\n}\r\n\r\n\r\n#ifndef NTL_WIZARD_HACK\r\nSmartPtr<zz_pInfoT> Build_zz_pInfo(FFTPrimeInfo *info);\r\n#else\r\nSmartPtr<zz_pInfoT> Build_zz_pInfo(FFTPrimeInfo *info) { return 0; }\r\n#endif\r\n\r\nvoid UseFFTPrime(long index)\r\n{\r\n   if (index < 0) LogicError(\"invalud FFT prime index\");\r\n   if (index >= NTL_MAX_FFTPRIMES) ResourceError(\"FFT prime index too large\");\r\n\r\n   do {  // NOTE: thread safe lazy init\r\n      FFTTablesType::Builder bld(FFTTables, index+1);\r\n      long amt = bld.amt();\r\n      if (!amt) break;\r\n\r\n      long first = index+1-amt;\r\n      // initialize entries first..index\r\n\r\n      long i;\r\n      for (i = first; i <= index; i++) {\r\n         UniquePtr<FFTPrimeInfo> info;\r\n         info.make();\r\n\r\n         long q, w;\r\n         NextFFTPrime(q, w, i);\r\n\r\n         bool bigtab = false;\r\n\r\n#ifdef NTL_FFT_BIGTAB\r\n         if (i < NTL_FFT_BIGTAB_LIMIT)\r\n            bigtab = true;\r\n#endif\r\n\r\n         InitFFTPrimeInfo(*info, q, w, bigtab);\r\n         info->zz_p_context = Build_zz_pInfo(info.get());\r\n         bld.move(info);\r\n      }\r\n\r\n   } while (0);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n * Our FFT is based on the routine in Cormen, Leiserson, Rivest, and Stein.\r\n * For very large inputs, it should be relatively cache friendly.\r\n * The inner loop has been unrolled and pipelined, to exploit any\r\n * low-level parallelism in the machine.\r\n * \r\n * This version now allows input to alias output.\r\n */\r\n\r\n\r\n#define NTL_PIPELINE\r\n//  Define to gets some software pipelining...actually seems\r\n//  to help somewhat\r\n\r\n#define NTL_LOOP_UNROLL\r\n//  Define to unroll some loops.  Seems to help a little\r\n\r\n// FIXME: maybe the above two should be tested by the wizard\r\n\r\n\r\nstatic\r\nlong RevInc(long a, long k)\r\n{\r\n   long j, m;\r\n\r\n   j = k; \r\n   m = 1L << (k-1);\r\n\r\n   while (j && (m & a)) {\r\n      a ^= m;\r\n      m >>= 1;\r\n      j--;\r\n   }\r\n   if (j) a ^= m;\r\n   return a;\r\n}\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL static \r\nVec<long> brc_mem[NTL_FFTMaxRoot+1];\r\n// FIXME: This could potentially be shared across threads, using\r\n// a \"lazy table\".\r\n\r\n\r\n#if 0\r\n\r\n\r\nstatic\r\nvoid BitReverseCopy(long * NTL_RESTRICT A, const long * NTL_RESTRICT a, long k)\r\n{\r\n   long n = 1L << k;\r\n   long* NTL_RESTRICT rev;\r\n   long i, j;\r\n\r\n   rev = brc_mem[k].elts();\r\n   if (!rev) {\r\n      brc_mem[k].SetLength(n);\r\n      rev = brc_mem[k].elts();\r\n      for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n         rev[i] = j;\r\n   }\r\n\r\n   for (i = 0; i < n; i++)\r\n      A[rev[i]] = a[i];\r\n}\r\n\r\n\r\nstatic\r\nvoid BitReverseCopy(unsigned long * NTL_RESTRICT A, const long * NTL_RESTRICT a, long k)\r\n{\r\n   long n = 1L << k;\r\n   long* NTL_RESTRICT rev;\r\n   long i, j;\r\n\r\n   rev = brc_mem[k].elts();\r\n   if (!rev) {\r\n      brc_mem[k].SetLength(n);\r\n      rev = brc_mem[k].elts();\r\n      for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n         rev[i] = j;\r\n   }\r\n\r\n   for (i = 0; i < n; i++)\r\n      A[rev[i]] = a[i];\r\n}\r\n\r\n#else\r\n\r\n// A more cache-friendly bit-reverse copy algorithm.\r\n// The \"COBRA\" algorithm from Carter and Gatlin, \"Towards an\r\n// optimal bit-reversal permutation algorithm\", FOCS 1998.\r\n\r\n// NOTE: for basic poly mul, we could consider not doing any\r\n// bit-reverse copy; however, a number of other operations\r\n// depend on this, so it would not be easy to do.\r\n\r\n#define NTL_BRC_THRESH (12)\r\n#define NTL_BRC_Q (5)\r\n\r\n// Must have NTL_BRC_THRESH > 2*NTL_BRC_Q\r\n// Should also have (1L << (2*NTL_BRC_Q)) small enough\r\n// so that we can fit that many long's into the cache\r\n\r\n\r\nstatic\r\nlong *BRC_init(long k)\r\n{\r\n   long n = (1L << k);\r\n   brc_mem[k].SetLength(n);\r\n   long *rev = brc_mem[k].elts();\r\n   long i, j;\r\n   for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n      rev[i] = j;\r\n   return rev;\r\n}\r\n\r\n\r\nstatic\r\nvoid BasicBitReverseCopy(long * NTL_RESTRICT B, \r\n                         const long * NTL_RESTRICT A, long k)\r\n{\r\n   long n = 1L << k;\r\n   long* NTL_RESTRICT rev;\r\n   long i, j;\r\n\r\n   rev = brc_mem[k].elts();\r\n   if (!rev) rev = BRC_init(k);\r\n\r\n   for (i = 0; i < n; i++)\r\n      B[rev[i]] = A[i];\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid COBRA(long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n   NTL_THREAD_LOCAL static Vec<long> BRC_temp;\r\n\r\n   long q = NTL_BRC_Q;\r\n   long k1 = k - 2*q;\r\n   long * NTL_RESTRICT rev_k1, * NTL_RESTRICT rev_q;\r\n   long *NTL_RESTRICT T;\r\n   long a, b, c, a1, b1, c1;\r\n   long i, j;\r\n\r\n   rev_k1 = brc_mem[k1].elts();\r\n   if (!rev_k1) rev_k1 = BRC_init(k1);\r\n\r\n   rev_q = brc_mem[q].elts();\r\n   if (!rev_q) rev_q = BRC_init(q);\r\n\r\n   T = BRC_temp.elts();\r\n   if (!T) {\r\n      BRC_temp.SetLength(1L << (2*q));\r\n      T = BRC_temp.elts();\r\n   }\r\n\r\n   for (b = 0; b < (1L << k1); b++) {\r\n      b1 = rev_k1[b]; \r\n      for (a = 0; a < (1L << q); a++) {\r\n         a1 = rev_q[a]; \r\n         for (c = 0; c < (1L << q); c++) \r\n            T[(a1 << q) + c] = A[(a << (k1+q)) + (b << q) + c]; \r\n      }\r\n\r\n      for (c = 0; c < (1L << q); c++) {\r\n         c1 = rev_q[c];\r\n         for (a1 = 0; a1 < (1L << q); a1++) \r\n            B[(c1 << (k1+q)) + (b1 << q) + a1] = T[(a1 << q) + c];\r\n      }\r\n   }\r\n}\r\n\r\nstatic\r\nvoid BitReverseCopy(long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n   if (k <= NTL_BRC_THRESH) \r\n      BasicBitReverseCopy(B, A, k);\r\n   else\r\n      COBRA(B, A, k);\r\n}\r\n\r\n\r\nstatic\r\nvoid BasicBitReverseCopy(unsigned long * NTL_RESTRICT B, \r\n                         const long * NTL_RESTRICT A, long k)\r\n{\r\n   long n = 1L << k;\r\n   long* NTL_RESTRICT rev;\r\n   long i, j;\r\n\r\n   rev = brc_mem[k].elts();\r\n   if (!rev) rev = BRC_init(k);\r\n\r\n   for (i = 0; i < n; i++)\r\n      B[rev[i]] = A[i];\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid COBRA(unsigned long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n   NTL_THREAD_LOCAL static Vec<unsigned long> BRC_temp;\r\n\r\n   long q = NTL_BRC_Q;\r\n   long k1 = k - 2*q;\r\n   long * NTL_RESTRICT rev_k1, * NTL_RESTRICT rev_q;\r\n   unsigned long *NTL_RESTRICT T;\r\n   long a, b, c, a1, b1, c1;\r\n   long i, j;\r\n\r\n   rev_k1 = brc_mem[k1].elts();\r\n   if (!rev_k1) rev_k1 = BRC_init(k1);\r\n\r\n   rev_q = brc_mem[q].elts();\r\n   if (!rev_q) rev_q = BRC_init(q);\r\n\r\n   T = BRC_temp.elts();\r\n   if (!T) {\r\n      BRC_temp.SetLength(1L << (2*q));\r\n      T = BRC_temp.elts();\r\n   }\r\n\r\n   for (b = 0; b < (1L << k1); b++) {\r\n      b1 = rev_k1[b]; \r\n      for (a = 0; a < (1L << q); a++) {\r\n         a1 = rev_q[a]; \r\n         for (c = 0; c < (1L << q); c++) \r\n            T[(a1 << q) + c] = A[(a << (k1+q)) + (b << q) + c]; \r\n      }\r\n\r\n      for (c = 0; c < (1L << q); c++) {\r\n         c1 = rev_q[c];\r\n         for (a1 = 0; a1 < (1L << q); a1++) \r\n            B[(c1 << (k1+q)) + (b1 << q) + a1] = T[(a1 << q) + c];\r\n      }\r\n   }\r\n}\r\n\r\nstatic\r\nvoid BitReverseCopy(unsigned long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n   if (k <= NTL_BRC_THRESH) \r\n      BasicBitReverseCopy(B, A, k);\r\n   else\r\n      COBRA(B, A, k);\r\n}\r\n\r\n\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root)\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n   if (k <= 1) {\r\n      if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n      }\r\n      if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n         A[0] = a0;\r\n         A[1] = a1;\r\n\t return;\r\n      }\r\n   }\r\n\r\n   // assume k > 1\r\n\r\n   \r\n\r\n   NTL_THREAD_LOCAL static Vec<long> wtab_store;\r\n   NTL_THREAD_LOCAL static Vec<mulmod_precon_t> wqinvtab_store;\r\n   NTL_THREAD_LOCAL static Vec<long> AA_store;\r\n\r\n   wtab_store.SetLength(1L << (k-2));\r\n   wqinvtab_store.SetLength(1L << (k-2));\r\n   AA_store.SetLength(1L << k);\r\n\r\n   long * NTL_RESTRICT wtab = wtab_store.elts();\r\n   mulmod_precon_t * NTL_RESTRICT wqinvtab = wqinvtab_store.elts();\r\n   long *AA = AA_store.elts();\r\n\r\n   double qinv = 1/((double) q);\r\n\r\n   wtab[0] = 1;\r\n   wqinvtab[0] = PrepMulModPrecon(1, q, qinv);\r\n\r\n\r\n   BitReverseCopy(AA, a, k);\r\n\r\n   long n = 1L << k;\r\n\r\n   long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\r\n\r\n   long w;\r\n   mulmod_precon_t wqinv;\r\n\r\n   // s = 1\r\n\r\n   for (i = 0; i < n; i += 2) {\r\n      t = AA[i + 1];\r\n      u = AA[i];\r\n      AA[i] = AddMod(u, t, q);\r\n      AA[i+1] = SubMod(u, t, q);\r\n   }\r\n\r\n   \r\n  \r\n   for (s = 2; s < k; s++) {\r\n      m = 1L << s;\r\n      m_half = 1L << (s-1);\r\n      m_fourth = 1L << (s-2);\r\n\r\n      w = root[s];\r\n      wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n      // prepare wtab...\r\n\r\n      if (s == 2) {\r\n         wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\r\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n      }\r\n      else {\r\n         // some software pipelining\r\n\r\n         i = m_half-1; j = m_fourth-1;\r\n         wtab[i-1] = wtab[j];\r\n         wqinvtab[i-1] = wqinvtab[j];\r\n         wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\r\n\r\n         i -= 2; j --;\r\n\r\n         for (; i >= 0; i -= 2, j --) {\r\n            long wp2 = wtab[i+2];\r\n            long wm1 = wtab[j];\r\n            wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\r\n            wtab[i-1] = wm1;\r\n            wqinvtab[i-1] = wqinvtab[j];\r\n            wtab[i] = MulModPrecon(wm1, w, q, wqinv);\r\n         }\r\n\r\n         wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n      }\r\n\r\n      for (i = 0; i < n; i+= m) {\r\n\r\n         long * NTL_RESTRICT AA0 = &AA[i];\r\n         long * NTL_RESTRICT AA1 = &AA[i + m_half];\r\n\r\n\r\n// #ifdef NTL_LOOP_UNROLL\r\n#if 1\r\n          \r\n         t = AA1[0];\r\n         u = AA0[0];\r\n         t1 = MulModPrecon(AA1[1], w, q, wqinv);\r\n         u1 = AA0[1];\r\n\r\n\r\n\r\n         for (j = 0; j < m_half-2; j += 2) {\r\n            long a02 = AA0[j+2];\r\n            long a03 = AA0[j+3];\r\n            long a12 = AA1[j+2];\r\n            long a13 = AA1[j+3];\r\n            long w2 = wtab[j+2];\r\n            long w3 = wtab[j+3];\r\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n            tt = MulModPrecon(a12, w2, q, wqi2);\r\n            long b00 = AddMod(u, t, q);\r\n            long b10 = SubMod(u, t, q);\r\n            t = tt;\r\n            u = a02;\r\n\r\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n            long b01 = AddMod(u1, t1, q);\r\n            long b11 = SubMod(u1, t1, q);\r\n            t1 = tt1;\r\n            u1 = a03;\r\n\r\n            AA0[j] = b00;\r\n            AA1[j] = b10;\r\n            AA0[j+1] = b01;\r\n            AA1[j+1] = b11;\r\n         }\r\n\r\n\r\n         AA0[j] = AddMod(u, t, q);\r\n         AA1[j] = SubMod(u, t, q);\r\n         AA0[j + 1] = AddMod(u1, t1, q);\r\n         AA1[j + 1] = SubMod(u1, t1, q);\r\n\r\n\r\n#else\r\n\r\n          \r\n         t = AA1[0];\r\n         u = AA0[0];\r\n\r\n         for (j = 0; j < m_half-1; j++) {\r\n            long a02 = AA0[j+1];\r\n            long a12 = AA1[j+1];\r\n            long w2 = wtab[j+1];\r\n            mulmod_precon_t wqi2 = wqinvtab[j+1];\r\n\r\n            tt = MulModPrecon(a12, w2, q, wqi2);\r\n            long b00 = AddMod(u, t, q);\r\n            long b10 = SubMod(u, t, q);\r\n            t = tt;\r\n            u = a02;\r\n\r\n            AA0[j] = b00;\r\n            AA1[j] = b10;\r\n         }\r\n\r\n\r\n         AA0[j] = AddMod(u, t, q);\r\n         AA1[j] = SubMod(u, t, q);\r\n\r\n\r\n#endif\r\n      }\r\n   }\r\n\r\n\r\n   // s == k...special case\r\n\r\n   m = 1L << s;\r\n   m_half = 1L << (s-1);\r\n   m_fourth = 1L << (s-2);\r\n\r\n\r\n   w = root[s];\r\n   wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n   // j = 0, 1\r\n\r\n   t = AA[m_half];\r\n   u = AA[0];\r\n   t1 = MulModPrecon(AA[1+ m_half], w, q, wqinv);\r\n   u1 = AA[1];\r\n\r\n   A[0] = AddMod(u, t, q);\r\n   A[m_half] = SubMod(u, t, q);\r\n   A[1] = AddMod(u1, t1, q);\r\n   A[1 + m_half] = SubMod(u1, t1, q);\r\n\r\n   for (j = 2; j < m_half; j += 2) {\r\n      t = MulModPrecon(AA[j + m_half], wtab[j >> 1], q, wqinvtab[j >> 1]);\r\n      u = AA[j];\r\n      t1 = MulModPrecon(AA[j + 1+ m_half], wtab[j >> 1], q, \r\n                        wqinvtab[j >> 1]);\r\n      t1 = MulModPrecon(t1, w, q, wqinv);\r\n      u1 = AA[j + 1];\r\n\r\n      A[j] = AddMod(u, t, q);\r\n      A[j + m_half] = SubMod(u, t, q);\r\n      A[j + 1] = AddMod(u1, t1, q);\r\n      A[j + 1 + m_half] = SubMod(u1, t1, q);\r\n     \r\n   }\r\n}\r\n\r\n\r\n#if (!defined(NTL_FFT_LAZYMUL) || (!defined(NTL_SPMM_ULL) && !defined(NTL_SPMM_ASM)))\r\n\r\n// FFT with precomputed tables \r\n\r\n\r\nstatic\r\nvoid PrecompFFTMultipliers(long k, long q, const long *root, const FFTMultipliers& tab)\r\n{\r\n   if (k < 1) LogicError(\"PrecompFFTMultipliers: bad input\");\r\n\r\n   do {  // NOTE: thread safe lazy init\r\n      FFTMultipliers::Builder bld(tab, k+1);\r\n      long amt = bld.amt();\r\n      if (!amt) break;\r\n\r\n      long first = k+1-amt;\r\n      // initialize entries first..k\r\n\r\n\r\n      double qinv = 1/((double) q);\r\n\r\n      for (long s = first; s <= k; s++) {\r\n         UniquePtr<FFTVectorPair> item;\r\n\r\n         if (s == 0) {\r\n            bld.move(item); // position 0 not used\r\n            continue;\r\n         }\r\n\r\n         if (s == 1) {\r\n            item.make();\r\n            item->wtab_precomp.SetLength(1);\r\n            item->wqinvtab_precomp.SetLength(1);\r\n            item->wtab_precomp[0] = 1;\r\n            item->wqinvtab_precomp[0] = PrepMulModPrecon(1, q, qinv);\r\n            bld.move(item);\r\n            continue;\r\n         }\r\n\r\n         item.make();\r\n         item->wtab_precomp.SetLength(1L << (s-1));\r\n         item->wqinvtab_precomp.SetLength(1L << (s-1));\r\n\r\n         long m = 1L << s;\r\n         long m_half = 1L << (s-1);\r\n         long m_fourth = 1L << (s-2);\r\n\r\n         const long *wtab_last = tab[s-1]->wtab_precomp.elts();\r\n         const mulmod_precon_t *wqinvtab_last = tab[s-1]->wqinvtab_precomp.elts();\r\n\r\n         long *wtab = item->wtab_precomp.elts();\r\n         mulmod_precon_t *wqinvtab = item->wqinvtab_precomp.elts();\r\n\r\n         for (long i = 0; i < m_fourth; i++) {\r\n            wtab[i] = wtab_last[i];\r\n            wqinvtab[i] = wqinvtab_last[i];\r\n         } \r\n\r\n         long w = root[s];\r\n         mulmod_precon_t wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n         // prepare wtab...\r\n\r\n         if (s == 2) {\r\n            wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\r\n            wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n         }\r\n         else {\r\n            // some software pipelining\r\n            long i, j;\r\n\r\n            i = m_half-1; j = m_fourth-1;\r\n            wtab[i-1] = wtab[j];\r\n            wqinvtab[i-1] = wqinvtab[j];\r\n            wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\r\n\r\n            i -= 2; j --;\r\n\r\n            for (; i >= 0; i -= 2, j --) {\r\n               long wp2 = wtab[i+2];\r\n               long wm1 = wtab[j];\r\n               wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\r\n               wtab[i-1] = wm1;\r\n               wqinvtab[i-1] = wqinvtab[j];\r\n               wtab[i] = MulModPrecon(wm1, w, q, wqinv);\r\n            }\r\n\r\n            wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n         }\r\n\r\n         bld.move(item);\r\n      }\r\n   } while (0);\r\n}\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root, const FFTMultipliers& tab)\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n   if (k <= 1) {\r\n      if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n      }\r\n      if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n         A[0] = a0;\r\n         A[1] = a1;\r\n\t return;\r\n      }\r\n   }\r\n\r\n\r\n\r\n   // assume k > 1\r\n\r\n   if (k >= tab.length()) PrecompFFTMultipliers(k, q, root, tab);\r\n\r\n   NTL_THREAD_LOCAL static Vec<long> AA_store;\r\n   AA_store.SetLength(1L << k);\r\n   long *AA = AA_store.elts();\r\n\r\n   BitReverseCopy(AA, a, k);\r\n\r\n   long n = 1L << k;\r\n\r\n   long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\r\n\r\n   // s = 1\r\n\r\n   for (i = 0; i < n; i += 2) {\r\n      t = AA[i + 1];\r\n      u = AA[i];\r\n      AA[i] = AddMod(u, t, q);\r\n      AA[i+1] = SubMod(u, t, q);\r\n   }\r\n   \r\n  \r\n   for (s = 2; s < k; s++) {\r\n      m = 1L << s;\r\n      m_half = 1L << (s-1);\r\n      m_fourth = 1L << (s-2);\r\n\r\n      const long* wtab = tab[s]->wtab_precomp.elts();\r\n      const mulmod_precon_t *wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n      for (i = 0; i < n; i+= m) {\r\n\r\n         long *AA0 = &AA[i];\r\n         long *AA1 = &AA[i + m_half];\r\n\r\n#ifdef NTL_PIPELINE\r\n\r\n// pipelining: seems to be faster\r\n          \r\n         t = AA1[0];\r\n         u = AA0[0];\r\n         t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\r\n         u1 = AA0[1];\r\n\r\n         for (j = 0; j < m_half-2; j += 2) {\r\n            long a02 = AA0[j+2];\r\n            long a03 = AA0[j+3];\r\n            long a12 = AA1[j+2];\r\n            long a13 = AA1[j+3];\r\n            long w2 = wtab[j+2];\r\n            long w3 = wtab[j+3];\r\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n            tt = MulModPrecon(a12, w2, q, wqi2);\r\n            long b00 = AddMod(u, t, q);\r\n            long b10 = SubMod(u, t, q);\r\n\r\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n            long b01 = AddMod(u1, t1, q);\r\n            long b11 = SubMod(u1, t1, q);\r\n\r\n            AA0[j] = b00;\r\n            AA1[j] = b10;\r\n            AA0[j+1] = b01;\r\n            AA1[j+1] = b11;\r\n\r\n\r\n            t = tt;\r\n            u = a02;\r\n            t1 = tt1;\r\n            u1 = a03;\r\n         }\r\n\r\n\r\n         AA0[j] = AddMod(u, t, q);\r\n         AA1[j] = SubMod(u, t, q);\r\n         AA0[j + 1] = AddMod(u1, t1, q);\r\n         AA1[j + 1] = SubMod(u1, t1, q);\r\n      }\r\n#else\r\n         for (j = 0; j < m_half; j += 2) {\r\n            const long a00 = AA0[j];\r\n            const long a01 = AA0[j+1];\r\n            const long a10 = AA1[j];\r\n            const long a11 = AA1[j+1];\r\n\r\n            const long w0 = wtab[j];\r\n            const long w1 = wtab[j+1];\r\n            const mulmod_precon_t wqi0 = wqinvtab[j];\r\n            const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n\r\n            const long tt = MulModPrecon(a10, w0, q, wqi0);\r\n            const long uu = a00;\r\n            const long b00 = AddMod(uu, tt, q); \r\n            const long b10 = SubMod(uu, tt, q);\r\n\r\n            const long tt1 = MulModPrecon(a11, w1, q, wqi1);\r\n            const long uu1 = a01;\r\n            const long b01 = AddMod(uu1, tt1, q); \r\n            const long b11 = SubMod(uu1, tt1, q);\r\n\r\n            AA0[j] = b00;\r\n            AA0[j+1] = b01;\r\n            AA1[j] = b10;\r\n            AA1[j+1] = b11;\r\n         }\r\n      }\r\n#endif\r\n   }\r\n\r\n\r\n   // s == k, special case\r\n   {\r\n      m = 1L << s;\r\n      m_half = 1L << (s-1);\r\n      m_fourth = 1L << (s-2);\r\n\r\n      const long* wtab = tab[s]->wtab_precomp.elts();\r\n      const mulmod_precon_t *wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n      for (i = 0; i < n; i+= m) {\r\n\r\n         long *AA0 = &AA[i];\r\n         long *AA1 = &AA[i + m_half];\r\n         long *A0 = &A[i];\r\n         long *A1 = &A[i + m_half];\r\n\r\n#ifdef NTL_PIPELINE\r\n\r\n// pipelining: seems to be faster\r\n          \r\n         t = AA1[0];\r\n         u = AA0[0];\r\n         t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\r\n         u1 = AA0[1];\r\n\r\n         for (j = 0; j < m_half-2; j += 2) {\r\n            long a02 = AA0[j+2];\r\n            long a03 = AA0[j+3];\r\n            long a12 = AA1[j+2];\r\n            long a13 = AA1[j+3];\r\n            long w2 = wtab[j+2];\r\n            long w3 = wtab[j+3];\r\n            mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n            mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n            tt = MulModPrecon(a12, w2, q, wqi2);\r\n            long b00 = AddMod(u, t, q);\r\n            long b10 = SubMod(u, t, q);\r\n\r\n            tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n            long b01 = AddMod(u1, t1, q);\r\n            long b11 = SubMod(u1, t1, q);\r\n\r\n            A0[j] = b00;\r\n            A1[j] = b10;\r\n            A0[j+1] = b01;\r\n            A1[j+1] = b11;\r\n\r\n\r\n            t = tt;\r\n            u = a02;\r\n            t1 = tt1;\r\n            u1 = a03;\r\n         }\r\n\r\n\r\n         A0[j] = AddMod(u, t, q);\r\n         A1[j] = SubMod(u, t, q);\r\n         A0[j + 1] = AddMod(u1, t1, q);\r\n         A1[j + 1] = SubMod(u1, t1, q);\r\n      }\r\n#else\r\n         for (j = 0; j < m_half; j += 2) {\r\n            const long a00 = AA0[j];\r\n            const long a01 = AA0[j+1];\r\n            const long a10 = AA1[j];\r\n            const long a11 = AA1[j+1];\r\n\r\n            const long w0 = wtab[j];\r\n            const long w1 = wtab[j+1];\r\n            const mulmod_precon_t wqi0 = wqinvtab[j];\r\n            const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n\r\n            const long tt = MulModPrecon(a10, w0, q, wqi0);\r\n            const long uu = a00;\r\n            const long b00 = AddMod(uu, tt, q); \r\n            const long b10 = SubMod(uu, tt, q);\r\n\r\n            const long tt1 = MulModPrecon(a11, w1, q, wqi1);\r\n            const long uu1 = a01;\r\n            const long b01 = AddMod(uu1, tt1, q); \r\n            const long b11 = SubMod(uu1, tt1, q);\r\n\r\n            A0[j] = b00;\r\n            A0[j+1] = b01;\r\n            A1[j] = b10;\r\n            A1[j+1] = b11;\r\n         }\r\n      }\r\n#endif\r\n   }\r\n\r\n}\r\n\r\n\r\n#else\r\n\r\n// FFT with precomputed tables and David Harvey's lazy multiplication\r\n// strategy:\r\n//   David Harvey.\r\n//   Faster arithmetic for number-theoretic transforms.\r\n//   J. Symb. Comp. 60 (2014) 113\u2013119. \r\n\r\n\r\n\r\nstatic inline \r\nunsigned long LazyPrepMulModPrecon(long b, long n, double ninv)\r\n{\r\n   unsigned long q, r;\r\n\r\n   q = (long) ( (((double) b) * NTL_SP_FBOUND) * ninv ); \r\n   r = (((unsigned long) b) << NTL_SP_NBITS ) - q * ((unsigned long) n);\r\n\r\n   if (r >> (NTL_BITS_PER_LONG-1)) {\r\n      q--;\r\n      r += n;\r\n   }\r\n   else if (((long) r) >= n) {\r\n      q++;\r\n      r -=n;\r\n   }\r\n\r\n   unsigned long res = q << (NTL_BITS_PER_LONG - NTL_SP_NBITS);\r\n   long qq, rr;\r\n\r\n   rr = MulDivRem(qq, (long) r, 4, n, 4*ninv);\r\n\r\n   res = res + (qq << (NTL_BITS_PER_LONG - NTL_SP_NBITS-2));\r\n\r\n   return res;\r\n}\r\n\r\nstatic inline \r\nunsigned long LazyMulModPrecon(unsigned long a, unsigned long b, \r\n                               unsigned long n, unsigned long bninv)\r\n{\r\n   unsigned long q = MulHiUL(a, bninv);\r\n   unsigned long res = a*b - q*n;\r\n   return res;\r\n}\r\n\r\n\r\nstatic inline \r\nunsigned long LazyReduce(unsigned long a, unsigned long q)\r\n{\r\n  unsigned long res;\r\n#if (NTL_ARITH_RIGHT_SHIFT && defined(NTL_AVOID_BRANCHING) && !defined(NTL_CLEAN_INT))\r\n  res = a - q;\r\n  res  += (((long) res) >> (NTL_BITS_PER_LONG-1)) & q; \r\n#elif (defined(NTL_AVOID_BRANCHING))\r\n  res = a - q;\r\n  res  += (-(res >> (NTL_BITS_PER_LONG-1))) & q; \r\n#else\r\n  if (a >= q)\r\n    res = a - q;\r\n  else\r\n    res = a;\r\n#endif\r\n\r\n  return res;\r\n}\r\n\r\n\r\nstatic\r\nvoid LazyPrecompFFTMultipliers(long k, long q, const long *root, const FFTMultipliers& tab)\r\n{\r\n   if (k < 1) LogicError(\"LazyPrecompFFTMultipliers: bad input\");\r\n\r\n   do { // NOTE: thread safe lazy init\r\n      FFTMultipliers::Builder bld(tab, k+1);\r\n      long amt = bld.amt();\r\n      if (!amt) break;\r\n\r\n      long first = k+1-amt;\r\n      // initialize entries first..k\r\n\r\n\r\n      double qinv = 1/((double) q);\r\n\r\n      for (long s = first; s <= k; s++) {\r\n         UniquePtr<FFTVectorPair> item;\r\n\r\n         if (s == 0) {\r\n            bld.move(item); // position 0 not used\r\n            continue;\r\n         }\r\n\r\n         if (s == 1) {\r\n            item.make();\r\n            item->wtab_precomp.SetLength(1);\r\n            item->wqinvtab_precomp.SetLength(1);\r\n            item->wtab_precomp[0] = 1;\r\n            item->wqinvtab_precomp[0] = LazyPrepMulModPrecon(1, q, qinv);\r\n            bld.move(item);\r\n            continue;\r\n         }\r\n\r\n         item.make();\r\n         item->wtab_precomp.SetLength(1L << (s-1));\r\n         item->wqinvtab_precomp.SetLength(1L << (s-1));\r\n\r\n         long m = 1L << s;\r\n         long m_half = 1L << (s-1);\r\n         long m_fourth = 1L << (s-2);\r\n\r\n         const long *wtab_last = tab[s-1]->wtab_precomp.elts();\r\n         const mulmod_precon_t *wqinvtab_last = tab[s-1]->wqinvtab_precomp.elts();\r\n\r\n         long *wtab = item->wtab_precomp.elts();\r\n         mulmod_precon_t *wqinvtab = item->wqinvtab_precomp.elts();\r\n\r\n         for (long i = 0; i < m_fourth; i++) {\r\n            wtab[i] = wtab_last[i];\r\n            wqinvtab[i] = wqinvtab_last[i];\r\n         } \r\n\r\n         long w = root[s];\r\n         mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, qinv);\r\n\r\n         // prepare wtab...\r\n\r\n         if (s == 2) {\r\n            wtab[1] = LazyReduce(LazyMulModPrecon(wtab[0], w, q, wqinv), q);\r\n            wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\r\n         }\r\n         else {\r\n            // some software pipelining\r\n            long i, j;\r\n\r\n            i = m_half-1; j = m_fourth-1;\r\n            wtab[i-1] = wtab[j];\r\n            wqinvtab[i-1] = wqinvtab[j];\r\n            wtab[i] = LazyReduce(LazyMulModPrecon(wtab[i-1], w, q, wqinv), q);\r\n\r\n            i -= 2; j --;\r\n\r\n            for (; i >= 0; i -= 2, j --) {\r\n               long wp2 = wtab[i+2];\r\n               long wm1 = wtab[j];\r\n               wqinvtab[i+2] = LazyPrepMulModPrecon(wp2, q, qinv);\r\n               wtab[i-1] = wm1;\r\n               wqinvtab[i-1] = wqinvtab[j];\r\n               wtab[i] = LazyReduce(LazyMulModPrecon(wm1, w, q, wqinv), q);\r\n            }\r\n\r\n            wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\r\n         }\r\n\r\n         bld.move(item);\r\n      }\r\n   } while (0);\r\n}\r\n\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root, const FFTMultipliers& tab)\r\n\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n   if (k <= 1) {\r\n      if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n      }\r\n      if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n         A[0] = a0;\r\n         A[1] = a1;\r\n\t return;\r\n      }\r\n   }\r\n\r\n   // assume k > 1\r\n\r\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, root, tab);\r\n\r\n   NTL_THREAD_LOCAL static Vec<unsigned long> AA_store;\r\n   AA_store.SetLength(1L << k);\r\n   unsigned long *AA = AA_store.elts();\r\n\r\n\r\n\r\n   BitReverseCopy(AA, a, k);\r\n\r\n   long n = 1L << k;\r\n\r\n\r\n   /* we work with redundant representations, in the range [0, 4q) */\r\n\r\n\r\n\r\n   long s, m, m_half, m_fourth, i, j; \r\n   unsigned long t, u, t1, u1;\r\n\r\n   long two_q = 2 * q; \r\n\r\n   // s = 1\r\n\r\n   for (i = 0; i < n; i += 2) {\r\n      t = AA[i + 1];\r\n      u = AA[i];\r\n      AA[i] = u + t;\r\n      AA[i+1] = u - t + q;\r\n   }\r\n\r\n\r\n   // s = 2\r\n\r\n   {\r\n      const long * NTL_RESTRICT wtab = tab[2]->wtab_precomp.elts();\r\n      const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab[2]->wqinvtab_precomp.elts();\r\n\r\n\r\n      for (i = 0; i < n; i += 4) {\r\n\r\n         unsigned long * NTL_RESTRICT AA0 = &AA[i];\r\n         unsigned long * NTL_RESTRICT AA1 = &AA[i + 2];\r\n\r\n         {\r\n            const long w1 = wtab[0];\r\n            const mulmod_precon_t wqi1 = wqinvtab[0];\r\n            const unsigned long a11 = AA1[0];\r\n            const unsigned long a01 = AA0[0];\r\n\r\n            const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n            const unsigned long uu1 = LazyReduce(a01, two_q);\r\n            const unsigned long b01 = uu1 + tt1; \r\n            const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n            AA0[0] = b01;\r\n            AA1[0] = b11;\r\n         }\r\n         {\r\n            const long w1 = wtab[1];\r\n            const mulmod_precon_t wqi1 = wqinvtab[1];\r\n            const unsigned long a11 = AA1[1];\r\n            const unsigned long a01 = AA0[1];\r\n\r\n            const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n            const unsigned long uu1 = LazyReduce(a01, two_q);\r\n            const unsigned long b01 = uu1 + tt1; \r\n            const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n            AA0[1] = b01;\r\n            AA1[1] = b11;\r\n         }\r\n      }\r\n   }\r\n\r\n\r\n   //  s = 3..k\r\n\r\n   for (s = 3; s <= k; s++) {\r\n      m = 1L << s;\r\n      m_half = 1L << (s-1);\r\n      m_fourth = 1L << (s-2);\r\n\r\n      const long* NTL_RESTRICT wtab = tab[s]->wtab_precomp.elts();\r\n      const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n      for (i = 0; i < n; i += m) {\r\n\r\n         unsigned long * NTL_RESTRICT AA0 = &AA[i];\r\n         unsigned long * NTL_RESTRICT AA1 = &AA[i + m_half];\r\n\r\n#ifdef NTL_LOOP_UNROLL\r\n\r\n         for (j = 0; j < m_half; j += 4) {\r\n            {\r\n               const long w1 = wtab[j+0];\r\n               const mulmod_precon_t wqi1 = wqinvtab[j+0];\r\n               const unsigned long a11 = AA1[j+0];\r\n               const unsigned long a01 = AA0[j+0];\r\n\r\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n               const unsigned long uu1 = LazyReduce(a01, two_q);\r\n               const unsigned long b01 = uu1 + tt1; \r\n               const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n               AA0[j+0] = b01;\r\n               AA1[j+0] = b11;\r\n            }\r\n            {\r\n               const long w1 = wtab[j+1];\r\n               const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n               const unsigned long a11 = AA1[j+1];\r\n               const unsigned long a01 = AA0[j+1];\r\n\r\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n               const unsigned long uu1 = LazyReduce(a01, two_q);\r\n               const unsigned long b01 = uu1 + tt1; \r\n               const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n               AA0[j+1] = b01;\r\n               AA1[j+1] = b11;\r\n            }\r\n            {\r\n               const long w1 = wtab[j+2];\r\n               const mulmod_precon_t wqi1 = wqinvtab[j+2];\r\n               const unsigned long a11 = AA1[j+2];\r\n               const unsigned long a01 = AA0[j+2];\r\n\r\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n               const unsigned long uu1 = LazyReduce(a01, two_q);\r\n               const unsigned long b01 = uu1 + tt1; \r\n               const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n               AA0[j+2] = b01;\r\n               AA1[j+2] = b11;\r\n            }\r\n            {\r\n               const long w1 = wtab[j+3];\r\n               const mulmod_precon_t wqi1 = wqinvtab[j+3];\r\n               const unsigned long a11 = AA1[j+3];\r\n               const unsigned long a01 = AA0[j+3];\r\n\r\n               const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n               const unsigned long uu1 = LazyReduce(a01, two_q);\r\n               const unsigned long b01 = uu1 + tt1; \r\n               const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n               AA0[j+3] = b01;\r\n               AA1[j+3] = b11;\r\n            }\r\n         }\r\n#else\r\n\r\n         for (j = 0; j < m_half; j++) {\r\n            const long w1 = wtab[j];\r\n            const mulmod_precon_t wqi1 = wqinvtab[j];\r\n            const unsigned long a11 = AA1[j];\r\n            const unsigned long a01 = AA0[j];\r\n\r\n            const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n            const unsigned long uu1 = LazyReduce(a01, two_q);\r\n            const unsigned long b01 = uu1 + tt1; \r\n            const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n            AA0[j] = b01;\r\n            AA1[j] = b11;\r\n         }\r\n\r\n#endif\r\n\r\n      }\r\n   }\r\n\r\n   /* need to reduce redundant representations */\r\n\r\n   for (i = 0; i < n; i++) {\r\n      unsigned long tmp = LazyReduce(AA[i], two_q);\r\n      A[i] = LazyReduce(tmp, q);\r\n   }\r\n}\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "cb6881730b64c936dc0b7642f3787ab74136072e", "size": 34608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/FFT.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": "WinNTL-8_1_2/src/FFT.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": "WinNTL-8_1_2/src/FFT.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "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": 24.354679803, "max_line_length": 94, "alphanum_fraction": 0.4691400832, "num_tokens": 11419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6917085090565984}}
{"text": "#pragma once\n\n/*\n * This file declares and implements a class representing a cubic spline.\n * After instantiating a Spline points (x, y) can be added; call calculate()\n * to compute coefficients of the cubic polynomial for each interval.\n * Spline::operator()(double x) computes the corresponding value of y\n * according to the computed spline.\n * \n * This isn't an elegant or optimal implementation but it gets the job done\n * for my purposes. Eigen is a dependency to do an SVD factorization to\n * compute the spline coefficients (the matrix obtained in my use cases\n * is numerically low-rank).\n */\n\n#include <cassert>\n#include <vector>\n\n#include <Eigen/Dense>\n\nnamespace {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nVectorXd find_spline_coeffs(const std::vector<double>& xs_, \n                            const std::vector<double>& ys_)\n{\n    assert(xs_.size() == ys_.size());\n    unsigned nintervals = xs_.size() - 1;\n    MatrixXd A = MatrixXd::Zero(nintervals*4, nintervals*4);\n    VectorXd B = VectorXd::Zero(nintervals*4);\n\n    A(0, 0) = 3*xs_[0]*xs_[0];\n    A(0, 1) = 2*xs_[0];\n    A(0, 2) = 1.0;\n    A(1, 0) = xs_[0] * xs_[0] * xs_[0];\n    A(1, 1) = xs_[0] * xs_[0];\n    A(1, 2) = xs_[0];\n    A(1, 3) = 1.0;\n    B(1) = ys_[0];\n\n    unsigned curr_row = 2;\n    for (unsigned node = 1; node < nintervals; ++node) {\n        double xn2 = xs_[node] * xs_[node];\n        double xn3 = xn2 * xs_[node];\n        unsigned j = (node - 1) * 4;\n        A(curr_row, j) = xn3;\n        A(curr_row, j+1) = xn2;\n        A(curr_row, j+2) = xs_[node];\n        A(curr_row, j+3) = 1.0;\n        B(curr_row) = ys_[node];\n        curr_row += 1;\n        A(curr_row, j) = 3*xn2;\n        A(curr_row, j+1) = 2*xs_[node];\n        A(curr_row, j+2) = 1.0;\n        A(curr_row, j+4) = -3*xn2;\n        A(curr_row, j+5) = -2*xs_[node];\n        A(curr_row, j+6) = -1.0;\n        curr_row += 1;\n        A(curr_row, j) = 6*xs_[node];\n        A(curr_row, j+1) = 2.0;\n        A(curr_row, j+4) = -6*xs_[node];\n        A(curr_row, j+5) = -2.0;\n        curr_row += 1;\n        A(curr_row, j+4) = xn3;\n        A(curr_row, j+5) = xn2;\n        A(curr_row, j+6) = xs_[node];\n        A(curr_row, j+7) = 1.0;\n        B(curr_row) = ys_[node];\n        curr_row += 1;\n    }\n\n    unsigned j = (nintervals - 1) * 4;\n    A(curr_row, j) = xs_[nintervals] * xs_[nintervals] * xs_[nintervals];\n    A(curr_row, j+1) = xs_[nintervals] * xs_[nintervals];\n    A(curr_row, j+2) = xs_[nintervals];\n    A(curr_row, j+3) = 1.0;\n    B(curr_row++) = ys_[nintervals];\n    A(curr_row, j) = 3*xs_[nintervals]*xs_[nintervals];\n    A(curr_row, j+1) = 2 * xs_[nintervals];\n    A(curr_row, j+2) = 1.0;\n\n    return A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n}\n\n}\n\nclass Spline\n{\nprivate:\n    struct Coefficients {\n        double a; double b;\n        double c; double d;\n    };\n    std::vector<double> xs_;\n    std::vector<double> ys_;\n    std::vector<Coefficients> coeffs_;\n\n    template <typename It>\n    It get_element_position(double x, It start, It end) const\n    {\n        if (end == start) {\n            return start;\n        } else if (end - start == 1) {\n            return *start > x ? start : end;\n        } else {\n            It middle = start + (end - start) / 2;\n            if (*middle > x) {\n                return get_element_position(x, start, middle);\n            } else {\n                return get_element_position(x, middle, end);\n            }\n        }\n    }\n\npublic:\n    typedef std::pair<double, double> Point;\n\n    void add_point(Point p)\n    {\n        auto it = get_element_position(p.first, xs_.begin(), xs_.end());\n        auto offset = it - xs_.begin();\n        xs_.insert(it, p.first);\n        ys_.insert(ys_.begin() + offset, p.second);\n    }\n\n    void reset()\n    {\n        *this = Spline();\n    }\n\n    void calculate()\n    {\n        assert(xs_.size() == ys_.size());\n        // X is a vector of a, b, c, d for each interval in the spline\n        // in that order.\n        auto X = find_spline_coeffs(xs_, ys_);\n        coeffs_.resize(xs_.size() - 1);\n        for (unsigned i = 0; i < coeffs_.size()*4; i += 4)\n            coeffs_[i/4] = Coefficients{ X(i), X(i + 1), X(i + 2), X(i + 3) };\n    }\n\n    double operator()(double x) const\n    {\n        auto it = get_element_position(x, xs_.begin(), xs_.end());\n        assert(!(it == xs_.begin() || it == xs_.end()));\n        const auto& coeffs = coeffs_[it - xs_.begin() - 1];\n        return coeffs.a * x * x * x + coeffs.b * x * x + coeffs.c * x +\n            coeffs.d;\n    }\n};\n", "meta": {"hexsha": "e8733b9dbd7d56be98f718e7cc6c17921948e2f9", "size": 4518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spline.hpp", "max_stars_repo_name": "slmcbane/fractalmake", "max_stars_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spline.hpp", "max_issues_repo_name": "slmcbane/fractalmake", "max_issues_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline.hpp", "max_forks_repo_name": "slmcbane/fractalmake", "max_forks_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_forks_repo_licenses": ["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.5294117647, "max_line_length": 78, "alphanum_fraction": 0.5442673749, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6916974891021166}}
{"text": "#include <CGAL/trace.h>\n#include <CGAL/Timer.h>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <CGAL/FPU_extension.h>\n\n\n#include <Eigen/Eigen>\n#include <Eigen/SVD>\n\n\ndouble norm_1(Eigen::Matrix3d X)\n{\n  double sum = 0;\n  for ( int i = 0; i < 3; i++ )\n  {\n    for ( int j = 0; j < 3; j++ )\n    {\n      sum += abs(X(i,j));\n    }\n  }\n  return sum;\n}\n\ndouble norm_inf(Eigen::Matrix3d X)\n{\n  double max_abs = abs(X(0,0));\n  for ( int i = 0; i < 3; i++ )\n  {\n    for ( int j = 0; j < 3; j++ )\n    {\n      double new_abs = abs(X(i,j));\n      if ( new_abs > max_abs )\n      {\n        max_abs = new_abs;\n      }\n    }\n  }\n  return max_abs;\n}\n\ntemplate<typename Mat>\nvoid polar_eigen(const Mat& A, Mat& R, bool& SVD)\n{\n  typedef typename Mat::Scalar Scalar;\n  typedef Eigen::Matrix<typename Mat::Scalar,3,1> Vec;\n\n  const Scalar th = std::sqrt(Eigen::NumTraits<Scalar>::dummy_precision());\n\n  Eigen::SelfAdjointEigenSolver<Mat> eig;\n  feclearexcept(FE_UNDERFLOW);\n  eig.computeDirect(A.transpose()*A);\n\n  if(fetestexcept(FE_UNDERFLOW) || eig.eigenvalues()(0)/eig.eigenvalues()(2)/100.0<th)\n  {\n    // The computation of the eigenvalues might have diverged.\n    // Fallback to an accurate SVD based decomposiiton method.\n    Eigen::JacobiSVD<Mat> svd;\n    svd.compute(A, Eigen::ComputeFullU | Eigen::ComputeFullV );\n    const Mat& u = svd.matrixU(); const Mat& v = svd.matrixV(); const Vec& w = svd.singularValues();\n    R = u*v.transpose();\n    SVD = true;\n    return;\n  }\n\n  Vec S = eig.eigenvalues().cwiseSqrt();\n  R = A  * eig.eigenvectors() * S.asDiagonal().inverse()\n    * eig.eigenvectors().transpose();\n  SVD = false;\n}\n\n\nint main() {\n  std::ifstream file;\n  file.open(\"Polar_benchmark\");\n  if (!file)\n  {\n    CGAL_TRACE_STREAM << \"Error loading file!\\n\";\n    return 0;\n  }\n\n  Eigen::Matrix3d A, U, r;\n  bool SVD = false;\n  int num_svd = 0;\n  int num_mtr = 0;\n\n  CGAL_TRACE_STREAM << \"start polar decomposition...\\n\";\n  while (!file.eof())\n  {\n    for (int j = 0; j < 3; j++)\n    {\n      for (int k = 0; k < 3; k++)\n      {\n        file >> A(j, k);\n      }\n    }\n    num_mtr++;\n    double det = A.determinant();\n    if (A.determinant() > 0)\n    {\n      polar_eigen<Eigen::Matrix3d> (A, U, SVD);\n      if (SVD)\n        num_svd++;\n      U.transposeInPlace();\n      double det_2 = U.determinant();\n      if ( abs(det_2-1) > 1e-2 )\n      {\n        CGAL_TRACE_STREAM << \"error matrix: det = \" << det_2 << \"\\n\";\n      }\n    }\n  }\n  file.close();\n\n  CGAL_TRACE_STREAM << \"done. \" << num_svd << \" SVD decompositions in \" << num_mtr << \" matrices\\n\";\n  return 0;\n\n  /*int ite = 200000;\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd;\n  Eigen::Matrix3d A, U, H, r;\n\n  int matrix_idx = rand()%200;\n  for (int i = 0; i < matrix_idx; i++)\n  {\n    for (int j = 0; j < 3; j++)\n    {\n      for (int k = 0; k < 3; k++)\n      {\n        file >> A(j, k);\n      }\n    }\n  }\n  file.close();\n\n  A(0,0) = 0.0014667022958104185; A(0,1) = 0.0024644551180079627; A(0,2) = 0.0040659871060825092;\n  A(1,0) = 0.0028327558016991478; A(1,1) = 0.0054236820249146406; A(1,2) = 0.0079280090866983826;\n  A(2,0) = 0.0039090073251031232; A(2,1) = 0.0066744523074963374; A(2,2) = 0.010848552426718550;\n  A = A*10000;\n  double det = A.determinant();\n\n  CGAL::Timer task_timer;\n\n  CGAL_TRACE_STREAM << \"Start SVD decomposition...\";\n  task_timer.start();\n  for (int i = 0; i < ite; i++)\n  {\n    if (A.determinant() > 0)\n    {\n      polar_eigen<Eigen::Matrix3d> (A, U);\n      U.transposeInPlace();\n      double det_2 = U.determinant();\n      r = U*U.transpose();\n    }\n  }\n  task_timer.stop();\n\n\n  CGAL_TRACE_STREAM << \"done: \" << task_timer.time() << \"s\\n\";\n\n        return 0;*/\n}\n\n", "meta": {"hexsha": "6000307464a0348904dc71002be79ba9e4abf3fe", "size": 3649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.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": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.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": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.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": 22.3865030675, "max_line_length": 100, "alphanum_fraction": 0.5735818032, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7549149923816046, "lm_q1q2_score": 0.6915848785054699}}
{"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n#include <cstdlib>\n#include <cstdio>\n#include <random>\n#include <iostream>\n#include <armadillo>\n#include <ctime>\n#include <chrono>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nstd::default_random_engine generator;\n\nstd::normal_distribution<double> distribution1(0,1);\n\nstd::chi_squared_distribution<double> distribution2(1.0);\n\nstd::student_t_distribution<double> distribution3(1.0);\n\nstd::uniform_real_distribution<double> distribution4(-1.0,1.0);\n\nstd::exponential_distribution<double> distribution5(1.0);\n\nstd::geometric_distribution<int> distribution6(0.5);\n\n\n//double laplace_random_number = distribution5(generator) ;\n//\n//if(distribution4(generator) < 0.0 )\n//\n//   laplace_random_number = - laplace_random_number;\n\ndouble get_random_number(int distribution)\n{\n    switch(distribution)\n    {\n        case 1: // Normal distribution\n            return distribution1(generator);\n        case 2: // chi-square\n            return distribution2(generator);\n        case 3: // student-t\n            return distribution3(generator);\n        case 4: // uniform\n            return distribution4(generator);\n        case 5: // exponential\n            return distribution5(generator);\n        case 6: // geometric\n            return distribution6(generator);\n        case 7:\n            return distribution5(generator)*(distribution4(generator) < 0.0 ? -1 : 1);\n        default:\n            return 0.0;\n            ;\n    }\n}\n\nint get_distribution_code(const char* var_dist)\n{\n    if(strcmp(var_dist,\"normal\") == 0)\n        return 1;\n    else if(strcmp(var_dist,\"chi-square\") == 0)\n        return 2;\n    else if(strcmp(var_dist,\"student-t\") == 0)\n        return 3;\n    else if(strcmp(var_dist,\"uniform\") == 0)\n        return 4;\n    else if(strcmp(var_dist,\"exponential\") == 0)\n        return 5;\n    else if(strcmp(var_dist,\"geometric\") == 0)\n        return 6;\n    else if(strcmp(var_dist, \"laplace\")== 0)\n        return 7;\n    return 0;\n}\n\nint main(int argc, char** argv)\n\n{\n    //int64_t seed = time(NULL);\n    //generator.seed(seed);\n    generator.seed(std::chrono::system_clock::now().time_since_epoch().count());\n    double signal_noise_ratio = 6.0;\n    int num_vars = 2;\n    int dependent_var_idx = 0;\n    int distribution = 1; // 1 for normal distribution\n    int noise_distribution = 1; \n    std::string outputFile;\n    int N = 1000;//sample size, number of rows\n    std::string description = std::string(\"Generate a csv file.  Example usage: \") + argv[0] + \" \";\n//    po::options_description desc(description);\n//    desc.add_options()\n//            (\"signal,s\", po::value<double > (&signal_noise_ratio), \"signal noise ratio\")\n//            (\"output,o\", po::value<std::string > (&outputFile), \"The output file. Second positional argument.\")\n//            (\"num_independents,i\", po::value<int>(&num_vars)->default_value(1), \"The number of independent variables\")\n//            (\"distribution,d\", po::value<int>(&distribution)->default_value(1)\n//              , (std::string(\"The probability distributions\\n\\t 1 for normal distribution\\n2 for chi-square\")\n//             // + \"\\n\\t 3 for student-t distribution\"\n//             // + \"\\n\\t 4 for uniform distribution\"\n//             // + \"\\n\\t 5 for exponential distribution\"\n//              + \"\\n\\t 6 for geometric distribution\").c_str()\n//            )\n//            (\"noise_distribution,z\", po::value<int>(&noise_distribution)->default_value(1), \"noise distribution\")\n//            (\"sample size, n\", po::value<int>(&N)->default_value(1000), \"number of rows\")\n//            (\"help,h\", \"Show this help message.\")\n//            ;\n\n//    po::positional_options_description positionalOptions;\n//    positionalOptions.add(\"input\", 1);\n//    positionalOptions.add(\"output\", 1);\n\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\") || argc == 1) {\n//        std::cout << desc;\n//        return 0;\n//    }\n    \n    // temporary solution due to program options not working\n    if(argc < 4)\n    {\n        printf(\"Usage: %s num_vars distribution noise_distribution noise_strength\\n\", argv[0]);\n        exit(1);\n    }\n    num_vars = atoi(argv[1]);\n    distribution = get_distribution_code ( argv[2] );\n    noise_distribution = get_distribution_code( argv[3] );\n    \n    double noise_strength = 1.0;\n    if(argc > 4)\n        noise_strength = atof(argv[4]);\n \n\n       const int cols =  num_vars + 1;\n\n       double data[N][cols];\n\n       //arma::vec error(N);\n\n\n\n       double sumX=0.0;\n\n       double sumX2=0.0;\n       \n       //dependent_var_idx = int((get_random_number(4)+1) * cols + 1) % cols;\n       arma::vec beta(num_vars+1);\n       //beta(dependent_var_idx) = 0.0;\n       std::vector<int> indices(cols);\n       for(int j=0;j<cols;j++)\n           indices[j] = j;\n       \n       //random_shuffle(indices.begin(), indices.end()); \n       \n       for(int i=0; i < N; i++)\n       {\n           data[i][ indices[0] ] = get_random_number(distribution);\n       }\n       for(int j=1; j < cols; j++)\n       {   \n           const int curr = indices[j];\n           const int prev = indices[j-1];\n           beta[curr] = get_random_number(4) + 8.0;// range (6, 11) + signal_noise_ratio;\n           if(abs(beta[curr]) < signal_noise_ratio)\n               beta[curr] = abs(beta[curr])/beta[curr]*signal_noise_ratio;\n           //double strength = int((get_random_number(4)) * 2000) % 50;\n\n           for(int i=0; i<N; i++)\n           {\n                data[i][curr] = beta[curr] * data[i][prev] + noise_strength*get_random_number(noise_distribution);\n           }\n       }\n       \n       for(int j=1; j < cols; j++)\n           printf(\"# %d -> %d, %12.4f\\n\", indices[j-1], indices[j], beta(indices[j]));\n       printf(\"\\n\");\n       for(int i=0; i<N; i++)\n       {\n           for(int j=0; j < cols; j++)\n              printf(\"%12.4f%s \", data[i][j], j == cols-1 ? \"\" : \",\");\n           printf(\"\\n\");\n       }\n\n       return 0;\n}\n\n", "meta": {"hexsha": "04466c78c3c2e07b342f60f5b63ae1d71264e384", "size": 6165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "urlearning/score/generate_chain.cpp", "max_stars_repo_name": "ninalu/urlearning-cpp", "max_stars_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "urlearning/score/generate_chain.cpp", "max_issues_repo_name": "ninalu/urlearning-cpp", "max_issues_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "urlearning/score/generate_chain.cpp", "max_forks_repo_name": "ninalu/urlearning-cpp", "max_forks_repo_head_hexsha": "c4c51b0046646b45573aec1b35c1678c422b3802", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T04:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T04:17:55.000Z", "avg_line_length": 32.109375, "max_line_length": 120, "alphanum_fraction": 0.5873479319, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6915848701317072}}
{"text": "// test_newton.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestNewton)\n\n\n    void test_newton_function_1(double *x, double *fv, int n) {\n        fv[0] = x[0]*x[0] + x[1]*x[1] - 5;\n        fv[1] = x[1] - 3*x[0] + 5;\n    }\n\n    void test_newton_function_2(double *x, double *fv, int n) {\n        fv[0] = pow(x[0], 5) + pow(x[1], 3) * pow(x[2], 4) + 1;\n        fv[1] = x[0]*x[0]*x[1]*x[2];\n        fv[2] = pow(x[2], 4) - 1;\n    }\n    \n\n    BOOST_AUTO_TEST_CASE(test_newton_1)\n    {\n        const int maxiter = 100;\n        int result, expected_result;\n        const double eps = 1.e-7;\n        double *x = new double[2], *fv = new double[2];\n        bool is_passed = false;\n        expected_result = 1;\n        x[0] = 1; x[1] = 2;\n\n        result = Numerary::nonlinear_systems_of_equations(test_newton_function_1, x, fv, 2, \"newton\", eps, maxiter);\n        BOOST_CHECK_EQUAL(result, expected_result);\n\n        if ((fabs(x[0] - 1) < 1.e-5) && (fabs(x[1] + 2) < 1.e-5)) is_passed = true;\n        if ((fabs(x[0] - 2) < 1.e-5) && (fabs(x[1] - 1) < 1.e-5)) is_passed = true;\n\n        BOOST_CHECK(is_passed);\n\n        delete[] x;\n        delete[] fv;\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_newton_2)\n    {\n        const int maxiter = 100;\n        int result, expected_result;\n        const double eps = 1.e-7;\n        double *x = new double[3], *fv = new double[3];\n        bool is_passed = false;\n        expected_result = 1;\n        x[0] = 1; x[1] = 2, x[2] = -1;\n\n        result = Numerary::nonlinear_systems_of_equations(test_newton_function_2, x, fv, 3, \"newton\", eps, maxiter);\n        BOOST_CHECK_EQUAL(result, expected_result);\n\n        if ((fabs(x[0] + 1) < 1.e-4) && (fabs(x[1]) < 1.e-4) && (fabs(x[2] + 1) < 1.e-4)) is_passed = true;\n        if ((fabs(x[0] + 1) < 1.e-4) && (fabs(x[1]) < 1.e-4) && (fabs(x[2] - 1) < 1.e-4)) is_passed = true;\n        if ((fabs(x[0]) < 1.e-4) && (fabs(x[1] + 1) < 1.e-4) && (fabs(x[2] + 1) < 1.e-4)) is_passed = true;\n        if ((fabs(x[0]) < 1.e-4) && (fabs(x[1] + 1) < 1.e-4) && (fabs(x[2] - 1) < 1.e-4)) is_passed = true;\n\n        BOOST_CHECK(is_passed);\n\n        delete[] x;\n        delete[] fv;\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "02f1d2b978635e5bd8b1c93b2bf4d624ca8c26de", "size": 2271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_newton.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_newton.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_newton.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 30.28, "max_line_length": 116, "alphanum_fraction": 0.5222369, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6915457692647206}}
{"text": "//\n// Created by yuan on 27/07/2021.\n//\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <chrono>\n#include <thread>\n#include <array>\n#include <cmath>\n#include <functional>\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include <vector>\n\nEigen::MatrixXd pinv_Eigen_SVD(Eigen::MatrixXd &origin) {\n\n  const float er = 0;\n  // perform svd decomposition\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd_holder(origin, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  // Build SVD decomposition results\n  Eigen::MatrixXd U = svd_holder.matrixU();\n  Eigen::MatrixXd V = svd_holder.matrixV();\n  Eigen::MatrixXd D = svd_holder.singularValues();\n\n  // Build the S matrix\n  Eigen::MatrixXd S(V.cols(), U.cols());\n  S.setZero();\n\n  for (unsigned int i = 0; i < D.size(); ++i) {\n\n    if (D(i, 0) > er) {\n      S(i, i) = 1 / D(i, 0);\n    } else {\n      S(i, i) = 0;\n    }\n  }\n\n  // pinv_matrix = V * S * U^T\n  return V * S * U.transpose();\n}\n\nint main()\n{\n  std::vector<int> values(10000);\n\n  // Generate Random values\n  auto f = []() -> int { return rand() % 10000; };\n\n  // Fill up the vector\n  generate(values.begin(), values.end(), f);\n\n  // Get starting timepoint\n  auto start = std::chrono::high_resolution_clock::now();\n\n  // Call the function, here sort()\n  Eigen::MatrixXd jacobian;\n\n//  for ( int i(0); i<1; i++ ) {\n    jacobian.setRandom(6,7);\n//    Eigen::MatrixXd pinv_jacobian1 = pinv_Eigen_SVD(jacobian);\n//    Eigen::MatrixXd pinv_jacobian2 = jacobian.completeOrthogonalDecomposition().pseudoInverse();\n    Eigen::MatrixXd pinv_jacobian3 = jacobian.transpose() * (jacobian * jacobian.transpose()).inverse();\n//  }\n\n  // Get ending timepoint\n  auto stop = std::chrono::high_resolution_clock::now();\n\n//  std::cout << pinv_jacobian1 << std::endl << std::endl;\n//  std::cout << pinv_jacobian2 << std::endl << std::endl;\n//  std::cout << pinv_jacobian3 << std::endl << std::endl;\n\n  // Get duration. Substart timepoints to\n  // get durarion. To cast it to proper unit\n  // use duration cast method\n  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);\n\n  std::cout << \"Time taken by function: \"\n       << duration.count() << \" microseconds\" << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "150b5ac609f4fadbd804aae5cdb81baa0a88ba5c", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/test_pinv_time.cpp", "max_stars_repo_name": "VinceGuan/Franka_Teleop", "max_stars_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "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": "examples/test_pinv_time.cpp", "max_issues_repo_name": "VinceGuan/Franka_Teleop", "max_issues_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "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": "examples/test_pinv_time.cpp", "max_forks_repo_name": "VinceGuan/Franka_Teleop", "max_forks_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-06T14:25:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T14:25:37.000Z", "avg_line_length": 26.4761904762, "max_line_length": 104, "alphanum_fraction": 0.6456834532, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.691545760021906}}
{"text": "#include \"wave.h\"\n#include <boost/math/special_functions/bessel.hpp>\n\n/**\n * Hankel_n^{(1)} function\n * \n * @param n index\n * @param x argument\n * @return value\n */\nstd::complex<double>\nhankel1(const int n, const double x) {\n    double besselJ = boost::math::cyl_bessel_j<int, double>(n, x);\n    double besselY = boost::math::cyl_neumann<int, double>(n, x);\n    return besselJ + J1*besselY;\n}\n\n/**\n * Incident wave\n * \n * @param kvec incident wave vector\n * @param point target point\n * @return amplitude\n */\nstd::complex<double> \nincident(const double kvec[], const double point[]) {\n    return std::exp(J1*(kvec[0]*point[0] + kvec[1]*point[1]));\n}\n\n/**\n * Normal gradient of the incident wave, assumes incident wave is exp(1j * kvec.x)\n *\n * @param nvec normal vector pointing inwards\n * @param kvec incident wave vector\n * @param point (source) point\n * @return amplitude\n */\nstd::complex<double> \ngradIncident(const double nvec[], const double kvec[], \n             const double point[]) {\n    return J1*(nvec[0]*kvec[0] + nvec[1]*kvec[1])*incident(kvec, point);\n}\n\n/**\n * Scattered wave contribution from a single segment\n *\n * @param kvec incident wave vector\n * @param p0 starting point of the segment\n * @param p1 end point of the segment\n * @param point observer point\n * @return wave contribution\n */\nstd::complex<double> \ncomputeScatteredWaveElement(const double kvec[], const double p0[], \n                            const double p1[], const double point[]) {\n\n    // xdot is anticlockwise\n    double xdot[] = {p1[0] - p0[0], p1[1] - p0[1]};\n\n    // mid point of the segment\n    double pmid[] = {0.5*(p0[0] + p1[0]), 0.5*(p0[1] + p1[1])};\n\n    // segment length\n    double dsdt = std::sqrt(xdot[0]*xdot[0] + xdot[1]*xdot[1]);\n\n    // normal vector, pointintg inwards and normalised\n    double nvec[] = {-xdot[1]/dsdt, xdot[0]/dsdt, 0.};\n\n    // from segment mid-point to observer\n    double rvec[] = {point[0] - pmid[0], point[1] - pmid[1]};\n    double r = std::sqrt(rvec[0]*rvec[0] + rvec[1]*rvec[1]);\n\n    double kmod = std::sqrt(kvec[0]*kvec[0] + kvec[1]*kvec[1]);\n    double kr = kmod * r;\n\n    // Green functions and normal derivatives\n    std::complex<double> g = (J1/4.) * hankel1(0, kr);\n    double nDotR = nvec[0]*rvec[0] + nvec[1]*rvec[1];\n    std::complex<double> dgdn = (-J1/4.) * hankel1(1, kr) * kmod * nDotR / r;\n\n    // contribution from the gradient of the incident wave on the surface\n    // of the obstacle. The normal derivative of the scattered wave is\n    // - normal derivative of the incident wave.\n    std::complex<double> scattered_wave = - dsdt * g * gradIncident(nvec, kvec, pmid);\n\n    // shadow side: total wave is nearly zero\n    //              => scattered wave amplitude = -incident wave ampl.\n    //\n    // illuminated side:\n    //              => scattered wave amplitude = +incident wave ampl.\n    //\n    double nDotK = nvec[0]*kvec[0] + nvec[1]*kvec[1];          \n    double shadow = (nDotK > 0 ? 1.0 : -1.0);\n        \n    scattered_wave += shadow * dsdt * dgdn * incident(kvec, pmid);\n\n    return scattered_wave;\n}\n\nextern \"C\" void\ncincident (const double kvec[], const double point[], double* real_part, double* imag_part) {\n    std::complex<double> res = incident(kvec, point);\n    *real_part = res.real();\n    *imag_part = res.imag();\n}\n\nextern \"C\" void computeScatteredWave(const double kvec[], int nc, const double xc[], const double yc[], \n                                     const double point[], double* real_part, double* imag_part) {\n    double res_real = 0;\n    double res_imag = 0;\n    // ADD OPENMP PRAGMA HERE\n    for (int i = 0; i < nc - 1; ++i) {\n        double p0[] = {xc[i], yc[i]};\n        double p1[] = {xc[i + 1], yc[i + 1]};\n        std::complex<double> res = computeScatteredWaveElement(kvec, p0, p1, point);\n        res_real += res.real();\n        res_imag += res.imag();\n    }\n    *real_part = res_real;\n    *imag_part = res_imag;\n}\n\n", "meta": {"hexsha": "817de27eda45678c3efbfb123a90be7c5f82935b", "size": 3912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openmp/src/wave.cpp", "max_stars_repo_name": "pletzer/scatter", "max_stars_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-01T06:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T19:47:05.000Z", "max_issues_repo_path": "openmp/src/wave.cpp", "max_issues_repo_name": "pletzer/scatter", "max_issues_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T02:06:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-27T08:57:08.000Z", "max_forks_repo_path": "openmp/src/wave.cpp", "max_forks_repo_name": "pletzer/scatter", "max_forks_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-21T03:58:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-19T01:53:46.000Z", "avg_line_length": 31.8048780488, "max_line_length": 104, "alphanum_fraction": 0.6129856851, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6914964861439815}}
{"text": "\n#include <Eigen/Dense>\n\n#include \"boundingbox.h\"\n#include \"color.h\"\n#include \"command.h\"\n#include \"functions.h\"\n#include \"numstring.h\"\n#include \"part.h\"\n#include \"renderer.h\"\n#include \"hexgrid.h\"\n\n//using namespace BWCNC;\n\nvoid BWCNC::HexGrid::nested_params( double spacing_ratio, int nth_from_outer, const Eigen::Vector3d & start, Eigen::Vector3d & pos, double & nsidelen )\n{\n    double hypot = spacing_ratio * nth_from_outer * m_sidelen;\n    pos = start + hypot * Eigen::Vector3d( sin( M_PI/3.0 ), cos( M_PI/3.0 ), 0 );\n    nsidelen = m_sidelen - hypot;\n}\n\nBWCNC::Part * BWCNC::HexGrid::make_inner_hexagon(\n    BWCNC::PartContext & k,\n    double inner_fraction,\n    int nth_inner,\n    const Eigen::Vector3d & start )\n{\n  Eigen::Vector3d pos(0,0,0);\n  double nested_sidelen = 0;\n  nested_params( inner_fraction, nth_inner, start, pos, nested_sidelen );\n  return hexagon( k, nested_sidelen, pos, nullptr, true );\n}\n\nBWCNC::Part * BWCNC::HexGrid::hexagon( BWCNC::PartContext & k, const double sidelen, const Eigen::Vector3d & start, const uint8_t * sides2skip, bool closed )\n{\n  // orientation: left-right symmetry around the vertical center line through two vertices\n  const double triangle_longside  = sidelen * cos(M_PI_2/3);\n  const double triangle_shortside = sidelen * sin(M_PI_2/3);\n\n  std::vector<Eigen::Vector3d> path;\n  {\n    path.push_back( Eigen::Vector3d( triangle_longside, -triangle_shortside, 0 ) );\n    path.push_back( Eigen::Vector3d( triangle_longside,  triangle_shortside, 0 ) );\n    path.push_back( Eigen::Vector3d(                 0,             sidelen, 0 ) );\n    path.push_back( Eigen::Vector3d(-triangle_longside,  triangle_shortside, 0 ) );\n    path.push_back( Eigen::Vector3d(-triangle_longside, -triangle_shortside, 0 ) );\n    path.push_back( Eigen::Vector3d(                 0,            -sidelen, 0 ) );\n  }\n\n  BWCNC::Part * part = k.get_new_part();\n  part->update_starting_position( start );\n\n  Eigen::Vector3d vec = start;\n  for( int i = 0; i < 6; i++ )\n  {\n    bool closedok = false;\n    if( closed && i == 5 )\n      part->lineto_close( closedok );\n\n    if( ! closedok )\n    {\n      vec = vec + path[i];\n      if( sides2skip && sides2skip[i] ) part->moveto( vec );\n      else                              part->lineto( vec );\n    }\n  }\n\n  return part;\n}\n\n\nvoid BWCNC::HexGrid::fill_partctx_with_grid( BWCNC::PartContext & k )\n{\n  const uint8_t skip0[]    = {1,0,0,0,0,0};\n//const uint8_t skip01[]   = {1,1,0,0,0,0};\n  const uint8_t skip05[]   = {1,0,0,0,0,1};\n  const uint8_t skip015[]  = {1,1,0,0,0,1};\n  const uint8_t skip1[]    = {0,1,0,0,0,0};\n//const uint8_t skip2[]    = {0,0,1,0,0,0};  // debugging only\n  const uint8_t skip5[]    = {0,0,0,0,0,1};\n\n  //###############################################################################################################\n  //#### Row #1\n  //###############################################################################################################\n  double x_ref = 0, y_ref = m_sidelen/2.0;\n  Eigen::Vector3d start( x_ref, y_ref, 0);\n\n  for( int i = m_nested; i > 0; i-- )\n    k.add_part( make_inner_hexagon( k, m_nested_spacing, i, start ) );\n\n  if( m_includegrid )\n    k.add_part( hexagon( k, m_sidelen, start ) );\n\n  for( int j = 1; j < m_cols; j++ )\n  {\n    start = Eigen::Vector3d( j * sqrt(3) * m_sidelen, y_ref, 0);\n\n    for( int i =  m_nested; i > 0; i-- )\n      k.add_part( make_inner_hexagon( k, m_nested_spacing, i, start ) );\n\n    if( m_includegrid )\n      k.add_part( hexagon( k, m_sidelen, start, skip5 ) );\n  }\n  //###############################################################################################################\n  //#### End of Row #1\n  //###############################################################################################################\n\n  //###############################################################################################################\n  //#### remaining rows\n  //###############################################################################################################\n  double xoffset;\n  for( int row = 2; row <= m_rows; row++ )\n  {\n    bool row_iseven  = (row % 2 == 0);\n    x_ref       = row_iseven ? (sqrt(3) * m_sidelen / 2.0) : 0.0;\n    xoffset     = row_iseven ? 0.5 : 0.0;\n    y_ref      += 1.5 * m_sidelen;\n\n    start = Eigen::Vector3d( x_ref, y_ref, 0);\n\n    for( int i = m_nested; i > 0; i-- )\n      k.add_part( make_inner_hexagon( k, m_nested_spacing, i, start ) );\n\n    if( m_includegrid )\n    {\n      if( row_iseven ) k.add_part( hexagon( k, m_sidelen, start, skip0 ) );\n      else             k.add_part( hexagon( k, m_sidelen, start, skip1 ) );\n    }\n\n\n    for( int j = 1; j < m_cols; j++ )\n    {\n      x_ref = (j + xoffset) * sqrt(3) * m_sidelen;\n\n      start = Eigen::Vector3d( x_ref, y_ref, 0);\n\n      for( int i = m_nested; i > 0; i-- )\n        k.add_part( make_inner_hexagon( k, m_nested_spacing, i, start ) );\n\n      if( m_includegrid )\n      {\n        Part * p = nullptr;\n        if( row_iseven )\n        {\n          if( j < m_cols - 1 ) p = hexagon( k, m_sidelen, start, skip015 );\n          else                 p = hexagon( k, m_sidelen, start,  skip05 );\n        }\n        else\n        {\n          if( j == 1 )         p = hexagon( k, m_sidelen, start,   skip1 );\n          else                 p = hexagon( k, m_sidelen, start, skip015 );\n        }\n\n        if( p != nullptr )\n        {\n          //std::cerr << \"context: \" << k.get_bbox();\n          //std::cerr << \" -- adding new: \" << p->get_bbox();\n          k.add_part( p );\n          //std::cerr << \" -- results in context: \" << k.get_bbox() << \"\\n\";\n        }\n        //else std::cerr << \"no hexagon part was made\\n\";\n      }\n    }\n  }\n  //###############################################################################################################\n  //#### end of remaining rows\n  //###############################################################################################################\n}\n\n#ifdef HEXGRID_UNITTEST\n\nstruct cmdline_params {\n    int cols;\n    int rows;\n    int nested;\n    double nested_spacing;\n\n    double sidelen;\n    double scale;\n    double yshift;\n    double xshift;\n\n    bool suppress_grid;\n    const char * moveto_clr;\n    const char * lineto_clr;\n} parms = {\n    //5, 5, 3, 2,\n    40, 40, 1, .2,\n    //4, 4, 1, .2,\n    .2, 60, 0, 0,\n    true,\n    nullptr,     // \"#0000FF\",\n    \"#ff0000\"\n};\n\n\n\n//static const double w = (2 * M_PI)/6.0;\nstatic const double w = (2 * M_PI)/30;\n\nstatic const Eigen::Vector3d shift_tform( const Eigen::Vector3d & v )\n{\n    return 1.8 * Eigen::Vector3d( cos(w*(v[1] + parms.yshift)), sin(w*(v[0] + parms.xshift)), 0 );\n}\n\nstatic const Eigen::Matrix3d rotation_tform( const Eigen::Vector3d & )\n{\n    Eigen::Matrix3d mat;\n    double t = M_PI/2;\n    mat <<  cos(t), -sin(t), 0,\n            sin(t),  cos(t), 0,\n            0, 0, 1 ;\n    return mat;\n}\n\n\nstatic const Eigen::Matrix3d skew_tform( const Eigen::Vector3d & v )\n{\n    Eigen::Matrix3d mat;\n    mat <<  cos(w*(v[1] + parms.yshift)), 0, 0,\n            0, sin(w*(v[0] + parms.xshift)), 0,\n            0, 0, 0 ;\n    return 1.8 * mat;\n}\n\n\nstatic bool handle_params( int argc, char ** argv )\n{\n    for( int i = 1; i < argc; i++ )\n    {\n        if( 0 == strcmp( \"--suppress_grid\", argv[i] ) )\n            parms.suppress_grid = true;\n        else\n            return false;\n    }\n    return true;\n}\n\nint main( int argc, char ** argv )\n{\n    Eigen::Vector3d shift_hist;\n    BWCNC::PartContext k;\n\n    if( handle_params( argc, argv ) )\n    {\n        BWCNC::HexGrid grid( parms.cols, parms.rows, parms.sidelen,\n                             parms.nested, parms.nested_spacing, ! parms.suppress_grid );\n\n        grid.fill_partctx_with_grid( k );\n        //k.remake_boundingbox();\n\n        shift2center( k, &shift_hist );\n\n        k.position_dependent_transform( skew_tform, shift_tform );\n        //k.remake_boundingbox();\n\n        k.scale( parms.scale );\n\n        k.position_dependent_transform( rotation_tform, nullptr );\n        //k.remake_boundingbox();\n        undo_shift2( k, shift_hist );\n\n        BWCNC::SVG renderer;\n        renderer.set_moveto_color( parms.moveto_clr );\n        renderer.set_lineto_color( parms.lineto_clr );\n        renderer.render_all( k );\n    }\n\n    return 0;\n}\n#endif\n\n#if 0\n    HexGrid( int c = 10, int r = 10, double len = 1,\n             int nested_count = 1, double nested_pcnt = .5, bool includegrid = true,\n             const char * clr_lineto = \"#ff0000\",\n             const char * clr_moveto = nullptr,\n             const char * clr_bckgrd = \"#ffffff\" )\n#endif\n\n", "meta": {"hexsha": "451322eb77ac5893b21d3719fb4787d32c26db40", "size": 8551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/libbwcnc/hexgrid.cpp", "max_stars_repo_name": "bridgewire/SillyGCodeProjects", "max_stars_repo_head_hexsha": "13ed368681e43749c02125286ff93a0218256375", "max_stars_repo_licenses": ["MIT"], "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++/libbwcnc/hexgrid.cpp", "max_issues_repo_name": "bridgewire/SillyGCodeProjects", "max_issues_repo_head_hexsha": "13ed368681e43749c02125286ff93a0218256375", "max_issues_repo_licenses": ["MIT"], "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++/libbwcnc/hexgrid.cpp", "max_forks_repo_name": "bridgewire/SillyGCodeProjects", "max_forks_repo_head_hexsha": "13ed368681e43749c02125286ff93a0218256375", "max_forks_repo_licenses": ["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.4306049822, "max_line_length": 157, "alphanum_fraction": 0.5112852298, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582535657919, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6914868021067653}}
{"text": "// main.cpp\n#include <stdio.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"sophus/so3.hpp\"\n#include \"sophus/common.hpp\"\n\n\nusing Eigen::MatrixXd;\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  m(1,1) = 0;\n  std::cout << m << std::endl;\n\n\n  // The following demonstrates the group multiplication of rotation matrices\n\n  // Create rotation matrices from rotations around the x and y and z axes:\n  const double kPi = Sophus::Constants<double>::pi();\n  Sophus::SO3d R1 = Sophus::SO3d::rotX(kPi / 4);\n  Sophus::SO3d R2 = Sophus::SO3d::rotY(kPi / 6);\n  Sophus::SO3d R3 = Sophus::SO3d::rotZ(-kPi / 3);\n\n  std::cout << \"The rotation matrices are\" << std::endl;\n  std::cout << \"R1:\\n\" << R1.matrix() << std::endl;\n  std::cout << \"R2:\\n\" << R2.matrix() << std::endl;\n  std::cout << \"R3:\\n\" << R3.matrix() << std::endl;\n  std::cout << \"Their product R1*R2*R3:\\n\"\n            << (R1 * R2 * R3).matrix() << std::endl;\n  std::cout << std::endl;\n\n  // Rotation matrices can act on vectors\n  Eigen::Vector3d x;\n  x << 0.0, 0.0, 1.0;\n  std::cout << \"Rotation matrices can act on vectors\" << std::endl;\n  std::cout << \"x\\n\" << x << std::endl;\n  std::cout << \"R2*x\\n\" << R2 * x << std::endl;\n  std::cout << \"R1*(R2*x)\\n\" << R1 * (R2 * x) << std::endl;\n  std::cout << \"(R1*R2)*x\\n\" << (R1 * R2) * x << std::endl;\n  std::cout << std::endl;\n\n  // SO(3) are internally represented as unit quaternions.\n  std::cout << \"R1 in matrix form:\\n\" << R1.matrix() << std::endl;\n  std::cout << \"R1 in unit quaternion form:\\n\"\n            << R1.unit_quaternion().coeffs() << std::endl;\n  // Note that the order of coefficiences of Eigen's quaternion class is\n  // (imag0, imag1, imag2, real)\n  std::cout << std::endl;\n  // The following demonstrates the group multiplication of rotation matrices\n\n  // Create rotation matrices from rotations around the x and y and z axes:\n  // const double kPi = Sophus::Constants<double>::pi();\n  // Sophus::SO3d R1 = Sophus::SO3d::rotX(kPi / 4);\n  // Sophus::SO3d R2 = Sophus::SO3d::rotY(kPi / 6);\n  // Sophus::SO3d R3 = Sophus::SO3d::rotZ(-kPi / 3);\n\n  // std::cout << \"The rotation matrices are\" << std::endl;\n  // std::cout << \"R1:\\n\" << R1.matrix() << std::endl;\n  // std::cout << \"R2:\\n\" << R2.matrix() << std::endl;\n  // std::cout << \"R3:\\n\" << R3.matrix() << std::endl;\n  // std::cout << \"Their product R1*R2*R3:\\n\"\n  //           << (R1 * R2 * R3).matrix() << std::endl;\n  // std::cout << std::endl;\n\n  // // Rotation matrices can act on vectors\n  // Eigen::Vector3d x;\n  // x << 0.0, 0.0, 1.0;\n  // std::cout << \"Rotation matrices can act on vectors\" << std::endl;\n  // std::cout << \"x\\n\" << x << std::endl;\n  // std::cout << \"R2*x\\n\" << R2 * x << std::endl;\n  // std::cout << \"R1*(R2*x)\\n\" << R1 * (R2 * x) << std::endl;\n  // std::cout << \"(R1*R2)*x\\n\" << (R1 * R2) * x << std::endl;\n  // std::cout << std::endl;\n\n  // // SO(3) are internally represented as unit quaternions.\n  // std::cout << \"R1 in matrix form:\\n\" << R1.matrix() << std::endl;\n  // std::cout << \"R1 in unit quaternion form:\\n\"\n  //           << R1.unit_quaternion().coeffs() << std::endl;\n  // // Note that the order of coefficiences of Eigen's quaternion class is\n  // (imag0, imag1, imag2, real)\n  std::cout << std::endl;\n\n}\n", "meta": {"hexsha": "f9208487b4e5f2b73d8c493433010010d84677fc", "size": 3296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sqlite.cpp", "max_stars_repo_name": "ahtamjidi/learn_cpp", "max_stars_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "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": "sqlite.cpp", "max_issues_repo_name": "ahtamjidi/learn_cpp", "max_issues_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "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": "sqlite.cpp", "max_forks_repo_name": "ahtamjidi/learn_cpp", "max_forks_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "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": 36.6222222222, "max_line_length": 77, "alphanum_fraction": 0.5700849515, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6914389829481044}}
{"text": "/*\n * Copyright 2017 Mahdi Khanalizadeh\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 HEADER_EXT_MATRIX2_HPP_INCLUDED\n#define HEADER_EXT_MATRIX2_HPP_INCLUDED\n\n#include \"vector2.hpp\"\n\n#include <cassert>\n\n#include <algorithm>\n\n#include <boost/operators.hpp>\n\nnamespace ext\n{\n\n\ttemplate <typename T>\n\tclass Matrix2 :\n\t\tboost::equality_comparable<Matrix2<T>,\n\t\tboost::ring_operators<Matrix2<T>,\n\t\tboost::multipliable<Matrix2<T>, T\n\t\t>>>\n\t{\n\tpublic:\n\t\tusing Type = T;\n\n\t\tType x[4];\n\t};\n\n\tusing Matrix2f = Matrix2<float>;\n\tusing Matrix2d = Matrix2<double>;\n\tusing Matrix2ld = Matrix2<long double>;\n\n\ttemplate <typename T>\n\tbool operator==(Matrix2<T> const& m1, Matrix2<T> const& m2)\n\t{\n\t\treturn std::equal(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x);\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T>& operator+=(Matrix2<T>& m1, Matrix2<T> const& m2)\n\t{\n\t\tstd::transform(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x, m1.x, [](T one, T two){ return one + two; });\n\t\treturn m1;\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T>& operator-=(Matrix2<T>& m1, Matrix2<T> const& m2)\n\t{\n\t\tstd::transform(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x, m1.x, [](T one, T two){ return one - two; });\n\t\treturn m1;\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T>& operator*=(Matrix2<T>& m1, Matrix2<T> const& m2)\n\t{\n\t\tauto const m = m1;\n\t\tm1.x[0] = m.x[0] * m2.x[0] + m.x[1] * m2.x[2];\n\t\tm1.x[1] = m.x[0] * m2.x[1] + m.x[1] * m2.x[3];\n\t\tm1.x[2] = m.x[2] * m2.x[0] + m.x[3] * m2.x[2];\n\t\tm1.x[3] = m.x[2] * m2.x[1] + m.x[3] * m2.x[3];\n\t\treturn m1;\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T>& operator*=(Matrix2<T>& m, T const a)\n\t{\n\t\tstd::transform(m.x, m.x + (sizeof m.x / sizeof m.x[0]), m.x, [a](T x){ return x * a; });\n\t\treturn m;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T> operator * (Matrix2<T> const& m, Vector2<T> const& v)\n\t{\n\t\treturn {m.x[0] * v.x + m.x[1] * v.y, m.x[2] * v.x + m.x[3] * v.y};\n\t}\n\n\ttemplate <typename T>\n\tVector2<T> operator * (Vector2<T> const& v, Matrix2<T> const& m)\n\t{\n\t\treturn {v.x * m.x[0] + v.y * m.x[2], v.x * m.x[1] + v.y * m.x[3]};\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T> transpose(Matrix2<T> const& m)\n\t{\n\t\tauto t = m;\n\t\tt.x[1] = m.x[2];\n\t\tt.x[2] = m.x[1];\n\t\treturn t;\n\t}\n\n\ttemplate <typename T>\n\tT trace(Matrix2<T> const& m)\n\t{\n\t\treturn m.x[0] + m.x[3];\n\t}\n\n\ttemplate <typename T>\n\tT determinant(Matrix2<T> const& m)\n\t{\n\t\treturn m.x[0] * m.x[3] - m.x[1] * m.x[2];\n\t}\n\n\ttemplate <typename T>\n\tMatrix2<T> inverse(Matrix2<T> const& m)\n\t{\n\t\tassert(determinant(m) != 0);\n\t\tMatrix2<T> n;\n\t\tn.x[0] = m.x[3];\n\t\tn.x[1] = -m.x[1];\n\t\tn.x[2] = -m.x[2];\n\t\tn.x[3] = m.x[0];\n\t\tn *= 1/determinant(m);\n\t\treturn n;\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_MATRIX2_HPP_INCLUDED\n", "meta": {"hexsha": "b31c599a9a4310db75a16b95722b5bca5f654a34", "size": 3183, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/matrix2.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/matrix2.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/matrix2.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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.5777777778, "max_line_length": 113, "alphanum_fraction": 0.6145146089, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.6913913405242378}}
{"text": "#ifndef _LINEAR_ALGEBRA_HPP_\n#define _LINEAR_ALGEBRA_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/StdVector>\n#include <dlib/optimization.h>\n#include <mimkl/definitions.hpp>\n#include <mimkl/utilities.hpp>\n#include <numeric>\n#include <spdlog/fmt/ostr.h>\n#include <spdlog/spdlog.h>\n\nusing mimkl::definitions::Index;\n\nnamespace mimkl\n{\nnamespace linear_algebra\n{\n\n//! \\f$ K' = K / (tr(K) / n)\\f$\n/*!\ndevide matrix by a factor so that trace will equal the number of rows \\f$ tr(K')\n= n \\f$\n@param K square matrix to be trace_normalized by reference\n@return trace_factor \\f$ tr(K) / n\\f$\n*/\ntemplate <typename Derived>\ntypename Derived::Scalar trace_normalize(Derived &K)\n{\n    typename Derived::Scalar trace_factor = K.trace() / K.rows();\n    K = K / trace_factor;\n    return trace_factor;\n}\n\n//! \\f$ k^{*}(x,y) = \\fraq{k(x,y)}{\\sqrt{k(x,x) k(y,y)}}\\f$\ntemplate <typename Derived>\nDerived normalize_kernel(const Derived &K)\n{\n    COLUMN(typename Derived::Scalar) diag = 1 / K.diagonal().array().sqrt();\n    return K.array() * (diag * diag.transpose()).array(); // outer product of\n                                                          // diagonal elements\n}\n\n//! \\f$ k^{*}(x,y) = \\fraq{k(x,y)}{\\sqrt{k(x,x) k(y,y)}}\\f$, where k(x,x) stems\n//! from the training data and k(y,y) from the test data\ntemplate <typename LhsDerived, typename RhsDerived, typename Derived>\nDerived normalize_kernel_prediction(const Derived &K,\n                                    const LhsDerived &lhs,\n                                    const RhsDerived &rhs)\n{\n    COLUMN(typename Derived::Scalar)\n    diag_lhs = 1 / lhs.diagonal().array().sqrt();\n    COLUMN(typename Derived::Scalar)\n    diag_rhs = 1 / rhs.diagonal().array().sqrt();\n    return K.array() *\n           (diag_lhs * diag_rhs.transpose()).array(); // outer product of\n                                                      // diagonal elements\n}\n\n//! centralizing the data in feature space \\f$ \\mathbf{K}' = ( \\mathbf{I} -\n//! \\mathbf{1_N}) \\mathbf{K} ( \\mathbf{I} - \\mathbf{1_N}) =  \\mathbf{K} -\n//! \\mathbf{1_N} \\mathbf{K} - \\mathbf{K} \\mathbf{1_N} + \\mathbf{1_N} \\mathbf{K}\n//! \\mathbf{1_N}\\f$\n/*!\nwhere \\f$\\mathbf{1_N}\\f$ denotes a N-by-N matrix for which each element takes\nvalue 1/N\n*/\ntemplate <typename Derived>\nDerived centralize_kernel(const Derived &K)\n{ // TODO how to do for test data?\n    Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1> rowwise_mean =\n    K.rowwise().mean();\n    return ((K.colwise() - rowwise_mean).rowwise() - rowwise_mean.transpose())\n           .array() +\n           rowwise_mean.mean();\n}\n\ntemplate <typename Scalar,\n          typename StorageOrder> // TODO why does const & not compile?\nEigen::Map<const COLUMN(Scalar)> dlib_to_eigen(\nconst dlib::matrix<Scalar, 0, 1, dlib::default_memory_manager, StorageOrder> &vector)\n{ // more general case\n    // with template\n    // specializations not\n    // needed as of yet.\n    spdlog::get(\"console\")->debug(\"sum over passed vector:\\n{}\",\n                                  dlib::sum(vector));\n    typedef COLUMN(Scalar) Column;\n    typedef Eigen::Map<const Column> MapColumn;\n    // Map Dlib to Eigen\n    const Scalar *dlib_ptr = vector.begin(); //&vector.data(0,0);\n    if (dlib::is_row_major(vector) ^ (Column::Flags & Eigen::RowMajorBit))\n    { // if XOR warn, for instance Y: Y.isRowMajor\n        auto logger = spdlog::get(\"console\");\n        logger->critical(\"make sure LibMat is in col-major or that mapping \"\n                         \"happens \"\n                         \"in row-major:\\n\"\n                         \"dlib::is_row_major(vector): {}\\n\"\n                         \"Column::Options: {}\\n\"\n                         \"(Column::Flags&Eigen::RowMajorBit): {}\",\n                         dlib::is_row_major(vector), Column::Options,\n                         (Column::Flags & Eigen::RowMajorBit));\n    };\n    return MapColumn(dlib_ptr, vector.nr(), 1);\n}\n\n//! squared euclidean distance of rows in X to itself: M_ij =  x_i^T*x_i +\n//! x_j^T*x_j -\n//! 2*x_i^T*x_j\ntemplate <typename LhsDerived, typename MDerived>\nvoid squared_euclidean_distances(const Eigen::MatrixBase<LhsDerived> &lhs,\n                                 const Eigen::MatrixBase<MDerived> &distance_matrix)\n{\n    MDerived lin_kernel = lhs * lhs.transpose();\n    const_cast<Eigen::MatrixBase<MDerived> &>(distance_matrix) =\n    ((-2 * lin_kernel.real()).colwise() + lin_kernel.diagonal()).rowwise() +\n    lin_kernel.diagonal().adjoint();\n}\n\ntemplate <typename Scalar>\nMATRIX(Scalar)\nrowwise_soft_max(MATRIX(Scalar) M)\n{\n    for (Index i = 0; i < M.rows(); i++)\n    {\n        Scalar max = M.row(i).maxCoeff(); // numerical stability\n        Scalar sum = 0;\n        for (Index j = 0; j < M.cols(); j++)\n        {\n            sum += std::exp(M(i, j) - max);\n        }\n        Scalar normalizer = std::log(sum); // numerical stability\n        for (Index j = 0; j < M.cols(); j++)\n        {\n            M(i, j) = std::exp(M(i, j) - max - normalizer);\n        }\n    }\n    return M;\n}\n\n// TODO documentation\ntemplate <typename Scalar>\nMATRIX(Scalar)\nsum_matrices(const std::vector<MATRIX(Scalar)> &Ks)\n{\n    // fold over Ks\n    return std::accumulate(Ks.begin(), Ks.end(),\n                           MATRIX(Scalar)::Zero((*Ks.begin()).rows(),\n                                                (*Ks.begin()).cols())\n                           .eval()); //, [](a,b){operator+(a,b)}\n}\n\ntemplate <typename Scalar>\nMATRIX(Scalar)\nsum_trace_normalized_matrices(const std::vector<MATRIX(Scalar)> &Ks,\n                              std::vector<Scalar> &trace_factors)\n{\n    // fold over Ks, trace_normalize K before summing and store its trace\n    MATRIX(Scalar) acc; // not writing 0s\n    MATRIX(Scalar) K;   // temporary holding the trace_normalized kernel\n    if (Ks.begin() != Ks.end())\n    {\n        Index i = 0;\n        acc = Ks[i]; // non const copy\n        trace_factors[i] = trace_normalize(acc);\n        ++i;\n        for (; i < Ks.size(); ++i)\n        {\n            K = Ks[i];\n            trace_factors[i] = trace_normalize(K);\n            acc += K;\n        }\n    }\n}\n\n// not using std::accumulate, see commented version below\ntemplate <typename Scalar, typename Function>\nMATRIX(Scalar)\naggregate_kernels(const MATRIX(Scalar) & lhs,\n                  const MATRIX(Scalar) & rhs,\n                  const std::vector<Function> &Ks)\n{\n    MATRIX(Scalar) acc; // not writing 0s\n    if (Ks.begin() != Ks.end())\n    {\n        typename std::vector<Function>::const_iterator iter = Ks.begin();\n        acc = (*iter)(lhs, rhs);\n        ++iter;\n        for (; iter != Ks.end(); ++iter)\n        {\n            acc += (*iter)(lhs, rhs);\n        }\n    } // TODO else { throw | warn | ....}\n    return acc;\n}\n\ntemplate <typename Scalar, typename Function>\nMATRIX(Scalar)\naggregate_trace_normalized_kernels(const MATRIX(Scalar) & lhs,\n                                   const MATRIX(Scalar) & rhs,\n                                   const std::vector<Function> &Ks,\n                                   std::vector<Scalar> &trace_factors,\n                                   bool update_trace_factors)\n{\n    if (Ks.size() != trace_factors.size())\n        throw std::length_error(\n        \" number of functions does not match number of trace_factors\");\n    MATRIX(Scalar) acc; // not writing 0s\n    if (update_trace_factors)\n    {\n        MATRIX(Scalar) K; // temporary holding the trace_normalized kernel\n        if (Ks.begin() != Ks.end())\n        {\n            Index i = 0;\n            K = Ks[i](lhs, rhs); // non const copy\n            trace_factors[i] = trace_normalize(K);\n            acc = K;\n            ++i;\n            for (; i < Ks.size(); ++i)\n            {\n                K = Ks[i](lhs, rhs);\n                trace_factors[i] = trace_normalize(K);\n                acc += K;\n            }\n        }\n    }\n    else\n    {\n        if (Ks.begin() != Ks.end())\n        {\n            Index i = 0;\n            acc = Ks[i](lhs, rhs) / trace_factors[i];\n            ++i;\n            for (; i < Ks.size(); ++i)\n            {\n                acc += Ks[i](lhs, rhs) / trace_factors[i];\n            }\n        }\n    }\n    return acc;\n}\n\n// TODO documentation\ntemplate <typename Scalar>\nMATRIX(Scalar)\nsum_weighted_matrices(const std::vector<MATRIX(Scalar)> &Ks,\n                      const COLUMN(Scalar) & eta)\n{\n    return std::inner_product(\n    Ks.begin(), Ks.end(),\n    eta.data(), // Eigen has no .begin() and .end()\n    MATRIX(Scalar)::Zero((*Ks.begin()).rows(), (*Ks.begin()).cols()).eval());\n}\n\ntemplate <typename Scalar, typename Function>\nMATRIX(Scalar)\naggregate_weighted_kernels(const MATRIX(Scalar) & lhs,\n                           const MATRIX(Scalar) & rhs,\n                           const std::vector<Function> &fs,\n                           const COLUMN(Scalar) & eta)\n{\n    MATRIX(Scalar) acc; // not writing 0s\n    if (fs.begin() != fs.end())\n    {\n        Index i = 0;\n        acc = fs[i](lhs, rhs) * eta(i);\n        ++i;\n        for (; i < fs.size(); ++i)\n        {\n            acc += fs[i](lhs, rhs) * eta(i);\n        }\n    } // TODO else { throw | warn | ....}\n    return acc;\n}\n\ntemplate <typename Scalar, typename Function>\nMATRIX(Scalar)\naggregate_weighted_trace_normalized_kernels(const MATRIX(Scalar) & lhs,\n                                            const MATRIX(Scalar) & rhs,\n                                            const std::vector<Function> &Ks,\n                                            std::vector<Scalar> &trace_factors,\n                                            bool update_trace_factors, // update_trace_factors\n                                                                       // or\n                                            // read trace_factors\n                                            const COLUMN(Scalar) & eta)\n{\n    if (Ks.size() != trace_factors.size())\n        throw std::length_error(\n        \" number of functions does not match number of trace_factors\");\n    MATRIX(Scalar) acc; // not writing 0s\n    if (update_trace_factors)\n    {\n        MATRIX(Scalar) K; // temporary holding the trace_normalized kernel\n        if (Ks.begin() != Ks.end())\n        {\n            Index i = 0;\n            K = Ks[i](lhs, rhs); // non const copy\n            trace_factors[i] = trace_normalize(K);\n            acc = K * eta(i);\n            ++i;\n            for (; i < Ks.size(); ++i)\n            {\n                K = Ks[i](lhs, rhs);\n                trace_factors[i] = trace_normalize(K);\n                acc += K * eta(i);\n            }\n        }\n    }\n    else\n    {\n        if (Ks.begin() != Ks.end())\n        {\n            Index i = 0;\n            acc = Ks[i](lhs, rhs) / trace_factors[i] * eta(i);\n            ++i;\n            for (; i < Ks.size(); ++i)\n            {\n                acc += Ks[i](lhs, rhs) / trace_factors[i] * eta(i);\n            }\n        }\n    } // TODO else { throw | warn | ....}\n    return acc;\n}\n\n//! fill a sparse diagonal matrix with a given value\n/*! only if elements don't exist already, else use coeffRef() instead of\ninsert()\n\\param I a sparse matrix of type Eigen::SparseMatrixBase<Derived>.\n\\param value a value to fill the diagonal of type double.\n\\sa test/sparse_diagonal\n*/\ntemplate <typename Derived>\nvoid fill_sparse_diagonal(Eigen::SparseMatrixBase<Derived> const &I,\n                          const double value)\n{\n    // size of diagonal\n    const Index &m = I.rows();\n    const Index &n = I.cols();\n    Index d = (m < n ? m : n);\n    Eigen::SparseMatrixBase<Derived> &I_ =\n    const_cast<Eigen::SparseMatrixBase<Derived> &>(I);\n    for (Index i = 0; i < d; ++i)\n    {\n        I_.derived().insert(i, i) = value;\n    }\n}\n\n// helpers for indexing an Eigen::Matrix\n// adapted from\n// http://eigen.tuxfamily.org/dox-devel/TopicCustomizing_NullaryExpr.html#title1\ntemplate <class ArgumentType, class RowIndexType, class ColumnIndexType>\nclass IndexingFunctor\n{\n    private:\n    const ArgumentType &argument_;\n    const RowIndexType &row_indices_;\n    const ColumnIndexType &column_indices_;\n\n    public:\n    typedef Eigen::Matrix<\n    typename ArgumentType::Scalar,\n    RowIndexType::SizeAtCompileTime,\n    ColumnIndexType::SizeAtCompileTime,\n    ArgumentType::Flags & Eigen::RowMajorBit ? Eigen::RowMajor : Eigen::ColMajor,\n    RowIndexType::MaxSizeAtCompileTime,\n    ColumnIndexType::MaxSizeAtCompileTime>\n    MatrixType;\n    IndexingFunctor(const ArgumentType &argument,\n                    const RowIndexType &row_indices,\n                    const ColumnIndexType &column_indices)\n    : argument_(argument),\n      row_indices_(row_indices),\n      column_indices_(column_indices)\n    {\n    }\n    const typename ArgumentType::Scalar &\n    operator()(Eigen::Index row, Eigen::Index column) const\n    {\n        return argument_(row_indices_[row], column_indices_[column]);\n    }\n};\n\ntemplate <class ArgumentType, class RowIndexType, class ColumnIndexType>\nEigen::CwiseNullaryOp<\nIndexingFunctor<ArgumentType, RowIndexType, ColumnIndexType>,\ntypename IndexingFunctor<ArgumentType, RowIndexType, ColumnIndexType>::MatrixType>\nindexing(const Eigen::MatrixBase<ArgumentType> &argument,\n         const RowIndexType &row_indices,\n         const ColumnIndexType &column_indices)\n{\n    typedef IndexingFunctor<ArgumentType, RowIndexType, ColumnIndexType> Indexer;\n    typedef typename Indexer::MatrixType MatrixType;\n    return MatrixType::NullaryExpr(row_indices.size(), column_indices.size(),\n                                   Indexer(argument.derived(), row_indices,\n                                           column_indices));\n};\n} // namespace linear_algebra\n} // namespace mimkl\n\n#endif /*_LINEAR_ALGEBRA_HPP_*/\n", "meta": {"hexsha": "019c85d40a0ebe4769c3bb3f884301cacafccdd8", "size": 13649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/linear_algebra.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/linear_algebra.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/linear_algebra.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": 33.8684863524, "max_line_length": 94, "alphanum_fraction": 0.5623855227, "num_tokens": 3347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6913913248905628}}
{"text": "#include <iostream>\n//\n#include <polyvec/api.hpp>\n#include <polyvec/core/log.hpp>\n#include <polyvec/misc.hpp>\n#include <polyvec/io/vtk_curve_writer.hpp>\n#include <polyvec/curve-tracer/bezier_merging.hpp>\n//\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nNAMESPACE_BEGIN()\nNAMESPACE_END()\n\nNAMESPACE_BEGIN(polyvectest)\nNAMESPACE_BEGIN(BezierMerging)\n\nint find_affine_transformation(int, char**) {\n\n  // Creat the points and then test the mapping\n  Eigen::Matrix<double, 2,3> points0;\n  Eigen::Matrix<double, 2,3> points1;\n  Eigen::Matrix2d A;\n  Eigen::Vector2d b;\n  Eigen::Matrix2d Amanu;\n  Eigen::Vector2d bmanu;\n\n  points0.col(0) << 2,10;\n  points0.col(1) << 5,7;\n  points0.col(2) << 4,12;\n\n  //\n  // Identity test\n  // \n  Amanu = Eigen::Matrix2d::Identity();\n  bmanu = Eigen::Vector2d::Zero();\n  points1 = (Amanu * points0).colwise() + bmanu;\n\n  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);\n  assert_break( (A - Amanu).norm() < 1e-12 );\n  assert_break( (b - bmanu).norm() < 1e-12 );\n\n  //\n  // Translation test\n  // \n  Amanu = Eigen::Matrix2d::Identity();\n  bmanu = Eigen::Vector2d(2, -1.48);\n  points1 = (Amanu * points0).colwise() + bmanu;\n\n  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);\n  assert_break( (A - Amanu).norm() < 1e-12 );\n  assert_break( (b - bmanu).norm() < 1e-12 );\n\n  //\n  // A test\n  // \n  Amanu << 5, 12, -1, 30;\n  bmanu = Eigen::Vector2d::Zero();\n  points1 = (Amanu * points0).colwise() + bmanu;\n\n  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);\n  assert_break( (A - Amanu).norm() < 1e-12 );\n  assert_break( (b - bmanu).norm() < 1e-12 );\n\n  //\n  // together\n  // \n  Amanu << 5, 12, -1, 30;\n  bmanu << 9, -3;\n  points1 = (Amanu * points0).colwise() + bmanu;\n\n  ::polyfit::BezierMerging::find_affine_transformation(points0, points1, A, b);\n  assert_break( (A - Amanu).norm() < 1e-12 );\n  assert_break( (b - bmanu).norm() < 1e-12 );\n\n  return EXIT_FAILURE;\n}\n\nNAMESPACE_END(BezierMerging)\nNAMESPACE_END(polyvectest)\n", "meta": {"hexsha": "ced81f2f0b3b31bcdd9b8cca45fb349f19d5be43", "size": 2034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/tests/bezier_merging/_find_affine_transformation.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": "apps/tests/bezier_merging/_find_affine_transformation.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": "apps/tests/bezier_merging/_find_affine_transformation.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": 25.1111111111, "max_line_length": 79, "alphanum_fraction": 0.6578171091, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6912890536459573}}
{"text": "// Standard\n#include <math.h>\n#include <stdio.h>\n#include <iostream>\n\n// Timer\n#include <chrono>\n\n#include <ExternalSource/myOptimizer/Goldfarb/QuadProg++.hh>\n\n#include <Eigen/Dense>\n#include <eigen3/unsupported/Eigen/MatrixFunctions>\n#include <vector>\n\n// #define MPC_PRINT_ALL\n// #define MPC_TIME_ALL\n\n// We are following the MPC formulation from:\n// Di Carlo, Jared, et al. \"Dynamic locomotion in the mit cheetah 3 through\n// convex model-predictive control.\" 2018 IEEE/RSJ International Conference on\n// Intelligent Robots and Systems (IROS). IEEE, 2018.\n\ninline Eigen::MatrixXd R_roll(const double& phi) {\n    Eigen::MatrixXd Rx(3, 3);\n    Rx.setZero();\n    Rx << 1.0, 0.0, 0.0, 0.0, cos(phi), -sin(phi), 0.0, sin(phi), cos(phi);\n    return Rx;\n}\n\ninline Eigen::MatrixXd R_pitch(const double& theta) {\n    Eigen::MatrixXd Ry(3, 3);\n    Ry.setZero();\n    Ry << cos(theta), 0.0, sin(theta), 0.0, 1.0, 0.0, -sin(theta), 0.0,\n        cos(theta);\n    return Ry;\n}\n\ninline Eigen::MatrixXd R_yaw(const double& psi) {\n    Eigen::MatrixXd Rz(3, 3);\n    Rz.setZero();\n    Rz << cos(psi), -sin(psi), 0.0, sin(psi), cos(psi), 0.0, 0.0, 0.0, 1.0;\n    return Rz;\n}\n\ninline Eigen::MatrixXd skew_sym_mat(const Eigen::MatrixXd& r) {\n    Eigen::MatrixXd cm(3, 3);\n    cm << 0.f, -r(2), r(1), r(2), 0.f, -r(0), -r(1), r(0), 0.f;\n    return cm;\n}\n\n// Transform input vector to nxm matrix. Vector must have dimension n*m.\nvoid assemble_vec_to_matrix(const int& n, const int& m,\n                            const Eigen::VectorXd& vec,\n                            Eigen::MatrixXd& mat_out) {\n    mat_out = Eigen::MatrixXd::Zero(n, m);\n    for (int j = 0; j < m; j++) {\n        mat_out.col(j) = vec.segment(j * n, n);\n    }\n    // std::cout << \"mat_out:\" << std::endl;\n    // std::cout << mat_out << std::endl;\n}\n\n// Given dt, current x state, f_Mat, and r_feet. Find the next state, x1\nvoid integrate_robot_dynamics(const double& dt,\n                              const Eigen::VectorXd& x_current,\n                              const Eigen::MatrixXd& f_Mat,\n                              const Eigen::MatrixXd& r_feet, const double& mass,\n                              const Eigen::MatrixXd& I_body,\n                              Eigen::VectorXd& x_next) {\n    // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n    double roll = x_current[0];\n    double pitch = x_current[1];\n    double yaw = x_current[2];\n    // std::cout << \"x_current:\" << x_current.transpose() << std::endl;\n\n    Eigen::VectorXd theta_prior = x_current.head(3);\n    Eigen::VectorXd p_prior = x_current.segment(3, 3);\n    Eigen::VectorXd omega_prior = x_current.segment(6, 3);\n    Eigen::VectorXd pdot_prior = x_current.segment(9, 3);\n\n    Eigen::MatrixXd Rx = R_roll(roll);\n    Eigen::MatrixXd Ry = R_pitch(pitch);\n    Eigen::MatrixXd Rz = R_yaw(yaw);\n\n    Eigen::MatrixXd R_zyx = Rz * Ry * Rx;\n    Eigen::MatrixXd I_world =\n        R_zyx * I_body *\n        R_zyx.transpose();  // Inertia matrix aligned to CoM frame.\n\n    // CoM acceleration, velocity, and position\n    Eigen::VectorXd pddot(3);  // pddot = 1/m sum(f_i) - g\n    Eigen::VectorXd pdot(3);   // pdot = pddot*dt + pdot prior;\n    Eigen::VectorXd p(3);      // p = 0.5*pddot*dt*dt + pdot_prior*dt + p_prior;\n\n    Eigen::VectorXd grav_vec(3);\n    grav_vec.setZero();\n    grav_vec[2] = -9.81;\n    pddot.setZero();\n    pddot += grav_vec;\n    for (int i = 0; i < f_Mat.cols(); i++) {\n        pddot += ((1.0 / mass) * f_Mat.col(i));\n    }\n    pdot = pddot * dt + pdot_prior;                         // CoM velocity\n    p = 0.5 * pddot * dt * dt + pdot_prior * dt + p_prior;  // CoM position\n\n    // Angular Acceleration, velocity, and new orientation\n    Eigen::VectorXd omega_dot(3);  // omega_dot = I_inv * (sum(skew(r_i)*f_i)\n                                   // -skew(omega_prior)*I*omega_prior\n    Eigen::VectorXd omega(3);      // omega = omega_dot*dt + omega_prior;\n    Eigen::VectorXd theta;         // theta = Omega_Rate*(0.5*omega_dot*dt +\n                                   // omega_prior)*dt + theta_prior\n\n    // ZYX from ZYX rates integration\n    Eigen::MatrixXd omega_to_zyx_rate(3, 3);\n    omega_to_zyx_rate << cos(yaw) / cos(pitch), sin(yaw) / cos(pitch), 0,\n        -sin(yaw), cos(yaw), 0, cos(yaw) * sin(pitch) / cos(pitch),\n        sin(yaw) * sin(pitch) / cos(pitch), 1;\n\n    Eigen::VectorXd moments(3);\n    moments.setZero();\n    for (int i = 0; i < f_Mat.cols(); i++) {\n        moments += skew_sym_mat(r_feet.col(i)) * f_Mat.col(i);\n    }\n    omega_dot = I_world.inverse() *\n                (moments - skew_sym_mat(omega_prior) * (I_world * omega_prior));\n    omega = omega_dot * dt + omega_prior;\n    theta = omega_to_zyx_rate * (0.5 * omega_dot * dt + omega_prior) * dt +\n            theta_prior;\n\n    // std::cout << \"pddot:\" << pddot.transpose() << std::endl;\n    // std::cout << \"pdot:\" << pdot.transpose() << std::endl;\n    // std::cout << \"p_prior:\" << p_prior.transpose() << std::endl;\n    // std::cout << \"p_post:\" <<  p.transpose() << std::endl;\n\n    // std::cout << std::endl;\n    // std::cout << \"omega_dot:\" << omega_dot.transpose() << std::endl;\n    // std::cout << \"omega:\" << omega.transpose() << std::endl;\n\n    // std::cout << \"omega_to_zyx_rate\" << std::endl;\n    // std::cout << omega_to_zyx_rate << std::endl;\n\n    // std::cout << \"theta_prior:\" << theta_prior.transpose() << std::endl;\n    // std::cout << \"theta_post:\" << theta.transpose() << std::endl;\n\n    // Set new x_next;\n    x_next.head(3) = theta;\n    x_next.segment(3, 3) = p;\n    x_next.segment(6, 3) = omega;\n    x_next.segment(9, 3) = pdot;\n    x_next[12] = -9.81;\n\n    // std::cout << \"x_next:\" << x_next.transpose() << std::endl;\n}\n\n// Inputs: m, I, current yaw, and footstep locations.\n// Output: A, B matrix to be used for zero-order hold MPC\nvoid cont_time_state_space(const double& mass, const Eigen::MatrixXd& I_body,\n                           const double& psi_in, const Eigen::MatrixXd& r_feet,\n                           Eigen::MatrixXd& A, Eigen::MatrixXd& B) {\n    // Get System State: Current Robot yaw\n    Eigen::MatrixXd Rz = R_yaw(psi_in);\n\n    Eigen::MatrixXd I_world =\n        Rz * I_body * Rz.transpose();  // Inertia matrix aligned to CoM frame.\n    Eigen::MatrixXd I_inv = I_world.inverse();  // Inverse\n\n    // Number of reaction forces equal to number of feet contacts\n\n    int n_Fr = r_feet.cols();\n\n    // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n    // There is an additional gravity state.\n    // Populate A matrix\n    A = Eigen::MatrixXd::Zero(13, 13);\n    A.block(0, 6, 3, 3) = Rz;\n    A.block(3, 9, 3, 3) = Eigen::MatrixXd::Identity(3, 3);\n    A(11, 12) = 1.0;  // Gravity vector\n\n    // Populate B matrix\n    B = Eigen::MatrixXd::Zero(13, 3 * n_Fr);\n    Eigen::MatrixXd eye3 = Eigen::MatrixXd::Identity(3, 3);\n    for (int i = 0; i < n_Fr; i++) {\n        B.block(6, i * 3, 3, 3) = I_inv * skew_sym_mat(r_feet.col(i));\n        B.block(9, i * 3, 3, 3) = eye3 * 1.0 / mass;\n    }\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"Rz:\" << std::endl;\n    std::cout << Rz << std::endl;\n\n    std::cout << \"I_body:\" << std::endl;\n    std::cout << I_body << std::endl;\n\n    std::cout << \"I_world:\" << std::endl;\n    std::cout << I_world << std::endl;\n\n    std::cout << \"I_inv:\" << std::endl;\n    std::cout << I_inv << std::endl;\n\n    std::cout << \"r_feet:\" << std::endl;\n    std::cout << r_feet << std::endl;\n\n    std::cout << \"A:\" << std::endl;\n    std::cout << A << std::endl;\n\n    std::cout << \"B:\" << std::endl;\n    std::cout << B << std::endl;\n\n    std::cout << \"A.exp()\" << std::endl;\n    std::cout << A.exp() << std::endl;\n#endif\n}\n\n// Returns the discretized matrices for a given A and B matrix.\nvoid discrete_time_state_space(const double& dt, const Eigen::MatrixXd& A,\n                               const Eigen::MatrixXd& B, Eigen::MatrixXd& Adt,\n                               Eigen::MatrixXd& Bdt) {\n    // p.215 Raymond DeCarlo: Linear Systems: A State Variable Approach with\n    // Numerical Implementation, Prentice Hall, NJ, 1989\n    int n = A.cols() + B.cols();\n    Eigen::MatrixXd AB(n, n);\n    Eigen::MatrixXd expAB(n, n);\n    AB.setZero();\n    AB.block(0, 0, A.cols(), A.cols()) = A;\n    AB.block(0, A.cols(), A.cols(), B.cols()) = B;\n\n    expAB = (AB * dt).exp();\n\n    Adt = expAB.block(0, 0, A.cols(), A.cols());\n    Bdt = expAB.block(0, A.cols(), A.cols(), B.cols());\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"Adt\" << std::endl;\n    std::cout << Adt << std::endl;\n\n    std::cout << \"Bdt\" << std::endl;\n    std::cout << Bdt * dt << std::endl;\n#endif\n}\n\n// Zero order hold qp matrices\nvoid qp_matrices(const int& horizon, const Eigen::MatrixXd& Adt,\n                 const Eigen::MatrixXd& Bdt, Eigen::MatrixXd& Aqp,\n                 Eigen::MatrixXd& Bqp) {\n    if (horizon < 1) {\n        std::cerr << \"Error! MPC horizon must be at least 1 timestep long.\"\n                  << std::endl;\n    }\n\n    int n = Adt.cols();\n    int m = Bdt.cols();\n    std::vector<Eigen::MatrixXd> powerMats;\n    for (int i = 0; i < horizon + 1; i++) {\n        powerMats.push_back(Eigen::MatrixXd::Identity(n, n));\n    }\n\n    // Construct power matrices foe Adt\n    for (int i = 1; i < horizon + 1; i++) {\n        powerMats[i] = powerMats[i - 1] * Adt;\n    }\n\n    // Construct Aqp and Bqp matrices\n    Aqp.setZero();\n    Bqp.setZero();\n\n    for (int i = 0; i < horizon; i++) {\n        Aqp.block(i * n, 0, n, n) = powerMats[i + 1];  // Adt.pow(i+1);\n        for (int j = 0; j < horizon; j++) {\n            if (i >= j) {\n                int a_num = i - j;\n                Bqp.block(i * n, j * m, n, m) =\n                    powerMats[a_num] * Bdt;  // Adt.pow(a_num)*Bdt;\n            }\n        }\n    }\n\n    // Print power matrices for Adt\n    // for(int i = 0; i < horizon; i++){\n    // \tstd::cout << \"powerMats[\" << i << \"]\" << std::endl;\n    // \tstd::cout << powerMats[i] << std::endl;\n    // }\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"Aqp\" << std::endl;\n    std::cout << Aqp << std::endl;\n\n    std::cout << \"Bqp\" << std::endl;\n    std::cout << Bqp << std::endl;\n#endif\n}\n\nvoid get_desired_x(const int& horizon, Eigen::VectorXd& X_ref) {\n    Eigen::VectorXd x_des(13);\n\n    x_des.setZero();\n    x_des[0] = 0.0;        // M_PI/8; //des roll orientation\n    x_des[1] = 0.0;        //-M_PI/8; //des pitch orientation\n    x_des[2] = M_PI / 12;  // Yaw orientation\n\n    x_des[3] =\n        -0.1;  //;0.75; // Set desired z height to be 0.75m from the ground\n    x_des[5] =\n        0.75;  //;0.75; // Set desired z height to be 0.75m from the ground\n\n    X_ref = Eigen::VectorXd(horizon * 13);\n    X_ref.setZero();\n    for (int i = 0; i < horizon; i++) {\n        X_ref.segment(13 * i, 13) = x_des;\n        // X_ref[13*i + 5] = x_des[5]; // Set constant desired z-height\n    }\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"X_ref \" << std::endl;\n    std::cout << X_ref.transpose() << std::endl;\n#endif\n}\n\nvoid get_force_constraints(const int& n_Fr, Eigen::MatrixXd& CMat,\n                           Eigen::VectorXd& cvec) {\n    // Unilateral constraints on the force vector\n    // CMat * u + cvec >= 0\n    double mu = 0.9;      // coefficient of friction\n    double fz_max = 500;  // maximum z reaction force for one force vector.\n\n    Eigen::MatrixXd cfmat(\n        6, 3);  // the constraint matrix for a single force vector\n    Eigen::VectorXd cfvec(\n        6);  // the constraint vector for a single force vector\n\n    cfmat.setZero();\n    cfvec.setZero();\n\n    // -mu*fz <= fx <= mu*fz\n    cfmat(0, 0) = -1;\n    cfmat(0, 2) = mu;\n    cfmat(1, 0) = 1;\n    cfmat(1, 2) = mu;\n\n    // -mu*fz <= fy <= mu*fz\n    cfmat(2, 1) = -1;\n    cfmat(2, 2) = mu;\n    cfmat(3, 1) = 1;\n    cfmat(3, 2) = mu;\n\n    // fz_min = 0.0 <= fz <= fz_max\n    cfmat(4, 2) = -1.0;\n    cfvec[4] = fz_max;  // -fz + fz_max >= 0\n    cfmat(5, 2) = 1.0;\n\n#ifdef MPC_PRINT_ALL\n\n    std::cout << \"cfmat \" << std::endl;\n    std::cout << cfmat << std::endl;\n\n    std::cout << \"cfvec \" << std::endl;\n    std::cout << cfvec << std::endl;\n#endif\n\n    // Populate constraint matrix\n    CMat.setZero();\n    cvec.setZero();\n    for (int i = 0; i < n_Fr; i++) {\n        CMat.block(6 * i, 3 * i, 6, 3) = cfmat;\n        cvec.segment(6 * i, 6) = cfvec;\n    }\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"CMat \" << std::endl;\n    std::cout << CMat << std::endl;\n\n    std::cout << \"cvec \" << std::endl;\n    std::cout << cvec << std::endl;\n#endif\n}\n\nvoid get_qp_constraints(const int& horizon, const Eigen::MatrixXd& CMat,\n                        const Eigen::VectorXd& cvec, Eigen::MatrixXd& Cqp,\n                        Eigen::VectorXd& cvec_qp) {\n    Cqp.setZero();\n    cvec_qp.setZero();\n\n    int num_rows = CMat.rows();\n    int num_cols = CMat.cols();\n\n    // Set the force constraints over the horizon\n    // To DO: add 0 upperbound when reaction force should be 0.0 depending on\n    // the gate cycle.\n    for (int i = 0; i < horizon; i++) {\n        Cqp.block(i * num_rows, i * num_cols, num_rows, num_cols) = CMat;\n        cvec_qp.segment(i * num_rows, num_rows) = cvec;\n    }\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"Cqp\" << std::endl;\n    std::cout << Cqp.rows() << \"x\" << Cqp.cols() << std::endl;\n    std::cout << Cqp << std::endl;\n\n    std::cout << \"cvec_qp\" << std::endl;\n    std::cout << cvec_qp << std::endl;\n#endif\n}\n\nvoid get_qp_costs(const int& n, const int& m, const int& horizon,\n                  const Eigen::VectorXd& vecS_cost, const double& control_alpha,\n                  Eigen::MatrixXd& Sqp, Eigen::MatrixXd& Kqp) {\n    Eigen::MatrixXd S_cost = vecS_cost.asDiagonal();\n    Sqp.setZero();\n    for (int i = 0; i < horizon; i++) {\n        Sqp.block(n * i, n * i, n, n) = S_cost;\n    }\n\n    Kqp = control_alpha * Eigen::MatrixXd::Identity(m * horizon, m * horizon);\n\n#ifdef MPC_PRINT_ALL\n    std::cout << \"S_cost\" << std::endl;\n    std::cout << S_cost << std::endl;\n\n    std::cout << \"Sqp\" << std::endl;\n    std::cout << Sqp << std::endl;\n\n    std::cout << \"Kqp\" << std::endl;\n    std::cout << Kqp << std::endl;\n#endif\n}\n\nvoid solve_mpc_qp(const Eigen::MatrixXd& Aqp, const Eigen::MatrixXd& Bqp,\n                  const Eigen::VectorXd& X_ref, const Eigen::VectorXd& x0,\n                  const Eigen::MatrixXd& Sqp, const Eigen::MatrixXd& Kqp,\n                  const Eigen::MatrixXd& Cqp, const Eigen::VectorXd& cvec_qp,\n                  Eigen::VectorXd& f_vec_out) {\n#ifdef MPC_TIME_ALL\n    std::chrono::high_resolution_clock::time_point t_qp_prep_start;\n    std::chrono::high_resolution_clock::time_point t_qp_prep_end;\n    double dur_qp_prep = 0.0;\n\n    std::chrono::high_resolution_clock::time_point t_qp_mult_start;\n    std::chrono::high_resolution_clock::time_point t_qp_mult_end;\n    double dur_qp_mult = 0.0;\n\n    t_qp_prep_start = std::chrono::high_resolution_clock::now();\n    t_qp_mult_start = std::chrono::high_resolution_clock::now();\n#endif\n\n    Eigen::MatrixXd H(Bqp.cols(), Bqp.cols());\n    Eigen::VectorXd g_qp(Bqp.cols());\n\n    // For some reason g_qp evaluates slow unless we do these operations first\n    // std::cout << \"x0\" << x0.transpose() << std::endl;\n    Eigen::MatrixXd BqpT = Bqp.transpose();\n    Eigen::MatrixXd m1;\n    m1.noalias() = BqpT * Sqp;\n    Eigen::MatrixXd m2;\n    m2.noalias() = 2.0 * m1;\n    Eigen::VectorXd v1 = (Aqp * x0).eval() - X_ref;\n\n    H = 2.0 * (m1 * Bqp + Kqp);\n    g_qp.noalias() = m1 * v1;\n\n#ifdef MPC_TIME_ALL\n    t_qp_mult_end = std::chrono::high_resolution_clock::now();\n#endif\n\n    // std::cout << \"H\" << std::endl;\n    // std::cout << H << std::endl;\n\n    // std::cout << \"g\" << std::endl;\n    // std::cout << g.transpose() << std::endl;\n\n    // Quadprog matrices vectors\n    GolDIdnani::GMatr<double> G, CE, CI;\n    GolDIdnani::GVect<double> g0, ce0, ci0, x;\n    int n_quadprog_ = 1;\n    int p_quadprog_ = 0;\n    int m_quadprog_ = 0;\n\n    // Quadprog size setup\n    n_quadprog_ = Bqp.cols();      // number of decision variables\n    m_quadprog_ = 0;               // number of equality constraints\n    p_quadprog_ = cvec_qp.size();  // number of inequality constraints\n                                   // (unilateral force constraints).\n\n    // std::cout << \"n_quadprog_\" << n_quadprog_ << std::endl;\n    // std::cout << \"p_quadprog_\" << p_quadprog_ << std::endl;\n\n    f_vec_out.resize(n_quadprog_);\n\n    x.resize(n_quadprog_);  // Decision Variables\n    // Objective\n    G.resize(n_quadprog_, n_quadprog_);\n    g0.resize(n_quadprog_);\n    // Equality Constraints\n    CE.resize(n_quadprog_, m_quadprog_);\n    ce0.resize(m_quadprog_);\n    // Inequality Constraints\n    CI.resize(n_quadprog_, p_quadprog_);\n    ci0.resize(p_quadprog_);\n\n    // Solve the following QP:\n    // min (1/2)*U^T*H*U + U^T*g\n    // st. C*U <= cvec_qp\n    // where U is the decision variable (vector of forces)\n\n    // Populate G Cost Matrix\n    // G = P\n    for (int i = 0; i < n_quadprog_; i++) {\n        for (int j = 0; j < n_quadprog_; j++) {\n            G[i][j] = H(i, j);\n        }\n    }\n\n    // Populate g0 cost vector\n    for (int i = 0; i < n_quadprog_; i++) {\n        g0[i] = g_qp[i];\n    }\n\n    // No equality constraints. So CE and ce0 are untouched.\n\n    // Populate Inequality Constraint Matrix\n    for (int i = 0; i < p_quadprog_; i++) {\n        for (int j = 0; j < n_quadprog_; j++) {\n            CI[j][i] = Cqp(i, j);\n        }\n    }\n\n    // Populate Inequality Constraint Vector\n    // ci0 = h_\n    for (int i = 0; i < p_quadprog_; i++) {\n        ci0[i] = cvec_qp[i];\n    }\n\n#ifdef MPC_TIME_ALL\n\n    t_qp_prep_end = std::chrono::high_resolution_clock::now();\n    dur_qp_mult = std::chrono::duration_cast<std::chrono::duration<double> >(\n                      t_qp_mult_end - t_qp_mult_start)\n                      .count();\n    dur_qp_prep = std::chrono::duration_cast<std::chrono::duration<double> >(\n                      t_qp_prep_end - t_qp_prep_start)\n                      .count();\n\n    std::cout << \"QP mult took \" << dur_qp_mult << \" seconds.\" << std::endl;\n    std::cout << \"QP mult rate \" << (1.0 / dur_qp_mult) << \" Hz\" << std::endl;\n    std::cout << \"QP prep took \" << dur_qp_prep << \" seconds.\" << std::endl;\n    std::cout << \"QP prep rate \" << (1.0 / dur_qp_prep) << \" Hz\" << std::endl;\n\n    // Time the QP solve\n    std::chrono::high_resolution_clock::time_point t_qp_solve_start;\n    std::chrono::high_resolution_clock::time_point t_qp_solve_end;\n    double dur_qp_solve = 0.0;\n\n    // Start\n    t_qp_solve_start = std::chrono::high_resolution_clock::now();\n#endif\n\n    double qp_result = solve_quadprog(G, g0, CE, ce0, CI, ci0, x);\n\n#ifdef MPC_TIME_ALL\n    // End\n    t_qp_solve_end = std::chrono::high_resolution_clock::now();\n    dur_qp_solve = std::chrono::duration_cast<std::chrono::duration<double> >(\n                       t_qp_solve_end - t_qp_solve_start)\n                       .count();\n#endif\n\n    // Populate qd result from QP answer\n    for (int i = 0; i < n_quadprog_; i++) {\n        f_vec_out[i] = x[i];\n    }\n    // std::cout << \"qp_result = \" << qp_result << std::endl;\n    // std::cout << \"f_vec_out = \" << f_vec_out.transpose() << std::endl;\n\n#ifdef MPC_TIME_ALL\n    std::cout << \"QP took \" << dur_qp_solve << \" seconds.\" << std::endl;\n    std::cout << \"QP rate \" << (1.0 / dur_qp_solve) << \" Hz\" << std::endl;\n#endif\n}\n\nvoid print_f_vec(int& horizon, int& n_Fr, const Eigen::VectorXd& f_vec_out) {\n    for (int i = 0; i < horizon; i++) {\n        std::cout << \"horizon:\" << i + 1 << std::endl;\n\n        for (int j = 0; j < n_Fr; j++) {\n            std::cout << \"  f\" << j << \":\"\n                      << f_vec_out.segment(3 * i * n_Fr + 3 * j, 3).transpose()\n                      << std::endl;\n        }\n    }\n}\n\nvoid solve_mpc(const Eigen::VectorXd& x0, const Eigen::VectorXd& X_des,\n               const Eigen::MatrixXd& r_feet, const double& robot_mass,\n               const Eigen::MatrixXd& I_body, const int& horizon,\n               const double& mpc_dt, Eigen::VectorXd& f_vec_out) {\n#ifdef MPC_TIME_ALL\n    // Time the QP solve\n    std::chrono::high_resolution_clock::time_point t_mat_setup_start;\n    std::chrono::high_resolution_clock::time_point t_mat_setup_end;\n    double dur_mat_setup = 0.0;\n    // Start\n    t_mat_setup_start = std::chrono::high_resolution_clock::now();\n#endif\n\n    int n_Fr = r_feet.cols();\n\n    // create continuous time state space matrices\n    double psi_yaw = x0[2];\n    Eigen::MatrixXd A(13, 13);\n    A.setZero();\n    Eigen::MatrixXd B(13, 3 * n_Fr);\n    B.setZero();\n    int n = A.cols();\n    int m = B.cols();\n    cont_time_state_space(robot_mass, I_body, psi_yaw, r_feet, A, B);\n\n    // create discrete time state space matrices\n    Eigen::MatrixXd Adt(n, n);\n    Adt.setZero();\n    Eigen::MatrixXd Bdt(n, m);\n    Bdt.setZero();\n    discrete_time_state_space(mpc_dt, A, B, Adt, Bdt);\n\n    // create A and B QP matrices\n    Eigen::MatrixXd Aqp(n * horizon, n);\n    Aqp.setZero();\n    Eigen::MatrixXd Bqp(n * horizon, m * horizon);\n    Bqp.setZero();\n    qp_matrices(horizon, Adt, Bdt, Aqp, Bqp);\n\n    // create force constraint matrices and vectors\n    Eigen::MatrixXd CMat(\n        6 * n_Fr,\n        3 * n_Fr);  // the QP constraint matrix for n_Fr reaction forces\n    Eigen::VectorXd cvec(\n        6 * n_Fr);  // the constraint matrix for n_Fr reaction forces\n    get_force_constraints(n_Fr, CMat, cvec);\n\n    Eigen::MatrixXd Cqp(horizon * 6 * n_Fr, horizon * 3 * n_Fr);\n    Eigen::VectorXd cvec_qp(horizon * 6 * n_Fr);\n    get_qp_constraints(horizon, CMat, cvec, Cqp, cvec_qp);\n\n    // Cost matrices (Values similar to cheetah 3)\n    Eigen::MatrixXd Sqp(n * horizon, n * horizon);\n    Eigen::MatrixXd Kqp(m * horizon, m * horizon);\n\n    Eigen::VectorXd vecS_cost(n);\n    //        <<  th1,  th2,  th3,  px,  py,  pz,   w1,  w2,   w3,   dpx,  dpy,\n    //        dpz,  g\n    // vecS_cost << 0.25, 0.25, 10.0, 2.0, 2.0, 50.0, 0.05, 0.05, 0.30, 0.20,\n    // 0.2, 0.10, 0.0;\n    vecS_cost << 1.0, 1.0, 10.0, 2.0, 2.0, 50.0, 0.05, 0.05, 0.30, 0.20, 0.2,\n        0.10, 0.0;\n    Eigen::MatrixXd S_cost = vecS_cost.asDiagonal();\n    double control_alpha = 4e-5;\n    get_qp_costs(n, m, horizon, vecS_cost, control_alpha, Sqp, Kqp);\n\n#ifdef MPC_TIME_ALL\n    // End\n    t_mat_setup_end = std::chrono::high_resolution_clock::now();\n    dur_mat_setup = std::chrono::duration_cast<std::chrono::duration<double> >(\n                        t_mat_setup_end - t_mat_setup_start)\n                        .count();\n\n    std::cout << \"QP matrices setup took \" << dur_mat_setup << \" seconds.\"\n              << std::endl;\n    std::cout << \"QP matrices setup rate \" << (1.0 / dur_mat_setup) << \" Hz\"\n              << std::endl;\n\n    std::cout << \"robot state x_cur:\" << x0.transpose() << std::endl;\n    std::cout << \"            x_des:\" << X_des.head(n).transpose() << std::endl;\n    std::cout << \"horizon steps = \" << horizon\n              << \", horizon_time = \" << horizon * mpc_dt << std::endl;\n#endif\n\n    // Solve MPC\n    solve_mpc_qp(Aqp, Bqp, X_des, x0, Sqp, Kqp, Cqp, cvec_qp, f_vec_out);\n}\n\nvoid simulate_mpc() {\n    // System Params\n    double robot_mass = 10;  // kg mass of the robot\n    Eigen::MatrixXd I_body =\n        Eigen::MatrixXd::Identity(3, 3);  // Body Inertia matrix\n    I_body(0, 0) = 5;\n    I_body(0, 1) = 2;\n    I_body(1, 0) = 2;\n    I_body(1, 1) = 5;\n    I_body(2, 2) = 2.5;\n\n    // starting robot state\n    // Current reduced state of the robot\n    // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n    Eigen::VectorXd x0(13);\n    x0.setZero();\n    x0[2] = 0.0;   // M_PI/24.0;; // Yaw orientation\n    x0[3] = 0.0;   // x translation error\n    x0[4] = 0.0;   // y translation error\n    x0[5] = 0.75;  // Height\n    x0[12] = -9.81;\n\n    // Feet Configuration\n    // Set Foot contact locations\n    Eigen::MatrixXd r_feet(3, 4);  // Each column is a reaction force in x,y,z\n    r_feet.setZero();\n    double foot_length = 0.05;   // 5cm distance between toe and heel\n    double nominal_width = 0.1;  // 10cm distance between left and right feet\n\n    // Flat ground contact, z = 0.0\n    // 2 Contact Configuration\n    // // Right Foot\n    // r_feet(0, 0) = 0.0; // x\n    // r_feet(1, 0) = -nominal_width/2.0; //y\n    // // Left Foot\n    // r_feet(0, 1) = 0.0;  // x\n    // r_feet(1, 1) = nominal_width/2.0; //y\n\n    // 4 Contact Configuration\n    // Right Foot Front\n    r_feet(0, 0) = foot_length / 2.0;     // x\n    r_feet(1, 0) = -nominal_width / 2.0;  // y\n    // Right Foot Back\n    r_feet(0, 1) = -foot_length / 2.0;    // x\n    r_feet(1, 1) = -nominal_width / 2.0;  // y\n    // Left Foot Front\n    r_feet(0, 2) = foot_length / 2.0;    // x\n    r_feet(1, 2) = nominal_width / 2.0;  // y\n    // Left Foot Back\n    r_feet(0, 3) = -foot_length / 2.0;   // x\n    r_feet(1, 3) = nominal_width / 2.0;  // y\n\n    int horizon = 10;\n    double mpc_dt = 0.025;\n\n    int n_Fr = r_feet.cols();  // Number of contacts\n    int n = 13;\n    int m = 3 * n_Fr;\n\n    Eigen::VectorXd f_vec_out(m * horizon);\n    Eigen::MatrixXd f_Mat(3, n_Fr);\n    f_Mat.setZero();\n\n    // Get desired reference\n    Eigen::VectorXd X_des(n * horizon);\n    get_desired_x(horizon, X_des);\n\n    // Solve the MPC\n    solve_mpc(x0, X_des, r_feet, robot_mass, I_body, horizon, mpc_dt,\n              f_vec_out);\n    print_f_vec(horizon, n_Fr, f_vec_out);\n    // Populate force output from 1 horizon.\n    assemble_vec_to_matrix(3, n_Fr, f_vec_out.head(3 * n_Fr), f_Mat);\n\n    // Simulate MPC for one time step\n    double sim_dt = 1e-3;\n    Eigen::VectorXd x_prev(n);\n    x_prev = x0;\n    Eigen::VectorXd x_next(n);\n    x_next.setZero();\n    integrate_robot_dynamics(sim_dt, x_prev, f_Mat, r_feet, robot_mass, I_body,\n                             x_next);\n\n    // Simulate MPC for x seconds\n    double total_sim_time = 7.0;\n    int sim_steps = static_cast<int>(total_sim_time / sim_dt);\n    std::cout << \"sim_steps:\" << sim_steps << std::endl;\n\n    double last_control_time = 0.0;\n    double cur_time = 0.0;\n\n    std::cout << \"x_start:\" << x0.transpose() << std::endl;\n    Eigen::VectorXd f_cmd(12);\n    f_cmd.setZero();\n\n    bool print_for_plots = false;\n\n    if (print_for_plots) {\n        printf(\n            \"t, r, p, y, x, y, z, wx, wy, wz, dx, dy, dz, f0x, f0y, f0z, f1x, \"\n            \"f1y, f1z, f2x, f2y, f2z, f3x, f3y, f3z\\n\");\n    }\n    for (int i = 0; i < sim_steps; i++) {\n        // Solve new MPC every mpc control tick\n        if ((cur_time - last_control_time) > mpc_dt) {\n            solve_mpc(x_prev, X_des, r_feet, robot_mass, I_body, horizon,\n                      mpc_dt, f_vec_out);\n            assemble_vec_to_matrix(3, n_Fr, f_vec_out.head(3 * n_Fr), f_Mat);\n            last_control_time = cur_time;\n            f_cmd.head(m) = f_vec_out.head(m);\n\n            if (!print_for_plots) {\n                std::cout << \"  Computed MPC Forces\" << std::endl;\n                printf(\"  f0:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[0], f_cmd[1],\n                       f_cmd[2]);\n                printf(\"  f1:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[3], f_cmd[4],\n                       f_cmd[5]);\n                if (n_Fr > 2) {\n                    printf(\"  f2:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[6], f_cmd[7],\n                           f_cmd[8]);\n                    printf(\"  f3:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[9], f_cmd[10],\n                           f_cmd[11]);\n                }\n            }\n        }\n\n        // Integrate the robot dynamics\n        integrate_robot_dynamics(sim_dt, x_prev, f_Mat, r_feet, robot_mass,\n                                 I_body, x_next);\n        // Update x\n        x_prev = x_next;\n        // Increment time\n        cur_time += sim_dt;\n\n        if (print_for_plots) {\n            printf(\n                \"%0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, \"\n                \"%0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f,%0.3f,%0.3f, \"\n                \"%0.3f,%0.3f,%0.3f, %0.3f,%0.3f,%0.3f, %0.3f,%0.3f,%0.3f \\n\",\n                cur_time, x_next[0], x_next[1], x_next[2], x_next[3], x_next[4],\n                x_next[5], x_next[6], x_next[7], x_next[8], x_next[9],\n                x_next[10], x_next[11], f_cmd[0], f_cmd[1], f_cmd[2], f_cmd[3],\n                f_cmd[4], f_cmd[5], f_cmd[6], f_cmd[7], f_cmd[8], f_cmd[9],\n                f_cmd[10], f_cmd[11]);\n        } else {\n            printf(\n                \"t:%0.3f, (R,P,Y):(%0.3f, %0.3f, %0.3f), (x,y,z):(%0.3f, \"\n                \"%0.3f, %0.3f), (wx, wy, wz):(%0.3f, %0.3f, %0.3f), (dx, dy, \"\n                \"dz):(%0.3f, %0.3f, %0.3f) \\n\",\n                cur_time, x_next[0], x_next[1], x_next[2], x_next[3], x_next[4],\n                x_next[5], x_next[6], x_next[7], x_next[8], x_next[9],\n                x_next[10], x_next[11]);\n        }\n\n        // std::cout << \"    f:\" << f_vec_out.head(m).transpose() << std::endl;\n        // for(int j = 0; j < n_Fr; j++){\n        //   std::cout << \"    f\" << j << \":\" << f_vec_out.segment(3*j,\n        //   3).transpose() << std::endl;\n        // }\n        // std::cout << \"cur_time:\" << cur_time << \"  last_control_time:\" <<\n        // last_control_time << std::endl;\n    }\n    std::cout << \"x_des\" << X_des.tail(n).transpose() << std::endl;\n}\n\nint main(int argc, char** argv) {\n    simulate_mpc();\n    return 0;\n}\n", "meta": {"hexsha": "07bc4ea3ae143e16a479bd50425cbb75e7451464", "size": 28939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PnC/MPC/test_mpc.cpp", "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": "PnC/MPC/test_mpc.cpp", "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": "PnC/MPC/test_mpc.cpp", "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": 34.1664698937, "max_line_length": 80, "alphanum_fraction": 0.5547531014, "num_tokens": 9285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6911513325621575}}
{"text": "#ifndef HH_PRE_HPP_INCLUDED\n#define HH_PRE_HPP_INCLUDED\n\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n//UNITS: sec, V, A, M\n\n//DECLARATIONS FOR HH_PRE_MODEL\n\nclass HH_PRE\n{\n   private:\n      const double pi = boost::math::constants::pi<double>();\n      double Cm = 1.0;   // F/m^2 Specific capacitance\n      //----Reversal potentials for Na, K, channels in mV\n      double ENa = 50.0;   // Reversal potential for Sodium currents in Volts\n      double EK = -85.0;    // Reversal potential for Potassium currents in Volts\n      double ELeak = -81; // Reversal potential for Leak currents in Volts\n\n      double GNa = 100;   // Maximum conductance for Sodium channels S/m^2\n      double GK = 36;    // Maximum conductance for Potassium channels S/m^2\n      double GLeak = 0.5;  // Maximum conductance for Leak channels S/m^2\n\n   public:\n      double IExt = 0.0; //extern current in Amps\n      double Area = 0.0;\n      double Cap = 0.0;\n      double V = 0.0;      // Membrane voltage V\n      /* NEURON class explicit constructor */\n      HH_PRE( double Area_ = 500E-08): Area(Area_)\n      {\n         Cap = Cm * Area;\n      };\n      //---Equations for bouton Na Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n      double alpha_Na_act(const double V);\n      double beta_Na_act(const double V);\n      double alpha_Na_inact(const double V);\n      double beta_Na_inact(const double V);\n      //---Equations for bouton K Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n      double alpha_K_act(const double V);\n      double beta_K_act(const double V);\n      //---Declaration of the ODE solver\n      template <class State, class Deriv >\n      void operator() ( const State &x, Deriv &dxdt , const double  t );\n};\n//Function declarations\n//------------- Na+ channels --- implimented from classical HH (1952)\ndouble HH_PRE::alpha_Na_act(const double V)\n{\n   double a = 0.1;\n   double b = 45;\n   double c = 10;\n   double val = (- a * ( (V + b) / (exp( -(V + b) / c ) - 1 ) ) );\n\n   double A = 93.82;\n   double B = -105;\n   double C = 17;\n   double VAL = (- A * ( (V + B) / (exp( -(V + B) / C ) - 1 ) ) );\n   return (VAL);\n}\ndouble HH_PRE::beta_Na_act(const double V)\n{\n   double a = 4;\n   double b = 70;\n   double c = 18;\n   double val = ( a * ( exp( - (V + b) / c )) );\n\n   double A = 0.168;\n   double C = 23.27;\n   double VAL = ( A *  exp( - V / C ) );\n\n   return (VAL);\n}\ndouble HH_PRE::alpha_Na_inact(const double V)\n{\n   double val = 0.07 * exp( -( V + 70) /20 );\n\n   double A = 0.0001;\n   double C = 18.706;\n   double VAL = ( A *  exp( - (V + 0) / C ) );\n\n   return (VAL);\n}\ndouble HH_PRE::beta_Na_inact(const double V)\n{\n   double val = ( 1 / ( exp( - (V + 40) / 10) + 1) );\n\n   double A = 6.6;\n   double B = 17.6;\n   double C = 13.3;\n   double VAL = ( A / ( (exp( -(V + B) / C ) + 1 ) ) );\n\n   return (VAL);\n}\n//--------K+ channel alpha & beta\ndouble HH_PRE::alpha_K_act(const double V)\n{\n   double val = -0.01 * (V + 60) / ( exp( -(V +  60) / 10) - 1 );\n   double VAL = -0.01 * (V + 55) / ( exp( -(V +  55) / 10) - 1 );\n   return (VAL);\n};\ndouble HH_PRE::beta_K_act(const double V)\n{\n   double val = 0.125 * exp (- (V + 70) / 80);\n   double VAL = 0.125 * exp (- (V + 65) / 80);\n   return (VAL);\n};\n//-------HH_PRE class ODE Function\n\ntemplate <class State, class Deriv >\nvoid HH_PRE::operator() ( const State &x, Deriv &dxdt , const double t )\n{\n   //typename boost::range_iterator< const State >::type x_it = boost::begin( x_ );\n   //typename boost::range_iterator< Deriv >::type dxdt_it = boost::begin( dxdt_ );\n\n   dxdt[0] = ( alpha_Na_act(x[3]) * (1 - x[0]) ) - (beta_Na_act(x[3]) * x[0]); // Na activation\n   dxdt[1] = ( alpha_Na_inact(x[3]) * (1 - x[1]) ) - (beta_Na_inact(x[3]) * x[1]); // Na inactivation\n   dxdt[2] = ( alpha_K_act(x[3]) * (1 - x[2]) ) - (beta_K_act(x[3]) * x[2]); // K activation\n   double INa =   -(Area * GNa * pow(x[0],3) * x[1] * (x[3] - ENa) );\n   double IK =   -(Area * GK * pow(x[2],4) * (x[3] - EK) );\n   double ILeak = -(Area * GLeak *  (x[3] - ELeak) );\n   dxdt[3] = (1/Cap) * (INa + IK + ILeak  + (IExt * Area)  );\n};\n\n#endif // HH_PRE_HPP_INCLUDED\n\n", "meta": {"hexsha": "97821f63849b83815ff675221acf7d87b1ec6f1f", "size": 4163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/hh_pre_det_model.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/hh_pre_det_model.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/hh_pre_det_model.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": 32.0230769231, "max_line_length": 101, "alphanum_fraction": 0.5741052126, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.691151324297171}}
{"text": "#include \"icp.h\"\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing FloatType = double;\nusing IndexType = int64_t;\nusing EigenMatrix = Eigen::MatrixXd;\nusing EigenVector = Eigen::VectorXd;\n\n#include \"common/io.h\"\n#include \"common/kdtree.h\"\n#include \"common/debug.h\"\n#include \"svd.h\"\n\n// Custom struct for KD tree\nstruct Point : public Vec3 {\n    Point() {}\n    Point(const Vec3 &v, int index = -1) : Vec3(v), i(index) {}\n    int i;\n};\n\n// Rodrigues rotation matrix\nEigenMatrix rodrigues(const EigenVector &w, const double theta) {\n    const double c = std::cos(theta);\n    const double s = std::sin(theta);\n\n    const double wx = w(0);\n    const double wy = w(1);\n    const double wz = w(2);\n    EigenMatrix K(3, 3);\n    K << 0.0, -wz, wy, wz, 0.0, -wx, -wy, wx, 0.0;\n\n    EigenMatrix I = EigenMatrix::Identity(3, 3);\n    return I + K * s + (K * K) * (1.0 - c);\n}\n\n//! single point to point ICP step\nvoid point2pointICP_step(const std::vector<Vec3> &target, const std::vector<Vec3> &source, EigenMatrix *rotMat,\n                         EigenVector *trans) {\n    // Construct Kd-tree to find closest points\n    KDTree<Vec3> tree;\n    tree.construct(target);\n\n    // {{ NOT_IMPL_ERROR();\n\n    // Match closest point pairs\n    // Hint:\n    // Construct here that two matrices X and P,\n    // whose elements are positions of source vertices (X),\n    // and those for closest points of the sources (P)\n    const int nPoints = (int)source.size();\n    EigenMatrix X(nPoints, 3);\n    EigenMatrix P(nPoints, 3);\n    for (int i = 0; i < nPoints; i++) {\n        const Vec3 &v = source[i];\n        const Vec3 u = tree.nearest(v);\n        X.row(i) << v.x, v.y, v.z;\n        P.row(i) << u.x, u.y, u.z;\n    }\n\n    // Subtract xMean, pMean from X, P\n    // Hint:\n    // Row-wise or column-wise mean (also sum, max, min etc.) of Eigen matrices\n    // can be easily calculate using \"rowwise()\" or \"colwise()\".\n    const EigenVector xMean = X.colwise().mean();\n    const EigenVector pMean = P.colwise().mean();\n    X.rowwise() -= xMean.transpose();\n    P.rowwise() -= pMean.transpose();\n\n    // Solve with SVD to obtain R\n    // Hint:\n    // An SVD method \"eigenSVD\" is already given in \"svd.h\".\n    // See its arguments carefully when using it.\n    const EigenMatrix M = P.transpose() * X;\n    EigenMatrix U, V;\n    EigenVector sigma;\n    eigenSVD(M, U, sigma, V);\n    const double detVU = (U * V.transpose()).determinant();\n\n    // Revise sign of determinant\n    EigenVector diagH(3);\n    diagH << 1.0, 1.0, detVU;\n\n    // Output\n    // Hint:\n    // Be careful that arguments for output matrices and vectors\n    // are represented as \"pointers\". Therefore, you should insert\n    // values for them with \"asterisk\" like \"*lhs = rhs\".\n    *rotMat = U * diagH.asDiagonal() * V.transpose();\n    *trans = pMean - (*rotMat) * xMean;\n\n    // }}\n}\n\n//! single point to plane ICP step\nvoid point2planeICP_step(const std::vector<Vec3> &target, const std::vector<Vec3> &targetNorm,\n                         const std::vector<Vec3> &source, Eigen::MatrixXd *rotMat, Eigen::VectorXd *trans) {\n    // Construct Kd-tree to find closest points\n    std::vector<Point> points;\n    for (int i = 0; i < (int)target.size(); i++) {\n        points.emplace_back(target[i], i);\n    }\n\n    KDTree<Point> tree;\n    tree.construct(points);\n\n    // {{ NOT_IMPL_ERROR();\n\n    // Construct linear system\n    // Hint:\n    // prepare matrix A and vector b\n    // A is 6x6 matrix, and b is 6-D vector\n    const int nPoints = (int)source.size();\n    EigenMatrix A(6, 6);\n    EigenVector b(6);\n    A.setZero();\n    b.setZero();\n    for (int i = 0; i < nPoints; i++) {\n        const Vec3 &x = source[i];\n        const Point pt = tree.nearest(x);\n        const Vec3 &p = Vec3(pt.x, pt.y, pt.z);\n        const Vec3 &n = targetNorm[pt.i];\n        const Vec3 x_cross_n = cross(x, n);\n        EigenVector v(6);\n        v << x_cross_n.x, x_cross_n.y, x_cross_n.z, n.x, n.y, n.z;\n        A += v * v.transpose();\n        b += v * (dot(n, p - x));\n    }\n\n    // Solve\n    // Hint:\n    // Use \"Eigen::PartialPivLU\" to solve the system\n    Eigen::PartialPivLU<EigenMatrix> lu(A);\n    EigenVector u = lu.solve(b);\n\n    // Substitute to instances a, t\n    // Hint:\n    // Eigen matrices and vectors can be initialized\n    // with its elements by \"<<\" operator.\n    EigenVector a(3);\n    a << u(0), u(1), u(2);\n    EigenVector t(3);\n    t << u(3), u(4), u(5);\n\n    // Reproduce rotation matrix\n    // Hint:\n    // Remember that vector \"a\" is the multiple of\n    // the direction of rotation axis and\n    // the degree of rotation angle.\n    const double theta = a.norm();\n    const EigenVector w = a / theta;\n    *rotMat = rodrigues(w, theta);\n    *trans = t;\n\n    // }}\n}\n\nvoid rigidICP(const std::vector<Vec3> &target, const std::vector<Vec3> &targetNorm, std::vector<Vec3> &source,\n              std::vector<Vec3> &sourceNorm, ICPMetric metric, int maxIters, double tolerance, bool verbose) {\n    // Point-to-point ICP\n    for (int it = 0; it < maxIters; it++) {\n        Eigen::MatrixXd R(3, 3);\n        Eigen::VectorXd t(3);\n        switch (metric) {\n        case ICPMetric::Point2Point:\n            point2pointICP_step(target, source, &R, &t);\n            break;\n\n        case ICPMetric::Point2Plane:\n            point2planeICP_step(target, targetNorm, source, &R, &t);\n            break;\n\n        default:\n            throw std::runtime_error(\"Unknown ICP metric type!\");\n        }\n\n        // Apply rigid transformation\n        for (int i = 0; i < (int)source.size(); i++) {\n            Eigen::VectorXd v(3);\n            v << source[i].x, source[i].y, source[i].z;\n            Eigen::VectorXd u = R * v + t;\n            source[i] = Vec3(u(0), u(1), u(2));\n\n            Eigen::VectorXd n(3);\n            n << sourceNorm[i].x, sourceNorm[i].y, sourceNorm[i].z;\n            Eigen::VectorXd m = R * n;\n            sourceNorm[i] = Vec3(m(0), m(1), m(2));\n        }\n\n        // Check current error\n        const double error = t.norm() + (R - Eigen::MatrixXd::Identity(3, 3)).norm();\n\n        // Report\n        if (verbose) {\n            printf(\"*** %d iteration ***\\n\", it + 1);\n            printf(\"R = \\n\");\n            std::cout << R << std::endl;\n            printf(\"t = \\n\");\n            std::cout << t << std::endl;\n            printf(\"error = %f\\n\", error);\n            printf(\"\\n\");\n        }\n\n        char outfile[256];\n        sprintf(outfile, \"intermediate_%03d.off\", it);\n        write_off(std::string(outfile), source, sourceNorm);\n\n        if (error < tolerance) {\n            break;\n        }\n    }\n}\n", "meta": {"hexsha": "ba76ac5a897a6485e6e4fe1bb0a7bdb03bfea1c7", "size": 6551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_stars_repo_name": "tatsy/cpp-python-beginners", "max_stars_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-23T12:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T12:35:56.000Z", "max_issues_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_issues_repo_name": "tatsy/cpp-python-beginners", "max_issues_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_forks_repo_name": "tatsy/cpp-python-beginners", "max_forks_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T10:20:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T09:04:47.000Z", "avg_line_length": 30.4697674419, "max_line_length": 111, "alphanum_fraction": 0.5660204549, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6911408099607699}}
{"text": "#include <doctest/doctest.h>\n\n#include <non_lin_optim/solvelin.h>\n#include <non_lin_optim/version.h>\n\n#include <iostream>\n#include <Eigen/Dense>\n\nbool print = false;\n\ntemplate<typename T, typename U>\nvoid f(const Eigen::MatrixBase<T>& A, \n       const Eigen::MatrixBase<U>& b, \n       const Eigen::MatrixBase<U>& x, \n       bool positive){\n    \n    auto x_hat = solvelin::lu::fullPiv(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat lu::fullPiv \\n\" << x_hat << std::endl;   \n    \n    x_hat = solvelin::qr::householderQr(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat qr::householderQr \\n\" << x_hat << std::endl;\n    \n    x_hat = solvelin::qr::colPivHouseholderQr(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat qr::colPivHouseholderQr \\n\" << x_hat << std::endl;  \n    \n    x_hat = solvelin::qr::fullPivHouseholderQr(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat qr::fullPivHouseholderQr \\n\" << x_hat << std::endl;   \n    \n    x_hat = solvelin::qr::completeOrthogonalDecomposition(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat qr::completeOrthogonalDecomposition \\n\" << x_hat << std::endl;    \n    \n    if(positive){\n        x_hat = solvelin::cholesky::llt(A, b);\n        CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));\n        if(print) std::cout << \"x_hat cholesky::llt \\n\" << x_hat << std::endl;\n        \n        x_hat = solvelin::cholesky::ldlt(A, b);\n        CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n        if(print) std::cout << \"x_hat cholesky::ldlt \\n\" << x_hat << std::endl;         \n    }else{\n        CHECK_THROWS(solvelin::cholesky::llt(A, b));\n        if(print) std::cout << \"cholesky::llt cannot solve non-positive matrices!\\n\" << std::endl;\n        \n        CHECK_THROWS(solvelin::cholesky::ldlt(A, b));\n        if(print) std::cout << \"cholesky::ldlt cannot solve non-positive matrices!\\n\" << std::endl;        \n    }   \n    \n    x_hat = solvelin::svd::bdc(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat svd::bdc \\n\" << x_hat << std::endl; \n    \n    x_hat = solvelin::svd::jacobi(A, b);\n    CHECK((x_hat-x).cwiseAbs().maxCoeff() == doctest::Approx(0).epsilon(0.0001));    \n    if(print) std::cout << \"x_hat svd::jacobi \\n\" << x_hat << std::endl;       \n}\n\nTEST_CASE(\"Positive definite\") {\n\n    Eigen::MatrixXf A(3,3);\n    Eigen::Vector3f b;\n    Eigen::Vector3f x;\n    A << 2,-1,0,  -1,2,-1,  0,-1,2;   \n    b << 3, 3, 4;\n    x << 4.75, 6.5, 5.25;\n    \n    if(print) std::cout << \"Positive definite\" << std::endl;\n    f(A, b, x, true);\n}\n\nTEST_CASE(\"Normal case\") {\n\n    Eigen::MatrixXf A(3,3);\n    Eigen::Vector3f b;\n    Eigen::Vector3f x;\n    A << 1,2,3,  4,5,6,  7,8,10;  \n    b << 3, 3, 4;\n    x << -2, 1, 1;\n    \n    if(print) std::cout << \"Normal case\" << std::endl;\n    f(A, b, x, false);\n}\n\nTEST_CASE(\"Singular Matrix\") {\n    \n    if(print) std::cout << \"Singular Matrix\" << std::endl;\n\n    Eigen::MatrixXf A(3,3);\n    Eigen::Vector3f b;\n    A << 9,17,1, 12,18,9, 11,13,14;\n    b << 18, 0, 18;\n    \n    auto x_hat = solvelin::lu::fullPiv(A, b);\n    if(print) std::cout << \"x_hat lu::fullPiv \\n\" << x_hat << std::endl;\n    \n    x_hat = solvelin::MoorePenrose(A, b);\n    if(print) std::cout << \"x_hat MoorePenrose \\n\" << x_hat << std::endl;\n    \n    x_hat = solvelin::qr::householderQr(A, b);\n    if(print) std::cout << \"x_hat qr::householderQr \\n\" << x_hat << std::endl;  \n    \n    x_hat = solvelin::qr::colPivHouseholderQr(A, b);    \n    if(print) std::cout << \"x_hat qr::colPivHouseholderQr \\n\" << x_hat << std::endl;  \n    \n    x_hat = solvelin::qr::fullPivHouseholderQr(A, b);  \n    if(print) std::cout << \"x_hat qr::fullPivHouseholderQr \\n\" << x_hat << std::endl;   \n    \n    x_hat = solvelin::qr::completeOrthogonalDecomposition(A, b);    \n    if(print) std::cout << \"x_hat qr::completeOrthogonalDecomposition \\n\" << x_hat << std::endl;    \n    /*\n    x_hat = solvelin::cholesky::llt(A, b);    \n    if(print) std::cout << \"x_hat cholesky::llt \\n\" << x_hat << std::endl;   \n    \n    x_hat = solvelin::cholesky::ldlt(A, b);  \n    if(print) std::cout << \"x_hat cholesky::ldlt \\n\" << x_hat << std::endl;\n    */\n    x_hat = solvelin::svd::bdc(A, b);  \n    if(print) std::cout << \"x_hat svd::bdc \\n\" << x_hat << std::endl; \n    \n    x_hat = solvelin::svd::jacobi(A, b);    \n    if(print) std::cout << \"x_hat svd::jacobi \\n\" << x_hat << std::endl;    \n}\n\nTEST_CASE(\"Dynamic\") {\n\n    Eigen::MatrixXd A(3,3);\n    Eigen::VectorXd b(3);\n    Eigen::VectorXd x(3);\n    A << 1,2,3,  4,5,6,  7,8,10;  \n    b << 3, 3, 4;\n    x << -2, 1, 1;   \n    \n    if(print) std::cout << \"Dynamic matrix\" << std::endl;\n    f(A, b, x, false);\n}\n\nTEST_CASE(\"Version\") {\n    static_assert(std::string_view(NON_LIN_OPTIM_VERSION) == std::string_view(\"1.0\"));\n    CHECK(std::string(NON_LIN_OPTIM_VERSION) == std::string(\"1.0\"));\n}\n", "meta": {"hexsha": "bb9a95c2d3d4e9c000e915af2b1a3fb586624569", "size": 5274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/solvelin.cpp", "max_stars_repo_name": "lcit/non_lin_optim", "max_stars_repo_head_hexsha": "5c9d54a6d9692171fab889c0ad7f25c7a6aa22d7", "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": "test/src/solvelin.cpp", "max_issues_repo_name": "lcit/non_lin_optim", "max_issues_repo_head_hexsha": "5c9d54a6d9692171fab889c0ad7f25c7a6aa22d7", "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": "test/src/solvelin.cpp", "max_forks_repo_name": "lcit/non_lin_optim", "max_forks_repo_head_hexsha": "5c9d54a6d9692171fab889c0ad7f25c7a6aa22d7", "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": 36.3724137931, "max_line_length": 107, "alphanum_fraction": 0.5716723549, "num_tokens": 1873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6911408069129996}}
{"text": "/*\n utils.cxx\n\n Copyright (c) 2018 Guy Skinner\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory\n or http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include <boost/range/numeric.hpp>\n#include <cmath>\n\n#include \"utils.hxx\"\n\ndouble det3(ublas::matrix<double> a) {\n  /* Fast Determinant of 3x3 Matrix */\n  double det = a(0,0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1))\n             - a(0,1)*(a(1,0)*a(2,2) - a(1,2)*a(2,0))\n             + a(0,2)*(a(1,0)*a(2,1) - a(1,1)*a(2,0));\n  return det;\n}\n\nublas::vector<double> cross3(ublas::vector<double> a,\n                             ublas::vector<double> b) {\n\n  /* Cross Product for Three-Dimensional Vectors */\n  if (a.size() != 3 or b.size() != 3) {\n    std::cout << \"Exit(1): Vector dimensions not compatible for cross product\\n\";\n    exit(1);\n  }\n  ublas::vector<double> c(3);\n  c(0) = a(1)*b(2) - a(2)*b(1);\n  c(1) = a(2)*b(0) - a(0)*b(2);\n  c(2) = a(0)*b(1) - a(1)*b(0);\n  return c;\n}\n\nublas::matrix<double> inv3(ublas::matrix<double> a) {\n\n  /* Matrix Inversion for Three-Dimensional Vectors */\n  ublas::matrix<double> ia(a.size1(),a.size2());\n  double det = det3(a);\n  \n  ia(0,0) = a(1,1)*a(2,2) - a(1,2)*a(2,1);\n  ia(0,1) = a(0,2)*a(2,1) - a(0,1)*a(2,2);\n  ia(0,2) = a(0,1)*a(1,2) - a(0,2)*a(1,1);\n  \n  ia(1,0) = a(1,2)*a(2,0) - a(1,0)*a(2,2);\n  ia(1,1) = a(0,0)*a(2,2) - a(0,2)*a(2,0);\n  ia(1,2) = a(0,2)*a(1,0) - a(0,0)*a(1,2);\n  \n  ia(2,0) = a(1,0)*a(2,1) - a(1,1)*a(2,0);\n  ia(2,1) = a(0,1)*a(2,0) - a(0,0)*a(2,1);\n  ia(2,2) = a(0,0)*a(1,1) - a(1,0)*a(0,1);\n  \n  return ia/det;\n}\n\nlong linear_search(const std::vector<double>& vec,\n\t\t   double a,\n\t\t   double tol) {\n\n  for (long i = 0; i < vec.size(); i++) {\n    double value = fabs(vec[i] - a);\n    if (value < tol) {\n      return i;\n    }\n  }\n  \n  return vec.size();\n}\n\n//inline long product(ublas::vector<long> vec) {\n//  return boost::accumulate(vec,1,std::multiplies<long>());\n//}\n", "meta": {"hexsha": "e11c1e43a26dc100587e29592259f14e4a39f7a9", "size": 1972, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/utils.cxx", "max_stars_repo_name": "gcgs1/cxx.sqs", "max_stars_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_stars_repo_licenses": ["MIT"], "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.cxx", "max_issues_repo_name": "gcgs1/cxx.sqs", "max_issues_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_issues_repo_licenses": ["MIT"], "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.cxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["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.6103896104, "max_line_length": 81, "alphanum_fraction": 0.5385395538, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6911407975017393}}
{"text": "#include \"openbr/plugins/openbr_internal.h\"\n#include \"openbr/core/opencvutils.h\"\n#include \"openbr/core/eigenutils.h\"\n\n#include <opencv2/contrib/contrib.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace cv;\n\nnamespace br\n{\n\nclass ShapeAxisRatioTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        Mat indices;\n        findNonZero(src,indices);\n\n        dst.m() = Mat(1,1,CV_32FC1);\n\n        if (indices.total() > 0) {\n            MatrixXd data(indices.total(),2);\n\n            for (size_t i=0; i<indices.total(); i++) {\n                data(i,0) = indices.at<Point>(i).y;\n                data(i,1) = indices.at<Point>(i).x;\n            }\n\n            MatrixXd centered = data.rowwise() - data.colwise().mean();\n            MatrixXd cov = (centered.adjoint() * centered) / double(data.rows() - 1);\n\n            SelfAdjointEigenSolver<Eigen::MatrixXd> eSolver(cov);\n            MatrixXd D = eSolver.eigenvalues();\n\n            if (eSolver.info() == Success)\n                dst.m().at<float>(0,0) = D(0)/D(1);\n            else\n                dst.file.fte = true;\n        } else {\n            dst.file.fte = true;\n            qWarning(\"No mask content for %s.\",qPrintable(src.file.baseName()));\n        }\n    }\n};\n\nBR_REGISTER(Transform, ShapeAxisRatioTransform)\n\n} // namespace br\n\n#include \"imgproc/shapeaxisratio.moc\"\n", "meta": {"hexsha": "31d561d6b2dfe64693b7850ad1a2e3d5ac15abab", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_stars_repo_name": "kassemitani/openbr", "max_stars_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2016-01-27T04:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T20:45:16.000Z", "max_issues_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_issues_repo_name": "kassemitani/openbr", "max_issues_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-09T13:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-21T03:08:08.000Z", "max_forks_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_forks_repo_name": "kassemitani/openbr", "max_forks_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T13:07:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:19:18.000Z", "avg_line_length": 24.7068965517, "max_line_length": 85, "alphanum_fraction": 0.5764131193, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6911360898465019}}
{"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/epnp/epnp.hpp\"\n\n#include <Eigen/SVD>\n\n#include <cmath>\n#include <utility>\n\nnamespace isaac {\nnamespace pnp {\nnamespace epnp {\n\n// High-level function that implements the full EPnP pipeline\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  if (result == nullptr) {\n    return pnp::Status::kErrorBadInputParams;\n  }\n\n  // Make sure focal lengths in pixels are non-zero.\n  // There is no restriction on the principal point location.\n  if (focal_u == 0 || focal_v == 0) {\n    return pnp::Status::kErrorBadInputParams;\n  }\n\n  // At least 6 2D-3D point correspondences are required currently.\n  // TODO: extend to 5 and 4 (requires complicated relinearization)\n  if (points2.cols() != points3.cols() || points3.cols() < 6) {\n    return pnp::Status::kErrorBadNumInputPoints;\n  }\n\n  // Compute control points in world coordinates. They represent a chosen 3D basis.\n  constexpr double tol = 1e-3;\n  result->ctl_points_world = ChooseBasis(points3, tol);\n\n  // The dimensionality of the point cloud is the number of control points minus one because\n  // the first control point is always the centroid.\n  // Except when zero input points passed to ChooseBasis().\n  result->input_dims = result->ctl_points_world.cols();\n  if (result->input_dims) {\n    result->input_dims--;\n  }\n\n  // Only planar and 3D input point cloud shapes are useful for camera pose estimation.\n  if (result->input_dims < 2 || result->input_dims > 3) {\n    return pnp::Status::kErrorDegenerateGeom;\n  }\n\n  // Compute barycentric coordinates of all input 3D points with respect to chosen basis.\n  result->bary_coeffs = ComputeBaryCoords(points3, result->ctl_points_world);\n  if (result->bary_coeffs.cols() == 0) {\n    return pnp::Status::kErrorDegenerateGeom;\n  }\n\n  // Calculate space of the control point camera coordinates such that all\n  // projection constraints are approximately satisified.\n  if (!SolveProjConstraints(focal_u, focal_v, principal_u, principal_v, result->bary_coeffs,\n                            points2, &result->proj_coeffs, &result->solution_basis,\n                            &result->singular_values)) {\n    return pnp::Status::kErrorDegenerateGeom;\n  }\n\n  // Precompute distances between control points in the world frame.\n  VectorXd ctl_distances = ComputeDistances(result->ctl_points_world);\n\n  // Construct calibration matrix needed for reprojections at residual calculation.\n  Matrix3d calib_matrix;\n  calib_matrix << focal_u, 0, principal_u, 0, focal_v, principal_v, 0, 0, 1;\n\n  // Given the solution basis, solve for control point camera coordinates.\n  // Solve for various possible dimensions of the solution space and retain\n  // the resulting pose that has the least reprojection error.\n  const int max_solution_dims = 3;  // Only 1,2,3 are supported\n  double min_rss_error = Inf;\n  result->rss_repr_errors = VectorXd::Constant(max_solution_dims, Inf);\n  for (int k = 0; k < max_solution_dims; k++) {\n    const int sol_dims = k + 1;\n\n    // Compute weights that describe the concrete solution in the solution space.\n    Vector4d weights = SolveControlPoints(result->solution_basis, sol_dims, ctl_distances);\n    if (weights == Vector4d::Zero()) {\n      continue;\n    }\n\n    // Calculate control points in camera frame given the weights and the base vectors.\n    Matrix3Xd ctl_points_cam = ReshapeToMatrix3xN(result->solution_basis * weights);\n\n    // Compute rigid-body transform between control points in world and in camera frame.\n    // The resulting transformation is the sought camera pose.\n    Matrix3d rotation;\n    Vector3d translation;\n    if (!pnp::RegisterPointsEucl(result->ctl_points_world, ctl_points_cam, &rotation,\n                                 &translation)) {\n      continue;\n    }\n\n    // Compute squared reprojection errors of the input points, given the computed camera pose.\n    VectorXd repr_errors = pnp::ColwiseSquaredNorms(\n        points2 - pnp::EuclideanFromHomogeneous(calib_matrix *\n                                                ((rotation * points3).colwise() + translation)));\n\n    // Calculate reprojection Residual Sum of Squares (RSS).\n    double rss_error = repr_errors.sum();\n    result->rss_repr_errors(k) = rss_error;\n\n    // Keep the best solution in terms of reprojection RSS.\n    if (rss_error < min_rss_error) {\n      min_rss_error = rss_error;\n      result->ctl_points_cam = ctl_points_cam;\n      result->rotation = rotation;\n      result->translation = translation;\n      result->solution_dims = sol_dims;\n    }\n  }\n\n  // Solution could not be found with any dimensionality of the solution space.\n  if (min_rss_error == Inf) {\n    return pnp::Status::kErrorDegenerateGeom;\n  }\n\n  return pnp::Status::kSuccess;\n}\n\n// Choose a suitable 3D basis to represent the input 3D points in (via barycentric coordinates).\n// Principal Component Analysis of the 3D point cloud.\nMatrix3Xd ChooseBasis(const Matrix3Xd& points3, double tol) {\n  // The output basis will be represented by a small set of 3D control points (up to 4).\n  Matrix3Xd ctl_points;\n  ctl_points.resize(3, 0);\n\n  // At least 1 input point is required for further calculations to make sense.\n  const int num_points = points3.cols();\n  if (num_points < 1) {\n    return ctl_points;\n  }\n\n  // Calculate centroid of the point cloud - requires at least 1 point.\n  Vector3d centroid = points3.rowwise().sum() / num_points;\n\n  // Center the point cloud - requires at least 1 point\n  Matrix3Xd centered_points3 = points3;\n  for (int i = 0; i < num_points; i++) {\n    centered_points3.col(i) -= centroid;\n  }\n\n  // Compute principal components.\n  // Singular values are sorted in decreasing order.\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd;\n  svd.compute(centered_points3, Eigen::ComputeFullU | Eigen::ComputeThinV);\n  const VectorXd& singular_values = svd.singularValues();\n  const MatrixXd& principal_directions = svd.matrixU();\n\n  // Determine the number of non-vanishing principal components given a tolerance.\n  int dims = 0;\n  for (int i = 0; i < singular_values.rows(); i++) {\n    if (singular_values(i) > tol) {\n      dims++;\n    }\n  }\n\n  // The output matrix is always of size 3-by-(dims+1) with the first column being the centroid\n  // of the input point cloud.\n  ctl_points = Matrix3Xd::Zero(3, dims + 1);\n  ctl_points.col(0) = centroid;\n\n  // Scale the other control points with respect to the centroid along the principal directions\n  // such that their distance from the centroid equals the square root of the point variance.\n  // This is only done for non-vanishing principal directions.\n  const double factor = 1.0 / std::sqrt(static_cast<double>(num_points));\n  for (int i = 0; i < dims; i++) {\n    ctl_points.col(i + 1) = principal_directions.col(i) * factor * singular_values(i) + centroid;\n  }\n\n  return ctl_points;\n}\n\n// Compute barycentric coords of points with respect to a basis defined by 3 or 4 control points.\n// Solves the linear problem A*X = B for X where:\n// B is the 4xN matrix of homogeneous 3D points (3xN matrix points3 extended by a row of 1's)\n// A is the 4x3 or 4x4 homogenenous matrix of control point coordinates,\n// X is the 3xN or 4xN matrix of barycentric coordinates.\n// Since the last columns of A and B are all 1's, the column sums of X are 1.\nMatrixXd ComputeBaryCoords(const Matrix3Xd& points3, const Matrix3Xd& ctl_points) {\n  MatrixXd bary_coords;\n  bary_coords.resize(ctl_points.cols(), 0);\n  if (points3.cols() && (ctl_points.cols() == 3 || ctl_points.cols() == 4)) {\n    Matrix4Xd basis = pnp::HomogeneousFromEuclidean(ctl_points);\n\n    // Solve the problem A*X = B\n    bary_coords = basis.householderQr().solve(pnp::HomogeneousFromEuclidean(points3));\n  }\n  return bary_coords;\n}\n\n// Solve the projection equations via Singular-Value Decomposition and\n// find the solution space of the control point camera coordinates.\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* singular_values) {\n  if (proj_coeffs == nullptr || sol_basis == nullptr || singular_values == nullptr) {\n    return false;\n  }\n\n  proj_coeffs->resize(0, 0);\n\n  // At least 6 input points are required, each generating 2 equations.\n  int num_points = points2.cols();\n  if (num_points < 6) {\n    return false;\n  }\n  if (bary_coords.cols() != num_points) {\n    return false;\n  }\n\n  // Focal lengths should be non-zero.\n  if (focal_u == 0 || focal_v == 0) {\n    return false;\n  }\n\n  // Shorthands to make it easier to visually verify projection coefficients below.\n  const double fu = focal_u;\n  const double fv = focal_v;\n  const double uc = principal_u;\n  const double vc = principal_v;\n\n  // Non-planar case with 4 control points (12 unknowns)\n  if (bary_coords.rows() == 4) {\n    // Construct the 2Nx12 coefficient matrix\n    proj_coeffs->resize(2 * num_points, 12);\n    for (int i = 0; i < num_points; i++) {\n      // Shorthands to make it easier to check coefficient matrix\n      const double u = points2(0, i);\n      const double v = points2(1, i);\n      const double b1 = bary_coords(0, i);\n      const double b2 = bary_coords(1, i);\n      const double b3 = bary_coords(2, i);\n      const double b4 = bary_coords(3, i);\n      proj_coeffs->row(2 * i + 0) << b1 * fu, 0, b1 * (uc - u), b2 * fu, 0, b2 * (uc - u), b3 * fu,\n          0, b3 * (uc - u), b4 * fu, 0, b4 * (uc - u);\n      proj_coeffs->row(2 * i + 1) << 0, b1 * fv, b1 * (vc - v), 0, b2 * fv, b2 * (vc - v), 0,\n          b3 * fv, b3 * (vc - v), 0, b4 * fv, b4 * (vc - v);\n    }\n\n    // Planar case with 3 control points (9 unknowns)\n  } else if (bary_coords.rows() == 3) {\n    // Construct the 2Nx9 coefficient matrix\n    proj_coeffs->resize(2 * num_points, 9);\n    for (int i = 0; i < num_points; i++) {\n      // Shorthands to make it easier to check coefficient matrix\n      const double u = points2(0, i);\n      const double v = points2(1, i);\n      const double b1 = bary_coords(0, i);\n      const double b2 = bary_coords(1, i);\n      const double b3 = bary_coords(2, i);\n      proj_coeffs->row(2 * i + 0) << b1 * fu, 0, b1 * (uc - u), b2 * fu, 0, b2 * (uc - u), b3 * fu,\n          0, b3 * (uc - u);\n      proj_coeffs->row(2 * i + 1) << 0, b1 * fv, b1 * (vc - v), 0, b2 * fv, b2 * (vc - v), 0,\n          b3 * fv, b3 * (vc - v);\n    }\n\n    // Cases that are not solved with the current implementation.\n  } else {\n    return false;\n  }\n\n  // Solve the homogeneous linear problem by SVD\n  // Matrix V is 9x9 (planar case) or 12x12 (non-planar case)\n  // There are 9 (planar case) or 12 singular values  (non-planar case)\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd;\n  svd.compute(*proj_coeffs, Eigen::ComputeThinU | Eigen::ComputeFullV);\n  *singular_values = svd.singularValues();\n  const MatrixXd& singular_vectors = svd.matrixV();\n\n  // Output the last 4 columns of V in reverse order\n  sol_basis->resize(singular_vectors.rows(), 4);\n  for (int i = 0; i < 4; i++) {\n    sol_basis->col(i) = singular_vectors.col(singular_vectors.cols() - i - 1);\n  }\n\n  // Put singular values in increasing order\n  for (int i = 0; i < singular_values->size() / 2; i++) {\n    std::swap((*singular_values)(i), (*singular_values)(singular_values->size() - 1 - i));\n  }\n\n  return true;\n}\n\n// Convert a solution vector of control point coordinates of length 3*C to a 3xC matrix for C=3,4\n// such that the input vector contains the elements of the output matrix column-wise.\nMatrix3Xd ReshapeToMatrix3xN(const VectorXd& vec) {\n  Matrix3Xd matrix;\n  if (vec.size() % 3) {\n    return matrix;  // return a 3x0 matrix\n  }\n  matrix.resize(3, vec.size() / 3);\n  for (int i = 0; i < matrix.cols(); i++) {\n    matrix.col(i) = vec.block(3 * i, 0, 3, 1);\n  }\n\n  return matrix;\n}\n\n// Project points directly given in camera coordinates to the image\nMatrix2Xd ProjectPoints(const Matrix3d& calib_matrix, const Matrix3Xd& points3) {\n  Matrix2Xd points2;\n  points2.resize(2, points3.cols());\n  for (int i = 0; i < points3.cols(); i++) {\n    Vector3d proj = calib_matrix * points3.col(i);\n    if (proj(2) == 0) {\n      // Avoids NaNs due to 0/0.\n      points2(0, i) = Inf;\n      points2(1, i) = Inf;\n    } else {\n      // Division by homogeneous coordinate.\n      points2(0, i) = proj(0) / proj(2);\n      points2(1, i) = proj(1) / proj(2);\n    }\n  }\n  return points2;\n}\n\n// Compute distances between all possible pairs (i,j) of input points (in matrix columns).\nVectorXd ComputeDistances(const MatrixXd& points) {\n  int num_points = points.cols();\n  if (num_points < 2) {\n    return VectorXd(0);\n  }\n\n  VectorXd distances(num_points * (num_points - 1) / 2);\n  int k = 0;\n  for (int i = 0; i < points.cols(); i++) {\n    for (int j = i + 1; j < points.cols(); j++) {\n      distances[k++] = (points.col(i) - points.col(j)).norm();\n    }\n  }\n\n  return distances;\n}\n\n// Compute the weights that correspond to a concrete solution for the control point camera\n// coordinates in the basis given as input.\nVector4d SolveControlPoints(const MatrixXd& sol_basis, int sol_dims, const VectorXd& distances) {\n  Vector4d weights = Vector4d::Zero();\n  if (sol_basis.cols() != 4) {\n    return weights;\n  }\n  if (sol_basis.rows() != 12 && sol_basis.rows() != 9) {\n    return weights;\n  }\n\n  // non-planar case\n  if (sol_basis.rows() == 12 && distances.size() != 6) {\n    return weights;\n  }\n\n  // planar case\n  if (sol_basis.rows() == 9 && distances.size() != 3) {\n    return weights;\n  }\n\n  // Planar and non-planar case for 1-dimensional solution space\n  if (sol_dims == 1) {\n    // Only use singular vector corresponding to the least singular value.\n    // Solution space is 1-dimensional -> only need to find a single global scale.\n\n    // Calculate the unscaled camera coordinates of the control points.\n    Matrix3Xd v = ReshapeToMatrix3xN(sol_basis.col(0));\n\n    // Calculate distances between the unscaled control points.\n    VectorXd distances_cam = ComputeDistances(v);\n\n    // Calculate the unknown scale from the distances between control points in the world frame\n    // and the corresponding distances in the camera frame.\n    double scale = distances.dot(distances_cam) / distances_cam.dot(distances_cam);\n\n    // Find sign of the scale such that a majority of control points are in front of the camera.\n    int num_points_behind = (v.row(2).array() < 0).count();\n    if (num_points_behind > 1) {\n      scale = -scale;\n    }\n\n    weights(0) = scale;\n\n    // Planar and non-planar for 2-dimensional solution space\n  } else if (sol_dims == 2) {\n    // Reshape the two basis vectors of the solution space into two 3xN matrices.\n    // The sought matrix ctl_points_cam is a linear combination of these matrices.\n    // ctl_points_cam = w1*v1 + w2*v2, where the weights w1 and w2 are still unknown.\n    Matrix3Xd v1 = ReshapeToMatrix3xN(sol_basis.col(0));\n    Matrix3Xd v2 = ReshapeToMatrix3xN(sol_basis.col(1));\n\n    // Looking for the linear combination preserving the distances between control points.\n    // This is a non-linear problem in the linear combination weights (w1,w2).\n    // Strategy:\n    //   (Step1) Solve for (w11,w22,w12) = (w1*w1, w2*w2, w1*w2) (linearized problem)\n    //   (Step2) Extract (w1,w2) from (w11,w22,w12).\n    // Both steps are over-determined problems.\n\n    // Construct coefficient matrix of linearized problem (see Eq.13 in the paper).\n    // This matrix is 6x4 in the non-planar case.\n    const int num_points = v1.cols();\n    const int num_equations = num_points * (num_points - 1) / 2;\n    int k = 0;\n    MatrixXd coeff_matrix(num_equations, 3);\n    for (int i = 0; i < num_points; i++) {\n      for (int j = i + 1; j < num_points; j++) {\n        Vector3d d1 = v1.col(i) - v1.col(j);\n        Vector3d d2 = v2.col(i) - v2.col(j);\n        coeff_matrix.row(k++) << d1.dot(d1), d2.dot(d2), 2 * d1.dot(d2);\n      }\n    }\n\n    // Step1: Compute least squares solution to the linearized problem.\n    VectorXd squared_distances = distances.cwiseProduct(distances);\n    VectorXd lin_sol =\n        coeff_matrix.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(squared_distances);\n\n    // Solution of the linearized problem.\n    const double w11 = lin_sol(0);\n    const double w22 = lin_sol(1);\n    const double w12 = lin_sol(2);\n\n    // Step2: Calculate weights w1 and w2 (denoted beta_i in the EPnP paper)\n    // from the non-linear constraints (w11,w22,w12) = (w1*w1, w2*w2, w1*w2).\n    // There are always two solutions, (w1,w2) and (-w1,-w2) -> sign is solved further below.\n    // Over-constrained quadratic problem - least-squares solution has no simple closed form.\n    // Empirical tests show that solution order largely affects pose accuracy.\n    // Strategy: we exactly match the larger magnitude wij and hope for less overall alg. error.\n    double w1, w2;\n    w1 = w2 = 0;\n    if (w11 >= w22 && w11 > 0) {\n      w1 = std::sqrt(w11);\n      if (w22 > std::abs(w12)) {\n        w2 = std::sqrt(w22);\n      } else {\n        w2 = w12 / w1;\n      }\n    } else if (w11 <= w22 && w22 > 0) {\n      w2 = std::sqrt(w22);\n      if (w11 > std::abs(w12)) {\n        w1 = std::sqrt(w11);\n      } else {\n        w1 = w12 / w2;\n      }\n    }\n\n    // There are always two solutions: (w1,w2) and (-w1,-w2) but\n    // one corresponds to control points behind the camera.\n    // Find sign such that a majority all control points are in front of the camera.\n    VectorXd ctl_point_depths = w1 * v1.row(2) + w2 * v2.row(2);\n    int num_points_behind = (ctl_point_depths.array() < 0).count();\n    if (num_points_behind > int{num_points / 2}) {\n      weights << -w1, -w2, 0, 0;\n    } else {\n      weights << w1, w2, 0, 0;\n    }\n\n    // Non-planar case for 2-dimensional solution space\n  } else if (sol_dims == 3 && sol_basis.rows() == 12) {\n    // Reshape the 3 basis vectors of the solution space into three 3xN matrices.\n    // The sought matrix ctl_points_cam is a linear combination of these matrices.\n    // ctl_points_cam = w1*v1 + w2*v2 + w3*v3, where the weights (w1,w2,w3) are still unknown.\n    Matrix3Xd v1 = ReshapeToMatrix3xN(sol_basis.col(0));\n    Matrix3Xd v2 = ReshapeToMatrix3xN(sol_basis.col(1));\n    Matrix3Xd v3 = ReshapeToMatrix3xN(sol_basis.col(2));\n\n    // Looking for the linear combination preserving the distances between control points.\n    // This is a non-linear problem in the linear combination weights (w1,w2,w3).\n    // Strategy:\n    //   (Step1) Solve for (w11,w22,w33,w12,w13,w23) = (w1*w1, w2*w2, w3*w3, w1*w2, w1*w3, w2*w3)\n    //           (linearized problem).\n    //   (Step2) Extract (w1,w2,w3) from (w11,w22,w33,w12,w13,w23).\n\n    // Step1: Construct coefficient matrix of linearized problem (Case N=3 in the paper).\n    // This matrix is 6x6 in the non-planar case.\n    const int num_points = v1.cols();\n    const int num_equations = num_points * (num_points - 1) / 2;\n    int k = 0;\n    MatrixXd coeff_matrix(num_equations, 6);\n    for (int i = 0; i < num_points; i++) {\n      for (int j = i + 1; j < num_points; j++) {\n        Vector3d d1 = v1.col(i) - v1.col(j);\n        Vector3d d2 = v2.col(i) - v2.col(j);\n        Vector3d d3 = v3.col(i) - v3.col(j);\n        coeff_matrix.row(k++) << d1.dot(d1), d2.dot(d2), d3.dot(d3), 2 * d1.dot(d2), 2 * d1.dot(d3),\n            2 * d2.dot(d3);\n      }\n    }\n\n    // Step1: Compute least squares solution to the linearized problem.\n    VectorXd squared_distances = distances.cwiseProduct(distances);\n    VectorXd lin_sol =\n        coeff_matrix.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(squared_distances);\n\n    // Solution of the linearized problem.\n    const double w11 = lin_sol(0);\n    const double w22 = lin_sol(1);\n    const double w33 = lin_sol(2);\n    const double w12 = lin_sol(3);\n    const double w13 = lin_sol(4);\n    const double w23 = lin_sol(5);\n\n    // Calculate weights w1, w2, w3 from the non-linear constraints\n    // (w11, w22, w33, w12, w13, w23) = (w1*w1, w2*w2, w3*w3, w1*w2, w1*w3, w2*w3).\n    // There are always two solutions (w1,w2,w3) and (-w1,-w2,-w3) -> sign solved further below.\n    // Over-constrained quadratic problem - leats-squares solution has no simple closed form.\n    // Empirical tests show that solution order largely affects pose accuracy.\n    // Strategy: we exactly match the larger magnitude wij and hope for less overall alg. error.\n    double w1 = 0, w2 = 0, w3 = 0;\n    if (w11 > w22 && w11 > w33 && w11 > 0) {\n      w1 = std::sqrt(w11);\n      if (w22 > std::abs(w12)) {\n        w2 = std::sqrt(w22);\n      } else {\n        w2 = w12 / w1;\n      }\n      if (w33 > std::abs(w13)) {\n        w3 = std::sqrt(w33);\n      } else {\n        w3 = w13 / w1;\n      }\n    } else if (w22 > w11 && w22 > w33 && w22 > 0) {\n      w2 = std::sqrt(w22);\n      if (w11 > std::abs(w12)) {\n        w1 = std::sqrt(w11);\n      } else {\n        w1 = w12 / w2;\n      }\n      if (w33 > std::abs(w23)) {\n        w3 = std::sqrt(w33);\n      } else {\n        w3 = w23 / w2;\n      }\n    } else if (w33 > w11 && w33 > w22 && w33 > 0) {\n      w3 = std::sqrt(w33);\n      if (w11 > std::abs(w13)) {\n        w1 = std::sqrt(w11);\n      } else {\n        w1 = w13 / w3;\n      }\n      if (w22 > std::abs(w23)) {\n        w2 = std::sqrt(w22);\n      } else {\n        w2 = w23 / w3;\n      }\n    }\n\n    // There are always two solutions: (w1,w2,w3) and (-w1,-w2,-w3) but\n    // one corresponds to control points behind the camera.\n    // Find sign such that a majority all control points are in front of the camera.\n    VectorXd ctl_point_depths = w1 * v1.row(2) + w2 * v2.row(2) + w3 * v3.row(2);\n    int num_points_behind = (ctl_point_depths.array() < 0).count();\n    if (num_points_behind > int{num_points / 2}) {\n      weights << -w1, -w2, -w3, 0;\n    } else {\n      weights << w1, w2, w3, 0;\n    }\n  }\n\n  // TODO: planar N=3 case using relinearization\n  // TODO: non-planar N=4 (affine camera) case using relinearization\n  // planar N=4 case is underconstrained = ambiguous (3 equations but 4 unknowns)\n\n  return weights;\n}\n\n}  // namespace epnp\n}  // namespace pnp\n}  // namespace isaac\n", "meta": {"hexsha": "ac59b3cc1c92f0c6c5f537c0c8793d2e99a082a6", "size": 22583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/epnp/epnp.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/epnp/epnp.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/epnp/epnp.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": 38.9362068966, "max_line_length": 100, "alphanum_fraction": 0.6520834256, "num_tokens": 6480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6911360858061321}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\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\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n#include <boost/multi_array.hpp>\n\n#include <limits>\n#include <vector>\n#include <cmath>\n\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/io/matrixTextFileReader.h\"\n\n#include \"tudat/math/interpolators/linearInterpolator.h\"\n#include \"tudat/math/interpolators/multiLinearInterpolator.h\"\n#include \"tudat/io/basicInputOutput.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_multi_linear_interpolation )\n\n// Test 1: Comparison to MATLAB solution of the example provided in matlab's interp2 function\n// documentation.\nBOOST_AUTO_TEST_CASE( test2Dimensions )\n{\n    // Create independent variable vector.\n    std::vector< std::vector< double > > independentValues;\n    \n    // Resize independent variable vector to two dimensions and assign values.\n    independentValues.resize( 2 );\n    for ( int i = 0; i < 5; i++ )\n    {\n        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );\n    }\n    \n    for ( int i = 0; i < 3; i++ )\n    {\n        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );\n    }\n    \n    // Create two-dimensional array for dependent values.\n    boost::multi_array< double, 2 > dependentValues;\n    dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n    \n    dependentValues[ 0 ][ 0 ] = 150.697;\n    dependentValues[ 0 ][ 1 ] = 199.592;\n    dependentValues[ 0 ][ 2 ] = 187.625;\n    dependentValues[ 1 ][ 0 ] = 179.323;\n    dependentValues[ 1 ][ 1 ] = 195.072;\n    dependentValues[ 1 ][ 2 ] = 250.287;\n    dependentValues[ 2 ][ 0 ] = 203.212;\n    dependentValues[ 2 ][ 1 ] = 179.092;\n    dependentValues[ 2 ][ 2 ] = 322.767;\n    dependentValues[ 3 ][ 0 ] = 226.505;\n    dependentValues[ 3 ][ 1 ] = 153.706;\n    dependentValues[ 3 ][ 2 ] = 426.730;\n    dependentValues[ 4 ][ 0 ] = 249.633;\n    dependentValues[ 4 ][ 1 ] = 120.281;\n    dependentValues[ 4 ][ 2 ] = 598.243;\n    \n    // Initialize interpolator.\n    interpolators::MultiLinearInterpolator< double, double, 2 > twoDimensionalInterpolator(\n                independentValues, dependentValues );\n    \n    // Set interpolation target's independent values.\n    std::vector< double > targetValue( 2 );\n    targetValue[ 0 ] = 1975.0;\n    targetValue[ 1 ] = 15.0;\n    \n    // Declare interpolated dependent variable value and execute interpolation.\n    const double interpolationResult = twoDimensionalInterpolator.interpolate( targetValue );\n    \n    // Check if equal to MATLAB result up to machine precision.\n    BOOST_CHECK_CLOSE_FRACTION( 190.62875, interpolationResult,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n// Test 2: 4-dimensional test. Comparison to matlab interpolated solution of analytical function.\nBOOST_AUTO_TEST_CASE( test4Dimensions )\n{\n    // Create independent variable vector.\n    std::vector< std::vector< double > > independentValues;\n    \n    // Resize independent variable vector to two dimensions and assign values.\n    independentValues.resize( 4 );\n    for ( int i = 0; i < 11; i++ )\n    {\n        independentValues[ 0 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );\n        independentValues[ 1 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );\n        independentValues[ 2 ].push_back( -1.0 + static_cast< double >( i ) * 0.2 );\n    }\n    \n    for ( int i = 0; i < 6; i++ )\n    {\n        independentValues[ 3 ].push_back( static_cast< double >( i ) * 2.0 );\n    }\n    \n    // Create four-dimensional array for dependent values based on analytical function\n    // f = t*e^(-x^2 - y^2 - z^2 ).\n    boost::multi_array< double, 4 > dependentValues;\n    dependentValues.resize( boost::extents[ 11 ][ 11 ][ 11 ][ 6 ] );\n    \n    for ( int i = 0; i < 11; i++ )\n    {\n        for ( int j = 0; j < 11; j++ )\n        {\n            for ( int k = 0; k < 11; k++ )\n            {\n                for ( int l = 0; l < 6; l++ )\n                {\n                    dependentValues[ i ][ j ][ k ][ l ] =\n                            independentValues[ 3 ][ l ] *\n                            std::exp( -std::pow( independentValues[ 0 ][ i ], 2 ) -\n                            std::pow( independentValues[ 1 ][ j ], 2 ) -\n                            std::pow( independentValues[ 2 ][ k ], 2 ) );\n                }\n            }\n        }\n    }\n    \n    // Initialize interpolator.\n    interpolators::MultiLinearInterpolator< double, double, 4 > fourDimensionalInterpolator(\n                independentValues, dependentValues );\n    \n    // Set interpolation target's independent values.\n    std::vector< double > targetValue( 4 );\n    targetValue[ 0 ] = -1.0;\n    targetValue[ 1 ] = 0.1;\n    targetValue[ 2 ] = 0.5;\n    targetValue[ 3 ] = 7.0;\n    \n    // Declare interpolated dependent variable value and execute interpolation.\n    const double interpolationResult = fourDimensionalInterpolator.interpolate( targetValue );\n    \n    // Check if equal to MATLAB result up to machine precision\n    BOOST_CHECK_CLOSE_FRACTION( 1.956391733957447, interpolationResult,\n                                std::numeric_limits< double >::epsilon( ) );\n}\n\n// Test 3: 2 dimensions, with independent variables out of range\nBOOST_AUTO_TEST_CASE( test2DimensionsBoundaryCase )\n{\n    using namespace tudat::interpolators;\n    \n    // Create independent variable vector.\n    std::vector< std::vector< double > > independentValues;\n    \n    // Resize independent variable vector to two dimensions and assign values.\n    independentValues.resize( 2 );\n    for ( int i = 0; i < 5; i++ )\n    {\n        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );\n    }\n    \n    for ( int i = 0; i < 3; i++ )\n    {\n        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );\n    }\n    \n    // Create two-dimensional array for dependent values.\n    boost::multi_array< double, 2 > dependentValues;\n    dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n    \n    dependentValues[ 0 ][ 0 ] = 150.697;\n    dependentValues[ 0 ][ 1 ] = 199.592;\n    dependentValues[ 0 ][ 2 ] = 187.625;\n    dependentValues[ 1 ][ 0 ] = 179.323;\n    dependentValues[ 1 ][ 1 ] = 195.072;\n    dependentValues[ 1 ][ 2 ] = 250.287;\n    dependentValues[ 2 ][ 0 ] = 203.212;\n    dependentValues[ 2 ][ 1 ] = 179.092;\n    dependentValues[ 2 ][ 2 ] = 322.767;\n    dependentValues[ 3 ][ 0 ] = 226.505;\n    dependentValues[ 3 ][ 1 ] = 153.706;\n    dependentValues[ 3 ][ 2 ] = 426.730;\n    dependentValues[ 4 ][ 0 ] = 249.633;\n    dependentValues[ 4 ][ 1 ] = 120.281;\n    dependentValues[ 4 ][ 2 ] = 598.243;\n    \n    // Set interpolation target's independent values.\n    std::vector< std::vector< double > > targetValue( 5 );\n    targetValue[ 0 ].resize( 2 );\n    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 0 ][ 1 ] = 15.0;\n    targetValue[ 1 ].resize( 2 );\n    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).back( ) + 10.0;\n    targetValue[ 1 ][ 1 ] = 15.0;\n    targetValue[ 2 ].resize( 2 );\n    targetValue[ 2 ][ 0 ] = 1975.0;\n    targetValue[ 2 ][ 1 ] = independentValues.at( 1 ).front( ) - 2.5;\n    targetValue[ 3 ].resize( 2 );\n    targetValue[ 3 ][ 0 ] = 1975.0;\n    targetValue[ 3 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;\n    targetValue[ 4 ].resize( 2 );\n    targetValue[ 4 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 4 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;\n\n    // Expected results\n    std::vector< double > boundaryResults( 5 ); // computed with MATLAB\n    boundaryResults[ 0 ] = 175.1445;\n    boundaryResults[ 1 ] = 184.957;\n    boundaryResults[ 2 ] = 214.8585;\n    boundaryResults[ 3 ] = 374.7485;\n    boundaryResults[ 4 ] = 187.625;\n    std::vector< double > extrapolationResults( 5 ); // computed with MATLAB\n    extrapolationResults[ 0 ] = 163.0915;\n    extrapolationResults[ 1 ] = 179.8085;\n    extrapolationResults[ 2 ] = 226.973375;\n    extrapolationResults[ 3 ] = 426.835875;\n    extrapolationResults[ 4 ] = 105.17575;\n    \n    // Loop over test cases and boundary handling methods.\n    bool exceptionIsCaught;\n    double interpolatedValue;\n    for( unsigned int i = 0; i < 7; i++ )\n    {\n        // Initialize interpolator.\n        MultiLinearInterpolator< double, double, 2 > twoDimensionalInterpolator(\n                    independentValues, dependentValues, huntingAlgorithm,\n                    static_cast< BoundaryInterpolationType >( i ) );\n\n        for ( unsigned int j = 0; j < 5; j++ )\n        {\n            if( static_cast< BoundaryInterpolationType >( i ) == throw_exception_at_boundary )\n            {\n                exceptionIsCaught = false;\n                try\n                {\n                    twoDimensionalInterpolator.interpolate( targetValue.at( j ) );\n                }\n                catch( std::runtime_error const& )\n                {\n                    exceptionIsCaught = true;\n                }\n                BOOST_CHECK_EQUAL( exceptionIsCaught, true );\n            }\n            else if( ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value ) ||\n                     ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value_with_warning ) )\n            {\n                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );\n                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, boundaryResults.at( j ), 1.0E-15 );\n            }\n            else if( ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary ) ||\n                     ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary_with_warning ) )\n            {\n                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );\n                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationResults.at( j ), 1.0E-15 );\n            }\n            else if( ( static_cast< BoundaryInterpolationType >( i ) == use_default_value ) ||\n                     ( static_cast< BoundaryInterpolationType >( i ) == use_default_value_with_warning ) )\n            {\n                interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( j ) );\n                BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0, 1.0E-15 );\n            }\n        }\n    }\n}\n\n// Test linear interpolation outside of independent variable range and compare with 1D linear interpolator\nBOOST_AUTO_TEST_CASE( test1DimensionBoundaryCase )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                tudat::paths::getTudatTestDataPath( ) +\n                \"/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< std::vector< double > > independentVariableValuesMulti;\n    std::vector< double > dependentVariableValues;\n    boost::multi_array< double, 1 > dependentVariableValuesMulti( boost::extents[ inputData.rows( ) ] );\n\n    for ( int i = 0; i < inputData.rows( ); i++ )\n    {\n        independentVariableValues.push_back( inputData( i, 0 ) );\n        dependentVariableValues.push_back( inputData( i, 1 ) );\n        dependentVariableValuesMulti[ i ] = inputData( i, 1 );\n    }\n    independentVariableValuesMulti.push_back( independentVariableValues );\n\n    // Create linear interpolator using hunting algorithm.\n    double valueOffset = 2.0;\n    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;\n    std::vector< double > valueBelowMinimumValueVector = { valueBelowMinimumValue };\n    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;\n    std::vector< double > valueAboveMaximumValueVector = { valueAboveMaximumValue };\n    double linearInterpolatedValue;\n    double multiLinearInterpolatedValue;\n\n    for ( unsigned int i = 1; i < 5; i++ )\n    {\n        // Initialize interpolatos.\n        LinearInterpolatorDouble linearInterpolator(\n                    independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                    static_cast< BoundaryInterpolationType >( i ) );\n        MultiLinearInterpolator< double, double, 1 > multiLinearInterpolator(\n                    independentVariableValuesMulti, dependentVariableValuesMulti, huntingAlgorithm,\n                    static_cast< BoundaryInterpolationType >( i ) );\n\n        if ( ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value ) ||\n             ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value_with_warning ) )\n        {\n            linearInterpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueBelowMinimumValueVector );\n            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );\n\n            linearInterpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueAboveMaximumValueVector );\n            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );\n\n        }\n        else if ( ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary ) ||\n                  ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary_with_warning ) )\n        {\n            linearInterpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueBelowMinimumValueVector );\n            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );\n\n            linearInterpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            multiLinearInterpolatedValue = multiLinearInterpolator.interpolate( valueAboveMaximumValueVector );\n            BOOST_CHECK_CLOSE_FRACTION( linearInterpolatedValue, multiLinearInterpolatedValue, 1.0E-15 );\n        }\n    }\n}\n\n// Test linear interpolation outside of independent variable range with default extrapolation value\nBOOST_AUTO_TEST_CASE( test2DimensionsDefaultExtrapolationCase )\n{\n    using namespace interpolators;\n\n    // Create independent variable vector.\n    std::vector< std::vector< double > > independentValues;\n\n    // Resize independent variable vector to two dimensions and assign values.\n    independentValues.resize( 2 );\n    for ( int i = 0; i < 5; i++ )\n    {\n        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );\n    }\n\n    for ( int i = 0; i < 3; i++ )\n    {\n        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );\n    }\n\n    // Create two-dimensional array for dependent values.\n    boost::multi_array< double, 2 > inputData;\n    inputData.resize( boost::extents[ 5 ][ 3 ] );\n\n    inputData[ 0 ][ 0 ] = 150.697;\n    inputData[ 0 ][ 1 ] = 199.592;\n    inputData[ 0 ][ 2 ] = 187.625;\n    inputData[ 1 ][ 0 ] = 179.323;\n    inputData[ 1 ][ 1 ] = 195.072;\n    inputData[ 1 ][ 2 ] = 250.287;\n    inputData[ 2 ][ 0 ] = 203.212;\n    inputData[ 2 ][ 1 ] = 179.092;\n    inputData[ 2 ][ 2 ] = 322.767;\n    inputData[ 3 ][ 0 ] = 226.505;\n    inputData[ 3 ][ 1 ] = 153.706;\n    inputData[ 3 ][ 2 ] = 426.730;\n    inputData[ 4 ][ 0 ] = 249.633;\n    inputData[ 4 ][ 1 ] = 120.281;\n    inputData[ 4 ][ 2 ] = 598.243;\n\n    // Set interpolation target's independent values.\n    std::vector< std::vector< double > > targetValue( 2 );\n    targetValue[ 0 ].resize( 2 );\n    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 0 ][ 1 ] = 15.0;\n    targetValue[ 1 ].resize( 2 );\n    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 1 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;\n\n    // Test with long double\n    {\n        // Put data in STL vectors.\n        boost::multi_array< long double, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                dependentValues[ i ][ j ] = static_cast< long double >( inputData[ i ][ j ] );\n            }\n        }\n        long double interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, long double, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Vector3d\n    {\n        // Put data in STL vectors.\n        boost::multi_array< Eigen::Vector3d, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                tempData[ 0 ] = inputData[ i ][ j ];\n                dependentValues[ i ][ j ] = tempData;\n            }\n        }\n        Eigen::Vector3d interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, Eigen::Vector3d, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Matrix3d\n    {\n        boost::multi_array< Eigen::Matrix3d, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                tempData( 0, 2 ) = inputData[ i ][ j ];\n                dependentValues[ i ][ j ] = tempData;\n            }\n        }\n        Eigen::Matrix3d interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, Eigen::Matrix3d, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );\n        }\n    }\n}\n\n// Test linear interpolation outside of independent variable range with extrapolation value given by user\nBOOST_AUTO_TEST_CASE( test2DimensionsUserExtrapolationCase )\n{\n    using namespace interpolators;\n\n    // Create independent variable vector.\n    std::vector< std::vector< double > > independentValues;\n\n    // Resize independent variable vector to two dimensions and assign values.\n    independentValues.resize( 2 );\n    for ( int i = 0; i < 5; i++ )\n    {\n        independentValues[ 0 ].push_back( 1950.0 + static_cast< double >( i ) * 10.0 );\n    }\n\n    for ( int i = 0; i < 3; i++ )\n    {\n        independentValues[ 1 ].push_back( 10.0 + static_cast< double >( i ) * 10.0 );\n    }\n\n    // Create two-dimensional array for dependent values.\n    boost::multi_array< double, 2 > inputData;\n    inputData.resize( boost::extents[ 5 ][ 3 ] );\n\n    inputData[ 0 ][ 0 ] = 150.697;\n    inputData[ 0 ][ 1 ] = 199.592;\n    inputData[ 0 ][ 2 ] = 187.625;\n    inputData[ 1 ][ 0 ] = 179.323;\n    inputData[ 1 ][ 1 ] = 195.072;\n    inputData[ 1 ][ 2 ] = 250.287;\n    inputData[ 2 ][ 0 ] = 203.212;\n    inputData[ 2 ][ 1 ] = 179.092;\n    inputData[ 2 ][ 2 ] = 322.767;\n    inputData[ 3 ][ 0 ] = 226.505;\n    inputData[ 3 ][ 1 ] = 153.706;\n    inputData[ 3 ][ 2 ] = 426.730;\n    inputData[ 4 ][ 0 ] = 249.633;\n    inputData[ 4 ][ 1 ] = 120.281;\n    inputData[ 4 ][ 2 ] = 598.243;\n\n    // Set interpolation target's independent values.\n    std::vector< std::vector< double > > targetValue( 2 );\n    targetValue[ 0 ].resize( 2 );\n    targetValue[ 0 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 0 ][ 1 ] = 15.0;\n    targetValue[ 1 ].resize( 2 );\n    targetValue[ 1 ][ 0 ] = independentValues.at( 0 ).front( ) - 10.0;\n    targetValue[ 1 ][ 1 ] = independentValues.at( 1 ).back( ) + 2.5;\n\n    // Test with long double\n    {\n        // Put data in STL vectors.\n        boost::multi_array< long double, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                dependentValues[ i ][ j ] = static_cast< long double >( inputData[ i ][ j ] );\n            }\n        }\n        long double interpolatedValue;\n        long double extrapolationValue = 1.0L;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, long double, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Vector3d\n    {\n        // Put data in STL vectors.\n        boost::multi_array< Eigen::Vector3d, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                tempData[ 0 ] = inputData[ i ][ j ];\n                dependentValues[ i ][ j ] = tempData;\n            }\n        }\n        Eigen::Vector3d interpolatedValue;\n        Eigen::Vector3d extrapolationValue;\n        extrapolationValue[ 0 ] = 1.5;\n        extrapolationValue[ 1 ] = -3;\n        extrapolationValue[ 2 ] = 0;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, Eigen::Vector3d, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Matrix3d\n    {\n        boost::multi_array< Eigen::Matrix3d, 2 > dependentValues;\n        dependentValues.resize( boost::extents[ 5 ][ 3 ] );\n        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );\n        for ( size_t i = 0; i < inputData.shape( )[ 0 ]; i++ )\n        {\n            for ( size_t j = 0; j < inputData.shape( )[ 1 ]; j++ )\n            {\n                tempData( 0, 2 ) = inputData[ i ][ j ];\n                dependentValues[ i ][ j ] = tempData;\n            }\n        }\n        Eigen::Matrix3d interpolatedValue;\n        Eigen::Matrix3d extrapolationValue = Eigen::Matrix3d::Random( );\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            MultiLinearInterpolator< double, Eigen::Matrix3d, 2 > twoDimensionalInterpolator(\n                        independentValues, dependentValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 0 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n\n            interpolatedValue = twoDimensionalInterpolator.interpolate( targetValue.at( 1 ) );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "4ae3442f2f89a0eb7b9695472a66074e79c45f63", "size": 26088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/interpolators/unitTestMultiLinearInterpolator.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "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": "tests/src/math/interpolators/unitTestMultiLinearInterpolator.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/interpolators/unitTestMultiLinearInterpolator.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "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": 41.6741214058, "max_line_length": 112, "alphanum_fraction": 0.6068690586, "num_tokens": 6833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6911360789721896}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <stan/math/prim/arr/fun/log_sum_exp.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nvoid test_log_sum_exp(double a, double b) {\n  using std::log;\n  using std::exp;\n  using stan::math::log_sum_exp;\n  EXPECT_FLOAT_EQ(log(exp(a) + exp(b)),\n                  log_sum_exp(a,b));\n}\n\nvoid test_log_sum_exp(const std::vector<double>& as) {\n  using std::log;\n  using std::exp;\n  using stan::math::log_sum_exp;\n  double sum_exp = 0.0;\n  for (size_t n = 0; n < as.size(); ++n)\n    sum_exp += exp(as[n]);\n  EXPECT_FLOAT_EQ(log(sum_exp),\n                  log_sum_exp(as));\n}\n\nTEST(MathFunctions, log_sum_exp) {\n  using stan::math::log_sum_exp;\n  std::vector<double> as;\n  test_log_sum_exp(as);\n  as.push_back(0.0);\n  test_log_sum_exp(as);\n  as.push_back(1.0);\n  test_log_sum_exp(as);\n  as.push_back(-1.0);\n  test_log_sum_exp(as);\n  as.push_back(-10000.0);\n  test_log_sum_exp(as);\n  \n  as.push_back(10000.0);\n  EXPECT_FLOAT_EQ(10000.0, log_sum_exp(as));\n}\n\nTEST(MathFunctions, log_sum_exp_2) {\n  using stan::math::log_sum_exp;\n  test_log_sum_exp(1.0,2.0);\n  test_log_sum_exp(1.0,1.0);\n  test_log_sum_exp(3.0,2.0);\n  test_log_sum_exp(-20.0,12);\n  test_log_sum_exp(-20.0,12);\n\n  // exp(10000.0) overflows\n  EXPECT_FLOAT_EQ(10000.0,log_sum_exp(10000.0,0.0));\n  EXPECT_FLOAT_EQ(0.0,log_sum_exp(-10000.0,0.0));\n}\n\nTEST(MathFunctions, log_sum_exp_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log_sum_exp(1.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log_sum_exp(nan, 1.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log_sum_exp(nan, nan));\n}\n", "meta": {"hexsha": "d742321dbc93ee94790ac97112493fcb9197474b", "size": 1763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_sum_exp_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3134328358, "max_line_length": 56, "alphanum_fraction": 0.6687464549, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.690832095969552}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date nov-20\n * @license GPLv3, see 'LICENSE' file\n *\n * g++ -std=c++20 -I.. -o cov cov.cpp\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\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, version 3 of the License.\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, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Cov1\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_equals, t_real, t_types)\n{\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\n\tstd::vector<t_vec> vecs{{\n\t\ttl2::create<t_vec>({1, 2, 3}),\n\t\ttl2::create<t_vec>({3, 2, 1}),\n\t\ttl2::create<t_vec>({5, -2, 0.5}),\n\t}};\n\n\tstd::vector<t_real> probs{{ 1., 1., 0.5 }};\n\n\tauto [cov, corr] = tl2::covariance<t_mat, t_vec>(vecs, &probs);\n\tstd::cout << \"cov  = \" << cov << std::endl;\n\tstd::cout << \"corr = \" << corr << std::endl;\n\n\t// comparing with: np.cov([[1,2,3], [3,2,1], [5,-2,0.5]], rowvar=False, aweights=[1,1,0.5], ddof=0)\n\tconst t_mat cov_cmp = tl2::create<t_mat>({\n\t\t 2.24, -1.92, -1.52,\n\t\t-1.92,  2.56,  0.96,\n\t\t-1.52,  0.96,  1.16\n\t});\n\tBOOST_TEST(tl2::equals(cov, cov_cmp, 1e-5));\n}\n", "meta": {"hexsha": "a76d524485ad24da87de2b59ecb23927eaad9ed5", "size": 2227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/cov.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/cov.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/cov.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 32.75, "max_line_length": 100, "alphanum_fraction": 0.6066457117, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6908320913755467}}
{"text": "/**\n * TSAI 1999 Hand-eye calibration\n * Emanuele Ruffaldi 2016\n *\n * Copyright Scuola Superiore Sant'Anna (2016) \n * Emanuele Ruffaldi, e.ruffaldi@sssup.it\n */\n#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <vector>\n\n\ntemplate <class T>\n using Vector3 = Eigen::Matrix<T,3,1>;\n\ntemplate <class T>\n using Matrix3 = Eigen::Matrix<T,3,3>;\n\ntemplate <class T>\n using Matrix4 = Eigen::Matrix<T,4,4>;\n\n\n/**\n * Computes Tsai calibration: four frames\n *\t R = robot root\n * \t E = robot end-effector\n *   C = camera\n *   M = marker\n *\n * The objective is EC\n * We move E wrt R and keep R and M fixed each other\n */\n\nfloat calibrationTsai(const std::vector<Eigen::Matrix4f> & cMm,\n                     const std::vector<Eigen::Matrix4f> & rMe,\n                     Eigen::Matrix4f &eMc, bool computeResidual = false);\n\ndouble calibrationTsai(const std::vector<Eigen::Matrix4d> & cMm,\n                     const std::vector<Eigen::Matrix4d> & rMe,\n                     Eigen::Matrix4d &eMc, bool computeResidual = false);\n\n/*\n * These are internal functions used for testing the Tsai\n * They mainly deal with the specific Tsai parametrization of the vector that is more robust to small values than the regular one\n */\ntemplate <class T>\nEigen::Matrix<T,3,1> paratsaiprime2paratsai(const Eigen::Matrix<T,3,1> & a);\ntemplate <class T>\nEigen::Matrix<T,3,1> paratsai2paratsaiprime(const Eigen::Matrix<T,3,1> & a);\ntemplate <class T>\nEigen::Matrix<T,3,3> paratsai2rot(const Eigen::Matrix<T,3,1> & a);\ntemplate <class T>\nEigen::Quaternion<T> paratsai2quat(const Eigen::Matrix<T,3,1> & a);\ntemplate <class T>\nEigen::Matrix<T,3,1> quat2paratsai(const Eigen::Quaternion<T> & q);\ntemplate <class T>\nT paratsaiprime2theta(const Eigen::Matrix<T,3,1> & x);\ntemplate <class T>\nT paratsai2theta(const Eigen::Matrix<T,3,1> & x);\n\n\n/// returns the skew of the vector\ntemplate <class T>\ninline Matrix3<T> skewtsai(const Vector3<T> & a)\n{\n  Matrix3<T> r;\n  r  << 0, -a(2), a(1),  a(2),0,-a(0),-a(1),a(0),0;\n  return r;\n}\n\n\ntemplate <class T>\nVector3<T> paratsaiprime2paratsai(const Vector3<T> & a)\n{\n    return 2*a/sqrt(1+a.squaredNorm()); // equation 14\n}\n\ntemplate <class T>\nVector3<T> paratsai2paratsaiprime(const Vector3<T> & a)\n{\n  return a/sqrt(4-a.squaredNorm());\n}\n\n/// converts the parametric in tsai form to rotation\n/// NO NEED OF TRIGONOMETRICS\n/// equation 10\ntemplate <class T>\nMatrix3<T> paratsai2rot(const Vector3<T> & a)\n{\n  T sn = a.squaredNorm();\n  T alpha = sqrt(4-sn);\n  return (1-sn/2)*Matrix3<T>::Identity() + 0.5*(a*a.transpose() + alpha * skewtsai(a));\n}\n\n/// converts the parametric in tsai form to rotation\n/// NO NEED OF TRIGONOMETRICS\n/// equation 9 modified NOT USED\ntemplate <class T>\nEigen::Quaternion<T> paratsai2quat(const Vector3<T> & a)\n{\n  double sinthetahalf = a.norm()/2; // 2 * sin(theta)/2 => sin(theta)/2\n  return Eigen::Quaternion<T>(sqrt(1-sinthetahalf*sinthetahalf),a.x()/2,a.y()/2,a.z()/2); // cos(theta/2)\n}\n\ntemplate <class T>\nT paratsai2theta(const Vector3<T> & x)\n{\n  return 2*asin(x.norm()/2); // eq. 9    \n}\n", "meta": {"hexsha": "e0f51d168be926af96e961ac854ad0c902ca553e", "size": 3054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tsai.hpp", "max_stars_repo_name": "eruffaldi/tsai_calib_eigen", "max_stars_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T03:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T07:15:11.000Z", "max_issues_repo_path": "tsai.hpp", "max_issues_repo_name": "eruffaldi/tsai_calib_eigen", "max_issues_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "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": "tsai.hpp", "max_forks_repo_name": "eruffaldi/tsai_calib_eigen", "max_forks_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-02T07:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T03:20:33.000Z", "avg_line_length": 27.2678571429, "max_line_length": 129, "alphanum_fraction": 0.6696136215, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6907862572904733}}
{"text": "// Catch includes\n#include \"catch.hpp\"\n\n// Eigen includes\n#include <Eigen/Core>\nusing namespace Eigen;\n\n// autodiff includes\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\nusing namespace autodiff;\nusing namespace autodiff::forward;\n\n#include <iostream>\n\ntemplate<typename T>\nauto approx(T&& expr) -> Approx\n{\n    const double zero = std::numeric_limits<double>::epsilon();\n    return Approx(val(std::forward<T>(expr))).margin(zero);\n}\n\nTEST_CASE(\"autodiff::dual tests\", \"[dual]\")\n{\n    dual x = 100;\n    dual y = 10;\n\n    SECTION(\"trivial tests\")\n    {\n        REQUIRE( x == 100 );\n        x += 1;\n        REQUIRE( x == 101 );\n        x -= 1;\n        REQUIRE( x == 100 );\n        x *= 2;\n        REQUIRE( x == 200 );\n        x /= 20;\n        REQUIRE( x == 10 );\n    }\n\n    SECTION(\"aliasing tests\")\n    {\n        x = 1; x = x + 3*x - 2*x + x;\n        REQUIRE( x == 3 );\n\n        x = 1; x += x + 3*x - 2*x + x;\n        REQUIRE( x == 4 );\n\n        x = 1; x -= x + 3*x - 2*x + x;\n        REQUIRE( x == -2 );\n\n        x = 1; x *= x + 3*x - 2*x + x;\n        REQUIRE( x == 3 );\n\n        x = 1; x /= x + x;\n        REQUIRE( x == 0.5 );\n    }\n\n    SECTION(\"testing comparison operators\")\n    {\n        x = 6;\n        y = 5;\n\n        REQUIRE( x == 6 );\n        REQUIRE( 6 == x );\n        REQUIRE( x == x );\n\n        REQUIRE( x != 5 );\n        REQUIRE( 5 != x );\n        REQUIRE( x != y );\n\n        REQUIRE( x > 5 );\n        REQUIRE( x > y );\n\n        REQUIRE( x >= 6 );\n        REQUIRE( x >= x );\n        REQUIRE( x >= y );\n\n        REQUIRE( 5 < x );\n        REQUIRE( y < x );\n\n        REQUIRE( 6 <= x );\n        REQUIRE( x <= x );\n        REQUIRE( y <= x );\n    }\n\n    SECTION(\"testing unary negative operator\")\n    {\n        std::function<dual(dual)> f;\n\n        // Testing positive operator on a dual\n        f = [](dual x) -> dual { return +x; };\n        REQUIRE( f(x) == x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == 1.0 );\n\n        // Testing positive operator on an expression\n        f = [](dual x) -> dual { return +(x * x); };\n        REQUIRE( f(x) == x * x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == 2.0 * x );\n\n        // Testing negative operator on a dual\n        f = [](dual x) -> dual { return -x; };\n        REQUIRE( f(x) == -x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -1.0 );\n\n        // Testing negative operator on a negative expression\n        f = [](dual x) -> dual { return -(-x); };\n        REQUIRE( f(x) == x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == 1.0 );\n\n        // Testing negative operator on a scaling expression expression\n        f = [](dual x) -> dual { return -(2.0 * x); };\n        REQUIRE( f(x) == -2.0 * x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -2.0 );\n\n        // Testing negative operator on a more complex expression\n        f = [](dual x) -> dual { return -x - (2*x); };\n        REQUIRE( f(x) == -val(x) - 2.0 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -3.0 );\n\n        // Testing negative operator on a more complex expression\n        f = [](dual x) -> dual { return -x - 2.0 * log(1.0 + exp(-x)); };\n        REQUIRE( f(x) == -val(x) - 2.0 * std::log(1.0 + std::exp(-val(x))) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -1.0 - 2.0/(1.0 + std::exp(-val(x))) * (-std::exp(-val(x))) );\n\n        // Testing negative operator on a more complex expression\n        f = [](dual x) -> dual { return -x - log(1.0 + exp(-x)); };\n        REQUIRE( f(x) == -val(x) - std::log(1.0 + std::exp(-val(x))) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -1.0 - 1.0/(1.0 + std::exp(-val(x))) * (-std::exp(-val(x))) );\n    }\n\n    SECTION(\"testing unary inverse operator\")\n    {\n        std::function<dual(dual)> f;\n\n        // Testing inverse operator on a dual\n        f = [](dual x) -> dual { return 1.0 / x; };\n        REQUIRE( f(x) == 1/x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -1.0 / (x * x) );\n\n        // Testing inverse operator on a trivial expression\n        f = [](dual x) -> dual { return x / x; };\n        REQUIRE( f(x) == 1.0 );\n        REQUIRE( derivative(f, wrt(x), at(x)) == 0.0 );\n\n        // Testing inverse operator on an inverse expression\n        f = [](dual x) -> dual { return 1.0 / (1.0 / x); };\n        REQUIRE( f(x) == x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == 1.0 );\n\n        // Testing inverse operator on a scaling expression\n        f = [](dual x) -> dual { return 1.0 / (2.0 * x); };\n        REQUIRE( f(x) == 0.5 / x );\n        REQUIRE( derivative(f, wrt(x), at(x)) == -0.5 / (x * x) );\n    }\n\n    SECTION(\"testing binary addition operator\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        // Testing addition operator on a `number + dual` expression\n        f = [](dual x, dual y) -> dual { return 1 + x; };\n        REQUIRE( f(x, y) == 1 + val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        // Testing addition operator on a `dual + number` expression\n        f = [](dual x, dual y) -> dual { return x + 1; };\n        REQUIRE( f(x, y) == val(x) + 1 );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        // Testing addition operator on a `dual + dual` expression\n        f = [](dual x, dual y) -> dual { return (-x) + (-y); };\n        REQUIRE( f(x, y) == -(val(x) + val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -1.0 );\n\n        // Testing addition operator on a `(-dual) + (-dual)` expression\n        f = [](dual x, dual y) -> dual { return (-x) + (-y); };\n        REQUIRE( f(x, y) == -(val(x) + val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -1.0 );\n\n        // Testing addition operator on a `dual * dual + dual * dual` expression\n        f = [](dual x, dual y) -> dual { return x * y + x * y; };\n        REQUIRE( f(x, y) == 2.0 * (val(x) * val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx( 2.0 * y ) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx( 2.0 * x ) );\n\n        // Testing addition operator on a `1/dual * 1/dual` expression\n        f = [](dual x, dual y) -> dual { return 1.0 / x + 1.0 / y; };\n        REQUIRE( f(x, y) == approx( 1.0 / val(x) + 1.0 / val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx( -1.0 / (x * x) ) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx( -1.0 / (y * y) ) );\n    }\n\n    SECTION(\"testing binary subtraction operator\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        // Testing subtraction operator on a `number - dual` expression\n        f = [](dual x, dual y) -> dual { return 1 - x; };\n        REQUIRE( f(x, y) == 1 - val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  0.0 );\n\n        // Testing subtraction operator on a `dual - number` expression\n        f = [](dual x, dual y) -> dual { return x - 1; };\n        REQUIRE( f(x, y) == val(x) - 1 );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        // Testing subtraction operator on a `(-dual) - (-dual)` expression\n        f = [](dual x, dual y) -> dual { return (-x) - (-y); };\n        REQUIRE( f(x, y) == -(val(x) - val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  1.0 );\n\n        // Testing subtraction operator on a `dual * dual - dual * dual` expression\n        f = [](dual x, dual y) -> dual { return x * y - x * y; };\n        REQUIRE( f(x, y) == 0.0 );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx( 0.0 ) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx( 0.0 ) );\n\n        // Testing subtraction operator on a `1/dual * 1/dual` expression\n        f = [](dual x, dual y) -> dual { return 1.0 / x - 1.0 / y; };\n        REQUIRE( f(x, y) == approx( 1.0 / val(x) - 1.0 / val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx( -1.0 / (x * x) ) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(  1.0 / (y * y) ) );\n    }\n\n    SECTION(\"testing binary multiplication operator\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        // Testing multiplication operator on a `number * dual` expression\n        f = [](dual x, dual y) -> dual { return 2.0 * x; };\n        REQUIRE( f(x, y) == 2.0 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        // Testing multiplication operator on a `dual * number` expression\n        f = [](dual x, dual y) -> dual { return x * 2; };\n        REQUIRE( f(x, y) == 2.0 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        // Testing multiplication operator on a `dual * dual` expression\n        f = [](dual x, dual y) -> dual { return x * y; };\n        REQUIRE( f(x, y) == val(x) * val(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == y );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == x );\n\n        // Testing multiplication operator on a `number * (number * dual)` expression\n        f = [](dual x, dual y) -> dual { return 5 * (2.0 * x); };\n        REQUIRE( f(x, y) == 10 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 10.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  0.0 );\n\n        // Testing multiplication operator on a `(dual * number) * number` expression\n        f = [](dual x, dual y) -> dual { return (x * 2) * 5; };\n        REQUIRE( f(x, y) == 10 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 10.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  0.0 );\n\n        // Testing multiplication operator on a `number * (-dual)` expression\n        f = [](dual x, dual y) -> dual { return 2.0 * (-x); };\n        REQUIRE( f(x, y) == -2.0 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  0.0 );\n\n        // Testing multiplication operator on a `(-dual) * number` expression\n        f = [](dual x, dual y) -> dual { return (-x) * 2; };\n        REQUIRE( f(x, y) == -2.0 * val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == -2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) ==  0.0 );\n\n        // Testing multiplication operator on a `(-dual) * (-dual)` expression\n        f = [](dual x, dual y) -> dual { return (-x) * (-y); };\n        REQUIRE( f(x, y) == val(x) * val(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == y );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == x );\n\n        // Testing multiplication operator on a `(1/dual) * (1/dual)` expression\n        f = [](dual x, dual y) -> dual { return (1 / x) * (1 / y); };\n        REQUIRE( f(x, y) == 1 / (val(x) * val(y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(-1/(x * x * y)) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-1/(x * y * y)) );\n    }\n\n    SECTION(\"testing binary division operator\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        // Testing division operator on a `number / dual` expression\n        f = [](dual x, dual y) -> dual { return 1 / x; };\n        REQUIRE( f(x, y) == 1 / val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(-1.0 / (x * x)) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        // Testing division operator on a `dual / number` expression\n        f = [](dual x, dual y) -> dual { return x / 2; };\n        REQUIRE( f(x, y) == val(x) / 2 );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.5) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        // Testing division operator on a `dual / dual` expression\n        f = [](dual x, dual y) -> dual { return x / y; };\n        REQUIRE( f(x, y) == val(x) / val(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(1 / y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-x / (y * y)) );\n\n        // Testing division operator on a `1 / (number * dual)` expression\n        f = [](dual x, dual y) -> dual { return 1 / (2.0 * x); };\n        REQUIRE( f(x, y) == approx(0.5 / x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(-0.5 / (x * x)) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        // Testing division operator on a `1 / (1 / dual)` expression\n        f = [](dual x, dual y) -> dual { return 1 / (1 / x); };\n        REQUIRE( f(x, y) == val(x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n    }\n\n    SECTION(\"testing operator+=\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        f = [](dual x, dual y) -> dual { return x += 1; };\n        REQUIRE( f(x, y) == approx(x + 1) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        f = [](dual x, dual y) -> dual { return x += y; };\n        REQUIRE( f(x, y) == approx(x + y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 1.0 );\n\n        f = [](dual x, dual y) -> dual { return x += -y; };\n        REQUIRE( f(x, y) == approx(x - y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -1.0 );\n\n        f = [](dual x, dual y) -> dual { return x += -(x - y); };\n        REQUIRE( f(x, y) == approx(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 0.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 1.0 );\n\n        f = [](dual x, dual y) -> dual { return x += 1.0 / y; };\n        REQUIRE( f(x, y) == approx(x + 1.0 / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-1.0 / (y * y)) );\n\n        f = [](dual x, dual y) -> dual { return x += 2.0 * y; };\n        REQUIRE( f(x, y) == approx(x + 2.0 * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 2.0 );\n\n        f = [](dual x, dual y) -> dual { return x += x * y; };\n        REQUIRE( f(x, y) == approx(x + x * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 + y );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == x );\n\n        f = [](dual x, dual y) -> dual { return x += x + y; };\n        REQUIRE( f(x, y) == approx(x + x + y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 1.0 );\n    }\n\n    SECTION(\"testing operator-=\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        f = [](dual x, dual y) -> dual { return x -= 1; };\n        REQUIRE( f(x, y) == approx(x - 1) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 0.0 );\n\n        f = [](dual x, dual y) -> dual { return x -= y; };\n        REQUIRE( f(x, y) == approx(x - y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -1.0 );\n\n        f = [](dual x, dual y) -> dual { return x -= -y; };\n        REQUIRE( f(x, y) == approx(x + y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 1.0 );\n\n        f = [](dual x, dual y) -> dual { return x -= -(x - y); };\n        REQUIRE( f(x, y) == approx(2.0 * x - y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  2.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -1.0 );\n\n        f = [](dual x, dual y) -> dual { return x -= 1.0 / y; };\n        REQUIRE( f(x, y) == approx(x - 1.0 / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(1.0 / (y * y)) );\n\n        f = [](dual x, dual y) -> dual { return x -= 2.0 * y; };\n        REQUIRE( f(x, y) == approx(x - 2.0 * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) ==  1.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -2.0 );\n\n        f = [](dual x, dual y) -> dual { return x -= x * y; };\n        REQUIRE( f(x, y) == approx(x - x * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 1.0 - y );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == -x );\n\n        f = [](dual x, dual y) -> dual { return x -= x - y; };\n        REQUIRE( f(x, y) == approx(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == 0.0 );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == 1.0 );\n    }\n\n    SECTION(\"testing operator*=\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        f = [](dual x, dual y) -> dual { return x *= 2; };\n        REQUIRE( f(x, y) == approx(2.0 * x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        f = [](dual x, dual y) -> dual { return x *= y; };\n        REQUIRE( f(x, y) == approx(x * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(x) );\n\n        f = [](dual x, dual y) -> dual { return x *= -x; };\n        REQUIRE( f(x, y) == approx(-x * x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(-2.0 * x) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        f = [](dual x, dual y) -> dual { return x *= (2.0 / y); };\n        REQUIRE( f(x, y) == approx(2.0 * x / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0 / y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-2.0 * x / (y * y)) );\n\n        f = [](dual x, dual y) -> dual { return x *= (2.0 * x); };\n        REQUIRE( f(x, y) == approx(2.0 * x * x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(4.0 * x) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        f = [](dual x, dual y) -> dual { return x *= (2.0 * y); };\n        REQUIRE( f(x, y) == approx(2.0 * x * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0 * y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(2.0 * x) );\n\n        f = [](dual x, dual y) -> dual { return x *= x + y; };\n        REQUIRE( f(x, y) == approx(x * (x + y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0 * x + y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(x) );\n\n        f = [](dual x, dual y) -> dual { return x *= x * y; };\n        REQUIRE( f(x, y) == approx(x * (x * y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0 * x * y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(x * x) );\n    }\n\n    SECTION(\"testing operator/=\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        f = [](dual x, dual y) -> dual { return x /= 2; };\n        REQUIRE( f(x, y) == approx(0.5 * x) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.5) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        f = [](dual x, dual y) -> dual { return x /= y; };\n        REQUIRE( f(x, y) == approx(x / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(1.0 / y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-x / (y * y)) );\n\n        f = [](dual x, dual y) -> dual { return x /= -x; };\n        REQUIRE( f(x, y) == approx(-1.0) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        f = [](dual x, dual y) -> dual { return x /= (2.0 / y); };\n        REQUIRE( f(x, y) == approx(0.5 * x * y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.5 * y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.5 * x) );\n\n        f = [](dual x, dual y) -> dual { return x /= (2.0 * y); };\n        REQUIRE( f(x, y) == approx(0.5 * x / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx( 0.5 / y) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-0.5 * x / (y * y)) );\n\n        f = [](dual x, dual y) -> dual { return x /= x + y; };\n        REQUIRE( f(x, y) == approx(x / (x + y)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(1.0 / (x + y) - x / (x + y) / (x + y)) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-x / (x + y) / (x + y)) );\n\n        f = [](dual x, dual y) -> dual { return x /= x * y; };\n        REQUIRE( f(x, y) == approx(1.0 / y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-1.0 / (y * y)) );\n    }\n\n    SECTION(\"testing combination of operations\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        // Testing multiplication with addition\n        f = [](dual x, dual y) -> dual { return 2.0 * x + y; };\n        REQUIRE( f(x, y) == 2.0 * val(x) + val(y) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(2.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(1.0) );\n\n        // Testing a complex expression that is actually equivalent to one\n        f = [](dual x, dual y) -> dual { return (2.0 * x * x - x * y + x / y + x / (2.0 * y)) / (x * (2.0 * x - y + 1 / y + 1 / (2.0 * y))); };\n        REQUIRE( f(x, y) == approx(1.0) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n    }\n\n    SECTION(\"testing mathematical functions\")\n    {\n        std::function<dual(dual)> f;\n\n        x = 0.5;\n\n        // Testing sin function\n        f = [](dual x) -> dual { return sin(x); };\n        REQUIRE( f(x) == std::sin(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(cos(x)) );\n\n        // Testing cos function\n        f = [](dual x) -> dual { return cos(x); };\n        REQUIRE( f(x) == std::cos(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(-sin(x)) );\n\n        // Testing tan function\n        f = [](dual x) -> dual { return tan(x); };\n        REQUIRE( f(x) == std::tan(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / (cos(x) * cos(x))) );\n\n        // Testing sinh function\n        f = [](dual x) -> dual { return sinh(x); };\n        REQUIRE( f(x) == std::sinh(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(cosh(x)) );\n\n        // Testing cosh function\n        f = [](dual x) -> dual { return cosh(x); };\n        REQUIRE( f(x) == std::cosh(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(sinh(x)) );\n\n        // Testing tanh function\n        f = [](dual x) -> dual { return tanh(x); };\n        REQUIRE( f(x) == std::tanh(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / (cosh(x) * cosh(x))) );\n\n        // Testing asin function\n        f = [](dual x) -> dual { return asin(x); };\n        REQUIRE( f(x) == std::asin(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / sqrt(1 - x * x)) );\n\n        // Testing acos function\n        f = [](dual x) -> dual { return acos(x); };\n        REQUIRE( f(x) == std::acos(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(-1 / sqrt(1 - x * x)) );\n\n        // Testing atan function\n        f = [](dual x) -> dual { return atan(x); };\n        REQUIRE( f(x) == std::atan(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / (1 + x * x)) );\n\n        // Testing exp function\n        f = [](dual x) -> dual { return exp(x); };\n        REQUIRE( f(x) == std::exp(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(exp(x)) );\n\n        // Testing log function\n        f = [](dual x) -> dual { return log(x); };\n        REQUIRE( f(x) == std::log(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / x) );\n\n        // Testing log function\n        f = [](dual x) -> dual { return log10(x); };\n        REQUIRE( f(x) == std::log10(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1 / (log(10) * x)) );\n\n        // Testing sqrt function\n        f = [](dual x) -> dual { return sqrt(x); };\n        REQUIRE( f(x) == std::sqrt(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(0.5 / sqrt(x)) );\n\n        // Testing pow function (with number exponent)\n        f = [](dual x) -> dual { return pow(x, 2.0); };\n        REQUIRE( f(x) == std::pow(val(x), 2.0) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(2.0 * x) );\n\n        // Testing pow function (with dual exponent)\n        f = [](dual x) -> dual { return pow(x, x); };\n        REQUIRE( f(x) == std::pow(val(x), val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx((log(x) + 1) * pow(x, x)) );\n\n        // Testing pow function (with expression exponent)\n        f = [](dual x) -> dual { return pow(x, 2.0 * x); };\n        REQUIRE( f(x) == std::pow(val(x), 2.0 * val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(2.0 * (log(x) + 1) * pow(x, 2.0 * x)) );\n\n        // Testing abs function (for x > 0, x < 0, and x = 0)\n        f = [](dual x) -> dual { return abs(x); };\n        x = 1.0;\n        REQUIRE( f(x) == std::abs(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(1.0) );\n        x = -1.0;\n        REQUIRE( f(x) == std::abs(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(-1.0) );\n        x = 0;\n        REQUIRE( f(x) == std::abs(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(0.0) );\n\n\n        // Testing erf function\n        f = [](dual x) -> dual { return erf(x); };\n        x = 1.0;\n        REQUIRE( f(x) == std::erf(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(0.415107) );\n        x = -1.4;\n        REQUIRE( f(x) == std::erf(val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(0.158942) );\n\n        // Testing atan2 function on (double, dual)\n        f = [](dual x) -> dual { return atan2(2.0, x); };\n        x = 1.0;\n        REQUIRE( f(x) == std::atan2(2.0, val(x)) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(-2.0 / (2*2 + x*x)) );\n\n        // Testing atan2 function on (dual, double)\n        f = [](dual y) -> dual { return atan2(y, 2.0); };\n        x = 1.0;\n        REQUIRE( f(x) == std::atan2(val(x), 2.0) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(2.0 /  (2*2 + x*x)) );\n\n        // Testing atan2 function on (dual, dual)\n        std::function<dual(dual, dual)> g = [](dual y, dual x) -> dual { return atan2(y, x); };\n        x = 1.1;\n        dual y = 0.9;\n        REQUIRE( g(y, x) == std::atan2(val(y), val(x)) );\n        REQUIRE( derivative(g, wrt(y), at(y, x)) == approx(x / (x*x + y*y)) );\n        REQUIRE( derivative(g, wrt(x), at(y, x)) == approx(-y / (x*x + y*y)) );\n\n        // Testing atan2 function on (expr, expr)\n        g = [](dual y, dual x) -> dual { return 3 * atan2(sin(y), 2*x+1); };\n        REQUIRE( g(y, x) == 3 * std::atan2(sin(val(y)), 2*val(x)+1) );\n        REQUIRE( derivative(g, wrt(y), at(y, x)) == approx(3*(2*x+1)*cos(y) / ((2*x+1)*(2*x+1) + sin(y)*sin(y))) );\n        REQUIRE( derivative(g, wrt(x), at(y, x)) == approx(3*-2*sin(y) / ((2*x+1)*(2*x+1) + sin(y)*sin(y))) );\n        \n        // Testing hypot function on (dual, double)\n        f = [](dual y) -> dual { return hypot(y, 2.0); };\n        x = 1.5;\n        REQUIRE( f(x) == std::hypot(val(x), 2.0) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(x / std::hypot(val(x), 2.0)) );\n        \n        // Testing hypot function on (double, dual)\n        f = [](dual y) -> dual { return hypot(2.0, y); };\n        y = 1.5;\n        REQUIRE( f(y) == std::hypot(2.0, val(y)) );\n        REQUIRE( derivative(f, wrt(y), at(y)) == approx(y / std::hypot(2.0, val(y))) );\n        \n        // Testing hypot function on (dual, dual)\n        g = [](dual x, dual y) -> dual { return hypot(x,y); };\n        x = 1.1;\n        y = 0.9;\n        REQUIRE( g(x, y) == std::hypot(val(x), val(y)) );\n        REQUIRE( derivative(g, wrt(y), at(x,y)) == approx(y / std::hypot(val(x), val(y))) );\n        REQUIRE( derivative(g, wrt(x), at(x,y)) == approx(x / std::hypot(val(x), val(y))) );\n        \n        // Testing hypot function on (expr, expr)\n        g = [](dual x, dual y) -> dual { return hypot(2.0*x,3.0*y); };\n        x = 1.1;\n        y = 0.9;\n        REQUIRE( g(x, y) == std::hypot(2.0*val(x), 3.0*val(y)) );\n        REQUIRE( derivative(g, wrt(x), at(x,y)) == approx(4.0*x / std::hypot(2.0*val(x), 3.0*val(y))) );\n        REQUIRE( derivative(g, wrt(y), at(x,y)) == approx(9.0*y / std::hypot(2.0*val(x), 3.0*val(y))) );\n        \n        // Testing hypot function on (dual, double, double)\n        f = [](dual x) -> dual { return hypot(x, 2.0, 2.0); };\n        x = 1.5;\n        REQUIRE( f(x) == std::hypot(val(x), 2.0, 2.0) );\n        REQUIRE( derivative(f, wrt(x), at(x)) == approx(x / std::hypot(val(x), 2.0, 2.0)) );\n        \n        // Testing hypot function on (double, dual, double)\n        f = [](dual y) -> dual { return hypot(2.0, y, 2.0); };\n        y = 2.5;\n        REQUIRE( f(y) == std::hypot(2.0, val(y), 2.0) );\n        REQUIRE( derivative(f, wrt(y), at(y)) == approx(y / std::hypot(2.0, val(y), 2.0)) );\n        \n        // Testing hypot function on (double, double, dual)\n        f = [](dual z) -> dual { return hypot(2.0, 2.0, z); };\n        dual z = 3.5;\n        REQUIRE( f(z) == std::hypot(2.0, 2.0, val(z)) );\n        REQUIRE( derivative(f, wrt(z), at(z)) == approx(z / std::hypot(2.0, 2.0, val(z))) );\n        \n        // Testing hypot function on (dual, dual, double)\n        g = [](dual x, dual y) -> dual { return hypot(x, y, 2.0); };\n        x = 1.4;\n        y = 2.4;\n        REQUIRE( g(x,y) == std::hypot(val(x), val(y), 2.0) );\n        REQUIRE( derivative(g, wrt(x), at(x,y)) == approx(x / std::hypot(val(x), val(y), 2.0)) );\n        REQUIRE( derivative(g, wrt(y), at(x,y)) == approx(y / std::hypot(val(x), val(y), 2.0)) );\n        \n        // Testing hypot function on (double, dual, dual)\n        g = [](dual y, dual z) -> dual { return hypot(2.0, y, z); };\n        y = 2.4;\n        z = 3.4;\n        REQUIRE( g(y,z) == std::hypot(2.0, val(y), val(z)) );\n        REQUIRE( derivative(g, wrt(y), at(y,z)) == approx(y / std::hypot(2.0, val(y), val(z))) );\n        REQUIRE( derivative(g, wrt(z), at(y,z)) == approx(z / std::hypot(2.0, val(y), val(z))) );\n        \n        // Testing hypot function on (dual, double, dual)\n        g = [](dual x, dual z) -> dual { return hypot(x, 2.0, z); };\n        x = 3.4;\n        z = 4.4;\n        REQUIRE( g(x,z) == std::hypot(val(x), 2.0, val(z)) );\n        REQUIRE( derivative(g, wrt(x), at(x,z)) == approx(x / std::hypot(val(x), 2.0, val(z))) );\n        REQUIRE( derivative(g, wrt(z), at(x,z)) == approx(z / std::hypot(val(x), 2.0, val(z))) );\n      \n        // Testing hypot function on (dual, double, dual)\n        std::function<dual(dual, dual, dual)> h = [](dual x, dual y, dual z) -> dual { return hypot(x, y, z); };\n        x = 1.6;\n        y = 2.6;\n        z = 3.6;\n        REQUIRE( h(x,y,z) == std::hypot(val(x), val(y), val(z)) );\n        REQUIRE( derivative(h, wrt(x), at(x,y,z)) == approx(x / std::hypot(val(x), val(y), val(z))) );\n        REQUIRE( derivative(h, wrt(y), at(x,y,z)) == approx(y / std::hypot(val(x), val(y), val(z))) );\n        REQUIRE( derivative(h, wrt(z), at(x,y,z)) == approx(z / std::hypot(val(x), val(y), val(z))) );\n      \n        // Testing hypot function on (expr, expr, expr)\n        h = [](dual x, dual y, dual z) -> dual { return hypot(2.0*x, 3.0*y, 4.0*z); };\n        x = 2.6;\n        y = 3.6;\n        z = 4.6;\n        REQUIRE( h(x,y,z) == std::hypot(2.0*val(x), 3.0*val(y), 4.0*val(z)) );\n        REQUIRE( derivative(h, wrt(x), at(x,y,z)) == approx(4.0*x / std::hypot(2.0*val(x), 3.0*val(y), 4.0*val(z))) );\n        REQUIRE( derivative(h, wrt(y), at(x,y,z)) == approx(9.0*y / std::hypot(2.0*val(x), 3.0*val(y), 4.0*val(z))) );\n        REQUIRE( derivative(h, wrt(z), at(x,y,z)) == approx(16.*z / std::hypot(2.0*val(x), 3.0*val(y), 4.0*val(z))) );\n    }\n\n    SECTION(\"testing complex expressions\")\n    {\n        std::function<dual(dual, dual)> f;\n\n        x = 0.5;\n        y = 0.8;\n\n        // Testing complex function involving sin, cos, and tan\n        f = [](dual x, dual y) -> dual { return sin(x + y) * cos(x / y) + tan(2.0 * x * y) - sin(4*(x + y)*2/8) * cos(x*x / (y*y) * y/x) - tan((x + y) * (x + y) - x*x - y*y); };\n        REQUIRE( val(f(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n\n        // Testing complex function involving log, exp, pow, and sqrt\n        f = [](dual x, dual y) -> dual { return log(x + y) * exp(x / y) + sqrt(2.0 * x * y) - 1 / pow(x, x + y) - exp(x*x / (y*y) * y/x) * log(4*(x + y)*2/8) - 4 * sqrt((x + y) * (x + y) - x*x - y*y) * 0.5 * 0.5 + 2 / pow(2.0 * x - x, y + x) * 0.5; };\n        REQUIRE( val(f(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(0.0) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(0.0) );\n    }\n\n\n    SECTION(\"testing higher order derivatives\")\n    {\n        using dual2nd = HigherOrderDual<2>;\n\n        std::function<dual2nd(dual2nd, dual2nd)> f;\n\n        dual2nd x = 5;\n        dual2nd y = 7;\n\n        // Testing simpler functions\n        f = [](dual2nd x, dual2nd y) -> dual2nd\n        {\n            return x*x + x*y + y*y;\n        };\n\n        REQUIRE( val(derivative(f, wrt(x), at(x, y))) == Approx(17.0) );\n        REQUIRE( derivative(f, wrt<2>(x), at(x, y)) == Approx(2.0) );\n        REQUIRE( derivative(f, wrt(x, y), at(x, y)) == Approx(1.0) );\n        REQUIRE( derivative(f, wrt(y, x), at(x, y)) == Approx(1.0) );\n        REQUIRE( derivative(f, wrt<2>(y), at(x, y)) == Approx(2.0) );\n\n        // Testing complex function involving log\n        x = 2.0;\n        y = 1.0;\n\n        f = [](dual2nd x, dual2nd y) -> dual2nd\n        {\n            return 1 + x + y + x * y + y / x + log(x / y);\n        };\n\n        REQUIRE( val(f(x, y)) == Approx( 1 + val(x) + val(y) + val(x) * val(y) + val(y) / val(x) + log(val(x) / val(y)) ) );\n        REQUIRE( val(derivative(f, wrt(x), at(x, y))) == Approx( 1 + val(y) - val(y) / (val(x) * val(x)) + 1.0/val(x) - log(val(y)) ) );\n        REQUIRE( val(derivative(f, wrt(y), at(x, y))) == Approx( 1 + val(x) + 1.0 / val(x) - 1.0/val(y) ) );\n        REQUIRE( val(derivative(f, wrt<2>(x), at(x, y))) == Approx( 2 * val(y) / (val(x) * val(x) * val(x)) + -1.0/(val(x) * val(x)) ) );\n        REQUIRE( val(derivative(f, wrt(y, y), at(x, y))) == Approx( 1.0/(val(y)*val(y)) ) );\n        REQUIRE( val(derivative(f, wrt(y, x), at(x, y))) == Approx( 1 - 1.0 / (val(x) * val(x)) ) );\n        REQUIRE( val(derivative(f, wrt(x, y), at(x, y))) == Approx( 1 - 1.0 / (val(x) * val(x)) ) );\n    }\n\n    SECTION(\"testing higher order derivatives\")\n    {\n        using dual3rd = HigherOrderDual<3>;\n\n        dual3rd x = 5;\n        dual3rd y = 7;\n\n        // Testing complex function involving sin and cos\n        auto f = [](dual3rd x, dual3rd y) -> dual3rd\n        {\n            return (x + y)*(x + y)*(x + y);\n        };\n\n        REQUIRE( derivative(f, wrt<3>(x), at(x, y)) == Approx(6.0) );\n        REQUIRE( derivative(f, wrt(x, x, x), at(x, y)) == Approx(6.0) );\n        REQUIRE( derivative(f, wrt(x, x, y), at(x, y)) == Approx(6.0) );\n        REQUIRE( derivative(f, wrt(x, y, y), at(x, y)) == Approx(6.0) );\n        REQUIRE( derivative(f, wrt<3>(y), at(x, y)) == Approx(6.0) );\n    }\n\n    SECTION(\"testing reference to unary and binary expression nodes are not present\")\n    {\n        x = -0.3;\n        y =  0.5;\n\n        auto pow2 = [](const auto& x)\n        {\n            return x*x;\n        };\n\n        auto rosenbrock = [&](const auto& x, const auto& y)\n        {\n            return 100.0 * pow2(x*x - y) + pow2(1.0 - x);\n        };\n\n        auto f = [&](const auto& x, const auto& y) -> dual\n        {\n            return rosenbrock(x, y);\n        };\n\n        REQUIRE( val(f(x, y)) == approx(100 * (x*x - y)*(x*x - y) + (1 - x)*(1 - x)) );\n        REQUIRE( derivative(f, wrt(x), at(x, y)) == approx(400*(x*x - y)*x - 2*(1 - x)) );\n        REQUIRE( derivative(f, wrt(y), at(x, y)) == approx(-200*(x*x - y)) );\n    }\n}\n\nTEST_CASE(\"Eigen::VectorXdual tests\", \"[dual]\")\n{\n    SECTION(\"testing gradient derivatives\")\n    {\n        // Testing complex function involving sin and cos\n        auto f = [](const VectorXdual& x) -> dual\n        {\n            return 0.5 * ( x.array() * x.array() ).sum();\n        };\n\n        VectorXdual x(3);\n        x << 1.0, 2.0, 3.0;\n\n        VectorXd g = gradient(f, wrt(x), at(x));\n\n        REQUIRE( g[0] == approx(x[0]) );\n        REQUIRE( g[1] == approx(x[1]) );\n        REQUIRE( g[2] == approx(x[2]) );\n    }\n\n    SECTION(\"testing gradient derivatives of only the last two variables\")\n    {\n        // Testing complex function involving sin and cos\n        auto f = [](const VectorXdual& x) -> dual\n        {\n            return 0.5 * ( x.array() * x.array() ).sum();\n        };\n\n        VectorXdual x(3);\n        x << 1.0, 2.0, 3.0;\n\n        VectorXd g = gradient(f, wrt(x.tail(2)), at(x));\n\n        REQUIRE( g[0] == approx(x[1]) );\n        REQUIRE( g[1] == approx(x[2]) );\n    }\n\n    SECTION(\"testing jacobian derivatives\")\n    {\n        // Testing complex function involving sin and cos\n        auto f = [](const VectorXdual& x) -> VectorXdual\n        {\n            return x / x.array().sum();\n        };\n\n        VectorXdual x(3);\n        x << 0.5, 0.2, 0.3;\n\n        VectorXdual F;\n\n        const MatrixXd J = jacobian(f, wrt(x), at(x), F);\n\n        for(auto i = 0; i < 3; ++i)\n            for(auto j = 0; j < 3; ++j)\n                REQUIRE( J(i, j) == approx(-F[i] + ((i == j) ? 1.0 : 0.0)) );\n    }\n\n    SECTION(\"testing jacobian derivatives of only the last two variables\")\n    {\n        // Testing complex function involving sin and cos\n        auto f = [](const VectorXdual& x) -> VectorXdual\n        {\n            return x / x.array().sum();\n        };\n\n        VectorXdual x(3);\n        x << 0.5, 0.2, 0.3;\n\n        VectorXdual F;\n\n        const MatrixXd J = jacobian(f, wrt(x.tail(2)), at(x), F);\n\n        for(auto i = 0; i < 3; ++i)\n            for(auto j = 0; j < 2; ++j)\n                REQUIRE( J(i, j) == approx(-F[i] + ((i == j + 1) ? 1.0 : 0.0)) );\n    }\n\n    SECTION(\"testing casting to VectorXd\")\n    {\n        VectorXdual x(3);\n        x << 0.5, 0.2, 0.3;\n\n        VectorXd y = x.cast<double>();\n\n        for(auto i = 0; i < 3; ++i)\n            REQUIRE( x(i) == approx(y(i)) );\n    }\n\n    SECTION(\"testing casting to VectorXf\")\n    {\n    \tMatrixXdual x(2, 2);\n        x << 0.5, 0.2, 0.3, 0.7;\n        MatrixXd y = x.cast<double>();\n        for(auto i = 0; i < 2; ++i)\n            for(auto j = 0; j < 2; ++j)\n                REQUIRE( x(i, j) == approx(y(i, j)) );\n    }\n\n    SECTION(\"test gradient size with respect to few arguments\")\n    {\n        // Testing complex function involving sin and cos\n        auto f = [](const VectorXdual& x, dual y, const VectorXdual& z) -> dual\n        {\n            return 0.5 * (( x.array() * x.array() ).sum() + y * y + (z.array() * z.array()).sum());\n        };\n\n        VectorXdual x(3);\n        x << 1.0, 2.0, 3.0;\n\n        dual y = 2;\n\n        VectorXdual z(4);\n        z << 1.0, 2.0, 3.0, 4.0;\n\n        VectorXd g = gradient(f, wrtpack(x.tail(2), y, z), at(x, y, z));\n\n        REQUIRE( g.size() == 7 );\n    }\n\n    SECTION(\"testing gradient derivatives wrt pack variables\")\n    {\n        auto f = [](const VectorXdual& x, dual y, const VectorXdual& z) -> dual\n        {\n            return 0.5 * (( x.array() * x.array() ).sum() + y * y + (z.array() * z.array()).sum());\n        };\n\n        VectorXdual x(2);\n        x << 1.0, 2.0;\n\n        dual y = 3.0;\n\n        VectorXdual z(1);\n        z << 4.0;\n\n        VectorXd g = gradient(f, wrtpack(x, y, z), at(x, y, z));\n\n        REQUIRE(g[0] == approx(x[0]));\n        REQUIRE(g[1] == approx(x[1]));\n        REQUIRE(g[2] == approx(y));\n        REQUIRE(g[3] == approx(z[0]));\n    }\n\n    SECTION(\"test jacobian size with respect to few arguments\")\n    {\n        auto f = [](const VectorXdual& x, dual y, const VectorXdual& z) -> VectorXdual\n        {\n            VectorXdual ret(x.size() + z.size());\n            ret.head(x.size()) = x * y / x.array().sum();\n            ret.tail(z.size()) = y * z;\n\n            return ret;\n        };\n\n        VectorXdual x(3);\n        x << 0.5, 0.2, 0.3;\n\n        dual y = 2.0;\n\n        VectorXdual z(3);\n        z << 1.0, 2.0, 3.0;\n\n        VectorXdual F;\n\n        const MatrixXd J = jacobian(f, wrtpack(x.tail(2), y), at(x, y, z), F);\n\n        REQUIRE(J.rows() == 6);\n        REQUIRE(J.cols() == 3);\n    }\n\n    SECTION(\"test jacobian size with respect to few arguments\")\n    {\n        auto f = [](const VectorXdual& x, dual y, const VectorXdual& z) -> VectorXdual\n        {\n            VectorXdual ret(x.size() + z.size());\n            ret.head(x.size()) = x * y / x.array().sum();\n            ret.tail(z.size()) = y * z;\n\n            return ret;\n        };\n\n        VectorXdual x(3);\n        x << 0.5, 0.2, 0.3;\n\n        dual y = 2.0;\n\n        VectorXdual z(3);\n        z << 1.0, 2.0, 3.0;\n\n        VectorXdual F;\n\n        const MatrixXd J = jacobian(f, wrtpack(x, y, z), at(x, y, z), F);\n\n        for (auto i = 0; i < 3; ++i)\n            for (auto j = 0; j < 3; ++j)\n                REQUIRE(J(i, j) == approx(-F[i] + ((i == j) ? y.val : 0.0)));\n\n        for (auto i = 0; i < 3; ++i)\n            for (auto j = 0; j < 3; ++j)\n                REQUIRE(J(i + 3, j) == approx(0.0));\n\n        for (auto i = 0; i < 6; ++i)\n                REQUIRE(J(i, 3) == approx( i < 3 ? x(i) : z(i - 3)));\n\n        for (auto i = 0; i < 3; ++i)\n            for (auto j = 0; j < 3; ++j)\n                REQUIRE(J(i, j + 4) == approx(0.0));\n\n        for (auto i = 0; i < 3; ++i)\n            for (auto j = 0; j < 3; ++j)\n                REQUIRE(J(i + 3, j + 4) == approx((i == j) ? y.val : 0.0));\n    }\n}\n", "meta": {"hexsha": "28e7abb641f75cffc1e395f81ba6d9a5050f096b", "size": 42054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/forward.test.cpp", "max_stars_repo_name": "pettni/autodiff", "max_stars_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-05T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T18:58:04.000Z", "max_issues_repo_path": "test/forward.test.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "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/forward.test.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-05T18:59:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-05T18:59:47.000Z", "avg_line_length": 39.5988700565, "max_line_length": 251, "alphanum_fraction": 0.4636657631, "num_tokens": 14060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6907750882240542}}
{"text": "#include<iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <vector>\n#include <Eigen/QR>    \n\nusing namespace std;\nEigen::MatrixXf pseudoinverse(Eigen::MatrixXf m)\n{\n    //Eigen::Matrix<float,2,3> m;\n  //  m<<0.68,0.597,-0.211, 0.823,0.566,-0.605;\n   // m<<1,2,3,4,5,6;\n    cout<<m<<endl;\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd =m.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n   // Eigen::JacobiSVD<Eigen::MatrixXf> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV); \n    const Eigen::MatrixXf singularValues = svd.singularValues();\n\tEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> singularValuesInv(m.cols(), m.rows());\n\tsingularValuesInv.setZero();\n\tdouble  pinvtoler = 1.e-6; // choose your tolerance wisely\n\tfor (unsigned int i = 0; i < singularValues.size(); ++i) {\n\t \tif (singularValues(i) > pinvtoler)\n\t \t\tsingularValuesInv(i, i) = 1.0f / singularValues(i);\n\t \telse\n\t \t\tsingularValuesInv(i, i) = 0.f;\n\t }\n    Eigen::MatrixXf pinvmat = svd.matrixV() * singularValuesInv * svd.matrixU().transpose();\n    std::cout << pinvmat << std::endl;\n\treturn pinvmat;\n}\nint main(int argc, char **argv){\n      Eigen::Matrix<double, 6, 1> error;\n      for(int i=0; i<6;i++)\n      for (int j = 0; j < 1; j++)\n      {\n          error(i,j)=1;\n          std::cout<<error(i,j);\n      }\n    cout<<endl;\n    std::vector<int>ve;\n    ve.push_back(1);\n    ve.push_back(2);\n    cout<<ve.data()<<endl;\n    Eigen::Vector4f ve4(1,2,3,4);\n    std::cout<<error.cols()<<error.rows()<<endl;\n    cout<<ve4<<endl;\n\n    Eigen::MatrixXf 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\n\n    array<double,4>arr={2,6,7.11,8.23};\n\n    Eigen::Map<const Eigen::Matrix<double, 2, 2>>m2(arr.data());\n    cout<<m2<<endl;\n    // m2<<1,2,3,4;\n    // cout<<m2<<endl;\n    //pseudoinverse();\n    // Eigen::Matrix<float, 6, 7> name=Eigen::Matrix<float,6,7>::Random();\n    // Eigen::Matrix<float,3,7> res;\n    // for (int i = 0; i < res.rows(); i++)\n    // {\n    //     for (int j = 0; j < res.cols(); j++)\n    //     {\n    //             res(i,j)=name(i,j);\n    //     }\n    // }\n    // cout<<res;\n\n//    Eigen::Matrix<float,2,3> m2;\n//    m2<<0.68,0.597,-0.211, 0.823,0.566,-0.605;\n//    m2<<1,2,3,4,5,6;\n//    cout<<m2;\n\n  //cout<<(pseudoinverse(res));\n\n}\n\n", "meta": {"hexsha": "284e5929e7b50b2d03a13c72ad8052574e8522a5", "size": 2281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/play.cpp", "max_stars_repo_name": "Colaplusice/libfranka", "max_stars_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "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": "examples/play.cpp", "max_issues_repo_name": "Colaplusice/libfranka", "max_issues_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "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": "examples/play.cpp", "max_forks_repo_name": "Colaplusice/libfranka", "max_forks_repo_head_hexsha": "a330115280de29de5d8cf2dbe311047c073711d5", "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.1604938272, "max_line_length": 98, "alphanum_fraction": 0.5620341955, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6907086905083488}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/generate_binary_vectors.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <array>\n#include <iostream>\n#include <iterator>\n#include <ostream>\n#include <vector>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_binary_vectors\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tint,\n\t\t2\n\t>\n\tvector2;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tint,\n\t\t3\n\t>\n\tvector3;\n\n\ttypedef\n\tstd::array<\n\t\tvector2,\n\t\t4\n\t>\n\tvector2_container;\n\n\ttypedef\n\tstd::array<\n\t\tvector3,\n\t\t8\n\t>\n\tvector3_container;\n\n\tstd::cout << \"Generating 2D binary vectors...\\n\";\n\n\tvector2_container const result2(\n\t\tfcppt::math::generate_binary_vectors<\n\t\t\tint,\n\t\t\t2\n\t\t>()\n\t);\n\n\tstd::cout << \"Result: \\n\";\n\n\tfor(\n\t\tauto const &element\n\t\t:\n\t\tresult2\n\t)\n\t\tstd::cout << element << '\\n';\n\n\tstd::cout << \"Now checking...\\n\";\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tresult2.size(),\n\t\t4u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult2[0],\n\t\tvector2(0,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult2[1],\n\t\tvector2(1,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult2[2],\n\t\tvector2(0,1)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult2[3],\n\t\tvector2(1,1)\n\t);\n\n\tstd::cout << \"Generating 3D binary vectors...\\n\";\n\n\tvector3_container const result3(\n\t\tfcppt::math::generate_binary_vectors<\n\t\t\tint,\n\t\t\t3\n\t\t>()\n\t);\n\n\tstd::cout << \"Result: \\n\";\n\n\tfor(\n\t\tauto const &element\n\t\t:\n\t\tresult3\n\t)\n\t\tstd::cout << element << '\\n';\n\n\tstd::cout << \"Now checking...\\n\";\n\n\tBOOST_REQUIRE_EQUAL(\n\t\tresult3.size(),\n\t\t8u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[0],\n\t\tvector3(0,0,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[1],\n\t\tvector3(1,0,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[2],\n\t\tvector3(0,1,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[3],\n\t\tvector3(1,1,0)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[4],\n\t\tvector3(0,0,1)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[5],\n\t\tvector3(1,0,1)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[6],\n\t\tvector3(0,1,1)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tresult3[7],\n\t\tvector3(1,1,1)\n\t);\n}\n", "meta": {"hexsha": "3705f4d45da939d5af4f704f7f9d090474662c83", "size": 2538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/binary_vectors.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/binary_vectors.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/binary_vectors.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7558139535, "max_line_length": 61, "alphanum_fraction": 0.6733648542, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.6907041059988996}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef QR_HPP\n#define QR_HPP\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n// QR decomposition using Gram-Schmit orthogonalization\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T> bool qr(const ub::matrix<T>& in, ub::matrix<T>& q, ub::matrix<T>& r)\n{\n\tint i, j, k;\n\tint n;\n\tub::vector<T> v;\n\tT tmp;\n\n\tn = in.size1();\n\tif (n != in.size2()) return false;\n\n\tq.resize(n, n);\n\tr.resize(n, n);\n\tv.resize(n);\n\n\tfor (i=0; i<n; i++) {\n\t\tfor (k=0; k<n; k++) v(k) = in(k, i);\n\t\tfor (j=0; j<i; j++) {\n\t\t\ttmp = 0.;\n\t\t\tfor (k=0; k<n; k++) {\n\t\t\t\ttmp += in(k, i) * q(k, j);\n\t\t\t}\n\t\t\tfor (k=0; k<n; k++) {\n\t\t\t\tv(k) -= tmp * q(k, j);\n\t\t\t}\n\t\t\tr(j, i) = tmp;\n\t\t}\n\t\ttmp = norm_2(v);\n\t\tif (tmp == 0.) return false;\n\t\tfor (k=0; k<n; k++) q(k, i) = v(k) / tmp;\n\t\tr(i, i) = tmp;\n\t\tfor (j=i+1; j<n; j++) r(j, i) = 0.;\n\t}\n\n\treturn true;\n}\n\n} // namespace kv\n\n#endif // QR_HPP\n", "meta": {"hexsha": "63956d3e7f6fd82a7f3ac8809f394fcc12d97060", "size": 988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/qr.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/qr.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/qr.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": 17.3333333333, "max_line_length": 87, "alphanum_fraction": 0.5334008097, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6906860089025104}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n//!\n//! @file\n//! @ingroup openOR_core_math\n\n#ifndef openOR_core_Math_detail_inverse_hpp\n#define openOR_core_Math_detail_inverse_hpp\n\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/void.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <openOR/Log/Logger.hpp>\n#include <openOR/Math/matrix.hpp>\n\n#include <openOR/Math/determinant.hpp>\n\nnamespace openOR {\n\tnamespace Math {\n\n\t\tstruct no_inverse_matrix_error : public std::runtime_error {\n\t\t\tno_inverse_matrix_error() : std::runtime_error(\"Could not get matrix inverse\") {\n\t\t\t\tLOG(Log::Level::Debug, Log::noAttribs, Log::msg(\"Exception thrown: Could not get matrix inverse\") );\n\t\t\t}\n\t\t};\n\n\t\tnamespace Impl {\n\n\t\t\ttemplate <class Type, int Dim>\n\t\t\tstruct Inverse {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\t// function has to be specialized\n\t\t\t\t\tBOOST_MPL_ASSERT((boost::is_same<Type, boost::mpl::void_>));\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type>\n\t\t\tstruct Inverse<Type, 2> {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType matResult;\n\t\t\t\t\tMath::get<0, 0>(matResult) = Math::get<1, 1>(mat);\n\t\t\t\t\tMath::get<0, 1>(matResult) = -Math::get<0, 1>(mat);\n\t\t\t\t\tMath::get<1, 0>(matResult) = -Math::get<1, 0>(mat);\n\t\t\t\t\tMath::get<1, 1>(matResult) = Math::get<0, 0>(mat);\n\t\t\t\t\tmatResult /= Math::determinant(mat);\n\t\t\t\t\treturn matResult;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type>\n\t\t\tstruct Inverse<Type, 3> {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType matResult;\n\t\t\t\t\tMath::get<0, 0>(matResult) = Math::get<1, 1>(mat) * Math::get<2, 2>(mat) - Math::get<1, 2>(mat) * Math::get<2, 1>(mat);\n\t\t\t\t\tMath::get<0, 1>(matResult) = Math::get<0, 2>(mat) * Math::get<2, 1>(mat) - Math::get<0, 1>(mat) * Math::get<2, 2>(mat);\n\t\t\t\t\tMath::get<0, 2>(matResult) = Math::get<0, 1>(mat) * Math::get<1, 2>(mat) - Math::get<0, 2>(mat) * Math::get<1, 1>(mat);\n\n\t\t\t\t\tMath::get<1, 0>(matResult) = Math::get<1, 2>(mat) * Math::get<2, 0>(mat) - Math::get<1, 0>(mat) * Math::get<2, 2>(mat);\n\t\t\t\t\tMath::get<1, 1>(matResult) = Math::get<0, 0>(mat) * Math::get<2, 2>(mat) - Math::get<0, 2>(mat) * Math::get<2, 0>(mat);\n\t\t\t\t\tMath::get<1, 2>(matResult) = Math::get<0, 2>(mat) * Math::get<1, 0>(mat) - Math::get<0, 0>(mat) * Math::get<1, 2>(mat);\n\n\t\t\t\t\tMath::get<2, 0>(matResult) = Math::get<1, 0>(mat) * Math::get<2, 1>(mat) - Math::get<1, 1>(mat) * Math::get<2, 0>(mat);\n\t\t\t\t\tMath::get<2, 1>(matResult) = Math::get<0, 1>(mat) * Math::get<2, 0>(mat) - Math::get<0, 0>(mat) * Math::get<2, 1>(mat);\n\t\t\t\t\tMath::get<2, 2>(matResult) = Math::get<0, 0>(mat) * Math::get<1, 1>(mat) - Math::get<0, 1>(mat) * Math::get<1, 0>(mat);\n\n\t\t\t\t\tmatResult /= Math::determinant(mat);\n\t\t\t\t\treturn matResult;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate <class Type>\n\t\t\tstruct Inverse<Type, 4> {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType inverse;\n\n\t\t\t\t\tusing namespace boost::numeric::ublas;\n\t\t\t\t\ttypedef permutation_matrix<std::size_t> pmatrix;\n\n\t\t\t\t\t// create a working copy of the input\n\t\t\t\t\tType A(mat);\n\n\t\t\t\t\t// create a permutation matrix for the LU-factorization\n\t\t\t\t\tpmatrix pm(A.size1());\n\n\t\t\t\t\t// perform LU-factorization\n\t\t\t\t\tint res = lu_factorize(A,pm);\n\t\t\t\t\tif( res != 0 ) { throw no_inverse_matrix_error(); }\n\n\t\t\t\t\t// create identity matrix of \"inverse\"\n\t\t\t\t\tinverse.assign( Math::MatrixTraits<Type>::IDENTITY );\n\n\t\t\t\t\t// backsubstitute to get the inverse\n\t\t\t\t\tlu_substitute(A, pm, inverse);\n\n\t\t\t\t\treturn inverse;\n\t\t\t\t}\n\t\t\t};\n\n\t\t}\n\t}\n}\n\n\n#endif\n", "meta": {"hexsha": "50f771664a88ad8f7c56ec2e4d02ffa5d4b254b7", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/detail/inverse_impl.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_stars_repo_licenses": ["MIT"], "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/include/openOR/Math/detail/inverse_impl.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "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/include/openOR/Math/detail/inverse_impl.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["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.7542372881, "max_line_length": 124, "alphanum_fraction": 0.579301423, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6906859855033097}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Regular_triangulation_2.h>\n#include <CGAL/boost/graph/graph_traits_Regular_triangulation_2.h>\n#include <CGAL/internal/boost/function_property_map.hpp>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <map>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel     K;\ntypedef K::FT                                                   FT;\ntypedef K::Weighted_point_2                                     Weighted_point;\n\ntypedef CGAL::Regular_triangulation_2<K>                        Triangulation;\n\ntypedef boost::graph_traits<Triangulation>::vertex_descriptor   vertex_descriptor;\ntypedef boost::graph_traits<Triangulation>::vertex_iterator     vertex_iterator;\ntypedef boost::graph_traits<Triangulation>::edge_descriptor     edge_descriptor;\n\ntemplate <typename T>\nstruct Compute_edge_weight\n{\n  const T& t_;\n\n  Compute_edge_weight(const T& t) : t_(t) { }\n\n  typedef typename boost::graph_traits<T>::vertex_descriptor vertex_descriptor;\n  typedef typename boost::graph_traits<T>::edge_descriptor   edge_descriptor;\n\n  FT operator()(const edge_descriptor ed) const {\n    vertex_descriptor svd = source(ed, t_);\n    vertex_descriptor tvd = target(ed, t_);\n    typename T::Vertex_handle sv = svd;\n    typename T::Vertex_handle tv = tvd;\n    return CGAL::power_product(sv->point(), tv->point());\n  }\n};\n\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map<vertex_descriptor,int> VertexIndexMap;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\n\nint main(int argc,char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/weighted_points.xyw\";\n  std::ifstream input(filename);\n  Triangulation tr;\n\n  Weighted_point wp;\n  while(input >> wp)\n    tr.insert(wp);\n\n  // Note that with the input \"data/weighted_points.xyw\", there is one hidden vertex\n  std::cout << \"number of hidden vertices: \" << tr.number_of_hidden_vertices() << std::endl;\n\n  // Associate indices to the vertices\n  VertexIndexMap vertex_id_map;\n  VertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n  int index = 0;\n\n  for(vertex_descriptor vd : vertices(tr))\n    vertex_id_map[vd]= index++;\n\n  // We use a custom edge length property map that computes the power distance\n  // between the extremities of an edge of the regular triangulation\n  typedef Compute_edge_weight<Triangulation> Edge_weight_functor;\n\n  // In the function call you can see a named parameter: vertex_index_map\n  std::list<edge_descriptor> mst;\n  boost::kruskal_minimum_spanning_tree(tr, std::back_inserter(mst),\n                                       vertex_index_map(vertex_index_pmap)\n                                       .weight_map(CGAL::internal::boost_::make_function_property_map<\n                                          edge_descriptor, FT, Edge_weight_functor>(Edge_weight_functor(tr))));\n\n  std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n  for(edge_descriptor ed : mst)\n  {\n    vertex_descriptor svd = source(ed, tr);\n    vertex_descriptor tvd = target(ed, tr);\n    Triangulation::Vertex_handle sv = svd;\n    Triangulation::Vertex_handle tv = tvd;\n    std::cout << \"[ \" << sv->point() << \"  |  \" << tv->point() << \" ] \" << std::endl;\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "40f9af43377274fedeb3c71efe1a66c0bce26bd9", "size": 3456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/BGL_triangulation_2/emst_regular.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/BGL_triangulation_2/emst_regular.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/BGL_triangulation_2/emst_regular.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": 37.1612903226, "max_line_length": 111, "alphanum_fraction": 0.6996527778, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6906724490098937}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/LinearStateModel.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nvoid LinearStateModel::propagate(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> pred_states)\n{\n    pred_states = getStateTransitionMatrix() * cur_states;\n}\n", "meta": {"hexsha": "45df7c3b82fefe5949899c7912049988870afeea", "size": 524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LinearStateModel.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "src/BayesFilters/src/LinearStateModel.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "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/BayesFilters/src/LinearStateModel.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 26.2, "max_line_length": 126, "alphanum_fraction": 0.7595419847, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.69067244088226}}
{"text": "/**\n * \\file Chebyshev1Filter.hxx\n */\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n\n#include <ATK/EQ/Chebyshev1Filter.h>\n#include <ATK/EQ/helpers.h>\n\nnamespace Chebyshev1Utilities\n{\n  template<typename DataType>\n  void create_chebyshev1_analog_coefficients(int order, DataType ripple, EQUtilities::ZPK<DataType>& zpk)\n  {\n    zpk.z.clear(); // no zeros for this filter type\n    zpk.p.clear();\n    if(ripple == 0)\n    {\n      return;\n    }\n    if(order == 0)\n    {\n      zpk.k = static_cast<DataType>(std::pow(10, (-ripple / 20)));\n      return;\n    }\n    \n    DataType eps = static_cast<DataType>(std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0));\n    DataType mu = static_cast<DataType>(1.0 / order * boost::math::asinh(1 / eps));\n    \n    for(gsl::index i = -order+1; i < order; i += 2)\n    {\n      DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);\n      zpk.p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));\n    }\n\n    std::complex<DataType> f = 1;\n    \n    for(gsl::index i = 0; i < zpk.p.size(); ++i)\n    {\n      f *= -zpk.p[i];\n    }\n    zpk.k = f.real();\n    if(order % 2 == 0)\n    {\n      zpk.k = zpk.k / std::sqrt(1 + eps * eps);\n    }\n  }\n  \n  template<typename DataType, typename Container>\n  void create_default_chebyshev1_coeffs(size_t order, DataType ripple, DataType Wn, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order), ripple, zpk);\n    EQUtilities::populate_lp_coeffs(Wn, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n  \n  template<typename DataType, typename Container>\n  void create_bp_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order/2), ripple, zpk);\n    EQUtilities::populate_bp_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n  \n  template<typename DataType, typename Container>\n  void create_bs_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order/2), ripple, zpk);\n    EQUtilities::populate_bs_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1LowPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1LowPassCoefficients<DataType_>::CoeffDataType Chebyshev1LowPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1LowPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1LowPassCoefficients<DataType_>::CoeffDataType Chebyshev1LowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void Chebyshev1LowPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev1LowPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void Chebyshev1LowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev1Utilities::create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1HighPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1HighPassCoefficients<DataType_>::CoeffDataType Chebyshev1HighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1HighPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1HighPassCoefficients<DataType_>::CoeffDataType Chebyshev1HighPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1HighPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev1HighPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void Chebyshev1HighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev1Utilities::create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(gsl::index i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n  \n  template <typename DataType>\n  Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n  \n  template <typename DataType_>\n  std::pair<typename Chebyshev1BandPassCoefficients<DataType_>::CoeffDataType, typename Chebyshev1BandPassCoefficients<DataType_>::CoeffDataType> Chebyshev1BandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1BandPassCoefficients<DataType_>::CoeffDataType Chebyshev1BandPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev1BandPassCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev1Utilities::create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n  \n  template <typename DataType_>\n  std::pair<typename Chebyshev1BandStopCoefficients<DataType_>::CoeffDataType, typename Chebyshev1BandStopCoefficients<DataType_>::CoeffDataType> Chebyshev1BandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev1BandStopCoefficients<DataType_>::CoeffDataType Chebyshev1BandStopCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandStopCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev1BandStopCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev1Utilities::create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n}\n", "meta": {"hexsha": "3c973c244f7fcbf255a032cd32ded3ddde0afde8", "size": 10729, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 30.4801136364, "max_line_length": 216, "alphanum_fraction": 0.7222481126, "num_tokens": 2916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.690672432334221}}
{"text": "#ifndef CONSTANTS_HPP_\n#define CONSTANTS_HPP_\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions.hpp>\n#include <complex> // constant::i\n#include <limits> // constant::omega\n#include <string> // constant::omega\n\nnamespace constant {\n\ntemplate<typename T> T alladi_grinstead() {\n\tT c = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || c != last; ++n) {\n\t\tlast = c;\n\t\tc += (boost::math::zeta<T>(n + 1) - 1) / n;\n\t}\n\n\tstatic const T ALLADI_GRINSTEAD = exp(c - 1);\n\treturn ALLADI_GRINSTEAD;\n}\n\ntemplate<typename T> T aperys() {\n\tstatic const T APERYS = boost::math::constants::zeta_three<T>();\n\treturn APERYS;\n}\n\ntemplate<typename T> T buffons() {\n\tstatic const T BUFFONS = 2 / boost::math::constants::pi<T>();\n\treturn BUFFONS;\n}\n\ntemplate<typename T> T catalans() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tCATALANS = 0.125 * (boost::math::trigamma<T>(0.25) - PI_SQR);\n\treturn CATALANS;\n}\n\ntemplate<typename T> T delian() {\n\tstatic const T DELIAN = boost::math::cbrt<T>(2);\n\treturn DELIAN;\n}\n\ntemplate<typename T> T e() {\n\tstatic const T E = boost::math::constants::e<T>();\n\treturn E;\n}\n\ntemplate<typename T> T erdos_borwein() {\n\tT e = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || e != last; ++n) {\n\t\tlast = e;\n\t\te += 1 / (exp2(static_cast<T>(n)) - 1);\n\t}\n\n\tstatic const T ERDOS_BORWEIN = e;\n\treturn ERDOS_BORWEIN;\n}\n\ntemplate<typename T> T euler_mascheroni() {\n\tstatic const T EULER_MASCHERONI = boost::math::constants::euler<T>();\n\treturn EULER_MASCHERONI;\n}\n\ntemplate<typename T> T gauss() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two<T>(),\n\t\tPI = boost::math::constants::pi<T>(),\n\t\tGAUSS = pow(boost::math::tgamma<T>(0.25), 2)\n\t\t\t/ (2 * ROOT_TWO * pow(PI, static_cast<T>(1.5)));\n\treturn GAUSS;\n}\n\ntemplate<typename T> T gelfond_schneider() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two<T>(),\n\t\tGELFOND_SCHNEIDER = exp2(ROOT_TWO);\n\treturn GELFOND_SCHNEIDER;\n}\n\ntemplate<typename T> T gelfonds() {\n\tstatic const T GELFONDS = boost::math::constants::e_pow_pi<T>();\n\treturn GELFONDS;\n}\n\ntemplate<typename T> T giesekings() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three<T>(),\n\t\tGIESEKINGS = (9 - boost::math::trigamma<T>(2 / static_cast<T>(3))\n\t\t\t+ boost::math::trigamma<T>(4 / static_cast<T>(3)))\n\t\t\t/ (4 * ROOT_THREE);\n\treturn GIESEKINGS;\n}\n\ntemplate<typename T> T glaisher_kinkelin() {\n\tstatic const T GLAISHER_KINKELIN = boost::math::constants::glaisher<T>();\n\treturn GLAISHER_KINKELIN;\n}\n\ntemplate<typename T> T golden_ratio() {\n\tstatic const T GOLDEN_RATIO = boost::math::constants::phi<T>();\n\treturn GOLDEN_RATIO;\n}\n\ntemplate<typename T> std::complex<T> i() {\n\tstatic const std::complex<T> I(0, 1);\n\treturn I;\n}\n\ntemplate<typename T> T inverse_golden_ratio() {\n\tstatic const T INVERSE_GOLDEN_RATIO = boost::math::constants::phi<T>() - 1;\n\treturn INVERSE_GOLDEN_RATIO;\n}\n\ntemplate<typename T> T khinchin() {\n\tstatic const T KHINCHIN = boost::math::constants::khinchin<T>();\n\treturn KHINCHIN;\n}\n\n// Not Levy constant\ntemplate<typename T> T khinchin_levy() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tLN_TWO = boost::math::constants::ln_two<T>(),\n\t\tKHINCHIN_LEVY = PI_SQR / (12 * LN_TWO);\n\treturn KHINCHIN_LEVY;\n}\n\n// Not Glaisher-Kinkelin constant\ntemplate<typename T> T kinkelin() {\n\tstatic const T GLAISHER_KINKELIN = boost::math::constants::glaisher<T>(),\n\t\tKINKELIN = 1 / static_cast<T>(12) - log(GLAISHER_KINKELIN);\n\treturn KINKELIN;\n}\n\ntemplate<typename T> T knuth() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three<T>(),\n\t\tKNUTH = (1 - (1 / ROOT_THREE)) / 2;\n\treturn KNUTH;\n}\n\ntemplate<typename T> T levys() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tLN_TWO = boost::math::constants::ln_two<T>(),\n\t\tLEVYS = exp(PI_SQR / (12 * LN_TWO));\n\treturn LEVYS;\n}\n\ntemplate<typename T> T liebs() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three<T>(),\n\t\tLIEBS = (8 * ROOT_THREE) / 9;\n\treturn LIEBS;\n}\n\ntemplate<typename T> T lochs() {\n\tstatic const T LN_TWO = boost::math::constants::ln_two<T>(),\n\t\tLN_TEN = boost::math::constants::ln_ten<T>(),\n\t\tPI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tLOCHS = (6 * LN_TWO * LN_TEN) / PI_SQR;\n\treturn LOCHS;\n}\n\ntemplate<typename T> T niven() {\n\tT c = 1, last;\n\n\tfor(std::size_t j = 2; j == 2 || c != last; ++j) {\n\t\tlast = c;\n\t\tc += 1 - 1/boost::math::zeta<T>(j);\n\t}\n\n\tstatic const T NIVEN = c;\n\treturn NIVEN;\n}\n\ntemplate<typename T> T nortons() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tLN_PI = log(boost::math::constants::pi<T>()),\n\t\tEULER = boost::math::constants::euler<T>(),\n\t\tLN_GLAISHER_KINKELIN = log(boost::math::constants::glaisher<T>()),\n\t\tLN_TWO = boost::math::constants::ln_two<T>(),\n\t\tNORTONS = (6 * LN_TWO\n\t\t\t* (24 * LN_GLAISHER_KINKELIN - 3 + 2 * EULER + LN_TWO - 2 * LN_PI)\n\t\t\t- PI_SQR) / PI_SQR;\n\treturn NORTONS;\n}\n\ntemplate<typename T> T omega() {\n\tT w = 0;\n\tstd::string w_pre, w_post;\n\n\tw_pre.reserve(std::numeric_limits<T>::digits10);\n\tw_post.reserve(std::numeric_limits<T>::digits10);\n\n\tdo {\n\t\tw_pre = static_cast<std::string>(w);\n\t\tw_pre.resize(std::numeric_limits<T>::digits10);\n\n\t\tconst T e_w = exp(w);\n\n\t\tw -= ((w * e_w) - 1)\n\t\t\t/ (e_w * (w + 1) - ((w + 2) * (w * e_w - 1) / ((w * 2) + 2)));\n\n\t\tw_post = static_cast<std::string>(w);\n\t\tw_post.resize(std::numeric_limits<T>::digits10);\n\t} while (w_pre != w_post);\n\n\tstatic const T OMEGA = w;\n\treturn OMEGA;\n}\n\ntemplate<typename T> T one() {\n\tstatic const T ONE = 1;\n\treturn ONE;\n}\n\ntemplate<typename T> T pi() {\n\tstatic const T PI = boost::math::constants::pi<T>();\n\treturn PI;\n}\n\ntemplate<typename T> T plastic_number() {\n\tstatic const T PLASTIC_NUMBER = (boost::math::cbrt<T>(108 + 12\n\t\t* sqrt(static_cast<T>(69))) + boost::math::cbrt<T>(108 - 12\n\t\t* sqrt(static_cast<T>(69)))) / static_cast<T>(6);\n\treturn PLASTIC_NUMBER;\n}\n\ntemplate<typename T> T pogsons() {\n\tstatic const T POGSONS = pow(10, 2 / static_cast<T>(5));\n\treturn POGSONS;\n}\n\ntemplate<typename T> T polyas_random_walk() {\n\tstatic const T PI_CUBED = boost::math::constants::pi_cubed<T>(),\n\t\tROOT_SIX = sqrt(static_cast<T>(6)),\n\t\tPOLYAS_RANDOM_WALK = 1 - 1/((ROOT_SIX / (32 * PI_CUBED))\n\t\t\t* boost::math::tgamma<T>(1 / static_cast<T>(24))\n\t\t\t* boost::math::tgamma<T>(5 / static_cast<T>(24))\n\t\t\t* boost::math::tgamma<T>(7 / static_cast<T>(24))\n\t\t\t* boost::math::tgamma<T>(11 / static_cast<T>(24)));\n\treturn POLYAS_RANDOM_WALK;\n}\n\ntemplate<typename T> T porters() {\n\tstatic const T LN_TWO = boost::math::constants::ln_two<T>(),\n\t\tLN_GLAISHER_KINKELIN = log(boost::math::constants::glaisher<T>()),\n\t\tLN_PI = log(boost::math::constants::pi<T>()),\n\t\tPI_SQR = boost::math::constants::pi_sqr<T>(),\n\t\tPORTERS = (6 * LN_TWO * (48 * LN_GLAISHER_KINKELIN\n\t\t\t- LN_TWO - 4 * LN_PI - 2)) / PI_SQR - 0.5;\n\treturn PORTERS;\n}\n\ntemplate<typename T> T prince_ruperts_cube() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two<T>(),\n\t\tPRINCE_RUPERTS_CUBE = (3 * ROOT_TWO) / 4;\n\treturn PRINCE_RUPERTS_CUBE;\n}\n\ntemplate<typename T> T pythagoras() {\n\tstatic const T PYTHAGORAS = boost::math::constants::root_two<T>();\n\treturn PYTHAGORAS;\n}\n\ntemplate<typename T> T robbins() {\n\tstatic const T PI = boost::math::constants::pi<T>(),\n\t\tROOT_TWO = boost::math::constants::root_two<T>(),\n\t\tROOT_THREE = boost::math::constants::root_three<T>(),\n\t\tROBBINS = ((4 + 17 * ROOT_TWO - 6 * ROOT_THREE - 7 * PI) / 105)\n\t\t\t+ (log1p(ROOT_TWO) / 5) + ((2 * log(2 + ROOT_THREE)) / 5);\n\treturn ROBBINS;\n}\n\ntemplate<typename T> T sierpinski_k() {\n\tstatic const T PI = boost::math::constants::pi<T>(),\n\t\tPI_CUBED = boost::math::constants::pi_cubed<T>(),\n\t\tEULER = boost::math::constants::euler<T>(),\n\t\tSIERPINSKI_K = PI * log((4 * PI_CUBED * exp(2 * EULER))\n\t\t\t/ pow(boost::math::tgamma<T>(0.25), 4));\n\treturn SIERPINSKI_K;\n}\n\ntemplate<typename T> T sierpinski_s() {\n\tstatic const T PI_CUBED = boost::math::constants::pi_cubed<T>(),\n\t\tEULER = boost::math::constants::euler<T>(),\n\t\tSIERPINSKI_S = log((4 * PI_CUBED * exp(2 * EULER))\n\t\t\t/ pow(boost::math::tgamma<T>(0.25), 4));\n\treturn SIERPINSKI_S;\n}\n\ntemplate<typename T> T silver_ratio() {\n\tstatic const T SILVER_RATIO = boost::math::constants::root_two<T>() + 1;\n\treturn SILVER_RATIO;\n}\n\ntemplate<typename T> T theodorus() {\n\tstatic const T THEODORUS = boost::math::constants::root_three<T>();\n\treturn THEODORUS;\n}\n\ntemplate<typename T> T twenty_vertex_entropy() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three<T>(),\n\t\tTWENTY_VERTEX_ENTROPY = (3 * ROOT_THREE) / 2;\n\treturn TWENTY_VERTEX_ENTROPY;\n}\n\ntemplate<typename T> T weierstrass() {\n\tstatic const T ROOT_PI = boost::math::constants::root_pi<T>(),\n\t\tPI = boost::math::constants::pi<T>(),\n\t\tWEIERSTRASS = (exp2(static_cast<T>(1.25)) * ROOT_PI\n\t\t\t* exp(PI / 8)) / pow(boost::math::tgamma<T>(0.25), 2);\n\treturn WEIERSTRASS;\n}\n\ntemplate<typename T> T wylers() {\n\tstatic const T PI = boost::math::constants::pi<T>(),\n\t\tWYLERS = (9 / (8 * pow(PI, 4))) * pow(pow(PI, 5) / 1920, 0.25);\n\treturn WYLERS;\n}\n\ntemplate<typename T> T zero() {\n\tstatic const T ZERO = 0;\n\treturn ZERO;\n}\n\n} // namespace constant\n\nnamespace constant {\nnamespace func {\n\n// use std::uint_fastNN_t if you believe it helps\ntemplate<typename T, typename A = unsigned>\nT champernowne(const A & b = 10) {\n\tT c = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || c != last; ++n) {\n\t\tT sub = 0;\n\n\t\tfor(std::size_t k = 1; k <= n; ++k) {\n\t\t\tsub += floor(log(k) / log(b));\n\t\t}\n\n\t\tlast = c;\n\t\tc += n / pow(b, n + sub);\n\t}\n\n\treturn c;\n}\n\n// throws error if r is negative and even\ntemplate<typename T, typename A = unsigned>\nT favard(const A & r = 2) {\n\tstatic const T PI = boost::math::constants::pi<T>();\n\n\tif (r == 0) {\n\t\treturn 1;\n\t} else if (r % 2) { // odd (dirichlet lambda)\n\t\treturn (4 / PI) * ((1 - exp2(-(static_cast<T>(r) + 1)))\n\t\t\t* boost::math::zeta<T>(r + 1));\n\t} else { // even (dirichlet beta)\n\t\treturn (-4 / PI) * (pow(-2, static_cast<T>(-2) * (r + 1))\n\t\t\t/ boost::math::tgamma<T>(r + 1))\n\t\t\t* (boost::math::polygamma<T>(r, 0.25)\n\t\t\t- boost::math::polygamma<T>(r, 0.75));\n\t}\n}\n\n\n} // namespace func\n} // namespace constant\n\n#endif // CONSTANTS_HPP_\n", "meta": {"hexsha": "f6a521aef83659f30a8845483151eb1f7819885a", "size": 10082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "constants.hpp", "max_stars_repo_name": "esote/mathematical-constants", "max_stars_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constants.hpp", "max_issues_repo_name": "esote/mathematical-constants", "max_issues_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "constants.hpp", "max_forks_repo_name": "esote/mathematical-constants", "max_forks_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_forks_repo_licenses": ["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.1752021563, "max_line_length": 76, "alphanum_fraction": 0.651458044, "num_tokens": 3333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.690652134767157}}
{"text": "#include <cmath>\n#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <boost/functional/hash.hpp>\n\nstruct Coord {\n    int x = 0;\n    int y = 0;\n\n    bool operator== (const Coord& o) const {\n        return x == o.x && y == o.y;\n    }\n};\n\nstruct pair_hash {\n    size_t operator()(const Coord& c) const {\n        size_t seed = 0;\n        boost::hash_combine(seed, c.x);\n        boost::hash_combine(seed, c.y);\n        return seed;\n    }\n};\nusing Map = std::unordered_map<Coord, uint64_t, pair_hash>;\nMap gMap;\n\nvoid report(const Coord& c) {\n    std::cout << \"X: \" << c.x << \", Y: \" << c.y << \", V: \" << gMap[c] << \"\\n\";\n}\n\nuint64_t sumNeigh(const Coord& c) {\n    static Coord null{0, 0};\n    if (c == null) {\n        return 1;\n    }\n    return gMap[{c.x, c.y + 1}]\n         + gMap[{c.x, c.y - 1}]\n         + gMap[{c.x + 1, c.y + 1}]\n         + gMap[{c.x + 1, c.y - 1}]\n         + gMap[{c.x - 1, c.y + 1}]\n         + gMap[{c.x - 1, c.y - 1}]\n         + gMap[{c.x - 1, c.y}]\n         + gMap[{c.x + 1, c.y}];\n}\n\nvoid Spiral(int X, int Y, int target) {\n    int x, y, dx, dy;\n    x = y = dx = 0;\n    dy         = -1;\n    int t      = std::max(X, Y);\n    int maxI   = t * t;\n    for (int i = 0; i < maxI; i++) {\n        if ((-X / 2 <= x) && (x <= X / 2) && (-Y / 2 <= y) && (y <= Y / 2)) {\n            Coord c{x, y};\n            auto V = gMap[c] = sumNeigh(c);\n            if (V > target) {\n                report(c);\n                return;\n            }\n        }\n        if ((x == y) || ((x < 0) && (x == -y)) || ((x > 0) && (x == 1 - y))) {\n            t  = dx;\n            dx = -dy;\n            dy = t;\n        }\n        x += dx;\n        y += dy;\n    }\n}\n\nint main() {\n    std::vector<int> inputs{325489};\n    for (auto n : inputs) {\n        std::cout << \"input: \" << n << \"; \";\n        Spiral(800, 800, n);\n    }\n}\n", "meta": {"hexsha": "dc96161afcb985ffe998dbff0d1cd586e4566d7f", "size": 1831, "ext": "cc", "lang": "C++", "max_stars_repo_path": "puzzle_03_2.cc", "max_stars_repo_name": "mody/Advent-of-Code-2017", "max_stars_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "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": "puzzle_03_2.cc", "max_issues_repo_name": "mody/Advent-of-Code-2017", "max_issues_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "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": "puzzle_03_2.cc", "max_forks_repo_name": "mody/Advent-of-Code-2017", "max_forks_repo_head_hexsha": "446300f2562ad56c3da14644111d06ea4d0303f8", "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.4743589744, "max_line_length": 78, "alphanum_fraction": 0.403058438, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6906432000830811}}
{"text": "#include <igl/doublearea.h>\n#include <igl/internal_angles.h>\n#include <igl/is_irregular_vertex.h>\n#include <igl/readOBJ.h>\n#include <igl/PI.h>\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"tutorial_shared_path.h\"\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n\n  MatrixXd V;\n  MatrixXi F;\n\n  igl::readOBJ(TUTORIAL_SHARED_PATH \"/horse_quad.obj\",V,F);\n\n  // Count the number of irregular vertices, the border is ignored\n  vector<bool> irregular = igl::is_irregular_vertex(V,F);\n\n  int vertex_count = V.rows();\n  int irregular_vertex_count = \n    std::count(irregular.begin(),irregular.end(),true);\n  double irregular_ratio = double(irregular_vertex_count)/vertex_count;\n\n  printf(\"Irregular vertices: \\n%d/%d (%.2f%%)\\n\",\n    irregular_vertex_count,vertex_count, irregular_ratio*100);\n\n  // Compute areas, min, max and standard deviation\n  VectorXd area;\n  igl::doublearea(V,F,area);\n  area = area.array() / 2;\n\n  double area_avg   = area.mean();\n  double area_min   = area.minCoeff() / area_avg;\n  double area_max   = area.maxCoeff() / area_avg;\n  double area_sigma = sqrt(((area.array()-area_avg)/area_avg).square().mean());\n\n  printf(\"Areas (Min/Max)/Avg_Area Sigma: \\n%.2f/%.2f (%.2f)\\n\",\n    area_min,area_max,area_sigma);\n\n  // Compute per face angles, min, max and standard deviation\n  MatrixXd angles;\n  igl::internal_angles(V,F,angles);\n  angles = 360.0 * (angles/(2*igl::PI)); // Convert to degrees\n\n  double angle_avg   = angles.mean();\n  double angle_min   = angles.minCoeff();\n  double angle_max   = angles.maxCoeff();\n  double angle_sigma = sqrt( (angles.array()-angle_avg).square().mean() );\n\n  printf(\"Angles in degrees (Min/Max) Sigma: \\n%.2f/%.2f (%.2f)\\n\",\n    angle_min,angle_max,angle_sigma);\n\n}\n", "meta": {"hexsha": "eba95cc460ef45dabf03b61bd6b897001350219e", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/701_Statistics/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/701_Statistics/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/tutorial/701_Statistics/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["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.813559322, "max_line_length": 79, "alphanum_fraction": 0.6969869244, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6906431907697526}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <typeinfo>\n#include <iostream>\n#include <cassert>\n#include <boost/numeric/mtl/mtl.hpp>\n\nstruct poisson2D_dirichlet\n{\n    poisson2D_dirichlet(int m, int n) : m(m), n(n) {}\n\n    template <typename Vector>\n    Vector operator*(const Vector& v) const\n    {\n\tassert(int(size(v)) == m * n);\n\tVector w(m * n);\n\t\n\tfor (int i= 0; i < m; i++)\n\t    for (int j= 0; j < n; j++) {\n\t\tint k= i * n + j; // offset\n\t\tw[k]= 4 * v[k];\n\t\tif (i > 0) w[k]-= v[k-n];   // upper neighbor\n\t\tif (i < m-1) w[k]-= v[k+n]; // lower neighbor\n\t\tif (j > 0) w[k]-= v[k-1];   // left neighbor\n\t\tif (j < n-1) w[k]-= v[k+1]; // right neighbor\n\t    }\n\treturn w;\n    }\n    int m, n;\n};\n\nnamespace mtl { namespace ashape {\n    template <> struct ashape_aux<poisson2D_dirichlet> \n    {\ttypedef nonscal type;    };\n}}\n\nint main(int, char**)\n{\n    using namespace std;\n    \n    mtl::compressed2D<double> A0;\n    laplacian_setup(A0, 4, 5);\n    cout << \"A0 is\\n\" << A0 << endl;\n\n    mtl::dense_vector<double> v(20);\n    iota(v);\n    cout << \"v is \" << v << endl;\n\n    mtl::dense_vector<double> w1(A0 * v);\n    cout << \"A0 * v is \" << w1 << endl;\n\n    poisson2D_dirichlet A(4, 5);\n    mtl::dense_vector<double> w2(A * v);\n    cout << \"A * v is \" << w2 << endl;\n\n    w1-= w2;\n    if (one_norm(w1) > 0.001) throw \"Wrong result\";\n\n    return 0;\n}\n", "meta": {"hexsha": "afb153e2dcb68134ff7e9c6fda3a67deb8f527be", "size": 1751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_free_1_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/matrix_free_1_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/matrix_free_1_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": 24.661971831, "max_line_length": 94, "alphanum_fraction": 0.5830953741, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6906431907697526}}
{"text": "#include <armadillo>\n\n#include <mona/utility.hpp>\n#include <mona/line.hpp>\n#include <mona/targets/window.hpp>\n#include <mona/axes.hpp>\n#include <mona/colors.hpp>\n\n\nauto fit(const arma::fvec& x, const arma::fvec& y) -> arma::fvec\n{\n    auto xx = x - arma::mean(x);\n    auto yy = y - arma::mean(y);\n    float b = arma::sum(xx % yy) / arma::sum(xx % xx);\n    float a = arma::mean(y) - b * arma::mean(x);\n    return a + b * x;\n}\n\n\nauto random(arma::fvec x, float mean, float std)\n{\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<> dis(mean, std);\n\n    for(auto& e: x)\n    {\n        e += dis(gen);\n    }\n\n    return x;\n}\n\n\nint main()\n{\n    arma::fvec x = mona::linspace(-4, 4, 15);\n    arma::fvec y = random(x, 0, 0.9);\n\n    auto target = mona::targets::window();\n    auto cam = mona::camera();\n    auto axes = mona::axes();\n\n    auto dots = mona::dots(x, y, mona::colors::tomato);\n    auto line = mona::line(x, fit(x, y), mona::colors::tomato);\n\n    float delta = 0;\n    while (target.active())\n    {\n        axes.submit(dots);\n        axes.submit(line);\n\n        cam = target.control_camera(cam);\n        target.submit(axes);\n        target.draw();\n    }\n}", "meta": {"hexsha": "a22c88d72069ebc0a2e3ae2a9becc8158ebbaf6e", "size": 1190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/scatter_plot/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/scatter_plot/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/scatter_plot/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8771929825, "max_line_length": 64, "alphanum_fraction": 0.5647058824, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6906374288155968}}
{"text": "//////////////////////////////////\n//\n// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5 -lboost_timer\n//\n//////////////////////////////////\n\n#include <iostream>\t\t// std::cout\n#include <fstream>\t\t// std::ifsteam\n#include <utility>\t\t// std::pair\n#include <vector>\t\t// std::vector\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp> \n#include <boost/spirit/include/qi.hpp>\n#include <boost/timer/timer.hpp>\n\nint main(int argc, char*argv[]){\n  \n  if (argc != 2)\n  {\n    std::cerr << \"No file!!!\" << std::endl;\n    return -1;\n  }\n  \n  std::ifstream file(argv[1]); // std::ifstream::in ??\n  std::string str;\n  \n  boost::timer::cpu_timer timer;\n\n  /* start get number of edges */\n  getline(file, str);\n\n  using namespace boost::spirit;\n  using qi::int_;\n  using qi::double_;\n  using qi::parse;\n  \n  int n;\n\n  auto it = str.begin();\n  bool r = parse(it, str.end(),\n\t\t int_[([&n](int i){n = i;})] >> int_);  \n  /* end get number of edges */\n  \n  \n  /* start get list of edges and weights */\n  typedef std::pair<int, int> Edge;\n  std::vector<Edge> Edges; // vector to store std::pair of edges.\n  std::vector<int> Weights; // vector to weights as integers.\n  \n  while (getline(file,str)){ // get graph line-by-line.\n    int Vert1;\n    int Vert2;\n    double Weight; // are all weights integer-valued ??\n    \n    auto it = str.begin(); // initialize iterator for qi::parse. \n    \n    bool r = parse(it, str.end(), // parse graph.\n\t\t int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);  \n    \n    Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.\n    Edges.push_back(edge);\n    Weights.push_back(Weight);\n  }\n  /* end get list of edges and weights */\n  \n  \n  typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty; // initialize type to store weights on edges.\n  // adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph; // create graph.\n\n  Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.\n \n  \n  // here, the graph should be built... Find shortest path.\n  typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.\n  std::vector<vertex_descriptor> parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.\n  std::vector<int> distances(boost::num_vertices(g));\n  \n  \n  // find shortest distances.\n  boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));\n\n  /* start find longest-shortest path */\n  int maxDistance = 0;\n  int maxVertex = 0;\n  \n  // create iterator over vertices.\n  // vertexPair.first is the iterated element, and .second is the end-index of all vertices.\n  typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;\n  std::pair<vertex_iter, vertex_iter> vertexPair;\n  \n  for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.\n  {\n    // replace maxDistance if a greater distance is found, and maxDistance must be less than \"infinity\" (of 32-bit signed integer).\n    if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){\n      maxDistance = distances[*vertexPair.first];\n      maxVertex = *vertexPair.first;\n    }\n    // if distance == maxDistance, check if vertex index is smaller.\n    if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){\n      maxVertex = *vertexPair.first;\n    }\n  }\n  \n  boost::timer::cpu_times times = timer.elapsed();\n  \n  // output vertex and distance of the longest-shortest path.\n  std::cout << \"RESULT VERTEX \" << maxVertex << std::endl;\n  std::cout << \"RESULT DIST \" << maxDistance <<  std::endl;\n  /* end find longest-shortest path */\n\n  // print CPU- and Wall-Time. \n  // boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.\n  std::cout << std::endl;\n  std::cout << \"WALL-CLOCK \" << times.wall / 1e9 << \"s\" << std::endl;\n  std::cout << \"USER TIME \" << times.user / 1e9 << \"s\" << std::endl;\n  \n  file.close();  \n  return 0;\n}\n", "meta": {"hexsha": "a4bde7f12e04a09af3071fd22e1446b2fa02d508", "size": 4477, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "RayChew/Ex5/ex5.cxx", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "RayChew/Ex5/ex5.cxx", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "RayChew/Ex5/ex5.cxx", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 36.3983739837, "max_line_length": 160, "alphanum_fraction": 0.6537860174, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6906374241195428}}
{"text": "/**\n * \\file SinusGeneratorFilter.cpp\n */\n\n#include \"SinusGeneratorFilter.h\"\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  SinusGeneratorFilter<DataType_>::SinusGeneratorFilter()\n  :Parent(0, 2), volume(1), offset(0), frequency(0), frequ_cos(1), frequ_sin(0), cos(1), sin(0)\n  {\n  }\n  \n  template<typename DataType_>\n  SinusGeneratorFilter<DataType_>::~SinusGeneratorFilter()\n  {\n  }\n  \n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_frequency(DataType_ frequency)\n  {\n    this->frequency = frequency;\n    this->frequ_cos = std::cos(2 * boost::math::constants::pi<DataType_>() * frequency / output_sampling_rate);\n    this->frequ_sin = std::sin(2 * boost::math::constants::pi<DataType_>() * frequency / output_sampling_rate);\n    Parent::setup();\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_frequency() const\n  {\n    return frequency;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_volume(DataType_ volume)\n  {\n    this->volume = volume;\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_volume() const\n  {\n    return volume;\n  }\n  \n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::set_offset(DataType_ offset)\n  {\n    this->offset = offset;\n  }\n  \n  template<typename DataType_>\n  DataType_ SinusGeneratorFilter<DataType_>::get_offset() const\n  {\n    return offset;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::full_setup()\n  {\n    Parent::full_setup();\n    cos = 1;\n    sin = 0;\n  }\n\n  template<typename DataType_>\n  void SinusGeneratorFilter<DataType_>::process_impl(int64_t size) const\n  {\n    DataType* ATK_RESTRICT output_cos = outputs[0];\n    DataType* ATK_RESTRICT output_sin = outputs[1];\n\n    for(int64_t i = 0; i < size; ++i)\n    {\n      auto new_cos = cos * frequ_cos - sin * frequ_sin;\n      auto new_sin = cos * frequ_sin + sin * frequ_cos;\n      auto norm = (new_cos * new_cos + new_sin * new_sin);\n\n      cos = new_cos / norm;\n      sin = new_sin / norm;\n\n      *(output_cos++) = volume * cos + offset;\n      *(output_sin++) = volume * sin + offset;\n    }\n  }\n  \n  template class SinusGeneratorFilter<float>;\n  template class SinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "6a8c1014e8cc799e467f4e4af4731e40ab380ac4", "size": 2337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "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": "ATK/Tools/SinusGeneratorFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 24.8617021277, "max_line_length": 111, "alphanum_fraction": 0.6884895165, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6905998683094975}}
{"text": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include <pinocchio/math/rotation.hpp>\n#include <pinocchio/math/sincos.hpp>\n#include <Eigen/Geometry>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_toRotationMatrix)\n{\n  using namespace pinocchio;\n  const int max_tests = 1e5;\n  for(int k = 0; k < max_tests; ++k)\n  {\n    const double theta = std::rand();\n    double cos_value, sin_value;\n    \n    pinocchio::SINCOS(theta,&sin_value,&cos_value);\n    Eigen::Vector3d axis(Eigen::Vector3d::Random().normalized());\n\n    Eigen::Matrix3d rot; toRotationMatrix(axis,cos_value,sin_value,rot);\n    Eigen::Matrix3d rot_ref = Eigen::AngleAxisd(theta,axis).toRotationMatrix();\n    \n    BOOST_CHECK(rot.isApprox(rot_ref));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "c754e20e08f9a7bc9d0a49ba03b31a5c5bbcf4a5", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rotation.cpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/rotation.cpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/rotation.cpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 23.2368421053, "max_line_length": 79, "alphanum_fraction": 0.7225368063, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6904868518111097}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n// Set the parameters |i|, |j|, and |k| to be the indices of the grid cell\n// containing the point |p| for a grid with lower corner |lc| and grid cell\n// width (spacing) |dx|.\ninline void floor(const Eigen::Vector3d& p, const Eigen::Vector3d& lc,\n                  double dx, int& i, int& j, int& k) {\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  // Set the indices to the floor of |p_lc_over_dx|'s elements.\n  i = static_cast<int>(p_lc_over_dx[0]);\n  j = static_cast<int>(p_lc_over_dx[1]);\n  k = static_cast<int>(p_lc_over_dx[2]);\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  int i, j, k;\n  floor(p1, lc, dx, i, j, k);\n  std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n  // (i, j, k) should be (3, 8, 9).\n  Eigen::Vector3d p2(7, 18, 22);\n  floor(p2, lc, dx, i, j, k);\n  std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n  // (i, j, k) should be (-1, 0, 0)--wait, negative indices aren't\n  // allowed, right?!\n  Eigen::Vector3d p3(-1, 2, 3);\n  floor(p3, lc, dx, i, j, k);\n  std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "aa3797d8ed932b2b0a53cf64d7a1949214e58467", "size": 1692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental0/GridIndexing_Bad.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_Bad.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_Bad.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": 36.7826086957, "max_line_length": 75, "alphanum_fraction": 0.5638297872, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6904868463278476}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/convex_hull_2.h>\n#include <CGAL/ch_jarvis.h>\n#include <CGAL/ch_eddy.h>\n#include <CGAL/Timer.h>\n\n#include <CGAL/point_generators_2.h>\n#include <CGAL/algorithm.h>\n#include <boost/math/special_functions/next.hpp>\n\n#include <iostream>\n#include <vector>\n\n\n#define bench(METHOD,CONTAINER) \\\n{\\\n  std::size_t previous=0;\\\n  unsigned run=0;\\\n  CGAL::Timer time;\\\n  do{\\\n    result.clear();\\\n    time.start();\\\n    METHOD( CONTAINER.begin(), CONTAINER.end(), std::back_inserter(result) );\\\n    time.stop();\\\n    if( previous!=0 && previous!=result.size()) std::cerr << \"error got different result\" << std::endl;\\\n    previous=result.size();\\\n  }while(++run<repeat+1);\\\n  std::cout << result.size() << \" points on the convex hull using \"<< #METHOD << \"; Done in \"<< time.time() << \"s\\n\";\\\n}\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef std::vector<Point_2> Points;\ntypedef CGAL::Creator_uniform_2<double,Point_2>  Creator;\n\nint main(int argc, char** argv)\n{\n  unsigned nbpts=100000;\n  unsigned repeat=0;\n  unsigned seed=0;\n  \n  if (argc>1)  nbpts=atoi(argv[1]);\n\n  if (argc>2)  repeat=atoi(argv[2]);\n  if (argc>3)  seed=atoi(argv[3]);\n  \n  Points points, result;\n  \n  CGAL::Random r(seed);\n  CGAL::Random_points_in_disc_2<Point_2,Creator> g( 150.0,r);\n  CGAL::cpp11::copy_n( g, nbpts, std::back_inserter(points));\n  \n  //the following code is for testing when there is only two extreme points, affine hull is 2D\n  /*\n  CGAL::Bbox_2 bbox=points.begin()->bbox();\n  for (Points::iterator it=points.begin();it!=points.end();++it)\n    bbox=bbox+it->bbox();\n  \n  points.push_back( Point_2(bbox.xmin()-1,bbox.ymin()-1) );\n  points.push_back( Point_2(bbox.xmax()+1,bbox.ymax()+1) );\n  */\n\n  //the following code is for testing when there is only three extreme points\n  /*\n  CGAL::Bbox_2 bbox=points.begin()->bbox();\n  for (Points::iterator it=points.begin();it!=points.end();++it)\n    bbox=bbox+it->bbox();\n  \n  points.push_back( Point_2(bbox.xmin()-1,bbox.ymin()-1) );\n  points.push_back( Point_2(bbox.xmax()+1,bbox.ymax()+1) );\n  points.push_back( Point_2(bbox.xmax(),bbox.ymax()+2) );\n  */ \n  \n  //the following code is for testing when there is only two extreme points, affine hull is 1D\n  /*\n  points.clear();\n  for (unsigned i=0;i<nbpts;++i)\n    points.push_back(Point_2(i,i));\n  */\n\n  \n  \n  \n  \n  std::cout << \"seed is \" << seed << \"; using \" << nbpts << \" pts; on \" << repeat+1 <<  \" run(s).\\n\";   \n  \n  std::cout << \"Using vector\" << std::endl;\n  bench(CGAL::convex_hull_2,points)\n  //bench(CGAL::ch_akl_toussaint,points)\n  //bench(CGAL::ch_bykat,points)\n  //bench(CGAL::ch_eddy,points)\n  //bench(CGAL::ch_graham_andrew,points)\n  //bench(CGAL::ch_jarvis,points)\n  \n  {\n    std::list<Point_2> pt_list;\n    std::copy(points.begin(),points.end(),std::back_inserter(pt_list));\n    std::cout << \"Using list\" << std::endl;\n    bench(CGAL::convex_hull_2,pt_list)\n  }\n}\n", "meta": {"hexsha": "c6f6762f97f61409debcd1caba442e9c0420d326", "size": 2987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Convex_hull_2/benchmark/Convex_hull_2/static_ch2.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Convex_hull_2/benchmark/Convex_hull_2/static_ch2.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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": "graphics/cgal/Convex_hull_2/benchmark/Convex_hull_2/static_ch2.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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.2843137255, "max_line_length": 118, "alphanum_fraction": 0.6595246066, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6904594058880177}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Construct_theta_graph_2.h>\n#include <CGAL/property_map.h>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n// select the kernel type\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel   Kernel;\ntypedef Kernel::Point_2                   Point_2;\ntypedef Kernel::Direction_2               Direction_2;\n\n/* define the struct for edge property */\nstruct Edge_property {\n  /* record the Euclidean length of the edge */\n  double euclidean_length;\n};\n\n// define the Graph (e.g., to be undirected,\n// and to use Edge_property as the edge property, etc.)\ntypedef boost::adjacency_list<boost::listS,\n                              boost::vecS,\n                              boost::undirectedS,\n                              Point_2,\n                              Edge_property>  Graph;\n\nint main(int argc, char ** argv)\n{\n  const std::string fname = argc!=3 ? \"data/n20.cin\" : argv[2];\n  unsigned int k = argc!=3 ? 6 : atoi(argv[1]);\n\n  if (argc != 3) {\n    std::cout << \"Usage: \" << argv[0] << \" <no. of cones> <input filename>\" << std::endl;\n    std::cout << \"Using default values \" << k << \" \" << fname << \"\\n\";\n  }\n\n  if (k<2) {\n    std::cout << \"The number of cones should be larger than 1!\" << std::endl;\n    return 1;\n  }\n  // open the file containing the vertex list\n  std::ifstream inf(fname);\n  if (!inf) {\n    std::cout << \"Cannot open file \" << argv[1] << \"!\" << std::endl;\n    return 1;\n  }\n\n  // iterators for reading the vertex list file\n  std::istream_iterator< Point_2 > input_begin( inf );\n  std::istream_iterator< Point_2 > input_end;\n\n  // initialize the functor\n  // If the initial direction is omitted, the x-axis will be used\n  CGAL::Construct_theta_graph_2<Kernel, Graph> theta(k);\n  // create an adjacency_list object\n  Graph g;\n  // construct the theta graph on the vertex list\n  theta(input_begin, input_end, g);\n\n  // select a source vertex for dijkstra's algorithm\n  boost::graph_traits<Graph>::vertex_descriptor v0;\n  v0 = vertex(0, g);\n  std::cout << \"The source vertex is: \" << g[v0] << std::endl;\n\n  std::cout << \"The index of source vertex is: \" << v0 << std::endl;\n\n  // calculating edge length in Euclidean distance and store them in the edge property\n  boost::graph_traits<Graph>::edge_iterator ei, ei_end;\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n    boost::graph_traits<Graph>::edge_descriptor e = *ei;\n    boost::graph_traits<Graph>::vertex_descriptor  u = source(e, g);\n    boost::graph_traits<Graph>::vertex_descriptor  v = target(e, g);\n    const Point_2& pu = g[u];\n    const Point_2& pv = g[v];\n\n    double dist = CGAL::sqrt( CGAL::to_double(CGAL::squared_distance(pu,pv)) );\n    g[e].euclidean_length = dist;\n    std::cout << \"Edge (\" << g[u] << \", \" << g[v] << \"): \" << dist << std::endl;\n  }\n\n  // calculating the distances from v0 to other vertices\n  boost::graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n  // vector for storing the results\n  std::vector<double> distances(n);\n  // Calling the Dijkstra's algorithm implementation from boost.\n  boost::dijkstra_shortest_paths(g,\n                                 v0,\n                                 boost::weight_map(get(&Edge_property::euclidean_length, g)).\n                                 distance_map(CGAL::make_property_map(distances)) );\n\n  std::cout << \"distances are:\" << std::endl;\n  for (unsigned int i=0; i < n; ++i) {\n    std::cout << \"distances[\" << i << \"] = \" << distances[i] << \", (x,y)=\" << g[vertex(i, g)];\n    std::cout << \" at Vertex \" << i << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "52f382fa6083bef97444bd394db58c518e3d34bb", "size": 3835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.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": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.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": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.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": 36.5238095238, "max_line_length": 94, "alphanum_fraction": 0.6276401565, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6904593865365009}}
{"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_POW_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_POW_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing pow capabilities\n\n    Computes \\f$x^y\\f$\n\n    @par Semantic:\n\n    For every parameters of floating types respectively T, U:\n\n    @code\n    T r = pow(x,y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = exp(y*log(x));\n    @endcode\n\n    The pow function is conformant to std:pow considering the limits behaviours\n    defined by the standard:\n\n         - pow(+0, y), where y is a negative odd integer, returns +Inf\n         - pow(-0, y), where y is a negative odd integer, returns -Inf\n         - pow(+/-0, y), where y is negative, finite, and is an even integer or a non-integer, returns +Inf\n         - pow(+/-0, -Inf) returns +inf\n         - pow(+0, y), where y is a positive odd integer, returns +0\n         - pow(-0, y), where y is a positive odd integer, returns -0\n         - pow(+/-0, y), where y is positive non-integer or a positive even integer, returns +0\n         - pow(-1, +/-Inf) returns 1\n         - pow(+1, y) returns 1 for any y, even when y is Nan\n         - pow(x, +/-0) returns 1 for any x, even when x is Nan\n         - pow(x, y) returns Nan if x is finite and negative and y is finite and non-integer.\n         - pow(x, -Inf) returns +Inf for any |x|<1\n         - pow(x, -Inf) returns +0 for any |x|>1\n         - pow(x, +Inf) returns +0 for any |x|<1\n         - pow(x, +Inf) returns +Inf for any |x|>1\n         - pow(-Inf, y) returns -0 if y is a negative odd integer\n         - pow(-Inf, y) returns +0 if y is a negative non-integer or even integer\n         - pow(-Inf, y) returns -Inf if y is a positive odd integer\n         - pow(-Inf, y) returns +Inf if y is a positive non-integer or even integer\n         - pow(+Inf, y) returns +0 for any negative y\n         - pow(+Inf, y) returns +Inf for any positive y\n\n      But return a value of the same type as the first parameter, which is necessary for good SIMD behaviour.\n\n      @par Decorators\n\n        -std_ decorator provides access to std:pow\n\n        -fast_ decorator almost nearly uses the naive formula and so doesnot really care for limits and leads to lower\n\n  **/\n  Value pow(Value const & v0, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/pow.hpp>\n#include <boost/simd/function/simd/pow.hpp>\n\n#endif\n", "meta": {"hexsha": "2c76258003b3296bf76029540253497e0ba8a337", "size": 2824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/pow.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/function/pow.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/pow.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 34.8641975309, "max_line_length": 118, "alphanum_fraction": 0.5913597734, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6904014959675703}}
{"text": "// IIR_Butterworth.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//Calculate the coefficients of the butterworth filter. It follows the steps as described in Matlab. \r\n//The same symbols as in Matlab are used to facilitate the writing of the code\r\n#define _CRTDBG_MAP_ALLOC\r\n#include <stdio.h> \r\n#include <stdlib.h> \r\n#include <crtdbg.h>\r\n#include <iostream>\r\n#include <math.h>\r\n#include <string.h> \r\n#include <vector> \r\n#include <complex.h>\r\n#include \"IIR_Butterworth.h\"\r\n\r\n#define ARMA_DONT_USE_CXX11\r\n#include <armadillo>\r\n\r\n#ifdef _DEBUG\r\n#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )\r\n// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the\r\n// allocations to be of _CLIENT_BLOCK type\r\n#else\r\n#define DBG_NEW new\r\n#endif\r\n\r\n#define PI 3.141592653589793\r\n\r\nint main()\r\n{\r\n    \r\n\r\n    double f1 = 100;  //High Pass\r\n    double f2 = 300; //Low Pass\r\n    double sf = 2048;    //Sampling frequency\r\n    int order_filt = 2; //Order\r\n    double Nyquist_F = sf / 2;\r\n    \r\n    std::vector<std::vector<double> > coeff_final(2);\r\n\r\n    int type_filt = 0;\r\n    IIR_B_F::IIR_Butterworth ir_b;\r\n    \r\n    bool check_stability_flag;\r\n\r\n    //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\r\n    //_CrtSetBreakAlloc(154);\r\n    //_CrtSetBreakAlloc(155);\r\n    //_CrtSetBreakAlloc(156);\r\n\r\n    int coeff_numb = 0;\r\n    switch (type_filt)\r\n    {\r\n    case 0:\r\n        \r\n        coeff_numb = 2*(size_t)order_filt + 1;\r\n\r\n\r\n        for (int i = 0; i < 2; i++)\r\n        {\r\n\r\n            coeff_final[i].resize(coeff_numb);\r\n\r\n        }\r\n        \r\n        \r\n        _CrtDumpMemoryLeaks();\r\n\r\n        coeff_final = ir_b.lp2bp(f1 / Nyquist_F, f2 / Nyquist_F, order_filt);\r\n        \r\n       check_stability_flag =  ir_b.check_stability_iir(coeff_final);\r\n\r\n       if (check_stability_flag)\r\n       {\r\n\r\n           std::cout << \"The filter is stable\" << std::endl;\r\n\r\n       }\r\n\r\n       else\r\n       {\r\n\r\n           std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n       }\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n            if (kk == 0)\r\n            {\r\n\r\n                std::cout << \"Numerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                std::cout << \"Denumerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n            {\r\n                std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n            }\r\n\r\n            std::cout << std::endl;\r\n\r\n        }\r\n        \r\n        break;\r\n\r\n    case 1:\r\n\r\n        coeff_numb = 2 * order_filt + 1;\r\n\r\n\r\n        for (int i = 0; i < 2; i++)\r\n        {\r\n\r\n            coeff_final[i].resize(coeff_numb);\r\n\r\n        }\r\n\r\n        _CrtDumpMemoryLeaks();\r\n        coeff_final = ir_b.lp2bs(f1 / Nyquist_F, f2 / Nyquist_F, order_filt);\r\n       \r\n\r\n        check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n        if (check_stability_flag)\r\n        {\r\n\r\n            std::cout << \"The filter is stable\" << std::endl;\r\n\r\n        }\r\n\r\n        else\r\n        {\r\n\r\n            std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n\r\n            if (kk == 0)\r\n            {\r\n\r\n                std::cout << \"Numerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                std::cout << \"Denumerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n            {\r\n\r\n                std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n            }\r\n\r\n            std::cout << std::endl;\r\n\r\n        }\r\n\r\n        break;\r\n\r\n    case 2:\r\n\r\n        coeff_numb = order_filt + 1;\r\n\r\n        for (int i = 0; i < 2; i++)\r\n        {\r\n\r\n            coeff_final[i].resize(coeff_numb);\r\n\r\n        }\r\n\r\n        _CrtDumpMemoryLeaks();\r\n        coeff_final = ir_b.lp2hp(f1 / Nyquist_F, order_filt);\r\n        \r\n        check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n        if (check_stability_flag)\r\n        {\r\n\r\n            std::cout << \"The filter is stable\" << std::endl;\r\n\r\n        }\r\n\r\n        else\r\n        {\r\n\r\n            std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n\r\n            if (kk == 0)\r\n            {\r\n\r\n                std::cout << \"Numerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                std::cout << \"Denumerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n            {\r\n\r\n                std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n            }\r\n\r\n            std::cout << std::endl;\r\n        }\r\n\r\n        break;\r\n\r\n    case 3:\r\n        coeff_numb = order_filt + 1;\r\n\r\n        for (int i = 0; i < 2; i++)\r\n        {\r\n\r\n            coeff_final[i].resize(coeff_numb);\r\n\r\n        }\r\n\r\n        _CrtDumpMemoryLeaks();\r\n        coeff_final = ir_b.lp2lp(f2 / Nyquist_F, order_filt);\r\n\r\n        check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n        if (check_stability_flag)\r\n        {\r\n\r\n            std::cout << \"The filter is stable\" << std::endl;\r\n\r\n        }\r\n\r\n        else\r\n        {\r\n\r\n            std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n\r\n            if (kk == 0)\r\n            {\r\n\r\n                std::cout << \"Numerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                std::cout << \"Denumerator: \" << std::ends;\r\n\r\n            }\r\n\r\n            for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n            {\r\n\r\n                std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n            }\r\n\r\n            std::cout << std::endl;\r\n\r\n        }\r\n\r\n        break;\r\n\r\n\r\n    }\r\n    \r\n     //Create a complex sine wave\r\n    std::vector<double> test_sin(sf,0.0);\r\n    double sf_1 = 20;\r\n    double sf_2 = 60;\r\n    for (double kk = 0; kk < sf; kk++)\r\n    {\r\n\r\n            test_sin[kk] = sin(2*PI*kk*sf_1/sf) + sin(2*PI*kk*sf_2/sf);\r\n\r\n    }\r\n\r\n    std::vector<double> filt_sign = ir_b.Filter_Data(coeff_final,test_sin);\r\n    \r\n}\r\n", "meta": {"hexsha": "ffddfa94601e277f8cf4b64db0c5d2fc43511c67", "size": 6224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IIR_Butterworth.cpp", "max_stars_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_stars_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IIR_Butterworth.cpp", "max_issues_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_issues_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IIR_Butterworth.cpp", "max_forks_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_forks_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_forks_repo_licenses": ["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.7587301587, "max_line_length": 106, "alphanum_fraction": 0.4546915167, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6904014890635484}}
{"text": "// Copyright (c) 2013, Manuel Blum\n// All rights reserved.\n\n// Define this symbol to enable runtime tests for allocations\n//#define EIGEN_RUNTIME_NO_MALLOC\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <string>\n#include <ctime>\n#include \"nn.h\"\n\nusing namespace std;\n\ninline void swap(int &val)\n{\n\tval = (val << 24) | ((val << 8) & 0x00ff0000) | ((val >> 8) & 0x0000ff00) | (val >> 24);\n}\n\nmatrix_t read_mnist_images(std::string filename)\n{\n\n\tmatrix_t X;\n\tstd::ifstream fs(filename.c_str(), std::ios::binary);\n\tif (fs)\n\t{\n\t\tint magic_number, num_images, num_rows, num_columns;\n\t\tfs.read((char *)&magic_number, sizeof(magic_number));\n\t\tfs.read((char *)&num_images, sizeof(num_images));\n\t\tfs.read((char *)&num_rows, sizeof(num_rows));\n\t\tfs.read((char *)&num_columns, sizeof(num_columns));\n\t\tif (magic_number != 2051)\n\t\t{\n\t\t\tswap(magic_number);\n\t\t\tswap(num_images);\n\t\t\tswap(num_rows);\n\t\t\tswap(num_columns);\n\t\t}\n\n\t\tX = matrix_t::Zero(num_images, num_rows * num_columns);\n\n\t\tfor (size_t i = 0; i < num_images; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < num_rows * num_columns; ++j)\n\t\t\t{\n\t\t\t\tunsigned char temp = 0;\n\t\t\t\tfs.read((char *)&temp, sizeof(temp));\n\t\t\t\tX(i, j) = (double)temp;\n\t\t\t}\n\t\t}\n\t\tfs.close();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"error reading file: \" << filename << std::endl;\n\t\texit(1);\n\t}\n\treturn X;\n}\n\nmatrix_t read_mnist_labels(std::string filename)\n{\n\tmatrix_t Y;\n\tstd::ifstream fs(filename.c_str(), std::ios::binary);\n\tif (fs)\n\t{\n\t\tint magic_number, num_images, num_rows, num_columns;\n\t\tfs.read((char *)&magic_number, sizeof(magic_number));\n\t\tfs.read((char *)&num_images, sizeof(num_images));\n\t\tif (magic_number != 2049)\n\t\t{\n\t\t\tswap(magic_number);\n\t\t\tswap(num_images);\n\t\t}\n\n\t\tY = matrix_t::Zero(num_images, 10);\n\n\t\tfor (size_t i = 0; i < num_images; ++i)\n\t\t{\n\t\t\tunsigned char temp = 0;\n\t\t\tfs.read((char *)&temp, sizeof(temp));\n\t\t\tY(i, (int)temp) = 1.0;\n\t\t}\n\t\tfs.close();\n\t}\n\telse\n\t{\n\t\tstd::cout << \"error reading file: \" << filename << std::endl;\n\t\texit(1);\n\t}\n\treturn Y;\n}\n\ndouble measure_accuracy(matrix_t Y, matrix_t Y_test)\n{\n\tint correct = 0;\n\tfor (int i = 0; i < Y.rows(); i++)\n\t{\n\t\tint j = 0;\n\t\tfor (; j < Y.cols(); j++)\n\t\t{\n\t\t\tint out = Y_test(i, j) > 0.7 ? 1 : 0;\n\t\t\t//printf(\"%3i   %4.4f\", (int)Y(i, j), Y_test(i, j));\n\n\t\t\tif (out != Y(i, j))\n\t\t\t\tbreak;\n\t\t}\n\t\t//cout << endl;\n\t\tif (j == Y.cols())\n\t\t{\n\t\t\tcorrect++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << Y_test.row(i) << endl;\n\t\t}\n\t}\n\t//cout << \"Correct answer \" << correct << \" among \" << Y.rows() << \" test\" << endl;\n\tdouble accuracy = (double)correct / (double)Y.rows() * 100;\n\treturn accuracy;\n\t//cout << \"Accuracy: \" <<  accuracy << \"%\" << endl;\n}\n\nint main(int argc, const char *argv[])\n{\n\t\n\tif (argc != 2)\n\t{\n\t\tstd::cout << \"please provide path to mnist data ...\" << std::endl;\n\t\tstd::cout << \"you can download the dataset at http://yann.lecun.com/exdb/mnist/\" << std::endl;\n\t\tstd::cout << std::endl\n\t\t\t\t  << \"usage: \" << argv[0] << \" path_to_data\" << std::endl\n\t\t\t\t  << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::string path = argv[1];\n\n\tstd::cout << \"reading data\" << std::endl;\n\n\tmatrix_t X_train = read_mnist_images(path + \"/train-images.idx3-ubyte\");\n\tmatrix_t Y_train = read_mnist_labels(path + \"/train-labels.idx1-ubyte\");\n\tmatrix_t X_test = read_mnist_images(path + \"/t10k-images.idx3-ubyte\");\n\tmatrix_t Y_test = read_mnist_labels(path + \"/t10k-labels.idx1-ubyte\");\n\t// number of optimization steps \n\tint max_steps = 5;\n\t// regularization parameter\n\tdouble lambda = 0.0;\n\n\t// specify network topology\n\tEigen::VectorXi topo(3);\n\ttopo << X_train.cols(), 300, Y_test.cols();\n\tstd::cout << \"topology: \" << topo.transpose() << std::endl;\n\n\t// initialize a neural network with given topology\n\tstd::cout << \"initializing network\" << std::endl;\n\tNeuralNet nn(topo);\n\n\tstd::cout << \"scaling the data\" << std::endl;\n\tnn.autoscale(X_train, Y_train);\n\n\t//std::cout << Y_train << std::endl;\n\t// train the network\n\tstd::cout << \"starting training\" << std::endl;\n\tstd::cout << \"iter        error\" << std::endl;\n\tdouble err;\n\tclock_t begin = clock();\n\tfor (int i = 0; i < max_steps; ++i)\n\t{\n\t\terr = nn.loss(X_train, Y_train, lambda);\n\t\tnn.rprop();\n\t\tprintf(\"%4i   %10.7f\\n\", i, err);\n\t}\n\tclock_t end = clock();\n\tdouble elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;\n\tcout << \"Training time: \" << elapsed_secs << endl;\n\n\t// test accuracy\n\tnn.forward_pass(X_test);\n\tmatrix_t prediction = nn.get_activation();\n\tint correct = 0;\n\tint k;\n\tfor (size_t i = 0; i < Y_test.rows(); ++i)\n\t{\n\t\tprediction.row(i).maxCoeff(&k);\n\t\tcorrect += Y_test(i, k);\n\t}\n\n\tstd::cout << \"test accuracy: \" << correct * 1.0 / Y_test.rows()*100 << \"% \" << std::endl;\n\t//cout << prediction << endl;\n\t// cout << \"*****************Printing the wrong output***************\" << endl; \n\t// double accuracy = measure_accuracy(Y_test, prediction);\n\t// std::cout << \"Accuracy: \" << accuracy << std::endl;\n\tnn.write(\"mnist.nn\");\n\t\n\n\treturn 0;\n}\n", "meta": {"hexsha": "003356bcf6c727eb7dce45aac83cffb74ca8d3c8", "size": 4889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mnist.cpp", "max_stars_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_stars_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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": "mnist.cpp", "max_issues_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_issues_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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": "mnist.cpp", "max_forks_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_forks_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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.3233830846, "max_line_length": 96, "alphanum_fraction": 0.611167928, "num_tokens": 1517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6903997075298458}}
{"text": "#include <cmath>\n#include <memory>\n#include <iostream>\n#include <random>\n\n#include <Eigen/Core>\n\n#include \"RandomGenerator.h\"\n#include \"mcmc/MCMC.h\"\n\nint main()\n{\n  // function handle, can be C++11 lambda, regular function pointer, or std::function\n  auto logdens = [](const Eigen::VectorXd& x) {\n    return -(x(0) * x(0)) - (x(1) * x(1));\n  };\n\n  auto rng = std::make_shared<RandomGenerator>();\n\n  auto mcmc = std::make_shared<MCMC>(logdens, 2, rng);\n\n  mcmc->Run(10000);\n\n  auto chain = mcmc->GetChain();\n\n  std::cout << \"Mean: \" << chain.colwise().mean() << std::endl;\n\n  std::cout << \"Autocorrelation: \" << mcmc->GetAutocorrelation(10).transpose() << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "7a252b39b1d81a7bca13a41ba38c47bc8dfb4ca2", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TestMCMC.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/TestMCMC.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/TestMCMC.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": 21.935483871, "max_line_length": 92, "alphanum_fraction": 0.6338235294, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6903996949000136}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2022, Jeferson Lima\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n *  @file   examples/rotation_ex.cpp\n *  @author Jeferson Lima\n *  @brief  Rotation Matrix Example \n *  @date   Mar 7, 2022\n **/\n\n#include <iostream>\n#include <Eigen/Core>\n\nvoid rot2dVec(const Eigen::Matrix<float, 4, 1>& v,\n              Eigen::Matrix<float, 4, 1>& r,\n\t      float theta)\n{\n\n  Eigen::Matrix<float, 4, 4> rotation;\n  rotation << std::cos(theta), -std::sin(theta), 0.0, 0.0, \n              std::sin(theta), std::cos(theta),  0.0, 0.0,\n\t      0.0,             0.0,              1.0, 0.0,\n\t      0.0,             0.0,              0.0, 1.0;\n\n  std::cout << \"v values: \\n\" << v << std::endl;\n  std::cout << \"rotation values: \\n\" << rotation << std::endl;\n\n  r = rotation * v;\n\n}\n\n\nint main(int argc, char* argv[])\n{\n\n  Eigen::Matrix<float, 4, 1> v;\n  Eigen::Matrix<float, 4, 1> r;\n  float theta;\n\n  // init matrix\n  v << 0.5, 0.5, 0.0, 1.0;\n  theta = 0.785398; // 45 degree -> radian\n\n  rot2dVec(v, r, theta);\n\n  std::cout << \"r values:\\n\" << r << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "932725b7fe1a1188bdda81414eea168ced484ce3", "size": 1251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/1/rotation_ex.cpp", "max_stars_repo_name": "jefersonjlima/robotics-codes", "max_stars_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_stars_repo_licenses": ["MIT"], "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/1/rotation_ex.cpp", "max_issues_repo_name": "jefersonjlima/robotics-codes", "max_issues_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_issues_repo_licenses": ["MIT"], "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/1/rotation_ex.cpp", "max_forks_repo_name": "jefersonjlima/robotics-codes", "max_forks_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_forks_repo_licenses": ["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.6037735849, "max_line_length": 80, "alphanum_fraction": 0.4684252598, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.6902072279706828}}
{"text": "#ifndef TRIUMF_NMR_UTILITIES_HPP\n#define TRIUMF_NMR_UTILITIES_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// nuclear magnetic resonance\nnamespace nmr {\n\n// miscellaneous helper functions\nnamespace utilities {\n\n// calculate the gyromagnetic ratio (MHz / T) of an NMR probe nucleus from its\n// magnetic dipole moment (nm) and spin quantum number\ntemplate <typename T>\nconstexpr T calculate_gamma(T magnetic_dipole_moment, T spin_quantum_number) {\n  return 1e6 * boost::math::constants::two_pi<T>() *\n         triumf::constants::codata_2018::nuclear_magneton_in_MHz_T<T>::value() *\n         magnetic_dipole_moment / spin_quantum_number;\n}\n\n} // namespace utilities\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_UTILITIES_HPP\n", "meta": {"hexsha": "e4cf06b2aa9ace158d71259b9a06875e9498f52b", "size": 862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/utilities.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/nmr/utilities.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/nmr/utilities.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.1212121212, "max_line_length": 80, "alphanum_fraction": 0.7656612529, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6901780290619267}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <sophus/se3.hpp>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <vector>\n#include <cmath>\n// need pangolin for plotting trajectory\n#include <pangolin/pangolin.h>\nusing namespace std;\nusing namespace Eigen;\n\nstring TrajectoryFile = \"../compare.txt\";\nvoid ICP(vector<Vector3d> pts_est, vector<Vector3d> pts_gt, Matrix3d &R, Vector3d &t);\nvoid DrawTrajectory(vector<Sophus::SE3d> poses1, vector<Sophus::SE3d> poses2, string winName=\"Trajectory Viewer\");\n\nint main(){\n    ifstream fin(TrajectoryFile);\n    vector<Vector3d> pts_est,pts_gt;\n    vector<Sophus::SE3d> poses_gt, poses_est;\n    while(!fin.eof()){\n        double time, tx,ty,tz,qx,qy,qz,qw;\n        fin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n        Quaterniond q(qw,qx,qy,qz);\n        Vector3d t_est(tx,ty,tz);\n        Sophus::SE3d SE3_est(q,t_est);\n        pts_est.push_back(t_est);\n        poses_est.push_back(SE3_est);\n\n        fin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n        Quaterniond q2(qw,qx,qy,qz);\n        Vector3d t_gt(tx,ty,tz);\n        Sophus::SE3d SE3_gt(q2,t_gt);\n        poses_gt.push_back(SE3_gt);\n        pts_gt.push_back(t_gt);\n    }\n    Matrix3d R;\n    Vector3d t;\n    ICP(pts_est, pts_gt, R, t);\n    Sophus::SE3d SE3_E2G(R, t);\n\n    int N = poses_gt.size();\n    vector<Sophus::SE3d> poses_after(N);\n    for(int i=0;i<N;i++){\n        poses_after[i] = SE3_E2G*poses_est[i];\n    }\n    DrawTrajectory(poses_gt, poses_est, \"before\");\n    DrawTrajectory(poses_gt, poses_after, \"after\");\n\n    double error=0;\n    for (int i=0;i<N;i++){\n        Sophus::SE3d SE3_differ = poses_gt[i].inverse()*poses_after[i];\n        typedef Eigen::Matrix<double, 6, 1> Vector6d;\n        Vector6d se3_differ = SE3_differ.log();\n        error += se3_differ.dot(se3_differ);\n    }\n    double RMSE = sqrt(error/N);\n    cout<<\"RMSE: \"<<RMSE<<endl;\n\n    return 0;\n}\n\nvoid ICP(vector<Vector3d> pts_est, vector<Vector3d> pts_gt, Matrix3d &R, Vector3d &t){\n    Vector3d pe(0,0,0), pg(0,0,0);\n    int N = pts_est.size();\n    for(int i=0;i<N;i++){\n        pe += pts_est[i];\n        pg += pts_gt[i];\n    }\n    pe /= N;\n    pg /= N;\n    vector<Vector3d> q_est(N), q_gt(N);\n    for (int i=0;i<N;i++){\n        q_est[i] = pts_est[i]-pe;\n        q_gt[i] = pts_gt[i]-pg;\n    }\n    Matrix3d W = Matrix3d::Zero();\n    for (int i=0;i<N;++i){\n        W += q_gt[i]*q_est[i].transpose();\n    }\n    cout<<\"W=\"<<W<<endl;\n    JacobiSVD<Matrix3d> svd(W, ComputeFullU|ComputeFullV);\n    Matrix3d U = svd.matrixU();\n    Matrix3d V = svd.matrixV();\n    cout<<\"U=\"<<U<<endl;\n    cout<<\"V=\"<<V<<endl;\n    Matrix3d R_ = U*(V.transpose());\n    if(R_.determinant()<0){\n        R_ = -R_;\n    }\n    \n    Vector3d t_ = pg-R_*pe;\n    R = R_;\n    t = t_;\n}\n\nvoid DrawTrajectory(vector<Sophus::SE3d> poses1, vector<Sophus::SE3d> poses2, string winName) {\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(winName, 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n            .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n    while (pangolin::ShouldQuit() == false) {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n        for (size_t i = 0; i < poses1.size() - 1; i++) {\n            glColor3f(1, 0.0f, 0);\n            glBegin(GL_LINES);\n            auto p1 = poses1[i], p2 = poses1[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n        for (size_t i = 0; i < poses2.size() - 1; i++) {\n            glColor3f(0, 0.0f, 1);\n            glBegin(GL_LINES);\n            auto p1 = poses2[i], p2 = poses2[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n\n}", "meta": {"hexsha": "594a6f7253464ecc2e83de1eb5c412b0a4d92188", "size": 4556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw5/icp.cpp", "max_stars_repo_name": "Yaozhuwa/slambook-homework", "max_stars_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T03:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T15:29:10.000Z", "max_issues_repo_path": "slamhw5/icp.cpp", "max_issues_repo_name": "Yaozhuwa/slambook-homework", "max_issues_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slamhw5/icp.cpp", "max_forks_repo_name": "Yaozhuwa/slambook-homework", "max_forks_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2054794521, "max_line_length": 114, "alphanum_fraction": 0.5862598771, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6901476489251218}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\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\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/math/basic/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n// Define Boost test suite.\nBOOST_AUTO_TEST_SUITE( test_mathematical_constants )\n\n//! Check correct pi using PI = circumference / diameter:\nBOOST_AUTO_TEST_CASE( test_PI )\n{    \n    const double radius = 5.0;\n\n    // Circumference circle with radius 5, 32 digits precision, see\n    // http://www.wolframalpha.com/input/?i=Circumference+of+a+circle+with+radius+5\n    // http://www.wolframalpha.com/input/?i=N[10*PI,66]\n    double circumference = 31.4159265358979323846264338327950288419716939937510582097494459230; \n    BOOST_CHECK_CLOSE(  mathematical_constants::PI,\n                        circumference / ( 2.0 * radius ) ,\n                        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct E using E Wolfram alpha as reference\nBOOST_AUTO_TEST_CASE( test_E )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=e+72+digits\n    BOOST_CHECK_CLOSE( mathematical_constants::E,\n        2.71828182845904523536028747135266249775724709369995957496696762772407663, \n        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct GOLDEN_RATIO using GOLDEN_RATIO Wolfram alpha as reference\nBOOST_AUTO_TEST_CASE( test_GOLDEN_RATIO )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=golden+ratio+72+digits\n    BOOST_CHECK_CLOSE(  mathematical_constants::GOLDEN_RATIO,\n        1.618033988749894848204586834365638117720309179805762862135448622705260463, \n        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct NAN using boost Floating Point Classification (fpclassify)\nBOOST_AUTO_TEST_CASE( test_NAN )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=golden+ratio+72+digits\n    BOOST_CHECK( boost::math::isnan( TUDAT_NAN ) );\n}\n\nBOOST_AUTO_TEST_CASE( test_TemplatedValues )\n{\n    double one = 1.0;\n    long double longOne = 1.00000000000000000000L;\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< double >( 1 ),\n                        one, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< long double >( 1 ),\n                        longOne, std::numeric_limits< long  double >::epsilon( ) );\n\n    BOOST_CHECK_SMALL(  mathematical_constants::getFloatingInteger< double >( 0 ),\n                        std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL(  mathematical_constants::getFloatingInteger< long double >( 0 ),\n                        std::numeric_limits< long  double >::epsilon( ) );\n\n    double two = 2.0;\n    long double longTwo = 2.00000000000000000000L;\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< double >( 2 ),\n                        two, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< long double >( 2 ),\n                        longTwo, std::numeric_limits< long  double >::epsilon( ) );\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingFraction< double >( 1, 2 ),\n                        mathematical_constants::getFloatingInteger< double >( 1 ) /\n                        mathematical_constants::getFloatingInteger< double >( 2 ),\n                        std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingFraction< long double >( 1, 2 ),\n                        mathematical_constants::getFloatingInteger< long double >( 1 ) /\n                        mathematical_constants::getFloatingInteger< long double >( 2 )\n                        , std::numeric_limits< long double >::epsilon( ) );\n\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getPi< double >( ),\n                        mathematical_constants::PI, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getPi< long double >( ),\n                        mathematical_constants::LONG_PI, std::numeric_limits< long  double >::epsilon( ) );\n\n}\n\n// Close Boost test suite.\nBOOST_AUTO_TEST_SUITE_END( ) // End test_mathematical_constants\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "bab53c7061b1e90cb40284025a58ae7da6d8a39f", "size": 4836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/basic/unitTestMathematicalConstants.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "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": "tests/src/math/basic/unitTestMathematicalConstants.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/basic/unitTestMathematicalConstants.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "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.9830508475, "max_line_length": 107, "alphanum_fraction": 0.6799007444, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6901476257344288}}
{"text": "#include <iostream>\n#include <array>\n#include <cmath>\n#include <tuple>\n#include <cassert>\n#include <NTL/ZZ.h>\n#include <NTL/vector.h>\n#include <random>\n#include <chrono>\n\nusing namespace std;\nusing namespace NTL;\n\n//ex. compile:\n//g++ -o <exe> remainder_alg_first_pass.cpp -std=c++11 -march=native -O2 -lntl -lgmp -lgmpxx -pthread\n\n\n// to compile and run on linux use\n// g++ -o <executable file name> remainder_alg_first_pass.cpp\n// ./<executable file name>\n\n\n//note that everywhere it says 'int' we will eventually want to use GMP or whatnot\n//ints are too small...\n\n//translates indices in trees to indices in arrays\n//if you want left child of (i,j), do (i+1, 2*j)\n//right child is (i+1, 2*j+1), and parent is (i-1, j//2)\nint flatten_index(int i, int j)\n{\n\tassert (j <= pow(2,i) - 1);\n\treturn pow(2,i) +j-1;\n}\n\n//gives tree indices from array index\ntuple<int, int> lift_index(int k)\n{\n\tint i = log2(k+1);\n\tint j = k + 1 - pow(2,i);\n\n\treturn make_tuple(i,j);\n}\n\n\nvoid print_tree(Vec<ZZ> & X)\n{\n\tcout << endl;\n\tfor (int i = 0; i < X.length(); i++)\n\t{\n\t\tcout << X[i] << \" , \";\n\t}\n\tcout << endl;\n}\n\n\nZZ mtree_val(int i, int j, const Vec<ZZ> &m)\n{\n\tint N = m.length();\n\tint depth = log2(N);\n\tassert ((i <= depth) and (j < pow(2, i)));\n\n\tif (i == depth)\n\t{\n\t\treturn m[j];\n\t}\n\n\telse\n\t{\n\t\treturn mtree_val(i+1, 2*j, m)*mtree_val(i+1, 2*j+1, m);\n\t}\n}\n\nZZ Atree_val(int i, int j, const Vec<ZZ> &A)\n{\n\tint N = A.length();\n\tint depth = log2(N);\n\tassert ((i <= depth) and (j < pow(2,i)));\n\n\tif ((i == depth) or (j == 0))\n\t{\n\t\treturn A[j];\n\t}\n\n\telse\n\t{\n\t\treturn Atree_val(i+1, 2*j-1, A)*Atree_val(i+1, 2*j, A);\n\t}\n}\n\n\n//k will be approx log log N (it's the space-time tradeoff)\n//when k = 0 we have normal remainder tree\nVec<ZZ> RemTree(const Vec<ZZ> &A, const Vec<ZZ> &m, const ZZ &V = ZZ(1))\n{\n\tint N = A.length();\n\tassert (N == m.length());\n\tint depth = log2(N);\n\n\t//assume the input is of size a power of 2\n\tVec<ZZ> mtree;\n\tmtree.SetLength(2*N-1);\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\t\tmtree[leaf] = m[j];\n\t}\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\tmtree[parent] = mtree[left]*mtree[right];\n\t\t}\n\t}\n\n\n\n\tVec<ZZ> Atree;\n\tAtree.SetLength(2*N-1);\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\t\tAtree[leaf] = A[j];\n\t}\n\n\t//build up the 'product' tree recursively\n\tfor (int i = depth-1; i >= 0; i--)\n\t{\n\t\tint leftmost = flatten_index(i,0);\n\t\tint leftmost_child = 2*leftmost + 1;\n\t\tAtree[leftmost] = A[leftmost_child];\n\n\t\tfor (int j = 1; j < pow(2, i); j++)\n\t\t{\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint superleft = 2*parent;\n\t\t\tint left = superleft + 1;\n\n\t\t\tAtree[parent] = Atree[superleft]*Atree[left];\n\t\t}\n\t}\n\n\tVec<ZZ> remtree;\n\tremtree.SetLength(2*N-1);\n\n\tremtree[0] = (V*A[0])%mtree[0];\n\n\tfor (int i = 0; i < depth; i++)\n\t{\n\t\t//notice it goes every two!\n\t\tfor (int j = 0; j < pow(2, i); j++)\n\t\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\tremtree[left] = remtree[parent]%mtree[left];\n\t\t\tremtree[right] = (remtree[parent]*Atree[right])%mtree[right];\n\t\t}\n\t}\n\n\tVec<ZZ> remainders;\n\tremainders.SetLength(N);\n\n\tint leftmost_leaf = flatten_index(depth, 0);\n\tfor (int j = 0; j < N; j++)\n\t{\n\t\tremainders[j] = remtree[leftmost_leaf+j];\n\t}\n\treturn remainders;\n}\n\n//searches up to N for Wilson primes\nVec<ZZ> WilsonRemainders(long N, long interval)\n{\n\tVec<ZZ> A;\n\tVec<ZZ> m;\n\n\tA.SetLength(interval);\n\tm.SetLength(interval);\n\n\tVec<ZZ> remainders;\n\tremainders.SetLength(N);\n\n\tZZ V = ZZ(1);\n\n\tfor (int b = 0; b*interval < N; b++)\n\t{\n\t\tfor (int i = 0; i < interval; i++)\n\t\t{\n\t\t\tZZ val = ZZ(b*interval+(i+1));\n\n\t\t\tA[i] = val-1;\n\t\t\tif (val == 1)\n\t\t\t{\n\t\t\t\tA[i] += 1;\n\t\t\t}\n\n\t\t\tif (ProbPrime(val))\n\t\t\t{\n\t\t\t\tm[i] = val*val;\n\t\t\t}\n\n\t\t\telse\n\t\t\t{\n\t\t\t\tm[i] = 1;\n\t\t\t}\n\t\t}\n\n\t\tVec<ZZ> interval_remainders = RemTree(A, m, V);\n\t\tfor (int i = 0; i < interval; i++)\n\t\t{\n\t\t\tremainders[b*interval+i] = interval_remainders[i];\n\t\t\tV *= A[i];\n\t\t}\n\t}\n\n\treturn remainders;\n}\n\nint main()\n{\n\tlong N = pow(2,1);\n\n\tVec<ZZ> A;\n\tVec<ZZ> m;\n\n\tA.SetLength(N);\n\tm.SetLength(N);\n\n\trandom_device rd;\n\tmt19937 mt(rd());\n\tuniform_int_distribution<int> dist(1, N);\n\n\tfor(int i = 0; i < N; i++){\n\t\tint bitsize = log2(i+1)+2;\n\n\t\t\n\t\tA[i] = dist(mt);\n\t\tm[i] = dist(mt);\n\n\t}\n\n\n\t//Vec<ZZ> ztree = zero_vector(2*N);\n\n\t//print_tree(A);\n\t//print_tree(m);\n\n\tauto start = chrono::high_resolution_clock::now();\n\tVec<ZZ> remainders = RemTree(A,m);\n\tVec<ZZ> WREM = WilsonRemainders(pow(2,18), pow(2,18));\n\tauto finish = chrono::high_resolution_clock::now();\n\n\tchrono::duration<double> runtime = finish-start;\n\n\t//print_tree(WREM);\n\tcout << remainders[0] << endl;\n\tcout << WREM[562] << \" , \" << 563*563 << endl;\n\tcout << runtime.count() << endl;\n\n\n\n\n}\n", "meta": {"hexsha": "1e9fef8ca2fbb1e9e808fda88c54e76fc7591470", "size": 4998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/cppfiles/RemTree_alternate.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/cppfiles/RemTree_alternate.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/cppfiles/RemTree_alternate.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": 18.1086956522, "max_line_length": 101, "alphanum_fraction": 0.5942376951, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6900702662613903}}
{"text": "// Compression methods for vectors\n// Author: Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <vector_compression/vector_compression.h>\n\n#include <Eigen/Core>\n\n#include \"contrib/angles.h\"\n\n#include <iostream>\n\n#define DEBUG 0\n\nnamespace vector_compression\n{\n\n// The \"hemi-oct\" compression scheme is taken from\n//  Cigolle, Zina H., Sam Donow, and Daniel Evangelakos.\n//  \"A survey of efficient representations for independent unit vectors.\"\n//  Journal of Computer Graphics Techniques Vol 3.2 (2014).\n\n// Assume normalized input on +Z hemisphere.\n// Output is [-1, 1]\nstatic Eigen::Vector2f float32x3_to_hemioct(const Eigen::Vector3f& v)\n{\n\t// Project the hemisphere onto the hemi-octahedron,\n\t// and then project into the xy plane\n\tEigen::Vector2f p = v.head<2>() * (1.0f / (fabsf(v.x()) + fabsf(v.y()) + v.z()));\n\n\t// Rotate and scale the center diamond to the unit square\n\treturn Eigen::Vector2f(p.x() + p.y(), p.x() - p.y());\n}\n\nstatic Eigen::Vector3f hemioct_to_float32x3(const Eigen::Vector2f& e)\n{\n\t// Rotate and scale the unit square back to the center diamond\n\tEigen::Vector2f temp = 0.5f * Eigen::Vector2f(e.x() + e.y(), e.x() - e.y());\n\tEigen::Vector3f v;\n\tv << temp, 1.0 - fabsf(temp.x()) - fabsf(temp.y());\n\n\treturn v.normalized();\n}\n\nint32_t float_to_snormb(float v, int b)\n{\n\treturn std::round(std::min(1.0f, std::max(-1.0f, v)) * ((1 << (b-1)) - 1));\n}\n\nfloat snormb_to_float(int32_t v, int b)\n{\n\t// Sign extend\n\tif(v & (1 << (b-1)))\n\t\tv |= 0xFFFFFFFF & ~((1 << b) - 1);\n\n\treturn std::min(1.0f, std::max(-1.0f, ((float)v) / ((1 << (b-1)) - 1)));\n}\n\nvoid encodeQuaternion(const Eigen::Quaternionf& quat, uint8_t* dest)\n{\n\t// Recover rotation angle & axis\n\tfloat angle = 2.0f * acosf(quat.w());\n\tangle = angles::normalize_angle(angle);\n\n\tfloat norm = sqrtf(1.0f - quat.w()*quat.w());\n\n\tEigen::Vector3f axis;\n\n\tif(norm != 0)\n\t{\n\t\taxis << quat.x() / norm, quat.y() / norm, quat.z() / norm;\n\t}\n\telse\n\t\taxis << 0.0f, 0.0f, 0.0f;\n\n\t// Map to the upper hemisphere\n\tif(axis.z() < 0)\n\t{\n\t\taxis *= -1.0f;\n\t\tangle = -angle;\n\t}\n\n\tEigen::Vector2f hemi = float32x3_to_hemioct(axis);\n\n\tint32_t hemi_a = float_to_snormb(hemi.x(), 12);\n\tint32_t hemi_b = float_to_snormb(hemi.y(), 12);\n\n\tint32_t angle_sn = float_to_snormb(angle / M_PI, 16);\n\n#if DEBUG\n\tprintf(\"encode: %f, %f, %f, angle_sn: %u (0x%X)\\n\", hemi.x(), hemi.y(), angle, angle_sn, angle_sn);\n\tprintf(\"angle scale: %d\\n\", ((1 << (16-1)) - 1));\n#endif\n\n\tdest[0] = hemi_a;\n\tdest[1] = ((hemi_a >> 8) & 0xF) | ((hemi_b & 0xF) << 4);\n\tdest[2] = hemi_b >> 4;\n\tdest[3] = angle_sn;\n\tdest[4] = angle_sn >> 8;\n}\n\nEigen::Quaternionf decodeQuaternion(const uint8_t* src)\n{\n\tint32_t hemi_a = src[0] | (((uint32_t)src[1] & 0xF) << 8);\n\tint32_t hemi_b = (src[1] >> 4) | (((uint32_t)src[2]) << 4);\n\tint32_t angle_sn = src[3] | (((uint32_t)src[4]) << 8);\n\n\tEigen::Vector2f hemi(\n\t\tsnormb_to_float(hemi_a, 12), snormb_to_float(hemi_b, 12)\n\t);\n\n\tEigen::Vector3f axis = hemioct_to_float32x3(hemi);\n\n\tfloat angle = snormb_to_float(angle_sn, 16) * M_PI;\n\n#if DEBUG\n\tprintf(\"decode: %f, %f, %f, angle_sn: %d\\n\", hemi.x(), hemi.y(), angle, angle_sn);\n#endif\n\n\treturn Eigen::Quaternionf(Eigen::AngleAxisf(angle, axis));\n}\n\nEigen::Vector3f latticeToVector(const Eigen::Vector3i& lattice, float r)\n{\n\treturn r * Eigen::Vector3f(\n\t\tlattice.y() + lattice.z(),\n\t\tlattice.x() + lattice.z(),\n\t\tlattice.x() + lattice.y()\n\t);\n}\n\nEigen::Vector3f alignedLatticeToVector(const Eigen::Vector3i& lattice, float r)\n{\n\tEigen::Vector3f m = lattice.cast<float>();\n\n\tEigen::Vector3f x = m + m.y() * Eigen::Vector3f::UnitY() + ((lattice.x() + lattice.z()) % 2) * Eigen::Vector3f::UnitY();\n\n\tx *= r;\n\n\treturn x;\n}\n\nstatic inline int sgn(float x)\n{\n\tif(x >= 0)\n\t\treturn 1;\n\telse\n\t\treturn -1;\n}\n\nstatic inline float roundFloat(float x)\n{\n\treturn std::round(x);\n}\n\nEigen::Vector3i vectorToAlignedLattice(const Eigen::Vector3f& p, float r)\n{\n\tEigen::Vector3f m = p / r;\n\n\tEigen::Vector3f cartesian_lattice = m.unaryExpr(std::ptr_fun(roundFloat));\n\tEigen::Vector3i lattice_int = cartesian_lattice.cast<int>();\n\n\tif(lattice_int.sum() % 2 != 0)\n\t{\n\t\tEigen::Vector3f local = m - cartesian_lattice;\n\t\tint c;\n\t\tlocal.array().abs().maxCoeff(&c);\n\n\t\tlattice_int[c] += sgn(local[c]);\n\t}\n\n\tlattice_int.y() = (lattice_int.y() - ((lattice_int.x() + lattice_int.z()) % 2)) / 2;\n\n\treturn lattice_int;\n}\n\nEigen::Vector3i vectorToLattice(const Eigen::Vector3f& p, float r)\n{\n\tEigen::Vector3f normalized = p / r;\n\n\tEigen::Vector3f cartesian_lattice = normalized.unaryExpr(std::ptr_fun(roundFloat));\n\tEigen::Vector3i lattice_int = cartesian_lattice.cast<int>();\n\n\tif(lattice_int.sum() % 2 != 0)\n\t{\n\t\tEigen::Vector3f local = normalized - cartesian_lattice;\n\t\tint c;\n\t\tlocal.array().abs().maxCoeff(&c);\n\n\t\tlattice_int[c] += sgn(local[c]);\n\t}\n\n\tEigen::Matrix3i inv;\n\tinv <<\n\t\t-1, 1, 1,\n\t\t1, -1, 1,\n\t\t1, 1, -1\n\t;\n\n\treturn (inv * lattice_int) / 2;\n}\n\nvoid encode3DVector6(const Eigen::Vector3f& vec, float extent, uint8_t* dest)\n{\n\t// We are using 16 bit resolution per lattice index.\n\tfloat lattice_r = extent / (2.0f * ((1 << 15)-1));\n\n\tEigen::Vector3i lattice = vectorToLattice(vec, lattice_r);\n\n\tfor(int i = 0; i < 3; ++i)\n\t{\n\t\tlattice[i] = std::min(32767, std::max(-32768, lattice[i]));\n\t\tdest[2*i] = lattice[i];\n\t\tdest[2*i+1] = lattice[i] >> 8;\n\t}\n}\n\nEigen::Vector3f decode3DVector6(float extent, const uint8_t* src)\n{\n\t// We are using 16 bit resolution per lattice index.\n\tfloat lattice_r = extent / (2.0f * ((1 << 15)-1));\n\n\tEigen::Vector3i lattice;\n\tfor(int i = 0; i < 3; ++i)\n\t{\n\t\tint16_t idx = src[2*i] | (((uint16_t)src[2*i+1]) << 8);\n\t\tlattice[i] = idx;\n\t}\n\n\treturn latticeToVector(lattice, lattice_r);\n}\n\nVectorCompression::VectorCompression(unsigned int bits)\n : m_bits(bits)\n{\n\tsetExtent(Eigen::Vector3f(1.0, 1.0, 1.0));\n}\n\nvoid VectorCompression::setExtent(const Eigen::Vector3f& extent)\n{\n\tm_extent = extent;\n\n\tm_r = powf(sqrtf(2.0) * extent.x() * extent.y() * extent.z() / (1LL << m_bits), 1.0f / 3.0f) * sqrtf(2.0);\n\n\tm_latticeExtent.x() = std::floor(extent.x() / m_r);\n\tm_latticeExtent.y() = std::floor(extent.y() / m_r / 2.0f);\n\tm_latticeExtent.z() = std::floor(extent.z() / m_r);\n\n\tuint64_t high = 8 * m_latticeExtent.x() * m_latticeExtent.y() * m_latticeExtent.z();\n\tif(high > (1ULL << m_bits))\n\t{\n\t\tstd::cerr << \"lattice overflow: \" << high << \" > \" << (1LL << 24) << \"\\n\";\n\t\tstd::cerr << \"calculated radius: \" << m_r;\n\t\tthrow std::runtime_error(\"lattice overflow\");\n\t}\n}\n\nuint64_t VectorCompression::compress(const Eigen::Vector3f& vec) const\n{\n\tEigen::Vector3i lattice = vectorToAlignedLattice(vec, m_r);\n\n\t// Shift to [0, 2*m_latticeExtent]\n\tlattice += m_latticeExtent;\n\n\t// Constrain\n\tlattice.x() = std::max(0, std::min(2*m_latticeExtent.x(), lattice.x()));\n\tlattice.y() = std::max(0, std::min(2*m_latticeExtent.y(), lattice.y()));\n\tlattice.z() = std::max(0, std::min(2*m_latticeExtent.z(), lattice.z()));\n\n\tuint64_t index = lattice.x() + lattice.y() * 2 * m_latticeExtent.x() + lattice.z() * 4 * m_latticeExtent.x() * m_latticeExtent.y();\n\n\t// Sanity check\n\tif(index >= (1ULL << m_bits))\n\t{\n\t\tstd::cerr << \"lattice overflow while compressing \" << vec.transpose() << \"\\n\";\n\t\tstd::cerr << \"radius: \" << m_r << \"\\n\";\n\t\tstd::cerr << \"lattice extents: \" << m_latticeExtent.transpose() << \"\\n\";\n\t\tstd::cerr << \"lattice coords: \" << lattice.transpose() << \"\\n\";\n\t\tstd::cerr << \"=> index: \" << index << \"\\n\";\n\t\tindex = (1 << m_bits) - 1;\n\t}\n\n\treturn index;\n}\n\nEigen::Vector3f VectorCompression::uncompress(uint64_t compressed) const\n{\n\tEigen::Vector3i lattice;\n\n\tlattice.z() = compressed / (4 * m_latticeExtent.x() * m_latticeExtent.y());\n\n\tuint64_t remainder = compressed % (4 * m_latticeExtent.x() * m_latticeExtent.y());\n\n\tlattice.y() = remainder / (2*m_latticeExtent.x());\n\tlattice.x() = remainder % (2*m_latticeExtent.x());\n\n\t// Shift to [-extent, extent]\n\tlattice -= m_latticeExtent;\n\n\treturn alignedLatticeToVector(lattice, m_r);\n}\n\nfloat VectorCompression::guaranteedPrecision() const\n{\n\treturn sqrt(2.0f) * m_r;\n}\n\n}\n", "meta": {"hexsha": "2c2bf181d50fffd6212e80df06996e556da246ef", "size": 7933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vector_compression.cpp", "max_stars_repo_name": "AIS-Bonn/vector_compression", "max_stars_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-01T12:33:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T15:13:58.000Z", "max_issues_repo_path": "src/vector_compression.cpp", "max_issues_repo_name": "AIS-Bonn/vector_compression", "max_issues_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "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/vector_compression.cpp", "max_forks_repo_name": "AIS-Bonn/vector_compression", "max_forks_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T05:38:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T05:05:09.000Z", "avg_line_length": 25.7564935065, "max_line_length": 132, "alphanum_fraction": 0.6442707677, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6900702573637083}}
{"text": "#include <medusa/Medusa_fwd.hpp>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n\n/// Basic medusa example, we are solving 2D Poisson's equation on unit square\n/// with Dirichlet boundary conditions.\n/// http://e6.ijs.si/medusa/wiki/index.php/Poisson%27s_equation\n\nusing namespace mm;  // NOLINT\n\nint main() {\n    // Create the domain and discretize it\n    BoxShape <Vec2d> box(0.0, 1.0);\n    double dx = 0.01;\n    DomainDiscretization <Vec2d> domain = box.discretizeWithStep(dx);\n\n    // Find support for the nodes\n    int N = domain.size();\n    domain.findSupport(FindClosest(9));  // the support for each node is the closest 9 nodes\n\n    // Construct the approximation engine, in this case a weighted least squares using monomials as\n    // basis functions, no weight, and scale to farthest\n    int m = 2;  // basis order\n    WLS <Monomials<Vec2d>, NoWeight<Vec2d>,\n    ScaleToFarthest> wls(Monomials<Vec2d>::tensorBasis(m));  // tensor basis of monomials\n    // up to order 2,\n    // {1,x,x2,y,yx,yx2,y2,y2x,y2x2}\n\n    // compute the shapes (we only need the Laplacian) using our WLS\n    auto storage = domain.computeShapes<sh::lap>(wls);\n\n    Eigen::SparseMatrix<double, Eigen::RowMajor> M(N, N);\n    Eigen::VectorXd rhs(N); rhs.setZero();\n    M.reserve(storage.supportSizes());\n\n    // construct implicit operators over our storage\n    auto op = storage.implicitOperators(M, rhs);\n    auto op3 = storage.implicitVectorOperators(M, rhs);\n\n    ExplicitVectorOperators<decltype(storage)> op2(storage);\n\n\n    for (int i : domain.interior()) {\n        double x = domain.pos(i, 0);\n        double y = domain.pos(i, 1);\n        // set the case for nodes in the domain\n\n        // op.lap(i) = -2 * PI * PI * std::sin(PI * x) * std::sin(PI * y);\n        op2.div(op2.grad(i, {-1, -1, -1}),{-1, -1, -1}) = -2 * PI * PI * std::sin(PI * x) * std::sin(PI * y);\n        // op.div(epsilon(i) * op.grad(i)) = epsilon(i) -3 * PI * PI * std::sin(PI * x) * std::sin(PI * y);\n    }\n    for (int i : domain.boundary()) {\n        // enforce the boundary conditions\n        op.value(i) = 0.0;\n    }\n\n    Eigen::BiCGSTAB<decltype(M), Eigen::IncompleteLUT<double>> solver;\n    solver.compute(M);\n    ScalarFieldd u = solver.solve(rhs);\n\n    // Write the solution into file\n    std::ofstream out_file(\"poisson_dirichlet_2D_data.m\");\n    out_file << \"positions = \" << domain.positions() << \";\" << std::endl;\n    out_file << \"solution = \" << u << \";\" << std::endl;\n    out_file.close();\n    return 0;\n}\n", "meta": {"hexsha": "b380f2635098c0f9c0fb283d4117d067320f6796", "size": 2500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "subprojects/molecular_dynamics/poisson_boltzmann/medusa/medusa_test.cpp", "max_stars_repo_name": "0xDBFB7/covidinator", "max_stars_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "subprojects/molecular_dynamics/poisson_boltzmann/medusa/medusa_test.cpp", "max_issues_repo_name": "0xDBFB7/covidinator", "max_issues_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "subprojects/molecular_dynamics/poisson_boltzmann/medusa/medusa_test.cpp", "max_forks_repo_name": "0xDBFB7/covidinator", "max_forks_repo_head_hexsha": "e9c103e5e62bc128169400998df5f5cd13bd8949", "max_forks_repo_licenses": ["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.7647058824, "max_line_length": 109, "alphanum_fraction": 0.6332, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6900702538880628}}
{"text": "// MIT License\n\n// Copyright (c) 2018 Benjamin Bercovici\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 STATE_HEADER \n#define STATE_HEADER\n\n#include <armadillo>\n\nnamespace OC{\n\n\tclass State{\n\n\tpublic:\n\n\t\tState(arma::vec state,double mu);\n\n\n\t\t/**\n\t\tComputes true anomaly from eccentric anomaly \n\t\t@param ecc eccentric anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_ecc(const double & ecc,const double & e);\n\n\t\t/**\n\t\tComputes eccentric anomaly eccentric from true anomaly\n\t\t@param f true anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return eccentric anomaly\n\t\t*/\n\t\tstatic double ecc_from_f(const double & f,const double & e);\n\n\t\t/**\n\t\tComputes hyperbolic anomaly from true anomaly \n\t\t@param f true anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return hyperbolic anomaly\n\t\t*/\n\t\tstatic double H_from_f(const double & f,const double & e);\n\n\t\t/**\n\t\tComputes true anomaly from hyperbolic anomaly\n\t\t@param H hyperbolic anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_H(const  double & H,const  double & e); \n\n\t\t/**\n\t\tComputes true anomaly from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_M(const double & M,const double & e);\n\n\t\t/**\n\t\tComputes eccentric anomaly eccentric from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@param pedantic if true, will print out convergence details\n\t\t@return eccentric anomaly\n\t\t*/\n\t\tstatic double ecc_from_M(const double & M,const double & e,const bool & pedantic = false);\n\t\t\n\n\t\t/**\n\t\tComputes hyperbolic anomaly eccentric from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@param pedantic if true, will print out convergence details\n\t\t@return hyperbolic anomaly\n\t\t*/\n\t\tstatic double H_from_M(const  double & M,const  double & e,const bool & pedantic = false);\n\t\t\n\n\t\t/**\n\t\tComputes mean anomaly from eccentric anomaly \n\t\t@param ecc eccentric anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_ecc(const double & ecc,const double & e);\n\n\t\t/**\n\t\tComputes mean anomaly from hyperbolic anomaly \n\t\t@param H hyperbolic anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_H(const double & H,const double & e);\n\n\t\t/**\n\t\tComputes mean anomaly from true anomaly \n\t\t@param f true anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_f(const double & f,const double & e);\n\n\t\tvirtual double get_momentum() const = 0;\n\t\tvirtual double get_energy() const = 0;\n\t\tvirtual double get_a() const = 0;\n\t\tvirtual double get_eccentricity() const = 0;\n\n\n\t\t/**\n\t\tGet the state vector\n\t\t@return 6x1 state vector (either cartesian state or keplerian state) \n\t\t*/\n\t\tarma::vec get_state() const;\n\n\t\t/**\n\t\tGet mean motion\n\t\t@return mean motion (rad/s)\n\t\t*/\n\t\tdouble get_n() const;\n\n\n\t\t/**\n\t\tGet ellipse parameter\n\t\t@return ellipse parameter (m)\n\t\t*/\n\t\tdouble get_parameter() const;\n\n\n\t\t/**\n\t\tGet standard gravitational parameter\n\t\t@return standard gravitational parameter (kg^3/s^2)\n\t\t*/\n\t\tdouble get_mu() const;\n\n\n\t\t/**\n\t\tSet standard gravitational parameter\n\t\t@param mu standard gravitational parameter (kg^3/s^2)\n\t\t*/\n\t\tvoid set_mu(double mu);\n\n\t\t/**\n\t\tSets the state to the prescribed value\n\t\t@param state 6x1 state\n\t\t*/\n\t\tvoid set_state(arma::vec state) ;\n\n\n\n\tprotected:\n\t\tarma::vec state;\n\t\tdouble mu;\n\n\t};\n\n}\n\n#endif", "meta": {"hexsha": "5cccdb6e04092b061abd5c90eae3c045b7b3b755", "size": 4507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OrbitConversions/State.hpp", "max_stars_repo_name": "bbercovici/OrbitConversions", "max_stars_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_stars_repo_licenses": ["MIT"], "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/OrbitConversions/State.hpp", "max_issues_repo_name": "bbercovici/OrbitConversions", "max_issues_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_issues_repo_licenses": ["MIT"], "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/OrbitConversions/State.hpp", "max_forks_repo_name": "bbercovici/OrbitConversions", "max_forks_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_forks_repo_licenses": ["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.6079545455, "max_line_length": 92, "alphanum_fraction": 0.7080097626, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.690059882735106}}
{"text": "#include \"Geometry3D.hpp\"\n\n#include <Eigen/Dense>\n#include <numeric>\n\nnamespace pointcloudhandler {\n\n\t\tEigen::Vector3d Geometry3D::ComputeMinBound(const std::vector<Eigen::Vector3d>& points) const \n\t\t{\n\t\t\tif (points.empty()) \n\t\t\t{\n\t\t\t\treturn Eigen::Vector3d(0.0, 0.0, 0.0);\n\t\t\t}\n\t\t\treturn std::accumulate(points.begin(), points.end(), points[0],\n\t\t\t\t[](const Eigen::Vector3d& a, const Eigen::Vector3d& b) \n\t\t\t{\n\t\t\t\treturn a.array().min(b.array()).matrix();\n\t\t\t});\n\t\t}\n\n\t\tEigen::Vector3d Geometry3D::ComputeMaxBound(const std::vector<Eigen::Vector3d>& points) const \n\t\t{\n\t\t\tif (points.empty()) {\n\t\t\t\treturn Eigen::Vector3d(0.0, 0.0, 0.0);\n\t\t\t}\n\t\t\treturn std::accumulate(points.begin(), points.end(), points[0],\n\t\t\t\t[](const Eigen::Vector3d& a, const Eigen::Vector3d& b) \n\t\t\t{\n\t\t\t\treturn a.array().max(b.array()).matrix();\n\t\t\t});\n\t\t}\n\n\t\tEigen::Vector3d Geometry3D::ComputeCenter(const std::vector<Eigen::Vector3d>& points) const \n\t\t{\n\t\t\tEigen::Vector3d center(0, 0, 0);\n\t\t\tif (points.empty()) \n\t\t\t{\n\t\t\t\treturn center;\n\t\t\t}\n\t\t\tcenter = std::accumulate(points.begin(), points.end(), center);\n\t\t\tcenter /= double(points.size());\n\t\t\treturn center;\n\t\t}\n\n\t\tvoid Geometry3D::TransformPoints(const Eigen::Matrix4d& transformation, std::vector<Eigen::Vector3d>& points) const \n\t\t{\n\t\t\tfor (auto& point : points) \n\t\t\t{\n\t\t\t\tEigen::Vector4d newPoint = transformation * Eigen::Vector4d(point(0), point(1), point(2), 1.0);\n\t\t\t\tpoint = newPoint.head<3>() / newPoint(3);\n\t\t\t}\n\t\t}\n\n\t\tvoid Geometry3D::TranslatePoints(const Eigen::Vector3d& translation, std::vector<Eigen::Vector3d>& points, bool relative) const \n\t\t{\n\t\t\tEigen::Vector3d transform = translation;\n\t\t\tif (!relative) \n\t\t\t{\n\t\t\t\ttransform -= ComputeCenter(points);\n\t\t\t}\n\t\t\tfor (auto& point : points) \n\t\t\t{\n\t\t\t\tpoint += transform;\n\t\t\t}\n\t\t}\n\n\t\tvoid Geometry3D::ScalePoints(const double scale, std::vector<Eigen::Vector3d>& points, bool center) const \n\t\t{\n\t\t\tEigen::Vector3d pointsCenter(0, 0, 0);\n\t\t\tif (center && !points.empty()) \n\t\t\t{\n\t\t\t\tpointsCenter = ComputeCenter(points);\n\t\t\t}\n\t\t\tfor (auto& point : points) \n\t\t\t{\n\t\t\t\tpoint = (point - pointsCenter) * scale + pointsCenter;\n\t\t\t}\n\t\t}\n\n\t\tvoid Geometry3D::RotatePoints(const Eigen::Matrix3d& R, std::vector<Eigen::Vector3d>& points, bool center) const \n\t\t{\n\t\t\tEigen::Vector3d pointsCenter(0, 0, 0);\n\t\t\tif (center && !points.empty()) \n\t\t\t{\n\t\t\t\tpointsCenter = ComputeCenter(points);\n\t\t\t}\n\t\t\tfor (auto& point : points) \n\t\t\t{\n\t\t\t\tpoint = R * (point - pointsCenter) + pointsCenter;\n\t\t\t}\n\t\t}\n\n\n}  // namespace pointcloudfilter", "meta": {"hexsha": "dea2f6643ec317945af13a44002e93f7e32f9038", "size": 2510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PointCloudHandler/PointCloud/Geometry3D.cpp", "max_stars_repo_name": "serjik85kg/PointCloudHandler", "max_stars_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PointCloudHandler/PointCloud/Geometry3D.cpp", "max_issues_repo_name": "serjik85kg/PointCloudHandler", "max_issues_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudHandler/PointCloud/Geometry3D.cpp", "max_forks_repo_name": "serjik85kg/PointCloudHandler", "max_forks_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_forks_repo_licenses": ["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.7021276596, "max_line_length": 130, "alphanum_fraction": 0.6386454183, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.6900189069645639}}
{"text": "//  (C) Copyright Gennadiy Rozental 2011-2015.\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//  See http://www.boost.org/libs/test for the library home page.\n\n//[example_code\n#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE( test )\n{\n  // sin 45 radians is actually ~ 0.85, sin 45 degrees is ~0.707\n  double res = std::sin( 45. ); \n\n  BOOST_WARN_MESSAGE( res < 0.71, \n                      \"sin(45){\" << res << \"} is > 0.71. Arg is not in radian?\" );\n}\n//]\n", "meta": {"hexsha": "a9682ef2ecc54212bc541918bac2afcaba33f8e8", "size": 642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/example38.run.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "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": "thirdparty/boost_1_71_0/libs/test/doc/examples/example38.run.cpp", "max_issues_repo_name": "anonymouscode1/djxperf", "max_issues_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/test/doc/examples/example38.run.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "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": 27.9130434783, "max_line_length": 82, "alphanum_fraction": 0.6635514019, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6899470862627071}}
{"text": "// lu_decomposition.cpp example program comparing float vs posit equation solver\n//\n// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"common.hpp\"\n\n#include <iostream>\n#include <typeinfo>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <universal/posit/posit>\n\nusing namespace std;\nusing namespace sw::unum;\n\n// Turn it off for now\n#define USE_POSIT\n\nint main(int argc, char** argv)\ntry {\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\n#ifdef USE_POSIT\n\tusing Matrix = mtl::dense2D< posit<nbits, es> >;\n\tusing Vector = mtl::dense_vector< posit<nbits, es> >;\n#else\n\tusing Matrix = mtl::dense2D<float>;\n\tusing Vector = mtl::dense_vector<float>;\n#endif\n\n\n\tMatrix  A(4, 4), L(4, 4), U(4, 4), AA(4, 4);\n\tVector\tv(4);\n\tdouble \tc = 1.0;\n\t\n\tfor (unsigned i = 0; i < 4; i++)\n\t\tfor (unsigned j = 0; j < 4; j++) {\n\t\t\tU[i][j] = i <= j ? c * (i + j + 2) : (0);\n\t\t\tL[i][j] = i > j ? c * (i + j + 1) : (i == j ? (1) : (0));\n\t\t}\n\n\tstd::cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n\tA = L * U;\n\tstd::cout << \"A is:\\n\" << A;\n\tAA = adjoint(A);\n\n\tfor (unsigned i = 0; i < 4; i++)\n\t\tv[i] = double(i);\n\n\tVector b(A*v), b2(adjoint(A)*v);\n\n\tMatrix LU(A);\n\tlu(LU);\n\tstd::cout << \"LU decomposition of A is:\\n\" << LU;\n\n\tMatrix B(lu_f(A));\n\tstd::cout << \"LU decomposition of A (as function result) is:\\n\" << B;\n\n\tVector v1(lu_solve_straight(A, b));\n\tstd::cout << \"v1 is \" << v1 << \"\\n\";\n\n\tVector v2(lu_solve(A, b));\n\tstd::cout << \"v2 is \" << v2 << \"\\n\";\n\n\tmtl::dense_vector<unsigned> P;\n\tlu(A, P);\n\tstd::cout << \"LU with pivoting is \\n\" << with_format(A, 5, 2) << \"Permutation is \" << P << \"\\n\";\n\tVector v3(lu_apply(A, P, b));\n\tstd::cout << \"v3 is \" << v3 << \"\\n\";\n\n\tVector v4(lu_adjoint_apply(A, P, b2));\n\tstd::cout << \"v4 is \" << v4 << \"\\n\";\n\n\tVector v5(lu_adjoint_solve(AA, b));\n\tstd::cout << \"v5 is \" << v5 << \"\\n\";\n\n\tint nrOfFailedTestCases = 0;\n\treturn nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tcerr << msg << 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\tcerr << \"caught unknown exception\" << endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "f6f1d86ae1f1bd88a553515b6527c6c32d1e1217", "size": 2731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/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": "applications/blas/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": "applications/blas/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": 25.287037037, "max_line_length": 106, "alphanum_fraction": 0.6151592823, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6898640307983782}}
{"text": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include <pinocchio/math/rpy.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_rpyToMatrix)\n{\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n\n  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(r, p, y);\n\n  Eigen::Matrix3d R_Eig = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())\n                           * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                           * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())\n                          ).toRotationMatrix();\n\n  BOOST_CHECK(R.isApprox(R_Eig));\n\n  Eigen::Vector3d v;\n  v << r, p, y;\n\n  Eigen::Matrix3d Rv = pinocchio::rpy::rpyToMatrix(v);\n\n  BOOST_CHECK(Rv.isApprox(R_Eig));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrixToRpy)\n{\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n\n  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(r, p, y);\n\n  Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n\n  BOOST_CHECK_CLOSE(r,v[0],1e-12);\n  BOOST_CHECK_CLOSE(p,v[1],1e-12);\n  BOOST_CHECK_CLOSE(y,v[2],1e-12);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "cd7ac131a8b9949b1e5b5cd5ad07149bd19a1a6a", "size": 1656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rpy.cpp", "max_stars_repo_name": "yDMhaven/pinocchio", "max_stars_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T07:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T07:23:34.000Z", "max_issues_repo_path": "unittest/rpy.cpp", "max_issues_repo_name": "yDMhaven/pinocchio", "max_issues_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/rpy.cpp", "max_forks_repo_name": "yDMhaven/pinocchio", "max_forks_repo_head_hexsha": "fabed17d5ad0dc1c8d251c64cfa656a0215469a5", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6666666667, "max_line_length": 95, "alphanum_fraction": 0.6533816425, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.800692004473946, "lm_q1q2_score": 0.6898267444539964}}
{"text": "// Group A - Exact Pricing Methods\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-9-19\r\n//\r\n// NormalDistribution.hpp\r\n//\r\n// Function pertaining to the normal distribution including the CDF and PDF.\r\n// Used in option pricing. \r\n\r\n#ifndef NormalDistribution_hpp\r\n#define NormalDistribution_hpp\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <boost/math/distributions.hpp> \r\nusing namespace boost::math;\r\n\r\n\r\ndouble N(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn cdf(myNormal, x);\r\n\r\n}\r\n\r\ndouble n(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn pdf(myNormal, x);\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "d6c37ce871d3b1d81bdfd907de28961b2be5bb94", "size": 672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GroupA/GroupA/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": "GroupA/GroupA/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": "GroupA/GroupA/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": 16.0, "max_line_length": 77, "alphanum_fraction": 0.6785714286, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6897480935762412}}
{"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// purely phenomenological relations in superconductivity\nnamespace phenomenology {\n\n// temperature dependence of the (reduced) penetration depth\ntemplate <typename T = double>\nT reduced_penetration_depth(T reduced_temperature, T exponent) {\n  if (reduced_temperature >= 1.0) {\n    return std::numeric_limits<T>::infinity();\n  } else if (reduced_temperature <= 0.0) {\n    return 1.0;\n  } else {\n    return 1.0 / std::sqrt(1.0 - std::pow(reduced_temperature, exponent));\n  }\n}\n\n// temperature dependence of the (reduced) penetration depth\ntemplate <typename T = double>\nT reduced_penetration_depth(T temperature, T critical_temperature, T exponent) {\n  return reduced_penetration_depth<T>(temperature / critical_temperature,\n                                      exponent);\n}\n\n// temperature dependence of the penetration depth\ntemplate <typename T = double>\nT penetration_depth(T temperature, T critical_temperature, T exponent,\n                    T lambda_0) {\n  return lambda_0 * reduced_penetration_depth<T>(\n                        temperature, critical_temperature, exponent);\n}\n\n// reduced gap\n// after Halbritter ca. 1970\ntemplate <typename T = double> T reduced_gap(T reduced_temperature) {\n  if (reduced_temperature >= 1.0) {\n    return 0.0;\n  } else if (reduced_temperature <= 0.0) {\n    return 1.0;\n  } else {\n    return std::cos(boost::math::constants::half_pi<T>() *\n                    std::pow(reduced_temperature, 2));\n  }\n}\n\n/// The superconducting transition temperature T_c (K) as a function of applied\n/// magnetic field. The calculation assumes a \"parabolic\" relationship by\n/// default (i.e., exponent = 0.5).\ntemplate <typename T = double>\nT critical_temperature(T applied_field, T critical_temperature_0,\n                       T critical_field, T exponent = 0.5) {\n  if (applied_field < 0.0) {\n    // don't consider negative fields\n    return critical_temperature_0;\n  } else if (applied_field > critical_field) {\n    // no superconductivity above the critical field\n    return 0.0;\n  } else {\n    // the phenomenological field dependence\n    return critical_temperature_0 *\n           std::pow(1.0 - (applied_field / critical_field), exponent);\n  }\n}\n\n/// The superconducting transition temperature T_c (K) as a function of applied\n/// magnetic field. The calculation assumes a relationship obtained from\n/// inverting: Hc2(T) / Hc2(0) = [1 - (T / Tc)^2] / [1 + (T / Tc)^2]. See e.g.,:\n/// M. Tinkham, Phys. Rev. 129, 2413 (1963).\n/// https://doi.org/10.1103/PhysRev.129.2413\ntemplate <typename T = double>\nT critical_temperature_II(T applied_field, T critical_temperature_0,\n                          T upper_critical_field) {\n  if (applied_field < 0.0) {\n    // don't consider negative fields\n    return critical_temperature_0;\n  } else if (applied_field > upper_critical_field) {\n    // no superconductivity above the critical field\n    return 0.0;\n  } else {\n    // reduced field\n    T reduced_field = applied_field / upper_critical_field;\n    // the phenomenological field dependence\n    return critical_temperature_0 *\n           std::sqrt((1.0 - reduced_field * reduced_field) /\n                     (1.0 + reduced_field * reduced_field));\n  }\n}\n\n} // namespace phenomenology\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n", "meta": {"hexsha": "77acadf0f98b620bb2af06fb9efeb07a38097311", "size": 3591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/superconductivity/phenomenology.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/superconductivity/phenomenology.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/superconductivity/phenomenology.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.5607476636, "max_line_length": 80, "alphanum_fraction": 0.693678641, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6896504545682296}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[union\n//` Shows how to get a united geometry of two polygons\n\n#include <iostream>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\n\n#include <boost/foreach.hpp>\n/*<-*/ #include \"create_svg_overlay.hpp\" /*->*/\n\nint main()\n{\n    typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\n    polygon green, blue;\n\n    boost::geometry::read_wkt(\n        \"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)\"\n            \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", green);\n\n    boost::geometry::read_wkt(\n        \"POLYGON((4.0 -0.5 , 3.5 1.0 , 2.0 1.5 , 3.5 2.0 , 4.0 3.5 , 4.5 2.0 , 6.0 1.5 , 4.5 1.0 , 4.0 -0.5))\", blue);\n\n    std::vector<polygon> output;\n    boost::geometry::union_(green, blue, output);\n\n    int i = 0;\n    std::cout << \"green || blue:\" << std::endl;\n    BOOST_FOREACH(polygon const& p, output)\n    {\n        std::cout << i++ << \": \" << boost::geometry::area(p) << std::endl;\n    }\n\n    /*<-*/ create_svg(\"union.svg\", green, blue, output); /*->*/\n    return 0;\n}\n\n//]\n\n\n//[union_output\n/*`\nOutput:\n[pre\ngreen || blue:\n0: 5.64795\n\n[$img/algorithms/union.png]\n\n]\n*/\n//]\n\n", "meta": {"hexsha": "84ab620c6b426e7e32f9bc5ba44ac7f25f62aba1", "size": 1662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/union.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/union.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/union.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "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": 24.8059701493, "max_line_length": 118, "alphanum_fraction": 0.6179302046, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.8152324983301568, "lm_q1q2_score": 0.68963977927582}}
{"text": "//\n// Created by tomlucas on 26.06.20.\n//\n\n#include \"types/SO3.h\"\n#include <vector>\n#include \"GaussianNoiseVector.h\"\n#include \"adekf_viz.h\"\n#include <Eigen/Eigenvalues>\n\n#define max_iterations 100\n#define weighted_mean_epsilon 1e-12\nusing namespace adekf;\n\n/**\n * Calculate the weighted mean of quaternions\n * @param quats  list of quaternions\n * @param probs the corresponding probabilities\n * @return The weighted mean of quats\n */\nSO3d weightedMean(std::vector<SO3d> &quats, std::vector<double> &probs)\n{\n    SO3d sum = quats[0];\n    SO3d old_sum = sum;\n    decltype(sum - old_sum) diff_sum = diff_sum.Zero();\n    decltype(sum - old_sum) selector_weights = selector_weights.Zero();\n\n    int iterations = 0;\n    do\n    {\n        iterations++;\n        old_sum = sum;\n        diff_sum = diff_sum.Zero();\n        for (int i = 0; i < quats.size(); i++)\n        {\n            diff_sum = diff_sum + probs[i] * (quats[i] - sum); //.cwiseProduct(selectors[filter_bank[i].second]);\n        }\n        sum = sum + diff_sum; //.cwiseQuotient(selector_weights);\n    } while (iterations <= max_iterations && (sum - old_sum).norm() > weighted_mean_epsilon);\n    if (iterations > max_iterations)\n        printf(\"Warning: stopped due to excess of iterations\");\n    return sum;\n}\n\n/**\n * Calculate the weighted covariance of quaternion distributions\n * @param quats The list of mean points of the distributions\n * @param covs The covariances of the distributions\n * @param probs The weights of the distributions\n * @param target The weighted mean of the means\n * @return The weighted covariance sum\n */\nEigen::Matrix3d weightedCovarianceSum(std::vector<SO3d> &quats, std::vector<Eigen::Matrix3d> &covs, std::vector<double> &probs, const SO3d &target)\n{\n    Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n    Eigen::Matrix3d weights = Eigen::Matrix3d::Zero();\n    for (size_t i = 0; i < quats.size(); i++)\n    {\n        if (probs[i] > 0.)\n        {\n            auto diff = (quats[i] - target).eval();\n            auto plus_diff = eval((quats[i] + getDerivator<3>()) - target);\n            Eigen::Matrix<double, 3, 3> D(3, 3);\n            //Initialise the Jacobian\n            for (size_t j = 0; j < 3; ++j)\n                D.col(j) = plus_diff[j].v; //write to cols since col major (transposes matrix )\n            //Covariance select = selectors[filter_bank[i].second] * selectors[filter_bank[i].second].transpose() * probabilities(i);\n            sum += probs[i] * (D.transpose() * (covs[i]) * D + diff * diff.transpose());\n            //weights += select;\n        }\n    }\n    assert(sum.determinant() > 0.);\n    return sum;\n}\n\n/**\n * Calculates the weighted mean of quaternions with naive/improper mixing (in parameter space)\n * @param quats The quaternions to mix\n * @param probs The weights\n * @return Weighted mean of quats\n */\nSO3d badWeightedMean(std::vector<SO3d> &quats, std::vector<double> &probs)\n{\n    Eigen::Vector4d sum = sum.Zero();\n    for (int i = 0; i < quats.size(); i++)\n    {\n        sum += quats[i].coeffs() * probs[i];\n    }\n    sum = sum.normalized();\n    return SO3d(sum.data());\n}\n/**\n * Calculates a numeric gold standard Variance of quats.\n *\n * Uses a list of uniformly sampled quaternions from the distributions and combines them with the proper mixing\n *\n * @param quats The list of uniformly sampled quaternions\n * @param probs The probabilities of the quaternioms\n * @param target The weighted mean of means of the distributions\n * @return The weighted covariance sum\n */\nEigen::Matrix3d goldWeightedCovarianceSum(std::vector<SO3d> &quats, std::vector<double> &probs, const SO3d &target)\n{\n\n    Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n    for (size_t i = 0; i < quats.size(); i++)\n    {\n        if (probs[i] > 0.)\n        {\n            auto diff = (quats[i] - target).eval();\n            sum += probs[i] * (diff * diff.transpose());\n        }\n    }\n    return sum;\n}\n\n/**\n * Improper way of the weighted sum of covariances.\n *\n * Uses the naive approach from the original IMM\n * @param quats The list of quaternion means\n * @param covs The covariances\n * @param probs The weights of the quaternions\n * @param target The weighted mean of means\n * @return The naive weighted covariance sum\n */\nEigen::Matrix3d badWeightedCovarianceSum(std::vector<SO3d> &quats, std::vector<Eigen::Matrix3d> &covs, std::vector<double> &probs, const SO3d &target)\n{\n\n    Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n    for (size_t i = 0; i < quats.size(); i++)\n    {\n        if (probs[i] > 0.)\n        {\n            auto diff = (quats[i] - target).eval();\n            sum += probs[i] * (covs[i] + diff * diff.transpose());\n        }\n    }\n    return sum;\n}\n\n/**\n * Calculates the difference between the bp-weighted mean and the naive weighted mean\n * @param quats List of quaternions\n * @param probs weights\n * @return BPMean-NaiveMean\n */\ndouble diff(std::vector<SO3d> &quats, std::vector<double> &probs)\n{\n    return (weightedMean(quats, probs) - badWeightedMean(quats, probs)).norm();\n}\n\n/**\n * Plots the naive mixing vs the boxplus mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_bad_vs_bp()\n{\n    std::vector<SO3d> quats;\n    std::vector<std::vector<double>> probs;\n    std::vector<Eigen::Matrix3d> covs;\n    covs.push_back(Eigen::Matrix3d::Identity() * 0.01);\n    covs.push_back(Eigen::Matrix3d::Identity() * 0.02);\n\n    quats.push_back(SO3d(Eigen::Vector3d(0, 0, 0)));\n    quats.push_back(SO3d(Eigen::Vector3d(0, 0, 0.0)));\n    std::vector<double> trial{0.7, 0.3};\n    std::cout << weightedMean(quats, trial) << std::endl;\n    //return 0;\n    //list of probability pairs\n    for (double prob = 0.5; prob <= 1.; prob += 0.05)\n    {\n        probs.push_back(std::vector<double>(2));\n        probs.back()[0] = prob;\n        probs.back()[1] = 1. - prob;\n    }\n    //compute for different sigmas\n    for (double sigma = 0.0; sigma < 3.; sigma += 0.01)\n    {\n        quats[1] = SO3d{Eigen::Vector3d(0, 0, sigma)};\n        Eigen::Matrix<double, -1, 1> diffs = diffs.Zero(probs.size());\n        //compute mean diff for different probabilities\n        for (int i = 0; i < probs.size(); i++)\n        {\n            diffs(i) = diff(quats, probs[i]);\n        }\n        std::cout << \"Sigma: \" << sigma << \" Max diff: \" << diffs.maxCoeff() << \" Diffs: \" << diffs.transpose() << std::endl;\n        adekf::viz::plotVector(diffs, \"Mean diff\", 300, \"abcdefghiklmn\");\n        //compute covariance diff for different probabilities\n        for (int i = 0; i < probs.size(); i++)\n        {\n            diffs(i) = (weightedCovarianceSum(quats, covs, probs[i], weightedMean(quats, probs[i])) - badWeightedCovarianceSum(quats, covs, probs[i], badWeightedMean(quats, probs[i]))).norm();\n        }\n        std::cout << \"Sigma: \" << sigma << \" Max diff: \" << diffs.maxCoeff() << \" Diffs: \" << diffs.transpose() << std::endl;\n        adekf::viz::plotVector(diffs, \"Sigma diff\", 300, \"abcdefghiklmn\");\n    }\n}\n\n/**\n * Calculates the likelihood of a vector given the covariance of the distribution\n * @param delta the vector to check the likelihood of\n * @param sigma The covariance\n * @return N(delta; 0, sigma)\n */\ndouble likelihood(const Eigen::Vector3d &delta, const Eigen::Matrix3d &sigma)\n{\n    return exp(-0.5 * (delta).transpose() * sigma.inverse() * delta) / sqrt(sigma.determinant() * pow((2 * M_PI), sigma.rows()));\n}\n\n/**\n * Plots a numeric gold standard mixing against the naive mixing and the bp-mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_real_gold_vs_()\n{\n    std::vector<SO3d> quats(2);\n    std::vector<double> probs{0.7, 0.3};\n\n    std::vector<Eigen::Matrix3d> covs;\n    covs.push_back(Eigen::Matrix3d::Identity() * 0.01);\n    covs.push_back(Eigen::Matrix3d::Identity() * 0.02);\n    //Compute for different sigmas\n    for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n    {\n        quats[0] = (SO3d(Eigen::Vector3d(0, 0, 0)));\n        quats[1] = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n        //return 0;\n\n        const double max = M_PI / 2;\n        const double step = 0.02;\n        const int steps = max / step;\n        std::vector<SO3d> gold_quats(pow(steps, 3));\n        std::vector<double> gold_probs(pow(steps, 3));\n        //uniform sample of quaternions from distributions\n        for (int l = 0; l < probs.size(); ++l)\n        {\n\n            for (int i = -steps; i < steps; i++)\n            {\n                for (int j = -steps; j < steps; j++)\n                {\n                    for (int k = -steps; k < steps; ++k)\n                    {\n                        Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n                        gold_quats.push_back(quats[l] + delta);\n                        gold_probs.push_back(likelihood(delta, covs[l]) * probs[l]);\n                    }\n                }\n            }\n        }\n        double sum = 0;\n        //normalise probabilities of sampled quats\n        for (const auto &prob : gold_probs)\n        {\n            sum += prob;\n        }\n        for (auto &prob : gold_probs)\n        {\n            prob /= sum;\n        }\n        sum = 0;\n        //compute means\n        auto mean = weightedMean(quats, probs);\n        auto badMean = badWeightedMean(quats, probs);\n        auto goldMean = weightedMean(gold_quats, gold_probs);\n        Eigen::Matrix<double, 2, 1> diffs = diffs.Zero();\n        diffs(0) = (mean - goldMean).norm();\n        diffs(1) = (badMean - goldMean).norm();\n        adekf::viz::plotVector(diffs, \"Gold Mean diff\", 305, \"mb\");\n        auto goldCov = goldWeightedCovarianceSum(gold_quats, gold_probs, goldMean);\n        diffs(0) = (weightedCovarianceSum(quats, covs, probs, mean) - goldCov).norm();\n        diffs(1) = (badWeightedCovarianceSum(quats, covs, probs, badMean) - goldCov).norm();\n        adekf::viz::plotVector(diffs, \"Gold Sigma diff\", 305, \"mb\");\n    }\n}\n\nEigen::Vector3d weightedRefMean(aligned_vector<SO3d> &quats, std::vector<double> &probs, SO3d ref)\n{\n    Eigen::Vector3d sum = sum.Zero();\n\n    for (int i = 0; i < quats.size(); i++)\n    {\n        sum = sum + probs[i] * (quats[i] - ref);\n    }\n    return sum;\n}\n\n/**\n * Calculates a numeric gold standard Variance of quats.\n *\n * Uses a list of uniformly sampled quaternions from the distributions and combines them with the proper mixing\n *\n * @param quats The list of uniformly sampled quaternions\n * @param probs The probabilities of the quaternioms\n * @param target The weighted mean of means of the distributions\n * @return The weighted covariance sum\n */\nEigen::Matrix3d goldWeightedCovarianceSumRef(aligned_vector<SO3d> &quats, std::vector<double> &probs, const SO3d &ref)\n{\n\n    Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n    Eigen::Vector3d mu_ref = weightedRefMean(quats, probs, ref);\n    for (size_t i = 0; i < quats.size(); i++)\n    {\n        if (probs[i] > 0.)\n        {\n            auto diff = ((quats[i] - ref) - mu_ref).eval();\n            sum += probs[i] * (diff * diff.transpose());\n        }\n    }\n    return sum;\n}\n\n/**\n * Plots a numeric gold standard mixing against the naive mixing and the bp-mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_covariance_centered()\n{\n    SO3d r1, r2; //r1 r2\n\n    Eigen::Matrix3d cov = cov.Identity() * 0.1;\n    //Compute for different sigmas\n    for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n    {\n        r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n        r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n        Eigen::Vector3d diff = r2 - r1;\n        const double max = M_PI / 2;\n        const double step = 0.02;\n        const int steps = max / step;\n        aligned_vector<SO3d> gold_quats(pow(steps, 3));\n        std::vector<double> gold_probs(pow(steps, 3));\n        //uniform sample of quaternions from distribution\n\n        for (int i = -steps; i < steps; i++)\n        {\n            for (int j = -steps; j < steps; j++)\n            {\n                for (int k = -steps; k < steps; ++k)\n                {\n                    Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n                    gold_quats.push_back(r1 + (diff + delta));\n                    gold_probs.push_back(likelihood(delta, cov));\n                }\n            }\n        }\n        double sum = 0;\n        //normalise probabilities of sampled quats\n        for (const auto &prob : gold_probs)\n        {\n            sum += prob;\n        }\n        for (auto &prob : gold_probs)\n        {\n            prob /= sum;\n        }\n        sum = 0;\n        //compute means\n\n        Eigen::Matrix<double, 2, 1> diffs = diffs.Zero();\n        auto goldCov = goldWeightedCovarianceSumRef(gold_quats, gold_probs, r2);\n        auto transform = transformReferenceJacobian(r1, r2, diff);\n        auto linearCov = transform * cov * transform.transpose();\n        diffs(0)=(linearCov-goldCov).norm();\n        diffs(1)=(cov-goldCov).norm();\n        //diffs(0) = goldCov.determinant();\n        adekf::viz::plotVector(diffs, \"Covariance transform centered\", 61, \"mb\");\n    }\n}\n\nvoid plot_covariance_displaced()\n{\n    SO3d r1, r2; //r1 r2\n\n    Eigen::Matrix3d cov = cov.Identity() * 0.1;\n    //Compute for different sigmas\n    for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n    {\n        r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n        r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n        Eigen::Vector3d diff = r2 - r1;\n        const double max = M_PI / 2;\n        const double step = 0.02;\n        const int steps = max / step;\n        aligned_vector<SO3d> gold_quats(pow(steps, 3));\n        std::vector<double> gold_probs(pow(steps, 3));\n        //uniform sample of quaternions from distribution\n\n        for (int i = -steps; i < steps; i++)\n        {\n            for (int j = -steps; j < steps; j++)\n            {\n                for (int k = -steps; k < steps; ++k)\n                {\n                    Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n                    gold_quats.push_back(r1 + (delta));\n                    gold_probs.push_back(likelihood(delta, cov));\n                }\n            }\n        }\n        double sum = 0;\n        //normalise probabilities of sampled quats\n        for (const auto &prob : gold_probs)\n        {\n            sum += prob;\n        }\n        for (auto &prob : gold_probs)\n        {\n            prob /= sum;\n        }\n        sum = 0;\n        //compute means\n\n        Eigen::Matrix<double, 2, 1> diffs = diffs.Zero();\n        auto goldCov = goldWeightedCovarianceSumRef(gold_quats, gold_probs, r2);\n        auto transform = transformReferenceJacobian(r1, r2);\n        auto linearCov = transform * cov * transform.transpose();\n        diffs(0)=(linearCov-goldCov).norm();\n        diffs(1)=(cov-goldCov).norm();\n        //diffs(0) = goldCov.determinant();\n        adekf::viz::plotVector(diffs, \"Covariance transform displaced\", 61, \"mb\");\n    }\n}\n\n\nvoid plot_covariance_gold()\n{\n    SO3d r1, r2; //r1 r2\n\n    Eigen::Matrix3d cov = cov.Identity() * 0.1;\n    //Compute for different sigmas\n    for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n    {\n        r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n        r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n        Eigen::Vector3d diff = r2 - r1;\n        const double max = M_PI / 2;\n        const double step = 0.02;\n        const int steps = max / step;\n        aligned_vector<SO3d> gold_quats_centered(pow(steps, 3));\n       \n        aligned_vector<SO3d> gold_quats_displaced(pow(steps, 3));\n       \n        std::vector<double> gold_probs(pow(steps, 3));\n\n        //uniform sample of quaternions from distribution\n\n        for (int i = -steps; i < steps; i++)\n        {\n            for (int j = -steps; j < steps; j++)\n            {\n                for (int k = -steps; k < steps; ++k)\n                {\n                    Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n                    gold_quats_displaced.push_back(r1 + (delta));\n                    gold_quats_centered.push_back(r1+(diff+delta));\n                    gold_probs.push_back(likelihood(delta, cov));\n                }\n            }\n        }\n        double sum = 0;\n        //normalise probabilities of sampled quats\n        for (const auto &prob : gold_probs)\n        {\n            sum += prob;\n        }\n        for (auto &prob : gold_probs)\n        {\n            prob /= sum;\n        }\n        sum = 0;\n        //compute means\n\n        Eigen::Matrix<double, 3, 1> diffs = diffs.Zero();\n        auto goldCovDisplaced = goldWeightedCovarianceSumRef(gold_quats_displaced, gold_probs, r2);\n        auto goldCovCentered=goldWeightedCovarianceSumRef(gold_quats_centered,gold_probs,r2);\n        diffs(0)=goldCovDisplaced.determinant()/cov.determinant();\n        diffs(1)=goldCovCentered.determinant()/cov.determinant();\n        diffs(2)=diffs(0)*diffs(1);\n\n\n        //diffs(0) = goldCov.determinant();\n        adekf::viz::plotVector(diffs, \"Covariance transform gold\", 61, \"DCM\");\n        auto transform = transformReferenceJacobian(r1, r2);\n        auto linearCov = (transform * cov * transform.transpose()).eval();\n        diffs(0)=linearCov.determinant()/cov.determinant();\n        transform=transformReferenceJacobian(r1,r2,diff);\n        linearCov = transform * cov * transform.transpose();\n        diffs(1)=linearCov.determinant()/cov.determinant();\n        diffs(2)=diffs(0)*diffs(1);\n        adekf::viz::plotVector(diffs, \"Covariance transform linear\", 61, \"DCM\");\n    }\n}\n\nstd::vector<std::thread> threads;\nauto parallel=[](auto function){ threads.emplace_back(function);};\nint main(int argc, char *argv[])\n{\n    viz::initGuis(argc, argv);\n    \n    //Choose some to plot\n    //parallel(plot_bad_vs_bp);\n    //parallel(plot_real_gold_vs_);//takes really long ~10 min\n    //parallel(plot_covariance_displaced);\n    //parallel(plot_covariance_centered); \n    parallel(plot_covariance_gold);\n    viz::runGuis();\n    for(auto & thread: threads) thread.join();\n    return 0;\n}", "meta": {"hexsha": "ea56ee99dc7a8fa29f35797ee9fc3529ffb0cf23", "size": 17908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuatMixing.cpp", "max_stars_repo_name": "TomLKoller/Boxplus-IMM", "max_stars_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T08:50:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T13:45:56.000Z", "max_issues_repo_path": "QuatMixing.cpp", "max_issues_repo_name": "TomLKoller/Boxplus-IMM", "max_issues_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-16T06:50:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T13:37:04.000Z", "max_forks_repo_path": "QuatMixing.cpp", "max_forks_repo_name": "TomLKoller/Boxplus-IMM", "max_forks_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T08:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:39:15.000Z", "avg_line_length": 34.8404669261, "max_line_length": 192, "alphanum_fraction": 0.5869443824, "num_tokens": 5015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6896240167433088}}
{"text": "/*\n * euclidean.hpp\n *\n *  Created on: Aug 16, 2009\n *      Author: stewie\n */\n\n#ifndef EUCLIDEAN_HPP_\n#define EUCLIDEAN_HPP_\n\n#include <cmath>\n#include <functional> // for std::plus\n#include <numeric> // for std::inner_product\n\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n\n/**\n * @ingroup lab\n *\n * @file euclidean.hpp\n *\n * This file contains routines for computing various kinds of distances between\n * attractors and other objects.\n */\n\nnamespace bn {\n\nnamespace detail {\n\n/**\n * @private\n * Helper class to compute a squared difference.\n */\nstruct SquareDifference {\n\t/**\n\t * Result type of this function object.\n\t */\n\ttypedef double result_type;\n\n\t/**\n\t * Computes a squared difference.\n\t * @param x an object\n\t * @param y another object\n\t * @return the squared difference\n\t */\n\ttemplate<class T> result_type operator()(const T& x, const T& y) const {\n\t\treturn std::pow(x - y, 2);\n\t}\n};\n\n}\n\n/**\n * @ingroup lab\n *\n * Computes the euclidean distance between two ranges.\n *\n * The second range shall have at least as many elements as the first.\n * @param first1 input iterator to the initial position of the first range\n * @param last1 input iterator to the final position of the first range\n * @param first2 input iterator to the initial position of the second range\n * @return the euclidean distance\n */\ntemplate<class InputIterator> double euclidean_distance(\n\t\tconst InputIterator first1, const InputIterator last1,\n\t\tconst InputIterator first2) {\n\treturn std::sqrt(std::inner_product(first1, last1, first2, 0.0, std::plus<\n\t\t\tdouble>(), detail::SquareDifference()));\n}\n\n/**\n * @ingroup lab\n *\n * Computes the euclidean distance between two ranges.\n *\n * The second range shall have at least as many elements as the first. This\n * overload uses concepts from <a href=\"http://www.boost.org/libs/range\">\n * The Boost Range Library</a>. Practically it is syntactic sugar which replaces:\n * @code\n * vector<double> v1 = ...\n * vector<double> v2 = ...\n * euclidean_distance(v1.begin(), v1.end(), v2.begin());\n * @endcode\n * with the tighter:\n * @code\n * vector<double> v1 = ...\n * vector<double> v2 = ...\n * euclidean_distance(v1, v2);\n * @endcode\n * @param x first input range\n * @param y second input range\n * @return the euclidean distance\n */\ntemplate<class SinglePassRange> double euclidean_distance(\n\t\tconst SinglePassRange& x, const SinglePassRange& y) {\n\treturn euclidean_distance(boost::begin(x), boost::end(x), boost::begin(y));\n}\n\n/**\n * @ingroup lab\n *\n * A function object to compute the euclidean distance between objects.\n *\n * This is particularly useful in STL algorithms since it is cumbersome (or\n * simply impossible) to pass template function pointers as arguments.\n *\n * For example:\n * @code\n * vector<AttractorExpression> expr = ...\n * util::Matrix<double> m = make_distance_matrix<double>(expr.begin(),\n * \texpr.end(), &euclidean_distance);\n * @endcode\n * is wrong because the compiler cannot determine which overload to choose; also\n * that function is a template so you have to explicitly instantiate its\n * parameters to take a pointer. On the contrary, this is simpler and correct:\n * @code\n * vector<AttractorExpression> expr = ...\n * util::Matrix<double> m = make_distance_matrix<double>(expr.begin(),\n * \texpr.end(), Euclidean());\n * @endcode\n */\nstruct Euclidean {\n\t/**\n\t * Result type of this function object.\n\t */\n\ttypedef double result_type;\n\n\t/**\n\t * Computes the euclidean distance between two vector of the same length.\n\t * @param x the first vector\n\t * @param y the second vector\n\t * @return the euclidean distance\n\t */\n\ttemplate<class T> result_type operator()(const T& x, const T& y) const {\n\t\treturn euclidean_distance(x, y);\n\t}\n};\n\n}\n\n#endif /* EUCLIDEAN_HPP_ */\n", "meta": {"hexsha": "7c5f66f9782f98d011b105729586cea4a4059be4", "size": 3730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_stars_repo_name": "Markfrancisrogers/BooleanNetwork", "max_stars_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-04T14:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-04T19:03:51.000Z", "max_issues_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_issues_repo_name": "Markfrancisrogers/BooleanNetwork", "max_issues_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "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": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_forks_repo_name": "Markfrancisrogers/BooleanNetwork", "max_forks_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "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.0839160839, "max_line_length": 81, "alphanum_fraction": 0.7032171582, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171069, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6896240166838986}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\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. See accompanying LICENSE file.\n */\n/* EncryptedArray.cpp - Data-movement operations on arrays of slots\n */\n#include <NTL/ZZ.h>\nNTL_CLIENT\n#include \"EncryptedArray.h\"\n#include \"polyEval.h\"\n\nstatic void buildDigitPolynomial(ZZX& result, long p, long e);\n\n\n// extractDigits assumes that the slots of *this contains integers mod p^r\n// i.e., that only the free terms are nonzero. (If that assumptions does\n// not hold then the result will not be a valid ciphertext anymore.)\n// \n// It returns in the slots of digits[j] the j'th-lowest gigits from the\n// integers in the slots of the input. Namely, the i'th slot of digits[j]\n// contains the j'th digit in the p-base expansion of the integer in the\n// i'th slot of the *this.\n//\n// If the shortCut flag is set then digits[j] contains the j'th digits wrt\n// mod-p plaintext space and the highest possible level (for all j). Otherwise\n// digits[j] still contains the j'th digit in the base-p expansion, but wrt\n// mod-p^{r-j} plaintext space, and all the ciphertexts are at the same level.\nvoid extractDigits(vector<Ctxt>& digits, const Ctxt& c, long r, bool shortCut)\n{\n  FHEcontext& context = (FHEcontext&) c.getContext();\n  long rr = c.effectiveR();\n  if (r<=0 || r>rr) r = rr; // how many digits to extract\n\n  long p = context.zMStar.getP();\n  ZZX x2p;\n  if (p>3) { \n    buildDigitPolynomial(x2p, p, r);\n  }\n\n  Ctxt tmp(c.getPubKey(), c.getPtxtSpace());\n  digits.resize(r, tmp);      // allocate space\n  vector<Ctxt> w(r, tmp);\n  for (long i=0; i<r; i++) {\n    tmp = c;\n    for (long j=0; j<i; j++) {\n      FHE_NTIMER_START(square);\n      if (p==2) w[j].square();\n      else if (p==3) w[j].cube();\n      else polyEval(w[j], x2p, w[j]); // \"in spirit\" w[j] = w[j]^p\n      FHE_NTIMER_STOP(square);\n      tmp -= w[j];\n      tmp.divideByP();\n    }\n    w[i] = tmp; // needed in the next round\n    if (shortCut) {\n      digits[i] = tmp; // digits[i]=i'th lowest digit\n      digits[i].reducePtxtSpace(p);\n    }\n  }\n  // If not shortCut, copy w into digits\n  if (!shortCut) for (long i=0; i<r; i++) digits[i] = w[i];\n}\n\n\n\n// Compute a degree-p polynomial poly(x) s.t. for any t<e and integr z of the\n// form z = z0 + p^t*z1 (with 0<=z0<p), we have poly(z) = z0 (mod p^{t+1}).\n//\n// We get poly(x) by interpolating a degree-(p-1) polynomial poly'(x)\n// s.t. poly'(z0)=z0 - z0^p (mod p^e) for all 0<=z0<p, and then setting\n// poly(x) = x^p + poly'(x).\nstatic void buildDigitPolynomial(ZZX& result, long p, long e)\n{\n  if (p<2 || e<=1) return; // nothing to do\n  FHE_TIMER_START;\n  long p2e = power_long(p,e); // the integer p^e\n\n  // Compute x - x^p (mod p^e), for x=0,1,...,p-1\n  vec_long x(INIT_SIZE, p);\n  vec_long y(INIT_SIZE, p);\n  long bottom = -(p/2);\n  for (long j=0; j<p; j++) {\n    long z = bottom+j;\n    x[j] = z;\n    y[j] = z-PowerMod((z < 0 ? z + p2e : z), p, p2e);  // x - x^p (mod p^e)\n\n    while (y[j] > p2e/2)         y[j] -= p2e;\n    while (y[j] < -(p2e/2))      y[j] += p2e;\n  }\n  interpolateMod(result, x, y, p, e);\n  assert(deg(result)<p); // interpolating p points, should get deg<=p-1\n  SetCoeff(result, p);   // return result = x^p + poly'(x)\n  //  cerr << \"# digitExt mod \"<<p<<\"^\"<<e<<\"=\"<<result<<endl;\n  FHE_TIMER_STOP;\n}\n", "meta": {"hexsha": "f78d4ef872c1811ac015c397c93e7869a578445b", "size": 3787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extractDigits.cpp", "max_stars_repo_name": "bryongloden/HElib", "max_stars_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-01-02T00:53:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-11T04:41:29.000Z", "max_issues_repo_path": "src/extractDigits.cpp", "max_issues_repo_name": "bryongloden/HElib", "max_issues_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "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/extractDigits.cpp", "max_forks_repo_name": "bryongloden/HElib", "max_forks_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "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": 36.7669902913, "max_line_length": 78, "alphanum_fraction": 0.6366517032, "num_tokens": 1199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6896170497765385}}
{"text": "#include <Eigen/Core>\n#include <iostream>\nusing namespace Eigen;\nusing namespace std;\n\ntemplate<typename Derived>\nEigen::Reshaped<Derived, 4, 2>\nreshape_helper(MatrixBase<Derived>& m)\n{\n  return Eigen::Reshaped<Derived, 4, 2>(m.derived());\n}\n\nint main(int, char**)\n{\n  MatrixXd m(2, 4);\n  m << 1, 2, 3, 4,\n       5, 6, 7, 8;\n  MatrixXd n = reshape_helper(m);\n  cout << \"matrix m is:\" << endl << m << endl;\n  cout << \"matrix n is:\" << endl << n << endl;\n  return 0;\n}\n", "meta": {"hexsha": "b6d4085dea39cc0d291ddc4670bf034d2c48ccae", "size": 467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/eigen/doc/examples/class_FixedReshaped.cpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/doc/examples/class_FixedReshaped.cpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/doc/examples/class_FixedReshaped.cpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 20.3043478261, "max_line_length": 53, "alphanum_fraction": 0.6188436831, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.689617041637428}}
{"text": "/**\n * \\file Chebyshev2Filter.hxx\n */\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n\n#include <ATK/EQ/Chebyshev2Filter.h>\n#include <ATK/EQ/helpers.h>\n\nnamespace Chebyshev2Utilities\n{\n  template<typename DataType>\n  void create_chebyshev2_analog_coefficients(int order, DataType ripple, EQUtilities::ZPK<DataType>& zpk)\n  {\n    zpk.z.clear(); // no zeros for this filter type\n    zpk.p.clear();\n    \n    DataType de = static_cast<DataType>(1.0 / std::sqrt(std::pow(10, (0.1 * ripple)) - 1));\n    DataType mu = static_cast<DataType>(boost::math::asinh(1.0 / de) / order);\n    \n    for(gsl::index i = -order+1; i < order; i += 2)\n    {\n      std::complex<DataType> p1 = -std::complex<DataType>(std::cos(i * boost::math::constants::pi<DataType>() / (2 * order)), std::sin(i * boost::math::constants::pi<DataType>() / (2 * order)));\n      std::complex<DataType> p2 = std::complex<DataType>(std::sinh(mu) * p1.real(), std::cosh(mu) * p1.imag());\n      \n      zpk.p.push_back(std::complex<DataType>(1, 0) / p2);\n      \n      if(i == 0)\n      {\n        continue;\n      }\n      \n      zpk.z.push_back(std::complex<DataType>(0, 1 / std::sin(i * boost::math::constants::pi<DataType>() / (2 * order))));\n    }\n    \n    std::complex<DataType> f = 1;\n    for(gsl::index i = 0; i < zpk.p.size(); ++i)\n    {\n      f *= - zpk.p[i];\n    }\n    for(gsl::index i = 0; i < zpk.z.size(); ++i)\n    {\n      f /= - zpk.z[i];\n    }\n    zpk.k = f.real();\n  }\n  \n  template<typename DataType, typename Container>\n  void create_default_chebyshev2_coeffs(size_t order, DataType ripple, DataType Wn, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order), ripple, zpk);\n    EQUtilities::populate_lp_coeffs(Wn, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n  \n  template<typename DataType, typename Container>\n  void create_bp_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order/2), ripple, zpk);\n    EQUtilities::populate_bp_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n  \n  template<typename DataType, typename Container>\n  void create_bs_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order/2), ripple, zpk);\n    EQUtilities::populate_bs_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  Chebyshev2LowPassCoefficients<DataType>::Chebyshev2LowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2LowPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2LowPassCoefficients<DataType_>::CoeffDataType Chebyshev2LowPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2LowPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2LowPassCoefficients<DataType_>::CoeffDataType Chebyshev2LowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2LowPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev2LowPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void Chebyshev2LowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev2Utilities::create_default_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev2HighPassCoefficients<DataType>::Chebyshev2HighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2HighPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2HighPassCoefficients<DataType_>::CoeffDataType Chebyshev2HighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2HighPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2HighPassCoefficients<DataType_>::CoeffDataType Chebyshev2HighPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2HighPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev2HighPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void Chebyshev2HighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev2Utilities::create_default_chebyshev2_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(gsl::index i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n  \n  template <typename DataType>\n  Chebyshev2BandPassCoefficients<DataType>::Chebyshev2BandPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n  \n  template <typename DataType_>\n  std::pair<typename Chebyshev2BandPassCoefficients<DataType_>::CoeffDataType, typename Chebyshev2BandPassCoefficients<DataType_>::CoeffDataType> Chebyshev2BandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2BandPassCoefficients<DataType_>::CoeffDataType Chebyshev2BandPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev2BandPassCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void Chebyshev2BandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev2Utilities::create_bp_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev2BandStopCoefficients<DataType>::Chebyshev2BandStopCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n  \n  template <typename DataType_>\n  std::pair<typename Chebyshev2BandStopCoefficients<DataType_>::CoeffDataType, typename Chebyshev2BandStopCoefficients<DataType_>::CoeffDataType> Chebyshev2BandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_ripple(CoeffDataType ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename Chebyshev2BandStopCoefficients<DataType_>::CoeffDataType Chebyshev2BandStopCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandStopCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int Chebyshev2BandStopCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void Chebyshev2BandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    Chebyshev2Utilities::create_bs_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n}\n", "meta": {"hexsha": "80a3bb8c55fc76a45d436aefe3f31055eb07c31d", "size": 10986, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 31.2991452991, "max_line_length": 216, "alphanum_fraction": 0.718459858, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6895382521933583}}
{"text": "#ifndef THIN_PLATE_SPLINE_HPP\n#define THIN_PLATE_SPLINE_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include \"arc_utilities/arc_exceptions.hpp\"\n#include \"arc_utilities/eigen_helpers.hpp\"\n\nnamespace arc_utilities {\n// Note that DIMENSIONS must be 2 or 3, not something like `Eigen::Dynamic`\ntemplate <int DIMENSIONS = 3>\nclass ThinPlateSpline {\n public:\n  typedef Eigen::Matrix<double, DIMENSIONS, Eigen::Dynamic> PointSet;\n  typedef Eigen::Matrix<double, DIMENSIONS + 1, Eigen::Dynamic> HomogeneousPointSet;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  static_assert(DIMENSIONS > 1, \"Using TPS only makes sense for 2 or more dimensions\");\n  static_assert(DIMENSIONS <= 3,\n                \"The choice of kernel function for DIMENSIONS >= 4 is not clear.\"\n                \" See note after equation (29) in \"\n                \"https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf\");\n\n  ThinPlateSpline() : solved_(false) {}\n\n  /**\n   * @brief ThinPlateSpline::ThinPlateSpline An arbitrary dimensional thin\n   *  plate spline for interpolation between points.\n   * @param template_points A (DIMINESION x NUMPOINTS) matrix which define\n   *  the starting points that control the warping. I.e. the template is\n   *  warped to the target\n   * @param target_points A (DIMINESION x NUMPOINTS) matrix which define\n   *  the target points that control the warping. I.e. the template is\n   *  warped to the target\n   */\n  template <typename DerivedA, typename DerivedB>\n  ThinPlateSpline(const Eigen::MatrixBase<DerivedA>& template_points, const Eigen::MatrixBase<DerivedB>& target_points)\n      : solved_(false) {\n    setTemplatePoints(template_points);\n    setTargetPoints(target_points);\n    solveForCoeffs();\n  }\n\n  /**\n   * @note Checking for the vailidty of the input data is put off until\n   *  the warping function is solved\n   */\n  template <typename Derived>\n  void setTemplatePoints(const Eigen::MatrixBase<Derived>& template_points) {\n    using namespace Eigen;\n    static_assert(\n        MatrixBase<Derived>::RowsAtCompileTime == DIMENSIONS || MatrixBase<Derived>::RowsAtCompileTime == Dynamic,\n        \"INVALID DATA DIMENSIONS FOR template_points\");\n\n    homogeneous_template_points_.resize(DIMENSIONS + 1, template_points.cols());\n    homogeneous_template_points_ << template_points, RowVectorXd::Ones(template_points.cols());\n    solved_ = false;\n  }\n\n  /**\n   * @note Checking for the vailidty of the input data is put off until\n   *  the warping function is solved\n   */\n  template <typename Derived>\n  void setTargetPoints(const Eigen::MatrixBase<Derived>& target_points) {\n    using namespace Eigen;\n    static_assert(\n        MatrixBase<Derived>::RowsAtCompileTime == DIMENSIONS || MatrixBase<Derived>::RowsAtCompileTime == Dynamic,\n        \"INVALID DATA DIMENSIONS FOR target_points\");\n\n    target_points_ = target_points;\n    solved_ = false;\n  }\n\n  void solveForCoeffs() {\n    using namespace Eigen;\n    if (homogeneous_template_points_.cols() < 1 || target_points_.cols() < 1) {\n      throw_arc_exception(std::invalid_argument, \"template and target points must have valid data before solving\");\n    }\n    if (homogeneous_template_points_.cols() != target_points_.cols()) {\n      throw_arc_exception(std::invalid_argument, \"template and target points must have the same number of points\");\n    }\n\n    const auto NUMPOINTS = homogeneous_template_points_.cols();\n\n    // Calculate the kernel matrix for the template (control) points\n    const MatrixXd Rsquared = EigenHelpers::CalculateSquaredDistanceMatrix(homogeneous_template_points_);\n    const MatrixXd kernel = Rsquared.unaryExpr(&ThinPlateSpline::KernelFunction);\n\n    // Form the system:   A * params = B\n    //       A = [K,       template'\n    //            template,    0]\n    //       B = [target'\n    //              0    ]\n    MatrixXd A(NUMPOINTS + DIMENSIONS + 1, NUMPOINTS + DIMENSIONS + 1);\n    A << kernel, homogeneous_template_points_.transpose(), homogeneous_template_points_,\n        MatrixXd::Zero(DIMENSIONS + 1, DIMENSIONS + 1);\n    MatrixXd B(NUMPOINTS + DIMENSIONS + 1, DIMENSIONS);\n    B << target_points_.transpose(), MatrixXd::Zero(DIMENSIONS + 1, DIMENSIONS);\n\n    // params = A \\ B\n    const Matrix<double, Dynamic, DIMENSIONS> params = A.colPivHouseholderQr().solve(B).eval();\n    warping_coeffs_ = params.topRows(NUMPOINTS).transpose();\n    affine_coeffs_ = params.bottomRows(DIMENSIONS + 1).transpose();\n    solved_ = true;\n  }\n\n  template <typename Derived>\n  Eigen::Matrix<double, DIMENSIONS, Eigen::Dynamic> interpolate(\n      const Eigen::MatrixBase<Derived>& interpolation_points) {\n    using namespace Eigen;\n    static_assert(\n        MatrixBase<Derived>::RowsAtCompileTime == DIMENSIONS || MatrixBase<Derived>::RowsAtCompileTime == Dynamic,\n        \"INVALID DATA DIMENSIONS FOR interpolation_points\");\n\n    if (!solved_) {\n      solveForCoeffs();\n    }\n\n    const auto num_points = interpolation_points.cols();\n    HomogeneousPointSet homogeneous_interpolation_points(DIMENSIONS + 1, num_points);\n    homogeneous_interpolation_points << interpolation_points, RowVectorXd::Ones(num_points);\n\n    // Calculate the kenerl matrix comparing the new points to the template (control) points\n    const MatrixXd Rsquared =\n        EigenHelpers::SquaredDistancesBetweenPointSets(homogeneous_template_points_, homogeneous_interpolation_points);\n    const MatrixXd kernel = Rsquared.unaryExpr(&ThinPlateSpline::KernelFunction);\n\n    return affine_coeffs_ * homogeneous_interpolation_points + warping_coeffs_ * kernel;\n  }\n\n protected:\n  static double KernelFunction(const double r_sq) {\n    // Equations taken from\n    // https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf\n    // with coefficient (alpha) dropped as it is absorbed by warping_coeffs_\n    switch (DIMENSIONS) {\n      case 2:\n        // This should be r^2 * log(r). We do not take the square root\n        // because the factor of 2 gets absorbed by warping_coeffs_\n        return r_sq == 0.0 ? 0.0 : r_sq * std::log(r_sq);\n      case 3:\n        // The negative is kept here for consistency with\n        // https://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntpThinPlateSpline3.h\n        // and other TPS implementations found online\n        return r_sq == 0.0 ? 0.0 : -std::sqrt(r_sq);\n      default:\n        static_assert(DIMENSIONS == 2 || DIMENSIONS == 3, \"Only 2 and 3 dimensional kernels are implemented\");\n    }\n  }\n\n  HomogeneousPointSet homogeneous_template_points_;\n  PointSet target_points_;\n  Eigen::Matrix<double, DIMENSIONS, DIMENSIONS + 1> affine_coeffs_;\n  PointSet warping_coeffs_;\n  bool solved_;\n};\n}  // namespace arc_utilities\n\n#endif  // THIN_PLATE_SPLINE_HPP\n", "meta": {"hexsha": "f3ccbb8f069f31f481c8d85f6bbc43361bf02fde", "size": 6673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 41.1913580247, "max_line_length": 119, "alphanum_fraction": 0.7151206354, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6895224062845285}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n* \\file\n* \\author   Collin Johnson\n*\n* Definition of binomial_proportion_z_test.\n*/\n\n#include <math/z_test.h>\n#include <boost/math/distributions/normal.hpp>\n\nnamespace vulcan\n{\nnamespace math\n{\n\nz_test_results_t binomial_proportion_z_test(const z_test_sample_t& sampleA,\n                                            const z_test_sample_t& sampleB,\n                                            double confidence)\n{\n    // Code closely related to Boost.Math example at:\n    // http://www.boost.org/doc/libs/1_65_1/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html\n\n    using namespace boost::math;\n\n    assert(sampleA.numSamples > 1);\n    assert(sampleB.numSamples > 1);\n    assert(sampleA.numTrue >= 0);\n    assert(sampleB.numTrue >= 0);\n\n    double successA = static_cast<double>(sampleA.numTrue) / sampleA.numSamples;\n    double successB = static_cast<double>(sampleB.numTrue) / sampleB.numSamples;\n\n    double totalSuccess = static_cast<double>(sampleA.numTrue + sampleB.numTrue)\n        / (sampleA.numSamples + sampleB.numSamples);\n\n    double zDenom = std::sqrt(totalSuccess * (1.0 - totalSuccess)\n        * ((1.0 / sampleA.numSamples) + (1.0 / sampleB.numSamples)));\n\n    z_test_results_t results;\n    results.zValue     = (successA - successB) / zDenom;\n    results.confidence = confidence;\n\n    normal dist;\n\n    results.pValueDifferent = cdf(complement(dist, std::abs(results.zValue)));\n    results.areDifferent    = results.pValueDifferent < (confidence / 2.0);\n\n    results.pValueGreater = cdf(complement(dist, results.zValue));\n    results.isGreater     = results.pValueGreater < confidence;\n\n    results.pValueLess = cdf(dist, results.zValue);\n    results.isLess     = results.pValueLess < confidence;\n\n    return results;\n}\n\n} // namespace math\n} // namespace vulcan\n", "meta": {"hexsha": "c774fe50e2b92cfadd254e8d474f36510ad82bc1", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/z_test.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/math/z_test.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/math/z_test.cpp", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 31.9852941176, "max_line_length": 121, "alphanum_fraction": 0.6933333333, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657177, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6895223901992305}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2018 Prabhsimran Singh\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#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\nusing namespace Eigen;\n\nnamespace F {\n\ninline float glorot_uniform(const int &n_in, const int &n_out) {\n    return 2.0 / (n_in + n_out);\n}\n\ninline MatrixXf sigmoid(const MatrixXf &x) {\n    return (1.0 + (-x).array().exp()).inverse().matrix();\n}\n\ninline MatrixXf sigmoid_derivative(const MatrixXf &x) {\n    return x * (1 - x.array()).matrix();\n}\n\ninline MatrixXf relu(const MatrixXf &x) {\n    return x.cwiseMax(0.0);\n}\n\nMatrixXf tanh(const MatrixXf &x) {\n    return sigmoid(x);\n}\n\nMatrixXf log_softmax(const MatrixXf &x) {\n    auto e = x.array().exp();\n    return (e / e.sum()).log().matrix();\n}\n} // namespace F", "meta": {"hexsha": "f8ef05a9d0f48f1bdb890ed03fb6954416f91aec", "size": 1896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/functions.hpp", "max_stars_repo_name": "pskrunner14/lstm-from-scratch", "max_stars_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T04:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:48:40.000Z", "max_issues_repo_path": "include/functions.hpp", "max_issues_repo_name": "pskrunner14/lstm-from-scratch", "max_issues_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-23T06:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-23T06:59:28.000Z", "max_forks_repo_path": "include/functions.hpp", "max_forks_repo_name": "pskrunner14/lstm-from-scratch", "max_forks_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T00:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T01:39:40.000Z", "avg_line_length": 31.6, "max_line_length": 81, "alphanum_fraction": 0.7209915612, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.6894950384756123}}
{"text": "#include \"SimplePly.h\"\n#include \"rply.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n/**Calculates the distance the point is from the plane\n   @param point a single point's position.\n   @param planeEq plane Equation.\n   @return distance between point and plane.\n */\nfloat distToPlane(Eigen::Vector3f point, Eigen::Vector4f planeEq){\n  float distance = planeEq(0)*point(0) + planeEq(1)*point(1) + planeEq(2)*point(2) + planeEq(3);\n  distance /= std::sqrt(std::pow(planeEq(0),2) + std::pow(planeEq(1),2) + std::pow(planeEq(2),2));\n  distance = std::abs(distance);\n  return distance;\n}\n\n/**builds a plane out of 3 points\n   @param point list of point positions.\n   @return the equation of the plane.\n */\nEigen::Vector4f calcPlane(std::vector<Eigen::Vector3f> points){\n  Eigen::Vector3f vectAB = points[1] - points[0], vectAC = points[2] - points[0];\n  Eigen::Vector3f planeNorm = vectAB.cross(vectAC);\n  float planeConst = -points[0].dot(planeNorm);\n  Eigen::Vector4f planeEquation(planeNorm(0),planeNorm(1),planeNorm(2),planeConst);\n  return planeEquation;\n}\n\n/**finds the distance that a point (with the greatest distance from the plane) has\n   @param points list of points positions.\n   @param planeEq the equation for the plane.\n   @return the max distance between any point and the plane.\n */ \nfloat maxDistance(std::vector<Eigen::Vector3f> points, Eigen::Vector4f planeEq){\n  float maxDist = 0, dist = 0;\n  for(int i = 0; i < points.size(); i++){\n    if((dist = distToPlane(points[i], planeEq)) > maxDist){\n      maxDist = dist;\n    }\n  }\n  return maxDist;\n}\n\n/**calculates the centroid of the points given.\n   @param points list of points positions.\n   @return the centroid of the points positions.\n */\nEigen::Vector3f calcCentroid(std::vector<Eigen::Vector3f> points){\n  float aveX = 0, aveY = 0, aveZ = 0;\n  Eigen::Vector3f centroid;\n  for(int i = 0; i < points.size(); i++){\n    aveX += points[i](0);\n    aveY += points[i](1);\n    aveZ += points[i](2);\n  }\n  //averaging the values.\n  aveX/=points.size();\n  aveY/=points.size();\n  aveZ/=points.size();\n  centroid(0) = aveX;\n  centroid(1) = aveY;\n  centroid(2) = aveZ;\n  return centroid;\n}\n\n/** Preforms orthogonal least squares on the points given to find the best plane. Then the\n    method projects the points onto the plane.\n    @param points list of points location.\n    @param plyPoints list of points in ply format.\n*/\nvoid leastSquares(std::vector<Eigen::Vector3f> points, std::vector<PlyPoint *> &plyPoints){\n  Eigen::MatrixXf pointsMat(points.size(),3), pointsV;\n  Eigen::Vector3f centroid = calcCentroid(points), planeNorm, adjustedPoint;\n  Eigen::Vector4f planeEq;\n  float planeNormNorm = 0, dist = 0;\n  //builds matrix to use SVD on.\n  for(int i = 0; i < points.size(); i++){\n    for(int j = 0; j < 3; j++){\n      pointsMat(i,j) = points[i](j) - centroid(j);\n    }\n  }\n  //preforms SVD\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(pointsMat, Eigen::ComputeFullV);\n  pointsV = svd.matrixV();\n  //builds plane based off of the SVD eigen vector and the centroid.\n  for(int i = 0; i < 3; i++){\n    planeEq(i) = pointsV(i,0);\n    planeEq(3) -= planeEq(i)*centroid(i);\n  }\n  //finds normal of the plane normal.\n  for(int i = 0; i < 3; i++){\n    planeNormNorm += std::pow(planeEq(i),2);\n  }\n  planeNormNorm = std::sqrt(planeNormNorm);\n  //builds a normalised plane normal vector.\n  for(int i = 0; i < 3; i++){\n    planeNorm(i) = planeEq(i)/planeNormNorm;\n  }\n  //projects points positions onto the calcuated Plane.\n  for(int i = 0; i < plyPoints.size(); i++){\n    dist = distToPlane(points[i],planeEq);\n    \n    adjustedPoint(0)= points[i](0) - (dist*planeNorm(0));\n    adjustedPoint(1)= points[i](1) - (dist*planeNorm(1));\n    adjustedPoint(2)= points[i](2) - (dist*planeNorm(2));\n    if(dist < distToPlane(adjustedPoint,planeEq)){\n      adjustedPoint(0)= points[i](0) + (2*dist*planeNorm(0));\n      adjustedPoint(1)= points[i](1) + (2*dist*planeNorm(1));\n      adjustedPoint(2)= points[i](2) + (2*dist*planeNorm(2));\n    }\n    \n    (*plyPoints[i]).location(0) = adjustedPoint(0);\n    (*plyPoints[i]).location(1) = adjustedPoint(1);\n    (*plyPoints[i]).location(2) = adjustedPoint(2);\n  }\n}\n\n\n\n\n\n\n/** Based on a percentage of points in the biggest plane, it calculates the threshold for the plane.\n * @param points the list of points positions.\n * @param planeEq the equation for the plane.\n * @param probThreshold the percentage of points required to determine threshold.\n * @return the calculated threshold.\n */\nfloat calcThreshold(std::vector<Eigen::Vector3f> points, Eigen::Vector4f planeEq, float probThreshold){\n  std::vector<float> buckets;\n  float maxDist = maxDistance(points, planeEq);\n  int numJumps = 10000, pointCount = 0, placeHold = 0, reqPoints = std::ceil(points.size()*probThreshold);\n  float jumpSize = maxDist/(numJumps-1), dist, threshold = 0;\n    \n  for(int i = 0; i < numJumps; i++){\n    buckets.push_back(0);\n  }\n  //Counts the number of Points in each region bucket.\n  for(int i = 0; i < points.size(); i++){\n    dist = distToPlane(points[i],planeEq);\n    buckets[std::floor(dist/jumpSize)]++;\n  }\n  //sums point count in buckets until it goes over the users estimated plane count.\n  while(pointCount < reqPoints){\n    pointCount += buckets[placeHold];\n    placeHold++;\n  }\n  //sets that point as threshold.\n  threshold = (placeHold+1)*jumpSize;\n    \n  return threshold;\n\n}\n\n\n\n\n/**Determines the number of trials needed to have the accuracy that is requested.\n * @param inlierProb the probability of a point being an inlier.\n * @param acceptedFailProb the accepted rate of failure.\n *@return the number of trials required.\n */\nfloat numChecks(float inlierProb, float acceptedFailProb){\n  float numChecks = 0;\n  if(inlierProb < 1){\n    numChecks = ((std::log(acceptedFailProb))/(std::log(1 - (std::pow(inlierProb,3)))));\n  }\n  \n  return numChecks;\n}\n\n\n/**Determines if the plane is a null plane.\n   @param plane the plane equation.x\n   @return a statement of if the plane is a null plane.\n */\nbool planeNull(Eigen::Vector4f plane){\n  return (abs(plane(0)) == 0 && plane(1) == 0 && plane(2) == 0 && plane(3) == 0);\n}\n\n\n\n\n\n\n\n/**Proforms analysis on the inputed point cloud, to find planes in the point cloud, colouring\n   them accordingly. The program requires the user to input some information about the data,\n   such as a points limit to when to stop looking for planes, an estimate of the percentage\n   of points in the largest plane, and the probability of success.\n*/\nint main (int argc, char *argv[]) {\n  int pointIn, count, bestCount, point1In, point2In, point3In, reqPlaneCalcs = 0;\n  float posThresh = 0, threshProb = 0.4, threshold = 0, inlierProb = 0.001;\n  Eigen::Vector4f bestPlane(0,0,0,0), curPlane;\n  Eigen::Vector3f holdPoint;\n  Eigen::Vector3i baseColour;\n  std::vector<Eigen::Vector3f> points, pointsList, planePoints;\n  int trialCount = 0,planeCount = 0;\n  bool stillPlanes = true, threshFound = false;\n  // Check the commandline arguments.\n  if (argc != 6) {\n    std::cout << \"Usage: planeFinder <input file> <output file> <min num of points in plane> <percentage of points in largest plane> <accepted failure rate>\" << std::endl;\n    return -1;\n  }\n  int planeSizeThreshold = atoi(argv[3]);\n  float pointPercentBiggestPlane = atof(argv[4]);\n  float acceptedFailProb = atof(argv[5]);\n  std::vector<PlyPoint *> pointsList2, planePoints2;\n  \n  reqPlaneCalcs = numChecks(pointPercentBiggestPlane, acceptedFailProb);\n  threshold = std::numeric_limits<float>::max();\n  std::cout << \"Searching for planes until the next best plane size is less than \" << planeSizeThreshold << std::endl;\n  std::cout << \"The estimated percentage of points in the biggest plane is \" << pointPercentBiggestPlane << std::endl;\n  std::cout << \"Applying RANSAC with an acceptedFailRate of \" << acceptedFailProb << std::endl;  \n\n  // Storage for the point cloud.\n  SimplePly ply;\n  // Read in the data from a PLY file\n  std::cout << \"Reading PLY data from \" << argv[1] << std::endl;\n  if (!ply.read(argv[1])) {\n    std::cout << \"Could not read PLY data from file \" << argv[1] << std::endl;\n    return -1;\n  }\n\n  // Stores copy of points read in.\n  for(int i = 0; i < ply.size(); ++i){\n    pointsList2.push_back(&ply[i]);\n  }\n  \n  \n  std::cout << \"Read \" << ply.size() << \" points\" << std::endl;\n  \n  // Recolour points - here we are just doing colour based on index\n  std::cout << \"Recolouring points\" << std::endl;\n  \n  //Sets colours\n  std::vector<Eigen::Vector3i> colours;\n  colours.push_back(Eigen::Vector3i(255,0,0));\n  colours.push_back(Eigen::Vector3i(0,255,0));\n  colours.push_back(Eigen::Vector3i(0,0,255));\n  colours.push_back(Eigen::Vector3i(255,255,0));\n  colours.push_back(Eigen::Vector3i(0,255,255));\n  colours.push_back(Eigen::Vector3i(255,0,255));\n  colours.push_back(Eigen::Vector3i(255,255,255));\n  colours.push_back(Eigen::Vector3i(0,0,0));\n  \n  holdPoint = Eigen::Vector3f(ply[0].location(0),ply[0].location(1),ply[0].location(2));\n  \n  \n  \n  //builds a vector containing vectors of the points positions.\n  for(int i = 0; i < ply.size(); i++){\n    holdPoint = Eigen::Vector3f(ply[i].location(0),ply[i].location(1),ply[i].location(2));\n    pointsList.push_back(holdPoint);\n  }\n\n  \n  \n\n  //starts looking for planes.\n  while(stillPlanes && pointsList.size() > 2){\n    //zeros bestPlane.\n    for(int j = 0; j < 4; j++){\n      bestPlane(j) = 0;\n    }\n    \n    //increase plane Count.\n\n    planeCount++;\n    //Resets variables.\n    bestCount = 0;\n    inlierProb = 0.001;\n    trialCount = 0;\n    \n    //finds the threshold based off of users estimate.\n    if(!threshFound){\n      for(int z = 0; z < 110; z++){\n\tpoint1In = std::rand()%pointsList.size();\n\tpoint2In = std::rand()%pointsList.size();\n\tpoint3In = std::rand()%pointsList.size();\n\tpoints.clear();\n\tpoints.push_back(pointsList[point1In]);\n\tpoints.push_back(pointsList[point2In]);\n\tpoints.push_back(pointsList[point3In]);\n\tcurPlane = calcPlane(points);\n\tif(!planeNull(curPlane)){\n\t  posThresh = calcThreshold(pointsList, curPlane, pointPercentBiggestPlane);\n\t  if(posThresh < threshold){\n\t    threshold = posThresh;\n\t    bestPlane = curPlane;\n\t  }\n\t}\n      }\n      //makes sure only one threshold is found.\n      threshFound = true;\n    }\n\n\n\n    //starts looking for planes with the calculated threshold.\n    while(trialCount <  numChecks(inlierProb, acceptedFailProb)){\n      trialCount++;\n      std::cout << numChecks(inlierProb, acceptedFailProb) << std::endl;\n      //finds three random points and builds a plane.\n      point1In = std::rand()%pointsList.size();\n      point2In = std::rand()%pointsList.size();\n      point3In = std::rand()%pointsList.size();\n      points.clear();\n      points.push_back(pointsList[point1In]);\n      points.push_back(pointsList[point2In]);\n      points.push_back(pointsList[point3In]);\n      curPlane = calcPlane(points);\n      count = 0;\n      //makes sure it isn't a null plane.\n      if(!planeNull(curPlane)){\n\tfor(int k = 0; k < pointsList.size(); k++){\n\t  //counts number of points within threshold.\n\t  if(distToPlane(pointsList[k], curPlane) <= threshold){\n\t    count++;\n\t  }\n\t}\n\t//checks if this is best plane then updates if it is.\n\tif(count > bestCount){\n\t  bestCount = count;\n\t  bestPlane = curPlane;\n\t  inlierProb = ((float)bestCount)/pointsList.size();\n\t  \n\t}\n      }\n    }\n    //Cuts out if the plane is too small.\n    if(bestCount < planeSizeThreshold){\n      stillPlanes = false;\n    }\n    //Makes sure the unlikely chance of a null best plane occuring doesn't get through.\n    else if(!planeNull(bestPlane)){\n      //recolours and removes points.\n      for(int j = pointsList2.size() - 1; j > -1; j--){\n\tholdPoint(0) = (*pointsList2[j]).location(0);\n\tholdPoint(1) =  (*pointsList2[j]).location(1);\n\tholdPoint(2) =  (*pointsList2[j]).location(2);\n\t\n\tif(distToPlane(holdPoint, bestPlane) <= threshold){\n\t  \n\t  (*pointsList2[j]).colour = colours[planeCount%colours.size()];\n\t  //planePoints.push_back(pointsList[j]);\n\t  pointsList[j] = pointsList[pointsList.size() - 1];\n\t  pointsList.pop_back();\n\t  //planePoints2.push_back(pointsList2[j]);\n\t  pointsList2[j] = pointsList2[pointsList2.size() - 1];\n\t  pointsList2.pop_back();\n\t\n\t}\n      }\n      //would do least squares if it worked properly. No time to work out the error.\n      //leastSquares(planePoints, planePoints2);\n      //planePoints.clear();\n      //planePoints2.clear();\n    }\n  }\n  \n \n  // Write the resulting (re-coloured) point cloud to a PLY file.\n  std::cout << \"Writing PLY data to \" << argv[2] << std::endl;\n  if (!ply.write(argv[2])) {\n    std::cout << \"Could not write PLY data to file \" << argv[2] << std::endl;\n    return -2;\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "5851b7518d101d308ceba8de8b6003e590e24e50", "size": 12652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "planeFinder.cpp", "max_stars_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_stars_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-12-13T07:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T09:14:19.000Z", "max_issues_repo_path": "planeFinder.cpp", "max_issues_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_issues_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T07:39:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-21T07:39:29.000Z", "max_forks_repo_path": "planeFinder.cpp", "max_forks_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_forks_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T08:40:43.000Z", "avg_line_length": 33.6489361702, "max_line_length": 171, "alphanum_fraction": 0.6651912741, "num_tokens": 3642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6894446618139808}}
{"text": "/* Boost example/transc.cpp\n * how to use an external library (GMP/MPFR in this case) in order to\n * get correct transcendental functions on intervals\n *\n * Copyright 2003 Guillaume Melquiond\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#include <boost/numeric/interval.hpp>\n//extern \"C\" {\n#include <gmp.h>\n#include <mpfr.h>\n//}\n#include <iostream>\n\nstruct full_rounding:\n  boost::numeric::interval_lib::rounded_arith_opp<double>\n{\nprivate:\n  typedef int mpfr_func(mpfr_t, const __mpfr_struct*, mp_rnd_t);\n  double invoke_mpfr(double x, mpfr_func f, mp_rnd_t r) {\n    mpfr_t xx;\n    mpfr_init_set_d(xx, x, GMP_RNDN);\n    f(xx, xx, r);\n    double res = mpfr_get_d(xx, r);\n    mpfr_clear(xx);\n    return res;\n  }\npublic:\n# define GENR_FUNC(name) \\\n  double name##_down(double x) { return invoke_mpfr(x, mpfr_##name, GMP_RNDD); } \\\n  double name##_up  (double x) { return invoke_mpfr(x, mpfr_##name, GMP_RNDU); }\n  GENR_FUNC(exp)\n  GENR_FUNC(log)\n  GENR_FUNC(sin)\n  GENR_FUNC(cos)\n  GENR_FUNC(tan)\n  GENR_FUNC(asin)\n  GENR_FUNC(acos)\n  GENR_FUNC(atan)\n  GENR_FUNC(sinh)\n  GENR_FUNC(cosh)\n  GENR_FUNC(tanh)\n  GENR_FUNC(asinh)\n  GENR_FUNC(acosh)\n  GENR_FUNC(atanh)\n};\n\nnamespace dummy {\n  using namespace boost;\n  using namespace numeric;\n  using namespace interval_lib;\n  typedef save_state<full_rounding> R;\n  typedef checking_strict<double> P;\n  typedef interval<double, policies<R, P> > I;\n};\n\ntypedef dummy::I I;\n\ntemplate<class os_t>\nos_t& operator<<(os_t &os, const I &a) {\n  os << '[' << a.lower() << ',' << a.upper() << ']';\n  return os;\n}\n\nint main() {\n  I x(0.5, 2.5);\n  std::cout << \"x = \" << x << std::endl;\n  std::cout.precision(16);\n# define GENR_TEST(name) \\\n  std::cout << #name \"(x) = \" << name(x) << std::endl\n  GENR_TEST(exp);\n  GENR_TEST(log);\n  GENR_TEST(sin);\n  GENR_TEST(cos);\n  GENR_TEST(tan);\n  GENR_TEST(asin);\n  GENR_TEST(acos);\n  GENR_TEST(atan);\n  GENR_TEST(sinh);\n  GENR_TEST(cosh);\n  GENR_TEST(tanh);\n  GENR_TEST(asinh);\n  GENR_TEST(acosh);\n  GENR_TEST(atanh);\n  return 0;\n}\n", "meta": {"hexsha": "2036f98323a407dd264734b6b930756f8499662f", "size": 2121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/interval/examples/transc.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/numeric/interval/examples/transc.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/numeric/interval/examples/transc.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 23.3076923077, "max_line_length": 82, "alphanum_fraction": 0.676096181, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6893668200395321}}
{"text": "// find_mean_and_sd_normal.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 finding mean or sd for normal distribution.\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//[normal_std\r\n/*`\r\nFirst we need some includes to access the normal distribution,\r\nthe algorithms to find location and scale\r\n(and some std output of course).\r\n*/\r\n\r\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\r\n  using boost::math::normal; // typedef provides default type is double.\r\n#include <boost/math/distributions/cauchy.hpp> // for cauchy_distribution\r\n  using boost::math::cauchy; // typedef provides default type is double.\r\n#include <boost/math/distributions/find_location.hpp>\r\n  using boost::math::find_location;\r\n#include <boost/math/distributions/find_scale.hpp>\r\n  using boost::math::find_scale;\r\n  using boost::math::complement;\r\n  using boost::math::policies::policy;\r\n\r\n#include <iostream>\r\n  using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\r\n#include <iomanip>\r\n  using std::setw; using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n#include <stdexcept>\r\n  using std::exception;\r\n//] [/normal_std Quickbook]\r\n\r\nint main()\r\n{\r\n  cout << \"Find_location (mean) and find_scale (standard deviation) examples.\" << endl;\r\n  try\r\n  {\r\n\r\n//[normal_find_location_and_scale_eg\r\n\r\n/*`\r\n[h4 Using find_location and find_scale to meet dispensing and measurement specifications]\r\n\r\nConsider an example from K Krishnamoorthy,\r\nHandbook of Statistical Distributions with Applications,\r\nISBN 1-58488-635-8, (2006) p 126, example 10.3.7.\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\nAssume the packing is normally distributed.\"\r\n\r\nWe start by constructing a normal distribution with the given parameters:\r\n*/\r\n\r\ndouble mean = 3.; // kg\r\ndouble standard_deviation = 0.1; // kg\r\nnormal packs(mean, standard_deviation);\r\n/*`We can then find the fraction (or %) of packages that weigh more than 3.1 kg.\r\n*/\r\n\r\ndouble max_weight = 3.1; // kg\r\ncout << \"Percentage of packs > \" << max_weight << \" is \"\r\n<< cdf(complement(packs, max_weight)) * 100. << endl; // P(X > 3.1)\r\n\r\n/*`We might want to ensure that 95% of packs are over a minimum weight specification,\r\nthen we want the value of the mean such that P(X < 2.9) = 0.05.\r\n\r\nUsing the mean of 3 kg, we can estimate\r\nthe fraction of packs that fail to meet the specification of 2.9 kg.\r\n*/\r\n\r\ndouble minimum_weight = 2.9;\r\ncout <<\"Fraction of packs <= \" << minimum_weight << \" with a mean of \" << mean\r\n  << \" is \" << cdf(complement(packs, minimum_weight)) << endl;\r\n// fraction of packs <= 2.9 with a mean of 3 is 0.841345\r\n\r\n/*`This is 0.84 - more than the target fraction of 0.95.\r\nIf we want 95% to be over the minimum weight,\r\nwhat should we set the mean weight to be?\r\n\r\nUsing the KK StatCalc program supplied with the book and the method given on page 126 gives 3.06449.\r\n\r\nWe can confirm this by constructing a new distribution which we call 'xpacks'\r\nwith a safety margin mean of 3.06449 thus:\r\n*/\r\ndouble over_mean = 3.06449;\r\nnormal xpacks(over_mean, standard_deviation);\r\ncout << \"Fraction of packs >= \" << minimum_weight\r\n<< \" with a mean of \" << xpacks.mean()\r\n  << \" is \" << cdf(complement(xpacks, minimum_weight)) << endl;\r\n// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005\r\n\r\n/*`Using this Math Toolkit, we can calculate the required mean directly thus:\r\n*/\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// mean + (mean - low_limit - quantile(packs, under_fraction));\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 >= \" << minimum_weight\r\n  << \" is \" << cdf(complement(nominal_packs, minimum_weight)) << endl;\r\n// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`\r\nThis calculation is generalized as the free function called\r\n[link math_toolkit.dist.dist_ref.dist_algorithms find_location].\r\n\r\nTo use this we will need to\r\n*/\r\n\r\n#include <boost/math/distributions/find_location.hpp>\r\n  using boost::math::find_location;\r\n/*`and then use find_location function to find safe_mean,\r\n& construct a new normal distribution called 'goodpacks'.\r\n*/\r\ndouble safe_mean = find_location<normal>(minimum_weight, under_fraction, standard_deviation);\r\nnormal good_packs(safe_mean, standard_deviation);\r\n/*`with the same confirmation as before:\r\n*/\r\ncout << \"Setting the packer to \" << nominal_mean << \" will mean that \"\r\n  << \"fraction of packs >= \" << minimum_weight\r\n  << \" is \" << cdf(complement(good_packs, minimum_weight)) << endl;\r\n// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`\r\n[h4 Using Cauchy-Lorentz instead of normal distribution]\r\n\r\nAfter examining the weight distribution of a large number of packs, we might decide that,\r\nafter all, the assumption of a normal distribution is not really justified.\r\nWe might find that the fit is better to a __cauchy_distrib.\r\nThis distribution has wider 'wings', so that whereas most of the values\r\nare closer to the mean than the normal, there are also more values than 'normal'\r\nthat lie further from the mean than the normal.\r\n\r\nThis might happen because a larger than normal lump of meat is either included or excluded.\r\n\r\nWe first create a __cauchy_distrib with the original mean and standard deviation,\r\nand estimate the fraction that lie below our minimum weight specification.\r\n*/\r\n\r\ncauchy cpacks(mean, standard_deviation);\r\ncout << \"Cauchy Setting the packer to \" << mean << \" will mean that \"\r\n  << \"fraction of packs >= \" << minimum_weight\r\n  << \" is \" << cdf(complement(cpacks, minimum_weight)) << endl;\r\n// Cauchy Setting the packer to 3 will mean that fraction of packs >= 2.9 is 0.75\r\n\r\n/*`Note that far fewer of the packs meet the specification, only 75% instead of 95%.\r\nNow we can repeat the find_location, using the cauchy distribution as template parameter,\r\nin place of the normal used above.\r\n*/\r\n\r\ndouble lc = find_location<cauchy>(minimum_weight, under_fraction, standard_deviation);\r\ncout << \"find_location<cauchy>(minimum_weight, over fraction, standard_deviation); \" << lc << endl;\r\n// find_location<cauchy>(minimum_weight, over fraction, packs.standard_deviation()); 3.53138\r\n/*`Note that the safe_mean setting needs to be much higher, 3.53138 instead of 3.06449,\r\nso we will make rather less profit.\r\n\r\nAnd again confirm that the fraction meeting specification is as expected.\r\n*/\r\ncauchy goodcpacks(lc, standard_deviation);\r\ncout << \"Cauchy Setting the packer to \" << lc << \" will mean that \"\r\n  << \"fraction of packs >= \" << minimum_weight\r\n  << \" is \" << cdf(complement(goodcpacks, minimum_weight)) << endl;\r\n// Cauchy Setting the packer to 3.53138 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`Finally we could estimate the effect of a much tighter specification,\r\nthat 99% of packs met the specification.\r\n*/\r\n\r\ncout << \"Cauchy Setting the packer to \"\r\n  << find_location<cauchy>(minimum_weight, 0.99, standard_deviation)\r\n  << \" will mean that \"\r\n  << \"fraction of packs >= \" << minimum_weight\r\n  << \" is \" << cdf(complement(goodcpacks, minimum_weight)) << endl;\r\n\r\n/*`Setting 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 kg per pack.\r\n\r\nOf course, this calculation is not limited to packs of meat, it applies to dispensing anything,\r\nand it also applies to a 'virtual' material like any measurement.\r\n\r\nThe only caveat is that the calculation assumes that the standard deviation (scale) is known with\r\na reasonably low uncertainty, something that is not so easy to ensure in practice.\r\nAnd that the distribution is well defined, __normal_distrib or __cauchy_distrib, or some other.\r\n\r\nIf one is simply dispensing a very large number of packs,\r\nthen it may be feasible to measure the weight of hundreds or thousands of packs.\r\nWith a healthy 'degrees of freedom', the confidence intervals for the standard deviation\r\nare not too wide, typically about + and - 10% for hundreds of observations.\r\n\r\nFor other applications, where it is more difficult or expensive to make many observations,\r\nthe confidence intervals are depressingly wide.\r\n\r\nSee [link math_toolkit.dist.stat_tut.weg.cs_eg.chi_sq_intervals Confidence Intervals on the standard deviation]\r\nfor a worked example\r\n[@../../../example/chi_square_std_dev_test.cpp chi_square_std_dev_test.cpp]\r\nof estimating these intervals.\r\n\r\n\r\n[h4 Changing the scale or standard deviation]\r\n\r\nAlternatively, we could invest in a better (more precise) packer\r\n(or measuring device) with a lower standard deviation, or scale.\r\n\r\nThis might cost more, but would reduce the amount we have to 'give away'\r\nin order to meet the specification.\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 kg.\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// Quantile of 0.05 = 2.91776, mean = 3, sd = 0.05\r\n\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n  << \" and standard deviation of \" << pack05.standard_deviation()\r\n  << \" is \" << cdf(complement(pack05, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.97725\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 standard deviation to 0.06 kg,\r\nconstructing another new distribution called pack06.\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// Quantile of 0.05 = 2.90131, mean = 3, sd = 0.06\r\n\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n  << \" and standard deviation of \" << pack06.standard_deviation()\r\n  << \" is \" << cdf(complement(pack06, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.95221\r\n/*`\r\nNow we are getting really close, but to do the job properly,\r\nwe might need to use root finding method, for example the tools provided,\r\nand used elsewhere, in 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 can and should be even smarter\r\nand make a direct calculation.\r\n*/\r\n\r\n/*`Our required limit is minimum_weight = 2.9 kg, often called the random variate z.\r\nFor a standard normal distribution, then probability p = N((minimum_weight - mean) / sd).\r\n\r\nWe want to find the standard deviation that would be required to meet this limit,\r\nso that the p th quantile is located at z (minimum_weight).\r\nIn this case, the 0.05 (5%) quantile is at 2.9 kg pack weight, when the mean is 3 kg,\r\nensuring that 0.95 (95%) of packs are above the minimum weight.\r\n\r\nRearranging, we can directly calculate the required standard deviation:\r\n*/\r\nnormal N01; // standard normal distribution with meamn zero and unit standard deviation.\r\np = 0.05;\r\ndouble qp = quantile(N01, p);\r\ndouble sd95 = (minimum_weight - mean) / qp;\r\n\r\ncout << \"For the \"<< p << \"th quantile to be located at \"\r\n  << minimum_weight << \", would need a standard deviation of \" << sd95 << endl;\r\n// For the 0.05th quantile to be located at 2.9, would need a standard deviation of 0.0607957\r\n\r\n/*`We can now construct a new (normal) distribution pack95 for the 'better' packer,\r\nand check that our distribution will meet the specification.\r\n*/\r\n\r\nnormal pack95(mean, sd95);\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n  << \" and standard deviation of \" << pack95.standard_deviation()\r\n  << \" is \" << cdf(complement(pack95, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n/*`This calculation is generalized in the free function find_scale,\r\nas shown below, giving the same standard deviation.\r\n*/\r\ndouble ss = find_scale<normal>(minimum_weight, under_fraction, packs.mean());\r\ncout << \"find_scale<normal>(minimum_weight, under_fraction, packs.mean()); \" << ss << endl;\r\n// find_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\n\r\n/*`If we had defined an over_fraction, or percentage that must pass specification\r\n*/\r\ndouble over_fraction = 0.95;\r\n/*`And (wrongly) written\r\n\r\n double sso = find_scale<normal>(minimum_weight, over_fraction, packs.mean());\r\n\r\nWith the default policy, we would get a message like\r\n\r\n[pre\r\nMessage from thrown exception was:\r\n   Error in function boost::math::find_scale<Dist, Policy>(double, double, double, Policy):\r\n   Computed scale (-0.060795683191176959) is <= 0! Was the complement intended?\r\n]\r\n\r\nBut this would return a *negative* standard deviation - obviously impossible.\r\nThe probability should be 1 - over_fraction, not over_fraction, thus:\r\n*/\r\n\r\ndouble ss1o = find_scale<normal>(minimum_weight, 1 - over_fraction, packs.mean());\r\ncout << \"find_scale<normal>(minimum_weight, under_fraction, packs.mean()); \" << ss1o << endl;\r\n// find_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\n\r\n/*`But notice that using '1 - over_fraction' - will lead to a\r\n[link why_complements loss of accuracy, especially if over_fraction was close to unity.]\r\nIn this (very common) case, we should instead use the __complements,\r\ngiving the most accurate result.\r\n*/\r\n\r\ndouble ssc = find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean()));\r\ncout << \"find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean())); \" << ssc << endl;\r\n// find_scale<normal>(complement(minimum_weight, over_fraction, packs.mean())); 0.0607957\r\n\r\n/*`Note that our guess of 0.06 was close to the accurate value of 0.060795683191176959.\r\n\r\nWe can again confirm our prediction thus:\r\n*/\r\n\r\nnormal pack95c(mean, ssc);\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n  << \" and standard deviation of \" << pack95c.standard_deviation()\r\n  << \" is \" << cdf(complement(pack95c, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n/*`Notice that these two deceptively simple questions:\r\n\r\n* Do we over-fill to make sure we meet a minimum specification (or under-fill to avoid an overdose)?\r\n\r\nand/or\r\n\r\n* Do we measure better?\r\n\r\nare actually extremely common.\r\n\r\nThe weight of beef might be replaced by a measurement of more or less anything,\r\nfrom drug tablet content, Apollo landing rocket firing, X-ray treatment doses...\r\n\r\nThe scale can be variation in dispensing or uncertainty in measurement.\r\n*/\r\n//] [/normal_find_location_and_scale_eg Quickbook end]\r\n\r\n  }\r\n  catch(const 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    cout <<\r\n      \"\\n\"\"Message from thrown exception was:\\n   \" << e.what() << endl;\r\n  }\r\n  return 0;\r\n}  // int main()\r\n\r\n\r\n/*\r\n\r\nOutput is:\r\n\r\n//[normal_find_location_and_scale_output\r\n\r\nFind_location (mean) and find_scale (standard deviation) examples.\r\nPercentage of packs > 3.1 is 15.8655\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.06449 is 0.950005\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\nCauchy Setting the packer to 3 will mean that fraction of packs >= 2.9 is 0.75\r\nfind_location<cauchy>(minimum_weight, over fraction, standard_deviation); 3.53138\r\nCauchy Setting the packer to 3.53138 will mean that fraction of packs >= 2.9 is 0.95\r\nCauchy Setting the packer to -0.282052 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\nFor the 0.05th quantile to be located at 2.9, would need a standard deviation of 0.0607957\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\nfind_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\nfind_scale<normal>(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\nfind_scale<normal>(complement(minimum_weight, over_fraction, packs.mean())); 0.0607957\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n//] [/normal_find_location_and_scale_eg_output]\r\n\r\n*/\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0e5e0376c5df591b466fef42522ee9d78fbb42a9", "size": 18314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/find_mean_and_sd_normal.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_mean_and_sd_normal.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_mean_and_sd_normal.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": 44.1301204819, "max_line_length": 112, "alphanum_fraction": 0.7160642132, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6892892154310121}}
{"text": "#ifndef RSVD_ERROR_ESTIMATORS_HPP_\n#define RSVD_ERROR_ESTIMATORS_HPP_\n\n#include <Eigen/Dense>\n\nnamespace Rsvd {\n\n/// \\brief Compute the relative Frobenius error of a matrix approximation.\n///\n/// \\long The formula for the relative error is\n/// \\f[ \\varepsilon = \\frac{ \\| \\tilde{A} - A \\|_{\\mathrm{F}} }{ \\| A \\|_{\\mathrm{F}} }. \\f]\n///\n/// Both matrices can be real or complex.\n///\n/// \\tparam MatrixType Eigen matrix type.\n///\n/// \\param reference Reference matrix \\f$ A \\f$. It is assumed that this matrix has positive\n/// Frobenius norm.\n///\n/// \\param approximation Approximation \\f$ \\tilde{A} \\f$ of the reference matrix.\n///\n/// \\return Relative Frobenius error \\f$ \\varepsilon \\f$ of the approximation (non-negative real).\ntemplate <typename MatrixType>\ntypename Eigen::NumTraits<typename MatrixType::Scalar>::Real\nrelativeFrobeniusNormError(const MatrixType &reference, const MatrixType &approximation) {\n  const auto differenceNorm = (approximation - reference).norm();\n  const auto referenceNorm = reference.norm();\n\n  assert(referenceNorm > 0);\n\n  return differenceNorm / referenceNorm;\n}\n\n} // namespace Rsvd\n\n#endif\n", "meta": {"hexsha": "8659b0fb25f43c685c35c5172dc3a4b2cdf9c714", "size": 1130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rsvd/ErrorEstimators.hpp", "max_stars_repo_name": "valerii-filev-picsart/rsvd", "max_stars_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "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/rsvd/ErrorEstimators.hpp", "max_issues_repo_name": "valerii-filev-picsart/rsvd", "max_issues_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "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/rsvd/ErrorEstimators.hpp", "max_forks_repo_name": "valerii-filev-picsart/rsvd", "max_forks_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "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.5405405405, "max_line_length": 98, "alphanum_fraction": 0.717699115, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6891477594085732}}
{"text": "#include \"optimizers.h\"\n#include <Eigen/Dense>\n\nusing namespace probreg;\n\nGaussNewtonResult probreg::gaussNewton(const Vector& x, const gn_func_type& fn, Float eps, Integer num_max_iteration) {\n    const Float eps2 = eps * eps;\n    Vector xn = x;\n    Matrix rx;\n    for (Integer n = 0; n < num_max_iteration; ++n) {\n        ResidualAmatBvec amat_bvec = fn(xn);\n        const Vector dx = std::get<1>(amat_bvec).ldlt().solve(std::get<2>(amat_bvec));\n        xn -= dx;\n        rx = std::get<0>(amat_bvec);\n        if (dx.squaredNorm() < eps2) {\n            break;\n        }\n    }\n    return std::make_pair(xn, rx);\n}", "meta": {"hexsha": "38898e7b2181c2ce73b1253194d29da919620e97", "size": 613, "ext": "cc", "lang": "C++", "max_stars_repo_path": "probreg/cc/optimizers.cc", "max_stars_repo_name": "bing-jian/probreg", "max_stars_repo_head_hexsha": "eee9839e4f9d7286128371f8d58444fe7fae589c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probreg/cc/optimizers.cc", "max_issues_repo_name": "bing-jian/probreg", "max_issues_repo_head_hexsha": "eee9839e4f9d7286128371f8d58444fe7fae589c", "max_issues_repo_licenses": ["MIT"], "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/optimizers.cc", "max_forks_repo_name": "bing-jian/probreg", "max_forks_repo_head_hexsha": "eee9839e4f9d7286128371f8d58444fe7fae589c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T08:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T08:29:05.000Z", "avg_line_length": 30.65, "max_line_length": 119, "alphanum_fraction": 0.6084828711, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6891417481936336}}
{"text": "//\n// Created by robin jodon on 2020-04-16.\n//\n// Test file to understand how to use CLP\n//\n\n#include <catch2/catch.hpp>\n#include <iostream>\n#include <Eigen/Sparse>\n\n#include \"Interlocking/InterlockingSolver_Clp.h\"\n#include \"IO/JsonIOReader.h\"\n#include \"ClpSimplex.hpp\"\n\n\ntypedef Eigen::SparseMatrix<double> SpMat;\ntypedef Eigen::Triplet<double> T;\ntypedef Eigen::Matrix<double, 3, 1> Vector3d;\n\n/**\n * @brief Simple test case of CLP simplex solver\n *        We are solving the following LP problem\n *\n *        max 3x + 4y + 2z\n *    s.t.    2x           >= 4     E1\n *             x      + 2z >= 8     E2\n *                 3y +  z >= 6     E3\n *             (x,y,z)     >= 0     E4\n *\n *        Solution is: x,y,z = (2,1,3)\n *                     max   = 16\n */\nTEST_CASE(\"CLP simplex - Simple LP problem\") {\n    // Mock\n    shared_ptr<InputVarList> varList = make_shared<InputVarList>();\n    InitVar(varList.get());\n    shared_ptr<ContactGraph<double>> dat = make_shared<ContactGraph<double>>(varList);\n    InterlockingSolver_Clp<double> solver(dat, varList);\n    shared_ptr<typename InterlockingSolver<double>::InterlockingData> data;\n    //\n    int num_col = 3;\n    int num_row = 3;\n    int num_var = 3;\n\n    Vector3d objective_function(3, 4, 2);   // coefficients in objective function\n    Vector3d rhs(4, 8, 6);                  // the right hand side vector resulting from the constraints\n    SpMat A(num_row, num_col);                      // coefficient matrix\n\n    // Define A\n    std::vector<T> coef;\n    //\n    coef.emplace_back(T(0, 0, 2));\n    coef.emplace_back(T(1, 0, 1));\n    coef.emplace_back(T(1, 2, 2));\n    coef.emplace_back(T(2, 1, 3));\n    coef.emplace_back(T(2, 2, 1));\n\n    A.setFromTriplets(coef.begin(), coef.end());\n\n    CoinPackedMatrix matrix(true, num_row, num_col, A.nonZeros(), A.valuePtr(), A.innerIndexPtr(), A.outerIndexPtr(), A.innerNonZeroPtr());\n\n    // boundaries for rows and columns values\n\n    auto *objective(new double[num_var]);           // objective function params\n    auto *constraintLower(new double[num_row]);     // E1...E3 lower bounds\n    auto *constraintUpper(new double[num_row]);     // E1...E3 upper bounds\n    auto *varLower(new double[num_var]);            // E4\n    auto *varUpper(new double[num_var]);            // E4\n\n    // E4\n    for (size_t id = 0; id < num_var; id++) {\n        varLower[id] = 0;\n        varUpper[id] = COIN_DBL_MAX;\n    }\n\n    // Objective func + Ei for i in [1,2,3]\n    for (size_t id = 0; id < num_row; id++) {\n        constraintLower[id] = -COIN_DBL_MAX;\n        constraintUpper[id] = rhs[id];\n        objective[id] = -objective_function[id];  // simplex minimises by default\n    }\n\n    ClpSimplex model;\n    CoinMessageHandler handler;\n    handler.setLogLevel(0);\n    model.passInMessageHandler(&handler);\n    model.newLanguage(CoinMessages::us_en);\n    model.loadProblem(matrix, varLower, varUpper, objective, constraintLower, constraintUpper);\n    model.setPrimalTolerance(1e-9);\n    model.primal();\n    // Get the solution\n    const double obj_solution = model.rawObjectiveValue();\n    double *solution = model.primalColumnSolution();\n    double *row_solution = model.primalRowSolution();\n\n    SECTION(\"CLP simplex - Solutions checkup\") {\n        REQUIRE(solution[0] == Approx(2.0).epsilon(1E-9));\n        REQUIRE(solution[1] == Approx(1.0).epsilon(1E-9));\n        REQUIRE(solution[2] == Approx(3.0).epsilon(1E-9));\n    }\n\n    SECTION(\"CLP simplex - Constraints checkup\") {\n        REQUIRE(row_solution[0] == Approx(4.0).epsilon(1E-9));\n        REQUIRE(row_solution[1] == Approx(8.0).epsilon(1E-9));\n        REQUIRE(row_solution[2] == Approx(6.0).epsilon(1E-9));\n    }\n\n    SECTION(\"CLP simplex - Problem checkup\") {\n        REQUIRE(model.isProvenOptimal());\n        REQUIRE_FALSE(model.isProvenPrimalInfeasible());\n    }\n}", "meta": {"hexsha": "e3d93e84d051dc2bd09195c3405c0d9fe6671620", "size": 3818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Interlocking/Test_toymodel_clp.cpp", "max_stars_repo_name": "carlostapiarq/TopoLite", "max_stars_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-06-10T08:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T02:55:35.000Z", "max_issues_repo_path": "test/Interlocking/Test_toymodel_clp.cpp", "max_issues_repo_name": "carlostapiarq/TopoLite", "max_issues_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T12:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T07:56:42.000Z", "max_forks_repo_path": "test/Interlocking/Test_toymodel_clp.cpp", "max_forks_repo_name": "carlostapiarq/TopoLite", "max_forks_repo_head_hexsha": "d6eb9125518a88ea546917df5217978f34661b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-22T10:07:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T06:02:33.000Z", "avg_line_length": 34.0892857143, "max_line_length": 139, "alphanum_fraction": 0.6189104243, "num_tokens": 1073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684334, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6891417325697574}}
{"text": "#include <iostream>\n#include <sstream>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n \nusing big_int = boost::multiprecision::cpp_int;\n \nbig_int ipow(big_int base, big_int exp) {\n  big_int result(1);\n  while (exp) {\n    if (exp & 1) {\n      result *= base;\n    }\n    exp >>= 1;\n    base *= base;\n  }\n  return result;\n}\n \nbig_int ackermann(unsigned m, unsigned n) {\n  static big_int (*ack)(unsigned, big_int) =\n      [](unsigned m, big_int n)->big_int {\n    switch (m) {\n    case 0:\n      return n + 1;\n    case 1:\n      return n + 2;\n    case 2:\n      return 3 + 2 * n;\n    case 3:\n      return 5 + 8 * (ipow(big_int(2), n) - 1);\n    default:\n      return n == 0 ? ack(m - 1, big_int(1)) : ack(m - 1, ack(m, n - 1));\n    }\n  };\n  return ack(m, big_int(n));\n}\n \nint main() {\n  for (unsigned m = 0; m < 4; ++m) {\n    for (unsigned n = 0; n < 10; ++n) {\n      std::cout << \"A(\" << m << \", \" << n << \") = \" << ackermann(m, n) << \"\\n\";\n    }\n  }\n \n  std::cout << \"A(4, 1) = \" << ackermann(4, 1) << \"\\n\";\n \n  std::stringstream ss;\n  ss << ackermann(4, 2);\n  auto text = ss.str();\n  std::cout << \"A(4, 2) = (\" << text.length() << \" digits)\\n\"\n            << text.substr(0, 80) << \"\\n...\\n\"\n            << text.substr(text.length() - 80) << \"\\n\";\n}\n\n", "meta": {"hexsha": "f5f3f6f5a3ea3fa1b4b44d0a97c92c46862c2d4d", "size": 1258, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ackermann/better_main.cc", "max_stars_repo_name": "DomirScire/Ackermann", "max_stars_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T01:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T01:20:46.000Z", "max_issues_repo_path": "ackermann/better_main.cc", "max_issues_repo_name": "DomirScire/Ackermann", "max_issues_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_issues_repo_licenses": ["MIT"], "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/better_main.cc", "max_forks_repo_name": "DomirScire/Ackermann", "max_forks_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_forks_repo_licenses": ["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.4642857143, "max_line_length": 79, "alphanum_fraction": 0.4944356121, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739774, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.689099131534952}}
{"text": "/* \n * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org)\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\n#include <votca/tools/linalg.h>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"mkl.h\"\n#include \"mkl_lapacke.h\"\n\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\nvoid linalg_cholesky_decompose( ub::matrix<double> &A){\n    // Cholesky decomposition using MKL\n    // input matrix A will be changed\n\n    // LAPACK variables\n    MKL_INT info;\n    MKL_INT n = A.size1();\n    char uplo = 'L';\n    \n    // pointer for LAPACK\n    double * pA = const_cast<double*>(&A.data().begin()[0]);\n    info = LAPACKE_dpotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n    if ( info != 0 )\n        throw std::runtime_error(\"Matrix not symmetric positive definite\");\n}\n\n\nvoid linalg_cholesky_decompose( ub::matrix<float> &A){\n    // Cholesky decomposition using MKL\n    // input matrix A will be changed\n\n    // LAPACK variables\n    MKL_INT info;\n    MKL_INT n = A.size1();\n    char uplo = 'L';\n    \n    // pointer for LAPACK\n    float * pA = const_cast<float*>(&A.data().begin()[0]);\n    info = LAPACKE_spotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n    if ( info != 0 )\n        throw std::runtime_error(\"Matrix not symmetric positive definite\");\n}\n\n\n\n\nvoid linalg_cholesky_solve( ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b ){\n    /* calling program should catch the error error code\n     * thrown by LAPACKE_dpotrf and take\n     * necessary steps\n     */\n    \n    \n    // LAPACK variables\n    MKL_INT info;\n    MKL_INT n = A.size1();\n    char uplo = 'L';\n    \n    // pointer for LAPACK LU factorization of input matrix\n    double * pA = const_cast<double*>(&A.data().begin()[0]); // input array\n     \n    // get LU factorization\n    info = LAPACKE_dpotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n    \n    if ( info != 0 )\n        throw std::runtime_error(\"Matrix not symmetric positive definite\");\n    \n    MKL_INT nrhs = 1;\n    \n    // pointer of LAPACK LU solver\n    double * pb = const_cast<double*>(&b.data()[0]);\n    info = LAPACKE_dpotrs(LAPACK_ROW_MAJOR, uplo, n, nrhs, pA, n, pb, n );\n\n    // on output, b contains solution\n    x = b;\n}\n\n}}\n", "meta": {"hexsha": "51df6071f7254223e2b12d2e0fef21da5ac41bdb", "size": 2713, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/mkl/cholesky.cc", "max_stars_repo_name": "tomspur/votca-tools", "max_stars_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "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/libtools/linalg/mkl/cholesky.cc", "max_issues_repo_name": "tomspur/votca-tools", "max_issues_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "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/libtools/linalg/mkl/cholesky.cc", "max_forks_repo_name": "tomspur/votca-tools", "max_forks_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "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": 27.6836734694, "max_line_length": 98, "alphanum_fraction": 0.6509399189, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6890900626969079}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\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//[transform\r\n//` Shows how points can be transformed using the default strategy\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n\r\n\r\nint main()\r\n{\r\n    namespace bg = boost::geometry;\r\n\r\n    // Select a point near the pole (theta=5.0, phi=15.0)\r\n    bg::model::point<long double, 2, bg::cs::spherical<bg::degree> > p1(15.0, 5.0);\r\n    \r\n    // Transform from degree to radian. Default strategy is automatically selected,\r\n    // it will convert from degree to radian\r\n    bg::model::point<long double, 2, bg::cs::spherical<bg::radian> > p2;\r\n    bg::transform(p1, p2);\r\n    \r\n    // Transform from degree (lon-lat) to 3D (x,y,z). Default strategy is automatically selected, \r\n    // it will consider points on a unit sphere\r\n    bg::model::point<long double, 3, bg::cs::cartesian> p3;\r\n    bg::transform(p1, p3);\r\n    \r\n    std::cout \r\n        << \"p1: \" << bg::dsv(p1) << std::endl\r\n        << \"p2: \" << bg::dsv(p2) << std::endl\r\n        << \"p3: \" << bg::dsv(p3) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[transform_output\r\n/*`\r\nOutput:\r\n[pre\r\np1: (15, 5)\r\np2: (0.261799, 0.0872665)\r\np3: (0.084186, 0.0225576, 0.996195)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "440e633b0aef90313b662991d1b4c1b5e2330c91", "size": 1486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/transform.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/doc/src/examples/algorithms/transform.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/doc/src/examples/algorithms/transform.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.0181818182, "max_line_length": 99, "alphanum_fraction": 0.6150740242, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.689090060180712}}
{"text": "#include <Eigen/Dense>\n#include \"gtest/gtest.h\"\n#include \"lsq.h\"\n\n\nTEST(LSQ, TestRunnable){\n    Eigen::Matrix2f A;\n    A << 1, 2, 2, 1;\n    Eigen::Vector2f b;\n    b << 5, 4;\n    Eigen::Vector2f expected;\n    expected << 1, 2;\n    LSQ* lsq = new LSQ(A, b);\n    Eigen::Vector2f x = lsq->solve();\n    EXPECT_TRUE(expected.isApprox(x));\n}\n\n", "meta": {"hexsha": "63586f5d2d0a48b73b6eebec63d2b4c28935ce2b", "size": 336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bijou/lsq/lsq_test.cpp", "max_stars_repo_name": "sonnyhu/bijou", "max_stars_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bijou/lsq/lsq_test.cpp", "max_issues_repo_name": "sonnyhu/bijou", "max_issues_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bijou/lsq/lsq_test.cpp", "max_forks_repo_name": "sonnyhu/bijou", "max_forks_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6666666667, "max_line_length": 38, "alphanum_fraction": 0.5833333333, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6889910047062562}}
{"text": "/*\n * Introduction to the header template.\n * For each function FUNC, the file name shall be FUNC.hpp in src/DeemaAlomair folder.\n * Every FUNC shall be replaced with implemented function name.\n * The type of a CFS with FLOAT is CFST<FLOAT>\n * The code shall follow c++17 standard.\n * Only the c++ standard libraries are allowed.\n * C-style code is highly not recommended.\n */\n\n#ifndef FSL_FUNC_H\n#define FSL_FUNC_H\n\n#include <vector>\n#include <Eigen/Dense>\n/*Other library inclusion is here*/\nnamespace FSL{\n    template <class FLOAT>\n    void LinSolve(size_t n, const std::vector<std::vector<FLOAT>>& M, const std::vector<FLOAT>& y, std::vector<FLOAT>& x)\n    {\n        Eigen::Matrix<FLOAT, Eigen::Dynamic, Eigen::Dynamic> ME(n, n);\n        for(size_t i = 0; i < n; ++i)\n        {\n            for(size_t j = 0; j < n; ++j)\n            {\n                ME(i, j) = M[i][j];\n            }\n        }\n        Eigen::Matrix<FLOAT, Eigen::Dynamic, 1> xE(n), yE(n);\n        for(size_t i =0; i<n; ++i)\n        {\n            yE(i) = y[i];\n        }\n        xE = ME.colPivHouseholderQr().solve(yE);\n        x.resize(n);\n        for (size_t i=0; i< n; ++i)\n        {\n            x[i]=xE(i);\n        }\n    }\n}\n#endif\n\n/*\n * Type N in MIS shall be translated to size_t in C++. \n * This type is already introduced in CFSData.h\n */", "meta": {"hexsha": "4cf72858c642f8acedd46ec7937daf1a1332f0e3", "size": 1318, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSolve.hpp", "max_stars_repo_name": "caobo1994/FourierSeries", "max_stars_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_stars_repo_licenses": ["MIT"], "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/LinSolve.hpp", "max_issues_repo_name": "caobo1994/FourierSeries", "max_issues_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-09-18T21:51:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T17:54:25.000Z", "max_forks_repo_path": "src/LinSolve.hpp", "max_forks_repo_name": "caobo1994/FourierSeries", "max_forks_repo_head_hexsha": "e6b3cab9409aaaa8071adc82276dc22d82c0575c", "max_forks_repo_licenses": ["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.0425531915, "max_line_length": 121, "alphanum_fraction": 0.5690440061, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.6889667381281432}}
{"text": "#include \"pch.h\"\n#include <Eigen/Dense>\n#include \"ReverseDistortionEstimator.h\"\n#include \"photogrammetry.h\"\n\n\nReverseDistortionEstimator::ReverseDistortionEstimator(const Camera& cam)\n{\n\t//solves for the inverse distortion (like opencv)\n\t//see: https://docs.opencv.org/3.4.6/d9/d0c/group__calib3d.html\n\t\n\tint x_spacing = cam.W / 10;\n\tint y_spacing = cam.H / 10;\n\tvector<std::array<double, 2> > grid_points;\n\tvector<std::array<double, 2> > grid_points_undistorted;\n\tvector<std::array<double, 2> > dist_corrections;\n\tgrid_points.reserve(200);\n\t\n\t//calculating the estimation grid:\n\tfor (int x = 0; x <= cam.W; x += x_spacing)\n\t{\n\t\tfor (int y = 0; y <= cam.H; y += y_spacing)\n\t\t{\n\t\t\tgrid_points.push_back({\n\t\t\t\tstatic_cast<double>(x),\n\t\t\t\tstatic_cast<double>(y) });\n\t\t}\n\t}\n\tgrid_points.shrink_to_fit();\n\n\t//transformation from column/row coordinates to image-centered coordinates\n\tstd::transform(grid_points.begin(), grid_points.end(), grid_points.begin(),\n\t\t[&](std::array<double,2>& p ){\n\t\treturn std::array<double, 2>{\n\t\t\tp[0] = p[0] - cam.W / 2.0 + 0.5,\n\t\t\tp[1] = cam.H / 2.0 - p[1] - 0.5}; });\n\n\n\t//transformation from image-centered coordinates to fiducial coordiantes\n\tstd::transform(grid_points.begin(), grid_points.end(), grid_points.begin(),\n\t\t[&](std::array<double, 2>& p) {\n\t\treturn std::array<double, 2>{\n\t\t\tp[0] = p[0] - cam.InternalOrientation[1],\n\t\t\tp[1] = p[1] - cam.InternalOrientation[2]}; });\n\n\t\n\tgrid_points_undistorted.resize(grid_points.size());\n\tdist_corrections.resize(grid_points.size());\n\n\t\n\tstd::transform(grid_points.begin(), grid_points.end(), dist_corrections.begin(),\n\t\t[&](std::array<double, 2>& p) {\n\t\treturn std::array<double, 2>{\n\t\t\tfT_xDistCorrection(cam.RadialDistortion, cam.TangentialDistortion, p[0], p[1]),\n\t\t\tfT_yDistCorrection(cam.RadialDistortion, cam.TangentialDistortion, p[0], p[1])}; });\n\t\n\n\tfor (size_t i = 0, S = grid_points.size(); i < S; i++)\n\t{\n\t\tgrid_points_undistorted.at(i)[0] = grid_points.at(i)[0] - dist_corrections.at(i)[0];\n\t\tgrid_points_undistorted.at(i)[1] = grid_points.at(i)[1] - dist_corrections.at(i)[1];\n\t}\n\n\t//solving the reversed distortion using Eieng linear algerbra tools:\n\t//each coordinate generates one equation:\n\tEigen::MatrixXd A(2 * grid_points_undistorted.size(), 5);\n\tEigen::VectorXd L(2 * grid_points_undistorted.size());\n\tEigen::VectorXd X(5);\n\tEigen::VectorXd V(2 * grid_points_undistorted.size());\n\n\tfor (size_t i = 0, S = grid_points_undistorted.size(); i < S; i++)\n\t{\n\t\t//we are estimating in the normalized space so w have to use normalized values\n\t\tdouble x = grid_points_undistorted.at(i)[0] /cam.InternalOrientation[0];\n\t\tdouble y = -grid_points_undistorted.at(i)[1] /cam.InternalOrientation[0];\n\t\tdouble dx = dist_corrections.at(i)[0] / cam.InternalOrientation[0];\n\t\tdouble dy = -dist_corrections.at(i)[1] / cam.InternalOrientation[0];\n\t\tdouble rr = x * x + y * y;\n\n\t\tA(2 * i, 0) = x * rr;\n\t\tA(2 * i, 1) = x * rr*rr;\n\t\tA(2 * i, 2) = x * rr*rr*rr;\n\t\tA(2 * i, 3) = 2 * x * y;\n\t\tA(2 * i, 4) = rr + 2 * x*x;\n\t\tL(2 * i) = dx;\n\n\t\tA(2 * i + 1, 0) = y * rr;\n\t\tA(2 * i + 1, 1) = y * rr*rr;\n\t\tA(2 * i + 1, 2) = y * rr*rr*rr;\n\t\tA(2 * i + 1, 3) = rr + 2 * y * y;\n\t\tA(2 * i + 1, 4) = 2 * x * y;\n\t\tL(2 * i + 1) = dy;\n\t}\n\n\tX = A.colPivHouseholderQr().solve(L);\n\tV = L - A * X;\n\tRMSE = std::sqrt((1.0 /(L.rows()-1)) * V.transpose()*V);\n\n\tfor (int i = 0; i < 5; i++) DistortionYDown.at(i) = X(i);\n\n}\n\n\nReverseDistortionEstimator::~ReverseDistortionEstimator()\n{\n}\n", "meta": {"hexsha": "a4638bcf645eb0ba273a6ae89c111f9464655972", "size": 3437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xtrel/ReverseDistortionEstimator.cpp", "max_stars_repo_name": "kubakolecki/xtrel", "max_stars_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T14:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T03:38:52.000Z", "max_issues_repo_path": "xtrel/ReverseDistortionEstimator.cpp", "max_issues_repo_name": "kubakolecki/xtrel", "max_issues_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "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": "xtrel/ReverseDistortionEstimator.cpp", "max_forks_repo_name": "kubakolecki/xtrel", "max_forks_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "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.1214953271, "max_line_length": 87, "alphanum_fraction": 0.6488216468, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6888924592939887}}
{"text": "/*****************************************************************************\n * where.cpp     Blitz++ 1D Array example, illustrating where(X,Y,Z)\n *               expressions.\n *****************************************************************************/\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n//  Vector<int> x = Range(-3,+3);   // [ -3 -2 -1  0  1  2  3 ]\n    Array<int,1> x(Range(-3,+3));\n    x = tensor::i;\n\n    // The where(X,Y,Z) function is similar to the X ? Y : Z operator.\n    // If X is logical true, then Y is returned; otherwise, Z is\n    // returned.\n\n//  Vector<int> y = where(abs(x) > 2, x+10, x-10);\n    Array<int,1> y(x.shape());\n    y = where(abs(x) > 2, x+10, x-10);\n\n    // The above statement is transformed into something resembling:\n    //\n    // for (unsigned i=0; i < 7; ++i)\n    //     y[i] = (abs(x[i]) > 2) ? (x[i]+10) : (x[i]-10);\n    //\n    // The first expression (abs(x) > 2) can involve the usual\n    // comparison and logical operators: < > <= >= == != && || \n\n    cout << x << endl\n         << y << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "9ff8a2c4f2f2bdd80a870e73d97a999c492adb81", "size": 1090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/where.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/where.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/where.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.6842105263, "max_line_length": 79, "alphanum_fraction": 0.4449541284, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.8104789086703224, "lm_q1q2_score": 0.6888837046878981}}
{"text": "#include \"mnist_loader.h\"\n#include \"node.h\"\n\n#include <iostream>\n#include <memory>\n#include <Eigen/Core>\n\n#define EIGEN_MPL2_ONLY\n\n#define INPUT_SIZE  784\n#define HIDDEN_SIZE 50\n#define OUTPUT_SIZE 10\n\nconst double VAR_DIFF  = 1.0e-4;\nconst double MOD_RATIO = 1.0e-2;\n\nnamespace {\n\tEigen::VectorXf ReLu(Eigen::VectorXf &val)\n\t{\n\t\tEigen::VectorXf ret(val.rows());\n\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\tret[i] = fmax(0, val[i]);\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tEigen::VectorXf Softmax(Eigen::VectorXf &val)\n\t{\n\t\tEigen::VectorXf ret(val.rows());\n\n\t\tdouble sum = 0;\n\t\tdouble *exp_array = new double[val.rows()];\n\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\texp_array[i] = exp(val[i]);\n\t\t\tsum += exp_array[i];\n\t\t}\n\n\t\t// printf(\"softmax sum = %f\\n\", sum);\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\tret[i] = exp_array[i] / sum;\n\t\t}\n\n\t\tdelete[] exp_array;\n\n\t\treturn ret;\n\t}\n\n\tEigen::VectorXf MakeOnehotVector(int size, int index)\n\t{\n\t\tEigen::VectorXf ret = Eigen::VectorXf::Zero(size);\n\t\tret[index] = 1;\n\t\treturn ret;\n\t}\n\n\tfloat SquareError(Eigen::VectorXf vec1, Eigen::VectorXf vec2)\n\t{\n\t\tassert(vec1.rows() == vec2.rows());\n\t\tassert(vec1.cols() == vec2.cols());\n\t\tassert(vec1.cols() == 1);\n\n\t\tfloat error = 0;\n\t\tfor(int i = 0 ; i < vec1.rows() ; i++)\n\t\t{\n\t\t\tfloat v = vec1[i] - vec2[i];\n\t\t\terror += v * v;\n\t\t}\n\n\t\treturn error;\n\t}\n\n\tint MaxIndex(Eigen::VectorXf vec)\n\t{\n\t\tint max_index = 0;\n\t\tfor(int i = 0 ; i < vec.rows() ; i++)\n\t\t{\n\t\t\tif(vec[max_index] < vec[i])\n\t\t\t{\n\t\t\t\tmax_index = i;\n\t\t\t}\n\t\t}\n\t\treturn max_index;\n\t}\n};\n\nEigen::VectorXf Array2VectorXf(uint8_t *array, int size)\n{\n\tEigen::VectorXf ret(size);\n\n\t// this conversion needs due to different data format\n\tfor(int i = 0 ; i < size ; i++)\n\t{\n\t\tret[i] = array[i];\n\t}\n\n\treturn ret;\n}\n\nEigen::VectorXf Predict(Node &node1, Node &node2, Eigen::VectorXf input)\n{\n\tEigen::VectorXf temp;\n\n\ttemp = node1.Calc(input);\n\ttemp = ReLu(temp);\n\ttemp = node2.Calc(temp);\n\ttemp = Softmax(temp);\n\n\treturn temp;\n}\n\ndouble CalcError(Node &node1, Node &node2, Eigen::VectorXf input, Eigen::VectorXf ans)\n{\n\tEigen::VectorXf output     = Predict(node1, node2, input);\n\tdouble          error_rate = SquareError(output, ans);\n\n\treturn error_rate;\n}\n\nint main()\n{\n\tstd::vector<std::shared_ptr<Image> > train_image_list;\n\tstd::vector<uint8_t>                 train_label_list;\n\tstd::vector<std::shared_ptr<Image> > test_image_list;\n\tstd::vector<uint8_t>                 test_label_list;\n\n\tEigen::initParallel();\n\tEigen::setNbThreads(4);\n\n\tprintf(\"[INFO] load image...\\n\");\n\tstd::shared_ptr<MnistLoader> loader = std::make_shared<MnistLoader>();\n\tif(loader->LoadImage(\"../train-images-idx3-ubyte\", train_image_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadLabel(\"../train-labels-idx1-ubyte\", train_label_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadImage(\"../t10k-images-idx3-ubyte\", test_image_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadLabel(\"../t10k-labels-idx1-ubyte\", test_label_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tNode node1(INPUT_SIZE, HIDDEN_SIZE);\n\tif(node1.Load(\"weight_node1\") == false)\n\t{\n\t\tprintf(\"[INFO] node1 weight value initialize with random value.\\n\");\n\t}\n\tNode node2(HIDDEN_SIZE, OUTPUT_SIZE);\n\tif(node2.Load(\"weight_node2\") == false)\n\t{\n\t\tprintf(\"[INFO] node2 weight value initialize with random value.\\n\");\n\t}\n\n\tprintf(\"[INFO] training...\\n\");\n\tsranddev();\n\t// for(int image_index = 0 ; image_index < train_image_list.size() ; image_index++)\n\t// for(int image_index = 0 ; image_index < 100 ; image_index++)\n\tfor(int train_count = 0 ; train_count < 100 ; train_count++)\n\t{\n\t\tint image_index = rand() % train_image_list.size();\n\n//\t\tif(image_index % 100 == 0)\n//\t\t{\n//\t\t\tprintf(\"[INFO] exec %d/%d\\n\", image_index, (int)train_label_list.size());\n//\t\t}\n\n\t\tstd::shared_ptr<Image> image = train_image_list[image_index];\n\t\tEigen::VectorXf        input = Array2VectorXf(image->image, image->image_size);\n\t\tint                    ans   = train_label_list[image_index];\n\t\tEigen::VectorXf        ans_vec = MakeOnehotVector(OUTPUT_SIZE, ans);\n//\t\tprintf(\"image_index = %d, ans = %d\\n\", image_index, ans);\n\n\t\tinput.normalize();\n\n\t\tdouble *node1_mod = new double[node1.GetMaxWeightIndex()];\n\t\tdouble *node2_mod = new double[node2.GetMaxWeightIndex()];\n\n\t\tfor(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tdouble dyp = 0;\n\t\t\tdouble dyn = 0;\n\n\t\t\tnode1.PushWeightDiff(i, VAR_DIFF);\n\t\t\tdyp = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode1.PopWeightDiff();\n\n\t\t\tnode1.PushWeightDiff(i, -VAR_DIFF);\n\t\t\tdyn = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode1.PopWeightDiff();\n\n\t\t\tnode1_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF);\n\n//\t\t\tprintf(\"dyp=%f, dyn=%f, mod=%f\\n\", dyp, dyn, node1_mod[i]);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tdouble dyp = 0;\n\t\t\tdouble dyn = 0;\n\n\t\t\tnode2.PushWeightDiff(i, VAR_DIFF);\n\t\t\tdyp = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode2.PopWeightDiff();\n\n\t\t\tnode2.PushWeightDiff(i, -VAR_DIFF);\n\t\t\tdyn = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode2.PopWeightDiff();\n\n\t\t\tnode2_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF);\n\n//\t\t\tprintf(\"dyp=%lf, dyn=%lf, mod=%lf\\n\", dyp, dyn, node2_mod[i]);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tnode1.AddWeight(i, node1_mod[i] * -MOD_RATIO);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tnode2.AddWeight(i, node2_mod[i] * -MOD_RATIO);\n\t\t}\n\n\t\tdelete[] node1_mod;\n\t\tdelete[] node2_mod;\n\n\t\t//return 1;\n\n//\t\tif(image_index == 10)\n//\t\t{\n//\t\t\t// optimization test\n//\t\t\treturn 1;\n//\t\t}\n\t}\n\n\tnode1.Save(\"weight_node1\");\n\tnode2.Save(\"weight_node2\");\n\n\tprintf(\"[INFO] test...\\n\");\n\tstd::vector<uint8_t> result_list;\n\tfor(int image_index = 0 ; image_index < test_image_list.size() ; image_index++)\n\t{\n\t\tstd::shared_ptr<Image> image = test_image_list[image_index];\n\t\tEigen::VectorXf        input = Array2VectorXf(image->image, image->image_size);\n\n\t\tinput.normalize();\n\t\tEigen::VectorXf output = Predict(node1, node2, input);\n\n\t\tint result = MaxIndex(output);\n\t\tresult_list.push_back(result);\n\n\t}\n\n\tassert(result_list.size() == test_label_list.size());\n\tint success_count = 0;\n\tint fail_count    = 0;\n\tfor(int i = 0 ; i < result_list.size() ; i++)\n\t{\n//\t\tprintf(\"result = %d, test = %d,\", result_list[i], test_label_list[i]);\n\t\tif(result_list[i] == test_label_list[i])\n\t\t{\n\t\t\tsuccess_count++;\n\t\t}else\n\t\t{\n\t\t\tfail_count++;\n\t\t}\n\t}\n\tfloat accuracy = success_count / (float)(success_count + fail_count);\n\tstd::cout << \"accuracy = \" << accuracy << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d31b1b03277cfc79788d0a6426a3d0fb0c05b018", "size": 6577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c/main.cpp", "max_stars_repo_name": "yasuharu/dlearning", "max_stars_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "yasuharu/dlearning", "max_issues_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "yasuharu/dlearning", "max_forks_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_forks_repo_licenses": ["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.9965034965, "max_line_length": 86, "alphanum_fraction": 0.6346358522, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6887970265746812}}
{"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_EPS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_EPS_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Eps Eps (function template)\n\n  Generates a constant equals to the [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon).\n\n  @headerref{<boost/simd/constant/eps.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Eps();\n      @endcode\n\n  2.  @code\n      template<typename T> T Eps( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T equals to the difference between 1 and the next representable\n  value of type @c T.\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:\n\n  | Type       | `double`       | `float`       | Integer |\n  |:-----------|:---------------|---------------|---------|\n  | **Values** | \\f$2^{-52}\\f$  | \\f$2^{-23}\\f$ |    1    |\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/eps.hpp>\n#include <boost/simd/constant/simd/eps.hpp>\n\n#endif\n", "meta": {"hexsha": "f9266804d4e4395add7321ba486193c4bd99608c", "size": 1711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/eps.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/eps.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/eps.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": 30.5535714286, "max_line_length": 102, "alphanum_fraction": 0.5008766803, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6887127253404526}}
{"text": "#include <iostream>\n#include <ctime>\n#include <Eigen/Dense>\n\nint main(int argc, char **argv)\n{\n  // 100x100 Random Matrix\n  Eigen::MatrixXd Rand = Eigen::MatrixXd::Random(100, 100);\n  Eigen::MatrixXd A = Rand * Rand.transpose();\n  Eigen::VectorXd b_ = Eigen::VectorXd::Random(100);\n  Eigen::VectorXd x_ = Eigen::VectorXd::Zero(100);\n\n  clock_t t_start = clock();\n\n  // LU Decomposition\n  x_ = A.partialPivLu().solve(b_);  // A must be Invertible\n  std::cout << \"time of partialPivLu() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n  x_ = A.fullPivLu().solve(b_);\n  std::cout << \"time of fullPivLu() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n\n  // QR Decomposition\n  x_ = A.householderQr().solve(b_);\n  std::cout << \"time of householderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n  x_ = A.colPivHouseholderQr().solve(b_);\n  std::cout << \"time of colPivHouseholderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n  x_ = A.fullPivHouseholderQr().solve(b_);\n  std::cout << \"time of fullPivHouseholderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n\n  // Cholesky Decomposition\n  x_ = A.llt().solve(b_); // A must be Positive Definite\n  std::cout << \"time of llt() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n  x_ = A.ldlt().solve(b_);  // A must be Positive or Negative Semidefinite\n  std::cout << \"time of ldlt() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n  // std::cout << \"x = \" << x_.transpose() << std::endl;\n  t_start = clock();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "014e19efa93b70e7980fac0640e8a22809268c1a", "size": 2211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PA2/code/src/useSolvers.cpp", "max_stars_repo_name": "SS47816/VSLAM", "max_stars_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA2/code/src/useSolvers.cpp", "max_issues_repo_name": "SS47816/VSLAM", "max_issues_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA2/code/src/useSolvers.cpp", "max_forks_repo_name": "SS47816/VSLAM", "max_forks_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_forks_repo_licenses": ["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.7894736842, "max_line_length": 129, "alphanum_fraction": 0.5929443691, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.688545545376078}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"algorithms/math/greatest_common_divisor.hpp\"\n\nBOOST_AUTO_TEST_SUITE(TestGreatestCommonDivisor)\n\nBOOST_AUTO_TEST_CASE(numbers)\n{\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(1, 1) == 1);\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(5, 1) == 1);\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(5, 15) == 5);\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(18, 35) == 1);\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(28851538, 1183019) == 17657);\n    BOOST_CHECK(Algo::Math::GreatestCommonDivisor::Calc(3918848, 1653264) == 61232);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f0a01c01836e6b0a3ab8292c186a2db4fe7f46ab", "size": 655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/math/test_greates_common_divisor.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/algorithms/math/test_greates_common_divisor.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/algorithms/math/test_greates_common_divisor.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 38.5294117647, "max_line_length": 85, "alphanum_fraction": 0.7496183206, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6885455217452241}}
{"text": "// Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n#define BOOST_TEST_MODULE AlgorithmTest\n#include <boost/test/unit_test.hpp>\n#include <poplibs_support/Algorithm.hpp>\n\nusing namespace poplibs_support;\n\nBOOST_AUTO_TEST_CASE(BalancedPartitionZeroPartitions) {\n  // The correct answer is 0 of either size of partition as\n  // ceil(1/0) and floor(1/0) are both infinity.\n  auto p = balancedPartition(1u, 0u);\n  BOOST_CHECK_EQUAL(p.first, 0u);\n  BOOST_CHECK_EQUAL(p.second, 0u);\n}\n\nBOOST_AUTO_TEST_CASE(BalancedPartitionZeroSize) {\n  // Any answer is correct here so just check this works.\n  BOOST_CHECK_NO_THROW(balancedPartition(0u, 1u));\n}\n\nBOOST_AUTO_TEST_CASE(BalancedPartitionNLessThanD) {\n  auto p = balancedPartition(1u, 2u);\n  // We expect n partitions of size 1 and d - n partitions of size 0.\n  BOOST_CHECK_EQUAL(p.first, 1u);\n  BOOST_CHECK_EQUAL(p.second, 1u);\n\n  p = balancedPartition(3u, 5u);\n  BOOST_CHECK_EQUAL(p.first, 3u);\n  BOOST_CHECK_EQUAL(p.second, 2u);\n}\n\nBOOST_AUTO_TEST_CASE(BalancedPartitionDividesEqually) {\n  auto p = balancedPartition(20u, 5u);\n  // We expect the non-zero answer in the first return even\n  // though mathematically the answer being in the second return would\n  // be correct.\n  BOOST_CHECK_EQUAL(p.first, 5u);\n  BOOST_CHECK_EQUAL(p.second, 0u);\n}\n\nBOOST_AUTO_TEST_CASE(BalancedPartitionDividesUnequally) {\n  constexpr unsigned n = 20u;\n\n  // For all divisors which give ceil(n/d)=2 and floor(n/d)=1\n  for (unsigned d = n / 2 + 1; d < n; ++d) {\n    auto p = balancedPartition(n, d);\n    BOOST_CHECK_EQUAL(p.first * ceildiv(n, d) + p.second * floordiv(n, d), n);\n    BOOST_CHECK_EQUAL(p.first + p.second, d);\n  }\n}\n", "meta": {"hexsha": "c35869388b7e95c97d32cf67ee13fd5ce7276c20", "size": 1662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/poplibs_support/AlgorithmTest.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tests/poplibs_support/AlgorithmTest.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/poplibs_support/AlgorithmTest.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 32.5882352941, "max_line_length": 78, "alphanum_fraction": 0.7352587244, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6884177848406229}}
{"text": "//\n// Dynamics of a single pendulum.\n// State space is 2-d [\\theta, \\dot\\theta]: angle, angular velocity\n// If \\theta=\\pi is straight up, \\theta=0 is straight down\n// \n\n# pragma once\n\n#include <Eigen/Dense>\n\n#include <experiments/simulators/simulator_utils.hh>\n\nnamespace simulators\n{\nnamespace pendulum\n{\n\ntemplate<int dim>\nusing Vector = simulators::Vector<dim>;\n\nenum State\n{\n    THETA = 0,\n    THETADOT,\n    STATE_DIM\n};\n\nenum Control \n{\n    TORQUE = 0,\n    CONTROL_DIM\n};\n\n// Useful for holding the parameters of the pendulum, including integration timestep.\nclass Pendulum\n{\npublic:\n    Pendulum(const double dt, const double damping_coeff, const double length);\n    // Discrete time dynamics.\n    Vector<STATE_DIM> operator()(const Vector<STATE_DIM>& x, const Vector<CONTROL_DIM>& u);\nprivate:\n    double dt_;\n    double damping_coeff_;\n    double length_;\n\n};\n\n\n// Returns a function that can return x_{t+1} = f(x_t, u_t) for a chosen dt. \n// Underlying uses RK4 integration.\nilqr::DynamicsFunc make_discrete_dynamics_func(const double dt, const double length, const double damping_coeff);\n\n// Defines pendulum dynamics as xdot = f(x,u).\n//Eigen::VectorXd continuous_dynamics(const Eigen::VectorXd& state, const Eigen::VectorXd& control, \n//                                    const double length, const double damping_coeff);\n\nVector<STATE_DIM> continuous_dynamics(const Vector<STATE_DIM>& x, const Vector<CONTROL_DIM>& u, \n                                    const double length, const double damping_coeff);\n} // namespace pendulum\n} // namespace simulators\n", "meta": {"hexsha": "e0a689ab1a94c40477d3974b23047898ee8860cb", "size": 1569, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/pendulum.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/experiments/simulators/pendulum.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/experiments/simulators/pendulum.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 25.7213114754, "max_line_length": 113, "alphanum_fraction": 0.6998087954, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012309124793}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__SO3_HPP_\n#define SMOOTH__SO3_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/so3.hpp\"\n#include \"lie_group.hpp\"\n#include \"map.hpp\"\n\nnamespace smooth {\n\n// \\cond\ntemplate<typename Scalar>\nclass SO2;\n// \\endcond\n\n/**\n * @brief Base class for SO3 Lie group types\n *\n * Internally represented as a member of \\f$ \\mathbb{S}^3 \\f$ (unit quaternions).\n *\n * Memory layout\n * -------------\n *\n * - Group:    \\f$ \\mathbf{x} = [q_x, q_y, q_z, q_w] \\f$ (same as Eigen quaternion).\n * - Tangent:  \\f$ \\mathbf{a} = [\\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, q_w >= 0 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_x, \\omega_y, \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * 3x3 rotation matrix\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n *   0 & -\\omega_z & \\omega_y \\\\\n *  \\omega_z &   0 & -\\omega_x \\\\\n *  -\\omega_y &   \\omega_x & 0 \\\\\n * \\end{bmatrix} \\in \\mathbb{R}^{3 \\times 3}\n * \\f]\n */\ntemplate<typename _Derived>\nclass SO3Base : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  SO3Base() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Access quaterion.\n   */\n  Eigen::Map<Eigen::Quaternion<Scalar>> quat() requires is_mutable\n  {\n    return Eigen::Map<Eigen::Quaternion<Scalar>>(static_cast<_Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Access const quaterion.\n   */\n  Eigen::Map<const Eigen::Quaternion<Scalar>> quat() const\n  {\n    return Eigen::Map<const Eigen::Quaternion<Scalar>>(static_cast<const _Derived &>(*this).data());\n  }\n\n  /**\n   * @brief Return euler angles.\n   *\n   * @param i1, i2, i3 euler angle axis convention (\\f$0=x, 1=y, 2=z\\f$).\n   *        Default values correspond to ZYX rotation.\n   *\n   * Returned angles a1, a2, a3 are s.t. rotation is described by\n   * \\f$ Rot_{i_1}(a_1) * Rot_{i_2}(a_2) * Rot_{i_3}(a_3). \\f$\n   * where \\f$ Rot_i(a) \\f$ rotates an angle \\f$a\\f$ around the \\f$i\\f$:th axis.\n   */\n  Eigen::Vector3<Scalar>\n  eulerAngles(Eigen::Index i1 = 2, Eigen::Index i2 = 1, Eigen::Index i3 = 0) const\n  {\n    return quat().toRotationMatrix().eulerAngles(i1, i2, i3);\n  }\n\n  /**\n   * @brief Rotation action on 3D vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Vector3<Scalar> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return quat() * v;\n  }\n\n  /**\n   * @brief Project to SO2.\n   *\n   * This keeps the yaw/z axis component of the rotation.\n   *\n   * @note SO2 header must be included.\n   */\n  SO2<Scalar> project_so2() const\n  {\n    using std::atan2;\n\n    const auto q = quat();\n    Scalar yaw   = atan2(\n      Scalar(2) * (q.w() * q.z() + q.x() * q.y()),\n      Scalar(1) - Scalar(2) * (q.y() * q.y() + q.z() * q.z()));\n    return SO2<Scalar>(yaw);\n  }\n};\n\n// STORAGE TYPE TRAITS\n\n// \\cond\ntemplate<typename _Scalar>\nclass SO3;\n// \\endcond\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<SO3<_Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = SO3Impl<_Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = SO3<NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate<typename _Scalar>\nclass SO3 : public SO3Base<SO3<_Scalar>>\n{\n  using Base = SO3Base<SO3<_Scalar>>;\n\n  SMOOTH_GROUP_API(SO3);\n\npublic:\n  /**\n   * @brief Construct from quaternion.\n   *\n   * @param quat Eigen quaternion.\n   *\n   * @note Input is normalized inside constructor.\n   */\n  template<typename Derived>\n  SO3(const Eigen::QuaternionBase<Derived> & quat) : coeffs_(quat.normalized().coeffs())\n  {\n    if (coeffs_(3) < 0) { coeffs_ *= Scalar(-1); }\n  }\n\n  /**\n   * @brief SO3 representing rotation around the x axis\n   * @param angle angle of rotation [rad]\n   */\n  static SO3 rot_x(const Scalar & angle)\n  {\n    using std::cos, std::sin;\n\n    SO3 ret;\n    ret.coeffs() << sin(angle / 2), Scalar(0), Scalar(0), cos(angle / 2);\n    if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n    return ret;\n  }\n\n  /**\n   * @brief SO3 representing rotation around the y axis\n   * @param angle angle of rotation [rad]\n   */\n  static SO3 rot_y(const Scalar & angle)\n  {\n    using std::cos, std::sin;\n\n    SO3 ret;\n    ret.coeffs() << Scalar(0), sin(angle / 2), Scalar(0), cos(angle / 2);\n    if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n    return ret;\n  }\n\n  /**\n   * @brief SO3 representing rotation around the z axis\n   * @param angle angle of rotation [rad]\n   */\n  static SO3 rot_z(const Scalar & angle)\n  {\n    using std::cos, std::sin;\n\n    SO3 ret;\n    ret.coeffs() << Scalar(0), Scalar(0), sin(angle / 2), cos(angle / 2);\n    if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n    return ret;\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<SO3<_Scalar>>> : public liebase_info<SO3<_Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate<typename _Scalar>\nclass Map<SO3<_Scalar>> : public SO3Base<Map<SO3<_Scalar>>>\n{\n  using Base = SO3Base<Map<SO3<_Scalar>>>;\n\n  SMOOTH_MAP_API();\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct liebase_info<Map<const SO3<_Scalar>>> : public liebase_info<SO3<_Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate<typename _Scalar>\nclass Map<const SO3<_Scalar>> : public SO3Base<Map<const SO3<_Scalar>>>\n{\n  using Base = SO3Base<Map<const SO3<_Scalar>>>;\n\n  SMOOTH_CONST_MAP_API();\n};\n\nusing SO3f = SO3<float>;   ///< SO3 with float scalar representation\nusing SO3d = SO3<double>;  ///< SO3 with double scalar representation\n\n}  // namespace smooth\n\n#endif  // SMOOTH__SO3_HPP_\n", "meta": {"hexsha": "073c8e9783a81d56dba1bc15ae47dd866775be2c", "size": 7214, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/so3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "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/smooth/so3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "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/smooth/so3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["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.2237762238, "max_line_length": 100, "alphanum_fraction": 0.6443027447, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012285660999}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\nnamespace mdk {\n    using VRef = Eigen::Vector3d const&;\n\n    inline double angle(VRef v1, VRef v2, VRef v3) {\n        auto u1 = v2 - v1, u2 = v2 - v3;\n        return acos(u1.dot(u2) / (u1.norm() * u2.norm()));\n    }\n\n    inline double dihedral(VRef v1, VRef v2, VRef v3, VRef v4) {\n        auto u1 = v2 - v1, u2 = v3 - v2, u3 = v4 - v3;\n        auto d1 = u1.cross(u2), d2 = u2.cross(u3);\n\n        if (d1.isZero() || d2.isZero()) return 0.0;\n        double phi = acos(d1.dot(d2) / (d1.norm() * d2.norm()));\n        if (d1.dot(u3) < 0.) phi = -phi;\n        return phi;\n    }\n\n    double asphericity(Vectors const& v) {\n        Vector mean = v.vectorwise().mean();\n\n        Eigen::Matrix3d mit;\n        double crg;\n        for (size_t i = 0; i < v.size(); ++i) {\n            Vector diff = v.col(i) - mean;\n            crg += diff.squaredNorm();\n\n            Vector sq_diff = diff.array() * diff.array();\n            mit(0,0) += sq_diff(1) + sq_diff(2);\n            mit(1,1) += sq_diff(2) + sq_diff(0);\n            mit(2,2) += sq_diff(0) + sq_diff(1);\n            mit(0,1) -= diff(0) * diff(1);\n            mit(1,2) -= diff(1) * diff(2);\n            mit(0,2) -= diff(0) * diff(2);\n        }\n        mit(1,0) = mit(0,1);\n        mit(2,1) = mit(1,2);\n        mit(2,0) = mit(0,2);\n        crg = sqrt(crg / v.size());\n\n        auto eigenvaluesC = mit.eigenvalues();\n        double eigenvalues[3] = {\n            sqrt(eigenvaluesC(0).real() / v.size()),\n            sqrt(eigenvaluesC(1).real() / v.size()),\n            sqrt(eigenvaluesC(2).real() / v.size())\n        };\n\n        std::sort(eigenvalues, eigenvalues + 3);\n        return eigenvalues[1] - 0.5 * (eigenvalues[0] + eigenvalues[2]);\n    }\n}\n", "meta": {"hexsha": "17c8dbe19268ad864652c5a3721d5946ed8a0b80", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mdk/src/utils/Math.hpp", "max_stars_repo_name": "if-pan-zpp/mdk", "max_stars_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mdk/src/utils/Math.hpp", "max_issues_repo_name": "if-pan-zpp/mdk", "max_issues_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdk/src/utils/Math.hpp", "max_forks_repo_name": "if-pan-zpp/mdk", "max_forks_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T09:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T09:24:34.000Z", "avg_line_length": 31.4545454545, "max_line_length": 72, "alphanum_fraction": 0.4855491329, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6883992963676202}}
{"text": "/*\nCopyright 2012-2018 Tamas Bolner\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#include <cinttypes>\n#include <Eigen/Dense>\n#include \"SimplexSolver.h\"\n#include \"exception.h\"\n\nusing namespace Eigen;\n\n/**\n * Constructor\n * \n * @param int mode This can be one of these: SIMPLEX_MINIMIZE, SIMPLEX_MAXIMIZE\n * @param const VectorXd &objectiveFunction The coefficients of the objective function.\n * @param const MatrixXd &constraints Full matrix for the constraints. Contains also the righthand-side values.\n * @returns SimplexSolver\n */\nSimplexSolver::SimplexSolver(int mode, const VectorXd &objectiveFunction, const MatrixXd &constraints) {\n    int64_t constantColumn, temp;\n    this->foundSolution = false;\n    this->optimum = 0;\n    this->numberOfVariables = objectiveFunction.rows();\n    \n    /*\n        Validate input parameters\n    */\n    if (mode != SIMPLEX_MINIMIZE && mode != SIMPLEX_MAXIMIZE) {\n        throw FException(\"SimplexSolver: invalid value for the 'mode' parameter.\");\n    }\n\n    if (objectiveFunction.rows() < 1) {\n        throw FException(\"SimplexSolver: The coefficient vector of the objective function must contain at least one row.\");\n    }\n\n    if (constraints.rows() < 1) {\n        throw FException(\"SimplexSolver: The constraint matrix must contain at least one row.\");\n    }\n    \n    if (constraints.cols() != objectiveFunction.rows() + 1) {\n        throw FException(\"SimplexSolver: The constraint matrix has %d columns, but should have %d, because the coefficient vector of the objective function has %d rows.\",\n            constraints.cols(), objectiveFunction.rows() + 1, objectiveFunction.rows());\n    }\n    \n    for (int i = 0; i < this->numberOfVariables; i++) {\n        if (objectiveFunction(i) == 0) {\n            throw FException(\"SimplexSolver: One of the coefficients of the objective function is zero.\");\n        }\n    }\n\n    temp = constraints.cols() - 1;\n    for (int i = 0; i < constraints.rows(); i++) {\n        if (constraints(i, temp) < 0) {\n            throw FException(\"SimplexSolver: All righthand-side coefficients of the constraint matrix must be non-negative.\");\n        }\n    }\n    \n    /*\n        Build tableau\n    */\n    if (mode == SIMPLEX_MAXIMIZE) {\n        // Maximize\n        this->tableau.resize(constraints.rows() + 1, this->numberOfVariables + constraints.rows() + 1);\n\n        this->tableau <<    -objectiveFunction.transpose(),                   MatrixXd::Zero(1, constraints.rows() + 1),\n                            constraints.leftCols(this->numberOfVariables),    MatrixXd::Identity(constraints.rows(), constraints.rows()), constraints.rightCols(1);\n    } else {\n        // Minimize: construct the Dual problem\n        this->tableau.resize(this->numberOfVariables + 1, this->numberOfVariables + constraints.rows() + 1);\n\n        this->tableau <<    -constraints.rightCols(1).transpose(),                        MatrixXd::Zero(1, this->numberOfVariables + 1),\n                            constraints.leftCols(this->numberOfVariables).transpose(),    MatrixXd::Identity(this->numberOfVariables, this->numberOfVariables), objectiveFunction;\n    }\n    \n    /*\n        Simplex algorithm\n    */\n    if (mode == SIMPLEX_MAXIMIZE) {\n        // Maximize original problem\n        if (!this->simplexAlgorithm(this->numberOfVariables)) {\n            return;    // No solution\n        }\n    } else {\n        // Maximize the dual of the minimization problem\n        if (!this->simplexAlgorithm(constraints.rows())) {\n            return;    // No solution\n        }\n    }\n    \n    /*\n        Fetch solution\n    */\n    constantColumn = this->tableau.cols() - 1;\n    this->solution.resize(this->numberOfVariables);\n\n    if (mode == SIMPLEX_MAXIMIZE) {\n        // Maximize\n        for (int i = 0; i < this->numberOfVariables; i++) {\n            temp = this->getPivotRow(i);\n            \n            if (temp > 0) {\n                // Basic variable\n                this->solution(i) = this->tableau(temp, constantColumn);\n            } else {\n                // Non-basic variable\n                this->solution(i) = 0;\n            }\n        }\n        this->foundSolution = true;\n        this->optimum = this->tableau(0, constantColumn);\n    } else {\n        // Minimize\n        for (int i = 0; i < this->numberOfVariables; i++) {\n            this->solution(i) = this->tableau(0, constraints.rows() + i);\n        }\n        this->foundSolution = true;\n        this->optimum = this->tableau(0, constantColumn);\n    }\n}\n\n/**\n * Returns true if a solution has been found.\n * Return false otherwise.\n *\n * @returns boolean\n */\nbool SimplexSolver::hasSolution() {\n    return this->foundSolution;\n}\n\n/**\n * Returns the maximum/minimum value of\n * the objective function.\n * \n * @returns double\n */\ndouble SimplexSolver::getOptimum() {\n    return this->optimum;\n}\n\n/**\n * Returns a vector with the variable\n * values for the solution.\n *\n * return VectorXd\n */\nVectorXd SimplexSolver::getSolution() {\n    return this->solution;\n}\n\n/**\n * Searches for the pivot row in the given column, by calculating the ratios.\n * Tries to find smallest non-negative ratio.\n * Returns -1 if all possible pivots are 0 or if the ratios are negative.\n * Deals with cases like this:  0/negative < 0/positive\n * \n * @param int64_t column\n * @returns int64_t Returns the number of the pivot row, or -1 if found none.\n */\nint64_t SimplexSolver::findPivot_min(int64_t column) {\n    int64_t minIndex = -1;\n    int64_t constantColumn = this->tableau.cols() - 1;\n    double minRatio = 0;\n    double minConstant = 0;    // For the \"0/negative < 0/positive\" difference the constants have to be tracked also.\n    double ratio;\n    int64_t rowNum = this->tableau.rows();\n    \n    for (int i = 1; i < rowNum; i++) {\n        if (this->tableau(i, column) == 0) {\n            continue;\n        }\n\n        ratio = this->tableau(i, constantColumn) / this->tableau(i, column);\n        if (ratio < 0) {\n            //The ratio must be non-negative\n            continue;\n        }\n\n        if (minIndex == -1) {\n            // First pivot candidate\n            minIndex = i;\n            minRatio = ratio;\n            minConstant = this->tableau(i, constantColumn);\n        } else {\n            if (ratio == 0 && ratio == minRatio) {\n                // 0/negative < 0/positive\n                if (this->tableau(i, constantColumn) < minConstant) {\n                    minIndex = i;\n                    minRatio = ratio;\n                    minConstant = this->tableau(i, constantColumn);\n                }\n            } else if (ratio < minRatio) {\n                minIndex = i;\n                minRatio = ratio;\n                minConstant = this->tableau(i, constantColumn);\n            }\n        }\n    }\n\n    return minIndex;\n}\n\n/**\n * Iterates through the this->tableau matrix to solve the problem.\n * \n * @param int64_t variableNum The number of variables (dimensions). (different for the minimization problem)\n * @returns bool Returns true if a solution has been found. Returns false otherwise.\n */\nbool SimplexSolver::simplexAlgorithm(int64_t variableNum) {\n    MatrixXd::Index pivotColumn;\n    int64_t pivotRow;\n    \n    while (true) {\n        /*\n            Find pivot column, check for halt condition\n        */\n        this->tableau.row(0).leftCols(variableNum).minCoeff(&pivotColumn);\n        if (this->tableau(0, pivotColumn) >= 0) {\n            //Found no negative coefficient\n            break;\n        }\n        \n        /*\n            Find pivot row\n        */\n        pivotRow = this->findPivot_min(pivotColumn);\n        if (pivotRow == -1) {\n            //no solution\n            return false;\n        }\n        \n        /*\n            Do pivot operation\n        */\n        this->tableau.row(pivotRow) /= this->tableau(pivotRow, pivotColumn);\n        this->tableau(pivotRow, pivotColumn) = 1;    // For possible precision issues\n        for (int i = 0; i < this->tableau.rows(); i++) {\n            if (i == pivotRow) continue;\n            \n            this->tableau.row(i) -= this->tableau.row(pivotRow) * this->tableau(i, pivotColumn);\n            this->tableau(i, pivotColumn) = 0;    // For possible precision issues\n        }\n    }\n\n    return true;\n}\n\n/**\n * If the given column has only one coefficient with value 1 (except in topmost row), and all other\n * coefficients are zero, then returns the row of the non-zero value.\n * Otherwise return -1.\n * This method is used in the final step of maximization, when we read\n * the solution from the tableau.\n * \n * @param int64_t column\n * @returns int64_t\n */\nint64_t SimplexSolver::getPivotRow(int64_t column) {\n    int64_t one_row = -1;\n\n    for (int i = 1; i < this->tableau.rows(); i++) {\n        if (this->tableau(i, column) == 1) {\n            if (one_row >= 0) {\n                return -1;\n            } else {\n                one_row = i;\n                continue;\n            }\n        } else if (this->tableau(i, column) != 0) {\n            return -1;\n        }\n    }\n\n    return one_row;\n}\n", "meta": {"hexsha": "f480c026a61616c94615a6aa89e1ed4b963177dd", "size": 9453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithm/src/SimplexSolver.cpp", "max_stars_repo_name": "besha94/master-thesis", "max_stars_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-09-09T14:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T01:38:20.000Z", "max_issues_repo_path": "algorithm/src/SimplexSolver.cpp", "max_issues_repo_name": "besha94/master-thesis", "max_issues_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-27T09:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T13:32:56.000Z", "max_forks_repo_path": "algorithm/src/SimplexSolver.cpp", "max_forks_repo_name": "besha94/master-thesis", "max_forks_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-17T07:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:36:06.000Z", "avg_line_length": 32.7093425606, "max_line_length": 178, "alphanum_fraction": 0.5981169999, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385591833583}}
{"text": "#include <iostream>\r\n#include <vector>\r\n#include <Eigen/Eigen>\r\n#include <cmath>\r\n\r\n// #include <Python.h>\r\n// #include \"matplotlibcpp.h\"\r\n\r\n// namespace plt = matplotlibcpp;\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\n\r\nvoid ucitajTacke(vector<pair<float, float>> &tacke, int duzina) {\r\n\tpair<float, float> tacka;\r\n\tfor (int i = 0; i < duzina; i++) {\r\n\t\tcin >> tacka.first >> tacka.second;\r\n\t\ttacke.push_back(tacka);\r\n\t}\r\n}\r\n\r\n\r\nMatrixXf kreirajMatricuIx3(vector<pair<float, float>> &tacke) {\r\n\tMatrixXf Mat(tacke.size(), 3);\r\n\r\n\tint i = 0;\r\n\twhile (i < tacke.size()) {\r\n\t\tMat(i, 0) = tacke[i].first;\r\n\t\tMat(i, 1) = tacke[i].second;\r\n\t\tMat(i, 2) = 1;\r\n\t\ti++;\r\n\t}\r\n\t/*\r\n\t\t| t[0][p1] t[0][p2] 1 |\r\n\t\t| t[1][p1] t[1][p2] 1 |\r\n\t\t| t[2][p1] t[3][p2] 1 | \r\n\t\t| t[4][p1] t[4][p2] 1 |\r\n\t\t| ........\t\t\t  |\r\n\t*/\r\n\treturn Mat;\r\n}\r\n\r\n\r\n// Svaka tacka i njena slika iz vektora pravi ovu matricu 2 x 9\r\n// Za broj tacaka n, pravi matricu 2n x 9\r\nMatrixXf kreirajMatricu2nx9(vector<pair<float, float>> &pocetne, vector<pair<float, float>> &projektovane) {\r\n\t\r\n\tMatrixXf matrix2nx9(2 * pocetne.size(), 9);\r\n\t\r\n\tauto i = pocetne.begin();\r\n\tauto j = projektovane.begin();\r\n\tint k = 0;\r\n\t\r\n\twhile (i < pocetne.end()) {\r\n\t\tmatrix2nx9(k, 0) = 0;\r\n\t\tmatrix2nx9(k, 1) = 0;\r\n\t\tmatrix2nx9(k, 2) = 0;\r\n\t\tmatrix2nx9(k, 3) = -i->first;\r\n\t\tmatrix2nx9(k, 4) = -i->second;\r\n\t\tmatrix2nx9(k, 5) = -1;\r\n\t\tmatrix2nx9(k, 6) = j->second * i->first;\r\n\t\tmatrix2nx9(k, 7) = j->second * i->second;\r\n\t\tmatrix2nx9(k, 8) = j->second;\r\n\r\n\t\tmatrix2nx9(k + 1, 0) = i->first;\r\n\t\tmatrix2nx9(k + 1, 1) = i->second;\r\n\t\tmatrix2nx9(k + 1, 2) = 1;\r\n\t\tmatrix2nx9(k + 1, 3) = 0;\r\n\t\tmatrix2nx9(k + 1, 4) = 0;\r\n\t\tmatrix2nx9(k + 1, 5) = 0;\r\n\t\tmatrix2nx9(k + 1, 6) = -(j->first * i->first);\r\n\t\tmatrix2nx9(k + 1, 7) = -(j->first * i->second);\r\n\t\tmatrix2nx9(k + 1, 8) = -(j->first);\r\n\t\r\n\t\ti++; \r\n\t\tj++; \r\n\t\tk += 2;\r\n\t\t/// |  0\t 0    0  -b[0] -b[1] -1   (p[1]*b[0])   (p[1]*b[1])   p[1]\t|\t\tb - par pocetnih koordinata tacaka\r\n\t\t///\t| p[0]  p[1]  1   0     0     0  -(p[0]*b[0])  -(p[0]*b[1])  -p[0]\t|\t\tp - par projektovanih koordinata tacaka\r\n\t\t///\t|\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t\t/// |\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t\t/// |\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t}\r\n\r\n\treturn matrix2nx9;\r\n}\r\n\r\nMatrixXf resiP(MatrixXf Mat, Vector3f vec, int k) {\r\n\tVector3f stepen = ((Mat.transpose()).inverse()) * vec;\r\n\r\n\tint m = stepen.size();\r\n\tint n = k;\r\n\tMatrixXf P(n, m);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tP(i, j) = stepen(i) * Mat(i, j);\r\n\t\t}\r\n\t}\r\n\treturn P.transpose();\r\n}\r\n\r\n\r\nMatrixXf naivniAlgoritam(vector<pair<float, float>> pocetne, vector<pair<float, float>> projektovane) {\r\n\r\n\tfloat x, y;\r\n\r\n\tx = pocetne.back().first;\r\n\ty = pocetne.back().second;\r\n\tVector3f v(x, y, 1);\r\n\r\n\tx = projektovane.back().first;\r\n\ty = projektovane.back().second;\r\n\tVector3f vp(x, y, 1);\r\n\r\n\tpocetne.pop_back();\r\n\tprojektovane.pop_back();\r\n\r\n\tMatrixXf M = kreirajMatricuIx3(pocetne);\r\n\tMatrixXf Mp = kreirajMatricuIx3(projektovane);\r\n\r\n\tMatrixXf P1 = resiP(M, v, pocetne.size());\r\n\tMatrixXf P2 = resiP(Mp, vp, projektovane.size());\r\n\r\n\r\n\treturn P2 * P1.inverse();\r\n}\r\n\r\n\r\nMatrixXf DLTAlgoritam(vector<pair<float, float>> pocetne, vector<pair<float, float>> projektovane) {\r\n\r\n\tint br_tacaka = pocetne.size();\r\n\r\n\tMatrixXf matrix2nx9 = kreirajMatricu2nx9(pocetne, projektovane);\r\n\t// SVD razbija matricu na proizvode 3 matrice\r\n\tJacobiSVD<MatrixXf> Svd(matrix2nx9, ComputeFullV);\r\n\t\r\n\tMatrixXf Mat(2 * br_tacaka, 9);\r\n\tMatrixXf matrica_poslednje_kolone(3, 3);\r\n\tMat = Svd.matrixV();\t// Uzimamo 3. matricu V iz A = USV*\r\n\r\n\tint br_kolona = Mat.cols();\r\n\t// Uzimamo poslednju kolonu iz dekompozicije\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tmatrica_poslednje_kolone(i, j) = Mat(i * 3 + j, br_kolona - 1);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\treturn matrica_poslednje_kolone;\r\n}\r\n\r\nfloat izrSrednjeRastojanje(vector<pair<float, float>> tacke, pair<float, float> tezite) {\r\n\r\n\tfloat prosecno_rastojanje = 0;\r\n\tint n = tacke.size();\r\n\tfor (auto i = tacke.begin(); i < tacke.end(); i++) {\r\n\t\tfloat medju_rastojanje = sqrt(pow(i->first - tezite.first, 2) + pow(i->second - tezite.second, 2));\t// sqrt((x2-x1)^2 + (y2-y1)^2)\r\n\t\tprosecno_rastojanje += medju_rastojanje;\r\n\t}\r\n\r\n\treturn prosecno_rastojanje / n;\r\n}\r\n\r\nVector3f izrCentroidu(vector<pair<float, float>> tacke) {\r\n\r\n\tfloat tx = 0;\r\n\tfloat ty = 0;\r\n\tint n = tacke.size();\r\n\r\n\t// Sabiramo tezine koordinata\r\n\tfor (auto i = tacke.begin(); i < tacke.end(); i++) {\r\n\t\ttx += i->first;\r\n\t\tty += i->second;\r\n\t}\r\n\r\n\t// centroida = (tx/n, ty/n, 1)\r\n\t// homogene\r\n\tVector3f centroida;\r\n\tcentroida << tx / n, ty / n, 1;\r\n\r\n\t/*\r\n\t// Test: teziste\r\n\tcout << \"Teziste je : \" << centroida;\r\n\tcout << endl;\r\n\t*/\r\n\r\n\treturn centroida;\r\n}\r\n\r\nMatrixXf izrMatricuNormalizacije(vector<pair<float, float>> tacke) {\r\n\t/*\r\n\t1. Izracunati teziste sistema tacaka\r\n\t2. Translirati teziste u koordinatni pocetak (matrica T)\r\n\t3. Skalirati tacke tako da prosecna udaljenost tacke od koordinatnog pocetka bude sqrt(2) (matrica homotetije S)\r\n\t4. Matrica normalizacije je jednaka S * T\r\n\t*/\r\n\tVector3f vteziste = izrCentroidu(tacke);\r\n\tpair<float, float> t(vteziste(0), vteziste(1));\r\n\r\n\t// Matrica T: Translira teziste ovog skupa tacaka u O(0,0)\r\n\tMatrixXf T(3, 3);\r\n\tT << 1, 0, -vteziste(0),\r\n\t\t 0, 1, -vteziste(1),\r\n\t\t 0, 0,\t    1;\r\n\t// cout << T << endl;\r\n\tfloat srednje_rastojanje = izrSrednjeRastojanje(tacke, t);\r\n\tfloat k_skaliranja = sqrt(2) / srednje_rastojanje;\r\n\t// Matrica S: Skalira, tako da prosecno rastojanje tacaka od koordinatnog pocetka bude jednak sqrt(2)\r\n\tMatrixXf S(3, 3);\r\n\tS << k_skaliranja,\t\t0,\t\t\t0,\r\n\t\t\t0,\t\t\tk_skaliranja,\t0,\r\n\t\t\t0,\t\t\t\t0,\t\t\t1;\r\n\t// cout << S << endl;\r\n\t// Prvo transliramo pa skaliramo\r\n\treturn S * T;\r\n}\r\n\r\nMatrixXf nDLTAlgoritam(vector<pair<float, float>> pocetne, vector<pair<float, float>> projektovane) {\r\n\t/*\r\n\t1. Normalizuj tacke i slike:\tnx[i] = T * x[i], npx[i] = Tp * px[i]\r\n\t2. Uradi DLT na:\t\t\t\tnx[i] <-> npx[i]\r\n\t3. Denormalizuj resenje:\t\tH = Tp_inv * nH * T\r\n\t*/\r\n\t\r\n\tMatrixXf T = izrMatricuNormalizacije(pocetne);\r\n\tMatrixXf s_tacka = (T * kreirajMatricuIx3(pocetne).transpose()).transpose();\t// 3x3 * nx3.transp\r\n\t//\tcout << T << endl << endl << s_tacka << endl << endl;\r\n\r\n\tMatrixXf Tp = izrMatricuNormalizacije(projektovane);\r\n\tMatrixXf p_tacka = (Tp * kreirajMatricuIx3(projektovane).transpose()).transpose();\t// 3x3 * nx3.transp\r\n\t//\tcout << Tp << endl << endl << p_tacka << endl << endl;\r\n\r\n\r\n\tint n = pocetne.size();\r\n\tvector<pair<float, float>> s;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ts.push_back(pair<float, float>(s_tacka(i, 0), s_tacka(i, 1)));\r\n\t\t//\tcout << s_tacka(i, 0) << \" \" << s_tacka(i, 1) << endl;\r\n\t}\r\n\t\r\n\tvector<pair<float, float>> p;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tp.push_back(pair<float, float>(p_tacka(i, 0), p_tacka(i, 1)));\r\n\t\t//\tcout << p_tacka(i, 0) << \" \" << p_tacka(i, 1) << endl;\r\n\t}\r\n\r\n\t/*\r\n\t////\t---- Plot ----\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tplt::plot(s_tacka(i,0), s_tacka(i, 1), 'go');\r\n\t\tplt::plot(p_tacka(i, 0), p_tacka(i, 1), 'g+');\r\n\t}\r\n\t*/\r\n\r\n\tMatrixXf H = DLTAlgoritam(s, p);\r\n\treturn Tp.inverse() * H * T;\r\n}\r\n\r\nint main() {\r\n\tint opcija;\r\n\tcout << \"Izaberite opciju: \" << endl << \"1. Rucni unos koordinata\" << endl << \"2. Izabir koordinata pomocu misa\" << endl << \":::  \";\r\n\tcin >> opcija;\r\n\tif (opcija == 1) {\t\t\t\t// Rucni unos koordinata\r\n\t\t// Unos tacaka\r\n\t\tint br_tacaka;\r\n\t\tcout << \"Unesite broj korespodencija: \";\r\n\t\tcin >> br_tacaka;\r\n\t\tif (br_tacaka < 0) {\r\n\t\t\tcout << \"greska: Neispravan unos! (ocekivan broj veci od 0)\" << endl;\r\n\t\t\treturn -1;\r\n\t\t\r\n\t\t}\r\n\r\n\t\tvector<pair<float, float>> pocetne_tacke;\r\n\t\tvector<pair<float, float>> projektovane_tacke;\r\n\r\n\t\tcout << \"Ucitajte ulazne tacke kao parove x, y: \" << endl;\r\n\t\tucitajTacke(pocetne_tacke, br_tacaka);\r\n\t\tcout << \"Ucitajte izlazne tacke kao parove x, y: \" << endl;\r\n\t\tucitajTacke(projektovane_tacke, br_tacaka);\r\n\t\tcout << endl;\r\n\t\tif (br_tacaka == 4) {\r\n\t\t\tcout << \"--- Naivni algoritam: ---\" << endl;\r\n\t\t\tcout << naivniAlgoritam(pocetne_tacke, projektovane_tacke) << endl;\r\n\t\t\t\r\n\t\t\t/*\r\n\t\t\t////\t---- Plot ----\r\n\t\t\tfor (int i = 0; i < br_tacaka; i++) {\r\n\t\t\t\tplt::plot(pocetne_tacke[i].first, pocetne_tacke[i].second, 'ro');\r\n\t\t\t\tplt::plot(projektovane_tacke[i].first, projektovane_tacke[i].second, 'r+');\r\n\t\t\t}\r\n\t\t\t*/\r\n\r\n\t\t}\r\n\r\n\t\tcout << \"--- DLT algoritam: ---\" << endl;\r\n\t\tcout << DLTAlgoritam(pocetne_tacke, projektovane_tacke) << endl;\r\n\r\n\t\tcout << \"---Normalizovani DLT algoritam: ---\" << endl;\r\n\t\tcout << nDLTAlgoritam(pocetne_tacke, projektovane_tacke);\r\n\r\n\t\t//\tERROR: Error\tC1083\tCannot open include file : 'Python.h' : No such file or directory\r\n\t\t//\tVS ne cita Python header iako je ubacen u Additional Include Libraries, kao i postaveljen kao header u src dir\r\n\r\n\t\t/*\r\n\t\t////\t---- Plot ----\r\n\t\tplt::figure_size(1200, 780);\r\n\t\tplt::show();\r\n\t\t*/\r\n\r\n\t}\r\n\telse if (opcija == 2) {\t\t\t// Izabir koordinata pomocu misa\r\n\t\t\r\n\t\tcout << \"Nije zavrseno!\";\r\n\t\treturn 0;\r\n\t\t\r\n\t}\r\n\telse {\t\t\t\t\t\t\t// Greska\r\n\t\tcout << \"greska: Izabrana je nepostojeca opcija!\";\r\n\t\treturn -1;\r\n\t}\r\n\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "559331d43cb97c1754b1d42fc86cfbf9d0f65180", "size": 9054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_stars_repo_name": "lkora/MATF-PPGR", "max_stars_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-06T19:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T18:41:25.000Z", "max_issues_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_issues_repo_name": "lkora/MATF-PPGR", "max_issues_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_forks_repo_name": "lkora/MATF-PPGR", "max_forks_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_forks_repo_licenses": ["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.6036585366, "max_line_length": 134, "alphanum_fraction": 0.5863706649, "num_tokens": 3565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.688325886646285}}
{"text": "//  Copyright John Maddock 2007.\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// 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//[policy_eg_10\r\n\r\n/*`\r\n\r\nTo understand how the rounding policies for \r\nthe discrete distributions can be used, we'll\r\nuse the 50-sample binomial distribution with a \r\nsuccess fraction of 0.5 once again, and calculate\r\nall the possible quantiles at 0.05 and 0.95.\r\n\r\nBegin by including the needed headers:\r\n\r\n*/\r\n\r\n#include <iostream>\r\n#include <boost/math/distributions/binomial.hpp>\r\n\r\n/*`\r\n\r\nNext we'll bring the needed declarations into scope, and\r\ndefine distribution types for all the available rounding policies:\r\n\r\n*/\r\n\r\nusing namespace boost::math::policies;\r\nusing namespace boost::math;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_outwards> > > \r\n        binom_round_outwards;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_inwards> > > \r\n        binom_round_inwards;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_down> > > \r\n        binom_round_down;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_up> > > \r\n        binom_round_up;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_nearest> > > \r\n        binom_round_nearest;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<real> > > \r\n        binom_real_quantile;\r\n\r\n/*`\r\n\r\nNow let's set to work calling those quantiles:\r\n\r\n*/\r\n\r\nint main()\r\n{\r\n   std::cout << \r\n      \"Testing rounding policies for a 50 sample binomial distribution,\\n\"\r\n      \"with a success fraction of 0.5.\\n\\n\"\r\n      \"Lower quantiles are calculated at p = 0.05\\n\\n\"\r\n      \"Upper quantiles at p = 0.95.\\n\\n\";\r\n\r\n   std::cout << std::setw(25) << std::right\r\n      << \"Policy\"<< std::setw(18) << std::right \r\n      << \"Lower Quantile\" << std::setw(18) << std::right \r\n      << \"Upper Quantile\" << std::endl;\r\n   \r\n   // Test integer_round_outwards:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"integer_round_outwards\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_outwards(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_outwards(50, 0.5), 0.95) \r\n      << std::endl;\r\n   \r\n   // Test integer_round_inwards:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"integer_round_inwards\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_inwards(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_inwards(50, 0.5), 0.95) \r\n      << std::endl;\r\n   \r\n   // Test integer_round_down:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"integer_round_down\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_down(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_down(50, 0.5), 0.95) \r\n      << std::endl;\r\n   \r\n   // Test integer_round_up:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"integer_round_up\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_up(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_up(50, 0.5), 0.95) \r\n      << std::endl;\r\n   \r\n   // Test integer_round_nearest:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"integer_round_nearest\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_nearest(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_round_nearest(50, 0.5), 0.95) \r\n      << std::endl;\r\n   \r\n   // Test real:\r\n   std::cout << std::setw(25) << std::right\r\n      << \"real\"\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_real_quantile(50, 0.5), 0.05)\r\n      << std::setw(18) << std::right\r\n      << quantile(binom_real_quantile(50, 0.5), 0.95) \r\n      << std::endl;\r\n}\r\n\r\n/*`\r\n\r\nWhich produces the program output:\r\n\r\n[pre\r\nTesting rounding policies for a 50 sample binomial distribution,\r\nwith a success fraction of 0.5.\r\n\r\nLower quantiles are calculated at p = 0.05\r\n\r\nUpper quantiles at p = 0.95.\r\n\r\nTesting rounding policies for a 50 sample binomial distribution,\r\nwith a success fraction of 0.5.\r\n\r\nLower quantiles are calculated at p = 0.05\r\n\r\nUpper quantiles at p = 0.95.\r\n\r\n                   Policy    Lower Quantile    Upper Quantile\r\n   integer_round_outwards                18                31\r\n    integer_round_inwards                19                30\r\n       integer_round_down                18                30\r\n         integer_round_up                19                31\r\n    integer_round_nearest                19                30\r\n                     real            18.701            30.299\r\n]\r\n\r\n*/\r\n\r\n//] ends quickbook import\r\n\r\n", "meta": {"hexsha": "e1970cf2bcf9860ccc6b1d28f5f43c46b9320d8e", "size": 5157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_10.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/policy_eg_10.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/policy_eg_10.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": 29.9825581395, "max_line_length": 75, "alphanum_fraction": 0.5896839248, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6882335456325815}}
{"text": "#include <iostream>\n#include <Eigen\\Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\t{\n\t\tMatrixXf M1(3, 3); // column-major storage\n\t\tM1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\t\tcout << \"M1: \\n\" << M1 << endl;\n\t\tMap<RowVectorXf> v1(M1.data(), M1.size());\n\t\tcout << \"v1: \\n\" << v1 << endl;\n\n\t\tMatrix<float, Dynamic, Dynamic, RowMajor> M2(M1);\n\t\tcout << \"M2: \\n\" << M2 << endl;\n\t\tMap<RowVectorXf> v2(M2.data(), M2.size());\n\t\tcout << \"v2: \\n\" << v2 << endl;\n\t}\n\t{\n\t\tMatrixXf M1(2, 6);\n\t\tM1 << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;\n\t\tcout << \"M1: \\n\" << M1 << endl;\n\t\tMap<VectorXf> v1(M1.data(), M1.size());\n\t\tcout << \"v1: \\n\" << v1 << endl;\n\t\tMap<MatrixXf> M2(M1.data(), 6, 2);\n\t\tMap<VectorXf> v2(M2.data(), M2.size());\n\t\tcout << \"M2: \\n\" << M2 << endl;\n\t\tcout << \"v2: \\n\" << v2 << endl;\n\t}\n\t{\n\t\t// Slicing\n\t\tRowVectorXf v = RowVectorXf::LinSpaced(20, 0, 19);\n\t\tcout << \"Input: \\n\" << v << endl;\n\t\tMap<RowVectorXf, 0, InnerStride<2>> v2(v.data(), v.size() / 2);\n\t\tcout << \"Even: \\n\" << v2 << endl;\n\t}\n\t{\n\t\tMatrixXf M1 = MatrixXf::Random(3, 8);\n\t\tcout << \"Column major input: \\n\" << M1 << endl;\n\t\tMap<MatrixXf, 0, OuterStride<>> M2(M1.data(), M1.rows(), \n\t\t\t\t\t\t\t\t\t\t  (M1.cols() + 2) / 3, \n\t\t\t\t\t\t\t\t\t\t   OuterStride<>(M1.outerStride() * 3));\n\t\tcout << \"1 column over 3: \\n\" << M2 << endl;\n\n\t\ttypedef Matrix<float, Dynamic, Dynamic, RowMajor> RowMajorMatrixXf;\n\t\tRowMajorMatrixXf M3(M1);\n\t\tcout << \"Row major input:\" << endl << M3 << \"\\n\";\n\t\tMap<RowMajorMatrixXf, 0, Stride<Dynamic, 3> > M4(M3.data(), M3.rows(), (M3.cols() + 2) / 3,\n\t\t\tStride<Dynamic, 3>(M3.outerStride(), 3));\n\t\tcout << \"1 column over 3:\" << endl << M4 << \"\\n\";\n\t}\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "18f5694265c8a9edb1f346c22b3edc32af8990fc", "size": 1657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.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": 30.6851851852, "max_line_length": 93, "alphanum_fraction": 0.5383222692, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.6882335413361578}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"matrix_transpose.h\"\n\n#include <opencv2/opencv.hpp>\n#include \"common/pixel_benchmark.h\"\n#include <Eigen/Dense>\n\nusing std::cout;\nusing std::endl;\n\nstatic void matrix_transpose_u8_opencv(unsigned char* src, uint32_t height, uint32_t width, unsigned char* dst)\n{\n    cv::Mat src_mat(height, width, CV_8UC1, src);\n    cv::Mat dst_mat(width, height, CV_8UC1, dst);\n    dst_mat = src_mat.t();\n}\n\nstatic void matrix_transpose_u8_eigen(unsigned char* src, uint32_t height, uint32_t width, unsigned char* dst)\n{\n    Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eSrc(src, height, width);\n    Eigen::Map<Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eDst(dst, width, height);\n    eDst = eSrc.transpose();\n\n    // cout << \"eSrc:\" << endl << eSrc << endl;\n    // cout << \"eDst:\" << endl << eDst << endl;\n}\n\n\nstatic void matrix_transpose_f32_opencv(float* src, uint32_t height, uint32_t width, float* dst)\n{\n    cv::Mat src_mat(height, width, CV_32FC1, src);\n    cv::Mat dst_mat(width, height, CV_32FC1, dst);\n    dst_mat = src_mat.t();\n}\n\nstatic void matrix_transpose_f32_eigen(float* src, uint32_t height, uint32_t width, float* dst)\n{\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eSrc(src, height, width);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> eDst(dst, width, height);\n    eDst = eSrc.transpose();\n\n    // cout << \"eSrc:\" << endl << eSrc << endl;\n    // cout << \"eDst:\" << endl << eDst << endl;\n}\n\nstatic void prepare_big(uint32_t& height, uint32_t& width, cv::Mat& gray)\n{\n    cv::Mat image = cv::imread(\"river_bank2.png\");\n\n    // \u4e3a\u4e86\u68c0\u67e5\u8fb9\u754c\u662f\u5426\u5904\u7406\u6b63\u786e\uff0cresize\u5230\u4e0d\u662f4\u7684\u500d\u6570\u7684\u5c3a\u5bf8\n    // cv::Size dsize;\n    // dsize.height = image.rows - 1;\n    // dsize.width = image.cols - 1;\n    // cv::resize(image, image, dsize);\n\n    // cv::Size dsize;\n    // dsize.height = 1024;\n    // dsize.width = 1024;\n    // cv::resize(image, image, dsize);\n\n    cv::Size size = image.size();\n    printf(\"image info: height=%d, width=%d\\n\", size.height, size.width);\n\n    \n    gray = cv::Mat(size, CV_8UC1);\n    cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n    height = size.height;\n    width = size.width;\n}\n\nstatic void prepare_small(uint32_t& height, uint32_t& width, cv::Mat& gray)\n{\n    height = 3;\n    width = 5;\n    gray = cv::Mat(height, width, CV_8UC1);\n    \n    unsigned char* data = gray.data;\n    for (uint32_t i=0; i<height*width; i++) {\n        data[i] = i%256;\n    }\n}\n\nstatic void matrix_transpose_f32_test()\n{\n    uint32_t height;\n    uint32_t width;\n    cv::Mat gray;\n    prepare_big(height, width, gray);\n    //prepare_small(height, width, gray);\n\n    // u8 to float\n    gray.convertTo(gray, CV_32FC1);\n\n    float* src = (float*)gray.data;\n    double t_start, t_cost;\n    uint32_t len = height * width;\n    float* dst_naive = (float*)malloc(sizeof(float)*len);\n    float* dst_order_opt = (float*)malloc(sizeof(float)*len);\n    float* dst_opencv = (float*)malloc(sizeof(float)*len);\n    float* dst_eigen = (float*)malloc(sizeof(float)*len);\n    float* dst_partition4x4 = (float*)malloc(sizeof(float)*len);\n    float* dst_partition4x4_asimd = (float*)malloc(sizeof(float)*len);\n    float* dst_partition8x8 = (float*)malloc(sizeof(float)*len);\n    float* dst_partition8x8_asimd = (float*)malloc(sizeof(float)*len);\n\n    // naive\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_naive(src, height, width, dst_naive);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, naive,         time cost %.2lf ms\\n\", t_cost);\n\n    // order_opt\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_order_opt(src, height, width, dst_order_opt);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, order_opt,     time cost %.2lf ms\\n\", t_cost);\n\n    // opencv\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_opencv(src, height, width, dst_opencv);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, opencv,        time cost %.2lf ms\\n\", t_cost);\n\n    // eigen\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_eigen(src, height, width, dst_eigen);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, eigen,         time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 4x4\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_partition(src, height, width, dst_partition4x4, 4);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, partition4x4,  time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 4x4, asimd\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_partition_asimd(src, height, width, dst_partition4x4_asimd, 4);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, partition4x4 asimd, time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 8x8\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_partition(src, height, width, dst_partition8x8, 8);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, partition8x8,  time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 8x8, asimd\n    t_start = pixel_get_current_time();\n    matrix_transpose_f32_partition_asimd(src, height, width, dst_partition8x8_asimd, 8);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose f32, partition8x8 asimd, time cost %.2lf ms\\n\", t_cost);\n\n    int mis_order_opt = 0;\n    int mis_opencv = 0;\n    int mis_eigen = 0;\n    int mis_partition4x4 = 0;\n    int mis_partition4x4_asimd = 0;\n    int mis_partition8x8 = 0;\n    int mis_partition8x8_asimd = 0;\n\n    for (uint32_t i=0; i<len; i++) {\n        if (dst_naive[i]!=dst_order_opt[i]) {\n            mis_order_opt++;\n        }\n        if (dst_naive[i]!=dst_opencv[i]) {\n            mis_opencv++;\n        }\n        if (dst_naive[i]!=dst_eigen[i]) {\n            mis_eigen++;\n        }\n        if (dst_naive[i]!=dst_partition4x4[i]) {\n            mis_partition4x4++;\n            printf(\"dst_naive[%d]=%f, dst_partition4x4[%d]=%f\\n\", i, dst_naive[i], i, dst_partition4x4[i]);\n        }\n        if (dst_naive[i]!=dst_partition4x4_asimd[i]) {\n            mis_partition4x4_asimd++;\n        }\n        if (dst_naive[i]!=dst_partition8x8[i]) {\n            mis_partition8x8++;\n            printf(\"dst_naive[%d]=%f, dst_partition4x4[%d]=%f\\n\", i, dst_naive[i], i, dst_partition8x8[i]);\n        }\n        if (dst_naive[i]!=dst_partition8x8_asimd[i]) {\n            mis_partition8x8_asimd++;\n        }\n    }\n\n    printf(\"mis_order_opt=%d, mis_opencv=%d, mis_eigen=%d, \\nmis_partition4x4=%d, mis_partition4x4_asimd=%d, mis_partition8x8=%d, mis_partition8x8_asimd=%d\\n\",\n        mis_order_opt, mis_opencv, mis_eigen, mis_partition4x4, mis_partition4x4_asimd, mis_partition8x8, mis_partition8x8_asimd);\n}\n\nstatic void matrix_transpose_u8_test()\n{\n    uint32_t height;\n    uint32_t width;\n    cv::Mat gray;\n    prepare_big(height, width, gray);\n    //prepare_small(height, width, gray);\n\n    unsigned char* src = gray.data;\n    double t_start, t_cost;\n    uint32_t len = height * width;\n    unsigned char* dst_naive = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_order_opt = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_opencv = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_eigen = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_partition8x8 = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_partition8x8_asimd = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_partition16x16 = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    unsigned char* dst_partition16x16_asimd = (unsigned char*)malloc(sizeof(unsigned char)*len);\n    \n    // naive\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_naive(src, height, width, dst_naive);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, naive,         time cost %.2lf ms\\n\", t_cost);\n\n    // order_opt\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_order_opt(src, height, width, dst_order_opt);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, order_opt,     time cost %.2lf ms\\n\", t_cost);\n\n    // opencv\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_opencv(src, height, width, dst_opencv);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, opencv,        time cost %.2lf ms\\n\", t_cost);\n\n    // eigen\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_eigen(src, height, width, dst_eigen);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, eigen,         time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 8x8\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_partition(src, height, width, dst_partition8x8, 8);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, partition8x8,  time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 8x8, asimd\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_partition_asimd(src, height, width, dst_partition8x8_asimd, 8);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, partition8x8 asimd, time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 16x16\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_partition(src, height, width, dst_partition16x16, 16);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, partition16x16,  time cost %.2lf ms\\n\", t_cost);\n\n    // partition, 16x16, asimd\n    t_start = pixel_get_current_time();\n    matrix_transpose_u8_partition_asimd(src, height, width, dst_partition16x16_asimd, 16);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"matrix transpose u8, partition16x16 asimd, time cost %.2lf ms\\n\", t_cost);\n\n    int mis_order_opt = 0;\n    int mis_opencv = 0;\n    int mis_eigen = 0;\n    int mis_partition8x8 = 0;\n    int mis_partition8x8_asimd = 0;\n    int mis_partition16x16 = 0;\n    int mis_partition16x16_asimd = 0;\n\n    for (uint32_t i=0; i<len; i++) {\n        if (dst_naive[i]!=dst_order_opt[i]) {\n            mis_order_opt++;\n        }\n        if (dst_naive[i]!=dst_opencv[i]) {\n            mis_opencv++;\n        }\n        if (dst_naive[i]!=dst_eigen[i]) {\n            mis_eigen++;\n        }\n        if (dst_naive[i]!=dst_partition8x8[i]) {\n            mis_partition8x8++;\n        }\n        if (dst_naive[i]!=dst_partition8x8_asimd[i]) {\n            mis_partition8x8_asimd++;\n        }\n        if (dst_naive[i]!=dst_partition16x16[i]) {\n            mis_partition16x16++;\n        }\n        if (dst_naive[i]!=dst_partition16x16_asimd[i]) {\n            mis_partition16x16_asimd++;\n        }\n    }\n\n    printf(\"mis_order_opt=%d, mis_opencv=%d, mis_eigen=%d, \\nmis_partition8x8=%d, mis_partition8x8_asimd=%d, mis_partition16x16=%d, mis_partition16x16_asimd=%d\\n\",\n        mis_order_opt, mis_opencv, mis_eigen, mis_partition8x8, mis_partition8x8_asimd, mis_partition16x16, mis_partition16x16_asimd);\n}\n\nstatic void eigen_test()\n{\n    using namespace Eigen;\n\n    // Matrix3d Mat1;\n    // Mat1 << 1, 2, 3,\n    //     4, 6, 8,\n    //     7, 9, 9;\n\n    Eigen::Matrix <double, 3, 5, RowMajor> Mat1;\n    Mat1 << 1, 2, 3, 4, 5,\n            11, 12, 13, 14, 15,\n            21, 22, 23, 24, 25;\n\n    cout << \"Mat1=\\n\" << Mat1 << endl;\n    cout << \"Mat1\u8f6c\u7f6e\u77e9\u9635\uff1a\\n\" << Mat1.transpose() << endl;\n    // cout << \"Mat1\u4f34\u968f\u77e9\u9635\uff1a\\n\" << Mat1.adjoint() << endl;\n    // cout << \"Mat1\u9006\u77e9\u9635\uff1a\\n\" << Mat1.inverse() << endl;\n    // cout << \"Mat1\u884c\u5217\u5f0f\uff1a\\n\" << Mat1.determinant() << endl;\n    // SelfAdjointEigenSolver<Matrix3d>eigensover(Mat1);\n    // if (eigensover.info() != Success) abort();\n    // cout << \"\u7279\u5f81\u503c\uff1a\\n\" << eigensover.eigenvalues() << endl;\n    // cout << \"\u7279\u5f81\u5411\u91cf\uff1a\\n\" << eigensover.eigenvectors() << endl;\n}\n\nstatic void vtrn_f32_test()\n{\n    float data0[4] = {0, 1, 2, 3};\n    float data1[4] = {32, 33, 34, 35};\n    float data2[4] = {64, 65, 66, 67};\n    float data3[4] = {96, 97, 98, 99};\n\n    printf(\"before transpose32x4x4:\\n\");\n    printf(\"data0: %f %f %f %f\\n\", data0[0], data0[1], data0[2], data0[3]);\n    printf(\"data1: %f %f %f %f\\n\", data1[0], data1[1], data1[2], data1[3]);\n    printf(\"data2: %f %f %f %f\\n\", data2[0], data2[1], data2[2], data2[3]);\n    printf(\"data3: %f %f %f %f\\n\", data3[0], data3[1], data3[2], data3[3]);\n\n    transpose_f32_4x4_asimd(data0, data1, data2, data3);\n\n\n    printf(\"--------------------------------------------------\\n\");\n\n    printf(\"after transpose32x4x4:\\n\");\n    printf(\"data0: %f %f %f %f\\n\", data0[0], data0[1], data0[2], data0[3]);\n    printf(\"data1: %f %f %f %f\\n\", data1[0], data1[1], data1[2], data1[3]);\n    printf(\"data2: %f %f %f %f\\n\", data2[0], data2[1], data2[2], data2[3]);\n    printf(\"data3: %f %f %f %f\\n\", data3[0], data3[1], data3[2], data3[3]);\n}\n\nstatic void print_u8_array(unsigned char* data, uint32_t len) {\n    for (size_t i=0; i<len; i++) {\n        printf(\" %2d\", data[i]);\n    }\n    printf(\"\\n\");\n}\n\nstatic void vtrn_u8_test()\n{\n    unsigned char data0[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n    unsigned char data1[8] = {10, 11, 12, 13, 14, 15, 16, 17};\n    unsigned char data2[8] = {20, 21, 22, 23, 24, 25, 26, 27};\n    unsigned char data3[8] = {30, 31, 32, 33, 34, 35, 36, 37};\n    unsigned char data4[8] = {40, 41, 42, 43, 44, 45, 46, 47};\n    unsigned char data5[8] = {50, 51, 52, 53, 54, 55, 56, 57};\n    unsigned char data6[8] = {60, 61, 62, 63, 64, 65, 66, 67};\n    unsigned char data7[8] = {70, 71, 72, 73, 74, 75, 76, 77};\n\n    printf(\"before transpose_u8_8x8:\\n\");\n    printf(\"data0:\"); print_u8_array(data0, 8);\n    printf(\"data1:\"); print_u8_array(data1, 8);\n    printf(\"data2:\"); print_u8_array(data2, 8);\n    printf(\"data3:\"); print_u8_array(data3, 8);\n    printf(\"data4:\"); print_u8_array(data4, 8);\n    printf(\"data5:\"); print_u8_array(data5, 8);\n    printf(\"data6:\"); print_u8_array(data6, 8);\n    printf(\"data7:\"); print_u8_array(data7, 8);\n    \n    transpose_u8_8x8_asimd(data0, data1, data2, data3, data4, data5, data6, data7);\n\n    printf(\"--------------------------------------------------\\n\");\n\n    printf(\"after transpose_u8_8x8:\\n\");\n    printf(\"data0:\"); print_u8_array(data0, 8);\n    printf(\"data1:\"); print_u8_array(data1, 8);\n    printf(\"data2:\"); print_u8_array(data2, 8);\n    printf(\"data3:\"); print_u8_array(data3, 8);\n    printf(\"data4:\"); print_u8_array(data4, 8);\n    printf(\"data5:\"); print_u8_array(data5, 8);\n    printf(\"data6:\"); print_u8_array(data6, 8);\n    printf(\"data7:\"); print_u8_array(data7, 8);\n}\n\n\nint main() {\n\n    matrix_transpose_u8_test();\n    matrix_transpose_f32_test();\n    //eigen_test();\n    //vtrn_f32_test();\n    //vtrn_u8_test();\n\n    return 0;\n}", "meta": {"hexsha": "ca4b0983f7f2407b30dcbe61df413d2f15e0d31c", "size": 14901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/matrix_transpose_test.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/matrix_transpose_test.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/matrix_transpose_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": 37.0671641791, "max_line_length": 163, "alphanum_fraction": 0.6388832964, "num_tokens": 4746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6881230248778465}}
{"text": "//\n//  Polynomials.cpp\n//  kcalg\n//\n//  Created by knightc on 2019/7/15.\n//  Copyright \u00a9 2019 knightc. All rights reserved.\n//\n\n#include <stdio.h>\n#include <fstream>\n\n#include \"opentsb/math.h\"\n\n#include <NTL/ZZXFactoring.h> //\u5355 x \u7684\u6574\u6570\u7cfb\u6570\u7684\u591a\u9879\u5f0f\u56e0\u5f0f\u5206\u89e3\n#include <NTL/ZZX.h>  //\u5355 x \u7684 \u6574\u6570\u7cfb\u6570\u51fd\u6570/\u591a\u9879\u5f0f\n#include <NTL/ZZ_pX.h> //\u5355 x \u7684 \u6a21 p \u7684\u6574\u6570\u7cfb\u6570\u51fd\u6570/\u591a\u9879\u5f0f\n#include <NTL/ZZ_pXFactoring.h> //\u5355 x \u7684 \u6a21 p \u7684\u6574\u6570\u7cfb\u6570\u591a\u9879\u5f0f\u56e0\u5f0f\u5206\u89e3\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <NTL/GF2EX.h>\n#include <NTL/GF2EXFactoring.h>\n\nusing namespace NTL;\nusing namespace std;\n\n\nZZ y_polynomials(const ZZX &f,const ZZ xPoint) {\n   \n    ZZ m;\n    m= f.rep[0];\n    \n    for (long i=1 ; i < f.rep.length(); i++) {\n        if (!IsZero(f.rep[i])){\n        m+=power(xPoint, i) * f.rep[i];\n        }\n    }\n\n\n    return m;\n}\n\n\nvoid test_polynomials_main() {\n    \n    ZZX f;\n    \n    //f= a0+a1*x +a2*x^2 + a3 * x^3 +... + an * x^n\n    ifstream fin(\"/Users/kc/git/alg-test/kcalg/kcalg/poly.txt\");\n    fin >> f;\n   // cin >> f;//xcode\u7684\u8f93\u5165\u4f1a\u81ea\u52a8\u8865\u9f50\uff0c\u4f46\u662f\u952e\u76d8\u8f93\u5165\u9700\u8981\u624b\u52a8\u8f93\u5165\"\u3010 \"\u4e0e \" \u3011\"\n    \n    Vec< Pair<ZZX,long> > factors;//pair--\u7cfb\u6570\u3001\u6307\u6570\u7684\u5bf9\uff1bvec_pair_ZZX_long\n    ZZ c;\n    \n    factor(c, factors, f);//\u591a\u9879\u5f0f\u7684\u56e0\u5f0f\u5206\u89e3\n    \n //   cout << c << \"\\n\" << factors << \"\\n\";\n    \n    \n    //\u7279\u5b9a\u591a\u9879\u5f0f\u8f93\u51fa:\u5206\u5706\u591a\u9879\u5f0f\n    vec_ZZX phi(INIT_SIZE, 5);\n    for (long i = 1; i <= 5; i++) {\n        ZZX t;\n        t = 1;\n        \n        for (long j = 1; j <= i-1; j++)\n            if (i % j == 0)\n                t *= phi(j);\n        \n        phi(i) = (ZZX(INIT_MONO, i) - 1)/t;\n        \n     //   cout << phi(i) << \"\\n\";\n    }\n    \n\n    //\u591a\u9879\u5f0f\u8d4b\u503c\u793a\u4f8b\n    ZZX t1;\n    ZZ t11;\n    SetCoeff(t1, 4, 1);    //SetCoeff\u7684\u4f18\u70b9\uff1a\u81ea\u52a8\u5224\u65ad\u957f\u5ea6\u662f\u5426\u53d8\u5316\uff0c\u5373\u4fdd\u8bc1\u9886\u9879\u7cfb\u6570\u975e0\n    //SetCoeff(t1, 2560, 128); //\u5c1d\u8bd5\u4e00\u4e0b\uff0c\u5927\u6570\n    t1.rep[2] = 2; //ZZX.rep\u7684\u7f3a\u70b9\uff1a\u6539\u53d8\u7cfb\u6570\u7684\u540c\u65f6\u4e0d\u5224\u65ad\u957f\u5ea6\u662f\u5426\u53d8\u5316\n    SetCoeff(t1, 0, -1);\n    SetCoeff(t1, 5, 0); //\u9886\u9879\u7cfb\u6570\u8bbe\u4e3a 0 \u65f6\uff0c\u81ea\u52a8\u53bb\u6389\n  //  t1[4]=2; //\u4e5f\u53ef\u4ee5\u76f4\u63a5\u5b9a\u4e49\u7cfb\u6570\u503c\n    \n    cout << t1 << \"\\n\";\n    ZZ t12;\n    t12=12345678901234567890;//long \u6700\u5927\u53ea\u80fd 20 \u4f4d\uff0c\u4e0d\u80fd\u76f4\u63a5\u8f6c\u6362\u3002\u4f46\u662f ZZ \u7c7b\u578b\u53ef\u4ee5\u65e0\u7a77\u5927\n    t11=y_polynomials(t1, t12);\n    cout << t11 << endl;//t12=2 \u65f6\uff0c\u6b63\u786e\u503c\u4e3a 23\n    \n    ZZX t2;\n    t2.rep.SetLength(6); //\u5982\u679c\u6ca1\u6709SetCoeff\uff0c\u4f7f\u7528ZZX.rep\u4e4b\u524d\u5fc5\u987b\u5148\u7528\u8be5\u53e5\u521d\u59cb\u5316\u957f\u5ea6\n    t2.rep[4] = 1;\n    t2.rep[0] = -1;\n//    cout << t2 << \"\\n\"; //\u6ce8\uff1a\u6b64\u65f6\u9886\u9879\u7cfb\u6570\u662f0\uff0c\u5373\u7b2c 6 \u9879\u7684\u7cfb\u6570\u4e3a 0\n    \n    t2.normalize(); //\u4f5c\u7528\uff1a\u91cd\u65b0\u8c03\u6574\u957f\u5ea6\uff0c\u4ee5\u4fdd\u8bc1\u9886\u9879\u7cfb\u6570\u975e0\n //   cout << t2 << \"\\n\";\n    \n    //\u4e0b\u9762\u4e24\u79cd\u4ece\u591a\u9879\u5f0f\u4e2d\u53d6\u7cfb\u6570\u7684\u503c\u7684\u65b9\u6cd5\u7b49\u4ef7\n    if (t1.rep[4] == 1 and coeff(t1, 4) == 1 ){\n      //  cout << \"\u591a\u9879\u5f0f\u53d6\u503c\u6b63\u786e\" << \"\\n\";\n    }\n  //  cout << GCD(t1, t2) << endl;\n    \n    //mod p polynomials\n    ZZ p(65537);\n    ZZ_p::init(p);\n    \n    ZZ_pX f_px;\n    //cin >> f_px;\n    SetCoeff(f_px, 4, 2);\n    f_px.rep[3]=35;\n    SetCoeff(f_px,5,1);//\u9886\u9879\u7cfb\u6570\u5fc5\u987b\u4e3a 1\uff1aleadcoeff=1\n    \n    \n    vec_pair_ZZ_pX_long factors_px;\n    CanZass(factors_px, f_px);  // calls \"Cantor/Zassenhaus\" algorithm\n  //  cout << factors_px << \"\\n\" << f_px << \"\\n\";\n    \n    \n    // mod gf2e polynomials\n    GF2X P;\n    SetCoeff(P, 8, 1);\n    SetCoeff(P, 4, 1);\n    SetCoeff(P, 3, 1);\n    SetCoeff(P, 1, 1);\n    SetCoeff(P, 0, 1);\n    GF2E::init(P);\n    \n    GF2EX f_gf2ex;\n    SetCoeff(f_gf2ex, 0, 65537);\n   // f_gf2ex.rep[2]= 23;\n    \n    vec_pair_GF2EX_long factors_gf2ex;\n  //  CanZass(factors_gf2ex, f_gf2ex);\n   // cout << factors_gf2ex << \"\\n\" << f_gf2ex << \"\\n\";\n    \n}\n\n\n\n\n", "meta": {"hexsha": "6f94377d2329fb19b76ecb295d69379c57bd136c", "size": 3184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/math/Polynomials.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/math/Polynomials.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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": "kcalg/math/Polynomials.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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.9586206897, "max_line_length": 70, "alphanum_fraction": 0.5288944724, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230228824331}}
{"text": "#include <Eigen/CholmodSupport>\n#include <fstream>\n#include <iomanip>\n#include \"../../include/Optimization/LineSearch.h\"\n#include \"../../include/Optimization/NewtonDescent.h\"\n#include \"../../include/timer.h\"\n// #include \"SuiteSparse_config.h\"\n\nvoid OptSolver::newtonSolver(std::function<double(const Eigen::VectorXd&, Eigen::VectorXd*, Eigen::SparseMatrix<double>*, bool)> objFunc, std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> findMaxStep, Eigen::VectorXd& x0, int numIter, double gradTol, double xTol, double fTol, bool disPlayInfo, std::function<void(const Eigen::VectorXd&, double&, double&)> getNormFunc, std::string* savingFolder, std::function<void(Eigen::VectorXd&)> postProcess)\n{\n\tconst int DIM = x0.rows();\n    Eigen::VectorXd randomVec = x0;\n    randomVec.setRandom();\n    x0 += 1e-6 * randomVec;\n\tEigen::VectorXd grad = Eigen::VectorXd::Zero(DIM);\n\tEigen::SparseMatrix<double> hessian;\n\n\tEigen::VectorXd neggrad, delta_x;\n\tdouble maxStepSize = 1.0;\n\tdouble reg = 1e-8;\n\n\tbool isProj = true;\n    Timer<std::chrono::high_resolution_clock> totalTimer;\n    double totalAssemblingTime = 0;\n    double totalSolvingTime = 0;\n    double totalLineSearchTime = 0;\n\n    totalTimer.start();\n\tstd::ofstream optInfo;\n\tif (savingFolder)\n\t{\n\t\toptInfo = std::ofstream((*savingFolder) + \"_optInfo.txt\");\n\t\toptInfo << \"Newton solver with termination criterion: \" << std::endl;\n\t\tstd::cout << \"gradient tol: \" << gradTol << \", function update tol: \" << fTol << \", variable update tol: \" << xTol << \", maximum iteration: \" << numIter << std::endl << std::endl;\n\t}\n\tint i = 0;\n\tfor (; i < numIter; i++)\n\t{\n\t\tif(disPlayInfo)\n\t\t\tstd::cout << \"\\niter: \" << i << std::endl;\n\t\tif(savingFolder)\n\t\t\toptInfo << \"\\niter: \" << i << std::endl;\n        Timer<std::chrono::high_resolution_clock> localTimer;\n        localTimer.start();\n\t\tdouble f = objFunc(x0, &grad, &hessian, isProj);\n        localTimer.stop();\n        double localAssTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n        totalAssemblingTime += localAssTime;\n\n        localTimer.start();\n\t\tEigen::SparseMatrix<double> H = hessian;\n\t\tEigen::SparseMatrix<double> I(DIM, DIM);\n\t\tI.setIdentity();\n\t\tstd::cout << \"num of nonzeros: \" << H.nonZeros() << \", rows: \" << H.rows() << \", cols: \" << H.cols() << std::endl;\n\t\tEigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver(H);\n\n\t\t// Eigen::CholmodSimplicialLLT<Eigen::SparseMatrix<double> > solver(H);\n\n\n\t\twhile (solver.info() != Eigen::Success)\n\t\t{\n\t\t\tif (disPlayInfo)\n\t\t\t{\n\t\t\t\tif (isProj)\n\t\t\t\t\tstd::cout << \"some small perturb is needed to remove round-off error, current reg = \" << reg << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"Matrix is not positive definite, current reg = \" << reg << std::endl;\n\t\t\t}\n\t\t\t\t\n\t\t\tH = hessian + reg * I;\n\t\t\tsolver.compute(H);\n\t\t\treg = std::max(2 * reg, 1e-16);\n\n            if(reg > 1e4)\n            {\n                std::cout << \"reg is too large, use SPD hessian instead.\" << std::endl;\n                reg = 1e-6;\n                isProj = true;\n                f = objFunc(x0, &grad, &hessian, isProj);\n            }\n\t\t}\n\n\t\tneggrad = -grad;\n\t\tdelta_x = solver.solve(neggrad);\n\n        localTimer.stop();\n        double localSolvingTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n        totalSolvingTime += localSolvingTime;\n\n\n\t\tmaxStepSize = findMaxStep(x0, delta_x);\n\n        localTimer.start();\n\t\tdouble rate = LineSearch::backtrackingArmijo(x0, grad, delta_x, objFunc, maxStepSize);\n        localTimer.stop();\n        double localLinesearchTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n        totalLineSearchTime += localLinesearchTime;\n\n\n\t\tif (!isProj)\n\t\t{\n\t\t\treg *= 0.5;\n\t\t\treg = std::max(reg, 1e-16);\n\t\t}\n\t\t\n\t\tx0 = x0 + rate * delta_x;\n\n\t\tdouble fnew = objFunc(x0, &grad, NULL, isProj);\n\t\tif (disPlayInfo)\n\t\t{\n\t\t\tstd::cout << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\tstd::cout << \"f_old: \" << f << \", f_new: \" << fnew << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\tstd::cout << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew  << std::endl;\n\t\t\t}\n            std::cout << \"timing info (in total seconds): \" << std::endl;\n            std::cout << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \"  << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\t\t}\n\n        if(postProcess)\n        {\n            postProcess(x0);\n            if (disPlayInfo)\n            {\n                double tmpfnew = objFunc(x0, &grad, NULL, isProj);\n                std::cout << \"after post process, f_new: \" << tmpfnew << \", grad norm: \" << grad.norm() << std::endl;\n            }\n\n        }\n\n\t\tif (savingFolder)\n\t\t{\n\t\t\toptInfo << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\toptInfo << \"f_old: \" << f << \", f_new: \" << fnew << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\toptInfo << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew << std::endl;\n\t\t\t}\n\t\t\toptInfo << \"timing info (in total seconds): \" << std::endl;\n\t\t\toptInfo << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\t\tif (i % 100 == 0)\n\t\t\t{\n\t\t\t\tstd::string fileName = (*savingFolder) + \"intermediate.txt\";\n\t\t\t\tstd::ofstream ofs(fileName);\n\t\t\t\tif (ofs)\n\t\t\t\t{\n\t\t\t\t\tofs << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << x0 << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ((f - fnew) / f < 1e-5 || rate * delta_x.norm() < 1e-5 || grad.norm() < 1e-4 || std::abs(f) < 1e-4)\n\t\t{\n\t\t\tisProj = false;\n\t\t\t// double f = objFunc(x0, &grad, &hessian, isProj);\n\t\t\t// H = hessian;\n\t\t\t// solver.compute(hessian);\n\t\t\t// double tmpReg = 1e-8;\n\t\t\t// while (solver.info() != Eigen::Success)\n\t\t\t// {\t\n\t\t\t// \thessian = H + tmpReg * I;\n\t\t\t// \tsolver.compute(hessian);\n\t\t\t// \ttmpReg = std::max(2 * tmpReg, 1e-16);\n\t\t\t// }\n\t\t\t// if(tmpReg > 1e-5)\n\t\t\t// {\n\t\t\t// \tstd::cout << \"hessian is far away from PD, stick with PD hessian.\" << std::endl;\n\t\t\t// \tisProj = true;\n\t\t\t// }\n\n\t\t}\n\t\t\t\n\n\t\tif (rate < 1e-8)\n\t\t{\n\t\t\tstd::cout << \"terminate with small line search rate (<1e-8): L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (grad.norm() < gradTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t\t\n\t\tif (rate * delta_x.norm() < xTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with small variable change, gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t\t\n\t\tif (f - fnew < fTol)\n\t\t{ \n\t\t\tstd::cout << \"terminate with small energy change, gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (i >= numIter)\n\t\tstd::cout << \"terminate with reaching the maximum iteration, with gradient L2-norm = \" << grad.norm() << std::endl;\n\n    double f = objFunc(x0, &grad, &hessian, false);\n    Eigen::SparseMatrix<double> I(DIM, DIM), H = hessian;\n    I.setIdentity();\n    Eigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver(H);\n\n    reg = 1e-10;\n    while (solver.info() != Eigen::Success)\n    {\n        if (disPlayInfo)\n        {\n            if (isProj)\n                std::cout << \"some small perturb is needed to remove round-off error, current reg = \" << reg << std::endl;\n            else\n                std::cout << \"Matrix is not positive definite, current reg = \" << reg << std::endl;\n        }\n\n        H = hessian + reg * I;\n        solver.compute(H);\n        reg = std::max(2 * reg, 1e-16);\n    }\n    std::cout << \"end up with energy: \" << f << \", gradient: \" << grad.norm() << std::endl;\n    std::cout << \"mininal evalues of hessian is between: \" << reg / 2 << \", \" << reg << std::endl;\n\n    totalTimer.stop();\n    if(disPlayInfo)\n    {\n        std::cout << \"total time costed (s): \" << totalTimer.elapsed<std::chrono::milliseconds>() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \"  << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n    }\n\n\tif (savingFolder)\n\t{\n\t\toptInfo << \"total time costed (s): \" << totalTimer.elapsed<std::chrono::milliseconds>() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\tstd::string fileName = (*savingFolder) + \"final_res.txt\";\n\t\tstd::ofstream ofs(fileName);\n\t\tif (ofs)\n\t\t{\n\t\t\tofs << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << x0 << std::endl;\n\t\t}\n\n\n\t}\n\t\t\n}\n\n\n", "meta": {"hexsha": "c9b4eaaace0f39b1e532014bd6b75e712234e14d", "size": 9136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Optimization/NewtonDescent.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "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/Optimization/NewtonDescent.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "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/Optimization/NewtonDescent.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["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.2741312741, "max_line_length": 467, "alphanum_fraction": 0.5829684764, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230150608545}}
{"text": "#include \"PolyMesh/IOManager.h\"\n#include <Eigen/Sparse>\n#define pi 3.1415926\n\nusing namespace acamcad;\nusing namespace polymesh;\nusing namespace Eigen;\n\nvoid BarycentricCoordinates(PolyMesh* mesh)\n{\n\tint v_n = mesh->numVertices();\n\tstd::vector<int> inner_id(v_n);\n\tint iter;\n\tint boundary_num, inner_num;\n\n\tstd::vector<double> u(mesh->numVertices());\n\tstd::vector<double> v(mesh->numVertices());\n\n\titer = 0;\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\tinner_id[(*v_it)->index()] = iter;\n\t\t\titer++;\n\t\t}\n\t}\n\tinner_num = iter;\n\tboundary_num = v_n - iter;\n\n\tMHalfedge* first_heh;\n\tfor (HalfEdgeIter he_it = mesh->halfedge_begin(); he_it != mesh->halfedge_end(); ++he_it)\n\t{\n\t\tif (mesh->isBoundary(*he_it))\n\t\t{\n\t\t\tfirst_heh = *he_it;\n\t\t\tbreak;\n\t\t}\n\t}\n\tMHalfedge* iter_heh = first_heh->next();\n\titer = 0;\n\twhile (iter_heh != first_heh)\n\t{\n\t\tMVert* from_v = iter_heh->fromVertex();\n\t\tu[from_v->index()] = cos(double(2 * pi *iter / boundary_num));\n\t\tv[from_v->index()] = sin(double(2 * pi *iter / boundary_num));\n\t\titer_heh = iter_heh->next();\n\t\titer++;\n\t}\n\tu[first_heh->fromVertex()->index()] = cos(double(2 * pi *iter / boundary_num));\n\tv[first_heh->fromVertex()->index()] = sin(double(2 * pi *iter / boundary_num));\n\n\tSparseMatrix<double> weight(v_n, v_n);\n\tstd::vector<Triplet<double>> triplet;\n\n\tfor (FaceIter f_it = mesh->polyfaces_begin(); f_it != mesh->polyfaces_end(); ++f_it)\n\t{\n\t\tMHalfedge* heh = (*f_it)->halfEdge();\n\t\tMVert* v0 = heh->fromVertex();\n\t\tMVert* v1 = heh->toVertex();\n\t\tMHalfedge* next_heh = heh->next();\n\t\tMVert* v2 = next_heh->toVertex();\n\n\t\tdouble l2 = (v0->position() - v1->position()).norm();\n\t\tdouble l1 = (v0->position() - v2->position()).norm();\n\t\tdouble l0 = (v1->position() - v2->position()).norm();\n\n\t\tdouble angle = acos(dot(v2->position() - v0->position(), v1->position() - v0->position())/(l1*l2));\n\t\ttriplet.push_back(Triplet<double>(v0->index(), v1->index(), tan(angle*0.5) / l2));\n\t\ttriplet.push_back(Triplet<double>(v0->index(), v2->index(), tan(angle*0.5) / l1));\n\n\t\tangle = acos(dot(v0->position() - v1->position(), v2->position() - v1->position())/(l2*l0));\n\t\ttriplet.push_back(Triplet<double>(v1->index(), v0->index(), tan(angle*0.5) / l2));\n\t\ttriplet.push_back(Triplet<double>(v1->index(), v2->index(), tan(angle*0.5) / l0));\n\n\t\tangle = acos(dot(v0->position() - v2->position(), v1->position() - v2->position())/(l0*l1));\n\t\ttriplet.push_back(Triplet<double>(v2->index(), v0->index(), tan(angle*0.5) / l1));\n\t\ttriplet.push_back(Triplet<double>(v2->index(), v1->index(), tan(angle*0.5) / l0));\n\t}\n\tweight.setFromTriplets(triplet.begin(), triplet.end());\n\n\tSparseMatrix<double> inner(inner_num, inner_num);\n\tVectorXd ub(inner_num), vb(inner_num);\n\n\ttriplet.clear();\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\tdouble tempu = 0;\n\t\t\tdouble tempv = 0;\n\t\t\tfor (VertexVertexIter vv_it = mesh->vv_iter(*v_it); vv_it.isValid(); ++vv_it)\n\t\t\t{\n\t\t\t\tif (mesh->isBoundary(*vv_it))\n\t\t\t\t{\n\t\t\t\t\ttempu += u[(*vv_it)->index()] * weight.coeff((*v_it)->index(), (*vv_it)->index());\n\t\t\t\t\ttempv += v[(*vv_it)->index()] * weight.coeff((*v_it)->index(), (*vv_it)->index());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttriplet.push_back(Triplet<double>(inner_id[(*v_it)->index()], inner_id[(*vv_it)->index()], -weight.coeff((*v_it)->index(), (*vv_it)->index())));\n\t\t\t\t}\n\t\t\t\ttriplet.push_back(Triplet<double>(inner_id[(*v_it)->index()], inner_id[(*v_it)->index()], weight.coeff((*v_it)->index(), (*vv_it)->index())));\n\t\t\t}\n\t\t\tub[inner_id[(*v_it)->index()]] = tempu;\n\t\t\tvb[inner_id[(*v_it)->index()]] = tempv;\n\t\t}\n\t}\n\tinner.setFromTriplets(triplet.begin(), triplet.end());\n\tSparseLU<SparseMatrix<double>> solver;\n\tsolver.analyzePattern(inner);\n\tsolver.factorize(inner);\n\tVectorXd result_u = solver.solve(ub);\n\tVectorXd result_v = solver.solve(vb);\n\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\t(*v_it)->setPosition(result_u[inner_id[(*v_it)->index()]], result_v[inner_id[(*v_it)->index()]], 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t(*v_it)->setPosition(u[(*v_it)->index()], v[(*v_it)->index()], 0);\n\t\t}\n\t}\n}\n\n\nint main(int argc, const char **argv)\n{\n\tif (argc != 2)\n\t{\n\t\tstd::cout << \"========== Hw7 Usage  ==========\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"blablabla.exe\ttest.obj\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"=================================================\\n\";\n        return 0;\n\t}\n\tstd::string mesh_path = argv[1];\n\tPolyMesh* mesh = new PolyMesh();\n\tloadMesh(mesh_path, mesh);\n\tBarycentricCoordinates(mesh);\n\twriteMesh(\"result_\" + mesh_path, mesh);\n    return 0;\n}", "meta": {"hexsha": "ebff0af19973c613082bf4ed4ba3e45bfea83bc7", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/hw7/main.cpp", "max_stars_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_stars_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-03-08T02:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:09:20.000Z", "max_issues_repo_path": "code/src/hw7/main.cpp", "max_issues_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_issues_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/hw7/main.cpp", "max_forks_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_forks_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_forks_repo_licenses": ["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.0816326531, "max_line_length": 149, "alphanum_fraction": 0.6212892282, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6880861308195402}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"diophantienne.h\"\n\nBOOST_AUTO_TEST_SUITE(test_diophantienne)\n\n    BOOST_AUTO_TEST_CASE(pqa1) {\n        auto resultat = diophantienne::PQa(11, 108, 13);\n        std::vector<long long> fractions{0, 7, 2, 1, 1, 6, 1, 1};\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.first.begin(), resultat.first.end(), fractions.begin(), fractions.end());\n        BOOST_CHECK_EQUAL(resultat.second, 5);\n    }\n\n    BOOST_AUTO_TEST_CASE(pqa2) {\n        auto resultat = diophantienne::PQa(0, 1, 13);\n        std::vector<long long> fractions{3, 1, 1, 1, 1, 6};\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.first.begin(), resultat.first.end(), fractions.begin(), fractions.end());\n        BOOST_CHECK_EQUAL(resultat.second, 5);\n    }\n\n    BOOST_AUTO_TEST_CASE(pell1_min) {\n        BOOST_CHECK_EQUAL(diophantienne::pell1_min(13, 1), std::make_pair(649, 180));\n        BOOST_CHECK_EQUAL(diophantienne::pell1_min(13, -1), std::make_pair(18, 5));\n    }\n\n    BOOST_AUTO_TEST_CASE(pell4_min) {\n        BOOST_CHECK_EQUAL(diophantienne::pell4_min(13, 1), std::make_pair(11, 3));\n        BOOST_CHECK_EQUAL(diophantienne::pell4_min(13, -1), std::make_pair(3, 1));\n    }\n\n    BOOST_AUTO_TEST_CASE(pell1_1) {\n        std::vector<std::pair<long long, long long>> resultat;\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(649, 180),\n                std::make_pair(842401, 233640)\n        };\n        auto callback = [&resultat, &solution](long long x, long long y) {\n            resultat.push_back(std::make_pair(x, y));\n            return resultat.size() != solution.size();\n        };\n\n        diophantienne::pell1<long long>(13, 1, callback);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell1_2) {\n        std::vector<std::pair<long long, long long>> resultat;\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(18, 5),\n                std::make_pair(23382, 6485),\n                std::make_pair(30349818, 8417525)\n        };\n        auto callback = [&resultat, &solution](long long x, long long y) {\n            resultat.push_back(std::make_pair(x, y));\n            return resultat.size() != solution.size();\n        };\n\n        diophantienne::pell1<long long>(13, -1, callback);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell4_1) {\n        std::vector<std::pair<long long, long long>> resultat;\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(649, 180),\n                std::make_pair(421200, 116820)\n        };\n        auto callback = [&resultat, &solution](long long x, long long y) {\n            resultat.push_back(std::make_pair(x, y));\n            return resultat.size() != solution.size();\n        };\n\n        diophantienne::pell4<long long>(13, 1, callback);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell4_2) {\n        std::vector<std::pair<long long, long long>> resultat;\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(18, 5),\n                std::make_pair(5841, 1620),\n                std::make_pair(1895386, 525685)\n        };\n        auto callback = [&resultat, &solution](long long x, long long y) {\n            resultat.push_back(std::make_pair(x, y));\n            return resultat.size() != solution.size();\n        };\n\n        diophantienne::pell4<long long>(13, -1, callback);\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_funds_bf1) {\n        auto resultat = diophantienne::pell_funds_bf<long long>(13, 108);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(11, 1),\n                std::make_pair(-11, 1),\n                std::make_pair(15, 3),\n                std::make_pair(-15, 3),\n                std::make_pair(24, 6),\n                std::make_pair(-24, 6),\n                std::make_pair(41, 11),\n                std::make_pair(-41, 11),\n                std::make_pair(80, 22),\n                std::make_pair(-80, 22),\n                std::make_pair(141, 39),\n                std::make_pair(-141, 39)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_funds_bf2) {\n        auto resultat = diophantienne::pell_funds_bf<long long>(157, 12);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(13, 1),\n                std::make_pair(-13, 1),\n                std::make_pair(10663, 851),\n                std::make_pair(-10663, 851),\n                std::make_pair(579160, 46222),\n                std::make_pair(-579160, 46222)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_funds_bf3) {\n        auto resultat = diophantienne::pell_funds_bf<long long>(13, 27);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(12, 3),\n                std::make_pair(-12, 3),\n                std::make_pair(40, 11),\n                std::make_pair(-40, 11)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_bf1) {\n        auto resultat = diophantienne::pell_bf<long long>(13, 108, 1000);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(11, 1),\n                std::make_pair(15, 3),\n                std::make_pair(24, 6),\n                std::make_pair(41, 11),\n                std::make_pair(80, 22),\n                std::make_pair(141, 39),\n                std::make_pair(249, 69),\n                std::make_pair(440, 122),\n                std::make_pair(869, 241)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_bf2) {\n        auto resultat = diophantienne::pell_bf<long long>(157, 12, 100000000);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(13, 1),\n                std::make_pair(10663, 851),\n                std::make_pair(579160, 46222)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(pell_bf3) {\n        auto resultat = diophantienne::pell_bf<long long>(13, 27, 1000);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(12, 3),\n                std::make_pair(40, 11),\n                std::make_pair(220, 61),\n                std::make_pair(768, 213)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(quad_s) {\n        auto resultat = diophantienne::quad_s<long long>(8, 9, 72, 1000);\n        std::vector<std::pair<long long, long long>> solution{\n                std::make_pair(3, 0),\n                std::make_pair(9, 8),\n                std::make_pair(51, 48),\n                std::make_pair(297, 280)\n        };\n        BOOST_CHECK_EQUAL_COLLECTIONS(resultat.begin(), resultat.end(), solution.begin(), solution.end());\n    }\n\n    BOOST_AUTO_TEST_CASE(iterateur_diophantienne1) {\n        // 10x + 84y + 16 = 0\n        long long int A = 10, B = 84, C = 16;\n        size_t compteur = 0;\n        for (auto s : diophantienne::equation_lineaire(A, B, C)) {\n            ++compteur;\n            if (compteur > 10) {\n                break;\n            }\n            BOOST_CHECK_EQUAL(A * s.first + B * s.second + C, 0);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(iterateur_diophantienne2) {\n        // 10x + 84y - 16 = 0\n        long long int A = 10, B = 84, C = -16;\n        size_t compteur = 0;\n        for (auto s : diophantienne::equation_lineaire(A, B, C)) {\n            ++compteur;\n            if (compteur > 10) {\n                break;\n            }\n            BOOST_CHECK_EQUAL(A * s.first + B * s.second + C, 0);\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1a54967b17e8bce2478ed2fbaecae51083f8a67e", "size": 8452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/diophantienne.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "tests/diophantienne.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/diophantienne.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": 40.0568720379, "max_line_length": 120, "alphanum_fraction": 0.5677946048, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336302, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.688017030474254}}
{"text": "using namespace std;\n#include <cassert>\n#include <string> \n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <random>\n#include <boost/random/discrete_distribution.hpp>\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n\nusing namespace Eigen;\n\nclass RNN\n{\n    private: \n        struct loss_result\n        {\n            /* Structure for recording the result of the loss method */\n            double loss;\n            MatrixXd dWxh;\n            MatrixXd dWhh;\n            MatrixXd dWhy;\n            MatrixXd dbh;\n            MatrixXd dby;\n            MatrixXd hs;   \n        }; \n\n        vector <string> data;                                           //vector that holds the corpus\n        map <string, int> char_id;                                      //map holds corpus unique char and their id\n        map <int, string> id_char;                                      //map id to unique char\n\n        int hiddens;                                                    //hidden layers number\n        int sequence_length;                                            //sequence length\n        int data_size;                                                  //length of corpus\n        int vocab_size;                                                 //vocabulary size for the network\n\n        MatrixXd W_XH;                                                  //Weights from Input to Hiddens\n        MatrixXd W_HH;                                                  //Weights from Hidden to Hidden\n        MatrixXd W_HY;                                                  //Weights from Hidden to Output\n        MatrixXd BH;                                                    //Bias of Hiddens\n        MatrixXd BY;                                                    //Bias of Outputs\n\n        double check (const double min, const double max, double &target)\n        {\n            /* Sub-method to use for Clip Method */\n            if (target > max)\n            {\n                return max;\n            }\n            else if (target < min)\n            {\n                return min;\n            }\n            return target;\n        }\n\n        void clip(const double min, const double max, MatrixXd &target)\n        {\n            /* Clip elements' value inside the Matrix to leave them remain in between min and max */\n            for (int r = 0; r < target.rows(); r ++)\n            {\n                for (auto item = target.row(r).data(); item < target.row(r).data() + target.size(); item += target.outerStride()) \n                {\n                    *item = check(min, max, *item);\n                }   \n            }\n        }\n\n        const vector <double> ravel(MatrixXd &target)\n        {\n            /* Generate a 1 by M Vector; Keep all values of target in 1D vector */\n            vector <double> p;\n            \n            for (int r = 0; r < target.rows(); r ++)\n            {\n                for (auto item = target.row(r).data(); item < target.row(r).data() + target.size(); item += target.outerStride())\n                {\n                    p.push_back(*item);\n                }\n            }\n\n            return p;\n        }\n\n        const int choice (vector <double> &p)\n        {\n            /* Random Choice Method*/\n            random_device rng;                                                  //set rng\n            mt19937 gen(rng());                                                 //use another generator to generate upon rng\n            boost::random::discrete_distribution<> dist (p.begin(), p.end());   //apply discrete distrib upon probabilities vector\n\n            int randomNumber = dist(gen);                                       //set random ID & return\n            return randomNumber;\n        }\n\n        loss_result* loss(const vector <int> &inputs, const vector <int> &targets, const MatrixXd &hprev)\n        {\n            /* Inputs and Targets are list of IDs \n               Hprev holds a matrix of initial Hidden States x 1\n               Return Loss Result Structure\n            */\n\n            map <int, MatrixXd > xs, hs, ys, ps;     //map that holds iteration -> Matrix correspond to Inputs, Hiddens, Outputs, Probs\n            MatrixXd original (hprev);               //Make a copy of hprev\n            hs[-1] = original;                       //Set -1 as original; this is for the 1st iteration; hs[i - 1]\n            double loss = 0.0;                       //Initialize loss\n\n            //Forward Propagation\n            for (int i = 0; i < inputs.size(); i ++)\n            {\n                xs[i] = MatrixXd::Zero(vocab_size, 1);             //Initalizes first X\n                xs[i].row(inputs[i]).array() = 1;                  //encode X in 1 of K representation \n                \n                //Apply Activation Function; Tanh(X * Weights of X->H + Weights of Hidden * Hidden States + Bias Hidden)\n                hs[i] = ((W_XH * xs[i]) + (W_HH * hs[i - 1]) + BH).unaryExpr<double(*)(double)>(&tanh);\n                \n                //Set Outputs; Weights of Y * Hidden States + Bias Y\n                ys[i] = (W_HY * hs[i]) + BY;\n                \n                //Set Exp(current Y)\n                MatrixXd ys_exp = ys[i].unaryExpr<double(*)(double)>(&exp);\n\n                //Set Probabilities of the next Y\n                ps[i] = ys_exp / ys_exp.sum();\n\n                //Set new loss \n                loss += -log(ps[i].coeff(targets[i], 0));\n            }\n\n            //Gradients\n            MatrixXd dWxh = MatrixXd::Zero(W_XH.rows(), W_XH.cols());\n            MatrixXd dWhy = MatrixXd::Zero(W_HY.rows(), W_HY.cols());\n            MatrixXd dWhh = MatrixXd::Zero(W_HH.rows(), W_HH.cols());\n            MatrixXd dbh = MatrixXd::Zero(BH.rows(), BH.cols());\n            MatrixXd dby = MatrixXd::Zero(BY.rows(), BY.cols());\n            MatrixXd dh_next = MatrixXd::Zero(hs[0].rows(), hs[0].cols());\n            \n            //Backpropagation: Computing Gradient \n            for (int i = inputs.size() - 1; i >= 0; i --)\n            { \n                //copy current probabilities\n                MatrixXd dy(ps[i]);    \n                //back prop into y \n                dy.row(targets[i]) = dy.row(targets[i]).array() - 1.0;           \n                \n                //grab gradients of weights and biases of y\n                dWhy += (dy * hs[i].transpose());\n                dby.noalias() += dy;\n\n                //back prop into h\n                MatrixXd dh = ((W_HY.transpose() * dy) + dh_next);\n                //back prop into tanh nonlinear\n                MatrixXd dhraw = ((1 - (hs[i].array() * hs[i].array())).array() * dh.array()); \n\n                //set gradients\n                dbh.noalias() += dhraw;\n                dWxh += (dhraw * xs[i].transpose());\n                dWhh += (dhraw * hs[i - 1].transpose());\n                dh_next = (W_HH.transpose() * dhraw);\n            }\n            \n            /* Clip values in matrices to prevent gradient explosion */\n            clip(-10, 10, dWxh);\n            clip(-10, 10, dWhh);\n            clip(-10, 10, dWhy);\n            clip(-10, 10, dbh);\n            clip(-10, 10, dby);\n            \n            /* Allocate necessary items into newly created Structure */\n            loss_result* item = new loss_result();\n            item->loss = loss; item->dbh = dbh; item->dby = dby;\n            item->dWhh = dWhh; item->dWhy = dWhy; item->dWxh = dWxh;\n            item->hs = hs[inputs.size() - 1];\n\n            return item;\n        }\n\n        const vector <int> sample(const MatrixXd &h_prev, const int &seedID, const int &m)\n        {\n            /* Generate a Sample of Char ID for Text Generation */\n            MatrixXd x = MatrixXd::Zero(vocab_size, 1);                      //generate a new bias called x\n            x.row(seedID).array() = 1.0;                                     //set the entry at seedID equals to 1\n            vector <int> samples;                                            //new samples of char IDs\n\n            for (int i = 0; i < m; i ++)\n            { \n                MatrixXd h = (W_XH * x) + (W_HH * h_prev) + BH;             //current Hypothesis\n                h = h.unaryExpr<double(*)(double)>(&tanh);                  //apply tanh\n\n                MatrixXd y = W_HY * h + BY;                                 //Produce Y\n                MatrixXd exp_y = y.unaryExpr<double(*)(double)>(&exp);      //Apply Exp\n\n                MatrixXd p = exp_y / exp_y.sum();                           //Create Probabilities \n                vector <double> probabilities = ravel(p);                   //Produce 1 by M vector\n\n                int ix = choice(probabilities);                             //Select a choice based on probabilities\n\n                x = MatrixXd::Zero(vocab_size, 1);                          //Reset X or Inputs\n\n                x.row(ix).array() = 1.0;                                    //Set all elements in row SeedID equals to 1.0 again\n                samples.push_back(ix);                                      //Push ID onto samples vector\n            }\n\n            return samples;\n        }\n        \n        const vector <int> getID(const int min, const int max)\n        {\n            // Get a list of characters based on the range of p and sequence length \n            vector <int> item;\n      \n            for (int c = min; c < max; c ++)\n            {\n                item.push_back(char_id[data[c]]);\n            }\n            \n            return item;\n        }\n\n        const string genText(const vector <int> samples)\n        {\n            /* Generate Text With Parallelism Enabled */\n            string output = \"\";\n\n            #pragma omp declare reduction (merge : string : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))\n            #pragma omp parallel for reduction (merge : output)\n            for (int i = 0; i < samples.size(); i++)\n            {\n                #pragma omp critical\n                output += id_char[samples[i]];\n            }\n\n            return output;\n        }\n\n    public: \n        RNN(const int &hidden_size, const int &seq_length)\n        {\n            hiddens = hidden_size;\n            sequence_length = seq_length;\n        }  \n\n        void load(const string filename)\n        {\n            /* Load File and Enumerate through each character in the text file; get unique char and assign their ID */\n            ifstream file(filename);    // grab file\n            string line;                // a string for holding  current line\n            int count = 0;              // count variable\n            vector <string> corpus;\n\n            /* Grab all lines in the text file */\n            while(getline(file, line))\n            {\n                corpus.push_back(line);\n            }\n\n            file.close();               // close the file\n\n            //set next line into the map and allocate the same ID into both map; then increment the ID\n            char_id[\"\\n\"] = count; id_char[count] = \"\\n\"; count ++; \n            char_id[\" \"] = count; id_char[count] = \" \"; count ++;\n\n            //Loop through the corpus\n            //Find Unique characters and allocate it with a unique ID\n            //Also, append each character in the line onto the data vector for RNN's feeding\n            for (auto &line: corpus)\n            {\n                int line_size = line.size();\n                if (line_size > 0)\n                {\n                    int c = 0;\n                    istringstream word(line);\n                    for (string current; word >> current;)\n                    {\n                        data.push_back(current);\n                        if (c < line_size)\n                        {\n                            data.push_back(\" \");\n                        }\n\n                        if (char_id.find(current) == char_id.end())\n                        {\n                            char_id[current] = count;\n                            id_char[count] = current;\n                            count ++;\n                        }\n                        c ++;\n                    }\n\n                    data.push_back(\"\\n\");\n                }\n                else\n                {\n                    data.push_back(\"\\n\");\n                }\n            }\n\n            data_size = data.size();                //set data size\n            vocab_size = char_id.size();            //set vocab size\n            \n            /* Set Weights and Biases */\n            W_XH = MatrixXd::Random(hiddens, vocab_size) * 0.01;\n            W_HH = MatrixXd::Random(hiddens, hiddens) * 0.01;\n            W_HY = MatrixXd::Random(vocab_size, hiddens) * 0.01;\n            BH = MatrixXd::Zero(hiddens, 1);\n            BY = MatrixXd::Zero(vocab_size, 1);\n\n            cout << \"Create Topology: Done!\" << endl;\n        }\n\n        const void learn()\n        {\n            /* Learn Method */\n\n            //Initalizes memory variables for Adam Gradient Descent aka AdaGrad\n            MatrixXd mWXH = MatrixXd::Zero(W_XH.rows(), W_XH.cols());\n            MatrixXd mWHH = MatrixXd::Zero(W_HH.rows(), W_HH.cols());\n            MatrixXd mWHY = MatrixXd::Zero(W_HY.rows(), W_HY.cols());\n            MatrixXd mBH = MatrixXd::Zero(BH.rows(), BH.cols());\n            MatrixXd mBY = MatrixXd::Zero(BY.rows(), BY.cols());\n\n            int n = 0;  //iteration\n            int p = 0;  //incrementer for input & target\n\n            double smooth_loss = -log(1.0/ double(vocab_size)) * double(sequence_length); \n            double learning_rate = 1 * exp(-1);\n            \n            MatrixXd h_prev; //saving previous hiddens\n\n            while (true)\n            {\n                if ( ((p + sequence_length + 1) >= data_size) or (n == 0))\n                {\n                    h_prev = MatrixXd::Zero(hiddens, 1);  //Initalizes or Reset the memory of RNN\n                    p = 0;                                //Set sequence incrementer back to 0\n                }\n\n                /* Grab Inputs and Targets */\n                vector <int> inputs = getID(p, p + sequence_length); \n                vector <int> targets = getID(p + 1, p + sequence_length + 1);\n\n                // Grab Loss Function's Outputs\n                loss_result* item = loss(inputs, targets, h_prev);\n\n                // Set new loss\n                smooth_loss = smooth_loss * 0.999 + item->loss * 0.001;\n\n                if ((n % 100 == 0) && (n != 0))\n                {\n                    /* Generate Text and Display Current Loss */\n                    auto samples = sample(h_prev, inputs[0], 200);\n                    auto text = genText(samples);\n\n                    cout << \"\\n\" << text << endl;\n                    cout << \"\\n\";\n                    cout << \"Iteration #: \"  << n << \" Loss: \" << smooth_loss << endl;\n                }\n                \n                if ((n % 1000000 == 0) && (n != 0))\n                {\n                   // decreases learning rate as number of iteration increases\n                   if (learning_rate >= 0.0000001)\n                   {\n                       learning_rate = learning_rate / (1.0 + (exp(-n/(n + 1))));\n                   }\n                   else\n                   {\n                       //restart\n                       learning_rate = 0.1;\n                   }\n                       \n                }\n\n                /* Update Weight using AdaGrad*/\n                mWXH.noalias() += MatrixXd(item->dWxh.array() * item->dWxh.array());\n                W_XH += MatrixXd(-learning_rate * item->dWxh.array() / sqrt(mWXH.array() + 1e-8));\n\n                mWHH.noalias() += MatrixXd(item->dWhh.array() * item->dWhh.array());\n                W_HH += MatrixXd(-learning_rate * item->dWhh.array() / sqrt(mWHH.array() + 1e-8));\n        \n                mWHY.noalias() += MatrixXd(item->dWhy.array() * item->dWhy.array());\n                W_HY += MatrixXd(-learning_rate * item->dWhy.array() / sqrt(mWHY.array() + 1e-8));\n\n                /* Update Biases*/\n                mBH.noalias() += MatrixXd(item->dbh.array() * item->dbh.array());\n                BH += MatrixXd(-learning_rate * item->dbh.array() / sqrt(mBH.array() + 1e-8));\n\n                mBY.noalias() += MatrixXd(item->dby.array() * item->dby.array());\n                BY += MatrixXd(-learning_rate * item->dby.array() / sqrt(mBY.array() + 1e-8));\n\n                delete(item);                           //free the loss result structure\n                \n                p += sequence_length;                   //update current sequence length\n                n ++;                                   //increment current iteration\n            }\n        }\n};\n\nint main(int argc, char* argv[])\n{\n    if (argc != 4)\n    {\n        cout << \"Arguments: Corpus File, hidden size, sequence length\" << endl;\n        return 0;\n    }\n    //grab arguments and convert char to int for hidden size and sequence length\n    string filename = argv[1]; int hidden_size = atoi(argv[2]); int seq_length = atoi(argv[3]);\n\n    Eigen::initParallel();\n    RNN rnn = RNN(hidden_size, seq_length);\n    rnn.load(filename);\n    rnn.learn();\n}\n", "meta": {"hexsha": "32b835a943291a31306a0b64065a7847deaa3cc7", "size": 17121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RNN.cpp", "max_stars_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_stars_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RNN.cpp", "max_issues_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_issues_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RNN.cpp", "max_forks_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_forks_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_forks_repo_licenses": ["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.9593301435, "max_line_length": 135, "alphanum_fraction": 0.4455931312, "num_tokens": 3707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6880170218995671}}
{"text": "#include \"Triangle.h\"\n#include \"Ray.h\"\n#include <Eigen/Geometry>\n\nbool Triangle::intersect(\n  const Ray & ray, const double min_t, double & t, Eigen::Vector3d & n) const\n{\n  ////////////////////////////////////////////////////////////////////////////\n  // Replace with your code here\n  double beta = 0;\n  double gamma = 0;\n  double t_prime = 0;\n\n  // corners: a = corners[0], b = corners[1], c = corners[2]\n  // Calculate dummy variables for Cramer's rule calculation (from textbook)\n  double a = std::get<0>(corners)(0) - std::get<1>(corners)(0);\n  double d = std::get<0>(corners)(0) - std::get<2>(corners)(0);\n  double g = ray.direction(0);\n\n  double b = std::get<0>(corners)(1) - std::get<1>(corners)(1);\n  double e = std::get<0>(corners)(1) - std::get<2>(corners)(1);\n  double h = ray.direction(1);\n\n  double c = std::get<0>(corners)(2) - std::get<1>(corners)(2);\n  double f = std::get<0>(corners)(2) - std::get<2>(corners)(2);\n  double i = ray.direction(2);\n\n  double j = std::get<0>(corners)(0) - ray.origin(0);\n  double k = std::get<0>(corners)(1) - ray.origin(1);\n  double l = std::get<0>(corners)(2) - ray.origin(2);\n\n  // intermediate dummy variables for calculating beta, gamma, and t\n  double ei_minus_hf = (e * i) - (h * f);\n  double gf_minus_di = (g * f) - (d * i);\n  double dh_minus_eg = (d * h) - (e * g);\n  double ak_minus_jb = (a * k) - (j * b);\n  double jc_minus_al = (j * c) - (a * l);\n  double bl_minus_kc = (b * l) - (k * c);\n\n  double M = (a * ei_minus_hf) + (b * gf_minus_di) + (c * dh_minus_eg);\n  t_prime = -(((f * ak_minus_jb) + (e * jc_minus_al) + (d * bl_minus_kc)) / M);\n\n  if (t_prime < min_t)\n  {\n    return false;\n  }\n\n  gamma = ((i * ak_minus_jb) + (h * jc_minus_al) + (g * bl_minus_kc)) / M;\n  if (gamma < 0 || gamma > 1)\n  {\n    return false;\n  }\n\n  beta = ((j * ei_minus_hf) + (k * gf_minus_di) + (l * dh_minus_eg)) / M;\n  if (beta < 0 || beta > (1 - gamma))\n  {\n    return false;\n  }\n\n  if (t_prime < t)\n  {\n    t = t_prime;\n    // given two vectors u and v, the cross product (u X v) = n (normal vector)\n    // u = b - a, v = c - a\n    Eigen::Vector3d u = std::get<1>(corners) - std::get<0>(corners);\n    Eigen::Vector3d v = std::get<2>(corners) - std::get<0>(corners);\n    n = u.cross(v);\n    n.normalize();\n\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n  ////////////////////////////////////////////////////////////////////////////\n}\n\n\n", "meta": {"hexsha": "70c0b2f5a55ec9382dc49b1ab66190f30bac58c4", "size": 2386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Triangle.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/Triangle.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/Triangle.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": 29.825, "max_line_length": 79, "alphanum_fraction": 0.537300922, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6880170115799661}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE RasterizerTestSuite\n#include <boost/test/unit_test.hpp>\n\n#include <BilinearPatch.hpp>\n#include <QuadraticSolver.hpp>\n#include <RationalBilinearInverter.hpp>\n#include <Vec.hpp>\n\nBOOST_AUTO_TEST_CASE(TEST_QUADRATIC_SOLVER) {\n\tQuadraticSolver<float> q(1.0f, 0.0f, -4.0f);\n\tBOOST_CHECK_EQUAL(q.size(), 2);\n\tBOOST_CHECK_EQUAL(q[0], -2.0f);\n\tBOOST_CHECK_EQUAL(q[1], 2.0f);\n}\n\nBOOST_AUTO_TEST_CASE(TEST_BILINEAR_PATCH) {\n\tBilinearPatch<Vec2> patch(\n\t\tVec2(-1, -1), Vec2(1, -1),\n\t\tVec2(-1, 1), Vec2(1, 1)\n\t);\n\n\tBOOST_CHECK_EQUAL(patch(0.5f, 0.0f), Vec2(0, -1));\n}\n\nBOOST_AUTO_TEST_CASE(TEST_RATIONAL_BILINEAR_INVERTER) {\n\tBilinearPatch<Vec4> patch(\n\t\tVec4(0, 0, 1, 1),\n\t\tVec4(1, 1, 1, 1),\n\t\tVec4(0, 1, 1, 1),\n\t\tVec4(1, 2, 1, 1)\n\t);\n\n\tfor (int j = 0; j <= 64; ++j) {\n\t\tfloat v = static_cast<float>(j) / 64.0f;\n\n\t\tfor (int i = 0; i <= 64; ++i) {\n\t\t\tfloat u = static_cast<float>(i) / 64.0f;\n\n\t\t\tVec4 p4 = patch(u, v);\n\t\t\tVec2 p2 = Vec2(p4.x(), p4.y()) / (p4.z() * p4.w());\n\n\t\t\tRationalBilinearInverter rbi(p2,\n\t\t\t\tpatch[0], patch[1], patch[2], patch[3]\n\t\t\t);\n\n\t\t\tBOOST_REQUIRE(rbi.size() > 0);\n\t\t\tBOOST_CHECK_EQUAL(rbi.front().second, Vec2(u, v));\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "98802bc1357ac0bbf5e9fb4dbd159d1332bf5dc6", "size": 1200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "handsome/cpp_src/test/test_suite.cpp", "max_stars_repo_name": "bracket/handsome", "max_stars_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "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": "handsome/cpp_src/test/test_suite.cpp", "max_issues_repo_name": "bracket/handsome", "max_issues_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "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": "handsome/cpp_src/test/test_suite.cpp", "max_forks_repo_name": "bracket/handsome", "max_forks_repo_head_hexsha": "c93d34f94d0eea24f5514efc9bc423eb28b44a6b", "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": 23.0769230769, "max_line_length": 55, "alphanum_fraction": 0.6466666667, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6878981957700537}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2014 Jianwei Cui <thucjw@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n#include <complex>\r\n#include <cmath>\r\n#include <Eigen/CXX11/Tensor>\r\n\r\nusing Eigen::Tensor;\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_1D_fft_ifft_invariant(int sequence_length) {\r\n  Tensor<double, 1, DataLayout> tensor(sequence_length);\r\n  tensor.setRandom();\r\n\r\n  array<int, 1> fft;\r\n  fft[0] = 0;\r\n\r\n  Tensor<std::complex<double>, 1, DataLayout> tensor_after_fft;\r\n  Tensor<std::complex<double>, 1, DataLayout> tensor_after_fft_ifft;\r\n\r\n  tensor_after_fft = tensor.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(fft);\r\n  tensor_after_fft_ifft = tensor_after_fft.template fft<Eigen::BothParts, Eigen::FFT_REVERSE>(fft);\r\n\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), sequence_length);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), sequence_length);\r\n\r\n  for (int i = 0; i < sequence_length; ++i) {\r\n    VERIFY_IS_APPROX(static_cast<float>(tensor(i)), static_cast<float>(std::real(tensor_after_fft_ifft(i))));\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_2D_fft_ifft_invariant(int dim0, int dim1) {\r\n  Tensor<double, 2, DataLayout> tensor(dim0, dim1);\r\n  tensor.setRandom();\r\n\r\n  array<int, 2> fft;\r\n  fft[0] = 0;\r\n  fft[1] = 1;\r\n\r\n  Tensor<std::complex<double>, 2, DataLayout> tensor_after_fft;\r\n  Tensor<std::complex<double>, 2, DataLayout> tensor_after_fft_ifft;\r\n\r\n  tensor_after_fft = tensor.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(fft);\r\n  tensor_after_fft_ifft = tensor_after_fft.template fft<Eigen::BothParts, Eigen::FFT_REVERSE>(fft);\r\n\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n\r\n  for (int i = 0; i < dim0; ++i) {\r\n    for (int j = 0; j < dim1; ++j) {\r\n      //std::cout << \"[\" << i << \"][\" << j << \"]\" <<  \"  Original data: \" << tensor(i,j) << \" Transformed data:\" << tensor_after_fft_ifft(i,j) << std::endl;\r\n      VERIFY_IS_APPROX(static_cast<float>(tensor(i,j)), static_cast<float>(std::real(tensor_after_fft_ifft(i,j))));\r\n    }\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_3D_fft_ifft_invariant(int dim0, int dim1, int dim2) {\r\n  Tensor<double, 3, DataLayout> tensor(dim0, dim1, dim2);\r\n  tensor.setRandom();\r\n\r\n  array<int, 3> fft;\r\n  fft[0] = 0;\r\n  fft[1] = 1;\r\n  fft[2] = 2;\r\n\r\n  Tensor<std::complex<double>, 3, DataLayout> tensor_after_fft;\r\n  Tensor<std::complex<double>, 3, DataLayout> tensor_after_fft_ifft;\r\n\r\n  tensor_after_fft = tensor.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(fft);\r\n  tensor_after_fft_ifft = tensor_after_fft.template fft<Eigen::BothParts, Eigen::FFT_REVERSE>(fft);\r\n\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(2), dim2);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(2), dim2);\r\n\r\n  for (int i = 0; i < dim0; ++i) {\r\n    for (int j = 0; j < dim1; ++j) {\r\n      for (int k = 0; k < dim2; ++k) {\r\n        VERIFY_IS_APPROX(static_cast<float>(tensor(i,j,k)), static_cast<float>(std::real(tensor_after_fft_ifft(i,j,k))));\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_sub_fft_ifft_invariant(int dim0, int dim1, int dim2, int dim3) {\r\n  Tensor<double, 4, DataLayout> tensor(dim0, dim1, dim2, dim3);\r\n  tensor.setRandom();\r\n\r\n  array<int, 2> fft;\r\n  fft[0] = 2;\r\n  fft[1] = 0;\r\n\r\n  Tensor<std::complex<double>, 4, DataLayout> tensor_after_fft;\r\n  Tensor<double, 4, DataLayout> tensor_after_fft_ifft;\r\n\r\n  tensor_after_fft = tensor.template fft<Eigen::BothParts, Eigen::FFT_FORWARD>(fft);\r\n  tensor_after_fft_ifft = tensor_after_fft.template fft<Eigen::RealPart, Eigen::FFT_REVERSE>(fft);\r\n\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(2), dim2);\r\n  VERIFY_IS_EQUAL(tensor_after_fft.dimension(3), dim3);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(2), dim2);\r\n  VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(3), dim3);\r\n\r\n  for (int i = 0; i < dim0; ++i) {\r\n    for (int j = 0; j < dim1; ++j) {\r\n      for (int k = 0; k < dim2; ++k) {\r\n        for (int l = 0; l < dim3; ++l) {\r\n          VERIFY_IS_APPROX(static_cast<float>(tensor(i,j,k,l)), static_cast<float>(tensor_after_fft_ifft(i,j,k,l)));\r\n        }\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\nvoid test_cxx11_tensor_ifft() {\r\n  CALL_SUBTEST(test_1D_fft_ifft_invariant<ColMajor>(4));\r\n  CALL_SUBTEST(test_1D_fft_ifft_invariant<ColMajor>(16));\r\n  CALL_SUBTEST(test_1D_fft_ifft_invariant<ColMajor>(32));\r\n  CALL_SUBTEST(test_1D_fft_ifft_invariant<ColMajor>(1024*1024));\r\n\r\n  CALL_SUBTEST(test_2D_fft_ifft_invariant<ColMajor>(4,4));\r\n  CALL_SUBTEST(test_2D_fft_ifft_invariant<ColMajor>(8,16));\r\n  CALL_SUBTEST(test_2D_fft_ifft_invariant<ColMajor>(16,32));\r\n  CALL_SUBTEST(test_2D_fft_ifft_invariant<ColMajor>(1024,1024));\r\n\r\n  CALL_SUBTEST(test_3D_fft_ifft_invariant<ColMajor>(4,4,4));\r\n  CALL_SUBTEST(test_3D_fft_ifft_invariant<ColMajor>(8,16,32));\r\n  CALL_SUBTEST(test_3D_fft_ifft_invariant<ColMajor>(16,4,8));\r\n  CALL_SUBTEST(test_3D_fft_ifft_invariant<ColMajor>(256,256,256));\r\n\r\n  CALL_SUBTEST(test_sub_fft_ifft_invariant<ColMajor>(4,4,4,4));\r\n  CALL_SUBTEST(test_sub_fft_ifft_invariant<ColMajor>(8,16,32,64));\r\n  CALL_SUBTEST(test_sub_fft_ifft_invariant<ColMajor>(16,4,8,12));\r\n  CALL_SUBTEST(test_sub_fft_ifft_invariant<ColMajor>(64,64,64,64));\r\n}\r\n", "meta": {"hexsha": "76e67afe26d443f82a257d7b864a050211582a85", "size": 6088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_ifft.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/unsupported/test/cxx11_tensor_ifft.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/unsupported/test/cxx11_tensor_ifft.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": 39.2774193548, "max_line_length": 157, "alphanum_fraction": 0.7094283837, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6878632293042737}}
{"text": "/*\nA class to represent an extension field \n*/\n\n#ifndef EXTENSION_FIELD\n#define EXTENSION_FIELD\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <vector>\n\n#include \"polynomial.hpp\"\n\nusing namespace std;\n\n// extension field element (EFE)\ntemplate<class PFE> class EFE:\n\tboost::field_operators< EFE<PFE>,\n\tboost::equality_comparable< EFE<PFE>\n\t> >\n{\npublic: \n\t//! an element of the extension field is a polynomial with coefficients in the prime field PFE\n\tpolynomial<PFE> el;\n\t//! the degree of the extension\n\tstatic unsigned m; \n\t//! primitive polynomial defining the extension field\n\tstatic polynomial<PFE> prim_poly;\n\t//! constructors\n\tEFE(vector<PFE>& v): el(polynomial<PFE>(v)) {};\n\tEFE(polynomial<PFE>& el_): el(el_) {};\n\tEFE(unsigned x){ // set the coeff with exponent zero to x\n\t\tvector<PFE> tmpv(m, PFE(0) );\n\t\ttmpv[0] = PFE(x);\n\t\tel = polynomial<PFE>(tmpv);\n\t}\n\tEFE(){};\n\n\tEFE& operator += (const EFE& x){\n\t\tel += x.el;\n\t\treturn *this;\n\t}\n\t\n\tEFE& operator -= (const EFE& x){\n\t\tel -= x.el;\n\t\treturn *this;\n\t}\n\n\tEFE& operator *= (const EFE& x){\n\t\t// multiply\n\t\tpolynomial<PFE> ptmp = el*x.el;\n\t\t// modulo the primitive polynomial\n\t\n\t\tint exp;\n\t\twhile( (exp = ptmp.degree() - prim_poly.degree()) >= 0 ){\n\t\t\t// difference in exponents\n\t\t\t//unsigned exp = ptmp.degree() - prim_poly.degree();\n\t\t\t// primitive polynomial; to be muliplied..\t\n\t\t\tpolynomial<PFE> primtmp = prim_poly;\n\t\t\tPFE co_mo = ptmp.poly[ptmp.degree()];  \n\t\t\tco_mo /= prim_poly.poly[prim_poly.degree()];\n\t\t\tprimtmp.multiply_monomial( co_mo , exp  );\n\t\t\tptmp -= primtmp;\n\t\t}\n\n\t\tptmp.poly.resize(ptmp.degree()+1);\n\t\tel = ptmp;\n\t\treturn *this;\n\t}\n\n\tEFE& operator /= (const EFE& x){\n\t\t*this = (x.inverse() * (*this)); \n\t\treturn *this;\n\t}\n\t\n\t//! compute the multiplicative inverse via the extended Euclidean algorithm \n\tEFE inverse() const {\n\t\t\n\t\tpolynomial<PFE> rem1 = prim_poly;\n\t\tpolynomial<PFE> rem2 = el;\n\t\tpolynomial<PFE> aux1 = polynomial<PFE>(0);\n\t\tpolynomial<PFE> aux2 = polynomial<PFE>(1);\n\n\n\t\twhile(! rem2.iszero() ){\n\t\t\t// res.first = quotient(rem1/rem2)\n\t\t\t// res.second = remainder(rem1/rem2)\n\t\t\t\n\t\t\tpair<polynomial<PFE>, polynomial<PFE> > res = divide<PFE>(rem1,rem2);\n\n\t\t\tpolynomial<PFE> aux_new = polynomial<PFE>(0) - res.first*aux2 + aux1;\n\n\t\t\t// prepare for the next step\n\t\t\trem1 = rem2;\n\t\t\trem2 = res.second;\n\t\t\taux1 = aux2;\n\t\t\taux2 = aux_new;\n\t\t\t\n\t\t}\n\t\n\t\taux1.multiply_monomial(pow(rem1.poly[0],-1), 0);\n\n\t\treturn aux1;\n\t}\n\n\n\t\n\tunsigned order() const {\n\t\t// multiplicative neutral element = 1\n\t\t//PFE one = PFE(1);\n\t\tvector<PFE> vecone = vector<PFE>(1,PFE(1));\n\t\tEFE one = EFE(vecone); \n\t\tEFE tmp = *this;  //EFE(el);\t\t\n\t\tunsigned ord = 1;\n\t\twhile(!(tmp == one)){\n\t\t\tord++;\n\t\t\ttmp *= *this;\n\t\t\t//cout << tmp << endl;\n\t\t}\n\t\treturn ord;\n\t}\n\t/*\n\t// not a good solution\n\tvector<unsigned> tovec() const {\n\t\tvector<unsigned> vec(m,0);\n\t\tfor(unsigned i=0;i<el.poly.size();++i){\n\t\t\tvec[i] = el.poly[i].element;\n\t\t}\n\t\treturn vec;\n\t}\n\t*/\n\n\tvector<PFE> tovec() const {\n\t\tif(el.poly.size()!=m){\n\t\t\tvector<PFE> tmp(m,PFE(0));\n\t\t\tfor(unsigned i=0;i<el.poly.size();++i){\n\t\t\t\ttmp[i] = el.poly[i];\n\t\t\t}\n\t\t\treturn tmp;\n\t\t}else\n\t\t\treturn el.poly;\n\t}\n\n\tbool iszero() const {\n\t\tvector<PFE> veczero = vector<PFE>(1,PFE(0));\n\t\tEFE zero = EFE(veczero);\n\t\treturn (zero == *this);\n\t}\n\t\n\tbool isempty() const {\n\t\treturn (el.poly.size() == 0);\n\t}\n\n\tbool operator ==(const EFE& x) const {\n\t\t\n\t\tfor(unsigned i = 0; i < min(el.poly.size(),x.el.poly.size()); ++i)\n\t\t\tif(!(x.el.poly[i] == el.poly[i]) ) return false;\n\t\t\n\t\t// need to verify if the coefficients of the larger vector that are necessarily zero in the smaller vector are also zero in the larger vector \n\t\tif(el.poly.size() > x.el.poly.size()){\n\t\t\tfor(unsigned i = x.el.poly.size() ; i<el.poly.size(); ++i) \n\t\t\t\tif( !(el.poly[i].iszero()) ) return false;\n\t\t} else if(el.poly.size() < x.el.poly.size()){\n\t\t\tfor(unsigned i = el.poly.size(); i<x.el.poly.size(); ++i) \n\t\t\t\tif( !(x.el.poly[i].iszero()) ) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n};\t\n\n template<class PFE>\n    ostream &operator<<(ostream &stream, const EFE<PFE> x)\n    {\n\t  \tstream <<  x.el;\n      \treturn stream; // must return stream\n\t};\n\ntemplate<class PFE>\n \tEFE<PFE> pow(const EFE<PFE>& a, int exp){\n\t\t\n\t\tif(a.iszero()) return a;\n\t\tif(exp == 0) {\n\t\t\tvector<PFE> vecone = vector<PFE>(1,PFE(1));\n\t\t\treturn EFE<PFE>(vecone); \n\t\t}\n\t\t\n\t\tEFE<PFE> tmp;\n\t\t\n\t\tif(exp < 0){\n\t\t\tEFE<PFE> am = a.inverse(); \n\t\t\ttmp = am;\n\t\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= am;\n\t\t} else { // exp > 0\n\t\t\ttmp = a;\n\t\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= a;\n\t\t}\n\n\t\treturn tmp;\n\t};\n\n\n\n#endif\n", "meta": {"hexsha": "ed0da9b432b11173b30aff4980b0a810ecadd8fe", "size": 4584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/EFE.hpp", "max_stars_repo_name": "libingzheren/dna_rs_coding", "max_stars_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "include/EFE.hpp", "max_issues_repo_name": "libingzheren/dna_rs_coding", "max_issues_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "include/EFE.hpp", "max_forks_repo_name": "libingzheren/dna_rs_coding", "max_forks_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 22.2524271845, "max_line_length": 144, "alphanum_fraction": 0.6112565445, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6878632188176235}}
{"text": "/*\n * 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 */\n\n#include \"math_unit_test.hpp\"\n#include <random>\n#include <boost/math/tools/cubic_roots.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::tools::cubic_roots;\nusing boost::math::tools::cubic_root_residual;\nusing std::cbrt;\n\ntemplate<class Real>\nvoid test_zero_coefficients()\n{\n    Real a = 0;\n    Real b = 0;\n    Real c = 0;\n    Real d = 0;\n    auto roots = cubic_roots(a,b,c,d);\n    CHECK_EQUAL(roots[0], Real(0));\n    CHECK_EQUAL(roots[1], Real(0));\n    CHECK_EQUAL(roots[2], Real(0));\n\n    a = 1;\n    roots = cubic_roots(a,b,c,d);\n    CHECK_EQUAL(roots[0], Real(0));\n    CHECK_EQUAL(roots[1], Real(0));\n    CHECK_EQUAL(roots[2], Real(0));\n\n    a = 1;\n    d = 1;\n    // x^3 + 1 = 0:\n    roots = cubic_roots(a,b,c,d);\n    CHECK_EQUAL(roots[0], Real(-1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    d = -1;\n    // x^3 - 1 = 0:\n    roots = cubic_roots(a,b,c,d);\n    CHECK_EQUAL(roots[0], Real(1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n    d = -2;\n    // x^3 - 2 = 0\n    roots = cubic_roots(a,b,c,d);\n    CHECK_ULP_CLOSE(roots[0], cbrt(Real(2)), 2);\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n    d = -8;\n    roots = cubic_roots(a,b,c,d);\n    CHECK_EQUAL(roots[0], Real(2));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n\n    // (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6\n    roots = cubic_roots(Real(1), Real(-6), Real(11), Real(-6));\n    CHECK_ULP_CLOSE(roots[0], Real(1), 2);\n    CHECK_ULP_CLOSE(roots[1], Real(2), 2);\n    CHECK_ULP_CLOSE(roots[2], Real(3), 2);\n\n    // Double root:\n    // (x+1)^2(x-2) = x^3 - 3x - 2:\n    // Note: This test is unstable wrt to perturbations!\n    roots = cubic_roots(Real(1), Real(0), Real(-3), Real(-2));\n    CHECK_ULP_CLOSE(Real(-1), roots[0], 2);\n    CHECK_ULP_CLOSE(Real(-1), roots[1], 2);\n    CHECK_ULP_CLOSE(Real(2), roots[2], 2);\n\n    std::uniform_real_distribution<Real> dis(-2,2);\n    std::mt19937 gen(12345);\n    // Expected roots\n    std::array<Real, 3> r;\n    int trials = 10;\n    for (int i = 0; i < trials; ++i) {\n        // Mathematica:\n        // Expand[(x - r0)*(x - r1)*(x - r2)]\n        // - r0 r1 r2 + (r0 r1 + r0 r2 + r1 r2) x\n        // - (r0 + r1 + r2) x^2 + x^3\n        for (auto & root : r) {\n            root = static_cast<Real>(dis(gen));\n        }\n        std::sort(r.begin(), r.end());\n        Real a = 1;\n        Real b = -(r[0] + r[1] + r[2]);\n        Real c = r[0]*r[1] + r[0]*r[2] + r[1]*r[2];\n        Real d = -r[0]*r[1]*r[2];\n\n        auto roots = cubic_roots(a, b, c, d);\n        // I could check the condition number here, but this is fine right?\n        if(!CHECK_ULP_CLOSE(r[0], roots[0], 25)) {\n            std::cerr << \"  Polynomial x^3 + \" << b << \"x^2 + \" << c << \"x + \" << d << \" has roots {\";\n            std::cerr << r[0] << \", \" << r[1] << \", \" << r[2] << \"}, but the computed roots are {\";\n            std::cerr << roots[0] << \", \" << roots[1] << \", \" << roots[2] << \"}\\n\";\n        }\n        CHECK_ULP_CLOSE(r[1], roots[1], 25);\n        CHECK_ULP_CLOSE(r[2], roots[2], 25);\n        for (auto root : roots) {\n            auto res = cubic_root_residual(a, b,c,d, root);\n            CHECK_LE(abs(res[0]), 20*res[1]);\n        }\n    }\n}\n\n\nint main()\n{\n    test_zero_coefficients<float>();\n    test_zero_coefficients<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_zero_coefficients<long double>();\n#endif\n\n#ifdef BOOST_HAS_FLOAT128\n    // For some reason, the quadmath is way less accurate than the float/double/long double:\n    //test_zero_coefficients<float128>();\n#endif\n\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "28ddac9142032299da38bc0b1e80e7c5f3eeacf8", "size": 3876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/math/test/cubic_roots_test.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "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": "console/src/boost_1_78_0/libs/math/test/cubic_roots_test.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "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": "console/src/boost_1_78_0/libs/math/test/cubic_roots_test.cpp", "max_forks_repo_name": "vany152/FilesHash", "max_forks_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "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": 29.3636363636, "max_line_length": 102, "alphanum_fraction": 0.5614035088, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.6876684052173294}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n  VectorXf v(6);\n  \n  v << 1, 2, 3, 4, 5, 6;\n\n  //print first three elements\n  cout << \"-- head(3) --\" << endl\n    << v.head(3) << endl << endl;\n  \n  //print last three elements\n  cout << \"-- tail(3) --\" << endl\n    << v.tail(3) << endl << endl;\n    \n  //print between 2nd and 5th elem. inclusive\n  cout << \"-- segment(1,4) --\" << endl\n    << v.segment(1,4) << endl;\n}\n", "meta": {"hexsha": "211b554729757dc59face292eaedff960608e269", "size": 471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_vector.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_vector.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_vector.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": 18.84, "max_line_length": 45, "alphanum_fraction": 0.5435244161, "num_tokens": 161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.8128673155708975, "lm_q1q2_score": 0.687638964456751}}
{"text": "#include <Eigen/Core>\n#include <Spectra/SymEigsSolver.h>\n\n#include <iostream>\n\nint main() {\n    // We are going to calculate the eigenvalues of M\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 10);\n    Eigen::MatrixXd M = A + A.transpose();\n\n    // Construct matrix operation object using the wrapper class DenseSymMatProd\n    Spectra::DenseSymMatProd<double> op(M);\n\n    // Construct eigen solver object, requesting the largest three eigenvalues\n#ifdef SPECTRA_LESS_1_0_0\n    Spectra::SymEigsSolver< double, Spectra::LARGEST_ALGE, Spectra::DenseSymMatProd<double> > eigs(&op, 3, 6);\n#else\n    Spectra::SymEigsSolver<Spectra::DenseSymMatProd<double>> eigs(op, 3, 6);\n#endif\n\n    // Initialize and compute\n    eigs.init();\n#ifdef SPECTRA_LESS_1_0_0\n    int nconv = eigs.compute();\n#else\n    int nconv = eigs.compute(Spectra::SortRule::LargestAlge);\n#endif\n\n    // Retrieve results\n    Eigen::VectorXd evalues;\n#ifdef SPECTRA_LESS_1_0_0\n    if (eigs.info() == Spectra::SUCCESSFUL) {\n#else\n    if (eigs.info() == Spectra::CompInfo::Successful) {\n#endif\n        evalues = eigs.eigenvalues();\n    }\n\n    std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "3da7ef12504b7aee33400f24d597b0f7eb4bdcf2", "size": 1182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_stars_repo_name": "rockandsalt/conan-center-index", "max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 562.0, "max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z", "max_issues_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_issues_repo_name": "rockandsalt/conan-center-index", "max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9799.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z", "max_forks_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_forks_repo_name": "rockandsalt/conan-center-index", "max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1126.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z", "avg_line_length": 27.488372093, "max_line_length": 110, "alphanum_fraction": 0.6878172589, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6875560943357715}}
{"text": "#include <Eigen/SVD>\n#include <rct_optimizations/validation/noise_qualification.h>\n#include <rct_optimizations/pnp.h>\n\n//accumulators\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <cassert>\n\nnamespace rct_optimizations\n{\n\nEigen::Quaterniond computeQuaternionMean(const std::vector<Eigen::Quaterniond>& quaterns)\n{\n /* Mean quaternion is found using method described by Markley et al: Quaternion Averaging\n  * https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20070017872.pdf\n  *\n  * M = sum(w_i * q_i * q_i^T)    Eq. 12\n  * q_bar = argmax(q^T * M * q)   Eq. 13\n  *\n  * \"The solution of this maximization problem is well known. The average quaternion is\n  * the eigenvector of M corresponding to the maximum eigenvalue.\"\n  *\n  * In the above equations, w_i is the weight of the ith quaternion.\n  * In this case, all quaternions are equally weighted (i.e. w_i = 1)\n  */\n\n  Eigen::Matrix4d M = Eigen::Matrix4d::Zero();\n\n  for(const Eigen::Quaterniond& q : quaterns)\n  {\n    M += q.coeffs() * q.coeffs().transpose();\n  }\n\n  // Calculate the SVD of the M matrix\n  Eigen::JacobiSVD<Eigen::Matrix4d> svd(M, Eigen::ComputeFullU);\n\n  // The eigenvectors are represented by the columns of the U matrix; the eigenvector corresponding to the largest eigenvalue is in row 0\n  Eigen::Quaterniond q;\n  q.coeffs() << svd.matrixU().col(0);\n\n  assert(std::isnan(q.w()) == false &&\n         std::isnan(q.x()) == false &&\n         std::isnan(q.y()) == false &&\n         std::isnan(q.z()) == false);\n\n  return q;\n};\n\nQuaternionStats computeQuaternionStats(const std::vector<Eigen::Quaterniond> &quaternions)\n{\n  QuaternionStats q_stats;\n  q_stats.mean = computeQuaternionMean(quaternions);\n\n  double q_var = 0.0;\n  for (const Eigen::Quaterniond &q : quaternions)\n  {\n    q_var += std::pow(q_stats.mean.angularDistance(q), 2.0);\n  }\n  q_var /= static_cast<double>(quaternions.size() - 1);\n  q_stats.stdev = std::sqrt(q_var);\n\n  return q_stats;\n}\n\nPnPNoiseStat qualifyNoise2D(const std::vector<PnPProblem>& params)\n{\n  PnPNoiseStat output;\n  std::size_t count = params.size();\n\n  std::vector<Eigen::Isometry3d> solution_transforms;\n  solution_transforms.reserve(count);\n\n  std::vector<Eigen::Vector3d> translations;\n  translations.reserve(count);\n\n  std::vector<Eigen::Quaterniond> orientations;\n  orientations.reserve(count);\n\n  namespace ba = boost::accumulators;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> x_acc;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> y_acc;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> z_acc;\n\n  for (auto& prob : params)\n  {\n    rct_optimizations::PnPResult result;\n\n    result = rct_optimizations::optimize(prob);\n\n    if (result.converged)\n    {\n      //we will save the full result here for debugging purposes\n      solution_transforms.push_back(result.camera_to_target);\n      translations.push_back(solution_transforms.back().translation());\n\n      x_acc(result.camera_to_target.translation()(0));\n      y_acc(result.camera_to_target.translation()(1));\n      z_acc(result.camera_to_target.translation()(2));\n\n      orientations.push_back(Eigen::Quaterniond(result.camera_to_target.rotation()));\n    }\n  }\n\n  output.p_stat.mean << ba::mean(x_acc), ba::mean(y_acc), ba::mean(z_acc);\n  output.p_stat.stdev << std::sqrt(ba::variance(x_acc)), std::sqrt(ba::variance(y_acc)), std::sqrt(ba::variance(z_acc));\n  output.q_stat = computeQuaternionStats(orientations);\n\n  return output;\n}\n\nPnPNoiseStat qualifyNoise3D(const std::vector<PnPProblem3D>& params)\n{\n  PnPNoiseStat output;\n  std::size_t count = params.size();\n\n  std::vector<Eigen::Isometry3d> solution_transforms;\n  solution_transforms.reserve(count);\n\n  std::vector<Eigen::Vector3d> translations;\n  translations.reserve(count);\n\n  std::vector<Eigen::Quaterniond> orientations;\n  orientations.reserve(count);\n\n  namespace ba = boost::accumulators;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> x_acc;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> y_acc;\n  ba::accumulator_set<double, ba::stats<ba::tag::mean, ba::tag::variance>> z_acc;\n\n  for (auto& prob : params)\n  {\n    rct_optimizations::PnPResult result;\n\n    result = rct_optimizations::optimize(prob);\n\n    if (result.converged)\n    {\n      //we will save the full result here for debugging purposes\n      solution_transforms.push_back(result.camera_to_target);\n      translations.push_back(solution_transforms.back().translation());\n\n      x_acc(result.camera_to_target.translation()(0));\n      y_acc(result.camera_to_target.translation()(1));\n      z_acc(result.camera_to_target.translation()(2));\n\n      orientations.push_back(Eigen::Quaterniond(result.camera_to_target.rotation()));\n    }\n  }\n\n  output.p_stat.mean << ba::mean(x_acc), ba::mean(y_acc), ba::mean(z_acc);\n  output.p_stat.stdev << std::sqrt(ba::variance(x_acc)), std::sqrt(ba::variance(y_acc)), std::sqrt(ba::variance(z_acc));\n  output.q_stat = computeQuaternionStats(orientations);\n\n  return output;\n}\n\n}//rct_optimizations\n", "meta": {"hexsha": "46b576c98843288445fb185649816cfeacac6b29", "size": 5229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_stars_repo_name": "m-limbird/robot_cal_tools", "max_stars_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 110.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:27:44.000Z", "max_issues_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_issues_repo_name": "m-limbird/robot_cal_tools", "max_issues_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2018-07-02T02:29:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T19:11:41.000Z", "max_forks_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_forks_repo_name": "m-limbird/robot_cal_tools", "max_forks_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2018-07-01T01:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:14:47.000Z", "avg_line_length": 32.4782608696, "max_line_length": 137, "alphanum_fraction": 0.7116083381, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6875398646818064}}
{"text": "#pragma once\n\n#include <string>\n#include <cmath>\n#include <exception>\n#include <armadillo>\n\n/*!\n  * \\defgroup typedefs Typedefs\n  */\n\nnamespace utils\n{\n    inline double pow2(const double a);\n    inline arma::vec pow2(const arma::vec& a);\n    inline double pow3(const double a);\n    inline double pow4(const double a);\n    inline double pow5(const double a);\n    inline double pow6(const double a);\n\n    inline arma::vec cubeRoot(const arma::vec& input);\n\n    inline arma::vec centerDifference(const arma::vec& input);\n\n    inline arma::vec centerDifference(const arma::subview_col<arma::mat::elem_type>& input);\n\n    inline arma::vec centerSum(const arma::vec& input);\n\n    inline arma::vec centerSum(const arma::subview_col<arma::mat::elem_type>& input);\n\n    inline arma::vec centerAverage(const arma::vec& input);\n\n    inline arma::vec centerAverage(const arma::subview_col<arma::mat::elem_type>& input);\n\n    inline arma::vec weightedAverage(const arma::vec& weightA, const arma::vec& weightB, const arma::vec& A, const arma::vec& B);\n\n    inline double weightedAverage(const double weightA, const double weightB, const double A, const double B);\n\n    inline bool isRelativeDifferenceWithinTolerance(\n            const double oldValue,\n            const double newValue,\n            const double tolerance);\n\n    inline bool areRelativeDifferencesWithinTolerance(\n            const arma::vec& oldValues,\n            const arma::vec& newValues,\n            const double tolerance);\n\n    inline double convertBurialToStandardDefinition(\n            const double burial,\n            const double innerDiameter,\n            const arma::rowvec& width);\n\n    inline double convertBurialToStandardDefinition(\n            const double burial,\n            const double innerDiameter,\n            const arma::subview_row<arma::mat::elem_type>& width);\n\n    inline arma::vec convertBurialToStandardDefinition(\n            const arma::vec& burial,\n            const arma::vec& innerDiameter,\n            const arma::colvec& width);\n\n    inline arma::vec convertBurialToStandardDefinition(\n            const arma::vec& burial,\n            const arma::vec& innerDiameter,\n            const arma::mat& width);\n\n    inline arma::vec smooth(const arma::vec& x, const double smoothness);\n\n    inline arma::vec smoothTransition(const arma::vec& firstPart, const arma::vec& lastPart, double smoothness = 1.0, const double timeStep = 60);\n\n    inline arma::vec createSmoothTransient(\n            const double initialValue,\n            const double finalValue,\n            const arma::uword n,\n            const double smoothness,\n            const arma::uword dt);\n\n    inline arma::vec findLogSpacedConcentricShellWidths(\n            const double innerRadius,\n            const double outerRadius,\n            const arma::uword nShells);\n\n    inline arma::cube loadCubeFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n    inline arma::mat loadMatFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n    inline arma::vec loadVecFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n}\n\ninline double utils::pow2(const double a)\n{\n    return a*a;\n}\n\ninline arma::vec utils::pow2(const arma::vec& a)\n{\n    return a%a;\n}\n\ninline double utils::pow3(const double a)\n{\n    return a*a*a;\n}\n\ninline double utils::pow4(const double a)\n{\n    return a*a*a*a;\n}\n\ninline double utils::pow5(const double a)\n{\n    return a*a*a*a*a;\n}\n\ninline double utils::pow6(const double a)\n{\n    return a*a*a*a*a*a;\n}\n\ninline arma::vec utils::cubeRoot(const arma::vec& input)\n{\n    arma::vec cubed = arma::zeros<arma::vec>(input.n_elem);\n    for (arma::uword i = 0; i < input.n_elem; i++)\n    {\n        cubed(i) = std::cbrt(input(i));\n    }\n    return cubed;\n}\n\narma::vec utils::centerDifference(const arma::vec& input)\n{\n    return input(arma::span(1, input.n_elem - 1)) - input(arma::span(0, input.n_elem - 2));\n}\n\narma::vec utils::centerDifference(const arma::subview_col<arma::mat::elem_type>& input)\n{\n    return input.rows(1, input.n_elem - 1) - input.rows(0, input.n_elem - 2);\n}\n\narma::vec utils::centerSum(const arma::vec& input)\n{\n    return input(arma::span(1, input.n_elem - 1)) + input(arma::span(0, input.n_elem - 2));\n}\n\narma::vec utils::centerSum(const arma::subview_col<arma::mat::elem_type>& input)\n{\n    return input.rows(1, input.n_elem - 1) + input.rows(0, input.n_elem - 2);\n}\n\narma::vec utils::centerAverage(const arma::vec& input)\n{\n    return centerSum(input)/2.0;\n}\n\narma::vec utils::centerAverage(const arma::subview_col<arma::mat::elem_type>& input)\n{\n    return centerSum(input)/2.0;\n}\n\ndouble utils::weightedAverage(const double weightA, const double weightB, const double A, const double B)\n{\n    if (std::round(weightA + weightB) == 0)\n    {\n        throw std::invalid_argument(\"utils::weightedAverage(): both weights are zero\");\n    }\n\n    return (A*weightA + B*weightB)/(weightA + weightB);\n}\n\narma::vec utils::weightedAverage(const arma::vec& weightA, const arma::vec& weightB, const arma::vec& A, const arma::vec& B)\n{\n    if (!arma::all((weightA + weightB) != 0))\n    {\n        throw std::invalid_argument(\"utils::weightedAverage(): both weights are zero\");\n    }\n\n    return (A % weightA + B % weightB)/(weightA + weightB);\n}\n\nbool utils::isRelativeDifferenceWithinTolerance(\n        const double oldValue,\n        const double newValue,\n        const double tolerance)\n{\n    double relativeDifference;\n    if (oldValue != 0)\n    {\n        relativeDifference = std::abs(newValue - oldValue)/std::abs(oldValue);\n    }\n    else if (newValue != 0)\n    {\n        relativeDifference = std::abs(newValue - oldValue)/std::abs(newValue);\n    }\n    else\n    {\n        // both values zero, difference also zero\n        return true;\n    }\n    return relativeDifference < tolerance;\n}\n\nbool utils::areRelativeDifferencesWithinTolerance(\n        const arma::vec& oldValues,\n        const arma::vec& newValues,\n        const double tolerance)\n{\n    for (arma::uword i = 0; i < oldValues.n_elem; i++)\n    {\n        double relativeDifference;\n        if (oldValues(i) != 0)\n        {\n            relativeDifference = std::abs(newValues(i) - oldValues(i))/std::abs(oldValues(i));\n        }\n        else if (newValues(i) != 0)\n        {\n            relativeDifference = std::abs(newValues(i) - oldValues(i))/std::abs(newValues(i));\n        }\n        else\n        {\n            // both values zero, difference also zero\n            continue;\n        }\n\n        if (relativeDifference > tolerance)\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\ndouble utils::convertBurialToStandardDefinition(\n        const double burial,\n        const double innerDiameter,\n        const arma::rowvec& width)\n{\n    return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\ndouble utils::convertBurialToStandardDefinition(\n        const double burial,\n        const double innerDiameter,\n        const arma::subview_row<arma::mat::elem_type>& width)\n{\n    return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\narma::vec utils::convertBurialToStandardDefinition(\n        const arma::vec& burial,\n        const arma::vec& innerDiameter,\n        const arma::colvec& width)\n{\n    return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\narma::vec utils::convertBurialToStandardDefinition(\n        const arma::vec& burial,\n        const arma::vec& innerDiameter,\n        const arma::mat& width)\n{\n    // burial depth is defined as \"from top of soil to center of pipe\" in our code,\n    // but given as distance from top of pipe to top of soil in thesis and in SIM\n    // this means that we have to add half a diameter + the width of all layers to convert\n    arma::vec convertedBurial = arma::zeros<arma::vec>(burial.n_elem);\n    for (arma::uword i = 0; i < burial.n_elem; i++)\n    {\n        convertedBurial(i) = convertBurialToStandardDefinition(burial(i), innerDiameter(i), width.row(i));\n    }\n\n    return convertedBurial;\n}\n\narma::vec utils::smooth(const arma::vec& x, const double smoothness)\n{\n    return 0.5 + 0.5*tanh((x - 0.5)/smoothness); // use x - 0.5 to get transition point to be between x = 0 and x = 1.0\n}\n\narma::vec utils::smoothTransition(\n        const arma::vec& firstPart,\n        const arma::vec& lastPart,\n        double smoothness,\n        const double timeStep)\n{\n    // smooths transition from firstPart to lastPart by using a tanh function\n    // idea from here: http://www.j-raedler.de/2010/10/smooth-transition-between-functions-with-tanh/\n\n    // the smoothing is time-independent (or time-depending, depending on how you look at it),\n    // meaning that changing the time step but using the same smoothness should result in the same smoothed curve,\n    // if you also scale the x-axis correctly (meaning: use time on the x-axis, not number of time steps)\n\n    // a smoothness of 1.0 will give a transition that uses approx. 10 minutes\n    // a smoothness of 5.0 will use around 30 minutes\n\n    arma::uword m = firstPart.n_elem;\n    arma::uword n = lastPart.n_elem;\n\n    // non-dimensionalizing smoothness\n    // default time step of 60 gives no scaling\n    smoothness *= 60.0/timeStep; // 60 is standard timestep\n\n    arma::vec f = arma::join_cols(\n                firstPart,\n                arma::zeros<arma::vec>(n) + firstPart(m-1) // repeat last element of firstPart\n                );\n    arma::vec g = arma::join_cols(\n                arma::zeros<arma::vec>(m) + lastPart(0), // repeat first element of lastPart\n                lastPart\n                );\n\n    arma::vec x = arma::linspace(-int(m)+1, n, m+n);  // !!! cast to int before subtracting, since m is unsigned int!!!\n    arma::vec s = smooth(x, smoothness);\n\n    arma::vec h = (1-s) % f + s % g;\n\n    return h;\n}\n\narma::vec utils::createSmoothTransient(\n        const double initialValue,\n        const double finalValue,\n        const arma::uword n,\n        const double smoothness,\n        const arma::uword dt)\n{\n    // transient will be centered in interval [0, n]\n    if (n % 2 != 0)\n    {\n        std::cout << \"n (\" << n << \") should be divisible by 2!\" << std::endl;\n    }\n    arma::vec a = arma::zeros<arma::vec>(n/2) + initialValue;\n    arma::vec b = arma::zeros<arma::vec>(n/2) + finalValue;\n    return smoothTransition(a, b, smoothness, dt);\n}\n\narma::vec utils::findLogSpacedConcentricShellWidths(\n        const double innerRadius,\n        const double outerRadius,\n        const arma::uword nShells)\n{\n    arma::vec logSpacedLayerRadii = arma::logspace(log10(innerRadius), log10(outerRadius), nShells+1);\n    arma::vec logSpacedLayerWidths = arma::zeros<arma::vec>(nShells);\n    for (arma::uword i = 0; i < nShells; i++)\n    {\n        logSpacedLayerWidths(i) = logSpacedLayerRadii(i+1) - logSpacedLayerRadii(i);\n    }\n\n    return logSpacedLayerWidths;\n}\n\narma::cube utils::loadCubeFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n    arma::cube c;\n    if (!c.load(filename, fileType))\n    {\n        throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n    }\n\n    return c;\n}\n\narma::mat utils::loadMatFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n    arma::mat m;\n    if (!m.load(filename, fileType))\n    {\n        throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n    }\n\n    return m;\n}\n\narma::vec utils::loadVecFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n    arma::vec v;\n    if (!v.load(filename, fileType))\n    {\n        throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n    }\n\n    return v;\n}\n", "meta": {"hexsha": "dbbfbc3790538fc7c8bd621cee02103bc11f736e", "size": 11633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/utilities.hpp", "max_stars_repo_name": "kewin1983/transient-pipeline-flow", "max_stars_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T03:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T03:30:07.000Z", "max_issues_repo_path": "src/utilities/utilities.hpp", "max_issues_repo_name": "kewin1983/transient-pipeline-flow", "max_issues_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_issues_repo_licenses": ["MIT"], "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/utilities.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["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.3733681462, "max_line_length": 146, "alphanum_fraction": 0.6436860655, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6873971989817607}}
{"text": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <boost/math/special_functions/beta.hpp> \n\nusing namespace std;\nusing namespace boost::math;\n\ninline double calcindex(double beta, const double a, const double nn)\n{\n  double p = double(a)/double(nn);\n  const double b = nn - a;\n  const double r = ((double)a/(double)nn);\n  const double rup = ((double)a+1.0)/((double)nn+1.0);\n  const double rdn = ((double)a)/((double)nn+1.0);\n  \n  for(int k = 0; k < 10; ++k)\n  {\n    if(p > 1 || p < r || p != p) \n    {\n      cerr << \"Warning! returning approximation for a = \" << a << \" and b = \" << b << endl;\n      return r;\n    }\n    const double safe = p/(1-beta);\n\n    const double lhs = r*(1-ibeta(a+1,b,p));\n    const double expmax = lhs + p*ibeta((double)a,b,p);  \n    //cout << expmax << \". lhs = \" << lhs << \". rhs = \" << p*ibeta((double)a,b,p) << endl;\n    const double risky = r+ beta/(1-beta)*expmax;\n\n    const double orig = risky - safe;\n    const double deriv = beta/(1-beta)*ibeta(a,b,p) - 1/(1-beta);\n    p -= orig/deriv;\n  }\n  return p;\n}\n\nvoid computeIndices(const int n, const double beta, vector<vector<double> >& indices)\n{\n  for(int nn = n-1; nn >= 2; --nn)\n  {\n    for(int a = 1; a <= nn-1; ++a)\n    {\n      double p = calcindex(beta, a, nn);\n      indices[a-1][nn-a-1] = p;\n    }\n  }\n}\n\nint main(int argc, const char** args)\n{\n  if(argc != 3)\n  {\n    cerr << \"need 2 arguments [n] [beta]\" << endl;\n    exit(1);\n  }\n  int n;\n  string strnum = args[1];\n  stringstream ss(strnum);\n  ss >> n;\n\n  double beta;\n  string betastr = args[2];\n  stringstream ssbeta(betastr);\n  ssbeta >> beta;\n  \n  //cout << calcindex(beta,292,292+1170) << endl;\n  //cout << \"finding indices for size limit [\" << n << \"] and step size [\" << step << \"]\" << endl; \n  vector<vector<double> > indices(n-1, vector<double>(n-1, 0));\n  computeIndices(n, beta, indices);\n\n  for(int i = 0; i < n-1; ++i)\n  {\n    for(int j=0; j < n-2; ++j)\n    {\n      cout << indices[i][j] << \", \"; \n    }\n    cout << indices[i][n-2] << endl;\n  }\n}\n\n", "meta": {"hexsha": "a8e60a00d030a761e89cc2706734878c5350908d", "size": 2044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ibetas.cpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/ibetas.cpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "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/ibetas.cpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 24.6265060241, "max_line_length": 99, "alphanum_fraction": 0.5557729941, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6873655788156859}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#ifndef FCPPT_MATH_VECTOR_LENGTH_HPP_INCLUDED\n#define FCPPT_MATH_VECTOR_LENGTH_HPP_INCLUDED\n\n#include <fcppt/cast/int_to_float.hpp>\n#include <fcppt/math/size_type.hpp>\n#include <fcppt/math/vector/length_square.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <cmath>\n#include <type_traits>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace fcppt\n{\nnamespace math\n{\nnamespace vector\n{\n\n/**\n\\brief Calculates the length of a vector\n\\ingroup fcpptmathvector\n\nThis is the Euclidean distance (or 2 norm) of the vector. There are two\nvariants of this function. One works only for floating point vectors (so you\ndon't have to specify the return type). The other one works for arbitrary\nvectors and uses a cast internally.\n\n\\note\nIf you want the length <em>squared</em>, use fcppt::math::vector::length_square\n\n\\see\nfcppt::math::vector::length_square\n\nExample:\n\n\\code\ntypedef\nfcppt::math::vector::static_<float,3>\nvector3f;\n\ntypedef\nfcppt::math::vector::static_<int,3>\nvector3i;\n\nvector3f vf(1.0f,2.0f,3.0f);\nvector3f vi(1,2,3);\n\n// No need to specify the return type here, it'll be float.\nfloat vf_length =\n\tfcppt::math::vector::length(\n\t\tvf);\n\n// It's not so clear here. So we specify \"float\" explicitly\nfloat vi_length =\n\tfcppt::math::vector::length<float>(\n\t\tvi);\n\n// Hopefully, this prints \"true\"\nstd::cout << (std::abs(vf_length - vi_length) < 0.001f);\n\\endcode\n*/\ntemplate<\n\ttypename T,\n\tfcppt::math::size_type N,\n\ttypename S\n>\ninline\ntypename\nstd::enable_if<\n\tstd::is_floating_point<\n\t\tT\n\t>::value,\n\tT\n>::type\nlength(\n\tfcppt::math::vector::object<\n\t\tT,\n\t\tN,\n\t\tS\n\t> const &_vec\n)\n{\n\treturn\n\t\tstd::sqrt(\n\t\t\tfcppt::math::vector::length_square(\n\t\t\t\t_vec\n\t\t\t)\n\t\t);\n}\n\n/**\n\\brief Calculates the length of a vector\n\\ingroup fcpptmathvector\n\nThis is the Euclidean distance (or 2 norm) of the vector. There are two\nvariants of this function. One works only for floating point vectors (so you\ndon't have to specify the return type). The other one works for arbitrary\nvectors and uses a cast internally.\n\n\\note\nIf you want the length <em>squared</em>, use fcppt::math::vector::length_square\n\n\\see\nfcppt::math::vector::length_square\n\nExample:\n\n\\code\ntypedef\nfcppt::math::vector::static_<float,3>\nvector3f;\n\ntypedef\nfcppt::math::vector::static_<int,3>\nvector3i;\n\nvector3f vf(1.0f,2.0f,3.0f);\nvector3f vi(1,2,3);\n\n// No need to specify the return type here, it'll be float.\nfloat vf_length =\n\tfcppt::math::vector::length(\n\t\tvf);\n\n// It's not so clear here. So we specify \"float\" explicitly\nfloat vi_length =\n\tfcppt::math::vector::length<float>(\n\t\tvi);\n\n// Hopefully, this prints \"true\"\nstd::cout << (std::abs(vf_length - vi_length) < 0.001f);\n\\endcode\n*/\ntemplate<\n\ttypename Dest,\n\ttypename T,\n\tfcppt::math::size_type N,\n\ttypename S\n>\ninline\ntypename\nstd::enable_if<\n\t!std::is_floating_point<\n\t\tT\n\t>::value,\n\tDest\n>::type\nlength(\n\tfcppt::math::vector::object<\n\t\tT,\n\t\tN,\n\t\tS\n\t> const &_vec\n)\n{\n\treturn\n\t\tstd::sqrt(\n\t\t\tfcppt::cast::int_to_float<\n\t\t\t\tDest\n\t\t\t>(\n\t\t\t\tfcppt::math::vector::length_square(\n\t\t\t\t\t_vec\n\t\t\t\t)\n\t\t\t)\n\t\t);\n}\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "a163ac8fdeb2fac1dec45b78205c8d0c10ae2a04", "size": 3345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fcppt/math/vector/length.hpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/fcppt/math/vector/length.hpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fcppt/math/vector/length.hpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3791208791, "max_line_length": 79, "alphanum_fraction": 0.711509716, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6873497134467386}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of calc_kernel_mat function.\n */\n#include \"num_collect/interp/kernel/calc_kernel_mat.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nTEST_CASE(\"num_collect::interp::kernel::calc_kernel_mat\") {\n    using num_collect::interp::kernel::calc_kernel_mat;\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::rbf_kernel;\n\n    SECTION(\"calculate\") {\n        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,\n            gaussian_rbf<double>>();\n        const auto list = std::vector<Eigen::Vector3d,\n            Eigen::aligned_allocator<Eigen::Vector3d>>{\n            Eigen::Vector3d(1.234, 2.345, 3.456),\n            Eigen::Vector3d(1.357, 2.468, 3.579)};\n\n        const Eigen::MatrixXd mat = calc_kernel_mat(kernel, list);\n\n        REQUIRE(mat.rows() == 2);\n        REQUIRE(mat.cols() == 2);\n\n        const double non_diagonal_elem =\n            std::exp(-(list[0] - list[1]).squaredNorm());\n        REQUIRE_THAT(mat(0, 0), Catch::Matchers::WithinRel(1.0));\n        REQUIRE_THAT(mat(0, 1), Catch::Matchers::WithinRel(non_diagonal_elem));\n        REQUIRE_THAT(mat(1, 0), Catch::Matchers::WithinRel(non_diagonal_elem));\n        REQUIRE_THAT(mat(1, 1), Catch::Matchers::WithinRel(1.0));\n    }\n}\n", "meta": {"hexsha": "10602aaaead8d1ede4ec1647f0e3c3d94f939c28", "size": 2181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/calc_kernel_mat_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/interp/kernel/calc_kernel_mat_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/interp/kernel/calc_kernel_mat_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2631578947, "max_line_length": 79, "alphanum_fraction": 0.6964695094, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6873497099461418}}
{"text": "#include \"patMixtureNormal.h\"\n#include \"patErrMiscError.h\"\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\n#include \"patDisplay.h\"\n#include \"patError.h\"\n#include <sstream>\n#include <vector>\nusing boost::math::normal;\n\npatMixtureNormal::patMixtureNormal(int& components, \n\tvector<double>& w,   \n\tvector<double>& mu,\n\tvector<double>& sigma, \n\tpatError *& err):\n\tm_components(components),m_w(w),m_mu(mu),m_sigma(sigma){\n\n\tbool flag = false;\t\t\n\tdouble total_w=0.0;\n\n\tif(m_mu.size()==m_components  && m_sigma.size()==m_components && m_w.size()==m_components){\n\t\tfor(vector<double>::const_iterator iter = m_w.begin();iter!=m_w.end();++iter){\n\t\t\ttotal_w+=*iter;\n\t\t}\n\n\t\tif (total_w< 1.0000001 && total_w > 0.999999){\n\t\t\tflag= true;\n\t\t}\n\t}\n\n\tif(flag !=true){\n\t\tstringstream str;\n\t\tstr << \"Wrong distribution\" <<total_w;\n\t\terr = new patErrMiscError(str.str());\n\t\tWARNING(err->describe());\n\t}\n}\n\ndouble patMixtureNormal::pdf(const double& value) const{\n\n\tdouble proba = 0.0;\n\tfor (int i = 0; i < m_components;++i) {\n\n\tboost::math::normal s(m_mu[i],m_sigma[i]);\n\t\tproba += m_w[i]\n\t\t\t\t* boost::math::pdf(s,value ) ;\n\t}\n\treturn proba;\n}\n", "meta": {"hexsha": "dc3c09fd77191a152f9267873d82e444334dc0ab", "size": 1149, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Math/patMixtureNormal.cc", "max_stars_repo_name": "godosou/smaroute", "max_stars_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T16:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T17:58:53.000Z", "max_issues_repo_path": "src/Math/patMixtureNormal.cc", "max_issues_repo_name": "godosou/smaroute", "max_issues_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_issues_repo_licenses": ["MIT"], "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/patMixtureNormal.cc", "max_forks_repo_name": "godosou/smaroute", "max_forks_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T16:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-04T16:13:16.000Z", "avg_line_length": 23.4489795918, "max_line_length": 92, "alphanum_fraction": 0.6736292428, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6873451080738194}}
{"text": "/**\r\n *  @file    FEMesh.hpp\r\n *  @brief   The finite element mesh for a line.\r\n *  @author  Francois Roy\r\n *  @date    01/06/2020\r\n */\r\n#ifndef FEMESH_H\r\n#define FEMESH_H\r\n\r\n#include <stdexcept>\r\n#include <vector>\r\n#include <Eigen/Core>\r\n#include \"spdlog/spdlog.h\"\r\n#include \"utils/Utils.hpp\"\r\n\r\nnamespace numerical {\r\n\r\nnamespace fem {\r\n\r\n/**\r\n* Holds data structures for a uniform mesh on a line in space, plus a \r\n* uniform mesh in time.\r\n* \r\n* The finite element mesh has n elements and an associated polynomial of \r\n* degree d.\r\n*\r\n* @param lengths A 2-lists of min and max coordinates in the spatial 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 Number of cells in the spatial direction.\r\n* @param d The polynomial degree, default = 1.\r\n*/\r\ntemplate <typename T>\r\nclass FEMesh {  // TODO inherit form common/Mesh\r\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\r\nprivate:\r\n\tconst std::vector<T> m_lengths;\r\n\tconst T m_t0, m_tend;\r\n    const int m_nt, m_nx, m_d;\r\n\tT m_dt, m_dx;\r\n\tVec m_x;\r\n\tVec m_t;\r\npublic:\r\n\tFEMesh(const std::vector<T>& lengths, T t0, T tend, int nx, int nt, \r\n        int d=1) \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      m_d(d)\r\n\t{\r\n      \tif(m_lengths.size() != 2){\r\n      \t\tthrow std::invalid_argument(\"length is not a 2-list.\");\r\n       \t}\r\n       \tm_dx = (m_lengths[1] - m_lengths[0])/ T(m_nx);\r\n        if(m_dx <= 0){\r\n            throw std::invalid_argument(\"not a valid interval.\");\r\n        }\r\n        m_dt = m_tend / T(m_nt);\r\n        m_x = Vec::LinSpaced(m_nx + 1, m_lengths[0], m_lengths[1]);\r\n        m_t = Vec::LinSpaced(m_nt + 1, m_t0, m_tend);\r\n\t}\r\n    /**\r\n    *  Local vertex to global vertex mapping (cells).\r\n    */\r\n    std::vector<std::vector<int>> cells(){\r\n        std::vector<std::vector<int>> out;\r\n        for(int i=0; i<m_nx; i++){\r\n            out.push_back({i, i+1});\r\n        }\r\n        return out;\r\n    }\r\n    /**\r\n    *  Local to global degree of freedom mapping (dof_map).\r\n    */\r\n    std::vector<std::vector<int>> dof_map(){\r\n        std::vector<std::vector<int>> out;\r\n        std::vector<int> m;\r\n        if(m_d == 0){\r\n            for(int i; i<m_nx; i++){\r\n                out.push_back({i});\r\n            }\r\n        } else {\r\n            for(int i; i<m_nx; i++){\r\n                for(int j; j<m_d+1; j++){\r\n                    m.push_back(i*m_d + j);\r\n                }\r\n                out.push_back(m);\r\n            }\r\n        }\r\n        return out;\r\n    }\r\n    /**\r\n    * @return the constant time increment.\r\n    */\r\n    T dt() {\r\n        return m_dt;\r\n    }\r\n    /**\r\n    * @return the space increment.\r\n    */\r\n    T dx() {\r\n        return m_dx;\r\n    }\r\n    /**\r\n    *  The indices of the nodes on the left boundary.\r\n    *\r\n    * @return The indices of the nodes on the left boundary. \r\n    */\r\n    std::vector<int> left(){\r\n        return {0};\r\n    }\r\n    /**\r\n    *  The indices of the nodes on the right boundary.\r\n    *\r\n    * @return The indices of the nodes on the right boundary, \r\n    */\r\n    std::vector<int> right(){\r\n        std::vector<int> out = left();\r\n        for(int& i : out){\r\n            i += m_nx;\r\n        }\r\n    \treturn out;\r\n    }\r\n    /**\r\n    * @return the time list.\r\n    */\r\n    Vec t() {\r\n        return m_t;\r\n    }\r\n\t/**\r\n\t* @return the list of coordinates.\r\n\t*/\r\n\tVec vertices() {\r\n\t\treturn m_x;\r\n\t}\r\n};\r\n\r\n}  // namespace fem\r\n\r\n} // namespace numerical\r\n\r\n#endif  // MESH_H\r\n", "meta": {"hexsha": "eb40c1d9701f749f71e610fac66d2bd836c92886", "size": 3550, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fem/FEMesh.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": "numerical/fem/FEMesh.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": "numerical/fem/FEMesh.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": 24.3150684932, "max_line_length": 80, "alphanum_fraction": 0.5216901408, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.6872600020386364}}
{"text": "#include \"../misc_math.h\"\n#include \"../string_utils.h\"\n#include <boost/math/special_functions/bessel.hpp>\n#include <algorithm>\n#include <stdexcept>\n\n\n\nusing namespace std;\nnamespace coela {\nnamespace misc_math {\n\n\n\ndouble linearly_interpolate(double x1, double y1, double x2, double y2, double x_between)\n{\n//    cerr<<\"Inputs: \"<<endl;\n//    cerr<<\"x1, y1: \"<< x1 <<\",\"<<y1<<endl;\n//    cerr<<\"x2, y2: \"<< x2 <<\",\"<<y2<<endl;\n//    cerr<<\"xinterp: \"<< x_between<<endl;\n\n    assert(std::min(x1,x2) - err_margin <= x_between\n           && std::max(x1,x2) + err_margin >= x_between);\n\n    //Flat line case,  pick arbitrary mid point.\n    if (x1==x2) { return (y1+y2)/2.0; }\n\n    double grad = (y2 - y1) / (x2 - x1);\n    return y1 + grad*(x_between-x1);\n}\n\ndouble dimensionless_airy_function(double x, double ratio)\n{\n    //ratio = ratio of DIAMETERS ( or equiv, ratio of radii.) (not area)\n    double j = 2.0 * (boost::math::cyl_bessel_j(1, x) -  ratio*boost::math::cyl_bessel_j(1,\n                      ratio*x)) / (x*(1.0 - ratio*ratio)) ;     // 2[ J(x)/x - f*f*J(fx)/fx ] / (1-f*f)\n    return j*j;\n}\n\ndouble airy_function(double angle, double wavelength, double aperture_diameter,\n                     double obscuration_diameter)\n{\n    double f = obscuration_diameter / aperture_diameter;  //fractional obscuration\n    double x = M_PI * aperture_diameter * (angle) /\n               wavelength; //rescaled distance from centre\n//            double x = M_PI * aperture_diameter * sin(angle) / wavelength; //better for large angles? But irrelevant here\n    //avoid divide by 0 - return the value \"in the limit\" as x-->0:\n    if (x==0) { x=1e-9; }\n    //simple case: I = ( 2 J1[x] / x )^2\n//             double j = 2.0 * ( boost::math::cyl_bessel_j(1, x) -  f*boost::math::cyl_bessel_j(1, f*x) ) / (x*(1.0 - f*f )  );  // 2( J(x) - fJ(fx) ) / x(1-f*f)\n//            return j*j;\n    return dimensionless_airy_function(x, f);\n}\n\ndouble airy_fwhm_in_rads(double wavelength, double aperture_diameter,\n                         double obscuration_diameter)\n{\n    //Monotonic between peak and first minima- use bisection and linear interpolation NB first minima not at 1.22 if obscuration !=0, but will do for a first approximation\n    double lower_limit(0.0), upper_limit(1.22*wavelength/aperture_diameter), eps(1e-5),\n           delta(1.0);\n    double hwhm_angle(upper_limit/2.0);\n    while (fabs(delta)>eps) {\n        delta = airy_function(hwhm_angle, wavelength, aperture_diameter,\n                              obscuration_diameter) -0.5;\n        if (delta >0) {\n            //too close to origin\n            lower_limit = hwhm_angle;\n        } else { upper_limit = hwhm_angle; }\n        hwhm_angle = (upper_limit + lower_limit) /2.0;\n    }\n    return hwhm_angle*2.0;\n}\n\ndouble gaussian_1d_function(double radius, double peak_value, double sigma)\n{\n    if (sigma!=0) { return peak_value*exp(-1.0*radius*radius/(2.0*sigma*sigma)); }\n    else if (radius<1e-7) { return peak_value; }\n    return 0;\n}\n\ndouble moffat_function(double radius, double sigma, double beta)\n{\n    assert(sigma!=0);\n    double scale_length = radius/sigma;\n    return pow((1+scale_length*scale_length), -1.0*beta);\n}\n\ndouble moffat_fwhm(double sigma, double beta)\n{\n    return 2.0*sigma* sqrt(pow(2.0, 1.0/beta) - 1);\n}\n\ndouble moffat_sigma(double fwhm, double beta)\n{\n    double radius_of_half_maximum=fwhm/2.0;\n    return radius_of_half_maximum / sqrt((pow(2.0, 1.0/beta) - 1.0));\n}\n\nunsigned long integer_factorial(int n)\n{\n    assert(n<20);\n    if (n==0) { return 1ul; }\n    return n*integer_factorial(n-1);\n}\n\n\n///Sidesteps the integer limits, but as such is not exact. Used for calculating PDFs for an EMCCD (which are already approximations anyway).\ndouble approx_factorial_double(double number)\n{\n    if (number <= 1.0) { return 1.0; }\n    return number * approx_factorial_double(number - 1.0);\n}\n\ndouble integer_power(double x, int n)\n{\n    if (n==0) { return 1.0; }\n    if (n<0) { return 1.0/integer_power(x,-1*n); }\n\n    double result=x;\n    while (n!=1) {\n        result*=x;\n        n--;\n    }\n    return result;\n}\n\npair<double,double> fit_1d_parabola_to_find_local_maxima(double x0,\n        double y_xm1, double y_x0, double y_xp1)\n{\n    //nb should have been fed a local maximum, so:\n//            using string_utils::ftoa;\n//            if (!(y_x0 > y_xm1 && y_x0 > y_xp1))\n//                throw std::runtime_error(\"Fit parabola: Not a local max: \"+ftoa(y_x0) +\" less than \"+ftoa(y_xm1)+\"or\"+ftoa(y_xp1));\n//                ;\n    assert(y_x0 >= y_xm1 && y_x0 >= y_xp1);\n    pair<double,double> xmax_ymax;\n//See Lisa Poyneer 2003, \"scene-based SHWFS\" for a nicely formatted version... but it's just very simple math.\n    double b = -0.5*(y_xm1 - y_xp1);\n    double two_a =(y_xm1 + y_xp1 -2*y_x0);\n    //c = y_x0\n\n//            xmax_ymax.first= x0 + ( 0.5*(y_xm1 - y_xp1)  )/(y_xm1 + y_xp1 -2*y_x0);\n    xmax_ymax.first= x0 - b/two_a;\n    xmax_ymax.second=y_x0 - b*b/(2*two_a);\n\n    return xmax_ymax;\n}\n\ndouble bilinear_interpolate(double x, double y,\n                            double x0, double y0,\n                            double x1, double y1,\n                            double f_x0_y0, double f_x1_y0, double f_x0_y1, double f_x1_y1)\n{\n    double x_frac(x-x0 / (x1-x0)), y_frac(y-y0 / (y1-y0));\n\n    return f_x0_y0 *(1 - x_frac)*(1 - y_frac)\n           + f_x1_y0 *(x_frac)*(1 - y_frac)\n           + f_x0_y1 *(1-x_frac)*(y_frac)\n           + f_x1_y1 *(x_frac)*(y_frac)    ;\n}\n\n}\n}\n", "meta": {"hexsha": "f67d282e81275c0ec70500318d4bc37510f6cf6f", "size": 5472, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_utility/src/implementation/misc_math.cc", "max_stars_repo_name": "timstaley/coelacanth", "max_stars_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:08:45.000Z", "max_issues_repo_path": "coela_utility/src/implementation/misc_math.cc", "max_issues_repo_name": "timstaley/coelacanth", "max_issues_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "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": "coela_utility/src/implementation/misc_math.cc", "max_forks_repo_name": "timstaley/coelacanth", "max_forks_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "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.3658536585, "max_line_length": 171, "alphanum_fraction": 0.6120248538, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.687213934337948}}
{"text": "//\n// Created by jennings on 2018/10/26.\n//\n\n#ifndef CSCI5570_LOGITSTIC_REGRESSION_HPP\n#define CSCI5570_LOGITSTIC_REGRESSION_HPP\n\n#include \"base/magic.hpp\"\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n#include \"lib/svm_sample.hpp\"\n\nusing namespace Eigen;\nusing namespace csci5570;\nusing DataStore = std::vector<lib::SVMSample>;\n\ntemplate <typename T>\nclass LogisticRegression {\npublic:\n  LogisticRegression(DataStore* data_store, float learning_rate=0.001)\n    : data_store_(data_store), learning_rate_(learning_rate) {\n    // initialize theta\n    for(auto& row : (*data_store_)) {\n      for(auto& col : row.x_) {\n        theta_[col.first] = 0.0;\n        grad_[col.first] = 0.0;\n      }\n    }\n  }\n\n  double predict(lib::SVMSample sample) {\n    double z = 0;\n    for(auto& col : sample.x_) {\n      Key key = col.first;\n      auto x = col.second;\n      z += x * theta_[key];\n    }\n    return 1.0 / (1 + std::exp(-z));\n  }\n\n  double get_loss() {\n    double loss = 0;\n    for (auto& row : (*data_store_)) {\n      int y = row.y_ <= 0 ? 0 : 1;\n      double pred = predict(row);\n      loss += (-1 * y * std::log(pred) - (1 - y) * std::log(1 - pred));\n    }\n    return loss/data_store_->size();\n  }\n\n  void compute_gradient(std::vector<T>& grad) {\n    for(auto& g : grad_) {\n      g.second = 0.0;\n    }\n    for (auto& row : (*data_store_)) {\n      // NOTICE that row.y_ maybe +1/-1\n      auto y = row.y_ <= 0 ? 0 : 1;\n      auto z = 0;\n      for(auto& col : row.x_) {\n        Key key = col.first;\n        auto x = col.second;\n        z += x * theta_[key];\n      }\n      auto g = 1 / (1 + std::exp(-z));\n      for(auto& col : row.x_) {\n        Key key = col.first;\n        auto x = col.second;\n        grad_[key] += -learning_rate_ * x * (g - y);\n      }\n    }\n    for(auto& g : grad_) {\n      grad.push_back(g.second / data_store_->size());\n    }\n//    Matrix<T, Dynamic, 1> Z = (*X_) * theta_;\n//    Matrix<T, Dynamic, 1> G = Z.unaryExpr([](T z){\n//      return 1 / (1 + std::exp(-z));\n//    });\n//    grad = -learning_rate_ * X_->transpose() * (G - (*Y_));\n  }\n\n  void update_theta(const std::vector<Key>& keys, const std::vector<T>& vals) {\n    uint32_t size = keys.size();\n    for(uint32_t i = 0; i < size; i++) {\n      if (theta_.find(keys[i]) == theta_.end()) {continue;}\n      theta_[keys[i]] = vals[i];\n    }\n  }\n\n  float test_acc() {\n    float correct = 0;\n    uint32_t total = 0;\n    for (auto& row : (*data_store_)) {\n      // NOTICE that row.y_ maybe +1/-1\n      auto y = row.y_ <= 0 ? 0 : 1;\n      auto z = 0;\n      for(auto& col : row.x_) {\n        Key key = col.first;\n        auto x = col.second;\n        z += x * theta_[key];\n      }\n      auto g = 1 / (1 + std::exp(-z));\n      auto y_pred = g <= 0.5 ? 0 : 1;\n      if (y_pred == y) {correct++;}\n      total++;\n    }\n    if (total == 0) {\n      return -1;\n    }\n    return correct / total;\n  }\n\n  void get_keys(std::vector<Key>& keys) {\n    for(auto& kv : theta_) {\n      keys.push_back(kv.first);\n    }\n  }\n\nprivate:\n  DataStore* data_store_;\n  std::map<Key, T> theta_;\n  std::map<Key, T> grad_;\n  float learning_rate_;\n};\n\n\n#endif //CSCI5570_LOGITSTIC_REGRESSION_HPP\n", "meta": {"hexsha": "5d1e3f93990ea8ca21aeeefcd6f458c8fac35121", "size": 3142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/logitstic_regression.hpp", "max_stars_repo_name": "samjjx/csci5570", "max_stars_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-03T00:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-03T00:44:21.000Z", "max_issues_repo_path": "app/logitstic_regression.hpp", "max_issues_repo_name": "samjjx/csci5570", "max_issues_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "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": "app/logitstic_regression.hpp", "max_forks_repo_name": "samjjx/csci5570", "max_forks_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T16:09:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T09:46:39.000Z", "avg_line_length": 24.546875, "max_line_length": 79, "alphanum_fraction": 0.5432845321, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6872139274147401}}
{"text": "#include \"EpipolarConsistency.h\"\n\n#include <Eigen/Dense>\n\nnamespace EpipolarConsistency\n{\n\tusing Geometry::Pi;\n\n\t/// 2DO Should use SVD from Geometry module to reduce compile time.\n\tGeometry::RP3Point estimateIsoCenter(const std::vector<ProjectionMatrix> &Ps)\n\t{\n\t\tint n=(int)Ps.size();\n\t\tEigen::Matrix3d A=Eigen::Vector3d(n,n,n).asDiagonal();\n\t\tEigen::Vector3d b(0,0,0);\n\t\t// Distance as norm of a point projected to plane orthogonal to view direction through the origin.\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tconst ProjectionMatrix &P(Ps[i]);\n\t\t\t// Center of projection\n\t\t\tEigen::Vector3d C=Geometry::getCameraCenter(P).block<3,1>(0,0);\n\t\t\t// View direction\n\t\t\tEigen::Vector3d V=P.block<1,3>(2,0).normalized();\n\t\t\t// O=id-v*v^T is projection in direction v.\n\t\t\tA-=V*V.transpose();\n\t\t\t// For points x on the principal ray it holds that O*x=O*C\n\t\t\tb+=C-V*(V.transpose()*C);\n\t\t}\n\t\t// Solve by SVD\n\t\tEigen::JacobiSVD<Eigen::Matrix3d> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tGeometry::RP3Point O(0,0,0,1);\n\t\tO.block<3,1>(0,0)=svd.solve(b);\n\t\treturn O;\n\t}\n\n\tdouble estimateObjectRadius(const ProjectionMatrix& P, int n_u, int n_v)\n\t{\n\t\tusing namespace Geometry;\n\t\tusing namespace std;\n\t\t// Get the focal lengths in pixels.\n\t\tauto   alphas=getCameraFocalLengthPx(P);\n\t\t// Compute field of view (use maximum of u and v).\n\t\tdouble fov   =max(abs(atan(0.5*n_u/alphas.first)), abs(atan(0.5*n_v/alphas.second)));\n\t\t// The source to iso-center distance.\n\t\tdouble sid   =getCameraCenter(P).head(3).norm();\n\t\t// Return approximate radius of an circumscribed  sphere.\n\t\treturn sin(fov)*sid;\n\t}\n\n\tstd::pair<double,double> estimateAngularRange(const RP3Line& B, double object_radius_mm)\n\t{\n\t\t// Distance of baseline to origin\n\t\tdouble baseline_dist=Geometry::pluecker_distance_to_origin(B);\n\t\t// If the baseline intersects the object, ECC is not well-defined. We return a half circle anyway.\n\t\tif (baseline_dist<=object_radius_mm)\n\t\t\treturn std::make_pair(-0.5*Pi,0.5*Pi);\n\t\t// Else, find angle of plane which touches the sphere\n\t\tdouble kappa_max=std::abs(std::asin(object_radius_mm/baseline_dist));\n\t\treturn std::make_pair(-kappa_max,kappa_max);\n\t}\n\n\tdouble estimateAngularStep(const ProjectionMatrix& P0, const ProjectionMatrix& P1, int n_u, int n_v)\n\t{\n\t\tusing namespace Geometry;\n\t\tdouble radius_mm=std::max(estimateObjectRadius(P0,n_u,n_v),estimateObjectRadius(P1,n_u,n_v));\n\t\tauto baseline=join_pluecker(getCameraCenter(P0),getCameraCenter(P1));\n\t\tauto range_kappa=estimateAngularRange(baseline,radius_mm);\n\t\treturn 2.0*(range_kappa.second-range_kappa.first)/std::sqrt(n_u*n_u+n_v*n_v);\n\t}\n\n\tMetric& Metric::setObjectRadius(double radius_mm)\n\t{\n\t\tobject_radius_mm=radius_mm;\n\t\treturn *this;\n\t}\n\n\tdouble Metric::getObjectRadius() const\n\t{\n\t\tif (object_radius_mm>0)\n\t\t\treturn object_radius_mm;\n\t\tif (getProjectionMatrices().empty())\n\t\t\treturn 0;\n\t\tauto P=getProjectionMatrices().front();\n\t\treturn estimateObjectRadius(P,n_u,n_v);\n\t}\n\n\tMetric& Metric::setEpipolarPlaneStep(double dkappa_rad) {\n\t\tdkappa=dkappa_rad;\n\t\treturn *this;\n\t}\n\n\tMetric& Metric::setProjectionMatrices(const std::vector<ProjectionMatrix>& _Ps)\n\t{\n\t\tPs=_Ps;\n\t\treturn *this;\n\t}\n\n\tconst std::vector<ProjectionMatrix>&Metric:: getProjectionMatrices() const\n\t{\n\t\treturn Ps;\n\t}\n\n\tMetric::Metric() : object_radius_mm(0), dkappa(0), n_u(0), n_v(0) {}\n\n\tMetric::~Metric() {}\n\n} // namespace EpipolarConsistency\n", "meta": {"hexsha": "7b5299abdb736956b8d0cbdfd0933e7eaecf99d5", "size": 3368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_stars_repo_name": "mareikethies/EpipolarConsistency", "max_stars_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T16:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T03:03:00.000Z", "max_issues_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_issues_repo_name": "mareikethies/EpipolarConsistency", "max_issues_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T07:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-14T07:48:55.000Z", "max_forks_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_forks_repo_name": "mareikethies/EpipolarConsistency", "max_forks_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:20:47.000Z", "avg_line_length": 31.476635514, "max_line_length": 101, "alphanum_fraction": 0.7211995249, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.687184390196371}}
{"text": "/*--\r\n  Open3DMotion \r\n  Copyright (c) 2004-2012.\r\n  All rights reserved.\r\n  See LICENSE.txt for more information.\r\n--*/\r\n\r\n#include <math.h>\r\n#include <stdlib.h>\r\n#include \"Open3DMotion/Maths/LinearSolve3.h\"\r\n\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\nextern \"C\"\r\n{\r\n#include <f2clibs/f2c.h>\r\n#include <clapack.h>\r\n}\r\n#else\r\n#include <Eigen/Dense>\r\n#endif\r\n\r\nnamespace Open3DMotion\r\n{\r\n\r\n\t// Linear alegebra helper function: calls LAPACK routine\r\n\t// Solves linear least squares in 3D\r\n\tbool LinearSolve3(float* x, const float* A, const float* b, int numrows, float* rms /*=NULL*/, float rcond /*=0.001*/)\r\n\t{\t\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\n\r\n\t\tint i, j;\r\n\r\n\t\t// transpose as required for lapack\r\n\t\tfloat* AT = new float[3*numrows];\r\n\t\tfor (i = 0; i < 3; i++)\r\n\t\t\tfor (j = 0; j < numrows; j++)\r\n\t\t\t\tAT[i*numrows+j] = A[3*j + i];\r\n\r\n\t\t// copy input vector\r\n\t\tfloat* y = new float[numrows];\r\n\t\tfor (i = 0; i < numrows; i++)\r\n\t\t\ty[i] = b[i];\r\n\r\n\t\t// params required for lapack\r\n\t\tlong mrows = numrows;\r\n\t\tlong ncols = 3;\r\n\t\tlong nrhs = 1;\r\n\t\tlong lda = numrows;\r\n\t\tlong ldb = numrows;\r\n\t\tlong jpvt[3] = { 0, 0, 0 };\r\n\t\tlong rank = 0;\r\n\t\tlong info = 0;\r\n\r\n\t\t// call lapack function to query work size\r\n\t\tlong lwork_query = -1;\r\n\t\tfloat opt_work_size = 1.0f;\r\n\t\tsgelsy_(&mrows, &ncols, &nrhs, AT, &lda, y, &ldb, jpvt, &rcond, &rank, &opt_work_size, &lwork_query, &info);\r\n\r\n\t\t// return if any probs with params\r\n\t\tif (info != 0)\r\n\t\t\treturn false;\r\n\r\n\t\t// get opt work size and call for real\r\n\t\tlong lwork_opt = (long)opt_work_size;\r\n\t\tfloat* work = new float[lwork_opt];\r\n\t\tsgelsy_(&mrows, &ncols, &nrhs, AT, &lda, y, &ldb, jpvt, &rcond, &rank, work, &lwork_opt, &info);\r\n\r\n\t\t// copy result\r\n\t\tfor (i = 0; i < 3; i++)\r\n\t\t\tx[i] = y[i];\r\n\r\n\t\t// done with temp data\r\n\t\tdelete [] work;\r\n\t\tdelete [] AT;\r\n\t\tdelete [] y;\r\n\r\n\t\t// must have params ok (info = 0) and full rank (3)\r\n\t\tif (info != 0 || rank != 3)\r\n\t\t\treturn false;\r\n\r\n\t\t// if requested, compute RMS\r\n\t\tif (rms)\r\n\t\t{\r\n\t\t\tfloat sumsq(0.0f);\r\n\t\t\tfor (i = 0; i < numrows; i++)\r\n\t\t\t{\r\n\t\t\t\tfloat ax(0.0f);\r\n\t\t\t\tfor (j = 0; j < 3; j++)\r\n\t\t\t\t\tax += A[3*i+j] * x[j];\r\n\t\t\t\tfloat diff = ax - b[i];\r\n\t\t\t\tsumsq += diff*diff;\r\n\t\t\t}\r\n\t\t\t*rms = sqrt(sumsq / numrows);\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\r\n#else\r\n\r\n\t\t// Map to Eigen objects\r\n\t\tEigen::Map< const Eigen::Matrix<float, Eigen::Dynamic, 3, Eigen::RowMajor> > C(A, numrows, 3);\r\n    Eigen::Map< const Eigen::Matrix<float, Eigen::Dynamic, 1> > d(b, numrows, 1);\r\n    Eigen::Map< Eigen::Matrix<float, 3, 1> > y(x, 3, 1);\r\n\r\n\t\t// compute CTC ( = ATA )\r\n\t\tEigen::MatrixXf CT = C.transpose();\r\n\t\tEigen::Matrix3f CTC = CT * C;\r\n\r\n\t\t// perform check on reciprocal condition number\tto mimic LAPACK behaviour\r\n\t\tEigen::Vector3f e = Eigen::EigenSolver<Eigen::Matrix3f> (CTC).eigenvalues().real();\r\n\t\tfloat CTC_rcond = e.minCoeff() / e.maxCoeff();\r\n\t\tif (CTC_rcond < rcond)\r\n\t\t\treturn false;\t\t\r\n\r\n\t\t// compute CTd = ATb\r\n\t\tEigen::Vector3f CTd = CT * d;\r\n\r\n\t\t// solve\r\n\t\ty = CTC.ldlt().solve(CTd);\r\n\r\n\t\t// compute rms error if requested\r\n\t\tif (rms)\r\n\t\t\t*rms = sqrt((C*y - d).squaredNorm() / numrows);\r\n\r\n\t\treturn true;\r\n\r\n#endif\r\n\t}\r\n\r\n}\r\n", "meta": {"hexsha": "52b1755fe8bd023b3f758d50df594d9f175136e3", "size": 3128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_stars_repo_name": "mitkof6/BTKCore", "max_stars_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_stars_repo_licenses": ["Barr", "Unlicense"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:35:03.000Z", "max_issues_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_issues_repo_name": "mitkof6/BTKCore", "max_issues_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_issues_repo_licenses": ["Barr", "Unlicense"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-06-23T20:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-17T17:08:57.000Z", "max_forks_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_forks_repo_name": "mitkof6/BTKCore", "max_forks_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_forks_repo_licenses": ["Barr", "Unlicense"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T11:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T20:37:04.000Z", "avg_line_length": 23.8778625954, "max_line_length": 120, "alphanum_fraction": 0.5875959079, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6871678187617931}}
{"text": "/*\n * Copyright (C) 2021 Open Source Robotics Foundation\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\n#ifndef IGNITION_MATH_EIGEN3_UTIL_HH_\n#define IGNITION_MATH_EIGEN3_UTIL_HH_\n\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\n#include <ignition/math/AxisAlignedBox.hh>\n#include <ignition/math/Matrix3.hh>\n#include <ignition/math/OrientedBox.hh>\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Quaternion.hh>\n#include <ignition/math/Vector3.hh>\n#include <ignition/math/eigen3/Conversions.hh>\n\nnamespace ignition\n{\n  namespace math\n  {\n    namespace eigen3\n    {\n      /// \\brief Get covariance matrix from a set of 3d vertices\n      /// https://github.com/isl-org/Open3D/blob/76c2baf9debd460900f056a9b51e9a80de9c0e64/cpp/open3d/utility/Eigen.cpp#L305\n      /// \\param[in] _vertices a vector of 3d vertices\n      /// \\return Covariance matrix\n      inline Eigen::Matrix3d covarianceMatrix(\n        const std::vector<math::Vector3d> &_vertices)\n      {\n        if (_vertices.empty())\n          return Eigen::Matrix3d::Identity();\n\n        Eigen::Matrix<double, 9, 1> cumulants;\n        cumulants.setZero();\n        for (const auto &vertex : _vertices)\n        {\n          const Eigen::Vector3d &point = math::eigen3::convert(vertex);\n          cumulants(0) += point(0);\n          cumulants(1) += point(1);\n          cumulants(2) += point(2);\n          cumulants(3) += point(0) * point(0);\n          cumulants(4) += point(0) * point(1);\n          cumulants(5) += point(0) * point(2);\n          cumulants(6) += point(1) * point(1);\n          cumulants(7) += point(1) * point(2);\n          cumulants(8) += point(2) * point(2);\n        }\n\n        Eigen::Matrix3d covariance;\n\n        cumulants /= static_cast<double>(_vertices.size());\n\n        covariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n        covariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n        covariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n        covariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n        covariance(1, 0) = covariance(0, 1);\n        covariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n        covariance(2, 0) = covariance(0, 2);\n        covariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n        covariance(2, 1) = covariance(1, 2);\n        return covariance;\n      }\n\n      /// \\brief Get the oriented 3d bounding box of a set of 3d\n      /// vertices using PCA\n      /// http://codextechnicanum.blogspot.com/2015/04/find-minimum-oriented-bounding-box-of.html\n      /// \\param[in] _vertices a vector of 3d vertices\n      /// \\return Oriented 3D box\n      inline ignition::math::OrientedBoxd verticesToOrientedBox(\n        const std::vector<math::Vector3d> &_vertices)\n      {\n        math::OrientedBoxd box;\n\n        // Return an empty box if there are no vertices\n        if (_vertices.empty())\n          return box;\n\n        math::Vector3d mean;\n        for (const auto &point : _vertices)\n          mean += point;\n        mean /= static_cast<double>(_vertices.size());\n\n        Eigen::Vector3d centroid = math::eigen3::convert(mean);\n        Eigen::Matrix3d covariance = covarianceMatrix(_vertices);\n\n        // Eigen Vectors\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>\n          eigenSolver(covariance, Eigen::ComputeEigenvectors);\n        Eigen::Matrix3d eigenVectorsPCA = eigenSolver.eigenvectors();\n\n        // This line is necessary for proper orientation in some cases.\n        // The numbers come out the same without it, but the signs are\n        // different and the box doesn't get correctly oriented in some cases.\n        eigenVectorsPCA.col(2) =\n          eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1));\n\n        // Transform the original cloud to the origin where the principal\n        // components correspond to the axes.\n        Eigen::Matrix4d projectionTransform(Eigen::Matrix4d::Identity());\n        projectionTransform.block<3, 3>(0, 0) = eigenVectorsPCA.transpose();\n        projectionTransform.block<3, 1>(0, 3) =\n          -1.0f * (projectionTransform.block<3, 3>(0, 0) * centroid);\n\n        Eigen::Vector3d minPoint(INF_I32, INF_I32, INF_I32);\n        Eigen::Vector3d maxPoint(-INF_I32, -INF_I32, -INF_I32);\n\n        // Get the minimum and maximum points of the transformed cloud.\n        for (const auto &point : _vertices)\n        {\n          Eigen::Vector4d pt(0, 0, 0, 1);\n          pt.head<3>() = math::eigen3::convert(point);\n          Eigen::Vector4d tfPoint = projectionTransform * pt;\n          minPoint = minPoint.cwiseMin(tfPoint.head<3>());\n          maxPoint = maxPoint.cwiseMax(tfPoint.head<3>());\n        }\n\n        const Eigen::Vector3d meanDiagonal = 0.5f * (maxPoint + minPoint);\n\n        // quaternion is calculated using the eigenvectors (which determines\n        // how the final box gets rotated), and the transform to put the box\n        // in correct location is calculated\n        const Eigen::Quaterniond bboxQuaternion(eigenVectorsPCA);\n        const Eigen::Vector3d bboxTransform =\n          eigenVectorsPCA * meanDiagonal + centroid;\n\n        math::Vector3d size(\n            maxPoint.x() - minPoint.x(),\n            maxPoint.y() - minPoint.y(),\n            maxPoint.z() - minPoint.z()\n        );\n        math::Pose3d pose;\n        pose.Rot() = math::eigen3::convert(bboxQuaternion);\n        pose.Pos() = math::eigen3::convert(bboxTransform);\n\n        box.Size(size);\n        box.Pose(pose);\n        return box;\n      }\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "25f740bd8948117430292137561dbfd3eb9ece4c", "size": 6031, "ext": "hh", "lang": "C++", "max_stars_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_stars_repo_name": "srmainwaring/ign-math", "max_stars_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T20:50:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:48:25.000Z", "max_issues_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_issues_repo_name": "srmainwaring/ign-math", "max_issues_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 277.0, "max_issues_repo_issues_event_min_datetime": "2020-04-16T23:38:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:11:58.000Z", "max_forks_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_forks_repo_name": "srmainwaring/ign-math", "max_forks_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T21:15:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T19:29:04.000Z", "avg_line_length": 37.2283950617, "max_line_length": 123, "alphanum_fraction": 0.6330625104, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6871678049234973}}
{"text": "#pragma once\n\n#include <math.h>\n#include <vector>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Mahi/Util/Timing/Clock.hpp>\n        \nstruct ardsqexpKernel{\n    ardsqexpKernel():\n    length_scales(1,1),\n    length_scales_2(1,1),\n    train(1,std::vector<double>(1,0)),\n    sigma_f(1.0),\n    sigma_f_2(1.0),\n    K(train.size(),0)\n    {\n    }\n\n    ardsqexpKernel(std::vector<std::vector<double>> train, std::vector<double> theta):\n    train(train),\n    sigma_f(theta[theta.size()-1]),\n    sigma_f_2(sigma_f*sigma_f),\n    K(train.size(),0)\n    {\n        length_scales = std::vector<double>(theta.begin(),theta.end()-1);\n        length_scales_2 = std::vector<double>(length_scales.size(),0);\n        for (size_t i = 0; i < length_scales.size(); i++){\n            length_scales_2[i] = length_scales[i]*length_scales[i];\n        }   \n    }\n\n    std::vector<double> operator()(const std::vector<double>& New){       \n        for (auto i = 0; i < train.size(); i++){\n            double ard_sum = 0;\n            for(auto j = 0; j < train[0].size(); j++) {\n                double diff = train[i][j]-New[j];\n                ard_sum += diff*diff/(length_scales_2[j]);\n            }\n            K[i] = sigma_f_2*exp(-0.5*ard_sum);\n        }\n        return K;\n    }\n\n    std::vector<std::vector<double>> train;\n    std::vector<double> length_scales;\n    std::vector<double> length_scales_2;\n    double sigma_f;\n    double sigma_f_2;\n    std::vector<double> K;\n};\n", "meta": {"hexsha": "e64b0c8f9356af92f30f8871d7214ecfc622aa9f", "size": 1454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Mahi/FesExo/Kernels.hpp", "max_stars_repo_name": "mahilab/FES_Exo", "max_stars_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_stars_repo_licenses": ["MIT"], "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/Mahi/FesExo/Kernels.hpp", "max_issues_repo_name": "mahilab/FES_Exo", "max_issues_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_issues_repo_licenses": ["MIT"], "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/Mahi/FesExo/Kernels.hpp", "max_forks_repo_name": "mahilab/FES_Exo", "max_forks_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_forks_repo_licenses": ["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.9615384615, "max_line_length": 86, "alphanum_fraction": 0.5694635488, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6871396809394892}}
{"text": "//\n//  kc_rsa.cpp\n//  kcalg\n//\n//  Created by knightc on 2019/7/22.\n//  Copyright \u00a9 2019 knightc. All rights reserved.\n//\n\n#include \"opentsb/kc_sec.h\"\n#include \"opentsb/kc_common.h\"\n#include \"rsaUtil.hpp\"\n\n#include \"opentsb/test.h\"\n\n#include <cstdio>\n#include <vector>\n\n#include <NTL/vec_ZZ.h>\n\n\nint rsa_getKey(ZZ pubKey[],ZZ privKey[]) {\n    \n    ZZ p,q,n ,f_n;\n    ZZ pubkey_e,privKey_d;\n    \n   pubkey_e= 65537;\n    \n       RandomPrime(p, 1024);\n       RandomPrime(q, 1024);\n    //    NextPrime(q, p );\n//    p= 37;\n//    q= 23;\n//    if (GCD(p , q )==1) {\n//        cout << \"p and q is prime \" << endl;\n//    }\n    \n    \n    n= p * q;\n    oula(p, q, f_n);\n    \n    if (GCD(pubkey_e, f_n )== 1) {\n        cout << \" pubkey_e is true \\n\" << endl;\n    }\n    \n    privKey_d = InvMod(pubkey_e, f_n);\n    \n    pubKey[0]=pubkey_e;\n    pubKey[1]=n;\n    \n    \n    privKey[0] = privKey_d;\n    privKey[1] =p;\n    privKey[2] = q ;\n  \n    cout <<\"\u516c\u94a5 e = \"<< pubkey_e <<\"\\n\"\n    << \"\u5171\u6a21 n = \" << n << \"\\n\"\n    << \"\u6b27\u62c9 n = \" << f_n << \"\\n\"\n    <<\"\u79c1\u94a5 d = \" <<privKey_d<< endl;\n    \n    return 1;\n}\n\nZZ rsa_enc(const ZZ pubKey[],unsigned char *plaintext ,long plain_len) {\n    \n//    unsigned char *cyperTxt={0};\n    ZZ e,n,plaintx_z,cypertx_z;\n    \n    e= pubKey[0];\n    n= pubKey[1];\n    \n    plaintx_z= ZZFromBytes(plaintext, plain_len);\n   cout  <<\"\u660e\u6587 M = \" <<plaintx_z<< endl;\n//    cout <<\"\u516c\u94a5 e = \"<< e <<\"\\n\"\n//        << \"\u5171\u6a21 n = \" << n << \"\\n\"\n//        <<\"\u660e\u6587 M = \" <<plaintx_z<< endl;\n    \n    cypertx_z = PowerMod(plaintx_z, e, n);\n    cout << \"\u5bc6\u6587 C = \" << cypertx_z << endl;\n    \n    \n//    BytesFromZZ(cyperTxt, cypertx_z, 256);\n//\n//    return cyperTxt;\n    return cypertx_z;\n   \n    \n}\n\nint rsa_decy(ZZ cyperTxt_z,ZZ privKey[] , unsigned char *plaintext) {\n    \n    ZZ d,n,plaintx_z;\n//    long ctx_len;\n    \n //   ctx_len= getArrayLen(cyperTxt);\n    \n    d= privKey[0];\n    n= privKey[1] * privKey[2];\n//    cout <<\"\u79c1\u94a5 d = \"<< d <<\"\\n\"\n//    << \"\u5171\u6a21 n = \" << n << \"\\n\"\n//      <<\"\u5bc6\u6587 C = \" <<cyperTxt_z<< endl;\n  //  ZZFromBytes(cyperTxt_z, cyperTxt, ctx_len);\n    \n   plaintx_z= PowerMod(cyperTxt_z, d, n);\n    cout << \"\u89e3\u5bc6 M = \" << plaintx_z << endl;\n    \n//    BytesFromZZ(plaintext, plaintx_z,1);\n//    cout << \"\u660e\u6587 M = \" << plaintext << endl;\n    \n    return 0;\n}\n\nint test_rsa() {\n    \n//    unsigned   char std_Message[19]={\n//        0x65,0x6E,0x63,0x72,0x79,0x70,0x74,0x69,0x6F,0x6E,0x20,0x73,0x74,0x61,0x6E,\n//        0x64,0x61,0x72,0x64};\n    unsigned char std_Message[1]={0x65};\n\n\n    unsigned char *plaintx={0};\n   // unsigned char *cypertx= {0};\n    ZZ cypertx;\n    \n    long plain_len;\n    ZZ pubKey[2],privKey[3];\n    ZZ e,d,n;\n    \n    plain_len= getArrayLen(std_Message);\n    rsa_getKey(pubKey, privKey);\n    \n    cypertx= rsa_enc(pubKey,std_Message, plain_len);\n    \n    rsa_decy(cypertx, privKey, plaintx);\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "363dee7a5b19102122f70264729aab1e41c3314f", "size": 2848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/sec/rsa/kc_rsa.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/sec/rsa/kc_rsa.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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": "kcalg/sec/rsa/kc_rsa.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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.6376811594, "max_line_length": 85, "alphanum_fraction": 0.5270365169, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133464597458, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6871317261130627}}
{"text": "#include <iostream>\n#include <chrono>\n#include <random>\n#include <map>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// #include \"g2o/core/auto_differentiation.h\"\n// #include \"g2o/core/base_unary_edge.h\"\n// #include \"g2o/core/base_vertex.h\"\n// #include \"g2o/core/optimization_algorithm_factory.h\"\n// #include \"g2o/core/sparse_optimizer.h\"\n// #include \"g2o/stuff/command_args.h\"\n// #include \"g2o/stuff/sampler.h\"\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/auto_differentiation.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_factory.h>\n#include \"matplotlibcpp.h\"\n\nG2O_USE_OPTIMIZATION_LIBRARY(dense);\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\n\ntemplate <class T, class TT>\nT g(TT x, T a, T b, T c)\n{\n  return ceres::exp(a * x * x + b * x + c);\n}\n\n\n\n\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d> {\n  public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n  virtual void setToOriginImpl() override {\n    _estimate << 0.0, 0.0, 0.0;\n  }\n  virtual void oplusImpl(const double* update) override {\n    _estimate += Eigen::Vector3d(update);\n  }\n\n  virtual bool read(std::istream&) {}\n  virtual bool write(std::ostream&) const {}\n};\n\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {\n  public:  \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    CurveFittingEdge(double x): _x(x) {}\n\n    // Without auto-diff\n    virtual void computeError() override {\n      const CurveFittingVertex* v = static_cast<CurveFittingVertex*>(_vertices[0]);\n      const Eigen::Vector3d abc = v->estimate();\n      _error(0, 0) = _measurement - g(_x, abc[0], abc[1], abc[2]);\n    }\n\n    // Analytical jacobian\n    virtual void linearizeOplus() override {\n      const CurveFittingVertex *v = static_cast<CurveFittingVertex*>(_vertices[0]);\n      const Eigen::Vector3d abc = v->estimate();\n      double y = g(_x, abc[0], abc[1], abc[2]);\n      _jacobianOplusXi[0] = -_x * _x * y;\n      _jacobianOplusXi[1] = -_x * y;\n      _jacobianOplusXi[2] = -y;\n    }\n\n\n\n    // with auto-diff\n    // template <class T>\n    // bool operator() (const T* abc, T *error) const {\n    //   error[0] = measurement() - g(_x, abc[0], abc[1], abc[2]);\n    //   return true;\n    // }\n\n    virtual bool read(istream&) {}\n    virtual bool write(ostream&) const {}\n\n  private:\n    double _x;\n\n\n  // G2O_MAKE_AUTO_AD_FUNCTIONS  // use autodiff\n};  \n\n\nint main(int argc, char **argv) {\n  std::cout << \"Gauss-Newton \\n\";\n\n  double aa = 1.0, bb = 2.0, cc = 1.0;\n  double a = 2.0, b = -1.0, c = 5.5;\n\n  double obs_sigma = 1.0;\n  std::default_random_engine generator;\n  std::normal_distribution<double> obs_noise_distrib(0.0, obs_sigma);\n\n\n  int N = 100;\n  std::vector<double> x_data(N), y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    x_data[i] = static_cast<double>(i) / 100.0;\n    y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n  }\n\n\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType;\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n  // auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n  //   g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>())\n  // );\n\n  g2o::SparseOptimizer optimizer;\n  // optimizer.setAlgorithm(solver);\n  g2o::OptimizationAlgorithmProperty solverProperty;\n  optimizer.setAlgorithm(g2o::OptimizationAlgorithmFactory::instance()->construct(\"lm_dense\", solverProperty));\n  optimizer.setVerbose(true);\n\n\n  // Create vertex\n  CurveFittingVertex *v = new CurveFittingVertex();\n  v->setEstimate(Eigen::Vector3d(a, b, c));\n  v->setId(0);\n  optimizer.addVertex(v);\n\n  // Add edges\n  for (int i = 0; i < N; ++i)\n  {\n    CurveFittingEdge * edge = new CurveFittingEdge(x_data[i]);\n    edge->setId(i);\n    edge->setVertex(0, v);\n    edge->setMeasurement(y_data[i]);\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() / (obs_sigma * obs_sigma));\n    optimizer.addEdge(edge);\n  }\n\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n  \n  \n  a = v->estimate()[0];\n  b = v->estimate()[1];\n  c = v->estimate()[2];\n\n  std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n\n\n  vector<double> final_y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    final_y_data[i] = g(x_data[i], a, b, c);\n  }\n\n  plt::scatter(x_data, y_data);\n  std::map<std::string, std::string> parameters;\n  parameters[\"c\"] = \"red\";\n  plt::scatter(x_data, final_y_data, 1.0, parameters);\n  plt::show();  \n\n\n  return 0;\n}\n", "meta": {"hexsha": "6128e8a94e1b7962d873b8e15d76dcad8ef34ba1", "size": 5020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/curve_fitting_g2o.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/curve_fitting_g2o.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/curve_fitting_g2o.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": 26.9892473118, "max_line_length": 111, "alphanum_fraction": 0.6651394422, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6870962337313626}}
{"text": "#define BOOST_TEST_MODULE \"test_JacobiMethod\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include \"../src/JacobiMethod.hpp\"\n#include \"../src/InverseMatrix.hpp\"\n#include \"../src/io.hpp\"\n\n#include \"test_Defs.hpp\"\nusing ax::test::seed;\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(matrix_2x2)\n{\n    constexpr std::size_t msize = 2;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    ax::Matrix<double, msize,msize> mat;\n    double det(0e0);\n\n    while(det == 0e0)\n    {\n        for(std::size_t i=0; i<msize; ++i)\n            for(std::size_t j=i; j<msize; ++j)\n                if(i==j)\n                    mat(i,j) = randreal(mt);\n                else\n                    mat(i,j) = mat(j,i) = randreal(mt);\n        det = ax::determinant(mat);\n   }\n\n    const ax::Matrix<double, msize,msize> values = mat;\n    const ax::Matrix<double, msize,msize> E(1e0);\n\n//     ax::JacobiMethod<ax::Matrix<double, msize,msize>> jacobi(mat);\n//     auto eigenpair = jacobi.solve();\n    auto eigenpair = Jacobimethod(mat);\n\n    for(std::size_t i=0; i<msize; ++i)\n    {\n        const double eigenvalue = eigenpair.at(i).first;\n        const ax::Vector<double, msize> eigenvector = eigenpair.at(i).second; \n\n        std::cout << \"eval \" << eigenvalue << std::endl;\n        std::cout << \"evec \" << eigenvector << std::endl;\n\n        const ax::Vector<double, msize> zeros = (values - eigenvalue * E) * eigenvector; \n        for(std::size_t j=0; j<msize; ++j)\n            BOOST_CHECK_SMALL(zeros[j], 1e-7);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(matrix_3x3)\n{\n    constexpr std::size_t msize = 3;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    ax::Matrix<double, msize,msize> mat;\n    double det(0e0);\n\n    while(det == 0e0)\n    {\n        for(std::size_t i=0; i<msize; ++i)\n            for(std::size_t j=i; j<msize; ++j)\n                if(i==j)\n                    mat(i,j) = randreal(mt);\n                else\n                    mat(i,j) = mat(j,i) = randreal(mt);\n        det = ax::determinant(mat);\n    }\n\n    const ax::Matrix<double, msize,msize> values = mat;\n    const ax::Matrix<double, msize,msize> E(1e0);\n\n//     ax::JacobiMethod<ax::Matrix<double, msize,msize>> jacobi(mat);\n//     const auto eigenpair = jacobi.solve();\n    auto eigenpair = Jacobimethod(mat);\n\n    for(std::size_t i=0; i<msize; ++i)\n    {\n        const double eigenvalue = eigenpair.at(i).first;\n        const ax::Vector<double, msize> eigenvector = eigenpair.at(i).second; \n\n        std::cout << \"eval \" << eigenvalue << std::endl;\n        std::cout << \"evec \" << eigenvector << std::endl;\n\n        const ax::Vector<double, msize> zeros = (values - eigenvalue * E) * eigenvector;\n        for(std::size_t j=0; j<msize; ++j)\n            BOOST_CHECK_SMALL(zeros[j], 1e-7);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(matrix_4x4)\n{\n    constexpr std::size_t msize = 4;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(1e0, 2e0);\n\n    ax::Matrix<double, msize,msize> mat;\n\n    for(std::size_t i=0; i<msize; ++i)\n        for(std::size_t j=i; j<msize; ++j)\n            if(i==j)\n                mat(i,j) = randreal(mt);\n            else\n                mat(i,j) = mat(j,i) = randreal(mt);\n\n    const ax::Matrix<double, msize,msize> values = mat;\n    const ax::Matrix<double, msize,msize> E(1e0);\n\n//     ax::JacobiMethod<ax::Matrix<double, msize,msize>> jacobi(mat);\n//     auto eigenpair = jacobi.solve();\n\n    auto eigenpair = Jacobimethod(mat);\n\n    for(std::size_t i=0; i<msize; ++i)\n    {\n        const double eigenvalue = eigenpair.at(i).first;\n        const ax::Vector<double, msize> eigenvector = eigenpair.at(i).second; \n\n        std::cout << \"eval \" << eigenvalue << std::endl;\n        std::cout << \"evec \" << eigenvector << std::endl;\n\n        const ax::Vector<double, msize> zeros = (values - eigenvalue * E) * eigenvector; \n        for(std::size_t j=0; j<msize; ++j)\n            BOOST_CHECK_SMALL(zeros[j], 1e-7);\n    }\n}\n", "meta": {"hexsha": "0bdac7a76a2d7d6d896dbf8c6b64c786f3325df5", "size": 4103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_JacobiMethod.cpp", "max_stars_repo_name": "ToruNiina/AX", "max_stars_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T13:56:31.000Z", "max_issues_repo_path": "test/test_JacobiMethod.cpp", "max_issues_repo_name": "ToruNiina/AX", "max_issues_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_JacobiMethod.cpp", "max_forks_repo_name": "ToruNiina/AX", "max_forks_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_forks_repo_licenses": ["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.8943661972, "max_line_length": 89, "alphanum_fraction": 0.5834755057, "num_tokens": 1242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.6870913376911918}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      100903    K. Kumar          File created.\n *      100916    L. Abdulkadir     File checked.\n *      100929    K. Kumar          Checked code by D. Dirkx added.\n *      101110    K. Kumar          Added raiseToExponentPower() function.\n *      102410    D. Dirkx          Minor comment changes as code check.\n *      101213    K. Kumar          Bugfix raiseToIntegerExponent(); renamed raiseToIntegerPower().\n *                                  Added computeAbsoluteValue() functions.\n *      110202    K. Kumar          Added overload for State* for computeLinearInterpolation().\n *      110111    J. Melman         Added computeModulo() function.\n *      110411    K. Kumar          Added convertCartesianToSpherical() function.\n *      110606    J. Melman         Removed possible singularity from\n *                                  convertCartesianToSpherical.\n *      110707    K. Kumar          Added computeSampleMean(), computeSampleVariance() functions.\n *      110905    S. Billemont      Reorganized includes.\n *                                  Moved (con/de)structors and getter/setters to header.\n *      120127    D. Dirkx          First version branched from basic mathematics in Tudat Core.\n *      120127    K. Kumar          Minor comment edits.\n *      120118    D. Gondelach      Added new convertCylindricalToCartesian functions.\n *      120214    K. Kumar          Branched from old Tudat trunk for new coordinate conversions.\n *      120217    K. Kumar          Updated computeModuloForSignedValues() to computeModulo()\n *                                  from Tudat Core.\n *      120926    E. Dekens         Added spherical gradient to Cartesian conversion.\n *      131022    T. Roegiers       Added conversion from spherical state to Cartesian state.\n *                                  Added conversion from Cartesian state to spherical state.\n *      140114    E. Brandon        Reorganized includes.\n *                                  Minor changes during code check.\n *\n *    References\n *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n *          University Press, February 2002.\n *      Torok, J.S. Analytical Mechanics: with an Introduction to Dynamical Systems, John Wiley and\n *          Sons, Inc., 2000.\n *      Vallado, D.A. Fundamentals of Astrodynamics and Applications. Microcosm Press, 2001.\n *\n *    Notes\n *\n */\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\n\nnamespace tudat\n{\n\nnamespace coordinate_conversions\n{\n\n\n//! Convert spherical (radius_, zenith, azimuth) to Cartesian (x,y,z) coordinates.\nEigen::Vector3d convertSphericalToCartesian( const Eigen::Vector3d& sphericalCoordinates )\n{\n    // Create local variables.\n    double radius_ = sphericalCoordinates( 0 );\n    double zenithAngle_ = sphericalCoordinates( 1 );\n    double azimuthAngle_ = sphericalCoordinates( 2 );\n\n    // Declaring sine which has multiple usages to save computation time.\n    double sineOfZenithAngle_ = std::sin( sphericalCoordinates( 1 ) );\n\n    // Create output Vector3d.\n    Eigen::Vector3d convertedCartesianCoordinates_ = Eigen::Vector3d::Zero( 3 );\n\n    // Perform transformation.\n    convertedCartesianCoordinates_( 0 ) = radius_ * std::cos( azimuthAngle_ ) * sineOfZenithAngle_;\n    convertedCartesianCoordinates_( 1 ) = radius_ * std::sin( azimuthAngle_ ) * sineOfZenithAngle_;\n    convertedCartesianCoordinates_( 2 ) = radius_ * std::cos( zenithAngle_ );\n\n    return convertedCartesianCoordinates_;\n}\n\n//! Convert Cartesian (x,y,z) to spherical (radius, zenith, azimuth) coordinates.\nEigen::Vector3d convertCartesianToSpherical( const Eigen::Vector3d& cartesianCoordinates )\n{\n    // Create output Vector3d.\n    Eigen::Vector3d convertedSphericalCoordinates_ = Eigen::Vector3d::Zero( 3 );\n\n    // Compute transformation of Cartesian coordinates to spherical coordinates.\n    convertedSphericalCoordinates_( 0 ) = cartesianCoordinates.norm( );\n\n    // Check if coordinates are at origin.\n    if ( convertedSphericalCoordinates_( 0 ) < std::numeric_limits< double >::epsilon( ) )\n    {\n        convertedSphericalCoordinates_( 1 ) = 0.0;\n        convertedSphericalCoordinates_( 2 ) = 0.0;\n    }\n    // Else compute coordinates using trigonometric relationships.\n    else\n    {\n        convertedSphericalCoordinates_( 1 ) = std::acos( cartesianCoordinates( 2 )\n                                                         / convertedSphericalCoordinates_( 0 ) );\n        convertedSphericalCoordinates_( 2 ) = std::atan2( cartesianCoordinates( 1 ),\n                                                          cartesianCoordinates( 0 ) );\n    }\n\n    return convertedSphericalCoordinates_;\n}\n\n\n//! Convert cylindrical to Cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const double radius,\n                                               const double azimuthAngle, const double z )\n{\n    // Create Cartesian coordinates vector.\n    Eigen::Vector3d cartesianCoordinates;\n\n    // If radius < 0, then give warning.\n    if ( radius < 0.0 )\n    {\n        std::cerr << \"Warning: cylindrical radial coordinate is negative!\\n\"\n                  << \"This could give incorrect results!\\n\";\n    }\n\n    // Compute and set Cartesian coordinates.\n    cartesianCoordinates << radius * std::cos( azimuthAngle ),   // x-coordinate\n                            radius * std::sin( azimuthAngle ),   // y-coordinate\n                            z;                                   // z-coordinate\n\n    return cartesianCoordinates;\n}\n\n//! Convert cylindrical to cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const Eigen::Vector3d& cylindricalCoordinates )\n{\n    // Create Cartesian coordinates vector.\n    Eigen::Vector3d cartesianCoordinates;\n\n    // If radius < 0, then give warning.\n    if ( cylindricalCoordinates( 0 ) < 0.0 )\n    {\n        std::cerr << \"Warning: cylindrical radial coordinate is negative! \"\n                  << \"This could give incorrect results!\\n\";\n    }\n\n    // Compute and set Cartesian coordinates.\n    cartesianCoordinates\n            << cylindricalCoordinates( 0 )\n               * std::cos( cylindricalCoordinates( 1 ) ),    // x-coordinate\n               cylindricalCoordinates( 0 )\n               * std::sin( cylindricalCoordinates( 1 ) ),    // y-coordinate\n               cylindricalCoordinates( 2 );                  // z-coordinate\n\n    return cartesianCoordinates;\n}\n\n//! Convert cylindrical to Cartesian state.\nbasic_mathematics::Vector6d convertCylindricalToCartesianState(\n        const basic_mathematics::Vector6d& cylindricalState )\n{\n    // Create Cartesian state vector, initialized with zero entries.\n    basic_mathematics::Vector6d cartesianState = basic_mathematics::Vector6d::Zero( );\n\n    // Get azimuth angle, theta.\n    double azimuthAngle = cylindricalState( 1 );\n\n    // Compute and set Cartesian coordinates.\n    cartesianState.head( 3 ) = convertCylindricalToCartesian(\n                Eigen::Vector3d( cylindricalState.head( 3 ) ) );\n\n    // If r = 0 AND Vtheta > 0, then give warning and assume Vtheta=0.\n    if ( std::fabs(cylindricalState( 0 )) <= std::numeric_limits< double >::epsilon( )\n         && std::fabs(cylindricalState( 4 )) > std::numeric_limits< double >::epsilon( ) )\n    {\n        std::cerr << \"Warning: cylindrical velocity Vtheta (r*thetadot) does not equal zero while \"\n                  << \"the radius (r) is zero! Vtheta is taken equal to zero!\\n\";\n\n        // Compute and set Cartesian velocities.\n        cartesianState.tail( 3 )\n                << cylindricalState( 3 ) * std::cos( azimuthAngle ),   // xdot\n                   cylindricalState( 3 ) * std::sin( azimuthAngle ),   // ydot\n                   cylindricalState( 5 );                              // zdot\n    }\n\n    else\n    {\n        // Compute and set Cartesian velocities.\n        cartesianState.tail( 3 )\n                << cylindricalState( 3 ) * std::cos( azimuthAngle )\n                   - cylindricalState( 4 ) * std::sin( azimuthAngle ),   // xdot\n                   cylindricalState( 3 ) * std::sin( azimuthAngle )\n                   + cylindricalState( 4 ) * std::cos( azimuthAngle ),   // ydot\n                   cylindricalState( 5 );                                // zdot\n    }\n\n    return cartesianState;\n}\n\n//! Convert Cartesian to cylindrical coordinates.\nEigen::Vector3d convertCartesianToCylindrical( const Eigen::Vector3d& cartesianCoordinates )\n{\n    // Create cylindrical coordinates vector.\n    Eigen::Vector3d cylindricalCoordinates;\n\n    // Declare new variable, the azimuth angle.\n    double azimuthAngle;\n\n    // Compute azimuth angle, theta.\n    /* If x = 0, then azimuthAngle = pi/2 (y>0) or 3*pi/2 (y<0) or 0 (y=0),\n       else azimuthAngle = arctan(y/x).\n    */\n    using mathematical_constants::PI;\n    if ( std::fabs(cartesianCoordinates( 0 ) ) <= std::numeric_limits< double >::epsilon( ) )\n    {\n        azimuthAngle = basic_mathematics::computeModulo(\n                    static_cast< double >( boost::math::sign( cartesianCoordinates( 1 ) ) )\n                    * 0.5 * PI, 2.0 * PI );\n    }\n\n    else\n    {\n        azimuthAngle = basic_mathematics::computeModulo(\n                    std::atan2( cartesianCoordinates( 1 ),\n                                cartesianCoordinates( 0 ) ), 2.0 * PI );\n    }\n\n    // Compute and set cylindrical coordinates.\n    cylindricalCoordinates <<\n        std::sqrt( pow( cartesianCoordinates( 0 ), 2 )\n                   + pow( cartesianCoordinates( 1 ), 2 ) ), // Radius\n        azimuthAngle,                                       // Azimuth angle, theta\n        cartesianCoordinates( 2 );                          // z-coordinate\n\n    return cylindricalCoordinates;\n}\n\n//! Convert Cartesian to cylindrical state.\nbasic_mathematics::Vector6d convertCartesianToCylindricalState(\n        const basic_mathematics::Vector6d& cartesianState )\n{\n    // Create cylindrical state vector, initialized with zero entries.\n    basic_mathematics::Vector6d cylindricalState = basic_mathematics::Vector6d::Zero( );\n\n    // Compute and set cylindrical coordinates.\n    cylindricalState.head( 3 ) = convertCartesianToCylindrical(\n                Eigen::Vector3d( cartesianState.head( 3 ) ) );\n\n    // Compute and set cylindrical velocities.\n    /* If radius = 0, then Vr = sqrt(xdot^2+ydot^2) and Vtheta = 0,\n       else Vr = (x*xdot+y*ydot)/radius and Vtheta = (x*ydot-y*xdot)/radius.\n    */\n    if ( cylindricalState( 0 ) <= std::numeric_limits< double >::epsilon( ) )\n    {\n        cylindricalState.tail( 3 ) <<\n            std::sqrt( pow( cartesianState( 3 ), 2 ) + pow( cartesianState( 4 ), 2 ) ), // Vr\n            0.0,                                                                        // Vtheta\n            cartesianState( 5 );                                                        // Vz\n    }\n\n    else\n    {\n        cylindricalState.tail( 3 ) <<\n            ( cartesianState( 0 ) * cartesianState( 3 )\n              + cartesianState( 1 ) * cartesianState( 4 ) ) / cylindricalState( 0 ),    // Vr\n            ( cartesianState( 0 ) * cartesianState( 4 )\n              - cartesianState( 1 ) * cartesianState( 3 ) ) / cylindricalState( 0 ),    // Vtheta\n                cartesianState( 5 );                                                    // Vz\n    }\n\n    return cylindricalState;\n}\n\n//! Convert spherical to Cartesian gradient.\nEigen::Vector3d convertSphericalToCartesianGradient( const Eigen::Vector3d& sphericalGradient,\n                                                     const Eigen::Vector3d& cartesianCoordinates )\n{\n    // Compute radius.\n    const double radius = std::sqrt( cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n                                     + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 )\n                                     + cartesianCoordinates( 2 ) * cartesianCoordinates( 2 ) );\n\n    // Compute square of distance within xy-plane.\n    const double xyDistanceSquared = cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n            + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 );\n\n    // Compute distance within xy-plane.\n    const double xyDistance = std::sqrt( xyDistanceSquared );\n\n    // Compute transformation matrix.\n    const Eigen::Matrix3d transformationMatrix = (\n                Eigen::Matrix3d( 3, 3 ) <<\n                cartesianCoordinates( 0 ) / radius,\n                - cartesianCoordinates( 0 ) * cartesianCoordinates( 2 )\n                / ( radius * radius * xyDistance ),\n                - cartesianCoordinates( 1 ) / xyDistanceSquared,\n                cartesianCoordinates( 1 ) / radius,\n                - cartesianCoordinates( 1 ) * cartesianCoordinates( 2 )\n                / ( radius * radius * xyDistance ),\n                + cartesianCoordinates( 0 ) / xyDistanceSquared,\n                cartesianCoordinates( 2 ) / radius,\n                xyDistance / ( radius * radius ),\n                0.0\n                ).finished( );\n\n    // Return Cartesian gradient.\n    return transformationMatrix * sphericalGradient;\n}\n\n//! Convert spherical to Cartesian state.\nbasic_mathematics::Vector6d convertSphericalToCartesianState(\n        const basic_mathematics::Vector6d& sphericalState )\n{\n    // Create Cartesian state vector, initialized with zero entries.\n    basic_mathematics::Vector6d convertedCartesianState = basic_mathematics::Vector6d::Zero( );\n\n    // Create local variables.\n    const double radius = sphericalState( 0 );\n    const double azimuthAngle = sphericalState( 1 );\n    const double elevationAngle = sphericalState( 2 );\n\n    // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n    const double cosineOfElevationAngle = std::cos( elevationAngle );\n    const double sineOfElevationAngle = std::sin( elevationAngle );\n    const double cosineOfAzimuthAngle = std::cos( azimuthAngle );\n    const double sineOfAzimuthAngle = std::sin( azimuthAngle );\n\n    // Set up transformation matrix for spherical to cylindrical conversion.\n    Eigen::Matrix3d transformationMatrixSphericalToCylindrical = Eigen::Matrix3d::Zero( );\n    transformationMatrixSphericalToCylindrical( 0, 0 ) = cosineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 0, 2 ) = -sineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 1, 1 ) = 1.0;\n    transformationMatrixSphericalToCylindrical( 2, 0 ) = sineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 2, 2 ) = cosineOfElevationAngle;\n\n    // Set up transformation matrix for cylindrical to Cartesian conversion.\n    Eigen::Matrix3d transformationMatrixCylindricalToCartesian = Eigen::Matrix3d::Zero( );\n    transformationMatrixCylindricalToCartesian( 0, 0 ) = cosineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 0, 1 ) = -sineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 1, 0 ) = sineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 1, 1 ) = cosineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 2, 2 ) = 1.0;\n\n    // Compute transformation matrix for spherical to Cartesian conversion.\n    const Eigen::Matrix3d transformationMatrixSphericalToCartesian\n            = transformationMatrixCylindricalToCartesian\n            * transformationMatrixSphericalToCylindrical;\n\n    // Perform transformation of position coordinates.\n    convertedCartesianState( 0 ) = radius * cosineOfAzimuthAngle * cosineOfElevationAngle;\n    convertedCartesianState( 1 ) = radius * sineOfAzimuthAngle * cosineOfElevationAngle;\n    convertedCartesianState( 2 ) = radius * sineOfElevationAngle;\n\n    // Perform transformation of velocity vector.\n    convertedCartesianState.segment( 3, 3 ) =\n        transformationMatrixSphericalToCartesian * sphericalState.segment( 3, 3 );\n\n    // Return Cartesian state vector.\n    return convertedCartesianState;\n}\n\n//! Convert Cartesian to spherical state.\nbasic_mathematics::Vector6d convertCartesianToSphericalState(\n        const basic_mathematics::Vector6d& cartesianState )\n{\n    // Create spherical state vector, initialized with zero entries.\n    basic_mathematics::Vector6d convertedSphericalState = basic_mathematics::Vector6d::Zero( );\n\n    // Compute radius.\n    convertedSphericalState( 0 ) = cartesianState.segment( 0, 3 ).norm( );\n\n    // Check if radius is nonzero.\n    /*\n     * If r > 0, the elevation and azimuth angles are computed using trigonometric relationships.\n     * If r = 0, the coordinates are at the origin, the elevation and azimuth angles equal to zero.\n     * Since the state vector was initialized with zeroes, this is already the case.\n     */\n    if ( convertedSphericalState( 0 ) > std::numeric_limits< double >::epsilon( ) )\n    {\n        // Compute elevation and azimuth angles using trigonometric relationships.\n        // Azimuth angle.\n        convertedSphericalState( 1 ) = std::atan2( cartesianState( 1 ), cartesianState( 0 ) );\n        // Elevation angle.\n        convertedSphericalState( 2 ) = std::asin( cartesianState( 2 )\n                                                   / convertedSphericalState( 0 ) );\n    }\n\n    // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n    const double cosineOfElevationAngle = std::cos( convertedSphericalState( 2 ) );\n    const double sineOfElevationAngle = std::sin( convertedSphericalState( 2 ) );\n    const double cosineOfAzimuthAngle = std::cos( convertedSphericalState( 1 ) );\n    const double sineOfAzimuthAngle = std::sin( convertedSphericalState( 1 ) );\n\n    // Set up transformation matrix for cylindrical to spherical conversion.\n    Eigen::Matrix3d transformationMatrixCylindricalToSpherical = Eigen::Matrix3d::Zero( );\n    transformationMatrixCylindricalToSpherical( 0, 0 ) = cosineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 0, 2 ) = sineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 1, 1 ) = 1.0;\n    transformationMatrixCylindricalToSpherical( 2, 0 ) = -sineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 2, 2 ) = cosineOfElevationAngle;\n\n    // Set up transformation matrix for Cartesian to cylindrical conversion.\n    Eigen::Matrix3d transformationMatrixCartesianToCylindrical = Eigen::Matrix3d::Zero( );\n    transformationMatrixCartesianToCylindrical( 0, 0 ) = cosineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 0, 1 ) = sineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 1, 0 ) = -sineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 1, 1 ) = cosineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 2, 2 ) = 1.0;\n\n    // Compute transformation matrix for Cartesian to spherical conversion.\n    const Eigen::Matrix3d transformationMatrixCartesianToSpherical\n            = transformationMatrixCylindricalToSpherical\n            * transformationMatrixCartesianToCylindrical;\n\n    // Perform transformation of velocity vector.\n    convertedSphericalState.segment( 3, 3 )\n            = transformationMatrixCartesianToSpherical * cartesianState.segment( 3, 3 );\n\n    // Return spherical state vector.\n    return convertedSphericalState;\n}\n\n} // namespace coordinate_conversions\n\n} // namespace tudat\n", "meta": {"hexsha": "4e56e6b3f1e89f21166332a8f4a6b6f920bc877d", "size": 21171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/coordinateConversions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "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/BasicMathematics/coordinateConversions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "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/BasicMathematics/coordinateConversions.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 47.4686098655, "max_line_length": 99, "alphanum_fraction": 0.6569363752, "num_tokens": 4808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6870443839026318}}
{"text": "#include <iostream>\n#include <g2o/core/g2o_core_api.h>\n#include <g2o/core/base_vertex.h>\n#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <sophus/se3.hpp>\n#include <chrono>\nusing namespace std;\nusing namespace cv;\n// define VecVec2d and VecVec3d\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\n// Functions Get the matching points\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches);\n\n// Functions to Change the pixel points into camera normalization points\nPoint2d pixel2cam(const Point2d &p, const Mat &K);\n\n// Bundle Adjustment  By Gauss-Newton\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d, \n  const VecVector2d &points_2d,\n  const Mat &K,     \n  Sophus::SE3d &pose    // need to be optimazied\n);\n\n// Bundle Adjustment By G2O\nvoid bundleAdjustmentG2O(\n  const VecVector3d &points_3d,  \n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose\n);\n\nint main(int argc, char const *argv[]){\n    if(argc!=5){\n        cout<<\"Usage (bash): pose_estimation3d2d.cpp  <image01> <image02> <rgbd-image01-path>  <rgbd-image02-path> \"<<endl;\n       return 1;\n    }\n //  Load Images\n  Mat img_1 = imread(argv[1]);\n  Mat img_2 = imread(argv[2]);\n  assert(img_1.data && img_2.data && \"Can not load images!\");\n \n // Find keypoints matches using orb-brief\nvector<KeyPoint> keypoints_1, keypoints_2;\nvector<DMatch> matches;\nfind_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\ncout << \"Totally found \" << matches.size() << \" matches\" << endl;\n\n//  Build 3d -2d  reflections\n\n//  depth image is 16-bit unchar mono-channel picture\nMat rgbd_image01 = imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);\nMat camera_K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);  \nvector<Point3f> pts_3d;\nvector<Point2f> pts_2d;\nfor(DMatch m :matches){\n // reference : Mat.ptr<unchar>(int a)[int b] : means the pixel in row a, col b.\n // get the keypoint's deep\nushort d = rgbd_image01.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];  \nif(d==0) continue;   \nfloat normalized_d = d /1000.0;\nPoint2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt,camera_K);\npts_3d.push_back(Point3f(p1.x*normalized_d,p1.y*normalized_d,normalized_d));  // keypint one's 3d , \u76f8\u673a\u5750\u6807\npts_2d.push_back(keypoints_2[m.trainIdx].pt);      // keypoint2 :only 2d\n}\n\n// Solve PNP using OpenCV\nMat r, t;  // r is rotation vector , t is translation vector\nsolvePnP(pts_3d,pts_2d,camera_K,Mat(),r,t, false, cv::SOLVEPNP_EPNP);\nMat inliners;\nbool result  = solvePnPRansac(pts_3d,pts_2d,camera_K,Mat(),r,t,false,100,4.0,0.99,inliners);\ncout<<result<<endl;\nMat R;\ncv::Rodrigues(r,R);\ncout<<\" Rotation Matrix R (3,3 ): \"<<\"\\n\"<<R<<endl;\ncout<<\"  translation vector  (3,1): \"<<\"\\n\"<<t<<endl;\n  \n  \n  VecVector3d pts_3d_eigen;\n  VecVector2d pts_2d_eigen;\n  for (size_t i = 0; i < pts_3d.size(); ++i) {\n    pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n    pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n  }\n  // \u4f7f\u7528 G-N  BA\n  cout << \"Calling bundle adjustment by gauss newton\" << endl;\n  Sophus::SE3d pose_gn;\n  bundleAdjustmentGaussNewton(pts_3d_eigen, pts_2d_eigen, camera_K, pose_gn);\n \n Sophus::SE3d pose_g2o;\nbundleAdjustmentG2O(pts_3d_eigen, pts_2d_eigen, camera_K, pose_g2o);\nreturn 0;\n}\n\n\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,\n                          std::vector<KeyPoint> &keypoints_1,\n                          std::vector<KeyPoint> &keypoints_2,\n                          std::vector<DMatch> &matches) {\n  //-- \u521d\u59cb\u5316\n  Mat descriptors_1, descriptors_2;\n  // used in OpenCV3\n  Ptr<FeatureDetector> detector = ORB::create();\n  Ptr<DescriptorExtractor> descriptor = ORB::create();\n  // use this if you are in OpenCV2\n  // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n  // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n  Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n  //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n  vector<DMatch> match;\n  //BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n  double min_dist = 10000, max_dist = 0;\n\n  //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n    if (dist < min_dist) min_dist = dist;\n    if (dist > max_dist) max_dist = dist;\n  }\n  //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\n\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose) {\n typedef Eigen::Matrix<double, 6, 1> Vector6d;   // because Se(3) is a 6 dim vector, First 3 P is translation, Second 3 Fi is rotatiom\n  const int iterations = 10;\n  double cost = 0, lastCost = 0;\n  /// camera model//\n  // X' = f(X/Z) Y'= f(Y/Z)\n  // u = aX' +cx   v= bY' + cy\n  \n  // Camera inner parameter\n  //         [ fx, 0 , cx ]\n //  K =  [ 0, fx,  cy ]\n //          [ 0,  0,   1  ]\n  double fx = K.at<double>(0, 0);\n  double fy = K.at<double>(1, 1);\n  double cx = K.at<double>(0, 2);\n  double cy = K.at<double>(1, 2);\n\n  for (int iter = 0; iter < iterations; iter++) {\n    Eigen::Matrix<double, 6, 6> H = Eigen::Matrix<double, 6, 6>::Zero();  //\u8fd9\u91cc\u4e4b\u6240\u4ee5\u662f 6 x 6 \u662f\u56e0\u4e3aJ(x)TJ(X) = H, J(X)\u662f2 x 6 \n    Vector6d b = Vector6d::Zero(); // b = J(x)Tf(x), J(x)T\u662f 6 x 2, f(x)\u662f x,y 2\u4e2a\u7ef4\u5ea6\u7684\u8bef\u5dee\uff0c\u6240\u4ee5\u662f2 x 1.\n    cost = 0;\n    // compute cost\n    for (int i = 0; i < points_3d.size(); i++) {\n      Eigen::Vector3d pc = pose * points_3d[i];\n      double inv_z = 1.0 / pc[2]; // 1/Z'\n      double inv_z2 = inv_z * inv_z;  // 1/Z^2\n      Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx, fy * pc[1] / pc[2] + cy);\n\n      Eigen::Vector2d e = points_2d[i] - proj;  // \u91cd\u6295\u5f71\u8bef\u5dee\n\n      cost += e.squaredNorm();\n      Eigen::Matrix<double, 2, 6> J;  // \u53ef\u4ee5\u76f4\u63a5\u5957\u7ed3\u8bba\u7684\u77e9\u9635\n      J << -fx * inv_z,\n        0,\n        fx * pc[0] * inv_z2,\n        fx * pc[0] * pc[1] * inv_z2,\n        -fx - fx * pc[0] * pc[0] * inv_z2,\n        fx * pc[1] * inv_z,\n        0,\n        -fy * inv_z,\n        fy * pc[1] * inv_z2,\n        fy + fy * pc[1] * pc[1] * inv_z2,\n        -fy * pc[0] * pc[1] * inv_z2,\n        -fy * pc[0] * inv_z;\n\n      H += J.transpose() * J;  // n\u70b9\u7d2f\u52a0\n      b += -J.transpose() * e;\n    }\n\n    Vector6d dx;\n    dx = H.ldlt().solve(b); // \u66f4\u65b0 se3\n\n    if (isnan(dx[0])) {\n      cout << \"result is nan!\" << endl;\n      break;\n    }\n\n    if (iter > 0 && cost >= lastCost) {\n      // cost increase, update is not good\n      cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n      break;\n    }\n\n    // update your estimation // \u66f4\u65b0SE(3)\n    pose = Sophus::SE3d::exp(dx) * pose; \n    lastCost = cost;\n\n    cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << endl;\n    if (dx.norm() < 1e-6) {  // \u5f53\u9700\u8981\u66f4\u65b0\u7684\u5de6\u4e58se(3)\u8db3\u591f\u5c0f\u3002\n      // converge\n      break;\n    }\n  }\n  cout << \"pose by g-n: \\n\" << pose.matrix() << endl;\n\n}\n\n// \u5b9a\u4e49 Vertex \u548c  Edge\n\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d>{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW; // Eigen \u5185\u90e8\u5904\u7406\u52a8\u6001\u5206\u914d\u53d8\u91cf\u7684\u5bf9\u9f50\u95ee\u9898\n    // setToOriginImpl()\u7528\u6765\u91cd\u7f6e\u4f18\u5316\u53d8\u91cf\uff0c \u8fd9\u91cc\u521d\u59cb\u5316\u4e00\u4e2a\u7a7a \u7684 SE3\n    // \u8fd9\u91cc\u4f7f\u7528\u865a\u51fd\u6570\u7684\u539f\u56e0\u662f\u7531C++11\u65b0\u7279\u6027\uff0c\u91cd\u5199\u4e86\u7236\u7c7b\u7684\u865a\u51fd\u6570\n    virtual void setToOriginImpl() override {\n    _estimate = Sophus::SE3d(); \n  }\n   /// left multiplication on SE3\uff0c setToOriginImpl()\u7528\u6765Upfate\u4f18\u5316\u53d8\u91cf,\u8fd9\u91cc\u4f7f\u7528\u5de6\u4e58\u6765\u66f4\u65b0\n  virtual void oplusImpl(const double *update) override {\n    Eigen::Matrix<double, 6, 1> update_eigen;\n    update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n    _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n  }\n    virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n};\n\n/// \u5b9a\u4e49\u8fb9\uff0c \u4e5f\u5c31\u662f\u91cd\u65b0\u6295\u5f71\u8bef\u5dee\uff0c \u6211\u4eec\u77e5\u9053\u91cd\u6295\u5f71\u8bef\u5dee\u4e3a2\u4f4d\uff0c \u7c7b\u578b\u662fvector2d, \u4f18\u5316\u5bf9\u8c61\u7684\u7c7b\u578b\u662f\u4e00\u4e2aVertexPose\nclass EdgeProjection : public g2o::BaseUnaryEdge<2, Eigen::Vector2d, VertexPose> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n // \u6784\u9020\u51fd\u6570\n  EdgeProjection(const Eigen::Vector3d &pos, const Eigen::Matrix3d &K) : _pos3d(pos), _K(K) {}\n// \u8ba1\u7b97\u91cd\u65b0\u6295\u5f71\u8bef\u5dee\n  virtual void computeError() override {\n    const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n    Sophus::SE3d T = v->estimate();  // \u83b7\u5f97\u9876\u70b9\u7684\u89c2\u6d4bvalue\n    Eigen::Vector3d pos_pixel = _K * (T * _pos3d); // // K TP = s[u,v]\n    pos_pixel /= pos_pixel[2]; // \u9f50\u6b21\u5230\u975e\u9f50\u6b21\n    _error = _measurement - pos_pixel.head<2>(); //_measurement\uff1a\u5b58\u50a8\u89c2\u6d4b\u503c\n  }\n   // \u66f4\u65b0\u64cd\u4f5c, \u5b9a\u4e49Jaco\u77e9\u9635\u5373\u53ef\uff0c\u8fd9\u91cc\u4f7f\u7528\u5c31\u662fG-N\u6cd5\n  virtual void linearizeOplus() override {\n    const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n    Sophus::SE3d T = v->estimate();\n    Eigen::Vector3d pos_cam = T * _pos3d;  \n    double fx = _K(0, 0);\n    double fy = _K(1, 1);\n    double cx = _K(0, 2);\n    double cy = _K(1, 2);\n    double X = pos_cam[0];\n    double Y = pos_cam[1];\n    double Z = pos_cam[2];\n    double Z2 = Z * Z;\n    _jacobianOplusXi\n      << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n      0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n  };\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n\nprivate:\n  Eigen::Vector3d _pos3d;\n  Eigen::Matrix3d _K;\n};\n\nvoid bundleAdjustmentG2O(\n  const VecVector3d &points_3d,  \n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose\n){\n  // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n  // pose is 6 \uff0c 3 for rotation, 3 for translation. landmark is 3 : X,Y,Z,\u89c2\u6d4b\u70b9\u7684\u7ef4\u5ea6\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // pose is 6, landmark is 3\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // \u7ebf\u6027\u6c42\u89e3\u5668, \u53bb\u4f18\u5316Pose Matrix\n    // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u53ef\u4ee5\u4eceGN, LM, DogLeg \u4e2d\u9009\uff0c \u63a5\u53d7\u4e00\u4e2aBlockSolverType,\u7528Linear\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n\n    g2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n  optimizer.setAlgorithm(solver);   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n  optimizer.setVerbose(true);       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n\n  // \u4e0b\u9762\u5f00\u59cb\u5f80\u56fe\u91cc\u9762\u6dfb\u52a0 Vertex \u548c Edge\n  // vertex\uff0c \u53ea\u6709\u4e00\u4e2aR,t\n  VertexPose *vertex_pose = new VertexPose(); // camera vertex_pose\n  vertex_pose->setId(0);\n  vertex_pose->setEstimate(Sophus::SE3d());\n  optimizer.addVertex(vertex_pose);\n\n    //  Camera K\n  Eigen::Matrix3d K_eigen;\n  K_eigen <<\n          K.at<double>(0, 0), K.at<double>(0, 1), K.at<double>(0, 2),\n    K.at<double>(1, 0), K.at<double>(1, 1), K.at<double>(1, 2),\n    K.at<double>(2, 0), K.at<double>(2, 1), K.at<double>(2, 2);\n\n  // edges\n  int index = 1;\n  for (size_t i = 0; i < points_2d.size(); ++i) {\n    auto p2d = points_2d[i];\n    auto p3d = points_3d[i];\n    EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n    edge->setId(index);\n    edge->setVertex(0, vertex_pose); // \u5bf9\u5e94\u6210\u5458\u51fd\u6570_vertex\n    edge->setMeasurement(p2d); // \u5bf9\u5e94\u6210\u5458\u51fd\u6570_mesurement\n    edge->setInformation(Eigen::Matrix2d::Identity()); // \u56fe\u4e2d\u7684Q\u5c31\u662f\u4fe1\u606f\u77e9\u9635\uff0c\u4e3a\u4e86\u8868\u793a\u6211\u4eec\u5bf9\u8bef\u5dee\u5404\u5206\u91cf\u91cd\u89c6\u7a0b\u5ea6\u7684\u4e0d\u4e00\u6837\u3002\n    // \u4e00\u822c\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u90fd\u8bbe\u7f6e\u8fd9\u4e2a\u77e9\u9635\u4e3a\u5355\u4f4d\u77e9\u9635\uff0c\u8868\u793a\u6211\u4eec\u5bf9\u6240\u6709\u7684\u8bef\u5dee\u5206\u91cf\u7684\u91cd\u89c6\u7a0b\u5ea6\u90fd\u4e00\u6837\u3002\n    optimizer.addEdge(edge);\n    index++;\n  }\n  optimizer.setVerbose(true);\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  cout << \"pose estimated by g2o =\\n\" << vertex_pose->estimate().matrix() << endl;\n  pose = vertex_pose->estimate();\n}", "meta": {"hexsha": "70c85929dc6c6c1d1ed363a763647d8a5f430177", "size": 12406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_stars_repo_name": "kant/VO", "max_stars_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-20T04:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T04:52:45.000Z", "max_issues_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_issues_repo_name": "kant/VO", "max_issues_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_forks_repo_name": "kant/VO", "max_forks_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T23:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T23:30:49.000Z", "avg_line_length": 34.7507002801, "max_line_length": 134, "alphanum_fraction": 0.6474286635, "num_tokens": 4565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.68703709162585}}
{"text": "#include <iostream>\n#include <chrono>\n#include <dlib/matrix.h>\n\nusing namespace dlib;\nusing namespace std;\n\n#define LOOP_COUNT 10\n\nint main()\n{\n    int m = 2000;\n    int p = 200;\n    int n = 1000;\n    \n    matrix<double> A(m,p);\n    matrix<double> B(p,n);\n    \n    for (int i = 0; i < m; i++)\n    {\n        for (int j = 0; j < p; j++)\n        {\n            A(i, j) = i * p + j + 1;\n        }\n    }\n    for (int i = 0; i < p; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            B(i, j) = -(i * n + j) - 1;\n        }\n    }\n    \n    cout << \"Making the first run of matrix product using the * operator\" << endl;\n    cout << \"to get stable run time measurements.\" << endl << endl;\n    matrix<double> C = A * B;\n    \n    cout << \"Measuring performance of matrix product using the * operator.\" << endl << endl;\n    auto start = chrono::steady_clock::now();\n    for (int i = 0; i < LOOP_COUNT;i++)\n    {\n        C = A * B;\n    }\n    auto end = chrono::steady_clock::now();\n    double elapsed_time = chrono::duration_cast<chrono::milliseconds>(end -start).count() / LOOP_COUNT;\n    cout << \"Elapsed time: \" << elapsed_time << \" milliseconds.\" << endl;\n}\n", "meta": {"hexsha": "612399c8f56a4eac4b7fe3977cf490a889cc9dcc", "size": 1163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matrix-multiplication-speed/Dlib/matrix_multiplication.cpp", "max_stars_repo_name": "trvoid/scientific-computing-examples", "max_stars_repo_head_hexsha": "490618ae3d2b638435dbd51e7d71c84bfcf55882", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-07T03:22:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T03:25:24.000Z", "max_issues_repo_path": "matrix-multiplication-speed/Dlib/matrix_multiplication.cpp", "max_issues_repo_name": "trvoid/scientific-computing-examples", "max_issues_repo_head_hexsha": "490618ae3d2b638435dbd51e7d71c84bfcf55882", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix-multiplication-speed/Dlib/matrix_multiplication.cpp", "max_forks_repo_name": "trvoid/scientific-computing-examples", "max_forks_repo_head_hexsha": "490618ae3d2b638435dbd51e7d71c84bfcf55882", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-10T03:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-10T03:09:36.000Z", "avg_line_length": 24.2291666667, "max_line_length": 103, "alphanum_fraction": 0.5116079106, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6870154763964507}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_euler_angles.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nusing namespace OpenTissue;\n\n\nvoid do_test( double const & phi_in, double const & psi_in, double const & theta_in)\n{\n  OpenTissue::math::Quaternion<double> Q_in;\n  OpenTissue::math::Quaternion<double> Q_out;\n  OpenTissue::math::Quaternion<double> identity;\n  OpenTissue::math::Quaternion<double> Qz1;\n  OpenTissue::math::Quaternion<double> Qy;\n  OpenTissue::math::Quaternion<double> Qz2;\n\n  double const too_small = 10e-7;\n\n  double phi_out   = 0.0;\n  double psi_out   = 0.0;\n  double theta_out = 0.0;\n\n  Qz1.Rz(theta_in);\n  Qy.Ry(psi_in);\n  Qz2.Rz(phi_in);\n\n  Q_in = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );\n\n  OpenTissue::math::ZYZ_euler_angles(Q_in,phi_out,psi_out,theta_out);\n\n  if(psi_in > 0.0)\n  {\n    // we only want to do this if we are not in a gimbal lock\n    Qz1.Rz(theta_out);\n    Qy.Ry(psi_out);\n    Qz2.Rz(phi_out);\n    Q_out = OpenTissue::math::prod( Qz2 , OpenTissue::math::prod( Qy , Qz1) );\n    identity = OpenTissue::math::prod( OpenTissue::math::conj(Q_out), Q_in );\n\n    double const s = fabs( fabs(identity.s())  - 1.0 );\n    double const v0 = fabs(identity.v()(0));\n    double const v1 = fabs(identity.v()(1));\n    double const v2 = fabs(identity.v()(2));\n\n    BOOST_CHECK( s < too_small);\n    BOOST_CHECK( v0 < too_small);\n    BOOST_CHECK( v1 < too_small);\n    BOOST_CHECK( v2 < too_small);\n\n    double const dphi = fabs(phi_in - phi_out);\n    double const dpsi = fabs(psi_in - psi_out);\n    double const dtheta = fabs(theta_in - theta_out);\n    BOOST_CHECK( dphi < too_small);\n    BOOST_CHECK( dpsi < too_small);\n    BOOST_CHECK( dtheta < too_small);\n  }\n  else\n  {\n    // In gimbal lock phi and theta behaves strangely\n    BOOST_CHECK_CLOSE( 0.0, theta_out, 0.01);\n    double const dpsi = fabs(psi_out);\n    BOOST_CHECK( dpsi < too_small);\n\n    double new_phi = phi_in + theta_in;\n    double const pi     = 3.1415926535897932384626433832795;\n    double const two_pi = 2.0*pi;\n    while(new_phi>pi) new_phi -= two_pi;\n    while(new_phi<-pi) new_phi += two_pi;\n\n    double const dphi = fabs(new_phi - phi_out);\n    BOOST_CHECK( dphi < too_small);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_euler_angles);\n\nBOOST_AUTO_TEST_CASE(ZYZ)\n{\n  size_t N = 15;\n\n  double const pi     = 3.1415926535897932384626433832795;\n  double const two_pi = 2.0*pi;\n  double const delta = (two_pi)/(N-1);\n\n  double phi = -pi+delta;\n  for(;phi<pi;)\n  {\n    double psi = 0.0;\n    for(;psi<pi;)\n    {\n      double theta = -pi+delta;\n      for(;theta<pi;)\n      {\n        do_test( phi, psi, theta );\n        theta += delta;\n      }\n      psi += delta;\n    }\n    phi += delta;\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "238de8358cb0938b34eacfe1305a0bb6b5442982", "size": 3202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/euler_angles/src/unit_euler_angles.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 27.3675213675, "max_line_length": 84, "alphanum_fraction": 0.6761399126, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.687015467764019}}
{"text": "#ifndef SEGWAY_SIM_COMMON_H\n#define SEGWAY_SIM_COMMON_H\n\n#include \"segway_sim/CyberTimer.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <functional>\n#include <signal.h>\n\nstatic const uint32_t STATE_LENGTH = 7;\nstatic const uint32_t INPUT_LENGTH = 2;\nstatic const uint32_t CMD_LENGTH = 2;\n\ninline void quat2eulZYX(const Eigen::Quaterniond &q,\n                              Eigen::Vector3d &eul)\n{\n\tdouble eul_tmp = 2.0 * (q.y() * q.y());\n\teul(0) = atan2(2.0 * q.w() * q.x() + 2.0 * q.y() * q.z(), (1.0 - 2.0 * (q.x() * q.x())) - eul_tmp);\n\t\n\tdouble sinp = +2.0 * (q.w() * q.y() - q.z() * q.x());\n\tif (abs(sinp) >= 1)\n\t\teul(1) = copysign(M_PI / 2, sinp); // use 90 degrees if out of range\n\telse\n\t\teul(1) = asin(sinp);\n\n\teul(2) = atan2(2.0 * q.w() * q.z() + 2.0 * q.x() * q.y(), (1.0 - eul_tmp) - 2.0 * (q.z() * q.z()));\n}\n\ninline void quat2rotm(const Eigen::Quaterniond &q,\n                            Eigen::Matrix3d &rotm)\n{\n\trotm(0,0) = 1-2*q.y()*q.y()-2*q.z()*q.z();\n\trotm(0,1) = 2*q.x()*q.y()-2*q.z()*q.w();\n\trotm(0,2) = 2*q.x()*q.z()+2*q.y()*q.w();\n\trotm(1,0) = 2*q.x()*q.y()+2*q.z()*q.w();\n\trotm(1,1) = 1-2*q.x()*q.x()-2*q.z()*q.z();\n\trotm(1,2) = 2*q.y()*q.z()-2*q.x()*q.w();\n\trotm(2,0) = 2*q.x()*q.z()-2*q.y()*q.w();\n\trotm(2,1) = 2*q.y()*q.z()+2*q.x()*q.w();\n\trotm(2,2) = 1-2*q.x()*q.x()-2*q.y()*q.y();\n}\n\ninline void eul2quatZYX(const Eigen::Vector3d &eul,\n                              Eigen::Quaterniond &q)\n{\n\tdouble cy = cos(eul(2) * 0.5);\n\tdouble sy = sin(eul(2) * 0.5);\n\tdouble cp = cos(eul(1) * 0.5);\n\tdouble sp = sin(eul(1) * 0.5);\n\tdouble cr = cos(eul(0) * 0.5);\n\tdouble sr = sin(eul(0) * 0.5);\n\n\tq.w() = cy * cp * cr + sy * sp * sr;\n\tq.x() = cy * cp * sr - sy * sp * cr;\n\tq.y() = sy * cp * sr + cy * sp * cr;\n\tq.z() = sy * cp * cr - cy * sp * sr;\n}\n\ninline void removeYaw(Eigen::Quaterniond &q)\n{\n\tEigen::Vector3d eul;\n\tquat2eulZYX(q,eul);\n\teul(2) = 0;\n\teul2quatZYX(eul,q);\n}\n\ninline Eigen::Matrix3d rotx(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) =  1; rotm(0,1) =           0; rotm(0,2) =           0;\n\trotm(1,0) =  0; rotm(1,1) =  cos(angle); rotm(1,2) = -sin(angle);\n\trotm(2,0) =  0; rotm(2,1) =  sin(angle); rotm(2,2) =  cos(angle);\n\treturn rotm;\n}\n\ninline Eigen::Matrix3d roty(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) =  cos(angle); rotm(0,1) =  0; rotm(0,2) = sin(angle);\n\trotm(1,0) =           0; rotm(1,1) =  1; rotm(1,2) = 0;\n\trotm(2,0) = -sin(angle); rotm(2,1) =  0; rotm(2,2) = cos(angle);\n\treturn rotm;\n}\n\ninline Eigen::Matrix3d rotz(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) =  cos(angle); rotm(0,1) = -sin(angle); rotm(0,2) = 0;\n\trotm(1,0) =  sin(angle); rotm(1,1) =  cos(angle); rotm(1,2) = 0;\n\trotm(2,0) =           0; rotm(2,1) =           0; rotm(2,2) = 1;\n\treturn rotm;\n}\n\ninline double deg2rad(double angle)\n{\n\treturn angle*M_PI/180.0;\n}\n\ninline double rad2deg(double angle)\n{\n\treturn angle*180.0/M_PI;\n}\n\ninline double saturate(double in, double min, double max)\n{\n\tdouble out;\n\tif(min>max)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tif(in>max)\n\t\tout = max;\n\telse if(in<min)\n\t\tout = min;\n\telse\n\t\tout = in;\n\n\treturn out;\n}\n\ninline void saturateInPlace(double &in, double min, double max)\n{\n\tif(min>max)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tif(in>max)\n\t\tin = max;\n\telse if(in<min)\n\t\tin = min;\n}\n\ninline void saturateInPlace(double in[], double min, double max, uint32_t len)\n{\n\tif(min>max)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tfor(uint32_t i = 0; i<len; i++)\n\t{\n\t\tif(in[i]>max)\n\t\t\tin[i] = max;\n\t\telse if(in[i]<min)\n\t\t\tin[i] = min;\n\t}\n\n}\n\ninline double constrainAngle(double x){\n    x = fmod(x + M_PI,2*M_PI);\n    if (x < 0)\n        x += M_PI;\n    return x - M_PI;\n}\n\ninline void omega2eulRatesZYX(const Eigen::Vector3d &omega,\n                              const Eigen::Quaterniond &q,\n                                    Eigen::Vector3d &eulDot)\n{\n\tEigen::Vector3d eul;\n\tquat2eulZYX(q,eul);\n\tconst double x = eul(0);\n\tconst double y = eul(1);\n\n\tEigen::Matrix3d M;\n\tM(0,0) = 1; M(0,1) = sin(x)*tan(y); M(0,2) = cos(x)*tan(y);\n\tM(1,0) = 0; M(1,1) =        cos(x); M(1,2) =       -sin(x);\n\tM(2,0) = 0; M(2,1) = sin(x)/cos(y); M(2,2) = cos(x)/cos(y);\n\n\teulDot = M*omega;\n}\n\ninline void eulRates2omegaZYX(const Eigen::Vector3d &eulDot,\n                              const Eigen::Quaterniond &q,\n                                    Eigen::Vector3d &omega)\n{\n\tEigen::Vector3d eul;\n\tquat2eulZYX(q,eul);\n\tconst double x = eul(0);\n\tconst double y = eul(1);\n\n\tEigen::Matrix3d M;\n\tM(0,0) = 1; M(0,1) =       0; M(0,2) =       -sin(y);\n\tM(1,0) = 0; M(1,1) =  cos(x); M(1,2) = sin(x)*cos(y);\n\tM(2,0) = 0; M(2,1) = -sin(x); M(2,2) = cos(x)*cos(y);\n\n\tomega = M*eulDot;\n}\n#endif", "meta": {"hexsha": "1a220c7f363b092f1c306143a902829c409e3016", "size": 4735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/segway_sim/common.hpp", "max_stars_repo_name": "hardikparwana/segway_sim", "max_stars_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-10-08T03:16:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-19T02:58:53.000Z", "max_issues_repo_path": "include/segway_sim/common.hpp", "max_issues_repo_name": "hardikparwana/segway_sim", "max_issues_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_issues_repo_licenses": ["MIT"], "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/segway_sim/common.hpp", "max_forks_repo_name": "hardikparwana/segway_sim", "max_forks_repo_head_hexsha": "792c8ed9e6e26e3e28e5f120be6822f178f17bf2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-10-07T22:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:22:21.000Z", "avg_line_length": 23.5572139303, "max_line_length": 100, "alphanum_fraction": 0.5349524815, "num_tokens": 1925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.686964519635166}}
{"text": "// Array stencil benchmark\n\n#include <blitz/array.h>\n#include <blitz/traversal.h>\n#include <blitz/benchext.h>\n#include <blitz/rand-uniform.h>\n#include <blitz/array/stencil-et.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n#if defined(BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES)\n  #define stencilf stencilf_\n  #define stencilftiled stencilftiled_\n  #define stencilf90 stencilf90_\n#elif defined(BZ_FORTRAN_SYMBOLS_CAPS)\n  #define stencilf       STENCILF\n  #define stencilftiled  STENCILFTILED\n  #define stencilf90     STENCILF90\n#endif\n\nextern \"C\" {\n    void stencilf(double* A, double* B, int& N, int& iters);\n    void stencilftiled(double* A, double* B, int& N, int& iters);\n    void stencilf90(double* A, double* B, int& N, int& iters);\n}\n\n#ifdef FORTRAN_90\nvoid stencilFortran90Version(BenchmarkExt<int>& bench);\n#endif\nvoid stencilFortran77Version(BenchmarkExt<int>& bench);\nvoid stencilFortran77VersionTiled(BenchmarkExt<int>& bench);\nvoid stencilBlitzVersion(BenchmarkExt<int>& bench);\nvoid stencilBlitzExpressionVersion(BenchmarkExt<int>& bench);\nvoid stencilBlitzProductVersion(BenchmarkExt<int>& bench);\nvoid stencilBlitzProductVersion2(BenchmarkExt<int>& bench);\nvoid stencilBlitzProductVersion3(BenchmarkExt<int>& bench);\nvoid stencilBlitzStencilVersion(BenchmarkExt<int>& bench);\nvoid stencilBlitzIndexVersion(BenchmarkExt<int>& bench);\n\nint main()\n{\n    int numBenchmarks = 10;\n#ifndef FORTRAN_90\n\t\tnumBenchmarks--;   // No fortran 90\n#endif\n\n    BenchmarkExt<int> bench(\"Array stencil\", numBenchmarks);\n\n    const int numSizes = 28;\n\n    bench.setNumParameters(numSizes);\n    bench.setRateDescription(\"Mflops/s\");\n\n    Vector<int> parameters(numSizes);\n    Vector<long> iters(numSizes);\n    Vector<double> flops(numSizes);\n\n    for (int i=0; i < numSizes; ++i)\n    {\n        parameters[i] = (i+1) * 8;\n        iters[i] = 32*8*8*8/(i+1)/(i+1)/(i+1)/4;\n        if (iters[i] < 2)\n            iters[i] = 2;\n        int npoints = parameters[i] - 2;\n        flops[i] = npoints * npoints * npoints * 7 * 2;\n    }\n\n    bench.setParameterVector(parameters);\n    bench.setIterations(iters);\n    bench.setOpsPerIteration(flops);\n\n    bench.beginBenchmarking();\n#ifdef FORTRAN_90\n    stencilFortran90Version(bench);\n#endif\n    stencilBlitzVersion(bench);\n    stencilBlitzStencilVersion(bench);\n    stencilBlitzExpressionVersion(bench);\n    stencilBlitzProductVersion(bench);\n    stencilBlitzProductVersion2(bench);\n    stencilBlitzProductVersion3(bench);\n    stencilBlitzIndexVersion(bench);\n    stencilFortran77Version(bench);\n    stencilFortran77VersionTiled(bench);\n    bench.endBenchmarking();\n\n    bench.saveMatlabGraph(\"stencil.m\",\"plot\");\n\n    return 0;\n}\n\nvoid initializeRandomDouble(double* data, int numElements, int stride = 1)\n{\n    static Random<Uniform> rnd;\n\n    for (int i=0; i < numElements; ++i)\n        data[i*stride] = rnd.random();\n}\n\nvoid stencilBlitzVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ Range Expr\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\n            A(I,J,K) = c * (B(I,J,K) + B(I+1,J,K) + B(I-1,J,K) + B(I,J+1,K)\n                + B(I,J-1,K) + B(I,J,K+1) + B(I,J,K-1));\n\n            B(I,J,K) = c * (A(I,J,K) + A(I+1,J,K) + A(I-1,J,K) + A(I,J+1,K)\n                + A(I,J-1,K) + A(I,J,K+1) + A(I,J,K-1));\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nBZ_DECLARE_STENCIL_OPERATOR1(test1,B)\nreturn (1./7) * ( (*B) + B.shift(1,0) + B.shift(-1,0) + B.shift(1,1)\n\t\t  + B.shift(-1,1) + B.shift(1,2) + B.shift(-1,2));\nBZ_END_STENCIL_OPERATOR\n\nBZ_ET_STENCIL(test1, double, double,shape(-1,-1,-1),shape(1,1,1))\n\nBZ_DECLARE_STENCIL2(test1stencil,A,B)\n  A=test1(B);\nBZ_END_STENCIL_WITH_SHAPE(shape(-1,-1,-1),shape(1,1,1))\n\nvoid stencilBlitzExpressionVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ StencilOp\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Stencil Operator: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    A(I,J,K) = test1(B);\n\n\t    B(I,J,K) = test1(A);\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilBlitzProductVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ product\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Stencil Operator on product: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N),C(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    C=B*B;\n\t    A(I,J,K) = test1(C);\n\t    C=A*A;\n\t    B(I,J,K) = test1(C);\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilBlitzProductVersion2(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ product w alloc\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Stencil Operator on product: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    {\n\t      Array<double,3>C(B*B);\n\t      A(I,J,K) = test1(C);\n\t    }\n\t    {\n\t      Array<double,3>C(A*A);\n\t      B(I,J,K) = test1(C);\n\t    }\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilBlitzProductVersion3(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ product expr\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Stencil Operator on product expr: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    A(I,J,K) = test1(B*B);\n\n\t    B(I,J,K) = test1(A*A);\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilBlitzIndexVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ Indexed StencilOp\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Indexed Stencil Operator: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    A(I,J,K) = test1(B(tensor::i, tensor::j, tensor::k));\n\n\t    B(I,J,K) = test1(A(tensor::i, tensor::j, tensor::k));\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilBlitzStencilVersion(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Blitz++ Stencil\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Blitz++ Stencil: N = \" << N << endl;\n        cout.flush();\n\n        long iters = bench.getIterations();\n\n        Array<double,3> A(N,N,N), B(N,N,N);\n        initializeRandomDouble(A.data(), N*N*N, A.stride(thirdDim));\n        initializeRandomDouble(B.data(), N*N*N, B.stride(thirdDim));\n        TinyVector<int,2> size = N-2;\n        generateFastTraversalOrder(size);\n        double c = 1/7.;\n       \n\t;        bench.start();\n        for (long i=0; i < iters; ++i)\n        {\n            Range I(1,N-2), J(1,N-2), K(1,N-2);\n\t    applyStencil(test1stencil(),A,B);\n\t    applyStencil(test1stencil(),B,A);\n        }\n        bench.stop();\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilFortran77Version(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Fortran 77\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 77: N = \" << N << endl;\n        cout.flush();\n\n        int iters = (int)bench.getIterations();\n\n        size_t arraySize = size_t(N) * size_t(N) * N;\n       \n        double* A = new double[arraySize];\n        double* B = new double[arraySize];\n\n        initializeRandomDouble(A, arraySize);\n        initializeRandomDouble(B, arraySize);\n\n        bench.start();\n        stencilf(A, B, N, iters);\n        bench.stop();\n\n        delete [] A;\n        delete [] B;\n    }\n\n    bench.endImplementation();\n}\n\nvoid stencilFortran77VersionTiled(BenchmarkExt<int>& bench)\n{\n    bench.beginImplementation(\"Fortran 77 (tiled)\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 77: N = \" << N << endl;\n        cout.flush();\n\n        int iters = (int)bench.getIterations();\n\n        size_t arraySize = size_t(N) * size_t(N) * N;\n\n        double* A = new double[arraySize];\n        double* B = new double[arraySize];\n\n        initializeRandomDouble(A, arraySize);\n        initializeRandomDouble(B, arraySize);\n\n        bench.start();\n        stencilftiled(A, B, N, iters);\n        bench.stop();\n\n        delete [] A;\n        delete [] B;\n    }\n\n    bench.endImplementation();\n}\n\n#ifdef FORTRAN_90\nvoid stencilFortran90Version(BenchmarkExt<int>& bench)\n{\n   bench.beginImplementation(\"Fortran 90\");\n\n    while (!bench.doneImplementationBenchmark())\n    {\n        int N = bench.getParameter();\n\n        cout << \"Fortran 90: N = \" << N << endl;\n        cout.flush();\n\n        int iters = (int)bench.getIterations();\n\n        size_t arraySize = size_t(N) * size_t(N) * N;\n\n        double* A = new double[arraySize];\n        double* B = new double[arraySize];\n\n        initializeRandomDouble(A, arraySize);\n        initializeRandomDouble(B, arraySize);\n\n        bench.start();\n        stencilf90(A, B, N, iters);\n        bench.stop();\n\n        delete [] A;\n        delete [] B;\n    }\n\n    bench.endImplementation();\n}\n#endif\n", "meta": {"hexsha": "e91fa102a20d856525abb5782a4ca0514c9a213e", "size": 12020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/stencil.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/benchmarks/stencil.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/benchmarks/stencil.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": 26.4757709251, "max_line_length": 78, "alphanum_fraction": 0.5883527454, "num_tokens": 3276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.6869254725603849}}
{"text": "/**\n * @brief 2D\u914d\u51c6 \u95ed\u5f0f\u89e3\u7b97\u6cd5\n * @author hqy\n * @date 2021.3.15\n */\n\n#include <opencv2/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/features2d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\ntemplate<typename T>\nvoid printMat(const T& mat, int size){\n    for (int i = 0; i < size; i++){\n        for (int j = 0; j < size - 1; j++){\n            std::cout << mat(i, j) << \", \";\n        }\n        std::cout << mat(i, size - 1) << std::endl;\n    }\n}\n\nvoid hMatrixSolver(\n    const std::vector<cv::DMatch>& matches,\n    const std::vector<cv::KeyPoint>& pts1,\n    const std::vector<cv::KeyPoint>& pts2,\n    Eigen::Matrix3d& H\n) {\n    int size = matches.size();\n    Eigen::Matrix3Xd P(3, size);\n    Eigen::Matrix3Xd Q(3, size);\n    P.setZero();\n    Q.setZero();\n    #pragma omp parallel for num_threads(8)\n    for (size_t i = 0; i < matches.size(); i++) {\n        const cv::Point2f& _p1 = pts1[matches[i].queryIdx].pt;\n        const cv::Point2f& _p2 = pts2[matches[i].trainIdx].pt;\n        P.block<3, 1>(0, i) = Eigen::Vector3d(_p1.x, _p1.y, 1);\n        Q.block<3, 1>(0, i) = Eigen::Vector3d(_p2.x, _p2.y, 1);\n    }\n    Eigen::Matrix3d PPT = P * P.transpose();\n    Eigen::Matrix3d inv = (PPT).ldlt().solve(Eigen::Matrix3d::Identity());    // LDLT\u5206\u89e3\u6c42\u9006\u77e9\u9635 (PP^T)\n    Eigen::Matrix3d res = PPT * inv;\n    H = Q * P.transpose() * inv;\n}\n\nvoid featureExtract(\n    const cv::Mat& src1,\n    const cv::Mat& src2,\n    cv::Mat& dst,\n    Eigen::Matrix3d& H\n){\n    std::vector<cv::DMatch> matches;\n    std::vector<cv::KeyPoint> pts1, pts2;\n    #define POINT_NUM 64\n    cv::Mat dscp1, dscp2;\n    #pragma omp parallel sections\n    {\n        #pragma omp section\n        {\n            cv::Ptr<cv::FeatureDetector> det1 = cv::ORB::create(POINT_NUM);\n            cv::Ptr<cv::DescriptorExtractor> des1 = cv::ORB::create(POINT_NUM);\n            det1->detectAndCompute(src1, cv::noArray(), pts1, dscp1);\n        }\n        #pragma omp section\n        {\n            cv::Ptr<cv::FeatureDetector> det2 =  cv::ORB::create(POINT_NUM);\n            cv::Ptr<cv::DescriptorExtractor> des2 =  cv::ORB::create(POINT_NUM);\n            det2->detectAndCompute(src2, cv::noArray(), pts2, dscp2);\n        }\n    }\n    std::cout << \"Parallel ORB descriptors found.\\n\";\n    cv::Ptr<cv::DescriptorMatcher> match = cv::DescriptorMatcher::create(cv::DescriptorMatcher::BRUTEFORCE_HAMMINGLUT);\n    match->match(dscp1, dscp2, matches);\n    std::cout << \"ORB descriptors matched.\\n\";\n    std::vector<cv::Point2f> crn1, crn2;\n    for (const cv::DMatch& mt: matches){\n        crn1.push_back(pts1[mt.queryIdx].pt);\n        crn2.push_back(pts2[mt.trainIdx].pt);\n    }\n    cv::Mat mask;\n    \n    cv::Mat cvH = cv::findHomography(crn1, crn2, mask, cv::RANSAC, 16);\n    printf(\"Homography found. mask is %d, %d, %d, %d\\n\", mask.cols, mask.rows, mask.type(), CV_8UC1);\n    printf(\"The original match num is %lu.\\n\", matches.size());\n    std::vector<cv::DMatch> truth;\n    for (size_t i = 0; i < matches.size(); i++){\n        if (mask.at<uchar>(i) == 1){\n            truth.push_back(matches[i]);\n        }\n    }\n    cv::drawMatches(src1, pts1, src2, pts2, truth, dst);\n    hMatrixSolver(truth, pts1, pts2, H);\n    for (int i = 0; i < 3; i++) {\n        for (int j = 0; j < 3; j++) {\n            printf(\"%lf, \", cvH.at<double>(i, j));\n        }\n        printf(\"\\n\");\n    }\n}\n\n\n/// \u53ef\u89c6\u5316\nvoid alignmentVisualize(const cv::Mat& src, cv::Mat&dst, Eigen::Matrix3d H) {\n    dst.create(src.rows, src.cols, CV_8UC3);\n    #pragma for num_threads(8);\n    for (int i = 0; i < src.rows; i++) {\n        for (int j = 0; j < src.cols; j++) {\n            Eigen::Vector3d now(j, i, 1.0);\n            Eigen::Vector3d trans = H * now;\n            int px = trans[0], py = trans[1];\n            if (px >= 0 && px < dst.cols && py >= 0 && py < dst.rows) {\n                dst.at<cv::Vec3b>(py, px) = src.at<cv::Vec3b>(i, j);\n            } \n        }\n    }\n}\n\nint main() {\n    cv::Mat src1 = cv::imread(\"../data/ImageA.jpg\");\n    cv::Mat src2 = cv::imread(\"../data/ImageB.jpg\");\n    cv::Mat gray1, gray2;\n    cv::cvtColor(src1, gray1, cv::COLOR_BGR2GRAY);\n    cv::cvtColor(src2, gray2, cv::COLOR_BGR2GRAY);\n    cv::equalizeHist(gray1, gray1);\n    cv::equalizeHist(gray2, gray2);\n    cv::Mat aligned;\n    cv::Mat feats;\n\n    Eigen::Matrix3d H;\n\n    featureExtract(gray1, gray2, feats, H);\n    std::cout << \"H matrix is:\\n\";\n    printMat<Eigen::Matrix3d>(H, 3);\n    cv::imwrite(\"../data/features.jpg\", feats);\n\n    alignmentVisualize(src1, aligned, H);\n    cv::imwrite(\"../data/result.jpg\", aligned);\n    return 0;\n}", "meta": {"hexsha": "af1ae2bba3d655b1ffc8051dacdaef4a760f682a", "size": 4620, "ext": "cc", "lang": "C++", "max_stars_repo_path": "second/align.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": "second/align.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": "second/align.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.3076923077, "max_line_length": 119, "alphanum_fraction": 0.5681818182, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6869024410469349}}
{"text": "/**\n * Kalman Filter \n * Skeleton code for teaching \n * A3M33MKR\n * Czech Technical University \n * Faculty of Electrical Engineering\n * Intelligent and Mobile Robotics group\n *\n * Authors: Zden\u011bk Kasl, Karel Ko\u0161nar kosnar@labe.felk.cvut.cz\n *\n * this code is inspired by tutorial on Kalman Filter by Greg Czerniak \n *\n * Licence: MIT (see LICENSE file)\n **/\n/*TODO set up the convarience matrices better and re-measure the noice constants (process noise/measurenment noice)*/\n\n#include<cmath>\n#include<cassert>\n#include<cstdlib>\n#include<fstream>\n#include<iostream>\n#include <Eigen/Dense>\n\n#include \"gui/gui.h\"\n#include \"systemSimulator/system.h\"\n\nusing namespace imr;\nusing namespace gui;\nusing namespace Eigen;\nusing namespace std;\n\n#define PRINT(name) Print(#name, (name))\n\nvoid Print(const char *name, Matrix4f m);\n\nPoint KalmanFilter(Point measuredPosition);\n\nIOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\n\nMatrix4f A, B, Sigma, R, Q, E, C;\n//Matrix2f Q;\n//Matrix<float, 2, 4> C;\nVector4f mu, u;\nfloat dt = 0.1;\n\n//noice constants\ndouble q = 100;\ndouble r = 0.1;\n\n//step constant\nint step = 10;\n\nvoid initMatrices() {\n    A << 1, 0, dt, 0,\n            0, 1, 0, dt,\n            0, 0, 1, 0,\n            0, 0, 0, 1;\n\n    B << 0, 0, 0, 0,\n            0, -0.5 * dt * dt, 0, 0,\n            0, 0, 0, 0,\n            0, 0, 0, -dt;\n\n    u << 9.8, 9.8, 9.8, 9.8;\n\n    mu << -300, 100, 0, 0;\n\n    Sigma << 0.1, 0, 0, 0,\n            0, 0.1, 0, 0,\n            0, 0, 0.1, 0,\n            0, 0, 0, 0.1;\n\n// /Noice consts.\n//-------------------------------------------------------------------\n    C <<    1, 0, 0, 0,\n            0, 1, 0, 0,\n            0, 0, 1, 0,\n            0, 0, 0, 1;\n\n    Q <<    q, 0, 0, 0,\n            0, q, 0, 0,\n            0, 0, q, 0,\n            0, 0, 0, q;\n\n    R <<    r, 0, 0, 0,\n            0, r, 0, 0,\n            0, 0, r, 0,\n            0, 0, 0, r;\n//-------------------------------------------------------------------\n    E <<    1, 0, 0, 0,\n            0, 1, 0, 0,\n            0, 0, 1, 0,\n            0, 0, 0, 1;\n}\n\n\nvoid help(char **argv) {\n    std::cout << \"\\nUsage of the program \" << argv[0] + 2 << std::endl\n              << \"Parameter [-h or -H] displays this message.\" << std::endl\n              << \" Parametr [-n or -N] number of simulation steps.\"\n              << std::endl;\n}\n\nint main(int argc, char **argv) {\n    int nSteps = 1000;\n    char *dataFile;\n\n    // Parse all console parameters\n    for (int i = 0; i < argc; i++) {\n        if (argv[i][0] == '-') {\n            switch (argv[i][1]) {\n                //> HELP\n                case 'H' :\n                case 'h' :\n                    help(argv);\n                    break;\n                case 'N':\n                case 'n':\n                    assert(i + 1 < argc);\n                    assert(atoi(argv[i + 1]) > 1);\n                    step = atoi(argv[i + 1]);\n                    break;\n                default :\n                    std::cout << \"Parameter \\033[1;31m\" << argv[i] << \"\\033[0m is not valid!\\n\"\n                              << \"Use parameter -h or -H for help.\" << std::endl;\n                    break;\n            }\n        }\n    }\n    // All parameters parsed\n\n    Gui gui;\n    System system;\n\n    //> comment line below in order to let the program\n    //> continue right away\n    gui.startInteractor();\n\n    initMatrices();\n\n    Point measurement;\n    Point truth;\n    Point kfPosition;\n\n\n    for (int i = 1; i < nSteps; i++) {\n        system.makeStep();\n        truth = system.getTruthPosition();\n        measurement = system.getMeasurement();\n        kfPosition = KalmanFilter(measurement);\n        gui.setPoints(truth, measurement, kfPosition);\n\n        //> comment line below in order to let the program\n        //> continue right away\n        //if (i % step == 0) gui.startInteractor();\n\n    }\n    gui.startInteractor();\n    return EXIT_SUCCESS;\n}\n\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n//                               implement Kalman Filter here\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\nPoint KalmanFilter(const Point measuredPosition) {\n    Point ret;\n    Vector4f mu_actual, z, y;\n    Matrix4f Sigma_actual, K, S, S_inv;\n\n    z << measuredPosition.x,\n            measuredPosition.y,\n            0,\n            0;\n\n    PRINT(A);\n    PRINT(C);\n    //-------------------------------------------------------------------------------\n    mu_actual = A * mu + B * u;\n\n    //Error estimation\n    //-------------------------------------------------------------------------------\n    Sigma_actual = A * Sigma * A.transpose() + R;\n    PRINT(Sigma_actual);\n\n    //K gain\n    //-------------------------------------------------------------------------------\n    S = C * Sigma_actual * C.transpose() + Q;\n    PRINT(S);\n\n    K = Sigma_actual * C.transpose() * S.inverse();\n    PRINT(K);\n\n    //improvement\n    //-------------------------------------------------------------------------------\n    y = z - C * mu_actual;\n    mu = mu_actual + K * y;\n    Sigma = (E - K * C) * Sigma_actual;\n    PRINT(Sigma);\n\n    ret.x = mu(0);\n    ret.y = mu(1);\n\n    //Simulation of system\n    //ret.x = mu_actual(0);\n    //ret.y = mu_actual(1);\n    //mu = mu_actual;\n\n    cout << \"X: \" << ret.x << \"    Y: \" << ret.y <<\n             \"    Vx: \" << mu(2) << \"    Vy: \" << mu(3) << endl;\n    cout << \"-------------------------------------------------------------------\" << endl;\n\n    return ret;\n}\n\nvoid Print(const char *name, Matrix4f m){\n    cout << name << \": \" << endl;\n    cout << m.format(CleanFmt) << endl;\n    cout << \"-------------------------------------------------------------------\" << endl;\n}\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n\n", "meta": {"hexsha": "8c561f41e28422cf1a62ac1e3d875f0b9ed8fcf8", "size": 5868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kf_main.cpp", "max_stars_repo_name": "ondrejKunte/Kalman", "max_stars_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kf_main.cpp", "max_issues_repo_name": "ondrejKunte/Kalman", "max_issues_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kf_main.cpp", "max_forks_repo_name": "ondrejKunte/Kalman", "max_forks_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_forks_repo_licenses": ["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.6244541485, "max_line_length": 117, "alphanum_fraction": 0.4074642127, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.686833913658352}}
{"text": "// Software License for MTL\r\n//\r\n// Copyright (c) 2007 The Trustees of Indiana University.\r\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\r\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\r\n// All rights reserved.\r\n// Authors: Shikhar Vashistha\r\n//\r\n// This file is part of the Matrix Template Library\r\n//\r\n// See also license.mtl.txt in the distribution.\r\n\r\n#include <iostream>\r\n#include <boost/utility.hpp>\r\n#include <boost/numeric/mtl/mtl.hpp>\r\n\r\n\r\nusing namespace std;\r\n\r\n\r\ndouble f(double) { /* cout << \"double\\n\"; */ return 1.0; }\r\ncomplex<double> f(complex<double>)\r\n{\r\n    //cout << \"complex\\n\"; \r\n    return complex<double>(1.0, -1.0);\r\n}\r\n\r\n\r\nint main(int, char**)\r\n{\r\n    using namespace mtl; using mtl::io::tout;\r\n    unsigned size = 4, row = size + 1, col = size;\r\n\r\n    double tol(0.00001);\r\n    dense_vector<double>                vec(size), vec1(size);\r\n    dense2D<double>                     A(row, col), Q(row, row), R(row, col), A_test(row, col),\r\n        A_t(col, row), Q_t(col, col), R_t(col, row), A_t_test(col, row);\r\n    dense2D<complex<double> >                            dz(row, col), Qz(row, row), Rz(row, col);\r\n    dense2D<double, mat::parameters<col_major> >         dc(size, size);\r\n    compressed2D<double>                                 Ac(size, size), Qc(size, size), Rc(size, size), A_testc(size, size);\r\n    A = 0;\r\n\r\n    A[0][0] = 1;    A[0][1] = 1;    A[0][2] = 1;\r\n    A[1][0] = 3;    A[1][1] = -1;   A[1][2] = -2;\r\n    A[2][0] = 1;    A[2][1] = 7;    A[2][2] = 1;\r\n    A[3][3] = -10;  A[4][0] = 4;    A[4][2] = 3;\r\n    tout << \"A=\\n\" << A << \"\\n\";\r\n    laplacian_setup(Ac, 2, 2);\r\n\r\n\r\n    tout << \"START-----dense2d---------row > col\\n\";\r\n\r\n    dense2D<double> A1(A[iall][iall]), A2(A);\r\n    boost::tie(Q, R) = lq(A1);\r\n    tout << \"R=\\n\" << R << \"\\n\";\r\n    tout << \"Q=\\n\" << Q << \"\\n\";\r\n    A_test = Q * R - A2;\r\n    tout << \"Q*R=\\n\" << Q * R << \"\\n\";\r\n\r\n    tout << \"one_norm(Rest A)=\" << one_norm(A_test) << \"\\n\";\r\n    MTL_THROW_IF(one_norm(A_test) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix A\"));\r\n\r\n\r\n    tout << \"START------dense2d-------row < col\\n\";\r\n\r\n    A_t = trans(A);\r\n    boost::tie(Q_t, R_t) = lq(A_t);\r\n    tout << \"R_t=\\n\" << R_t << \"\\n\";\r\n    tout << \"Q_t=\\n\" << Q_t << \"\\n\";\r\n    A_t_test = Q_t * R_t - A_t;\r\n    tout << \"Q_t*R_t=\\n\" << Q_t * R_t << \"\\n\";\r\n\r\n    tout << \"one_norm(Rest A')=\" << one_norm(A_t_test) << \"\\n\";\r\n    MTL_THROW_IF(one_norm(A_t_test) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix trans(A)\"));\r\n\r\n    tout << \"START-------compressed2d-------row > col\\n\";\r\n#if 1\r\n    boost::tie(Qc, Rc) = lq(Ac);\r\n    tout << \"R=\\n\" << Rc << \"\\n\";\r\n    tout << \"Q=\\n\" << Qc << \"\\n\";\r\n    A_testc = Qc * Rc - Ac;\r\n    tout << \"Q*R=\\n\" << Qc * Rc << \"\\n\";\r\n    tout << \"A=\\n\" << Ac << \"\\n\";\r\n\r\n    tout << \"one_norm(Rest A)=\" << one_norm(A_testc) << \"\\n\";\r\n    MTL_THROW_IF(one_norm(A_testc) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix A\"));\r\n#endif\r\n\r\n#if 0\r\n    dz[0][0] = complex<double>(1.0, 0.0);\r\n    dz[0][1] = complex<double>(1.0, 0.0);\r\n    dz[0][2] = complex<double>(1, 0);\r\n    dz[1][0] = complex<double>(1, 0);\r\n    dz[1][1] = complex<double>(-1, 0);\r\n    dz[1][2] = complex<double>(-2, 0);\r\n    dz[2][0] = complex<double>(1, 0);\r\n    dz[2][1] = complex<double>(-2, 0);\r\n    dz[2][2] = complex<double>(1, 0);\r\n    dz[3][3] = complex<double>(-10, 0);\r\n    tout << \"MAtrix complex=\\n\" << dz << \"\\n\";\r\n\r\n    tout << \"START-----complex---------\" << dz[0][0] << \"\\n\";\r\n    //AxB==BxA(For square matrix) LQ==QR(Transpose(A)\r\n    boost::tie(Qz, Rz) = lq(dz);\r\n    // Rz= lq_zerl(dz).second;\r\n    // tout<<\"MAtrix  R=\"<< Rz <<\"\\n\";\r\n    // tout<<\"MAtrix  Q=\"<< Qz <<\"\\n\";\r\n    // tout<<\"MAtrix  A=Q*R--outside\"<< Qz*Rz <<\"\\n\";\r\n#endif\r\n    /*\r\n    Normal equations\r\n    A^T A x = A^T b\r\n    \r\n    These equations are called the normal equations of the least squares problem\r\n    \r\n    Coefficient matrix  A^TA is the Gram matrix of A\r\n\r\n    Equivalent to del f(x) = 0 where f(x) = ||Ax-b||^2\r\n\r\n    All solutions of the least squares problem satisfy the normal equations.\r\n\r\n\r\n    if A has linearly independent columns, then:\r\n\r\n    A^T is non-singular\r\n    \r\n    Normal equations have unique solution xcap=(A^T A)^-1 A^T b\r\n     */\r\n    //Rewriting least squares solution using QR/LQ factorization A = QR, QR==LQ(transpose(A)).\r\n    //  x = R^-1 Q^T x b\r\n    /*  1. compute QR factorization A = QR(2mn^2 flops if A is m \u00d7 n)\r\n        2. matrix - vector product d = Q^T b(2mn flops)\r\n        3. solve Rx = d by back substitution(n^2 flops)\r\n        complexity: 2mn^2 flops\r\n    */\r\n    /*\r\n       Example\r\n\r\n         | 3 -6|    |-1 |\r\n       A=| 4 -8|, b=| 7 |\r\n\t | 0  1|    | 2 |\r\n     \r\n    1. QR/LQ factorization A = QR/LQ with\r\n\r\n          |3/5 0|    \r\n    \tQ=|4/5 0|, R=|5 -10|\r\n     \t  | 0  1|    |0\t 1 |\r\n\r\n    2. calculate d=Q^Tb = (5,2)\r\n\r\n    3. solve Rx=d\r\n    \t\t\r\n    \t|5 -10| |x1| = |5|\r\n\t|0  1 | |x2|   |2|\r\n\r\n\tsolution is x1=5, x2=2\t\r\n     \r\n     */\r\n    //Problem with regular method occurs when forming Gram matrix A^T A as it is unstable\r\n    //QR factorization method is more stable because it avoids forming A^T A\r\n    dense2D<double> x(A[iall][iall]),d(A[iall][iall]),b(A[iall][iall]);\r\n    hessian_setup(x, 3.0); hessian_setup(d, 1.0);\r\n    hessian_setup(b, 3.0);\r\n    b[0][0] = -1, b[1][0] = 7, b[2][0] = 2;\r\n    boost::tie(Q, R) = lq(A);\r\n    mult(Q,b,d);\r\n    d = trans(Q) * b;\r\n    //d = trans(Q) * b;\r\n    //lq decomposition is performed here so R==L here \r\n    x = inv(R) * d;\r\n    tout << \"Solution to least square's problem is:\" << x;\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "96c3fe58e4c58e61ac3d94449377fa8d121223bf", "size": 5670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/lq_test.cpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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/lq_test.cpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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/lq_test.cpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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": 32.5862068966, "max_line_length": 126, "alphanum_fraction": 0.5091710758, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.6868338495844546}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n\nint main()\n{\n  Eigen::Vector4d v;\n  Eigen::Matrix4d C;\n\n  v << 1,2,3,4;\n  C = v.asDiagonal();\n\n  std::cout << C << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a01e1b606fc8a72412144824e6742346ae1f37cd", "size": 184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/eigen/diagonal_matrix.cpp", "max_stars_repo_name": "RyuYamamoto/sandbox", "max_stars_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_stars_repo_licenses": ["MIT"], "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++/eigen/diagonal_matrix.cpp", "max_issues_repo_name": "RyuYamamoto/sandbox", "max_issues_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_issues_repo_licenses": ["MIT"], "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++/eigen/diagonal_matrix.cpp", "max_forks_repo_name": "RyuYamamoto/sandbox", "max_forks_repo_head_hexsha": "799f32f92eea944c8d467cccd24f8bd4cd80a9d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.5, "max_line_length": 30, "alphanum_fraction": 0.5706521739, "num_tokens": 66, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6868080589820569}}
{"text": "//\n// Created by Sabar Nimmagadda on 4/25/20.\n//\n#include \"Linear Algebra/computations.h\"\n#include <Eigen/LU>\n\n#include <Eigen/QR>\n#include <Eigen/Householder>\n#include <Eigen/Eigenvalues>\n\n\nusing Eigen::MatrixXd;\nusing std::string;\n\n\n  MatrixXd Computations::ComputeL(MatrixXd m) {\n     typedef Eigen::Matrix<double, 3, 3 > L_Matrix;\n     Eigen::FullPivLU<L_Matrix> lu(m);\n     //Since the L matrix is a square matrix with the rowsize of the original matrix.\n     L_Matrix l = L_Matrix::Identity();\n     l.block<3,3>(0,0).triangularView<Eigen::StrictlyLower>() = lu.matrixLU();\n     return l;\n  }\n  MatrixXd Computations::ComputeU(MatrixXd m) {\n     typedef Eigen::Matrix<double, 3, 3> U_Matrix;\n     Eigen::FullPivLU<U_Matrix> lu(m);\n     //Since the U matrix has the exact dimensions of the original matrix.\n     U_Matrix u = lu.matrixLU().triangularView<Eigen::Upper>();\n     return u;\n  }\n  MatrixXd Computations::ComputePermutationMatrix(MatrixXd m) {\n      typedef Eigen::Matrix<double, 3, 3> P_Matrix;\n      Eigen::FullPivLU<P_Matrix> lu(m);\n      P_Matrix p = lu.matrixLU();\n      return p;\n  }\n  MatrixXd Computations::ComputeInverse(const MatrixXd& m) {\n      return m.inverse();\n  }\n\n  MatrixXd Computations::ComputeRREF(const MatrixXd& m) {\n      if (m.rows() >= 1 && m.cols() >= 1) {\n          int lead = 0;\n          MatrixXd out = m;\n          while (lead < m.rows()) {\n              float divisor, multiplier;\n              for (int r = 0; r < m.rows(); r++) {\n                  if (out(lead, lead) != 0) {\n                      divisor = out(lead, lead); //What divides a cell to make its value = 1.\n                      multiplier = out(r, lead)/ out(lead, lead); //What is multiplied to a cell, so that when it is subtracted the value becomes 0.\n                  } else {\n                      divisor = 1;\n                      multiplier = 1;\n                  }\n                  for(int c = 0; c < m.cols(); c++) {\n                      if (lead == r) {\n                          out(r,c) /= divisor;//This makes the pivots = 1.\n                      } else {\n                          out(r,c) -= out(lead, c) * multiplier; //Making everything that is not a pivot = 0;\n                      }\n                  }\n              }\n              lead++;\n          }\n          return out;\n      }\n  }\n\n  MatrixXd Computations::ComputeMultiply(MatrixXd matrix1, MatrixXd matrix2) {\n      if (matrix1.cols() == matrix2.rows()) {\n          return matrix1*matrix2;\n      }\n  }\n\n  MatrixXd Computations::ComputeR(const MatrixXd& matrix) {\n      Eigen::HouseholderQR<M3X3> qr(matrix.rows(), matrix.cols());\n      qr.compute(matrix);\n      MatrixXd R = qr.matrixQR().triangularView<Eigen::Upper>();\n      return R;\n  }\n\n  MatrixXd Computations::ComputeQ(const MatrixXd& matrix) {\n      Eigen::HouseholderQR<M3X3> qr(matrix.rows(), matrix.cols());\n      qr.compute(matrix);\n      MatrixXd Q = qr.householderQ();\n      return Q;\n  }\n\n  double Computations::ComputeDotProduct(MatrixXd matrix1, MatrixXd matrix2, int dim) {\n      double product = 0;\n      for (int i = 0; i < dim; i++) {\n          for (int j = 0; j < dim; j++) {\n              product += matrix1(i, j) * matrix2(i, j);\n          }\n      }\n      return product;\n  }\n\n  VectorXcd Computations::ComputeEigenValues(const MatrixXd& matrix) {\n      VectorXcd ret = matrix.eigenvalues();\n      return ret;\n  }\n\n  MatrixXcd Computations::ComputeEigenVectors(const MatrixXd& matrix) {\n      Eigen::EigenSolver<MatrixXd> es(matrix);\n      return es.eigenvectors();\n  }\n\n  int Computations::ComputeDeterminant(const MatrixXd& matrix) {\n      return matrix.determinant();\n  }\n  MatrixXd Computations::ComputeColSpace(MatrixXd matrix) {\n      if (matrix.size() >= 1) {\n          Eigen::ColPivHouseholderQR<MatrixXd> qr(matrix);\n          MatrixXd new_mat;\n          if (qr.rank() != 0) {\n              for (auto i : qr.colsPermutation().indices()) {\n                  new_mat.col(i) = matrix.col(i);\n              }\n              return new_mat;\n          }\n          return new_mat;\n      }\n  }\n\n  MatrixXd Computations::ComputeRowSpace(MatrixXd matrix) {\n      MatrixXd transp = matrix.transpose();\n      Eigen::ColPivHouseholderQR<MatrixXd> qr(transp);\n      MatrixXd new_mat;\n      for (auto i : qr.colsPermutation().indices()) {\n          new_mat.col(i) = transp.col(i);\n      }\n      return new_mat;\n  }\n\n\n\n", "meta": {"hexsha": "9121938685a2f029015f4d792c0722af5009e608", "size": 4379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/computations.cpp", "max_stars_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_stars_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_stars_repo_licenses": ["MIT"], "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/computations.cpp", "max_issues_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_issues_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_issues_repo_licenses": ["MIT"], "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/computations.cpp", "max_forks_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_forks_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_forks_repo_licenses": ["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.731884058, "max_line_length": 148, "alphanum_fraction": 0.5670244348, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6867926360291264}}
{"text": "// =============================================================================\n//                    MetaProg Chapter III Solution 1\n//                         Author : Xin Liu\n// =============================================================================\n\n#include <iostream>\n#include <limits>\n#include <type_traits>\n#include <boost/mpl/apply.hpp>\n#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/multiplies.hpp>\n\n\nnamespace mpl = boost::mpl;\n\n////////////////////////////////////////////////////////////////////////////////\nnamespace dimension_analysis\n{\n    using mass                  = mpl::vector_c<int, 1, 0, 0, 0, 0, 0, 0>;\n    using length                = mpl::vector_c<int, 0, 1, 0, 0, 0, 0, 0>;\n    using time                  = mpl::vector_c<int, 0, 0, 1, 0, 0, 0, 0>;\n    using charge                = mpl::vector_c<int, 0, 0, 0, 1, 0, 0, 0>;\n    using temperature           = mpl::vector_c<int, 0, 0, 0, 0, 1, 0, 0>;\n    using intensity             = mpl::vector_c<int, 0, 0, 0, 0, 0, 1, 0>;\n    using amount_of_substance   = mpl::vector_c<int, 0, 0, 0, 0, 0, 0, 1>;\n\n    using velocity              = mpl::vector_c<int, 0, 1, -1, 0, 0, 0, 0>; // l/t\n    using acceleration          = mpl::vector_c<int, 0, 1, -2, 0, 0, 0, 0>; // l/(t^2)\n    using momentum              = mpl::vector_c<int, 1, 1, -1, 0, 0, 0, 0>; // ml/t\n    using force                 = mpl::vector_c<int, 1, 1, -2, 0, 0, 0, 0>; // ml/(t^2)\n\n    using scalar                = mpl::vector_c<int, 0, 0, 0, 0, 0, 0, 0>;\n\n\n    template<typename T, typename Dimensions>\n    class quantity\n    {\n    public:\n        explicit quantity(T x)\n                : m_value(x)\n        { }\n\n        template <typename OtherDimensions>\n        quantity(quantity<T, OtherDimensions> const& q)\n                : m_value(q.value())\n        {\n            static_assert(mpl::equal<Dimensions, OtherDimensions>::type::value, \"OtherDimensions should be same as Dimensions.\");\n        }\n\n    public:\n        T value() const\n        {\n            return m_value;\n        }\n\n    private:\n        T m_value;\n    };\n\n    template <typename T, typename D>\n    quantity<T, D>\n    operator+ (const quantity<T, D>& lhs, const quantity<T, D>& rhs)\n    {\n        //static_assert(mpl::equal<D1, D2>(), \"D1 and D2 dimensions should be same.\");\n        return quantity<T, D>(lhs.value() + rhs.value());\n    }\n\n    template <typename T, typename D>\n    quantity<T, D>\n    operator- (const quantity<T, D>& lhs, const quantity<T, D>& rhs)\n    {\n        //static_assert(mpl::equal<D1, D2>(), \"D1 and D2 dimensions should be same.\");\n        return quantity<T, D>(lhs.value() - rhs.value());\n    }\n\n    using mpl::placeholders::_;\n\n    template <typename D1, typename D2>\n    struct multiply_dimensions\n            : mpl::transform<D1, D2, mpl::plus<_, _> >\n    { };\n\n    template <typename T, typename D1, typename D2>\n    quantity<T, typename multiply_dimensions<D1, D2>::type>\n    operator* (const quantity<T, D1>& lhs, const quantity<T, D2>& rhs)\n    {\n        return quantity<T, typename multiply_dimensions<D1, D2>::type>(lhs.value() * rhs.value());\n    }\n\n    template <typename D1, typename D2>\n    struct divide_dimensions\n            : mpl::transform<D1, D2, mpl::minus<_, _>>\n    { };\n\n    template <typename T, typename D1, typename D2>\n    quantity<T, typename divide_dimensions<D1, D2>::type>\n    operator/ (const quantity<T, D1>& lhs, const quantity<T, D2>& rhs)\n    {\n        return quantity<T, typename divide_dimensions<D1, D2>::type>(lhs.value() / rhs.value());\n    }\n} // namespace dimension_analysis\n\n\nint main()\n{\n    using namespace dimension_analysis;\n\n    quantity<float, length> l{ 1.0f };\n    quantity<float, mass> m{ 2.0f };\n\n    // expected compile error\n    // m = l;\n\n    quantity<float, length> len1{ 1.0f };\n    quantity<float, length> len2{ 2.0f };\n\n    len1 = len1 + len2;\n\n    // expected compile error\n    //len1 = len2 + quantity<float, mass>{ 3.7f };\n\n    quantity<float, mass> m1{ 5.0f };\n    quantity<float, mass> m3{ 10.0f };\n    quantity<float, acceleration> a1{ 9.8f };\n\n    quantity<float, force> f1 = m1 * a1;\n\n    quantity<float, mass> m2 = f1 / a1;\n    float rounding_error = std::abs((m2 - m1).value());\n    std::cout << \"error: \" << rounding_error << \"\\n\";\n\n    f1 = f1 + (quantity<float, force>)(m3 * a1);\n    float rounding_error2 = std::abs((m2 - m1).value());\n    std::cout << \"error2: \" << rounding_error2 << \"\\n\";\n    bool res = rounding_error2 <= std::numeric_limits<float>::min(); \n    if(res) return 0;\n    else return -1;\n}\n", "meta": {"hexsha": "d40ed7f138200c440ad8e4af3e24b6ff937e128e", "size": 4668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ChapterIII/Solution1/main.cpp", "max_stars_repo_name": "Trigolds/MetaCppNN", "max_stars_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ChapterIII/Solution1/main.cpp", "max_issues_repo_name": "Trigolds/MetaCppNN", "max_issues_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ChapterIII/Solution1/main.cpp", "max_forks_repo_name": "Trigolds/MetaCppNN", "max_forks_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_forks_repo_licenses": ["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.6433566434, "max_line_length": 129, "alphanum_fraction": 0.5379177378, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6867917367463804}}
{"text": "#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <utility>\n#include <vector>\n// this header only for ch8\n#ifndef STATISTICS_HPP\n#define STATISTICS_HPP\nusing namespace std;\n\ndouble genZValue(double alpha) {\n    boost::math::normal Ndistribution(0, 1);\n    auto Z = boost::math::quantile(complement(Ndistribution, alpha / 2));\n    return Z;\n}\n\ndouble genTValue(int degree, double upperTailArea) {\n    boost::math::students_t Tdistribution(degree);\n    auto T = boost::math::quantile(complement(Tdistribution, upperTailArea));\n    return T;\n}\n\ndouble genMean(vector<double>& _dataSet) {\n    double sum = 0;\n    for (auto i : _dataSet)\n        sum += i;\n    return sum / _dataSet.size();\n}\n\ndouble genSampleStandardDeviation(vector<double>& _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 errorRadius(vector<double>& _dataSet, int degree, int sampleSize, double upperTailArea) {\n    double mean = genMean(_dataSet);\n    double ssd = genSampleStandardDeviation(_dataSet, mean, sampleSize);\n    return ssd / sqrt(sampleSize) * genTValue(degree, upperTailArea);\n}\n\ndouble errorRadius(vector<double>& _dataSet, double upperTailArea = 0.025) {\n    /*\n    * giving data set and the upper tail area of Student-T distribution\n    * return the error radius\n    * for too lazy to only input data set\n    */\n    int sampleSize = _dataSet.size();\n    return errorRadius(_dataSet, sampleSize - 1, sampleSize, upperTailArea);\n}\n\ndouble errorRadius(double knownSigma, double alpha, int sampleSize) {\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    return knownSigma / sqrt(sampleSize) * genZValue(alpha);\n}\n\npair<double, double> genConfidenceInterval(double theta, double errorRadius) {\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     */\n    return make_pair(theta - errorRadius, theta + errorRadius);\n}\n\ntemplate <typename T, typename S>\nostream& operator<<(ostream& os, const pair<T, S>& v) {\n    os << \"[\" << v.first << \", \" << v.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);\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);\n    auto sampleSize = z * z * knownTheta * knownTheta / marginError / marginError;\n    return ceil(sampleSize);\n}\n}  // namespace needingSampleSize\n\ntemplate <class T>\nstring readSingleLineCSV(vector<T>& _dataSet, string fileName) {\n    /* will return the file's title\n    * read only single line csv file\n    * @_dataSet: a container you want to storge at\n    * @fileName: fileName\n    */\n    ifstream inFile(fileName, ios::in);\n    if (inFile.fail()) {\n        cerr << \"Open file failed\" << endl;\n        return \"\";\n    }\n    string title;\n    T rawdata;\n    getline(inFile, title);\n    while (inFile >> rawdata)\n        _dataSet.push_back(rawdata);\n    inFile.close();\n    return title;\n}\n\ntemplate <class T>\nstring readSingleLineCSV(map<T, int>& proportionDataSet, string fileName) {\n    /* \n    * only for reading proportion Data\n    * will return the file's title\n    * read only single line csv file\n    * @proportionDataSet: a container you want to storge at\n    * @fileName: fileName\n    */\n    ifstream inFile(fileName, ios::in);\n    if (inFile.fail()) {\n        cerr << \"Open file failed\" << endl;\n        return \"\";\n    }\n    string title;\n    T rawData;\n    getline(inFile, title);\n    while (getline(inFile, rawData)) {\n        auto isInMap = proportionDataSet.find(rawData);\n        if (isInMap != proportionDataSet.end())\n            proportionDataSet.at(isInMap->first)++;\n        else\n            proportionDataSet.insert(pair<T, int>(rawData, 1));\n    }\n    inFile.close();\n    return title;\n}\n\n#endif\n", "meta": {"hexsha": "1b76e8d7dc0e3070c324a4b91d762661d92e455a", "size": 4671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch8/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": "ch8/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": "ch8/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": 30.7302631579, "max_line_length": 96, "alphanum_fraction": 0.6636694498, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6867917255923042}}
{"text": "#ifndef TEST_UNIT_MATH_PRIM_SCAL_PROB_HPP\n#define TEST_UNIT_MATH_PRIM_SCAL_PROB_HPP\n\n#include <boost/math/distributions.hpp>\n#include <gtest/gtest.h>\n#include <algorithm>\n#include <vector>\n\n/**\n * Uses a chi-squared test to assert that a vector of observed counts\n * is consistent with a vector of expected counts. Useful for testing RNGs.\n */\nvoid assert_chi_squared(const std::vector<int>& counts,\n                        const std::vector<double>& expected, double tolerance) {\n  int bins = counts.size();\n  EXPECT_EQ(bins, expected.size());\n\n  double chi = 0;\n  for (int i = 0; i < bins; ++i) {\n    double discrepancy = expected[i] - counts[i];\n    chi += discrepancy * discrepancy / expected[i];\n  }\n  boost::math::chi_squared dist(bins - 1);\n  double chi_threshold = quantile(complement(dist, tolerance));\n\n  EXPECT_TRUE(chi < chi_threshold);\n}\n\n/**\n * Like assert_matches_quantiles, but the bins are not necessarily\n * equiprobable. Assert that approximately proportions[i] of the\n * samples are in bin i, which has lower bound bin_boundaries[i-1] and\n * upper bound bin_boundaries[i], using a chi-squared goodness of fit\n * test. bin_boundaries is assumed sorted in increasing order.\n **/\nvoid assert_matches_bins(const std::vector<double>& samples,\n                         const std::vector<double>& bin_boundaries,\n                         const std::vector<double>& proportions,\n                         double tolerance) {\n  ASSERT_GT(samples.size(), 0);\n  int N = samples.size();\n  std::vector<double> mysamples = samples;\n  std::sort(mysamples.begin(), mysamples.end());\n\n  ASSERT_GT(bin_boundaries.size(), 0);\n  ASSERT_TRUE(bin_boundaries.size() == proportions.size());\n  int K = bin_boundaries.size();\n  std::vector<double> expected;\n  for (int i = 0; i < K; i++) {\n    ASSERT_TRUE(proportions[i] >= 0 && proportions[i] <= 1);\n    expected.push_back(proportions[i] * N);\n  }\n\n  std::vector<int> counts(K);\n  size_t current_index = 0;\n  for (int i = 0; i < N; ++i) {\n    while (mysamples[i] >= bin_boundaries[current_index]) {\n      ++current_index;\n      EXPECT_TRUE(current_index < bin_boundaries.size());\n    }\n    ++counts[current_index];\n  }\n  assert_chi_squared(counts, expected, tolerance);\n}\n\n/**\n * From a collection of samples and a list of quantiles, assumed\n * ordered, assert that the samples resemble draws from a distribution\n * with those quantiles, using a chi_squared goodness of fit\n * test. That is, assert that the samples are approximately evenly\n * distributed among the quantiles.size() equiprobable bins, who's\n * upper bounds are given in quantiles in increasing order.\n */\nvoid assert_matches_quantiles(const std::vector<double>& samples,\n                              const std::vector<double>& quantiles,\n                              double tolerance) {\n  int K = quantiles.size();\n  std::vector<double> proportions;\n  for (int i = 0; i < K; ++i)\n    proportions.push_back(1.0 / K);\n\n  assert_matches_bins(samples, quantiles, proportions, tolerance);\n}\n#endif\n", "meta": {"hexsha": "eb65e2bf0049b627d179692408bddcb4b7089063", "size": 3006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/prob/util.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "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.3647058824, "max_line_length": 80, "alphanum_fraction": 0.6769793746, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6867681716262509}}
{"text": "#include <cmath>\n#include <fftw3.h>\n#include <tuple>\n#include <vector>\n\n#include \"specgram.h\"\n\nstd::vector<float> window_hanning(int size) {\n    std::vector<float> window;\n    float scale =  2 * M_PI / (size - 1);\n    for (int n = 0; n < size; n++)\n        window.push_back(0.5 * (1 - cos(scale * n)));\n    return window;\n}\n\nstd::pair<int, int> specgram_shape(int n, int NFFT,\n                                   int noverlap) {\n    int stride = NFFT - noverlap;\n    int time_steps = (n - noverlap) / stride;\n    int n_freqs = NFFT / 2 + 1;\n    return std::make_pair(n_freqs, time_steps);\n}\n\nvoid log_cspecgram(const int16_t* const in, int n,\n                  int NFFT, int Fs,\n                  int noverlap, float* out,\n                  float epsilon /* default=1e-7 */) {\n    cspecgram(in, n, NFFT, Fs, noverlap, out);\n    auto spec_shape = specgram_shape(n, NFFT, noverlap);\n    int size = spec_shape.first * spec_shape.second;\n    for (int i = 0; i < size; i++)\n        out[i] = log(out[i] + epsilon);\n}\n\nvoid cspecgram(const int16_t* const in, int n,\n              int NFFT, int Fs,\n              int noverlap, float* out) {\n\n    int stride = NFFT - noverlap;\n    int n_freqs;\n    int time_steps;\n    std::tie(n_freqs, time_steps) = specgram_shape(n, NFFT, noverlap);\n\n    std::vector<float> window(window_hanning(NFFT));\n\n    float *x = new float[NFFT * time_steps];\n\n    float* in_f = new float[n];\n    for (int i = 0; i < n; i++)\n        in_f[i] = static_cast<float>(in[i]);\n\n    for (int i = 0; i < time_steps; i++) {\n        for (int j = 0; j < NFFT; j++) {\n            x[i * NFFT + j] = window[j]  * in_f[i * stride + j];\n        }\n    }\n\n    // Do an fft for each NFFT seg of x\n    fftwf_complex* res = (fftwf_complex*) fftwf_malloc(\n                            sizeof(fftwf_complex) * n_freqs * time_steps);\n\n    fftwf_plan plan = fftwf_plan_many_dft_r2c(1, &NFFT,\n                              time_steps, x, NULL, 1, NFFT,\n                              res, NULL, 1, n_freqs,\n                              FFTW_ESTIMATE | FFTW_DESTROY_INPUT);\n    fftwf_execute(plan);\n    fftwf_destroy_plan(plan);\n\n    for (int i = 0; i < time_steps; i++) {\n        int s = i * n_freqs;\n        for (int j = 0; j < n_freqs; j++) {\n            out[s + j] = res[s + j][0] * res[s + j][0] + \n                            res[s + j][1] * res[s + j][1];\n        }\n    }\n\n    // Cleanup temporaries\n    fftwf_free(res);\n    delete[] x;\n    delete[] in_f;\n\n    // Scale output in the same style as matplotlib\n    float scale = 0;\n    for (float w : window)\n        scale += w * w;\n    scale *= Fs;\n    for (int i = 0; i < time_steps; i++) {\n        int s = i * n_freqs;\n        out[s] /= scale;\n        for (int j = 1; j < n_freqs - 1; j++) {\n            out[s + j] *= (2.0 / scale);\n        }\n        if (NFFT % 2 == 0) {\n            out[s + n_freqs - 1] /= scale;\n        } else {\n            out[s + n_freqs - 1] *= (2.0 / scale);\n        }\n    }\n}\n\n#ifdef PYTHON\n#include <boost/python.hpp>\n#include <boost/python/numeric.hpp>\n#include <boost/python/extract.hpp>\n#include <numpy/noprefix.h>\n\nnamespace py = boost::python;\nnamespace np = boost::python::numeric;\n\nvoid specgram(np::array input, int NFFT, int Fs,\n               int noverlap, np::array output) {\n   \n    py::object i_shape = input.attr(\"shape\");\n    py::object o_shape = output.attr(\"shape\");\n\n    if (len(i_shape) != 1 || len(o_shape) != 2)\n        throw std::invalid_argument(\"Bad input or ouput shape\");\n    unsigned int n = py::extract<unsigned int>(i_shape[0]);\n    \n    int16_t* in_dat = static_cast<int16_t*>(PyArray_DATA(input.ptr()));\n    float* out_dat = static_cast<float*>(PyArray_DATA(output.ptr()));\n    cspecgram(in_dat, n, NFFT, Fs, noverlap, out_dat);\n}\n\nBOOST_PYTHON_MODULE(cspecgram) {\n    np::array::set_module_and_type(\"numpy\", \"ndarray\");\n    py::def(\"specgram\", &specgram);\n}\n#endif\n", "meta": {"hexsha": "9ccd3ea1811bf1668f9d9a840e1588445602dcfa", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/specgram.cpp", "max_stars_repo_name": "gaoyiyeah/KWS-CTC", "max_stars_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T22:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:51:05.000Z", "max_issues_repo_path": "utils/specgram.cpp", "max_issues_repo_name": "gaoyiyeah/KWS-CTC", "max_issues_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-03-08T07:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:26:52.000Z", "max_forks_repo_path": "utils/specgram.cpp", "max_forks_repo_name": "gaoyiyeah/KWS-CTC", "max_forks_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2017-12-21T01:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T09:27:23.000Z", "avg_line_length": 29.7461538462, "max_line_length": 74, "alphanum_fraction": 0.5435738298, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.686768148817579}}
{"text": "//\n// Created by Vlad Argunov on 19/10/2021.\n//\n\n#include \"Regression.h\"\n\n#include <Eigen/Dense>\n#include <string>\n#include <iostream>\n\n\nRegression::Regression(std::string type) {\n    type_regression = type;\n}\n\n\nvoid Regression::set_data(Eigen::MatrixXd x_values_, Eigen::VectorXd y_values_) {\n    x_values = x_values_;\n    y_values = y_values_;\n}\n\nvoid Regression::add_constant() {\n    Eigen::MatrixXd x_values_with_constant;\n    x_values_with_constant.resize(x_values.rows(), x_values.cols() + 1);\n    x_values_with_constant.rightCols(x_values.cols()) = x_values;\n\n    x_values_with_constant.col(0) = Eigen::VectorXd::Ones(x_values.rows());\n    x_values = x_values_with_constant;\n\n}\n\nvoid Regression::print_data() {\n    std::cout << \"Data Matrix:\\n\";\n    std::cout << x_values << \"\\n\";\n}\n\nvoid Regression::print_responses() {\n    std::cout << \"Responses vector:\\n\";\n    std::cout << y_values << \"\\n\";\n}\n\nvoid Regression::solve() {\n    if (type_regression == \"Linear\"){\n        Eigen::MatrixXd computation_matrix;\n        computation_matrix.resize(x_values.rows(), x_values.rows());\n        computation_matrix = (x_values.transpose() * x_values).inverse();\n        parameters = computation_matrix * x_values.transpose() * y_values;\n    }\n}\n\nvoid Regression::print_parameters() {\n    std::cout << \"Parameters vector:\\n\";\n    std::cout << parameters << \"\\n\";\n}\n", "meta": {"hexsha": "f1aa8b152a8104c33fc2161686b9e445a4b59391", "size": 1360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Regression.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Regression.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Regression.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7272727273, "max_line_length": 81, "alphanum_fraction": 0.6742647059, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6867338785686556}}
{"text": "#pragma once\n#ifndef MANIFOLDMATH_H\n#define MANIFOLDMATH_H\n\n#include <vector>\n#include <memory>\n\n#include <Eigen/Core>\n\n#include <engine/Vectormath_Defines.hpp>\n\nnamespace Engine\n{\n    // Basically all math inside this namespace assumes that the given\n    //      vectorfields contain unit vectors. They are therefore interpreted\n    //      as living in a manifold which is the direct product space of N\n    //      spheres.\n    // The only exception are functions which interpret the vectorfield\n    //      as a single 3N-dimensional vector.\n    // TODO: cleanly separate these two cases!\n    namespace Manifoldmath\n    {\n        // Get the norm of a vectorfield (interpreted as a 3N-vector)\n        scalar norm(const vectorfield & vf);\n        // Normalize a vectorfield (interpreted as a 3N-vector)\n        void normalize(vectorfield & vf);\n\n\n        // Project v1 to be parallel to v2\n        //      Note: this assumes normalized vectorfields\n        void project_parallel(vectorfield & vf1, const vectorfield & vf2);\n        // Project v1 to be orthogonal to v2\n        //      Note: this assumes normalized vectorfields\n        void project_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n        // Invert v1's component parallel to v2\n        //      Note: this assumes normalized vectorfields\n        void invert_parallel(vectorfield & vf1, const vectorfield & vf2);\n        // Invert v1's component orthogonal to v2\n        //      Note: this assumes normalized vectorfields\n        void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n        // Project vf1's vectors into the tangent plane of vf2\n        //      Note: vf2 must have normalized vectors\n        void project_tangential(vectorfield & vf1, const vectorfield & vf2);\n\n\n        // The tangential projector is a matrix which projects any vector into the tangent\n        //      space of a vectorfield, considered to live on the direct product of N unit\n        //      spheres. It is a 3N x 3N matrix.\n        MatrixX tangential_projector(const vectorfield & image);\n\n        // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n        //      a vectorfield, considered to live on the direct product of N unit spheres.\n        //      The basis vectors will be the spherical unit vectors, except at the poles.\n        //      The basis will be a 3Nx2N matrix.\n        void tangent_basis_spherical(const vectorfield & vf, MatrixX & basis);\n\n        // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n        //      a vectorfield, considered to live on the direct product of N unit spheres.\n        //      The basis vectors will be generated from cross products with euclidean basis\n        //      vectors. The basis will be a 3Nx2N matrix.\n        void tangent_basis_cross(const vectorfield & vf, MatrixX & basis);\n\n        // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n        //      a vectorfield, considered to live on the direct product of N unit spheres.\n        //      The basis vectors will form righthanded sets with the vectors of vf.\n        //      The basis will be a 3Nx2N matrix.\n        void tangent_basis_righthanded(const vectorfield & vf, MatrixX & basis);\n\n        // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n        //      a vectorfield, considered to live on the direct product of N unit spheres.\n        //      The basis vectors will be calculated from orthonormalizations with respect\n        //      to a random vector. The basis will be a 3Nx2N matrix.\n        // void tangent_basis_random(const vectorfield & vf, MatrixX & basis);\n\n\n        // This is the derivatives of the coordinate transformation from (unit-)spherical to cartesian\n        // i.e. d_cartesian/d_spherical\n        void spherical_to_cartesian_jacobian(const vectorfield & vf, MatrixX & jacobian);\n\n        // This is the second derivatives of the coordinate transformation from (unit-)spherical to cartesian\n        // i.e. d^2_cartesian/d^2_spherical\n        void spherical_to_cartesian_hessian(const vectorfield & vf, MatrixX & gamma_x, MatrixX & gamma_y, MatrixX & gamma_z);\n        \n        //\n        void spherical_to_cartesian_coordinate_basis(const vectorfield & vf, MatrixX & basis);\n\n        //\n        void spherical_coordinate_christoffel_symbols(const vectorfield & vf, MatrixX & gamma_theta, MatrixX & gamma_phi);\n\n\n        // Calculate Hessian for a vectorfield constrained to unit length, at any extremum (i.e. where vectors || gradient)\n        void hessian_bordered(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n        // Calculate tangential derivatives and correction terms according to the projector approach\n        void hessian_projected(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n        // Calculate tangential derivatives and correction terms according to the projector and Weingarten map approach\n        void hessian_weingarten(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n        // Calculate spherical derivatives using coordinate transformations via jacobians\n        void hessian_spherical(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out);\n        // Calculate spherical derivates and correction terms using jacobians and christoffel symbols\n        void hessian_covariant(const vectorfield & image,  const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out);\n\n        // Geodesic distance between two vectorfields\n        scalar dist_geodesic(const vectorfield & v1, const vectorfield & v2);\n\n        // Calculate the \"tangent\" vectorfields pointing between a set of configurations\n        void Tangents(std::vector<std::shared_ptr<vectorfield>> configurations, const std::vector<scalar> & energies, std::vector<vectorfield> & tangents);\n    }\n}\n\n#endif", "meta": {"hexsha": "6ea03f950afe8f034df9b88d038c95e39a7af625", "size": 6156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Manifoldmath.hpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T22:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:54:54.000Z", "max_issues_repo_path": "core/include/engine/Manifoldmath.hpp", "max_issues_repo_name": "ddkn/spirit", "max_issues_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_issues_repo_licenses": ["MIT"], "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/include/engine/Manifoldmath.hpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-05T13:24:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T07:46:47.000Z", "avg_line_length": 55.9636363636, "max_line_length": 162, "alphanum_fraction": 0.6985055231, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6866351941701577}}
{"text": "#include \"lrgNormalEquationSolverStrategy.h\"\n#include <vector>\n#include <random>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nDataSolver::DataSolver(){}\n\n// empty class method above\n\nstd::pair<double, double> &DataSolver::FitData(std::vector<std::pair<double, double> >&Inputs,std::pair<double, double>&Theta){\n\n// as with the gradient solver, we need to create input matricies (the code was copied from this file so it is identical)\n\n    VectorXd Y_e = VectorXd::Ones(Inputs.size());\n    MatrixXd M_X = MatrixXd::Ones(Inputs.size(),2);\n\n    for(int i=0; i < Inputs.size();++i){\n        Y_e(i) = Inputs[i].second;\n        M_X(i,0) = Inputs[i].first;\n    }\n\n// create a matrix to append our output theta to\n\n    MatrixXd Theta_e = MatrixXd::Ones(2,1);\n\n// here is all the linear algebra\n\n    Theta_e =  (((M_X.transpose()*M_X).inverse())*(M_X.transpose()))*Y_e;\n\n    Theta.first = Theta_e(0);\n    Theta.second = Theta_e(1);\n    \n    return Theta; \n};\n", "meta": {"hexsha": "4f348244e73ddeef33b34346c95557d3658e8b47", "size": 973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/lrgNormalEquationSolverStrategy.cpp", "max_stars_repo_name": "sukrire/PHAS0100Assignment1", "max_stars_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "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": "Code/Lib/lrgNormalEquationSolverStrategy.cpp", "max_issues_repo_name": "sukrire/PHAS0100Assignment1", "max_issues_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Lib/lrgNormalEquationSolverStrategy.cpp", "max_forks_repo_name": "sukrire/PHAS0100Assignment1", "max_forks_repo_head_hexsha": "33013ee65f5c071a18e513ce46fc28c2de80e039", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T16:41:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-16T22:13:23.000Z", "avg_line_length": 25.6052631579, "max_line_length": 127, "alphanum_fraction": 0.6670092497, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6865539989685625}}
{"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, 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 tools/license/license.mtl.txt in the distribution.\n\n// Author: Marc Hartung\n\n#ifndef MTL_MATRIX_QR_GIVENS_INCLUDE\n#define MTL_MATRIX_QR_GIVENS_INCLUDE\n\n#include <cmath>\n#include <utility>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\n\nnamespace mtl { namespace matrix {\n\n\n/// General Given's transformator\n/**\n * Input-matrix A will be splitted in A = Q*R. Q and R are accessible from getQ() and getR().\n * \\sa givens\n */    \ntemplate <typename Matrix>\nclass qr_givens_solver {\n    \n    typedef typename Collection<Matrix>::value_type value_type;\n    typedef typename Collection<Matrix>::size_type size_type;\n\npublic:\n    \n   /** \\brief Constructor needs a sqare-matrix as input\n     * \\param MTL-Matrix type\n     *  \n     */\n    \n    qr_givens_solver(const Matrix& IN) : R(IN), G(2,2), Q(num_cols(IN), num_rows(IN)) {\n\tvalue_type one = math::one(c);\n\tQ = one;\n\teps = 1.0e-8;\n    }\n    \n    /** \\brief Returns Q as the input-matrix-type \n     * \n     * \\return Matrix Q\n     */\n    \n    Matrix& getQ() {\n\treturn Q;\n    }\n    \n    /** \\brief Returns R as the input-matrix-type \n     * \n     * \\return Matrix R\n     */    \n    Matrix& getR() {\n\treturn R;\n    }\n    \n    /** \\brief Sets the distance to zero\n     * \n     * \\param value_type tolerance to zero\n     */    \n    void setTolerance(value_type tol) {\n\teps = tol;\n    }\n    \n    /** \\brief Starts QR decompostion\n     */\t\n    void calc() \n    {\n\tvalue_type zero= math::zero(c);\n\tMatrix RIter(2, num_rows(R)), Iter(2, num_rows(R));\n\tfor(size_type i= 0; i < R.num_cols() - 1; i++) {\n\t    irange r(i, num_cols(R));\n \t    for(size_type j= num_rows(R)-1;j>i;j--) {\n\t\tif (std::abs(R[j][i]) > eps) {\n\t\t    set_rotation(R[i][i], R[j][i]);\n\t\t    Iter[0][r] = R[i][r];\n\t\t    Iter[1][r] = R[j][r];\n\t\t    RIter[iall][r] = G*Iter[iall][r];\n\t\t    R[i][r] = RIter[0][r];\n\t\t    R[j][r] = RIter[1][r];\n\t\t    Iter[0][iall] = Q[i][iall];\n\t\t    Iter[1][iall] = Q[j][iall];\n\t\t    RIter = G*Iter;\n\t\t    Q[i][iall] = RIter[0][iall];\n\t\t    Q[j][iall] = RIter[1][iall];\n\t\t}\n\t\tR[j][i] = zero;\n\t    }\n\t    \n\t}\n\t\n\tfor(size_type i= 0; i < num_cols(R) - 1; i++) \n\t    R[i+1][i] = zero;\n\t\n    }\n        \n  private:\n    \n    Matrix     R, G, Q;\n    value_type c, s, eps;\n    \n    template <typename T>\n    inline T square(T x) const { return x * x; }\n\n    /// Coefficients for Given's rotation    \n    void set_rotation(value_type a, value_type b)\n    {\n\tusing std::abs;\n\tusing mtl::conj;\n\t\n\tvalue_type zero= math::zero(a), one= math::one(b), t;\n\t\n\tif ( b == zero ) {\n\t    c= one; s= zero;\n\t} else if ( abs(b) > abs(a) ) {\n\t    t = a / abs(b);\n\t    s = one/ sqrt(one + square(abs(t)));\n\t    c = s * t;\n\t    s *= (b/abs(b));\n\t} else {\n\t    t = b / abs(a);\n\t    c = one / sqrt(one + square(abs(t)));\n\t    s = c * t;\n\t    c = (a/abs(a))*c;\n\t}\n\t\n\tG= conj(c), conj(s),\n\t  -s, c;\n    }\n    \n};\n\n/// QR-Factorization of matrix A(m x n) based on Givens' rotation\ntemplate <typename Matrix>\nstd::pair<Matrix, Matrix>\ninline qr_givens(const Matrix& A)\n{\n    qr_givens_solver<Matrix> solver(A);\n    solver.calc();\n    return std::make_pair(solver.getQ(), solver.getR());\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_QR_GIVENS_INCLUDE\n", "meta": {"hexsha": "0e242a1e2a9226d490f92afe7a31ded086e22d36", "size": 3699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "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/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["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.11875, "max_line_length": 94, "alphanum_fraction": 0.5796161125, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6865539943066427}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2010.\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// 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//[policy_ref_snip6\n\n#include <boost/math/distributions/negative_binomial.hpp>\nusing boost::math::negative_binomial;\n\n// Use the default rounding policy integer_round_outwards.\n// Lower quantile rounded down:\ndouble x = quantile(negative_binomial(20, 0.3), 0.05); // rounded up 27 from 27.3898\n// Upper quantile rounded up:\ndouble y = quantile(complement(negative_binomial(20, 0.3), 0.05)); // rounded down to 69 from 68.1584\n\n//] //[/policy_ref_snip6]\n\n#include <iostream>\nusing std::cout; using std::endl;\n\nint main()\n{\n   cout << \"quantile(negative_binomial(20, 0.3), 0.05) = \"<< x <<endl\n     << \"quantile(complement(negative_binomial(20, 0.3), 0.05)) = \" << y << endl;\n}\n\n/*\nOutput:\n\n  quantile(negative_binomial(20, 0.3), 0.05) = 27\n  quantile(complement(negative_binomial(20, 0.3), 0.05)) = 69\n*/\n", "meta": {"hexsha": "0b4d0eac1a58510155a2385a4488d1ef8b32aaed", "size": 1199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_ref_snip6.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_ref_snip6.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_ref_snip6.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.5526315789, "max_line_length": 101, "alphanum_fraction": 0.7114261885, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6864645826875864}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/optimization.h>\n#include \"optimization_test_functions.h\"\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../rand.h\"\n\n#include \"tester.h\"\n\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n    using namespace dlib::test_functions;\n\n    logger dlog(\"test.least_squares\");\n\n// ----------------------------------------------------------------------------------------\n\n    void test_with_chebyquad()\n    {\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(2);\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"chebyquad 2 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 2 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 2 error: \" << length(ch - chebyquad_solution(2));\n\n            DLIB_TEST(length(ch - chebyquad_solution(2)) < 1e-5);\n\n        }\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(2);\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"LM chebyquad 2 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"LM chebyquad 2 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"LM chebyquad 2 error: \" << length(ch - chebyquad_solution(2));\n\n            DLIB_TEST(length(ch - chebyquad_solution(2)) < 1e-5);\n\n        }\n\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = chebyquad_start(2);\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"chebyquad 2 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 2 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 2 error: \" << length(ch - chebyquad_solution(2));\n\n            DLIB_TEST(length(ch - chebyquad_solution(2)) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = chebyquad_start(2);\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"LM chebyquad 2 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"LM chebyquad 2 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"LM chebyquad 2 error: \" << length(ch - chebyquad_solution(2));\n\n            DLIB_TEST(length(ch - chebyquad_solution(2)) < 1e-5);\n\n        }\n\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(4);\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"chebyquad 4 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 4 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 4 error: \" << length(ch - chebyquad_solution(4));\n\n            DLIB_TEST(length(ch - chebyquad_solution(4)) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(4);\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"LM chebyquad 4 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"LM chebyquad 4 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"LM chebyquad 4 error: \" << length(ch - chebyquad_solution(4));\n\n            DLIB_TEST(length(ch - chebyquad_solution(4)) < 1e-5);\n\n        }\n\n\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(6);\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"chebyquad 6 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 6 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 6 error: \" << length(ch - chebyquad_solution(6));\n\n            // the ch variable contains a permutation of what is in chebyquad_solution(6).\n            // Apparently there is more than one minimum?.  Just check that the objective \n            // goes to zero.\n            DLIB_TEST(chebyquad(ch) < 1e-10);\n\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(6);\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"LM chebyquad 6 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"LM chebyquad 6 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"LM chebyquad 6 error: \" << length(ch - chebyquad_solution(6));\n\n            DLIB_TEST(chebyquad(ch) < 1e-10);\n\n        }\n\n\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(8);\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"chebyquad 8 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"chebyquad 8 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"chebyquad 8 error: \" << length(ch - chebyquad_solution(8));\n\n            DLIB_TEST(length(ch - chebyquad_solution(8)) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,0,1> ch;\n\n            ch = chebyquad_start(8);\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                chebyquad_residual,\n                                derivative(chebyquad_residual),\n                                range(0,ch.size()-1),\n                                ch);\n\n            dlog << LINFO << \"LM chebyquad 8 obj: \" << chebyquad(ch);\n            dlog << LINFO << \"LM chebyquad 8 der: \" << length(chebyquad_derivative(ch));\n            dlog << LINFO << \"LM chebyquad 8 error: \" << length(ch - chebyquad_solution(8));\n\n            DLIB_TEST(length(ch - chebyquad_solution(8)) < 1e-5);\n\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_with_brown()\n    {\n        print_spinner();\n        {\n            matrix<double,4,1> ch;\n\n            ch = brown_start();\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 300),\n                                brown_residual,\n                                derivative(brown_residual),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"brown obj: \" << brown(ch);\n            dlog << LINFO << \"brown der: \" << length(brown_derivative(ch));\n            dlog << LINFO << \"brown error: \" << length(ch - brown_solution());\n\n            DLIB_TEST_MSG(length(ch - brown_solution()) < 1e-5,length(ch - brown_solution()) );\n\n        }\n        print_spinner();\n        {\n            matrix<double,4,1> ch;\n\n            ch = brown_start();\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                brown_residual,\n                                derivative(brown_residual),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"LM brown obj: \" << brown(ch);\n            dlog << LINFO << \"LM brown der: \" << length(brown_derivative(ch));\n            dlog << LINFO << \"LM brown error: \" << length(ch - brown_solution());\n\n            DLIB_TEST(length(ch - brown_solution()) < 1e-5);\n\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n// These functions are declared here because wrapping the real rosen functions in this\n// way avoids triggering a bug in visual studio 2005 which prevents this code from compiling.\n    double rosen_residual_double (int i, const matrix<double,2,1>& m)\n    { return rosen_residual(i,m); }\n    float rosen_residual_float (int i, const matrix<float,2,1>& m)\n    { return rosen_residual(i,m); }\n\n    matrix<double,2,1> rosen_residual_derivative_double (int i, const matrix<double,2,1>& m)\n    { return rosen_residual_derivative(i,m); }\n    matrix<float,2,1> rosen_residual_derivative_float (int i, const matrix<float,2,1>& m)\n    { return rosen_residual_derivative(i,m); }\n\n    double rosen_big_residual_double (int i, const matrix<double,2,1>& m)\n    { return rosen_big_residual(i,m); }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_with_rosen()\n    {\n\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_start<double>();\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_double,\n                                rosen_residual_derivative_double,\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"rosen error: \" << length(ch - rosen_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_solution<double>()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_start<double>();\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_double,\n                                rosen_residual_derivative_double,\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"lm rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"lm rosen error: \" << length(ch - rosen_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_solution<double>()) < 1e-5);\n\n        }\n\n\n\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_start<double>();\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_double,\n                                derivative(rosen_residual_double),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"rosen error: \" << length(ch - rosen_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_solution<double>()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<float,2,1> ch;\n\n            ch = rosen_start<float>();\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_float,\n                                derivative(rosen_residual_float),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"float rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"float rosen error: \" << length(ch - rosen_solution<float>());\n\n            DLIB_TEST(length(ch - rosen_solution<float>()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<float,2,1> ch;\n\n            ch = rosen_start<float>();\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_float,\n                                derivative(rosen_residual_float),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"LM float rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"LM float rosen error: \" << length(ch - rosen_solution<float>());\n\n            DLIB_TEST(length(ch - rosen_solution<float>()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_start<double>();\n\n            solve_least_squares_lm(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_residual_double,\n                                derivative(rosen_residual_double),\n                                range(1,20),\n                                ch);\n\n            dlog << LINFO << \"LM rosen obj: \" << rosen(ch);\n            dlog << LINFO << \"LM rosen error: \" << length(ch - rosen_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_solution<double>()) < 1e-5);\n\n        }\n        print_spinner();\n        {\n            matrix<double,2,1> ch;\n\n            ch = rosen_big_start<double>();\n\n            solve_least_squares(objective_delta_stop_strategy(1e-13, 80),\n                                rosen_big_residual_double,\n                                derivative(rosen_big_residual_double),\n                                range(1,2),\n                                ch);\n\n            dlog << LINFO << \"rosen big obj: \" << rosen_big(ch);\n            dlog << LINFO << \"rosen big error: \" << length(ch - rosen_big_solution<double>());\n\n            DLIB_TEST(length(ch - rosen_big_solution<double>()) < 1e-5);\n\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class optimization_tester : public tester\n    {\n    public:\n        optimization_tester (\n        ) :\n            tester (\"test_least_squares\",\n                    \"Runs tests on the least squares optimization component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            test_with_chebyquad();\n            test_with_brown();\n            test_with_rosen();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "068a3c6812a38eb8cad859995a34311a20b2698b", "size": 15366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/least_squares.cpp", "max_stars_repo_name": "prathyusha12924/eye-gaze", "max_stars_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_stars_repo_licenses": ["MIT"], "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": "src/dlib/test/least_squares.cpp", "max_issues_repo_name": "prathyusha12924/eye-gaze", "max_issues_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_issues_repo_licenses": ["MIT"], "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": "src/dlib/test/least_squares.cpp", "max_forks_repo_name": "prathyusha12924/eye-gaze", "max_forks_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_forks_repo_licenses": ["MIT"], "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": 34.0709534368, "max_line_length": 95, "alphanum_fraction": 0.4731224782, "num_tokens": 3375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6864203435897078}}
{"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2015 Adam Wulkiewicz, Lodz, Poland.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[multi_polygon\n//` Declaration and use of the Boost.Geometry model::multi_polygon, modelling the MultiPolygon Concept\n\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\nnamespace bg = boost::geometry;\n\nint main()\n{\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::polygon<point_t> polygon_t; /*< Default parameters, clockwise, closed polygon. >*/\n    typedef bg::model::multi_polygon<polygon_t> mpolygon_t; /*< Clockwise, closed multi_polygon. >*/\n\n    mpolygon_t mpoly1; /*< Default-construct a multi_polygon. >*/\n\n#if !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX) \\\n && !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)\n\n    mpolygon_t mpoly2{{{{0.0, 0.0}, {0.0, 5.0}, {5.0, 5.0}, {5.0, 0.0}, {0.0, 0.0}},\n                       {{1.0, 1.0}, {4.0, 1.0}, {4.0, 4.0}, {1.0, 4.0}, {1.0, 1.0}}},\n                      {{{5.0, 5.0}, {5.0, 6.0}, {6.0, 6.0}, {6.0, 5.0}, {5.0, 5.0}}}}; /*< Construct a multi_polygon containing two polygons, using C++11 unified initialization syntax. >*/\n\n#endif\n\n    mpoly1.resize(2); /*< Resize a multi_polygon, store two polygons. >*/\n\n    bg::append(mpoly1[0].outer(), point_t(0.0, 0.0)); /*< Append point to the exterior ring of the first polygon. >*/\n    bg::append(mpoly1[0].outer(), point_t(0.0, 5.0));\n    bg::append(mpoly1[0].outer(), point_t(5.0, 5.0));\n    bg::append(mpoly1[0].outer(), point_t(5.0, 0.0));\n    bg::append(mpoly1[0].outer(), point_t(0.0, 0.0));\n\n    mpoly1[0].inners().resize(1); /*< Resize a container of interior rings of the first polygon. >*/\n    bg::append(mpoly1[0].inners()[0], point_t(1.0, 1.0)); /*< Append point to the interior ring of the first polygon. >*/\n    bg::append(mpoly1[0].inners()[0], point_t(4.0, 1.0));\n    bg::append(mpoly1[0].inners()[0], point_t(4.0, 4.0));\n    bg::append(mpoly1[0].inners()[0], point_t(1.0, 4.0));\n    bg::append(mpoly1[0].inners()[0], point_t(1.0, 1.0));\n\n    bg::append(mpoly1[1].outer(), point_t(5.0, 5.0)); /*< Append point to the exterior ring of the second polygon. >*/\n    bg::append(mpoly1[1].outer(), point_t(5.0, 6.0));\n    bg::append(mpoly1[1].outer(), point_t(6.0, 6.0));\n    bg::append(mpoly1[1].outer(), point_t(6.0, 5.0));\n    bg::append(mpoly1[1].outer(), point_t(5.0, 5.0));\n\n    double a = bg::area(mpoly1);\n\n    std::cout << a << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[multi_polygon_output\n/*`\nOutput:\n[pre\n17\n]\n*/\n//]\n", "meta": {"hexsha": "d5414868f4906d55a75a09d2215e9dc540bc3030", "size": 2793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/geometries/multi_polygon.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/geometries/multi_polygon.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/geometries/multi_polygon.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 36.75, "max_line_length": 188, "alphanum_fraction": 0.6337271751, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.6862836288024128}}
{"text": "#ifndef InitCondLV_CC_\n#define InitCondLV_CC_\n/**\n * @file initcondlv.cc\n * @brief NPDE homework InitCondLV code\n * @author lfilippo, tille, jgacon, dcasati\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n#include <utility>\n\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n\nnamespace InitCondLV {\n\n/* Compute the maps Phi(t,y0) and W(t,y0) at final time T.\n * Use initial data given by u0 and v0. */\n/* SAM_LISTING_BEGIN_1 */\nstd::pair<Eigen::Vector2d, Eigen::Matrix2d> PhiAndW(double u0, double v0,\n                                                    double T) {\n  // Save the values of Phi and W at time T in PaW.first and PaW.second resp.\n  std::pair<Eigen::Vector2d, Eigen::Matrix2d> PaW;\n\n#if SOLUTION\n  auto f = [](const Eigen::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  // Construct ode solver with r.h.s\n  Ode45<Eigen::VectorXd> O(f);\n  // Set options\n  O.options.rtol = 1e-14;\n  O.options.atol = 1e-12;\n  // Solve ODE\n  auto sol = O.solve(w0, T);\n  // Extract needed component\n  Eigen::VectorXd wT = sol.back().first;\n\n  PaW.first << wT(0), wT(1);\n  PaW.second << wT(2), wT(4), wT(3), wT(5);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return PaW;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace InitCondLV\n\n#endif  // #define InitCondLV_CC_\n", "meta": {"hexsha": "634f2187afa4e09784102e986ea825095fe97203", "size": 1670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/InitCondLV/mastersolution/initcondlv.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/InitCondLV/mastersolution/initcondlv.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/InitCondLV/mastersolution/initcondlv.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": 25.6923076923, "max_line_length": 77, "alphanum_fraction": 0.5604790419, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.6862836104512117}}
{"text": "#include <boost/multiprecision/gmp.hpp>\n#include <boost/format.hpp>\n#include <iostream>\nnamespace mp = boost::multiprecision;\n\ntypedef mp::mpf_float_1000 MPFloat;\n\nstruct MPConstant {\n  const char *name {};\n  const char *expr {};\n  MPFloat value;\n};\n\nint main() {\n  const MPFloat one(1);\n  const MPFloat two(2);\n  const MPFloat ten(10);\n  const MPFloat e = mp::exp(one);\n  const MPFloat ln2 = mp::log(two);\n  const MPFloat ln10 = mp::log(ten);\n  const MPFloat pi = 4 * mp::atan(one);\n  const MPFloat sqrtpi = mp::sqrt(pi);\n  const MPFloat sqrt2 = mp::sqrt(two);\n\n  const MPConstant constants[] = {\n    {\"E\", \"e\", e},\n    {\"LOG2E\", \"log2(e)\", mp::log2(e)},\n    {\"LOG10E\", \"log10(e)\", mp::log10(e)},\n    {\"LN2\", \"log(2)\", mp::log(two)},\n    {\"LN10\", \"log(10)\", mp::log(ten)},\n    {\"PI\", \"pi\", pi},\n    {\"2PI\", \"2*pi\", 2 * pi},\n    {\"4PI\", \"4*pi\", 4 * pi},\n    {\"PI_2\", \"pi/2\", pi / 2},\n    {\"PI_4\", \"pi/4\", pi / 4},\n    {\"1_PI\", \"1/pi\", 1 / pi},\n    {\"2_PI\", \"2/pi\", 2 / pi},\n    {\"4_PI\", \"4/pi\", 4 / pi},\n    {\"1_SQRTPI\", \"1/sqrt(pi)\", 1 / sqrtpi},\n    {\"2_SQRTPI\", \"2/sqrt(pi)\", 2 / sqrtpi},\n    {\"SQRT2\", \"sqrt(2)\", sqrt2},\n    {\"1_SQRT2\", \"1/sqrt(2)\", 1 / sqrt2},\n  };\n\n  for (const MPConstant &c: constants) {\n    std::cout << \"#define \" <<\n        boost::format(\"K_%s%|15t|::coreutil::math_constant(%s)%|85t|// %s\\n\")\n        % c.name % (c.value.str(36) + 'L') % c.expr;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e39a4b3fa52a89658fbd5070a5e23430cf58c5d8", "size": 1394, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/generate_math_constants.cc", "max_stars_repo_name": "jpcima/coreutil", "max_stars_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "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": "tools/generate_math_constants.cc", "max_issues_repo_name": "jpcima/coreutil", "max_issues_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "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": "tools/generate_math_constants.cc", "max_forks_repo_name": "jpcima/coreutil", "max_forks_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "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.3018867925, "max_line_length": 77, "alphanum_fraction": 0.5337159254, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6861811606392413}}
{"text": "#include \"project/LinearRegression.hpp\"\n#include <armadillo>\n\nLinearRegression::LinearRegression(arma::mat &x,\n                                   arma::vec &y){\n\n    X = x;\n    Y = y;\n}\n\nvoid LinearRegression::fit(bool fit_inter = true){\n    fit_intercept = fit_inter;\n    if(fit_intercept){\n        coef = arma::solve(\n                arma::join_rows(arma::ones(X.n_rows, 1), X),\n                Y);\n    } else {\n        coef = arma::solve(X, Y);\n    }\n}\n\narma::colvec LinearRegression::predict(arma::mat &X_pred){\n    if(fit_intercept) {        \n        return arma::join_rows(\n                arma::ones(X_pred.n_rows, 1),\n                X_pred)*coef;\n    }\n    else{\n        return X_pred*coef;\n    }\n}\n", "meta": {"hexsha": "a0e1f95eebde460fce1e476b7d590b819c405502", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LinearRegression.cpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "src/LinearRegression.cpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "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/LinearRegression.cpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["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.125, "max_line_length": 60, "alphanum_fraction": 0.5254237288, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6861811587344232}}
{"text": "#pragma once\n\n// C++ standard library\n#include <utility>\n#include <vector>\n\n// Armadillo\n#include <armadillo>\n\nnamespace mant {\n  arma::uword factorial(\n      const arma::uword n);\n\n  arma::uword nchoosek(\n      arma::uword n,\n      const arma::uword k);\n\n  arma::uword secondStirlingNumber(\n      const arma::uword numberOfElements,\n      const arma::uword numberOfParts);\n\n  std::vector<arma::uvec> combinations(\n      const arma::uword numberOfElements,\n      const arma::uword cycleSize);\n\n  std::vector<arma::uvec> multicombinations(\n      const arma::uword numberOfElements,\n      const arma::uword cycleSize);\n\n  std::vector<std::pair<arma::uvec, arma::uvec>> twoSetsPartitions(\n      const arma::uword numberOfElements);\n}\n", "meta": {"hexsha": "ec6c8147d6578241560792b93db17f7104cadfa7", "size": 731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/combinatorics.hpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "include/mantella_bits/combinatorics.hpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "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/mantella_bits/combinatorics.hpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["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.1515151515, "max_line_length": 67, "alphanum_fraction": 0.683994528, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6861634722935487}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"ResizeBilinear.hpp\"\n\n#include \"TensorBufferArrayView.hpp\"\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <cmath>\n#include <algorithm>\n\nusing namespace armnnUtils;\n\nnamespace armnn\n{\n\nnamespace\n{\n\ninline float Lerp(float a, float b, float w)\n{\n    return w * b + (1.f - w) * a;\n}\n\n}\n\nvoid ResizeBilinear(const float*      in,\n                    const TensorInfo& inputInfo,\n                    float*            out,\n                    const TensorInfo& outputInfo,\n                    DataLayoutIndexed dataLayout)\n{\n    // We follow the definition of TensorFlow and AndroidNN: the top-left corner of a texel in the output\n    // image is projected into the input image to figure out the interpolants and weights. Note that this\n    // will yield different results than if projecting the centre of output texels.\n\n    const unsigned int batchSize = inputInfo.GetShape()[0];\n    const unsigned int channelCount = inputInfo.GetShape()[dataLayout.GetChannelsIndex()];\n\n    const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];\n    const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];\n    const unsigned int outputHeight = outputInfo.GetShape()[dataLayout.GetHeightIndex()];\n    const unsigned int outputWidth = outputInfo.GetShape()[dataLayout.GetWidthIndex()];\n\n    // How much to scale pixel coordinates in the output image, to get the corresponding pixel coordinates\n    // in the input image.\n    const float scaleY = boost::numeric_cast<float>(inputHeight) / boost::numeric_cast<float>(outputHeight);\n    const float scaleX = boost::numeric_cast<float>(inputWidth) / boost::numeric_cast<float>(outputWidth);\n\n    TensorBufferArrayView<const float> input(inputInfo.GetShape(), in, dataLayout);\n    TensorBufferArrayView<float> output(outputInfo.GetShape(), out, dataLayout);\n\n    for (unsigned int n = 0; n < batchSize; ++n)\n    {\n        for (unsigned int c = 0; c < channelCount; ++c)\n        {\n            for (unsigned int y = 0; y < outputHeight; ++y)\n            {\n                // Corresponding real-valued height coordinate in input image.\n                const float iy = boost::numeric_cast<float>(y) * scaleY;\n\n                // Discrete height coordinate of top-left texel (in the 2x2 texel area used for interpolation).\n                const float fiy = floorf(iy);\n                const unsigned int y0 = boost::numeric_cast<unsigned int>(fiy);\n\n                // Interpolation weight (range [0,1]).\n                const float yw = iy - fiy;\n\n                for (unsigned int x = 0; x < outputWidth; ++x)\n                {\n                    // Real-valued and discrete width coordinates in input image.\n                    const float ix = boost::numeric_cast<float>(x) * scaleX;\n                    const float fix = floorf(ix);\n                    const unsigned int x0 = boost::numeric_cast<unsigned int>(fix);\n\n                    // Interpolation weight (range [0,1]).\n                    const float xw = ix - fix;\n\n                    // Discrete width/height coordinates of texels below and to the right of (x0, y0).\n                    const unsigned int x1 = std::min(x0 + 1, inputWidth - 1u);\n                    const unsigned int y1 = std::min(y0 + 1, inputHeight - 1u);\n\n                    // Interpolation\n                    const float ly0 = Lerp(input.Get(n, c, y0, x0), input.Get(n, c, y0, x1), xw); // lerp along row y0.\n                    const float ly1 = Lerp(input.Get(n, c, y1, x0), input.Get(n, c, y1, x1), xw); // lerp along row y1.\n                    const float l = Lerp(ly0, ly1, yw);\n\n                    output.Get(n, c, y, x) = l;\n                }\n            }\n        }\n    }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "2d1087c9a0736da92fb0fbe8c1af804c99625c72", "size": 3831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/ResizeBilinear.cpp", "max_stars_repo_name": "jnorwood/armnn", "max_stars_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T23:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T23:00:46.000Z", "max_issues_repo_path": "src/backends/reference/workloads/ResizeBilinear.cpp", "max_issues_repo_name": "jnorwood/armnn", "max_issues_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_issues_repo_licenses": ["MIT"], "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/backends/reference/workloads/ResizeBilinear.cpp", "max_forks_repo_name": "jnorwood/armnn", "max_forks_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_forks_repo_licenses": ["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.696969697, "max_line_length": 119, "alphanum_fraction": 0.6034977813, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6859954287894193}}
{"text": "//\n// Copyright (c) 2019-2020 INRIA\n//\n\n#include <iostream>\n\n#include <pinocchio/math/rotation.hpp>\n#include <pinocchio/math/sincos.hpp>\n#include <Eigen/Geometry>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_toRotationMatrix)\n{\n  using namespace pinocchio;\n  const int max_tests = 1e5;\n  for(int k = 0; k < max_tests; ++k)\n  {\n    const double theta = std::rand();\n    double cos_value, sin_value;\n    \n    pinocchio::SINCOS(theta,&sin_value,&cos_value);\n    Eigen::Vector3d axis(Eigen::Vector3d::Random().normalized());\n\n    Eigen::Matrix3d rot; toRotationMatrix(axis,cos_value,sin_value,rot);\n    Eigen::Matrix3d rot_ref = Eigen::AngleAxisd(theta,axis).toRotationMatrix();\n    \n    BOOST_CHECK(rot.isApprox(rot_ref));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(test_orthogonal_projection)\n{\n  using namespace pinocchio;\n  const int max_tests = 1e5;\n  \n  typedef Eigen::Vector4d Vector4;\n  typedef Eigen::Quaterniond Quaternion;\n  typedef Eigen::Matrix3d Matrix3;\n  \n  for(int k = 0; k < max_tests; ++k)\n  {\n    const Vector4 vec4 = Vector4::Random();\n    const Quaternion quat(vec4.normalized());\n    \n    const Matrix3 rot = quat.toRotationMatrix();\n    \n    Matrix3 rot_proj = orthogonalProjection(rot);\n    BOOST_CHECK(rot.isApprox(rot_proj));\n  }\n  \n  for(int k = 0; k < max_tests; ++k)\n  {\n    const Matrix3 mat = Matrix3::Random();\n    \n    Matrix3 rot_proj = orthogonalProjection(mat);\n    BOOST_CHECK((rot_proj.transpose()*rot_proj).isIdentity());\n    BOOST_CHECK(fabs(rot_proj.determinant() - 1.) <= Eigen::NumTraits<double>::dummy_precision());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "10ae784911b9ce6622d6ba94ef9770ef74b1fe87", "size": 1731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rotation.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/rotation.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/rotation.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 24.7285714286, "max_line_length": 98, "alphanum_fraction": 0.7036395147, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6859826957884533}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <boost/math/tools/centered_continued_fraction.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/core/demangle.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::tools::centered_continued_fraction;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::constants::pi;\n\ntemplate<class Real>\nvoid test_integral()\n{\n    for (int64_t i = -20; i < 20; ++i) {\n        Real ii = i;\n        auto cfrac = centered_continued_fraction<Real>(ii);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(1), a.size());\n        CHECK_EQUAL(i, a.front());\n    }\n}\n\ntemplate<class Real>\nvoid test_halves()\n{\n    for (int64_t i = 0; i < 20; ++i) {\n        // std::round rounds 0.5 up if i > 0, and rounds down if i < 0.\n        // Should we care? These representations are not unique anyway;\n        // In any case, this behavior agrees with Maple.\n        Real x = i + Real(1)/Real(2);\n        auto cfrac = centered_continued_fraction<Real>(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i + 1, a.front());\n        CHECK_EQUAL(int64_t(-2), a.back());\n    }\n\n    // We'll also test quarters; why not?\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(1)/Real(4);\n        auto cfrac = centered_continued_fraction<Real>(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i, a.front());\n        CHECK_EQUAL(int64_t(4), a.back());\n    }\n\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(1)/Real(8);\n        auto cfrac = centered_continued_fraction<Real>(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i, a.front());\n        CHECK_EQUAL(int64_t(8), a.back());\n    }\n\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(3)/Real(4);\n        auto cfrac = centered_continued_fraction<Real>(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i+1, a.front());\n        CHECK_EQUAL(int64_t(-4), a[1]);\n    }\n\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(7)/Real(8);\n        auto cfrac = centered_continued_fraction<Real>(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i + 1, a.front());\n        CHECK_EQUAL(int64_t(-8), a[1]);\n    }\n}\n\ntemplate<typename Real>\nvoid test_simple()\n{\n    std::cout << \"Testing rational numbers on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    {\n        Real x = Real(649)/200;\n        // ContinuedFraction[649/200] = [3; 4, 12, 4]\n        auto cfrac = centered_continued_fraction(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(4), a.size());\n        CHECK_EQUAL(int64_t(3), a[0]);\n        CHECK_EQUAL(int64_t(4), a[1]);\n        CHECK_EQUAL(int64_t(12), a[2]);\n        CHECK_EQUAL(int64_t(4), a[3]);\n    }\n\n    {\n        Real x = Real(415)/Real(93);\n        // [4; 2, 6, 7]:\n        auto cfrac = centered_continued_fraction(x);\n        auto const & a = cfrac.partial_denominators();\n        CHECK_EQUAL(size_t(4), a.size());\n        CHECK_EQUAL(int64_t(4), a[0]);\n        CHECK_EQUAL(int64_t(2), a[1]);\n        CHECK_EQUAL(int64_t(6), a[2]);\n        CHECK_EQUAL(int64_t(7), a[3]);\n    }\n\n}\n\ntemplate<typename Real>\nvoid test_khinchin()\n{\n    using std::sqrt;\n    auto rt_cfrac = centered_continued_fraction(sqrt(static_cast<Real>(2)));\n    Real K0 = rt_cfrac.khinchin_geometric_mean();\n    CHECK_ULP_CLOSE(Real(2), K0, 10);\n}\n\n\nint main()\n{\n    test_integral<float>();\n    test_integral<double>();\n    test_integral<long double>();\n    test_integral<cpp_bin_float_100>();\n    test_halves<float>();\n    test_halves<double>();\n    test_halves<long double>();\n    test_halves<cpp_bin_float_100>();\n    test_simple<float>();\n    test_simple<double>();\n    test_simple<long double>();\n    test_simple<cpp_bin_float_100>();\n    test_khinchin<cpp_bin_float_100>();\n    #ifdef BOOST_HAS_FLOAT128\n    test_integral<float128>();\n    test_halves<float128>();\n    test_simple<float128>();\n    test_khinchin<float128>();\n    #endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "f553b703f8b8ce9466ec40eea7288ca73c26078e", "size": 4723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/centered_continued_fraction_test.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": "test/centered_continued_fraction_test.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": "test/centered_continued_fraction_test.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": 31.4866666667, "max_line_length": 107, "alphanum_fraction": 0.6161338133, "num_tokens": 1300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.6859747319586915}}
{"text": "#include <QatGenericFunctions/Variable.h>\n#include <QatGenericFunctions/Parameter.h>\n#include <QatGenericFunctions/Square.h>\n#include <QatGenericFunctions/Sqrt.h>\n#include <QatGenericFunctions/Exp.h>\n#include <QatGenericFunctions/Sin.h>\n#include <QatGenericFunctions/Cos.h>\n#include <QatGenericFunctions/VoigtDistribution.h>\n#include <QatGenericFunctions/RKIntegrator.h>\n#include <QatDataAnalysis/Hist1D.h>\n#include <QatDataAnalysis/Table.h>\n#include <QatDataModeling/TableLikelihoodFunctional.h>\n#include <QatDataModeling/MinuitMinimizer.h>\n#include <QatPlotWidgets/PlotView.h>\n#include <QatPlotWidgets/MultipleViewWindow.h>\n#include <QatPlotting/PlotStream.h>\n#include <QatPlotting/PlotHist1D.h>\n#include <QatPlotting/PlotFunction1D.h>\n#include <QatPlotting/PlotProfile.h>\n#include <QatPlotting/PlotKey.h>\n#include <QatPlotting/PlotOrbit.h>\n#include <Eigen/Dense>\n#include <QApplication>\n#include <QMainWindow>\n#include <QAction>\n#include <QToolBar>\n#include <QFont>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <random>\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange,  const double Width=1200, const double Height=800);\n\ntypedef std::vector<double> Data;\ntypedef std::unique_ptr<Genfun::AbsFunction> FuncPtr;\ntypedef std::weak_ptr<Genfun::Parameter> ParamPtr;\n\nclass PlanetOrbit\n{\nprivate:\n    Genfun::RKIntegrator integrator;\n\npublic:\n    Genfun::Parameter* GM;\n    Genfun::Parameter* e;\n    Genfun::Parameter* a;\n    Genfun::Parameter* theta0;\n    Genfun::Parameter* inclination;\n    Genfun::Parameter* orientation;\n    FuncPtr X;\n    FuncPtr Y;\n\n    PlanetOrbit()\n    {\n        Genfun::Variable theta;\n        Genfun::Sin qSin;\n        Genfun::Cos qCos;\n        Genfun::Sqrt qSqrt;\n\n        GM = integrator.createControlParameter(\"GM\", 0.0002959, 0);\n        e = integrator.createControlParameter(\"eccentricity\", 0, 0, 1);\n        a = integrator.createControlParameter(\"semimajor axis\", 1);\n        theta0 = integrator.createControlParameter(\"Theta0\", 0, -2*M_PI, 2*M_PI);\n        orientation = new Genfun::Parameter(\"Orientation\", 0, -2*M_PI, 2*M_PI);\n        inclination = new Genfun::Parameter(\"Inclination\", 0, 0, M_PI);\n\n        Genfun::GENFUNCTION r = (*a) * (1 - (*e)*(*e)) / (1 + (*e) * qCos(theta - (*theta0)));\n        Genfun::GENFUNCTION DTheta = qSqrt((*GM) * (*a) * (1 - (*e)*(*e))) / (r*r);\n\n        integrator.addDiffEquation(&DTheta);\n\n        Genfun::GENFUNCTION Theta = *integrator.getFunction(theta);\n        Genfun::GENFUNCTION Radius = (*a) * (1 - (*e) * (*e)) / (1 + (*e) * qCos(Theta - (*theta0)));\n\n        X = FuncPtr((Radius * qCos(Theta - (*theta0) + (*orientation))).clone());\n        Y = FuncPtr((Radius * qSin(Theta - (*theta0) + (*orientation))).clone());\n    }\n\n    ~PlanetOrbit()\n    {\n        delete orientation;\n    }\n};\n\nconst double MAX_ANGLE = 3 * M_PI;\n\ndouble Time2Radian(const double hour, const double minute, const double second)\n{\n    const double Hour2Radian = 2 * M_PI / 24;\n    const double Minute2Radian = Hour2Radian / 60;\n    const double Second2Radian = Minute2Radian/ 60;\n    double angle = Hour2Radian*std::abs(hour) + Minute2Radian*std::abs(minute) + Second2Radian*std::abs(second);\n    return std::signbit(hour) ? -angle : angle;\n}\n\ndouble Degree2Radian(const double degree, const double minute, const double second)\n{\n    const double Degree2Radian = 2 * M_PI / 360;\n    const double Minute2Radian = Degree2Radian / 60;\n    const double Second2Radian = Minute2Radian / 60;\n    double angle = Degree2Radian*std::abs(degree) + Minute2Radian*std::abs(minute) + Second2Radian*std::abs(second);\n    return std::signbit(degree) ? -angle : angle;\n}\n\nvoid readData(const std::string& file, Data& TIME, Data& RA, Data& DEC)\n{\n    std::ifstream inFile(file);\n    std::string day, time;\n\n    for (size_t i = 1; inFile >> day >> time; i++)\n    {\n        TIME.push_back(i);\n\n        double hour, minute, second;\n        inFile >> hour >> minute >> second;\n        RA.push_back(Time2Radian(hour, minute, second));\n        inFile >> hour >> minute >> second;\n        DEC.push_back(Degree2Radian(hour, minute, second));\n    }  \n}\n\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 = \"Mars01.dat\";\nconst bool verbose = true;\n\nint main(int argc, char **argv)\n{\n    QApplication app(argc, argv);\n    MultipleViewWindow window;\n\n    QToolBar *toolBar = window.addToolBar(\"Tools\");\n    QAction *quitAction = toolBar->addAction(\"Quit (q)\");\n    quitAction->setShortcut(QKeySequence(\"q\"));\n\tQObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit()));\n\n    PlanetOrbit Earth;\n    Earth.e->setValue(0.8);\n    Earth.theta0->setValue(M_PI/3);\n    Earth.orientation->setValue(-M_PI/3);\n    PlotOrbit earthOrbit(*(Earth.X), *(Earth.Y), 0, 360);\n    PlotView *earthView = createPlotView(\"Earth\", \"X\", \"Y\", PRectF(-2, 2, -2, 2), 800, 800);\n    earthView->add(&earthOrbit);\n    window.add(earthView, \"Earth\");\n\n    Data TIME, RA, DEC;\n    readData(dataFileName, TIME, RA, DEC);\n\n    std::cout << \"RA @ 0: \" << RA[0] << std::endl;\n    std::cout << \"DEC @ 0: \" << DEC[0] << std::endl;\n\n    PlotView *RAView = createPlotView(\"Right Ascension\", \"Days\", \"\", PRectF(-10, 760, -0.5, 2*M_PI + 0.5));\n    window.add(RAView, \"RA\");\n\n    PlotProfile RAProfile;\n    for (size_t i = 0; i < TIME.size(); i++)\n    {\n        RAProfile.addPoint(TIME[i],RA[i]);\n    }\n    {\n        PlotProfile::Properties prop;\n        prop.pen.setWidth(1);\n        RAProfile.setProperties(prop);\n    }\n    RAView->add(&RAProfile);\n\n\n    PlotView *DECView = createPlotView(\"Declination\", \"Days\", \"\", PRectF(-10, 760, -1, 1));\n    window.add(DECView, \"DEC\");\n\n    PlotProfile DECProfile;\n    for (size_t i = 0; i < TIME.size(); i++)\n    {\n        DECProfile.addPoint(TIME[i], DEC[i]);\n    }\n    {\n        PlotProfile::Properties prop;\n        prop.pen.setWidth(1);\n        DECProfile.setProperties(prop);\n    }\n    DECView->add(&DECProfile);\n    \n\n\twindow.show();\n\tapp.exec();\n\n    return 0;\n}\n\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange, const double Width, const double Height)\n{\n    PlotView *view_ptr = new PlotView(viewRange);\n    view_ptr->setFixedWidth(Width);\n    view_ptr->setFixedHeight(Height);\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": "30878b19a7641708e81ebb2fa6591bdd294fd28c", "size": 7404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignments/Assignments_12/EX7/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/EX7/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/EX7/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": 32.4736842105, "max_line_length": 180, "alphanum_fraction": 0.6442463533, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6859731728870447}}
{"text": "// Implementing the class that is defined in the header file: PerpetualAmericanOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n#include \"PerpetualAmericanOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\r\n#include <vector>\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble PerpetualAmericanOption::CallPrice() const\r\n{\r\n\treturn ::PerpetualCall(S, K, r, sig, b);\r\n}\r\n\r\ndouble PerpetualAmericanOption::PutPrice() const\r\n{\r\n\treturn ::PerpetualPut(S, K, r, sig, b);\r\n}\r\n\r\nvoid PerpetualAmericanOption::init()\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 105;\r\n\tS = 100;\t\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\r\n\ttype = \"C\";\t\t\t\t//\tCall option as the default\r\n}\r\n\r\nvoid PerpetualAmericanOption::copy(const PerpetualAmericanOption& option)\r\n{\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nPerpetualAmericanOption::PerpetualAmericanOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nPerpetualAmericanOption::PerpetualAmericanOption(const PerpetualAmericanOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nPerpetualAmericanOption::PerpetualAmericanOption(const double& S1, const double& K1, const double& r1,\r\n\tconst double& sig1, const double& b1, const string type1) : Option(), S(S1), K(K1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nPerpetualAmericanOption::~PerpetualAmericanOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nPerpetualAmericanOption& PerpetualAmericanOption::operator = (const PerpetualAmericanOption& 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 PerpetualAmericanOption::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 PerpetualAmericanOption::toggle()\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 PerpetualCall(const double S, const double K, const double r, const double sig, const double b)\r\n{\r\n\tdouble y1 = 0.5 - (b / (sig * sig)) + sqrt(pow(((b / (sig * sig)) - 0.5), 2) + (2 * r / (sig * sig)));\r\n\r\n\tif (y1 == 1.0)\r\n\t{\r\n\t\treturn S;\r\n\t}\r\n\tdouble C = (K / (y1 - 1)) * pow(((y1 - 1) / y1) * (S / K), y1);\r\n\r\n\treturn C;\r\n}\r\n\r\n\r\ndouble PerpetualPut(const double S, const double K, const double r, const double sig, const double b)\r\n{\r\n\tdouble y2 = 0.5 - (b / (sig * sig)) - sqrt(pow(((b / (sig * sig)) - 0.5), 2) + (2 * r / (sig * sig)));\r\n\r\n\tif (y2 == 1.0)\r\n\t{\r\n\t\treturn S;\r\n\t}\r\n\tdouble P = (K / (1 - y2)) * pow(((y2 - 1) / y2) * (S / K), y2);\r\n\r\n\treturn P;\r\n}\r\n\r\n", "meta": {"hexsha": "592df624800ba1d832d20a228a9f7ee4627e2b8a", "size": 2933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PerpetualAmericanOption.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": "PerpetualAmericanOption.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": "PerpetualAmericanOption.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": 22.2196969697, "max_line_length": 125, "alphanum_fraction": 0.6310944426, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6859707317032143}}
{"text": "#include \"homography/compute_homography_model.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/IterativeLinearSolvers>\n\n#include \"homography/compute_homography_error.hpp\"\n\nusing namespace Eigen;\nusing namespace cv;\n\nHomographyModel ComputeHomographyModel::operator()(vector<HomographyMeasurement> m) {\n  MatrixXd A = MatrixXd::Zero(2*m.size(), 8);\n  VectorXd b = VectorXd::Zero(2*m.size());\n\n  // normalize the points\n  double m_x=0, m_y=0, d=0;\n  double m_xp=0, m_yp=0, dp=0;\n\n  // calculate translation\n  for(size_t i = 0; i < m.size(); i++) {\n    HomographyMeasurement& measurement = m[i];\n    float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n    m_x += x;\n    m_y += y;\n    m_xp += xp;\n    m_yp += yp;\n  }\n  m_x /= m.size(), m_y /= m.size(), m_xp /= m.size(), m_yp /= m.size();\n\n  // calculate distance\n  for(size_t i = 0; i < m.size(); i++) {\n    HomographyMeasurement& measurement = m[i];\n    float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n    d += sqrt((x-m_x)*(x-m_x) + (y-m_y)*(y-m_y));\n    dp += sqrt((xp-m_xp)*(xp-m_xp) + (yp-m_yp)*(yp-m_yp));\n  }\n  d /= sqrt(2)*m.size(), dp /= sqrt(2)*m.size();\n\n  // transform points\n  for(size_t i = 0; i < m.size(); i++) {\n    HomographyMeasurement& measurement = m[i];\n    float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n    x = (x-m_x)/d; \n    y = (y-m_y)/d;\n    xp = (xp-m_xp)/dp;\n    yp = (yp-m_yp)/dp;\n  }\n\n  Matrix3d T = Matrix3d::Zero();\n  Matrix3d Tpi = Matrix3d::Zero();\n  Matrix3d S = Matrix3d::Zero();\n  Matrix3d Spi = Matrix3d::Zero();\n\n  T(0,2) = -m_x;\n  T(1,2) = -m_y;\n  T(0,0) = T(1,1) = T(2,2) = 1;\n  S(0,0) = S(1,1) = 1/d;\n  S(2,2) = 1;\n\n  Tpi(0,2) = +m_xp;\n  Tpi(1,2) = +m_yp;\n  Tpi(0,0) = Tpi(1,1) = Tpi(2,2) = 1;\n  Spi(0,0) = Spi(1,1) = dp;\n  Spi(2,2) = 1;\n\n  for(size_t i = 0; i < m.size(); i++) {\n    const HomographyMeasurement& measurement = m[i];\n    double x = measurement.src.x, y = measurement.src.y, xp = measurement.dst.x, yp = measurement.dst.y;\n\n    A(2*i,0) = x;\n    A(2*i,1) = y;\n    A(2*i,2) = 1;\n    A(2*i,6) = -x*xp;\n    A(2*i,7) = -y*xp;\n    // A(2*i,8) = -xp;\n\n    A(2*i+1,3) = x;\n    A(2*i+1,4) = y;\n    A(2*i+1,5) = 1;\n    A(2*i+1,6) = -x*yp;\n    A(2*i+1,7) = -y*yp;\n    // A(2*i+1,8) = -yp;\n\n    b(2*i) = xp;\n    b(2*i+1) = yp;\n  }\n  FullPivHouseholderQR<MatrixXd> solver(A);\n  auto h = solver.solve(b);\n\n  Matrix3d H;\n\n  H(0,0) = h(0);\n  H(0,1) = h(1);\n  H(0,2) = h(2);\n  H(1,0) = h(3);\n  H(1,1) = h(4);\n  H(1,2) = h(5);\n  H(2,0) = h(6);\n  H(2,1) = h(7);\n  H(2,2) = 1;\n  \n  H = Tpi*Spi*H*S*T;\n  \n  return HomographyModel(H/H(2,2));\n};", "meta": {"hexsha": "ed3da279e3bfcd6ff65c6f19c90c3444d9363ff9", "size": 2719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/homography/compute_homography_model.cpp", "max_stars_repo_name": "matheuscarius/project-inf573", "max_stars_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_stars_repo_licenses": ["MIT"], "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/homography/compute_homography_model.cpp", "max_issues_repo_name": "matheuscarius/project-inf573", "max_issues_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_issues_repo_licenses": ["MIT"], "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/homography/compute_homography_model.cpp", "max_forks_repo_name": "matheuscarius/project-inf573", "max_forks_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_forks_repo_licenses": ["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.6509433962, "max_line_length": 107, "alphanum_fraction": 0.5476278043, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333005, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6859577292976937}}
{"text": "#pragma once\n#ifndef PARAMETERIZATION_HPP\n#define PARAMETERIZATION_HPP\n#include <math.h>\n#include <vector>\n#include <set>\n#include <iostream>\n#include <list>\n#include <string>\n#include <map>\n#include <utility>\n#include <sstream>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include \"./lib/Mesh_Library/Mesh/mesh.h\"\n#include \"./lib/Mesh_Library/Mesh/iterators.h\"\n#include \"./lib/mesh_library/Geometry/Point.h\"\n#include \"./lib/mesh_library/Geometry/Point2.H\"\n#define M_PI 3.14159\nusing std::vector;\nusing std::set;\nusing namespace MeshLib;\nusing namespace Eigen;\n\n//Computes the harmonic weight for the edge.\nfloat HarmonicWeight(CEdge* e) {\n\t// length of edge shared by the two triangles.\n\tfloat c = e->GetLength();\n\tCHalfEdge* he = e->halfedge(0);\n\n\tauto a1_p1 = he->he_next()->vertex()->point();\n\tauto a1_p2 = he->he_next()->he_next()->vertex()->point();\n\tfloat a1 = CPoint::distance(a1_p1, a1_p2);\n\t\n\tauto b1_p1 = he->he_next()->he_next()->vertex()->point();\n\tauto b1_p2 = he->he_next()->he_next()->he_next()->vertex()->point();\n\tfloat b1 = CPoint::distance(b1_p1, b1_p2);\n\n\the = e->halfedge(1);\n\n\tauto a2_p1 = he->he_next()->vertex()->point();\n\tauto a2_p2 = he->he_next()->he_next()->vertex()->point();\n\tfloat a2 = CPoint::distance(a2_p1, a2_p2);\n\t\n\tauto b2_p1 = he->he_next()->he_next()->vertex()->point();\n\tauto b2_p2 = he->he_next()->he_next()->he_next()->vertex()->point();\n\tfloat b2 = CPoint::distance(b2_p1, b2_p2);\n\n\tfloat cos_u = (b1*b1 + a1*a1 - c*c) / (2.0 * b1 * a1);\n\tfloat cos_v = (b2*b2 + a2*a2 - c*c) / (2.0 *b2 *a2);\n\n\tfloat sin_u = sqrt(abs(1.0 - cos_u*cos_u));\n\tfloat sin_v = sqrt(abs(1.0 - cos_v*cos_v));\n\n\tfloat weight;\n\tweight = ((cos_u / sin_u) + (cos_v / sin_v)) * 0.5;\n\n\treturn weight;\n\n}\n\nvoid uvMap(CMesh* mesh, std::vector<float>* outUvs) {\n\n\n\tstd::list<CVertex*> mvs = mesh->vertices();\n\tstd::list<CFace*> mfs = mesh->faces();\n\tstd::list<CEdge*> mes = mesh->edges();\n\tstd::list<CHalfEdge*> mhes = mesh->halfedges();\n\n\tstd::vector<CVertex*> verts{ std::begin(mvs), std::end(mvs)};\n\tstd::vector<CFace*> faces {std::begin(mfs), std::end(mfs)};\n\tstd::vector<CEdge*> edges { std::begin(mes), std::end(mes)};\n\n\tconst int N = verts.size();\n\n\n\tstd::list<CHalfEdge*>::iterator firstBoundary = mesh->EndHalfEdges();\n\tstd::list<CHalfEdge*>::iterator currentBoundary = mesh->EndHalfEdges();\n\n\tfor(std::list<CHalfEdge*>::iterator hiter = mesh->halfedges().begin(); hiter != mesh->halfedges().end(); hiter++ )\n\t{\n\t\tCHalfEdge* item = *hiter;\n\t\tif(mesh->isBoundary(hiter)) {\n\t\t\tfirstBoundary = hiter;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::map<int, CVertex*> vertexMap;\n\t\n\tfor (std::vector<CVertex*>::iterator it = verts.begin(); it != verts.end(); ++it) {\n\t\tCVertex* item = *it;\n\t\titem->set_index(vertexMap.size());\n\t\tvertexMap.insert(std::make_pair(vertexMap.size(), item));\n\n\t}\n\n\tstd::vector<CHalfEdge*> boundaryEdges;\n\tstd::vector<CVertex*> boundaryVertices;\n\tset<int> boundarySet;\n\tvector<float> edgeLengths; \n\tfloat totalEdgeLength = 0.0;\n\tstd::list<CHalfEdge*>::iterator previousBoundary = firstBoundary;\n\tcurrentBoundary = firstBoundary;\n\tint testi = 0;\n\n\tCVertex* prevItem;\n\tfor (std::vector<CVertex*>::iterator it = verts.begin(); it != verts.end(); ++it) {\n\t\tCVertex* item = *it;\n\t\tif (item->boundary()) {\n\t\t\tif (testi == 0) {\n\t\t\t\ttesti++;\n\t\t\t\tprevItem = item;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tboundaryVertices.push_back(item);\n\t\t\tauto halfedge = item->halfedge();\n\t\t\tboundaryEdges.push_back(halfedge);\n\t\t\tboundarySet.insert(item->index());\n\t\t\tedgeLengths.push_back(totalEdgeLength);\n\t\t\tauto bo_p1 = prevItem->point();\n\t\t\tauto bo_p2 = item->point();\n\t\t\ttotalEdgeLength += CPoint::distance(bo_p1, bo_p2);\n\t\t\ttesti++;\n\t\t\tprevItem = item;\n\t\t}\n\t}\n\n\tEigen::VectorXd bx(N);\n\tEigen::VectorXd by(N);\n\n\tfor(int i =0; i<N;i++)\n\t{\n\t\tbx[i] = 0.0f;\n\t\tby[i] = 0.0f;\n\t}\n\n\tfor (int i=0; i < boundaryVertices.size(); i++) {\n\t\tCVertex* v = boundaryVertices[i];\n\t\tdouble theta = (edgeLengths[i]/totalEdgeLength)*2.0f * M_PI;\n\t\tbx[v->index()] = cos(theta);\n\t\tby[v->index()] = sin(theta);\n\t}\n\n\ttypedef Eigen::Triplet<double> Triplet;\n\ttypedef Eigen::SparseMatrix<double> SparseMatrix;\n\tSparseMatrix W(N, N);\n\n\tvector<Triplet> triplets;\n\tvector<double> diag;\n\tdiag.resize(N, 0);\n\n\tfor (std::vector<CEdge*>::iterator it = edges.begin(); it != edges.end(); ++it) {\n\t\tCEdge* item = *it;\n\t\tif (mesh->isBoundary(item)) {\n\t\t\tcontinue;\n\t\t}\n\t\tCVertex* v0 = item->halfedge(0)->vertex();\n\t\tCVertex* v1 = item->halfedge(1)->vertex();\n\n\t\tint i0 = v0->index();\n\t\tint i1 = v1->index();\n\n\t\tfloat weight = HarmonicWeight(item);\n\n\n\t\tif (boundarySet.count(i0) == 0) {\n\t\t\ttriplets.push_back(Triplet(i0, i1, weight));\n\t\t}\n\t\tif (boundarySet.count(i1) == 0) {\n\t\t\ttriplets.push_back(Triplet(i1, i0, weight));\n\t\t}\n\n\t\tdiag[i0] -= weight;\n\t\tdiag[i1] -= weight;\n\t}\n\n\tfor (int i = 0; i < diag.size(); i++) {\n\t\tif(boundarySet.count(i) > 0) {\n\n\t\t\ttriplets.push_back(Triplet(i, i, 1.0));\n\t\t}\n\t\telse {\n\t\t\ttriplets.push_back(Triplet(i, i, diag[i]));\n\t\t}\n\t}\n\tW.setFromTriplets(triplets.begin(), triplets.end());\n\tEigen::SparseLU<SparseMatrix > solver;\n\tsolver.compute(W);\n\tif (solver.info() != Eigen::Success) {\n\t\tprintf(\"ERROR: found no decomposition of sparse matrix\");\n\t\tassert(true);\n\t}\n\n\tEigen::VectorXd x(N);\n\tEigen::VectorXd y(N);\n\tx = solver.solve(bx);\n\ty = solver.solve(by);\n\n\tstd::vector<CPoint2> uvpoints;\n\tfor (int i = 0; i < N; i++) {\n\t\toutUvs->push_back(x[i]);\n\t\toutUvs->push_back(y[i]);\n\n\t\tCPoint2 cp(x[i], y[i]);\n\t\tuvpoints.push_back(cp);\n\t\tverts[i]->set_uv(cp);\n\n\t\tstd::ostringstream attrs;\n\t\tattrs << verts[i]->string() << \" uv=(\" << std::to_string(cp[0]) << \" \" << std::to_string(cp[1]) << \")\";\n\t\tverts[i]->set_string(attrs.str());\n\t}\n\n}\n\nvoid Parameterization(std::string meshfile, std::string outmeshfile) {\n\tCMesh mesh;\n\tstd::vector<float> outUvs;\n\tmesh.read_m(meshfile.c_str());\n\tuvMap(&mesh, &outUvs);\n\tmesh.write_m(outmeshfile.c_str());\n\n\treturn;\n}\n\n#endif\n\n", "meta": {"hexsha": "7defb71e5d2e03f90caadc0a982f264ee8ce8f49", "size": 5831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Parameterization.hpp", "max_stars_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_stars_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "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": "Parameterization.hpp", "max_issues_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_issues_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "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": "Parameterization.hpp", "max_forks_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_forks_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "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": 25.352173913, "max_line_length": 115, "alphanum_fraction": 0.6458583433, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6859577237915074}}
{"text": "/**\n * @brief Linear Discriminant Analysis with Eigen\n * \n * Dead simple, blazing fast LDA, \\cite friedman2001elements\n * \n * @file lda.hpp\n * @author Fran\u00e7ois-David Collin <Francois-David.Collin@umontpellier.fr>\n * @date 2018-08-31\n */\n#pragma once\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Matrix<size_t, Dynamic, 1> VectorXs;\n\n/**\n * @brief Computes lda with Trevor/hastie algorithm\n * \n * @param x data\n * @param y labels from 0 to K \n * @param Ld computes matrix whoses columns are Ld vectors\n */\ntemplate<class Derived>\nstd::vector<int> lda(const MatrixBase<Derived> &x,\n         const VectorXs &y,\n         MatrixXd& Ld)\n{\n    auto n = x.rows();\n    auto K = y.maxCoeff() + 1;\n    auto p = x.cols();\n\n    // M = Centroids\n    MatrixXd M = MatrixXd::Zero(K, p);\n    VectorXd m = VectorXd::Zero(p);\n    VectorXs d = VectorXs::Zero(K);\n\n    for (auto i = 0; i < n; i++)\n    {\n        auto c = y[i];\n        auto r = x.row(i);\n        d[c]++;\n        M.row(c) += r;\n        m += r;\n    }\n\n    for (auto c = 0; c < K; c++)\n    {\n        M.row(c) /= static_cast<double>(d[c]);\n    }\n\n    // m = Global mean\n    m /= static_cast<double>(n);\n\n    // D is x centered data and sorted by classes\n    MatrixXd D(n, p);\n\n    // W = Within-class covariance matrix\n    MatrixXd Wraw = MatrixXd::Zero(p, p);\n    size_t slicepos = 0;\n    for (auto c = 0; c < K; c++)\n    {\n        // Dc is a single class subrange of x\n        MatrixXd Dc = x.block(slicepos, 0, d[c], p);\n        // Centering\n        Dc.rowwise() -= M.row(c);\n        Wraw += Dc.transpose() * Dc;\n        slicepos += d[c];\n    }\n    Wraw /= static_cast<double>(n - K);\n    auto validvars = std::vector<int>();\n    for(auto i = 0; i< x.cols(); i++) {\n        if (std::abs(Wraw(i,i)) >= 1.0e-8) validvars.push_back(i);\n    }\n    auto W = Wraw(validvars,validvars);\n    // [4,4]((0.265008,0.0927211,0.167514,0.0384014),(0.0927211,0.115388,0.0552435,0.0327102),(0.167514,0.0552435,0.185188,0.0426653),(0.0384014,0.0327102,0.0426653,0.0418816))\n\n    // Calculate pseudo-inverse square root for W with SVD\n    // https://math.stackexchange.com/a/1176942\n    JacobiSVD<MatrixXd> svd(W,ComputeFullU|ComputeFullV);\n    double tolerance = std::numeric_limits<double>::epsilon() * std::max(W.cols(), W.rows()) * svd.singularValues().array().abs().maxCoeff();\n    auto W12 = svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse().sqrt(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n    // SelfAdjointEigenSolver<MatrixXd> svd(W);\n    // if (svd.info() != Success) {\n    //     throw std::runtime_error(\"LDA's first solver failed\");\n    // }\n    //auto W12 = svd.matrixU() * svd.eigenvalues().array().inverse().sqrt().matrix().asDiagonal() * svd.matrixU().transpose();\n//    auto W12 = svd.operatorInverseSqrt();\n    MatrixXd Mvalid = M(all,validvars);\n    MatrixXd Mstar = Mvalid * W12;\n    VectorXd mstar = VectorXd::Zero(validvars.size());\n    for (auto c = 0; c < K; c++)\n        mstar += Mstar.row(c);\n    mstar /= static_cast<double>(K);\n\n    Mstar.rowwise() -= mstar.transpose();\n    auto Bstar = Mstar.transpose() * Mstar / static_cast<double>(K - 1);\n\n    // We get the eigenvectors of B* via SVD\n    JacobiSVD<MatrixXd> svd2(Bstar,ComputeThinU);\n    MatrixXd Vl = W12 * svd2.matrixU();\n    Ld = Vl.leftCols(K-1);\n    return validvars;\n}", "meta": {"hexsha": "8a05bf401d43aa4bfe242f028312ddbe6de43115", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lda-eigen.hpp", "max_stars_repo_name": "diyabc/abcranger", "max_stars_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T12:11:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T16:32:37.000Z", "max_issues_repo_path": "src/lda-eigen.hpp", "max_issues_repo_name": "vitorpavinato/abcranger", "max_issues_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2019-06-20T11:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T04:13:46.000Z", "max_forks_repo_path": "src/lda-eigen.hpp", "max_forks_repo_name": "fradav/abcranger", "max_forks_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-17T03:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T13:31:10.000Z", "avg_line_length": 31.8691588785, "max_line_length": 185, "alphanum_fraction": 0.6017595308, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6859292733349153}}
{"text": "// Group E - Excel Visualization\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-15-19\r\n//\r\n// NormalDistribution.cpp\r\n//\r\n// Normal distribution functionality.\r\n\r\n#ifndef NormalDistribution_hpp\r\n#define NormalDistribution_hpp\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <boost/math/distributions.hpp> \r\nusing namespace boost::math;\r\n\r\n\r\ndouble N(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn cdf(myNormal, x);\r\n\r\n}\r\n\r\ndouble n(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn pdf(myNormal, x);\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "0b3187f1cf84836757238a64c1b46d084e9fedd3", "size": 603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/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": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/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": "GroupE/Level9/Level9/Level9Code/Level9Code/Projects/ExcelVisualisation/ExcelVisualisation/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": 14.7073170732, "max_line_length": 47, "alphanum_fraction": 0.6733001658, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6859292589845226}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <iomanip>\n#include <iostream>\n\nusing namespace boost::numeric::ublas;\nusing namespace std;\n\n// A custom, more pretty way to print matrices\nstd::ostream &operator<<(std::ostream &Str, matrix<double> const &v)\n{\n\tfor (int i = 0; i < v.size1(); i++)\n\t{\n\t\tStr << ((i == 0) ? \"[[\" : \" [\");\n\t\tfor (int j = 0; j < v.size2(); j++)\n\t\t{\n\t\t\tStr << setw(4);\n\t\t\tStr << v(i, j);\n\t\t\tStr << setw(0);\n\t\t}\n\t\tStr << ((i == v.size1() - 1) ? \"]]\" : \"]\");\n\t\tif (i != v.size1() - 1)\n\t\t\tStr << endl;\n\t}\n\treturn Str;\n}\n\nint main()\n{\n\tmatrix<double> A(2, 2);\n\tA(0, 0) = 1;\n\tA(0, 1) = 2;\n\tA(1, 0) = 3;\n\tA(1, 1) = 4;\n\n\tmatrix<double> B(2, 2);\n\tB(0, 0) = -1;\n\tB(0, 1) = 0;\n\tB(1, 0) = 0;\n\tB(1, 1) = -1;\n\n\tmatrix<double> C = prod(A, B);\n\n\tcout << \"Multiplication of \" << endl\n\t\t << A << endl;\n\tcout << \"and \" << endl\n\t\t << B << endl;\n\tcout << \"is\" << endl;\n\tcout << C << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "cadf7ea1ef1ab1fb97a067ec1bac7e7a5e0de80e", "size": 910, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Cpp SOURCE CODE/Boost/uBLAS/matmult.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/uBLAS/matmult.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/uBLAS/matmult.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": 17.8431372549, "max_line_length": 68, "alphanum_fraction": 0.4934065934, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.685911058091755}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n// from numpy import random\nusing Eigen::MatrixXd; // Objeto que me crea una matriz DINAMICA\nusing namespace std;\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  cout << m << endl;\n}", "meta": {"hexsha": "bfe90ee22cbe4a62b8f199a025e683e03b5be8c2", "size": 286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejercicios/semana5/matrix1.cpp", "max_stars_repo_name": "lschinchilla/FISI2028-202120", "max_stars_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "ejercicios/semana5/matrix1.cpp", "max_issues_repo_name": "lschinchilla/FISI2028-202120", "max_issues_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "ejercicios/semana5/matrix1.cpp", "max_forks_repo_name": "lschinchilla/FISI2028-202120", "max_forks_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 17.875, "max_line_length": 64, "alphanum_fraction": 0.5909090909, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6859110487326173}}
{"text": "// This file is part of:\n// gnss-sim: A GNSS Signal Simulator\n//\n// Copyright (c) 2020 Damien Dusha\n// SPDX-License-Identifier: MIT\n//\n// Derived from https://github.com/osqzss/gps-sdr-sim (MIT Licence):\n// Copyright (c) 2015-2020 Takuji Ebinuma\n\n#include \"geodesy.h\"\n#include \"gpssim.h\"\n#include \"gps_math.h\"\n\n#include <Eigen/Core>\n\n#include <cmath>\n\nGeodeticPosition xyz2llh(const Eigen::Vector3d &ecef)\n{\n\tconstexpr double a = WGS84_RADIUS;\n\tconstexpr double e = WGS84_ECCENTRICITY;\n\tconstexpr double e2 = e*e;\n\n    constexpr double eps = 1.0e-3;\n\tif (ecef.norm() < eps)\n\t{\n        // Invalid ECEF vector\n        return GeodeticPosition::FromRadians(0.0, 0.0, -a);\n\t}\n\n\tconst double x = ecef.x();\n\tconst double y = ecef.y();\n\tconst double z = ecef.z();\n\n\tconst double rho2 = x*x + y*y;\n\tdouble dz = e2*z;\n\n    double n, zdz, nh;\n\twhile (1)\n\t{\n\t\tzdz = z + dz;\n\t\tnh = std::sqrt(rho2 + zdz*zdz);\n\t\tconst double slat = zdz / nh;\n\t\tn = a / std::sqrt(1.0-e2*slat*slat);\n\t\tconst double dz_new = n*e2*slat;\n\n\t\tif (std::fabs(dz-dz_new) < eps)\n\t\t\tbreak;\n\n\t\tdz = dz_new;\n\t}\n\n    const double lat_rad = std::atan2(zdz, std::sqrt(rho2));\n    const double lon_rad = std::atan2(y, x);\n    const double height_m = nh - n;\n\n    return GeodeticPosition::FromRadians(lat_rad, lon_rad, height_m);\n}\n\nEigen::Vector3d llh2xyz(const GeodeticPosition &llh)\n{\n\tconstexpr double a = WGS84_RADIUS;\n\tconstexpr double e = WGS84_ECCENTRICITY;\n\tconstexpr double e2 = e*e;\n\n\tconst double clat = std::cos(llh.latitude_rad());\n\tconst double slat = std::sin(llh.latitude_rad());\n\tconst double clon = std::cos(llh.longitude_rad());\n\tconst double slon = std::sin(llh.longitude_rad());\n\tconst double d = e*slat;\n\n\tconst double n = a / std::sqrt(1.0-d*d);\n\tconst double nph = n + llh.height_m();\n\n\tconst double tmp = nph*clat;\n\tconst double x = tmp*clon;\n\tconst double y = tmp*slon;\n\tconst double z = ((1.0-e2)*n + llh.height_m())*slat;\n\n\treturn Eigen::Vector3d(x, y, z);\n}\n\nvoid ltcmat(const GeodeticPosition &llh, double t[3][3])\n{\n\tconst double slat = std::sin(llh.latitude_rad());\n\tconst double clat = std::cos(llh.latitude_rad());\n\tconst double slon = std::sin(llh.longitude_rad());\n\tconst double clon = std::cos(llh.longitude_rad());\n\n\tt[0][0] = -slat*clon;\n\tt[0][1] = -slat*slon;\n\tt[0][2] = clat;\n\tt[1][0] = -slon;\n\tt[1][1] = clon;\n\tt[1][2] = 0.0;\n\tt[2][0] = clat*clon;\n\tt[2][1] = clat*slon;\n\tt[2][2] = slat;\n}\n\nvoid ecef2neu(const double *xyz, double t[3][3], double *neu)\n{\n\tneu[0] = t[0][0]*xyz[0] + t[0][1]*xyz[1] + t[0][2]*xyz[2];\n\tneu[1] = t[1][0]*xyz[0] + t[1][1]*xyz[1] + t[1][2]*xyz[2];\n\tneu[2] = t[2][0]*xyz[0] + t[2][1]*xyz[1] + t[2][2]*xyz[2];\n\n\treturn;\n}\n\nAzimuthElevation neu2azel(const double *neu)\n{\n\tdouble azimuth_rad = std::atan2(neu[1],neu[0]);\n\tif (azimuth_rad < 0.0)\n\t\tazimuth_rad += 2.0*PI;\n    \n\tconst double ne = std::hypot(neu[0], neu[1]);\n\tconst double elevation_rad = std::atan2(neu[2], ne);\n\n    return AzimuthElevation::FromRadians(azimuth_rad, elevation_rad);\n}\n", "meta": {"hexsha": "1f4770034afd1c22c37fc023dbbf6d117917bb4d", "size": 2964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geodesy.cpp", "max_stars_repo_name": "damiendusha/gnss-sim", "max_stars_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-12T21:27:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T17:44:55.000Z", "max_issues_repo_path": "geodesy.cpp", "max_issues_repo_name": "damiendusha/gnss-sim", "max_issues_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geodesy.cpp", "max_forks_repo_name": "damiendusha/gnss-sim", "max_forks_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T22:33:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T14:40:43.000Z", "avg_line_length": 24.4958677686, "max_line_length": 69, "alphanum_fraction": 0.6396761134, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6858949101899317}}
{"text": "#include \"nombre_modulaire.h\"\n#include \"numerique.h\"\n\n#include <boost/multiprecision/integer.hpp>\n\nstd::ostream &operator<<(std::ostream &os, const nombre_modulaire &a) {\n    os << a.value() << \"[\" << a.modulo() << \"]\";\n    return os;\n}\n\nstd::pair<size_t, nombre_modulaire> nombre_modulaire::factoriel2(size_t modulo, size_t n) {\n    nombre_modulaire resultat(modulo, 1);\n    size_t exposant = 0;\n    bool sgn = false;\n    while (n > 0) {\n        for (size_t i = n % modulo; i > 1; --i)\n            resultat *= i;\n        n /= modulo;\n        sgn ^= (n % 2 == 1);\n        exposant += n;\n    }\n    return std::make_pair(exposant, sgn ? -resultat : resultat);\n}\n\nvoid nombre_modulaire::meme_mod(const nombre_modulaire &n1, const nombre_modulaire &n2) {\n    if (n1._modulo != n2._modulo) {\n        throw std::domain_error(\"Modulo different !\");\n    }\n}\n\nvoid nombre_modulaire::meme_mod(const nombre_modulaire &n) const {\n    meme_mod(*this, n);\n}\n\nnombre_modulaire::nombre_modulaire(const nombre_modulaire &n) : _modulo(n._modulo), _value(n._value) {\n}\n\nnombre_modulaire nombre_modulaire::puissance(nombre_modulaire a, size_t n) {\n    nombre_modulaire result(a._modulo, 1);\n    while (n > 0) {\n        if (n % 2)\n            result *= a;\n        a *= a;\n        n /= 2;\n    }\n    return result;\n}\n\nnombre_modulaire nombre_modulaire::puissance(size_t a, size_t n, size_t modulo) {\n    nombre_modulaire result(modulo, 1);\n    nombre_modulaire p(modulo, a);\n    while (n > 0) {\n        if (n % 2)\n            result *= p;\n        p *= a;\n        n /= 2;\n    }\n    return result;\n}\n\n\nunsigned long long nombre_modulaire::value() const { return _value; }\n\nsize_t nombre_modulaire::modulo() const { return _modulo; }\n\nnombre_modulaire nombre_modulaire::operator-() const {\n    return nombre_modulaire(_modulo, _modulo - value());\n}\n\nnombre_modulaire &nombre_modulaire::operator=(const nombre_modulaire &op) {\n    // meme_mod(op);\n\n    _modulo = op._modulo;\n    _value = op._value;\n    return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator+=(const nombre_modulaire &op) {\n    meme_mod(op);\n\n    _value += op._value;\n    if (_value >= _modulo) _value -= _modulo;\n    return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator-=(const nombre_modulaire &op) {\n    meme_mod(op);\n\n    _value = _value < op._value ? _modulo + _value - op._value : _value - op._value;\n    return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator*=(const nombre_modulaire &op) {\n    meme_mod(op);\n\n    uint128_t c = 0;\n    boost::multiprecision::multiply(c, _value, op._value);\n    _value = boost::multiprecision::integer_modulus(c, _modulo);\n\n    return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator/=(const nombre_modulaire &op) {\n    meme_mod(op);\n    return operator*=(puissance(op, _modulo - 2));\n}\n\nnombre_modulaire nombre_modulaire::operator+(const nombre_modulaire &op) const {\n    nombre_modulaire result(*this);\n    result.operator+=(op);\n    return result;\n}\n\nnombre_modulaire nombre_modulaire::operator-(const nombre_modulaire &op) const {\n    nombre_modulaire result(*this);\n    result.operator-=(op);\n    return result;\n}\n\nnombre_modulaire nombre_modulaire::operator*(const nombre_modulaire &op) const {\n    nombre_modulaire result(*this);\n    result.operator*=(op);\n    return result;\n}\n\nnombre_modulaire nombre_modulaire::operator/(const nombre_modulaire &op) const {\n    nombre_modulaire result(*this);\n    result.operator/=(op);\n    return result;\n}\n\nnombre_modulaire nombre_modulaire::factoriel(size_t modulo, size_t n) {\n    auto[exposant, resultat] = factoriel2(modulo, n);\n    if (exposant > 0) {\n        return nombre_modulaire(modulo, 0);\n    } else {\n        return resultat;\n    }\n}\n\nnombre_modulaire nombre_modulaire::arrangement(size_t modulo, size_t n, size_t k) {\n    auto fn = factoriel2(modulo, n);\n    auto fnk = factoriel2(modulo, n - k);\n    if (fn.first - fnk.first > 0)\n        return nombre_modulaire(modulo, 0);\n    return fn.second / fnk.second;\n}\n\nnombre_modulaire nombre_modulaire::coefficient_binomial(size_t modulo, size_t n, size_t k) {\n    auto fn = factoriel2(modulo, n);\n    auto fk = factoriel2(modulo, k);\n    auto fnk = factoriel2(modulo, n - k);\n    if (fn.first - fk.first - fnk.first > 0)\n        return nombre_modulaire(modulo, 0);\n    return fn.second / (fk.second * fnk.second);\n}\n", "meta": {"hexsha": "15fddd37562627dcb086243a892fa26238be8372", "size": 4328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "maths/nombre_modulaire.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": "maths/nombre_modulaire.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": "maths/nombre_modulaire.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": 27.5668789809, "max_line_length": 102, "alphanum_fraction": 0.6621996303, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6858949090816759}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <math.h>\n#include <algorithm>    // std::swap\n\n#include \"isam_plane3d.h\"\n\n\nnamespace isam {\n  \n//copied from pop_up_wall  rays is 3*n, each column is a ray staring from origin  plane is (4\uff0c1\uff09 parameters, compute intersection  output is 3*n \nvoid ray_plane_interact(const Eigen::MatrixXd &rays,const Eigen::Vector4d &plane,Eigen::MatrixXd &intersections)\n{  \n    Eigen::VectorXd frac=-plane[3]/(plane.head(3).transpose()*rays).array();   //n*1 \n    intersections= frac.transpose().replicate<3,1>().array() * rays.array();\n}\n// copied from pop_up_wall (update_plane_equation_from_seg_fast), don't want to depend on that. no ground. ground_seg_ray=invK*groundlines  3*2n, precomputed\n// output is not quaternion normized\nvoid get_wall_plane_equation(const Eigen::MatrixXd& ground_seg_ray, const Eigen::Matrix4d& transToWorld, Eigen::MatrixXd& all_planes_sensor_out)\n{\n    if (ground_seg_ray.cols()>0)\n    {\n\tEigen::Vector4d ground_plane_world(0,0,-1,0);  //plane parameters for ground in world(footprint), treated as column vector\n\tEigen::Vector4d ground_plane_sensor = transToWorld.transpose()*ground_plane_world;  // using a new pose to project\n\n\tEigen::MatrixXd ground_seg3d_sensor; // 3*2n\n\tray_plane_interact(ground_seg_ray,ground_plane_sensor,ground_seg3d_sensor);\n\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> temp;\n\ttemp = ground_seg3d_sensor.transpose();\n\ttemp.resize(ground_seg3d_sensor.cols()/2,6); // n * 6\n\tground_seg3d_sensor = temp;\n\n\tint num_seg = ground_seg3d_sensor.rows();\n\tall_planes_sensor_out.resize(num_seg,4);\n\n\tfor (int seg=0;seg<num_seg;seg++)\n\t{\n\t    Eigen::Vector3d partwall_line3d_sensor_bg=ground_seg3d_sensor.row(seg).head(3);\n\t    Eigen::Vector3d partwall_line3d_sensor_en=ground_seg3d_sensor.row(seg).tail(3);\n\t    Eigen::Vector3d temp1=partwall_line3d_sensor_en-partwall_line3d_sensor_bg;\n\t    Eigen::Vector3d temp2=ground_plane_sensor.head(3);\n\t    Eigen::Vector3d partwall_normal_sensor=temp1.cross(temp2);\n\t    double dist=-partwall_normal_sensor.transpose()*partwall_line3d_sensor_bg;\n\t    Eigen::Vector4d partwall_plane_sensor;   partwall_plane_sensor<<partwall_normal_sensor,dist;\n\n\t    all_planes_sensor_out.row(seg)=partwall_plane_sensor;\n\t}\n    }\n    else\n    {\n\tall_planes_sensor_out.resize(0,4);\n    }\n}\n\n\n}", "meta": {"hexsha": "366f67fc65543f2e0e84b7055b7b1d841c4b22a8", "size": 2356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pop_planar_slam/src/isam_plane3d.cpp", "max_stars_repo_name": "gaunthan/pop_up_slam", "max_stars_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 196.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T00:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:32:37.000Z", "max_issues_repo_path": "pop_planar_slam/src/isam_plane3d.cpp", "max_issues_repo_name": "gaunthan/pop_up_slam", "max_issues_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2018-11-13T14:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:27:12.000Z", "max_forks_repo_path": "pop_planar_slam/src/isam_plane3d.cpp", "max_forks_repo_name": "gaunthan/pop_up_slam", "max_forks_repo_head_hexsha": "4d85a89f2cc09bf018af18ecba9e0a82e3c0ba1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 65.0, "max_forks_repo_forks_event_min_datetime": "2018-10-12T07:02:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:43:21.000Z", "avg_line_length": 40.6206896552, "max_line_length": 157, "alphanum_fraction": 0.7593378608, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374122, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6858949059253687}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // dot product of two std::vectors'\n    std::vector<float> x = {1,2,3,4};\n    std::vector<float> y = {1,2,3,4};\n    auto d = dot<float> (x,y); // d = x.y\n    BOOST_CHECK (d == 30);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> cm (\n           make_rowmajor_matrix_local_load<float>(\"./sample_4x4\"));\n  \n    // checking dot() operation  \n    auto row1 = make_row_vector<float> (cm,1);\n    auto row2 = make_row_vector<float> (cm,2);\n    \n    // checking whether the dot operation successfully taken place \n    auto r = dot<float>(row1, row2); // r = row1 . row2\n    BOOST_CHECK (r == 2);\n}\n\n", "meta": {"hexsha": "bfc1e6a179fbc3e27ba16fedf7050aab597455aa", "size": 941, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test6.5/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test6.5/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test6.5/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 26.8857142857, "max_line_length": 67, "alphanum_fraction": 0.6524973433, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6858742543733557}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/extensions/nsphere/nsphere.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/io/wkt/read.hpp>\n\ntypedef bg::model::d2::point_xy<double> point_type;\ntypedef bg::model::box<point_type> box_type;\ntypedef bg::model::nsphere<point_type, double> circle_type;\n\ntemplate <typename Geometry>\nvoid test_circle(Geometry const& geometry, std::string const& wkt_geometry, bool expected)\n{\n    circle_type circle(point_type(1.0, 1.0), 3.0);\n\n    bool detected = bg::disjoint(geometry, circle);\n\n    BOOST_CHECK_MESSAGE(detected == expected,\n        \"disjoint: \" << wkt_geometry\n        << \" in circle (1,1) with radius 3\"\n        << \" -> Expected: \" << expected\n        << \" detected: \" << detected);\n}\n\ntemplate <typename Geometry>\nvoid test_circle(std::string const& wkt_geometry, bool expected)\n{\n    Geometry geometry;\n    bg::read_wkt(wkt_geometry, geometry);\n\n    test_circle<Geometry>(geometry, wkt_geometry, expected);\n}\n\nint test_main( int , char* [] )\n{\n    test_circle<point_type>(\"POINT(2 1)\", false);\n    test_circle<point_type>(\"POINT(12 1)\", true);\n\n    test_circle<box_type>(\"BOX(2 1, 4 4)\", false);\n    test_circle<box_type>(\"BOX(-3 -3, -2 -2)\", true);\n\n    test_circle<circle_type>(circle_type(point_type(4, 4), 2), \"CIRCLE(4 4, 2)\", false);\n    test_circle<circle_type>(circle_type(point_type(4, 4), 0.5), \"CIRCLE(4 4, 0.5)\", true);\n\n    return 0;\n}\n", "meta": {"hexsha": "7d0ca456678c9c94dc87dd73bf6201ba1b5e66ec", "size": 1922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/nsphere/nsphere-disjoint.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/nsphere/nsphere-disjoint.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/nsphere/nsphere-disjoint.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 32.0333333333, "max_line_length": 91, "alphanum_fraction": 0.7044745057, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6858403495573212}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/qz.hpp\n *\n * \\brief QZ factorization for generalized eigenvalues.\n *\n * Given two square matrices, \\f$A\\f$ and \\f$B\\f$, there exist two unitary\n * matrices, \\f$Q\\f$ and \\f$Z\\f$, such that \\f$S=Q^{H}AZ\\f$ and \\f$T=Q^{H}BZ\\f$\n * are both upper quasi-triangular matrices (they are triangular if \\f$A\\f$ and\n * \\f$B\\f$ are complex matrices).\n *\n * Equivalently, given two square matrices \\f$A\\f$ and \\f$B\\f$, there exist four\n * matrices, \\f$S\\f$, \\f$T\\f$, \\f$Q\\f$, and \\f$Z\\f$, such that \\f$A=QSZ^{H}\\f$\n * and \\f$B=QTZ^{H}\\f$.\n *\n * This decomposition is called the <em>generalized Schur decomposition</em> and\n * is also known as <em>QZ decomposition</em>.\n *\n * The pair of matrices \\f$(A,B)\\f$ is also referred to as <em>matrix\n * pencil</em> and the problem of finding the eigenvalues of a pencil is called\n * the <em>generalized eigenvalue problem</em>.\n * A pencil is called <em>regular</em> if there is at least one value of\n * \\f$\\lambda\\f$ such that \\f$\\det(A-\\lambda B) \\ne 0\\f$.\n * We call <em>eigenvalues</em> of a matrix pencil \\f$(A,B)\\f$ all complex\n * numbers \\f$\\lambda\\f$ for which \\f$\\det(A-\\lambda B) = 0\\f$.\n * The set of the eigenvalues is called the <em>spectrum</em> of the pencil and\n * is written \\f$\\sigma(A,B)\\f$; specifically:\n * \\f[\n *  \\sigma (A,B) = \\left\\{z \\in \\mathbb{C} : \\det(A-zB)=0\\right\\}\n * \\f]\n * If \\f$\\lambda \\in \\sigma (A,B)\\f$ and\n * \\f[\n *   Ax = \\lambda Bx, \\quad x \\ne 0\n * \\f]\n * then \\f$x\\f$ is referred to as an eigenvector of \\f$A-\\lambda B\\f$.\n * Moreover, the pencil is said to have one or more eigenvalues at infinity if\n * \\f$B\\f$ has one or more \\f$0\\f$ eigenvalues.\n *\n * Although the decomposition is not unique, it yields the same generalized\n * eigenvalues that can be obtained by dividing the diagonal entries of \\f$S\\f$\n * by the corresponding diagonal entries of \\f$T\\f$.\n * Specifically, the generalized eigenvalues \\f$\\lambda\\f$ that solve the\n * generalized eigenvalue problem  \\f$A x = \\lambda B x\\f$ (where \\f$x\\f$ is an\n * unknown nonzero vector) can be calculated as the ratio of the diagonal\n * elements of \\f$S\\f$ to those of \\f$T\\f$. That is, using subscripts to denote\n * matrix elements, the \\f$i\\f$-th generalized eigenvalue \\f$\\lambda_i\\f$\n * satisfies \\f$\\lambda_i = S_{ii}  / T_{ii}\\f$.\n * The eigenvalues are finite when all the diagonal entries of \\f$T\\f$ are\n * nonzero.\n * By convention, the eigenvalues corresponding to zero diagonal entries of\n * \\f$T\\f$ are \\f$\\infty\\f$.\n * If both \\f$A\\f$ and \\f$B\\f$ are real, the complex eigenvalues occur in\n * conjugate pairs.\n * In this case, \\f$S\\f$ is a real quasi-upper triangular matrix.\n * Each \\f$2 \\times 2\\f$ block on the diagonal of \\f$S\\f$ corresponds to a\n * complex conjugate pair of eigenvalues, and the scalar diagonal entries\n * correspond to the real eigenvalues.\n * Such a decomposition is sometimes referred to as the <em>generalized real\n * Schur decomposition</em>.\n *\n * For more information see [1,2].\n *\n * \\note\n * Matlab users: the Matlab \\c qz function return the Hermitian of the \\f$Q\\f$\n * matrix computed by this decomposition, so that:\n * \\f{align}\n *  S &= Q^H*A*Z,\\\\\n *  T &= Q^H*B*Z\n * \\f}\n *\n * References:\n * - [1] Anderson et al,\n *       <em>The LAPACK User Guide</em>,\n *       http://www.netlib.org/lapack/lug/node56.html\n * - [2] Golub et al,\n *       <em>Matrix Computations, 3rd ed.</em>,\n *       (Sec. 7.7), Johns Hopkins University Press, 1996\n * .\n *\n * \\todo Optimize mem allocation similarly to eigen.hpp (where we used\n *  work_n_LV, out_n_LV, work_n_RV, and out_n_RV).\n *\n * <hr/>\n *\n * Copyright (c) 2010-2011, 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_QZ_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_QZ_HPP\n\n\n#include <boost/function.hpp>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/numeric/bindings/lapack/computational/tgsen.hpp>\n#include <boost/numeric/bindings/lapack/computational/tgevc.hpp>\n#include <boost/numeric/bindings/lapack/driver/gges.hpp>\n#include <boost/numeric/bindings/tag.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/detail/compiler.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n//#include <boost/numeric/ublasx/operation/balance.hpp>\n//#include <boost/numeric/ublasx/operation/eigen.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/traits/layout_type.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n#include <limits>\n\n\n/// Cast the given function \\a f to the QZ selector signature.\n#define BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(T,f) \\\n\t\t( \\\n\t\t\t::boost::is_complex<T>::value \\\n\t\t\t\t? ( \\\n\t\t\t\t\t::boost::is_same<float, typename type_traits<T>::real_type>::value \\\n\t\t\t\t\t\t? reinterpret_cast< ::external_fp >(static_cast<detail::qz_complex_single_selector_type>(f)) \\\n\t\t\t\t\t\t: reinterpret_cast< ::external_fp >(static_cast<detail::qz_complex_double_selector_type>(f)) \\\n\t\t\t\t) \\\n\t\t\t\t: ( \\\n\t\t\t\t\t::boost::is_same<float, typename type_traits<T>::real_type>::value \\\n\t\t\t\t\t\t? reinterpret_cast< ::external_fp >(static_cast<detail::qz_single_selector_type>(f)) \\\n\t\t\t\t\t\t: reinterpret_cast< ::external_fp >(static_cast<detail::qz_double_selector_type>(f)) \\\n\t\t\t\t) \\\n\t\t)\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n/// Eigenvalues selectors for QZ factorization.\nenum qz_eigenvalues_selection\n{\n\tall_qz_eigenvalues, ///< select all eigenvalues in the order of appearance (essentially, no ordering is performed).\n\tlhp_qz_eigenvalues, ///< Stable continuous-time space: select eigenvalues in the left-half plane (\\f$\\operatorname{real}(E) < 0\\f$).\n\trhp_qz_eigenvalues, ///< Unstable continuous-time space: select eigenvalues in the right-half plane (\\f$\\operatorname{real}(E) > 0\\f$).\n\tudi_qz_eigenvalues, ///< Stable discrete-time space: select eigenvalues which are interior of unit disk (\\f$\\operatorname{abs}(E) < 1\\f$).\n\tudo_qz_eigenvalues ///< Unstable discrete-time space: select eigenvalues which are exterior of unit disk (\\f$\\operatorname{abs}(E) > 1\\f$).\n};\n\t\n\nnamespace detail {\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n *  (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(::std::complex<float> a, ::std::complex<float> b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex<float>(a/b).real() < 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n *  (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(::std::complex<double> a, ::std::complex<double> b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex<double>(a/b).real() < 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n *  (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(float ar, float ai, float b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b < 0) || (ar < 0 && b > 0))\n\t\t   && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits<float>::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n *  (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(double ar, double ai, double b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b < 0) || (ar < 0 && b > 0))\n\t\t   && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits<double>::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n *  (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(::std::complex<float> a, ::std::complex<float> b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex<float>(a/b).real() > 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n *  (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(::std::complex<double> a, ::std::complex<double> b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex<double>(a/b).real() > 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n *  (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(float ar, float ai, float b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b > 0) || (ar < 0 && b < 0))\n\t\t   && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits<float>::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n *  (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(double ar, double ai, double b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b > 0) || (ar < 0 && b < 0))\n\t\t   && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits<double>::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(::std::complex<float> a, ::std::complex<float> b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\treturn ::std::abs(a) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(::std::complex<double> a, ::std::complex<double> b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\treturn ::std::abs(a) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(float ar, float ai, float b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\treturn ::std::abs(::std::complex<float>(ar, ai)) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(double ar, double ai, double b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\treturn ::std::abs(::std::complex<double>(ar, ai)) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(::std::complex<float> a, ::std::complex<float> b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t//        In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t//        In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(a) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(::std::complex<double> a, ::std::complex<double> b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t//        In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t//        In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(a) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(float ar, float ai, float b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t//        In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t//        In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(::std::complex<float>(ar, ai)) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n *  (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(double ar, double ai, double b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t//        In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t//        In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(::std::complex<double>(ar, ai)) >= ::std::abs(b);\n}\n\n\nnamespace /*<anoymous>*/ {\n\n/// Type for the QZ eigenvalues selector (single precision case).\ntypedef ::fortran_bool_t (*qz_single_selector_type)(float, float, float);\n/// Type for the QZ eigenvalues selector (double precision case).\ntypedef ::fortran_bool_t (*qz_double_selector_type)(double, double, double);\n/// Type for the QZ eigenvalues selector (single precision complex case).\ntypedef ::fortran_bool_t (*qz_complex_single_selector_type)(::std::complex<float>, ::std::complex<float>);\n/// Type for the QZ eigenvalues selector (single precision complex case).\ntypedef ::fortran_bool_t (*qz_complex_double_selector_type)(::std::complex<double>, ::std::complex<double>);\n\n\n/// Options to select what Schur vectors compute in the QZ decomposition.\nenum qz_schurvectors_side\n{\n\tnone_qz_schurvectors, ///< Do not compute vectors.\n\tleft_qz_schurvectors, ///< Compute only left vectors.\n\tright_qz_schurvectors, ///< Compute only right vectors.\n\tboth_qz_schurvectors ///< Compute both left and right vectors.\n};\n\n\n/// Options to select what generalized eigenvectors compute from the QZ decomposition.\nenum qz_eigenvectors_side\n{\n//\tnone_qz_eigenvectors, ///< Do not compute generalized eigenvectors.\n\tleft_qz_eigenvectors, ///< Compute only left generalized eigenvectors.\n\tright_qz_eigenvectors, ///< Compute only right generalized eigenvectors.\n\tboth_qz_eigenvectors ///< Compute both left and right generalized eigenvectors.\n};\n\n\n/// Options for reordering QZ factorizations.\nenum qz_order_option\n{\n\tno_extra_qz_option, ///< Only reorder w.r.t. SELECT. No extras.\n\tprojections_qz_option, ///<  Reciprocal of norms of \\e projections onto left and righteigenspaces w.r.t. the selected cluster (PL and PR).\n\tupper_bounds_fnorm_qz_option, ///< Upper bounds on Difu and Difl. F-norm-based estimate (DIF(1:2)).\n\tupper_bounds_1norm_qz_option, ///< Estimate of Difu and Difl. 1-norm-based estimate (DIF(1:2)).\n\tprojections_upper_bounds_fnorm_qz_option, ///< Compute PL, PR and DIF (F-norm based): Economic version to get it all.\n\tprojections_upper_bounds_1norm_qz_option ///< Compute PL, PR and DIF (1-norm based).\n};\n\n\n/// Options for computing generalized Schur eigenvectors.\nenum qz_eigenvectors_option\n{\n\tall_qz_eigenvectors_option, ///< Compute all right and/or left eigenvectors.\n\tbacktransform_qz_eigenvectors_option, ///< Compute all right and/or left eigenvectors, backtransformed by the matrices in VR and/or VL.\n\tselect_qz_eigenvectors_option ///< Compute selected right and/or left eigenvectors.\n};\n\n\n/// Create a selector function according to the given \\a selection method.\ntemplate <typename ValueT>\nBOOST_UBLAS_INLINE\n::external_fp create_qz_eigvals_selector(qz_eigenvalues_selection selection)\n{\n\t::external_fp selctg = 0;\n\n\tswitch (selection)\n\t{\n\t\tcase lhp_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_lhp_eigenval_sel);\n\t\t\tbreak;\n\t\tcase rhp_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_rhp_eigenval_sel);\n\t\t\tbreak;\n\t\tcase udi_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_udi_eigenval_sel);\n\t\t\tbreak;\n\t\tcase udo_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_udo_eigenval_sel);\n\t\t\tbreak;\n\t\tcase all_qz_eigenvalues:\n\t\tdefault:\n\t\t\tselctg = 0;\n\t\t\tbreak;\n\t}\n\n\treturn selctg;\n}\n\n\n/**\n * \\brief Call the proper selector function according to the given \\a selection\n *  method.\n *\n * \\todo Replace this function with something at compile-time, like below:\n *  <pre>\n *   // Declare the selector with the proper type (this should emulate the\n *   // switch below, but at compile-time)\n *   BOOST_UBLAS_DETAIL_QZ_DECLARE_SELECTOR(selection, selector);\n *   ...\n *   // Invoke the selector\n *   selector(a, b);\n *  </pre>\n *  This way, we avoid to perform the switch at every invocation of the\n *  selector.\n */\ntemplate <typename AValueT, typename BValueT>\nBOOST_UBLAS_INLINE\nbool invoke_qz_eigvals_selector(qz_eigenvalues_selection selection, AValueT a, BValueT b)\n{\n\tswitch (selection)\n\t{\n\t\tcase lhp_qz_eigenvalues:\n\t\t\treturn qz_lhp_eigenval_sel(a, b);\n\t\tcase rhp_qz_eigenvalues:\n\t\t\treturn qz_rhp_eigenval_sel(a, b);\n\t\tcase udi_qz_eigenvalues:\n\t\t\treturn qz_udi_eigenval_sel(a, b);\n\t\t\tbreak;\n\t\tcase udo_qz_eigenvalues:\n\t\t\treturn qz_udo_eigenval_sel(a, b);\n\t\tcase all_qz_eigenvalues:\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\n\n/// Extract the generalized Schur eigenvectors from a QZ decomposition\n/// (column-major case).\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename LVMatrixT,\n\ttypename RVMatrixT\n>\nvoid extract_eigenvectors(SMatrixT const& S, TMatrixT const& T, qz_eigenvectors_side eigvec_side, qz_eigenvectors_option eigvec_opt, vector< ::fortran_bool_t > eigvecs_sel, QMatrixT const& Q, ZMatrixT const& Z, LVMatrixT& LV, RVMatrixT& RV, column_major_tag)\n{\n\ttypedef typename matrix_traits<SMatrixT>::size_type size_type;\n\n\tsize_type nr_LV = 0;\n\tsize_type nc_LV = 0;\n\tsize_type nr_RV = 0;\n\tsize_type nc_RV = 0;\n\tbool resize_LV = true;\n\tbool resize_RV = true;\n\tchar howmny;\n\t::fortran_int_t n = static_cast< ::fortran_int_t >(num_rows(S));\n\t::fortran_int_t mm = 0;\n\t::fortran_int_t m = 0;\n\n\tswitch (eigvec_opt)\n\t{\n\t\tcase backtransform_qz_eigenvectors_option:\n\t\t\thowmny = 'B';\n\t\t\tif (eigvec_side != right_qz_eigenvectors)\n\t\t\t{\n\t\t\t\tLV = Q;\n\t\t\t}\n\t\t\tif (eigvec_side != left_qz_eigenvectors)\n\t\t\t{\n\t\t\t\tRV = Z;\n\t\t\t}\n\t\t\tmm = n;\n\t\t\tbreak;\n\t\tcase select_qz_eigenvectors_option:\n\t\t\thowmny = 'S';\n\t\t\tmm = static_cast< ::fortran_int_t >(size(eigvecs_sel));\n\t\t\tbreak;\n\t\tcase all_qz_eigenvectors_option:\n\t\tdefault:\n\t\t\thowmny = 'A';\n\t\t\tmm = n;\n\t}\n\n\tswitch (eigvec_side)\n\t{\n\t\tcase left_qz_eigenvectors:\n\t\t\tnr_RV = nc_RV = 1;\n\t\t\tnr_LV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_LV = mm = ::std::max(n, mm);\n\t\t\t\tresize_LV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_LV = mm;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase right_qz_eigenvectors:\n\t\t\tnr_LV = nc_LV = 1;\n\t\t\tnr_RV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_RV = mm = ::std::max(n, mm);\n\t\t\t\tresize_RV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_RV = mm;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase both_qz_eigenvectors:\n\t\tdefault:\n\t\t\tnr_LV = nr_RV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_LV = nc_RV = mm = ::std::max(n, mm);\n\t\t\t\tresize_LV = resize_RV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_LV = nc_RV = mm;\n\t\t\t}\n\t}\n\n\tif (resize_LV)\n\t{\n\t\tLV.resize(nr_LV, nc_LV, false);\n\t}\n\tif (resize_RV)\n\t{\n\t\tRV.resize(nr_RV, nc_RV, false);\n\t}\n\n\tswitch (eigvec_side)\n\t{\n\t\tcase left_qz_eigenvectors:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t\t\tbreak;\n\t\tcase right_qz_eigenvectors:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t\t\tbreak;\n\t\tcase both_qz_eigenvectors:\n\t\tdefault:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::both(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t}\n}\n\n\n/**\n * \\brief Generalized (real/complex) Schur decomposition.\n *\n * Given two square matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n *   A &= Q S Z^T,\\\\\n *   B &= Q T Z^T\n * \\f}\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <bool IsComplex>\nstruct qz_decomposition_impl;\n\n\n/**\n * \\brief Generalized real Schur decomposition.\n *\n * Given two square real matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n *   A &= Q S Z^T,\\\\\n *   B &= Q T Z^T\n * \\f}\n *\n * The diagonal elements of \\f$S\\f$ and \\f$T\\f$,\n * \\f$\\alpha = \\operatorname{diag}{S}\\f$ and\n * \\f$\\beta = \\operatorname{diag}{S}\\f$, are the generalized eigenvalues that\n * satisfy:\n * \\f{align}{\n *   A V \\beta &= B V \\alpha,\\\\\n *   \\beta W A &= \\alpha W^T B.\n * \\f}\n *\n * The ratios:\n * \\f[\n *   \\frac{\\alpha_i}{\\beta_i}\n * \\f]\n * are the generalized eigenvalues.\n * \\f$\\alpha_i\\f$ and \\f$\\beta_i\\f$ are the diagonals of the complex Schur\n * form (S,T) that would result if the 2-by-2 diagonal blocks of\n * the real Schur form of \\f$(A,B)\\f$ were further reduced to\n * triangular form using 2-by-2 complex unitary transformations.\n * If \\f$\\operatorname{imag}(\\alpha_i)\\f$ is zero, then the \\f$i\\f$-th\n * eigenvalue is real; if positive, then the \\f$j\\f$-th and \\f$(i+1)\\f$-st\n * eigenvalues are a complex conjugate pair, with\n * \\f$\\operatorname{imag}(\\alpha_{i+1})\\f$ negative.\n * The quotients \\f$\\alpha_i/\\beta_i\\f$ may easily over- or underflow, and\n * \\f$\\beta_i\\f$ may even be zero.\n * It should be avoided to naively computing the ratio \\f$alpha_i/beta_i\\f$.\n * However, \\f$\\alpha\\f$ will be always less than and usually\n * comparable with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f\\beta\\f$\n * always less than and usually comparable with \\f$\\operatorname{norm}(B)\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct qz_decomposition_impl<false>\n{\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (column-major\n \t *  case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t *  (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate <typename AMatrixT, typename BMatrixT, typename QMatrixT, typename ZMatrixT, typename AlphaVectorT, typename BetaVectorT>\n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<AMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<BMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<AMatrixT>::size_type,\n\t\t\t\t\ttypename matrix_traits<BMatrixT>::size_type\n\t\t\t\t>::promote_type size_type;\n\t\ttypedef vector<value_type> work_vector_type;\n\n\t\tsize_type n = num_rows(A);\n\t\tchar jobvsl;\n\t\tchar jobvsr;\n\t\tchar sort;\n\t\tsize_type n_q;\n\t\tsize_type n_z;\n\n\t\tswitch (eigvecs_side)\n\t\t{\n\t\t\tcase both_qz_schurvectors:\n\t\t\t\tjobvsl = jobvsr = 'V';\n\t\t\t\tn_q = n_z = n;\n\t\t\t\tbreak;\n\t\t\tcase left_qz_schurvectors:\n\t\t\t\tjobvsl = 'V';\n\t\t\t\tjobvsr = 'N';\n\t\t\t\tn_q = n;\n\t\t\t\tn_z = 0;\n\t\t\t\tbreak;\n\t\t\tcase right_qz_schurvectors:\n\t\t\t\tjobvsl = 'N';\n\t\t\t\tjobvsr = 'V';\n\t\t\t\tn_q = 0;\n\t\t\t\tn_z = n;\n\t\t\t\tbreak;\n\t\t\tcase none_qz_schurvectors:\n\t\t\tdefault:\n\t\t\t\tjobvsl = jobvsr = 'N';\n\t\t\t\tn_q = n_z = 0;\n\t\t}\n\n\t\tif (reorder_eigvals)\n\t\t{\n\t\t\tsort = 'S';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsort = 'N';\n\t\t}\n\n\t\tif (num_rows(Q) != n)\n\t\t{\n\t\t\tQ.resize(n, n, false);\n\t\t}\n\t\tif (num_rows(Z) != n)\n\t\t{\n\t\t\tZ.resize(n, n, false);\n\t\t}\n\n\t\twork_vector_type alpha_real(n);\n\t\twork_vector_type alpha_imag(n);\n\t\tif (size(beta) != n)\n\t\t{\n\t\t\tbeta.resize(n, false);\n\t\t}\n\n\t\t::fortran_int_t sdim;\n\n\t\t::boost::numeric::bindings::lapack::gges(\n\t\t\tjobvsl,\n\t\t\tjobvsr,\n\t\t\tsort,\n\t\t\teigvals_selector,\n\t\t\tA,\n\t\t\tB,\n\t\t\tsdim,\n\t\t\talpha_real,\n\t\t\talpha_imag,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ\n\t\t);\n\n\t\t// Create the alpha vector\n\t\tif (want_eigvals)\n\t\t{\n\t\t\tif (size(alpha) != n)\n\t\t\t{\n\t\t\t\talpha.resize(n, false);\n\t\t\t}\n\t\t\t// From LAPACK ?GGES documentation\n\t\t\t// \"If ALPHAI(j) is zero, then the j-th eigenvalue is real; if\n\t\t\t// positive, then the j-th and (j+1)-st eigenvalues are a\n\t\t\t// complex conjugate pair, with ALPHAI(j+1) negative.\"\n\t\t\t//\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t// Underflow threshold (used in the 'safety check' inside the 'for' loop)\n\t\t\tvalue_type rmin(::std::numeric_limits<value_type>::min());\n#endif // BOOST_UBLASX_DEBUG\n\t\t\tfor (size_type i = 0; i < n; ++i)\n\t\t\t{\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t\t// Safety check: when beta_i is near to zero the corresponding\n\t\t\t\t//               eigenvalue is infinite.\n\t\t\t\t//               This test was inspired by the 'f08wafe.f'\n\t\t\t\t//               subrouting found on NAG libraries.\n\t\t\t\tif ((::std::abs(alpha_real(i))+::std::abs(alpha_imag(i)))*rmin >= ::std::abs(beta(i)))\n\t\t\t\t{\n\t\t\t\t\tBOOST_UBLASX_DEBUG_TRACE(\"[Warning] Eigenvalue(\" << i << \") is numerically infinite or undetermined: alpha_r(\" << i << \") = \" << alpha_real(i) << \", alpha_i(\" << i << \") = \" << alpha_imag(i) << \", beta(\" << i << \") = \" << beta(i));\n\t\t\t\t}\n#endif // BOOST_UBLASX_DEBUG\n\n//\t\t\t\tif (alpha_imag(i) == value_type/*zero*/())\n//\t\t\t\t{\n//\t\t\t\t\talpha(i) = ::std::complex<value_type>(alpha_real(i), value_type/*zero*/());\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t{\n//\t\t\t\t\talpha(i) = ::std::complex<value_type>(alpha_real(i), alpha_imag(i));\n//\t\t\t\t\t// safety check (even if it should not happen)\n//\t\t\t\t\tif ((i+1) < n)\n//\t\t\t\t\t{\n//\t\t\t\t\t\talpha(i+1) = ::std::conj(alpha(i));\n//\t\t\t\t\t}\n//\t\t\t\t\t++i;\n//\t\t\t\t}\n\t\t\t\tif (alpha_imag(i) == value_type/*zero*/())\n\t\t\t\t{\n\t\t\t\t\talpha(i) = ::std::complex<value_type>(alpha_real(i), value_type/*zero*/());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talpha(i) = ::std::complex<value_type>(alpha_real(i), alpha_imag(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\n\t\tif (num_rows(Q) != n_q)\n\t\t{\n\t\t\tQ.resize(n_q, n_q, n_q > 0 ? true : false);\n\t\t}\n\t\tif (num_rows(Z) != n_z)\n\t\t{\n\t\t\tZ.resize(n_z, n_z, n_z > 0 ? true : false);\n\t\t}\n\t}\n\n\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (row-major case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t *  (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate <typename AMatrixT, typename BMatrixT, typename QMatrixT, typename ZMatrixT, typename AlphaVectorT, typename BetaVectorT>\n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n//\t\tmatrix<typename matrix_traits<AMatrixT>::value_type, typename layout_type<AMatrixT>::type> tmp_A(A);\n//\t\tmatrix<typename matrix_traits<BMatrixT>::value_type, typename layout_type<BMatrixT>::type> tmp_B(B);\n//\t\tmatrix<typename matrix_traits<QMatrixT>::value_type, typename layout_type<QMatrixT>::type> tmp_Q(Q);\n//\t\tmatrix<typename matrix_traits<ZMatrixT>::value_type, typename layout_type<ZMatrixT>::type> tmp_Z(Z);\n\t\tmatrix<typename matrix_traits<AMatrixT>::value_type, column_major> tmp_A(A);\n\t\tmatrix<typename matrix_traits<BMatrixT>::value_type, column_major> tmp_B(B);\n\t\tmatrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\t\tmatrix<typename matrix_traits<ZMatrixT>::value_type, column_major> tmp_Z(Z);\n\n\t\tdecompose(tmp_A, tmp_B, eigvecs_side, want_eigvals, reorder_eigvals, eigvals_selector, tmp_Q, tmp_Z, alpha, beta, column_major_tag());\n\n\t\tA = tmp_A;\n\t\tB = tmp_B;\n\t\tQ = tmp_Q;\n\t\tZ = tmp_Z;\n\n\t\tif (!want_eigvals)\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (column-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector< ::fortran_bool_t > eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\n\t\t::fortran_int_t ijob; // type of job the LAPACK function has to perform [intput]\n\t\t::fortran_int_t m; // dimension of the specified pair of left and right eigenspaces [output]\n\t\tvalue_type projl; // lower bounds on the reciprocal of the norm of \"projections\" onto left eigenspace [output]\n\t\tvalue_type projr; // lower bounds on the reciprocal of the norm of \"projections\" onto right eigenspace [output]\n\t\tvector<value_type> dif; // store the estimates of Difu and Difl [output]\n\n\t\t// Decode order option\n\t\tswitch (order_opt)\n\t\t{\n\t\t\tcase projections_qz_option:\n\t\t\t\tijob = 1;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 2;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 3;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 4;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 5;\n\t\t\t\tbreak;\n\t\t\tcase no_extra_qz_option:\n\t\t\tdefault:\n\t\t\t\tijob = 0;\n\t\t}\n\n\t\tif (ijob >= 2)\n\t\t{\n\t\t\tdif.resize(2, false);\n\t\t}\n\n\t\tvector<value_type> aux_alphar(real(alpha));\n\t\tvector<value_type> aux_alphai(imag(alpha));\n\n\t\t::boost::numeric::bindings::lapack::tgsen(\n\t\t\tijob,\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Q ? 1 : 0),\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Z ? 1 : 0),\n\t\t\teigvals_sel,\n\t\t\tS,\n\t\t\tT,\n\t\t\taux_alphar,\n\t\t\taux_alphai,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ,\n\t\t\tm,\n\t\t\tprojl,\n\t\t\tprojr,\n\t\t\tdif\n\t\t);\n\n\t\t// Update the alpha vector\n\t\t//\n\t\t// From LAPACK ?TGSEN documentation\n\t\t// \"If ALPHAI(j) is zero, then the j-th eigenvalue is real; if\n\t\t// positive, then the j-th and (j+1)-st eigenvalues are a\n\t\t// complex conjugate pair, with ALPHAI(j+1) negative.\"\n\t\t//\n\t\ttypedef typename vector_traits<AlphaVectorT>::size_type alpha_size_type;\n\t\talpha_size_type n = size(alpha);\n\t\tfor (alpha_size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (aux_alphai(i) == value_type/*zero*/())\n\t\t\t{\n\t\t\t\talpha(i) = ::std::complex<value_type>(aux_alphar(i), value_type/*zero*/());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\talpha(i) = ::std::complex<value_type>(aux_alphar(i), aux_alphai(i));\n\t\t\t\t// safety check (even if it should not happen)\n\t\t\t\tif ((i+1) < n)\n\t\t\t\t{\n\t\t\t\t\talpha(i+1) = ::std::conj(alpha(i));\n\t\t\t\t}\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (row-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector< ::fortran_bool_t > eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\t\tcolmaj_matrix_type tmp_S(S);;\n\t\tcolmaj_matrix_type tmp_T(T);;\n\t\tcolmaj_matrix_type tmp_Q;//(Q); //FIXME: maybe unnecessary if update_Q == false\n\t\tcolmaj_matrix_type tmp_Z;//(Z); //FIXME: maybe unnecessary if update_Z == false\n\n\t\tif (update_Q)\n\t\t{\n\t\t\ttmp_Q = Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\ttmp_Z = Z;\n\t\t}\n\n\t\treorder(tmp_S, tmp_T, order_opt, eigvals_sel, alpha, beta, update_Q, tmp_Q, update_Z, tmp_Z, column_major_tag());\n\n\t\tS = tmp_S;\n\t\tT = tmp_T;\n\t\tif (update_Q)\n\t\t{\n\t\t\tQ = tmp_Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\tZ = tmp_Z;\n\t\t}\n\t}\n}; // struct qz_decomposition_impl<false>\n\n\n/**\n * \\brief Generalized complex Schur decomposition.\n *\n * Given two square complex matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n *   A &= Q S Z^T,\\\\\n *   B &= Q T Z^T\n * \\f}\n *\n * The diagonal elements of \\f$S\\f$ and \\f$T\\f$,\n * \\f$\\alpha = \\operatorname{diag}{S}\\f$ and\n * \\f$\\beta = \\operatorname{diag}{S}\\f$, are the generalized eigenvalues that\n * satisfy:\n * \\f{align}{\n *   A V \\beta &= B V \\alpha,\\\\\n *   \\beta W A &= \\alpha W^T B.\n * \\f}\n *\n * The ratios\n * \\f[\n *   \\lambda_i = \\frac{\\alpha_i}{\\beta_i}\n * \\f]\n * represents the generalized eigenvalues of the matrix pair \\f$(A,B)\\f$, such\n * that \\f$A - \\lambda_i*B\\f$ is singular.\n * The quotients \\f$\\alpha_i/\\beta_i\\f$ may easily over- or underflow, and\n * \\f$\\beta_i\\f$ may even be zero.\n * It should be avoided to naively computing the ratio \\f$alpha_i/beta_i\\f$.\n * However, \\f$\\alpha\\f$ will be always less than and usually\n * comparable with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f\\beta\\f$\n * always less than and usually comparable with \\f$\\operatorname{norm}(B)\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct qz_decomposition_impl<true>\n{\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (row-major case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t *  (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate <typename AMatrixT, typename BMatrixT, typename QMatrixT, typename ZMatrixT, typename AlphaVectorT, typename BetaVectorT>\n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\tmatrix<typename matrix_traits<AMatrixT>::value_type, column_major> tmp_A(A);\n\t\tmatrix<typename matrix_traits<BMatrixT>::value_type, column_major> tmp_B(B);\n\t\tmatrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\t\tmatrix<typename matrix_traits<ZMatrixT>::value_type, column_major> tmp_Z(Z);\n\n\t\t//decompose(tmp_A, tmp_B, tmp_Q, tmp_Z, alpha, beta, side, order, selctg, column_major_tag());\n\t\tdecompose(tmp_A, tmp_B, tmp_Q, tmp_Z, alpha, beta, eigvecs_side, reorder_eigvals, eigvals_selector, column_major_tag());\n\n\t\tA = tmp_A;\n\t\tB = tmp_B;\n\t\tQ = tmp_Q;\n\t\tZ = tmp_Z;\n\n\t\tif (!want_eigvals)\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\t}\n\n\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (column-major\n \t *  case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t *  (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate <typename AMatrixT, typename BMatrixT, typename QMatrixT, typename ZMatrixT, typename AlphaVectorT, typename BetaVectorT>\n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, column_major_tag)\n\t{\n\t\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(want_eigvals);\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<AMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<BMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename type_traits<value_type>::real_type real_type;\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<AMatrixT>::size_type,\n\t\t\t\t\ttypename matrix_traits<BMatrixT>::size_type\n\t\t\t\t>::promote_type size_type;\n\n\t\tsize_type n = num_rows(A);\n\t\tchar jobvsl;\n\t\tchar jobvsr;\n\t\tchar sort;\n\t\tsize_type n_q;\n\t\tsize_type n_z;\n\n\t\tswitch (eigvecs_side)\n\t\t{\n\t\t\tcase both_qz_schurvectors:\n\t\t\t\tjobvsl = jobvsr = 'V';\n\t\t\t\tn_q = n_z = n;\n\t\t\t\tbreak;\n\t\t\tcase left_qz_schurvectors:\n\t\t\t\tjobvsl = 'V';\n\t\t\t\tjobvsr = 'N';\n\t\t\t\tn_q = n;\n\t\t\t\tn_z = 0;\n\t\t\t\tbreak;\n\t\t\tcase right_qz_schurvectors:\n\t\t\t\tjobvsl = 'N';\n\t\t\t\tjobvsr = 'V';\n\t\t\t\tn_q = 0;\n\t\t\t\tn_z = n;\n\t\t\t\tbreak;\n\t\t\tcase none_qz_schurvectors:\n\t\t\tdefault:\n\t\t\t\tjobvsl = jobvsr = 'N';\n\t\t\t\tn_q = n_z = 0;\n\t\t}\n\n\t\tif (reorder_eigvals)\n\t\t{\n\t\t\tsort = 'S';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsort = 'N';\n\t\t}\n\n\t\tif (num_rows(Q) != n)\n\t\t{\n\t\t\tQ.resize(n, n, false);\n\t\t}\n\t\tif (num_rows(Z) != n)\n\t\t{\n\t\t\tZ.resize(n, n, false);\n\t\t}\n\t\tif (size(alpha) != n)\n\t\t{\n\t\t\talpha.resize(n, false);\n\t\t}\n\t\tif (size(beta) != n)\n\t\t{\n\t\t\tbeta.resize(n, false);\n\t\t}\n\n\t\t::fortran_int_t sdim;\n\n\t\t::boost::numeric::bindings::lapack::gges(\n\t\t\tjobvsl,\n\t\t\tjobvsr,\n\t\t\tsort,\n\t\t\teigvals_selector,\n\t\t\tA,\n\t\t\tB,\n\t\t\tsdim,\n\t\t\talpha,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ\n\t\t);\n\n\t\tif (want_eigvals)\n\t\t{\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t// Safety check: when beta_i is near to zero the corresponding\n\t\t\t//               eigenvalue is infinite.\n\t\t\t//               This test was inspired by the 'f08wnfe.f'\n\t\t\t//               subrouting found on NAG libraries.\n\t\t\treal_type rmin(::std::numeric_limits<real_type>::min());\n\t\t\tfor (size_type i = 0; i < n; ++i)\n\t\t\t{\n\t\t\t\tif (::std::abs(alpha(i))*rmin >= ::std::abs(beta(i)))\n\t\t\t\t{\n\t\t\t\t\tBOOST_UBLASX_DEBUG_TRACE(\"[Warning] Eigenvalue(\" << i << \") is numerically infinite or undetermined: alpha(\" << i << \") = \" << alpha(i) << \", beta(\" << i << \") = \" << beta(i));\n\t\t\t\t}\n\t\t\t}\n#endif // BOOST_UBLASX_DEBUG\n\t\t}\n\t\telse\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\n\t\tif (num_rows(Q) != n_q)\n\t\t{\n\t\t\tQ.resize(n_q, n_q, n_q > 0 ? true : false);\n\t\t}\n\t\tif (num_rows(Z) != n_z)\n\t\t{\n\t\t\tZ.resize(n_z, n_z, n_z > 0 ? true : false);\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (column-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector<fortran_bool_t> eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename type_traits<value_type>::real_type real_type;\n\n\t\t::fortran_int_t ijob; // type of job the LAPACK function has to perform [intput]\n\t\t::fortran_int_t m; // dimension of the specified pair of left and right eigenspaces [output]\n\t\treal_type projl; // lower bounds on the reciprocal of the norm of \"projections\" onto left eigenspace [output]\n\t\treal_type projr; // lower bounds on the reciprocal of the norm of \"projections\" onto right eigenspace [output]\n\t\tvector<real_type> dif; // store the estimates of Difu and Difl [output]\n\n\t\t// Decode order option\n\t\tswitch (order_opt)\n\t\t{\n\t\t\tcase projections_qz_option:\n\t\t\t\tijob = 1;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 2;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 3;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 4;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 5;\n\t\t\t\tbreak;\n\t\t\tcase no_extra_qz_option:\n\t\t\tdefault:\n\t\t\t\tijob = 0;\n\t\t}\n\n\t\tif (ijob >= 2)\n\t\t{\n\t\t\tdif.resize(2, false);\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::tgsen(\n\t\t\tijob,\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Q ? 1 : 0),\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Z ? 1 : 0),\n\t\t\teigvals_sel,\n\t\t\tS,\n\t\t\tT,\n\t\t\talpha,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ,\n\t\t\tm,\n\t\t\tprojl,\n\t\t\tprojr,\n\t\t\tdif\n\t\t);\n\t}\n\n\n\t/// Reorder the given QZ decomposition (row-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector<bool> eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\t\tcolmaj_matrix_type tmp_S(S);;\n\t\tcolmaj_matrix_type tmp_T(T);;\n\t\tcolmaj_matrix_type tmp_Q; //(Q); //FIXME: maybe unnecessary if update_Q == false\n\t\tcolmaj_matrix_type tmp_Z; //(Z); //FIXME: maybe unnecessary if update_Z == false\n\n\t\tif (update_Q)\n\t\t{\n\t\t\ttmp_Q = Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\ttmp_Z = Z;\n\t\t}\n\n\t\treorder(tmp_S, tmp_T, order_opt, eigvals_sel, alpha, beta, update_Q, tmp_Q, update_Z, tmp_Z, column_major_tag());\n\n\t\tS = tmp_S;\n\t\tT = tmp_T;\n\t\tif (update_Q)\n\t\t{\n\t\t\tQ = tmp_Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\tZ = tmp_Z;\n\t\t}\n\t}\n}; // struct qz_decomposition_impl<true>\n\n}} // Namespace detail::<anonymous>\n\n\n/**\n * \\brief Generalized Schur (QZ) decomposition.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename ValueT>\nclass qz_decomposition\n{\n\tpublic: typedef ValueT value_type;\n\t//private: typedef typename type_traits<value_type>::real_type real_type;\n\tprivate: typedef matrix<value_type, column_major> work_matrix_type;\n\tpublic: typedef work_matrix_type S_matrix_type;\n\tpublic: typedef work_matrix_type T_matrix_type;\n\tpublic: typedef work_matrix_type Q_matrix_type;\n\tpublic: typedef work_matrix_type Z_matrix_type;\n\tpublic: typedef work_matrix_type eigvecs_matrix_type;\n\tpublic: typedef vector<\n\t\t\t\t\t\ttypename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t::boost::is_complex<value_type>,\n\t\t\t\t\t\t\t\tvalue_type,\n\t\t\t\t\t\t\t\t::std::complex<value_type>\n\t\t\t\t\t\t\t>::type\n\t\t\t\t> alpha_vector_type; // NOTE: alpha is a complex vector both for real and complex case. \n\tpublic: typedef vector<value_type> beta_vector_type; // NOTE: beta is a complex vector only for complex case.\n\tpublic: typedef alpha_vector_type eigvals_vector_type;\n\tprivate: typedef typename matrix_traits<work_matrix_type>::size_type size_type;\n\n\n\t/// Default constructor.\n\tpublic: qz_decomposition()\n\t{\n\t\t// empty\n\t}\n\n\n\t/**\n\t * \\brief A constructor: QZ decomposition of \\a A and \\a B with optional\n\t *  reordering.\n\t *\n\t * \\param A The first input matrix.\n\t * \\param B The second input matrix.\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tpublic: template <typename MatrixExprT1, typename MatrixExprT2>\n\t\tqz_decomposition(matrix_expression<MatrixExprT1> const& A, matrix_expression<MatrixExprT2> const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n\t\t: S_(A),\n\t\t  T_(B)\n\t{\n\t\t// NOTE: preconditions check moved inside decompose.\n\n\t\tdecompose(selection);\n\t}\n\n\n\t/**\n\t * \\brief QZ decomposition of \\a A and \\a B with optional reordering.\n\t *\n\t * \\param A The first input matrix.\n\t * \\param B The second input matrix.\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tpublic: template <typename MatrixExprT1, typename MatrixExprT2>\n\t\tvoid decompose(matrix_expression<MatrixExprT1> const& A, matrix_expression<MatrixExprT2> const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n\t{\n\t\t// precondition: A and B have same orientation category\n\t\tBOOST_MPL_ASSERT(\n\t\t\t(\n\t\t\t\t::boost::is_same<\n\t\t\t\t\t\ttypename matrix_traits<MatrixExprT1>::orientation_category,\n\t\t\t\t\t\ttypename matrix_traits<MatrixExprT2>::orientation_category\n\t\t\t\t>\n\t\t\t)\n\t\t);\n\t\t// precondition: A is square\n\t\tBOOST_UBLAS_CHECK( num_rows(A) == num_columns(A), bad_size() );\n\t\t// precondition: B is square\n\t\tBOOST_UBLAS_CHECK( num_rows(B) == num_columns(B), bad_size() );\n\n\t\tS_ = A;\n\t\tT_ = B;\n\n\t\tdecompose(selection);\n\t}\n\n\n\t/**\n\t * \\brief Get the Schur form of the first input matrix \\f$A\\f$ in the\n\t *  QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The Schur form of the input matrix \\f$A\\f$.\n\t */\n\tpublic: S_matrix_type const& S() const\n\t{\n\t\treturn S_;\n\t}\n\n\n\t/**\n\t * \\brief Get the Schur form of the second input matrix \\f$B\\f$ in the\n\t *  QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The Schur form of the input matrix \\f$B\\f$.\n\t */\n\tpublic: T_matrix_type const& T() const\n\t{\n\t\treturn T_;\n\t}\n\n\n\t/**\n\t * \\brief Get the orthogonal (or unitary) \\f$Q\\f$ matrix in the\n\t *  QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The orthogonal (or unitary) \\f$Q\\f$ matrix.\n\t */\n\tpublic: Q_matrix_type const& Q() const\n\t{\n\t\treturn Q_;\n\t}\n\n\n\t/**\n\t * \\brief Get the orthogonal (or unitary) \\f$Z\\f$ matrix in the\n\t *  QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The orthogonal (or unitary) \\f$Z\\f$ matrix.\n\t */\n\tpublic: Z_matrix_type const& Z() const\n\t{\n\t\treturn Z_;\n\t}\n\n\n\t/**\n\t * \\brief Get the numerators of the generalized eigenvalues.\n\t *\n\t * \\return The numerators of the generalized eigenvalues.\n\t */\n\tpublic: alpha_vector_type const& alpha() const\n\t{\n\t\treturn alpha_;\n\t}\n\n\n\t/**\n\t * \\brief Get the denominators of the generalized eigenvalues.\n\t *\n\t * \\return The denominators of the generalized eigenvalues.\n\t */\n\tpublic: beta_vector_type const& beta() const\n\t{\n\t\treturn beta_;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized eigenvalues.\n\t *\n\t * Compute the generalized eigenvalues as the ratio:\n\t * \\f[\n\t *   \\frac{\\alpha_i}{\\beta_i}\n\t * \\f]\n\t * where \\f$\\alpha_i\\f$ and \\f$\\beta_i\\f$ are the are the diagonals of the\n\t * Schur form of the original input matrices \\f$(A,B)\\f$.\n\t *\n\t * \\return The generalized eigenvalues.\n\t *\n\t * \\note\n\t *  It is generally not safe to directly compute this ratio since it may\n\t *  easily over- or underflow, and \\f$\\beta_i\\f$ may even be zero.\n\t *  However, \\f$\\alpha\\f$ will be always less than and usually comparable\n\t *  with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f$\\beta\\f$ always\n\t *  less than and usually comparable with  \\f$\\operatorname{norm}(B)\\f$.\n\t */\n\tpublic: eigvals_vector_type eigenvalues() const\n\t{\n\t\treturn element_div(alpha_, beta_);\n\n//Another (more costly) alternative to get eigenvalues\n//\t\teigvals_vector_type l;\n//\t\tmatrix<typename vector_traits<eigvals_vector_type>::value_type,column_major> L;\n//\t\tmatrix<typename vector_traits<eigvals_vector_type>::value_type,column_major> V;\n//\t\teigen(S_, T_, l, L, V);\n\n//Try to balance before computing eigenvalues (really needed?)\n//\t\tS_matrix_type SS(S_);\n//\t\tT_matrix_type TT(T_);\n//\n//\t\tbalance_inplace(SS, TT, false, true);\n//\t\teigen(SS, TT, l, L, V);\n//\n//\t\treturn l;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized left eigenvectors.\n\t *\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t *  pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return A matrix whose columns are the generalized left eigenvectors.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t *  S x &= w T x,\\\\\n\t *  y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t *  \n\t * This function returns the matrix \\f$Y\\f$ of left eigenvectors of\n\t * \\f$(S,T)\\f$, or the product \\f$Q*Y\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the\n\t * Schur vectors computed by the QZ decomposition, representing the left\n\t * eigenvectors of \\f$(A,B)\\f$.\n\t */\n\tpublic: eigvecs_matrix_type left_eigenvectors(bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\t\teigvecs_matrix_type LV;\n\t\teigvecs_matrix_type dummy_RV;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::left_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tLV,\n\t\t\tdummy_RV,\n\t\t\tcolumn_major_tag()\n\t\t);\n\n\t\treturn LV;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized right eigenvectors.\n\t *\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t *  pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return A matrix whose columns are the generalized right eigenvectors.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t *  S x &= w T x,\\\\\n\t *  y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t *  \n\t * This function returns the matrix \\f$X\\f$ of right eigenvectors of\n\t * \\f$(S,T)\\f$, or the product \\f$Z*X\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the\n\t * Schur vectors computed by the QZ decomposition, representing the right\n\t * eigenvectors of \\f$(A,B)\\f$.\n\t */\n\tpublic: eigvecs_matrix_type right_eigenvectors(bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\t\teigvecs_matrix_type dummy_Y;\n\t\teigvecs_matrix_type X;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::right_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tdummy_Y,\n\t\t\tX,\n\t\t\tcolumn_major_tag()\n\t\t);\n\n\t\treturn X;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized eigenvectors.\n\t *\n\t * \\param LV A matrix whose columns are the generalized left eigenvectors.\n\t * \\param RV A matrix whose columns are the generalized right eigenvectors.\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t *  pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return None, but output parameters \\a LV and \\a RV stores, on exit, the\n\t *  left and right eigenvectors, respectively.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t *  S x &= w T x,\\\\\n\t *  y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t *  \n\t * This function returns the matrices \\f$X\\f$ and \\f$Y\\f$ of right and\n\t * left eigenvectors of \\f$(S,T)\\f$, or the products \\f$Z*X\\f$ and\n\t * \\f$Q*Y\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the Schur vectors computed by\n\t * the QZ decomposition, representing the right and left eigenvectors of\n\t * \\f$(A,B)\\f$.\n\t */\n\tpublic: void eigenvectors(eigvecs_matrix_type& X, eigvecs_matrix_type& Y, bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::both_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tY,\n\t\t\tX,\n\t\t\tcolumn_major_tag()\n\t\t);\n\t}\n\n\n\t/**\n\t * \\brief Reorder the QZ decomposition.\n\t *\n\t * Reorders the generalized real Schur decomposition so that a\n\t * selected cluster of eigenvalues appears in the leading diagonal blocks\n\t * of the upper quasi-triangular matrix \\c S and the upper triangular\n\t * \\c T.\n\t * The leading columns of \\c Q and \\c Z form orthonormal bases of the\n\t * corresponding left and right eigenspaces (deflating subspaces).\n\t *\n\t * \\note\n\t *  The \\c i-th element of the input vector \\a selection must evaluate\n\t *  to \\c true if the \\c i-th eigenvalue is to be selected.\n\t * \\note\n\t *  As a side effect this function changes the original QZ decomposition\n\t *  (i.e., matrices \\c S, \\c T, \\c Q, and \\c Z, and vector \\c alpha and\n\t *  \\c beta).\n\t */\n\tpublic: void reorder(qz_eigenvalues_selection selection)\n\t{\n\t\t//::external_fp selctg;\n\t\tsize_type n = size(alpha_);\n\t\tvector< ::fortran_bool_t > eigvals_sel(n);\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (detail::invoke_qz_eigvals_selector(selection, alpha_(i), beta_(i)))\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 0;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex<\n\t\t\t\t\tvalue_type\n\t\t\t\t>::value\n\t\t\t>::template reorder(S_, T_, detail::no_extra_qz_option, eigvals_sel, alpha_, beta_, true, Q_, true, Z_, column_major_tag());\n\t}\n\n\n\t/**\n\t * \\brief Reorder the QZ decomposition.\n\t *\n\t * \\tparam VectorExprT The type of the input selection vector.\n\t * \\param selection Logical vector whose i-th element specifies whether the\n\t * \ti-th eigenvalue is to be selected.\n\t *\n\t * Reorders the generalized real Schur decomposition so that a\n\t * selected cluster of eigenvalues appears in the leading diagonal blocks\n\t * of the upper quasi-triangular matrix \\c S and the upper triangular\n\t * \\c T.\n\t * The leading columns of \\c Q and \\c Z form orthonormal bases of the\n\t * corresponding left and right eigenspaces (deflating subspaces).\n\t *\n\t * \\note\n\t *  The \\c i-th element of the input vector \\a selection must evaluate\n\t *  to \\c true if the \\c i-th eigenvalue is to be selected.\n\t * \\note\n\t *  As a side effect this function changes the original QZ decomposition\n\t *  (i.e., matrices \\c S, \\c T, \\c Q, and \\c Z, and vector \\c alpha and\n\t *  \\c beta).\n\t */\n\tpublic: template <typename VectorExprT>\n\t\tvoid reorder(vector_expression<VectorExprT> const& selection)\n\t{\n\t\t// precondition: size(selection) == size(alpha_) [ == size(beta_) ]\n\t\tBOOST_UBLAS_CHECK( size(selection) == size(alpha_), bad_size() );\n\n\t\tsize_type n = size(selection);\n\t\tvector< ::fortran_bool_t > eigvals_sel(n);\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (static_cast<bool>(selection()(i)))\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 0;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex<\n\t\t\t\t\tvalue_type\n\t\t\t\t>::value\n\t\t\t>::template reorder(S_, T_, detail::no_extra_qz_option, eigvals_sel, alpha_, beta_, true, Q_, true, Z_, column_major_tag());\n\t}\n\n\n\t/**\n\t * \\brief QZ decomposition with optional reordering.\n\t *\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tprivate: void decompose(qz_eigenvalues_selection selection)\n\t{\n\t\t//typedef typename type_traits<value_type>::real_type real_type;\n\n\t\tbool sort = false;\n\t\t::external_fp selctg = 0;\n\n\t\tselctg = detail::create_qz_eigvals_selector<value_type>(selection);\n\t\tif (selctg != 0)\n\t\t{\n\t\t\tsort = true;\n\t\t}\n\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template decompose(S_, T_, detail::both_qz_schurvectors, true, sort, selctg, Q_, Z_, alpha_, beta_, column_major_tag());\n\t}\n\n\n\t/// The Schur form of the input matrix \\f$A\\f$.\n\tprivate: S_matrix_type S_;\n\t/// The Schur form of the input matrix \\f$B\\f$.\n\tprivate: T_matrix_type T_;\n\t/// The orthogonal/unitary matrix such that \\f$QAZ=S\\f$ and \\f$QBZ=T\\f$.\n\tprivate: Q_matrix_type Q_;\n\t/// The orthogonal/unitary matrix such that \\f$QAZ=S\\f$ and \\f$QBZ=T\\f$.\n\tprivate: Z_matrix_type Z_;\n\t/// The numerator of the generalized Schur eigenvalues.\n\tprivate: alpha_vector_type alpha_; // == diag(S_)\n\t/// The denominator of the generalized Schur eigenvalues.\n\tprivate: beta_vector_type beta_;\n}; // qz_decomposition\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixExprT The type of the first matrix expression.\n * \\tparam BMatrixExprT The type of the second matrix expression.\n *\n * \\param A The first matrix expression.\n * \\param B The second matrix expression.\n * \\return An object containing information on the QZ decomposition of\n *  \\f$(A,B)\\f$ (\\see qz_decomposition).\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\a S\n * and \\a T, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n *   QSZ' &= A,\\\\\n *   QTZ' &= B.\n * \\f}\n * For complex matrices, S and T are triangular.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename AMatrixExprT, typename BMatrixExprT>\nBOOST_UBLAS_INLINE\nqz_decomposition<\n\ttypename promote_traits<\n\t\ttypename matrix_traits<AMatrixExprT>::value_type,\n\t\ttypename matrix_traits<BMatrixExprT>::value_type\n\t>::promote_type\n> qz_decompose(matrix_expression<AMatrixExprT> const& A, matrix_expression<BMatrixExprT> const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits<AMatrixExprT>::value_type,\n\t\t\ttypename matrix_traits<BMatrixExprT>::value_type\n\t\t>::promote_type value_type;\n\n\treturn qz_decomposition<value_type>(A, B, selection);\n}\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixT The type of the first input matrix.\n * \\tparam BMatrixT The type of the second input matrix.\n *\n * \\param A On entry, the first input matrix.\n *  On exit, the generalized Schur form of matrix \\a A.\n * \\param B On entry, the second input matrix.\n *  On exit, the generalized Schur form of matrix \\a B.\n * \\param Q An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n *  \\f$QBZ=T\\f$, where \\f$S\\f$ and \\f$T\\f$ denote the generalized Schur form\n *  of matrices \\a A and \\a B, respectively.\n * \\param Z An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n *  \\f$QBZ=T\\f$, where \\f$S\\f$ and \\f$T\\f$ denote the generalized Schur form\n *  of matrices \\a A and \\a B, respectively.\n * \\return No return value, but the function returns the computed QZ\n *  decomposition in the arguments \\a A, \\a B, \\a Q, and \\a Z.\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\f$S\\f$\n * and \\f$T\\f$, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n *   QAZ &= S,\\\\\n *   QBZ &= T.\n * \\f}\n * For complex matrices, S and T are triangular.\n * Matrix \\f$S\\f$ and \\f$T\\f$ are stored, at the exit of the function call, in\n * the arguments \\a A and \\a B, respectively.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename AMatrixT,\n\ttypename BMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT\n>\nBOOST_UBLAS_INLINE\nvoid qz_decompose_inplace(AMatrixT& A, BMatrixT& B, QMatrixT& Q, ZMatrixT& Z, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits<AMatrixT>::value_type,\n\t\t\ttypename matrix_traits<BMatrixT>::value_type\n\t\t>::promote_type value_type;\n\n\tqz_decomposition<value_type> qz(A, B, selection);\n\n\tA = qz.S();\n\tB = qz.T();\n\tQ = qz.Q();\n\tZ = qz.Z();\n}\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixExprT The type of the first matrix expression.\n * \\tparam BMatrixExprT The type of the second matrix expression.\n *\n * \\param A The first matrix expression.\n * \\param B The second matrix expression.\n * \\param S The generalized Schur form of matrix \\a A.\n * \\param T The generalized Schur form of matrix \\a B.\n * \\param Q An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n *  \\f$QBZ=T\\f$.\n * \\param Z An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n *  \\f$QBZ=T\\f$.\n * \\return No return value, but the function returns the computed QZ\n *  decomposition in the arguments \\a S, \\a T, \\a Q, and \\a Z.\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\a S\n * and \\a T, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n *   QAZ &= S,\\\\\n *   QBZ &= T.\n * \\f}\n * For complex matrices, S and T are triangular.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT\n>\nBOOST_UBLAS_INLINE\nvoid qz_decompose(matrix_expression<AMatrixExprT> const& A, matrix_expression<BMatrixExprT> const& B, SMatrixT& S, TMatrixT& T, QMatrixT& Q, ZMatrixT& Z, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits<AMatrixExprT>::value_type,\n\t\t\ttypename matrix_traits<BMatrixExprT>::value_type\n\t\t>::promote_type value_type;\n\n\tqz_decomposition<value_type> qz(A, B, selection);\n\n\tS = qz.S();\n\tT = qz.T();\n\tQ = qz.Q();\n\tZ = qz.Z();\n}\n\n\n/**\n * \\brief Reorder the QZ decomposition.\n *\n * \\tparam SMatrixT The type of the \\a S matrix.\n * \\tparam TMatrixT The type of the \\a T matrix.\n * \\tparam QMatrixT The type of the \\a Q matrix.\n * \\tparam ZMatrixT The type of the \\a Z matrix.\n * \\tparam SelVectorExprT The type of the \\a selection vector.\n * \\param S The Schur form of the matrix \\f$A\\f$ in QZ decomposition of the\n *  matrix pair \\f$(A,B)\\f$.\n * \\param T The Schur form of the matrix \\f$B\\f$ in the QZ decomposition of the\n *  matrix pair \\f$(A,B)\\f$.\n * \\param Q The orthogonal (or unitary) matrix obtained by the QZ decomposition\n *  of the matrix pair \\f$(A,B)\\f$.\n * \\param Z The orthogonal (or unitary) matrix obtained by the QZ decomposition\n *  of the matrix pair \\f$(A,B)\\f$.\n * \\param selection A vector where the i-th element specifies whether or not the\n *  i-th eigenvalue should be selected in order to appear in the leading (upper\n *  left) diagonal blocks of the quasi-triangular pair \\f$(SS,TS)\\f$,\n * \\return None, but the result of the reordering is stored in the parameters\n * \\a S, \\a T, \\a Q, and \\a Z.\n *\n * Reorders the generalized Schur decomposition\n * \\f{align}\n *  Q*A*Z &= S,\n *  Q*B*Z &= T.\n * \\f}\n * for a matrix pair \\f$(A,B)\\f$ so that a selected cluster of eigenvalues\n * appears in the leading diagonal blocks of the upper quasi-triangular matrix\n * \\a SS and the upper triangular \\a TS.\n * The leading columns of cumulative orthogonal transformation \\a QS and \\a ZS\n * form orthonormal bases of the corresponding left and right eigenspaces\n * (deflating subspaces).\n * After reordering, the following relations are still valid:\n * \\f{align}\n *  Q*A*Z &= S,\n *  Q*B*Z &= T.\n * \\f}\n */\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename SelVectorT\n>\nBOOST_UBLAS_INLINE\nvoid qz_reorder_inplace(SMatrixT& S, TMatrixT& T, QMatrixT& Q, ZMatrixT& Z, vector_expression<SelVectorT> const& selection)\n{\n\ttypedef typename matrix_traits<SMatrixT>::orientation_category orientation_category;\n\n\t// precondition: check that orientation category is the same for all the matrices\n\tBOOST_MPL_ASSERT(\n\t\t(::boost::mpl::and_<\n\t\t\t::boost::is_same<\n\t\t\t\torientation_category,\n\t\t\t\ttypename matrix_traits<TMatrixT>::orientation_category\n\t\t\t>,\n\t\t\t::boost::mpl::and_<\n\t\t\t\t::boost::is_same<\n\t\t\t\t\torientation_category,\n\t\t\t\t\ttypename matrix_traits<QMatrixT>::orientation_category\n\t\t\t\t>,\n\t\t\t\t::boost::is_same<\n\t\t\t\t\torientation_category,\n\t\t\t\t\ttypename matrix_traits<ZMatrixT>::orientation_category\n\t\t\t\t>\n\t\t\t>\n\t\t>)\n\t);\n\n\ttypedef typename promote_traits<\n\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\n\t// NOTE: alpha is always a complex vector while beta is complex only for the complex case\n\tvector< ::std::complex<real_type> > dummy_alpha(num_columns(S));\n\tvector<value_type> dummy_beta(num_columns(S));\n\n\tdetail::qz_decomposition_impl<\n\t\t\t::boost::is_complex<\n\t\t\t\ttypename promote_traits<\n\t\t\t\t\ttypename matrix_traits<SMatrixT>::value_type,\n\t\t\t\t\ttypename matrix_traits<TMatrixT>::value_type\n\t\t\t\t>::promote_type\n\t\t\t>::value\n\t\t>::template reorder(S, T, detail::no_extra_qz_option, selection, dummy_alpha, dummy_beta, true, Q, true, Z, orientation_category());\n}\n\n\n/**\n * \\brief Reorder the QZ decomposition.\n *\n * \\tparam SMatrixT The type of the \\a S matrix.\n * \\tparam TMatrixT The type of the \\a T matrix.\n * \\tparam QMatrixT The type of the \\a Q matrix.\n * \\tparam ZMatrixT The type of the \\a Z matrix.\n * \\tparam SelVectorExprT The type of the \\a selection vector.\n * \\param S The Schur form of the matrix \\f$A\\f$ in QZ decomposition of the\n *  matrix pair \\f$(A,B)\\f$.\n * \\param T The Schur form of the matrix \\f$B\\f$ in the QZ decomposition of the\n *  matrix pair \\f$(A,B)\\f$.\n * \\param Q The orthogonal (or unitary) matrix obtained by the QZ decomposition\n *  of the matrix pair \\f$(A,B)\\f$.\n * \\param Z The orthogonal (or unitary) matrix obtained by the QZ decomposition\n *  of the matrix pair \\f$(A,B)\\f$.\n * \\param selection A vector where the i-th element specifies whether or not the\n *  i-th eigenvalue should be selected in order to appear in the leading (upper\n *  left) diagonal blocks of the quasi-triangular pair \\f$(SS,TS)\\f$,\n * \\param SS The new matrix \\a S obtained after the reordering.\n * \\param TS The new matrix \\a T obtained after the reordering.\n * \\param QS The new matrix \\a Q obtained after the reordering.\n * \\param ZS The new matrix \\a Z obtained after the reordering.\n * \\return None, but the result of the reordering is stored in the output\n *  parameters \\a SS, \\a TS, \\a QS, and \\a ZS.\n *\n * Reorders the generalized Schur decomposition\n * \\f{align}\n *  Q*A*Z &= S,\n *  Q*B*Z &= T.\n * \\f}\n * for a matrix pair \\f$(A,B)\\f$ so that a selected cluster of eigenvalues\n * appears in the leading diagonal blocks of the upper quasi-triangular matrix\n * \\a SS and the upper triangular \\a TS.\n * The leading columns of cumulative orthogonal transformation \\a QS and \\a ZS\n * form orthonormal bases of the corresponding left and right eigenspaces\n * (deflating subspaces).\n * After reordering, the following relations are still valid:\n * \\f{align}\n *  QS*A*ZS &= SS,\n *  QS*B*ZS &= TS.\n * \\f}\n */\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename SelVectorExprT\n>\nBOOST_UBLAS_INLINE\nvoid qz_reorder(SMatrixT const& S, TMatrixT const& T, QMatrixT const& Q, ZMatrixT const& Z, vector_expression<SelVectorExprT> const& selection, SMatrixT& SS, TMatrixT& TS, QMatrixT& QS, ZMatrixT& ZS)\n{\n\tSS = S;\n\tTS = T;\n\tQS = Q;\n\tZS = Z;\n\n\tqz_reorder_inplace(SS, TS, QS, ZS, selection);\n}\n\n}}} // Namespace boost::numeric::ublas\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_QZ_HPP\n", "meta": {"hexsha": "a133fdd4bf68c764b05d0e71fefbed9f7ac0a138", "size": 67603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/qz.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/qz.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/qz.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": 31.1247697974, "max_line_length": 258, "alphanum_fraction": 0.6842595743, "num_tokens": 20859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.685728239408573}}
{"text": "/**\n * @file TestProblem02.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-06\n */\n\n#pragma once\n\n#include <limits>\n#include <iostream>\n#include <Eigen/Dense>\n\n#include <solver/interface/NlpDescription.hpp>\n\nnamespace nlp_test_problems\n{\n\n  class TestProblem02 : public solver::NlpDescription\n  {\n    public:\n\t  TestProblem02(){};\n      virtual ~TestProblem02(){};\n\n      // definition of problem size\n      void getNlpParameters(int& n_vars, int& n_cons)\n      {\n        n_vars = 2;\n        n_cons = 0;\n      }\n\n      // definition of problem box constraints\n      void getNlpBounds(int n_vars, int /*n_cons*/, double* x_l, double* x_u, double* /*g_l*/, double* /*g_u*/)\n      {\n    \t    for (int i=0; i<n_vars; i++)\n        {\n          x_l[i] = -2.;\n          x_u[i] =  2.;\n        }\n      }\n\n      // definition of starting point\n      void getStartingPoint(int /*n_vars*/, double* x)\n      {\n        x[0] =  0.0;\n        x[1] = -1.0;\n      }\n\n      // definition of objective function\n      double evaluateObjective(int /*n_vars*/, const double* x)\n      {\n        return 4.*pow(x[0],2.) - 2.1*pow(x[0],4.)+ 1./3.*pow(x[0],6.) + x[0]*x[1] - 4.*pow(x[1],2.) + 4.*pow(x[1],4.);\n      }\n\n      // definition of constraints function\n      void evaluateConstraintsVector(int /*n_vars*/, int /*n_cons*/, const double* /*x*/, double* /*constraints*/)\n      {\n      }\n  };\n}\n", "meta": {"hexsha": "44a879748a1a0b1fc75ead7863d85133c924e03c", "size": 1521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/tests/test_problems/TestProblem02.hpp", "max_stars_repo_name": "machines-in-motion/kino-dynamic-opt", "max_stars_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver/tests/test_problems/TestProblem02.hpp", "max_issues_repo_name": "machines-in-motion/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver/tests/test_problems/TestProblem02.hpp", "max_forks_repo_name": "machines-in-motion/kino-dynamic-opt", "max_forks_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 24.5322580645, "max_line_length": 118, "alphanum_fraction": 0.5726495726, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6857282373822352}}
{"text": "\n#include \"bresenham_supercover.h\"\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE (brezenham_supercover)\n\nBOOST_AUTO_TEST_CASE (one_point)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 5), math::vec<2, int>(1, 5));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (two_points_digonal_1)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 5), math::vec<2, int>(2, 6));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (two_points_digonal_2)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 5), math::vec<2, int>(2, 4));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\n\nBOOST_AUTO_TEST_CASE (two_points_digonal_3)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(2, 6), math::vec<2, int>(1, 5));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (two_points_digonal_4)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(2, 4), math::vec<2, int>(1, 5));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (three_points_digonal_1)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 5), math::vec<2, int>(3, 6));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (three_points_digonal_2)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 5), math::vec<2, int>(3, 4));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (three_points_digonal_3)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(3, 6), math::vec<2, int>(1, 5));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (three_points_digonal_4)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(3, 4), math::vec<2, int>(1, 5));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (many_points_1)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(1, 1), math::vec<2, int>(12, 9));\n\n\tmath::vec<2, int> position;\n\tbool flag;\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 1);\n\tBOOST_REQUIRE (position.y == 1);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 1);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 2);\n\tBOOST_REQUIRE (position.y == 2);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 2);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 3);\n\tBOOST_REQUIRE (position.y == 3);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 4);\n\tBOOST_REQUIRE (position.y == 3);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 4);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 5);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 6);\n\tBOOST_REQUIRE (position.y == 4);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 6);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 7);\n\tBOOST_REQUIRE (position.y == 5);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 7);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 8);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 9);\n\tBOOST_REQUIRE (position.y == 6);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 9);\n\tBOOST_REQUIRE (position.y == 7);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 10);\n\tBOOST_REQUIRE (position.y == 7);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 10);\n\tBOOST_REQUIRE (position.y == 8);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 11);\n\tBOOST_REQUIRE (position.y == 8);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 11);\n\tBOOST_REQUIRE (position.y == 9);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (position.x == 12);\n\tBOOST_REQUIRE (position.y == 9);\n\tBOOST_REQUIRE (flag == false);\n\n\tboost::tie(position, flag) = bs.get();\n\tBOOST_REQUIRE (flag == true);\n}\n\nBOOST_AUTO_TEST_CASE (many_points_2)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(4, 7), math::vec<2, int>(0, 0));\n\n\tmath::vec<2, int> position, prev_position;\n\tbool flag;\n\n\tdo\n\t{\n\t\tprev_position = position;\n\t\tboost::tie(position, flag) = bs.get();\n\t}\n\twhile (flag == false);\n}\n\nBOOST_AUTO_TEST_CASE (final_point_1)\n{\n\tmath::bresenham_supercover<> bs(math::vec<2, int>(2, 5), math::vec<2, int>(0, 0));\n\n\tmath::vec<2, int> position, prev_position;\n\tbool flag;\n\n\tdo\n\t{\n\t\tprev_position = position;\n\t\tboost::tie(position, flag) = bs.get();\n\t}\n\twhile (flag == false);\n\n\tBOOST_REQUIRE (prev_position.x == 0);\n\tBOOST_REQUIRE (prev_position.y == 0);\n}\n\nBOOST_AUTO_TEST_CASE (final_point_2)\n{\n\tfor (int i = 0; i < 100; ++i)\n\t{\n\t\tint x1 = rand();\n\t\tint x2 = rand();\n\t\tint y1 = rand();\n\t\tint y2 = rand();\n\n\t\tmath::bresenham_supercover<> bs(math::vec<2, int>(x1, y1), math::vec<2, int>(x2, y2));\n\n\t\tmath::vec<2, int> position, prev_position;\n\t\tbool flag;\n\n\t\tdo\n\t\t{\n\t\t\tprev_position = position;\n\t\t\tboost::tie(position, flag) = bs.get();\n\t\t}\n\t\twhile (flag == false);\n\n\t\tBOOST_REQUIRE (prev_position.x == x2);\n\t\tBOOST_REQUIRE (prev_position.y == y2);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\n", "meta": {"hexsha": "c3f1d5aede8ea88c1d77b0deab8fd787fa987a7b", "size": 11238, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_bresenham_supercover.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_bresenham_supercover.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_bresenham_supercover.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2539325843, "max_line_length": 88, "alphanum_fraction": 0.6607047517, "num_tokens": 3163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.68567148670029}}
{"text": "#include <armadillo>  // arma::datum/mat/vec\n#include <cmath>      // std::cos/sin\n#include <iomanip>    // std::setprecision/setw\n#include <iostream>   // std::cout/fixed\n\nusing namespace std;\n\nint main()\n{\n    arma::vec pos{1.0, 0.0};\n\n    auto& pi = arma::datum::pi;\n    double angle = pi / 2;\n    arma::mat rot = {\n        {cos(angle), -sin(angle)},\n        {sin(angle), cos(angle)}};\n\n    cout << \"Current position:\\n\" << pos;\n    cout << \"Rotating \" << angle * 180 / pi << \" deg\\n\";\n\n    arma::vec new_pos = rot * pos;\n    cout << \"New position:\\n\" << new_pos;\n\n    cout << fixed << setw(9) << setprecision(4);\n    new_pos.raw_print(cout, \"New position:\");\n\n    cout << fixed << setw(9) << setprecision(4);\n    new_pos.t().raw_print(cout, \"New position:\");\n}\n", "meta": {"hexsha": "235c2e24dcd3e8d21f5a37d5a50f1e7f9704acc6", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "23/armadillo/arma_test.cpp", "max_stars_repo_name": "qsyttkx/geek_time_cpp", "max_stars_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2020-02-11T01:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:12:48.000Z", "max_issues_repo_path": "23/armadillo/arma_test.cpp", "max_issues_repo_name": "qsyttkx/geek_time_cpp", "max_issues_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "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": "23/armadillo/arma_test.cpp", "max_forks_repo_name": "qsyttkx/geek_time_cpp", "max_forks_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2020-02-16T08:50:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:12:13.000Z", "avg_line_length": 25.5, "max_line_length": 56, "alphanum_fraction": 0.5647058824, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6856262794396248}}
{"text": "#include <common_robotics_utilities/conversions.hpp>\n\n#include <vector>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace conversions\n{\nEigen::Quaterniond QuaternionFromRPY(const double R,\n                                     const double P,\n                                     const double Y)\n{\n  const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n  const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n  const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n  const Eigen::Quaterniond quat(roll * pitch * yaw);\n  return quat;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Quaterniond QuaternionFromUrdfRPY(const double R,\n                                         const double P,\n                                         const double Y)\n{\n  const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n  const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n  const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n  const Eigen::Quaterniond quat(yaw * pitch * roll);\n  return quat;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromRotationMatrix(\n    const Eigen::Matrix3d& rot_matrix)\n{\n  // Use XYZ angles\n  const Eigen::Vector3d euler_angles = rot_matrix.eulerAngles(0, 1, 2);\n  return euler_angles;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat)\n{\n  return EulerAnglesFromRotationMatrix(quat.toRotationMatrix());\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans)\n{\n  return EulerAnglesFromRotationMatrix(trans.rotation());\n}\n\nEigen::Isometry3d TransformFromXYZRPY(const double x,\n                                      const double y,\n                                      const double z,\n                                      const double roll,\n                                      const double pitch,\n                                      const double yaw)\n{\n  const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z)\n                                      * QuaternionFromRPY(roll, pitch, yaw);\n  return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation,\n                                   const Eigen::Vector3d& rotation)\n{\n  const Eigen::Isometry3d transform = (Eigen::Translation3d)translation\n                                      * QuaternionFromRPY(rotation.x(),\n                                                          rotation.y(),\n                                                          rotation.z());\n  return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components)\n{\n  if (components.size() == 6)\n  {\n    return Eigen::Translation3d(components(0),\n                                components(1),\n                                components(2))\n           * QuaternionFromRPY(components(3),\n                               components(4),\n                               components(5));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"VectorXd source vector is not 6 elements in size\");\n  }\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfXYZRPY(const double x,\n                                          const double y,\n                                          const double z,\n                                          const double roll,\n                                          const double pitch,\n                                          const double yaw)\n{\n  const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z)\n                                      * QuaternionFromUrdfRPY(roll, pitch, yaw);\n  return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::Vector3d& translation,\n                                       const Eigen::Vector3d& rotation)\n{\n  const Eigen::Isometry3d transform = (Eigen::Translation3d)translation\n                                      * QuaternionFromUrdfRPY(rotation.x(),\n                                                              rotation.y(),\n                                                              rotation.z());\n  return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::VectorXd& components)\n{\n  if (components.size() == 6)\n  {\n    return Eigen::Translation3d(components(0),\n                                components(1),\n                                components(2))\n           * QuaternionFromUrdfRPY(components(3),\n                                   components(4),\n                                   components(5));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"VectorXd source vector is not 6 elements in size\");\n  }\n}\n\nEigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform)\n{\n  Eigen::VectorXd components = Eigen::VectorXd::Zero(6);\n  const Eigen::Vector3d translation = transform.translation();\n  const Eigen::Vector3d rotation\n      = EulerAnglesFromRotationMatrix(transform.rotation());\n  components << translation, rotation;\n  return components;\n}\n\nEigen::Vector3d StdVectorDoubleToEigenVector3d(\n    const std::vector<double>& vector)\n{\n  if (vector.size() == 3)\n  {\n    return Eigen::Vector3d(vector[0], vector[1], vector[2]);\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"Vector3d source vector is not 3 elements in size\");\n  }\n}\n\nEigen::VectorXd StdVectorDoubleToEigenVectorXd(\n    const std::vector<double>& vector)\n{\n  Eigen::VectorXd eigen_vector(vector.size());\n  for (size_t idx = 0; idx < vector.size(); idx++)\n  {\n    const double val = vector[idx];\n    eigen_vector((ssize_t)idx) = val;\n  }\n  return eigen_vector;\n}\n\nstd::vector<double> EigenVector3dToStdVectorDouble(\n    const Eigen::Vector3d& point)\n{\n  return std::vector<double>{point.x(), point.y(), point.z()};\n}\n\nstd::vector<double> EigenVectorXdToStdVectorDouble(\n    const Eigen::VectorXd& eigen_vector)\n{\n  std::vector<double> vector((size_t)eigen_vector.size());\n  for (size_t idx = 0; idx < (size_t)eigen_vector.size(); idx++)\n  {\n    const double val = eigen_vector[(ssize_t)idx];\n    vector[idx] = val;\n  }\n  return vector;\n}\n\n// Takes <x, y, z, w> as is the ROS custom!\nEigen::Quaterniond StdVectorDoubleToEigenQuaterniond(\n    const std::vector<double>& vector)\n{\n  if (vector.size() == 4)\n  {\n    return Eigen::Quaterniond(vector[3], vector[0], vector[1], vector[2]);\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"Quaterniond source vector is not 4 elements in size\");\n  }\n}\n\n// Returns <x, y, z, w> as is the ROS custom!\nstd::vector<double> EigenQuaterniondToStdVectorDouble(\n    const Eigen::Quaterniond& quat)\n{\n  return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n}\n\nEigen::Vector3d GeometryPointToEigenVector3d(\n    const geometry_msgs::Point& point)\n{\n  Eigen::Vector3d eigen_point(point.x, point.y, point.z);\n  return eigen_point;\n}\n\ngeometry_msgs::Point EigenVector3dToGeometryPoint(\n    const Eigen::Vector3d& point)\n{\n  geometry_msgs::Point geom_point;\n  geom_point.x = point.x();\n  geom_point.y = point.y();\n  geom_point.z = point.z();\n  return geom_point;\n}\n\nEigen::Vector4d GeometryPointToEigenVector4d(\n    const geometry_msgs::Point& point)\n{\n  Eigen::Vector4d eigen_point(point.x, point.y, point.z, 1.0);\n  return eigen_point;\n}\n\ngeometry_msgs::Point EigenVector4dToGeometryPoint(\n    const Eigen::Vector4d& point)\n{\n  geometry_msgs::Point geom_point;\n  geom_point.x = point(0);\n  geom_point.y = point(1);\n  geom_point.z = point(2);\n  return geom_point;\n}\n\ngeometry_msgs::PointStamped EigenVector3dToGeometryPointStamped(\n    const Eigen::Vector3d& point, const std::string& frame_id)\n{\n  geometry_msgs::PointStamped point_stamped;\n  point_stamped.header.frame_id = frame_id;\n  point_stamped.point = EigenVector3dToGeometryPoint(point);\n  return point_stamped;\n}\n\nEigen::Vector3d GeometryVector3ToEigenVector3d(\n    const geometry_msgs::Vector3& vector)\n{\n  Eigen::Vector3d eigen_vector(vector.x, vector.y, vector.z);\n  return eigen_vector;\n}\n\ngeometry_msgs::Vector3 EigenVector3dToGeometryVector3(\n    const Eigen::Vector3d& vector)\n{\n  geometry_msgs::Vector3 geom_vector;\n  geom_vector.x = vector.x();\n  geom_vector.y = vector.y();\n  geom_vector.z = vector.z();\n  return geom_vector;\n}\n\nEigen::Vector4d GeometryVector3ToEigenVector4d(\n    const geometry_msgs::Vector3& vector)\n{\n  Eigen::Vector4d eigen_vector(vector.x, vector.y, vector.z, 0.0);\n  return eigen_vector;\n}\n\ngeometry_msgs::Vector3 EigenVector4dToGeometryVector3(\n    const Eigen::Vector4d& vector)\n{\n  geometry_msgs::Vector3 geom_vector;\n  geom_vector.x = vector(0);\n  geom_vector.y = vector(1);\n  geom_vector.z = vector(2);\n  return geom_vector;\n}\n\nEigen::Quaterniond GeometryQuaternionToEigenQuaterniond(\n    const geometry_msgs::Quaternion& quat)\n{\n  Eigen::Quaterniond eigen_quaternion(quat.w, quat.x, quat.y, quat.z);\n  return eigen_quaternion;\n}\n\ngeometry_msgs::Quaternion EigenQuaterniondToGeometryQuaternion(\n    const Eigen::Quaterniond& quat)\n{\n  geometry_msgs::Quaternion geom_quaternion;\n  geom_quaternion.w = quat.w();\n  geom_quaternion.x = quat.x();\n  geom_quaternion.y = quat.y();\n  geom_quaternion.z = quat.z();\n  return geom_quaternion;\n}\n\nEigen::Isometry3d GeometryPoseToEigenIsometry3d(\n    const geometry_msgs::Pose& pose)\n{\n  const Eigen::Translation3d trans(pose.position.x,\n                                   pose.position.y,\n                                   pose.position.z);\n  const Eigen::Quaterniond quat(pose.orientation.w,\n                                pose.orientation.x,\n                                pose.orientation.y,\n                                pose.orientation.z);\n  const Eigen::Isometry3d eigen_pose = trans * quat;\n  return eigen_pose;\n}\n\ngeometry_msgs::Pose EigenIsometry3dToGeometryPose(\n    const Eigen::Isometry3d& transform)\n{\n  const Eigen::Vector3d trans = transform.translation();\n  const Eigen::Quaterniond quat(transform.rotation());\n  geometry_msgs::Pose geom_pose;\n  geom_pose.position.x = trans.x();\n  geom_pose.position.y = trans.y();\n  geom_pose.position.z = trans.z();\n  geom_pose.orientation.w = quat.w();\n  geom_pose.orientation.x = quat.x();\n  geom_pose.orientation.y = quat.y();\n  geom_pose.orientation.z = quat.z();\n  return geom_pose;\n}\n\ngeometry_msgs::PoseStamped EigenIsometry3dToGeometryPoseStamped(\n    const Eigen::Isometry3d& transform, const std::string& frame_id)\n{\n  geometry_msgs::PoseStamped pose_stamped;\n  pose_stamped.header.frame_id = frame_id;\n  pose_stamped.pose = EigenIsometry3dToGeometryPose(transform);\n  return pose_stamped;\n}\n\nEigen::Isometry3d GeometryTransformToEigenIsometry3d(\n    const geometry_msgs::Transform& transform)\n{\n  const Eigen::Translation3d trans(transform.translation.x,\n                                   transform.translation.y,\n                                   transform.translation.z);\n  const Eigen::Quaterniond quat(transform.rotation.w,\n                                transform.rotation.x,\n                                transform.rotation.y,\n                                transform.rotation.z);\n  const Eigen::Isometry3d eigen_transform = trans * quat;\n  return eigen_transform;\n}\n\ngeometry_msgs::Transform EigenIsometry3dToGeometryTransform(\n    const Eigen::Isometry3d& transform)\n{\n  const Eigen::Vector3d trans = transform.translation();\n  const Eigen::Quaterniond quat(transform.rotation());\n  geometry_msgs::Transform geom_transform;\n  geom_transform.translation.x = trans.x();\n  geom_transform.translation.y = trans.y();\n  geom_transform.translation.z = trans.z();\n  geom_transform.rotation.w = quat.w();\n  geom_transform.rotation.x = quat.x();\n  geom_transform.rotation.y = quat.y();\n  geom_transform.rotation.z = quat.z();\n  return geom_transform;\n}\n\ngeometry_msgs::TransformStamped EigenIsometry3dToGeometryTransformStamped(\n    const Eigen::Isometry3d& transform, const std::string& frame_id,\n    const std::string& child_frame_id)\n{\n  geometry_msgs::TransformStamped transform_stamped;\n  transform_stamped.header.frame_id = frame_id;\n  transform_stamped.child_frame_id = child_frame_id;\n  transform_stamped.transform = EigenIsometry3dToGeometryTransform(transform);\n  return transform_stamped;\n}\n\nEigen::Matrix3Xd VectorGeometryPointToEigenMatrix3Xd(\n    const std::vector<geometry_msgs::Point>& vector_geom)\n{\n  Eigen::Matrix3Xd eigen_matrix = Eigen::MatrixXd(3, vector_geom.size());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    eigen_matrix.block<3,1>(0, (ssize_t)idx)\n        = GeometryPointToEigenVector3d(vector_geom[idx]);\n  }\n  return eigen_matrix;\n}\n\nstd::vector<geometry_msgs::Point> EigenMatrix3XdToVectorGeometryPoint(\n    const Eigen::Matrix3Xd& eigen_matrix)\n{\n  std::vector<geometry_msgs::Point> vector_geom((size_t)eigen_matrix.cols());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    vector_geom[idx]\n        = EigenVector3dToGeometryPoint(\n            eigen_matrix.block<3,1>(0, (ssize_t)idx));\n  }\n  return vector_geom;\n}\n\nstd::vector<geometry_msgs::Point>\nVectorEigenVector3dToVectorGeometryPoint(\n    const common_robotics_utilities::math::VectorVector3d& vector_eigen)\n{\n  std::vector<geometry_msgs::Point> vector_geom(vector_eigen.size());\n  for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n  {\n    vector_geom[idx] = EigenVector3dToGeometryPoint(vector_eigen[idx]);\n  }\n  return vector_geom;\n}\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryPointToVectorEigenVector3d(\n    const std::vector<geometry_msgs::Point>& vector_geom)\n{\n  common_robotics_utilities::math::VectorVector3d vector_eigen(\n      vector_geom.size());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    vector_eigen[idx] = GeometryPointToEigenVector3d(vector_geom[idx]);\n  }\n  return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryVector3ToEigenVector3d(\n    const std::vector<geometry_msgs::Vector3>& vector_geom)\n{\n  common_robotics_utilities::math::VectorVector3d vector_eigen(\n      vector_geom.size());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    vector_eigen[idx] = GeometryVector3ToEigenVector3d(vector_geom[idx]);\n  }\n  return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n    const std::vector<geometry_msgs::Pose>& vector_geom)\n{\n  common_robotics_utilities::math::VectorIsometry3d vector_eigen(\n      vector_geom.size());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    vector_eigen[idx] = GeometryPoseToEigenIsometry3d(vector_geom[idx]);\n  }\n  return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n    const std::vector<geometry_msgs::Transform>& vector_geom)\n{\n  common_robotics_utilities::math::VectorIsometry3d vector_eigen(\n      vector_geom.size());\n  for (size_t idx = 0; idx < vector_geom.size(); idx++)\n  {\n    vector_eigen[idx] = GeometryTransformToEigenIsometry3d(vector_geom[idx]);\n  }\n  return vector_eigen;\n}\n\nstd::vector<geometry_msgs::Pose> VectorIsometry3dToVectorGeometryPose(\n    const common_robotics_utilities::math::VectorIsometry3d& vector_eigen)\n{\n  std::vector<geometry_msgs::Pose> vector_geom(vector_eigen.size());\n  for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n  {\n    vector_geom[idx] = EigenIsometry3dToGeometryPose(vector_eigen[idx]);\n  }\n  return vector_geom;\n}\n\nstd::vector<geometry_msgs::Transform> VectorIsometry3dToVectorGeometryTransform(\n    const common_robotics_utilities::math::VectorIsometry3d& vector_eigen)\n{\n  std::vector<geometry_msgs::Transform> vector_geom(vector_eigen.size());\n  for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n  {\n    vector_geom[idx] = EigenIsometry3dToGeometryTransform(vector_eigen[idx]);\n  }\n  return vector_geom;\n}\n}  // namespace conversions\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "6c9c1511bd4a85acc0d0e59a6f9b7ebae36a2f3e", "size": 15782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.500998004, "max_line_length": 80, "alphanum_fraction": 0.6658218223, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.685583235757676}}
{"text": "#include \"utils.hpp\"\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp>\n#include <cmath>\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\nstring RSAPrivateKeyFactorizer_cppfunc(string s, string d_, string e_){\n    Bint n(s);\n    Bint d(d_);\n    Bint e(e_);\n    Bint t = e*d-1;\n    Bint u = 0;\n    using engine = boost::random::independent_bits_engine<boost::mt19937, 16384, Bint>;\n    engine gen;\n    while(true){\n        Bint quotient = t/2;\n        Bint remainder = t%2;\n        if(remainder!=0){break;}\n        u += 1;\n        t = quotient;\n    }\n    bool found = false;\n    Bint c1, c2;\n    while(!found){\n        Bint i(\"1\");\n        Bint a = (gen()+1)%n;\n        while(i<=u and !found){\n            Bint c1_ = powm(Bint(\"2\"),i-1,n);\n            c1 = powm(a,c1_*t,n);\n            Bint c2_ = powm(Bint(\"2\"),i,n);\n            c2 = powm(a,c2_*t,n);\n            found = (c1!=1) and (c1!=-1%n) and (c2==1);\n            i+=1;\n        }\n    }\n    Bint retval =  gcd(c1-1, n);\n    return retval.str();\n    \n}\n", "meta": {"hexsha": "a04edbc690ef5faa3d8ef17361c6c925dd74f916", "size": 1065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RSAPrivateKeyFactorizer_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/RSAPrivateKeyFactorizer_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/RSAPrivateKeyFactorizer_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": 25.3571428571, "max_line_length": 87, "alphanum_fraction": 0.5305164319, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6855832346502889}}
{"text": "/*\n * warp_statistics.hpp\n *\n *  Created on: Nov 14, 2018\n *      Author: Gregory Kramida\n *   Copyright: 2018 Gregory Kramida\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#pragma once\n\n//libraries\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n//local\n#include \"typedefs.hpp\"\n\nnamespace math {\n\n/**\n * Locates the maximum L2 norm (length) of the vector in the given field.\n * @param[out] max_norm length of the longest vector\n * @param[out] coordinate the location of the longest vector\n * @param[in] vector_field the vector field to look at\n */\ntemplate<typename Scalar>\nvoid locate_max_norm(typename Scalar::Scalar& max_norm, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field);\n/**\n * Locates the maximum L2 norm (length) of the vector in the given field.\n * @overload\n */\ntemplate<typename Scalar>\nvoid locate_max_norm(typename Scalar::Scalar& max_norm, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& vector_field);\n/**\n * Locates the minimum L2 norm (length) of the vector in the given field.\n * @param[out] max_norm length of the longest vector\n * @param[out] coordinate the location of the longest vector\n * @param[in] vector_field the vector field to look at\n */\ntemplate<typename Scalar>\nvoid locate_min_norm(typename Scalar::Scalar& min_norm, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field);\n\n/**\n * Locates the minimum L2 norm (length) of the vector in the given field.\n * @overload\n */\ntemplate<typename Scalar>\nvoid locate_min_norm(typename Scalar::Scalar& min_norm, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& vector_field);\n/**\n * Locates the maximum in the given field.\n * @param[out] maximum the maximum coefficient\n * @param[out] coordinates coordinate of the maximum coefficient\n * @param[in] scalar_field the scalar field to look at\n */\ntemplate<typename Scalar>\nvoid locate_maximum(Scalar& maximum, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& scalar_field);\n/**\n * Locates the maximum in the given field.\n * @overload\n */\ntemplate<typename Scalar>\nvoid locate_maximum(Scalar& maximum, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& scalar_field);\n\ntemplate<typename Scalar>\ninline\nScalar maximum(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& scalar_field){\n\treturn static_cast<Eigen::Tensor<Scalar,0,Eigen::ColMajor> >(scalar_field.maximum())(0);\n}\n\ntemplate<typename Scalar>\ninline\nScalar maximum(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& scalar_field){\n\treturn scalar_field.maxCoeff();\n}\n\ntemplate<typename Scalar>\ninline\nScalar minimum(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& scalar_field){\n\treturn static_cast<Eigen::Tensor<Scalar,0,Eigen::ColMajor> >(scalar_field.minimum())(0);\n}\n\ntemplate<typename Scalar>\ninline\nScalar minimum(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& scalar_field){\n\treturn scalar_field.minCoeff();\n}\n\n\n\n//uses traversal function/functor combo, otherwise the same as locate_max_norm\nvoid locate_max_norm2(float& max_norm, math::Vector2i& coordinates, const math::MatrixXv2f& vector_field);\n\n/**\n * Locate the maximum L2 norm (length) of the vector in the given field.\n * @param[out] min_norm length of the shortest vector\n * @param[out] coordinate the location of the shortest vector\n * @param[in] vector_field the field to look at\n */\ntemplate<typename Scalar>\ntypename Scalar::Scalar max_norm(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field);\n/**\n * Locate the maximum L2 norm (length) of the vector in the given field.\n * @override\n */\ntemplate<typename Scalar>\ntypename Scalar::Scalar max_norm(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& vector_field);\n/**\n * Locate the minimum L2 norm (length) of the vector in the given field.\n * @param[out] min_norm length of the shortest vector\n * @param[out] coordinate the location of the shortest vector\n * @param[in] vector_field the field to look at\n */\ntemplate<typename Scalar>\ntypename Scalar::Scalar min_norm(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& vector_field);\n/**\n * Locate the minimum L2 norm (length) of the vector in the given field.\n * @override\n */\ntemplate<typename Scalar>\ntypename Scalar::Scalar min_norm(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& vector_field);\n\ntemplate<typename Scalar>\nScalar mean(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\nScalar mean(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\nScalar std(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n\ntemplate<typename Scalar>\nScalar std(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\nfloat ratio_of_vector_lengths_above_threshold(const math::MatrixXv2f& vector_field, float threshold);\nfloat mean_vector_length(const math::MatrixXv2f& vector_field);\nvoid mean_and_std_vector_length(float& mean, float& standard_deviation, const math::MatrixXv2f& vector_field);\n\n}\n", "meta": {"hexsha": "fe4cabd980a7afa4d12c4615389273126737e8bb", "size": 5836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/statistics.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/statistics.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/statistics.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 37.1719745223, "max_line_length": 125, "alphanum_fraction": 0.7553118574, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6854898506731701}}
{"text": "//\n// Created by Hamza El-Kebir on 4/18/21.\n//\n\n#ifndef LODESTAR_TRANSFERFUNCTION_HPP\n#define LODESTAR_TRANSFERFUNCTION_HPP\n\n#include \"SystemStateless.hpp\"\n#include \"StateSpace.hpp\"\n#include \"DiscreteStateSpace.hpp\"\n#include \"Lodestar/analysis/BilinearTransformation.hpp\"\n#include \"Lodestar/LodestarErrors.hpp\"\n\n#include <Eigen/Dense>\n\n#ifdef LS_USE_GINAC\n\n#include <ginac/ginac.h>\n\n#undef Mutable\n\n#endif\n\nnamespace ls {\n    namespace systems {\n        class TransferFunction : SystemStateless {\n        public:\n            /**\n             * @brief Default constructor.\n             */\n            TransferFunction() : num_(Eigen::MatrixXd::Ones(1, 1)),\n                                 den_(Eigen::MatrixXd::Ones(1, 1))\n            {}\n\n            /**\n             * @brief Copy constructor.\n             *\n             * @param other Transfer function to copy.\n             */\n            TransferFunction(const TransferFunction &other);\n\n            /**\n             * @brief Constructs a transfer function from a vector of numerator\n             * and denominator coefficients.\n             *\n             * @note Coefficients are in descending order (starting with the\n             * monomial with highest power).\n             *\n             * @param num Numerator coefficients.\n             * @param den Denominator coefficients.\n             */\n            TransferFunction(const Eigen::MatrixXd &num,\n                             const Eigen::MatrixXd &den) : num_(num), den_(den)\n            {}\n\n            /**\n             * @brief Gets numerator coefficients.\n             *\n             * @return Numerator coefficients.\n             */\n            Eigen::MatrixXd getNum() const;\n\n            /**\n             * @brief Sets numerator coefficients.\n             *\n             * @param num Numerator coefficients.\n             */\n            void setNum(const Eigen::MatrixXd &num);\n\n            /**\n             * Returns polynomial degree of the numerator.\n             *\n             * @return Numerator degree.\n             */\n            long getNumDegree() const;\n\n            /**\n             * @brief Gets denominator coefficients.\n             *\n             * @return Denominator coefficients.\n             */\n            Eigen::MatrixXd getDen() const;\n\n            /**\n             * @brief Set denominator coefficients.\n             *\n             * @param den Denominator coefficients.\n             */\n            void setDen(const Eigen::MatrixXd &den);\n\n            /**\n             * Returns polynomial degree of the denominator.\n             *\n             * @return denominator degree.\n             */\n            long getDenDegree() const;\n\n            /**\n             * @brief Normalizes transfer function in place.\n             */\n            void normalizeInPlace();\n\n            /**\n             * @brief Creates normalized transfer function.\n             *\n             * @return Normalized transfer function.\n             */\n            TransferFunction normalized() const;\n\n            /**\n             * @brief Converts transfer function to state space object.\n             *\n             * @return TState space object.\n             */\n            StateSpace<> toStateSpace() const;\n\n            /**\n             * @brief Converts transfer function to discrete-time state space\n             * object.\n             *\n             * @note This method uses the backward difference method by default.\n             *\n             * @see ls::analysis::BilinearTransformation::c2dBwdDiff\n             *\n             * @param dt Sampling period.\n             * @return Discrete-time state space system.\n             */\n            StateSpace<> toDiscreteStateSpace(double dt) const;\n\n            /**\n             * @brief Convert transfer function to discrete-time state space\n             * object.\n             *\n             * This method adds the option to set \\p alpha in the generalized\n             * bilinear transform.\n             *\n             * @param dt Sampling period.\n             * @param alpha Generalized bilinear transform parameter.\n             * @return Discrete-time state space system.\n             */\n            StateSpace<> toDiscreteStateSpace(double dt, double alpha) const;\n\n#ifdef LS_USE_GINAC\n\n            /**\n             * @brief Constructs a transfer function from the given symbolic\n             * expression.\n             *\n             * @param tf Transfer function expression.\n             * @param symbol Symbol used for the independent variable.\n             */\n            TransferFunction(const GiNaC::ex &tf, const GiNaC::ex &symbol);\n\n            /**\n             * @brief Generates a symbolic expression of the numerator\n             * polynomial.\n             *\n             * @param symbol Symbol to use for the independent variable.\n             *\n             * @return GiNaC expression of the numerator polynomial.\n             */\n            GiNaC::ex getNumExpression(const GiNaC::ex &symbol) const;\n\n            /**\n             * @brief Generates a symbolic expression of the denominator\n             * polynomial.\n             *\n             * @param symbol Symbol to use for the independent variable.\n             *\n             * @return GiNaC expression of the denominator polynomial.\n             */\n            GiNaC::ex getDenExpression(const GiNaC::ex &symbol) const;\n\n            /**\n             * @brief Generates a symbolic expression of the transfer function.\n             *\n             * @param symbol Symbol to use for the independent variable.\n             * @return GiNaC expression of the transfer function.\n             */\n            GiNaC::ex getExpression(const GiNaC::ex &symbol) const;\n\n            /**\n             * @brief Copies transfer function coefficients from the given\n             * symbolic expression.\n             *\n             * @param tf Transfer function expression.\n             * @param symbol Symbol used for the independent variable.\n             */\n            void\n            copyFromExpression(const GiNaC::ex &tf, const GiNaC::ex &symbol);\n\n#endif\n\n        private:\n            Eigen::MatrixXd num_, /// Numerator coefficients.\n            den_; /// Denominator coefficients.\n        };\n    }\n}\n\n#endif //LODESTAR_TRANSFERFUNCTION_HPP\n", "meta": {"hexsha": "859391c41e7b79e136660450bab962d9d6ea1e2c", "size": 6279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/systems/TransferFunction.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/systems/TransferFunction.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/systems/TransferFunction.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": 31.0841584158, "max_line_length": 80, "alphanum_fraction": 0.5188724319, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6854898351839815}}
{"text": "//\n// Multivariate Guassian Class.\n// Original from Humphrey Hu \n// (https://github.com/Humhu/argus_utils/blob/devel/include/argus_utils/random/MultivariateGaussian.hpp)\n// Adapted by Arun Venkatraman\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n\n#include <cassert>\n#include <random>\n\nnamespace math\n{\n\nclass MultivariateGaussian \n{\npublic:\n\n\t// Seeds the engine using a true random number. Sets mean_ to zero\n\t// and covariance to identity. \n\tMultivariateGaussian(const int dim);\n\n\t// Seeds the engine using the specified seed. Sets mean_ to zero\n\t// and _covariance to identity.\n\tMultivariateGaussian(const int dim, const int seed);\n\t\n\t// Sets the mean to mu and covariance to sigma.\n\tMultivariateGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma);\n    \n\t// Sets the mean to mu and covariance to sigma. Seeds the engine using a specified seed. \n\tMultivariateGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma, const int seed);\n\n\tMultivariateGaussian(const MultivariateGaussian& other);\n\tMultivariateGaussian& operator=(const MultivariateGaussian& other);\n    \n    void set_mean(const Eigen::VectorXd& mu);\n    void set_covariance(const Eigen::MatrixXd& sigma);\n\tvoid set_information(const Eigen::MatrixXd& inv_sigma);\n\n\tunsigned int get_dimension() const { return mean_.size(); }\n\tconst Eigen::VectorXd& mean() const { return mean_; }\n\tconst Eigen::MatrixXd covariance() const { return llt_.reconstructedMatrix(); }\n\tconst Eigen::MatrixXd cholesky() const { return llt_.matrixL(); }\n\t\n\t// Generate a sample truncated at a specified number of standard deviations.\n\tEigen::VectorXd sample(double max_var = 3.0);\n\n\t// Evaluate the multivariate normal PDF for the specified sample.\n    double evaluate_probability(const Eigen::VectorXd& x) const;\n    \nprotected:\n\t\n    std::mt19937 gen_;\n\tstd::normal_distribution<double> distribution_;\n\n    // Mean of the distribution.\n\tEigen::VectorXd mean_;\n    // Store covariance as its cholesky decomposition.\n\tEigen::LLT<Eigen::MatrixXd> llt_;\n\n    // Normalization constant;\n\tdouble z_; \n\n\tvoid initialize_cov(const Eigen::MatrixXd& cov);\n};\n\n}\n", "meta": {"hexsha": "4a24da8f3cb2edbf1a9b8e53dca7142075c3ea47", "size": 2136, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/multivariate_gaussian.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/multivariate_gaussian.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/multivariate_gaussian.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 29.6666666667, "max_line_length": 104, "alphanum_fraction": 0.7457865169, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6854180576338373}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#define BOOST_TEST_MODULE polynomial_arithmetic_test\n\n#include <vector>\n#include <cstdint>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n\n#include <nil/crypto3/math/polynomial/basic_operations.hpp>\n#include <nil/crypto3/math/polynomial/xgcd.hpp>\n\nusing namespace nil::crypto3::algebra;\nusing namespace nil::crypto3::math;\n\ntypedef fields::bls12<381> FieldType;\n\nBOOST_AUTO_TEST_SUITE(polynomial_addition_test_suite)\n\nBOOST_AUTO_TEST_CASE(polynomial_addition_equal) {\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7, 1, 5, 8};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_addition(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {10, 6, 15, 39, 13, 8, 12, 10};\n\n    for (std::size_t i = 0; i < c.size(); ++i) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_addition_long_a) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_addition(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {10, 6, 15, 39, 13, 7, 7, 2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_addition_long_b) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7, 1, 5, 8};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_addition(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {10, 6, 15, 39, 13, 1, 5, 8};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_addition_zero_a) {\n\n    std::vector<typename FieldType::value_type> a = {0, 0, 0};\n    std::vector<typename FieldType::value_type> b = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_addition(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {1, 3, 4, 25, 6, 7, 7, 2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_addition_zero_b) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {0, 0, 0};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_addition(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {1, 3, 4, 25, 6, 7, 7, 2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(polynomial_subtraction_test_suite)\n\nBOOST_AUTO_TEST_CASE(polynomial_subtraction_equal) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7, 1, 5, 8};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_subtraction(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {-8, 0, -7, 11, -1, 6, 2, -6};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_subtraction_long_a) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_subtraction(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {-8, 0, -7, 11, -1, 7, 7, 2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_subtraction_long_b) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6};\n    std::vector<typename FieldType::value_type> b = {9, 3, 11, 14, 7, 1, 5, 8};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_subtraction(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {-8, 0, -7, 11, -1, -1, -5, -8};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_subtraction_zero_a) {\n\n    std::vector<typename FieldType::value_type> a = {0, 0, 0};\n    std::vector<typename FieldType::value_type> b = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_subtraction(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {-1, -3, -4, -25, -6, -7, -7, -2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_subtraction_zero_b) {\n\n    std::vector<typename FieldType::value_type> a = {1, 3, 4, 25, 6, 7, 7, 2};\n    std::vector<typename FieldType::value_type> b = {0, 0, 0};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_subtraction(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {1, 3, 4, 25, 6, 7, 7, 2};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE(polynomial_multiplication_test_suite)\n\nBOOST_AUTO_TEST_CASE(polynomial_multiplication_long_a) {\n\n    std::vector<typename FieldType::value_type> a = {5, 0, 0, 13, 0, 1};\n    std::vector<typename FieldType::value_type> b = {13, 0, 1};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_multiplication<FieldType>(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {65, 0, 5, 169, 0, 26, 0, 1};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_multiplication_long_b) {\n\n    std::vector<typename FieldType::value_type> a = {13, 0, 1};\n    std::vector<typename FieldType::value_type> b = {5, 0, 0, 13, 0, 1};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_multiplication<FieldType>(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {65, 0, 5, 169, 0, 26, 0, 1};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_multiplication_zero_a) {\n\n    std::vector<typename FieldType::value_type> a = {0};\n    std::vector<typename FieldType::value_type> b = {5, 0, 0, 13, 0, 1};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_multiplication<FieldType>(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {0};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(polynomial_multiplication_zero_b) {\n\n    std::vector<typename FieldType::value_type> a = {5, 0, 0, 13, 0, 1};\n    std::vector<typename FieldType::value_type> b = {0};\n    std::vector<typename FieldType::value_type> c(1, FieldType::value_type::zero());\n\n    _polynomial_multiplication<FieldType>(c, a, b);\n\n    std::vector<typename FieldType::value_type> c_ans = {0};\n\n    for (std::size_t i = 0; i < c.size(); i++) {\n        BOOST_CHECK_EQUAL(c_ans[i].data, c[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_CASE(polynomial_division) {\n\n    std::vector<typename FieldType::value_type> a = {5, 0, 0, 13, 0, 1};\n    std::vector<typename FieldType::value_type> b = {13, 0, 1};\n\n    std::vector<typename FieldType::value_type> Q(1, FieldType::value_type::zero());\n    std::vector<typename FieldType::value_type> R(1, FieldType::value_type::zero());\n\n    _polynomial_division<FieldType>(Q, R, a, b);\n\n    std::vector<typename FieldType::value_type> Q_ans = {0, 0, 0, 1};\n    std::vector<typename FieldType::value_type> R_ans = {5};\n\n    for (std::size_t i = 0; i < Q.size(); i++) {\n        BOOST_CHECK_EQUAL(Q_ans[i].data, Q[i].data);\n    }\n    for (std::size_t i = 0; i < R.size(); i++) {\n        BOOST_CHECK_EQUAL(R_ans[i].data, R[i].data);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(extended_gcd) {\n\n    std::vector<typename FieldType::value_type> a = {0, 0, 0, 0, 1};\n    std::vector<typename FieldType::value_type> b = {1, -6, 11, -6};\n\n    std::vector<typename FieldType::value_type> pg(1, FieldType::value_type::zero());\n    std::vector<typename FieldType::value_type> pu(1, FieldType::value_type::zero());\n    std::vector<typename FieldType::value_type> pv(1, FieldType::value_type::zero());\n\n    extended_euclidean<FieldType>(a, b, pg, pu, pv);\n\n    std::vector<typename FieldType::value_type> pv_ans = {1, 6, 25, 90};\n\n    for (std::size_t i = 0; i < pv.size(); i++) {\n        BOOST_CHECK_EQUAL(pv_ans[i].data, pv[i].data);\n    }\n}\n", "meta": {"hexsha": "dcc1ea9a3adcbdde397f55cee28553fa979ee5b2", "size": 10871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/polynomial_arithmetic.cpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "test/polynomial_arithmetic.cpp", "max_issues_repo_name": "tonlabs/crypto3-math", "max_issues_repo_head_hexsha": "5f40a52fd9cb9b5733a6cafb05a5b4931bd26e32", "max_issues_repo_licenses": ["MIT"], "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/polynomial_arithmetic.cpp", "max_forks_repo_name": "tonlabs/crypto3-math", "max_forks_repo_head_hexsha": "5f40a52fd9cb9b5733a6cafb05a5b4931bd26e32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 35.7598684211, "max_line_length": 90, "alphanum_fraction": 0.6526538497, "num_tokens": 3343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6853406084793688}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// modified version of Normalization.hpp code\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass RobustScaling\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n\n  void init(double low, double high, RealMatrixView in)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    const double epsilon = std::numeric_limits<double>::epsilon();\n    mLow = low;\n    mHigh = high;\n    ArrayXXd input = asEigen<Array>(in);\n    mDataLow.resize(input.cols());\n    mDataHigh.resize(input.cols());\n    mMedian.resize(input.cols());\n    mRange.resize(input.cols());\n    index length = input.rows();\n    for (index i = 0; i < input.cols(); i++)\n    {\n      ArrayXd sorted = input.col(i);\n      std::sort(sorted.data(), sorted.data() + length);\n      mMedian(i) = sorted(lrint(0.5 * (length - 1)));\n      mDataLow(i) = sorted(lrint((mLow / 100.0) * (length - 1)));\n      mDataHigh(i) = sorted(lrint((mHigh / 100.0) * (length - 1)));\n    }\n    mRange = mDataHigh - mDataLow;\n    mRange = mRange.max(epsilon);\n    mInitialized = true;\n  }\n\n  void init(double low, double high, RealVectorView dataLow,\n            RealVectorView dataHigh, RealVectorView median,\n            RealVectorView range)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    const double epsilon = std::numeric_limits<double>::epsilon();\n    mLow = low;\n    mHigh = high;\n    mDataLow = asEigen<Array>(dataLow);\n    mDataHigh = asEigen<Array>(dataHigh);\n    mMedian = asEigen<Array>(median);\n    mRange = asEigen<Array>(range);\n    mRange =\n        mRange.max(epsilon); // in case it is imported from the outside world\n    mInitialized = true;\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out,\n                    bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXd input = asEigen<Array>(in);\n    ArrayXd result;\n    if (!inverse) { result = (input - mMedian) / mRange; }\n    else\n    {\n      result = (input * mRange) + mMedian;\n    }\n    out = asFluid(result);\n  }\n\n  void process(const RealMatrixView in, RealMatrixView out,\n               bool inverse = false) const\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    ArrayXXd input = asEigen<Array>(in);\n    ArrayXXd result;\n    if (!inverse)\n    {\n      result = (input.rowwise() - mMedian.transpose());\n      result = result.rowwise() / mRange.transpose();\n    }\n    else\n    {\n      result = (input.rowwise() * mRange.transpose());\n      result = (result.rowwise() + mMedian.transpose());\n    }\n    out = asFluid(result);\n  }\n\n  void setLow(double low) { mLow = low; }\n  void setHigh(double high) { mHigh = high; }\n  bool initialized() const { return mInitialized; }\n\n  double getLow() const { return mLow; }\n  double getHigh() const { return mHigh; }\n\n  void getDataLow(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mDataLow);\n  }\n\n  void getDataHigh(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mDataHigh);\n  }\n\n  void getMedian(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mMedian);\n  }\n\n  void getRange(RealVectorView out) const\n  {\n    using namespace _impl;\n    out = asFluid(mRange);\n  }\n\n  index dims() const { return mMedian.size(); }\n  index size() const { return 1; }\n\n  void clear()\n  {\n    mLow = 0;\n    mHigh = 1.0;\n    mMedian.setZero();\n    mRange.setZero();\n    mRange.setZero();\n    mInitialized = false;\n  }\n\n  double  mLow{0.0};\n  double  mHigh{1.0};\n  ArrayXd mDataHigh;\n  ArrayXd mDataLow;\n  ArrayXd mMedian;\n  ArrayXd mRange;\n  bool    mInitialized{false};\n};\n}; // namespace algorithm\n}; // namespace fluid\n", "meta": {"hexsha": "3de029baef15e8801cea1a0e184536ad01228f74", "size": 4212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/RobustScaling.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/RobustScaling.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/RobustScaling.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": 26.0, "max_line_length": 77, "alphanum_fraction": 0.6495726496, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.685340604913568}}
{"text": "#include <vector>\n#include <chrono>\n#include <Eigen/Dense>\n\n#include \"homography/compute_homography_model.hpp\"\n#include \"homography/compute_homography_error.hpp\"\n#include \"ransac.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid random_measurements(Matrix3d& H, vector<Point2f>& src, vector<Point2f>& dst, int n) {\n  src.clear();\n  dst.clear();\n  H = Matrix3d::Random();\n  H /= H(2,2);\n  VectorXd x = 1000*VectorXd::Random(n);\n  VectorXd y = 1000*VectorXd::Random(n);\n  for(int i = 0; i < n; i++) {\n    Vector3d p(x(i), y(i), 1);\n    Vector3d pp = H*p+Vector3d(1.*rand()/RAND_MAX, 1.*rand()/RAND_MAX, 0);\n    src.emplace_back(p.x()/p.z(), p.y()/p.z());\n    dst.emplace_back(pp.x()/pp.z(), pp.y()/pp.z());\n  }\n}\n\nint main() {\n  ComputeHomographyModel chm;\n  ComputeHomographyError che;\n  vector<HomographyMeasurement> measurements;\n\n  measurements.emplace_back(Point2f(0,0), Point2f(1,1));\n  measurements.emplace_back(Point2f(1,1), Point2f(2,2));\n  measurements.emplace_back(Point2f(2,1), Point2f(3,4));\n  measurements.emplace_back(Point2f(4,3), Point2f(1,5));\n\n  auto start = chrono::high_resolution_clock::now();\n  HomographyModel hm = chm(measurements);\n  auto finish = chrono::high_resolution_clock::now();\n\n  // cout << che(hm, measurements[0]) << endl;\n\n  cout << \"Simple homography calculation\\n\";\n  cout << \"Both matrices should be equal\\n\";\n  cout << \"Ours: \" << chrono::duration<double>(finish-start).count() << \" s\" << endl;\n  hm.print();\n\n  vector<Point2f> src, dst;\n  src.emplace_back(0,0);\n  src.emplace_back(1,1);\n  src.emplace_back(2,1);\n  src.emplace_back(4,3);\n  dst.emplace_back(1,1);\n  dst.emplace_back(2,2);\n  dst.emplace_back(3,4);\n  dst.emplace_back(1,5);\n\n  start = chrono::high_resolution_clock::now();\n  Mat H = findHomography(src, dst);\n  finish = chrono::high_resolution_clock::now();\n  cout << \"OpenCV's: \" << chrono::duration<double>(finish-start).count() << \" s\" << endl;\n  cout << H << endl;\n\n  Matrix3d real_H;\n  double opencv = 0, our = 0;\n  for(int i = 0; i < 1000; i++) {\n    random_measurements(real_H, src, dst, 10000);\n    start = chrono::high_resolution_clock::now();\n    H = findHomography(src, dst, CV_RANSAC);\n    finish = chrono::high_resolution_clock::now();\n    opencv += chrono::duration<double>(finish-start).count();\n    // cout << \"Real H:\\n\" << real_H << endl;\n    // cout << \"OpenCV's H: \" << chrono::duration<double>(finish - start).count()\n        //  << \" s\" << endl;\n    // cout << H << endl;\n\n    measurements.clear();\n    for (size_t i = 0; i < src.size(); i++) {\n      measurements.emplace_back(src[i], dst[i]);\n    }\n\n    start = chrono::high_resolution_clock::now();\n    auto my_H =\n        ransac<HomographyModel, HomographyMeasurement, ComputeHomographyModel,\n               ComputeHomographyError, 4>(measurements);\n    finish = chrono::high_resolution_clock::now();\n    our += chrono::duration<double>(finish-start).count();\n\n    // cout << \"Our H: \" << chrono::duration<double>(finish - start).count()\n        //  << \" s\" << endl;\n    // my_H.print();\n  }\n  cout << \"OpenCV's: \" << opencv << \" s\" << endl;\n  cout << \"Ours: \" << our << \" s\" << endl;\n\n  return EXIT_SUCCESS;\n}", "meta": {"hexsha": "d4efbc87436083e825d65335d3322630825e01da", "size": 3145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test.cpp", "max_stars_repo_name": "matheuscarius/project-inf573", "max_stars_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_stars_repo_licenses": ["MIT"], "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/test.cpp", "max_issues_repo_name": "matheuscarius/project-inf573", "max_issues_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_issues_repo_licenses": ["MIT"], "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/test.cpp", "max_forks_repo_name": "matheuscarius/project-inf573", "max_forks_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_forks_repo_licenses": ["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.4226804124, "max_line_length": 90, "alphanum_fraction": 0.6359300477, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6853139073661535}}
{"text": "// Copyright Paul A. Bristow 2016\n// Copyright John Z. Maddock 2016\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/*! brief Example of using Lambert W function to compute current through a diode connected transistor with preset series resistance.\n  \\details T. C. Banwell and A. Jayakumar,\n  Exact analytical solution of current flow through diode with series resistance,\n  Electron Letters, 36(4):291-2 (2000)\n  DOI:  doi.org/10.1049/el:20000301 \n\n  The current through a diode connected NPN bipolar junction transistor (BJT) \n  type 2N2222 (See https://en.wikipedia.org/wiki/2N2222 and \n  https://www.fairchildsemi.com/datasheets/PN/PN2222.pdf Datasheet)\n  was measured, for a voltage between 0.3 to 1 volt, see Fig 2 for a log plot,\n  showing a knee visible at about 0.6 V.\n\n  The transistor parameter isat was estimated to be 25 fA and the ideality factor = 1.0.\n  The intrinsic emitter resistance re was estimated from the rsat = 0 data to be 0.3 ohm.\n\n  The solid curves in Figure 2 are calculated using equation 5 with rsat included with re.\n\n  http://www3.imperial.ac.uk/pls/portallive/docs/1/7292572.PDF\n*/\n\n#include <boost/math/special_functions/lambert_w.hpp>\nusing boost::math::lambert_w0;\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n#include <exception>\n#include <stdexcept>\n#include <string>\n#include <array>\n#include <vector>\n\n/*!\nCompute thermal voltage as a function of temperature,\nabout 25 mV at room temperature.\nhttps://en.wikipedia.org/wiki/Boltzmann_constant#Role_in_semiconductor_physics:_the_thermal_voltage\n\n\\param temperature Temperature (degrees centigrade).\n*/\nconst double v_thermal(double temperature)\n{\n  constexpr const double boltzmann_k = 1.38e-23; // joules/kelvin.\n  const double charge_q = 1.6021766208e-19; // Charge of an electron (columb).\n  double temp =+ 273; // Degrees C to K.\n  return boltzmann_k * temp / charge_q;\n} // v_thermal\n\n/*!\nBanwell & Jayakumar, equation 2\n*/\ndouble i(double isat, double vd, double vt, double nu)\n{\n  double i = isat * (exp(vd / (nu * vt)) - 1);\n  return i;\n} // \n\n/*!\n\nBanwell & Jayakumar, Equation 4.\ni current flow = isat\nv voltage source.\nisat reverse saturation current in equation 4.\n(might implement equation 4 instead of simpler equation 5?).\nvd voltage drop = v - i* rs  (equation 1).\nvt  thermal voltage, 0.0257025 = 25 mV.\nnu junction ideality factor (default = unity), also known as the emission coefficient.\nre intrinsic emitter resistance, estimated to be 0.3 ohm from low current.\nrsat reverse saturation current\n\n\\param v Voltage V to compute current I(V).\n\\param vt Thermal voltage, for example 0.0257025 = 25 mV, computed from boltzmann_k * temp / charge_q; \n\\param rsat Resistance in series with the diode.\n\\param re Instrinsic emitter resistance (estimated to be 0.3 ohm from the Rs = 0 data)\n\\param isat Reverse saturation current (See equation 2).\n\\param nu Ideality factor (default = unity).\n\n\\returns I amp as function of V volt.\n\n*/\ndouble iv(double v, double vt, double rsat, double re, double isat, double nu = 1.)\n{ \n  // V thermal 0.0257025 = 25 mV\n  // was double i = (nu * vt/r) * lambert_w((i0 * r) / (nu * vt)); equ 5.\n\n  rsat = rsat + re; \n  double i = nu * vt / rsat;\n  std::cout << \"nu * vt / rsat = \" << i << std::endl; // 0.000103223\n\n  double x = isat * rsat / (nu * vt);\n  std::cout << \"isat * rsat / (nu * vt) = \" << x << std::endl;\n\n  double eterm = (v + isat * rsat) / (nu * vt);\n  std::cout << \"(v + isat * rsat) / (nu * vt) = \" << eterm << std::endl;\n\n  double e = exp(eterm);\n  std::cout << \"exp(eterm) = \" << e << std::endl;\n\n  double w0 = lambert_w0(x * e);\n  std::cout << \"w0 = \" << w0 << std::endl;\n  return i * w0 - isat;\n\n} // double iv\n\nstd::array<double, 5> rss = {0., 2.18, 10., 51., 249};  // series resistance (ohm).\nstd::array<double, 8> vds = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 };  // Diode voltage.\n\nint main()\n{\n  try\n  {\n    std::cout << \"Lambert W diode current example.\" << std::endl;\n\n    //[lambert_w_diode_example_1\n    double x = 0.01;\n    //std::cout << \"Lambert W (\" << x << \") = \" << lambert_w(x) << std::endl; // 0.00990147\n\n    double nu = 1.0;                  // Assumed ideal.\n    double vt = v_thermal(25);        // v thermal, Shockley equation, expect about 25 mV at room temperature.\n    double boltzmann_k = 1.38e-23;    // joules/kelvin\n    double temp = 273 + 25;\n    double charge_q = 1.6e-19;        // column\n    vt = boltzmann_k * temp / charge_q;\n    std::cout << \"V thermal \" \n       << vt << std::endl;            // V thermal 0.0257025 = 25 mV\n    double rsat = 0.;\n    double isat = 25.e-15;            //  25 fA;\n    std::cout << \"Isat = \" << isat << std::endl;\n\n    double re = 0.3;  // Estimated from slope of straight section of graph (equation 6).\n\n    double v = 0.9;\n    double icalc = iv(v, vt, 249., re, isat);\n\n    std::cout << \"voltage = \" << v << \", current = \" << icalc << \", \" << log(icalc) << std::endl; // voltage = 0.9, current = 0.00108485, -6.82631\n //] [/lambert_w_diode_example_1]\n  }\n  catch (std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}  // int main()\n\n/*\n   Output:\n//[lambert_w_output_1\n   Lambert W diode current example.\n   V thermal 0.0257025\n   Isat = 2.5e-14\n   nu * vt / rsat = 0.000103099\n   isat * rsat / (nu * vt) = 2.42486e-10\n   (v + isat * rsat) / (nu * vt) = 35.016\n   exp(eterm) = 1.61167e+15\n   w0 = 10.5225\n   voltage = 0.9, current = 0.00108485, -6.82631\n\n//] [/lambert_w_output_1]\n*/\n\n", "meta": {"hexsha": "cad03b1c6a9010c4f1b70322e5c40a877a5fd494", "size": 5554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_diode.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/lambert_w_diode.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/lambert_w_diode.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": 33.4578313253, "max_line_length": 146, "alphanum_fraction": 0.650882247, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6852731783195742}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix2f m = Matrix2f::Random();\nm = (m + m.adjoint()).eval();\nJacobiRotation<float> J;\nJ.makeJacobi(m, 0, 1);\ncout << \"Here is the matrix m:\" << endl << m << endl;\nm.applyOnTheLeft(0, 1, J.adjoint());\nm.applyOnTheRight(0, 1, J);\ncout << \"Here is the matrix J' * m * J:\" << endl << m << endl;\n  return 0;\n}\n", "meta": {"hexsha": "9c15c8e1e2dd099918408fac3cff580ec5312348", "size": 512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 20.48, "max_line_length": 62, "alphanum_fraction": 0.654296875, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6852185865642837}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Paul Bristow 2015.\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\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//! \\file\r\n//!\\brief Tests round-trip for fixed_point negatable with 5.2 binary digits.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_round_trip_digits02_005m2\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  // Define a binary fixed-point type with resolution 5 range -2\r\n  typedef boost::fixed_point::negatable<5, -2> fixed_point_type;\r\n\r\n  bool round_trip(const fixed_point_type& x);\r\n\r\n  // Here we need to invert Kahan's formula to ensure that all of\r\n  // the binary fractional digits can be printed in decimal form.\r\n  // In this case, we need to print two decimal digits10,\r\n  // even tough we are only have two binary fractional digits2.\r\n\r\n  // Begin with\r\n  //   digits2 = 8 (i.e. what is required for two decimal digits10)\r\n  // This gives\r\n  //  digits10 = [(8 - 1) * 301] / 1000\r\n  //  digits10 = 2107 / 1000 = 2\r\n\r\n  // In this case, we simply hard-code the value of 2\r\n  // for the number of decimal digits in the fixed-point field.\r\n\r\n  // For an additional example using the fixed-point negatable class\r\n  // with 2 decimal digits of precision, see also the test file\r\n  // named \"test_negatable_round_trip_digits10_002.cpp\".\r\n\r\n  BOOST_CONSTEXPR_OR_CONST int digits10 = int((long(8L - 1L) * 301L) / 1000L);\r\n\r\n  volatile fixed_point_type object_to_be_instantiated_at_least_once;\r\n}\r\n\r\nbool local::round_trip(const local::fixed_point_type& x)\r\n{\r\n  using local::fixed_point_type;\r\n\r\n  std::stringstream ss1;\r\n\r\n  ss1.precision(local::digits10);\r\n\r\n  ss1 << std::fixed\r\n      << x;\r\n\r\n  std::stringstream ss2(ss1.str());\r\n\r\n  fixed_point_type y;\r\n  ss2 >> y;\r\n\r\n  const bool b(x == y);\r\n\r\n  return b;\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_round_trip_digits02_005m2)\r\n{\r\n  using local::fixed_point_type;\r\n\r\n  typedef fixed_point_type::float_type floating_point_type;\r\n\r\n  boost::uint_fast16_t count;\r\n\r\n  BOOST_CONSTEXPR_OR_CONST boost::uint_fast16_t number_of_test_cases = UINT16_C(255);\r\n\r\n  bool b = true;\r\n\r\n  // Test sequential values with 5.2 binary digits of precision\r\n  // ranging from 0.25, 0.50, 0.75, ... 63.75.\r\n  for(count = UINT16_C(1); ((count < number_of_test_cases) && b); ++count)\r\n  {\r\n    std::stringstream ss1;\r\n\r\n    ss1 << std::fixed\r\n        << std::setprecision(local::digits10)\r\n        << (float(count) / 4.0F);\r\n\r\n    std::string str(ss1.str());\r\n\r\n    const fixed_point_type x(boost::lexical_cast<floating_point_type>(str));\r\n\r\n    const bool next_test_result = local::round_trip(x);\r\n\r\n    b = (b && next_test_result);\r\n  }\r\n\r\n  BOOST_CHECK_EQUAL(count, number_of_test_cases);\r\n\r\n  BOOST_CHECK_EQUAL(b, true);\r\n}\r\n", "meta": {"hexsha": "bbbab71f1a749f00edddec3993a1bb552fa23716", "size": 3125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_round_trip_digits02_005m2.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": "test/test_negatable_round_trip_digits02_005m2.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": "test/test_negatable_round_trip_digits02_005m2.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": 28.4090909091, "max_line_length": 86, "alphanum_fraction": 0.67424, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.808067204308405, "lm_q1q2_score": 0.6852149358560347}}
{"text": "/*\n * Copyright (C) 2014-2015 DubinsPathPlanner.\n * Created by David Goodman <dagoodma@gmail.com>\n * Redistribution and use of this file is allowed according to the terms of the MIT license.\n * For details see the LICENSE file distributed with DubinsPathPlanner.\n*/\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <ctime>\n#include <cstdlib>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <ogdf/basic/List.h>\n\n#include <dpp/basic/Util.h>\n\nusing Eigen::Vector3d;\nusing Eigen::Vector2d;\n\nusing ogdf::List;\nusing ogdf::ListIterator;\nusing ogdf::ListConstIterator;\nusing ogdf::NodeArray;\nusing ogdf::DPoint;\nusing ogdf::DLine;\nusing ogdf::DSegment;\n\nusing std::vector;\n\n// TODO parameterize data-driven tests in this file\n\n#define DELTA           1E-2 // input perturbation constant\n#define EPSILON_ERROR   1E-5  // output error threshold\n\n// --------------------- myMod() -------------------\nTEST(MyModTest, FmodEquivalenceComparison) {\n    EXPECT_DOUBLE_EQ(fmod(0.0,2), dpp::myMod(0.0,2));\n    EXPECT_DOUBLE_EQ(fmod(1.0,2), dpp::myMod(1.0,2));\n    EXPECT_DOUBLE_EQ(fmod(1.0,2), dpp::myMod(1.0,2));\n    EXPECT_DOUBLE_EQ(fmod(2.0,2), dpp::myMod(2.0,2));\n    EXPECT_DOUBLE_EQ(fmod(2.1,2), dpp::myMod(2.1,2));\n    EXPECT_DOUBLE_EQ(fmod(5,2), dpp::myMod(5,2));\n}\n\nTEST(MyModTest, RemovesNegatives) {\n    EXPECT_DOUBLE_EQ(1, dpp::myMod(-1.0,2));\n    EXPECT_DOUBLE_EQ(0, dpp::myMod(-2.0,2));\n    EXPECT_DOUBLE_EQ(1.9, dpp::myMod(-2.1,2));\n}\n\n// --------------------- headingToAngle() -------------------\nTEST(HeadingToAngleTest, Quadrants) {\n    EXPECT_DOUBLE_EQ(M_PI/2.0, dpp::headingToAngle(0.0));\n    EXPECT_DOUBLE_EQ(0.0, dpp::headingToAngle(M_PI/2.0));\n    EXPECT_DOUBLE_EQ(3.0*M_PI/2.0, dpp::headingToAngle(M_PI));\n    EXPECT_DOUBLE_EQ(M_PI, dpp::headingToAngle(3.0*M_PI/2.0));\n}\n\n// --------------------- angleToHeading() -------------------\nTEST(AngleToHeadingTest, Quadrants) {\n    EXPECT_DOUBLE_EQ(M_PI/2.0, dpp::angleToHeading(0.0));\n    EXPECT_DOUBLE_EQ(0.0, dpp::angleToHeading(M_PI/2.0));\n    EXPECT_DOUBLE_EQ(3.0*M_PI/2.0, dpp::angleToHeading(M_PI));\n    EXPECT_DOUBLE_EQ(M_PI, dpp::angleToHeading(3.0*M_PI/2.0));\n}\n\n// --------------------- wrapAngle() -------------------\nTEST(WrapAngleTest, NoWrap) {\n    EXPECT_DOUBLE_EQ(0.0, dpp::wrapAngle(0.0));\n    EXPECT_DOUBLE_EQ(M_PI, dpp::wrapAngle(M_PI));\n    EXPECT_DOUBLE_EQ(3.0*M_PI/2.0, dpp::wrapAngle(3.0*M_PI/2.0));\n}\nTEST(WrapAngleTest, Wrap) {\n    EXPECT_DOUBLE_EQ(0.0, dpp::wrapAngle(2.0*M_PI));\n    EXPECT_DOUBLE_EQ(M_PI/2.0, dpp::wrapAngle(5.0*M_PI/2.0));\n    EXPECT_NEAR(DELTA, dpp::wrapAngle(2.0*M_PI + DELTA), EPSILON_ERROR);\n}\nTEST(WrapAngleTest, TwoPiWraps) {\n    double input=2*M_PI;\n    double expectedOutput=0.0;\n    EXPECT_NEAR(expectedOutput, dpp::wrapAngle(input), EPSILON_ERROR);\n}\nTEST(WrapAngleTest, BoundaryWrap) {\n    double input=6.283195307179586;\n    double expectedOutput=0.0;\n    EXPECT_NEAR(expectedOutput, dpp::wrapAngle(input), EPSILON_ERROR);\n}\n\n// --------------------- angleBetween() -------------------\nconst Vector2d uAngle(1.0, 0.0); \n\nTEST(AngleBetweenTest, SameAngle) {\n    Vector2d v(1.0, 0.0);\n    double expectedOutput = 0.0;\n    double actualOutput = dpp::angleBetween(uAngle,v);\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\nTEST(AngleBetweenTest, AcuteAngle) {\n    Vector2d v(0.707, 0.707);\n    double expectedOutput = dpp::degToRad(45);\n    double actualOutput = dpp::angleBetween(uAngle,v);\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\nTEST(AngleBetweenTest, ObtuseAngle) {\n    Vector2d v(0.0, -1.0);\n    //double expectedOutput = dpp::degToRad(270); // not clockwise-only\n    double expectedOutput = dpp::degToRad(90);\n    double actualOutput = dpp::angleBetween(uAngle,v);\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\n// --------------------- angleOfLine() -------------------\nTEST(AngleOfLineTest, HorizontalLine) {\n    DLine line(DPoint(-1,0), DPoint(5,0));\n    double expectedOutput = 0.0;\n    double actualOutput = dpp::angleOfLine(line);\n\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\nTEST(AngleOfLineTest, VerticalLine) {\n    DLine line(DPoint(0,-1), DPoint(0,10));\n    double expectedOutput = dpp::degToRad(90);\n    double actualOutput = dpp::angleOfLine(line);\n\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\nTEST(AngleOfLineTest, AnotherLine) {\n    DLine line(DPoint(-1,-1), DPoint(-3,-3));\n    double expectedOutput = dpp::degToRad(225);\n    double actualOutput = dpp::angleOfLine(line);\n\n    EXPECT_DOUBLE_EQ(expectedOutput, actualOutput);\n}\n\n// --------------------- headingBetween() -------------------\n// note: headings are between points (not vectors), and are taken in the\n//      clockwise direction from north\nconst Vector2d uHeading(0.0,0.0); // point at the origin\n\nTEST(HeadingBetweenTest, AtanAtZero) {\n    double x1=0,y1=0,x2=1,y2=0;\n    EXPECT_DOUBLE_EQ(0.0, atan((y1 - y2)/(x2 - x1)));\n}\n\nTEST(HeadingBetweenTest, SamePoint) {\n    Vector2d v(uHeading);\n    EXPECT_DOUBLE_EQ(0.0, dpp::headingBetween(uHeading, v));\n    EXPECT_DOUBLE_EQ(0.0, dpp::headingBetween(v, uHeading));\n}\n\nTEST(HeadingBetweenTest, QuadrantI) {\n    // Test Case for Quadrant 1 Boundaries\n    Vector2d v(\n        0.0,\n        1.0);\n    EXPECT_DOUBLE_EQ(0.0, dpp::headingBetween(uHeading, v));\n\n    v[0] = 1.0;\n    v[1] = 1.0;\n    EXPECT_DOUBLE_EQ(dpp::degToRad(45.0), dpp::headingBetween(uHeading,v));\n}\n\nTEST(HeadingBetweenTest, QuadrantII) {\n    // Test Case for Quadrant 2 Boundaries\n    Vector2d v(\n        1.0,\n        0.0);\n    EXPECT_DOUBLE_EQ(dpp::degToRad(90.0), dpp::headingBetween(uHeading,v));\n\n    v[0] = 1.0;\n    v[1] = -1.0;\n    EXPECT_DOUBLE_EQ(dpp::degToRad(135.0), dpp::headingBetween(uHeading,v));\n}\nTEST(HeadingBetweenTest, QuadrantIII) {\n    // Test Case for Quadrant 3 Boundaries\n    Vector2d v(\n        0.0,\n        -1.0);\n    EXPECT_DOUBLE_EQ(dpp::degToRad(180.0), dpp::headingBetween(uHeading,v));\n\n    v[0] = -1.0;\n    v[1] = -1.0;\n    EXPECT_DOUBLE_EQ(dpp::degToRad(225.0), dpp::headingBetween(uHeading,v));\n}\n\nTEST(HeadingBetweenTest, QuadrantIV) {\n    // Test Case for Quadrant 4 Boundaries\n    Vector2d v(\n        -1.0,\n        0.0);\n    EXPECT_DOUBLE_EQ(dpp::degToRad(270.0), dpp::headingBetween(uHeading,v));\n\n    v[0] = -1.0;\n    v[1] = 1.0;\n    EXPECT_DOUBLE_EQ(dpp::degToRad(315.0), dpp::headingBetween(uHeading,v));\n}\n\nTEST(HeadingBetweenTest, Various) {\n    // Some various test cases\n    Vector2d u(\n        1.0,\n        1.0),\n        v(\n        1.0,\n        -1.0);\n    EXPECT_DOUBLE_EQ(dpp::degToRad(180), dpp::headingBetween(u,v));\n    EXPECT_DOUBLE_EQ(dpp::degToRad(0), dpp::headingBetween(v,u));\n}\n\n// --------------------- polarToCartesian() -------------------\nconst double expectedC = 0.707106781186547;\n\nTEST(PolarToCartesianTest, AtOrigin) {\n    DPoint expectedP(0,0);\n    {\n        DPoint actualP = dpp::polarToCartesian(0,0);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n    {\n        DPoint actualP = dpp::polarToCartesian(270,0);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n}\n\nTEST(PolarToCartesianTest, QuadrantI) {\n    {\n        DPoint expectedP(1,0);\n        DPoint actualP = dpp::polarToCartesian(0,1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n    {\n        DPoint expectedP(expectedC,expectedC);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(45),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n    {\n        DPoint expectedP(0,1);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(90),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n}\n\nTEST(PolarToCartesianTest, QuadrantII) {\n    {\n        DPoint expectedP(-expectedC,expectedC);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(135),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n    {\n        DPoint expectedP(-1,0);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(180),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n}\n\nTEST(PolarToCartesianTest, QuadrantIII) {\n    {\n        DPoint expectedP(-expectedC,-expectedC);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(225),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n    {\n        DPoint expectedP(0,-2);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(270),2);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n}\n\nTEST(PolarToCartesianTest, QuadrantIV) {\n    {\n        DPoint expectedP(expectedC,-expectedC);\n        DPoint actualP = dpp::polarToCartesian(dpp::degToRad(315),1);\n\n        EXPECT_EQ(expectedP, actualP);\n    }\n}\n\n// --------------------- clearEdges() -------------------\nusing ogdf::node;\nusing ogdf::edge;\nusing ogdf::Graph;\nusing ogdf::GraphAttributes;\n\nusing ::testing::Test;\nusing ::testing::Values;\nusing ::testing::ValuesIn;\nclass ClearEdgesTest : public Test {\npublic:\n    ClearEdgesTest()\n        : m_G(),\n          m_GA (m_G, \n            GraphAttributes::nodeId) {}\n\n    virtual ~ClearEdgesTest() { }\n\n    virtual void SetUp() {\n        // Add nodes\n        node u = m_G.newNode();\n        node v = m_G.newNode();\n        m_nodeList.push_back(u);\n        m_nodeList.push_back(v);\n\n    } // InitializeScenario()\n\n    virtual void TearDown() {\n    } // TearDown()\n\n    int GetIndex(node &u) {\n        return m_GA.idNode(u);\n    }\n\n    node GetNode(int i) {\n        i -= 1;\n        if (i < m_G.numberOfNodes()) {\n            return m_nodeList.at(i);\n        }\n        return nullptr;\n    }\n\n    int GetSize() {\n        return m_G.numberOfEdges();\n    }\n\nprotected:\n    Graph m_G;\n    GraphAttributes m_GA;\n    vector<node> m_nodeList;\n\n}; // class ClearEdgesTest \n\nTEST_F(ClearEdgesTest, NoEdges) {\n    // Nothing is cleared\n    EXPECT_EQ(0, GetSize());\n    dpp::clearEdges(m_G);\n    EXPECT_EQ(0, GetSize());\n}\n\nTEST_F(ClearEdgesTest, OneEdge) {\n    EXPECT_EQ(0, GetSize());\n\n    // Add an edge\n    edge e = m_G.newEdge(GetNode(1), GetNode(2));\n    EXPECT_EQ(1, GetSize());\n\n    // Delete it\n    dpp::clearEdges(m_G);\n    EXPECT_EQ(0, GetSize());\n}\n\n\nTEST_F(ClearEdgesTest, TwoEdges) {\n    EXPECT_EQ(0, GetSize());\n\n    // Add two edges\n    edge e1 = m_G.newEdge(GetNode(1), GetNode(2));\n    edge e2 = m_G.newEdge(GetNode(2), GetNode(1));\n    EXPECT_EQ(2, GetSize());\n\n    // Delete them\n    dpp::clearEdges(m_G);\n    EXPECT_EQ(0, GetSize());\n}\n\n// --------------------- graphsAreEquivalent() -------------------\n\n// These nodes are used in several tests\nconst List<DPoint> nodes {\n    {0, 0},\n    {5.1, 0.0},\n    {5.1, -3.3}\n};\n\nclass GraphsAreEquivalentTest : public Test {\npublic:\n    GraphsAreEquivalentTest()\n        : m_G(),\n          m_GA (m_G, DPP_GRAPH_ATTRIBUTES ),\n          m_Gcopy(),\n          m_GAcopy(m_Gcopy, DPP_GRAPH_ATTRIBUTES)\n    { }\n\n    virtual ~GraphsAreEquivalentTest() { }\n\n    virtual void SetUp() {\n        // Add nodes to original\n        int i = 1;\n        ListConstIterator<DPoint> iter;\n        for ( iter = nodes.begin(); iter != nodes.end(); iter++ ) {\n            DPoint Pu = *iter;\n            node u = m_G.newNode();\n            m_GA.x(u) = Pu.m_x;\n            m_GA.y(u) = Pu.m_y;\n            m_GA.idNode(u) = i;\n            i++;\n        }\n\n        // Add the same nodes to copy\n        int icopy = 1;\n        for ( iter = nodes.begin(); iter != nodes.end(); iter++ ) {\n            DPoint Pu = *iter;\n            node u = m_Gcopy.newNode();\n            m_GAcopy.x(u) = Pu.m_x;\n            m_GAcopy.y(u) = Pu.m_y;\n            m_GAcopy.idNode(u) = icopy;\n            icopy++;\n        }\n\n        // Generate random seed for edge weight generation\n        srand (static_cast <unsigned> (time(0)));\n    } // SetUp()\n\n    virtual void TearDown() {\n    } // TearDown()\n\n    // Returns a random from 0 to 1.0\n    double getRandomEdgeWeight(void) {\n        return static_cast <float> (rand()) / static_cast <float> (RAND_MAX);\n    }\n\n    // Add directed edges between nodes in index order with random weights\n    void addEdges() {\n        node u, v;\n        forall_nodes(v,m_G) {\n            // Skip the first node\n            if (m_G.firstNode() == v) {\n                u = v;\n                continue;\n            }\n            edge e = m_G.newEdge(u, v);\n            // Generate: w = [0, 1.0]\n            float w = getRandomEdgeWeight();\n            m_GA.doubleWeight(e) = w;\n            u = v;\n        }\n        forall_nodes(v,m_Gcopy) {\n            // Skip the first node\n            if (m_Gcopy.firstNode() == v) {\n                u = v;\n                continue;\n            }\n            edge e = m_Gcopy.newEdge(u, v);\n            // Generate: w = [0, 1.0]\n            float w = getRandomEdgeWeight();\n            m_GAcopy.doubleWeight(e) = w;\n            u = v;\n        }\n    }\n\nprotected:\n    Graph m_G, m_Gcopy;\n    GraphAttributes m_GA, m_GAcopy;\n\n}; // class GraphsAreEquivalentTest \n\n// Test for equivalence with empty graphs\nTEST_F(GraphsAreEquivalentTest, EmptyGraphsAreEquivalent) {\n    Graph G, Gcopy;\n    GraphAttributes GA(G, DPP_GRAPH_ATTRIBUTES),\n        GAcopy(Gcopy, DPP_GRAPH_ATTRIBUTES);\n\n    ASSERT_EQ(0, G.numberOfNodes());\n    ASSERT_EQ(0, Gcopy.numberOfNodes());\n    ASSERT_EQ(0, G.numberOfEdges());\n    ASSERT_EQ(0, Gcopy.numberOfEdges());\n\n    EXPECT_EQ(1, dpp::graphsAreEquivalent(G, GA, Gcopy, GAcopy));\n}\n\n// Test for equivalence with empty graphs\nTEST_F(GraphsAreEquivalentTest, SimpleGraphsNotEquivalent) {\n    Graph G, Gcopy;\n    GraphAttributes GA(G, DPP_GRAPH_ATTRIBUTES),\n        GAcopy(Gcopy, DPP_GRAPH_ATTRIBUTES);\n\n    node u = G.newNode();\n    GA.x(u) = getRandomEdgeWeight();\n    GA.x(u) = getRandomEdgeWeight();\n    GA.idNode(u) = 1;\n\n    ASSERT_EQ(1, G.numberOfNodes());\n    ASSERT_EQ(0, Gcopy.numberOfNodes());\n    ASSERT_EQ(0, G.numberOfEdges());\n    ASSERT_EQ(0, Gcopy.numberOfEdges());\n\n    EXPECT_EQ(0, dpp::graphsAreEquivalent(G, GA, Gcopy, GAcopy));\n}\n\n// Test for equivalence with node-only graphs\nTEST_F(GraphsAreEquivalentTest, NodeOnlyGraphsAreEquivalent) {\n    int expectedSize = nodes.size();\n    ASSERT_EQ(expectedSize, m_G.numberOfNodes());\n    ASSERT_EQ(expectedSize, m_Gcopy.numberOfNodes());\n\n    EXPECT_EQ(1, dpp::graphsAreEquivalent(m_G, m_GA, m_Gcopy, m_GAcopy));\n}\n\n// Test for equivalence with full graphs\nTEST_F(GraphsAreEquivalentTest, GraphsAreEquivalent) {\n    int expectedSize = nodes.size();\n    ASSERT_EQ(expectedSize, m_G.numberOfNodes());\n    ASSERT_EQ(expectedSize, m_Gcopy.numberOfNodes());\n\n    addEdges();\n    ASSERT_EQ(m_G.numberOfNodes() - 1, m_G.numberOfEdges());\n    ASSERT_EQ(m_G.numberOfNodes() - 1, m_Gcopy.numberOfEdges());\n\n    EXPECT_EQ(1, dpp::graphsAreEquivalent(m_G, m_GA, m_Gcopy, m_GAcopy));\n}\n\n// --------------------- copyGraph() -------------------\nclass GraphCopyTest : public Test {\npublic:\n    GraphCopyTest()\n        : m_G(),\n          m_GA (m_G, DPP_GRAPH_ATTRIBUTES ),\n          m_Gcopy(),\n          m_GAcopy (m_Gcopy, DPP_GRAPH_ATTRIBUTES )\n    { }\n\n    virtual ~GraphCopyTest() { }\n\n    virtual void SetUp() {\n        // Add nodes\n        int i = 1;\n        ListConstIterator<DPoint> iter;\n        for ( iter = nodes.begin(); iter != nodes.end(); iter++ ) {\n            DPoint Pu = *iter;\n            node u = m_G.newNode();\n            m_GA.x(u) = Pu.m_x;\n            m_GA.y(u) = Pu.m_y;\n            m_GA.idNode(u) = i;\n            i++;\n        }\n        // Generate random seed for edge weight generation\n        srand (static_cast <unsigned> (time(0)));\n    } // SetUp()\n\n    virtual void TearDown() {\n    } // TearDown()\n\n    // Add directed edges between nodes in index order with random weights\n    void addEdges() {\n        node u, v;\n        forall_nodes(v,m_G) {\n            // Skip the first node\n            if (m_G.firstNode() == v) {\n                u = v;\n                continue;\n            }\n            edge e = m_G.newEdge(u, v);\n            float w = getRandomEdgeWeight();\n            m_GA.doubleWeight(e) = w;\n        }\n    }\n\n    // Returns a random from 0 to 1.0\n    double getRandomEdgeWeight(void) {\n        return static_cast <float> (rand()) / static_cast <float> (RAND_MAX);\n    }\n\nprotected:\n    Graph m_G, m_Gcopy;\n    GraphAttributes m_GA, m_GAcopy;\n\n}; // class GraphCopyTest \n\nTEST_F(GraphCopyTest, CopiesNodesOnly) {\n    ASSERT_GT(m_G.numberOfNodes(), 0);\n    ASSERT_EQ(m_G.numberOfEdges(), 0);\n    ASSERT_EQ(m_Gcopy.numberOfNodes(), 0);\n    ASSERT_EQ(m_Gcopy.numberOfEdges(), 0);\n\n    int n = dpp::copyGraph(m_G, m_GA, m_Gcopy, m_GAcopy);\n\n    EXPECT_EQ(m_G.numberOfNodes(), n);\n\n    EXPECT_EQ(true, dpp::graphsAreEquivalent(m_G, m_GA, m_Gcopy, m_GAcopy)); \n}\n\nTEST_F(GraphCopyTest, ClearsExistingNodes) {\n    ASSERT_GT(m_G.numberOfNodes(), 0);\n    ASSERT_EQ(m_G.numberOfEdges(), 0);\n    ASSERT_EQ(m_Gcopy.numberOfNodes(), 0);\n    ASSERT_EQ(m_Gcopy.numberOfEdges(), 0);\n\n    node u = m_Gcopy.newNode();\n    m_GAcopy.x(u) = 0.5;\n    m_GAcopy.y(u) = 0.77;\n    m_GAcopy.idNode(u) = 1;\n\n    ASSERT_EQ(1, m_Gcopy.numberOfNodes());\n\n    int n = dpp::copyGraph(m_G, m_GA, m_Gcopy, m_GAcopy);\n\n    EXPECT_EQ(m_G.numberOfNodes(), n);\n\n    EXPECT_EQ(true, dpp::graphsAreEquivalent(m_G, m_GA, m_Gcopy, m_GAcopy)); \n}\n/*\nTEST_F(GraphCopyTest, CopiesNodesAndEdges) {\n    ASSERT_GT(m_G.numberOfNodes(), 0);\n    ASSERT_EQ(m_G.numberOfEdges(), 0);\n\n    addEdges();\n    ASSERT_EQ(m_G.numberOfNodes() - 1, m_G.numberOfEdges());\n\n    int n = dpp::copyGraph(m_G, m_GA, Gcopy, GAcopy);\n\n    EXPECT_EQ(m_G.numberOfNodes(), n);\n\n    EXPECT_EQ(true, dpp::graphsAreEquivalent(m_G, m_GA, m_Gcopy, m_GAcopy)); \n}\n*/\n\n\n// --------------------- Line2d -------------------\n// Tests for constructor\nTEST(Line2dTest, ConstructsWithDLine) {\n    DLine dl(DPoint(0,0), DPoint(1,0));\n    dpp::Line2d line(dl);\n\n    EXPECT_DOUBLE_EQ(0, line.m_a);\n    EXPECT_DOUBLE_EQ(1, line.m_b);\n    EXPECT_DOUBLE_EQ(0, line.m_c);\n    EXPECT_DOUBLE_EQ(dl.slope(), line.slope());\n}\n\nTEST(Line2dTest, ConstructsWithDSegment) {\n    DSegment s(DPoint(0,0), DPoint(1,0));\n    dpp::Line2d line(s);\n\n    EXPECT_DOUBLE_EQ(0, line.m_a);\n    EXPECT_DOUBLE_EQ(1, line.m_b);\n    EXPECT_DOUBLE_EQ(0, line.m_c);\n    EXPECT_DOUBLE_EQ(s.slope(), s.slope());\n}\n\nTEST(Line2dTest, ConstructsVerticalLine) {\n    DLine dl(DPoint(2,0), DPoint(2,1));\n    dpp::Line2d line(dl);\n\n    EXPECT_DOUBLE_EQ(2, line.m_a);\n    EXPECT_DOUBLE_EQ(1, line.m_b);\n    EXPECT_DOUBLE_EQ(std::numeric_limits<double>::max(), line.m_c);\n    EXPECT_DOUBLE_EQ(dl.slope(), line.slope());\n    EXPECT_TRUE(line.isVertical());\n}\n\n// Tests for equality operators\nTEST(Line2dEquality, HorizontalLinesEqual) {\n    DLine dl(DPoint(-1,8), DPoint(5,8));\n    DLine dl2(DPoint(-3,8), DPoint(1,8));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl2);\n\n    ASSERT_TRUE(dl != dl2); // ensure Line2d == is different than DLine\n    EXPECT_TRUE(line == line2);\n}\n\nTEST(Line2dEquality, HorizontalLinesNotEqual) {\n    DLine dl(DPoint(-1,8), DPoint(5,8));\n    DLine dl2(DPoint(-3,-8), DPoint(1,-8));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl2);\n\n    ASSERT_TRUE(dl != dl2);\n    EXPECT_TRUE(line != line2);\n}\n\nTEST(Line2dEquality, VerticalLinesEqual) {\n    DLine dl(DPoint(-1,3), DPoint(-1,5));\n    DLine dl2(DPoint(-1,-50), DPoint(-1,10));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl2);\n\n    ASSERT_TRUE(dl != dl2);\n    EXPECT_TRUE(line == line2);\n}\n\nTEST(Line2dEquality, VerticalLinesNotEqual) {\n    DLine dl(DPoint(-1,3), DPoint(-1,5));\n    DLine dl2(DPoint(-50,-50), DPoint(-50,10));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl2);\n\n    ASSERT_TRUE(dl != dl2);\n    EXPECT_TRUE(line != line2);\n}\n\nTEST(Line2dEquality, RegularLinesEqual) {\n    DLine dl(DPoint(0,0), DPoint(1,1));\n    DLine dl2(DPoint(-3,-3), DPoint(0,0));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl);\n    ASSERT_TRUE(dl != dl2);\n    EXPECT_TRUE(line == line2);\n}\n\nTEST(Line2dEquality, RegularLinesNotEqual) {\n    DLine dl(DPoint(0,0), DPoint(1,1));\n    DLine dl2(DPoint(-3,-3), DPoint(-3,0));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(dl2);\n    ASSERT_TRUE(dl != dl2);\n    EXPECT_TRUE(line != line2);\n}\n\n// Test for copy constructor\nTEST(Line2dCopyTest, CopyConstructor) {\n    DLine dl(DPoint(0,0), DPoint(-1, -2));\n    dpp::Line2d line(dl);\n    dpp::Line2d line2(line);\n\n    EXPECT_TRUE(line == line2);\n}\n\n// Test for length()\nTEST(Line2dTest, InfiniteLength) {\n    DLine dl(DPoint(0,0), DPoint(1,1));\n    dpp::Line2d line(dl);\n\n    EXPECT_TRUE(line.length() == std::numeric_limits<double>::max());\n}\n\n// Tests for angle()\nTEST(Line2dAngleTest, AngleOfHorizontalLine) {\n    DLine dl(DPoint(0,0), DPoint(1,0));\n    dpp::Line2d line(dl);\n    double expectedOutput = 0;\n\n    EXPECT_DOUBLE_EQ(expectedOutput, line.angle());\n}\n\nTEST(Line2dAngleTest, AngleOfVerticalLine) {\n    DLine dl(DPoint(-1,5), DPoint(-1,8));\n    dpp::Line2d line(dl);\n    double expectedOutput = dpp::degToRad(90);\n\n    EXPECT_DOUBLE_EQ(expectedOutput, line.angle());\n}\n\nTEST(Line2dAngleTest, AngleOfObtuseLine) {\n    DLine dl(DPoint(-1,0), DPoint(-3,1));\n    dpp::Line2d line(dl);\n    double expectedOutput = atan2(dl.dy(), dl.dx());\n\n    EXPECT_DOUBLE_EQ(expectedOutput, line.angle());\n}\n\nTEST(Line2dAngleTest, AngleOfLineWrapsAtPi) {\n    DLine dl(DPoint(0,0), DPoint(-1, 0));\n    dpp::Line2d line(dl);\n    double expectedOutput = 0;\n\n    EXPECT_DOUBLE_EQ(expectedOutput, line.angle());\n}\n\nTEST(Line2dAngleTest, AngleOfLineWrapsPastPi) {\n    DLine dl(DPoint(0,0), DPoint(0,-1));\n    dpp::Line2d line(dl);\n    double expectedOutput = dpp::degToRad(90);\n\n    EXPECT_DOUBLE_EQ(expectedOutput, line.angle());\n}\n\n// Tests for contains()\nTEST(Line2dContainsTest, ContainsSegmentEndpoints) {\n    DLine dl(DPoint(-5,3), DPoint(0,3));\n    dpp::Line2d line(dl);\n    DPoint p(-3,3);\n\n    ASSERT_TRUE(dl.contains(dl.start()));\n    ASSERT_TRUE(dl.contains(dl.end()));\n\n    EXPECT_TRUE(line.contains(dl.start()));\n    EXPECT_TRUE(line.contains(dl.end()));\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dContainsTest, ContainsPastSegmentEndpoints) {\n    DLine dl(DPoint(0,0), DPoint(-1,-1));\n    DPoint p1(-2,-2);\n    DPoint p2(5,5);\n    DPoint p3(0.5,0.5);\n    dpp::Line2d line(dl);\n\n    ASSERT_FALSE(dl.contains(p1));\n    ASSERT_FALSE(dl.contains(p2));\n\n    EXPECT_TRUE(line.contains(p1));\n    EXPECT_TRUE(line.contains(p2));\n    EXPECT_TRUE(line.contains(p3));\n}\n\nTEST(Line2dContainsTest, DoesNotContainPoint) {\n    DLine dl(DPoint(0,0), DPoint(1,0));\n    DPoint p(-1,-1);\n    dpp::Line2d line(dl);\n\n    ASSERT_FALSE(dl.contains(p));\n    EXPECT_FALSE(line.contains(p));\n}\n\nTEST(Line2dContainsTest, VerticalLineContains) {\n    DLine dl(DPoint(0,0), DPoint(0,-1));\n    DPoint p(0,10);\n    dpp::Line2d line(dl);\n\n    ASSERT_FALSE(dl.contains(p));\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dContainsTest, VerticalLineDoesNotContain) {\n    DLine dl(DPoint(0,0), DPoint(0,-1));\n    DPoint p(1,0);\n    dpp::Line2d line(dl);\n\n    ASSERT_FALSE(dl.contains(p));\n    EXPECT_FALSE(line.contains(p));\n}\n\n// Tests for translatePolar()\nTEST(Line2dTranslateTest, TranslateHorizontalLineUp) {\n    dpp::Line2d line(DLine(DPoint(-1,5), DPoint(5,5)));\n    dpp::Line2d originalLine(line);\n    DPoint p(10,8);\n    double d = 3;\n    double theta = dpp::degToRad(90);\n\n    ASSERT_FALSE(line.contains(p));\n    line.translatePolar(d, theta);\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateHorizontalLineDown) {\n    dpp::Line2d line(DLine(DPoint(-1,5), DPoint(5,5)));\n    dpp::Line2d originalLine(line);\n    DPoint p(10,2);\n    double d = 3;\n    double theta = dpp::degToRad(270);\n\n    ASSERT_FALSE(line.contains(p));\n    line.translatePolar(d, theta);\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateVerticalLineRight) {\n    dpp::Line2d line(DLine(DPoint(5,0), DPoint(5,7)));\n    dpp::Line2d originalLine(line);\n    DPoint p(7,59);\n    double d = 2;\n    double theta = dpp::degToRad(0);\n\n    ASSERT_FALSE(line.contains(p));\n    line.translatePolar(d, theta);\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateVerticalLineLeft) {\n    dpp::Line2d line(DLine(DPoint(5,0), DPoint(5,7)));\n    dpp::Line2d originalLine(line);\n    DPoint p(-3,-5);\n    double d = 8;\n    double theta = dpp::degToRad(180);\n\n    ASSERT_FALSE(line.contains(p));\n    line.translatePolar(d, theta);\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateRegularLineRight) {\n    dpp::Line2d line(DLine(DPoint(-1,1), DPoint(10,-7)));\n    dpp::Line2d originalLine(line);\n    DPoint p(1.058600941862662,\n        3.830576295061160);\n    double d = 3.5;\n    double theta = dpp::wrapAngle(line.angle() - M_PI/2);\n\n    ASSERT_FALSE(line.contains(p));\n    //std::cout << \"Before: \" << line << \" at \" << dpp::radToDeg(line.angle()) << \".\" << std::endl;\n    line.translatePolar(d, theta);\n    //std::cout << \"After: \" << line << std::endl;\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateRegularLineLeft) {\n    dpp::Line2d line(DLine(DPoint(-1,1), DPoint(10,-7)));\n    dpp::Line2d originalLine(line);\n    DPoint p(-3.176235281397672,\n        -1.992323511921797);\n    double d = 3.7;\n    double theta = dpp::wrapAngle(line.angle() + M_PI/2);\n\n    ASSERT_FALSE(line.contains(p));\n    line.translatePolar(d, theta);\n    ASSERT_TRUE(line != originalLine);\n    EXPECT_TRUE(line.contains(p));\n}\n\nTEST(Line2dTranslateTest, TranslateLineNonPerpendicular) {\n    // Test regular\n    {\n        dpp::Line2d line(DLine(DPoint(-10,0),DPoint(5,0)));\n        dpp::Line2d originalLine(line);\n        DPoint p(-9.292893218813452,\n            0.707106781186547);\n        double d = 1;\n        double theta = dpp::degToRad(45);\n        ASSERT_FALSE(line.contains(p));\n        line.translatePolar(d, theta);\n        ASSERT_TRUE(line != originalLine);\n        EXPECT_TRUE(line.contains(p));\n    }\n\n    // Test vertical\n    {\n        dpp::Line2d line(DLine(DPoint(0,5),DPoint(0,-3)));\n        dpp::Line2d originalLine(line);\n        DPoint p(0.707106781186548,0);\n        double d = 1;\n        double theta = dpp::degToRad(45);\n        ASSERT_FALSE(line.contains(p));\n        line.translatePolar(d, theta);\n        ASSERT_TRUE(line != originalLine);\n        EXPECT_TRUE(line.contains(p));\n    }\n}\n\nTEST(Line2dTranslateTest, TranslateLineParallelDoesNothing) {\n    // Test regular\n    {\n        dpp::Line2d line(DLine(DPoint(-10,0),DPoint(5,0)));\n        dpp::Line2d originalLine(line);\n        double d = 10;\n        double theta = dpp::degToRad(0);\n        //std::cout << \"Before: \" << line << \" at \" << dpp::radToDeg(line.angle()) << \".\" << std::endl;\n        line.translatePolar(d, theta);\n        //std::cout << \"After: \" << line << std::endl;\n        EXPECT_TRUE(line == originalLine);\n    }\n\n    // Test vertical\n    {\n        dpp::Line2d line(DLine(DPoint(0,5),DPoint(0,-3)));\n        dpp::Line2d originalLine(line);\n        double d = 10;\n        double theta = dpp::degToRad(90);\n        //std::cout << \"Before: \" << line << \" at \" << dpp::radToDeg(line.angle()) << \".\" << std::endl;\n        line.translatePolar(d, theta);\n        //std::cout << \"After: \" << line << std::endl;\n        EXPECT_TRUE(line == originalLine);\n    }\n}\n\nTEST(Line2dTranslateTest, TranslateLineZeroDistance) {\n    // Test regular\n    {\n        dpp::Line2d line(DLine(DPoint(-10,0),DPoint(5,0)));\n        dpp::Line2d originalLine(line);\n        double d = 0;\n        double theta = dpp::degToRad(90);\n        line.translatePolar(d, theta);\n        EXPECT_TRUE(line == originalLine);\n    }\n\n    // Test vertical\n    {\n        dpp::Line2d line(DLine(DPoint(0,5),DPoint(0,-3)));\n        dpp::Line2d originalLine(line);\n        double d = 0;\n        double theta = dpp::degToRad(0);\n        line.translatePolar(d, theta);\n        EXPECT_TRUE(line == originalLine);\n    }\n}\n\n// Tests for intersction() with lines\nTEST(Line2dIntersectionTest, NoIntersectionVertical) {\n    dpp::Line2d line(DLine(DPoint(-2,-10), DPoint(-2,14)));\n    dpp::Line2d line2(DLine(DPoint(-5,10), DPoint(-5,14)));\n\n    DPoint p;\n    EXPECT_FALSE(line.intersection(line2,p));\n}\n\nTEST(Line2dIntersectionTest, NoIntersectionHorizontal) {\n    dpp::Line2d line(DLine(DPoint(-2,-10), DPoint(10,-10)));\n    dpp::Line2d line2(DLine(DPoint(2,10), DPoint(10,10)));\n\n    DPoint p;\n    EXPECT_FALSE(line.intersection(line2,p));\n}\n\nTEST(Line2dIntersectionTest, NoIntersectionIdentical) {\n    // Horizontal\n    {\n        dpp::Line2d line(DLine(DPoint(-2,10), DPoint(10,10)));\n        dpp::Line2d line2(DLine(DPoint(2,10), DPoint(10,10)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(line2,p));\n    }\n    // Vertical\n    {\n        dpp::Line2d line(DLine(DPoint(-5,-10), DPoint(-5,14)));\n        dpp::Line2d line2(DLine(DPoint(-5,10), DPoint(-5,14)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(line2,p));\n    }\n}\n\nTEST(Line2dIntersectionTest, HasIntersection) {\n    // Horizontal and vertical\n    {\n        dpp::Line2d line(DLine(DPoint(-2,10), DPoint(10,10)));\n        dpp::Line2d line2(DLine(DPoint(0,10), DPoint(0,15)));\n\n        DPoint expectedP(0,10);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(line2,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n    // Horizontal and regular\n    {\n        dpp::Line2d line(DLine(DPoint(-2,0), DPoint(10,0)));\n        dpp::Line2d line2(DLine(DPoint(0,0), DPoint(10,10)));\n\n        DPoint expectedP(0,0);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(line2,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n    // Vertical and regular\n    {\n        dpp::Line2d line(DLine(DPoint(0,10), DPoint(0,15)));\n        dpp::Line2d line2(DLine(DPoint(-1,10), DPoint(-5,14)));\n\n        DPoint expectedP(0,9);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(line2,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n}\n\n// Tests for intersction() with segments\nTEST(Line2dIntersectionTest, NoSegmentIntersection) {\n    // Horizontal segment\n    {\n        dpp::Line2d line(DLine(DPoint(0,10), DPoint(0,10)));\n        DSegment s(DLine(DPoint(2,10), DPoint(10,10)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(s,p));\n    }\n    // Vertical segment\n    {\n        dpp::Line2d line(DLine(DPoint(0,10), DPoint(0,10)));\n        DSegment s(DLine(DPoint(1,5), DPoint(1,10)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(s,p));\n    }\n}\n\nTEST(Line2dIntersectionTest, NoSegmentIntersectionOnTopOf) {\n    // Horizontal\n    {\n        dpp::Line2d line(DLine(DPoint(-2,10), DPoint(10,10)));\n        DSegment s(DLine(DPoint(-5,10), DPoint(-3,10)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(s,p));\n    }\n    // Vertical\n    {\n        dpp::Line2d line(DLine(DPoint(-2,10), DPoint(-2,15)));\n        DSegment s(DLine(DPoint(-2,3), DPoint(-2,10)));\n\n        DPoint p;\n        EXPECT_FALSE(line.intersection(s,p));\n    }\n}\n\n\nTEST(Line2dIntersectionTest, HasSegmentIntersection) {\n    // Horizontal\n    {\n        dpp::Line2d line(DLine(DPoint(0,0), DPoint(5,5)));\n        DSegment s(DLine(DPoint(-5,0), DPoint(5,0)));\n\n        DPoint expectedP(0,0);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(s,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n    // Vertical\n    {\n        dpp::Line2d line(DLine(DPoint(0,0), DPoint(5,5)));\n        DSegment s(DLine(DPoint(-2,-2), DPoint(-2,10)));\n\n        DPoint expectedP(-2,-2);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(s,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n    // Regular\n    {\n        dpp::Line2d line(DLine(DPoint(0,10), DPoint(0,15)));\n        DSegment s(DLine(DPoint(-1,-1), DPoint(1,1)));\n\n        DPoint expectedP(0,0);\n        DPoint actualP;\n        EXPECT_TRUE(line.intersection(s,actualP));\n        EXPECT_TRUE(expectedP == actualP);\n    }\n}\n", "meta": {"hexsha": "7729bc0647e877c60f4ef90530e35ddf85178e21", "size": 31660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/basic/Util_test.cpp", "max_stars_repo_name": "dagoodma/dubins_coverage", "max_stars_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-09-28T00:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T16:02:56.000Z", "max_issues_repo_path": "test/basic/Util_test.cpp", "max_issues_repo_name": "dagoodma/dubins_coverage", "max_issues_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_issues_repo_licenses": ["MIT"], "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/basic/Util_test.cpp", "max_forks_repo_name": "dagoodma/dubins_coverage", "max_forks_repo_head_hexsha": "f05333b55fb2cb073bb572562726f8b711df54ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-12-16T03:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T06:54:03.000Z", "avg_line_length": 27.7963125549, "max_line_length": 103, "alphanum_fraction": 0.6158559697, "num_tokens": 9391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.8221891392358014, "lm_q1q2_score": 0.6851504249169}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cmath>\n#include <functional>\n\n#include \"pyinterp/eigen.hpp\"\n\nnamespace pyinterp::detail::math {\n\n/// Known radial functions.\nenum RadialBasisFunction : uint8_t {\n  Cubic,\n  Gaussian,\n  InverseMultiquadric,\n  Linear,\n  Multiquadric,\n  ThinPlate\n};\n\n//// A radial basis function (RBF) is a real-valued function \u03c6 whose value\n/// depends only on the distance between the input and some fixed point,\n/// either the origin, so that \u03c6(x) = \u03c6(\u2551x\u2551), or some other fixed point\n/// c, called a center, so that \u03c6(x) = \u03c6(\u2551x - c\u2551). Any function \u03c6 that\n/// satisfies the property \u03c6(x) = \u03c6(\u2551x\u2551) is a radial function.\ntemplate <typename T>\nclass RBF {\n public:\n  /// Pointer to the Radial function used\n  using PtrRadialBasisFunction =\n      Matrix<T> (*)(const Eigen::Ref<const Matrix<T>>& r, const T);\n\n  /// Default constructor\n  ///\n  /// @param epsilon Adjustable constant for gaussian or multiquadrics\n  /// functions - defaults to approximate average distance between nodes\n  /// (which is a good start).\n  /// @param smooth Values greater than zero increase the smoothness of the\n  /// approximation. 0 is for interpolation (default), the function will always\n  /// go through the nodal points in this case.\n  /// @param rbf The radial basis function, based on the radius, r, given by the\n  /// norm (Euclidean distance)\n  RBF(const T& epsilon, const T& smooth, const RadialBasisFunction rbf)\n      : epsilon_(T(1) / epsilon), smooth_(smooth) {\n    switch (rbf) {\n      case RadialBasisFunction::Cubic:\n        function_ = &RBF::cubic;\n        break;\n      case RadialBasisFunction::Gaussian:\n        function_ = &RBF::gaussian;\n        break;\n      case RadialBasisFunction::InverseMultiquadric:\n        function_ = &RBF::inverse_multiquadric;\n        break;\n      case RadialBasisFunction::Linear:\n        function_ = &RBF::linear;\n        break;\n      case RadialBasisFunction::Multiquadric:\n        function_ = &RBF::multiquadric;\n        break;\n      case RadialBasisFunction::ThinPlate:\n        function_ = &RBF::thin_plate;\n        break;\n      default:\n        throw std::invalid_argument(\"Radial function unknown: \" +\n                                    std::to_string(static_cast<int>(rbf)));\n    }\n  }\n\n  /// Calculates the interpolated values\n  ///\n  /// @param xk Coordinates of the nodes\n  /// @param yk Values of the nodes\n  /// @param xi Coordinates to evaluate the interpolant at.\n  /// @return interpolated values for each coordinates provided.\n  [[nodiscard]] auto interpolate(const Eigen::Ref<const Matrix<T>>& xk,\n                                 const Eigen::Ref<const Vector<T>>& yk,\n                                 const Eigen::Ref<const Matrix<T>>& xi) const\n      -> Vector<T> {\n    // Matrix of distances between the coordinates provided.\n    const auto r = RBF::distance_matrix(xk, xk);\n\n    // Default epsilon to approximate average distance between nodes\n    const auto epsilon =\n        std::isnan(epsilon_) ? 1 / RBF<T>::average(r) : epsilon_;\n\n    // TODO(fbriol)\n    auto A = function_(r, epsilon);\n\n    // Apply smoothing factor if needed\n    if (smooth_) {\n      A -= Matrix<T>::Identity(xk.cols(), xk.cols()) * smooth_;\n    }\n\n    return function_(distance_matrix(xk, xi), epsilon) *\n           RBF<T>::solve_linear_system(A, yk);\n  }\n\n private:\n  /// Adjustable constant for gaussian or multiquadrics functions\n  T epsilon_;\n\n  /// Smooth factor\n  T smooth_;\n\n  /// Radial bassis function, based on the radius\n  PtrRadialBasisFunction function_;\n\n  // Calculates the distance average excluding the diagonal\n  static auto average(const Eigen::Ref<const Matrix<T>>& distance) -> T {\n    assert(distance.cols() == distance.rows());\n    auto sum = T(0);\n    auto n = distance.cols();\n    for (Eigen::Index ix = 0; ix < distance.rows() - 1; ++ix) {\n      for (Eigen::Index jx = ix + 1; jx < distance.cols(); ++jx) {\n        sum += distance(ix, jx);\n      }\n    }\n    return static_cast<T>(sum / (n * (n - 1) * 0.5));\n  };\n\n  /// Returns the distance between two points in a euclidean space\n  static auto euclidean_distance(const Eigen::Ref<const Vector<T>>& x,\n                                 const Eigen::Ref<const Vector<T>>& y) -> T {\n    return std::sqrt((x - y).array().pow(2).sum());\n  }\n\n  /// Multiquadric\n  static auto multiquadric(const Eigen::Ref<const Matrix<T>>& r,\n                           const T epsilon) -> Matrix<T> {\n    return ((epsilon * r).array().pow(2) + 1).sqrt();\n  }\n\n  /// Inverse multiquadric\n  static auto inverse_multiquadric(const Eigen::Ref<const Matrix<T>>& r,\n                                   const T epsilon) -> Matrix<T> {\n    return 1.0 / multiquadric(r, epsilon).array();\n  }\n\n  /// Gauss\n  static auto gaussian(const Eigen::Ref<const Matrix<T>>& r, const T epsilon)\n      -> Matrix<T> {\n    return (-(epsilon * r).array().pow(2)).exp();\n  }\n\n  /// Linear spline\n  static auto linear(const Eigen::Ref<const Matrix<T>>& r, const T /*epsilon*/)\n      -> Matrix<T> {\n    return r;\n  }\n\n  /// Cubic spline\n  static auto cubic(const Eigen::Ref<const Matrix<T>>& r, const T /*epsilon*/)\n      -> Matrix<T> {\n    return r.array().pow(3);\n  }\n\n  /// Thin plate spline\n  static auto thin_plate(const Eigen::Ref<const Matrix<T>>& r,\n                         const T /*epsilon*/) -> Matrix<T> {\n    return (r.array() == 0).select(0, r.array().pow(2) * r.array().log());\n  }\n\n  /// Calculation of distances between the coordinates provided.\n  static auto distance_matrix(const Eigen::Ref<const Matrix<T>>& xk,\n                              const Eigen::Ref<const Matrix<T>>& xi)\n      -> Matrix<T> {\n    assert(xk.rows() == xi.rows());\n\n    auto result = Matrix<T>(xi.cols(), xk.cols());\n\n    for (Eigen::Index i0 = 0; i0 < xi.cols(); ++i0) {\n      for (Eigen::Index i1 = 0; i1 < xk.cols(); ++i1) {\n        result(i0, i1) = euclidean_distance(xi.col(i0), xk.col(i1));\n      }\n    }\n    return result;\n  }\n\n  /// Resolution of the linear system\n  static auto solve_linear_system(const Matrix<T>& A, const Vector<T>& di)\n      -> Vector<T> {\n    Eigen::FullPivLU<Matrix<T>> lu(A);\n    return lu.solve(di);\n  }\n};\n\n}  // namespace pyinterp::detail::math\n", "meta": {"hexsha": "a8e5f33db79852e3f84847a94958f182365c78cf", "size": 6329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "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/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "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/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "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.792746114, "max_line_length": 80, "alphanum_fraction": 0.6179491231, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6851428136441765}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n    const Eigen::MatrixXd &vertices,\n    std::function<double(const Eigen::Vector2d &)> f) {\n  // Number of nodes of the element: triangles = 3, rectangles = 4\n  const int num_nodes = vertices.cols();\n  // Vector for returning element vector\n  Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n  //====================\n\n  // first two midpoints of edges of cell\n  Eigen::Vector2d m1 = 0.5*(vertices.col(0) + vertices.col(1));\n  Eigen::Vector2d m2 = 0.5*(vertices.col(1) + vertices.col(2));\n\n  // == TRIANGLE ==\n  if (num_nodes == 3) {\n    // Third midpoint of edge\n    Eigen::Vector2d m3 = 0.5*(vertices.col(2) + vertices.col(0));\n    \n    // Area\n    double K = 0.5*( (vertices(0,1) - vertices(0,0)) * (vertices(1,2) - vertices(1,0)) -\n                     (vertices(1,1) - vertices(1,0)) * (vertices(0,2) - vertices(0,0)));\n    K /= num_nodes;\n\n    elem_vec(0) = f(m1) + f(m3);\n    elem_vec(1) = f(m1) + f(m2);\n    elem_vec(2) = f(m2) + f(m3);\n    elem_vec *= K/2.0;\n\n    // == QUADRILITERA ==\n    } else if (num_nodes == 4) {\n    // Third and forth midpoints of edge\n    Eigen::Vector2d m3 = 0.5*(vertices.col(2) + vertices.col(3));\n    Eigen::Vector2d m4 = 0.5*(vertices.col(3) + vertices.col(0));\n    \n    // Area\n    double K = ( vertices(0,1) - vertices(0,0) )*\n               ( vertices(1,3) - vertices(1,0) );\n    K /= num_nodes;\n\n    elem_vec(0) = f(m1) + f(m4);\n    elem_vec(1) = f(m1) + f(m2);\n    elem_vec(2) = f(m2) + f(m3);\n    elem_vec(3) = f(m3) + f(m4);\n    elem_vec *= K/2.0;\n    }\n\n  //====================\n\n  return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace\n\nEigen::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": "af3c184129c271229c6bbce6b0f8ce9e35094cfa", "size": 2614, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.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": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.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": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.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.8085106383, "max_line_length": 88, "alphanum_fraction": 0.6205049732, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6850618796788954}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix4f A = MatrixXf::Random(4,4);\ncout << \"Here is a random 4x4 matrix:\" << endl << A << endl;\nHessenbergDecomposition<MatrixXf> hessOfA(A);\nMatrixXf H = hessOfA.matrixH();\ncout << \"The Hessenberg matrix H is:\" << endl << H << endl;\nMatrixXf Q = hessOfA.matrixQ();\ncout << \"The orthogonal matrix Q is:\" << endl << Q << endl;\ncout << \"Q H Q^T is:\" << endl << Q * H * Q.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "7bd58627a52776c821df0fa0c745b8771aab348b", "size": 542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_matrixH.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_HessenbergDecomposition_matrixH.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_HessenbergDecomposition_matrixH.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.8095238095, "max_line_length": 63, "alphanum_fraction": 0.6420664207, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6850618744664725}}
{"text": "//\n// Created by Daniel on 31.03.2015.\n//\n#include \"stack.h\"\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <sstream>\nusing namespace boost::algorithm;\n\nbool checkParentheses(std::string str) {\n    auto parentheses = stack<char>();\n    for (auto c : str) {\n        if (c == ')' || c == ']' || c == '}' || c == '>') {\n            if (parentheses.isEmpty() || parentheses.pop() != c)\n                return false;\n        }\n        if (c == '(') parentheses.push(')');\n        if (c == '[') parentheses.push(']');\n        if (c == '{') parentheses.push('}');\n        if (c == '<') parentheses.push('>');\n    }\n    return parentheses.isEmpty();\n}\n\nstd::string toBinary(int num) {\n    return toBase(num, 2);\n}\n\nstd::string toBase(int num, int base) {\n    auto digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    auto digitsInBase = stack<char>();\n    while (num > 0) {\n        digitsInBase.push(digits[num % base]);\n        num /= base;\n    }\n\n    auto res = std::string();\n\n    while (!digitsInBase.isEmpty())\n    {\n        res += digitsInBase.pop();\n    }\n\n    return res;\n}\n\nstd::string toPostfix(std::string str) {\n    std::vector<std::string> tokens;\n    split(tokens, str, boost::is_space(), token_compress_on);\n    auto prec = [] (auto str) {\n        if(str == \"+\" || str == \"-\")\n            return 1;\n        if(str == \"*\" || str == \"/\")\n            return 2;\n        return 0;\n    };\n\n    auto operators = stack<std::string>();\n\n    std::stringstream res;\n\n    for (auto token : tokens) {\n        if(token == \"(\")\n            operators.push(token);\n        else if (token == \")\") {\n            auto op = operators.pop();\n            while (op != \"(\") {\n                res << op << \" \";\n                op = operators.pop();\n            };\n        }\n        else if (token == \"+\" || token == \"-\" || token == \"*\" || token == \"/\") {\n            while (!operators.isEmpty() && prec(token) <= prec(operators.peek()))\n                res << operators.pop() << \" \";\n            operators.push(token);\n        }\n        else\n            res << token << \" \";\n    }\n\n    while (!operators.isEmpty())\n        res << operators.pop() << \" \";\n\n    return res.str().erase(res.str().length() - 1);\n}\n\nint evalPostfix(std::string str) {\n    std::vector<std::string> tokens;\n    split(tokens, str, boost::is_space(), token_compress_on);\n    auto evalStack = stack<int>();\n    auto eval = [&](auto binOp) {\n        auto right = evalStack.pop();\n        auto left = evalStack.pop();\n        evalStack.push(binOp(left, right));\n    };\n\n    for(auto token : tokens)\n    {\n        if(token == \"+\") eval([](auto x, auto y) { return x + y; });\n        else if(token == \"-\") eval([](auto x, auto y) { return x - y; });\n        else if(token == \"*\") eval([](auto x, auto y) { return x * y; });\n        else if(token == \"/\") eval([](auto x, auto y) { return x / y; });\n        else evalStack.push(boost::lexical_cast<int>(token));\n    }\n\n    return evalStack.pop();\n}\n", "meta": {"hexsha": "da3906b1ae3acff83a122685924d867c5fb5e1c9", "size": 2981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/stack.cpp", "max_stars_repo_name": "DanielFabian/DataStructuresAndAlgorithms", "max_stars_repo_head_hexsha": "f02924337b88e7f4179740ff05d44f2ec95f2602", "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": "C++/stack.cpp", "max_issues_repo_name": "DanielFabian/DataStructuresAndAlgorithms", "max_issues_repo_head_hexsha": "f02924337b88e7f4179740ff05d44f2ec95f2602", "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": "C++/stack.cpp", "max_forks_repo_name": "DanielFabian/DataStructuresAndAlgorithms", "max_forks_repo_head_hexsha": "f02924337b88e7f4179740ff05d44f2ec95f2602", "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": 27.6018518519, "max_line_length": 81, "alphanum_fraction": 0.4981549815, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.8354835289107307, "lm_q1q2_score": 0.6850073776194322}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2014 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[buffer_point_square\n//` Shows how the point_square strategy can be used as a PointStrategy to create square buffers where the original point lies in the center\n\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n/*<-*/ #include \"../examples_utils/create_svg_buffer.hpp\" /*->*/\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point;\n    typedef boost::geometry::model::polygon<point> polygon;\n\n    // Declare the point_square strategy\n    boost::geometry::strategy::buffer::point_square point_strategy;\n\n    // Declare other strategies\n    boost::geometry::strategy::buffer::distance_symmetric<double> distance_strategy(0.5);\n    boost::geometry::strategy::buffer::join_round join_strategy;\n    boost::geometry::strategy::buffer::end_round end_strategy;\n    boost::geometry::strategy::buffer::side_straight side_strategy;\n\n    // Declare/fill of a multi point\n    boost::geometry::model::multi_point<point> mp;\n    boost::geometry::read_wkt(\"MULTIPOINT((3 3),(3 4),(4 4),(7 3))\", mp);\n\n    // Create the buffer of a multi point\n    boost::geometry::model::multi_polygon<polygon> result;\n    boost::geometry::buffer(mp, result,\n                distance_strategy, side_strategy,\n                join_strategy, end_strategy, point_strategy);\n    /*<-*/ create_svg_buffer(\"buffer_point_square.svg\", mp, result); /*->*/\n\n    return 0;\n}\n\n//]\n\n", "meta": {"hexsha": "d50c99d662c963fc9b35b438b785ceb8d02a3860", "size": 1776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/strategies/buffer_point_square.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "doc/src/examples/strategies/buffer_point_square.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/strategies/buffer_point_square.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 36.2448979592, "max_line_length": 139, "alphanum_fraction": 0.7184684685, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.6850073739425887}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"premiers.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nENREGISTRER_PROBLEME(108, \"Diophantine reciprocals I\") {\n    // In the following equation x, y, and n are positive integers.\n    //\n    //                                          1/x + 1/y = 1/n\n    //\n    // For n = 4 there are exactly three distinct solutions:\n    //\n    //      1/5 + 1/20 = 1/4\n    //      1/6 + 1/12 = 1/4\n    //      1/8 + 1/8 = 1/4\n    //\n    // What is the least value of n for which the number of distinct solutions exceeds one-thousand?\n    //\n    // NOTE: This problem is an easier version of Problem 110; it is strongly advised that you solve this one first.\n    vecteur premiers;\n    premiers::crible23<nombre>(1000000, std::back_inserter(premiers));\n\n    nombre resultat = 0;\n    for (nombre n = 2;; ++n) {\n        std::map<nombre, nombre> decomposition;\n        arithmetique::decomposition(n, premiers, decomposition);\n        nombre solutions = 1;\n        for (const auto &d: decomposition) {\n            solutions *= (2 * d.second + 1);\n        }\n        solutions = (solutions + 1) / 2;\n        if (solutions > 1000) {\n            resultat = n;\n            break;\n        }\n    }\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "a022a59ea7047d11cbe658a273c55b85f0ad3161", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme108.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/probleme108.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/probleme108.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.2, "max_line_length": 116, "alphanum_fraction": 0.5791022811, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6849885785132712}}
{"text": "#include <dlib/matrix.h>\n#include <dlib/optimization.h>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nusing column_vector = dlib::matrix<double, 0, 1>;\n\ndouble f(const column_vector& col) {\n    assert(col.nr() == 2);\n\n    const double x1 = col(0);\n    const double x2 = col(1);\n\n    const double ret = -(x1 - 2) * (x1 - 2) - (x2 - 3) * (x2 - 3) + 5;\n\n    printf(\"func called at x1 = %f, x2 = %f, f = %f\\n\", x1, x2, ret);\n\n    return ret;\n}\n\nint main() {\n    column_vector x = {0, 0};\n\n    double ret = dlib::find_max_bobyqa(\n        f, x, 5, dlib::uniform_matrix<double>(2, 1, -100.0),\n        dlib::uniform_matrix<double>(2, 1, 100.0), 10, 1.E-6, 100);\n\n    cout << x << endl;\n    cout << ret << endl;\n\n    return 0;\n}", "meta": {"hexsha": "23132a05dfb95db1cd75f527921b8155f0228b48", "size": 734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib-test/main.cpp", "max_stars_repo_name": "xwang233/bot-build", "max_stars_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-16T06:28:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-16T06:28:30.000Z", "max_issues_repo_path": "dlib-test/main.cpp", "max_issues_repo_name": "society765/bot-build", "max_issues_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlib-test/main.cpp", "max_forks_repo_name": "society765/bot-build", "max_forks_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_forks_repo_licenses": ["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.5882352941, "max_line_length": 70, "alphanum_fraction": 0.5667574932, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6849885752769691}}
{"text": "#include \"BoostOdeint.hpp\"\n\n#include <Eigen/Core>\n\n#include <tuple>\n#include <iostream>\n\nusing namespace sodes::odeint;\nusing namespace Eigen;\n\n// System to be solved\nArrayXd lorenz(const Ref<ArrayXd> x, Ref<ArrayXd> dxdt, const double &t)\n{\n    double sigma = 10.0;\n    double R = 28.0;\n    double b = 8.0 / 3.0;\n\n    dxdt[0] = sigma * (x[1] - x[0]);\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n\n    return dxdt;\n}\n\nint main (){\n    // Defining the state vector with initial conditions\n    int num_of_states = 3;\n    ArrayXd X(num_of_states);\n    X << 0., 1., 0.1;\n\n    // Set time range and increment\n    auto t_init = 0.0;\n    auto t_final = 10.0;\n    auto t_span = std::make_tuple(t_init, t_final);\n    auto dt = 0.01;\n\n    // Containers to store solution\n    std::vector<ArrayXd> x_sol;\n    std::vector<double> times;\n    std::tie(times, x_sol) = solve_ivp_const(lorenz, t_span, dt, X, \"runge_kutta_cash_karp54\");\n\n    // Displaying result on terminal\n    auto steps = times.size();\n    for (size_t i = 0; i < steps; i++)\n    {\n        std::cout << times[i] << '\\t' << x_sol[i][0] << '\\t' << x_sol[i][1] << '\\t' << x_sol[i][2] << '\\n';\n    }\n}\n", "meta": {"hexsha": "3ed229b7e4090b830ca69cf3574abea98504883f", "size": 1189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/call_sodes_rk4.cpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "examples/boost/call_sodes_rk4.cpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "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/boost/call_sodes_rk4.cpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 24.2653061224, "max_line_length": 107, "alphanum_fraction": 0.5777964676, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6849885744520516}}
{"text": "// TestRandom101.cpp\n//\n// Basic functionality to show how Random works\n//\n// (C) Datasim Education BV 2010-2011\n//\n\n#include <boost/random.hpp> // Convenience header file\n#include <iostream>\n#include <ctime>\t\t\t// std::time\n#include <boost/Random/detail/const_mod.hpp> // LCG class\n\nusing namespace std;\n\ntemplate<class PRNG, class Dist>\ninline boost::variate_generator<PRNG&, Dist> make_gen(PRNG & rng, Dist d)\n{\n  return boost::variate_generator<PRNG&, Dist>(rng, d);\n}\n\n\nint main()\n{\n\t\n\t// Get random number generator\n\tboost::mt19937 rng;\n\trng.seed(static_cast<unsigned int> (std::time(0)));\n\n\tboost::triangle_distribution<> tri(0.0, 0.5, 1.0);\n\t\n\t//boost::lagged_fibonacci607 rng;\n\trng.seed(static_cast<unsigned int> (std::time(0)));\n\tboost::variate_generator<boost::mt19937&, boost::triangle_distribution<> > \n\t\t\t\t\t\t\ttriRng(rng, tri);\n//\tboost::variate_generator<boost::lagged_fibonacci607&, boost::triangle_distribution<> > \n\t//\t\t\t\t\t\ttriRng(rng, tri);\n\n\tfor (int n = 0; n <=100; ++n)\n\t{\n\t\tcout << triRng() << \",\";\n\t}\n\n\treturn 0;\n\n}", "meta": {"hexsha": "2b51c9662732d2d44f47e83282e7e04993472fba", "size": 1037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/04a - Random/TestRandom101.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/04a - Random/TestRandom101.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Level_8/V. An Introduction to the Boost C++ Libraries/04a - Random/TestRandom101.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.0444444444, "max_line_length": 90, "alphanum_fraction": 0.6827386692, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6849435986761924}}
{"text": "#pragma once\n\n#include <cmath>\n#include <cstdint>\n#include <random>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace gaussian_distributions\n{\n/// See https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf\n/// for details on the implementations here.\n\n/// Evaluate the value of the CDF of the gaussian distribution specified by\n/// @param mean and @param std_dev at @param val.\ninline double EvaluateGaussianCDF(\n    const double mean, const double std_dev, const double val)\n{\n  return 0.5 * (1.0 + std::erf(((val - mean) / std_dev) / std::sqrt(2.0)));\n}\n\n/// Evaluate the value of the PDF of the gaussian distribution specified by\n/// @param mean and @param std_dev at @param val.\ninline double EvaluateGaussianPDF(\n    const double mean, const double std_dev, const double val)\n{\n  const double exponent = ((val - mean) * (val - mean))\n                          / (2.0 * std_dev * std_dev);\n  const double fraction = 1.0 / (std_dev * std::sqrt(2.0 * M_PI));\n  const double pdf = fraction * std::exp(-exponent);\n  return pdf;\n}\n\n/// Evaluate the value of the CDF of the truncated gaussian distribution\n/// specified by @param mean and @param std_dev and bounds @param lower_bound\n/// and @param upper_bound at @param val.\ninline double EvaluateTruncatedGaussianCDF(\n    const double mean, const double lower_bound, const double upper_bound,\n    const double std_dev, const double val)\n{\n  if (lower_bound > upper_bound)\n  {\n    throw std::invalid_argument(\"lower_bound > upper_bound\");\n  }\n  if (val <= lower_bound)\n  {\n    return 0.0;\n  }\n  else if (val >= upper_bound)\n  {\n    return 1.0;\n  }\n  else\n  {\n    const double cdf_lower_bound\n        = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n    const double numerator\n        = EvaluateGaussianCDF(mean, std_dev, val) - cdf_lower_bound;\n    const double denominator\n        = EvaluateGaussianCDF(mean, std_dev, upper_bound) - cdf_lower_bound;\n    return numerator / denominator;\n  }\n}\n\n/// Evaluate the value of the PDF of the truncated gaussian distribution\n/// specified by @param mean and @param std_dev and bounds @param lower_bound\n/// and @param upper_bound at @param val.\ninline double EvaluateTruncatedGaussianPDF(\n    const double mean, const double lower_bound, const double upper_bound,\n    const double std_dev, const double val)\n{\n  if (lower_bound > upper_bound)\n  {\n    throw std::invalid_argument(\"lower_bound > upper_bound\");\n  }\n  if (val <= lower_bound)\n  {\n    return 0.0;\n  }\n  else if (val >= upper_bound)\n  {\n    return 0.0;\n  }\n  else\n  {\n    const double cdf_upper = EvaluateGaussianCDF(mean, std_dev, upper_bound);\n    const double cdf_lower = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n    const double probability_enclosed = cdf_upper - cdf_lower;\n    const double gaussian_pdf = EvaluateGaussianPDF(mean, std_dev, val);\n    const double pdf = gaussian_pdf / probability_enclosed;\n    return pdf;\n  }\n}\n\n/// Integrate the probability contained between @param lower_limit and @param\n/// upper_limit for the gaussian distribution specified by @param mean and\n/// @param std_dev.\ninline double IntegrateGaussian(\n    const double mean, const double std_dev, const double lower_limit,\n    const double upper_limit)\n{\n  if (lower_limit > upper_limit)\n  {\n    throw std::invalid_argument(\"lower_limit > upper_limit\");\n  }\n  const double upper_limit_cdf\n      = EvaluateGaussianCDF(mean, std_dev, upper_limit);\n  const double lower_limit_cdf\n      = EvaluateGaussianCDF(mean, std_dev, lower_limit);\n  const double probability = upper_limit_cdf - lower_limit_cdf;\n  return probability;\n}\n\n/// Integrate the probability contained between @param lower_limit and @param\n/// upper_limit for the truncated gaussian distribution specified by @param mean\n/// and @param std_dev and bounds @param lower_bound and @param upper_bound.\ninline double IntegrateTruncatedGaussian(\n    const double mean, const double lower_bound, const double upper_bound,\n    const double std_dev, const double lower_limit, const double upper_limit)\n{\n  if (lower_bound > upper_bound)\n  {\n    throw std::invalid_argument(\"lower_bound > upper_bound\");\n  }\n  if (lower_limit > upper_limit)\n  {\n    throw std::invalid_argument(\"lower_limit > upper_limit\");\n  }\n  const double lower_limit_cdf\n      = EvaluateTruncatedGaussianCDF(\n          mean, lower_bound, upper_bound, std_dev, lower_limit);\n  const double upper_limit_cdf\n      = EvaluateTruncatedGaussianCDF(\n          mean, lower_bound, upper_bound, std_dev, upper_limit);\n  const double probability = upper_limit_cdf - lower_limit_cdf;\n  return probability;\n}\n\n/// Note that comments come from (and refer to) parts of the original R plugin\n/// that this implementation was derived from.\nclass TruncatedGaussianDistribution\n{\nprivate:\n\n  double mean_ = 0.0;\n  double stddev_ = 0.0;\n  double std_lower_bound_ = 0.0;\n  double std_upper_bound_ = 0.0;\n\n  enum class DrawCases {TYPE_1, TYPE_2, TYPE_3, TYPE_4, NONE};\n  DrawCases case_ = NONE;\n  std::uniform_real_distribution<double> uniform_unit_dist_;\n  std::uniform_real_distribution<double> uniform_range_dist_;\n  std::exponential_distribution<double> exponential_dist_;\n  std::normal_distribution<double> normal_dist_;\n\n  bool CheckSimple(const double lower_bound, const double upper_bound) const\n  {\n    // Init Values Used in Inequality of Interest\n    const double val1\n        = (2 * std::sqrt(std::exp(1)))\n          / (lower_bound + std::sqrt(std::pow(lower_bound, 2) + 4));\n    const double val2\n        = std::exp((std::pow(lower_bound, 2)\n                    - lower_bound * std::sqrt(std::pow(lower_bound, 2) + 4))\n                   / (4));\n    if (upper_bound > lower_bound + val1 * val2)\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n  // Naive Accept-Reject algorithm\n  template<typename Generator>\n  double NaiveAcceptReject(\n      const double lower_bound, const double upper_bound, Generator& prng)\n  {\n    while (true)\n    {\n      // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n      // is a call to std::normal_distribution<double>.\n      const double draw = normal_dist_(prng);\n      if ((draw <= upper_bound) && (draw >= lower_bound))\n      {\n          return draw;\n      }\n    }\n  }\n\n  // Accept-Reject Algorithm\n  template<typename Generator>\n  double SimpleAcceptReject(const double lower_bound, Generator& prng)\n  {\n    // Init Values\n    const double alpha\n        = (lower_bound + std::sqrt(std::pow(lower_bound, 2) + 4.0)) / (2.0);\n    while (true)\n    {\n      // In the R plugin, this was a call to Rf_rexp(1.0), in pure C++ it is a\n      // call to std::exponential_distribution<double>.\n      const double e = exponential_dist_(prng);\n      const double z = lower_bound + e / alpha;\n      const double rho = std::exp(-std::pow(alpha - z, 2) / 2);\n      // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n      // is a call to std::normal_distribution<double>.\n      const double u = uniform_unit_dist_(prng);\n      if (u <= rho)\n      {\n        return z;\n      }\n    }\n  }\n\n  // Accept-Reject Algorithm\n  template<typename Generator>\n  double ComplexAcceptReject(\n      const double lower_bound, const double upper_bound, Generator& prng)\n  {\n    while (true)\n    {\n      // In the R plugin, this was a call to Rf_rnorm(lower_bound, upper_bound),\n      // in pure C++ it is a call to std::normal_distribution<double>.\n      const double z = uniform_range_dist_(prng);\n      double rho = 0.0;\n      if (0 < lower_bound)\n      {\n        rho = std::exp((std::pow(lower_bound, 2) - std::pow(z, 2)) / 2);\n      }\n      else if (upper_bound < 0)\n      {\n        rho = std::exp((std::pow(upper_bound, 2) - std::pow(z, 2)) / 2);\n      }\n      else if (0 < upper_bound && lower_bound < 0)\n      {\n        rho = std::exp(-std::pow(z, 2) / 2);\n      }\n      // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n      // is a call to std::normal_distribution<double>.\n      const double u = uniform_unit_dist_(prng);\n      if (u <= rho)\n      {\n        return z;\n      }\n    }\n  }\n\n  template<typename Generator>\n  double Sample(Generator& prng)\n  {\n    if (case_ == DrawCases::TYPE_1)\n    {\n      const double draw\n          = NaiveAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n      return mean_ + stddev_ * draw;\n    }\n    else if (case_ == DrawCases::TYPE_2)\n    {\n      const double draw = SimpleAcceptReject(std_lower_bound_, prng);\n      return mean_ + stddev_ * draw;\n    }\n    else if (case_ == DrawCases::TYPE_3)\n    {\n      while (true)\n      {\n        const double draw = SimpleAcceptReject(std_lower_bound_, prng);\n        if (draw <= std_upper_bound_)\n        {\n          return mean_ + stddev_ * draw;\n        }\n      }\n    }\n    else if (case_ == DrawCases::TYPE_4)\n    {\n      const double draw\n          = ComplexAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n      return mean_ + stddev_ * draw;\n    }\n    else\n    {\n      if (case_ == DrawCases::NONE)\n      {\n        return mean_;\n      }\n      else\n      {\n        throw std::runtime_error(\"Invalid case\");\n      }\n    }\n  }\n\npublic:\n\n  TruncatedGaussianDistribution(\n      const double mean, const double stddev, const double lower_bound,\n      const double upper_bound)\n    : uniform_unit_dist_(0.0, 1.0),\n      uniform_range_dist_(lower_bound, upper_bound),\n      exponential_dist_(1.0), normal_dist_(0.0, 1.0)\n  {\n    // Set operating parameters\n    mean_ = mean;\n    stddev_ = stddev;\n    if (std::abs(stddev_) == 0.0)\n    {\n      case_ = DrawCases::NONE;\n    }\n    else\n    {\n      // Standardize the lower and upper bounds\n      std_lower_bound_ = (lower_bound - mean_) / stddev_;\n      std_upper_bound_ = (upper_bound - mean_) / stddev_;\n      // Set the operating case - i.e. which sampling method we will use\n      case_ = DrawCases::NONE;\n      if (0.0 <= std_upper_bound_ && 0.0 >= std_lower_bound_)\n      {\n        case_ = DrawCases::TYPE_1;\n      }\n      if (0.0 < std_lower_bound_\n          && std_upper_bound_ == std::numeric_limits<double>::infinity())\n      {\n        case_ = DrawCases::TYPE_2;\n      }\n      if (0.0 > std_upper_bound_\n          && std_lower_bound_ == -std::numeric_limits<double>::infinity())\n      {\n        std_lower_bound_ = -1 * std_upper_bound_;\n        std_upper_bound_ = std::numeric_limits<double>::infinity();\n        stddev_ = -1 * stddev_;\n        case_ = DrawCases::TYPE_2;\n      }\n      if ((0.0 > std_upper_bound_ || 0.0 < std_lower_bound_)\n          && !(std_upper_bound_ == std::numeric_limits<double>::infinity()\n               || std_lower_bound_ == -std::numeric_limits<double>::infinity()))\n      {\n        if (CheckSimple(std_lower_bound_, std_upper_bound_))\n        {\n          case_ = DrawCases::TYPE_3;\n        }\n        else\n        {\n          case_ = DrawCases::TYPE_4;\n        }\n      }\n      if ((case_ != DrawCases::TYPE_1) && (case_ != DrawCases::TYPE_2)\n          && (case_ != DrawCases::TYPE_3) && (case_ != DrawCases::TYPE_4))\n      {\n        throw std::invalid_argument(\"case cannot be NONE with stddev == 0\");\n      }\n    }\n  }\n\n  template<typename Generator>\n  double operator()(Generator& prng)\n  {\n    return Sample(prng);\n  }\n};\n\n/// Simple multivariate gaussian distribution.\nclass MultivariteGaussianDistribution\n{\nprivate:\n  const Eigen::VectorXd mean_;\n  const Eigen::MatrixXd norm_transform_;\n\n  std::normal_distribution<double> unit_gaussian_dist_;\n\n  template<typename Generator>\n  Eigen::VectorXd Sample(Generator& prng)\n  {\n    Eigen::VectorXd draw;\n    draw.resize(mean_.rows());\n    for (ssize_t idx = 0; idx < draw.rows(); idx++)\n    {\n      draw(idx) = unit_gaussian_dist_(prng);\n    }\n    return norm_transform_ * draw + mean_;\n  }\n\n  static Eigen::MatrixXd CalculateNormTransform(\n      const Eigen::MatrixXd& covariance)\n  {\n    Eigen::MatrixXd norm_transform;\n    Eigen::LLT<Eigen::MatrixXd> chol_solver(covariance);\n    if (chol_solver.info() == Eigen::Success)\n    {\n      // Use cholesky solver\n      norm_transform = chol_solver.matrixL();\n    }\n    else\n    {\n      // Use eigen solver\n      Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(covariance);\n      norm_transform\n          = eigen_solver.eigenvectors()\n            * eigen_solver.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal();\n    }\n    return norm_transform;\n  }\n\npublic:\n  MultivariteGaussianDistribution(\n      const Eigen::VectorXd& mean, const Eigen::MatrixXd& covariance)\n      : mean_(mean), norm_transform_(CalculateNormTransform(covariance)),\n        unit_gaussian_dist_(0.0, 1.0)\n  {\n    if (mean_.rows() != covariance.rows() || mean_.cols() != covariance.cols())\n    {\n      throw std::invalid_argument(\"mean and covariance are different sizes\");\n    }\n    const auto nan_check = [] (const double& val) { return std::isnan(val); };\n    if ((norm_transform_.unaryExpr(nan_check)).any())\n    {\n      throw std::runtime_error(\n          \"NaN Found in norm_transform in MultivariateGaussianDistribution\");\n    }\n    const auto inf_check = [] (const double& val) { return std::isinf(val); };\n    if ((norm_transform_.unaryExpr(inf_check)).any())\n    {\n      throw std::runtime_error(\n          \"Inf Found in norm_transform in MultivariateGaussianDistribution\");\n    }\n  }\n\n  template<typename Generator>\n  Eigen::VectorXd operator()(Generator& prng)\n  {\n    return Sample(prng);\n  }\n};\n}  // namespace gaussian_distributions\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "438f308b88a0d5c8aacdfa0a8909c45566561073", "size": 13464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/gaussian_distributions.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/gaussian_distributions.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/gaussian_distributions.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": 30.6697038724, "max_line_length": 80, "alphanum_fraction": 0.6530005942, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6849435986761924}}
{"text": "#include <iostream>\n\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(int argc, char **argv){\n\n    Matrix<float, 10, 10> originMat = Matrix<float, 10, 10>::Random(10, 10);\n    cout << \"original matrix: \\n\" << originMat << endl;\n\n    Matrix<float, 3, 3> eyeMat = Matrix<float, 3, 3>::Identity(3,3);\n    cout << \"3x3 identity matrix: \\n\" << eyeMat << endl;\n\n    originMat.block<3, 3>(0, 0) = eyeMat;\n    cout << \"original matrix with 3x3 identity block: \\n\" << originMat << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "3550847577c7cd49c0c854faf5aaf0b163b9702e", "size": 547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/exercise/ex_5.cpp", "max_stars_repo_name": "carmelocs/slambook2", "max_stars_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_stars_repo_licenses": ["MIT"], "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/exercise/ex_5.cpp", "max_issues_repo_name": "carmelocs/slambook2", "max_issues_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_issues_repo_licenses": ["MIT"], "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/exercise/ex_5.cpp", "max_forks_repo_name": "carmelocs/slambook2", "max_forks_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_forks_repo_licenses": ["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.7826086957, "max_line_length": 79, "alphanum_fraction": 0.6288848263, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6849435798834428}}
{"text": "/*!\n * @file basis_q1.hpp\n * @brief Contains implementation of \\f$Q_1\\f$-basis functions for a given quadrilateral.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_BASIS_Q1_HPP_\n#define INCLUDE_BASIS_Q1_HPP_\n\n// Deal.ii\n#include <deal.II/base/function.h>\n\n#include <deal.II/lac/full_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class BasisQ1\n * @brief Class implements scalar \\f$Q_1\\f$-basis functions for a given quadrilateral.\n */\ntemplate <int dim>\nclass BasisQ1 : public Function<dim>\n{\npublic:\n\tBasisQ1();\n\n\tvoid set_index (unsigned int index);\n\n\tvoid set_coeff(const typename Triangulation<dim>::active_cell_iterator &cell);\n\n\tvirtual double value(const Point<dim> &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\nprivate:\n\t/*!\n\t * Index of current basis function to be evaluated.\n\t */\n\tunsigned int \t\tindex_basis;\n\n\t/*!\n\t * Matrix columns hold coefficients of basis functions.\n\t */\n\tFullMatrix<double>\tcoeff_matrix;\n\tbool is_set_coeff_matrix;\n};\n\n\n/*!\n * Constructor.\n * @param cell\n */\ntemplate<int dim>\nBasisQ1<dim>::BasisQ1 ()\n:\nFunction<dim>(),\nindex_basis(0),\ncoeff_matrix(FullMatrix<double>(std::pow(2,dim),std::pow(2,dim))),\nis_set_coeff_matrix(false)\n{\n}\n\n\n\n/*!\n * Set the coefficients. Template specialization \\f$dim=2\\f$.\n * @param cell\n *\n * Build up coefficient matrix \\f$A=(a_{ij})\\f$ for basis polynomial\n * \\f$\\varphi_i(x,y)=a_i^0 + a_i^1 x + a_i^2 y + a_i^3 xy \\f$. The \\f$i\\f$-th column\n * of the matrix hence contains the coefficients for the \\f$i\\f$-th basis associated\n * to the \\f$i\\f$-th vertex.\n */\ntemplate<>\nvoid\nBasisQ1<2>::set_coeff (const typename Triangulation<2>::active_cell_iterator &cell)\n\n{\n\tFullMatrix<double>\tpoint_matrix(4,4);\n\n\tfor (unsigned int i=0; i<4; ++i)\n\t{\n\t\tconst Point<2>& p = cell->vertex(i);\n\n\t\tpoint_matrix(i,0) = 1;\n\t\tpoint_matrix(i,1) = p(0);\n\t\tpoint_matrix(i,2) = p(1);\n\t\tpoint_matrix(i,3) = p(0)*p(1);\n\t}\n\n\t// Columns of coeff_matrix are the coefficients of the polynomial\n\tcoeff_matrix.invert (point_matrix);\n\n\tis_set_coeff_matrix = true;\n}\n\n\n/*!\n * Set the coefficients. Template specialization \\f$dim=3\\f$.\n * @param cell\n *\n * Build up coefficient matrix \\f$A=(a_{ij})\\f$ for basis polynomial\n * \\f$\\varphi_i(x,y)=a_i^0 + a_i^1 x + a_i^2 y + a_i^3 xy \\f$. The \\f$i\\f$-th column\n * of the matrix hence contains the coefficients for the \\f$i\\f$-th basis associated\n * to the \\f$i\\f$-th vertex.\n */\ntemplate<>\nvoid\nBasisQ1<3>::set_coeff (const typename Triangulation<3>::active_cell_iterator &cell)\n{\n\tFullMatrix<double>\tpoint_matrix(8,8);\n\n\tfor (unsigned int i=0; i<8; ++i)\n\t{\n\t\tconst Point<3>& p = cell->vertex(i);\n\n\t\tpoint_matrix(i,0) = 1;\n\t\tpoint_matrix(i,1) = p(0);\n\t\tpoint_matrix(i,2) = p(1);\n\t\tpoint_matrix(i,3) = p(2);\n\t\tpoint_matrix(i,4) = p(0)*p(1);\n\t\tpoint_matrix(i,5) = p(1)*p(2);\n\t\tpoint_matrix(i,6) = p(0)*p(2);\n\t\tpoint_matrix(i,7) = p(0)*p(1)*p(2);\n\t}\n\n\t// Columns of coeff_matrix are the coefficients of the polynomial\n\tcoeff_matrix.invert (point_matrix);\n\n\tis_set_coeff_matrix = true;\n}\n\n\n/*!\n * Set the index of the basis function to be evaluated.\n *\n * @param index\n */\ntemplate<int dim>\nvoid\nBasisQ1<dim>::set_index (unsigned int index)\n{\n\tindex_basis = index;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index at one given point in 2D.\n *\n * @param p\n * @param component\n */\ntemplate<>\ndouble\nBasisQ1<2>::value (const Point<2> &p,\n\t\t\t\t\tconst unsigned int /* component */) const\n{\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tdouble value = coeff_matrix(0,index_basis)\n\t\t\t\t\t+ coeff_matrix(1,index_basis)*p(0)\n\t\t\t\t\t+ coeff_matrix(2,index_basis)*p(1)\n\t\t\t\t\t+ coeff_matrix(3,index_basis)*p(0)*p(1);\n\n\treturn value;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index at one given point in 3D.\n *\n * @param p\n * @param component\n */\ntemplate<>\ndouble\nBasisQ1<3>::value (const Point<3> &p,\n\t\t\t\t\tconst unsigned int /* component */) const\n{\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tdouble value = coeff_matrix(0,index_basis)\n\t\t\t\t\t+ coeff_matrix(1,index_basis)*p(0)\n\t\t\t\t\t+ coeff_matrix(2,index_basis)*p(1)\n\t\t\t\t\t+ coeff_matrix(3,index_basis)*p(2)\n\t\t\t\t\t+ coeff_matrix(4,index_basis)*p(0)*p(1)\n\t\t\t\t\t+ coeff_matrix(5,index_basis)*p(1)*p(2)\n\t\t\t\t\t+ coeff_matrix(6,index_basis)*p(0)*p(2)\n\t\t\t\t\t+ coeff_matrix(7,index_basis)*p(0)*p(1)*p(2);\n\n\treturn value;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index on a given set of points in 2D.\n *\n * @param points\n * @param values\n */\ntemplate<>\nvoid\nBasisQ1<2>::value_list(const std::vector<Point<2>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p] = coeff_matrix(0,index_basis)\n\t\t\t\t\t\t\t+ coeff_matrix(1,index_basis)*points[p](0)\n\t\t\t\t\t\t\t+ coeff_matrix(2,index_basis)*points[p](1)\n\t\t\t\t\t\t\t+ coeff_matrix(3,index_basis)*points[p](0)*points[p](1);\n\n\t} // end ++p\n}\n\n\n/*!\n * Evaluate a basis function with a preset index on a given set of points in 3D.\n *\n * @param points\n * @param values\n */\ntemplate<>\nvoid\nBasisQ1<3>::value_list(const std::vector<Point<3>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p] = coeff_matrix(0,index_basis)\n\t\t\t\t\t\t\t+ coeff_matrix(1,index_basis)*points[p](0)\n\t\t\t\t\t\t\t+ coeff_matrix(2,index_basis)*points[p](1)\n\t\t\t\t\t\t\t+ coeff_matrix(3,index_basis)*points[p](2)\n\t\t\t\t\t\t\t+ coeff_matrix(4,index_basis)*points[p](0)*points[p](1)\n\t\t\t\t\t\t\t+ coeff_matrix(5,index_basis)*points[p](1)*points[p](2)\n\t\t\t\t\t\t\t+ coeff_matrix(6,index_basis)*points[p](0)*points[p](2)\n\t\t\t\t\t\t\t+ coeff_matrix(7,index_basis)*points[p](0)*points[p](1)*points[p](2);\n\n\t} // end ++p\n}\n\n} // end namespace Coefficients\n\n#endif /* INCLUDE_BASIS_Q1_HPP_ */\n", "meta": {"hexsha": "67c9ab04bd9f21e92862b416cbc7028df356b3f2", "size": 6575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/basis_q1.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/basis_q1.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/basis_q1.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": 23.9090909091, "max_line_length": 89, "alphanum_fraction": 0.6714828897, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229961215457, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6848314962820347}}
{"text": "#pragma once\n#include \"dirichlet_boundary.hpp\"\n#include \"dofs.hpp\"\n#include \"load_vector_assembly.hpp\"\n#include \"stiffness_matrix_assembly.hpp\"\n#include <Eigen/Core>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n#include <string>\n#include <tuple>\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] quadraticDofs containing mesh data\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 QDofs &quadraticDofs,\n                       const std::function<double(double, double)> &f) {\n\t// get quadratic dofs\n\tEigen::MatrixXi qdof;\n\tint             N = quadraticDofs.get_dofs(qdof);\n\n\t// get mesh vertices\n\tconst Eigen::MatrixXd &vertices = quadraticDofs.get_vertices();\n\n\tSparseMatrix A;\n\t// (write your solution here)\n\tassembleStiffnessMatrix(A, vertices, qdof, N);\n\n\tVector F;\n\t// (write your solution here)\n\tassembleLoadVector(F, vertices, qdof, N, f);\n\n\tu.resize(N);\n\tu.setZero();\n\tEigen::VectorXi interiorDofs;\n\n\tauto zerobc = [](double x, double y) {\n\t\tstd::ignore = x;\n\t\tstd::ignore = y;\n\t\treturn 0;\n\t};\n\t// set homogeneous Dirichlet Boundary conditions\n\tsetDirichletBoundary(u, interiorDofs, quadraticDofs, zerobc);\n\tF -= A * u;\n\n\tSparseMatrix AInterior;\n\tigl::slice(A, interiorDofs, interiorDofs, AInterior);\n\tEigen::SimplicialLDLT<SparseMatrix> solver;\n\n\tVector FInterior;\n\tigl::slice(F, interiorDofs, FInterior);\n\n\t//initialize solver for AInterior\n\t// (write your solution here)\n\tsolver.compute(AInterior);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix\");\n\t}\n\n\t//solve interior system\n\t// (write your solution here)\n\tVector uInterior = solver.solve(FInterior);\n\tigl::slice_into(uInterior, interiorDofs, u);\n\n\treturn interiorDofs.size();\n}\n//----------------solveEnd----------------\n", "meta": {"hexsha": "c9aefbd9cc800ec0d7c33a742f3b5bdc655407f1", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/fem_solve.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/fem_solve.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/fem_solve.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": 26.84, "max_line_length": 72, "alphanum_fraction": 0.6810730253, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6848167141661192}}
{"text": "#include \"reverse.hpp\"\n#include \"forward.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n\nnamespace autodiff {\n\n/**\n * Set the value and derivative of the specified function at the\n * specified input.  The functor must define the method\n * `dual<double> operator()(const dual<double>& x) const;`\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] y function applied to input\n * @param[out] dy_dx derivative of y w.r.t. x\n */\ntemplate <typename F>\nvoid derivative(const F& f, double x, double& y, double& dy_dx) {\n  dual<double> xd{ x, 1 };\n  auto yd = f(xd);\n  y = yd.val();\n  dy_dx = yd.tan();\n}\n\n\n/**\n * Set the value and gradient of the specified function at the\n * specified input.  The functor must define the method\n * `adj operator()(const Eigen::Matrix<adj, -1, 1>& x) const;`.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] fx function applied to input\n * @param[out] grad gradient of function applied to input\n */\ntemplate <typename F>\nvoid gradient(const F& f, const Eigen::VectorXd& x,\n              double& fx, Eigen::RowVectorXd& grad) {\n  Eigen::Matrix<adj, -1, 1> xa(x.size());\n  for (int i = 0; i < xa.size(); ++i)\n    xa(i) = x(i);\n  adj y = f(xa);\n  std::vector<double> adjoints = chain(y);\n  fx = y.val();\n  grad.resize(x.size());\n  for (int i = 0; i < x.size(); ++i)\n    grad(i) = adjoints[xa(i).idx()];\n}\n\n/**\n * Set the value of the specified function at the specified value and\n * the product of the gradient of the function at the specified value\n * and the specified vector.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[in] v vector to multiply\n * @param[out] fx value of f(x)\n * @param[out] gradv product of gradient of f(x) and v\n */\ntemplate <typename F>\nvoid vector_gradient_product(const F& f, const Eigen::VectorXd& x,\n                             const Eigen::VectorXd v, double& fx,\n                             double& gradv) {\n  Eigen::Matrix<dual<double>, -1, 1> xd(x.size());\n  for (int i = 0; i < xd.size(); ++i)\n    xd(i) = { x(i), v(i) };\n  dual<double> fxd = f(xd);\n  fx = fxd.val();\n  gradv = fxd.tan();\n}\n\n/**\n * Set the specified Hessian matrix to the Hessian of the specified\n * function at the specified value.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] H set to Hessian of function at input\n */\ntemplate <typename F>\nvoid hessian(const F& f, const Eigen::VectorXd& x, Eigen::MatrixXd& H) {\n  int N = x.size();\n  H.resize(N, N);\n  for (int m = 0; m < N; ++m) {  // m-th row of H\n    Eigen::Matrix<dual<adj>, -1, 1> xd(N);\n    for (int n = 0; n < N; ++n)\n      xd(n) = { x(n), m == n };  // d.x(n)/d.x(m) = 1 iff m == n\n    auto y = f(xd);\n    std::vector<double> adjoints = chain(y.tan());\n    for (int n = 0; n < N; ++n)\n      H(m, n) = adjoints[xd(n).val().idx()];  // = bar(dot(x[m, n]))\n  }\n}\n\n}\n", "meta": {"hexsha": "4aba3ac658ae01a24664aa47af7634b6839208ac", "size": 2954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/functional.hpp", "max_stars_repo_name": "mortonjt/ad-handbook", "max_stars_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2020-01-14T23:18:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T19:57:08.000Z", "max_issues_repo_path": "cpp/functional.hpp", "max_issues_repo_name": "mortonjt/ad-handbook", "max_issues_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-01-15T11:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T20:12:19.000Z", "max_forks_repo_path": "cpp/functional.hpp", "max_forks_repo_name": "mortonjt/ad-handbook", "max_forks_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2020-01-16T04:04:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-13T12:42:58.000Z", "avg_line_length": 28.6796116505, "max_line_length": 72, "alphanum_fraction": 0.6032498307, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6847831154337717}}
{"text": "#include <Eigen/Core>\n\n#include \"quaternion_product.h\"\n\n/*\n  Assume quaternion data format is (x, y, z, w) and translational format is (x,\n  y, z)\n\n  Verifies against Eigen cross product implementation\n*/\n\n__attribute__((always_inline)) Eigen::Vector3f crossProduct(Eigen::Vector3f lhs,\n                                     Eigen::Vector3f rhs) {\n\n  Eigen::Vector3f result(\n      lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1),\n      lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2),\n      lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0));\n  return result;\n}\n\n/*\n  Computes the point product\n*/\n__attribute__((always_inline)) Eigen::Vector3f pointProduct(Eigen::Vector4f &q,\n                                     Eigen::Vector3f &p) {\n  Eigen::Vector3f qvec(q(0), q(1), q(2));\n\n  Eigen::Vector3f uv = crossProduct(qvec, p); // qvec.cross(p);\n  for (int i = 0; i < 3; i++) {\n    uv(i) = uv(i) * 2;\n  }\n  Eigen::Vector3f qxuv = crossProduct(qvec, uv); // qvec.cross(uv);\n\n  Eigen::Vector3f result;\n  result = p + (q(3) * uv) + qxuv;\n\n  return result;\n}\n\n/*\n  Takes two quaternions and multiplies them together\n\n  Verified against the SE3 product in Sophus\n*/\nSE3T quaternionProduct(SE3T &a, SE3T &b) {\n  Eigen::Vector3f resultTranslation;\n  Eigen::Vector4f resultQuaternion;\n\n  Eigen::Vector4f aq = a.quaternion;\n  Eigen::Vector4f bq = b.quaternion;\n\n  // Hamilton product\n  resultQuaternion(3) =\n      aq(3) * bq(3) - aq(0) * bq(0) - aq(1) * bq(1) - aq(2) * bq(2);\n  resultQuaternion(0) =\n      aq(3) * bq(0) + aq(0) * bq(3) + aq(1) * bq(2) - aq(2) * bq(1);\n  resultQuaternion(1) =\n      aq(3) * bq(1) + aq(1) * bq(3) + aq(2) * bq(0) - aq(0) * bq(2);\n  resultQuaternion(2) =\n      aq(3) * bq(2) + aq(2) * bq(3) + aq(0) * bq(1) - aq(1) * bq(0);\n\n  Eigen::Vector3f r = pointProduct(a.quaternion, b.translation);\n\n  resultTranslation = a.translation + r;\n\n  SE3T result = {resultQuaternion, resultTranslation};\n  return result;\n}\n", "meta": {"hexsha": "253ba8e5c4a119b3caed1165262d18d552e7654d", "size": 1955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_stars_repo_name": "sgpthomas/diospyros", "max_stars_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-16T22:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T04:17:19.000Z", "max_issues_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_issues_repo_name": "sgpthomas/diospyros", "max_issues_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T15:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T19:48:43.000Z", "max_forks_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_forks_repo_name": "sgpthomas/diospyros", "max_forks_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T20:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T20:35:15.000Z", "avg_line_length": 27.9285714286, "max_line_length": 80, "alphanum_fraction": 0.6040920716, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6847831014650312}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/diff.hpp>\n#include <fcppt/math/pi.hpp>\n#include <fcppt/math/vector/angle_between.hpp>\n#include <fcppt/math/vector/angle_between_cast.hpp>\n#include <fcppt/math/vector/componentwise_equal.hpp>\n#include <fcppt/math/vector/hypersphere_to_cartesian.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/math/vector/signed_angle_between.hpp>\n#include <fcppt/math/vector/signed_angle_between_cast.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\ntypedef\nfloat\nreal;\n\nreal const\nepsilon(\n\tstd::numeric_limits<\n\t\treal\n\t>::epsilon()\n);\n\ntypedef\nfcppt::math::vector::static_<\n\tunsigned,\n\t2\n>\nuivector2;\n\ntypedef\nfcppt::math::vector::static_<real,1>\nfvector1;\n\ntypedef\nfcppt::math::vector::static_<real,2>\nfvector2;\n\ntypedef\nfcppt::math::vector::static_<real,3>\nfvector3;\n\ntemplate<typename T>\nbool\ncompare(\n\tT const &t1,\n\tT const &t2)\n{\n\treturn fcppt::math::diff(t1, t2) < epsilon;\n}\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(vector_angle_between)\n{\nFCPPT_PP_POP_WARNING\n\n\tfvector2 const\n\t\tvec1(1.f, 0.f),\n\t\tvec2(0.f, 1.f);\n\n\tBOOST_CHECK(\n\t\t::compare(\n\t\t\tfcppt::math::vector::angle_between(\n\t\t\t\tvec1,\n\t\t\t\tvec2\n\t\t\t),\n\t\t\tfcppt::math::pi<real>() / 2.f\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(vector_angle_between_cast)\n{\nFCPPT_PP_POP_WARNING\n\n\tuivector2 const\n\t\tvec1(1u, 0u),\n\t\tvec2(0u, 1u);\n\n\tBOOST_CHECK(\n\t\t::compare(\n\t\t\tfcppt::math::vector::angle_between_cast<\n\t\t\t\treal\n\t\t\t>(\n\t\t\t\tvec1,\n\t\t\t\tvec2\n\t\t\t),\n\t\t\tfcppt::math::pi<real>() / 2.f\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(vector_signed_angle_between)\n{\nFCPPT_PP_POP_WARNING\n\n\tfvector2 const\n\t\tvec1(2.f, 1.f),\n\t\tvec2(2.f, 2.f);\n\n\tBOOST_CHECK(\n\t\t::compare(\n\t\t\tfcppt::math::vector::signed_angle_between(\n\t\t\t\tvec1,\n\t\t\t\tvec2\n\t\t\t),\n\t\t\tfcppt::math::pi<real>() / 2.f\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(vector_signed_angle_between_cast)\n{\nFCPPT_PP_POP_WARNING\n\n\tuivector2 const\n\t\tvec1(2u, 1u),\n\t\tvec2(2u, 2u);\n\n\tBOOST_CHECK(\n\t\t::compare(\n\t\t\tfcppt::math::vector::signed_angle_between_cast<\n\t\t\t\treal\n\t\t\t>(\n\t\t\t\tvec1,\n\t\t\t\tvec2\n\t\t\t),\n\t\t\tfcppt::math::pi<real>() / 2.f\n\t\t)\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(vector_hypersphere_to_cartesian)\n{\nFCPPT_PP_POP_WARNING\n\n\treal const\n\t\tphi1 =\n\t\t\tfcppt::literal<real>(1.5),\n\t\tphi2 =\n\t\t\tfcppt::literal<real>(0.5);\n\n\tfvector2 const result2 =\n\t\tfcppt::math::vector::hypersphere_to_cartesian(\n\t\t\tfvector1(\n\t\t\t\tphi1));\n\n\tfvector3 const result3 =\n\t\tfcppt::math::vector::hypersphere_to_cartesian(\n\t\t\tfvector2(\n\t\t\t\tphi1,\n\t\t\t\tphi2));\n\n\tstd::cout\n\t\t<< \"Testing the result of 2D hypersphere_to_cartesian.\\n\"\n\t\t<< \"The result should be:\\n\"\n\t\t<<\n\t\t\tfvector2(\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi1),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1))\n\t\t<< \"\\n and it is:\\n\"\n\t\t<< result2\n\t\t<< \"\\n\";\n\n\tBOOST_CHECK(\n\t\tfcppt::math::vector::componentwise_equal(\n\t\t\tresult2,\n\t\t\tfvector2(\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi1),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1)),\n\t\t\tepsilon));\n\n\tstd::cout\n\t\t<< \"Testing the result of 3D hypersphere_to_cartesian.\\n\"\n\t\t<< \"The result should be:\\n\"\n\t\t<<\n\t\t\tfvector3(\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi1),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1) *\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi2),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1) *\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi2))\n\t\t<< \"\\n and it is:\\n\"\n\t\t<< result3\n\t\t<< \"\\n\";\n\n\tBOOST_CHECK(\n\t\tfcppt::math::vector::componentwise_equal(\n\t\t\tresult3,\n\t\t\tfvector3(\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi1),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1) *\n\t\t\t\tstd::cos(\n\t\t\t\t\tphi2),\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi1) *\n\t\t\t\tstd::sin(\n\t\t\t\t\tphi2)),\n\t\t\tepsilon));\n}\n", "meta": {"hexsha": "5ee3894822e25b27ecb4d771debccb79d5aad690", "size": 4144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/vector.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/vector.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/vector.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.9836065574, "max_line_length": 61, "alphanum_fraction": 0.6759169884, "num_tokens": 1379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6847621268899745}}
{"text": "/*\nCopyright (C) 2012 Mathias Eitz and Ronald Richter.\nAll rights reserved.\n\nThis file is part of the imdb library and is made available under\nthe terms of the BSD license (see the LICENSE file).\n*/\n\n#ifndef DISTANCE_HPP\n#define DISTANCE_HPP\n\n#include <cmath>\n#include <limits>\n#include <iterator>\n\n#include <boost/function.hpp>\n\n#include \"../util/types.hpp\"\n\n// ----------------------------------------------------------------\n// Note: only distance metrics allowed here, i.e. functions that\n// describe the distance between two descriptors and thus smaller\n// distances denote more similar objects. The dotproduct itself\n// e.g. is NOT a distance measure, it is a similarity measure\n// ----------------------------------------------------------------\n\n\nnamespace imdb\n{\n\n\n/**\n * \\addtogroup distfn\n * @{\n */\n\n\n/// L1 norm\ntemplate <class T, class R = float>\nstruct l1norm\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    /// L1 distance between a and b.\n    R operator() (const T& a, const T& b) const\n    {\n        R s = 0;\n        for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n        {\n            R d = static_cast<R>(*ai) - static_cast<R>(*bi);\n            s += std::abs(d);\n        }\n        return s;\n    }\n};\n\n\n/**\n * @brief Squared L2 (Euclidean) distance function.\n *\n * Using the squared Euclidean distance is a bit faster than the L2 norm as we avoid the call to sqrt.\n */\ntemplate <class T, class R = float>\nstruct l2norm_squared\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    /// Squared L2 distance between a and b.\n    R operator() (const T& a, const T& b) const\n    {\n        R s = 0;\n        for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n        {\n            R d = static_cast<R>(*ai) - static_cast<R>(*bi);\n            s += d*d;\n        }\n        return s;\n    }\n};\n\n\n/**\n * @brief L2 (Euclidean) distance function\n */\ntemplate <class T, class R = float>\nstruct l2norm\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    l2norm_squared<T,R> n;\n\n    /// L2 (Euclidean) distance between a and b.\n    R operator() (const T& a, const T& b) const\n    {\n        return std::sqrt(n(a,b));\n    }\n};\n\n\n\n/**\n * @brief One minus dot product distance function.\n *\n * 1 - <a,b> distance function. Assumes a and b are two vectors in R^d\n * having \\b unit length\n */\ntemplate <class T, class R = float>\nstruct one_minus_dot\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    /// Computes 1 - <a,b>. As we assume that both a and b have unit length, the\n    /// result is guaranteed to lie in [0,2]\n    R operator() (const T& a, const T& b) const\n    {\n        R s = 0;\n        for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n        {\n            s += static_cast<R>(*ai) * static_cast<R>(*bi);\n        }\n        return (1.0 - s);\n    }\n};\n\n/// Jensen-Shannon divergence\ntemplate <class T, class R = float>\nstruct jsd\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    R operator() (const T& a, const T& b) const\n    {\n        R s = 0;\n        for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n        {\n            R v0 = *ai;\n            R v1 = *bi;\n            R n = 2.0 / (v0 + v1);\n\n            s += ((v0 > 0.0) ? v0 * std::log(v0*n):0.0) + ((v1 > 0.0) ? v1 * std::log(v1*n):0.0);\n        }\n        return s;\n    }\n};\n\n\n\n/**\n * @brief Chi squared distance function.\n *\n * Chi squared distance function between two vectors k and h; d = sum_i[(ai - bi)^2 / (ai+bi)].\n * We avoid division through zero by adding a tiny value to the denominator:\n * -# if ki == hi == 0 then the nominator is zero and the overall result is zero as desired\n * -# if ki or hi != 0 then ki + hi == ki + hi + float_min\n */\ntemplate <class T, class R = float>\nstruct chi2\n{\n\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    R operator() (const T& a, const T& b) const\n    {\n        R s = 0;\n        for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n        {\n            R v0 = *ai;\n            R v1 = *bi;\n            R nom = v0-v1;\n            R denom = v0+v1+std::numeric_limits<R>::epsilon();\n            s += nom*nom / denom;\n        }\n        return s;\n    }\n};\n\n\n/**\n * @brief Distance function from 'Eitz et al. - An evaluation of descriptors for large-scale image retrieval from sketched feature lines'\n *\n * Used to compare two Tensor descriptors generated by a tensor_generator. Note that this distance function\n * is different from all others in that before you can actually use operator() you need to set the member\n * variable mask, a vector<bool> of size a.size()/3 which contains a boolean for each grid cell of the\n * Tensor descriptor. mask[i] = true indicates that cell i is masked out, i.e. this cell is ignored when\n * computing the distance.\n */\ntemplate <class T, class R = float>\nstruct dist_frobenius\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n    R operator() (const T& a, const T& b) const\n    {\n        assert(a.size() % 3 == 0);\n        assert(a.size() == b.size());\n\n        size_t numCells = a.size() / 3;\n        assert(mask->size() == numCells);\n        size_t index = 0;\n        R dist = 0;\n\n        for (size_t i = 0; i < numCells; i++)\n        {\n            // masking vector provided by query sketch, if\n            // a cell in the query is empty (i.e. contains\n            // no lines, we ignore it in the distance computation\n            if ((*mask)[i]) continue;\n\n            // difference tensor\n            R dE = a[index] - b[index]; index++;\n            R dF = a[index] - b[index]; index++;\n            R dG = a[index] - b[index]; index++;\n\n            // frobenius norm of difference tensor\n            dist += std::sqrt(dE*dE + 2*dF*dF + dG*dG);\n        }\n\n        // normalization not required since the number of cells that are masked out\n        // is defined by the query sketch and thus is constant for all comparison\n        // required for one query\n        return dist;\n    }\n\n    // if you use this distance function, you will need to manually set the correct\n    // mask to be used for the query image\n    const vector<bool>* mask;\n};\n\n\n\n/**\n * @brief Distance function from 'Lee & Funkhouser - Sketch-Based Search and Composition of 3D Models'.\n */\ntemplate <class T, class R = float>\nstruct dist_df\n{\n    // stl\n    typedef T first_argument_type;\n    typedef T second_argument_type;\n    typedef R result_type;\n\n\n    /**\n     * @brief a and b are two descriptors we want to compare. First half of the vectors\n     * is expected to contain the distance transform, second half the image/sketch itself.\n     *\n     * @param a\n     * @param b\n     * @return Computes <a,dt(b)> + <b,dt(a)>, result range is [0,inf] where 0 means that a and b are equal\n     */\n    R operator() (const T& a, const T& b) const\n    {\n        assert(a.size() % 2 == 0);\n        assert(a.size() == b.size());\n\n        result_type dist = 0;\n        size_t offset = a.size() / 2;\n        for (size_t i = 0; i < offset; i++) {\n            dist += a[i]*b[i+offset];\n            dist += b[i]*a[i+offset];\n        }\n        return dist;\n    }\n};\n\n\n/**\n * @brief 'Base' template factory class for generating a distance function\n * by name, we typically use the partially specialized version for vector<T>, though.\n */\ntemplate <class T, class R = float>\nstruct distance_functions\n{\n    typedef boost::function<R (const T&, const T&)> distfn_t;\n\n    distfn_t make(const std::string& /*name*/)\n    {\n        return distfn_t();\n    }\n};\n\n\n/**\n * @brief Factory class that generates a distance function from its name.\n *\n * Note that this is a partial specialization of distance_functions\n * for data of type vector<T>. This makes constructing our typical\n * distance function that actually work on a vector<float> just\n * a little bit more convenient than if we would use the more general version.\n */\ntemplate <class X, class R>\nstruct distance_functions<std::vector<X>, R>\n{\n    typedef std::vector<X> T;\n    typedef boost::function<R (const T&, const T&)> distfn_t;\n\n    distfn_t make(const std::string& name)\n    {\n        if (name == \"l1norm\") return l1norm<T>();\n        if (name == \"l2norm\") return l2norm<T>();\n        if (name == \"l2norm_squared\") return l2norm_squared<T>();\n        if (name == \"jsd\") return jsd<T>();\n        if (name == \"chi2\") return chi2<T>();\n        if (name == \"one_minus_dot\") return one_minus_dot<T>();\n        if (name == \"df\") return dist_df<T>();\n        if (name == \"frobenius\") return dist_frobenius<T>();\n\n        return distfn_t();\n    }\n};\n\n/** @} */\n\n} // namespace imdb\n\n#endif // DISTANCE_HPP\n", "meta": {"hexsha": "80b8160d11bd55dd93adaa7dbadd535e9257ac13", "size": 9124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "search/distance.hpp", "max_stars_repo_name": "mathiaseitz/imdb_framework", "max_stars_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T04:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T20:11:12.000Z", "max_issues_repo_path": "search/distance.hpp", "max_issues_repo_name": "zddhub/imdb_framework", "max_issues_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "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": "search/distance.hpp", "max_forks_repo_name": "zddhub/imdb_framework", "max_forks_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-12-21T13:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T01:29:11.000Z", "avg_line_length": 26.9940828402, "max_line_length": 137, "alphanum_fraction": 0.5854888207, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6847621246562531}}
{"text": "// Eigen lib Tutorial\n// Source: http://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n// Compile: g++ -I /usr/include/eigen3/ eigen_ex4.cpp -o eigen_ex4\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(void)\n{\n    // addition and subtraction\n    Matrix2d a;\n    a << 1, 2,\n         3, 4;\n    MatrixXd b(2,2);\n    b << 2, 3,\n         1, 4;\n    std::cout << \"a + b =\\n\" << a + b << std::endl;\n    std::cout << \"a - b =\\n\" << a - b << std::endl;\n    std::cout << \"Doing a += b;\" << std::endl;\n    a += b;\n    std::cout << \"Now a = \\n\" << a << std::endl;\n    Vector3d v(1,2,3);\n    Vector3d w(1,0,0);\n    std::cout << \"-v + w - v =\\n\" << -v + w - v << std::endl;\n\n    // Scalar multiplication and division\n    a -= b;\n    std::cout << \"a * 2,5 =\\n\" << a * 2.5  << std::endl;\n    std::cout << \"0.1 * v =\\n\" << 0.1 * v  << std::endl;\n    std::cout << \"Doing v *= 2;\" << std::endl;\n    v *= 2;\n    std::cout << \"Now v =\\n\" << v << std::endl;\n\n    // Transposition and conjugation\n    MatrixXcf c = MatrixXcf::Random(2,2);\n    std::cout << \"Here is the matrix c\\n\" << c  << std::endl;\n    std::cout << \"Here is the matrix c^T\\n\" << c.transpose() << std::endl;\n    std::cout << \"Here is the conjugate of c\\n\" <<\n        c.conjugate() << std::endl;\n    std::cout << \"Here is the matrix c^*\\n\" << c.adjoint() << std::endl;\n\n    // Matrix-matrix and matrix-vector multiplication\n    Matrix2d mat;\n    mat << 1, 2,\n           3, 4;\n    Vector2d u(-1,1), x(2,0);\n    std::cout << \"Here is mat*mat:\\n\" << mat*mat  << std::endl;\n    std::cout << \"Here is mat*u:\\n\" << mat*u << std::endl;\n    std::cout << \"Here is u^T*mat:\\n\" << u.transpose()*mat << std::endl;\n    std::cout << \"Here is u^T*x\\n\" << u.transpose()*x << std::endl;\n    std::cout << \"Here is u*x^T\\n\" << u*x.transpose() << std::endl;\n    std::cout << \"let's multiply mat by itself\" << std::endl;\n    mat = mat*mat;\n    std::cout << \"Now mat is mat:\\n\" << mat << std::endl;\n\n    // Dot product and cross product\n    Vector3d e(1,2,3);\n    Vector3d f(0,1,2);\n\n    std::cout << \"Dot product: \" << e.dot(f) << std::endl;\n    double dp = e.adjoint()*f;  // automatic converiosn of the inner product to a scalar\n    std::cout << \"Dot product via a matrix product:\" << dp << std::endl;\n    std::cout << \"Cross product:\\n\" << e.cross(f) << std::endl;\n\n    // Basic arithmetic reduction operations\n    Matrix2d mat2;\n    mat2 << 1, 2,\n            3, 4;\n    std::cout << \"Here is mat2.sum():       \" << mat2.sum() << std::endl;\n    std::cout << \"Here is mat2.prod():      \" << mat2.prod() << std::endl;\n    std::cout << \"Here is mat2.mean():      \" << mat2.mean() << std::endl;\n    std::cout << \"Here is mat2.minCoeff():  \" << mat2.minCoeff() << std::endl;\n    std::cout << \"Here is mat2.maxCoeff():  \" << mat2.maxCoeff() << std::endl;\n    std::cout << \"Here is mat2.trace():     \" << mat2.trace() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "4e08b786ef46b9975a38929708516a20adb86e20", "size": 2910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex4.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "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/Eigen_practice/eigen_ex4.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "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_practice/eigen_ex4.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 36.375, "max_line_length": 88, "alphanum_fraction": 0.5250859107, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6847610163858822}}
{"text": "/*\n For more information, please see: http://software.sci.utah.edu\n \n The MIT License\n \n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n \n License for the specific language governing rights and limitations under\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//ComputePCA algorithm test.\n#include <gtest/gtest.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <Testing/Utils/MatrixTestUtilities.h>\n#include <Core/Algorithms/Math/ComputePCA.h>\n#include <Eigen/SVD>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::TestUtils;\n\nnamespace\n{\n    //Matrix for input.\n    DenseMatrixHandle inputMatrix()\n    {\n        //Hard coded for testing.\n        int column1 [12] = {5,4,7,8,10,10,4,6,8,7,9,6};\n        int column2 [12] = {7,6,9,8,5,7,9,3,4,5,5,9};\n        \n        //Puts the columns into a matrix.\n        DenseMatrixHandle inputM(boost::make_shared<DenseMatrix>(12,2));\n        for (int i = 0; i < inputM->rows(); i++){\n            (*inputM)(i,0) = column1[i];\n            (*inputM)(i,1) = column2[i];\n        }\n        return inputM;\n    }\n    \n    //The input matrix after centering.\n    DenseMatrixHandle centeredInputMatrix()\n    {\n        //Hard coded for testing.\n        double centeredColumn1 [12] = {-2.0,-3.0,-0.0,1.0,3.0,3.0,-3.0,-1.0,1.0,-0.0,2.0,-1.0};\n        double centeredColumn2 [12] = {0.583333,-0.416667,2.583333,1.583333,-1.416667,0.583333,2.583333,-3.416667,-2.416667,-1.416667,-1.416667,2.583333};\n        \n        //Puts the columns into a matrix.\n        DenseMatrixHandle centeredM(boost::make_shared<DenseMatrix>(12,2));\n        for (int i = 0; i < centeredM->rows(); i++){\n            (*centeredM)(i,0) = centeredColumn1[i];\n            (*centeredM)(i,1) = centeredColumn2[i];\n        }\n        return centeredM;\n    }\n}\n\n//Checks if the algorithm centers the data correctly.\nTEST(ComputePCAtest, CenterData)\n{\n    ComputePCAAlgo algo;\n    \n    DenseMatrixHandle m1(inputMatrix());\n    \n    auto centered = ComputePCAAlgo::centerData(m1);\n    \n    auto expected = *centeredInputMatrix();\n    \n    //Checking every element with a tolerance of 1e-5.\n    for (int i = 0; i < centered.rows(); ++i) {\n        for (int j = 0; j < centered.cols(); ++j)\n            ASSERT_NEAR(expected(i,j), centered(i,j), 1e-5);\n    }\n}\n\n//Checks if the outputs are correct.\n//U,S,V: U: Left principal matrix, S: principal values, V: Right principal matrix.\nTEST(ComputePCAtest, checkOutputs)\n{\n    ComputePCAAlgo algo;\n    \n    DenseMatrixHandle m1(inputMatrix());\n    DenseMatrixHandle LeftPrinMat_U;\n    DenseMatrixHandle PrinVals_S;\n    DenseMatrixHandle RightPrinMat_V;\n    \n    //Runs algorithm.\n    algo.run(m1,LeftPrinMat_U,PrinVals_S,RightPrinMat_V);\n    \n    //Testing if the results are null.\n    ASSERT_NE(nullptr,LeftPrinMat_U);\n    ASSERT_NE(nullptr,PrinVals_S);\n    ASSERT_NE(nullptr,RightPrinMat_V);\n    \n    //Check the dimensions of the matrices that were created for output.\n    \n    //Rows\n    ASSERT_EQ(12,LeftPrinMat_U->rows());\n    ASSERT_EQ(2,PrinVals_S->rows());\n    ASSERT_EQ(2,RightPrinMat_V->rows());\n    \n    //Columns\n    ASSERT_EQ(12,LeftPrinMat_U->cols());\n    ASSERT_EQ(1,PrinVals_S->cols());\n    ASSERT_EQ(2,RightPrinMat_V->cols());\n    \n    \n    \n    //Eigen does not create a diagonal matrix when it computes SVD, it just has a column with the principal values, so we must put it into a diagonal matrix to be able to do some matrix multiplication later.\n    DenseMatrix sDiag = Eigen::MatrixXd::Constant(12,2,0);\n    sDiag.diagonal() = PrinVals_S->col(0);\n    \n    //Multiplying back together and comparing to the centered matrix. They should be equal to each other with some tolerance.\n    DenseMatrix product = (*LeftPrinMat_U) * sDiag * (*RightPrinMat_V).transpose();\n    \n    auto expected = *centeredInputMatrix();\n    \n    //Comparing each element in the matrices.\n    for (int i = 0; i < product.rows(); ++i) {\n        for (int j = 0; j < product.cols(); ++j)\n            ASSERT_NEAR(expected(i,j), product(i,j), 1e-5);\n    }\n\n}\n\n//Tests for input with a dimension of zero.\nTEST(ComputePCAtest, ThrowsForZeroDimensionInput)\n{\n    ComputePCAAlgo algo;\n    \n    DenseMatrixHandle m1(new DenseMatrix(5, 0));\n    DenseMatrixHandle m2(new DenseMatrix(0, 5));\n    DenseMatrixHandle m3(new DenseMatrix(0, 0));\n    \n    DenseMatrixHandle LeftPrinMat_U;\n    DenseMatrixHandle PrinVals_S;\n    DenseMatrixHandle RightPrinMat_V;\n    \n    //Runs algorithm and expects an error.\n    EXPECT_ANY_THROW(algo.run(m1,LeftPrinMat_U,PrinVals_S,RightPrinMat_V));\n    EXPECT_ANY_THROW(algo.run(m2,LeftPrinMat_U,PrinVals_S,RightPrinMat_V));\n    EXPECT_ANY_THROW(algo.run(m3,LeftPrinMat_U,PrinVals_S,RightPrinMat_V));\n\n}", "meta": {"hexsha": "0d8b6d7fc0f1e5db8ad8bb6c59d29316d0e6decf", "size": 5792, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/Tests/ComputePCAtest.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/Tests/ComputePCAtest.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/Tests/ComputePCAtest.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": 35.7530864198, "max_line_length": 207, "alphanum_fraction": 0.6866367403, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.684707692249988}}
{"text": "/**\n * 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\n#pragma once\n\n#include <array>\n\n#include <Eigen/Core>\n\nnamespace ipc::rigid {\n\n/// @brief Barrier functions to choose from.\nenum BarrierType {\n    IPC,\n    POLY_LOG,\n    SPLINE,\n};\n\n///////////////////////////////////////////////////////////////////////////\n// Choose your barrier!\n\n/**\n * @brief Function that grows to infinity as x approaches 0 from the right.\n *\n * @param x             The x value at which to evaluate.\n * @param s             Activation value of the barrier.\n * @param barrier_type  Barrier function type to use.\n * @return The value of the barrier function at x.\n */\ntemplate <typename T> T barrier(const T& x, double s, BarrierType barrier_type);\n\ndouble barrier_gradient(double x, double s, BarrierType barrier_type);\n\ndouble barrier_hessian(double x, double s, BarrierType barrier_type);\n\n///////////////////////////////////////////////////////////////////////////\n// Poly-Log Barrier\n\n/// y := x/eps; b(x, \u03f5) = -log(y)*(2*y^3-3*y^2+1)\ntemplate <typename T> T poly_log_barrier(const T& x, double s);\n\ndouble poly_log_barrier_gradient(double x, double s);\n\ndouble poly_log_barrier_hessian(double x, double s);\n\n///////////////////////////////////////////////////////////////////////////\n// Spline Barrier\n\n/**\n * @brief Function that grows to infinity as x approaches 0 from the right.\n *\n * \\begin{align}\n * g(x, s) = \\frac{1}{s^3}x^3 - \\frac{3}{s^2}x^2 + \\frac{3}{s}x\n * \\end{align}\n * \\begin{align}\n * \\phi_{\\text{spline}}(x, s) = \\frac{1}{g(x, s)} - 1\n * \\end{align}\n *\n * where \\f$s\\f$ is a constant. See <a\n * href=\"https://cims.nyu.edu/gcl/papers/LIM-2013-schueller.pdf\">here</a>\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the barrier function at x.\n */\ntemplate <typename T> T spline_barrier(const T& x, double s);\n\n/**\n * @brief Derivative of the spline_barrier function with respect to x.\n *\n * \\begin{align}\n * g'(x, s) = \\frac{3}{s^3}x^2 - \\frac{6}{s^2}x + \\frac{3}{s}\n * \\end{align}\n * \\begin{align}\n * \\phi'_{\\text{spline}}(x, s) = \\frac{-1}{[g(x)]^2}g'(x)\n * \\end{align}\n *\n * where \\f$s\\f$ is a constant. See <a\n * href=\"https://cims.nyu.edu/gcl/papers/LIM-2013-schueller.pdf\">here</a>\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the derivative of the barrier function at x.\n */\ndouble spline_barrier_gradient(double x, double s);\n\n/**\n * @brief Second derivative of the spline_barrier function with respect to\n * x.\n *\n * \\begin{align}\n * g''(x, s) = \\frac{6}{s^3}x - \\frac{6}{s^2}\n * \\end{align}\n * \\begin{align}\n * \\phi''_{\\text{spline}}(x, s) = \\frac{2}{[g(x)]^3}[g'(x)]^2 +\n * \\frac{-1}{[g(x)]^2}g''(x) \\end{align}\n *\n * where \\f$s\\f$ is a constant. See <a\n * href=\"https://cims.nyu.edu/gcl/papers/LIM-2013-schueller.pdf\">here</a>\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the second derivative of the barrier function at x.\n */\ndouble spline_barrier_hessian(double x, double s);\n\n} // namespace ipc::rigid\n\n#include \"barrier.tpp\"\n", "meta": {"hexsha": "81bbd41f33215199920b734e708d5d3195473282", "size": 3589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/barrier/barrier.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/barrier/barrier.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/barrier/barrier.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 30.9396551724, "max_line_length": 80, "alphanum_fraction": 0.6216216216, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6847076895416744}}
{"text": "#include <iostream>\nusing namespace std;\n\n#include <ctime>\n\n// use eigin in c++\n// Eigen Core part\n#include <Eigen/Core>\n// \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE    50\n\n//---------------------\u4ecb\u7ecdeigen\u5e93\u7684\u57fa\u672c\u7528\u6cd5-----------------------\n//\u5185\u7f6e\u7c7b\u578b\uff1aEigen::Matrix<>\uff0c\u9002\u7528\u4e8e\u6240\u6709\u5411\u91cf\u548c\u77e9\u9635\n//\u8fd9\u662f\u4e00\u4e2a\u6a21\u7248\u7c7b\uff0c\u4e09\u4e2a\u53c2\u6570\u4e3a\uff1a\u6570\u636e\u7c7b\u578b\uff0c\u884c\uff0c\u5217\n\nint main(int argc, char const *argv[])\n{\n   //---------------------\u521b\u5efa\u4e0d\u540c\u7c7b\u578b\u7684\u5411\u91cf\u6216\u8005\u77e9\u9635------------------\n\n   //\u58f0\u660e\u4e00\u4e2a2*3\u7684float\u77e9\u9635\n   Eigen::Matrix<float, 2, 3> matrix_23;\n\n   //Eigen \u901a\u8fc7 typedef \u63d0\u4f9b\u4e86\u8bb8\u591a\u5185\u7f6e\u7c7b\u578b\uff0c\u4e0d\u8fc7\u5e95\u5c42\u4ecd\u7136\u662f Eigen::Matrix\n   //\u4f8b\u5982\uff0c Vector3d\u4e09\u4f4d\u5411\u91cf \u5c31\u662f Eigen::Matrix<double,3,1>\n   Eigen::Vector3d            v_3d;   //\u8fd9\u4e24\u4e2a\u7b49\u4ef7, \u4f46\u662f\u8fd9\u4e2a\u6570\u636e\u7c7b\u578b\u662fdouble\n   Eigen::Matrix<float, 3, 1> v_3d_1; //\u8fd9\u4e24\u4e2a\u7b49\u4ef7\uff0c\u8fd9\u4e2a\u6570\u636e\u7c7b\u578b\u662ffloat\n\n   //Matrix3d \u5b9e\u8d28\u4e0a\u662f Eigen::Matrix<double, 3, 3>\n   Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //\u521d\u59cb\u5316\u4e3a\u96f6\n\n   //\u52a8\u6001\u5927\u5c0f\u7684\u77e9\u9635\uff0c\u77e9\u9635\u5927\u5c0f\u4e0d\u786e\u5b9a\n   //\u7b2c\u4e00\u884c\u7528\u6700\u57fa\u672c\u7684\u7c7b\u578b\uff0c\u7b2c\u4e8c\u884c\u662feigen\u7528typedef\u63d0\u4f9b\u7684\n   Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_dynamic;\n   Eigen::MatrixXd matrix_dynamic_1;\n\n   //---------------------\u5bf9Eigen\u77e9\u9635\u7684\u64cd\u4f5c------------------\n\n   //\u6570\u636e\u521d\u59cb\u5316\n   matrix_23 << 1, 2, 3, 4, 5, 6;\n\n   //\u8f93\u51fa\n   cout << \"\u76f4\u63a5\u7528cout\u8f93\u51fa\\n\" << matrix_23 << endl;\n   //\u904d\u5386\u77e9\u9635\u5143\u7d20\n   //\n   // for (size_t i = 0; i < 2; i++)\n   // {\n   //    for (size_t j = 0; j < 3; j++)\n   //    {\n   //       cout << matrix_23(i, j) << \"\\t\";\n   //    }\n   //    cout << endl;\n   // }\n\n   //\u77e9\u9635\u95f4\u4e58\u6cd5\uff0c\u6216\u8005\u77e9\u9635\u548c\u5411\u91cf\n   //\u8981\u6ce8\u610f\u7684\uff1a\n   //1. \u4e24\u4e2a\u5bf9\u8c61\u5185\u5143\u7d20\u7684\u6570\u636e\u7c7b\u578b\u8981\u4e00\u6837\n   //   Wrong example:\n   //   Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;\n   //2. \u9075\u5faa\u77e9\u9635\u4e58\u6cd5\u89c4\u5219, \u4f8b\u5982\u77e9\u9635\u7ef4\u5ea6\n   //   Wrong example:\n   //   Eigen::Matrix<double, 2, 3> result_wrong_dimension = matrix_23.cast<double>() * v_3d;\n   v_3d << 3, 2, 1;   //v_3d\u6570\u636e\u7c7b\u578b\u662fdouble\n   v_3d_1 << 4, 5, 6; //v_3d_1\u6570\u636e\u7c7b\u578b\u662ffloat\n\n   //\u56db\u5219\u8fd0\u7b97 \u7528 + - * /\n   //\u8fd9\u91cc\u5c55\u793a\u4e58\u6cd5\n   //matrix_23\u6570\u636e\u7c7b\u578b\u662ffloat\uff0c\u5982\u679c\u8981\u548cv_3d\u76f8\u4e58\uff0c\u9700\u8981\u663e\u793a\u8f6c\u6362\n   //Eigen\u4e3a\u4e86\u6027\u80fd\uff0c\u4e0d\u4f1a\u63d0\u4f9b\u9690\u58eb\u8f6c\u6362\uff0c\u8f6c\u6362\u6210\u5458\u51fd\u6570\u662f .cast<double>()\n   Eigen::Matrix<double, 2, 1> result  = matrix_23.cast<double>() * v_3d;\n   Eigen::Matrix<float, 2, 1>  result2 = matrix_23 * v_3d_1;\n\n   //\u77e9\u9635\u8fd0\u7b97\n   matrix_33 = Eigen::Matrix3d::Random();                             //\u968f\u673a3x3\u7684\u77e9\u9635\uff0c\u4f46\u662f\u611f\u89c9\u600e\u4e48\u90fd\u4e0d\u53d8...\n   cout << \"matrix \\n\" << matrix_33 << endl << endl;\n   cout << \"matrix transpose\\n\" << matrix_33.transpose() << endl;     // \u8f6c\u7f6e\n   cout << \"matrix sum\\n\" << matrix_33.sum() << endl;                 // \u5404\u5143\u7d20\u548c\n   cout << \"matrix trace\\n\" << matrix_33.trace() << endl;             // \u8ff9\n   cout << \"matrix inverse\\n\" << matrix_33.inverse() << endl;         // \u9006\n   cout << \"matrix determinant\\n\" << matrix_33.determinant() << endl; // \u884c\u5217\u5f0f\n\n\n   //----------------------eigenvalues & eigenvectors-----------------\n   // Computes eigenvalues and eigenvectors of selfadjoint matrices.\n   // define a selfadjoint Matrix\n   Eigen::Matrix3d S = matrix_33.transpose() * matrix_33;\n   // use solver on 3x3 matrix S\n   Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(S);\n   cout << \"Eigen values = \\n\" << es.eigenvalues() << endl;\n   cout << \"Eigen vectors = \\n\" << es.eigenvectors() << endl;\n\n\n   //-------------------------\u89e3\u65b9\u7a0b-----------------------------\n   //Solve matrix_NN * x = v_Nd\n   //\u76f4\u63a5\u6c42\u9006\u6c42\u89e3 \u4e0e QR decomposition\u6c42\u89e3\n   //define matrix_NN and v_Nd\n   Eigen::Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN;\n   matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); //\u53e6\u4e00\u79cd\u4f7f\u7528random\u7684\u7528\u6cd5\n   Eigen::Matrix<double, MATRIX_SIZE, 1> v_Nd;\n   v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n   Eigen::Matrix<double, MATRIX_SIZE, 1> x;\n   //set timer\n   clock_t time_start = clock();\n   //1. solve by inverse, time used is4.151ms\n   x = matrix_NN.inverse() * v_Nd;\n   cout << \"time used is\" << 1000 * (clock() - time_start) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n   //2. solve by QR decomposition, time used is0.082ms\n   time_start = clock();\n   x          = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n   cout << \"time used is\" << 1000 * (clock() - time_start) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "f5fd875276fb73b8ae2e62151f8cf8f4d57c2fed", "size": 3891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libEigen/main.cpp", "max_stars_repo_name": "Qilko/VisualSLAM", "max_stars_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T02:35:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T17:52:55.000Z", "max_issues_repo_path": "libEigen/main.cpp", "max_issues_repo_name": "Qilko/VisualSLAM", "max_issues_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libEigen/main.cpp", "max_forks_repo_name": "Qilko/VisualSLAM", "max_forks_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_forks_repo_licenses": ["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.8347826087, "max_line_length": 100, "alphanum_fraction": 0.5833975842, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6846591643584707}}
{"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_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_AVERAGE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n                  {\n\n /*!\n    @ingroup group-arithmetic\n    Function object implementing average\n\n    Computes the arithmetic mean of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = average(x, y);\n    @endcode\n\n    For floating point values the code is equivalent to:\n\n    @code\n    T r = (x+y)/T(2);\n    @endcode\n\n    for integer types, it returns a rounded value at a distance guaranteed\n    to be less than or equal to 0.5 of the average floating value, but may differ\n    by unity from the truncation given by (x1+x2)/T(2).\n\n    @par Note:\n      This function does not overflow.\n\n    @see meanof\n\n  **/\n  Value average(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/average.hpp>\n#include <boost/simd/function/simd/average.hpp>\n\n#endif\n", "meta": {"hexsha": "03c58f0d4db1a433378fc1d4e7cbf2729f3e2dd5", "size": 1369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/average.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/function/average.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/average.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.8909090909, "max_line_length": 100, "alphanum_fraction": 0.5872899927, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.684659161828814}}
{"text": "/**\n * @file exponentialintegrator_main.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 <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n/**\n * @file exponentialintegrator_main.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 <Eigen/Core>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"exponentialintegrator.h\"\n\nint main() {\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::VectorXd dfy(1);\n    dfy << 1.0 - 2.0 * y(0);\n    return dfy;\n  };\n  double exactyT = y0(0) / (y0(0) + (1.0 - y0(0)) * std::exp(-T));\n\n  // Container for errors\n  std::vector<double> error(15);\n\n  // Test many step sizes\n  for (int j = 0; j < 15; ++j) {\n    int N = std::pow(2, j + 1);\n    Eigen::VectorXd y = y0;\n    double h = T / N;\n#if SOLUTION\n    for (int k = 0; k < N; ++k) {\n      y = ExponentialIntegrator::exponentialEulerStep(y, f, df, h);\n    }\n#else\n    //====================\n    // Your code goes here\n    // TODO: Perform N timesteps with inital data y0 and store the result in y.\n    //====================\n#endif\n\n    error[j] = std::abs(y(0) - exactyT);\n    std::cout << std::left << std::setfill(' ') << std::setw(3)\n              << \"N = \" << std::setw(7) << N << 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  return 0;\n}\n", "meta": {"hexsha": "28ffb908101114a1493795ec1b1c13e187669d52", "size": 2034, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.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": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.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": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.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": 26.0769230769, "max_line_length": 80, "alphanum_fraction": 0.5634218289, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.684659159769872}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/linspace.hpp\n *\n * \\brief Linearly spaced vector\n *\n * Inspired by MATLAB's linspace function.\n *\n * <hr/>\n *\n * Copyright (c) 2013, 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_LINSPACE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LINSPACE_HPP\n\n\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <cstddef>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n/**\n * \\brief Generates a linearly spaced vector.\n *\n * Generates \\a n values linearly spaced between \\a a and \\a b.\n * Note, in case \\f$a<b\\f$, generates a decreasing sequence.\n *\n * Inspired by MATLAB's linspace function.\n *\n * \\param a The starting value of the linearly spaced sequence.\n * \\param b The final value of the linearly spaced sequence.\n * \\param n The number of values to generate\n * \\return A vector of linearly spaced values in \\f$[a,b]\\f$; if\n *  <code>n=1</code>, returns \\a b.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename ValueT>\nBOOST_UBLAS_INLINE\nvector<ValueT> linspace(ValueT a, ValueT b, std::size_t n = 100)\n{\n\t// pre: n > 0\n\tBOOST_UBLAS_CHECK( n > 0,\n\t\t\t\t\t   bad_argument() );\n\n\tif (n < 2)\n\t{\n\t\treturn scalar_vector<ValueT>(1, b);\n\t}\n\n\tvector<ValueT> x(n);\n\n\t--n;\n\n\t// Check for possible overflows generated by opposite signs\n\tconst ValueT c = (b-a)*(n-1);\n\tif (std::isinf(c) && std::isinf(b-a))\n\t{\n\t\t// Overflows is happened => split computations\n\n\t\tconst ValueT an = a/n;\n\t\tconst ValueT bn = b/n;\n\n\t\tfor (std::size_t i = 0; i <= n; ++i)\n\t\t{\n\t\t\tx[i] = a + bn*i - an*i;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// No overflow\n\n\t\tconst ValueT step = (b-a)/n;\n\n\t\tfor (std::size_t i = 0; i <= n; ++i)\n\t\t{\n\t\t\tx[i] = a + step*i;\n\t\t}\n\t}\n\n\t// just make sure that endpoints are honored\n\tx[0] = a;\n\tx[n] = b;\n\n\treturn x;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LINSPACE_HPP\n", "meta": {"hexsha": "dca26e7f13b34d1e099a23cd6d1d8d82bc6f803e", "size": 2177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/linspace.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/linspace.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/linspace.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": 21.3431372549, "max_line_length": 66, "alphanum_fraction": 0.6688102894, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.6845784090892397}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <solvers/sqp.hpp>\n#include <unsupported/Eigen/AutoDiff>\n\nusing namespace sqp;\n\nnamespace sqp_test_autodiff {\n\ntemplate <typename SCALAR, typename DERIVED>\nstruct NonLinearProblemAutoDiff : public NonLinearProblem<SCALAR> {\n    using Scalar = SCALAR;\n    using Vector = NonLinearProblem<double>::Vector;\n    using Matrix = NonLinearProblem<double>::Matrix;\n\n    using ADScalar = Eigen::AutoDiffScalar<Vector>;\n    using ADVector = Eigen::Matrix<ADScalar, Eigen::Dynamic, 1>;\n\n    template <typename vec>\n    void ADVectorSeed(vec& x) {\n        for (int i = 0; i < x.rows(); i++) {\n            x[i].derivatives() = Vector::Unit(this->num_var, i);\n        }\n    }\n\n    void objective(const Vector& x, Scalar& obj) override {\n        static_cast<DERIVED*>(this)->objective(x, obj);\n    }\n\n    void objective_linearized(const Vector& x, Vector& grad, Scalar& obj) override {\n        ADVector ad_x = x;\n        ADScalar ad_obj;\n        ADVectorSeed(ad_x);\n        /* Static polymorphism using CRTP */\n        static_cast<DERIVED*>(this)->objective(ad_x, ad_obj);\n        obj = ad_obj.value();\n        grad = ad_obj.derivatives();\n    }\n\n    void constraint(const Vector& x, Vector& c, Vector& l, Vector& u) override {\n        static_cast<DERIVED*>(this)->constraint(x, c, l, u);\n    }\n\n    void constraint_linearized(const Vector& x, Matrix& Jc, Vector& c, Vector& l,\n                               Vector& u) override {\n        ADVector ad_c(this->num_constr);\n        ADVector ad_x = x;\n\n        ADVectorSeed(ad_x);\n        static_cast<DERIVED*>(this)->constraint(ad_x, ad_c, l, u);\n\n        // fill constraint Jacobian\n        for (int i = 0; i < ad_c.rows(); i++) {\n            c[i] = ad_c[i].value();\n            Eigen::Ref<Vector> deriv = ad_c[i].derivatives();\n            Jc.row(i) = deriv.transpose();\n        }\n    }\n};\n\ntemplate <typename Scalar>\ninline Scalar rosenbrock(const Eigen::Matrix<Scalar, Eigen::Dynamic, 1> x) {\n    const double a = 1;\n    const double b = 100;\n\n    Scalar z = 0;\n    for (int i = 0; i < x.rows() - 1; i++) {\n        z += pow(a - x[i], 2) + b * pow(x[i + 1] - pow(x[i], 2), 2);\n    }\n    return z;\n}\n\nstruct ConstrainedRosenbrock2D : public NonLinearProblemAutoDiff<double, ConstrainedRosenbrock2D> {\n    const Scalar a = 1;\n    const Scalar b = 100;\n    Eigen::Matrix<Scalar, 2, 1> SOLUTION = {0.707106781, 0.707106781};\n\n    ConstrainedRosenbrock2D() {\n        num_var = 2;\n        num_constr = 2;\n    }\n\n    template <typename DerivedA, typename DerivedB>\n    void objective(const DerivedA& x, DerivedB& obj) {\n        // (a-x)^2 + b*(y-x^2)^2\n        // obj = pow(a - x(0), 2) + b * pow(x(1) - pow(x(0), 2), 2);\n        obj = rosenbrock(x);\n    }\n\n    template <typename A, typename B>\n    void constraint(const A& x, B& c, Vector& l, Vector& u) {\n        const Scalar infinity = std::numeric_limits<Scalar>::infinity();\n        // y >= x\n        // x^2 + y^2 == 1\n        c << x(0) - x(1), x.squaredNorm();\n        u << 0, 1;\n        l << -infinity, 1;\n    }\n};\n\nTEST(SQPAutoDiff, TestConstrainedRosenbrock2D) {\n    ConstrainedRosenbrock2D problem;\n    SQP<double> solver;\n    Eigen::VectorXd x0 = Eigen::Vector2d(0, 0);\n    Eigen::VectorXd y0 = Eigen::VectorXd::Zero(2);\n\n    solver.settings().max_iter = 100;\n    // solver.settings().line_search_max_iter = 10;\n    // solver.settings().second_order_correction = true;\n\n    // solver.settings().eta = 0.5;\n    solver.solve(problem, x0, y0);\n\n    solver.info().print();\n    std::cout << \"primal solution \" << solver.primal_solution().transpose() << std::endl;\n    std::cout << \"dual solution \" << solver.dual_solution().transpose() << std::endl;\n\n    EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n\nstruct Rosenbrock : public NonLinearProblemAutoDiff<double, Rosenbrock> {\n    const Scalar a = 1;\n    const Scalar b = 100;\n    Vector SOLUTION;\n\n    Rosenbrock(int n) {\n        num_var = n;\n        num_constr = n;\n        SOLUTION = Vector::Ones(n);\n    }\n\n    template <typename DerivedA, typename DerivedB>\n    void objective(const DerivedA& x, DerivedB& obj) {\n        obj = rosenbrock(x);\n    }\n\n    template <typename A, typename B>\n    void constraint(const A& x, B& c, Vector& l, Vector& u) {\n        c << x;\n        u.setConstant(1);\n        l.setConstant(0);\n    }\n};\n\nTEST(SQPAutoDiff, TestRosenbrock) {\n    for (int i = 2; i < 4; i++) {\n        Rosenbrock problem(i);\n        SQP<double> solver;\n\n        solver.settings().max_iter = 100;\n        // solver.settings().line_search_max_iter = 100;\n        // solver.settings().second_order_correction = true;\n        solver.solve(problem);\n\n        solver.info().print();\n        std::cout << \"primal solution \" << solver.primal_solution().transpose() << std::endl;\n        std::cout << \"dual solution \" << solver.dual_solution().transpose() << std::endl;\n\n        EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2));\n        EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n    }\n}\n\ntemplate <typename T>\nvoid callback(SQP<T>& solver) {\n    Eigen::IOFormat fmt(Eigen::StreamPrecision, 0, \", \", \",\", \"[\", \"],\");\n    std::cout << solver.x_.transpose().format(fmt) << '\\n';\n}\n\nstruct SimpleNLP : public NonLinearProblemAutoDiff<double, SimpleNLP> {\n    Eigen::Vector2d SOLUTION = {1, 1};\n    const Scalar infinity = std::numeric_limits<Scalar>::infinity();\n\n    SimpleNLP() {\n        num_var = 2;\n        num_constr = 3;\n    }\n\n    template <typename A, typename B>\n    void objective(const A& x, B& obj) {\n        obj = -x.sum();\n    }\n\n    template <typename A, typename B>\n    void constraint(const A& x, B& c, Vector& l, Vector& u) {\n        // 1 <= x0^2 + x1^2 <= 2\n        // 0 <= x0\n        // 0 <= x1\n        c << x.squaredNorm(), x;\n        l << 1, 0, 0;  // x0 > 0 and x1 > 0\n        u << 2, infinity, infinity;\n    }\n};\n\nTEST(SQPAutoDiff, TestSimpleNLP) {\n    SimpleNLP problem;\n    SQP<double> solver;\n\n    // feasible initial point\n    Eigen::VectorXd x0 = Eigen::Vector2d(1.2, 0.1);\n    Eigen::VectorXd y0 = Eigen::VectorXd::Zero(3);\n\n    // TODO(mi): doesn't work for higher values\n    // solver.settings().line_search_max_iter = 10;\n    solver.settings().max_iter = 100;\n    solver.settings().second_order_correction = false;\n    // solver.settings().iteration_callback = callback<double>;\n\n    solver.solve(problem, x0, y0);\n\n    solver.info().print();\n    std::cout << \"primal solution \" << solver.primal_solution().transpose() << std::endl;\n    std::cout << \"dual solution \" << solver.dual_solution().transpose() << std::endl;\n\n    EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n\nTEST(SQPAutoDiff, TestSimpleNLP_SOC) {\n    SimpleNLP problem;\n    SQP<double> solver;\n\n    // feasible initial point\n    Eigen::VectorXd x0 = Eigen::Vector2d(1.2, 0.1);\n    Eigen::VectorXd y0 = Eigen::VectorXd::Zero(3);\n\n    // TODO(mi): doesn't work for higher values\n    // solver.settings().line_search_max_iter = 10;\n    solver.settings().max_iter = 100;\n    solver.settings().second_order_correction = true;\n    // solver.settings().iteration_callback = callback<double>;\n\n    solver.solve(problem, x0, y0);\n\n    solver.info().print();\n    std::cout << \"primal solution \" << solver.primal_solution().transpose() << std::endl;\n    std::cout << \"dual solution \" << solver.dual_solution().transpose() << std::endl;\n\n    EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n\n/** Example 12.1 from Nonlinear Optimization by Nocedal, Wright */\nstruct SimpleNLP2 : public NonLinearProblemAutoDiff<double, SimpleNLP2> {\n    Eigen::Vector2d SOLUTION = {-1, -1};\n\n    SimpleNLP2() {\n        num_var = 2;\n        num_constr = 1;\n    }\n\n    template <typename A, typename B>\n    void objective(const A& x, B& obj) {\n        obj = x.sum();\n    }\n\n    template <typename A, typename B>\n    void constraint(const A& x, B& c, Vector& l, Vector& u) {\n        // x0^2 + x1^2 = 2\n        c << x.squaredNorm();\n        l << 2;\n        u << 2;\n    }\n};\n\nTEST(SQPAutoDiff, TestSimpleNLP2) {\n    SimpleNLP2 problem;\n    SQP<double> solver;\n\n    Eigen::VectorXd x0 = Eigen::Vector2d(1.2, 0.1);\n    Eigen::VectorXd y0 = Eigen::VectorXd::Zero(1);\n\n    solver.solve(problem, x0, y0);\n\n    solver.info().print();\n    std::cout << \"primal solution \" << solver.primal_solution().transpose() << std::endl;\n    std::cout << \"dual solution \" << solver.dual_solution().transpose() << std::endl;\n\n    EXPECT_TRUE(solver.primal_solution().isApprox(problem.SOLUTION, 1e-2));\n    EXPECT_LT(solver.info().iter, solver.settings().max_iter);\n}\n\n}  // namespace sqp_test_autodiff\n", "meta": {"hexsha": "b627cfa9aa19a6458f7acd8ec139e1892a5bd38d", "size": 8838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/sqp_test_autodiff.cpp", "max_stars_repo_name": "nuft/sqp_solver", "max_stars_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-10-16T08:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T04:51:20.000Z", "max_issues_repo_path": "tests/sqp_test_autodiff.cpp", "max_issues_repo_name": "likping/sqp_solver", "max_issues_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T19:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T09:18:04.000Z", "max_forks_repo_path": "tests/sqp_test_autodiff.cpp", "max_forks_repo_name": "likping/sqp_solver", "max_forks_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-18T17:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:07:22.000Z", "avg_line_length": 31.0105263158, "max_line_length": 99, "alphanum_fraction": 0.6096401901, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6845757125793468}}
{"text": "/*\nThis program is meant to compute maximal Lyapunov expoennt of Lorenz system.\n*/\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <fstream>\n#include <string>\n#include <ctime>\n#include <cstdlib>\n#include <blitz/array.h>\n#include <sys/stat.h>\n\nusing namespace blitz;\n// ============ Declaration of functions ===================\ndouble Euclidean_measure(Array<double,1>);\nArray<double,1> Lorenz_system(Array<double,1>);\nArray<double,1> RK4_integrator(Array<double,1>, double, Array<double,1> (*F)(Array<double, 1>) );\nArray<double,1> linearized_Lorenz_system(Array<double,1>, Array<double,1>);\nArray<double,1> error_RK4_integrator(Array<double,1>, Array<double,1>, double, Array<double,1> (*F)(Array<double,1>, Array<double,1>));\ndouble max_lypo_expo(Array<double,1> , double, Array<double,1> (*F)(Array<double,1>) );\n\n// =========== I/O files ==================================\nofstream time_series_file;\n\n\nint main(int argc, char const *argv[])\n{\n\tArray<double,1> X(3);\t\t\t\t\t\t\t\t// State vector for the reference trajectory\n\tX = -3.16,-5.31,13.31;\t\t\t\t\t\t\t// Initial condition r = 28\n\t// X = 0.62225717,-0.08232857,30.60845379;\t\t\t\t// Initial condition r = 45.92\n\t// X = 4.29033, -0.577049, 28.8962;\n\tdouble dt = 0.001;\n\tmax_lypo_expo(X, dt, Lorenz_system);\n\treturn 0;\n}\n\ndouble Euclidean_measure(Array<double,1> A)\n{\n\tint N = A.numElements();\n\tdouble d = 0;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\td += pow(A(i),2);\n\t}\n\td = sqrt(d);\n\treturn d;\n}\n\nArray<double,1> RK4_integrator(Array<double,1> X0, double dt, Array<double,1> (*F)(Array<double,1>) )\n{\n\tint dim = X0.numElements();\n\tArray<double,1> X(dim);\t\t\t\t// State vector\n\t// -------- Intermediate derivatives --------\n\tArray<double,1> K1(dim);\n\tArray<double,1> K2(dim);\n\tArray<double,1> K3(dim);\n\tArray<double,1> K4(dim);\n\t// ------------------------------------------\n\tK1 = dt*F(X0);\n\tX = X0 + 0.5*K1;\n\tK2 = dt*F(X);\n\tX = X0 + 0.5*K2;\n\tK3 = dt*F(X);\n\tX = X0 + K3;\n\tK4 = dt*F(X);\n\tX = X0 + (1.0/6)*(K1 + 2*K2 + 2*K3 + K4);\n\treturn X;\n\n}\n\nArray<double,1> error_RK4_integrator( Array<double,1> E0, Array<double,1> X, double dt, Array<double,1> (*F)(Array<double,1>, Array<double,1>))\n{\n\t// X is the state vector\n\tint dim = E0.numElements();\n\tArray<double,1> E(dim);\t\t\t\t// Tangent vector\n\t// -------- Intermediate derivatives --------\n\tArray<double,1> K1(dim);\n\tArray<double,1> K2(dim);\n\tArray<double,1> K3(dim);\n\tArray<double,1> K4(dim);\n\t// ------------------------------------------\n\tK1 = dt*F(E0, X);\n\tE = E0 + 0.5*K1;\n\tK2 = dt*F(E0, X);\n\tE = E0 + 0.5*K2;\n\tK3 = dt*F(E0, X);\n\tE = E0 + K3;\n\tK4 = dt*F(E0, X);\n\tE = E0 + (1.0/6)*(K1 + 2*K2 + 2*K3 + K4);\n\treturn E;\n\n}\n\nArray<double,1> Lorenz_system(Array<double,1> X)\n{\n\t// ------ Parameters ------------------------\n\tdouble sigma = 10;//16; //10;\n\tdouble r = 28;//45.92; //28;\n\tdouble b = 8.0/3;//4; //8.0/3;\n\t// ------------------------------------------\n\n\tArray<double,1> F(3);\n\tF(0) = sigma*(-X(0) + X(1));\n\tF(1) = (r- X(2))*X(0) - X(1);\n\tF(2) = X(0)*X(1) - b*X(2);\n\treturn F;\n}\n\n/*Array<double,1> Rotating_Lorenz_system(Array<double,1> X)\n{\n\t// ------ Parameters ------------------------\n\tdouble sigma = 16; //10;\n\tdouble r = 45.92; //28;\n\tdouble b = 4; //8.0/3;\n\t// ------------------------------------------\n\n\tArray<double,1> F(3);\n\tF(0) = sigma*(-X(0) + X(1));\n\tF(1) = (r- X(2))*X(0) - X(1);\n\tF(2) = X(0)*X(1) - b*X(2);\n\treturn F;\n}*/\n\nArray<double,1> linearized_Lorenz_system(Array<double,1> E, Array<double,1> X)\n{\n\t// X is the reference trajectory while\n\t// E is the error along the refrence trajectory.\n\t// ------ Parameters ------------------------\n\tdouble sigma = 10;\n\tdouble r = 28;\n\tdouble b = 8.0/3;\n\t// ------------------------------------------\n\n\tArray<double,1> F(3);\n\tF(0) = sigma*(-E(0) + E(1));\n\tF(1) = (r- X(2))*E(0) - E(1)- X(0)*E(2);\n\tF(2) = X(1)*E(0) + X(0)*E(1)- b*E(2);\n\treturn F;\n}\n\ndouble max_lypo_expo(Array<double,1> X, double dt, Array<double,1> (*F)(Array<double,1>) )\n{\n\t\n\t// Array<double,1> X(3);\t\t\t\t// State vector for the reference trajectory\n\t// X = -3.16,-5.31,13.31;\t\t\t\t// Initial condition r = 28\n\t// X = 0.62225717,-0.08232857,30.60845379;\t\t\t\t// Initial condition r = 45.92\n\t// X = 4.29033, -0.577049, 28.8962;\n\n\n\tint T_transient = 32000;\n\t// ======  Removing the transience to enter the attractor========\n\tfor (int i = 0; i < T_transient; ++i)\n\t{\n\t\tX = RK4_integrator(X, dt, F);\n\t}\n\t// ==============================================================\n\n\tcout<<X<<endl;\t\t\t\t\t\t// After transient, the initial condition to start with.\n\t// ======================== Calculation of Lyapunov exponent ===============================\n\tArray<double,1> Y(3);\t\t\t\t// State vector for the second trajectory\n\n\tArray<double,1> E(3);\t\t\t\t// Tangent vector\n\tE = 1e-8,0,0;\t\t\t\t\t\t// Initial tangent vector\n\n\tdouble d0;\n\td0 = Euclidean_measure(E); \t\t\t// Initial error\t\t\t\t\t\n\tdouble d = 0;\t\t\t\t\t\t// length of tangent vector after one iteration\n\tdouble div_rate = 0;\t\t\t\t// divergence rate of trajectories defined as log(d/d0).\n\tdouble le=0;\t\t\t\t\t\t// Lyapunov exponent defined as the average of div_rate along the trajectories.\n\tint T = 100000;\n\t// time_series_file.open(\"test_data_lypo_r45.d\");\n\tfor (int i = 1; i <= T; ++i)\n\t{\n\t\tY = X+E;\t\t\t\t\t\t// Initial condition for the second trajectory\n\n\t\t//------Simultaneous evolution of the two trajectories by one time step ------\n\t\tX = RK4_integrator(X, dt, F);\n\t\tY = RK4_integrator(Y, dt, F);\n\t\t//---------------------------------------------------------------------------\n\n\t\tE = Y-X;\t\t\t\t\t\t// The tangent vector after one time step\n\t\t// cout<<E<<endl;\n\t\td = Euclidean_measure(E);\t\t// Length of the tangent vector\n\t\t// cout<<\"d: \"<<d<<endl;\n\t\tdiv_rate = log(d/d0);\t\t\t// Local divergence rate of the trajectories \n\t\tle +=div_rate;\t\t\t\t\t// For calculating running average of divergence rate\t\n\t\tE = (d0/d)*E;\t\t\t\t\t// Renormalization of the tangent vector to length d0\n\t\t// cout<<E<<endl;\n\t\t// time_series_file<<div_rate<<endl;\t// Writing local div rate in file\n\t\tif (i%1000==0)\n\t\t{\n\t\t\tcout<<i<<\"\\t\"<<le/i<<endl;\t\t//  Writing running average on std output \n\t\t}\n\t}\n\t// time_series_file.close();\n\tle = le/(T*dt);\n\tcout<<\"Lyapunov exponent: \\t\"<<le<<endl;\t\t//  Writing running average on std output \n\n\t// =========================================================================================\n\treturn le;\n\n}\n", "meta": {"hexsha": "0d09c0ce0cb4b88105f5deeb77fe104e5841ba0f", "size": 6266, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mle.cc", "max_stars_repo_name": "shail-kumar/DST", "max_stars_repo_head_hexsha": "5a52dd838a18894544e964e4c57c52d31d6ad10d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mle.cc", "max_issues_repo_name": "shail-kumar/DST", "max_issues_repo_head_hexsha": "5a52dd838a18894544e964e4c57c52d31d6ad10d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mle.cc", "max_forks_repo_name": "shail-kumar/DST", "max_forks_repo_head_hexsha": "5a52dd838a18894544e964e4c57c52d31d6ad10d", "max_forks_repo_licenses": ["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.7156862745, "max_line_length": 143, "alphanum_fraction": 0.5485157996, "num_tokens": 2003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6845373144005447}}
{"text": "/*\r\n * BezierCurve.cpp\r\n *\r\n *  Created on: Dec 5, 2008\r\n *      Author: eddyc\r\n */\r\n\r\n#include <iostream>\r\n#include <assert.h>\r\n#include <vector>\r\n#include <cmath>\r\n#include \"Point.h\"\r\n#include \"Vector.h\"\r\n#include \"matrix.h\"\r\n#include \"BezierCurve.h\"\r\n#include <boost/foreach.hpp>\r\n\r\nusing namespace std;\r\nusing namespace math;\r\n\r\nBezierCurve::BezierCurve(Point p1, Point p2, Point p3, Point p4) {\r\n\tthis->controls.SetSize(4,4);\r\n\tcontrols(0,0) = p1;\r\n\tcontrols(1,0) = p2;\r\n\tcontrols(2,0) = p3;\r\n\tcontrols(3,0) = p4;\r\n\tcurve.push_back(p1);\r\n\tcurve.push_back(p2);\r\n\tcurve.push_back(p3);\r\n\tcurve.push_back(p4);\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::BezierCurve(vector<Point> controls) : curve(controls) {\r\n\tassert(controls.size() == 4);\r\n\tthis->controls(0,0) = controls[0];\r\n\tthis->controls(1,0) = controls[1];\r\n\tthis->controls(2,0) = controls[2];\r\n\tthis->controls(3,0) = controls[3];\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::BezierCurve(matrix<Point> c) : controls(c) {\r\n\tcurve.push_back(c(0,0));\r\n\tcurve.push_back(c(1,0));\r\n\tcurve.push_back(c(2,0));\r\n\tcurve.push_back(c(3,0));\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::~BezierCurve() {\r\n\r\n}\r\n\r\nvoid BezierCurve::initMatrices() {\r\n\tSk.SetSize(4,4);\r\n\tSk(0,0) = 1.0;\r\n\tSk(1,0) = Sk(1,1) = Sk(2,1) = 0.5;\r\n\tSk(2,0) = Sk(2,2) = 0.25;\r\n\tSk(3,0) = Sk(3,3) = 1.0 / 8.0;\r\n\tSk(3,1) = Sk(3,2) = 3.0 / 8.0;\r\n\r\n\tSi.SetSize(4,4);\r\n\tSi(0,3) = Si(2,1) = 1.0;\r\n\tSi(1,2) = Si(3,0) = -1.0;\r\n\tSi(1,3) = 2.0;\r\n\tSi(2,2) = -4.0;\r\n\tSi(2,3) = 4.0;\r\n\tSi(3,1) = 6.0;\r\n\tSi(3,2) = -12.0;\r\n\tSi(3,3) = 8.0;\r\n}\r\n\r\nmatrix<Point> BezierCurve::apply(matrix<double> S, matrix<Point> controls) {\r\n\tmatrix<Point> newControls(4,1);\r\n\tnewControls(0,0) = S(0,0) * controls(0,0) + S(0,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(0,2) * controls(2,0) + S(0,3) * controls(3,0);\r\n\tnewControls(1,0) = S(1,0) * controls(0,0) + S(1,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(1,2) * controls(2,0) + S(1,3) * controls(3,0);\r\n\tnewControls(2,0) = S(2,0) * controls(0,0) + S(2,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(2,2) * controls(2,0) + S(2,3) * controls(3,0);\r\n\tnewControls(3,0) = S(3,0) * controls(0,0) + S(3,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(3,2) * controls(2,0) + S(3,3) * controls(3,0);\r\n\treturn newControls;\r\n}\r\n\r\nvoid BezierCurve::refine(int level) {\r\n\tmatrix<Point> subdivision = controls;\r\n\tcurve.clear();\r\n\r\n\t// get the first subdivision by applying Sk level times\r\n\tfor (int k = 0; k < level; k++)\r\n\t\tsubdivision = apply(Sk, subdivision);\r\n\tcurve.push_back(subdivision(0,0));\r\n\tcurve.push_back(subdivision(1,0));\r\n\tcurve.push_back(subdivision(2,0));\r\n\tcurve.push_back(subdivision(3,0));\r\n\r\n\t// get subsequent subdivisions by applying Si 2^level - 1 times\r\n\tfor (int i = 0; i < (int)pow(2.0,level) - 1; i++) {\r\n\t\tsubdivision = apply(Si, subdivision);\r\n\t\tcurve.push_back(subdivision(0,0));\r\n\t\tcurve.push_back(subdivision(1,0));\r\n\t\tcurve.push_back(subdivision(2,0));\r\n\t\tcurve.push_back(subdivision(3,0));\r\n\t}\r\n}\r\n\r\nvoid BezierCurve::print() {\r\n\tBOOST_FOREACH(Point p, curve) {\r\n\t\tcout << p << endl;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "bf3a839228f07137f463ae7b9865497bdc422391", "size": 2967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BezierCurve.cpp", "max_stars_repo_name": "eddy-chan/midas", "max_stars_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "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": "BezierCurve.cpp", "max_issues_repo_name": "eddy-chan/midas", "max_issues_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "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": "BezierCurve.cpp", "max_forks_repo_name": "eddy-chan/midas", "max_forks_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "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.0263157895, "max_line_length": 77, "alphanum_fraction": 0.5995955511, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6845373052796001}}
{"text": "/**\n * \\file RobertBristowJohnsonFilter.cpp\n */\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"RobertBristowJohnsonFilter.h\"\n#include \"IIRFilter.h\"\n\nnamespace ATK\n{\n  template<typename DataType>\n  RobertBristowJohnsonLowPassCoefficients<DataType>::RobertBristowJohnsonLowPassCoefficients(int nb_channels)\n    :Parent(nb_channels), Q(1)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 - cosw0)/2 / (1 + alpha);\n    coefficients_in[1] = (1 - cosw0) / (1 + alpha);\n    coefficients_in[0] = (1 - cosw0) / 2 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonLowPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonLowPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonHighPassCoefficients<DataType>::RobertBristowJohnsonHighPassCoefficients(int nb_channels)\n    :Parent(nb_channels), Q(1)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 + cosw0) / 2 / (1 + alpha);\n    coefficients_in[1] = -(1 + cosw0) / (1 + alpha);\n    coefficients_in[0] = (1 + cosw0) / 2 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonHighPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonHighPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonBandPassCoefficients<DataType>::RobertBristowJohnsonBandPassCoefficients(int nb_channels)\n    :Parent(nb_channels), Q(1)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = Q * alpha / (1 + alpha);\n    coefficients_in[1] = 0;\n    coefficients_in[0] = - Q * alpha / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonBandPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonBandPass2Coefficients<DataType>::RobertBristowJohnsonBandPass2Coefficients(int nb_channels)\n    :Parent(nb_channels), Q(1)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonBandPass2Coefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = alpha / (1 + alpha);\n    coefficients_in[1] = 0;\n    coefficients_in[0] = -alpha / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonBandPass2Coefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonBandPass2Coefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonBandStopCoefficients<DataType>::RobertBristowJohnsonBandStopCoefficients(int nb_channels)\n  :Parent(nb_channels), Q(1)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonBandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n    \n    coefficients_in[2] = 1 / (1 + alpha);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n    coefficients_in[0] = 1 / (1 + alpha);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandStopCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonBandStopCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  RobertBristowJohnsonAllPassCoefficients<DataType>::RobertBristowJohnsonAllPassCoefficients(int nb_channels)\n    :Parent(nb_channels), Q(1)\n  {\n  }\n\n  template <typename DataType>\n  void RobertBristowJohnsonAllPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n\n    coefficients_in[2] = (1 - alpha) / (1 + alpha);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n    coefficients_in[0] = 1;\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n    coefficients_out[0] = (alpha - 1) / (1 + alpha);\n  }\n\n  template <typename DataType_>\n  void RobertBristowJohnsonAllPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonAllPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonBandPassPeakCoefficients<DataType>::RobertBristowJohnsonBandPassPeakCoefficients(int nb_channels)\n  :Parent(nb_channels), Q(1)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n    \n    coefficients_in[2] = (1 + alpha * gain) / (1 + alpha / gain);\n    coefficients_in[1] = -2 * cosw0 / (1 + alpha / gain);\n    coefficients_in[0] = (1 - alpha * gain) / (1 + alpha / gain);\n    coefficients_out[1] = 2 * cosw0 / (1 + alpha / gain);\n    coefficients_out[0] = (alpha / gain - 1) / (1 + alpha / gain);\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonBandPassPeakCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonLowShelvingCoefficients<DataType>::RobertBristowJohnsonLowShelvingCoefficients(int nb_channels)\n  :Parent(nb_channels), Q(1), gain(1)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n    DataType d = (gain + 1) + (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n\n    coefficients_in[2] = gain * ((gain + 1) - (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n    coefficients_in[1] = 2 * gain * ((gain - 1) - (gain + 1) * cosw0) / d;\n    coefficients_in[0] = gain * ((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n    coefficients_out[1] = 2 * ((gain - 1) + (gain + 1) * cosw0) / d;\n    coefficients_out[0] = -((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonLowShelvingCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonLowShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonLowShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n  \n  template<typename DataType>\n  RobertBristowJohnsonHighShelvingCoefficients<DataType>::RobertBristowJohnsonHighShelvingCoefficients(int nb_channels)\n  :Parent(nb_channels), Q(1), gain(1)\n  {\n  }\n  \n  template <typename DataType>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    DataType w0 = 2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate;\n    DataType cosw0 = std::cos(w0);\n    DataType alpha = std::sin(w0) / (2 * Q);\n    DataType d = (gain + 1) - (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n    \n    coefficients_in[2] = gain * ((gain + 1) + (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n    coefficients_in[1] = -2 * gain * ((gain - 1) + (gain + 1) * cosw0) / d;\n    coefficients_in[0] = gain * ((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n    coefficients_out[1] = -2 * ((gain - 1) - (gain + 1) * cosw0) / d;\n    coefficients_out[0] = -((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if (Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonHighShelvingCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n  \n  template <typename DataType_>\n  void RobertBristowJohnsonHighShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if (gain <= 0)\n    {\n      throw std::out_of_range(\"gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ RobertBristowJohnsonHighShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template class RobertBristowJohnsonLowPassCoefficients<float>;\n  template class RobertBristowJohnsonLowPassCoefficients<double>;\n  template class RobertBristowJohnsonHighPassCoefficients<float>;\n  template class RobertBristowJohnsonHighPassCoefficients<double>;\n  template class RobertBristowJohnsonBandPassCoefficients<float>;\n  template class RobertBristowJohnsonBandPassCoefficients<double>;\n  template class RobertBristowJohnsonBandPass2Coefficients<float>;\n  template class RobertBristowJohnsonBandPass2Coefficients<double>;\n  template class RobertBristowJohnsonAllPassCoefficients<float>;\n  template class RobertBristowJohnsonAllPassCoefficients<double>;\n  template class RobertBristowJohnsonBandStopCoefficients<float>;\n  template class RobertBristowJohnsonBandStopCoefficients<double>;\n  template class RobertBristowJohnsonBandPassPeakCoefficients<float>;\n  template class RobertBristowJohnsonBandPassPeakCoefficients<double>;\n  template class RobertBristowJohnsonLowShelvingCoefficients<float>;\n  template class RobertBristowJohnsonLowShelvingCoefficients<double>;\n  template class RobertBristowJohnsonHighShelvingCoefficients<float>;\n  template class RobertBristowJohnsonHighShelvingCoefficients<double>;\n\n  template class IIRFilter<RobertBristowJohnsonLowPassCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonLowPassCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonHighPassCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonHighPassCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonBandPassCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonBandPassCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonBandPass2Coefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonBandPass2Coefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonBandStopCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonBandStopCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonAllPassCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonAllPassCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonBandPassPeakCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonBandPassPeakCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonLowShelvingCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonLowShelvingCoefficients<double> >;\n  template class IIRFilter<RobertBristowJohnsonHighShelvingCoefficients<float> >;\n  template class IIRFilter<RobertBristowJohnsonHighShelvingCoefficients<double> >;\n}\n", "meta": {"hexsha": "5d085961b67bf0f19028e9e74290ed9d2dc117e2", "size": 14662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "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": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 32.295154185, "max_line_length": 119, "alphanum_fraction": 0.6944482335, "num_tokens": 4241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6845321818692344}}
{"text": "/*\n * Code copied from\n * http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion\n */\n\n#ifndef INVERT_MATRIX_HPP\n#define INVERT_MATRIX_HPP\n\n// REMEMBER to update \"lu.hpp\" header includes from boost-CVS\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n/* Matrix inversion routine.\n   Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool invert_matrix (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {\n   typedef ublas::permutation_matrix<std::size_t> pmatrix;\n   \n   // create a working copy of the input\n   ublas::matrix<T> A(input);\n   \n   // create a permutation matrix for the LU-factorization\n   pmatrix pm(A.size1());\n   \n   // perform LU-factorization\n   int res = ublas::lu_factorize(A,pm);\n   if( res != 0 ) return false;\n\n   // create identity matrix of \"inverse\"\n   inverse.assign(ublas::identity_matrix<T>(A.size1()));\n\n   // backsubstitute to get the inverse\n   ublas::lu_substitute(A, pm, inverse);\n\n   return true;\n}\n#endif //INVERT_MATRIX_HPP\n", "meta": {"hexsha": "a86f1dde96552857811af9f1d2a4200019df22b7", "size": 1280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "invert_matrix.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.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.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": 29.7674418605, "max_line_length": 85, "alphanum_fraction": 0.728125, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6845112703861916}}
{"text": "#include <ipc/utils/eigen_ext.hpp>\n\n#include <stdexcept> // std::runtime_error\n\n#include <Eigen/Eigenvalues>\n\n#include <ipc/utils/logger.hpp>\n\nnamespace ipc {\n\n// Matrix Projection onto Positive Definite Cone\ntemplate <\n    typename _Scalar,\n    int _Rows,\n    int _Cols,\n    int _Options,\n    int _MaxRows,\n    int _MaxCols>\nEigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>\nproject_to_pd(\n    const Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& A,\n    double eps)\n{\n    assert(eps > 0);\n\n    // https://math.stackexchange.com/q/2776803\n    Eigen::SelfAdjointEigenSolver<\n        Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>>\n        eigensolver(A);\n    if (eigensolver.info() != Eigen::Success) {\n        IPC_LOG(error(\"unable to project matrix onto positive definite cone\"));\n        throw std::runtime_error(\n            \"unable to project matrix onto positive definite cone\");\n    }\n    // Check if all eigen values are positive.\n    // The eigenvalues are sorted in increasing order.\n    if (eigensolver.eigenvalues()[0] > 0.0) {\n        return A;\n    }\n    Eigen::DiagonalMatrix<double, Eigen::Dynamic> D(eigensolver.eigenvalues());\n    // Save a little time and only project the negative or zero values\n    for (int i = 0; i < A.rows(); i++) {\n        if (D.diagonal()[i] <= 0.0) {\n            D.diagonal()[i] = eps;\n        } else {\n            break;\n        }\n    }\n    return eigensolver.eigenvectors() * D\n        * eigensolver.eigenvectors().transpose();\n}\n\n// Matrix Projection onto Positive Semi-Definite Cone\ntemplate <\n    typename _Scalar,\n    int _Rows,\n    int _Cols,\n    int _Options,\n    int _MaxRows,\n    int _MaxCols>\nEigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>\nproject_to_psd(\n    const Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& A)\n{\n    // https://math.stackexchange.com/q/2776803\n    Eigen::SelfAdjointEigenSolver<\n        Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>>\n        eigensolver(A);\n    if (eigensolver.info() != Eigen::Success) {\n        IPC_LOG(\n            error(\"unable to project matrix onto positive semi-definite cone\"));\n        throw std::runtime_error(\n            \"unable to project matrix onto positive definite cone\");\n    }\n    // Check if all eigen values are zero or positive.\n    // The eigenvalues are sorted in increasing order.\n    if (eigensolver.eigenvalues()[0] >= 0.0) {\n        return A;\n    }\n    Eigen::DiagonalMatrix<double, Eigen::Dynamic> D(eigensolver.eigenvalues());\n    // Save a little time and only project the negative values\n    for (int i = 0; i < A.rows(); i++) {\n        if (D.diagonal()[i] < 0.0) {\n            D.diagonal()[i] = 0.0;\n        } else {\n            break;\n        }\n    }\n    return eigensolver.eigenvectors() * D\n        * eigensolver.eigenvectors().transpose();\n}\n\ntemplate <typename DerivedA, typename DerivedB, typename Result>\nResult cross(\n    const Eigen::MatrixBase<DerivedA>& a, const Eigen::MatrixBase<DerivedB>& b)\n{\n    assert(a.size() == 3 && b.size() == 3);\n    Result c(a.rows(), a.cols());\n    c(0) = a(1) * b(2) - a(2) * b(1);\n    c(1) = a(2) * b(0) - a(0) * b(2);\n    c(2) = a(0) * b(1) - a(1) * b(0);\n    return c;\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "aa50b82c34aec209a1253da6456cd28456682454", "size": 3281, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/utils/eigen_ext.tpp", "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/utils/eigen_ext.tpp", "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/utils/eigen_ext.tpp", "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": 30.9528301887, "max_line_length": 80, "alphanum_fraction": 0.6205425175, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6845112654451907}}
{"text": "#include <PCP/Curvature/Curvature.h>\n#include <PCP/Geometry/Geometry.h>\n\n#include <PCP/SpacePartitioning/KdTree.h>\n\n#include <Eigen/Eigenvalues>\n\nnamespace pcp {\n\n// see https://perso.liris.cnrs.fr/julie.digne/articles/compute_wavejets.m\nPointWiseEstimationData CurvatureComputer_WJets::compute(const Geometry& points, int i0, Scalar s) const\n{\n    constexpr auto order = 2;\n    constexpr auto I     = std::complex<Scalar>(0,1); // complex number 0+i\n\n    // % compute PCA normal\n    Matrix3 C      = Matrix3::Zero();\n    Vector3 m      = Vector3::Zero();\n    int     nneigh = 0;\n\n    for(int i : points.kdtree().range_neighbors(i0, s))\n    {\n        m      += points[i];\n        C      += points[i] * points[i].transpose();\n        nneigh += 1;\n    }\n\n    if(nneigh < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n    m /= nneigh;\n    C = C/nneigh - m * m.transpose();\n\n    // eigenvalues are positive and ordered\n    // eigenvectors are normalized\n    Eigen::SelfAdjointEigenSolver<Matrix3> solver(C);\n//    const Vector3 normal = solver.eigenvectors().col(0);\n    const Vector3 t2 = solver.eigenvectors().col(1);\n    const Vector3 t1 = solver.eigenvectors().col(2);\n    const Vector3 normal = t1.cross(t2);\n\n    Matrix3 P;\n    P.col(0) = t1;\n    P.col(1) = t2;\n    P.col(2) = normal;\n\n    // % compute Phi\n    constexpr int ncolM = order*order/2 + 3*order/2+1; // = 6\n    PCP_ASSERT(ncolM == 6);\n\n    Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, Eigen::Dynamic> M(nneigh,ncolM);\n    Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, 1>              b(nneigh);\n\n    M.setZero();\n    b.setZero();\n\n    int nei_count = 0;\n\n    int j=0;\n    for(int i : points.kdtree().range_neighbors(i0, s))\n    {\n        // % express neighbors in local coord system\n        const Vector3 locneighbors = P.transpose() * (points[i] - points[i0]);\n\n        // % switch to polar coordinates\n        const Scalar r     = locneighbors.head<2>().norm();\n        const Scalar theta = std::atan2(locneighbors.y(), locneighbors.x());\n              Scalar z     = locneighbors.z();\n\n        const Scalar normalized_r = r / s;\n        z = z / s;\n\n        const Scalar w = std::exp(-normalized_r * normalized_r/18.0);\n\n        int idx = 0;\n        for(int k=0; k<=order; ++k)\n        {\n            const Scalar rk = std::pow(normalized_r, k);\n            for(int n = -k; n <= k; n += 2)\n            {\n                M(j,idx) = rk * std::exp(I * Scalar(n) * theta) * w;\n                ++idx;\n            }\n        }\n        b[j] = z * w;\n        ++j;\n        ++nei_count;\n    }\n    if(nei_count < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n    Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, 1> Phi = M.colPivHouseholderQr().solve(b);\n\n    // % correct normal\n    Vector3 u = - t1 * std::imag(Phi(1) - Phi(2)) + t2 * std::real(Phi(2) + Phi(1)); // % axis\n    u.normalize();\n    Scalar gamma = - std::atan( 2 * std::abs(Phi(2))); // % angle\n\n    Vector3 nc = std::cos(gamma) * normal + (1 - std::cos(gamma)) * (normal.dot(u)) * u + std::sin(gamma) * u.cross(normal);\n    nc.normalize();\n    Vector3 t1c = t1 - (t1.transpose() * nc) * nc;\n    t1c.normalize();\n    Vector3 t2c = nc.cross(t1c);\n    t2c.normalize();\n\n    // % redo everything (instead of correcting the coefficients - quick and dirty method, to be improved later)\n    Matrix3 Pc;\n    Pc.col(0) = t1c;\n    Pc.col(1) = t2c;\n    Pc.col(2) = nc;\n\n    M.setZero();\n    b.setZero();\n\n    nei_count = 0;\n\n    j=0;\n    for(int i : points.kdtree().range_neighbors(i0, s))\n    {\n        // % express neighbors in local coord system\n        const Vector3 locneighbors = Pc.transpose() * (points[i] - points[i0]);   // Pc not P !\n\n        // switch to polar coordinates\n        const Scalar r     = locneighbors.head<2>().norm();\n        const Scalar theta = std::atan2(locneighbors.y(), locneighbors.x());\n              Scalar z     = locneighbors.z();\n\n        const Scalar normalized_r = r / s;\n        z = z / s;\n\n        const Scalar w  = std::exp(-normalized_r*normalized_r/18.0);\n\n        int idx = 0;\n        for(int k=0; k<=order; ++k)\n        {\n            const Scalar rk = std::pow(normalized_r, k);\n            for(int n = -k; n <= k; n += 2)\n            {\n                M(j,idx) = rk * std::exp(I * Scalar(n) * theta) * w;\n                ++idx;\n            }\n        }\n        b[j] = z * w;\n        ++j;\n        ++nei_count;\n    }\n    if(nei_count < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n    Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, 1> Phicorr = M.colPivHouseholderQr().solve(b);\n\n    // % compute real(a0) and |an| n>=1\n//    idx = 1;\n//    an=zeros(order+1,1);\n//    for k=0:order\n//        for n = -k:2:k\n//          if n>=0\n//           an(n+1) = an(n+1) + Phicorr(idx)/(k+2);\n//          end\n//          idx=idx+1;\n//        end\n//    end\n//    an(1)=real(an(1));%imaginary part is 0\n//    an(2:end)=abs(an(2:end));\n\n\n//    const std::complex<Scalar> phi_0_0  = Phicorr(0);\n//    const std::complex<Scalar> phi_1_m1 = Phicorr(1);\n//    const std::complex<Scalar> phi_1_p1 = Phicorr(2);\n    const std::complex<Scalar> phi_2_m2 = Phicorr(3);\n    const std::complex<Scalar> phi_2_0  = Phicorr(4);\n    const std::complex<Scalar> phi_2_p2 = Phicorr(5);\n\n    const Vector3 N = nc; // corrected normal !\n\n    Scalar k1 = 2 * std::real(phi_2_0 + phi_2_p2 + phi_2_m2);\n    Scalar k2 = 2 * std::real(phi_2_0 - phi_2_p2 - phi_2_m2);\n\n    if(std::abs(k2) > std::abs(k1)) std::swap(k1,k2);\n\n    // reset to original scale\n    k1 /= s;\n    k2 /= s;\n\n    const Scalar H = 0.5 * (k1 + k2);\n\n    return PointWiseEstimationData(k1, k2, H, N, Vector3::Constant(666), Vector3::Constant(666), nei_count);\n}\n\n} // namespace pcp\n", "meta": {"hexsha": "31b8f0486404ef1428106862865fefedbd7b90e5", "size": 5725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/src/PCP/Curvature/Methods/WJets.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/WJets.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/WJets.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": 30.4521276596, "max_line_length": 124, "alphanum_fraction": 0.5591266376, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6844791774091362}}
{"text": "#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef struct {\n\tMatrixXd Gamma;\n\tMatrixXd P;\n\tMatrixXd B;\n    double dt;\n} AdaptiveLaw_Config_t;\n\nclass AdaptiveLaw {\nprotected:\n    double dt;\n    MatrixXd BigTheta, Gamma, P, B;\n    \npublic:\n    AdaptiveLaw(void);\n    ~AdaptiveLaw(void);\n    \n    void initialize(const AdaptiveLaw_Config_t _config);\n    void reset();\n    void update(const VectorXd error, const VectorXd  phi);\n    void get_gains(MatrixXd &outputs);\n};\n\n", "meta": {"hexsha": "34a1c416ef3c62b99cbcdc053248426341a09f28", "size": 494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/include/AdaptiveLaw.hpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/include/AdaptiveLaw.hpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_controllers/include/AdaptiveLaw.hpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 17.6428571429, "max_line_length": 59, "alphanum_fraction": 0.6963562753, "num_tokens": 117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026663679976, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6844352826100446}}
{"text": "#include <Eigen/Core>\n\nnamespace Eigen {\nnamespace Vector {\ntemplate <class T>\ninline void push_back(Eigen::Matrix<T,Eigen::Dynamic,1>& v, const T d) {\n  Eigen::Matrix<T,Eigen::Dynamic,1> tmp = v;\n  v.resize(tmp.size() + 1);\n  v.head(tmp.size()) = tmp;\n  v[v.size()-1] = d;\n}\ntemplate <class T>\ninline void wedge(Eigen::Matrix<T,3,3>& mat, const Eigen::Matrix<T,3,1>&v) {\n  mat(0,0) = 0.0;\n  mat(0,1) = -v[2];\n  mat(0,2) = v[1];\n  mat(1,0) = v[2];\n  mat(1,1) = 0.0;\n  mat(1,2) = -v[0];\n  mat(2,0) = -v[1];\n  mat(2,1) = v[0];\n  mat(2,2) = 0.0;\n}\n}\n}\n", "meta": {"hexsha": "8fd963421694aa8d3fa32e3520e3b4e27ca78a89", "size": 549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils.hpp", "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/utils.hpp", "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/utils.hpp", "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": 21.1153846154, "max_line_length": 76, "alphanum_fraction": 0.5591985428, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6844233953300184}}
{"text": "#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <numeric>\n#include <boost/integer/common_factor.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing boost::multiprecision::cpp_int;\n\n\n\n\nconst int MOD = 1000000007;\n\ncpp_int gcd(cpp_int a, cpp_int b) {\n    if (a < b) swap(a, b);\n    return b == 0 ? a : gcd(b, a % b);\n}\n\ncpp_int lcm(cpp_int a, cpp_int b) {\n    return a * b / gcd(a, b);\n}\n\nint main() {\n    int n;\n    const int SIZE = 10007;\n\n    cpp_int A[SIZE];\n    scanf(\"%d\", &n);\n    for (auto i = 0; i < n; i ++) {\n        cin >> A[i];\n    }\n    cpp_int prod = lcm(A[0], A[1]);\n    for(auto i = 2; i < n; i ++) prod = lcm(prod, cpp_int(A[i]));\n    cpp_int sum = 0;\n    for(auto i = 0; i < n; i++) {\n        sum += (prod / A[i]);\n        sum %=  MOD;\n    }\n    std::cout << sum << endl;\n    return 0;\n}\n", "meta": {"hexsha": "a741dd9af1817a3e942dfdbac7441a1ac49ba560", "size": 846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc/152/E.cpp", "max_stars_repo_name": "515hikaru/solutions", "max_stars_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc/152/E.cpp", "max_issues_repo_name": "515hikaru/solutions", "max_issues_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-12-29T17:57:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-16T16:36:04.000Z", "max_forks_repo_path": "abc/152/E.cpp", "max_forks_repo_name": "515hikaru/solutions", "max_forks_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_forks_repo_licenses": ["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.6744186047, "max_line_length": 65, "alphanum_fraction": 0.5413711584, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6843240965259647}}
{"text": "#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/mat_ZZ.h>\n#include <gmp.h>\n\n#include \"FFT.h\"\n#include \"params.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\nvoid FFTStep(CC_t * const f_fft, RR_t const * const f, const unsigned long N, const CC_t w0)\n{\n    if(N==1)\n    {\n        f_fft[0] = f[0];\n    }\n    else\n    {\n        if(N==2)\n        {\n            f_fft[0] = f[0] + ii*f[1];\n            f_fft[1] = f[0] - ii*f[1];\n        }\n        else\n        {\n            assert(N%2==0);\n            RR_t f0[N0/2], f1[N0/2];\n            CC_t f0_fft[N0/2], f1_fft[N0/2], wk, w02;\n            unsigned int k;\n            for(k=0; k<(N/2); k++)\n            {\n                f0[k] = f[2*k];\n                f1[k] = f[2*k+1];\n            }\n\n            w02 = w0*w0;\n            wk = w0;\n            FFTStep(f0_fft, f0, N/2, w02);\n            FFTStep(f1_fft, f1, N/2, w02);\n            for(k=0; k<N; k++)\n            {\n                f_fft[k] = f0_fft[k%(N/2)] + wk*f1_fft[k%(N/2)];\n                wk *= w02;\n            }\n        }\n    }\n}\n\n\nvoid ReverseFFTStep(CC_t * const f, CC_t const * const f_fft, const unsigned long N, const CC_t w0)\n{\n    if(N!=2)\n    {\n        assert(N%2==0);\n        CC_t f0[N0/2], f1[N0/2];\n        CC_t f0_fft[N0/2], f1_fft[N0/2], w02, wk;\n        unsigned int k;\n\n        w02 = w0*w0;\n        wk = w0;\n\n        for(k=0; k<N/2; k++)\n        {\n            f0_fft[k] = (f_fft[k] + f_fft[k+(N/2)])*0.5l;\n            f1_fft[k] = wk*(f_fft[k] - f_fft[k+(N/2)])*0.5l;\n            wk *= w02;\n        }\n        ReverseFFTStep(f0, f0_fft, (N/2), w02);\n        ReverseFFTStep(f1, f1_fft, (N/2), w02);\n\n        for(k=0; k<N/2; k++)\n        {\n            f[2*k] = f0[k];\n            f[2*k+1] = f1[k];\n        }\n    }\n    else\n    {\n        f[0] = (f_fft[0] + f_fft[1])*0.5l;\n        f[1] = (f_fft[0] - f_fft[1])*(-0.5l*ii);\n    }\n}\n\n\nvoid MyRealReverseFFT(double * const f, CC_t const * const f_fft)\n{\n    CC_t fprime[N0];\n    unsigned int i;\n    ReverseFFTStep(fprime, f_fft, N0, omega_1);\n\n    for(i=0; i<N0; i++)\n    {\n        f[i] = (fprime[i]).real();\n    }\n}\n\n\nvoid MyIntReverseFFT(long int * const f, CC_t const * const f_fft)\n{\n    CC_t fprime[N0];\n    unsigned int i;\n\n    ReverseFFTStep(fprime, f_fft, N0, omega_1);\n    for(i=0; i<N0; i++)\n    {\n        f[i] = ((long int) round( fprime[i].real() ) );\n    }\n}\n\n\nvoid MyIntFFT(CC_t * f_FFT, const long int * const f)\n{\n    RR_t f_double[N0];\n    unsigned int i;\n    for(i=0; i<N0; i++)\n    {\n        f_double[i] = ( RR_t ( f[i] ) );\n    }\n\n    FFTStep(f_FFT, f_double, N0, omega);\n}\n\n\nvoid ZZXToFFT(CC_t * f_FFT, const ZZX f)\n{\n    RR_t f_double[N0];\n    unsigned int i;\n\n    assert(deg(f)==N0-1);\n    assert(MaxBits(f)<900);\n    for(i=0; i<N0; i++)\n    {\n        f_double[i] = ( RR_t ( conv<double>(f[i]) ) );\n    }\n\n    FFTStep(f_FFT, f_double, N0, omega);\n}\n\n\nvoid FFTToZZX(ZZX& f, CC_t const * const f_FFT)\n{\n    double f_double[N0];\n    unsigned int i;\n    MyRealReverseFFT(f_double, f_FFT);\n\n    f.SetLength(N0);\n    for(i=0; i<N0; i++)\n    {\n        f[i] = conv<ZZ>(round(f_double[i]));\n    }\n\n}\n", "meta": {"hexsha": "2e947e3968413563e49be8513e6220048e86a131", "size": 3178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/FFT.cc", "max_stars_repo_name": "Rbehnia/Full_PEKS", "max_stars_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-12-28T22:18:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T08:25:19.000Z", "max_issues_repo_path": "NTRU-PEKS/FFT.cc", "max_issues_repo_name": "Rbehnia/Full_PEKS", "max_issues_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-19T09:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-31T12:56:22.000Z", "max_forks_repo_path": "NTRU-PEKS/FFT.cc", "max_forks_repo_name": "Rbehnia/Full_PEKS", "max_forks_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T05:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T08:17:57.000Z", "avg_line_length": 19.8625, "max_line_length": 99, "alphanum_fraction": 0.4647577093, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6843014277758498}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n#include <array>\n\nint main(int argc, char **argv) \n{\n  // exploit namespaces to shorten code\n  using namespace boost::numeric::ublas;\n  using std::cout; \n  using std::endl;\n\n  // declare three 3x3 matrices of complex<long double> elements\n  matrix<std::complex<long double> > m(3, 3), n(3, 3), o(3, 3);\n\n  // iterate over 3x3 matrix entries\n  // r : row index\n  // c : column index\n  for (unsigned r = 0; r < m.size1(); r++) {\n    for (unsigned c = 0; c < m.size2(); c++) {\n      // enumerated matrix entries\n      m(r,c) = 3 * r + c;\n\n      // complex numbers designating rows and cols\n      n(r,c) = r + c * std::complex<long double>(0,1); \n\n      // elementwise square of n\n      o(r,c) = std::pow(n(r,c), 2);\n    }\n  }\n    \n  std::array<int,3> real = {-1, 0, 1};\n  std::array<int,3> imag = {-1, 0, 1};\n  int rs = real.size()-1;\n    \n  matrix<std::complex<long double> > p(3,3);\n    \n  for (unsigned r = 0; r < real.size(); r++) {\n      for (unsigned c = 0; c < imag.size(); c++) {\n          p(r,c) = real[rs-r] + imag[c] * std::complex<long double>(0,1);\n      }\n  }\n\n  // print to screen as demonstration\n  cout << \"m:\" << endl;\n  cout << m << endl;\n  cout << endl << \"n:\" << endl;\n  cout << n << endl;\n  cout << endl << \"o:\" << endl;\n  cout << n << endl;\n  cout << endl << \"m + n:\" << endl;\n  cout << m + n << endl;\n  cout << endl << \"m * n:\" << endl;\n  cout << prod(m, n) << endl;\n  cout << endl << \"n * n - o:\" << endl;\n  cout << prod(n, n) - o << endl;\n    \n  cout << \"complex plane:\" << endl;\n    for(unsigned i = 0;i<p.size1();i++) {\n        for (unsigned j = 0; j<p.size2();++j)\n        {\n            cout<<p(i,j);\n        }\n        cout<<endl;\n    }\n}\n", "meta": {"hexsha": "68abe6909257f26bc7e2288b4d80c57eef774f5e", "size": 1765, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/boost_matrix.cc", "max_stars_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_stars_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_stars_repo_licenses": ["MIT"], "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/blas/boost_matrix.cc", "max_issues_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_issues_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_issues_repo_licenses": ["MIT"], "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/blas/boost_matrix.cc", "max_forks_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_forks_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_forks_repo_licenses": ["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.3432835821, "max_line_length": 73, "alphanum_fraction": 0.5150141643, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882383, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6842925662360129}}
{"text": "/* Copyright (C) 2017 IBM Corp.\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 *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/****************************************************************************\nmat_l: a module for handling matrices of type long\nUsed mainly in TDMatrix.cpp as trapDoorMatR is of type mat_l\n*****************************************************************************/\n#include <cassert>\n#include <stdexcept>\n\n#include <NTL/matrix.h>\n#include \"utils/tools.h\"\n#include \"mat_l.h\"\n#include <cstdio>\n#include <cstdlib>\n\nNTL_CLIENT\n\n//#define DEBUG\n\n//X = I * n, set the dimension to n, clear and then set to value\nvoid ident(mat_l& X, long n)\n{\n    X.SetDims(n,n);\n    clear(X);\n    for (long i = 0; i < n; i++)\n        X[i][i] = 1L;\n}\n\nbool isZero(const mat_l& M)\n{\n  for (long i=0; i<M.NumRows(); i++) for (long j=0; j<M.NumCols(); j++) {\n      if (M[i][j] != 0)\n\treturn false;\n    }\n  return true;\n}\n\n/* square - compute X := A*A^t or X := A^t*A, depending on transpose flag.\n   Does not reset the matrix X dimension as long as it is large enough\n*/\nvoid square(mat_l& X, const mat_l& A, bool transpose)\n{\n    long n = A.NumRows();\n    long m = A.NumCols();\n\n    // If X is not large enough, set its dimension. If X is large enough then\n    // its dimension is not reset, and only the top-left n-by-m is affected.\n\n    if (transpose) swap(n,m);\n    if (X.NumRows() < n || X.NumCols() < m)\n        X.SetDims(n,n);\n\n    for (long i=0; i<n; i++)\n    {\n        for (long j=0; j<n; j++)\n        {\n            X[i][j] = 0;\n            if (transpose)\n            {\n                for (long k=0; k<m; k++)\n                    X[i][j] += A[k][i] * A[k][j];\n            }\n            else\n            {\n                for (long k=0; k<m; k++)\n                    X[i][j] += A[i][k] * A[j][k];\n            }\n        }\n    }\n}\n\n\n\n//mul - does not reset the matrix dimension as long as it is large enough\n//multiplies a vector and a matrix\n\nvoid mul(vec_l& x, const vec_l& a, const mat_l& B)\n{\n    long l = a.length();\n    long m = B.NumCols();\n\n    if (l != B.NumRows())\n    {\n        cerr << \"mul(vec_l, mat_l) dimension mismatch, vec[\"<< l\n             << \"] x mat[\" << B.NumRows() << \"][\" << B.NumCols() << \"]\\n\";\n        exit(0);\n    }\n\n    int oRow,iIndex, val;\n\n    x.SetLength(l);\n    for (oRow = 0; oRow < m; oRow++)\n    {\n        val=0;\n        for (iIndex = 0; iIndex<l; iIndex++)\n        {\n            val += (a.at(iIndex) * B[iIndex][oRow]);\n        }\n        x[oRow] = val;\n    }\n}\n\n//compute x = A*b, A is a matrix, x and b are vectors,\n//function sets length of x to be equal to A.NumRows()\nvoid mul(vec_l& x, const mat_l& A, const vec_l& b)\n{\n    int nRows, nCols, nVecSize;\n    int i,j;\n    long val;\n\n    nCols = A.NumCols();\n    nVecSize = b.length();\n    nRows = A.NumRows();\n    x.SetLength(nRows);\n\n    if (nCols != nVecSize)\n    {\n        throw std::logic_error(\"Matrix dimensions do not match\");\n        return;\n    }\n\n    for (i = 0; i < nRows; i++)\n    {\n        val=0;\n        for (j = 0; j < nVecSize; j++)\n            val+= A[i][j] * b.at(j);\n        x[i] = val;\n    }\n}\n\n//matrix multiplication by a number\nvoid mul(mat_l& X, const mat_l& A, long b)\n{\n    long n = A.NumRows();\n    long m = A.NumCols();\n\n    X.SetDims(n, m);\n    long i, j;\n\n    for (i = 0; i < n; i++)\n        for (j = 0; j < m; j++)\n            X[i][j] = A[i][j] * b;\n}\n\n\n// matrix multiplication, the most naive implementation\nvoid mul(mat_l& X, const mat_l& A, const mat_l& B)\n{\n    assert(A.NumCols() == B.NumRows());\n    mat_l tmp(INIT_SIZE, A.NumRows(), B.NumCols());\n    for (long i=0; i<tmp.NumRows(); i++) for (long j=0; j<tmp.NumCols(); j++)\n        {\n            tmp[i][j] = 0;\n            for (long k=0; k<A.NumCols(); k++)\n                tmp[i][j] += A[i][k] * B[k][j];\n        }\n    X = tmp;\n}\n\n//Reads and sets the size of the matrix and its values from an open file. The function gets the handle of the file to read from.\nlong readFromFile(mat_l& X, FILE* handle)\n{\n    long numRows,numCols;\n    long count = fread(&numRows,sizeof(long),1,handle);\n    count += fread(&numCols,sizeof(long),1,handle);\n    X.SetDims(numRows,numCols);\n    for (long i = 0; i < numRows; i++)\n        count+= fread(X[i].elts(), numCols*sizeof(long), 1, handle);\n    return count;\n}\n\n//Writes the size of the matrix and its values to an open file. Gets the handle of the file to write to.\nlong writeToFile(mat_l& X, FILE* handle)\n{\n    long numRows = X.NumRows();\n    long numCols = X.NumCols();\n    long count = fwrite(&numRows,sizeof(long),1,handle);\n    count += fwrite(&numCols,sizeof(long),1,handle);\n    for (long i = 0; i < numRows; i++)\n        count+= fwrite(X[i].elts(), numCols*sizeof(long), 1, handle);\n    return count;\n}\n", "meta": {"hexsha": "b501dfd9bd20bb0246b8e77c9981cbb6c2fa71cc", "size": 5206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mat_l.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "mat_l.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "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": "mat_l.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 27.1145833333, "max_line_length": 128, "alphanum_fraction": 0.5412985017, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6842925520155092}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::example::scalar_rp.cpp                                            //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. 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#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> //needed?\n#include <boost/math/tools/precision.hpp>\n#include <boost/mpl/int.hpp>\n\n#include <boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp>\n#include <boost/statistics/detail/kernel/estimation/rp_visitor.hpp>\n#include <boost/statistics/detail/kernel/estimation/estimator.hpp>\n#include <libs/statistics/detail/kernel/example/scalar_rp.h>\n\nvoid example_scalar_rp(std::ostream& out){\n    out << \"-> example_scalar_rp : \";\n    using namespace boost;\n\n    // This example shows how to compute a Rosenblatt-Parzen estimate of the \n    // density, p(x). The type used for each data-unit, here, is double\n\n    //Types\n    typedef double                                          val_;\n    typedef std::vector<val_>                               vec_;\n    typedef mt19937                                         urng_;\n    typedef normal_distribution<val_>                       norm_;\n    typedef variate_generator<urng_&,norm_>                 gen_;\n    typedef statistics::detail::kernel::scalar::gaussian_kernel<val_>      gauss_k_;\n    typedef statistics::detail::kernel::rp_visitor<gauss_k_,val_>   rp_visitor_;\n\n    // Contants\n    const val_ bandwidth = 0.5;\n    const val_ eps = math::tools::epsilon<val_>();\n    const unsigned n = 10;\n\n    // Initialization\n    vec_ dataset(n);\n    vec_ vec_rp; vec_rp.reserve(n);\n    urng_ urng;\n    norm_ norm;\n    gen_ gen(urng,norm);\n    std::generate_n(\n        begin(dataset),\n        n,\n        gen\n    );\n\n    // Computes a density estimate for each x in dataset\n    BOOST_FOREACH(val_& x,dataset){\n        val_ rp = for_each(\n            boost::begin(dataset),\n            boost::end(dataset),\n            rp_visitor_(bandwidth,x)\n        ).estimate();\n        vec_rp.push_back(rp);\n    } \n\n    // Same as previous but calls estimator instead of for_each\n    typedef sub_range<vec_> sub_x_;\n    typedef \n        statistics::detail::kernel::estimator<\n            sub_x_,\n            statistics::detail::kernel::rp_visitor,\n            gauss_k_\n        > estimator_;\n    estimator_ estimator(bandwidth); \n    sub_x_ sub_x(dataset);\n    estimator.train(sub_x);\n    vec_ vec_rp2; vec_rp2.reserve(n);\n    \n    for(unsigned i = 0; i<n; i++){\n        val_ x = dataset[i];\n        val_ rp = vec_rp[i];\n        val_ rp2 = estimator.predict(x);\n        BOOST_ASSERT(fabs(rp-rp2)<eps);\n    } \n            \n    out << \"<-\" << std::endl;\n\n}", "meta": {"hexsha": "9a4ffd5fc10d7ee06e62a954ac25a0f4bbbb086f", "size": 3252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/libs/statistics/detail/kernel/example/scalar_rp.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "kernel/libs/statistics/detail/kernel/example/scalar_rp.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "kernel/libs/statistics/detail/kernel/example/scalar_rp.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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.1333333333, "max_line_length": 84, "alphanum_fraction": 0.5661131611, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6842733805054972}}
{"text": "#include <iostream>\n#include <string>\n#include <iomanip>\n#include <fstream>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Straight_skeleton_2.h>\n#include <CGAL/Straight_skeleton_builder_traits_2.h>\n#include <CGAL/Straight_skeleton_builder_2.h>\n#include <boost/shared_ptr.hpp>\n#include <CGAL/gmp.h>\n#include <CGAL/Timer.h>\n\ntemplate<class K>\nvoid print_point ( CGAL::Point_2<K> const& p )\n{\n  //CGAL::exact(p);\n  std::cout <<  p.x() << \" \" << p.y();\n}\n\ntemplate<class K>\nvoid print_straight_skeleton( CGAL::Straight_skeleton_2<K> const& ss )\n{\n  typedef CGAL::Straight_skeleton_2<K> Ss ;\n  \n  typedef typename Ss::Vertex_const_handle     Vertex_const_handle ;\n  typedef typename Ss::Halfedge_const_handle   Halfedge_const_handle ;\n  typedef typename Ss::Halfedge_const_iterator Halfedge_const_iterator ;\n  \n  Halfedge_const_handle null_halfedge ;\n  Vertex_const_handle   null_vertex ;\n\n  std::cerr << \"Straight skeleton with \" << ss.size_of_vertices() \n            << \" vertices, \" << ss.size_of_halfedges()\n            << \" halfedges and \" << ss.size_of_faces()\n            << \" faces\" << std::endl ;\n            \n  for ( Halfedge_const_iterator i = ss.halfedges_begin(); i != ss.halfedges_end(); ++i )\n  {\n    if ( !i->is_bisector() ) continue;\n    std::cout << \"2 \" ;\n    print_point(i->opposite()->vertex()->point()) ;\n    std::cout << \" 0 \" ;\n    print_point(i->vertex()->point());\n    std::cout << \" 0\\n\" ;\n    //std::cout << \" \" << ( i->is_bisector() ? \"bisector\" : \"contour\" ) << std::endl;\n  }\n}\n\n\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel       EPEC;\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel       EPIC;\ntypedef CGAL::Simple_cartesian< CGAL::Lazy_exact_nt<CGAL::Gmpq> > SCLGQ;\ntypedef EPEC::Exact_kernel::FT                                EPEC_exact_ft;\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt       EPEC_with_sqrt;\n\n\n\ntemplate< class Kernel, class FT>\nvoid build_skeleton(const char* fname)\n{\n  typedef typename Kernel::Point_2                                         Point_2;\n  typedef CGAL::Polygon_2<Kernel>                                 Polygon_2;\n  typedef CGAL::Straight_skeleton_builder_traits_2<Kernel>        SsBuilderTraits;\n  typedef CGAL::Straight_skeleton_2<Kernel>                       Ss;\n  typedef CGAL::Straight_skeleton_builder_2<SsBuilderTraits,Ss>   SsBuilder;\n  \n  Polygon_2 pgn;\n  \n  std::ifstream input(fname);\n  \n  FT x,y;\n  while(input)\n  {\n    input >> x;\n    if (!input) break;\n    input >> y;\n    if (!input) break;\n    pgn.push_back( Point_2( typename Kernel::FT(x), typename Kernel::FT(y) ) );\n  }\n  input.close();\n  \n  std::cout << \"Polygon has \" << pgn.size() <<  \" points\\n\";\n  \n  if(!pgn.is_counterclockwise_oriented()) {\n      std::cerr << \"Polygon is not CCW Oriented\" << std::endl;\n  }\n  if(!pgn.is_simple()) {\n      std::cerr << \"Polygon is not simple\" << std::endl;\n  }  \n\n  CGAL::Timer time;\n  time.start();\n  SsBuilder ssb;\n  ssb.enter_contour(pgn.vertices_begin(), pgn.vertices_end());\n  boost::shared_ptr<Ss> straight_ske = ssb.construct_skeleton();\n  time.stop();\n  \n  std::cout << \"Time spent to build skeleton \" << time.time() << \"\\n\";\n  \n  if(!straight_ske->is_valid()) {\n      std::cerr << \"Straight skeleton is not valid\" << std::endl;\n  }\n\n  std::cerr.precision(60);\n  print_straight_skeleton(*straight_ske);\n  \n}\n\n\n\n\nint main(int argc, char** argv) {\n  if (argc!=2)\n    std::cerr << \"Usage: \" << argv[0] << \" polygon_points.txt\\n\";\n  else\n  {\n\n    std::cout <<\"Running with EPIC\\n\";\n    build_skeleton<EPIC, double>(argv[1]);\n    \n    std::cout <<\"Running with SCLGQ\\n\";\n    build_skeleton<SCLGQ, SCLGQ::FT>(argv[1]);\n\n    std::cout <<\"Running with EPEC_with_sqrt\\n\";\n    build_skeleton<EPEC_with_sqrt, EPEC_with_sqrt::FT>(argv[1]);\n\n    std::cout <<\"Running with EPEC\\n\";\n    build_skeleton<EPEC, EPEC_exact_ft>(argv[1]);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "58ddbe5bdcb7839d375664b13e28f095f768caa2", "size": 4066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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.4637681159, "max_line_length": 89, "alphanum_fraction": 0.6524840138, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6842733720425409}}
{"text": "/*!\n * @file neumann_bc.hpp\n * @brief Contains implementation of Neumann boundary conditions.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_NEUMANN_BC_HPP_\n#define INCLUDE_NEUMANN_BC_HPP_\n\n// Deal.ii\n#include <deal.II/base/function.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class NeumannBC\n * @brief Class implements scalar Neumann conditions.\n */\ntemplate <int dim>\nclass NeumannBC : public Function<dim>\n{\npublic:\n\tNeumannBC() : Function<dim>() {}\n\n\tvirtual double value(const Point<dim> &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n};\n\n\ntemplate <int dim>\ndouble\nNeumannBC<dim>::value(const Point<dim> &p,\n\t\t\t\t\t\t\t   const unsigned int /*component*/) const\n{\n\tdouble return_value = cos(2*PI_D*p(0)) * cos(2*PI_D*p(1));\n\n\treturn return_value;\n}\n\n\ntemplate <int dim>\nvoid\nNeumannBC<dim>::value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p] = cos(2*PI_D*points[p](0)) * cos(2*PI_D*points[p](1));\n\t} // end ++p\n}\n\n} // end namespace Coefficients\n\n#endif /* INCLUDE_NEUMANN_BC_HPP_ */\n", "meta": {"hexsha": "683b988fed77ffa2ae604b6c098d985bb0b61d06", "size": 1534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/neumann_bc.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/neumann_bc.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/neumann_bc.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 21.3055555556, "max_line_length": 66, "alphanum_fraction": 0.6812255541, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.6842661863777715}}
{"text": "/*\n *  vector_right_scale_test.cpp\n *  MTL\n *\n *  Created by Hui Li (huil@Princeton.EDU)\n *\n */\n\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/matrix/map_view.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/dot.hpp>\n\n\nusing namespace std;  \n\n\ntemplate <typename VectorU, typename VectorV, typename VectorW>\nvoid test(VectorU& u, VectorV& v, VectorW& w, const char* name)\n{\n    using mtl::dot;\n\n\t// test right scale\n    u= 3.0; v= 4.0; w= 5.0;\n\t\n    std::cout << name << \"  --- v= u*3 + w*4;:\\n\"; std::cout.flush();\n    v= u*3 + w*4;\n    cout << \"v: \" << v << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(v[0] != 29.0, mtl::runtime_error(\"v wrong\"));\n\t\n    std::cout << name << \"  --- u= 3; v= 4; u+= v+= (w= 5) * 3.0;:\\n\"; std::cout.flush();\n    u= 3; v= 4; \n    u+= v+= (w= 5.0) * 3.0;\n    cout << \"u: \" << u << \"v: \" << v << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(v[0] != 19.0, mtl::runtime_error(\"v wrong\"));\n    MTL_THROW_IF(u[0] != 22.0, mtl::runtime_error(\"u wrong\"));\n\t\n    std::cout << name << \"  --- u= 3; v= 4; w=5; u+= w * dot(v, w);:\\n\"; std::cout.flush();\n    u= 3; v= 4; w=5; u+= w * dot(v, w);\n    cout << \"u: \" << u << \"v: \" << v << \"w: \" << w << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(u[0] != 503.0, mtl::runtime_error(\"u wrong\"));\n\t\n    std::cout << name << \"  --- u+= w * dot<12>(v, w);:\\n\"; std::cout.flush();\n    u+= w * dot<12>(v, w);\n    cout << \"u: \" << u << \"v: \" << v << \"w: \" << w << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(u[0] != 1003.0, mtl::runtime_error(\"u wrong\"));\n\n\t// test divide by scalar\n    u= 3.0; v= 4.0; w= 5.0;\n\t\n    std::cout << name << \"  --- v= u/3 + w/5;:\\n\"; std::cout.flush();\n    v= u/3 + w/5;\n    cout << \"v: \" << v << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(v[0] != 2.0, mtl::runtime_error(\"v wrong\"));\n\t\n    std::cout << name << \"  --- u= 3; v= 4; u+= v+= (w= 6.0) / 3.0;:\\n\"; std::cout.flush();\n    u= 3; v= 4; \n    u+= v+= (w= 6.0) / 3.0;\n    cout << \"u: \" << u << \"v: \" << v << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(v[0] != 6.0, mtl::runtime_error(\"v wrong\"));\n    MTL_THROW_IF(u[0] != 9.0, mtl::runtime_error(\"u wrong\"));\n\t\n}\n\nint main(int, char**)\n{\n    using mtl::vec::parameters; using mtl::dense_vector;\n\t\n    dense_vector<float>   u(5), v(5), w(5);\n    dense_vector<double>  x(5), y(5), z(5);\n    dense_vector<std::complex<double> >  xc(5), yc(5), zc(5);\n\t\n    std::cout << \"Testing vector right scaling operations\\n\";\n\t\n    test(u, v, w, \"test float\");\n    test(x, y, z, \"test double\");\n    test(u, x, y, \"test float, double mixed\");\n#if 0\n    // test is not designed for complex\n    test(xc, yc, zc, \"test complex<double>\");\n    test(x, yc, zc, \"test complex<double>, double mixed\");\n#endif\n\t\n    dense_vector<float, parameters<mtl::row_major> >   ur(5), vr(5), wr(5);\n    test(ur, vr, wr, \"test float in row vector\");\n    \n    // test(ur, v, wr, \"test float in mixed vector (shouldn't work)\"); \n\t\n    return 0;\n}\n", "meta": {"hexsha": "947ed6ad6e8cfd9d7a584eba6fdd974e9a41a026", "size": 3209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/dense_vector_2_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/dense_vector_2_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/dense_vector_2_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": 33.0824742268, "max_line_length": 91, "alphanum_fraction": 0.5428482393, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6842661743363058}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, exp2_double) {\n  using stan::math::exp2;\n\n  EXPECT_FLOAT_EQ(1.0, exp2(0.0));\n  EXPECT_FLOAT_EQ(2.0, exp2(1.0));\n  EXPECT_FLOAT_EQ(4.0, exp2(2.0));\n  EXPECT_FLOAT_EQ(8.0, exp2(3.0));\n  \n  EXPECT_FLOAT_EQ(0.5, exp2(-1.0));\n  EXPECT_FLOAT_EQ(0.25, exp2(-2.0));\n  EXPECT_FLOAT_EQ(0.125, exp2(-3.0));\n}\n\nTEST(MathFunctions, exp2_int) {\n  using stan::math::exp2;\n\n  // promotes results to double\n  EXPECT_FLOAT_EQ(1.0, exp2(int(0)));\n  EXPECT_FLOAT_EQ(2.0, exp2(int(1)));\n  EXPECT_FLOAT_EQ(4.0, exp2(int(2)));\n  EXPECT_FLOAT_EQ(8.0, exp2(int(3)));\n\n  EXPECT_FLOAT_EQ(0.5, exp2(int(-1)));\n  EXPECT_FLOAT_EQ(0.25, exp2(int(-2)));\n  EXPECT_FLOAT_EQ(0.125, exp2(int(-3)));\n}\n\nTEST(MathFunctions, exp2_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::exp2(nan));\n}\n", "meta": {"hexsha": "3c0772323db3813a26469d9a644356db209735b5", "size": 978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/exp2_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/exp2_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/exp2_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7368421053, "max_line_length": 56, "alphanum_fraction": 0.6697341513, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.684266174301431}}
{"text": "#include <iostream>\r\n#include <Eigen/Dense>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <cmath>\r\nusing Eigen::MatrixXd;\r\nusing Eigen::VectorXd;\r\nusing namespace std;\r\n\r\nint n_aug = 7;\r\ndouble glambda;\r\ndouble weight1;\r\ndouble weightn;\r\ndouble dt;\r\nVectorXd x = VectorXd(5);//state vector\r\nVectorXd x_aug(7);//augmented vector\r\nMatrixXd P_aug(7,7);//augmented covariance matrix\r\nMatrixXd P = MatrixXd(5, 5);//covariance matrix\r\nMatrixXd sigma_aug(7,15);//augmented sigma point matrix\r\nMatrixXd predict_sigma_aug(5,15);//predicted augmented sigma point matrix\r\nMatrixXd measured_predict_sigma_aug(3,15);// predicted sigma points in measurement space\r\nVectorXd stateMean(5);\r\nMatrixXd stateCovariance(5,5);\r\nVectorXd measurementMean(3);\r\nMatrixXd measurementCovariance(3,3);\r\nMatrixXd crossCorrelationMatrix(5,3);\r\nMatrixXd kalmanGain;\r\nVectorXd z(3);\r\nint ccount = 0;\r\nfloat m_rho,m_pi,m_rdot;\r\n //Process noise standard deviation longitudinal acceleration in m/s^2\r\n  double std_a = 0.2;\r\n\r\n  //Process noise standard deviation yaw acceleration in rad/s^2\r\n  double std_yawdd = 0.2;\r\n \r\nMatrixXd  R_radar_(3,3);\r\n\r\n // Radar measurement noise standard deviation radius in m\r\n double std_radr_ = 0.3;\r\n\r\n  // Radar measurement noise standard deviation angle in rad\r\n double std_radphi_ = 0.03;\r\n\r\n  // Radar measurement noise standard deviation radius change in m/s\r\n double  std_radrd_ = 0.3;\r\n\r\n    \r\nvoid calculateError(VectorXd state,VectorXd groundTruth){\r\n    double error;\r\n    for(int i=0;i<3;i++){\r\n        error += abs(state(i)) - abs(groundTruth(i));\r\n    }\r\n   //print result\r\n  cout<<\"-------------------------------------------------------------\"<<endl;\r\n  cout << \"Updated state x: \" << endl << x << endl;\r\n  cout << \"Updated state covariance P: \" << endl << P << endl;\r\n  cout << \"Error : \" << endl << error << endl;\r\n  cout << \"Ground Truth: \" << endl << groundTruth << endl;\r\n   cout<<\"-------------------------------------------------------------\"<<endl;\r\n}\r\n\r\nvoid updateState(){\r\n  //set state dimension\r\n  int n_x = 5;\r\n\r\n  //set augmented dimension\r\n  int n_aug = 7;\r\n\r\n  //set measurement dimension, radar can measure r, phi, and r_dot\r\n  int n_z = 3;\r\n\r\n  //define spreading parameter\r\n  double lambda = 3 - n_aug;\r\n\r\n  //set vector for weights\r\n  VectorXd weights = VectorXd(2*n_aug+1);\r\n   double weight_0 = lambda/(lambda+n_aug);\r\n  weights(0) = weight_0;\r\n  for (int i=1; i<2*n_aug+1; i++) {  //2n+1 weights\r\n    double weight = 0.5/(n_aug+lambda);\r\n    weights(i) = weight;\r\n  }\r\n\r\n\r\n  MatrixXd Xsig_pred = predict_sigma_aug;\r\n  MatrixXd Zsig = measured_predict_sigma_aug;\r\n  VectorXd z_pred = measurementMean;\r\n  MatrixXd S = MatrixXd(n_z,n_z);\r\n S.fill(0.0);\r\n\r\n  for (int i = 0; i < 2*n_aug +1; i++) {  //2n+1 simga points\r\n    //residual\r\n    VectorXd z_diff = Zsig.col(i) - z_pred;\r\n    //angle normalization\r\n   while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;\r\n  while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n    S = S + weights(i) * z_diff * z_diff.transpose();\r\n  }\r\n\r\n  //add measurement noise covariance matrix\r\n  S = S + R_radar_;\r\n  //create example vector for incoming radar measurement\r\n\r\n  //create matrix for cross correlation Tc\r\n  MatrixXd Tc = MatrixXd(n_x, n_z);\r\n\r\n  //calculate cross correlation matrix\r\n  Tc.fill(0.0);\r\n  for (int i = 0; i < 2 * n_aug + 1; i++) {  //2n+1 simga points\r\n\r\n    //residual\r\n    VectorXd z_diff = Zsig.col(i) - z_pred;\r\n    //angle normalization\r\n    while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;\r\n    while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n\r\n    // state difference\r\n    VectorXd x_diff = Xsig_pred.col(i) - x;\r\n    //angle normalization\r\n    while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;\r\n    while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;\r\n\r\n    Tc = Tc + weights(i) * x_diff * z_diff.transpose();\r\n  }\r\n\r\n  //Kalman gain K;\r\n  MatrixXd K = Tc * S.inverse();\r\n\r\n  //residual\r\n  VectorXd z_diff = z - z_pred;\r\n\r\n  //angle normalization\r\n  while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;\r\n  while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n\r\n  //update state mean and covariance matrix\r\n  x = stateMean + K * z_diff;\r\n  P = stateCovariance - K*S*K.transpose();\r\n\r\n}\r\n\r\n\r\nVectorXd radar2State(VectorXd m_radar){\r\n   double r_m_rho = m_radar(0);\r\n   double r_m_pi = m_radar(1);\r\n   double r_m_rdot = m_radar(2);\r\n   double r_m_px = r_m_rho*cos(r_m_pi);\r\n        if ( r_m_px < 0.0001 ) {\r\n        r_m_px = 0.0001;\r\n      }\r\n        double r_m_py = r_m_rho*sin(r_m_pi);\r\n        if(r_m_py< 0.0001){\r\n          r_m_py = 0.0001;\r\n        }  \r\n        double r_m_vx = r_m_rdot*cos(r_m_pi);\r\n        double r_m_vy = r_m_rdot*sin(r_m_pi);\r\n        double r_m_v  = sqrt(r_m_vx*r_m_vx + r_m_vy*r_m_vy);\r\n  VectorXd r_x(5);\r\n  r_x << r_m_px,r_m_py,r_m_v,0,0;\r\n  return r_x;\r\n}\r\n\r\nvoid NormalizeAngleOnComponent(VectorXd vector, int index) {\r\n  while (vector(index)> M_PI) vector(index)-=2.*M_PI;\r\n  while (vector(index)<-M_PI) vector(index)+=2.*M_PI;\r\n}\r\n\r\n\r\nvoid convertIntoMeasurementSpace(){\r\n    double rho,theta,r_rho;\r\n    for(int i=0;i<predict_sigma_aug.cols();i++){\r\n        rho = sqrt((predict_sigma_aug(0,i)*predict_sigma_aug(0,i))+(predict_sigma_aug(1,i)*predict_sigma_aug(1,i)));\r\n        theta = atan2(predict_sigma_aug(1,i),predict_sigma_aug(0,i));\r\n         while (theta> M_PI) theta-=2.*M_PI;\r\n        while (theta<-M_PI) theta+=2.*M_PI;\r\n        r_rho = (predict_sigma_aug(0,i)*cos(predict_sigma_aug(3,i))*predict_sigma_aug(2,i) + predict_sigma_aug(1,i)*sin(predict_sigma_aug(3,i))*predict_sigma_aug(2,i))/rho;\r\n        measured_predict_sigma_aug.col(i) << rho,theta,r_rho;\r\n    }\r\n   \r\n}\r\n\r\nvoid predictMeanAndCovariance(MatrixXd x,int distinction){\r\n    VectorXd extractedMean(x.rows());\r\n    extractedMean.fill(0.0);\r\n    MatrixXd extractedCovariance(x.rows(),x.rows());\r\n    extractedCovariance.fill(0.0);\r\n    weight1 = glambda/(glambda+n_aug);\r\n    weightn = 0.5/(glambda+n_aug);\r\n    VectorXd x_diff(x.rows());\r\n    for(int i = 0;i<x.cols();i++){\r\n        if(i==0){\r\n            extractedMean += weight1*x.col(i);\r\n        }\r\n        else{\r\n             extractedMean += weightn*x.col(i);\r\n        }\r\n    }\r\n    \r\n\r\n    for(int i=0;i<x.cols();i++){\r\n        int select;\r\n        if(x.rows()>3){\r\n            select = 3;\r\n        }\r\n        else{\r\n            select = 1;\r\n        }\r\n        if(i==0){\r\n             while (x_diff(select)> M_PI) x_diff(select)-=2.*M_PI;\r\n             while (x_diff(select)<-M_PI) x_diff(select)+=2.*M_PI;\r\n            x_diff = x.col(i)-extractedMean;\r\n            extractedCovariance += weight1*x_diff*(x_diff.transpose());\r\n        }\r\n        else{\r\n             while (x_diff(select)> M_PI) x_diff(select)-=2.*M_PI;\r\n             while (x_diff(select)<-M_PI) x_diff(select)+=2.*M_PI;\r\n             x_diff = x.col(i)-extractedMean;\r\n             extractedCovariance += weightn*x_diff*(x_diff.transpose());\r\n        }\r\n    }\r\n    if(distinction==0){\r\n        stateMean = extractedMean;\r\n        stateCovariance = extractedCovariance;\r\n    }\r\n    else{\r\n        measurementMean = extractedMean;\r\n        measurementCovariance = extractedCovariance;\r\n    }\r\n\r\n}\r\n\r\nvoid predictSigmaPoints(double dt){\r\n    for(int i=0;i<sigma_aug.cols();i++){\r\n        VectorXd state(5); \r\n        state = sigma_aug.col(i).head(5);\r\n        VectorXd diffrential(5);\r\n        VectorXd noise(5);\r\n        noise(0) = 0.5*dt*dt*cos(state(3))*sigma_aug(5,i);\r\n        noise(1) = 0.5*dt*dt*sin(state(3))*sigma_aug(5,i);\r\n        noise(2) = dt*sigma_aug(5,i);\r\n        noise(3) = 0.5*dt*dt*sigma_aug(6,i);\r\n        noise(4) = dt*sigma_aug(6,i);\r\n        if(state(4)!=0 || state(4)!=0.0){\r\n            diffrential(0) = (state(2)/state(4))*(sin(state(3) + (state(4)*dt)) - sin(state(3)));\r\n            diffrential(1) = (state(2)/state(4))*(cos(state(3)) - cos(state(3) + (state(4)*dt)) );\r\n            diffrential(2) = 0;\r\n            diffrential(3) = dt*state(4);\r\n            diffrential(4) = 0;\r\n            state  = state + diffrential + noise;\r\n           \r\n        }\r\n        else{\r\n            diffrential(0) = state(2)*cos(state(3))*dt;\r\n            diffrential(1) = state(2)*sin(state(3))*dt;\r\n            diffrential(2) = 0;\r\n            diffrential(3) = dt*state(4);\r\n            diffrential(4) = 0;\r\n            state  = state + diffrential + noise;\r\n        }\r\n        predict_sigma_aug.col(i) = state;\r\n    }\r\n}\r\n\r\nvoid generateAugmentedMatrix(VectorXd x,MatrixXd P){\r\n  x_aug.head(5) = x;\r\n  x_aug(5) = 0;\r\n  x_aug(6) = 0;\r\n\r\n  //create augmented covariance matrix\r\n  P_aug.fill(0.0);\r\n  P_aug.topLeftCorner(5,5) = P;\r\n  P_aug(5,5) = std_a*std_a;\r\n  P_aug(6,6) = std_yawdd*std_yawdd;\r\n\r\n}\r\n\r\nMatrixXd genarateSigmaPoints(VectorXd state,MatrixXd P){\r\n    int nsigma = 2*state.rows() + 1;\r\n    int lambda = 3 - n_aug;\r\n    glambda = lambda;\r\n    MatrixXd sigmaPoints(state.rows(),nsigma);\r\n    double coeff = lambda + state.rows();\r\n    MatrixXd stage1 = P*coeff;\r\n    MatrixXd stage2 = stage1.llt().matrixL();\r\n    MatrixXd stage3_1(stage2.rows(),stage2.cols());\r\n    MatrixXd stage3_2(stage2.rows(),stage2.cols());\r\n    for(int i=0;i<stage2.cols();i++){\r\n        stage3_1.col(i) = state + stage2.col(i);\r\n        stage3_2.col(i) = state - stage2.col(i); \r\n    }\r\n    MatrixXd stage3(stage3_1.rows(),state.cols()+stage3_1.cols()+stage3_2.cols());\r\n    stage3 << state,stage3_1,stage3_2;\r\n    return stage3;\r\n    \r\n}\r\n\r\nint main(){\r\npredict_sigma_aug.fill(0.0);\r\nmeasured_predict_sigma_aug.fill(0.0);\r\nstateMean.fill(0.0);\r\nstateCovariance.fill(0.0);\r\nmeasurementMean.fill(0.0);\r\nmeasurementCovariance.fill(0.0);\r\nkalmanGain.fill(0.0);\r\n\r\n R_radar_ << std_radr_*std_radr_, 0, 0,\r\n              0, std_radphi_*std_radphi_, 0,\r\n              0, 0,std_radrd_*std_radrd_;\r\n\r\nifstream reader(\"C:\\\\DEV\\\\website\\\\data\\\\obj_pose-laser-radar-synthetic-input.txt\");\r\n   string line;\r\n     long long c_timestamp;\r\n  long long p_timestamp;\r\n  char type;\r\n  int count = 0;//for initializing\r\n  double gt_x;//ground truth\r\n  double gt_y;//ground truth\r\n  double gt_vy;//ground truth\r\n  double gt_vx;//ground truth \r\n   double gt_v;\r\n\r\n   while(getline(reader,line)){\r\n    istringstream my_stream(line);\r\n    my_stream>>type;\r\n    if(type=='R'){\r\n         my_stream>>m_rho;\r\n      my_stream>>m_pi;\r\n      my_stream>>m_rdot;\r\n      z<< m_rho,m_pi,m_rdot;\r\n       my_stream>>c_timestamp;\r\n        if(count==0){\r\n        x  = radar2State(z);\r\n         P <<  1, 0, 0, 0, 0,\r\n        0, 1, 0, 0, 0,\r\n        0, 0, 1, 0, 0,\r\n        0, 0, 0, 1, 0,\r\n        0, 0, 0, 0, 1;\r\n\r\n        p_timestamp = c_timestamp;\r\n        count++;\r\n        continue;\r\n      }\r\n       dt = (c_timestamp - p_timestamp)/1000000.0;\r\n      p_timestamp = c_timestamp;\r\n       my_stream>>gt_x;\r\n      my_stream>>gt_y;\r\n      my_stream>>gt_vx;\r\n      my_stream>>gt_vy;\r\n      gt_v = sqrt(gt_vx*gt_vx + gt_vy*gt_vy);\r\n       VectorXd gt(3);\r\n       gt << gt_x,gt_y,gt_v;\r\n        generateAugmentedMatrix(x,P);//converts vector of size 5 to 7 and matrix of 5x5 to 7x7\r\n    sigma_aug = genarateSigmaPoints(x_aug,P_aug);//outputs 7x15 matrix\r\n    predictSigmaPoints(0.1);//outputs 5x15 matrix\r\n    predictMeanAndCovariance(predict_sigma_aug,0);//outputs a vector of size 5 and matrix of size 5x5\r\n    convertIntoMeasurementSpace();//outputs 3x15 matrix from 5x15 matrix\r\n    predictMeanAndCovariance(measured_predict_sigma_aug,1);//mean and covariance in measurement space\r\n    updateState();\r\n    calculateError(x,gt);\r\n    }\r\n   }\r\n    return 0;\r\n}", "meta": {"hexsha": "65a26813817c382f3fe9a1044ef56031c05185da", "size": 11399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UKF.cpp", "max_stars_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_stars_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-06T05:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T05:40:32.000Z", "max_issues_repo_path": "UKF.cpp", "max_issues_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_issues_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UKF.cpp", "max_forks_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_forks_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_forks_repo_licenses": ["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.3159340659, "max_line_length": 173, "alphanum_fraction": 0.5973330994, "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6840260904258679}}
{"text": "/**\n * @file lqr_controller.h\n * @brief Infinite-horizon Linear Quadratic Regulator.\n * \n */\n\n#ifndef LQR_CONTROLLER_H\n#define LQR_CONTROLLER_H\n\n#include <Eigen/Dense>\n\nnamespace controller\n{\n\nclass LQR\n{\n    public:\n        LQR(const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R);\n        ~LQR() {};\n        \n        /**\n         * @brief An infinite-horizon LQR controller with penalties on the state feedback and input signal (Q and R, respectively).\n         * @brief LQR gain is solved by searching for stable poles of the system through the Hamiltonian matrix.\n         * \n         * @param A System dynamics matrix.\n         * @param B Input matrix.\n         * @param E State error.\n         * @return Eigen::MatrixXd LQR gain, K.\n         */\n        Eigen::MatrixXd computeHamiltonian(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E);\n\n    private:\n        // Declare generic MAT for LQR computations.\n        Eigen::MatrixXd K;\n        Eigen::MatrixXd Q;\n        Eigen::MatrixXd R;\n        Eigen::MatrixXd I;\n        Eigen::MatrixXd P;\n\n        // Declare Hamilton matrix.\n        Eigen::MatrixXd Ham;\n\n        // Output.\n        Eigen::MatrixXd cmd_vel;\n        Eigen::MatrixXd controlUpdate;\n};\n\n} // namespace controller\n\n#endif /* LQR_CONTROLLER_H */", "meta": {"hexsha": "f5a77ef5dc844bd03c4d3b0ec475d90731fa4048", "size": 1292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control_system/include/lqr_controller.hpp", "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/control_system/include/lqr_controller.hpp", "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/control_system/include/lqr_controller.hpp", "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": 25.84, "max_line_length": 131, "alphanum_fraction": 0.6160990712, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6840260904258678}}
{"text": "// Filename: ilu_0_complex_cg_example.cpp (part of MTL4)\n\n#include <complex>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nusing namespace mtl;\nusing namespace itl;\n\nint main()\n{\n    using std::complex;\n    typedef compressed2D<complex<double> >  matrix_type;\n\n    const int size = 4, N = size * size; \n    matrix_type                   A(N, N);\n    mat::laplacian_setup(A, size, size);\n\n    // Create an ILU(0) preconditioner with complex<float> values\n    pc::ilu_0<matrix_type, complex<float> > P(A);\n    \n    // Everything else is performed with complex<double> values (and double magnitudes)\n    dense_vector<complex<double> >          x(N, 1.0), b(N);\n    b= A * x; x= 0;\n    noisy_iteration<double>                 iter(b, 500, 1.e-6);\n    \n    // Solve Ax == b with mixed precision\n    cg(A, x, b, P, iter);\n\n    return 0;\n}\n    \n", "meta": {"hexsha": "0255ed4f11f811c78e52e89a0e59c7a21634c4d1", "size": 867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/ilu_0_complex_cg_example.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/examples/ilu_0_complex_cg_example.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/examples/ilu_0_complex_cg_example.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": 26.2727272727, "max_line_length": 87, "alphanum_fraction": 0.6170703576, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.684026088879456}}
{"text": "#ifndef _VGUGV_COMMON_HELPER_FUNCTIONS__\n#define _VGUGV_COMMON_HELPER_FUNCTIONS_\n\n#include <chrono>\n#include <cmath>\n#include \"commDefs.h\"\n#include <Eigen/Dense>\n#include \"cameraBase.h\"\n#include \"cudaDefs.h\"\n\nnamespace VGUGV\n{\n  namespace Common\n  {\n    typedef long long T_int64;\n    typedef std::chrono::high_resolution_clock T_clock;\n    typedef std::chrono::time_point<T_clock> T_time;\n    \n    /*-------------------------------------------------------------------------------------------------*/\n    /*------------------------------------ FUNCTION PROTOTYPES ----------------------------------------*/\n    /*-------------------------------------------------------------------------------------------------*/\n    \n    template<typename T> T INPI(T angle);\n    template<typename T> T deg2rad(T deg);\n    template<typename T> T rad2deg(T rad);\n    template<typename T> void rotMatrix2Euler(T r00, T r01, T r02, \n\t\t\t\t\t   T r10, T r11, T r12,\n\t\t\t\t\t   T r20, T r21, T r22,\n\t\t\t\t\t   T& phi, T& theta, T& psi);\n    template<typename T> void euler2rotMatrix(T phi, T theta, T psi,\n\t\t\t\t\t      T& r00, T& r01, T& r02, \n\t\t\t\t\t      T& r10, T& r11, T& r12,\n\t\t\t\t\t      T& r20, T& r21, T& r22);\n    \n    T_time   currentTime();\n    T_int64  elapsedTime(T_time start, TIME_TYPE type);\n    \n    Eigen::Matrix3f so3Exp(Eigen::Vector3f omega);\n    Eigen::Matrix3f fov2K(float fovDeg, int pixelWidth, int pixelHeight);\n    Eigen::Vector2f distort_radialNtangential(CameraBase::Ptr cameraModel, Eigen::Vector2f pixel0);\n    Eigen::Matrix3f computePlanarHomography(Eigen::Matrix4f T_l2r, float planeDepth_ref, Eigen::Vector3f planeNormal_ref);\n    \n    float  bilinearInterpolation(const unsigned char* pData, int nRows, int nCols, float r, float c); \n    __m128 bilinearInterpolation(const unsigned char* pData, int nRows, int nCols, const SSE_m128_v2& pixels);\n    bool getImagePatch(unsigned char* pImageData, int nRows, int nCols, int r, int c, int nPatchSize, unsigned char* pPatch);\n    bool getImagePatch(CameraBase::Ptr pRefCamera, \n\t\t       CameraBase::Ptr pCurCamera, \n\t\t       unsigned char* pCurImgData, \n\t\t       Eigen::Matrix3f Hl2r, \n\t\t       int r, \n\t\t       int c, \n\t\t       int nPatchSize, \n\t\t       unsigned char* pPatch);\n    \n    float znccScore(unsigned char* pRefPatch, unsigned char* pCurPatch, int nSize);\n    \n    //! Method to cluster 1D data into different clusters, each cluster is approximated by a Gaussian distribution\n      /*!\n      \\param inputData (data, weight), data is already sorted ascendingly. \n      \\param dataSize total number of data pairs \n      \\param Th threshold value used to split two clusters\n      \\param models fitted Gaussian models (mean, variance, weight) \n      \\return (nModels, nBestModelIndex)\n      */\n    Eigen::Vector2i cluster_1Ddata(Eigen::Vector2f* inputData, int dataSize, float Th, Eigen::Vector3f* models);\n    \n    //! Method to fit 1D data into a Gaussian distribution\n      /*!\n      \\param inputData (data, weight), data is already sorted ascendingly. \n      \\param dataSize total number of data pairs  \n      \\return (mean, variance, weight)\n      */\n    Eigen::Vector3f gaussian_fit(Eigen::Vector2f* inputData, int dataSize);\n    \n    float depthFromSubpixelInterpolation(const std::array<float, 3>& depths, const std::array<float, 3>& similarityScores);\n    \n    int intergerDivUp(int a, int b);\n    \n    // SSE related functions\n    void printSSE_m128(const __m128& a);\n    __m128 _mm_floor_ps2(const __m128& a);\n  }\n}\n#endif", "meta": {"hexsha": "e9bc497a5839f7ef8eab364d79943375bb9003d9", "size": 3485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_stars_repo_name": "Frozenheart1998/DynSLAM", "max_stars_repo_head_hexsha": "2de2c58c6eadbc037a19d393951b0f9d15191eab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 530.0, "max_stars_repo_stars_event_min_datetime": "2017-06-24T16:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:13:03.000Z", "max_issues_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_issues_repo_name": "38100514/DynSLAM", "max_issues_repo_head_hexsha": "5fa4374872af63192e0c6b367a5577548ffd6b87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T11:43:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T01:25:03.000Z", "max_forks_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_forks_repo_name": "38100514/DynSLAM", "max_forks_repo_head_hexsha": "5fa4374872af63192e0c6b367a5577548ffd6b87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 166.0, "max_forks_repo_forks_event_min_datetime": "2017-06-02T06:41:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T11:10:02.000Z", "avg_line_length": 41.4880952381, "max_line_length": 125, "alphanum_fraction": 0.6241032999, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6839984461976717}}
{"text": "//\n// Created by Ricardo Delfin Garcia on 4/20/16.\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\n\nclass HeatEquation {\npublic:\n    HeatEquation(const Eigen::VectorXd&, double timestep, double diststep, double alpha);\n\n    Eigen::MatrixXd step();\n\n    ~HeatEquation();\nprivate:\n    std::vector<Eigen::VectorXd> timeData;\n    Eigen::MatrixXd dx;\n    Eigen::MatrixXd dy;\n    double timestep, diststep, alpha;\n\n    void initDMat();\n};\n", "meta": {"hexsha": "e78c1e05844db55d9d39d718268dcba4ca1ad105", "size": 450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heat-equation-calc/include/heat-equation-calc/HeatEquation.hpp", "max_stars_repo_name": "rdelfin/heat-simulation", "max_stars_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/heat-equation-calc/include/heat-equation-calc/HeatEquation.hpp", "max_issues_repo_name": "rdelfin/heat-simulation", "max_issues_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heat-equation-calc/include/heat-equation-calc/HeatEquation.hpp", "max_forks_repo_name": "rdelfin/heat-simulation", "max_forks_repo_head_hexsha": "0f178c0934c88ee6071afbe42efcb7dc49fd4461", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3076923077, "max_line_length": 89, "alphanum_fraction": 0.6822222222, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6839984290333627}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2018 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//[mpfr_variable\n\n/*`\nThis example illustrates the use of variable-precision arithmetic with\nthe `mpfr_float` number type.  We'll calculate the median of the\nbeta distribution to an absurdly high precision and compare the\naccuracy and times taken for various methods.  That is, we want\nto calculate the value of `x` for which ['I[sub x](a, b) = 0.5].\n\nUltimately we'll use Newtons method and set the precision of\nmpfr_float to have just enough digits at each iteration.\n\nThe full source of the this program is in [@../../example/mpfr_precision.cpp]\n\nWe'll skip over the #includes and using declations, and go straight to\nsome support code, first off a simple stopwatch for performance measurement:\n\n*/\n\n//=template <class clock_type>\n//=struct stopwatch { /*details \\*/ };\n\n/*`\nWe'll use `stopwatch<std::chono::high_resolution_clock>` as our performance measuring device.\n\nWe also have a small utility class for controlling the current precision of mpfr_float:\n\n   struct scoped_precision\n   {\n      unsigned p;\n      scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())\n      {\n         mpfr_float::default_precision(new_p);\n      }\n      ~scoped_precision()\n      {\n         mpfr_float::default_precision(p);\n      }\n   };\n\n*/\n//<-\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <iostream>\n#include <chrono>\n\nusing boost::multiprecision::mpfr_float;\nusing boost::math::ibeta_inv;\nusing namespace boost::math::policies;\n\ntemplate <class clock_type>\nstruct stopwatch\n{\npublic:\n   typedef typename clock_type::duration duration_type;\n\n   stopwatch() : m_start(clock_type::now()) { }\n\n   stopwatch(const stopwatch& other) : m_start(other.m_start) { }\n\n   stopwatch& operator=(const stopwatch& other)\n   {\n      m_start = other.m_start;\n      return *this;\n   }\n\n   ~stopwatch() { }\n\n   float elapsed() const\n   {\n      return float(std::chrono::nanoseconds((clock_type::now() - m_start)).count()) / 1e9f;\n   }\n\n   void reset()\n   {\n      m_start = clock_type::now();\n   }\n\nprivate:\n   typename clock_type::time_point m_start;\n};\n\nstruct scoped_precision\n{\n   unsigned p;\n   scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())\n   {\n      mpfr_float::default_precision(new_p);\n   }\n   ~scoped_precision()\n   {\n      mpfr_float::default_precision(p);\n   }\n};\n//->\n\n/*`\nWe'll begin with a reference method that simply calls the Boost.Math function `ibeta_inv` and uses the\nfull working precision of the arguments throughout.  Our reference function takes 3 arguments:\n\n* The 2 parameters `a` and `b` of the beta distribution, and\n* The number of decimal digits precision to achieve in the result.\n\nWe begin by setting the default working precision to that requested, and then, since we don't know where\nour arguments `a` and `b` have been or what precision they have, we make a copy of them - note that since\ncopying also copies the precision as well as the value, we have to set the precision expicitly with a\nsecond argument to the copy.  Then we can simply return the result of `ibeta_inv`:\n*/\nmpfr_float beta_distribution_median_method_1(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n   scoped_precision sp(digits10);\n   mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);\n   return ibeta_inv(a, b, half);\n}\n/*`\nYou be wondering why we needed to change the precision of our variables `a` and `b` as well as setting the default -\nthere are in fact two ways in which this can go wrong if we don't do that:\n\n* The variables have too much precision - this will cause all arithmetic operations involving those types to be\npromoted to the higher precision wasting precious calculation time.\n* The variables have too little precision - this will cause expressions involving only those variables to be\ncalculated at the lower precision - for example if we calculate `exp(a)` internally, this will be evaluated at\nthe precision of `a`, and not the current default.\n\nSince our reference method carries out all calculations at the full precision requested, an obvious refinement\nwould be to calculate a first approximation to `double` precision and then to use Newton steps to refine it further.\n\nOur function begins the same as before: set the new default precision and then make copies of our arguments\nat the correct precision.  We then call `ibeta_inv` with all double precision arguments, promote the result\nto an `mpfr_float` and perform Newton steps to obtain the result.  Note that our termination condition is somewhat\ncude: we simply assume that we have approximately 14 digits correct from the double-precision approximation and\nthat the precision doubles with each step.  We also cheat, and use an internal Boost.Math function that calculates\n['I[sub x](a, b)] and it's derivative in one go:\n\n*/\nmpfr_float beta_distribution_median_method_2(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n   scoped_precision sp(digits10);\n   mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);\n   mpfr_float guess = ibeta_inv((double)a, (double)b, 0.5);\n   unsigned current_digits = 14;\n   mpfr_float f, f1;\n   while (current_digits < digits10)\n   {\n      f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - half;\n      guess -= f / f1;\n      current_digits *= 2;\n   }\n   return guess;\n}\n/*`\nBefore we refine the method further, it might be wise to take stock and see how method's 1 and 2 compare.\nWe'll ask them both for 1500 digit precision, and compare against the value produced by `ibeta_inv` at 1700 digits.\nHere's what the results look like:\n\n[pre\nMethod 1 time = 0.611647\nRelative error: 2.99991e-1501\nMethod 2 time = 0.646746\nRelative error: 7.55843e-1501\n]\n\nClearly they are both equally accurate, but Method 1 is actually faster and our plan for improved performance\nhasn't actually worked.  It turns out that we're not actually comparing like with like, because `ibeta_inv` uses\nHalley iteration internally which churns out more digits of precision rather more rapidly than Newton iteration.\nSo the time we save by refining an initial `double` approximation, then loose it again by taking more iterations\nto get to the result.\n\nTime for a more refined approach.  It follows the same form as Method 2, but now we set the working precision\nwithin the Newton iteration loop, to just enough digits to cover the expected precision at each step.  That means\nwe also create new copies of our arguments at the correct precision within the loop, and likewise change the precision\nof the current `guess` each time through:\n\n*/\n\nmpfr_float beta_distribution_median_method_3(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n   mpfr_float guess = ibeta_inv((double)a_, (double)b_, 0.5);\n   unsigned current_digits = 14;\n   mpfr_float f(0, current_digits), f1(0, current_digits), delta(1);\n   while (current_digits < digits10)\n   {\n      current_digits *= 2;\n      scoped_precision sp((std::min)(current_digits, digits10));\n      mpfr_float a(a_, mpfr_float::default_precision()), b(b_, mpfr_float::default_precision());\n      guess.precision(mpfr_float::default_precision());\n      f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - 0.5f;\n      guess -= f / f1;\n   }\n   return guess;\n}\n\n/*`\nThe new performance results look much more promising:\n\n[pre\nMethod 1 time = 0.591244\nRelative error: 2.99991e-1501\nMethod 2 time = 0.622679\nRelative error: 7.55843e-1501\nMethod 3 time = 0.143393\nRelative error: 4.03898e-1501\n]\n\nThis time we're 4x faster than `ibeta_inv`, and no doubt that could be improved a little more by carefully\noptimising the number of iterations and the method (Halley vs Newton) taken.\n\nFinally, here's the driver code for the above methods:\n\n*/\n\nint main()\n{\n   try {\n      mpfr_float a(10), b(20);\n\n      mpfr_float true_value = beta_distribution_median_method_1(a, b, 1700);\n\n      stopwatch<std::chrono::high_resolution_clock> my_stopwatch;\n\n      mpfr_float v1 = beta_distribution_median_method_1(a, b, 1500);\n      float hp_time = my_stopwatch.elapsed();\n      std::cout << \"Method 1 time = \" << hp_time << std::endl;\n      std::cout << \"Relative error: \" << boost::math::relative_difference(v1, true_value) << std::endl;\n\n      my_stopwatch.reset();\n      mpfr_float v2 = beta_distribution_median_method_2(a, b, 1500);\n      hp_time = my_stopwatch.elapsed();\n      std::cout << \"Method 2 time = \" << hp_time << std::endl;\n      std::cout << \"Relative error: \" << boost::math::relative_difference(v2, true_value) << std::endl;\n\n      my_stopwatch.reset();\n      mpfr_float v3 = beta_distribution_median_method_3(a, b, 1500);\n      hp_time = my_stopwatch.elapsed();\n      std::cout << \"Method 3 time = \" << hp_time << std::endl;\n      std::cout << \"Relative error: \" << boost::math::relative_difference(v3, true_value) << std::endl;\n   }\n   catch (const std::exception& e)\n   {\n      std::cout << \"Found exception with message: \" << e.what() << std::endl;\n   }\n   return 0;\n}\n//]\n\n", "meta": {"hexsha": "eb559cbe86a8bdee6e7db6a49a702b05c7d7ff7c", "size": 9352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/example/mpfr_precision.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/multiprecision/example/mpfr_precision.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "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/multiprecision/example/mpfr_precision.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "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.9644268775, "max_line_length": 118, "alphanum_fraction": 0.7209153122, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6839591644784752}}
{"text": "// stochastic_regression.cpp\n/*\n    This program performs a stochastic regression imputation\n    for a target variable y with missing values using completely\n    observed data X. The calculations are run in serial and then\n    in parallel. The parallel implementation is based on C++'s \n    std::thread. For matrix computations the C++ header only \n    library Eigen is used. You need Eigen to compile this code.\n    Eigen is free software and available at \n    https://eigen.tuxfamily.org/\n    \n    To comopile this program use one of the following:\n    $ g++ -I eigen-3.4.0 stochastic_regression.cpp -o stochastic_regression.out -std=c++2a -lpthread -O3\n    $ clang++ -I eigen-3.4.0 stochastic_regression.cpp -o stochastic_regression.out -std=c++2a -lpthread -O3\n\n    To run it, type\n    $ ./stochastic_regression.out\n*/\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <random>\n#include <string>\n#include <vector>\n#include <thread>\n#include <future>\n#include <chrono>\n\n#include <Eigen/Dense>\n#include <Eigen/QR> \n\n\n// Linear model object that can fit data in the form of a target y\n// and features X using multiple linear regression. \nclass LinearModel\n{\npublic:\n    double sigma;\n    Eigen::VectorXd beta;\n    Eigen::VectorXd residuals;\n    Eigen::MatrixXd design;\n    Eigen::MatrixXd inv_matrix_prod;\n\n    LinearModel();\n    ~LinearModel();\n    void fit(Eigen::MatrixXd X, Eigen::VectorXd y);\n    Eigen::VectorXd predict(Eigen::MatrixXd X);\n};\n\nLinearModel::LinearModel()\n{\n}\n\nLinearModel::~LinearModel()\n{\n}\n\n// Predicts y for a given Matrix X using the Matrix-Vector-Product\n// of X and beta.\nEigen::VectorXd LinearModel::predict(Eigen::MatrixXd X)\n{\n    return(X * beta);\n}\n\n// Fit a linear model of the form y = X * beta + epsilon\n// using least squares.\nvoid LinearModel::fit(Eigen::MatrixXd X, Eigen::VectorXd y)\n{   \n    // Add ones to the model for the intercept parameter.\n    // Therefore resize and reshape the matrix X.\n    X.conservativeResize(X.rows(), X.cols() + 1);\n    for (int i = X.cols() - 1; i > 0 ; i--) \n    {\n        X.col(i) = X.col(i - 1);\n    }\n    X.col(0) = Eigen::VectorXd::Ones(X.rows());\n    design = X;\n\n    // Calculate OLS estimates beta.\n    Eigen::MatrixXd XX = X.transpose() * X;\n    inv_matrix_prod = XX.inverse();\n    beta = X.transpose() * y;\n    beta = inv_matrix_prod * beta;\n\n    // Calculate the residuals.\n    Eigen::VectorXd predictions = predict(X);\n    residuals = y - predictions;\n    Eigen::VectorXd residuals_sq = residuals.array().pow(2);\n\n    // Calculate sigma, that is the variance of the error terms.\n    sigma = sqrt(1.0f / (X.rows() - beta.size()) * residuals_sq.sum());\n}\n\n\n// Generates draws from a multivariate normal distribution.\n// For reference see:\n// https://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c\nstruct normal_random_variable\n{\n    normal_random_variable(Eigen::MatrixXd const& covar)\n        : normal_random_variable(Eigen::VectorXd::Zero(covar.rows()), covar)\n    {}\n\n    normal_random_variable(Eigen::VectorXd const& mean, Eigen::MatrixXd const& covar)\n        : mean(mean)\n    {\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar);\n        transform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n    }\n\n    Eigen::VectorXd mean;\n    Eigen::MatrixXd transform;\n\n    Eigen::VectorXd operator()() const\n    {\n        static std::mt19937 gen{ std::random_device{}() };\n        static std::normal_distribution<> dist;\n\n        return mean + transform * Eigen::VectorXd{ mean.size() }.unaryExpr([&](auto x) { return dist(gen); });\n    }\n};\n\n\n// Reads a CSV file and pushes its content into an Eigen::MatrixXd.\n// For reference see:\n// https://stackoverflow.com/questions/34247057/how-to-read-csv-file-and-assign-to-eigen-matrix/39146048\n// https://www.py4u.net/discuss/80056\nEigen::MatrixXd read_matrix_csv(const std::string & filepath) \n{\n    // Read values form file and write it to buffer vector.\n    std::ifstream indata;\n    indata.open(filepath);\n    std::string line;\n    std::vector<double> values;\n    uint rows = 0;\n    while (std::getline(indata, line)) \n    {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ',')) \n        {\n            values.push_back(std::stod(cell));\n        }\n        ++rows;\n    }\n\n    // Detect or set number of rows/columns\n    size_t num_rows = rows;\n    size_t num_cols = values.size() / rows;\n\n    // Map buffer to Eigen::Matrix and return it.\n    Eigen::MatrixXd csv_matrix = Eigen::Map<Eigen::Matrix <double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> (&values.data()[0], num_rows, num_cols);\n    return csv_matrix;\n}\n\n\n// Performs stochastic regression imputation on a data vector y\n// and observed variables X. \nEigen::VectorXd stochastic_regression_imputation(Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs)\n{\n    int n_obs = X_obs.rows();\n    int n_miss = X_miss.rows();\n\n    std::default_random_engine generator;\n    std::chi_squared_distribution<double> chi(n_obs - 3); \n\n    // Fit linear model only on the observed values.\n    LinearModel regmod;\n    regmod.fit(X_obs, y_obs);\n    Eigen::VectorXd beta_hat = regmod.beta;\n\n    // Random draws for sigma^2 from the scaled inverse Chi^2-distribution.\n    double sigma_sq_tilde = (n_obs - 3) * pow(regmod.sigma, 2) / chi(generator);\n\n    // Random draws for beta from a mv. normal distribution.\n    Eigen::MatrixXd variance = regmod.inv_matrix_prod * sigma_sq_tilde;\n    normal_random_variable sample {beta_hat, variance};\n    Eigen::VectorXd beta_tilde = sample();\n    Eigen::VectorXd means = regmod.design * beta_tilde;\n\n    // Draw the imputations for y from a normal distribution.\n    Eigen::VectorXd y_imputation(n_miss);\n    for (int i = 0; i < n_miss; i++) \n    {\n        std::normal_distribution<double> normal(means[i], sqrt(sigma_sq_tilde));\n        y_imputation[i] = normal(generator);\n    }\n\n    return y_imputation;\n}\n\n\n// Performs M multiple imputations using stochastic_regression\n// and a Bayesian linear model. \nEigen::MatrixXd multiple_imputation(int num_imp, Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs) \n{\n    Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n\n    for (int m = 0; m < num_imp; m++)\n    {\n        // Calculate imputations for y and concantenate to one vector.\n        Eigen::VectorXd y_imp = stochastic_regression_imputation(X_miss, X_obs, y_obs);\n        Eigen::VectorXd y_complete(y_obs.size() + y_imp.size());\n        y_complete << y_obs, y_imp;\n        imputations.col(m) = y_complete;\n    }\n\n    return imputations;\n}\n\n\n// Performs M multiple imputations using stochastic_regression\n// and a Bayesian linear model. This function wraps the calculation\n// output for the use in a parallel setting.\nvoid parallel_multiple_imputation(int num_imp, Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs, std::promise<Eigen::MatrixXd> && p) \n{   \n    Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n    imputations = multiple_imputation(num_imp, X_miss, X_obs, y_obs);\n    p.set_value(imputations);\n}\n\n\n// Calculates the time difference between \"end\" and \"begin\" and prints\n// the result to the terminal.\nvoid print_runtime(std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end, const std::string & msg)\n{\n    std::cout << msg << \" Runtime = \" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << \" [\u00b5s]\" << std::endl;\n    std::cout << msg << \" Runtime = \" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / 1e6 << \" [s]\" << std::endl;\n}\n \n\n// Prints the global mean of an matrix to the terminal.\n// If col_means is ture, the mean for each column of \n// the data matrix is printed.\nvoid print_means(Eigen::MatrixXd data, const std::string & msg, bool col_means = false)\n{\n    std::cout << msg << \" Mean = \" << data.mean() << std::endl;\n    std::cout << std::endl;\n\n    if (col_means) \n    {\n        for (int i = 0; i < data.cols(); i++)\n        {\n            std::cout << \"Mean of imputation \" << i << \" is \" << data.col(i).mean() << std::endl;\n        }\n    }\n}\n\n\nint main() \n{   \n    // Imputation parameters.\n    int num_imp = 10000;\n\n    // Load the data.\n    Eigen::MatrixXd X_miss = read_matrix_csv(\"data/X_miss.csv\");\n    Eigen::VectorXd y_miss = read_matrix_csv(\"data/y_miss.csv\");\n    Eigen::MatrixXd X_obs = read_matrix_csv(\"data/X_obs.csv\");\n    Eigen::VectorXd y_obs = read_matrix_csv(\"data/y_obs.csv\");\n    Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n\n    std::chrono::steady_clock::time_point begin, end;\n\n    // Calculate one imputation.\n    //Eigen::VectorXd y_imp = stochastic_regression_imputation(X_miss, X_obs, y_obs);\n    //std::cout << y_imp << std::endl;\n\n    // Calculate multiple imputations in serial execution.\n    begin = std::chrono::steady_clock::now();\n    imputations = multiple_imputation(num_imp, X_miss, X_obs, y_obs);\n    end = std::chrono::steady_clock::now();\n    print_runtime(begin, end, \"(Serial)\");\n    print_means(imputations, \"(Serial)\");\n    //std::cout << imputations << std::endl;\n\n    // Parallel version using std::thread. Here the number of\n    // multiple imputations is distributed to different threads.\n    int num_cores = std::thread::hardware_concurrency();\n    begin = std::chrono::steady_clock::now();\n    \n    std::vector<std::thread> threads;\n    std::vector<std::future<Eigen::MatrixXd>> futures;\n\n    for (int i = 0; i < num_cores; i++) \n    {\n        std::promise<Eigen::MatrixXd> p;\n        futures.push_back(p.get_future());\n        threads.push_back(std::thread(parallel_multiple_imputation, num_imp / num_cores, X_miss, X_obs, y_obs, std::move(p)));\n    }\n    \n    for (auto &th : threads) \n    {\n        th.join();\n    }\n\n    // Get the results from the parallel execution and \n    // assemble them in a matrix.\n    int col_counter = 0;\n    for (auto &f : futures) \n    {   \n        imputations.block(0, (num_imp / num_cores) * col_counter, imputations.rows(), num_imp / num_cores) = f.get();\n        col_counter++;\n    }\n    \n    end = std::chrono::steady_clock::now();\n    std::cout << \"Running in parallel on \" << num_cores << \" core(s).\" << std::endl;\n    print_runtime(begin, end, \"(Parallel)\");\n    print_means(imputations, \"(Parallel)\");\n    \n    return 0;\n}\n", "meta": {"hexsha": "d5d4b05c32513797d233de256bf7118361575f27", "size": 10457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/C++/stochastic_regression.cpp", "max_stars_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_stars_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T15:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:59:52.000Z", "max_issues_repo_path": "src/C++/stochastic_regression.cpp", "max_issues_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_issues_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_issues_repo_licenses": ["MIT"], "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/C++/stochastic_regression.cpp", "max_forks_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_forks_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_forks_repo_licenses": ["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.4089456869, "max_line_length": 157, "alphanum_fraction": 0.6662522712, "num_tokens": 2638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6839452871981956}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <string>\n#include <cmath>\n#include <fstream>\n#include <numeric>\n\n// Input: m Vector, k Vector, l Vector (even though it is not needed as we later realized), dimension N\nEigen::ArrayXcd springchain(Eigen::VectorXd& m, Eigen::VectorXd& k, Eigen::VectorXd& l, int N){\n    // Initialisation of relative coordinates x (in protocol eta)\n    Eigen::VectorXd x(N);\n    x(0) = 0.;\n    std::partial_sum(l.begin(), l.end(), &x(1), std::plus<double>());\n\n    // Definition of M^-1 and K matrix\n    Eigen::MatrixXd M_inv = m.asDiagonal().inverse();\n    Eigen::MatrixXd K(N, N);\n    for (int i= 0; i < N; i++){\n        for(int j= 0; j <= i; j++){\n            K(i,j) = 0;\n            if(i==j){\n                if(i == 0){\n                    K(i,i) = k(i);\n                    K(i, i+1) = -k(i);\n                }\n                else if(i== N-1){\n                    K(i,i) = k(i-1);\n                    K(i, i-1) = -k(i-1);\n                }\n                else{\n                    K(i,i) = k(i-1)+k(i);\n                    K(i, i-1) = -k(i-1);\n                    K(i, i+1) = -k(i);\n                }\n            }\n        }\n    }\n    Eigen::MatrixXd A = M_inv*K;\n    // Calculate Eigenvalues   \n    return A.eigenvalues();\n}\n\n// Lanczos algorithm, sadly not finished. Returns only the tridiag matrix\nEigen::MatrixXd lanczos(Eigen::MatrixXd& A){\n\n    // Implementation as defined in the lecture\n\n    // q matrix with the new basis q\n    Eigen::MatrixXd q(A.rows(), A.cols()+2);\n    q(0,0) = 0;\n    q(0,1) = 1;\n    // gamma vector with all the normalisations\n    Eigen::VectorXd gamma(A.cols()+2);\n    gamma(1) = 1;\n    // delta vector with diagonal elements of the new tridiag matrix\n    Eigen::VectorXd delta(A.cols()+1);\n    \n    // the new basis build with a for loop\n    for (int i=1; i<=A.rows(); i++){\n        gamma(i+1) = std::sqrt(q.col(i).transpose()* q.col(i));\n        delta(i) = q.col(i).transpose()*A*q.col(i);\n        q.col(i+1) = 1/gamma(i+1) * (A- delta(1)*Eigen::MatrixXd::Identity(A.rows(), A.cols()))*q.col(i) - gamma(i)*q.col(i-1);\n    }\n\n    // make new tridiag matrix based on gamma-, and delta-vector, with some error\n    Eigen::MatrixXd T(A.rows(), A.cols());\n    for (int i= 0; i < A.rows()-1; i++){\n        T(i,i) = delta(i+1);\n        T(i, i+1) = gamma(i+3);\n        T(i+1, i) = gamma(i+3);\n    }\n    T(A.rows()-1, A.cols()-1) = delta(A.cols());\n\n    return T;\n    \n    // Begin of Jacobi-Rotation Implementation, sadly not finished\n    Eigen::MatrixXd Z = Eigen::MatrixXd::Identity(T.rows(), T.cols());\n\n    for (int i=0; i < T.rows()-1; i++){\n        Eigen::JacobiRotation<double> J;\n        Eigen::MatrixXd J_1 = Eigen::MatrixXd::Identity(T.rows(), T.cols());\n        J.makeJacobi(T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)), 0, 1);\n        J_1(Eigen::seq(i,i+1), Eigen::seq(i,i+1)) << J.c(), J.s(), -J.s(), J.c();\n        T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)).applyOnTheLeft(0, 1, J.adjoint());\n        T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)).applyOnTheRight(0, 1, J);\n        Z = Z * J_1;\n    }\n\n}\n\nint main()\n{\n\t// Ex. 1\n    // N is the dimension, here 10 for part b)\n    int N = 10;\n    Eigen::VectorXd m(N), k(N-1), l(N-1);\n    // Initialisation of m, k and l\n    for (int i=0; i<N; i++){\n        m(i) = i+1;\n    }\n    for (int j=0; j<N-1; j++){\n        k(j) = N-j-1;\n        l(j) = std::abs(5.-j-1) + 1;\n    }\n    // Calculate omega_squared with springchain function\n    Eigen::ArrayXcd omega_squared = springchain(m, k, l, N);\n    // Calculate omega with taking the square root of all omega_squared values\n    Eigen::ArrayXd omega = omega_squared.real().abs().sqrt();\n    \n    // Output in file ./output/omega.txt\n    std::ofstream file;\n    file.open(\"output/omega.txt\", std::ofstream::trunc);\n    file << \"\\nDas Ergebnis:\\n\" << omega << std::endl;\n    file.close();\n\n    // Ex. 2\n    int dim = 5;\n    Eigen::MatrixXd A= Eigen::MatrixXd::Random(dim,dim);\n    Eigen::MatrixXd T = lanczos(A);\n\n    std::ofstream file2;\n    file2.open(\"output/tridiag.txt\", std::ofstream::trunc);\n    file2 << \"Die Zufallsmatrix A:\\n\" << A << std::endl;\n    file2 << \"\\nwird zur Tridiagonalmatrix:\\n\" << T << std::endl;\n    file2.close();\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "6a091eb21f2536ec9891827c8ee8bb08cde377b4", "size": 4216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt3/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": "Blatt3/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": "Blatt3/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": 32.1832061069, "max_line_length": 127, "alphanum_fraction": 0.5265654649, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625107731764, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6838048123156903}}
{"text": "#include \"custom_libraries/convert_to_NED.hpp\"\n#include <vector>\n#include <cmath>\n//#include <tf2_ros/transform_listener.h>\n//#include <tf2_ros/transform_broadcaster.h>\n//#include <geometry_msgs/TransformStamped.h>\n//#include <Eigen/Dense>\n\n//tf2_ros::Buffer tfBuffer;\n//tf2_ros::TransformListener tfListener(tfBuffer);\n\n\n/*\nusing namespace Eigen;\n//Roll pitch and yaw in Radians\nQuaternionf euler2quaternions(double roll, double pitch, double yaw){\n  Quaternionf q;\n  q = AngleAxisf(roll, Vector3f::UnitX())\n      * AngleAxisf(pitch, Vector3f::UnitY())\n      * AngleAxisf(yaw, Vector3f::UnitZ());\n  return q;\n}*/\n/*\ngeometry_msgs::TransformStamped broadcast_tf(std:string parent, std:string child, std::vector<double> trans, double[] rot){\n  geometry_msgs::TransformStamped t;\n  t.header.frame_id = parent;\n  t.child_frame_id = child;\n  t.transform.translation.x = x;\n  t.transform.translation.y = y;\n  t.transform.translation.z = z;\n  tf2::Quaternion q;\n  q.setRPY(rot[0], rot[1], rot[2]);\n  q.normalize();\n  t.transform.rotation.x = q.x();\n  t.transform.rotation.y = q.y();\n  t.transform.rotation.z = q.z();\n  t.transform.rotation.w = q.w();\n\n  return t;\n}*/\n\n\nstd::vector<double> lla2nedPiren(double lat_deg, double long_deg, double altitude){\n    double lat0_deg  = 63.4389029083;\n    double long0_deg = 10.39908278;\n    double altitude0 = 39.923;\n\n    double deg2rad = M_PI/180;\n    double rad2deg = 180/M_PI;\n\n    double lat_rad   = lat_deg * deg2rad;\n    double long_rad  = long_deg * deg2rad;\n    double lat0_rad  = lat0_deg * deg2rad;\n    double long0_rad = long0_deg * deg2rad;\n\n    //From vik 2012 - page 4 - table 1.1\n    double re        = 6378137.0;  // [m]\n    double rp        = 6356752.0;  // [m]\n    double rad_curve = pow(re,2) / (sqrt(pow(re,2) * pow(cos(lat_rad),2) + pow(rp,2) * pow(sin(lat_rad),2)));  //N in vik\n\n    // LLA to ECEF\n    double xe = (rad_curve + altitude) * cos(lat_rad) * cos(long_rad);\n    double ye = (rad_curve + altitude) * cos(lat_rad) * sin(long_rad);\n    double ze = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude) * sin(lat_rad);\n\n    double xe0 = (rad_curve + altitude0) * cos(lat0_rad) * cos(long0_rad);\n    double ye0 = (rad_curve + altitude0) * cos(lat0_rad) * sin(long0_rad);\n    double ze0 = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude0) * sin(lat0_rad);\n\n    // ECEF to NED\n    double cosPhi    = cos(lat0_rad);\n    double sinPhi    = sin(lat0_rad);\n    double cosLambda = cos(long0_rad);\n    double sinLambda = sin(long0_rad);\n\n    double dist   = cosLambda * xe + sinLambda * ye;\n    double uNorth = -sinPhi * dist + cosPhi * ze;\n    double vEast  = -sinLambda * xe + cosLambda * ye;\n    double wDown  = -(cosPhi * dist + sinPhi * ze);\n\n    // ECEF0 to NED0\n    double cosPhi0    = cosPhi;\n    double sinPhi0    = sinPhi;\n    double cosLambda0 = cosLambda;\n    double sinLambda0 = sinLambda;\n\n    double dist0   = cosLambda0 * xe0 + sinLambda0 * ye0;\n    double vEast0  = -sinLambda0 * xe0 + cosLambda0 * ye0;\n    double wDown0  = -(cosPhi0 * dist0 + sinPhi0 * ze0);\n    double uNorth0 = -sinPhi0 * dist0 + cosPhi0 * ze0;\n\n    // Compute difference\n    double N = uNorth - uNorth0;  // [m]\n    double E = vEast - vEast0;   // [m]\n    double D = wDown - wDown0;   // [m]\n\n    std::vector<double> NED;\n    NED.push_back(N);\n    NED.push_back(E);\n    NED.push_back(D);\n\n    return NED;\n\n}\n\n\n\nstd::vector<double> lla2ned(double lat_deg, double long_deg, double altitude, double lat0_deg, double long0_deg, double altitude0){\n    double deg2rad = M_PI/180;\n    double rad2deg = 180/M_PI;\n\n    double lat_rad   = lat_deg * deg2rad;\n    double long_rad  = long_deg * deg2rad;\n    double lat0_rad  = lat0_deg * deg2rad;\n    double long0_rad = long0_deg * deg2rad;\n\n    //From vik 2012 - page 4 - table 1.1\n    double re        = 6378137.0;  // [m]\n    double rp        = 6356752.0;  // [m]\n    double rad_curve = pow(re,2) / (sqrt(pow(re,2) * pow(cos(lat_rad),2) + pow(rp,2) * pow(sin(lat_rad),2)));  //N in vik\n\n    // LLA to ECEF\n    double xe = (rad_curve + altitude) * cos(lat_rad) * cos(long_rad);\n    double ye = (rad_curve + altitude) * cos(lat_rad) * sin(long_rad);\n    double ze = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude) * sin(lat_rad);\n\n    double xe0 = (rad_curve + altitude0) * cos(lat0_rad) * cos(long0_rad);\n    double ye0 = (rad_curve + altitude0) * cos(lat0_rad) * sin(long0_rad);\n    double ze0 = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude0) * sin(lat0_rad);\n\n    // ECEF to NED\n    double cosPhi    = cos(lat0_rad);\n    double sinPhi    = sin(lat0_rad);\n    double cosLambda = cos(long0_rad);\n    double sinLambda = sin(long0_rad);\n\n    double dist   = cosLambda * xe + sinLambda * ye;\n    double uNorth = -sinPhi * dist + cosPhi * ze;\n    double vEast  = -sinLambda * xe + cosLambda * ye;\n    double wDown  = -(cosPhi * dist + sinPhi * ze);\n\n    // ECEF0 to NED0\n    double cosPhi0    = cosPhi;\n    double sinPhi0    = sinPhi;\n    double cosLambda0 = cosLambda;\n    double sinLambda0 = sinLambda;\n\n    double dist0   = cosLambda0 * xe0 + sinLambda0 * ye0;\n    double vEast0  = -sinLambda0 * xe0 + cosLambda0 * ye0;\n    double wDown0  = -(cosPhi0 * dist0 + sinPhi0 * ze0);\n    double uNorth0 = -sinPhi0 * dist0 + cosPhi0 * ze0;\n\n    // Compute difference\n    double N = uNorth - uNorth0;  // [m]\n    double E = vEast - vEast0;   // [m]\n    double D = wDown - wDown0;   // [m]\n\n    std::vector<double> NED;\n    NED.push_back(N);\n    NED.push_back(E);\n    NED.push_back(D);\n\n    return NED;\n\n}\n\n\nstd::vector<double> objectCoord2NED(double x, double y, double z, double n_MA, double e_MA, double d_MA, double heading_MA){\n  double E = (x*cos(heading_MA) - sin(heading_MA)*z)+e_MA;\n  double N = (x*sin(heading_MA) + cos(heading_MA)*z)+n_MA;\n  double D = d_MA;\n/*\n  double N = (x+n_MA)*cos(heading_MA) - sin(heading_MA)*(y+e_MA);\n  double E = (x+n_MA)*sin(heading_MA) + cos(heading_MA)*(y+e_MA);\n  double D = d_MA;\n*/\n  std::vector<double> NED;\n  NED.push_back(N);\n  NED.push_back(E);\n  NED.push_back(D);\n\n  return NED;\n}\n\n/*\nstd::vector<double> objectCoord_to_NED(double[] object_coord, std::vector<double> ma_NED, double ma_heading){\n  //Parent=piren, child=gps_antenna, translation = NED posisjon n\u00e5, orientation\n  //transform fra origio til n\u00e5v\u00e6rende posisjon\n\n  geometry_msgs::TransformStamped t = broadcast_tf(\"piren\", \"camera_frame\", ma_NED, [0, 0, heading]);\n  //NED i forhold til camera frame\n  geometry_msgs::TransformStamped tarns = t.lookup_transform(\"camera_frame\", \"camera_frame\", 2);\n\n  double N_cam = trans.transform.translation.x + object_coord[0];\n  double E_cam = trans.transform.translation.y + object_coord[1];\n  double D_cam = MA_d;\n\n  std::vector<double> NED_cam;\n  NED_cam.push_back(N_cam);\n  NED_cam.push_back(E_cam);\n  NED_cam.push_back(D_cam);\n\n  geometry_msgs::TransformStamped t1 = broadcast_tf(\"piren\", \"camera_frame\", ma_NED, [0, 0, heading]);\n\n  return NED;\n\n\n}*/\n", "meta": {"hexsha": "4de3cced354b66d99783c95cd9b55dd3f290e19e", "size": 6886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/custom_libraries/src/convert_to_NED.cpp", "max_stars_repo_name": "trineoo/stereo", "max_stars_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_stars_repo_licenses": ["MIT"], "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/custom_libraries/src/convert_to_NED.cpp", "max_issues_repo_name": "trineoo/stereo", "max_issues_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_issues_repo_licenses": ["MIT"], "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/custom_libraries/src/convert_to_NED.cpp", "max_forks_repo_name": "trineoo/stereo", "max_forks_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 131, "alphanum_fraction": 0.6488527447, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6838048121471666}}
{"text": "#ifndef EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n#define EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n\n#include <cmath>\n#include <string>\n#include <boost/math/special_functions/bessel.hpp>\n#include <functional>\n\n\nnamespace exactsolution{\n\nclass PartitionFunctionClassicalXYChain{\npublic :\n  static std::string name() { return \"Exact partition function , classical XY, open boundary\"; }\n  PartitionFunctionClassicalXYChain(double J,unsigned int num) : J_(J), num_(num) {}\n    \n  double operator()(double T) const {\n    double value = 0.0;\n    value = 2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T);\n    value = 2.0 * M_PI * std::pow(value , num_-1);\n    value += std::pow( std::sqrt(2.0 * M_PI * T), num_);\n    return value;\n  }\n\n  double logZ(double T) const {\n    double value = std::log(2.0 * M_PI);\n    value += (double)(num_ - 1) * std::log(2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T));\n    value += (double)(num_) * 0.5 * std::log(2.0 * M_PI * T );\n    return value;\n  }\n\nprivate :\n  double J_;\n  unsigned int num_;\n};  \n\n} //end namespce\n\n#endif //EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n", "meta": {"hexsha": "3c87de2bd8ab56b00711b97b0af322f3311021d0", "size": 1139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 28.475, "max_line_length": 96, "alphanum_fraction": 0.6918349429, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6837930816850699}}
{"text": "/**\n * @file crossprod.cc\n * @brief NPDE homework CrossProd code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"crossprod.h\"\n\n#include <Eigen/Geometry>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace CrossProd {\n\n/* SAM_LISTING_BEGIN_0 */\nvoid tab_crossprod() {\n  // Solve the cross-product ODE with the implicit RK method\n  // defined in solve_imp_mid. Tabulate the norms of the results at all steps.\n  //====================\n  // Your code goes here\n\n  // set data \n\n  double T =10; \n  int M =128; \n  int c=1; \n  Eigen::Vector3d y0(1.0, 1.0, 1.0); \n  Eigen::Vector3d a(1,0,0); \n\n\n\n  // define right hand side function fy\n  auto f [a,c] (Eigen::Vector3d y) -> Eigen::Vector3d {\n    return a.cross(y)+c*y.cross(a.cross(y)); \n  }\n\n  auto Jf [a,c] (Eigen::Vector3d y) -> Eigen::Matrix3d{\n    Eigen::Matrix3d Jf; \n    Jf << -c * (a(1) * y(1) + a(2) * y(2)),\n        c * (2 * a(0) * y(1) - a(1) * y(0)) - a(2),\n        a(1) + c * (2 * a(0) * y(2) - a(2) * y(0)),\n        a(2) - c * (a(0) * y(1) - 2 * a(1) * y(0)),\n        -c * (a(0) * y(0) + a(2) * y(2)),\n        c * (2 * a(1) * y(2) - a(2) * y(1)) - a(0),\n        -a(1) - c * (a(0) * y(2) - 2 * a(2) * y(0)),\n        a(0) - c * (a(1) * y(2) - 2 * a(2) * y(1)),\n        -c * (a(0) * y(0) + a(1) * y(1));\n    return Jf; \n  }\n\n  // define the Jacobian of rhs\n\n  std::vector<Eigen::VectorXd> sol_imp = solve_imp_mid(f, Jf, T, y0, M); \n\n  std::cout << \"1. Implicit midpoint method\" << std::endl; \n  std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\" << std::endl; \n\n  for (int i=0; i <M+1; ++i){\n    std::cout << std::setw(10) << T*i/M << std::stew(15) << sol_imp[i].norm() << std::end;\n  }\n\n  std::vector<Eigen::VectorXd> sol_lin = sol_lin_mid(f, Jf, T, y0, M); \n\n  std::cout << \"\\n2. Linear implicit midpoint method\" << std::endl; \n  std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\" << std::endl; \n\n  for (int i =0; i<M+1;i++){\n    // tabulate the ||yk||2 for the sequence of approcimate states generated by the linear implicit \n    //midpoint method\n    std::cout <<std::setw(10) << T*i/M << std::setw(15) << sol_lin[i].norm() << std::endl; \n\n  }\n\n  //====================\n  /* SAM_LISTING_END_0 */\n\n  /* SAM_LISTING_BEGIN_1 */\n  // Solve the cross-product ODE with the implicit RK method\n  // defined in solve_lin_mid. Tabulate the norms of the results at all steps.\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_1 */\n}\n\n}  // namespace CrossProd\n", "meta": {"hexsha": "a232325505650f32032e8e7f22c6a4b62f593b0e", "size": 2561, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/mysolution/crossprod.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/CrossProd/mysolution/crossprod.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/CrossProd/mysolution/crossprod.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4555555556, "max_line_length": 100, "alphanum_fraction": 0.530652089, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6837211158373631}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\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\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n#pragma once\n\n/// @file\n/// Function interpolation stuff.\n\n#include <unsupported/Eigen/Splines>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n\nnamespace alma {\n/// Perform spline interpolation of a tabulated function Y(X) at\n/// Xtarget.\ninline Eigen::VectorXd splineInterpolation(\n    const Eigen::Ref<const Eigen::VectorXd>& X,\n    const Eigen::Ref<const Eigen::VectorXd>& Y,\n    const Eigen::Ref<const Eigen::VectorXd>& Xtarget) {\n    Eigen::VectorXd result(Xtarget.size());\n\n    // map X values to 1D chord lengths ranging from 0 to 1\n    Eigen::VectorXd X_norm =\n        (X.array() - X.minCoeff()) / (X.maxCoeff() - X.minCoeff());\n\n    // construct cubic spline over the base points\n    typedef Eigen::Spline<double, 1> Spline1D;\n    Spline1D S(Eigen::SplineFitting<Spline1D>::Interpolate(\n        Y.transpose(), 3, X_norm.transpose()));\n\n    // convert Xtarget values to their equivalent chord length\n    Eigen::VectorXd Xtarget_norm =\n        (Xtarget.array() - X.minCoeff()) / (X.maxCoeff() - X.minCoeff());\n\n    // obtain spline value at each of these chord lengths\n\n    for (int nx = 0; nx < Xtarget.size(); nx++) {\n        result(nx) = S(Xtarget_norm(nx))(0);\n    }\n\n    return result;\n}\n\n\n/// Perform linear interpolation of a tabulated function Y(X) at\n/// Xtarget.\n/// X must be strictly ascending (no duplicate entries).\ninline Eigen::VectorXd linearInterpolation(\n    const Eigen::Ref<const Eigen::VectorXd>& X,\n    const Eigen::Ref<const Eigen::VectorXd>& Y,\n    const Eigen::Ref<const Eigen::VectorXd>& Xtarget) {\n    Eigen::VectorXd result(Xtarget.size());\n    int N = X.size();\n\n    // perform linear interpolation for each of the specified targets\n\n    for (int nx = 0; nx < Xtarget.size(); nx++) {\n        if (Xtarget(nx) < X(0)) {\n            std::cout << \"alma::linearInterpolation > \" << std::endl;\n            std::cout << \"WARNING: encountered target element out of bounds.\"\n                      << std::endl;\n            std::cout << \"Interpolated result will be clipped.\" << std::endl;\n\n            result(nx) = X(0);\n        }\n\n        else if (Xtarget(nx) > X(N - 1)) {\n            std::cout << \"alma::linearInterpolation > \" << std::endl;\n            std::cout << \"WARNING: encountered target element out of bounds.\"\n                      << std::endl;\n            std::cout << \"Interpolated result will be clipped.\" << std::endl;\n\n            result(nx) = X(N - 1);\n        }\n\n        else {\n            // use bisection algorithm to determine base array bin the target\n            // sits\n            // in.\n\n            int leftindex = 0;\n            int rightindex = N - 1;\n\n            while (rightindex - leftindex > 1) {\n                int midindex = (leftindex + rightindex) / 2;\n\n                if (X(midindex) > Xtarget(nx)) {\n                    rightindex = midindex;\n                }\n                else {\n                    leftindex = midindex;\n                }\n            }\n\n            double yleft = Y(leftindex);\n            double yright = Y(rightindex);\n            double xleft = X(leftindex);\n            double xright = X(rightindex);\n\n            result(nx) = yleft + (Xtarget(nx) - xleft) * (yright - yleft) /\n                                     (xright - xleft);\n        }\n    }\n\n    return result;\n}\n\n\n\n\n\nclass CubicSpline1D {\nprivate:\n    Eigen::MatrixXd splines;\n    std::vector<double> x;\n\npublic:\n    /// Default constructors\n    CubicSpline1D() = default;\n    CubicSpline1D(const CubicSpline1D& A) = default;\n\n    /// Constructor from data\n    CubicSpline1D(const Eigen::Ref<const Eigen::VectorXd>& X,\n                  const Eigen::Ref<const Eigen::VectorXd>& Y);\n\n    /// Build interpolation from given data\n    /// it discards the data\n    void BuildCubicSpline1D(const Eigen::Ref<const Eigen::VectorXd>& X,\n                            const Eigen::Ref<const Eigen::VectorXd>& Y);\n\n    /// Interpolates Y for newX\n    double Interpolate(double newX);\n};\n\n\n} // namespace alma\n", "meta": {"hexsha": "73f2313fb08aaf5affcbcdf2a684a9e544a92006", "size": 4583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/interpolation.hpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "include/interpolation.hpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "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": "include/interpolation.hpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "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.5533333333, "max_line_length": 77, "alphanum_fraction": 0.5978616627, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6835268073917052}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef boost::rational<nombre> fraction;\ntypedef std::pair<nombre, nombre> paire;\n\nnamespace {\n    fraction aire(const paire &A, const paire &B, const paire &C) {\n        nombre abc = (B.first - A.first) * (C.second - A.second) - (C.first - A.first) * (B.second - A.second);\n        if (abc < 0)\n            abc = -abc;\n        return fraction(abc, 2);\n    }\n\n    bool contient(const paire &A, const paire &B, const paire &C) {\n        static const paire O = std::make_pair(0, 0);\n        const fraction ABC = aire(A, B, C);\n        const fraction OBC = aire(O, B, C);\n        const fraction AOC = aire(A, O, C);\n        const fraction ABO = aire(A, B, O);\n\n        return (ABC == OBC + AOC + ABO);\n    }\n}\n\nENREGISTRER_PROBLEME(102, \"Triangle containment\") {\n    // Three distinct points are plotted at random on a Cartesian plane, for which -1000 \u2264 x, y \u2264 1000, such that a\n    // triangle is formed.\n    //\n    // Consider the following two triangles:\n    // \n    //                                  A(-340,495), B(-153,-910), C(835,-947)\n    //\n    //                                  X(-175,41), Y(-421,-714), Z(574,-645)\n    // \n    // It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.\n    // \n    // Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of\n    // one thousand \"random\" triangles, find the number of triangles for which the interior contains the origin.\n    // \n    // NOTE: The first two examples in the file represent the triangles in the example given above.\n    std::ifstream ifs(\"data/p102_triangles.txt\");\n    nombre resultat = 0;\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\"));\n        const paire A(stoll(v[0]), stoll(v[1]));\n        const paire B(stoll(v[2]), stoll(v[3]));\n        const paire C(stoll(v[4]), stoll(v[5]));\n        if (contient(A, B, C))\n            ++resultat;\n    }\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "73cb0158d6016ecd4b7f28a95a1bd920849ea312", "size": 2213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme102.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/probleme102.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/probleme102.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": 36.2786885246, "max_line_length": 117, "alphanum_fraction": 0.5892453683, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6835139632779077}}
{"text": "//\n// Copyright (c) 2016-2019 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/spatial/explog.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n#include \"utils/macros.hpp\"\n\nusing namespace pinocchio;\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\nBOOST_AUTO_TEST_CASE(exp)\n{\n  SE3 M(SE3::Random());\n  Motion v(Motion::Random()); v.linear().setZero();\n  \n  SE3::Matrix3 R = exp3(v.angular());\n  BOOST_CHECK(R.isApprox(Eigen::AngleAxis<double>(v.angular().norm(), v.angular().normalized()).matrix()));\n  \n  SE3::Matrix3 R0 = exp3(SE3::Vector3::Zero());\n  BOOST_CHECK(R0.isIdentity());\n  \n  // check the NAN case\n  #ifdef NDEBUG\n    Motion::Vector3 vec3_nan(Motion::Vector3::Constant(NAN));\n    SE3::Matrix3 R_nan = exp3(vec3_nan);\n    BOOST_CHECK(R_nan != R_nan);\n  #endif\n  \n  M = exp6(v);\n  \n  BOOST_CHECK(R.isApprox(M.rotation()));\n  \n  // check the NAN case\n  #ifdef NDEBUG\n    Motion::Vector6 vec6_nan(Motion::Vector6::Constant(NAN));\n    SE3 M_nan = exp6(vec6_nan);\n    BOOST_CHECK(M_nan != M_nan);\n  #endif\n  \n  R = exp3(SE3::Vector3::Zero());\n  BOOST_CHECK(R.isIdentity());\n  \n  // Quaternion\n  Eigen::Quaterniond quat;\n  quaternion::exp3(v.angular(),quat);\n  BOOST_CHECK(quat.toRotationMatrix().isApprox(M.rotation()));\n\n  quaternion::exp3(SE3::Vector3::Zero(),quat);\n  BOOST_CHECK(quat.toRotationMatrix().isIdentity());\n  BOOST_CHECK(quat.vec().isZero() && quat.coeffs().tail<1>().isOnes());\n  \n  // Check QuaternionMap\n  Eigen::Vector4d vec4;\n  Eigen::QuaternionMapd quat_map(vec4.data());\n  quaternion::exp3(v.angular(),quat_map);\n  BOOST_CHECK(quat_map.toRotationMatrix().isApprox(M.rotation()));\n}\n\nBOOST_AUTO_TEST_CASE(log)\n{\n  SE3 M(SE3::Identity());\n  Motion v(Motion::Random()); v.linear().setZero();\n  \n  SE3::Vector3 omega = log3(M.rotation());\n  BOOST_CHECK(omega.isZero());\n  \n  // check the NAN case\n#ifdef NDEBUG\n  SE3::Matrix3 mat3_nan(SE3::Matrix3::Constant(NAN));\n  SE3::Vector3 omega_nan = log3(mat3_nan);\n  BOOST_CHECK(omega_nan != omega_nan);\n#endif\n  \n  M.setRandom();\n  M.translation().setZero();\n  \n  v = log6(M);\n  omega = log3(M.rotation());\n  BOOST_CHECK(omega.isApprox(v.angular()));\n  \n  // check the NAN case\n  #ifdef NDEBUG\n    SE3::Matrix4 mat4_nan(SE3::Matrix4::Constant(NAN));\n    Motion::Vector6 v_nan = log6(mat4_nan);\n    BOOST_CHECK(v_nan != v_nan);\n  #endif\n  \n  // Quaternion\n  Eigen::Quaterniond quat(SE3::Matrix3::Identity());\n  omega = quaternion::log3(quat);\n  BOOST_CHECK(omega.isZero());\n\n  for(int k = 0; k < 1e3; ++k)\n  {\n    SE3::Vector3 w; w.setRandom();\n    quaternion::exp3(w,quat);\n    SE3::Matrix3 rot = exp3(w);\n    \n    BOOST_CHECK(quat.toRotationMatrix().isApprox(rot));\n    double theta;\n    omega = quaternion::log3(quat,theta);\n    const double PI_value = PI<double>();\n    BOOST_CHECK(omega.norm() <= PI_value);\n    double theta_ref;\n    SE3::Vector3 omega_ref = log3(quat.toRotationMatrix(),theta_ref);\n    \n    BOOST_CHECK(omega.isApprox(omega_ref));\n  }\n\n\n  // Check QuaternionMap\n  Eigen::Vector4d vec4;\n  Eigen::QuaternionMapd quat_map(vec4.data());\n  quat_map = SE3::Random().rotation();\n  BOOST_CHECK(quaternion::log3(quat_map).isApprox(log3(quat_map.toRotationMatrix())));\n}\n\nBOOST_AUTO_TEST_CASE(explog3)\n{\n  SE3 M(SE3::Random());\n  SE3::Matrix3 M_res = exp3(log3(M.rotation()));\n  BOOST_CHECK(M_res.isApprox(M.rotation()));\n  \n  Motion::Vector3 v; v.setRandom();\n  Motion::Vector3 v_res = log3(exp3(v));\n  BOOST_CHECK(v_res.isApprox(v));\n}\n\nBOOST_AUTO_TEST_CASE(explog3_quaternion)\n{\n  SE3 M(SE3::Random());\n  Eigen::Quaterniond quat;\n  quat = M.rotation();\n  Eigen::Quaterniond quat_res;\n  quaternion::exp3(quaternion::log3(quat),quat_res);\n  BOOST_CHECK(quat_res.isApprox(quat) || quat_res.coeffs().isApprox(-quat.coeffs()));\n  \n  Motion::Vector3 v; v.setRandom();\n  quaternion::exp3(v,quat);\n  BOOST_CHECK(quaternion::log3(quat).isApprox(v));\n  \n  SE3::Matrix3 R_next = M.rotation() * exp3(v);\n  Motion::Vector3 v_est = log3(M.rotation().transpose() * R_next);\n  BOOST_CHECK(v_est.isApprox(v));\n  \n  SE3::Quaternion quat_v;\n  quaternion::exp3(v,quat_v);\n  SE3::Quaternion quat_next = quat * quat_v;\n  v_est = quaternion::log3(quat.conjugate() * quat_next);\n  BOOST_CHECK(v_est.isApprox(v));\n}\n\nBOOST_AUTO_TEST_CASE(Jlog3_fd)\n{\n  SE3 M(SE3::Random());\n  SE3::Matrix3 R (M.rotation());\n  \n  SE3::Matrix3 Jfd, Jlog;\n  Jlog3 (R, Jlog);\n  Jfd.setZero();\n\n  Motion::Vector3 dR; dR.setZero();\n  const double eps = 1e-8;\n  for (int i = 0; i < 3; ++i)\n  {\n    dR[i] = eps;\n    SE3::Matrix3 R_dR = R * exp3(dR);\n    Jfd.col(i) = (log3(R_dR) - log3(R)) / eps;\n    dR[i] = 0;\n  }\n  BOOST_CHECK(Jfd.isApprox(Jlog, std::sqrt(eps)));\n}\n\nBOOST_AUTO_TEST_CASE(Jexp3_fd)\n{\n  SE3 M(SE3::Random());\n  SE3::Matrix3 R (M.rotation());\n\n  Motion::Vector3 v = log3(R);\n\n  SE3::Matrix3 Jexp_fd, Jexp;\n\n  Jexp3(Motion::Vector3::Zero(), Jexp);\n  BOOST_CHECK(Jexp.isIdentity());\n\n  Jexp3(v, Jexp);\n\n  Motion::Vector3 dv; dv.setZero();\n  const double eps = 1e-8;\n  for (int i = 0; i < 3; ++i)\n  {\n    dv[i] = eps;\n    SE3::Matrix3 R_next = exp3(v+dv);\n    Jexp_fd.col(i) = log3(R.transpose()*R_next) / eps;\n    dv[i] = 0;\n  }\n  BOOST_CHECK(Jexp_fd.isApprox(Jexp, std::sqrt(eps)));\n}\n\ntemplate<typename QuaternionLike, typename Matrix43Like>\nvoid Jexp3QuatLocal(const Eigen::QuaternionBase<QuaternionLike> & quat,\n                    const Eigen::MatrixBase<Matrix43Like> & Jexp)\n{\n  Matrix43Like & Jout = PINOCCHIO_EIGEN_CONST_CAST(Matrix43Like,Jexp);\n  \n  skew(0.5 * quat.vec(),Jout.template topRows<3>());\n  Jout.template topRows<3>().diagonal().array() += 0.5 * quat.w();\n  Jout.template bottomRows<1>() = -0.5 * quat.vec().transpose();\n}\n\nBOOST_AUTO_TEST_CASE(Jexp3_quat_fd)\n{\n  typedef double Scalar;\n  SE3::Vector3 w; w.setRandom();\n  SE3::Quaternion quat; quaternion::exp3(w,quat);\n  \n  typedef Eigen::Matrix<Scalar,4,3> Matrix43;\n  Matrix43 Jexp3, Jexp3_fd;\n  quaternion::Jexp3CoeffWise(w,Jexp3);\n  SE3::Vector3 dw; dw.setZero();\n  const double eps = 1e-8;\n  \n  for(int i = 0; i < 3; ++i)\n  {\n    dw[i] = eps;\n    SE3::Quaternion quat_plus; quaternion::exp3(w + dw,quat_plus);\n    Jexp3_fd.col(i) = (quat_plus.coeffs() - quat.coeffs()) / eps;\n    dw[i] = 0;\n  }\n  BOOST_CHECK(Jexp3.isApprox(Jexp3_fd,sqrt(eps)));\n  \n  SE3::Matrix3 Jlog;\n  pinocchio::Jlog3(quat.toRotationMatrix(),Jlog);\n  \n  Matrix43 Jexp_quat_local;\n  Jexp3QuatLocal(quat,Jexp_quat_local);\n  \n  \n  Matrix43 Jcompositon = Jexp3 * Jlog;\n  BOOST_CHECK(Jcompositon.isApprox(Jexp_quat_local));\n//  std::cout << \"Jcompositon\\n\" << Jcompositon << std::endl;\n//  std::cout << \"Jexp_quat_local\\n\" << Jexp_quat_local << std::endl;\n  \n  // Arount zero\n  w.setZero();\n  w.fill(1e-6);\n  quaternion::exp3(w,quat);\n  quaternion::Jexp3CoeffWise(w,Jexp3);\n  for(int i = 0; i < 3; ++i)\n  {\n    dw[i] = eps;\n    SE3::Quaternion quat_plus; quaternion::exp3(w + dw,quat_plus);\n    Jexp3_fd.col(i) = (quat_plus.coeffs() - quat.coeffs()) / eps;\n    dw[i] = 0;\n  }\n  BOOST_CHECK(Jexp3.isApprox(Jexp3_fd,sqrt(eps)));\n\n}\n\nBOOST_AUTO_TEST_CASE(Jexp3_quat)\n{\n  SE3 M(SE3::Random());\n  SE3::Quaternion quat(M.rotation());\n  \n  Motion dv(Motion::Zero());\n  const double eps = 1e-8;\n  \n  typedef Eigen::Matrix<double,7,6> Matrix76;\n  Matrix76 Jexp6_fd, Jexp6_quat; Jexp6_quat.setZero();\n  typedef Eigen::Matrix<double,4,3> Matrix43;\n  Matrix43 Jexp3_quat; Jexp3QuatLocal(quat,Jexp3_quat);\n  SE3 M_next;\n  \n  Jexp6_quat.middleRows<3>(Motion::LINEAR).middleCols<3>(Motion::LINEAR) = M.rotation();\n  Jexp6_quat.middleRows<4>(Motion::ANGULAR).middleCols<3>(Motion::ANGULAR) = Jexp3_quat;// * Jlog6_SE3.middleRows<3>(Motion::ANGULAR);\n  for(int i = 0; i < 6; ++i)\n  {\n    dv.toVector()[i] = eps;\n    M_next = M * exp6(dv);\n    const SE3::Quaternion quat_next(M_next.rotation());\n    Jexp6_fd.middleRows<3>(Motion::LINEAR).col(i) = (M_next.translation() - M.translation())/eps;\n    Jexp6_fd.middleRows<4>(Motion::ANGULAR).col(i) = (quat_next.coeffs() - quat.coeffs())/eps;\n    dv.toVector()[i] = 0.;\n  }\n  \n  BOOST_CHECK(Jexp6_quat.isApprox(Jexp6_fd,sqrt(eps)));\n}\n\nBOOST_AUTO_TEST_CASE(Jexplog3)\n{\n  Motion v(Motion::Random());\n  \n  Eigen::Matrix3d R (exp3(v.angular())),\n    Jexp, Jlog;\n  Jexp3 (v.angular(), Jexp);\n  Jlog3 (R          , Jlog);\n  \n  BOOST_CHECK((Jlog * Jexp).isIdentity());\n\n  SE3 M(SE3::Random());\n  R = M.rotation();\n  v.angular() = log3(R);\n  Jlog3 (R          , Jlog);\n  Jexp3 (v.angular(), Jexp);\n  \n  BOOST_CHECK((Jexp * Jlog).isIdentity());\n}\n\nBOOST_AUTO_TEST_CASE(Jlog3_quat)\n{\n  SE3::Vector3 w; w.setRandom();\n  SE3::Quaternion quat; quaternion::exp3(w,quat);\n  \n  SE3::Matrix3 R(quat.toRotationMatrix());\n  \n  SE3::Matrix3 res, res_ref;\n  quaternion::Jlog3(quat,res);\n  Jlog3(R,res_ref);\n  \n  BOOST_CHECK(res.isApprox(res_ref));\n}\n\nBOOST_AUTO_TEST_CASE(explog6)\n{\n  SE3 M(SE3::Random());\n  SE3 M_res = exp6(log6(M));\n  BOOST_CHECK(M_res.isApprox(M));\n  \n  Motion v(Motion::Random());\n  Motion v_res = log6(exp6(v));\n  BOOST_CHECK(v_res.toVector().isApprox(v.toVector()));\n}\n\nBOOST_AUTO_TEST_CASE(Jlog6_fd)\n{\n  SE3 M(SE3::Random());\n\n  SE3::Matrix6 Jfd, Jlog;\n  Jlog6 (M, Jlog);\n  Jfd.setZero();\n\n  Motion dM; dM.setZero();\n  double step = 1e-8;\n  for (int i = 0; i < 6; ++i)\n  {\n    dM.toVector()[i] = step;\n    SE3 M_dM = M * exp6(dM);\n    Jfd.col(i) = (log6(M_dM).toVector() - log6(M).toVector()) / step;\n    dM.toVector()[i] = 0;\n  }\n\n  BOOST_CHECK(Jfd.isApprox(Jlog, sqrt(step)));\n}\n\nBOOST_AUTO_TEST_CASE(Jexplog6)\n{\n  Motion v(Motion::Random());\n  \n  SE3 M (exp6(v));\n  {\n    Eigen::Matrix<double, 6, 6, Eigen::RowMajor> Jexp, Jlog;\n    Jexp6 (v, Jexp);\n    Jlog6 (M, Jlog);\n\n    BOOST_CHECK((Jlog * Jexp).isIdentity());\n  }\n\n  M.setRandom();\n  \n  v = log6(M);\n  {\n    Eigen::Matrix<double, 6, 6> Jexp, Jlog;\n    Jlog6 (M, Jlog);\n    Jexp6 (v, Jexp);\n\n    BOOST_CHECK((Jexp * Jlog).isIdentity());\n  }\n}\n\nBOOST_AUTO_TEST_CASE (test_basic)\n{\n  typedef pinocchio::SE3::Vector3 Vector3;\n  typedef pinocchio::SE3::Matrix3 Matrix3;\n  typedef Eigen::Matrix4d Matrix4;\n  typedef pinocchio::Motion::Vector6 Vector6;\n  \n  const double EPSILON = 1e-12;\n  \n  // exp3 and log3.\n  Vector3 v3(Vector3::Random());\n  Matrix3 R(pinocchio::exp3(v3));\n  BOOST_CHECK(R.transpose().isApprox(R.inverse(), EPSILON));\n  BOOST_CHECK_SMALL(R.determinant() - 1.0, EPSILON);\n  Vector3 v3FromLog(pinocchio::log3(R));\n  BOOST_CHECK(v3.isApprox(v3FromLog, EPSILON));\n  \n  // exp6 and log6.\n  pinocchio::Motion nu = pinocchio::Motion::Random();\n  pinocchio::SE3 m = pinocchio::exp6(nu);\n  BOOST_CHECK(m.rotation().transpose().isApprox(m.rotation().inverse(),\n                                                EPSILON));\n  BOOST_CHECK_SMALL(m.rotation().determinant() - 1.0, EPSILON);\n  pinocchio::Motion nuFromLog(pinocchio::log6(m));\n  BOOST_CHECK(nu.linear().isApprox(nuFromLog.linear(), EPSILON));\n  BOOST_CHECK(nu.angular().isApprox(nuFromLog.angular(), EPSILON));\n  \n  Vector6 v6(Vector6::Random());\n  pinocchio::SE3 m2(pinocchio::exp6(v6));\n  BOOST_CHECK(m2.rotation().transpose().isApprox(m2.rotation().inverse(),\n                                                 EPSILON));\n  BOOST_CHECK_SMALL(m2.rotation().determinant() - 1.0, EPSILON);\n  Matrix4 M = m2.toHomogeneousMatrix();\n  pinocchio::Motion nu2FromLog(pinocchio::log6(M));\n  Vector6 v6FromLog(nu2FromLog.toVector());\n  BOOST_CHECK(v6.isApprox(v6FromLog, EPSILON));\n}\n\nBOOST_AUTO_TEST_CASE(test_SE3_interpolate)\n{\n  SE3 A = SE3::Random();\n  SE3 B = SE3::Random();\n  \n  SE3 A_bis = SE3::Interpolate(A,B,0.);\n  BOOST_CHECK(A_bis.isApprox(A));\n  SE3 B_bis = SE3::Interpolate(A,B,1.);\n  BOOST_CHECK(B_bis.isApprox(B));\n  \n  A_bis = SE3::Interpolate(A,A,1.);\n  BOOST_CHECK(A_bis.isApprox(A));\n  \n  B_bis = SE3::Interpolate(B,B,1.);\n  BOOST_CHECK(B_bis.isApprox(B));\n  \n  SE3 C = SE3::Interpolate(A,B,0.5);\n  SE3 D = SE3::Interpolate(B,A,0.5);\n  BOOST_CHECK(D.isApprox(C));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6d5faa3652b4b86ceef61cab07e4161a35118b93", "size": 11838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/explog.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "unittest/explog.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/explog.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T06:24:52.000Z", "avg_line_length": 26.5426008969, "max_line_length": 134, "alphanum_fraction": 0.6556850819, "num_tokens": 3814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6835139491061827}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NNDSVD\n{\n\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n\n  index process(RealMatrixView X, RealMatrixView W, RealMatrixView H,\n                index minRank = 0, index maxRank = 200, double amount = 0.8,\n                index method = 0) // 0 - NMF-SVD, 1 NNDSVDar, 2 NNDSVDa 3 NNDSVD\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    MatrixXd XT = asEigen<Matrix>(X).transpose();\n    MatrixXd WT = asEigen<Matrix>(W).transpose();\n    MatrixXd HT = asEigen<Matrix>(H).transpose();\n\n    assert(amount > 0 || minRank > 0);\n\n    BDCSVD<MatrixXd> svd(XT, ComputeThinV | ComputeThinU);\n\n    MatrixXd U = svd.matrixU();\n    MatrixXd V = svd.matrixV().transpose();\n    VectorXd s = svd.singularValues();\n    MatrixXd S = svd.singularValues().asDiagonal();\n    index    k = 0;\n    if (amount == 0)\n      k = minRank;\n    else\n    {\n      double current = 0;\n      double total = s.sum();\n      while ((current / total) < amount) current += s[k++];\n    }\n    if (k < minRank) k = minRank;\n    if (k > maxRank) k = maxRank;\n\n    if (method == 0)\n    {\n      WT.block(0, 0, WT.rows(), k) = U.block(0, 0, U.rows(), k).array().abs();\n      HT.block(0, 0, k, HT.cols()) =\n          (S.block(0, 0, k, S.cols()) * V).array().abs();\n    }\n    else\n    {\n      // avoid scaling for NMF with normalized W\n      WT.col(0) = U.col(0).array().abs();\n      HT.row(0) = sqrt(s(0)) * V.row(0).array().abs();\n\n      for (index j = 1; j < k; j++)\n      {\n        VectorXd x = U.col(j);\n        VectorXd y = V.row(j);\n        VectorXd xP = x.array().max(0.0);\n        VectorXd yP = y.array().max(0.0);\n        VectorXd xN = x.array().min(0.0).abs();\n        VectorXd yN = y.array().min(0.0).abs();\n        double   xPNorm = xP.norm();\n        double   yPNorm = yP.norm();\n        double   xNNorm = xN.norm();\n        double   yNNorm = xN.norm();\n        double   mP = xPNorm * yPNorm;\n        double   mN = xNNorm * yNNorm;\n        ArrayXd  u;\n        ArrayXd  v;\n        double   sigma;\n        if (mP > mN)\n        {\n          u = xP / xPNorm;\n          v = yP / yPNorm;\n          sigma = mP;\n        }\n        else\n        {\n          u = xN / xNNorm;\n          v = yN / yNNorm;\n          sigma = mN;\n        }\n        auto lbd = std::sqrt(s[j] * sigma);\n        WT.col(j) = u; // avoid scaling for NMF with normalized W\n        HT.row(j) = lbd * v;\n      }\n      WT = WT.array().max(epsilon);\n      HT = HT.array().max(epsilon);\n      if (method == 1)\n      {\n        auto Wrand =\n            MatrixXd::Random(WT.rows(), WT.cols()).array().abs() / 100.0;\n        auto Hrand =\n            MatrixXd::Random(HT.rows(), HT.cols()).array().abs() / 100.0;\n        WT = (WT.array() < epsilon).select(Wrand, WT);\n        HT = (HT.array() < epsilon).select(Hrand, HT);\n      }\n      else if (method == 2)\n      {\n        double mean = XT.mean();\n        WT = (WT.array() < epsilon)\n                 .select(MatrixXd::Constant(WT.rows(), WT.cols(), mean), WT);\n        HT = (HT.array() < epsilon)\n                 .select(MatrixXd::Constant(HT.rows(), HT.cols(), mean), HT);\n      }\n    }\n    MatrixXd W1 = WT.transpose();\n    W <<= asFluid(W1);\n    MatrixXd H1 = HT.transpose();\n    H <<= asFluid(H1);\n    return k;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "243eeda5d2aa5257dd664fa9a3ec5f066e6a7e14", "size": 3915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NNDSVD.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/NNDSVD.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/NNDSVD.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.4360902256, "max_line_length": 80, "alphanum_fraction": 0.5463601533, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230211, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6834854695659527}}
{"text": "//------------------------------------------------------------------------------\n/// \\file FunctionT_tests.cpp\n/// \\ref Vandevoorde, Josuttis, Gregor. C++ Templates: The Complete Guide. 2nd\n/// Ed. Addison-Wesley Professional. 2017.\n//------------------------------------------------------------------------------\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n#include <complex>\n#include <string>\n\nusing std::cos;\nusing std::sin;\nusing std::sqrt;\n\nBOOST_AUTO_TEST_SUITE(Cpp)\nBOOST_AUTO_TEST_SUITE(Templates)\nBOOST_AUTO_TEST_SUITE(FunctionTemplates)\nBOOST_AUTO_TEST_SUITE(FunctionT_tests)\n\ntemplate <typename X, typename FX, FX ObjectMap(X)>\nFX object_map(const X& x)\n{\n  return ObjectMap(x);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MapAsTemplateParameter)\n{\n  const auto result = object_map<double, double, &sin>(M_PI_4);\n  BOOST_TEST(result == 1.0 / sqrt(2.0));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // FunctionT_tests\n\nBOOST_AUTO_TEST_SUITE_END() // FunctionTemplates\nBOOST_AUTO_TEST_SUITE_END() // Templates\nBOOST_AUTO_TEST_SUITE_END() // Cpp", "meta": {"hexsha": "45ce31083e6af5073556382ea5c22ccce057e863", "size": 1192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Cpp/Templates/FunctionT/FunctionT_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Cpp/Templates/FunctionT/FunctionT_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Cpp/Templates/FunctionT/FunctionT_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5641025641, "max_line_length": 80, "alphanum_fraction": 0.5612416107, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.6834284919375799}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <memory>\n\n#include \"fbstab/fbstab_dense.h\"\n#include \"tools/utilities.h\"\n\nnamespace fbstab {\nnamespace test {\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\n/**\n * Tests FBstab with\n *\n * H = [3 1]  f = [10]\n *     [1 1]      [5 ]\n *\n * A = [-1 0] b = [0]\n *     [0  1]     [0]\n *\n * This QP can be solved analytically\n * and has the unique primal(z) - dual(v) solution\n * z = [0 -5],  v = [5 0]\n */\nGTEST_TEST(FBstabDense, FeasibleQP) {\n  int n = 2;\n  int m = 0;\n  int q = 2;\n\n  FBstabDense::Variable x0(n, m, q);\n  FBstabDense::ProblemData data(n, m, q);\n  data.H << 3, 1, 1, 1;\n  data.f << 10, 5;\n  data.A << -1, 0, 0, 1;\n  data.b << 0, 0;\n\n  FBstabDense solver(n, m, q);\n  FBstabDense::Options opts = FBstabDense::DefaultOptions();\n  opts.abs_tol = 1e-8;\n  opts.display_level = Display::OFF;\n  solver.UpdateOptions(opts);\n\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n\n  VectorXd zopt(2);\n  VectorXd vopt(2);\n  zopt << 0, -5;\n  vopt << 5, 0;\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(x0.z(i), zopt(i), 1e-8);\n  }\n\n  for (int i = 0; i < q; i++) {\n    EXPECT_NEAR(x0.v(i), vopt(i), 1e-8);\n  }\n}\n\n/**\n * Tests FBstab with\n *\n * H = [4 1]  f = [1]\n *     [1 2]      [1]\n *\n * G = [1 1]  h = [1]\n *\n * A = [-1 0] b = [0]\n *     [0 -1]     [0]\n *\n */\nGTEST_TEST(FBstabDense, FeasibleQPwithEQ) {\n  int n = 2;\n  int m = 1;\n  int q = 2;\n\n  FBstabDense::Variable x0(n, m, q);\n  FBstabDense::ProblemData data(n, m, q);\n  data.H << 4, 1, 1, 2;\n  data.f << 1, 1;\n  data.G << 1, 1;\n  data.h << 1;\n  data.A << -1, 0, 0, -1;\n  data.b << 0, 0;\n\n  FBstabDense solver(n, m, q);\n  FBstabDense::Options opts = FBstabDense::DefaultOptions();\n  opts.abs_tol = 1e-8;\n  opts.display_level = Display::OFF;\n  solver.UpdateOptions(opts);\n\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n\n  VectorXd zopt(n);\n  zopt << 2.5e-1, 7.5e-1;\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(x0.z(i), zopt(i), 1e-8);\n  }\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1]\n *     [0 0]      [0]\n *\n * A = [0  0] b = [0 ]\n *     [1  0]     [3 ]\n *     [0  1]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is degenerate with a primal solution set\n * [1] x [1,3]\n */\nGTEST_TEST(FBstabDense, DegenerateQP) {\n  constexpr int n = 2;\n  constexpr int m = 0;\n  constexpr int q = 5;\n\n  // Using a ref variable\n  std::unique_ptr<double[]> zmem(new double[n]);\n  std::unique_ptr<double[]> lmem(new double[m]);\n  std::unique_ptr<double[]> vmem(new double[q]);\n  std::unique_ptr<double[]> ymem(new double[q]);\n\n  Eigen::Map<VectorXd> z(zmem.get(), n);\n  Eigen::Map<VectorXd> l(lmem.get(), m);\n  Eigen::Map<VectorXd> v(vmem.get(), q);\n  Eigen::Map<VectorXd> y(ymem.get(), q);\n\n  FBstabDense::VariableRef x0(&z, &l, &v, &y);\n  x0.fill(0.0);\n\n  std::unique_ptr<double[]> Hmem(new double[n * n]);\n  std::unique_ptr<double[]> fmem(new double[n]);\n  std::unique_ptr<double[]> Gmem(new double[m * n]);\n  std::unique_ptr<double[]> hmem(new double[m]);\n  std::unique_ptr<double[]> Amem(new double[q * n]);\n  std::unique_ptr<double[]> bmem(new double[q]);\n\n  Eigen::Map<MatrixXd> H(Hmem.get(), n, n);\n  Eigen::Map<VectorXd> f(fmem.get(), n);\n  Eigen::Map<MatrixXd> A(Amem.get(), q, n);\n  Eigen::Map<VectorXd> b(bmem.get(), q);\n  Eigen::Map<MatrixXd> G(Gmem.get(), m, n);\n  Eigen::Map<VectorXd> h(hmem.get(), m);\n  H << 1, 0, 0, 0;\n  f << 1, 0;\n  A << 0, 0, 1, 0, 0, 1, -1, 0, 0, -1;\n  b << 0, 3, 3, -1, -1;\n\n  FBstabDense::ProblemDataRef data(&H, &f, &G, &h, &A, &b);\n\n  FBstabDense solver(n, m, q);\n  FBstabDense::Options opts = FBstabDense::DefaultOptions();\n  opts.abs_tol = 1e-8;\n  opts.display_level = Display::OFF;\n  solver.UpdateOptions(opts);\n\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  EXPECT_NEAR(x0.z(0), 1, 1e-8);\n  EXPECT_TRUE((x0.z(1) >= 1) && (x0.z(1) <= 3));\n\n  // Check satisfaction of KKT conditions.\n  VectorXd r1 = data.H * x0.z + data.f + data.A.transpose() * x0.v;\n  VectorXd r2 = x0.y.cwiseMin(x0.v);\n\n  ASSERT_NEAR(r1.norm() + r2.norm(), 0, 1e-6);\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1 ]\n *     [0 0]      [-1]\n *\n * A = [1  1] b = [0 ]\n *     [1  0]     [3 ]\n *     [0  1]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is infeasible, i.e.,\n * there is no z satisfying Az <= b\n */\n\nGTEST_TEST(FBstabDense, InfeasibleQP) {\n  int n = 2;\n  int m = 0;\n  int q = 5;\n\n  FBstabDense::ProblemData data(n, m, q);\n  data.H << 1, 0, 0, 0;\n  data.f << 1, -1;\n  data.A << 1, 1, 1, 0, 0, 1, -1, 0, 0, -1;\n  data.b << 0, 3, 3, -1, -1;\n\n  FBstabDense::Variable x0(n, m, q);\n\n  FBstabDense solver(n, m, q);\n  FBstabDense::Options opts = FBstabDense::DefaultOptions();\n  opts.abs_tol = 1e-8;\n  opts.display_level = Display::OFF;\n  solver.UpdateOptions(opts);\n\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::PRIMAL_INFEASIBLE);\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1 ]\n *     [0 0]      [-1]\n *\n * A = [0  0] b = [0 ]\n *     [1  0]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is unbounded below, i.e.,\n * its optimal value is -infinity\n */\nGTEST_TEST(FBstabDense, UnboundedQP) {\n  int n = 2;\n  int m = 0;\n  int q = 4;\n\n  FBstabDense::ProblemData data(n, m, q);\n  data.H << 1, 0, 0, 0;\n  data.f << 1, -1;\n  data.A << 0, 0, 1, 0, -1, 0, 0, -1;\n  data.b << 0, 3, -1, -1;\n\n  FBstabDense::Variable x0(n, m, q);\n\n  FBstabDense solver(n, m, q);\n\n  FBstabDense::Options opts = FBstabDense::DefaultOptions();\n  opts.abs_tol = 1e-8;\n  opts.display_level = Display::OFF;\n  solver.UpdateOptions(opts);\n\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::DUAL_INFEASIBLE);\n}\n\n}  // namespace test\n}  // namespace fbstab\n", "meta": {"hexsha": "eab21bd683a0d8410946f9a9263a623b0034b641", "size": 5838, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fbstab/test/fbstab_dense_unit_tests.cc", "max_stars_repo_name": "tcunis/fbstab", "max_stars_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-08-09T18:43:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T12:38:27.000Z", "max_issues_repo_path": "fbstab/test/fbstab_dense_unit_tests.cc", "max_issues_repo_name": "tcunis/fbstab", "max_issues_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T17:33:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T12:03:36.000Z", "max_forks_repo_path": "fbstab/test/fbstab_dense_unit_tests.cc", "max_forks_repo_name": "tcunis/fbstab", "max_forks_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T19:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T23:03:33.000Z", "avg_line_length": 22.4538461538, "max_line_length": 67, "alphanum_fraction": 0.5565262076, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.683428467229507}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// A reference piece of code which computes matrix elements\n// of a reference sparse first derivative operator to fill a dense\n// Eigen matrix, then computes the spectrum and prints\n// the Eigenvalues.\n\n// This code is for real, indefinite matrices.\n// This code lives on github at github.com/weinbe2/eigens-with-eigen/\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\nusing namespace std; \nusing namespace Eigen;\n\n\n// This is just for convenience. By default, all matrices\n// in Eigen are column major. You can replace \"Dynamic\"\n// with a specific number to template just one size.\n// You can also ust use \"MatrixXd\".\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> dMatrix;\n// Likewise, we can use \"MatrixXcd\".\ntypedef Matrix<std::complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\n// We need both real and complex because, while the matrix itself is real,\n// the eigenvalues and eigenvectors can generically be complex.\n\n\n// Reference 1-D central difference operator\nvoid central_diff_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  complex<double> *out_cplx; // needed for eigenvectors\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 mass = 0.001;\n\n  // Print the basic info.\n  std::cout << \"1D central difference operator, length \" << length << \", mass \" << mass << \", periodic 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  out_cplx = new complex<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, INDEFINITE CASE //\n  ///////////////////////////\n\n  std::cout << \"Real, Indefinite 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    central_diff_1d(out_real, in_real, length, mass);\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  EigenSolver< dMatrix > eigsolve_real_indef(length);\n  eigsolve_real_indef.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  // Note that the eigenvalues are of type \"cMatrix\" as typedef'd above or\n  // MatrixXcd generically.\n  cMatrix evals = eigsolve_real_indef.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 \"VectorXcd\" as the type instead.\n      cMatrix evec = eigsolve_real_indef.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_cplx[j] = evec(j);\n      }\n    }\n  }\n\n  // Clean up.\n  delete[] in_real;\n  delete[] out_real;\n  delete[] out_cplx;\n\n  return 0;\n}\n\n\n\n// Reference 1-D central difference function.\nvoid central_diff_1d(double* out, double* in, const int L, const double mass)\n{\n  // Central difference operator with periodic boundary conditions.\n  for (int i = 0; i < L; i++)\n  {\n    out[i] = mass*in[i] + 0.5*(in[(i+1)%L] - in[(i-1+L)%L]);\n  }\n\n  // Done.\n  return;\n}\n\n", "meta": {"hexsha": "2cb86fae8d29e35f0368b125e3e22c6c0cbb8e30", "size": 4854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigens-with-eigen/real_indefinite/example_real_indefinite.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_indefinite/example_real_indefinite.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_indefinite/example_real_indefinite.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": 28.5529411765, "max_line_length": 127, "alphanum_fraction": 0.6456530696, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6833891378622109}}
{"text": "#include <iostream>\n#include <string>\n#include <map>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/two_layer_net.h\"\n\nusing namespace Eigen;\nusing namespace MyDL;\n\nint main(){\n    using std::cout;\n    using std::endl;\n    using std::string;\n    using std::map;\n\n    int batch_size = 2;\n    int input_size = 2;\n    int hidden_size = 3;\n    int output_size = 2;\n\n    // int batch_size = 3;\n    // int input_size = 2;\n    // int hidden_size = 3;\n    // int output_size = 5;\n\n//     int batch_size = 5;\n//     int input_size = 28 * 28;\n//     int hidden_size = 100;\n//     int output_size = 10;\n\n    TwoLayerNet net(input_size, hidden_size, output_size, 0.01);\n\n    MatrixXd X = MatrixXd::Random(batch_size, input_size);\n    MatrixXd y; // (batch_size, output_size)\n    MatrixXd t = MatrixXd::Zero(batch_size, output_size);\n//     MatrixXd t = MatrixXd::Random(batch_size, output_size);\n    double loss;\n    double accuracy;\n    map<string, MatrixXd> grads, numerical_grads;\n\n    X = -2 * MatrixXd::Identity(2, 2) + MatrixXd::Ones(2, 2);\n    t = MatrixXd::Identity(2, 2);\n\n    // X << 1, 2,\n    //      3, 4,\n    //      5, 6;\n    // t << 0, 1, 0, 0, 0,\n    //      0, 0, 0, 1, 0,\n    //      0, 0, 0, 1, 0;\n    \n    y = net.predict(X);\n    cout << \"y = \" << y << endl; // predict\u306e\u7d50\u679c\u306f\u3001\u884c\u65b9\u5411\u306b\u7dcf\u548c\u3092\u53d6\u3063\u305f\u5834\u5408\u3001\u300c1\u300d\u3068\u306a\u3063\u3066\u3044\u308b\u3053\u3068\u3092\u78ba\u8a8d\n\n    loss = net.loss(X, t);\n    cout << \"loss: \" << loss << endl;\n\n    accuracy = net.accuracy(X, t);\n    cout << \"accuracy: \" << accuracy << endl; // \u3053\u306e\u5165\u529b\u306e\u5834\u5408\u3001accuracy\u306f0.666..\u304c\u6b63\u89e3\n\n    grads = net.gradient(X, t);\n    cout << \"gradient of W1: \" << grads[\"W1\"] << endl;\n    cout << \"gradient of W2: \" << grads[\"W2\"] << endl;\n    cout << \"gradient of b1: \" << grads[\"b1\"] << endl;\n    cout << \"gradient of b2: \" << grads[\"b2\"] << endl;\n\n    cout << \"numerical gradient\" << endl;\n    numerical_grads = net.numerical_gradient(X, t);\n    cout << \"gradient of W1: \" << numerical_grads[\"W1\"] << endl;\n    cout << \"gradient of W2: \" << numerical_grads[\"W2\"] << endl;\n    cout << \"gradient of b1: \" << numerical_grads[\"b1\"] << endl;\n    cout << \"gradient of b2: \" << numerical_grads[\"b2\"] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "13374538c22c396fa3f28e151fed8ad3549d9c96", "size": 2120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/test_two_layer_net.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/test_two_layer_net.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/test_two_layer_net.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.6486486486, "max_line_length": 76, "alphanum_fraction": 0.5702830189, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6833606484180889}}
{"text": "//  (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#include \"math_unit_test.hpp\"\n#include <boost/math/statistics/z_test.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <limits>\n#include <vector>\n#include <random>\n#include <utility>\n\nusing quad = boost::multiprecision::cpp_bin_float_quad;\nusing std::sqrt;\n\ntemplate<typename Real>\nvoid test_one_sample_z()\n{\n    std::pair<Real, Real> temp = boost::math::statistics::one_sample_z_test(Real(10), Real(2), Real(100), Real(10));\n    Real computed_statistic = std::get<0>(temp);\n    Real computed_pvalue = std::get<1>(temp);\n    CHECK_ULP_CLOSE(Real(0), computed_statistic, 5);\n    CHECK_MOLLIFIED_CLOSE(Real(0), computed_pvalue, 5*std::numeric_limits<Real>::epsilon());\n\n    temp = boost::math::statistics::one_sample_z_test(Real(10), Real(2), Real(100), Real(5));\n    Real computed_statistic_2 = std::get<0>(temp);\n    CHECK_ULP_CLOSE(Real(25), computed_statistic_2, 5);\n\n    temp = boost::math::statistics::one_sample_z_test(Real(1)/2, Real(10), Real(100), Real(1)/3);\n    Real computed_statistic_3 = std::get<0>(temp);\n    CHECK_ULP_CLOSE(Real(1)/6, computed_statistic_3, 5);\n}\n\ntemplate<typename Z>\nvoid test_integer_one_sample_z()\n{\n    std::pair<double, double> temp = boost::math::statistics::one_sample_z_test(Z(10), Z(2), Z(100), Z(10));\n    double computed_statistic = std::get<0>(temp);\n    double computed_pvalue = std::get<1>(temp);\n    CHECK_ULP_CLOSE(0.0, computed_statistic, 5);\n    CHECK_MOLLIFIED_CLOSE(0.0, computed_pvalue, 5*std::numeric_limits<double>::epsilon());\n\n    temp = boost::math::statistics::one_sample_z_test(Z(10), Z(2), Z(100), Z(5));\n    double computed_statistic_2 = std::get<0>(temp);\n    CHECK_ULP_CLOSE(25.0, computed_statistic_2, 5);\n}\n\ntemplate<typename Real>\nvoid test_two_sample_z()\n{\n    std::vector<Real> set_1 {1,2,3,4,5};\n    std::vector<Real> set_2 {2,3,4,5,6};\n\n    std::pair<Real, Real> temp = boost::math::statistics::two_sample_z_test(set_2, set_1);\n    Real computed_statistic = std::get<0>(temp);\n    Real computed_pvalue = std::get<1>(temp);\n    CHECK_ULP_CLOSE(Real(1), computed_statistic, 5);\n    CHECK_MOLLIFIED_CLOSE(Real(0), computed_pvalue, sqrt(std::numeric_limits<Real>::epsilon()));\n}\n\ntemplate<typename Z>\nvoid test_integer_two_sample_z()\n{\n    std::vector<Z> set_1 {1,2,3,4,5};\n    std::vector<Z> set_2 {2,3,4,5,6};\n\n    std::pair<double, double> temp = boost::math::statistics::two_sample_z_test(set_2, set_1);\n    double computed_statistic = std::get<0>(temp);\n    double computed_pvalue = std::get<1>(temp);\n    CHECK_ULP_CLOSE(1.0, computed_statistic, 5);\n    CHECK_MOLLIFIED_CLOSE(0.0, computed_pvalue, 5*std::numeric_limits<double>::epsilon());\n}\n\nint main()\n{\n    test_one_sample_z<float>();\n    test_one_sample_z<double>();\n    test_one_sample_z<quad>();\n\n    test_integer_one_sample_z<int>();\n    test_integer_one_sample_z<int32_t>();\n    test_integer_one_sample_z<int64_t>();\n    test_integer_one_sample_z<uint32_t>();\n\n    test_two_sample_z<float>();\n    test_two_sample_z<double>();\n    test_two_sample_z<quad>();\n\n    test_integer_two_sample_z<int>();\n    test_integer_two_sample_z<int32_t>();\n    test_integer_two_sample_z<int64_t>();\n    test_integer_two_sample_z<uint32_t>();\n}\n", "meta": {"hexsha": "3f4ad99409217a46c96d302f86a89b357e9b31b9", "size": 3459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_z_test.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": "test/test_z_test.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": "test/test_z_test.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": 36.03125, "max_line_length": 116, "alphanum_fraction": 0.7123446083, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.752012568201972, "lm_q1q2_score": 0.6832920726041003}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd m(2,3);\nm << 2, -4, 6,   \n     -5, 1, 0;\ncout << m.cwiseAbs() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "108425661ccbb3127855a3e883b142473eee3fb2", "size": 231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_cwiseAbs.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_MatrixBase_cwiseAbs.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_MatrixBase_cwiseAbs.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": 13.5882352941, "max_line_length": 29, "alphanum_fraction": 0.5974025974, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6832910831788183}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nTEST(MathFunctions, inv_logit) {\n  using stan::math::inv_logit;\n  EXPECT_FLOAT_EQ(0.5, inv_logit(0.0));\n  EXPECT_FLOAT_EQ(1.0 / (1.0 + exp(-5.0)), inv_logit(5.0));\n}\n\nTEST(MathFunctions, inv_logit_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::inv_logit(nan));\n}\n", "meta": {"hexsha": "a306c518ba8e58ced10a416b7117c889041a296b", "size": 470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/inv_logit_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/inv_logit_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/inv_logit_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6470588235, "max_line_length": 71, "alphanum_fraction": 0.7170212766, "num_tokens": 143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6831645423500131}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nnamespace algo3\n{\n// Solves 2D concave hull in O((n ^ 2) * log(n)) complexity for Multipoint concept\n// Where n is the total input points\ntemplate <typename MultiPoint, typename Size, typename Factor>\nclass ConcaveHull {\n\n    private:\n        MultiPoint hull;\n        Size n;\n        Factor k;\n    \n    public:\n        ConcaveHull(MultiPoint mp, Size sz, Factor cur_k);\n        void print_hull();\n};\n\ntemplate <typename MultiPoint, typename Size, typename Factor>\nConcaveHull<MultiPoint, Size, Factor>::ConcaveHull(MultiPoint mp, Size sz, Factor cur_k)\n{\n    hull = mp;\n    n = sz;\n    k = cur_k;\n}\n\n// To print the concave hull\ntemplate <typename MultiPoint, typename Size, typename Factor>\nvoid ConcaveHull<MultiPoint, Size, Factor>::print_hull()\n{   \n    std::cout << \"Current value of k is: \" << k << std::endl;\n    std::cout << \"Resulting points of Concave Hull are: \" << std::endl;\n    for (Size i = 0; i < n; ++i)\n    {\n        std::cout << bg::get<0>(hull[i]) << \" \" << bg::get<1>(hull[i]) << std::endl;\n    }\n}\n\ntemplate <typename DataType>\nstatic inline DataType max(DataType a, DataType b)\n{\n    return (a > b ? a : b);\n}\n\ntemplate <typename DataType>\nstatic inline DataType min(DataType a, DataType b)\n{\n    return (a > b ? b : a);\n}\n\n// Sorts input in increasing order of x values and in case of ties, increasing y values\ntemplate <typename Range>\nstatic inline void sort(Range& range)\n{\n    typedef typename boost::range_value<Range>::type point_type;\n    typedef bg::less<point_type> comparator;\n\n    std::sort(boost::begin(range), boost::end(range), comparator());\n}\n\n// This function returns 1 if points are oriented in counter-clockwise manner and -1 if collinear\ntemplate <typename Point>\nstatic inline int RightHandTurn(Point a, Point b, Point c)\n{\n    typedef typename bg::coordinate_type<Point>::type c_type;\n\n    c_type value = (bg::get<1>(b) - bg::get<1>(a)) * (bg::get<0>(c) - bg::get<0>(b))\n                   - (bg::get<0>(b) - bg::get<0>(a)) * (bg::get<1>(c) - bg::get<1>(b));\n    if (value == 0)\n    {\n        return -1;\n    }\n    return (value < 0 ? 1 : 0);\n}\n\n// Removes duplicates from input in O(n * log(n)) complexity\ntemplate <typename MultiPoint>\nstatic inline void CleanList(MultiPoint& mp)\n{\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n    typedef typename bg::coordinate_type<MultiPoint>::type c_type;\n    typedef typename bg::point_type<MultiPoint>::type point_type;\n    typedef typename std::pair<c_type, c_type> pair_type;\n    typedef typename std::set<pair_type>::iterator itr_type;\n\n    size_type n = boost::size(mp);\n    std::set<pair_type> st;\n    for (size_type i = 0; i < n; ++i)\n    {\n        st.insert({bg::get<0>(mp[i]), bg::get<1>(mp[i])});\n    }\n    bg::clear(mp);\n\n    itr_type it;\n    for (it = st.begin(); it != st.end(); ++it)\n    {\n        pair_type p = *it;\n        point_type cur = {p.first, p.second};\n        bg::append(mp, cur);\n    }\n}\n\n// Removes a point from multipoint in O(n) complexity by swapping elements and poping out last one\ntemplate <typename MultiPoint, typename Point>\nstatic inline void RemovePoint(MultiPoint& mp, Point cur)\n{\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n\n    size_type n = boost::size(mp);\n    for (size_type i = 0; i < n; ++i)\n    {\n        if (bg::equals(mp[i], cur))\n        {\n            for (size_type j = i; j < n - 1; ++j)\n            {\n                mp[j] = mp[j + 1];    \n            }\n            break;\n        }\n    }\n    mp.pop_back();\n}\n\n// Building Rtree for a given container\ntemplate <typename MultiPoint, typename RTree>\ninline void BuildRTree(MultiPoint& mp, RTree& rt)\n{\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n\n    size_type n = boost::size(mp);\n    for (size_type i = 0; i < n; ++i)\n    {\n        bgi::insert(rt, mp[i]);\n    }\n}\n\n// Runs the main algorithm on dataset of points for a particular k value\n// Returns empty container when current k gives no solution\ntemplate <typename MultiPoint, typename Factor>\nstatic inline MultiPoint Solve(MultiPoint dataset, Factor k)\n{\n    typedef typename bg::point_type<MultiPoint>::type point_type;\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n    typedef typename bg::model::linestring<point_type> linestring_type;\n    typedef typename bg::model::segment<point_type> segment_type;\n    typedef typename bg::model::polygon<point_type> poly_type;\n\n    MultiPoint ans, discard;\n    bg::append(ans, dataset[0]);\n    point_type cur_point = dataset[0];\n    RemovePoint(dataset, cur_point);\n    int step = 0;\n\n    bgi::rtree<point_type, bgi::rstar<32>> rt1;\n    bgi::rtree<segment_type, bgi::rstar<8>> rt2;\n    BuildRTree(dataset, rt1);\n\n    while (boost::size(dataset))\n    {\n        if (step == 3)\n        {\n            // once a polygon with more than 3 edges is formed add the first point again\n            bg::append(dataset, ans[0]);\n            bgi::insert(rt1, ans[0]);\n        }\n        \n        // finding k-NN using RTree\n        std::vector<point_type> k_nearest;\n        Factor cur_k = min(k, Factor(boost::size(dataset)));\n        rt1.query(bgi::nearest(cur_point, cur_k), std::back_inserter(k_nearest));\n        \n        size_type size1 = boost::size(k_nearest);\n        std::vector<point_type> good;\n        for (size_type i = 0; i < size1; ++i)\n        {   \n            bool ok = true;\n            linestring_type ls1{k_nearest[i], cur_point};\n\n            // querying RTree to find all the intersecting edges of the hull with the current edge\n            std::vector<segment_type> bad;\n            segment_type seg(k_nearest[i], cur_point);\n            rt2.query(bgi::intersects(seg), std::back_inserter(bad));\n\n            size_type size2 = boost::size(bad);\n            if (size2 == 1 and bg::equals(k_nearest[i], ans[0]))\n            {   \n                // if linestring touches first edge, then its the last edge and is ok\n                linestring_type ls2{ans[0], ans[1]};\n                if (!bg::touches(ls1, ls2))\n                {   \n                    // if this linestring does not touch and only intersect then discard this point\n                    ok = false;\n                }\n            }\n            else if (size2 > 0)\n            {   \n                // interesections means point is discarded\n                ok = false;\n            }\n\n            if (ok)\n            {   \n                // non intersecting edge is good\n                good.push_back(k_nearest[i]);\n            }\n        }\n        if (good.empty())\n        {   \n            // if no good points are remaining, current k has no solution\n            return discard;\n        }\n\n        point_type best = good[0];\n        size1 = boost::size(good);\n        for (size_type i = 1; i < size1; ++i)\n        {\n            int value = RightHandTurn(cur_point, good[i], best);\n            if (value == -1)\n            {\n                // in case of collinear points take the nearest one as best\n                if (bg::distance(good[i], cur_point) < bg::distance(best, cur_point))\n                {\n                    best = good[i];\n                }\n            }\n            else if (value)\n            {\n                // update best if we have counter-clockwise orientation\n                best = good[i];\n            }\n        }\n        if (step)\n        {   \n            // adding previously formed edge to RTree\n            size_type last = boost::size(ans) - 2;\n            segment_type cur_segment(cur_point, ans[last]);\n            bgi::insert(rt2, cur_segment);\n        }\n        cur_point = best;\n        bg::append(ans, cur_point);\n        RemovePoint(dataset, cur_point);\n        bgi::remove(rt1, cur_point);\n\n        if (bg::equals(cur_point, ans[0]))\n        {\n            // cycle completed\n            break;\n        }\n        ++step;\n    }\n\n    // If any point is outside the final polygon, then current k has no solution\n    poly_type poly;\n    for (size_type i = 0; i < boost::size(ans); ++i)\n    {\n        bg::append(poly, ans[i]);\n    }\n    size_type n = boost::size(dataset);\n    for (size_type i = 0; i < n; ++i)\n    {\n        if (!(bg::covered_by(dataset[i], poly)))\n        {   \n            return discard;\n        }\n    }\n    return ans;\n}\n\n// Driver code\ntemplate <typename MultiPoint, typename Factor>\ninline void ConcaveHullKNN(MultiPoint input, MultiPoint& hull, Factor& k)\n{\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n\n    CleanList(input);\n    size_type n = boost::size(input);\n    k = max(k, 2);\n    k = min(k, Factor(n));\n\n    // At least three different points are required for concave hull to be formed\n    if (n < size_type(3))\n    {\n        return;\n    }\n    else if (n == size_type(3))\n    {\n        hull = input;\n        return;\n    }\n\n    sort(input);\n    while (k <= Factor(n))\n    {\n        hull = Solve(input, k);\n        // If current k given empty solution, then k is increased by one\n        if (bg::is_empty(hull))\n        {\n            ++k;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    // Uncomment lines below to print information about current concave hull\n    // size_type h = boost::size(hull);\n    // ConcaveHull<MultiPoint, size_type, Factor> debug(hull, h, k);\n    // debug.print_hull();\n}\n\n} // namespace algo3\n", "meta": {"hexsha": "7f5a82ddbfc9990322f9cdf8d49c79ea33159e55", "size": 9610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/concave_hull_k_nearest_neighbours_optimized.hpp", "max_stars_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_stars_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "includes/concave_hull_k_nearest_neighbours_optimized.hpp", "max_issues_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_issues_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "includes/concave_hull_k_nearest_neighbours_optimized.hpp", "max_forks_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_forks_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_forks_repo_licenses": ["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.1212121212, "max_line_length": 99, "alphanum_fraction": 0.57710718, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.6831645283003444}}
{"text": "#include <iostream>\n#include <blitz.h>\n\nusing namespace blitz;\n// M N\nShape input_shape(2);\n// N M\nShape output_shape(2);\n\nvoid output_matrix(size_t dim_left, size_t dim_right, float* matrix) {\n  for (size_t i = 0; i < dim_left; ++i) {\n    for (size_t j = 0; j < dim_right; ++j) {\n      std::cout << matrix[i * dim_right + j] << \" \";\n    }\n    std::cout << std::endl;\n  }\n}\n\nvoid transpose(size_t m, size_t n) {\n  // set up cpu\n  CPUTensor<float> input_cpu(input_shape);\n  CPUTensor<float> output_cpu(output_shape);\n  // init values\n  std::cout << \"Init:\" << std::endl;\n  Backend<CPUTensor, float>::UniformDistributionFunc(&input_cpu, 0.0, 1.0);\n  output_matrix(m, n, input_cpu.data());\n  std::cout << \"Transposed:\" << std::endl;\n  // transpose\n  Backend<CPUTensor, float>::Transpose2DFunc(&input_cpu, &output_cpu);\n  output_matrix(n, m, output_cpu.data());\n}\n\nint main(int argc, char** argv) {\n  const size_t NUM_ARGS = 2;\n  // M N\n  if (argc != NUM_ARGS + 1) {\n    std::cerr << \"Not matchable args!\" << std::endl;\n    exit(1);\n  }\n  const size_t M = atoi(argv[1]);\n  const size_t N = atoi(argv[2]);\n  // set shapes\n  input_shape[0] = M;\n  input_shape[1] = N;\n  output_shape[0] = N;\n  output_shape[1] = M;\n  // run\n  transpose(M, N);\n  return 0;\n}\n", "meta": {"hexsha": "51cf9175a1349c158093627ba8d2a3b1beff9586", "size": 1249, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/cpu/matrix/matrix_transpose.cc", "max_stars_repo_name": "ncic-sugon/blitz", "max_stars_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 149.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T08:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T03:06:41.000Z", "max_issues_repo_path": "samples/cpu/matrix/matrix_transpose.cc", "max_issues_repo_name": "ten1123love/blitz", "max_issues_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "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": "samples/cpu/matrix/matrix_transpose.cc", "max_forks_repo_name": "ten1123love/blitz", "max_forks_repo_head_hexsha": "ea9a06dc78ef15d772e36d5d47ffac8d3f46034d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 130.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T09:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T03:06:42.000Z", "avg_line_length": 24.4901960784, "max_line_length": 75, "alphanum_fraction": 0.6236989592, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6831645217894928}}
{"text": "#ifndef AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n#define AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n\n#include <armadillo>\n#include <functional>\n\nnamespace amt::regression{\n    \n    struct default_opt{\n\n        auto operator()(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y, double lm) const {\n            // x_t = x^T\n            auto x_t = x.t();\n            \n            // xt_y = x^T * y\n            auto xt_y = x_t * y;\n\n            if( lm == 0 ){\n                // xt_x = x^T * x\n                auto xt_x = x_t * x;\n\n                // (X * X^T) * B = X^T * Y\n                beta = arma::solve(xt_x,xt_y,arma::solve_opts::fast);\n            }else{\n                \n                arma::Mat<double> l_I = arma::eye(x.n_cols, x.n_cols) * lm;\n\n                // xt_x = x^T * x + l_I\n                auto xt_x_lI = ( x_t * x ) + l_I;\n\n                // (X * X^T) * B = X^T * Y\n                beta = arma::solve(xt_x_lI,xt_y,arma::solve_opts::fast);\n            }\n\n        }\n\n    };\n    \n    struct gradient_descent{\n\n        constexpr gradient_descent() noexcept = default;\n        constexpr gradient_descent(gradient_descent const&  other) noexcept = default;\n        constexpr gradient_descent(gradient_descent &&  other) noexcept = default;\n        constexpr gradient_descent& operator=(gradient_descent const&  other) noexcept = default;\n        constexpr gradient_descent& operator=(gradient_descent &&  other) noexcept = default;\n        ~gradient_descent() = default;\n        \n        constexpr gradient_descent(double alpha, std::size_t iter)\n            : alpha(alpha)\n            , iteration(iter)\n        {}\n\n        auto operator()(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y, double lm) const {\n            beta.resize(x.n_cols, 1ul);\n            beta.randu();\n            if( lm == 0.0 )\n                eval(beta,x,y,lm);\n            else\n                eval(beta,x,y);\n        }\n\n        // double compute_cost(arma::Mat<double> const& beta, arma::Mat<double> const& x, arma::Mat<double> const& y){\n        //     auto temp = ( x * beta ) - y;\n        //     auto m = 2 * x.n_rows;\n        //     auto J = ( temp * temp.t() ) / static_cast<double>(m);\n        //     return J[0];\n        // }\n\n        void eval(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y, double lm) const{\n            auto m = alpha / static_cast<double>(x.n_rows);\n            auto reg_coef = m * lm;\n\n            auto x_t = x.t();\n            for( auto i = 0u; i < iteration; ++i ){\n                auto p = ( x * beta ) - y;\n                auto temp = m * (x_t * p);\n                beta -= ( temp + ( reg_coef * beta ) );\n            }\n        }\n\n        void eval(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y) const{\n            auto m = alpha / static_cast<double>(x.n_rows);\n            auto x_t = x.t();\n            for( auto i = 0u; i < iteration; ++i ){\n                auto p = ( x * beta ) - y;\n                auto temp = m * (x_t * p);\n                beta -= temp;\n            }\n        }\n\n\n        double alpha{0.01};\n        std::size_t iteration{1500};\n    };\n\n    template<typename T>\n    inline static constexpr bool is_default_opt_v = std::is_same_v<T,default_opt>;\n\n    template<typename T>\n    inline static constexpr bool is_gradient_descent_v = std::is_same_v<T,gradient_descent>;\n\n} // namespace amt::regression\n\n\n#endif\n", "meta": {"hexsha": "34b798080edf779b24025bffc4cd793fdbc1a044", "size": 3488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/model/LinearRegression/optimizer.hpp", "max_stars_repo_name": "amitsingh19975/ML-v2", "max_stars_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T07:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T07:59:05.000Z", "max_issues_repo_path": "include/model/LinearRegression/optimizer.hpp", "max_issues_repo_name": "amitsingh19975/ML-v2", "max_issues_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "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/model/LinearRegression/optimizer.hpp", "max_forks_repo_name": "amitsingh19975/ML-v2", "max_forks_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "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": 32.9056603774, "max_line_length": 123, "alphanum_fraction": 0.5126146789, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6831572232738374}}
{"text": "/**\n * @file eigen.cpp\n * @author Wei Du\n *\n * @version 0.1\n * @date 2021-08-18\n */\n\n// STL include\n#include <array>\n#include <cassert>\n#include <iostream>\n\n// external include\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n/*\n * int main() {\n *   //  x, y, z, w\n *   std::array<double, 4> arr{0.3, 0.27, 0, 1.0};\n *   Eigen::Vector4d vct{0.3, 0.27, 0, 1};\n *\n *   // Eigen::Quaterniond quat1(vct(0), vct(1), vct(2), vct(3));\n *   // Eigen::Quaterniond quat2(arr[0], arr[1], arr[2], arr[3]);\n *   Eigen::Quaterniond quat1(vct.data());\n *   Eigen::Quaterniond quat2(arr.data());\n *\n *   printf(\"should be: %.2f %.2f %.2f %.2f\\n\", arr[0], arr[1], arr[2], arr[3]);\n *   printf(\"%.2f %.2f %.2f %.2f\\n\", quat1.x(), quat1.y(), quat1.z(),\n * quat1.w()); printf(\"%.2f %.2f %.2f %.2f\\n\", quat2.x(), quat2.y(), quat2.z(),\n * quat2.w()); return 0;\n * }\n */\n\n/*\n * int main() {\n *   Eigen::VectorXd v1(4);\n *   Eigen::Vector3d v2{0.1, 0.2, 0.3};\n *\n *   v1.head(3) = v2;\n *   v1(3) = 0.8;\n *   std::cout << v1 << std::endl;\n *   return 0;\n * }\n */\n\n/*\nint main() {\n  Eigen::Vector2d tran{0.2, 0.3};\n  Eigen::Rotation2Dd ori(0.785398);\n\n  Eigen::Affine2d pose;\n  pose.setIdentity();\n  pose.translate(tran);\n  pose.rotate(ori);\n\n  Eigen::Vector2d origin{0.1, 0.0};\n  Eigen::Vector2d newpt = pose * origin;\n  std::cout << newpt << std::endl;\n  return 0;\n}\n*/\n\n/*\nint main() {\n  Eigen::Vector3d vct1;\n  Eigen::VectorXd vct2;\n  if (vct1.isApprox(vct2)) {\n    printf(\"they are the same\\n\");\n  } else {\n    printf(\"they are not the same\\n\");\n  }\n  std::cout << vct1 << std::endl;\n\n  return 0;\n}\n*/\n\n/*\n * int main() {\n *   Eigen::MatrixXd mt;\n *   mt.resize(1000, 1000);\n *   mt.fill(-1);\n *   std::cout << mt;\n *   return 0;\n * }\n */\n\n/*\n * int main() {\n *   Eigen::MatrixXd mat(5, 4);\n *   mat << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n * 20;\n *\n *   std::cout << mat.rows() << std::endl;\n *   mat.conservativeResize(mat.rows() - 2, 3);\n *   std::cout << mat << std::endl;\n *   std::cout << mat.rows() << std::endl;\n *\n *   return 0;\n * }\n */\n\n/*\n * int main() {\n *   const Eigen::Vector3d vec{0, 1, 0};\n *   std::cout << vec << std::endl;\n *   return 0;\n * }\n */\n\nint main() {\n  Eigen::MatrixXd mt(2, 2);\n  mt << 0, 1, 2, 3;\n\n  Eigen::MatrixXd new_mt = mt;\n  mt(1, 1) = 8;\n  std::cout << mt << std::endl;\n  std::cout << new_mt << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "6410a7c081b8f672e717ab25458f9e14c40dbc7b", "size": 2371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen.cpp", "max_stars_repo_name": "SushiStar/Doubts", "max_stars_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "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/eigen.cpp", "max_issues_repo_name": "SushiStar/Doubts", "max_issues_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "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/eigen.cpp", "max_forks_repo_name": "SushiStar/Doubts", "max_forks_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "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": 19.1209677419, "max_line_length": 80, "alphanum_fraction": 0.5221425559, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6831501199960197}}
{"text": "#include \"convex_hull.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace GooBalls;\nusing namespace Spatial;\nusing namespace impl;\n\nBOOST_AUTO_TEST_CASE(convex_hull_angles){\n\tPoint p0;\n\tp0.x = 1;\n\tp0.y = 1;\n\n\tstd::vector<Point> ps(3);\n\n\t// -45\u00b0\n\tps[0].x = 2;\n\tps[0].y = 0;\n\n\t// 0\u00b0\n\tps[1].x = 2;\n\tps[1].y = 1;\n\t\n\tps[2].x = 2;\n\tps[2].y = 2;\n\n\tcomputeAngles(ps.begin(), ps.end(), p0);\n\n\tBOOST_CHECK_EQUAL(-45.0/180*M_PI, ps[0].angle);\n\tBOOST_CHECK_EQUAL(0.0/180*M_PI, ps[1].angle);\n\tBOOST_CHECK_EQUAL(45.0/180*M_PI, ps[2].angle);\n}\n\nBOOST_AUTO_TEST_CASE(convex_hull_turn_direction){\n\tPoint p0;\n\tp0.x = 1;\n\tp0.y = 1;\n\tPoint p1;\n\tp1.x = 2;\n\tp1.y = 1;\n\tPoint p2;\n\tp2.x = 1;\n\tp2.y = 2;\n\tPoint p3;\n\tp3.x = 3;\n\tp3.y = 1;\n\n\tBOOST_CHECK_EQUAL(Left, turnDirection(p0, p1, p2));\n    BOOST_CHECK_EQUAL(Right, turnDirection(p0, p2, p1));\n\tBOOST_CHECK_EQUAL(None, turnDirection(p0, p1, p3));\n}\n\nBOOST_AUTO_TEST_CASE(convex_hull_test1){\n\tCoordinates2d pointSet(5, 2);\n\t// lower left corner\n\tpointSet(0,0) = -1;\n\tpointSet(0,1) = -1;\n\t// upper left corner\n\tpointSet(1,0) = -1;\n\tpointSet(1,1) = 1;\n\t// center\n\tpointSet(2,0) = 0.5;\n\tpointSet(2,1) = -0.1;\n\t// lower right corner\n\tpointSet(3,0) = 1;\n\tpointSet(3,1) = -1;\n\t// upper right corner\n\tpointSet(4,0) = 1;\n\tpointSet(4,1) = 1;\n\n    pointSet = convex_hull(pointSet);\n\n    BOOST_CHECK_EQUAL(4, pointSet.rows());\n    // To be precise: this uses knowledge of the implementation, according to the contract, we could start with any point of the convex hull\n    BOOST_CHECK_EQUAL(-1, pointSet(0,0));\n    BOOST_CHECK_EQUAL(-1, pointSet(0,1));\n    BOOST_CHECK_EQUAL(1, pointSet(1,0));\n    BOOST_CHECK_EQUAL(-1, pointSet(1,1));\n    BOOST_CHECK_EQUAL(1, pointSet(2,0));\n    BOOST_CHECK_EQUAL(1, pointSet(2,1));\n    BOOST_CHECK_EQUAL(-1, pointSet(3,0));\n    BOOST_CHECK_EQUAL(1, pointSet(3,1));\n}\n", "meta": {"hexsha": "7652bc898dc6694827249228ac5fb99ca64e8b11", "size": 1826, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lib/spatial/2d/convex_hull.test.cc", "max_stars_repo_name": "Fluci/GooBalls", "max_stars_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "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/lib/spatial/2d/convex_hull.test.cc", "max_issues_repo_name": "Fluci/GooBalls", "max_issues_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "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/lib/spatial/2d/convex_hull.test.cc", "max_forks_repo_name": "Fluci/GooBalls", "max_forks_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "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.7380952381, "max_line_length": 140, "alphanum_fraction": 0.6571741512, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7981867801399694, "lm_q1q2_score": 0.6831290654074915}}
{"text": "//============================================================================\n// Daniel J. Greenhoe\n// normed linear space R^2\n//============================================================================\n//=====================================\n// headers\n//=====================================\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include \"r1.h\"\n#include \"r3.h\"\n\n\n//=====================================\n// VectR3\n//=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief Calculate magnitude of vector\n//-----------------------------------------------------------------------------\ndouble vectR3::mag(void) const \n{\n  const double x = getx();\n  const double y = gety();\n  const double z = getz();\n  const double magSq  = x*x + y*y + z*z;\n  const double magVal = sqrt( magSq );\n  return magVal;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Convert polar (r, theta, phi) coordinate to rectangular (x,y,z) coordinate\n//-----------------------------------------------------------------------------\nvoid vectR3::polartoxyz(const double r, const double theta, const double phi)\n{\n  const double x = r*cos(phi)*cos(theta);\n  const double y = r*cos(phi)*sin(theta);\n  const double z = r*sin(phi);\n  otriple::put( x, y, z );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Add vector q to vectR3 vector\n//-----------------------------------------------------------------------------\nvoid vectR3::operator+=(const vectR3 q)\n{\n  Eigen::Map< Eigen::Vector3d > a(   getdataa() );\n  const Eigen::Map< const Eigen::Vector3d > b( q.getdata() );\n  a += b;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Subtract vector q from vectR3 vector\n//-----------------------------------------------------------------------------\nvoid vectR3::operator-=(const vectR3 q)\n{\n  Eigen::Map< Eigen::Vector3d > a(   getdataa() );\n  const Eigen::Map< const Eigen::Vector3d > b( q.getdata() );\n  a -= b;\n}\n\n//=====================================\n// seqR3\n//=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR3 to 0\n//-----------------------------------------------------------------------------\nseqR3::seqR3(long M)\n{\n  N=M;\n  seqr3 = new vectR3[N];\n  clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR3 to <u>\n//-----------------------------------------------------------------------------\nseqR3::seqR3(long M, double u)\n{\n  N = M;\n  seqr3 = new vectR3[N];\n  fill( u );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the seqR3 with a value 0\n//-----------------------------------------------------------------------------\nvoid seqR3::clear(void)\n{\n  for( long n=0; n<N; n++) put( n, 0 );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the seqR3 with a value <u>\n//-----------------------------------------------------------------------------\nvoid seqR3::fill(double u)\n{\n  long n;\n  for(n=0; n<N; n++) put( n, u );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Put a single value <u> into the seqR3 x at location n\n//-----------------------------------------------------------------------------\nint seqR3::put(long n, double u, double v, double w)\n{\n  if(n<N){\n    seqr3[n].otriple::put( u, v, w );\n    return 0;\n    }\n  else{   \n    fprintf(stderr,\"n=%ld larger than seqR3 size N=%ld\\n\",n,N);\n    return -1;\n    }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Put a single value <u> into the seqR3 x at location n\n//-----------------------------------------------------------------------------\nint seqR3::put(long n, vectR3 abc)\n{\n  if(n<N)\n  {\n    (seqr3[n]).otriple::put( abc.getx(), abc.gety(), abc.gety() );\n    return 0;\n  }\n  else\n  {   \n    fprintf(stderr,\"n=%ld larger than seqR3 size N=%ld\\n\",n,N);\n    return -1;\n  }\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Get a single value from the sequence x at location n\n//-----------------------------------------------------------------------------\nvectR3 seqR3::get(long n)\n{\n  return seqr3[n];\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Get the x element from the sequence at location n\n//-----------------------------------------------------------------------------\ndouble seqR3::getx(long n)\n{\n  double u=0;\n  if(n<N)u = seqr3[n].getx();\n  else   fprintf(stderr,\"n=%ld larger than x seqR3 size N=%ld\\n\",n,N);\n  return u;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Get the y element from the sequence at location n\n//-----------------------------------------------------------------------------\ndouble seqR3::gety(long n){\n  double u=0;\n  if(n<N)u = seqr3[n].gety();\n  else   fprintf(stderr,\"n=%ld larger than y seqR3 size N=%ld\\n\",n,N);\n  return u;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief Get the z element from the sequence at location n\n//-----------------------------------------------------------------------------\ndouble seqR3::getz(long n){\n  double u=0;\n  if(n<N)u = seqr3[n].getz();\n  else   fprintf(stderr,\"n=%ld larger than z seqR3 size N=%ld\\n\",n,N);\n  return u;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief list contents of sequence\n//-----------------------------------------------------------------------------\nvoid seqR3::list(const long start, const long end, const char *str1, const char *str2, FILE *ptr){\n  long n,m;\n  if(ptr!=NULL){\n    if(strlen(str1)>0) fprintf(ptr,\"%s\",str1);\n    for(n=start,m=1; n<=end; n++,m++){\n      fprintf(ptr,\"(%6.3lf,%6.3lf,%6.3lf) \", seqr3[n].getx(), seqr3[n].gety(), seqr3[n].getz() );\n      if(m%3==0)fprintf(ptr,\"\\n\");\n      }\n    if(strlen(str2)>0)fprintf(ptr,\"%s\",str2);\n    }\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief list contents of seqR3 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR3::list1(void){\n  long n,m;\n  for(n=0,m=1; n<N; n++,m++){\n    printf(\"(%2.0lf,%2.0lf,%2.0lf)   \", seqr3[n].getx(), seqr3[n].gety(), seqr3[n].getz() );\n    if(m%5==0)printf(\"\\n\");\n    }\n  }\nvoid seqR3::list1(long start, long end){\n  long n,m;\n  for(n=start,m=1; n<=end; n++,m++){\n    printf(\"(%2.0lf,%2.0lf,%2.0lf)   \", seqr3[n].getx(), seqr3[n].gety(), seqr3[n].getz() );\n    if(m%50==0)printf(\"\\n\");\n    else if(m%10==0)printf(\" \");\n    }\n  }\n\n\n//=====================================\n// external operations\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief operator: return p+q\n//-----------------------------------------------------------------------------\nvectR3 operator+(vectR3 p, vectR3 q)\n{\n  const Eigen::Map< const Eigen::Vector3d > a( p.getdataa() );\n  const Eigen::Map< const Eigen::Vector3d > b( q.getdataa() );\n  const Eigen::Vector3d c = a + b;\n  const vectR3 r( c(0), c(1), c(2) );\n  return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return p-q\n//-----------------------------------------------------------------------------\nvectR3 operator-(vectR3 p, vectR3 q){\n  const Eigen::Map< const Eigen::Vector3d > a( p.getdataa() );\n  const Eigen::Map< const Eigen::Vector3d > b( q.getdataa() );\n  const Eigen::Vector3d c = a - b;\n  const vectR3 r( c(0), c(1), c(2) );\n  return r;\n  }\n\n//-----------------------------------------------------------------------------\n//! \\brief  operator: return -p\n//-----------------------------------------------------------------------------\nvectR3 operator-(vectR3 p)\n{\n  const Eigen::Map< const Eigen::Vector3d > a( p.getdataa() );\n  const Eigen::Vector3d b = -a;\n  const vectR3 q( b(0), b(1), b(2) );\n  return q;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief return the angle theta in radians between the two vectors induced by \n//! the points <p> and <q> in the space R^3.\n//! \\returns On SUCCESS return theta in the closed interval [0:PI];\n//!          On ERROR   return negative value or exit with value EXIT_FAILURE\n//-----------------------------------------------------------------------------\ndouble pqtheta(const vectR3 p, const vectR3 q)\n{\n  const double rp=p.mag();\n  const double rq=q.mag();\n  if(rp==0) return -1;\n  if(rq==0) return -2;\n  const double y = (p^q)/(rp*rq);\n  if(y>+1)  {fprintf(stderr,\"\\nERROR using pqtheta(vectR3 p, vectR3 q): (p^q)/(rp*rq)=%lf>+1\\n\",y); exit(EXIT_FAILURE);}\n  if(y<-1)  {fprintf(stderr,\"\\nERROR using pqtheta(vectR3 p, vectR3 q): (p^q)/(rp*rq)=%lf<-1\\n\",y); exit(EXIT_FAILURE);}\n  const double theta = acos(y);\n  return theta;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the minimum element of the tupple\n//-----------------------------------------------------------------------------\ndouble otriple::min(void) const\n{\n  const Eigen::Map< const Eigen::Vector3d > abc( getdata() );\n  int row, col;\n  const double min = abc.minCoeff( &row, &col );\n  return min;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the maximum element of the tupple\n//-----------------------------------------------------------------------------\ndouble otriple::max(void) const\n{\n  const Eigen::Map< const Eigen::Vector3d > abc( getdata() );\n  int row, col;\n  const double max = abc.maxCoeff( &row, &col );\n  return max;\n}\n", "meta": {"hexsha": "e02f71aa55cedf70ee89416605de83bf735aac52", "size": 10023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "r3.cpp", "max_stars_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_stars_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r3.cpp", "max_issues_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_issues_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r3.cpp", "max_forks_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_forks_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_forks_repo_licenses": ["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.9233449477, "max_line_length": 120, "alphanum_fraction": 0.3711463634, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6831290621791717}}
{"text": "#define BOOST_TEST_MODULE \"test_matrix_vector\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mill/math/Vector.hpp>\n\n#include <random>\nconstexpr static unsigned int seed = 32479327;\nconstexpr static std::size_t N = 10000;\n\nBOOST_AUTO_TEST_CASE(multiple_unit_matrix_and_vector)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    const mill::Matrix<double, 3, 3> E(1., 0., 0., 0., 1., 0., 0., 0., 1.);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const mill::Vector<double, 3> same = E * lhs;\n\n        BOOST_CHECK_EQUAL(lhs[0], same[0]);\n        BOOST_CHECK_EQUAL(lhs[1], same[1]);\n        BOOST_CHECK_EQUAL(lhs[2], same[2]);\n    }\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const mill::Matrix<double, 1, 3> same = mill::transpose(lhs) * E;\n        const mill::Vector<double, 3> rhs = mill::transpose(same);\n\n        BOOST_CHECK_EQUAL(lhs[0], rhs[0]);\n        BOOST_CHECK_EQUAL(lhs[1], rhs[1]);\n        BOOST_CHECK_EQUAL(lhs[2], rhs[2]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(multiple_matrix_and_vector)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        const double coef = uni(mt);\n        const mill::Matrix<double, 3, 3> M(coef, 0., 0., 0., coef, 0., 0., 0., coef);\n        const mill::Vector<double, 3> lhs(uni(mt), uni(mt), uni(mt));\n        const mill::Vector<double, 3> same = M * lhs;\n\n        BOOST_CHECK_EQUAL(lhs[0] * coef, same[0]);\n        BOOST_CHECK_EQUAL(lhs[1] * coef, same[1]);\n        BOOST_CHECK_EQUAL(lhs[2] * coef, same[2]);\n    }\n}\n", "meta": {"hexsha": "06efb206d66952f329dd4a4e44511f441135f525", "size": 1932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/test_matrix_vector.cpp", "max_stars_repo_name": "ToruNiina/Coffee-mill", "max_stars_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-11T07:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T07:33:37.000Z", "max_issues_repo_path": "tests/math/test_matrix_vector.cpp", "max_issues_repo_name": "ToruNiina/Coffee-mill", "max_issues_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/test_matrix_vector.cpp", "max_forks_repo_name": "ToruNiina/Coffee-mill", "max_forks_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_forks_repo_licenses": ["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.6721311475, "max_line_length": 85, "alphanum_fraction": 0.6345755694, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6831076381490537}}
{"text": "#ifndef MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n#define MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n\n#include <Eigen/Core>\n#include <cassert>\n#include <functional>\n#include <iostream>\n\n#define MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        // Algorithm 3.5: Line Search Algorithm\n        //\n        // This algoritmh tries to find an appropriate step size that satisfies the strong Wolfe conditions (i.e., both\n        // the safficient decreasing condition and the curvature condition).\n        inline double\n        RunStrongWolfeConditionsLineSearch(const std::function<double(const Eigen::VectorXd&)>&          f,\n                                           const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& g,\n                                           const Eigen::VectorXd&                                        x,\n                                           const Eigen::VectorXd&                                        p,\n                                           const double                                                  alpha_init,\n                                           const double alpha_max = 50.0,\n                                           const double c_1       = 1e-04,\n                                           const double c_2       = 0.9)\n        {\n            auto phi      = [&](const double alpha) { return f(x + alpha * p); };\n            auto phi_grad = [&](const double alpha) { return static_cast<double>(g(x + alpha * p).transpose() * p); };\n\n            const double phi_zero      = phi(0.0);\n            const double phi_grad_zero = phi_grad(0.0);\n\n            double alpha_prev     = 0.0;\n            double alpha          = alpha_init;\n            double phi_alpha_prev = phi_zero;\n\n            bool is_first = true;\n\n            // Algorithm 3.6: Zoom\n            auto zoom = [&](double alpha_l, double alpha_h) {\n                constexpr unsigned int max_num_iterations = 50;\n                for (unsigned int i = 0; i < max_num_iterations; ++i)\n                {\n                    const double alpha_j     = 0.5 * (alpha_l + alpha_h); // TODO: Use a better strategy\n                    const double phi_alpha_j = phi(alpha_j);\n\n                    if (phi_alpha_j > phi_zero + c_1 * alpha_j * phi_grad_zero || phi_alpha_j >= phi(alpha_l))\n                    {\n                        alpha_h = alpha_j;\n                    }\n                    else\n                    {\n                        const double phi_grad_alpha_j = phi_grad(alpha_j);\n                        if (std::abs(phi_grad_alpha_j) <= -c_2 * phi_grad_zero)\n                        {\n                            return alpha_j;\n                        }\n                        if (phi_grad_alpha_j * (alpha_h - alpha_l) >= 0.0)\n                        {\n                            alpha_h = alpha_l;\n                        }\n                        alpha_l = alpha_j;\n                    }\n                }\n#ifdef MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n                std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n#endif\n                return 0.5 * (alpha_l + alpha_h);\n            };\n\n            constexpr unsigned int max_num_iterations = 50;\n            for (int i = 0; i < max_num_iterations; ++i)\n            {\n                const double phi_alpha = phi(alpha);\n\n                if (phi_alpha > phi_zero + c_1 * alpha * phi_grad_zero || (!is_first && (phi_alpha >= phi_alpha_prev)))\n                {\n                    return zoom(alpha_prev, alpha);\n                }\n\n                const double phi_grad_alpha = phi_grad(alpha);\n\n                if (std::abs(phi_grad_alpha) <= -c_2 * phi_grad_zero)\n                {\n                    return alpha;\n                }\n\n                if (phi_grad_alpha >= 0.0)\n                {\n                    return zoom(alpha, alpha_prev);\n                }\n\n                alpha_prev     = alpha;\n                phi_alpha_prev = phi_alpha;\n\n                alpha = 0.5 * (alpha + alpha_max); // TODO: Use a better strategy\n            }\n#ifdef MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n            std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n#endif\n            return alpha_init;\n        }\n    } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n", "meta": {"hexsha": "be3ae4d67db88d693fe8c1296ea37839282f2da5", "size": 4444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/strong-wolfe-conditions-line-search.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/strong-wolfe-conditions-line-search.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/strong-wolfe-conditions-line-search.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": 40.7706422018, "max_line_length": 119, "alphanum_fraction": 0.4774977498, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6829342556950038}}
{"text": "/* \n * Rand_normal: generate random numbers (normal distribution) using boost::random.\n *\n * Copyright (c) 2012 J\u00e9r\u00e9mie Decock\n *\n * Required: boost.random library\n * Usage: g++ rand_normal.cc\n *\n */\n\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <ctime>\n#include <iostream>\n\nconst int num_it = 100000;\nconst double min = 1.0;\nconst double max = 10.0;\nconst double mu = 0.0;\nconst double sigma = 1.0;\n\nmain() {\n\n    // Pseudo-random number generator\n    //boost::mt19937 rng;               // deterministic\n    boost::mt19937 rng(std::time(NULL));\n\n    // Random number distribution\n    boost::normal_distribution<> distrib(mu, sigma);\n\n    // Generator (wrapper)\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > random_generator(rng, distrib);\n\n    for(int i=0 ; i<num_it ; i++) {\n        double x = random_generator();\n        double y = random_generator();\n        std::cout << x << \" \" << y << std::endl;\n    }\n\n}\n", "meta": {"hexsha": "9a8a945944d2fa16f493959011e03918be2bbaf2", "size": 985, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/boost_random/basic_snippets/rand_normal.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/boost_random/basic_snippets/rand_normal.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/boost_random/basic_snippets/rand_normal.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": 24.0243902439, "max_line_length": 108, "alphanum_fraction": 0.6467005076, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6829342479324029}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\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//[comparable_distance\r\n//` Shows how to efficiently get the closest point\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\n#include <boost/numeric/conversion/bounds.hpp>\r\n#include <boost/foreach.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\r\n    \r\n    point_type p(1.4, 2.6);\r\n    \r\n    std::vector<point_type> v;\r\n    for (double x = 0.0; x <= 4.0; x++)\r\n    {\r\n        for (double y = 0.0; y <= 4.0; y++)\r\n        {\r\n            v.push_back(point_type(x, y));\r\n        }\r\n    }\r\n    \r\n    point_type min_p;\r\n    double min_d = boost::numeric::bounds<double>::highest();\r\n    BOOST_FOREACH(point_type const& pv, v)\r\n    {\r\n        double d = boost::geometry::comparable_distance(p, pv);\r\n        if (d < min_d)\r\n        {\r\n            min_d = d;\r\n            min_p = pv;\r\n        }\r\n    }\r\n    \r\n    std::cout \r\n        << \"Closest: \" << boost::geometry::dsv(min_p) << std::endl\r\n        << \"At: \" << boost::geometry::distance(p, min_p) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[comparable_distance_output\r\n/*`\r\nOutput:\r\n[pre\r\nClosest: (1, 3)\r\nAt: 0.565685\r\n]\r\n*/\r\n//]\r\n\r\n", "meta": {"hexsha": "cb260d63203ef4984dfc63af3e47172dee311d2c", "size": 1528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/comparable_distance.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/doc/src/examples/algorithms/comparable_distance.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/doc/src/examples/algorithms/comparable_distance.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": 22.4705882353, "max_line_length": 80, "alphanum_fraction": 0.5778795812, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.6828550045345865}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include <algorithm>\n#include <cmath>\n\n#include \"gtest/gtest.h\"\n#include \"math/matrix/rq_decomposition.h\"\n\nnamespace GraphSfM {\n\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix3f;\nusing Eigen::Matrix4d;\nusing Eigen::Matrix4f;\nusing Eigen::MatrixXd;\n\nconst double kSmallTolerance = 1e-12;\nconst double kLargeTolerance = 1e-6;\n\ntemplate <typename MatrixType>\nvoid TestRQDecomposition(const int rows, const int cols, const double tol) {\n  for (int i = 0; i < 100; ++i) {\n    const MatrixType& m = MatrixType::Random(rows, cols);\n    RQDecomposition<MatrixType> rq(m);\n    EXPECT_TRUE(rq.matrixR().bottomRows(std::min(rows, cols))\n                    .isUpperTriangular());\n    EXPECT_TRUE(rq.matrixQ().isUnitary());\n    EXPECT_NEAR(rq.matrixQ().determinant(), 1.0, kLargeTolerance);\n\n    const MatrixType& diff = rq.matrixR() * rq.matrixQ() - m;\n    EXPECT_LE(diff.cwiseAbs().maxCoeff(), tol)\n        << rq.matrixR() << \"\\n\\n\" << rq.matrixQ() << \"\\n\\n\"\n        << rq.matrixR() * rq.matrixQ() << \"\\n\\n\" << m;\n  }\n}\n\nTEST(RQTest, FixedSizeMatrices) {\n  // Square matrices.\n  TestRQDecomposition<Matrix3d>(3, 3, kSmallTolerance);\n  TestRQDecomposition<Matrix4d>(4, 4, kSmallTolerance);\n  TestRQDecomposition<Matrix<double, 5, 5> >(5, 5, kSmallTolerance);\n  TestRQDecomposition<Matrix<double, 6, 6> >(6, 6, kSmallTolerance);\n\n  // Non-square matrices.\n  TestRQDecomposition<Matrix<double, 3, 4> >(3, 4, kSmallTolerance);\n  TestRQDecomposition<Matrix<double, 4, 3> >(4, 3, kSmallTolerance);\n}\n\nTEST(RQTest, DynamicSizedMatrices) {\n  // Square matrices.\n  TestRQDecomposition<MatrixXd>(25, 25, kSmallTolerance);\n  TestRQDecomposition<MatrixXd>(50, 50, kSmallTolerance);\n  TestRQDecomposition<MatrixXd>(75, 75, kSmallTolerance);\n  TestRQDecomposition<MatrixXd>(100, 100, kSmallTolerance);\n\n  // Non-square matrices.\n  TestRQDecomposition<MatrixXd>(30, 40, kSmallTolerance);\n  TestRQDecomposition<MatrixXd>(40, 30, kSmallTolerance);\n}\n\nTEST(RQTest, FloatMatrices) {\n  TestRQDecomposition<Matrix3f>(3, 3, kLargeTolerance);\n  TestRQDecomposition<Matrix4f>(4, 4, kLargeTolerance);\n}\n\nTEST(RQTest, RowMajorMatrices) {\n  TestRQDecomposition<Matrix<double, 3, 3, Eigen::RowMajor> >(3, 3,\n                                                              kSmallTolerance);\n  TestRQDecomposition<Matrix<float, 3, 3, Eigen::RowMajor> >(3, 3,\n                                                             kLargeTolerance);\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "fc7e208350ec5f01ff81f6fd01a5e1e1519c98d6", "size": 2484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/rq_decomposition_test.cpp", "max_stars_repo_name": "LumanYang/GraphSfM", "max_stars_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:18:43.000Z", "max_issues_repo_path": "src/math/rq_decomposition_test.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/rq_decomposition_test.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6842105263, "max_line_length": 79, "alphanum_fraction": 0.67431562, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6827535543514284}}
{"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n\n#include <boost/mpl/equal_to.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/multiplies.hpp>\n#include <boost/mpl/pair.hpp>\n#include <boost/mpl/plus.hpp>\n\n#include <boost/hana/constant.hpp>\n#include <boost/hana/core/models.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/pair.hpp>\n\n#include <cassert>\n#include <type_traits>\nnamespace hana = boost::hana;\n\n\ntemplate <typename T, typename = std::enable_if_t<\n  !hana::models<hana::Constant, T>()\n>>\nconstexpr T sqrt(T x) {\n  T inf = 0, sup = (x == 1 ? 1 : x/2);\n  while (!((sup - inf) <= 1 || ((sup*sup <= x) && ((sup+1)*(sup+1) > x)))) {\n    T mid = (inf + sup) / 2;\n    bool take_inf = mid*mid > x ? 1 : 0;\n    inf = take_inf ? inf : mid;\n    sup = take_inf ? mid : sup;\n  }\n\n  return sup*sup <= x ? sup : inf;\n}\n\ntemplate <typename T, typename = std::enable_if_t<\n  hana::models<hana::Constant, T>()\n>>\nconstexpr auto sqrt(T const&) {\n  return hana::integral_constant<typename T::value_type, sqrt(T::value)>;\n}\n\n\nnamespace then {\nusing namespace boost::mpl;\n\ntemplate <typename N>\nstruct sqrt\n  : integral_c<typename N::value_type, ::sqrt(N::value)>\n{ };\n\ntemplate <typename X, typename Y>\nstruct point {\n  using x = X;\n  using y = Y;\n};\n\n// sample(arithmetic-then)\ntemplate <typename P1, typename P2>\nstruct distance {\n  using xs = typename minus<typename P1::x,\n                            typename P2::x>::type;\n  using ys = typename minus<typename P1::y,\n                            typename P2::y>::type;\n  using type = typename sqrt<\n    typename plus<\n      typename multiplies<xs, xs>::type,\n      typename multiplies<ys, ys>::type\n    >::type\n  >::type;\n};\n\nstatic_assert(equal_to<\n  distance<point<int_<3>, int_<5>>, point<int_<7>, int_<2>>>::type,\n  int_<5>\n>::value, \"\");\n// end-sample\n}\n\n\nnamespace now {\nusing namespace boost::hana;\nusing namespace boost::hana::literals;\n\ntemplate <typename X, typename Y>\nstruct _point {\n  X x;\n  Y y;\n};\ntemplate <typename X, typename Y>\nconstexpr _point<X, Y> point(X x, Y y) { return {x, y}; }\n\n// sample(arithmetic-now)\ntemplate <typename P1, typename P2>\nconstexpr auto distance(P1 p1, P2 p2) {\n  auto xs = p1.x - p2.x;\n  auto ys = p1.y - p2.y;\n  return sqrt(xs*xs + ys*ys);\n}\n\nstatic_assert(distance(point(3_c, 5_c), point(7_c, 2_c)) == 5_c, \"\");\n// end-sample\n\nvoid test() {\n\n// sample(arithmetic-now-dynamic)\nauto p1 = point(3, 5); // dynamic values now\nauto p2 = point(7, 2); //\nassert(distance(p1, p2) == 5); // same function works!\n// end-sample\n\n}\n}\n\n\nint main() {\n  now::test();\n}\n", "meta": {"hexsha": "961239f0746344e4a133696a552a7a8d43cab14e", "size": 2682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/arithmetic.cpp", "max_stars_repo_name": "ldionne/cppnow-2015-hana", "max_stars_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-02T22:23:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:44:15.000Z", "max_issues_repo_path": "code/arithmetic.cpp", "max_issues_repo_name": "ldionne/cppnow-2015-hana", "max_issues_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/arithmetic.cpp", "max_forks_repo_name": "ldionne/cppnow-2015-hana", "max_forks_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_forks_repo_licenses": ["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.35, "max_line_length": 76, "alphanum_fraction": 0.6387024609, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6826745941630797}}
{"text": "//\n// Created by lei on 4/21/19.\n//\n\n#include \"catch.hpp\"\n\n#include \"topography.hpp\"\n#include <armadillo>\n#include <vector>\n#include <fmt/format.h>\n\narma::vec func1(const arma::vec &x, double c = 0.) {\n    return arma::pow((x-c), 2);\n}\n\n\nTEST_CASE(\"f = x^2\", \"[topo]\") {\n    int n = 8;\n    arma::vec x = arma::linspace(-1.1, 1, n);\n    arma::vec f = func1(x);\n    Topography topo(x, f, 3);\n    std::vector<double> min_pool = topo.minimize_pool();\n    double dx = (x(1) - x(0)) / 2.;\n    REQUIRE(min_pool[0] == Approx(0.0).margin(dx));\n}\n\nTEST_CASE(\"f = x^2 * (x-1)^2\", \"[topo]\") {\n    int n = 100;\n    arma::vec x = arma::linspace(-1.1, 1, n);\n    arma::vec f = func1(x) % func1(x, 1.0);\n    Topography topo(x, f, 3);\n    std::vector<double> min_pool = topo.minimize_pool();\n    double dx = (x(1) - x(0)) / 2.;\n    REQUIRE(min_pool[0] == Approx(0.0).margin(dx));\n    REQUIRE(min_pool[1] == Approx(1.0).margin(dx));\n}", "meta": {"hexsha": "d620b81cf3a62acc380c144f8628ab88bd197e41", "size": 916, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_topography.cc", "max_stars_repo_name": "pan3rock/tgo1d-cxx", "max_stars_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_topography.cc", "max_issues_repo_name": "pan3rock/tgo1d-cxx", "max_issues_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_topography.cc", "max_forks_repo_name": "pan3rock/tgo1d-cxx", "max_forks_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 56, "alphanum_fraction": 0.5633187773, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6826432841772581}}
{"text": "\n// solving A * X = B\n// A hermitian\n// driver function hesv()\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/hesv.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cin;\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> cherml_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> chermu_t; \n\nint main() {\n\n  cm_t cal (3, 3), cau (3, 3);   // matrices (storage)\n  cherml_t hcal (cal);   // hermitian adaptor \n  chermu_t hcau (cau);   // hermitian adaptor \n  cm_t cx (3, 1);\n  cm_t cbl (3, 1), cbu (3, 1);  // RHS\n\n  hcal (0, 0) = cmplx_t (3, 0);\n  hcal (1, 0) = cmplx_t (4, -2);\n  hcal (1, 1) = cmplx_t (5, 0);\n  hcal (2, 0) = cmplx_t (-7, -5);\n  hcal (2, 1) = cmplx_t (0, 3);\n  hcal (2, 2) = cmplx_t (2, 0);\n\n  hcau (0, 0) = cmplx_t (3, 0);\n  hcau (0, 1) = cmplx_t (4, 2);\n  hcau (0, 2) = cmplx_t (-7, 5);\n  hcau (1, 1) = cmplx_t (5, 0);\n  hcau (1, 2) = cmplx_t (0, -3);\n  hcau (2, 2) = cmplx_t (2, 0);\n\n  print_m (cal, \"cal\"); \n  cout << endl; \n  print_m (cau, \"cau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (hcal, cx);\n  cbu = prod (hcau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  cm_t cal2 (hcal), cau2 (hcau);  // for part 2\n  cm_t cbl2 (cbl), cbu2 (cbu); \n\n  int ierr = lapack::hesv (hcal, cbl); \n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  std::vector<integer_t> ipiv (3); \n  std::vector<cmplx_t> cwork (3*64); \n  // 3*64 -- optimal size\n\n  ierr = lapack::hesv (hcau, ipiv, cbu, cwork); \n  if (ierr == 0) {\n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu, \"cxu\"); \n  }\n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  // part 2\n\n  swap (row (cal2, 0), row (cal2, 2));\n  swap (column (cal2, 0), column (cal2, 2));\n\n  swap (row (cau2, 1), row (cau2, 2));\n  swap (column (cau2, 1), column (cau2, 2));\n\n  print_m (cal2, \"cal2\"); \n  cout << endl; \n  print_m (cau2, \"cau2\"); \n  cout << endl; \n\n  cbl2 = prod (cal2, cx);\n  cbu2 = prod (cau2, cx);\n  print_m (cbl2, \"cbl2\"); \n  cout << endl; \n  print_m (cbu2, \"cbu2\"); \n  cout << endl; \n\n  ierr = lapack::hesv ('L', cal2, cbl2); \n  if (ierr == 0)\n    print_m (cbl2, \"cxl2\"); \n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  ierr = lapack::hesv ('U', cau2, ipiv, cbu2, cwork); \n  if (ierr == 0) {\n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu2, \"cxu\"); \n  }\n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "f3bf14879d2404f0c0165129ce299133a91dacca", "size": 3242, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["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.8382352941, "max_line_length": 63, "alphanum_fraction": 0.5687847008, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.682643272116696}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Returns n!\r\ncpp_int factorial(cpp_int n) {\r\n\tif(n == 0) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn n * factorial(n - 1);\r\n}\r\n\r\n// Returns the sum of the factorials of the digits of a number.\r\ncpp_int sumDigitsFactorial(cpp_int n) {\r\n\tcpp_int sum = 0;\r\n\twhile(n) {\r\n\t\tsum += factorial(n % 10);\r\n\t\tn /= 10;\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcpp_int sum = 0;\r\n\t// Randomly decided to put limit as 100,000 for now.\r\n\tfor(cpp_int i = 3; i <= 100'000; i++) {\r\n\t\tsum = (i == sumDigitsFactorial(i)) ? sum + i : sum;\r\n\t}\r\n\tcout << sum << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "907e306534eac9aa2427b983c9d8d096e631fea2", "size": 695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/34/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/34/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/34/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": 21.0606060606, "max_line_length": 64, "alphanum_fraction": 0.6115107914, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6826256513290021}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <igl/boundary_facets.h>\n#include <igl/colon.h>\n#include <igl/setdiff.h>\n#include <igl/unique.h>\n\n//! Finds the boundary and interior vertices, and evaluates\n//! the function g on the boundary vertices.\n//!\n//! @param[out] u should be of size <number of vertices>. At the end:\n//!             u(index) = g(vertices(index))  for each boundary index.\n//!\n//! @param[out] interiorVertexIndices the list of vertices that are not on\n//!                                   the boundary.\n//!\n//! @param[in] vertices a list of vertices for the mesh\n//!\n//! @param[in] triangles the elements represented as triangles\n//!\n//! @param[in] g the boundary value function g.\nvoid setDirichletBoundary(Eigen::VectorXd &      u,\n                          Eigen::VectorXi &      interiorVertexIndices,\n                          const Eigen::MatrixXd &vertices,\n                          const Eigen::MatrixXi &triangles,\n                          const std::function<double(double, double)> &g) {\n\t// Find boundary edges\n\tEigen::MatrixXi boundaryEdgeIndices;\n\tigl::boundary_facets(triangles, boundaryEdgeIndices);\n\n\t// Find boundary vertices\n\tEigen::VectorXi boundaryVertexIndices, IA, IC;\n\tigl::unique(boundaryEdgeIndices, boundaryVertexIndices, IA, IC);\n\n\tfor (int i = 0; i < boundaryVertexIndices.size(); ++i) {\n\t\tconst int   index = boundaryVertexIndices(i);\n\t\tconst auto &x     = vertices.row(index);\n\t\tu(index)          = g(x(0), x(1));\n\t}\n\n\tEigen::VectorXi allIndices;\n\tigl::colon<int>(0, vertices.rows() - 1, allIndices);\n\tigl::setdiff(allIndices, boundaryVertexIndices, interiorVertexIndices, IA);\n}\n", "meta": {"hexsha": "b484ee592bf425876396c61e67125c7f8c6ea4f3", "size": 1633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2888888889, "max_line_length": 76, "alphanum_fraction": 0.6466625842, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.6825923007220569}}
{"text": "//\n// Created by philipp on 22.12.19.\n//\n\n#ifndef FUNNELS_CPP_LYAPUNOV_HH\n#define FUNNELS_CPP_LYAPUNOV_HH\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <cmath>\n\nnamespace lyapunov{\n  \n  \n  template <class DERIVED>\n  inline double projected_max_radius(const Eigen::MatrixBase<DERIVED> & C0,\n                                     const Eigen::MatrixBase<DERIVED> & C1){\n    // todo optimize for usage of triangular shape\n    // use spezialised version to compute smallest eigenvalue only\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    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);\n    virtual bool covers(const lyap_zone_t & other);\n    virtual bool is_covered(const lyap_zone_t & other);\n  };\n  \n  struct fixed_ellipsoidal_zone_t{\n    virtual const Eigen::VectorXd & x0() const {\n      throw std::runtime_error(\"Virtual\");\n      return Eigen::Vector2d::Zero();\n    };\n    virtual const Eigen::MatrixXd & C() const {\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  // Does zone0 cover zone1\n  template<class DIST>\n  bool covers_helper(const fixed_ellipsoidal_zone_t &zone0,\n                     const fixed_ellipsoidal_zone_t &zone1,\n                     DIST &dist){\n  \n  \n    // First compute the projected distance\n    auto dy = zone0.C()*(dist.cp_vv(zone1.x0(), zone0.x0()));\n    double dy_norm = dy.norm(); //l2 norm\n    // center out of bounds\n    if (dy_norm>=1.){\n      return false;\n    }\n  \n    // Compute radius\n    return dy_norm+projected_max_radius(zone0.C(), zone1.C())<=1.;\n  }\n  \n  template<class DIST>\n  class fixed_ellipsoidal_lyap_t:public lyapunov_t{\n  public:\n    using dist_t = DIST;\n    \n    fixed_ellipsoidal_lyap_t(const Eigen::MatrixXd &P,\n        double gamma, DIST &dist):\n        _gamma(gamma), _dist(dist){\n      // Compute cholesky\n      Eigen::LLT<Eigen::MatrixXd> llt_pre_comp;\n      llt_pre_comp.compute(P);\n      _C = llt_pre_comp.matrixU();\n    }\n    \n    const Eigen::MatrixXd &C() const {\n      return _C;\n    }\n    double gamma() const {\n      return _gamma;\n    }\n    \n    // Conservative intersect\n    // If true, the zone may intersect with this\n    // If false, the zone does definitively not intersect\n    template<class DERIVED>\n    bool intersect(const Eigen::MatrixBase<DERIVED> &x0,\n        const fixed_ellipsoidal_zone_t &zone) {\n      // First compute the projected distance\n      auto dy = _C*(_dist.cp_vv(zone.x0(), x0));\n      double dy_norm = dy.norm(); //l2 norm\n    \n      if (dy_norm <= 1.){\n        return true;\n      }\n    \n      return dy_norm>=1.+projected_max_radius(_C, zone.C());\n    }\n  \n    // Conservative cover\n    // If true, zone is definitively covered by this\n    // If false, it may not be covered\n    template<class DERIVED>\n    bool covers(const Eigen::MatrixBase<DERIVED> &x0, const fixed_ellipsoidal_zone_t &zone) {\n      fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n      return covers_helper(this_zone, zone, _dist);\n    }\n  \n    // Conservative cover\n    // If true, this is definitively covered by zone\n    // If false, it may not be covered\n    template<class DERIVED>\n    bool is_covered(const Eigen::MatrixBase<DERIVED> &x0, const fixed_ellipsoidal_zone_t &zone) {\n      fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n      return covers_helper(zone, this_zone, _dist);\n    }\n    \n    dist_t & dist(){\n      return _dist;\n    }\n    \n  protected:\n    Eigen::MatrixXd _C;\n    double _gamma;\n    DIST &_dist;\n  };\n  \n}\n\n#endif //FUNNELS_CPP_LYAPUNOV_HH\n", "meta": {"hexsha": "c0acd88409b5ccbc27ec090b6b63e8a314d9403c", "size": 4642, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/lyapunov.hh", "max_stars_repo_name": "schlepil/funnels_cpp", "max_stars_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_stars_repo_licenses": ["MIT"], "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", "max_issues_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_issues_repo_licenses": ["MIT"], "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", "max_forks_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_forks_repo_licenses": ["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.630952381, "max_line_length": 97, "alphanum_fraction": 0.6296854804, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6825851443514461}}
{"text": "#include <gtest/gtest.h>\n#include <boost/lexical_cast.hpp>\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/lagrange_polynomial.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\n\nTEST(spectral, LagrangePolySimple)\n{\n  std::vector<int> ks({10, 20, 30, 40, 80});\n  for (int K : ks) {\n    QHermite qh(1.0, K);\n\n    lagrange_poly_simple lp(qh.points_data(), qh.size());\n\n    for (int j = 0; j < qh.size(); ++j) {\n      for (int i = 0; i < qh.size(); ++i) {\n        double val = lp.eval(j, qh.pts(i));\n        if (i == j)\n          EXPECT_NEAR(val, 1, 1e-12);\n        else\n          EXPECT_NEAR(val, 0, 1e-12);\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "5eb966c18318f21af17282fb95626f489692d34f", "size": 635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_lagrange_polynomial.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gtest/gtest_lagrange_polynomial.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_lagrange_polynomial.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6785714286, "max_line_length": 57, "alphanum_fraction": 0.5779527559, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6825851441017866}}
{"text": "//StandardDeviation_StandardError.hpp\n//purpose: header file for standard deriation\n//author: bondxue\n//version: 1.0 11/22/2017\n\n#ifndef STANDARDDEVIATION_STANDARDERROR_HPP\n#define STANDARDDEVIATION_STANDARDERROR_HPP\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n\n#include <boost/tuple/tuple.hpp> // include tuple class\n#include <boost/tuple/tuple_io.hpp> // include I/O for tuple\n\nusing namespace std;\nusing boost::tuple;\n\n// function to obtain standard deviation and standard error\nboost::tuple <double, double> get_SD_SE(vector<double> price_vec, double r, double T)\n{\n\tint price_size = price_vec.size();\n\tdouble sum_price = 0.0;\n\tdouble square_sum_price = 0.0;\n\n\tfor (int i = 0; i < price_size; i++)\n\t{\n\t\tsum_price += price_vec[i];\n\t\tsquare_sum_price += pow(price_vec[i], 2);\n\t}\n\n\tdouble temp = sqrt((square_sum_price - pow(sum_price, 2)/double(price_size))/(double(price_size)-1.0)); // use temp to store the square root part in SD formula \n\tdouble SD = temp * exp(-r*T);\n\tdouble SE = SD / sqrt(double(price_size));\n\n\treturn boost::tuple<double, double>(SD, SE);\n}\n\n#endif", "meta": {"hexsha": "464d02acc2bdd9b65a557cc620adcf90a3ee4752", "size": 1087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_stars_repo_name": "bondxue/Option-Pricing-Model", "max_stars_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_issues_repo_name": "bondxue/Option-Pricing-Model", "max_issues_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_forks_repo_name": "bondxue/Option-Pricing-Model", "max_forks_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8717948718, "max_line_length": 161, "alphanum_fraction": 0.7322907084, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6825851272688712}}
{"text": "#include <Engine/MeshEdit/DeformRBF.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Dense>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid DeformRBF::Clear() {\n\ttriMesh = nullptr;\n\torigPos.clear();\n}\n\nbool DeformRBF::Init(Ptr<TriMesh> triMesh) {\n\tif (triMesh == this->triMesh)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::DeformRBF::Init\\n\"\n\t\t\t\"\\t\"\"triMesh->GetType() == TriMesh::INVALID\\n\");\n\t\treturn false;\n\t}\n\n\tthis->triMesh = triMesh;\n\torigPos = triMesh->GetPositions();\n\treturn true;\n}\n\nbool DeformRBF::Run(const std::vector<Constraint> & constraints, const vector<size_t> & updateIndice) {\n\tif (!triMesh) {\n\t\tprintf(\"ERROR::DeformRBF::Run\\n\"\n\t\t\t\"\\t\"\"!triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tfor (auto constraint : constraints) {\n\t\tif (constraint.id >= origPos.size()) {\n\t\t\tprintf(\"ERROR::DeformRBF::Run\\n\"\n\t\t\t\t\"\\t\"\"constraint.id >= origPos.size()\\n\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// compute RBF matrix\n\tauto phi = [](float r) -> float {return r*r*r; }; // basis function\n\tsize_t m = constraints.size();\n\tsize_t k = 10;\n\t\n\t// A = -       -\n\t//     | G   P |\n\t//     |       |\n\t//     |  t    |\n\t//     | P   0 |\n\t//     -       -\n\tMatrixXf A(m + k, m + k);\n\t\n\t// G : m x m\n\t// Gij = gj(ci) = basicFunc(||ci-cj||)\n\tfor (size_t i = 0; i < m; i++) {\n\t\tfor (size_t j = 0; j < m; j++) {\n\t\t\tauto ci = origPos[constraints[i].id];\n\t\t\tauto cj = origPos[constraints[j].id];\n\t\t\tfloat norm = pointf3::distance(ci, cj);\n\t\t\tA(i, j) = phi(norm);\n\t\t}\n\t}\n\n\t// P : m x k\n\t// Pij = pj(ci)\n\t// [p0, p1, ..., p9] is a basis of the space of trivariate quadratic polunomials\n\t// e[1]. [1, xx, xy, xz, yx, yy, yz, zx, zy, zz]\n\tfor (size_t i = 0; i < m; i++) {\n\t\tauto ci = origPos[constraints[i].id];\n\t\tA(m + 0, i) = A(i, m + 0) = 1.f;\n\t\tA(m + 1, i) = A(i, m + 1) = ci[0] * ci[0];\n\t\tA(m + 2, i) = A(i, m + 2) = ci[0] * ci[1];\n\t\tA(m + 3, i) = A(i, m + 3) = ci[0] * ci[2];\n\t\tA(m + 4, i) = A(i, m + 4) = ci[1] * ci[0];\n\t\tA(m + 5, i) = A(i, m + 5) = ci[1] * ci[1];\n\t\tA(m + 6, i) = A(i, m + 6) = ci[1] * ci[2];\n\t\tA(m + 7, i) = A(i, m + 7) = ci[2] * ci[0];\n\t\tA(m + 8, i) = A(i, m + 8) = ci[2] * ci[1];\n\t\tA(m + 9, i) = A(i, m + 9) = ci[2] * ci[2];\n\t}\n\n\t// 0 : k x k\n\tfor (size_t i = 0; i < k; i++) {\n\t\tfor (size_t j = 0; j < k; j++) {\n\t\t\tA(m + i, m + j) = 0.f;\n\t\t}\n\t}\n\n\tMatrixXf b(m + k, 3);\n\tfor (int i = 0; i < k; i++)\n\t\tb(m + i,0) = b(m + i, 1) = b(m + i, 2) = 0;\n\tfor (int i = 0; i < m; i++) {\n\t\tauto bi = constraints[i].pos;\n\t\tb(i, 0) = bi[0];\n\t\tb(i, 1) = bi[1];\n\t\tb(i, 2) = bi[2];\n\t}\n\n\tMatrixXf RBF = A.colPivHouseholderQr().solve(b);\n\n\t// compute target pos of vertex\n\tvector<pointf3> qVec;\n\tfor (auto id : updateIndice) {\n\t\tauto pos = origPos[id];\n\t\t// compute p\n\t\tMatrixXf p(1, m + k);\n\t\tfor (size_t i = 0; i < m; i++) {\n\t\t\tauto ci = origPos[constraints[i].id];\n\t\t\tp(i) = phi(pointf3::distance(ci, pos));\n\t\t}\n\t\tp(0, m + 0) = 1;\n\t\tp(0, m + 1) = pos[0] * pos[0];\n\t\tp(0, m + 2) = pos[0] * pos[1];\n\t\tp(0, m + 3) = pos[0] * pos[2];\n\t\tp(0, m + 4) = pos[1] * pos[0];\n\t\tp(0, m + 5) = pos[1] * pos[1];\n\t\tp(0, m + 6) = pos[1] * pos[2];\n\t\tp(0, m + 7) = pos[2] * pos[0];\n\t\tp(0, m + 8) = pos[2] * pos[1];\n\t\tp(0, m + 9) = pos[2] * pos[2];\n\n\t\t// compute q\n\t\tMatrixXf q = p * RBF;\n\t\ttriMesh->GetPositions()[id] = { q(0,0),q(0,1),q(0,2) };\n\t}\n\n\treturn true;\n}\n\nvoid DeformRBF::Restore() {\n\tif (triMesh == nullptr)\n\t\treturn;\n\n\ttriMesh->Update(origPos);\n}\n", "meta": {"hexsha": "cd1035bb4d8edcc2dc2415a4f48060c54d0b5531", "size": 3383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_stars_repo_name": "Ubpa/DGP", "max_stars_repo_head_hexsha": "5dcf6413126888fb2556bd7eddf4b899b23babed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 594.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T01:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:47:11.000Z", "max_issues_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_issues_repo_name": "xmlandroid/RenderLab", "max_issues_repo_head_hexsha": "71db49aa03de4fb258f9171691c8d570216e5e05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T07:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:04:30.000Z", "max_forks_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_forks_repo_name": "xmlandroid/RenderLab", "max_forks_repo_head_hexsha": "71db49aa03de4fb258f9171691c8d570216e5e05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T20:18:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:41:18.000Z", "avg_line_length": 23.6573426573, "max_line_length": 103, "alphanum_fraction": 0.5063553059, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.682585127019212}}
{"text": "#include <blitzml/smooth_loss/logistic_loss.h>\n#include <blitzml/base/math_util.h>\n#include <math.h>\n\nnamespace BlitzML {\n\nvalue_t LogisticLoss::compute_loss(value_t a_dot_omega, value_t label) const {\n  return log1p(exp(-label * a_dot_omega));\n}\n\n\nvalue_t LogisticLoss::compute_conjugate(value_t dual_variable, \n                                        value_t label) const {\n  if (label == 0. || dual_variable == 0.) return 0.;\n  value_t neg_ratio = -dual_variable / label;\n  return neg_ratio * log(neg_ratio) + (1 - neg_ratio) * log(1 - neg_ratio);\n}\n\n\nvalue_t LogisticLoss::compute_deriative(value_t a_dot_omega, \n                                        value_t label) const {\n  value_t exp_value = exp(label * a_dot_omega);\n  value_t prob = 1 / (1 + exp_value);\n  return -label * prob;\n}\n\n\nvalue_t LogisticLoss::compute_2nd_derivative(value_t a_dot_omega,\n                                             value_t label) const {\n  value_t exp_value = exp(label * a_dot_omega);\n  value_t prob = 1 / (1 + exp_value);\n  return label * label * prob * (1 - prob);\n}\n\n\nvalue_t LogisticLoss::lipschitz_constant() const {\n  return 0.25;\n}\n\n} // namespace BlitzML\n", "meta": {"hexsha": "f8426bb781346a986f5d17f2d24311bc21881dcb", "size": 1154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smooth_loss/logistic_loss.cpp", "max_stars_repo_name": "tbjohns/BlitzML", "max_stars_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T05:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-02T05:50:01.000Z", "max_issues_repo_path": "src/smooth_loss/logistic_loss.cpp", "max_issues_repo_name": "tbjohns/BlitzML", "max_issues_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T13:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T14:53:26.000Z", "max_forks_repo_path": "src/smooth_loss/logistic_loss.cpp", "max_forks_repo_name": "tbjohns/BlitzML", "max_forks_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T05:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T04:44:15.000Z", "avg_line_length": 28.1463414634, "max_line_length": 78, "alphanum_fraction": 0.6455805893, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6825530729166724}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n#include <map>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass WindowFuncs\n{\npublic:\n  enum class WindowTypes {\n    kHann,\n    kHannD,\n    kHamming,\n    kBlackmanHarris,\n    kGaussian\n  };\n  using WindowFuncsMap =\n      std::map<WindowTypes,\n               std::function<void(index, Eigen::Ref<Eigen::ArrayXd>)>>;\n\n  static WindowFuncsMap& map()\n  {\n    using namespace std;\n    static WindowFuncsMap _funcs = {\n        {WindowTypes::kHann,\n         [](index size, Eigen::Ref<Eigen::ArrayXd> out) {\n           for (index i = 0; i < size; i++)\n           { out(i) = 0.5 - 0.5 * cos((pi * 2 * i) / size); }\n         }},\n        {WindowTypes::kHannD,\n         [](index size, Eigen::Ref<Eigen::ArrayXd> out) {\n           double norm = pi / size;\n           for (index i = 0; i < size; i++)\n           { out(i) = norm * sin((2 * pi * i) / size); }\n         }},\n        {WindowTypes::kHamming,\n         [](index size, Eigen::Ref<Eigen::ArrayXd> out) {\n           for (index i = 0; i < size; i++)\n           { out(i) = 0.54 - 0.46 * cos((pi * 2 * i) / size); }\n         }},\n        {WindowTypes::kBlackmanHarris,\n         [](index size, Eigen::Ref<Eigen::ArrayXd> out) {\n           for (index i = 0; i < size; i++)\n           {\n             out(i) = 0.35875 - 0.48829 * cos((pi * 2 * i) / size) +\n                      0.14128 * cos((pi * 2 * i) / size) +\n                      0.01168 * cos((pi * 2 * i) / size);\n           }\n         }},\n        {WindowTypes::kGaussian,\n         [](index size, Eigen::Ref<Eigen::ArrayXd> out) {\n           double sigma = size / 3; // TODO: should be argument\n           assert(size % 2);\n           index h = (size - 1) / 2;\n           for (index i = -h; i <= h; i++)\n           { out(i + h) = exp(-i * i / (2 * sigma * sigma)); }\n         }}};\n    return _funcs;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "d11eb2cecce78f63e2ef5f305923e51751470ccb", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/WindowFuncs.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/WindowFuncs.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/WindowFuncs.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": 30.4050632911, "max_line_length": 74, "alphanum_fraction": 0.5395503747, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.682553062708704}}
{"text": "//===------------------------------------------------------------*- C++ -*-===//\n///\n/// \\brief \u7ebf\u6027\u53d8\u6362\u3002\n/// \\details \u8bbe U\u3001V \u4e3a\u6570\u57df K \u4e0a\u7684\u4e24\u4e2a\u7ebf\u6027\u7a7a\u95f4\uff0cf \u4e3a U \u5230 V \u7684\u4e00\u4e2a\u6620\u5c04\uff0c\u4e14\u6ee1\u8db3\u5982\u4e0b\u6761\u4ef6\uff1a  \n///          (i)  \u5bf9\u4efb\u610f \u03b1\uff0c\u03b2 \u2208 U \u6709 f(\u03b1+\u03b2) = f(\u03b1) + f(\u03b2)\uff1b  \n///          (ii) \u5bf9\u4efb\u610f \u03b1 \u2208 U\uff0ck \u2208 K\uff0c\u6709 f(k\u03b1) = kf(\u03b1)\u3002  \n///          \u5219\u79f0 f \u4e3a U \u5230 V \u7684\u4e00\u4e2a\u7ebf\u6027\u53d8\u6362\uff0e\n/// \\sa <https://zh.wikipedia.org/wiki/\u7ebf\u6027\u53d8\u6362>\n///\n/// \\version 2021-11-08\n/// \\since 2021-11-08\n/// \\authors zhengrr\n/// \\copyright Unlicense\n///\n//===----------------------------------------------------------------------===//\n\n#include <cmath>\n#include <execution>\n#include <numeric>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n/// \\brief \u77e9\u9635\u4e58\u6cd5\u3002\nTEST(LinearTransformation, MatrixMultiplication)\n{\n    using Scalar = float;\n    using MatrixXs = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    constexpr Eigen::Index m = 4;\n    constexpr Eigen::Index n = 1;\n    constexpr Eigen::Index p = 3;\n\n    // m \u884c n \u5217\u7684\u77e9\u9635 A\n    const Eigen::Matrix<Scalar, m, n> a = MatrixXs::Random(m, n);\n    // n \u884c p \u5217\u7684\u77e9\u9635 B\n    const Eigen::Matrix<Scalar, n, p> b = MatrixXs::Random(n, p);\n    // m \u884c p \u5217\u7684\u77e9\u9635 AB \u662f\u77e9\u9635 A \u548c\u77e9\u9635 B \u7684\u77e9\u9635\u79ef\uff08matrix product\uff09\n    const Eigen::Matrix<Scalar, m, p> ab = a * b;\n\n    //                  [B(0,0)  B(0,1)  B(0,2) ]  [B(0,j) ]\n    //                  [B(1,0)  B(1,1)  B(1,2) ]  [B(1,j) ]\n    //\n    // [A(0,0) A(0,1)]  [AB(0,0) AB(0,1) AB(0,2)]\n    // [A(1,0) A(1,1)]  [AB(1,0) AB(1,1) AB(1,2)]\n    // [A(2,0) A(2,1)]  [AB(2,0) AB(2,1) AB(2,2)]\n    // [A(3,0) A(3,1)]  [AB(3,0) AB(3,1) AB(3,2)]\n    //\n    // [A(i,0) A(i,1)]                             [AB(i,j)] = A(i,0)B(0,j) + A(i,1)B(1,j) + ... + A(i,n)B(n,j)\n\n    static const auto matrix_product_element = [&a, &b](Eigen::Index i, Eigen::Index j) -> Scalar {\n#if 1\n        return std::transform_reduce(std::execution::par_unseq, a.row(i).begin(), a.row(i).end(), b.col(j).begin(), Scalar {});\n#else\n        Scalar sum {};\n        for (Eigen::Index t = 0; t < n; ++t)\n            sum += a(i, t) * b(t, j);\n        return sum;\n#endif\n    };\n\n    for (Eigen::Index i = 0; i < m; ++i)\n        for (Eigen::Index j = 0; j < p; ++j)\n            EXPECT_EQ(ab(i, j), matrix_product_element(i, j));\n}\n\nnamespace {\n\nusing Scalar = float;\nconstexpr Eigen::Index dimension = 2;\nusing Point = Eigen::Vector<Scalar, dimension>;\nusing LinearTransformationMatrix = Eigen::Matrix<Scalar, dimension, dimension>;\n\n/// \\brief \u5706\u5468\u7387\nconst Scalar pi {std::acos(Scalar {-1})};\n\n/// \\brief \u7ed5\u539f\u70b9\u65cb\u8f6c\u3002\n/// \\param theta \u65cb\u8f6c\u89d2\uff08\u9006\u65f6\u9488\uff0c\u5f27\u5ea6\u5236\uff09\u3002\n/// \\sa [\u5750\u6807\u65cb\u8f6c\u53d8\u6362\u516c\u5f0f\u7684\u63a8\u5bfc](https://blog.csdn.net/Tangyongkang/article/details/5484636)\nLinearTransformationMatrix rotate_around_origin(Scalar theta)\n{\n    //                   [x ]\n    //                   [y ]\n    //\n    // [cos(\u03b8) -sin(\u03b8)]  [x'] = cos(\u03b8)x - sin(\u03b8)y\n    // [sin(\u03b8)  cos(\u03b8)]  [y'] = sin(\u03b8)x + cos(\u03b8)y\n\n    return LinearTransformationMatrix {\n        {std::cos(theta), -std::sin(theta)},\n        {std::sin(theta), std::cos(theta)}\n    };\n}\n\n/// \\brief \u901a\u8fc7\u8fc7\u539f\u70b9\u7684\u53cd\u5c04\u8f74\u53cd\u5c04\u3002\n/// \\param theta \u53cd\u5c04\u8f74\u4e0e x \u8f74\u6b63\u65b9\u5411\u7684\u5939\u89d2\uff08\u9006\u65f6\u9488\uff0c\u5f27\u5ea6\u5236\uff09\u3002\nLinearTransformationMatrix reflect_through_axis_that_cross_origin(Scalar theta)\n{\n    //                     [x ]\n    //                     [y ]\n    //\n    // [cos(2\u03b8)  sin(2\u03b8)]  [x'] = cos(2\u03b8)x + sin(2\u03b8)y\n    // [sin(2\u03b8) -cos(2\u03b8)]  [y'] = sin(2\u03b8)x - cos(2\u03b8)y\n\n    return LinearTransformationMatrix {\n        {std::cos(2 * theta), std::sin(2 * theta)},\n        {std::sin(2 * theta), -std::cos(2 * theta)}\n    };\n}\n\n/// \\brief \u901a\u8fc7 x \u8f74\u53cd\u5c04\u3002\nLinearTransformationMatrix reflect_through_x_axis() { return reflect_through_axis_that_cross_origin(0); }\n\n/// \\brief \u901a\u8fc7 y \u8f74\u53cd\u5c04\u3002\nLinearTransformationMatrix reflect_through_y_axis() { return reflect_through_axis_that_cross_origin(pi / 2); }\n\n/// \\breif \u7f29\u653e\u3002\n/// \\param xFactor x \u8f74\u5411\u7684\u7f29\u653e\u56e0\u5b50\u3002\n/// \\param yFactor y \u8f74\u5411\u7684\u7f29\u653e\u56e0\u5b50\u3002\nLinearTransformationMatrix scale(Scalar xFactor, Scalar yFactor)\n{\n    //        [x ]\n    //        [y ]\n    //\n    // [v 0]  [x'] = vx\n    // [0 w]  [y'] = wy\n\n    return LinearTransformationMatrix {\n        {xFactor, 0},\n        {0, yFactor}\n    };\n}\n\n/// \\brief \u6324\u538b\u3002\n/// \\details \u53d8\u6362\u524d\u540e\u9762\u79ef\u4e0d\u53d8\u3002\nLinearTransformationMatrix squeeze(Scalar factor) { return scale(factor, Scalar {1} / factor); }\n\n/// \\brief \u9519\u5207\u3002\n/// \\param xFactor x \u8f74\u5411\u7684\u9519\u5207\u56e0\u5b50\u3002\n/// \\param yFactor y \u8f74\u5411\u7684\u9519\u5207\u56e0\u5b50\u3002\nLinearTransformationMatrix shear(Scalar xFactor, Scalar yFactor)\n{\n    //        [x ]\n    //        [y ]\n    //\n    // [1 v]  [x'] = x + vy\n    // [w 1]  [y'] = wx + y\n\n    return LinearTransformationMatrix {\n        {1, xFactor},\n        {yFactor, 1}\n    };\n}\n\n/// \\brief \u6c34\u5e73\u9519\u5207\u3002\nLinearTransformationMatrix horizontal_shear(Scalar factor) { return shear(factor, 0); }\n\n/// \\brief \u5782\u76f4\u9519\u5207\u3002\nLinearTransformationMatrix vertical_shear(Scalar factor) { return shear(0, factor); }\n\n/// \\brief \u6b63\u4ea4\u6295\u5f71\u5230 x \u8f74\u3002\nLinearTransformationMatrix projection_onto_x_axis()\n{\n    //        [x ]\n    //        [y ]\n    //\n    // [0 0]  [x'] = 0\n    // [0 1]  [y'] = y\n\n    return LinearTransformationMatrix {\n        {0, 0},\n        {0, 1}\n    };\n}\n\n/// \\brief \u6b63\u4ea4\u6295\u5f71\u5230 y \u8f74\u3002\nLinearTransformationMatrix projection_onto_y_axis()\n{\n    //        [x ]\n    //        [y ]\n    //\n    // [1 0]  [x'] = x\n    // [0 0]  [y'] = 0\n\n    return LinearTransformationMatrix {\n        {0, 0},\n        {0, 1}\n    };\n}\n\n}\n\nTEST(LinearTransformation, RotateAroundOrigin)\n{\n    // \u70b9 A(x, y)\n    const Point a {1, 0};\n    // \u65cb\u8f6c\u89d2 \u03b8\n    const Scalar theta {pi / 2};\n    // \u70b9 A'(x', y')\n    const Point aPrime {0, 1};\n\n    EXPECT_TRUE((rotate_around_origin(theta) * a).isApprox(aPrime));\n}\n", "meta": {"hexsha": "81ae67e8d285e99d1d8596daf6a2be88f4c9566e", "size": 5451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rrEigen/Geometry/linear_transformation.cpp", "max_stars_repo_name": "afoolsbag/rrCnCxx", "max_stars_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T01:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:39:32.000Z", "max_issues_repo_path": "rrEigen/Geometry/linear_transformation.cpp", "max_issues_repo_name": "afoolsbag/rrCnCxx", "max_issues_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "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": "rrEigen/Geometry/linear_transformation.cpp", "max_forks_repo_name": "afoolsbag/rrCnCxx", "max_forks_repo_head_hexsha": "1e673bd4edac43d8406a0c726138cba194d17f48", "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": 26.9851485149, "max_line_length": 127, "alphanum_fraction": 0.5270592552, "num_tokens": 1989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6825530554816923}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/autodif.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\n// f: R->R\nkv::autodif<double> testfunc1(const kv::autodif<double>& x) {\n\tkv::autodif<double> tmp;\n\n\ttmp = x * x - 1.;\n\treturn cos(tmp + sin(tmp));\n}\n\n// f: R->R (use template)\ntemplate <class T> T testfunc2(const T& x) {\n\tT tmp;\n\n\ttmp = x * x - 1.;\n\treturn cos(tmp + sin(tmp));\n}\n\n// f: R^n->R\ntemplate <class T> T testfunc3(const ub::vector<T>& x) {\n\treturn atan(x(0) * x(0) + 2. * x(1) * x(1) - 1.);\n}\n\n// f: R->R^n\ntemplate <class T> ub::vector<T> testfunc4(const T& x) {\n\tub::vector<T> y(2);\n\n\ty(0) = sin(x);\n\ty(1) = cos(x);\n\n\treturn y;\n}\n\n// f: R^n->R^n\ntemplate <class T> ub::vector<T> testfunc5(const ub::vector<T>& x) {\n\tub::vector<T> y(2);\n\n\ty(0) = 2. * x(0) * x(0) * x(1) - 1.;\n\ty(1) = x(0) + 0.5 * x(1) * x(1) - 2.;\n\n\treturn y;\n}\n\n\nint main()\n{\n\tdouble d1, d2;\n\tkv::autodif<double> a1, a2, a3;\n\tub::vector<double> v1, v2;\n\tub::vector< kv::autodif<double> > va1, va2, va3, va4, va5;\n\tub::matrix<double> m;\n\tint i;\n\n\t//\n\t// f: R->R (testfunc1)\n\t//\n\n\t// helper function to initialize autodif variable with single variable\n\t// same as \" a1.v = 1.5; a1.d(0) = 1.; \"\n\ta1 = kv::autodif<double>::init(1.5);\n\n\ta2 = testfunc1(a1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" d1 = a2.v; d2 = a2.d(0); \"\n\tkv::autodif<double>::split(a2, d1, d2);\n\n\tstd::cout << \"testfunc1\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(1.5)\n\tstd::cout << d2 << \"\\n\"; // f'(1.5)\n\n\t//\n\t// f: R->R (testfunc2: use template)\n\t//\n\n\ta1 = kv::autodif<double>::init(1.5);\n\ta2 = testfunc2(a1);\n\n\tkv::autodif<double>::split(a2, d1, d2);\n\n\tstd::cout << \"testfunc2\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(1.5)\n\tstd::cout << d2 << \"\\n\"; // f'(1.5)\n\n\td1 = 1.5;\n\td2 = testfunc2(d1); // double can be also passed\n\tstd::cout << d2 << \"\\n\"; // f(1.5)\n\n\t//\n\t// f: R^n->R\n\t//\n\n\tv1.resize(2);\n\tv1(0) = 5.; v1(1) = 6.;\n\n\t// helper function to initialize autodif vector with vector variable\n\t// same as \" va1(0).v = 5.; va1(0).d(0) = 1.; va1(0).d(1) = 0,; \"\n\t//         \" va1(1).v = 6.; va1(1).d(0) = 0.; va1(1).d(1) = 1,; \"\n\tva1 = kv::autodif<double>::init(v1);\n\n\ta1 = testfunc3(va1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" y = a1.v; v2(0) = a1.d(0); v2(1) = a1.d(1) \"\n\tkv::autodif<double>::split(a1, d1, v2);\n\n\tstd::cout << \"testfunc3\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(5, 6)\n\tstd::cout << v2 << \"\\n\"; // gradient\n\n\t//\n\t// f: R->R^n\n\t//\n\n\ta1 = kv::autodif<double>::init(1.5);\n\n\tva1 = testfunc4(a1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" v1(0) = va1(0).v; v1(1) = va1(1).v; \"\n\t//         \" v2(0) = va1(0).d(0); v2(1) = va1(1).d(0); \"\n\tkv::autodif<double>::split(va1, v1, v2);\n\n\tstd::cout << \"testfunc4\\n\";\n\tstd::cout << v1 << \"\\n\"; // f(1.5)\n\tstd::cout << v2 << \"\\n\"; // f'(1.5)\n\n\t//\n\t// f: R^n->R^m\n\t//\n\n\tv1(0) = 5.; v1(1) = 6.;\n\n\tva1 = kv::autodif<double>::init(v1);\n\n\tva2 = testfunc5(va1);\n\n\t// helper function to separate autodif vector into vector value and jacobian\n\t// same as \" v2(0) = va2(0).v; m(0)(0) = va2(0).d(0); m(0)(1) = va2(0).d(1); \"\n\t//         \" v2(1) = va2(1).v; m(1)(0) = va2(1).d(0); m(1)(1) = va2(1).d(1); \"\n\tkv::autodif<double>::split(va2, v2, m);\n\n\tstd::cout << \"testfunc5\\n\";\n\tstd::cout << v2 << \"\\n\"; // f(5, 6)\n\tstd::cout << m << \"\\n\"; // Jacobian matrix\n\n\t//\n\t// operations for autodif\n\t//\n\n\tv1(0) = 0.7; v1(1) = 0.8;\n\tva1 = kv::autodif<double>::init(v1);\n\ta1 = va1(0);\n\ta2 = va1(1);\n\n\tstd::cout << \"autodif operations\\n\";\n\n\tstd::cout << a1 << \"\\n\";\n\tstd::cout << a2 << \"\\n\";\n\n\ta3 = a1 + a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 - a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 * a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 / a2; std::cout << a3 << \"\\n\";\n\ta3 = pow(a1, 3); std::cout << a3 << \"\\n\";\n\ta3 = pow(a1, a2); std::cout << a3 << \"\\n\";\n\ta2 = sqrt(a1); std::cout << a2 << \"\\n\";\n\ta2 = exp(a1); std::cout << a2 << \"\\n\";\n\ta2 = log(a1); std::cout << a2 << \"\\n\";\n\ta2 = sin(a1); std::cout << a2 << \"\\n\";\n\ta2 = cos(a1); std::cout << a2 << \"\\n\";\n\ta2 = tan(a1); std::cout << a2 << \"\\n\";\n\ta2 = sinh(a1); std::cout << a2 << \"\\n\";\n\ta2 = cosh(a1); std::cout << a2 << \"\\n\";\n\ta2 = tanh(a1); std::cout << a2 << \"\\n\";\n\ta2 = asin(a1); std::cout << a2 << \"\\n\";\n\ta2 = acos(a1); std::cout << a2 << \"\\n\";\n\ta2 = atan(a1); std::cout << a2 << \"\\n\";\n\t// asinh, acosh, atanh may not compile for autodif<double>\n\t// because c++03 does not have asinh, acosh, atanh\n\t// a2 = asinh(a1); std::cout << a2 << \"\\n\";\n\t// a2 = acosh(a1+1.); std::cout << a2 << \"\\n\";\n\t// a2 = atanh(a1); std::cout << a2 << \"\\n\";\n\n\t//\n\t// compress / expand\n\t//\n\n\tv1.resize(20);\n\tfor (i=0; i<20; i++) v1(i) = i + 2.;\n\tva1 = kv::autodif<double>::init(v1);\n\t// use only a few of the many variables\n\tva2.resize(2);\n\tva2(0) = va1(10);\n\tva2(1) = va1(11);\n\n\t// usual way\n\tstd::cout << \"usual input\\n\";\n\tstd::cout << va2 << \"\\n\";\n\tva3 = testfunc5(va2);\n\tstd::cout << \"usual output\\n\";\n\tstd::cout << va3 << \"\\n\";\n\n\t// using compress/expand to save calculation time\n\tub::matrix<double> save;\n\tva3 = kv::autodif<double>::compress(va2, save);\n\tstd::cout << \"compressed input\\n\";\n\tstd::cout << va3 << \"\\n\";\n\tva4 = testfunc5(va3);\n\tstd::cout << \"compressed output\\n\";\n\tstd::cout << va4 << \"\\n\";\n\tva5 = kv::autodif<double>::expand(va4, save);\n\tstd::cout << \"expanded output\\n\";\n\tstd::cout << va5 << \"\\n\";\n}\n", "meta": {"hexsha": "9a76939dbf5a14ed55dc71e0500e51542837a1ce", "size": 5427, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-autodif.cc", "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": "test/test-autodif.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "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": "test/test-autodif.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "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": 24.556561086, "max_line_length": 79, "alphanum_fraction": 0.5295743505, "num_tokens": 2237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6824901323986547}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <cmath>\n\nEigen::VectorXd poly(int const n, double & x){\n\tEigen::VectorXd v(n);\n\tv(0)=1;\n\tif(n>1) v(1)=x;\n\tfor (int i=2; i < n;i++){\n\t\tv(i)=2*x*v(i-1)-v(i-2);\n\t}\n\treturn v;\n}\n\nEigen::VectorXd zeroes(const int n){\n\tEigen::VectorXd v(n);\n\tfor (int i=0;i<n;i++){\n\t\tdouble temp=((2.*i-1.)/n*2)*M_PI;\n\t\tv(i)=cos(temp);\n\t}\n\treturn v;\n}\n\ntemplate <typename Function>\nvoid bestpolchebnodes (const Function&f, Eigen::VectorXd &alpha){\n\t\tsize_t n= alpha.size();\n\t\tEigen::VectorXd v;\n\t\tEigen::VectorXd fn(n+1);\n\t\tfor (int i=0; i<n+1; i++){\n\t\t\tdouble temp=cos(M_PI*(2*k+1)/2/(n+1));\n\t\t\tfn(i)=f(temp);\n\t\t}\n\t\tEigen::MatrixXd scal(n+1,n+1);\n\t\tfor (int j=0; j<n+1; j++) {\n\t\t\tv=poly(n,cos(M_PI*(2*j+1)/2/(n+1)));\n\t\t\tfor (int k=0; k<n+1; k++) scal(j,k)=V[k];\n\t\t}\n\t\tfor (int l=0;l<n;l++){\n\t\t\talpha(l)=0;\n\t\t\tfor (int k=0;k<n;k++){\n\t\t\t\talpha(l)+=2*(1./(n+1))*fn(k)*v(k);\n\t\t\t}\n\t\t}\n\t\talpha(0)=alpha(0)/2;\n\n}\nusing namespace std;\nint main(){\n    auto f = [] (double & x) {return 1/(pow(5*x,2)+1);};\n    int n=20;\n    Eigen::VectorXd alpha(n+1);\n    bestpolchebnodes(f, alpha);\n    \n    //Compute the error\n    Eigen::VectorXd X = Eigen::VectorXd::LinSpaced(1e6,-1,1);\n    auto qn = [&alpha,&n] (double & x) {\n        double temp;\n        vector<double> V=poly(n,x);\n        for (int k=0; k<n+1; k++) temp+=alpha(k)*V[k];\n        return temp;\n    };\n    double err_max=abs(f(X(0))-qn(X(0)));\n    for (int i=1; i<1e6; i++) err_max=std::max(err_max,abs(f(X(i))-qn(X(i))));\n    cout<<\"Error: \"<< err_max <<endl;\n}\n", "meta": {"hexsha": "ce18a496ef93627f59b60f7b536cd1ae6a783615", "size": 1537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS9/chebychev.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/chebychev.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/chebychev.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": 23.2878787879, "max_line_length": 78, "alphanum_fraction": 0.5439167209, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308184368928, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6823926073759169}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/inverse_gamma.hpp>\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/normal.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\n\ntemplate<typename T>\nclass IW : public Distribution<T>\n{\npublic:\n  Matrix<T,Dynamic,Dynamic> Delta_;\n  T nu_;\n  uint32_t D_;\n\n  IW(const Matrix<T,Dynamic,Dynamic>& Delta, T nu, boost::mt19937 *pRndGen);\n  IW(const Matrix<T,Dynamic,Dynamic>& Delta, T nu, const Matrix<T,Dynamic,Dynamic>& scatter, \n\t const Matrix<T,Dynamic,1>& mean, T counts, boost::mt19937 *pRndGen);\n  IW(const IW& iw);\n  ~IW();\n\n  IW<T>* copy();\n\n  IW<T> posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z,\n      uint32_t k, uint32_t zDivider=1);\n  IW<T> posterior(const Matrix<T,Dynamic,Dynamic>& outer, T count) const;\n  IW<T> posterior() const ;\n  void resetSufficientStatistics();\n\n  Matrix<T,Dynamic,Dynamic> sample();\n//  Normal<T> sample();\n  T logPdf(const Matrix<T,Dynamic,Dynamic>& Sigma) const;\n  T logPdf(const Normal<T>& normal) const;\n  T logLikelihoodMarginalized() const; // log pdf of SS under NIW prior\n  T logLikelihoodMarginalized(const Matrix<T,Dynamic,Dynamic>& Scatter, \n    T count) const;\n\n  Matrix<T,Dynamic,Dynamic> mode() const;\n\n  const Matrix<T,Dynamic,Dynamic>& scatter() const {return scatter_;};\n  Matrix<T,Dynamic,Dynamic>& scatter() {return scatter_;};\n  const Matrix<T,Dynamic,1>& mean() const {return mean_;};\n  Matrix<T,Dynamic,1>& mean() {return mean_;};\n  T count() const {return count_;};\n  T& count() {return count_;};\n\nprivate:\n  boost::random::normal_distribution<> gauss_;\n\n  // sufficient statistics\n  Matrix<T,Dynamic,Dynamic> scatter_;\n  Matrix<T,Dynamic,1> mean_;\n  T count_;\n};\n\ntypedef IW<double> IWd;\ntypedef IW<float> IWf;\n\n/* prior for spherical covariances (i.e. \\Sigma = \\sigma^2 I) */\ntemplate<typename T>\nclass IW_spherical : public Distribution<T>\n{\npublic:\n  T delta_;\n  T nu_;\n  uint32_t D_;\n\n  IW_spherical(T delta, T nu, uint32_t D, boost::mt19937 *pRndGen);\n  IW_spherical(const IW_spherical& iw);\n  ~IW_spherical();\n\n  IW_spherical<T>* copy();\n\n  IW_spherical<T> posterior(const Matrix<T,Dynamic,Dynamic>& x, \n      const VectorXu& z, uint32_t k, uint32_t zDivider=1);\n//  T sample();\n//  T logPdf(T sigma);\n////  T logPdf(const Normal& normal);\n\nprivate:\n  boost::random::normal_distribution<> gauss_;\n};\n\n// ----------------------------------------------------------------------------\n", "meta": {"hexsha": "b83a487ba789e3a4228f72373702eaea971b29ea", "size": 2805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/iw.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/iw.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "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/dpMM/iw.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 28.3333333333, "max_line_length": 120, "alphanum_fraction": 0.6802139037, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.682339985445466}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * 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 *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n#pragma once\n\n#include <Eigen/SVD>\n\nnamespace kindr {\n\n\n/*!\n * \\brief Gets a skew-symmetric matrix from a (column) vector\n * \\param   vec 3x1-matrix (column vector)\n * \\return skew   3x3-matrix\n */\ntemplate<typename PrimType_>\ninline static Eigen::Matrix<PrimType_, 3, 3> getSkewMatrixFromVector(const Eigen::Matrix<PrimType_, 3, 1>& vec) {\n  Eigen::Matrix<PrimType_, 3, 3> mat;\n  mat << 0, -vec(2), vec(1), vec(2), 0, -vec(0), -vec(1), vec(0), 0;\n  return mat;\n}\n\n/*!\n * \\brief Gets a 3x1 vector from a skew-symmetric matrix\n * \\param   matrix 3x3-matrix\n * \\return  column vector (3x1-matrix)\n */\ntemplate<typename PrimType_>\ninline static Eigen::Matrix<PrimType_, 3, 1> getVectorFromSkewMatrix(const Eigen::Matrix<PrimType_, 3, 3>& matrix) {\n  return Eigen::Matrix<PrimType_, 3, 1> (matrix(2,1), matrix(0,2), matrix(1,0));\n}\n\n/*!\n * \\brief Computes the Moore\u2013Penrose pseudoinverse\n * info: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257\n * \\param a: Matrix to invert\n * \\param result: Result is written here\n * \\param epsilon: Numerical precision (for example 1e-6)\n * \\return true if successful\n */\ntemplate<typename _Matrix_TypeA_, typename _Matrix_TypeB_>\nbool static pseudoInverse(const _Matrix_TypeA_ &a, _Matrix_TypeB_ &result,\n                          double epsilon = std::numeric_limits<typename _Matrix_TypeA_::Scalar>::epsilon())\n{\n  // Shorthands\n  constexpr auto rowsA = static_cast<int>(_Matrix_TypeA_::RowsAtCompileTime);\n  constexpr auto colsA = static_cast<int>(_Matrix_TypeA_::ColsAtCompileTime);\n  constexpr auto rowsB = static_cast<int>(_Matrix_TypeB_::RowsAtCompileTime);\n  constexpr auto colsB = static_cast<int>(_Matrix_TypeB_::ColsAtCompileTime);\n\n  // Assert wrong matrix types\n  static_assert(std::is_same<typename _Matrix_TypeA_::Scalar, typename _Matrix_TypeB_::Scalar>::value,\n                \"[kindr::pseudoInverse] Matrices must be of the same Scalar type!\");\n  static_assert(rowsA == colsB && colsA == rowsB, \"[kindr::pseudoInverse] Result type has wrong size!\");\n\n  // If one dimension is dynamic, compute everything as dynamic size\n  constexpr auto m = Eigen::JacobiSVD< _Matrix_TypeA_ >::DiagSizeAtCompileTime;\n\n  // JacobiSVD needs to be computed on dynamic size if we need ComputeThinU, ComputeThinV, see:\n  // https://eigen.tuxfamily.org/dox/classEigen_1_1JacobiSVD.html\n  Eigen::JacobiSVD< Eigen::Matrix<typename _Matrix_TypeA_::Scalar, Eigen::Dynamic, Eigen::Dynamic> > svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  typename _Matrix_TypeA_::Scalar tolerance =\n    epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs().maxCoeff();\n\n  // Sigma for ThinU and ThinV\n  Eigen::Matrix<typename _Matrix_TypeA_::Scalar, m, m> sigmaThin = Eigen::Matrix<typename _Matrix_TypeA_::Scalar, m, 1>(\n    (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0)).asDiagonal();\n\n  result = svd.matrixV() * sigmaThin * svd.matrixU().transpose();\n\n  return true;\n}\n\n\n} // end namespace kindr\n", "meta": {"hexsha": "336840d06ad4ea9a07660ca7a83c11573e7f00aa", "size": 4680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_stars_repo_name": "mcx/kindr", "max_stars_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 289.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T15:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:52:43.000Z", "max_issues_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_issues_repo_name": "mcx/kindr", "max_issues_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T10:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T13:24:52.000Z", "max_forks_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_forks_repo_name": "mcx/kindr", "max_forks_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2018-08-24T08:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T15:17:37.000Z", "avg_line_length": 46.3366336634, "max_line_length": 151, "alphanum_fraction": 0.7333333333, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6823399643757079}}
{"text": "/*\n * Using Sundaram' sieve, print the first 2,000,000 numbers\n * darkturo 2014\n */\n#include <iostream>\n#include <fstream>\n#include <bitset>\n#include <ctime>\n#include <limits>\n#include <boost/spirit/include/karma.hpp>\n\n#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC\n#define MAX 32452843\n#define MAXPRIMES 2000000\n#define BUFFER_SIZE 8l * MAX\n\nclass SundaramSieve\n{\n   std::bitset<MAX> N;\n   std::ofstream output;\n   int counter; \n   char * buffer;\n   char * p_input;\n\n   public:\n   SundaramSieve() : \n           output(\"primesEveryWhere.txt\", std::ios::out | std::ios::trunc),\n           counter(0)\n   {\n      buffer = new char[BUFFER_SIZE];\n      p_input = buffer;\n      N.set();\n   }\n\n   ~SundaramSieve()\n   {\n      if (p_input != buffer)\n         output.write(buffer, p_input - buffer);  // flush\n      output.close();\n   }\n\n   void sieve()\n   {\n      // Given i,j \u2208 \u2115, 1 \u2264 i \u2264 j\n      // Sieve all the x \u2208 \u2115, x = i + j + 2ij \u2264 MAX\n      for (long i = 1; (2*i + 2*(i^2)) <= 2*sqrt(MAX); i++)\n      {\n         for (long j = i; (i + j + 2*i*j) <= (MAX - 2)/2; j++)\n         {\n            N.set((i + j + 2*i*j) - 1, false);\n         }\n      }\n\n      // Generate the primes from the sieved list.\n      print( 2 );\n      for (int i = 1; counter < MAXPRIMES; i++)\n      {\n         if (N[i-1]) \n         {\n            print( 2*i + 1 );\n         }\n      }\n   }\n\n   int printedPrimes()\n   {\n      return counter;\n   }\n\n   private:\n   inline void print(int number)\n   {\n      doPrint(number);\n      counter ++;\n   }\n\n   inline void doPrint(int number)\n   {\n      boost::spirit::karma::generate(p_input, boost::spirit::int_, number);\n      *p_input++ = '\\n';\n   }\n};\n\nint main(int argc, char ** argv)\n{\n   clock_t t1, t2;\n\n   t1 = std::clock();\n\n   SundaramSieve siever;\n   siever.sieve();\n\n   t2 = std::clock();\n\n   // Summary\n   std::cout.precision(std::numeric_limits<double>::digits10);\n   std::cerr << \"Used \" << std::fixed << TIMEDIFF(t1, t2)\n             << \" msecs to calculate \" << siever.printedPrimes()\n             << \" primes.\" << std::endl;\n}\n", "meta": {"hexsha": "370465eae636c81d89a851c6fc09e72df8914830", "size": 2071, "ext": "cc", "lang": "C++", "max_stars_repo_path": "c++/sundaram.cc", "max_stars_repo_name": "darkturo/primo", "max_stars_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-07T16:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-07T16:35:32.000Z", "max_issues_repo_path": "c++/sundaram.cc", "max_issues_repo_name": "darkturo/primo", "max_issues_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_issues_repo_licenses": ["MIT"], "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++/sundaram.cc", "max_forks_repo_name": "darkturo/primo", "max_forks_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_forks_repo_licenses": ["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.504950495, "max_line_length": 75, "alphanum_fraction": 0.5287300821, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6823315145704235}}
{"text": "#pragma once\n\n#include \"modprop/compo/Interfaces.h\"\n#include \"modprop/compo/Parametric.hpp\"\n#include <Eigen/Dense>\n\nnamespace percepto\n{\n\n// TODO Support matrix inputs?\n/*! \\brief A simple linear regression class. Outputs Weights matrix * input. \n * The matrix and input are dynamically-sized. Assumes row-major ordering\n * for vectorizing the weights matrix. */\nclass LinearRegressor\n: public Source<VectorType>\n{\npublic:\n\t\n\ttypedef VectorType InputType;\n\ttypedef VectorType OutputType;\n\ttypedef Source<VectorType> SourceType;\n\n\tLinearRegressor( unsigned int inputDim, unsigned int outputDim )\n\t: _inputDim( inputDim ), _outputDim( outputDim ), _W( nullptr, 0, 0 ),\n\t_inputPort( this ) {}\n\n\tLinearRegressor( const LinearRegressor& other )\n\t: _inputDim( other._inputDim ), _outputDim( other._outputDim ),\n\t_params( other._params ), _W( other._W ), _inputPort( this ) {}\n\n\tvoid SetSource( SourceType* b ) { b->RegisterConsumer( &_inputPort ); }\n\n\tunsigned int InputDim() const { return _inputDim; }\n\tunsigned int OutputDim() const { return _outputDim; }\n\n\tParameters::Ptr CreateParameters()\n\t{\n\t\tParameters::Ptr params = std::make_shared<Parameters>();\n\t\tparams->Initialize( (_inputDim + 1) * _outputDim );\n\t\tSetParameters( params );\n\t\treturn params;\n\t}\n\n\tvoid SetParameters( Parameters::Ptr params )\n\t{\n\t\tif( params->ParamDim() != (_inputDim+1) * _outputDim )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Invalid parameter dimension.\" );\n\t\t}\n\t\t_params = params;\n\t\tnew (&_W) Eigen::Map<const RowMatrixType>( params->GetParamsVec().data(),\n\t\t                                        _outputDim, _inputDim + 1 );\n\t}\n\n\tvoid SetOffsets( const VectorType& off )\n\t{\n\t\tRowMatrixType p( _W );\n\t\tif( off.size() != p.rows() )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Offsets invalid dimension.\" );\n\t\t}\n\t\tp.col( p.cols() - 1 ) = off;\n\t\tEigen::Map<VectorType> v( p.data(), p.size(), 1 );\n\t\t_params->SetParamsVec( v );\n\t\tnew (&_W) Eigen::Map<const RowMatrixType>( _params->GetParamsVec().data(),\n\t\t                                              _outputDim, _inputDim + 1 );\n\t}\n\n\tvirtual void Foreprop()\n\t{\n\t\tVectorType out = _W * _inputPort.GetInput().homogeneous();\n\t\tSourceType::SetOutput( out );\n\t\tSourceType::Foreprop();\n\t}\n\t\n\tvirtual void BackpropImplementation( const MatrixType& nextDodx )\n\t{\n\t\tMatrixType nDodx;\n\t\tif( nextDodx.size() == 0 )\n\t\t{\n\t\t\tnDodx = MatrixType::Identity( OutputDim(), OutputDim() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnDodx = nextDodx;\n\t\t}\n\n\t\tif( nDodx.cols() != OutputDim() )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Backprop dim error!\" );\n\t\t}\n\n\t\tconst VectorType& input = _inputPort.GetInput();\n\t\tMatrixType thisDodw = MatrixType::Zero( nDodx.rows(), ParamDim() );\n\t\tfor( unsigned int i = 0; i < nDodx.rows(); i++ )\n\t\t{\n\t\t\tfor( unsigned int j = 0; j < OutputDim(); j++ )\n\t\t\t{\n\t\t\t\tthisDodw.block(i, j*(InputDim()+1), 1, InputDim()+1) =\n\t\t\t\t\tnDodx(i,j) * input.homogeneous().transpose();\n\t\t\t}\n\t\t}\n\t\tMatrixType thisDodx = nDodx * _W;\n\n\t\tif( !SourceType::modName.empty() )\n\t\t{\n\t\t\tstd::cout << SourceType::modName << \" dodx: \" << nDodx << std::endl << \"dodw: \" << thisDodw << std::endl;\n\t\t\tstd::cout << \"acc dodw: \" << _params->GetDerivs() << std::endl;\n\t\t\tstd::cout << \"input: \" << input.transpose() << std::endl;\n\t\t\tstd::cout << \"param dim: \" << ParamDim() << std::endl;\n\t\t}\n\n\t\t_params->AccumulateDerivs( thisDodw );\n\t\t_inputPort.Backprop( thisDodx );\n\t}\n\n\tvirtual unsigned int ParamDim() const { return _W.size(); }\n\n\tconst Eigen::Map<const RowMatrixType>& GetWeights() const { return _W; }\n\nprivate:\n\n\tfriend std::ostream& operator<<( std::ostream& os, const LinearRegressor& lreg );\n\t\n\tunsigned int _inputDim;\n\tunsigned int _outputDim;\n\tParameters::Ptr _params;\n\tEigen::Map<const RowMatrixType> _W; // The weight vector\n\tSink<VectorType> _inputPort;\n\t\n};\n\ninline\nstd::ostream& operator<<( std::ostream& os, const LinearRegressor& lreg )\n{\n\tos << lreg._W;\n\treturn os;\n}\n\n}", "meta": {"hexsha": "0cb14f0cc8ca402f43acc519aeb552c621854fb5", "size": 3898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/compo/LinearRegressor.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/compo/LinearRegressor.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.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/modprop/compo/LinearRegressor.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.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.8428571429, "max_line_length": 108, "alphanum_fraction": 0.6570035916, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6823102107592398}}
{"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2019 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[buffer_geographic_point_circle\n//` Shows how the point_circle strategy, for the Earth, can be used as a PointStrategy to create circular buffers around points\n\n#include <boost/geometry.hpp>\n#include <iostream>\n\nint main()\n{\n    namespace bg = boost::geometry;\n\n    typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point;\n\n    // Declare the geographic_point_circle strategy (with 36 points)\n    // Default template arguments (taking Andoyer strategy)\n    bg::strategy::buffer::geographic_point_circle<> point_strategy(36);\n\n    // Declare the distance strategy (one kilometer, around the point, on Earth)\n    bg::strategy::buffer::distance_symmetric<double> distance_strategy(1000.0);\n\n    // Declare other necessary strategies, unused for point\n    bg::strategy::buffer::join_round join_strategy;\n    bg::strategy::buffer::end_round end_strategy;\n    bg::strategy::buffer::side_straight side_strategy;\n\n    // Declare/fill a point on Earth, near Amsterdam\n    point p;\n    bg::read_wkt(\"POINT(4.9 52.1)\", p);\n\n    // Create the buffer of a point on the Earth\n    bg::model::multi_polygon<bg::model::polygon<point> > result;\n    bg::buffer(p, result,\n                distance_strategy, side_strategy,\n                join_strategy, end_strategy, point_strategy);\n\n    std::cout << \"Area: \" << bg::area(result) / (1000 * 1000) << \" square kilometer\" << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[buffer_geographic_point_circle_output\n/*`\nOutput:\n[pre\nArea: 3.12542 square kilometer\n]\n*/\n//]\n", "meta": {"hexsha": "4a160070e66d16912449ec78d065cff056db2a33", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/strategies/buffer_geographic_point_circle.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/strategies/buffer_geographic_point_circle.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/strategies/buffer_geographic_point_circle.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 30.5423728814, "max_line_length": 127, "alphanum_fraction": 0.704772475, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6822507808944722}}
{"text": "/**\n * @copyright   Copyright (c) 2021, Swift Engineering Inc.\n * @license     Licensed under the MIT license. See LICENSE for details.\n */\n#include <gtest/gtest.h>\n\n#include <string>\n#include <sstream>\n#include <boost/array.hpp>\n#include <stdio.h>\n#include <ignition/math/Pose3.hh>\n#include <ignition/math/Vector3.hh>\n\n#include \"Math_util.hpp\"\n\nconst unsigned int EQUALS = 1;\nconst unsigned int LESS_THAN = 2;\nconst unsigned int GREATER_THAN = 3;\nconst unsigned int LESS_THAN_EQ = 4;\nconst unsigned int GREATER_THAN_EQ = 5;\n\nclass MathUtilTest : public ::testing::Test {\n  protected:\n    avionics_sim::Math_util mathUtil;\n    double tolerance = 0.00001;\n};\n\nTEST_F(MathUtilTest, TestCalculateMean) {\n    // Given: Range of Values\n    std::vector<double> samples = {2.0, -10, 99, -100000};\n    double expectedMean = -24977.25;\n\n    // When: Dynamic Pressure is Calculated\n    double resultantMean = mathUtil.calculate_mean(samples.begin(), samples.end(),\n                           samples.size());\n\n    // Then: Dynamic Pressure should match expected\n    ASSERT_NEAR(resultantMean, expectedMean, tolerance);\n}\n\nTEST_F(MathUtilTest, TestCalculateRMS) {\n    // Given: Range of Values\n    std::vector<double> samples = {2.0, -10, 99, -100000};\n    double expectedRMS = 50000.02476;\n\n    // When: Dynamic Pressure is Calculated\n    double resultantRMS = mathUtil.calculate_rms(samples.begin(), samples.end(),\n                          samples.size());\n\n    // Then: Dynamic Pressure should match expected\n    ASSERT_NEAR(resultantRMS, expectedRMS, tolerance);\n}\n\n// TEST_F(MathUtilTest, TestCalculateFPComparison) {\n//   // Given: Planar Velocity and Air Density\n//   double lhs;\n//   double rhs;\n//   unsigned int operation;\n//   bool testValue;\n\n//   MathUtilFPComparisonParams param = GetParam();\n//   lhs = param.lhs;\n//   rhs = param.rhs;\n//   operation = param.operation;\n//   testValue = param.testValue;\n\n//   avionics_sim::Math_util mu;\n//   double result;\n\n//   switch (operation) {\n//   case EQUALS:\n//     result = mu.rough_eq(lhs, rhs);\n//     break;\n\n//   case LESS_THAN:\n//     result = mu.rough_lt(lhs, rhs);\n//     break;\n\n//   case LESS_THAN_EQ:\n//     result = mu.rough_lte(lhs, rhs);\n//     break;\n\n//   case GREATER_THAN:\n//     result = mu.rough_gt(lhs, rhs);\n//     break;\n\n//   case GREATER_THAN_EQ:\n//     result = mu.rough_gte(lhs, rhs);\n//     break;\n//   }\n\n//   ASSERT_EQ(result, testValue);\n// }\n\nTEST_F(MathUtilTest, TestLinearMap) {\n    // Given:\n    double x = 4.651;\n    double in_min = 4.0;\n    double in_max = 5.0;\n    double out_min = 0.44;\n    double out_max = 0.55;\n    double expectedValue = 0.511614;\n\n\n    // When:\n    double result = mathUtil.linear_map(x, in_min, in_max, out_min, out_max);\n\n    // Then:\n    ASSERT_NEAR(result, expectedValue, tolerance);\n}\n\n// TODO(Mike Lyons): Figure out why this has a hold up in the test\n// TEST_F(MathUtilTest, TestPowInteger) {\n//   // Given:\n//   double base = 5;\n//   size_t power = -2;\n//   double expectedValue = 0.04;\n\n//   // When:\n//   double result = mathUtil.pow_integer(base, power);\n\n//   // Then\n//   ASSERT_NEAR(result, expectedValue, tolerance);\n// }\n", "meta": {"hexsha": "c2b5dca1be269126a37b9c9d9bd2e19a021cb255", "size": 3146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/MathUtilTest.cpp", "max_stars_repo_name": "SwiftEngineering/avionics_sim", "max_stars_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/MathUtilTest.cpp", "max_issues_repo_name": "SwiftEngineering/avionics_sim", "max_issues_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/MathUtilTest.cpp", "max_forks_repo_name": "SwiftEngineering/avionics_sim", "max_forks_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_forks_repo_licenses": ["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.168, "max_line_length": 82, "alphanum_fraction": 0.6506675143, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6822507674086216}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n#define EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n\n#include <boost/random/uniform_real_distribution.hpp>\n// boost::math::uniform is not used as it is linked to real values rather than discrete integral values\n\nnamespace rjmcmc {\n\n    // 1_(n\\in[a,b])/(b-a+1)\n    class even_numbered_order_statistics_uniform_distribution {\n    public:\n        typedef double real_type;\n        typedef int    int_type;\n        typedef boost::random::uniform_real_distribution<real_type> rand_distribution_type;\n\n        even_numbered_order_statistics_uniform_distribution(int_type k , real_type a, real_type b)\n            : m_rand(a,b)\n            , m_size(k) {}\n\n        // new/old\n        template<typename Iterator> real_type pdf_ratio(Iterator begin0, Iterator end0, Iterator begin1, Iterator end1) const\n        {\n            return pdf(begin1,end1)/pdf(begin0,end0);\n        }\n\n        template<typename Iterator> real_type pdf(Iterator begin, Iterator end) const\n        {\n            typedef typename std::iterator_traits<Iterator>::value_type T;\n            const T a = m_rand.min();\n            const T b = m_rand.max();\n            const T s = b - a;\n            T x = a;\n            T res(1);\n            int i = 2;\n            for(Iterator it=begin; it != end; ++it, i+=2)\n            {\n                const T y = *it;\n                if(y<x) return 0;\n                res*=(y-x)*i*(i+1)/(s*s);\n                x=y;\n            }\n            if(b<x) return 0;\n            res *= (b - x) / s;\n            return res;\n        }\n\n        template<typename Engine, typename Iterator>\n        inline void operator()(Engine& e, Iterator out) const {\n            std::vector<real_type> v(2*m_size+1);\n            for(std::vector<real_type>::iterator it = v.begin(); it!=v.end(); ++it)\n                *it = m_rand(e);\n            std::sort(v.begin(),v.end());\n            for(std::vector<real_type>::iterator it = ++v.begin(); it!=v.end(); it+=2)\n                *out++ = *it;\n        }\n\n    private:\n        mutable rand_distribution_type m_rand;\n        int_type m_size;\n    };\n\n}; // namespace rjmcmc\n\n#endif // EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n", "meta": {"hexsha": "c50958037098cf1d33f32ff7006be1d66bee394f", "size": 4043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/distribution/even_numbered_order_statistics_uniform_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/even_numbered_order_statistics_uniform_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/even_numbered_order_statistics_uniform_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": 40.0297029703, "max_line_length": 125, "alphanum_fraction": 0.652733119, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.682226805953445}}
{"text": "#ifndef FVMSCALAR1D_RECONSTRUCTION_HPP\n#define FVMSCALAR1D_RECONSTRUCTION_HPP\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <memory>\n\n#include <ancse/grid.hpp>\n#include <ancse/model.hpp>\n#include <ancse/rate_of_change.hpp>\n#include <ancse/simulation_time.hpp>\n\ninline double sign(double a) { return copysign(1.0, a); }\n\n//// ANCSE_CUT_START_TEMPLATE\n//----------------SlopeLimiterABegin----------------\ninline double minmod(double a, double b) {\n    return 0.5 * (sign(a) + sign(b)) * std::min(std::abs(a), std::abs(b));\n}\n\ninline double maxmod(double a, double b) {\n    return 0.5 * (sign(a) + sign(b)) * std::max(std::abs(a), std::abs(b));\n}\n\ninline double minmod(double a, double b, double c) {\n    return minmod(a, minmod(b, c));\n}\n\ninline double minabs(double a, double b) {\n    double tolerance = 1e-10;\n    if (std::abs( std::abs(a) - std::abs(b) ) < tolerance)\n        return 0.5*(a+b);\n    return std::abs(a) < std::abs(b) ? a : b;\n}\n//----------------SlopeLimiterAEnd----------------\n\n//----------------SlopeLimiterBBegin----------------\nstruct MinMod {\n    inline double operator()(double sL, double sR) const {\n        return minmod(sL, sR);\n    }\n};\n//----------------SlopeLimiterBEnd----------------\n\n//----------------SlopeLimiterCBegin----------------\nstruct MinAbs {\n    inline double operator()(double sL, double sR) const {\n        return minabs(sL, sR);\n    }\n};\n\nstruct SuperBee {\n    inline double operator()(double sL, double sR) const {\n        double A = minmod(2.0 * sL, sR);\n        double B = minmod(sL, 2.0 * sR);\n\n        return maxmod(A, B);\n    }\n};\n\nstruct VanLeer {\n    inline double operator()(double sL, double sR) const {\n        double r = sL / (sR + eps);\n        return (r + std::abs(r)) / (1 + std::abs(r)) * sR;\n    }\n\n  private:\n    double eps = 1e-10;\n};\n\nstruct MonotonizedCentral {\n    inline double operator()(double sL, double sR) const {\n        return minmod(2.0 * sL, 0.5 * (sL + sR), 2.0 * sR);\n    }\n};\n\nstruct Unlimited {\n    inline double operator()(double a, double b) const { return 0.5 * (a + b); }\n};\n//----------------SlopeLimiterCEnd----------------\n//// ANCSE_END_TEMPLATE\n\nclass PWConstantReconstruction {\n  public:\n    /// Compute the left and right trace at the interface i + 1/2.\n    /** Note: This API is agnostic to the number of cell-averages required\n     *        by the method. Therefore, reconstructions with different stencil\n     *        sizes can implement this API; and this call can be used in parts\n     *        of the code that do not need to know about the details of the\n     *        reconstruction.\n     */\n    inline std::pair<double, double> operator()(const Eigen::VectorXd &u,\n                                                int i) const {\n        return (*this)(u[i], u[i + 1]);\n    }\n\n    /// Compute the left and right trace at the interface.\n    /** Piecewise constant reconstruction of the left and right trace only\n     *  requires the cell-average to the left and right of the interface.\n     *\n     *  Note: Compared to the other overload this reduces the assumption on\n     *        how the cell-averages are stored. This is useful when testing and\n     *        generally makes the function useful in more situations.\n     */\n    inline std::pair<double, double> operator()(double ua, double ub) const {\n        return {ua, ub};\n    }\n};\n\n//// ANCSE_CUT_START_TEMPLATE\n//----------------LinearRCBegin----------------\ntemplate <class SlopeLimiter>\nclass PWLinearReconstruction {\n  public:\n    explicit PWLinearReconstruction(const SlopeLimiter &slope_limiter)\n        : slope_limiter(slope_limiter) {}\n\n    std::pair<double, double> operator()(const Eigen::VectorXd &u,\n                                         int i) const {\n        return (*this)(u[i - 1], u[i], u[i + 1], u[i + 2]);\n    }\n\n    std::pair<double, double>\n    operator()(double ua, double ub, double uc, double ud) const {\n        double sL = ub - ua;\n        double sM = uc - ub;\n        double sR = ud - uc;\n\n        double uL = ub + 0.5 * slope_limiter(sL, sM);\n        double uR = uc - 0.5 * slope_limiter(sM, sR);\n\n        return {uL, uR};\n    }\n\n  private:\n    SlopeLimiter slope_limiter;\n};\n//----------------LinearRCEnd----------------\n//// ANCSE_END_TEMPLATE\n\n#endif // FVMSCALAR1D_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "49d5eb7246308ed547a71d5ed24a4e431121bdc3", "size": 4280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.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": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.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": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.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": 30.1408450704, "max_line_length": 80, "alphanum_fraction": 0.5820093458, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.682226796450036}}
{"text": "#include<iostream>\n#include<fstream>\n#include<string>\n#include<algorithm>\n#include<list>\n#include<stdexcept>\n#include<functional>\n\n#include <boost/program_options.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <Interp.hpp>\n\n#include \"Integrate.hpp\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n\nvoid print_version()\n{\n  cout<<\"integrate-cli - linked against libIntegrate version \"<< libIntegrate_VERSION_FULL << endl;\n}\n\nvoid print_usage(char prog_name[])\n{\n\n  cout<<\"usage: \"<<prog_name<<\" [OPTIONS]\"<<\"\\n\";\n  \n}\n\nvoid print_documentation( )\n{\n  cout<<\"Reads function from a file an integrates it.\"\n      <<\"\\n\"\n      <<\"The data is contained in a gnuplot-style text file, with each x-y pair on a new line, separated by white space.\"\n      <<\"\\n\";\n}\n\nstd::function<double(std::vector<double>&,std::vector<double>&)> create(std::string type)\n{\n  if( boost::starts_with(\"riemann\",type) )\n    return _1D::RiemannRule<double>();\n\n  if( boost::starts_with(\"trapezoid\",type) )\n    return _1D::TrapezoidRule<double>();\n\n  if( boost::starts_with(\"simpson\",type) )\n    return [](std::vector<double>& x, std::vector<double>& y){\n      // create an interpolator to pass to the integrator\n      _1D::CubicSplineInterpolator<double> interp(x,y);\n\n      double min = *std::min_element( x.begin(), x.end() );\n      double max = *std::max_element( x.begin(), x.end() );\n\n      _1D::SimpsonRule<double> integ;\n\n      return integ( interp, min, max, x.size() );\n    };\n\n  if( boost::starts_with(\"gauss-legendre\",type) )\n    return [](std::vector<double>& x, std::vector<double>& y){\n      // create an interpolator to pass to the integrator\n      _1D::CubicSplineInterpolator<double> interp(x,y);\n\n      double min = *std::min_element( x.begin(), x.end() );\n      double max = *std::max_element( x.begin(), x.end() );\n\n      // we have quadratures of order\n      // 8, 16, 32, and 64.\n      if( x.size() <= 8 )\n      {\n        _1D::GQ::GaussLegendreQuadrature<double,8> integ;\n        return integ( interp, min, max );\n      }\n      if( x.size() <= 16 )\n      {\n        _1D::GQ::GaussLegendreQuadrature<double,16> integ;\n        return integ( interp, min, max );\n      }\n      if( x.size() <= 32 )\n      {\n        _1D::GQ::GaussLegendreQuadrature<double,32> integ;\n        return integ( interp, min, max );\n      }\n\n      _1D::GQ::GaussLegendreQuadrature<double,64> integ;\n      return integ( interp, min, max );\n    };\n\n  return nullptr;\n}\n\nvoid ReadFunction(std::istream &_in, double *&_x, double *&_y, int &_n, int _dimensions = 1, int _multiplicity = 1);\n\n\nint main( int argc, char* argv[])\n{\n    po::options_description options(\"Allowed options\");\n    options.add_options()\n      (\"help,h\"      , \"print help message\")\n      (\"batch,b\"     , \"output in 'batch' mode\")\n      (\"method,m\"    , po::value<string>()->default_value(\"riemann\"),     \"integration method.\")\n      (\"list,l\"      ,                                                   \"list available integration methods.\")\n      (\"integrate-data\" ,                                                \"file containing data to be integrated.\")\n      ;\n\n    po::positional_options_description args;\n    args.add(\"integrate-data\", 1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(options).positional(args).run(), vm);\n    po::notify(vm);\n\n\n    if (argc == 1 || vm.count(\"help\"))\n    {\n      print_version();\n      print_usage( argv[0] );\n      cout<<\"\\n\";\n      cout << options<< \"\\n\";\n      cout<<\"\\n\";\n      print_documentation();\n      cout<<\"\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"list\"))\n    {\n      print_version();\n      cout<<\"\\t'riemann' : simple riemann sum\\n\";\n      cout<<\"\\t'trapezoid' : trapezoid rule\\n\";\n      cout<<\"\\t'simpson' : simposon's rule (uses interpolation)\\n\";\n      cout<<\"\\t'gauss-legendre' : Gauss-Legendre interpolation (uses interpolation)\\n\";\n      return 1;\n    }\n\n\n    ifstream in;\n    double *x, *y, sum;\n    int n;\n\n    // load data\n    in.open( vm[\"integrate-data\"].as<string>().c_str() );\n    if( !in.is_open() )\n    {\n      cerr << \"ERROR: could not open file: \"<<vm[\"integrate-data\"].as<string>()<< endl;\n      return 0;\n    }\n\n    ReadFunction( in, x, y, n );\n    in.close();\n\n    std::function<double(std::vector<double>&,std::vector<double>&)> interp;\n    interp = create(vm[\"method\"].as<string>());\n    if( !interp )\n    {\n      delete[] x;\n      delete[] y;\n      cerr << \"ERROR: Unrecognized interpolation method (\" << vm[\"method\"].as<string>()<< \").\" << endl;\n      return 0;\n    }\n    \n    std::vector<double> X(x,x+n),Y(y,y+n);\n\n    delete[] x;\n    delete[] y;\n\n    sum = interp(X,Y);\n\n    std::cout << sum << std::endl;\n  \n    return 0;\n}\n\n\n\n\n\nvoid ReadFunction(std::istream &_in, double  *&_x, double *&_y, int *&_n, int _dimensions, int _multiplicity)\n{\n\n  double *xbuffer1, *xbuffer2;\n  double *ybuffer1, *ybuffer2;\n\n  //////////////////////////////\n  //  READ IN DATA FROM FILE  //\n  //////////////////////////////\n\n  const int chunck = 1000;\n  int buffsize,buffsize_old;\n  int i,j;\n  int n;\n\n  std::string line;\n  \n\n  buffsize = chunck;\n\n  xbuffer1 = new double[buffsize*_dimensions  ];\n  ybuffer1 = new double[buffsize*_multiplicity];\n\n  i = 0;\n  while( getline( _in, line ) )\n  {\n    // if line is blank, skip it\n    if( line == \"\" )\n      continue;\n    std::vector<std::string> columns;\n    boost::char_separator<char> sep(\" \\t\");\n    boost::tokenizer<boost::char_separator<char>> toks(line,sep);\n    for( auto it = toks.begin(); it != toks.end(); ++it )\n      columns.push_back( *it );\n\n    // if first column starts with a #, this line is a comment\n    // and we should skip it.\n    if( columns.size() > 0 && columns[0].find('#') == 0 )\n      continue;\n\n    if(i == buffsize - 1)  // this \"grows\" the buffer\n    {\n      buffsize_old = buffsize;\n      buffsize = buffsize + chunck;\n\n      xbuffer2 = new double[buffsize*_dimensions  ];\n      std::copy( xbuffer1, xbuffer1 + buffsize_old*_dimensions, xbuffer2);\n      delete[] xbuffer1;\n\n      ybuffer2 = new double[buffsize*_multiplicity];\n      std::copy( ybuffer1, ybuffer1 + buffsize_old*_multiplicity, ybuffer2);\n      delete[] ybuffer1;\n\n      xbuffer1 = xbuffer2;\n      ybuffer1 = ybuffer2;\n    }\n\n    for(j = 0; j < _dimensions; j++)\n      xbuffer1[i*_dimensions + j]   = boost::lexical_cast<double>(columns[j]);\n    for(j = 0; j < _multiplicity; j++)\n      ybuffer1[i*_multiplicity + j] = boost::lexical_cast<double>(columns[j+_dimensions]);\n\n    i++;\n  }\n\n  n = i;\n\n\n  /** \\todo add actual multi-coordinate support */\n\n  _n = new int[_dimensions];\n  _x = new double[n * _dimensions  ];\n  _y = new double[n * _multiplicity];\n\n  for(j = 0; j < n * _dimensions  ; j++)\n    _x[j] = xbuffer1[j];\n  for(j = 0; j < n * _multiplicity; j++)\n    _y[j] = ybuffer1[j];\n  for(j = 0; j < _dimensions; j++)\n    _n[j] = n;\n\n  delete[] xbuffer1;\n  delete[] ybuffer1;\n\n}\n\nvoid ReadFunction(std::istream &_in, double *&_x, double *&_y, int &_n, int _dimensions, int _multiplicity)\n{\n  int *n;\n  ReadFunction(_in, _x, _y, n, _dimensions, _multiplicity);\n  _n = n[0];\n  delete[] n;\n}\n\n\n", "meta": {"hexsha": "c2db531ec687d43d36321ffbd1a6c9a04beb85ae", "size": 7163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/integrate-cli.cpp", "max_stars_repo_name": "CD3/libIntegrate", "max_stars_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T00:46:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T14:29:46.000Z", "max_issues_repo_path": "applications/integrate-cli.cpp", "max_issues_repo_name": "CD3/libIntegrate", "max_issues_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-09-27T02:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T04:28:02.000Z", "max_forks_repo_path": "applications/integrate-cli.cpp", "max_forks_repo_name": "CD3/libIntegrate", "max_forks_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-30T02:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T02:43:05.000Z", "avg_line_length": 25.8592057762, "max_line_length": 121, "alphanum_fraction": 0.5881613849, "num_tokens": 2026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6820272321602517}}
{"text": "#include <math.h>\n#include <random>\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\nboost::random::mt19937 gen(time(0));\n\n//distributions\ndouble runif(double lower, double higher)\n{\n\tboost::random::uniform_real_distribution<> dist(lower, higher);\n\treturn dist(gen);\n}\n\ndouble rnorm(double mean, double sd)\n{\n\tboost::random::normal_distribution<> dist(mean, sd);\n\treturn dist(gen);\n}\n\n\ndouble rbeta(double alpha, double beta)\n{\n\n\tboost::math::beta_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rinvchisq(double df, double scale)\n{\n\n\tboost::math::inverse_chi_squared_distribution<> dist(df, scale);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\nint rbernoulli(double p)\n{\n\tstd::bernoulli_distribution dist(p);\n\treturn dist(gen);\n}\n\n\nint rbinom(int k, double p)\n{\n\n\tstd::binomial_distribution<> dist(k,p);\n\treturn dist(gen);\n}\n", "meta": {"hexsha": "a3c2672155dfa7c83ac3034a8a2b86788648d53e", "size": 904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BayesC_distributions.cpp", "max_stars_repo_name": "kousathanas/BayesC", "max_stars_repo_head_hexsha": "57fc7016ea61b7fafdc7634d8d87d730af415383", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BayesC_distributions.cpp", "max_issues_repo_name": "kousathanas/BayesC", "max_issues_repo_head_hexsha": "57fc7016ea61b7fafdc7634d8d87d730af415383", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BayesC_distributions.cpp", "max_forks_repo_name": "kousathanas/BayesC", "max_forks_repo_head_hexsha": "57fc7016ea61b7fafdc7634d8d87d730af415383", "max_forks_repo_licenses": ["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.7254901961, "max_line_length": 65, "alphanum_fraction": 0.7146017699, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750360641185, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.681995829597602}}
{"text": "//\n// Created by yongqi on 17-12-4.\n//\n\n#ifndef VFORCE_MATHUTILS_HPP\n#define VFORCE_MATHUTILS_HPP\n\n#include <cmath>\n#include <Eigen/Eigen>\n\nnamespace VForce {\nnamespace Utils {\n/**\n * make angle between [-pi, pi)\n * @param x input angle in radius\n * @return normalized angle\n */\ninline double normalize_angle(double x) {\n  x = fmod(x + M_PI, 2 * M_PI);\n  return x < 0 ? x += 2 * M_PI : x - M_PI;\n}\n\ninline float normalize_anlge(float x) {\n  x = fmod(x + M_PI, 2 * M_PI);\n  return x < 0 ? x += 2 * M_PI : x - M_PI;\n}\n\n/**\n * radian to degree\n * @tparam T\n * @param x\n * @return\n */\ntemplate<typename T>\ninline T rad2deg(T x) {\n  return x / M_PI * 180.;\n}\n\n/**\n * degree to radian\n * @tparam T\n * @param x\n * @return\n */\ntemplate<typename T>\ninline T deg2rad(T x) {\n  return x * M_PI / 180.;\n}\n\n/**\n * Convert pose(in Rz(yaw)Ry(pitch)Rx(roll) order) into transformation matrix\n * @tparam T\n * @param x\n * @param y\n * @param z\n * @param roll\n * @param pitch\n * @param yaw\n * @param tf\n */\ntemplate<typename T>\nvoid pose2matrix(const T &x, const T &y, const T &z,\n                 const T &roll, const T &pitch, const T &yaw,\n                 Eigen::Matrix<T, 4, 4> &t) {\n  T A = cos(yaw),  B = sin(yaw),  C = cos(pitch), D = sin (pitch),\n      E = cos(roll), F = sin(roll), DE = D*E,       DF = D*F;\n\n  t(0, 0) = A*C;  t(0, 1) = A*DF - B*E;  t(0, 2) = B*F + A*DE;  t(0, 3) = x;\n  t(1, 0) = B*C;  t(1, 1) = A*E + B*DF;  t(1, 2) = B*DE - A*F;  t(1, 3) = y;\n  t(2, 0) = -D;   t(2, 1) = C*F;         t(2, 2) = C*E;         t(2, 3) = z;\n  t(3, 0) = 0;    t(3, 1) = 0;           t(3, 2) = 0;           t(3, 3) = 1;\n}\n\n/**\n * Convert transformation matrix into pose\n * @tparam T\n * @param matrix\n * @param x\n * @param y\n * @param z\n * @param roll\n * @param pitch\n * @param yaw\n */\ntemplate<typename T>\nvoid matrix2pose(const Eigen::Matrix<T, 4, 4> &t,\n                 T &x, T &y, T &z,\n                 T &roll, T &pitch, T &yaw) {\n  x = t(0, 3);\n  y = t(1, 3);\n  z = t(2, 3);\n  roll = atan2(t(2, 1), t(2, 2));\n  pitch = atan2(-t(2, 0), sqrt(t(2, 1) * t(2, 1) + t(2, 2) * t(2, 2)));\n  yaw = atan2(t(1, 0), t(0, 0));\n}\n\n}\n}\n\n#endif //VFORCE_MATHUTILS_HPP\n", "meta": {"hexsha": "9723786bf60c0ec7622abf655d045c2e738844fc", "size": 2145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/MathUtils.hpp", "max_stars_repo_name": "eagleeye1105/VForce", "max_stars_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-05-04T04:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T06:56:23.000Z", "max_issues_repo_path": "src/utils/MathUtils.hpp", "max_issues_repo_name": "eagleeye1105/VForce", "max_issues_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-06T06:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T06:22:58.000Z", "max_forks_repo_path": "src/utils/MathUtils.hpp", "max_forks_repo_name": "freealong/VForce", "max_forks_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-05-04T04:53:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T15:51:33.000Z", "avg_line_length": 21.2376237624, "max_line_length": 77, "alphanum_fraction": 0.5198135198, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6819103500488627}}
{"text": "/**\n * gaussian.hpp v1.0.0\n *\n * Contains methods related to Gaussian distributions and smoothing.\n * Methods for curve fitting are in gaussianfit.cpp.\n */\n\n#pragma once\n\n#define SQRT2PI 2.506628275\n\n#include <cmath>\n\n#define  ARMA_DONT_USE_WRAPPER\n#define  ARMA_USE_LAPACK\n#define  ARMA_DONT_PRINT_ERRORS\n#include <armadillo>\n\nnamespace bib {\n\n  namespace gaussian {\n\n    const double M_SQRT_2OVERPI = std::sqrt(2.0 / M_PI);\n    const double M_SQRT_2OVERPI_CUBED = std::pow(M_SQRT_2OVERPI, 3.0);\n  \n    /**\n     * Represents a Gaussian distribution. Comparison functions only\n     * compare amplitude (used for sorting from most to least important\n     * when curve fitting).\n     *\n     * amplitude: suqare root of the amplitude of the distribution.\n     * mean: center point of the distribution.\n     * stdev: standard deviation of the distribution.\n     */\n    struct Parameters {\n    \n      double amplitude;\n      double mean;\n      double stdev;\n\n      bool operator >(const Parameters& a) const {\n\treturn amplitude * amplitude / stdev > a.amplitude * a.amplitude / a.stdev;\n      }\n    \n      bool operator <(const Parameters& a) const {\n\treturn amplitude * amplitude / stdev < a.amplitude * a.amplitude / a.stdev;\n      }\n    \n    };\n\n    /**\n     * Represents a Gaussian distribution with shape (adds skewness).\n     * Comparison functions only compare amplitude (used for sorting\n     * from most to least important when curve fitting).\n     *\n     * shape: shape parameter (alpha) capturing skewness.\n     * amplitude: suqare root of the amplitude of the distribution.\n     * mean: center point of the distribution.\n     * stdev: standard deviation of the distribution.\n     */\n    struct SkewParameters {\n    \n      double amplitude;\n      double mean;\n      double stdev;\n      double shape;\n\n      bool operator >(const SkewParameters& a) const {\n\treturn amplitude * amplitude / stdev > a.amplitude * a.amplitude / a.stdev;\n      }\n    \n      bool operator <(const SkewParameters& a) const {\n\treturn amplitude * amplitude / stdev < a.amplitude * a.amplitude / a.stdev;\n      }\n    \n    };\n\n    /**\n     * Returns the value of a Gaussian distribution at a given point x.\n     *\n     * amplitude: suqare root of the amplitude of the distribution.\n     * mean: center point of the distribution.\n     * stdev: standard deviation of the distribution.\n     * x: the point at which to sample the distribution.\n     */\n    inline double curveValue(double amplitude, double mean, double stdev, double x) {\n      return amplitude * amplitude / stdev * std::exp( -(x - mean) * (x - mean) / stdev / stdev / 2.0 );\n    }\n\n    /**\n     * Returns the value of a Gaussian distribution with shape at a given point x.\n     *\n     * amplitude: suqare root of the amplitude of the distribution.\n     * mean: center point of the distribution.\n     * stdev: standard deviation of the distribution.\n     * shape: shape parameter (alpha) capturing skewness.\n     * x: the point at which to sample the distribution.\n     */\n    inline double curveValue(double amplitude, double mean, double stdev, double shape, double x) {\n      return amplitude * amplitude / stdev * std::exp( -(x - mean) * (x - mean) / stdev / stdev / 2.0 )\n\t* (1.0 + std::erf(shape * (x - mean) / (stdev * M_SQRT2)));\n    }\n  \n    /**\n     * Returns the value of a Gaussian distribution with shape at a given point x.\n     *\n     * distribution: the distribution to sample.\n     * x: the point at which to sample the distribution.\n     */\n    inline double curveValue(Parameters distribution, double x) {\n      return curveValue(distribution.amplitude, distribution.mean, distribution.stdev, x);\n    }\n\n    /**\n     * Returns the value of a Gaussian distribution with shape at a given point x.\n     *\n     * distribution: the distribution to sample.\n     * x: the point at which to sample the distribution.\n     */\n    inline double curveValue(SkewParameters distribution, double x) {\n      return curveValue(distribution.amplitude, distribution.mean, distribution.stdev,\n\t\t\tdistribution.shape, x);\n    }\n  \n    /**\n     * Smooths the input vector using a Gaussian distribution of the given width.\n     *\n     * input: the input vector to smooth.\n     * kernelWidth: standard deviation of the distribution to use for smoothing.\n     */\n    arma::Col<double> smooth(const arma::Col<double>& input, double kernelWidth);\n\n    /**\n     * Smooths the input vector using the second derivative of a Gaussian distribution\n     * of the given width.\n     *\n     * input: the input vector to smooth.\n     * kernelWidth: standard deviation of the distribution to use for smoothing.\n     */\n    arma::Col<double> scaleSpaceSmooth(const arma::Col<double>& input, double kernelWidth);\n\n    std::vector<double> getDistribution(double A, double x, double u, size_t length);\n\n    inline int sgn(double val) {\n      return (0.0 < val) - (val < 0.0);\n    }\n  \n    inline double skewMode(SkewParameters gaussian) {\n      double delta = gaussian.shape / std::sqrt(1.0 + gaussian.shape * gaussian.shape);\n      double uz = M_SQRT_2OVERPI * delta;\n      double oz = std::sqrt(1.0 - uz * uz);\n      double skewness = ((4.0 - M_PI) / 2.0)\n\t* ((M_SQRT_2OVERPI_CUBED * delta * delta * delta) / std::pow(1.0 - 2.0 * delta * delta / M_PI, 1.5));\n      return (uz - skewness * oz / 2.0 - sgn(gaussian.shape) / 2.0 * std::exp(-2.0 * M_PI / std::abs(gaussian.shape)))\n\t* gaussian.stdev + gaussian.mean;\n    }\n    \n  }\n\n} // namespace bib::gaussian\n", "meta": {"hexsha": "8f1dd3d98374bc1921d8d0544728d441f3a0854f", "size": 5477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_stars_repo_name": "genome-almanac/mnase-workflow", "max_stars_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_issues_repo_name": "genome-almanac/mnase-workflow", "max_issues_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_forks_repo_name": "genome-almanac/mnase-workflow", "max_forks_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_forks_repo_licenses": ["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.0186335404, "max_line_length": 118, "alphanum_fraction": 0.6558334855, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6819103302608538}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[intersection_ls_ls_point\n//` Calculate the intersection of two linestrings\n\n#include <iostream>\n#include <deque>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/linestring.hpp>\n\n#include <boost/foreach.hpp>\n\nBOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(std::vector)\n\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> P;\n    std::vector<P> line1, line2;\n    boost::geometry::read_wkt(\"linestring(1 1,2 2,3 1)\", line1);\n    boost::geometry::read_wkt(\"linestring(1 2,2 1,3 2)\", line2);\n\n    std::deque<P> intersection_points;\n    boost::geometry::intersection(line1, line2, intersection_points);\n\n    BOOST_FOREACH(P const& p, intersection_points)\n    {\n        std::cout << \" \" << boost::geometry::wkt(p);\n    }\n    std::cout << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[intersection_ls_ls_point_output\n/*`\nOutput:\n[pre\n POINT(1.5 1.5) POINT(2.5 1.5)\n]\n*/\n//]\n", "meta": {"hexsha": "336dde1aa11d3c65c3745e6f5709ecb476a5a561", "size": 1340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_ls_ls_point.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_ls_ls_point.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/intersection_ls_ls_point.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "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.9285714286, "max_line_length": 79, "alphanum_fraction": 0.7082089552, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6818044392514914}}
{"text": "#include \"Gaussian.h\"\n#include <iostream>\n#include <stdexcept>\n#include <cmath>\n#include \"../Utils.h\"\n//#include <boost/math/special_functions/erf.hpp>\n\nnamespace DNest4\n{\n\nGaussian::Gaussian(double center, double width)\n:center(center)\n,width(width)\n{\n    if(width <= 0.0)\n        throw std::domain_error(\"Gaussian distribution must have positive width.\");\n}\n\ndouble Gaussian::cdf(double x) const\n{\n    return normal_cdf((x-center)/width);\n}\n\ndouble Gaussian::cdf_inverse(double x) const\n{\n    if(x < 0.0 || x > 1.0)\n        throw std::domain_error(\"Input to cdf_inverse must be in [0, 1].\");\n    return center + width*normal_inverse_cdf(x);\n    //return center + width * sqrt(2) * boost::math::erf_inv(2*x - 1);\n}\n\ndouble Gaussian::log_pdf(double x) const\n{\n\tdouble r = (x - center)/width;\n    return -0.5*r*r - _norm_pdf_logC;\n}\n\n\n\nTruncatedGaussian::TruncatedGaussian(double center, double width, double lower, double upper)\n:center(center)\n,width(width)\n,lower(lower)\n,upper(upper)\n{\n    if(width <= 0.0)\n        throw std::domain_error(\"TruncatedGaussian distribution must have positive width.\");\n    if(lower >= upper)\n        throw std::domain_error(\"TruncatedGaussian: lower bound should be less than upper bound.\");\n    // the original, untruncated, Gaussian distribution\n    unG = Gaussian(center, width);\n    c = unG.cdf(upper) - unG.cdf(lower);\n}\n\ndouble TruncatedGaussian::cdf(double x) const\n{\n    double up = std::max(std::min(x,upper), lower);\n    return (unG.cdf(up) - unG.cdf(lower)) / c;\n}\n\ndouble TruncatedGaussian::cdf_inverse(double x) const\n{\n    if(x < 0.0 || x > 1.0)\n        throw std::domain_error(\"Input to cdf_inverse must be in [0, 1].\");\n    double xx = unG.cdf(lower) + x * c;\n    return unG.cdf_inverse(xx);\n}\n\ndouble TruncatedGaussian::log_pdf(double x) const\n{\n    if(x<lower or x>upper) return -std::numeric_limits<double>::infinity();\n    return unG.log_pdf(x) - log(c);\n}\n\n\n\n} // namespace DNest4", "meta": {"hexsha": "568d45c676bf76850dee23e48f544c092e9b31e5", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/Distributions/Gaussian.cpp", "max_stars_repo_name": "j-faria/DNest4", "max_stars_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Distributions/Gaussian.cpp", "max_issues_repo_name": "j-faria/DNest4", "max_issues_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Distributions/Gaussian.cpp", "max_forks_repo_name": "j-faria/DNest4", "max_forks_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-13T09:58:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T09:58:15.000Z", "avg_line_length": 25.1298701299, "max_line_length": 99, "alphanum_fraction": 0.6733850129, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6818044387953641}}
{"text": "/*\nMIT License\n\nCopyright (c) 2020 kyawakyawa\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#include <iostream>\n#include <utility>\n\n#include \"macros.h\"\n\nIGNORE_STRICT_WARNING_PUSH\n\n#include <Eigen/Core>\n\nIGNORE_STRICT_WARNING_POP\n\n// reference http://takashiijiri.com/study/miscs/QRfactorization.htm\n\ntemplate <typename Real, int N>\nEigen::Matrix<Real, N, N> HouseholderTransformation(\n    const Eigen::Matrix<Real, N, 1>& x, const Eigen::Matrix<Real, N, 1>& y) {\n  static_assert(N >= 1);\n  const auto aux = x - y;\n  const Eigen::Matrix<Real, N, 1> u = aux.normalized();\n\n  return Eigen::Matrix<Real, N, N>::Identity() - 2 * u * u.transpose();\n}\n\ntemplate <typename Real>\nEigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic> HouseholderTransformation(\n    const Eigen::Matrix<Real, Eigen::Dynamic, 1>& x,\n    const Eigen::Matrix<Real, Eigen::Dynamic, 1>& y) {\n  assert(x.rows() >= 1 && x.rows() == y.rows());\n  const auto aux = x - y;\n  const Eigen::Matrix<Real, Eigen::Dynamic, 1> u = aux.normalized();\n\n  return Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic>::Identity(\n             x.rows(), x.rows()) -\n         2 * u * u.transpose();\n}\n\ntemplate <typename Real, int N, int M>\nstd::pair<Eigen::Matrix<Real, N, N>, Eigen::Matrix<Real, N, M>>\nQRDecompositionWithHouseholderTransformation(\n    const Eigen::Matrix<Real, N, M>& input) {\n  static_assert(M >= 1 && N >= M);\n  Eigen::Matrix<Real, N, M> R = input;\n  Eigen::Matrix<Real, N, N> Q = Eigen::Matrix<Real, N, N>::Identity();\n\n  for (int k = 0; k < M - 1; ++k) {\n    const Real sign = (R(k, k) >= Real(0) ? Real(1) : Real(-1));\n    const int Mmk = M - k;\n\n    const Eigen::Matrix<Real, Eigen::Dynamic, 1> x = R.block(k, k, Mmk, 1);\n    // \u30b0\u30e9\u30d5\u30a3\u30c3\u30af\u7528\u9014(\u30ed\u30fc\u30c6\u30fc\u30b7\u30e7\u30f3\u3068\u30b9\u30b1\u30fc\u30eb\u306e\u5206\u96e2)\u306e\u5834\u5408\u3001\n    // y(0,0)\u306e\u7b26\u53f7\u306f+\u3067\u56fa\u5b9a\u3057\u305f\u307b\u3046\u304c\u3044\u3044(\u3053\u306e\u5024\u304cR\u306e\u5bfe\u89d2\u8981\u7d20\u306b\u306a\u308b)\n    Eigen::Matrix<Real, Eigen::Dynamic, 1> y =\n        Eigen::Matrix<Real, Eigen::Dynamic, 1>::Zero(Mmk, 1);\n    const Real norm = x.norm();\n    // u\u304c0 vector\u306b\u306a\u308b\u5834\u5408\n    // \u3053\u306e\u5834\u5408\u306f\u305d\u3082\u305d\u3082\u8a08\u7b97\u3059\u308b\u5fc5\u8981\u304c\u306a\u3044\n    if (std::abs(norm - std::abs(x[0])) <\n        std::numeric_limits<Real>::epsilon()) {\n      continue;\n    }\n    y[0] = -sign * x.norm();\n\n    const Eigen::Matrix<Real, Eigen::Dynamic, 1> u = (x - y).normalized();\n\n    R.bottomRightCorner(Mmk, Mmk) -=\n        Real(2) * u * (u.transpose() * R.bottomRightCorner(Mmk, Mmk));\n    //////////////////// R\u306e\u307f\u6b32\u3057\u3044\u5834\u5408\u306f\u3053\u3053\u307e\u3067\u306e\u8a08\u7b97\u3067\u826f\u3044\n    ///////////////////////\n\n    if (k > 0) {\n      Q.topRightCorner(k, Mmk) -=\n          Real(2) * (Q.topRightCorner(k, Mmk) * u) * u.transpose();\n    }\n    Q.bottomRightCorner(Mmk, Mmk) -=\n        Real(2) * (Q.bottomRightCorner(Mmk, Mmk) * u) * u.transpose();\n  }\n\n  return std::make_pair(Q, R);\n}\n\n#ifdef USE_STACK_TRACE_LOGGER\n#include <glog/logging.h>\n#endif\n\nint main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) {\n#ifdef USE_STACK_TRACE_LOGGER\n  (void)argc;\n  google::InitGoogleLogging(argv[0]);\n  google::InstallFailureSignalHandler();\n#endif\n\n  const Eigen::Vector3d x = {1, 2, 3};\n  const Eigen::Vector3d y = {3, 2, 1};\n\n  std::cout << \"----------HouseholderTransformation----------\" << std::endl;\n\n  std::cout << \" x = (\" << x.transpose() << \")^T\\n y = (\" << y.transpose()\n            << \")^T\\n\"\n            << std::endl;\n\n  const Eigen::Matrix3d H = HouseholderTransformation(x, y);\n  std::cout << \" H = \\n\" << H << \"\\n\" << std::endl;\n\n  const Eigen::Vector3d Hx = H * x;\n  const Eigen::Vector3d Hy = H * y;\n\n  std::cout << \" (Hx)^T = (\" << Hx.transpose() << \")\\n\" << std::endl;\n  std::cout << \" (Hy)^T = (\" << Hy.transpose() << \")\\n\" << std::endl;\n\n  std::cout << \" H*H^T = \\n\" << H * H.transpose() << \"\\n\" << std::endl;\n\n  std::cout << \"---------- ----------\" << std::endl;\n\n  std::cout\n      << \"----------QRDecompositionWithHouseholderTransformation----------\"\n      << std::endl;\n  Eigen::Matrix3d A;\n\n  A(0, 0) = 1.;\n  A(0, 1) = 4.;\n  A(0, 2) = 9.;\n\n  A(1, 0) = 16.;\n  A(1, 1) = 25.;\n  A(1, 2) = 36.;\n\n  A(2, 0) = 49.;\n  A(2, 1) = 64.;\n  A(2, 2) = 81.;\n\n  const auto result = QRDecompositionWithHouseholderTransformation(A);\n\n  std::cout << \" Q = \\n\" << result.first << \"\\n\" << std::endl;\n  std::cout << \" R = \\n\" << result.second << \"\\n\" << std::endl;\n\n  std::cout << \" QR = \\n\" << result.first * result.second << \"\\n\" << std::endl;\n\n  std::cout << \" QQ^T = \\n\"\n            << result.first * result.first.transpose() << \"\\n\"\n            << std::endl;\n\n  std::cout << \"---------- ----------\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "55539df7fa78f7fceaf60d03934df20d6b12d96b", "size": 5366, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pc/qr-decomposition.cc", "max_stars_repo_name": "kyawakyawa/cpp-junk-parts", "max_stars_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pc/qr-decomposition.cc", "max_issues_repo_name": "kyawakyawa/cpp-junk-parts", "max_issues_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pc/qr-decomposition.cc", "max_forks_repo_name": "kyawakyawa/cpp-junk-parts", "max_forks_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_forks_repo_licenses": ["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.7514792899, "max_line_length": 79, "alphanum_fraction": 0.6082743198, "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6817370454814721}}
{"text": "/**\n * @file Interpolation.hpp\n * @author bwu\n * @brief Interpolation method implementation\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_MATH_INTERPOLATION_HPP\n#define GENERIC_MATH_INTERPOLATION_HPP\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include \"generic/common/Traits.hpp\"\n#include \"MathUtility.hpp\"\n#include <vector>\nnamespace generic {\nnamespace math    {\nusing generic::common::float_type;\ntemplate <typename num_type>\nclass Interpolation\n{\n    using float_t = float_type<num_type>;\n    using vector_t = boost::numeric::ublas::vector<float_t>;\n    using band_matrix_t = boost::numeric::ublas::banded_matrix<float_t>;\npublic:\n    enum class Method { Linear = 1, Cubic = 2};\n    enum class BCType { FirstDeriv = 1, SecondDeriv = 2, NotAKnot = 3 };\n\n    ///@brief constructs an interpolation object with method\n    Interpolation(Method method = Method::Linear);\n    /**\n     * @brief constructs an interpolation object with parameters\n     * @param x input samples of x\n     * @param y input samples of y\n     * @param method interpolation method\n     * @note if Cubic method failed with input x, y samples, it will decay to Linear method\n     * @param monotonic set whether curve monotonic when interpolation\n     * @param left left boundary condition type\n     * @param lValue left boundary condition initial value\n     * @param right right boundary condition type\n     * @param rValue right boundary condition inital value\n     */\n    Interpolation(const std::vector<num_type> & x, const std::vector<num_type> & y,\n                    Method method, bool monotonic = false,\n                    BCType left  = BCType::SecondDeriv, float_t lValue  = 0,\n                    BCType right = BCType::SecondDeriv, float_t rValue = 0);\n\n    ///@brief sets boundary conditions and inital values\n    void SetBoundary(BCType left, BCType right, float_t lVal, float_t rVal);\n    ///@brief sets input samples of x and y\n    void SetSamples(const std::vector<num_type> & x, const std::vector<num_type> & y);\n\n    ///@brief gets interpolated value of input x\n    num_type operator() (num_type x) const { return Interpolate(x); }\n\nprivate:\n    void UpdateCoefficients();\n    bool makeMonotonic();\n    size_t FindClosest(num_type x) const;\n    num_type Interpolate(num_type x) const;\n    num_type Interpolate(num_type x, const num_integer_tag) const;\n    float_t Interpolate(num_type x, const num_floating_tag) const;\n\nprivate:\n    Method m_method;\n    bool m_monotonic;\n    BCType m_left, m_right;\n    float_t m_lVal, m_rVal;\n    std::vector<num_type> m_x, m_y;\n    float_t m_coef0 = 0;\n    std::vector<float_t> m_coef1, m_coef2, m_coef3;\n};\n\ntemplate <typename num_type>\ninline Interpolation<num_type>::Interpolation(Method method)\n : m_method(method), m_monotonic(false), m_left(BCType::SecondDeriv), m_right(BCType::SecondDeriv), m_lVal(0), m_rVal(0)\n{\n}\n\ntemplate <typename num_type>\ninline Interpolation<num_type>::Interpolation(const std::vector<num_type> & x, const std::vector<num_type> & y,\n                                                Method method, bool monotonic,\n                                                BCType left, float_t lValue, BCType right, float_t rValue)\n : m_method(method), m_monotonic(monotonic), m_left(left), m_right(right), m_lVal(lValue), m_rVal(rValue)\n{\n    SetSamples(x, y);\n}\n\ntemplate <typename num_type>\ninline void Interpolation<num_type>::SetBoundary(BCType left, BCType right, float_t lVal, float_t rVal)\n{\n    assert(m_x.size() == 0 && \"should set boundary type before setting samples\");\n    m_left = left; m_right = right;\n    m_lVal = lVal; m_rVal = rVal;\n}\n\ntemplate <typename num_type>\ninline void Interpolation<num_type>::SetSamples(const std::vector<num_type> & x, const std::vector<num_type> & y)\n{\n    const size_t size = x.size();\n    assert(size > 0 && size == y.size());\n    m_x = x; m_y = y;\n    m_coef1.assign(size, 0); m_coef2.assign(size, 0), m_coef3.assign(size, 0);\n    if(size < 2) return;\n    if(size < 3) m_method = Method::Linear;\n    if(Method::Linear == m_method){\n        for(size_t i = 0, j = 1; i < size - 1; ++i, ++j)\n            m_coef1[i] = float_t(m_y[j] - m_y[i]) / float_t(m_x[j] - m_x[i]);\n        m_coef1[size - 1] = m_coef1[size - 2];\n    }\n    else if(Method::Cubic == m_method){\n        size_t lower = (m_right == BCType::NotAKnot) ? 2 : 1;\n        size_t upper = (m_left  == BCType::NotAKnot) ? 2 : 1;\n        band_matrix_t m(size, size, lower, upper);\n        vector_t rhs(size);\n        for(size_t i = 0, j = 1, k = 2; k < size; ++i, ++j, ++k){\n            m(j, i) = 1.0 / 3.0 * (m_x[j] - m_x[i]);\n            m(j, j) = 2.0 / 3.0 * (m_x[k] - m_x[i]);\n            m(j, k) = 1.0 / 3.0 * (m_x[k] - m_x[j]);\n            rhs[j] = (m_y[k] - m_y[j]) / (m_x[k] - m_x[j]) - (m_y[j] - m_y[i]) / (m_x[j] - m_x[i]);\n        }\n        //BC\n        if(m_left == BCType::FirstDeriv){\n            m(0, 0) = 2.0 * (m_x[1] - m_x[0]);\n            m(0, 1) = 1.0 * (m_x[1] - m_x[0]);\n            rhs[0] = 3.0 * ((m_y[1] - m_y[0]) / (m_x[1] - m_x[0]) - m_lVal);\n        }\n        else if(m_left == BCType::SecondDeriv){\n            m(0, 0) = 2.0;\n            m(0, 1) = 0.0;\n            rhs[0] = m_lVal;\n        }\n        else if(m_left == BCType::NotAKnot){\n            m(0, 0) = - m_x[2] + m_x[1];\n            m(0, 1) =   m_x[2] - m_x[0];\n            m(0, 2) = - m_x[1] + m_x[0];\n            rhs[0] = 0.0;\n        }\n        else { assert(false); }\n\n        if(m_right == BCType::FirstDeriv){\n            m(size - 1, size - 1) = 2.0 * (m_x[size - 1] - m_x[size - 2]);\n            m(size - 1, size - 2) = 1.0 * (m_x[size - 1] - m_x[size - 2]);\n            rhs[size - 1] = 3.0 * (m_rVal - (m_y[size - 1] - m_y[size - 2]) / (m_x[size - 1] - m_x[size - 2]));\n        }\n        else if(m_right == BCType::SecondDeriv){\n            m(size - 1, size - 1) = 2.0;\n            m(size - 1, size - 2) = 0.0;\n            rhs[size - 1] = m_rVal;\n        }\n        else if(m_right == BCType::NotAKnot){\n            m(size - 1, size - 3) = - m_x[size - 1] + m_x[size - 2];\n            m(size - 1, size - 2) =   m_x[size - 1] - m_x[size - 3];\n            m(size - 1, size - 1) = - m_x[size - 2] + m_x[size - 3]; \n        }\n        else { assert(false); }\n\n        boost::numeric::ublas::permutation_matrix<size_t> pm(size);\n\n        //decay to linear method if fail at LU factorization  \n        try {\n            lu_factorize(m, pm);\n            lu_substitute(m, pm, rhs);\n        }\n        catch (...) {\n            m_method = Method::Linear;\n            SetSamples(x, y);\n            return;\n        }\n\n        for(size_t i = 0; i < size; ++i)\n            m_coef2[i] = rhs[i];\n        \n        for(size_t i = 0, j = 1; j < size; ++i, ++j) {\n            m_coef1[i] = (m_y[j] - m_y[i]) / (m_x[j] - m_x[i]) - 1.0 / 3.0 * (2.0 * m_coef2[i] + m_coef2[j]) * (m_x[j] - m_x[i]);\n            m_coef3[i] = 1.0 / 3.0 * (m_coef2[j] - m_coef2[i]) / (m_x[j] - m_x[i]);\n        }\n\n        float_t h = x[size - 1] - x[size - 2];\n        m_coef3[size - 1] = 0.0;\n        m_coef1[size - 1] = 3.0 * m_coef3[size - 2] * h * h + 2.0 * m_coef2[size - 2] * h + m_coef1[size - 2];\n        if(m_right == BCType::FirstDeriv) m_coef2[size - 1] = 0.0;\n    }\n    m_coef0 = (m_left == BCType::FirstDeriv) ? 0 : m_coef3[0];\n    \n    if(!m_monotonic && size > 2) makeMonotonic();\n}\n\ntemplate <typename num_type>\ninline void Interpolation<num_type>::UpdateCoefficients()\n{\n    size_t size = m_coef1.size();\n    for(size_t i = 0; i < size - 1; ++i){\n        const float_t h = m_x[i + 1] - m_x[i];\n        m_coef2[i] = (3.0 * (m_y[i + 1] - m_y[i]) / h - (2.0 * m_coef1[i] + m_coef1[i + 1])) / h;\n        m_coef3[i] = ((m_coef1[i + 1] - m_coef1[i]) / (3.0 * h) - 2.0 / 3.0 * m_coef2[i]) / h;\n    }\n    m_coef0 = (m_left == BCType::FirstDeriv) ? 0 : m_coef3[0];\n}\n\ntemplate <typename num_type>\ninline bool Interpolation<num_type>::makeMonotonic()\n{\n    assert(m_x.size() > 2);\n    bool modified = false;\n    for(size_t i = 0; i < m_x.size(); ++i){\n        size_t im1 = std::max(i - 1, size_t(0));\n        size_t ip1 = std::min(i + 1, m_x.size() - 1);\n        if((m_y[im1] <= m_y[i] && m_y[i] <= m_y[ip1] && m_coef1[i] < 0) ||\n           (m_y[im1] >= m_y[i] && m_y[i] >= m_y[ip1] && m_coef1[i] > 0)) {\n            modified = true;\n            m_coef1[i] = 0;\n        }\n    }\n\n    for(size_t i = 0; i < m_x.size() - 1; ++i){\n        float_t avg = float_t(m_y[i + 1] - m_y[i]) / float_t(m_x[i + 1] - m_x[i]);\n        if(EQ(avg, 0.0) && (!EQ(m_coef1[i], 0.0) || !EQ(m_coef1[i], 0.0))){\n            modified = true;\n            m_coef1[i] = 0;\n            m_coef1[i + 1] = 0;\n        }\n        else if((GE(m_coef1[i], 0.0) && GE(m_coef1[i + 1], 0.0) && GE(avg, 0.0)) ||\n                (LE(m_coef1[i], 0.0) && LE(m_coef1[i + 1], 0.0) && LE(avg, 0.0))) {\n            float_t r = std::sqrt(m_coef1[i] * m_coef1[i] + m_coef1[i + 1] * m_coef1[i + 1]) / std::fabs(avg);\n            if(r > 3.0){\n                modified = true;\n                m_coef1[i] *= (3.0 / r);\n                m_coef1[i + 1] *= (3.0 / r);\n            }\n        }\n    }\n\n    if(modified == true){\n        UpdateCoefficients();\n        m_monotonic = true;\n    }\n    return modified;\n}\n\ntemplate <typename num_type>\ninline size_t Interpolation<num_type>::FindClosest(num_type x) const\n{\n    typename std::vector<num_type>::const_iterator iter;\n    iter = std::upper_bound(m_x.begin(), m_x.end(), x);\n    size_t index = std::max(int(iter - m_x.begin() - 1), 0);\n    return index;\n}\n\ntemplate <typename num_type>\ninline num_type Interpolation<num_type>::Interpolate(num_type x) const\n{\n    return Interpolate(x, typename num_traits_float_or_int<num_type>::tag());\n}\n\ntemplate <typename num_type>\ninline num_type Interpolation<num_type>::Interpolate(num_type x, const num_integer_tag) const\n{\n    return num_type(std::round(Interpolate(x, num_floating_tag())));\n}\n\ntemplate <typename num_type>\ninline float_type<num_type> Interpolation<num_type>::Interpolate(num_type x, const num_floating_tag) const\n{\n    size_t n = m_x.size();\n    size_t idx = FindClosest(x);\n    float_t h = x - m_x[idx];\n    if(x < m_x[0]) return (m_coef0 * h + m_coef1[0]) * h + m_y[0];\n    else if(x > m_x[n - 1]) return (m_coef2[n-1] * h + m_coef1[n - 1]) * h + m_y[n - 1];\n    else return ((m_coef3[idx] * h + m_coef2[idx]) * h + m_coef1[idx]) * h + m_y[idx];        \n}\n\n}//namespace math\n}//namespace generic\n#endif//GENERIC_MATH_INTERPOLATION_HPP", "meta": {"hexsha": "70d467b7378f3d45d8e17c49f723ad4d786dd957", "size": 10481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/Interpolation.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "math/Interpolation.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "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": "math/Interpolation.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "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": 38.1127272727, "max_line_length": 129, "alphanum_fraction": 0.5646407786, "num_tokens": 3402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6817341856133396}}
{"text": "// http://www.alglib.net/specialfunctions/incompletegamma.php\n// http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_gamma/igamma_inv.html\n// http://www.cs.washington.edu/research/projects/uns/F9/src/boost-1.39.0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_gamma/igamma.html\n// http://en.wikipedia.org/wiki/Gamma_distribution\n// http://en.wikipedia.org/wiki/Incomplete_gamma_function\n#ifndef qlex_math_gamma_distribution_h\n#define qlex_math_gamma_distribution_h\n\n#include <ql/errors.hpp>\n#include <ql/types.hpp>\n#include <functional>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nusing namespace QuantLib;\n\nnamespace QLExtension {\n\tclass InverseCumulativeGamma\n\t\t: public std::unary_function < Real, Real > {\n\tpublic:\n\t\tInverseCumulativeGamma(Real shape = 1.0,\n\t\t\tReal scale = 1.0);\n\n\t\t// in boost p is lower incomplete gamma function, q is upper incomplete gamma function\n\t\t// gamma_p(a,z) = p = gamma(a,z)/Gamma(a)\n\t\tReal operator()(Real x) const;\n\t\t\n\t\tboost::math::gamma_distribution<> dist_;\n\t};\n}\n\n\n#endif\n", "meta": {"hexsha": "78f21370649e5e41ff3bb41c701c1ec332504692", "size": 1113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.hpp", "max_stars_repo_name": "qg0/EliteQuant_Excel", "max_stars_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:29:10.000Z", "max_issues_repo_path": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.hpp", "max_issues_repo_name": "qg0/EliteQuant_Excel", "max_issues_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "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": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.hpp", "max_forks_repo_name": "qg0/EliteQuant_Excel", "max_forks_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 32.7352941176, "max_line_length": 146, "alphanum_fraction": 0.7663971249, "num_tokens": 295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.681729682785794}}
{"text": "#include \"Tetrahedron.h\"\n#include <Ziran/CS/Util/Debug.h>\n#include <Eigen/Dense>\n\nnamespace ZIRAN {\n\ntemplate <class T>\nvoid barycentricWeights(\n    const Vector<T, 3>& p,\n    const Vector<T, 3>& a,\n    const Vector<T, 3>& b,\n    const Vector<T, 3>& c,\n    const Vector<T, 3>& d,\n    Vector<T, 4>& weights)\n{\n    Matrix<T, 3, 3> Dm;\n    Dm.col(0) = a - d;\n    Dm.col(1) = b - d;\n    Dm.col(2) = c - d;\n\n    Vector<T, 3> weights_for_abc = Dm.partialPivLu().solve(p - d);\n    weights.template head<3>() = weights_for_abc;\n    weights(3) = (T)1 - weights_for_abc.array().sum();\n    ZIRAN_ASSERT((weights.array() >= (T)0).all(), weights.transpose());\n    ZIRAN_ASSERT((weights.array() <= (T)1).all(), weights.transpose());\n    ZIRAN_ASSERT(std::abs(weights.array().sum() - (T)1) < 1e-7, weights.transpose());\n\n    Vector<T, 3> test_p = Vector<T, 3>::Constant((T)0);\n    test_p += weights(0) * a;\n    test_p += weights(1) * b;\n    test_p += weights(2) * c;\n    test_p += weights(3) * d;\n    ZIRAN_ASSERT((p - test_p).squaredNorm() < 1e-7);\n}\n\ntemplate void barycentricWeights<double>(Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 3, 1, 0, 3, 1> const&, Eigen::Matrix<double, 4, 1, 0, 4, 1>&);\ntemplate void barycentricWeights<float>(Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 3, 1, 0, 3, 1> const&, Eigen::Matrix<float, 4, 1, 0, 4, 1>&);\n} // namespace ZIRAN\n", "meta": {"hexsha": "9e2082496f919a12937dcc43fd9110b84e83ff9e", "size": 1664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_stars_repo_name": "NTForked/ziran2019", "max_stars_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T13:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T15:54:50.000Z", "max_issues_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_issues_repo_name": "NTForked/ziran2019", "max_issues_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-06-24T21:19:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T19:37:53.000Z", "max_forks_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_forks_repo_name": "NTForked/ziran2019", "max_forks_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-11-07T07:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T10:40:39.000Z", "avg_line_length": 42.6666666667, "max_line_length": 305, "alphanum_fraction": 0.6033653846, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6815997019099154}}
{"text": "//          Copyright Christopher Kormanyos 2021.\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 <boost/math/bindings/e_float.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/number.hpp>\n\n// cd C:\\Users\\User\\Documents\\Ks\\PC_Software\\NumericalPrograms\\ExtendedNumberTypes\\e_float\\libs\\e_float\\build\n\n// g++ -Wall -Wextra -m64 -O3 -std=gnu++11 -DE_FLOAT_TYPE_EFX -I../../../libs/e_float/src -IC:/boost/modular_boost/boost/libs/multiprecision/include -IC:/boost/modular_boost/boost/libs/math/include -IC:/boost/boost_1_75_0 ../src/e_float/efx/e_float_efx.cpp ../src/e_float/e_float.cpp ../src/e_float/e_float_base.cpp ../src/functions/constants/constants.cpp ../src/functions/elementary/elementary_complex.cpp ../src/functions/elementary/elementary_hyper_g.cpp ../src/functions/elementary/elementary_math.cpp ../src/functions/elementary/elementary_trans.cpp ../src/functions/elementary/elementary_trig.cpp ../test_boost/test_boost.cpp -o test_boost.exe\n\nnamespace local\n{\n  using big_float_type = boost::multiprecision::number<boost::math::ef::e_float, boost::multiprecision::et_off>;\n\n  template<typename FloatingPointType>\n  FloatingPointType hypergeometric_2f1(const FloatingPointType& a,\n                                       const FloatingPointType& b,\n                                       const FloatingPointType& c,\n                                       const FloatingPointType& x)\n  {\n    // Compute the series representation of hypergeometric_2f1\n    // taken from Abramowitz and Stegun 15.1.1.\n    // There are no checks on input range or parameter boundaries.\n\n    FloatingPointType x_pow_n_div_n_fact(x);\n    FloatingPointType pochham_a         (a);\n    FloatingPointType pochham_b         (b);\n    FloatingPointType pochham_c         (c);\n    FloatingPointType ap                (a);\n    FloatingPointType bp                (b);\n    FloatingPointType cp                (c);\n\n    FloatingPointType h2f1 = 1 + (((pochham_a * pochham_b) / pochham_c) * x_pow_n_div_n_fact);\n\n    const FloatingPointType tol = std::numeric_limits<FloatingPointType>::epsilon() * x;\n\n    // Series expansion of hyperg_2f1(a, b; c; x).\n    for(std::int32_t n = INT32_C(2); n < INT32_C(100000); ++n)\n    {\n      x_pow_n_div_n_fact *= x;\n      x_pow_n_div_n_fact /= n;\n\n      pochham_a *= ++ap;\n      pochham_b *= ++bp;\n      pochham_c *= ++cp;\n\n      const FloatingPointType term = ((pochham_a * pochham_b) / pochham_c) * x_pow_n_div_n_fact;\n\n      using std::fabs;\n\n      if((n > 11) && (fabs(term) < tol))\n      {\n        break;\n      }\n\n      h2f1 += term;\n    }\n\n    return h2f1;\n  }\n\n  template<typename FloatingPointType>\n  FloatingPointType hypergeometric_2f1_regularized(const FloatingPointType& a,\n                                                   const FloatingPointType& b,\n                                                   const FloatingPointType& c,\n                                                   const FloatingPointType& x)\n  {\n    return hypergeometric_2f1(a, b, c, x) / boost::math::tgamma(c);\n  }\n\n  template<typename FloatingPointType>\n  FloatingPointType pochhammer(const FloatingPointType& x,\n                               const FloatingPointType& a)\n  {\n    return boost::math::tgamma(x + a) / boost::math::tgamma(x);\n  }\n\n  template<typename FloatingPointType>\n  FloatingPointType legendre_pvu(const FloatingPointType& v,\n                                 const FloatingPointType& u,\n                                 const FloatingPointType& x)\n  {\n    using std::pow;\n\n    // See also the third series representation provided in:\n    // https://functions.wolfram.com/HypergeometricFunctions/LegendreP2General/06/01/04/\n\n    const FloatingPointType u_half       = u / 2U;\n    const FloatingPointType one_minus_x  = 1U - x;\n    const FloatingPointType one_minus_mu = 1U - u;\n\n    const FloatingPointType tgamma_term    = boost::math::tgamma(one_minus_mu);\n    const FloatingPointType h2f1_reg_term  = hypergeometric_2f1_regularized(FloatingPointType(-v),\n                                                                            FloatingPointType(1U + v),\n                                                                            one_minus_mu,\n                                                                            FloatingPointType(one_minus_x / 2U));\n\n    return (pow(1U + x, u_half) * h2f1_reg_term) / pow(one_minus_x, u_half);\n  }\n\n  template<typename FloatingPointType>\n  FloatingPointType legendre_qvu(const FloatingPointType& v,\n                                 const FloatingPointType& u,\n                                 const FloatingPointType& x)\n  {\n    using std::cos;\n    using std::pow;\n    using std::sin;\n\n    // See also the third series representation provided in:\n    // https://functions.wolfram.com/HypergeometricFunctions/LegendreQ2General/06/01/02/\n\n    const FloatingPointType u_pi     = u * boost::math::constants::pi<FloatingPointType>();\n    const FloatingPointType sin_u_pi = sin(u_pi);\n    const FloatingPointType cos_u_pi = cos(u_pi);\n\n    const FloatingPointType one_minus_x          = 1U - x;\n    const FloatingPointType one_plus_x           = 1U + x;\n    const FloatingPointType u_half               = u / 2U;\n    const FloatingPointType one_minus_x_over_two = one_minus_x / 2U;\n\n    const FloatingPointType one_plus_x_over_one_minus_x_pow_u_half = pow(one_plus_x / one_minus_x, u_half);\n\n    const FloatingPointType v_plus_one =  v + 1U;\n\n    const FloatingPointType h2f1_1 = hypergeometric_2f1_regularized(FloatingPointType(-v), v_plus_one, FloatingPointType(1U - u), one_minus_x_over_two);\n    const FloatingPointType h2f1_2 = hypergeometric_2f1_regularized(FloatingPointType(-v), v_plus_one, FloatingPointType(1U + u), one_minus_x_over_two);\n\n    const FloatingPointType term1 = (h2f1_1 * one_plus_x_over_one_minus_x_pow_u_half) * cos_u_pi;\n    const FloatingPointType term2 = (h2f1_2 / one_plus_x_over_one_minus_x_pow_u_half) * pochhammer(FloatingPointType(v_plus_one - u), FloatingPointType(u * 2U));\n\n    return (boost::math::constants::half_pi<FloatingPointType>() * (term1 - term2)) / sin_u_pi;\n  }\n}\n\nbool test___tgamma()\n{\n  const local::big_float_type x(0.5F);\n\n  const local::big_float_type g       = boost::math::tgamma(x);\n  const local::big_float_type sqrt_pi = boost::math::constants::root_pi<local::big_float_type>();\n\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << g       << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << sqrt_pi << std::endl;\n\n  const local::big_float_type ratio = g / sqrt_pi;\n  const local::big_float_type delta = fabs(1 - ratio);\n\n  const bool result_is_ok = delta < std::numeric_limits<local::big_float_type>::epsilon() * 10U;\n\n  return result_is_ok;\n}\n\nbool test_legendre()\n{\n  const local::big_float_type x = local::big_float_type(UINT32_C(789)) / 1000U;\n\n  // Compute some values of the Legendre function of the second kind\n  // on the real axis within the unit circle.\n\n  const local::big_float_type lpvu = local::legendre_pvu(local::big_float_type(local::big_float_type(1U) / 3),\n                                                         local::big_float_type(local::big_float_type(1U) / 7),\n                                                         x);\n\n  const local::big_float_type lqvu = local::legendre_qvu(local::big_float_type(local::big_float_type(1U) / 3),\n                                                         local::big_float_type(local::big_float_type(1U) / 7),\n                                                         x);\n\n  // N[LegendreP[1/3, 1/7, 2, 789/1000], 104]\n  const local::big_float_type control_lpvu\n  {\n    \"0.99315918549340645725680897933376572969241094126736434178747245976770375217673830111149222182128969080027\"\n  };\n\n  // N[LegendreQ[1/3, 1/7, 2, 789/1000], 104]\n  const local::big_float_type control_lqvu\n  {\n    \"0.18027013586354735033576549475861160812128148962186378344662781978695122523958952227406954299821460356031\"\n  };\n\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << lpvu         << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << control_lpvu << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << lqvu         << std::endl;\n  std::cout << std::setprecision(std::numeric_limits<local::big_float_type>::digits10) << control_lqvu << std::endl;\n\n  using std::fabs;\n\n  const local::big_float_type closeness_lpvu = fabs(1 - (lpvu / control_lpvu));\n  const local::big_float_type closeness_lqvu = fabs(1 - (lqvu / control_lqvu));\n\n  const bool result_lpvu_is_ok = (closeness_lpvu < (std::numeric_limits<local::big_float_type>::epsilon() * UINT32_C(10000000)));\n  const bool result_lqvu_is_ok = (closeness_lqvu < (std::numeric_limits<local::big_float_type>::epsilon() * UINT32_C(10000000)));\n\n  const bool result_is_ok = (result_lpvu_is_ok && result_lqvu_is_ok);\n\n  return result_is_ok;\n}\n\nbool test_boost_sf()\n{\n  const bool test_tgamma___is_ok = test___tgamma();\n  const bool test_legendre_is_ok = test_legendre();\n\n  std::cout << \"test_tgamma___is_ok: \" << std::boolalpha << test_tgamma___is_ok << std::endl;\n  std::cout << \"test_legendre_is_ok: \" << std::boolalpha << test_legendre_is_ok << std::endl;\n\n  const bool result_is_ok = (test_tgamma___is_ok && test_legendre_is_ok);\n\n  return result_is_ok;\n}\n", "meta": {"hexsha": "076a948786206c397c4192a870b0c8dc3a7a66b0", "size": 9603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/e_float/test_boost/test_boost_sf.cpp", "max_stars_repo_name": "ckormanyos/e_float-2021", "max_stars_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "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/e_float/test_boost/test_boost_sf.cpp", "max_issues_repo_name": "ckormanyos/e_float-2021", "max_issues_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T14:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:12:27.000Z", "max_forks_repo_path": "libs/e_float/test_boost/test_boost_sf.cpp", "max_forks_repo_name": "ckormanyos/e_float-2021", "max_forks_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "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.6651162791, "max_line_length": 650, "alphanum_fraction": 0.6593772779, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6815996945895881}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main()\n{\n  using namespace boost::numeric::ublas;\n\n  matrix<double> m(3,3);\n\n  for(int i=0; i!=m.size1(); ++i)\n    for(int j=0; j!=m.size2(); ++j)\n      m(i,j)=3*i+j;\n\n  std::cout << trans(m) << std::endl;\n}\n", "meta": {"hexsha": "b9563015728ebd3d588f2efa38209ae972d85620", "size": 293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/matrix-transposition-1.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++/matrix-transposition-1.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++/matrix-transposition-1.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": 18.3125, "max_line_length": 41, "alphanum_fraction": 0.590443686, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6815925084146519}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define BOOST_TEST_MODULE TestTransformReduce\r\n#include <boost/test/unit_test.hpp>\r\n\r\n#include <boost/compute/lambda.hpp>\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/functional.hpp>\r\n#include <boost/compute/algorithm/transform_reduce.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"context_setup.hpp\"\r\n\r\nnamespace compute = boost::compute;\r\n\r\nBOOST_AUTO_TEST_CASE(sum_abs_int_doctest)\r\n{\r\n    using boost::compute::abs;\r\n    using boost::compute::plus;\r\n\r\n    int data[] = { 1, -2, -3, -4, 5 };\r\n    compute::vector<int> vec(data, data + 5, queue);\r\n\r\n//! [sum_abs_int]\r\nint sum = 0;\r\nboost::compute::transform_reduce(\r\n    vec.begin(), vec.end(), &sum, abs<int>(), plus<int>(), queue\r\n);\r\n//! [sum_abs_int]\r\n\r\n    BOOST_CHECK_EQUAL(sum, 15);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(multiply_vector_length)\r\n{\r\n    float data[] = { 2.0f, 0.0f, 0.0f, 0.0f,\r\n                     0.0f, 3.0f, 0.0f, 0.0f,\r\n                     0.0f, 0.0f, 4.0f, 0.0f };\r\n    compute::vector<compute::float4_> vector(\r\n        reinterpret_cast<compute::float4_ *>(data),\r\n        reinterpret_cast<compute::float4_ *>(data) + 3,\r\n        queue\r\n    );\r\n\r\n    float product;\r\n    compute::transform_reduce(\r\n        vector.begin(),\r\n        vector.end(),\r\n        &product,\r\n        compute::length<compute::float4_>(),\r\n        compute::multiplies<float>(),\r\n        queue\r\n    );\r\n    BOOST_CHECK_CLOSE(product, 24.0f, 1e-4f);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(mean_and_std_dev)\r\n{\r\n    using compute::lambda::_1;\r\n    using compute::lambda::pow;\r\n\r\n    float data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\r\n    compute::vector<float> vector(data, data + 10, queue);\r\n\r\n    float sum;\r\n    compute::reduce(\r\n        vector.begin(),\r\n        vector.end(),\r\n        &sum,\r\n        compute::plus<float>(),\r\n        queue\r\n    );\r\n\r\n    float mean = sum / vector.size();\r\n    BOOST_CHECK_CLOSE(mean, 5.5f, 1e-4);\r\n\r\n    compute::transform_reduce(\r\n        vector.begin(),\r\n        vector.end(),\r\n        &sum,\r\n        pow(_1 - mean, 2),\r\n        compute::plus<float>(),\r\n        queue\r\n    );\r\n\r\n    float variance = sum / vector.size();\r\n    BOOST_CHECK_CLOSE(variance, 8.25f, 1e-4);\r\n\r\n    float std_dev = std::sqrt(variance);\r\n    BOOST_CHECK_CLOSE(std_dev, 2.8722813232690143, 1e-4);\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n", "meta": {"hexsha": "78f5cbb64e23abe94eadfe09471b01e6c58aa67f", "size": 2761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/test/test_transform_reduce.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/compute/test/test_transform_reduce.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/compute/test/test_transform_reduce.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": 27.068627451, "max_line_length": 80, "alphanum_fraction": 0.5653748642, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.6815818744699443}}
{"text": "// In this quiz you'll implement the global kinematic model.\n#include <iostream>\n#include <Eigen/Core>\n#include <kinematic.hpp>\n#include <iomanip>\n\nint main() {\n  using Eigen::VectorXd;\n  // [x, y, psi, v]\n  VectorXd state(4);\n  // [delta, v]\n  VectorXd actuators(2);\n\n  state << 0, 0, deg2rad(45), 1;\n  actuators << deg2rad(5), 1;\n\n  // should be [0.212132, 0.212132, 0.798488, 1.3]\n  VectorXd next_state = globalKinematic(state, actuators, 0.3);\n\n  std::cout << next_state << std::endl;\n}\n", "meta": {"hexsha": "4fc7c20c3697f95e568bc99b0391fa9322ed9002", "size": 491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "global_kinematic_model/src/main.cpp", "max_stars_repo_name": "Horki/CarND-MPC-Quizzes", "max_stars_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "global_kinematic_model/src/main.cpp", "max_issues_repo_name": "Horki/CarND-MPC-Quizzes", "max_issues_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "global_kinematic_model/src/main.cpp", "max_forks_repo_name": "Horki/CarND-MPC-Quizzes", "max_forks_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_forks_repo_licenses": ["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.3181818182, "max_line_length": 63, "alphanum_fraction": 0.649694501, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088025362857, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6815630416891174}}
{"text": "\n#ifndef NEURAL_NET_HPP\n#define NEURAL_NET_HPP\n\n#include <Eigen/Dense>\n#include <vector>\n\n//class Sigmoid_Neuron\n//{\n//Sigmoid_Neuron(int input_size,\n//private:\n//Eigen::VectorXd weights;\n//double activation;\n//double bias;\n//};\n\nclass Neural_Net_Functions\n{\n  public:\n    Neural_Net_Functions() {}\n    ~Neural_Net_Functions() {}\n\n    virtual double logistic(const double input) const;\n    virtual double logisticPrime(const double input) const;\n    virtual void vec_logistic(\n        const Eigen::VectorXd &input,\n        Eigen::VectorXd &output) const;\n    virtual void vec_logisticPrime(\n        const Eigen::VectorXd &input,\n        Eigen::VectorXd &output) const;\n    virtual double cost(\n        const Eigen::VectorXd &output,\n        const Eigen::VectorXd &desired_output) const;\n    virtual Eigen::VectorXd costPrime(\n        const Eigen::VectorXd &output,\n        const Eigen::VectorXd &desired_output) const;\n};\n\n\nclass Neural_Net\n{\n  public:\n    Neural_Net(\n        Eigen::VectorXd &weight_sizes,\n        Neural_Net_Functions *functions);\n    ~Neural_Net();\n\n    inline void setInput(Eigen::VectorXd input)\n    {\n      _activations[0] = input;\n    }\n\n    void feedForward();\n\n    double getCost(Eigen::VectorXd desired_output) const;\n    void computeError(Eigen::VectorXd desired_output);\n    //void gradientDescent(\n    void gradientSum();\n    void backPropagation(\n        Eigen::MatrixXd input,\n        Eigen::MatrixXd desired_output);\n\n    void print_neural_net() const;\n    void print_layer(unsigned int layer) const;\n\n  private:\n    unsigned int _layer_size;\n    std::vector<Eigen::MatrixXd> _weights;\n    std::vector<Eigen::VectorXd> _bias;\n    std::vector<Eigen::VectorXd> _activations;\n    std::vector<Eigen::VectorXd> _zs;\n    std::vector<Eigen::VectorXd> _errors;\n    double _gradientSum;\n    Neural_Net_Functions *_functions;\n};\n\n#endif\n\n", "meta": {"hexsha": "78ec57e07224e1577535ab3df2a268016035ddc7", "size": 1861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Neural_Net.hpp", "max_stars_repo_name": "kwon-young/Millenium-Neural-Net", "max_stars_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_stars_repo_licenses": ["MIT"], "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/Neural_Net.hpp", "max_issues_repo_name": "kwon-young/Millenium-Neural-Net", "max_issues_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_issues_repo_licenses": ["MIT"], "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/Neural_Net.hpp", "max_forks_repo_name": "kwon-young/Millenium-Neural-Net", "max_forks_repo_head_hexsha": "c52d3a4ad6fd0b59a89cec95437f58194b039b2c", "max_forks_repo_licenses": ["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.5569620253, "max_line_length": 59, "alphanum_fraction": 0.6878022569, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.8056321843145405, "lm_q1q2_score": 0.6815184410570748}}
{"text": "/*\n * FileName: main.cpp\n * Description: Main program.\n * Copyright (C) 2014  K M Masum Habib <masum.habib@gmail.com>\n * Created: 02 Nov 2014.\n */\n\n#include \"main.h\"\n#include \"config.h\"\n\n#include <iostream>\n#include <string>\n#include <stdexcept>\n\n#include <armadillo>\n\n\n\nusing namespace std;\nusing namespace arma;\n\n/*\n * The main function\n */\nint main(int argc, char** argv) {\n\n    cout << \"Armadillo Minimum Project v\" << ARMAMIN_VERSION << endl;\n\n    mat A = randu<mat>(3,3); // construct a random 3x3 matrix.\n    mat B;\n    B << 1 << 2 << 3 << endr // B = | 1    2    3 |\n      << 4 << 5 << 6 << endr //     | 4    5    6 |\n      << 7 << 8 << 9 << endr;//     | 7    8    8 |\n\n    // print A and B\n    cout << \"A = \" << endl << A << endl;\n    cout << \"B = \" << endl << B << endl;\n    \n    // compute A*B\n    mat C = A*B;\n    // show A*B\n    cout << \"A*B = \" << endl << C << endl;\n    \n    // compute A+B\n    C = A+B;\n    // show A+B\n    cout << \"A+B = \" << endl << C << endl;\n\n    // compute inverse\n    C = solve(A, B);\n    cout << \"A\\\\B = \" << endl << C << endl;\n\n    // Eigenvalue solver\n    cx_vec E = eig_gen(A);\n    cout << \"Eigen values of (A): \" << endl << E << endl;\n\n    \n    return MAIN_SUCCESS;\n}\n\n", "meta": {"hexsha": "a531023debdcd91e13a44b96e9fc97ea8b03d674", "size": 1213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "masumhabib/armamin", "max_stars_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "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/main.cpp", "max_issues_repo_name": "masumhabib/armamin", "max_issues_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "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/main.cpp", "max_forks_repo_name": "masumhabib/armamin", "max_forks_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "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": 19.8852459016, "max_line_length": 69, "alphanum_fraction": 0.4921681781, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6814486479587699}}
{"text": "//\n// Created by moriya on 02/10/17.\n//\n\n#ifndef LIBSCAPI_MATRIX_H\n#define LIBSCAPI_MATRIX_H\n\n#include <iostream>\n#include <NTL/GF2E.h>\n#include <NTL/GF2X.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/GF2XFactoring.h>\n#include <iostream>\n#include <vector>\n#include <array>\n#include <../../include/primitives/Mersenne.hpp>\n\n\nusing namespace NTL;\n\n/**\n * A hyper-invertible matrix is a matrix of which every (non-trivial) square sub-matrix is invertible. Given\n * a hyper-invertible matrix M and vectors x and y satisfying y = M x, then given any |x| components of x\n * and y (any mixture is fine!), one can compute all other components of x and y as a linear function from\n * the given components.\n * Such matrices provide very good diversion and concentration properties: Given a vector x with random-ness in some components;\n * then this very same randomness can be observed in any components of y.\n * Similarly, given a vector x with up to k non-zero elements, then either y will have a non-zero element in\n * each subset of k components, or x is the zero-vector.\n * We present a construction of hyper-invertible matrices and a bunch of applications.\n */\n\nusing namespace std;\nusing namespace NTL;\n\ntemplate <typename FieldType>\nclass HIM {\nprivate:\n    int m_n,m_m;\n    FieldType** m_matrix;\n    TemplateField<FieldType> *field;\npublic:\n\n    /**\n     * This method allocate m-by-n matrix.\n     * m rows, n columns.\n     */\n    HIM(int m, int n, TemplateField<FieldType> *field);\n\n    HIM();\n\n    /**\n     * This method is a construction of a hyper-invertible m-by-n matrix M over a finite field F with |F| \u2265 2n.\n     * Let \u03b11,...,\u03b1n , \u03b21,...,\u03b2m denote fixed distinct elements in F according the vectors alpha and beta,\n     * and consider the function f:Fn \u2192 Fm,\n     * mapping (x1,...,xn) to (y1,...,ym) such that the points (\u03b21,y1),...,(\u03b2m,ym) lie on the polynomial g(\u00b7)\n     * of degree n\u22121 defined by the points (\u03b11,x1),...,(\u03b1n,xn).\n     * Due to the linearity of Lagrange interpolation, f is linear and can be expressed as a matrix:\n     * M = {\u03bbi,j} j=1,...n i=1,...,m\n     * where \u03bb i,j = {multiplication}k=1,..n (\u03b2i\u2212\u03b1k)/(\u03b1j\u2212\u03b1k)\n     */\n    FieldType** InitHIMByVectors(vector<FieldType> &alpha, vector<FieldType> &beta);\n\n    FieldType** InitHIMVectorAndsizes(vector<FieldType> &alpha, int n, int m);\n\n    /**\n     * This method create vectors alpha and beta,\n     * and init the matrix by the method InitHIMByVectors(alpha, beta).\n     */\n    FieldType** InitHIM();\n\n    /**\n     * This method print the matrix\n     */\n    void Print();\n\n    /**\n     * matrix/vector multiplication.\n     * The result is the answer vector.\n     */\n    void MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer);\n\n    void allocate(int m, int n, TemplateField<FieldType> *field);\n\n    virtual ~HIM();\n};\n\n\n\ntemplate <typename FieldType>\nHIM<FieldType>::HIM(){}\n\ntemplate <typename FieldType>\nHIM<FieldType>::HIM(int m, int n, TemplateField<FieldType> *field) {\n    // m rows, n columns\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_m];\n\n    for (int i = 0; i < m_m; i++)\n    {\n        m_matrix[i] = new FieldType[m_n];\n    }\n}\n\ntemplate <typename FieldType>\nFieldType** HIM<FieldType>::InitHIMByVectors(vector<FieldType> &alpha, vector<FieldType> &beta)\n{\n    FieldType lambda;\n\n\n    int m = beta.size();\n    int n = alpha.size();\n    for (int i = 0; i < m; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            // lambda = 1\n            lambda = *(field->GetOne());\n\n            // compute value for matrix[i,j]\n            for (int k = 0; k < n; k++)\n            {\n                if (k == j)\n                {\n                    continue;\n                }\n\n                lambda *= ((beta[i]) - (alpha[k])) / ((alpha[j]) - (alpha[k]));\n            }\n\n            // set the matrix\n            (m_matrix[i][j]) = lambda;\n        }\n    }\n    return m_matrix;\n}\n\n\ntemplate <typename FieldType>\nFieldType** HIM<FieldType>::InitHIMVectorAndsizes(vector<FieldType> &alpha, int n, int m)\n{\n    FieldType lambda;\n\n    for (int i = 0; i < m; i++)\n    {\n        for (int j = 0; j < n; j++)\n        {\n            // lambda = 1\n            lambda = *(field->GetOne());\n\n            // compute value for matrix[i,j]\n            for (int k = 0; k < n; k++)\n            {\n                if (k == j)\n                {\n                    continue;\n                }\n\n                lambda *= ((alpha[n+i]) - (alpha[k])) / ((alpha[j]) - (alpha[k]));\n            }\n\n            // set the matrix\n            (m_matrix[i][j]) = lambda;\n        }\n    }\n    return m_matrix;\n}\n\n\n\ntemplate <typename FieldType>\nvoid HIM<FieldType>::allocate(int m, int n, TemplateField<FieldType> *field)\n{\n    // m rows, n columns\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_m];\n    for (int i = 0; i < m_m; i++)\n    {\n        m_matrix[i] = new FieldType[m_n];\n    }\n}\n\ntemplate <typename FieldType>\nFieldType** HIM<FieldType>::InitHIM()\n{\n    int i;\n    vector<FieldType> alpha(m_n);\n    vector<FieldType> beta(m_m);\n\n    // check if valid\n    if (256 <= m_m+m_n)\n    {\n        cout << \"error\";\n    }\n\n    // Let alpha_j and beta_i be arbitrary field elements\n    for (i = 0; i < m_n; i++)\n    {\n        alpha[i] = field->GetElement(i);\n    }\n\n    for (i = 0; i < m_m; i++)\n    {\n        beta[i] = field->GetElement(m_n+i);\n    }\n\n    return(InitHIMByVectors(alpha,beta));\n}\n\ntemplate <typename FieldType>\nvoid HIM<FieldType>::Print()\n{\n    for (int i = 0; i < m_m; i++) {\n        for (int j = 0; j < m_n; j++) {\n            cout << (m_matrix[i][j]) << \" \";\n        }\n\n        cout << \" \" << '\\n';\n    }\n\n}\n\ntemplate <typename FieldType>\nvoid HIM<FieldType>::MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer)\n{\n    FieldType temp1;\n    for(int i = 0; i < m_m; i++)\n    {\n        // answer[i] = 0\n        answer[i] = *(field->GetZero());\n\n        for(int j=0; j < m_n; j++)\n        {\n            temp1 = m_matrix[i][j] * vector[j];\n            //answer[i] = answer[i] + temp1;\n            answer[i] += temp1;\n        }\n    }\n}\n\ntemplate <typename FieldType>\nHIM<FieldType>::~HIM() {\n    for (int i = 0; i < m_m; i++)\n    {\n        delete[] m_matrix[i];\n    }\n    delete[] m_matrix;\n}\n\ntemplate<typename FieldType>\nclass VDM {\nprivate:\n    int m_n,m_m;\n    FieldType** m_matrix;\n    TemplateField<FieldType> *field;\npublic:\n    VDM(int n, int m, TemplateField<FieldType> *field);\n    VDM() {};\n    ~VDM();\n    void InitVDM();\n    void Print();\n    void MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer, int length);\n\n    void allocate(int n, int m, TemplateField<FieldType> *field);\n};\n\n\ntemplate<typename FieldType>\nVDM<FieldType>::VDM(int n, int m, TemplateField<FieldType> *field) {\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_n];\n    for (int i = 0; i < m_n; i++)\n    {\n        m_matrix[i] = new FieldType[m_m];\n    }\n}\n\ntemplate<typename FieldType>\nvoid VDM<FieldType>::allocate(int n, int m, TemplateField<FieldType> *field) {\n\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_n];\n    for (int i = 0; i < m_n; i++)\n    {\n        m_matrix[i] = new FieldType[m_m];\n    }\n}\n\ntemplate<typename FieldType>\nvoid VDM<FieldType>::InitVDM() {\n    vector<FieldType> alpha(m_n);\n    for (int i = 0; i < m_n; i++) {\n        alpha[i] = field->GetElement(i + 1);\n    }\n\n    for (int i = 0; i < m_n; i++) {\n        m_matrix[i][0] = *(field->GetOne());\n        for (int k = 1; k < m_m; k++) {\n            m_matrix[i][k] = m_matrix[i][k - 1] * (alpha[i]);\n        }\n    }\n}\n\n/**\n * the function print the matrix\n */\ntemplate<typename FieldType>\nvoid VDM<FieldType>::Print()\n{\n    for (int i = 0; i < m_n; i++)\n    {\n        for(int j = 0; j < m_m; j++)\n        {\n            cout << (m_matrix[i][j]) << \" \";\n\n        }\n        cout << \" \" << '\\n';\n    }\n\n}\n\ntemplate<typename FieldType>\nvoid VDM<FieldType>::MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer, int length)\n{\n    for(int i = 0; i < m_n; i++)\n    {\n        // answer[i] = 0\n        answer[i] = *(field->GetZero());\n\n        for(int j=0; j < length; j++)\n        {\n            answer[i] += (m_matrix[i][j] * vector[j]);\n        }\n    }\n\n}\n//\ntemplate<typename FieldType>\nVDM<FieldType>::~VDM() {\n    for (int i = 0; i < m_n; i++) {\n        delete[] m_matrix[i];\n    }\n    delete[] m_matrix;\n}\n\ntemplate<typename FieldType>\nclass VDMTranspose {\nprivate:\n    int m_n,m_m;\n    FieldType** m_matrix;\n    TemplateField<FieldType> *field;\npublic:\n    VDMTranspose(int n, int m, TemplateField<FieldType> *field);\n    VDMTranspose() {};\n    ~VDMTranspose();\n    void InitVDMTranspose();\n    void Print();\n    void MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer, int length);\n\n    void allocate(int n, int m, TemplateField<FieldType> *field);\n};\n\n\ntemplate<typename FieldType>\nVDMTranspose<FieldType>::VDMTranspose(int n, int m, TemplateField<FieldType> *field) {\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_n];\n    for (int i = 0; i < m_n; i++)\n    {\n        m_matrix[i] = new FieldType[m_m];\n    }\n}\n\ntemplate<typename FieldType>\nvoid VDMTranspose<FieldType>::allocate(int n, int m, TemplateField<FieldType> *field) {\n\n    this->m_m = m;\n    this->m_n = n;\n    this->field = field;\n    this->m_matrix = new FieldType*[m_n];\n    for (int i = 0; i < m_n; i++)\n    {\n        m_matrix[i] = new FieldType[m_m];\n    }\n}\n\ntemplate<typename FieldType>\nvoid VDMTranspose<FieldType>::InitVDMTranspose() {\n    vector<FieldType> alpha(m_m);\n    for (int i = 0; i < m_m; i++) {\n        alpha[i] = field->GetElement(i + 1);\n    }\n\n    for (int i = 0; i < m_m; i++) {\n        m_matrix[0][i] = *(field->GetOne());\n        for (int k = 1; k < m_n; k++) {\n            m_matrix[k][i] = m_matrix[k-1][i] * (alpha[k]);\n        }\n    }\n}\n\n/**\n * the function print the matrix\n */\ntemplate<typename FieldType>\nvoid VDMTranspose<FieldType>::Print()\n{\n    for (int i = 0; i < m_m; i++)\n    {\n        for(int j = 0; j < m_n; j++)\n        {\n            cout << (m_matrix[i][j]) << \" \";\n\n        }\n        cout << \" \" << '\\n';\n    }\n\n}\n\ntemplate<typename FieldType>\nvoid VDMTranspose<FieldType>::MatrixMult(std::vector<FieldType> &vector, std::vector<FieldType> &answer, int length)\n{\n    for(int i = 0; i < length; i++)\n    {\n        // answer[i] = 0\n        answer[i] = *(field->GetZero());\n\n        for(int j=0; j < m_m; j++)\n        {\n            answer[i] += (m_matrix[i][j] * vector[j]);\n        }\n    }\n\n}\n\n\n//\ntemplate<typename FieldType>\nVDMTranspose<FieldType>::~VDMTranspose() {\n    for (int i = 0; i < m_n; i++) {\n        delete[] m_matrix[i];\n    }\n    delete[] m_matrix;\n}\n\n\n\n#endif //LIBSCAPI_MATRIX_H\n", "meta": {"hexsha": "715038688ee5c30d64b491c7cd27d5b8d56316fd", "size": 10904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/primitives/Matrix.hpp", "max_stars_repo_name": "manel1874/libscapi", "max_stars_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "include/primitives/Matrix.hpp", "max_issues_repo_name": "cryptobiu/libscapi", "max_issues_repo_head_hexsha": "49eee7aee9eb3544a7facb199d0a6e98097b058a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "include/primitives/Matrix.hpp", "max_forks_repo_name": "manel1874/libscapi", "max_forks_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 23.7559912854, "max_line_length": 128, "alphanum_fraction": 0.5586023478, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.681349120014949}}
{"text": "#include <cassert>\n#include <cmath>\n#include <vector>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n\n// https://stackoverflow.com/a/24519913\ntemplate <typename T>\nstd::vector<T> full_convolve(const std::vector<T> &f, const std::vector<T> &g) {\n    const int nf = f.size();\n    const int ng = g.size();\n    const int n = nf + ng - 1;\n    std::vector<T> ret(n, T());\n    for (int i = 0; i < n; ++i) {\n        const int jmin = (i >= ng - 1)? i - (ng - 1) : 0;\n        const int jmax = (i <  nf - 1)? i            : nf - 1;\n        for(int j = jmin; j <= jmax; ++j) {\n            ret[i] += (f[j] * g[i - j]);\n        }\n    }\n    return ret;\n}\n\n\ntemplate <typename T>\nclass Lagrange {\npublic:\n    Lagrange(const std::vector<T> &x, const std::vector<T> &w) :\n        coefficients()\n    {\n        assert(x.size() == w.size());\n        std::vector<T> p;\n        p.push_back(0.0);\n        for (std::size_t j = 0; j < x.size(); ++j) {\n            std::vector<T> pt;\n            pt.push_back(w[j]);\n            for (std::size_t k = 0; k < x.size(); ++k) {\n                if (k == j) {\n                    continue;\n                }\n                T fac = x[j] - x[k];\n                std::vector<T> poly;\n                poly.push_back(1.0 / fac);\n                poly.push_back(-x[k] / fac);\n                pt = full_convolve(pt, poly);\n            }\n            p = add(p, pt);\n        }\n        coefficients = p;\n    }\n\n    T operator ()(const T &x) const {\n        assert(coefficients.size() > 0);\n        T result = 0.0;\n        std::size_t d = coefficients.size() - 1;\n        for (std::size_t i = 0; i < d; ++i) {\n            // result += std::pow(x, d) * coefficients[i];\n            result += coefficients[i];\n            result *= x;\n        }\n        result += coefficients[d];\n        return result;\n    }\n\n    std::vector<T> add(const std::vector<T> &a, const std::vector<T> &b) const {\n        int diff = a.size() - b.size();\n        if ( diff == 0 ) {\n            std::vector<T> result;\n            for (std::size_t i = 0; i < a.size(); ++i) {\n                result.push_back(a[i] + b[i]);\n            }\n            return result;\n        } else if ( diff > 0 ) {\n            std::vector<T> new_b(diff, 0);\n            new_b.reserve(diff + b.size());\n            new_b.insert(new_b.end(), b.begin(), b.end());\n            return add(a, new_b);\n        } else {\n            std::vector<T> new_a(-diff, 0);\n            new_a.reserve(-diff + a.size());\n            new_a.insert(new_a.end(), a.begin(), a.end());\n            return add(new_a, b);\n        }\n    }\n\n    std::vector<T> coefficients;\n\n    static T fast(T x, const std::vector<T> &xs, const std::vector<T> &ws) {\n        assert(xs.size() == ws.size());\n        T result = 0.0;\n        for (std::size_t j = 0; j < xs.size(); ++j) {\n            T n = 1.0, d = 1.0;\n            for (std::size_t k = 0; k < xs.size(); ++k) {\n                if ( j == k ) {\n                    continue;\n                }\n                n *= x     - xs[k];\n                d *= xs[j] - xs[k];\n            }\n            result += ws[j] * (n / d);\n        }\n        return result;\n    }\n\n};\n\n\ntemplate <typename T>\nclass DeltaLagrange {\npublic:\n    DeltaLagrange(const std::vector<T> &x, const std::vector<T> &w) :\n        x0(x[0]),\n        w0(w[0]),\n        coefficients()\n    {\n        assert(x.size() == w.size());\n        std::vector<T> p;\n        p.push_back(0.0);\n        for (std::size_t j = 0; j < x.size(); ++j) {\n            std::vector<T> pt;\n            pt.push_back(w[j] - w0);\n            auto xj = x[j] - x0;\n            for (std::size_t k = 0; k < x.size(); ++k) {\n                if (k == j) {\n                    continue;\n                }\n                auto xk = x[k] - x0;\n                T fac = xj - xk;\n                std::vector<T> poly;\n                poly.push_back(1.0 / fac);\n                poly.push_back(-xk / fac);\n                pt = full_convolve(pt, poly);\n            }\n            p = add(p, pt);\n        }\n        coefficients = p;\n    }\n\n    T operator ()(const T &x) const {\n        assert(coefficients.size() > 0);\n        T result = 0.0;\n        auto xd = x - x0;\n        std::size_t d = coefficients.size() - 1;\n        for (std::size_t i = 0; i < d; ++i) {\n            // result += std::pow(x, d) * coefficients[i];\n            result += coefficients[i];\n            result *= xd;\n        }\n        result += coefficients[d];\n        return result + w0;\n    }\n\n    std::vector<T> add(const std::vector<T> &a, const std::vector<T> &b) const {\n        int diff = a.size() - b.size();\n        if ( diff == 0 ) {\n            std::vector<T> result;\n            for (std::size_t i = 0; i < a.size(); ++i) {\n                result.push_back(a[i] + b[i]);\n            }\n            return result;\n        } else if ( diff > 0 ) {\n            std::vector<T> new_b(diff, 0);\n            new_b.reserve(diff + b.size());\n            new_b.insert(new_b.end(), b.begin(), b.end());\n            return add(a, new_b);\n        } else {\n            std::vector<T> new_a(-diff, 0);\n            new_a.reserve(-diff + a.size());\n            new_a.insert(new_a.end(), a.begin(), a.end());\n            return add(new_a, b);\n        }\n    }\n\n    T x0;\n    T w0;\n    std::vector<T> coefficients;\n\n};\n\n", "meta": {"hexsha": "1ccb02e326c05f984534817bc2b0ac8a8e3eb76a", "size": 5277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lagrange.hpp", "max_stars_repo_name": "mugwort-rc/boost_python_lagrange", "max_stars_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "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/lagrange.hpp", "max_issues_repo_name": "mugwort-rc/boost_python_lagrange", "max_issues_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "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/lagrange.hpp", "max_forks_repo_name": "mugwort-rc/boost_python_lagrange", "max_forks_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "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.1546961326, "max_line_length": 80, "alphanum_fraction": 0.4223990904, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.681349115096773}}
{"text": "///2\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <vector>\n#include <iostream>\n#include <queue>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/bipartite.hpp>\n\n// Epic kernel is enough, no constructions needed, provided the squared distance\n// fits into a double (!)\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n// we want to store an index with each vertex\ntypedef std::size_t                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Delaunay;\n\n// BGL Graph definitions\n// =====================\n// Graph Type, OutEdgeList Type, VertexList Type, (un)directedS\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS    // Use vecS for the VertexList! Choosing setS for the OutEdgeList disallows parallel edges.\n    >          graph;\ntypedef boost::graph_traits<graph>::vertex_descriptor    vertex_desc;    // Vertex Descriptor: with vecS vertex list, this is really just an int in the range [0, num_vertices(G)).  \ntypedef boost::graph_traits<graph>::edge_iterator    edge_it;    // to iterate over all edges\ntypedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;\n// Coloring definitions\ntypedef std::vector< boost::default_color_type > partition_t;\n\n\n\nvoid testcase() {\n  Index n, m;\n  double r;\n  std::cin >> n >> m >> r;\n  \n  // read points: first, we read all points and store them into a vector,\n  // together with their indices\n  typedef std::pair<K::Point_2,Index> IPoint;\n  std::vector<IPoint> points;\n  points.reserve(n);\n  for (Index i = 0; i < n; ++i) {\n    int x, y;\n    std::cin >> x >> y;\n    points.emplace_back(K::Point_2(x, y), i);\n  }\n  \n  Delaunay t;\n  t.insert(points.begin(), points.end());\n  \n  graph G(n);\n  for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n    Index i1 = e->first->vertex((e->second+1)%3)->info();\n    Index i2 = e->first->vertex((e->second+2)%3)->info();\n    if(t.segment(e).squared_length() <= r * r) {\n      boost::add_edge(int(i1), int(i2), G);\n    }\n  }\n   \n  // check for bipartiteness of the graph with *only* the delaunay edges\n  partition_t partition(n); \n  bool without_interference = boost::is_bipartite(G, boost::get(boost::vertex_index, G), \n        boost::make_iterator_property_map(partition.begin(), boost::get(boost::vertex_index, G)));\n  if(without_interference) {\n    // if bipartite only with delaunay edges, we can use the coloring found by BGL\n    // to create one triangulation for each color. Since same colored points should\n    // not be closer than r to each other, this new triangulation should not include small edges  \n    std::vector<K::Point_2> points_1;\n    std::vector<K::Point_2> points_2;\n    for(auto v = t.finite_vertices_begin(); v != t.finite_vertices_end(); ++v) {\n        Index i = v->info();\n        if(partition[i] == boost::color_traits<boost::default_color_type>::white()) {\n            points_1.push_back(v->point());\n        } else {\n            points_2.push_back(v->point());\n        }\n    }\n\n    for(int i = 0; i < 2; i++) {\n        if(!without_interference) break;\n        Delaunay ti;\n        if(i == 0) ti.insert(points_1.begin(), points_1.end());\n        else ti.insert(points_2.begin(), points_2.end());\n        // loop through edges\n        for (auto e = ti.finite_edges_begin(); e != ti.finite_edges_end(); ++e) {\n            if(t.segment(e).squared_length() <= r * r) {\n                without_interference = false;\n                break;\n            }\n        }\n    }\n  }\n  \n  \n  std::vector<int> component_map(n);\t// We MUST use such a vector as an Exterior Property Map: Vertex -> Component\n  boost::connected_components(G,\n        boost::make_iterator_property_map(component_map.begin(), boost::get(boost::vertex_index, G))); \n\n\n  for(Index i = 0; i < m; i++) {\n    int a0, a1, b0, b1;\n    std::cin >> a0 >> a1 >> b0 >> b1;\n    if(!without_interference) {\n        std::cout << \"n\";\n        continue;\n    }\n    K::Point_2 a = K::Point_2(a0, a1);\n    K::Point_2 b = K::Point_2(b0, b1);\n    \n    if(CGAL::squared_distance(a, b) <= r * r) {\n      std::cout << \"y\";\n      continue;\n    }\n    auto vertex_a = t.nearest_vertex(a);\n    auto vertex_b = t.nearest_vertex(b);\n    \n    if(CGAL::squared_distance(a, vertex_a->point()) > r * r || CGAL::squared_distance(b, vertex_b->point()) > r * r) {\n        std::cout << \"n\";\n        continue;\n    }\n    \n    int va = vertex_a->info();\n    int vb = vertex_b->info();\n    if(component_map[va] == component_map[vb]) {\n        std::cout << \"y\";\n        continue;\n    } else {\n        std::cout << \"n\";\n        continue;\n    }\n  }\n  \n  std::cout << \"\\n\";\n  \n}\n\nint main() \n{\n  std::ios_base::sync_with_stdio(false);\n  std::size_t t;\n  for (std::cin >> t; t > 0; --t) testcase();\n  return 0;\n}\n", "meta": {"hexsha": "443ceacba38897ab5908b9513251a91540523ea4", "size": 5202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week13-potw-clues/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/week13-potw-clues/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/week13-potw-clues/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": 35.1486486486, "max_line_length": 181, "alphanum_fraction": 0.6259131103, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6812386906441984}}
{"text": "/*\n *      Author:     Jonathan Bober\n *      Version:    .6\n *\n *      This program computes p(n), the number of integer partitions of n, using Rademacher's\n *      formula. (See Hans Rademacher, On the Partition Function p(n),\n *      Proceedings of the London Mathematical Society 1938 s2-43(4):241-254; doi:10.1112/plms/s2-43.4.241,\n *      currently at\n *\n *      http://plms.oxfordjournals.org/cgi/content/citation/s2-43/4/241\n *\n *      if you have access.)\n *\n *      We use the following notation:\n *\n *      p(n) = lim_{n --> oo} t(n,N)\n *\n *      where\n *\n *      t(n,N) = sum_{k=1}^N a(n,k) f_n(k),\n *\n *      where\n *\n *      a(n,k) = sum_{h=1, (h,k) = 1}^k exp(\\pi i s(h,k) - 2 \\pi i h  n / k)\n *\n *      and\n *\n *      f_n(k) = \\pi sqrt{2} cosh(A_n/(sqrt{3}*k))/(B_n*k) - sinh(C_n/k)/D_n;\n *\n *      where\n *\n *      s(h,k) = \\sum_{j=1}^{k-1}(j/k)((hj/k))\n *\n *      A_n = sqrt{2} \\pi * sqrt{n - 1/24}\n *      B_n = 2 * sqrt{3} * (n - 1/24)\n *      C_n = sqrt{2} * \\pi * sqrt{n - 1.0/24.0} / sqrt{3}\n *      D_n = 2 * (n - 1/24) * sqrt{n - 1.0/24.0}\n *\n *      and, finally, where ((x)) is the sawtooth function ((x)) = {x} - 1/2 if x is not an integer, 0 otherwise.\n *\n *      Some clever tricks are used in the computation of s(h,k), and perhaps at least\n *      some of these are due to Apostol. (I don't know a reference for this.)\n *\n *      TODO:\n *\n *          -- Search source code for other TODO comments.\n *\n *      OTHER CREDITS:\n *\n *      I looked source code written by Ralf Stephan, currently available at\n *\n *              http://www.ark.in-berlin.de/part.c\n *\n *      while writing this code, but didn't really make use of it.\n *      Maybe we could use the function cospi() instead of mpfr_cos()\n *      but there seems to be no gain in doing that.\n *\n *      More useful were notes currently available at\n *\n *              http://www.ark.in-berlin.de/part.pdf\n *\n *      and others at\n *\n *              http://www.math.uwaterloo.ca/~dmjackso/CO630/ptnform1.pdf\n *\n *      Also, Bill Hart made some comments about ways to speed up this computation on the SAGE\n *      mailing list.\n *\n *      A big clean up of this file was done by Jeroen Demeyer in\n *      https://trac.sagemath.org/ticket/24667\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, see <https://www.gnu.org/licenses/>.\n */\n\n#include <stdio.h>\n#include <cfloat>\n#include <time.h>\n\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n\n#include <iostream>\n#include <iomanip>\n#include <limits>\n\n#include <gmp.h>\n#include <mpfr.h>\n#include <NTL/ZZ.h>\n\nusing namespace std;\nusing NTL::GCD;\n\n\n/*****************************************************************************\n *\n *      We begin be declaring all the constant global variables.\n *\n ****************************************************************************/\n\n// First, some variables that can be set to have the program\n// output some information that might be useful for debugging.\n\nconst bool debug = false;                                       // If true, output some random stuff\n\nconst bool debug_precision = false;                             // If true, output information that might be useful for\n                                                                // debugging the precision setting code.\n\nconst bool debugf = false;                                      // Same for the f() functions.\nconst bool debuga = false;                                      // Same for the a() functions.\nconst bool debugt = false;                                      // Same for the t() functions.\n\n#if FLT_RADIX != 2\n#error \"I don't know what to do when the float radix is not 2\"\n#endif\n// Note - it might be unreasonable to not support a float radix other than\n// 2, but apparently gcc doesn't either. See http://gcc.gnu.org/ml/fortran/2006-12/msg00032.html\n\n\nconst unsigned int min_precision = DBL_MANT_DIG;                            // The minimum precision that we will ever use.\nconst unsigned int double_precision = DBL_MANT_DIG;                         // The assumed precision of a double.\n\n\n#if defined(__sparc) || defined(__CYGWIN__) || defined(__FreeBSD__)\n// On sparc solaris long double is bad/broken/different, etc.  E.g.,\n// LDBL_MANT_DIG is 113 rather than 106, which causes all kinds of trouble.\n// So we only use double_precision.\nconst unsigned int long_double_precision = double_precision;\n#else\nconst unsigned int long_double_precision = (LDBL_MANT_DIG == 106) ? double_precision : LDBL_MANT_DIG;\n#endif\n                                                                            // The assumed precision of a long double.\n                                                                            // Note: On many systems double_precision = long_double_precision. This is OK, as\n                                                                            // the long double stage of the computation will just be skipped.\n\n// Second, some constants that control the precision at which we compute.\n\n// When we compute the terms of the Rademacher series, we start by computing with\n// mpfr_t variables. But for efficiency we switch to special purpose code when\n// we don't need as much precision. These constants control the various\n// precision levels at which we switch to different special\n// purpose functions.\nconst unsigned int level_two_precision = long_double_precision;\nconst unsigned int level_five_precision = double_precision;\n\n// Third, the rounding mode for mpfr.\nconst mpfr_rnd_t round_mode = MPFR_RNDN;\n\n/*****************************************************************************\n *\n *  We are finished declaring constants, and next declare semi-constant\n *  variables. These are all set just once per call to part(n).\n *\n *  All of these are set in initialize_globals(), and\n *  cleared in clear_globals().\n *\n ****************************************************************************/\n\nmpfr_t mp_sqrt2, mp_sqrt3, mp_pi;                       // These need to be set at run time\n                                                        // because we don't know how much precision we will need\n                                                        // until we know for what n we are computing p(n).\n\nmpfr_t mp_A, mp_B, mp_C, mp_D;                          // These \"constants\" all depend on n\ndouble d_pi, d_A, d_B, d_C, d_D;\nlong double ld_pi, ld_A, ld_B, ld_C, ld_D;\n\n\n/*****************************************************************************\n *\n * We next declare the variables that actually vary. It is cumbersome to have\n * so many global variables, but it is somewhat necessary since we want to call\n * the functions mpz_init(), mpq_init(), mpfr_init(), and the corresponding\n * clear() functions as little as possible.\n *\n ****************************************************************************/\n\n// These are initialized in the function initialize_globals()\n// and cleared in clear_globals().\nmpq_t qtemps, qtempa, qtempa2;\nmpfr_t mptemp;\n\n\n/*****************************************************************************\n *\n * End of Global Variables, beginning of function declarations\n *\n ****************************************************************************/\n\n// A listing of the main functions, in \"conceptual\" order.\nvoid part(mpz_t answer, unsigned int n);\n\nstatic void mp_t(mpfr_t result, unsigned int n);                                // Compute t(n,N) for an N large enough, and with a high enough precision, so that\n                                                                                // |p(n) - t(n,N)| < .5\n\nstatic unsigned int compute_initial_precision(unsigned int n);                  // computes the precision required to accurately compute p(n)\n\nstatic void initialize_globals(mp_prec_t prec, unsigned int n);                 // Once we know the precision that we will need, we precompute\n                                                                                // some commonly used constants.\n\nstatic unsigned int compute_current_precision(unsigned int n, unsigned int N, unsigned int extra);  // Computed the precision required to\n                                                                                // accurately compute the tail of the rademacher series\n                                                                                // assuming that N terms have already been computed.\n                                                                                // This is called after computing each summand, unless\n                                                                                // we have already reached the minimum precision.\n\n                                                                                // Reducing the precision as fast as possible is key to\n                                                                                // fast performance.\n\nstatic double compute_remainder(unsigned int n, unsigned int N);                // Gives an upper bound on the error that occurs\n                                                                                // when only N terms of the Rademacher series have been\n                                                                                // computed.\n\n                                                                                // This should only be called when we know that compute_current_precision\n                                                                                // will return min_precision. Otherwise the error will be too large for\n                                                                                // it to compute.\n\nstatic void mp_f(mpfr_t result, unsigned int k);                                // See introduction for an explanation of these functions.\nstatic void q_s(mpq_t result, unsigned int h, unsigned int k);\nstatic void mp_a(mpfr_t result, unsigned int n, unsigned int k);\n\ntemplate <class T> static inline T a(unsigned int n, unsigned int k);           // Template versions of the above functions for computing with\ntemplate <class T> static inline T f(unsigned int k);                           // low precision. Currently used for computing with\ntemplate <class T> static inline T s(unsigned int h, unsigned int k);           // long double, and double.\n\n\n// The following are a bunch of \"fancy macros\" designed so that in the templated code\n// for a, for example, when we need to use pi, we just call pi<T>() to get pi to\n// the proper precision. The compiler should inline these, so using one of these\n// functions is just as good as using a constant, and since these functions are static\n// they shouldn't even appear in the object code generated.\ntemplate <class T> static inline T sqrt2() {return sqrt(T(2));}\ntemplate <class T> static inline T sqrt3() {return sqrt(T(3));}\n\ntemplate <class T> static inline T pi() {return T(d_pi);}\ntemplate <> inline long double pi() {return ld_pi;}\n\ntemplate <class T> static inline T A() {return T(d_A);}\ntemplate <> inline long double A() {return ld_A;}\n\ntemplate <class T> static inline T B() {return T(d_B);}\ntemplate <> inline long double B() {return ld_B;}\n\ntemplate <class T> static inline T C() {return T(d_C);}\ntemplate <> inline long double C() {return ld_C;}\n\ntemplate <class T> static inline T D() {return T(d_D);}\ntemplate <> inline long double D() {return ld_D;}\n\ntemplate <class T> static inline T pi_sqrt2() {return pi<T>() * sqrt(T(2));}\n\ntemplate <class T> static inline T one_over_12() {return T(1)/T(12);}\n\n// A few utility functions...\n\nint test(bool longtest = false, bool forever = false);                          // Runs a bunch of tests to make sure\n                                                                                // that we are getting the right answers.\n                                                                                // Tests are based on a few \"known\" values that\n                                                                                // have been verified by other programs, and\n                                                                                // also on known congruences for p(n)\n\nstatic int grab_last_digits(char * output, int n, mpfr_t x);                    // Might be useful for debugging, but\n                                                                                // don't use it for anything else.\n                                                                                // (See function definition for more information.)\n\n/***********************************************************************\n *\n * That should be the end of both function and variable definitions.\n *\n **********************************************************************/\n\n// The following function can be useful for debugging in come circumstances, but should not be used for anything else\n// unless it is rewritten.\nstatic int grab_last_digits(char * output, int n, mpfr_t x) {\n    // fill output with the n digits of x that occur\n    // just before the decimal point\n    // Note: this assumes that x has enough digits and enough\n    // precision -- otherwise bad things can happen\n\n    // returns: the number of digits to the right of the decimal point\n\n    char * temp;\n    mp_exp_t e;\n\n    temp = mpfr_get_str(NULL, &e, 10, 0, x, MPFR_RNDN);\n\n    int retval;\n\n    if (e > 0) {\n        strncpy(output, temp + e - n, n);\n        retval =  strlen(temp + e);\n    }\n    else {\n        for (int i = 0; i < n; i++)\n            output[i] = '0';\n        retval = strlen(temp);\n    }\n    output[n] = '\\0';\n\n    mpfr_free_str(temp);\n\n    return retval;\n}\n\n\nstatic unsigned int compute_initial_precision(unsigned int n) {\n    // We just want to know how many bits we will need to\n    // compute to get an accurate answer.\n\n    // We know that\n\n    //          p(n) ~ exp(pi * sqrt(2n/3))/(4n sqrt(3)),\n\n    // so for now we are assuming that p(n) < exp(pi * sqrt(2n/3))/n,\n    // so we need pi*sqrt(2n/3)/log(2) - log(n)/log(2) + EXTRA bits.\n\n    // EXTRA should depend on n, and should be something that ensures\n    // that the TOTAL ERROR in all computations is < (something small).\n    // This needs to be worked out carefully. EXTRA = log(n)/log(2) + 3\n    // is probably good enough, and is convenient...\n\n    // but we really need:\n\n    //                  p(n) < something\n\n    // to be sure that we compute the correct answer\n\n    unsigned int result = (unsigned int)(ceil(3.1415926535897931 * sqrt(2.0 * double(n)/ 3.0) / log(2))) + 3;\n    if (debug) cout << \"Using initial precision of \" << result << \" bits.\" << endl;\n\n    if (result <= min_precision)\n        result = min_precision;\n\n    return result;\n}\n\n\nstatic unsigned int compute_current_precision(unsigned int n, unsigned int N, unsigned int extra = 0) {\n    // Roughly, we compute\n\n    //      log(A/sqrt(N) + B*sqrt(N/(n-1))*sinh(C * sqrt(n) / N) / log(2)\n\n    // where A, B, and C are the constants listed below. These error bounds\n    // are given in the paper by Rademacher listed at the top of this file.\n    // We then return this + extra, if extra != 0. If extra == 0, return with\n    // what is probably way more extra precision than is needed.\n\n    // extra should probably have been set by a call to compute_extra_precision()\n    // before this function was called.\n\n    // n = the number for which we are computing p(n)\n    // N = the number of terms that have been computed so far\n\n    // if N is 0, then we can't use the above formula (because we would be\n    // dividing by 0).\n    if (N == 0) return compute_initial_precision(n) + extra;\n\n    mpfr_t A, B, C;\n    mpfr_init2(A, 32);\n    mpfr_init2(B, 32);\n    mpfr_init2(C, 32);\n\n    mpfr_set_d(A, 1.11431833485164, MPFR_RNDN);\n    mpfr_set_d(B, 0.059238439175445, MPFR_RNDN);\n    mpfr_set_d(C, 2.5650996603238, MPFR_RNDN);\n\n    mpfr_t error, t1, t2;\n    mpfr_init2(error, 32);                                // we shouldn't need much precision here since we just need the most significant bit\n    mpfr_init2(t1, 32);\n    mpfr_init2(t2, 32);\n\n    mpfr_set(error, A, MPFR_RNDF);                        // error = A\n    mpfr_sqrt_ui(t1, N, MPFR_RNDF);                       // t1 = sqrt(N)\n    mpfr_div(error, error, t1, MPFR_RNDF);                // error = A/sqrt(N)\n\n    mpfr_sqrt_ui(t1, n, MPFR_RNDF);                       // t1 = sqrt(n)\n    mpfr_mul(t1, t1, C, MPFR_RNDF);                       // t1 = C * sqrt(n)\n    mpfr_div_ui(t1, t1, N, MPFR_RNDF);                    // t1 = C * sqrt(n) / N\n    mpfr_sinh(t1, t1, MPFR_RNDF);                         // t1 = sinh( ditto )\n    mpfr_mul(t1, t1, B, MPFR_RNDF);                       // t1 = B * sinh( ditto )\n\n    mpfr_set_ui(t2, N, MPFR_RNDF);                        // t2 = N\n    mpfr_div_ui(t2, t2, n-1, MPFR_RNDF);                  // t2 = N/(n-1)\n    mpfr_sqrt(t2, t2, MPFR_RNDF);                         // t2 = sqrt( ditto )\n\n    mpfr_fma(error, t1, t2, error, MPFR_RNDF);            // error += t1 * t2 (= ERROR ESTIMATE)\n\n    // the number of bits required to hold the integer part of the error\n    unsigned int p = mpfr_get_exp(error);\n\n    if (extra == 0) {\n        // Stupid fall back case\n        extra = ceil(log(n)/log(2));\n    }\n\n    p += extra;                                           // Recall that the extra precision should be\n                                                          // large enough so that the accumulated errors\n                                                          // in all of the computations that we make\n                                                          // are not big enough to matter.\n    if (debug) {\n        cout << \"Error seems to be: \";\n        mpfr_out_str(stdout, 10, 0, error, round_mode);\n        cout << endl;\n        cout.flush();\n        cout << \"Switching to precision of \" << p << \" bits. \" << endl;\n    }\n\n    mpfr_clear(error);\n    mpfr_clear(t1);\n    mpfr_clear(t2);\n    mpfr_clear(A);\n    mpfr_clear(B);\n    mpfr_clear(C);\n\n    if (p <= min_precision)                               // We don't want to return < min_precision.\n        p = min_precision;                                // Note that when the code that calls this\n                                                          // function finds that the returned result\n                                                          // is min_precision, it should stop calling\n                                                          // this function, since the result won't change\n                                                          // after that. Also, it should probably switch\n                                                          // to computations with doubles, and should\n                                                          // start calling compute_remainder().\n    return p;\n}\n\n\nstatic int compute_extra_precision(unsigned int n, double error = .25) {\n    // Return the number of terms of the Rachemacher series that\n    // we will need to compute to get a remainder of less than error\n    // in absolute value, and then return the extra precision\n    // that will guarantee that the accumulated error after computing\n    // that number of steps will be less than .5 - error.\n\n    // How this works:\n    // We first need to figure out how many terms of the series we are going to\n    // need to compute. That is, we need to know how large k needs to be\n    // for compute_remainder(n,k) to return something smaller than error. There\n    // might be a clever way to do this, but instead we just keep calling\n    // compute_current_precision() until we know that the error will be\n    // small enough to call compute_remainder(). Then we just call compute_remainder()\n    // until the error is small enough.\n\n    // Now that we know how many terms we will need to compute, k, we compute\n    // the number of bits required to accurately store (.5 - error)/k. This ensures\n    // that the total error introduced when we add up all k terms of the sum\n    // will be less than (.5 - error). This way, if everything else works correctly,\n    // then the sum will be within .5 of the correct (integer) answer, and we\n    // can correctly find it by rounding.\n    unsigned int k = 1;\n    while (compute_current_precision(n, k, 0) > double_precision) k += 100;\n    while (compute_remainder(n, k) > error) k += 100;\n\n    if (debug_precision) {\n        cout << \"To compute p(\" << n << \") we will add up approximately \" << k << \" terms from the Rachemacher series.\" << endl;\n    }\n    int bits = (int)((log(k/(.5 - error)))/log(2)) + 5;   // NOTE: reducing the number of bits by 3 here is known to cause errors\n                                                          // Why the extra 5 bits? Anytime we call a function, eg mp_a(),\n                                                          // we end up doing a bunch of arithmetic operations, and if\n                                                          // we want the result of those operations to be accurate\n                                                          // within (.5 - error)/k, then we need that function to use\n                                                          // a slightly higher working precision, which should be\n                                                          // independent of n.\n                                                          // TODO:\n                                                          // Extensive trial and error has found 3 to be the smallest value\n                                                          // that doesn't seem to produce any wrong answers. Thus, to\n                                                          // be safe, we use 5 extra bits.\n                                                          // (Extensive trial and error means compiling this file to get\n                                                          // a.out and then running './a.out testforever' for a few hours.)\n    return bits;\n}\n\n\nstatic double compute_remainder(unsigned int n, unsigned int N) {\n    // This computes the remainder left after N terms have been computed.\n    // The formula is exactly the same as the one used to compute the required\n    // precision, but once we know the necessary precision is small, we can\n    // call this function to determine the actual error (rather than the precision).\n\n    // Generally, this is only called once we know that the necessary\n    // precision is <= min_precision, because then the error is small\n    // enough to fit into a double, and also, we know that we are\n    // getting close to the correct answer.\n\n    double A = 1.11431833485164;\n    double B = 0.059238439175445;\n    double C = 2.5650996603238;\n    double result;\n    result = A/sqrt(N) + B * sqrt(double(N)/double(n-1))*sinh(C * sqrt(double(n))/double(N));\n    return result;\n}\n\n\nstatic void initialize_globals(mp_prec_t prec, unsigned int n) {\n    // The variables mp_A, mp_B, mp_C, and mp_D are used for\n    // A_n, B_n, C_n, and D_n listed at the top of this file.\n\n    // They depend only on n, so we compute them just once in this function,\n    // and then use them many times elsewhere.\n\n    // Also, we precompute some extra constants that we use a lot, such as\n    // sqrt2, sqrt3, pi\n\n    // NOTE: Calls to this function must be paired with calls to clear_globals()\n\n    // To ensure that we compute a good approximation of these\n    // constants, we use a larger precision than needed and then round\n    // to a lower precision after we are done. Working at a larger\n    // precision also means that we can use MPFR_RNDF safely (this\n    // corresponds roughly to losing 1 bit of precision).\n    mpfr_prec_t p = prec;\n    if (p < long_double_precision) p = long_double_precision;\n    p += 10;\n\n    // Global constants\n    mpfr_init2(mp_sqrt2, p);\n    mpfr_init2(mp_sqrt3, p);\n    mpfr_init2(mp_pi, p);\n    mpfr_init2(mp_A, p);\n    mpfr_init2(mp_B, p);\n    mpfr_init2(mp_C, p);\n    mpfr_init2(mp_D, p);\n\n    // Global temporary variables\n    mpq_init(qtemps);\n    mpq_init(qtempa);\n    mpq_init(qtempa2);\n    mpfr_init2(mptemp, prec);\n\n    // Temporary variables only used in this function to compute\n    // the constants\n    mpfr_t n_minus;\n    mpfr_t sqrt_n_minus;\n    mpfr_init2(n_minus, p);\n    mpfr_init2(sqrt_n_minus, p);\n\n    mpfr_set_si(n_minus, -1, MPFR_RNDF);\n    mpfr_div_ui(n_minus, n_minus, 24, MPFR_RNDF);                          // n_minus = -1/24\n    mpfr_add_ui(n_minus, n_minus, n, MPFR_RNDF);                           // n_minus = n - 1/24\n\n    mpfr_sqrt(sqrt_n_minus, n_minus, MPFR_RNDF);                           // sqrt_n_minus = sqrt(n - 1/24)\n\n    mpfr_sqrt_ui(mp_sqrt2, 2, MPFR_RNDF);                                  // mp_sqrt2 = sqrt(2)\n    mpfr_sqrt_ui(mp_sqrt3, 3, MPFR_RNDF);                                  // mp_sqrt3 = sqrt(3)\n    mpfr_const_pi(mp_pi, MPFR_RNDF);                                       // mp_pi = \u03c0\n\n    // mp_A = sqrt(2) * \u03c0 * sqrt(n - 1/24)\n    mpfr_set(mp_A, mp_sqrt2, MPFR_RNDF);                                   // mp_A = sqrt(2)\n    mpfr_mul(mp_A, mp_A, mp_pi, MPFR_RNDF);                                // mp_A = sqrt(2) * \u03c0\n    mpfr_mul(mp_A, mp_A, sqrt_n_minus, MPFR_RNDF);                         // mp_A = sqrt(2) * \u03c0 * sqrt(n - 1/24)\n\n    // mp_B = 2 * sqrt(3) * (n - 1/24)\n    mpfr_set_ui(mp_B, 2, MPFR_RNDF);                                       // mp_A = 2\n    mpfr_mul(mp_B, mp_B, mp_sqrt3, MPFR_RNDF);                             // mp_A = 2 * sqrt(3)\n    mpfr_mul(mp_B, mp_B, n_minus, MPFR_RNDF);                              // mp_A = 2 * sqrt(3) * (n - 1/24)\n\n    // mp_C = sqrt(2) * \u03c0 * sqrt(n - 1/24) / sqrt(3)\n    mpfr_set(mp_C, mp_sqrt2, MPFR_RNDF);                                   // mp_C = sqrt(2)\n    mpfr_mul(mp_C, mp_C, mp_pi, MPFR_RNDF);                                // mp_C = sqrt(2) * \u03c0\n    mpfr_mul(mp_C, mp_C, sqrt_n_minus, MPFR_RNDF);                         // mp_C = sqrt(2) * \u03c0 * sqrt(n - 1/24)\n    mpfr_div(mp_C, mp_C, mp_sqrt3, MPFR_RNDF);                             // mp_C = sqrt(2) * \u03c0 * sqrt(n - 1/24) / sqrt3\n\n    // mp_D = 2 * (n - 1/24) * sqrt(n - 1/24)\n    mpfr_set_ui(mp_D, 2, MPFR_RNDF);                                       // mp_D = 2\n    mpfr_mul(mp_D, mp_D, n_minus, MPFR_RNDF);                              // mp_D = 2 * (n - 1/24)\n    mpfr_mul(mp_D, mp_D, sqrt_n_minus, MPFR_RNDF);                         // mp_D = 2 * (n - 1/24) * sqrt(n - 1/24)\n\n    // Convert these to double and long double\n    d_pi = mpfr_get_d(mp_pi, MPFR_RNDN);\n    d_A = mpfr_get_d(mp_A, MPFR_RNDN);\n    d_B = mpfr_get_d(mp_B, MPFR_RNDN);\n    d_C = mpfr_get_d(mp_C, MPFR_RNDN);\n    d_D = mpfr_get_d(mp_D, MPFR_RNDN);\n\n    ld_pi = mpfr_get_ld(mp_pi, MPFR_RNDN);\n    ld_A = mpfr_get_ld(mp_A, MPFR_RNDN);\n    ld_B = mpfr_get_ld(mp_B, MPFR_RNDN);\n    ld_C = mpfr_get_ld(mp_C, MPFR_RNDN);\n    ld_D = mpfr_get_ld(mp_D, MPFR_RNDN);\n\n    // Drop the precision of the computed constants\n    mpfr_prec_round(mp_pi, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_sqrt2, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_sqrt3, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_A, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_B, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_C, prec, MPFR_RNDN);\n    mpfr_prec_round(mp_D, prec, MPFR_RNDN);\n\n    mpfr_clear(n_minus);\n    mpfr_clear(sqrt_n_minus);\n}\n\n\nstatic void clear_globals() {\n    mpq_clear(qtemps);\n    mpq_clear(qtempa);\n    mpq_clear(qtempa2);\n    mpfr_clear(mptemp);\n    mpfr_clear(mp_sqrt2);\n    mpfr_clear(mp_sqrt3);\n    mpfr_clear(mp_pi);\n    mpfr_clear(mp_A);\n    mpfr_clear(mp_B);\n    mpfr_clear(mp_C);\n    mpfr_clear(mp_D);\n}\n\n\nstatic void set_temp_precision(mp_prec_t prec) {\n    // Set the precision of the temporary MPFR variables to \"prec\".\n    // This requires that the temporary variables have already been\n    // initialized by initialize_globals().\n    mpfr_set_prec(mptemp, prec);\n}\n\n\nstatic void mp_f(mpfr_t result, unsigned int k) {\n    // compute f_n(k) as described in the introduction\n\n    // notice that this doesn't use n - the \"constants\"\n    // A, B, C, and D depend on n, but they are precomputed\n    // once before this function is called.\n\n    //result =  pi * sqrt(2) * cosh(A/(sqrt(3)*k))/(B*k) - sinh(C/k)/D;\n\n    mpfr_set(result, mp_pi, round_mode);                            // result = pi\n\n    mpfr_mul(result, result, mp_sqrt2, round_mode);                 // result = sqrt(2) * pi\n\n    mpfr_div(mptemp, mp_A, mp_sqrt3, round_mode);                   // temp = mp_A/sqrt(3)\n    mpfr_div_ui(mptemp, mptemp, k, round_mode);                     // temp = mp_A/(sqrt(3) * k)\n    mpfr_cosh(mptemp, mptemp, round_mode);                          // temp = cosh(mp_A/(sqrt(3) * k))\n    mpfr_div(mptemp, mptemp, mp_B, round_mode);                     // temp = cosh(mp_A/(sqrt(3) * k))/mp_B\n    mpfr_div_ui(mptemp, mptemp, k, round_mode);                     // temp = cosh(mp_A/(sqrt(3) * k))/(mp_B*k)\n\n    mpfr_mul(result, result, mptemp, round_mode);                   // result = sqrt(2) * pi * cosh(mp_A/(sqrt(3) * k))/(mp_B*k)\n\n    mpfr_div_ui(mptemp, mp_C, k, round_mode);                       // temp = mp_C/k\n    mpfr_sinh(mptemp, mptemp, round_mode);                          // temp = sinh(mp_C/k)\n    mpfr_div(mptemp, mptemp, mp_D, round_mode);                     // temp = sinh(mp_C/k)/D\n\n    mpfr_sub(result, result, mptemp, round_mode);                   // result = RESULT!\n}\n\n\n// call the following when 4k < sqrt(UINT_MAX)\n\n// TODO: maybe a faster version of this can be written without using mpq_t,\n//       or maybe this version can be smarter.\n\n//       The actual value of the cosine that we compute using s(h,k)\n//       only depends on {s(h,k)/2}, that is, the fractional\n//       part of s(h,k)/2. It may be possible to make use of this somehow.\nstatic void q_s(mpq_t result, unsigned int h, unsigned int k) {\n    if (k < 3) {\n        mpq_set_ui(result, 0, 1);\n        return;\n    }\n\n    if (h == 1) {\n        unsigned int d = GCD( (k-1)*(k-2), 12*k);\n        if (d > 1) {\n            mpq_set_ui(result, ((k-1)*(k-2))/d, (12*k)/d);\n        }\n        else {\n            mpq_set_ui(result, (k-1)*(k-2), 12*k);\n        }\n        return;\n    }\n    // TODO:\n    // It may be advantageous to implement some of the special forms in the comments below,\n    // and also some more listed in some of the links mentioned in the introduction, but\n    // it seems like there might not be much speed benefit to this, and putting in too\n    // many seems to slow things down a little.\n\n    // if h = 2 and k is odd, we have\n    // s(h,k) = (k-1)*(k-5)/24k\n    //if(h == 2 && k > 5 && k % 2 == 1) {\n    //    unsigned int d = GCD( (k-1)*(k-5), 24*k);\n    //    if(d > 1) {\n    //        mpq_set_ui(result, ((k-1)*(k-5))/d, (24*k)/d);\n    //    }\n    //    else {\n    //        mpq_set_ui(result, (k-1)*(k-5), 24*k);\n    //    }\n    //    return;\n    //}\n\n/*\n\n    // if k % h == 1, then\n\n    //      s(h,k) = (k-1)(k - h^2 - 1)/(12hk)\n\n\n    // We need to be a little careful here because k - h^2 - 1 can be negative.\n    if(k % h == 1) {\n        int num = (k-1)*(k - h*h - 1);\n        int den = 12*k*h;\n        int d = GCD(num, den);\n        if(d > 1) {\n            mpq_set_si(result, num/d, den/d);\n        }\n        else {\n            mpq_set_si(result, num, den);\n        }\n        return;\n    }\n\n    // if k % h == 2, then\n\n    //      s(h,k) = (k-2)[k - .5(h^2 + 1)]/(12hk)\n\n\n    //if(k % h == 2) {\n    //}\n*/\n\n    mpq_set_ui(result, 0, 1);                             // result = 0\n\n    int r1 = k;\n    int r2 = h;\n\n    int n = 0;\n    int temp3;\n    while(r1 > 0 && r2 > 0) {\n        unsigned int d = GCD(r1 * r1 + r2 * r2 + 1, r1 * r2);\n        if (d > 1) {\n            mpq_set_ui(qtemps, (r1 * r1 + r2 * r2 + 1)/d, (r1 * r2)/d);\n        }\n        else{\n            mpq_set_ui(qtemps, r1 * r1 + r2 * r2 + 1, r1 * r2);\n        }\n\n        if (n % 2 == 0){\n            mpq_add(result, result, qtemps);                        // result += temp;\n        }\n        else {\n            mpq_sub(result, result, qtemps);                        // result -= temp;\n        }\n        temp3 = r1 % r2;\n        r1 = r2;\n        r2 = temp3;\n        n++;\n    }\n\n    mpq_set_ui(qtemps, 1, 12);\n    mpq_mul(result, result, qtemps);                                // result = result * 1.0/12.0;\n\n    if (n % 2 == 1) {\n        mpq_set_ui(qtemps, 1, 4);\n        mpq_sub(result, result, qtemps);                            // result = result - .25;\n    }\n}\n\n\nstatic void mp_a(mpfr_t result, unsigned int n, unsigned int k) {\n    // compute a(n,k)\n\n    if (k == 1) {\n        mpfr_set_ui(result, 1, round_mode);                         //result = 1\n        return;\n    }\n\n    mpfr_set_ui(result, 0, round_mode);\n\n    unsigned int h;\n    for (h = 1; h < k+1; h++) {\n        if (GCD(h,k) == 1) {\n\n            // Note that we compute each term of the summand as\n            //      result += cos(pi * ( s(h,k) - (2.0 * h * n)/k) );\n\n            // This is the real part of the exponential that was written\n            // down in the introduction, and we don't need to compute\n            // the imaginary part because we know that, in the end, the\n            // imaginary part will be 0, as we are computing an integer.\n\n            q_s(qtempa, h, k);\n\n            unsigned int r = n % k;                                     // here we make use of the fact that the\n            unsigned int d = GCD(r,k);                                  // cos() term written above only depends\n            unsigned int K;                                             // on {hn/k}.\n            if (d > 1) {\n                r = r/d;\n                K = k/d;\n            }\n            else {\n                K = k;\n            }\n            if (K % 2 == 0) {\n                K = K/2;\n            }\n            else {\n                r = r * 2;\n            }\n            mpq_set_ui(qtempa2, h*r, K);\n            mpq_sub(qtempa, qtempa, qtempa2);\n\n            mpfr_mul_q(mptemp, mp_pi, qtempa, round_mode);\n            mpfr_cos(mptemp, mptemp, round_mode);\n            mpfr_add(result, result, mptemp, round_mode);\n        }\n    }\n}\n\n\ntemplate <class T>\ninline T partial_sum_of_t(unsigned int n, unsigned int &k, unsigned int exit_precision, unsigned int extra_precision, double error = 0) {\n    unsigned int current_precision = compute_current_precision(n, k - 1, extra_precision);\n    T result = 0;\n    if (error == 0) {\n        for (; current_precision > exit_precision; k++) {                       // (don't change k -- it is already the right value)\n            result += sqrt(T(k)) * a<T>(n,k) * f<T>(k);\n            current_precision = compute_current_precision(n,k,extra_precision); // The only reason that we compute the new precision\n                                                                                // now is so that we know when we can change to using just doubles.\n                                                                                // (There should be a 'long double' version of the compute_current_precision function.\n        }\n    }\n    else {\n        double remainder = 1;\n        for (; remainder > error; k++) {                                        // (don't change k -- it is already the right value)\n            result += sqrt(T(k)) * a<T>(n,k) * f<T>(k);\n            remainder = compute_remainder(n,k);\n        }\n    }\n    return result;\n}\n\n\nstatic void mp_t(mpfr_t result, unsigned int n) {\n    // This is the function that actually computes p(n).\n\n    // More specifically, it computes t(n,N) to within 1/2 of p(n), and then\n    // we can find p(n) by rounding.\n\n    // NOTE: result should NOT have been initialized when this is called,\n    // as we initialize it to the proper precision in this function.\n    double error = .25;\n    int extra = compute_extra_precision(n, error);\n\n    unsigned int initial_precision = compute_initial_precision(n);  // We begin by computing the precision necessary to hold the final answer.\n                                                                    // and then initialize both the result and some temporary variables to that\n                                                                    // precision.\n    mpfr_t t1, t2;\n    mpfr_init2(t1, initial_precision);\n    mpfr_init2(t2, initial_precision);\n    mpfr_init2(result, initial_precision);\n    mpfr_set_ui(result, 0, round_mode);\n\n    initialize_globals(initial_precision, n);                       // Now that we have the precision information, we initialize some constants\n                                                                    // that will be used throughout, and also set the precision of the \"temp\"\n                                                                    // variables that are used in individual functions.\n    unsigned int current_precision = initial_precision;\n    unsigned int new_precision;\n\n    // We start by computing with high precision arithmetic, until\n    // we are sure enough that we don't need that much precision\n    // anymore. Once current_precision == min_precision, we drop\n    // out of this loop and switch to a computation\n    // that only involves doubles.\n    unsigned int k = 1;                                             // (k holds the index of the summand that we are computing.)\n    for (k = 1; current_precision > level_two_precision; k++) {\n        mpfr_sqrt_ui(t1, k, round_mode);                            // t1 = sqrt(k)\n\n        mp_a(t2, n, k);                                             // t2 = A_k(n)\n\n        if (debuga) {\n            cout << \"a(\" << k <<  \") = \";\n            mpfr_out_str(stdout, 10, 10, t2, round_mode);\n            cout << endl;\n        }\n\n        mpfr_mul(t1, t1, t2, round_mode);                           // t1 = sqrt(k)*A_k(n)\n\n        mp_f(t2, k);                                                // t2 = f_k(n)\n\n        if (debugf) {\n            cout << \"f(\" << n << \",\" << k <<  \") = \";\n            mpfr_out_str(stdout, 10, 0, t2, round_mode);\n            cout << endl;\n        }\n\n        mpfr_mul(t1, t1, t2, round_mode);                           // t1 = sqrt(k)*A_k(n)*f_k(n)\n\n        mpfr_add(result, result, t1, round_mode);                   // result += summand\n\n        if (debugt) {\n            int num_digits = 20;\n            int num_extra_digits;\n            char digits[num_digits + 1];\n            num_extra_digits = grab_last_digits(digits, 5, t1);\n            grab_last_digits(digits, num_digits, result);\n\n            mpfr_out_str(stdout, 10, 10, t1, round_mode);\n            cout << endl;\n\n            cout << k << \": current precision:\"  << current_precision << \". 20 last digits of partial result: \" << digits << \". Number of extra digits: \" << num_extra_digits << endl;\n            cout.flush();\n\n        }\n\n        new_precision = compute_current_precision(n,k,extra);       // After computing one summand, check what the new precision should be.\n        if (new_precision != current_precision) {                   // If the precision changes, we need to fix the\n            current_precision = new_precision;                      // precision of all \"temp\" variables.\n            set_temp_precision(current_precision);\n            mpfr_set_prec(t1, current_precision);\n            mpfr_set_prec(t2, current_precision);\n        }\n    }\n\n    long double ld_partial_sum = partial_sum_of_t<long double>(n, k, level_five_precision, extra, 0);\n    mpfr_set_prec(t1, long_double_precision);\n    mpfr_set_ld(t1, ld_partial_sum, round_mode);\n    mpfr_add(result, result, t1, round_mode);\n\n    double d_partial_sum = partial_sum_of_t<double>(n, k, 0, extra, error);\n    mpfr_add_d(result, result, d_partial_sum, round_mode);          // We add together the main result and the tail ends'\n\n    mpfr_div(result, result, mp_pi, round_mode);                    // The actual result is the sum that we have computed\n    mpfr_div(result, result, mp_sqrt2, round_mode);                 // divided by pi*sqrt(2).\n\n    clear_globals();\n    mpfr_clear(t1);\n    mpfr_clear(t2);\n}\n\n\ntemplate <class T>\nT f(unsigned int k) {\n    return pi_sqrt2<T>() * cosh(A<T>()/(sqrt3<T>()*k))/(B<T>() * k) - sinh(C<T>()/k)/D<T>();\n}\n\n\ntemplate <class T>\nT a(unsigned int n, unsigned int k) {\n    if (k == 1) {\n        return 1;\n    }\n    T result = 0;\n\n    unsigned int h = 0;\n    for (h = 1; h < k+1; h++) {\n        if (GCD(h,k) == 1) {\n            result += cos( pi<T>() * ( s<T>(h,k) - T(2.0 * double(h) * n)/T(k)) ); // be careful to promote 2 and h to Ts\n                                                                                   // because the result 2 * h * n could\n                                                                                   // be too large.\n        }\n    }\n    return result;\n}\n\n\ntemplate <class T>\nT s(unsigned int h, unsigned int k) {\n    if (k < 3) {\n        return T(0);\n    }\n\n    if (h == 1) {\n        return T((k-1) * (k-2))/T(12 * k);\n    }\n    // TODO: In the function mp_s() there are a few special cases for special forms of h and k.\n    // (And there are more special cases listed in one of the references listed in the introduction.)\n\n    // It may be advantageous to implement some here, but I'm not sure\n    // if there is any real speed benefit to this.\n\n    // In the mpfr_t version of this function, the speedups didn't seem to help too much, but\n    // they might make more of a difference here.\n\n    // Update to the above comments:\n    // Actually, a few tests seem to indicate that putting in too many special\n    // cases slows things down a little bit.\n\n    // if h = 2 and k is odd, we have\n    // s(h,k) = (k-1)*(k-5)/24k\n    if (h == 2 && k > 5 && k % 2 == 1) {\n        return T((k-1)*(k-5))/ T(24 * k);\n    }\n\n    int r1 = k;\n    int r2 = h;\n\n    int n = 1;\n    int temp3;\n\n    T result = T(0);\n    T temp;\n    while(r2 > 0)   // Note that we maintain the invariant r1 >= r2, so\n                    // we only need to make sure that r2 > 0\n    {\n        temp = T(r1 * r1 + r2 * r2 + 1)/(n * r1 * r2);\n        temp3 = r1 % r2;\n        r1 = r2;\n        r2 = temp3;\n\n        result += temp;\n\n        n = -n;\n    }\n\n    result *= one_over_12<T>();\n\n    if (n < 0) {\n        result -= T(.25);\n    }\n    return result;\n}\n\n\n// answer must have already been mpz_init'd.\nvoid part(mpz_t answer, unsigned int n){\n    if (n <= 1) {\n        mpz_set_ui(answer, 1);\n        return;\n    }\n    mpfr_t result;\n\n    mp_t(result, n);\n\n    mpfr_get_z(answer, result, MPFR_RNDN);\n\n    mpfr_clear(result);\n}\n\n\n// This program is mainly meant for inclusion in SageMath (or any other\n// program, if anyone feels like it). We include a main() function\n// anyway, because it is useful to compile this as a standalone program\n// for testing purposes.\nint main(int argc, char *argv[]){\n    unsigned int n = 10;\n\n    if (argc > 1)\n        if (strcmp(argv[1], \"test\") == 0) {\n            n = test(true);\n            if (n == 0) {\n                cout << \"All Tests Passed\" << endl;\n            }\n            else {\n                cout << \"Error computing p(\" << n << \")\" << endl;\n            }\n            return 0;\n        }\n        else if (strcmp(argv[1], \"testforever\") == 0) {\n            n = test(false, true);\n            if (n == 0) {\n                cout << \"All Tests Passed\" << endl;\n            }\n            else {\n                cout << \"Error computing p(\" << n << \")\" << endl;\n            }\n            return 0;\n        }\n        else {\n            n = atoi(argv[1]);\n        }\n    else {\n        n = test(false);\n        if (n == 0) {\n            cout << \"All short tests passed. Run '\" << argv[0] << \" test' to run all tests. (This may take some time, but it gives updates as it progresses, and can be interrupted.)\" << endl;\n            cout << \"Run with the argument 'testforever' to run tests until a failure is found (or, hopefully, to run tests forever.)\" << endl;\n        }\n        else {\n            cout << \"Error computing p(\" << n << \")\" << endl;\n        }\n        return 0;\n    }\n    //mpfr_t result;\n\n    //mp_t(result, n);\n\n    mpz_t answer;\n    mpz_init(answer);\n    part(answer, n);\n\n    //mpfr_get_z(answer, result, round_mode);\n\n    mpz_out_str (stdout, 10, answer);\n\n    cout << endl;\n\n    return 0;\n}\n\n\nint test(bool longtest, bool forever) {\n    // The exact values given below are confirmed by multiple sources, so are probably correct.\n    // Other tests rely on known congruences.\n    // If longtest is true, then we run some tests that probably take on the order\n    // of 10 minutes.\n    // If forever is true, then we just do randomized tests until a failure\n    // is found. Ideally, this should mean that we test forever, of course.\n\n    int n;\n\n    mpz_t expected_value;\n    mpz_t actual_value;\n\n    mpz_init(expected_value);\n    mpz_init(actual_value);\n\n    n= 1;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"1\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 10;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"42\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 100;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"190569292\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 1000;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"24061467864032622473692149727991\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 10000;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"36167251325636293988820471890953695495016030339315650422081868605887952568754066420592310556052906916435144\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 100000;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"27493510569775696512677516320986352688173429315980054758203125984302147328114964173055050741660736621590157844774296248940493063070200461792764493033510116079342457190155718943509725312466108452006369558934464248716828789832182345009262853831404597021307130674510624419227311238999702284408609370935531629697851569569892196108480158600569421098519\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 1000000;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    mpz_set_str(expected_value, \"1471684986358223398631004760609895943484030484439142125334612747351666117418918618276330148873983597555842015374130600288095929387347128232270327849578001932784396072064228659048713020170971840761025676479860846908142829356706929785991290519899445490672219997823452874982974022288229850136767566294781887494687879003824699988197729200632068668735996662273816798266213482417208446631027428001918132198177180646511234542595026728424452592296781193448139994664730105742564359154794989181485285351370551399476719981691459022015599101959601417474075715430750022184895815209339012481734469448319323280150665384042994054179587751761294916248142479998802936507195257074485047571662771763903391442495113823298195263008336489826045837712202455304996382144601028531832004519046591968302787537418118486000612016852593542741980215046267245473237321845833427512524227465399130174076941280847400831542217999286071108336303316298289102444649696805395416791875480010852636774022023128467646919775022348562520747741843343657801534130704761975530375169707999287040285677841619347472368171772154046664303121315630003467104673818\", 10);\n    part(actual_value, n);\n\n    if (mpz_cmp(expected_value, actual_value) != 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n\n    // We now run some tests based on the fact that if n = 369 (mod 385) then p(n) = 0 (mod 385).\n\n    n = 369 + 10*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 369 + 10*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 369 + 100*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 369 + 110*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 369 + 120*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    n = 369 + 130*385;\n    cout << \"Computing p(\" << n << \")...\";\n    cout.flush();\n    part(actual_value, n);\n    if (mpz_divisible_ui_p(actual_value, 385) == 0)\n        return n;\n\n    cout << \" OK.\" << endl;\n\n    // Randomized testing\n\n    srand( time(NULL) );\n\n    for (int i = 0; i < 100; i++) {\n        n = int(100000 * double(rand())/double(RAND_MAX) + 1);\n        n = n - (n % 385) + 369;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n            return n;\n        }\n        cout << \" OK.\" << endl;\n\n    }\n\n    if (longtest) {\n        n = 369 + 1000*385;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0)\n            return n;\n\n        cout << \" OK.\" << endl;\n\n        n = 369 + 10000*385;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0)\n            return n;\n\n        cout << \" OK.\" << endl;\n\n        n = 369 + 100000*385;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0)\n            return n;\n\n        cout << \" OK.\" << endl;\n\n        for (int i = 0; i < 20; i++) {\n            n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 100000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 20; i++) {\n            n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 500000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 20; i++) {\n            n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 1000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 10; i++) {\n            n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 10000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        n = 369 + 1000000*385;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0)\n            return n;\n\n        cout << \" OK.\" << endl;\n\n        for (int i = 0; i < 10; i++) {\n            n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 100000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        n = 1000000000 + 139;\n        cout << \"Computing p(\" << n << \")...\";\n        cout.flush();\n        part(actual_value, n);\n        if (mpz_divisible_ui_p(actual_value, 385) == 0)\n            return n;\n\n        cout << \" OK.\" << endl;\n\n        for (int i = 0; i < 10; i++) {\n            n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 1000000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n    }\n\n    while (forever) {\n        for (int i = 0; i < 100; i++) {\n            n = int(900000 * double(rand())/double(RAND_MAX) + 1) + 100000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 50; i++) {\n            n = int(9000000 * double(rand())/double(RAND_MAX) + 1) + 1000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 50; i++) {\n            n = int(90000000 * double(rand())/double(RAND_MAX) + 1) + 10000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n\n        for (int i = 0; i < 10; i++) {\n            n = int(900000000 * double(rand())/double(RAND_MAX) + 1) + 100000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n        for (int i = 0; i < 5; i++) {\n            n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 1000000000;\n            n = n - (n % 385) + 369;\n            cout << \"Computing p(\" << n << \")...\";\n            cout.flush();\n            part(actual_value, n);\n            if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n                return n;\n            }\n            cout << \" OK.\" << endl;\n        }\n    }\n\n    mpz_clear(expected_value);\n    mpz_clear(actual_value);\n    return 0;\n}\n", "meta": {"hexsha": "b432107241916495e748f9efc632c77bf3b3a5bd", "size": 56324, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/sage/combinat/partitions_c.cc", "max_stars_repo_name": "fchapoton/sage", "max_stars_repo_head_hexsha": "765c5cb3e24dd134708eca97e4c52e0221cd94ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T04:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T06:33:51.000Z", "max_issues_repo_path": "src/sage/combinat/partitions_c.cc", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "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/sage/combinat/partitions_c.cc", "max_forks_repo_name": "Ivo-Maffei/sage", "max_forks_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T17:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T18:11:28.000Z", "avg_line_length": 38.8709454796, "max_line_length": 1148, "alphanum_fraction": 0.5280697394, "num_tokens": 14279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6812386806875225}}
{"text": "#include \"SimpleESOSolver.h\"\n\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n\nSimpleESOSolver::SimpleESOSolver(ESO* eso)\n{\n\tm_ESO = eso;\n\tn_vars = m_ESO->GetNumVars();\n\tn_eqns = m_ESO->GetNumEqns();\n\n\tjac = std::unique_ptr<double[]>(new double[n_vars * n_eqns]);\n\txx = std::unique_ptr<double[]>(new double[n_vars]);\n\tFF = std::unique_ptr<double[]>(new double[n_eqns]);\n}\n\nvoid SimpleESOSolver::solve()\n{\n\tint kmax, k;\n\tconst auto& n = n_eqns;\n\n\tkmax = 300;\n\tdouble err = 0;\n\n\tEigen::Map<Eigen::VectorXd> F(FF.get(), n);\n\tEigen::Map<Eigen::VectorXd> x(xx.get(), n);\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> Jac(jac.get(), n, n);\n\n\tEigen::VectorXd delta(n);\n\n\tm_ESO->correctBoundaries();\n\tm_ESO->GetAllVariables(xx.get());\n\n\tfor (k = 0; k < kmax; ++k) {\n\n\t\tm_ESO->GetAllResiduals(FF.get());\n\t\tm_ESO->getAllJacobianValues(jac.get());\n\n\t\t// Solve linear system\n\t\tdelta = Jac.fullPivLu().solve(-F);\n\n\t\t// Update x values\n\t\tx = x + delta;\n\n\t\tm_ESO->SetAllVariables(xx.get());\n\n\t\t// criterion for stop\n\t\t// get max abs value of function\n\t\terr = 0.0;\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\terr = err < std::abs(F[i]) ? abs(F[i]) : err;\n\t\t\terr = err < std::abs(delta[i]) ? abs(delta[i]) : err;\n\t\t}\n\n\t\tif (err < m_tol) return;\n\n\t\tm_ESO->correctBoundaries();\n\t}\n}\n", "meta": {"hexsha": "475b9d948af33bef1dc26191210eadb90771de1a", "size": 1308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver/src/SimpleESOSolver.cpp", "max_stars_repo_name": "marcusbfs/HydroModel", "max_stars_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solver/src/SimpleESOSolver.cpp", "max_issues_repo_name": "marcusbfs/HydroModel", "max_issues_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solver/src/SimpleESOSolver.cpp", "max_forks_repo_name": "marcusbfs/HydroModel", "max_forks_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_forks_repo_licenses": ["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.4426229508, "max_line_length": 105, "alphanum_fraction": 0.6337920489, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.769080247656264, "lm_q1q2_score": 0.6811216732162738}}
{"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#include <iostream>\n#include <iomanip>\n#include <boost/math/tools/cohen_acceleration.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing boost::math::tools::cohen_acceleration;\nusing boost::math::constants::pi;\n\ntemplate<typename Real>\nclass G {\npublic:\n    G(){\n        k_ = 0;\n    }\n    \n    Real operator()() {\n        k_ += 1;\n        return 1/(k_*k_);\n    }\n\nprivate:\n    Real k_;\n};\n\nint main() {\n    using Real = float;\n    auto g = G<Real>();\n    Real computed = cohen_acceleration(g);\n    Real expected = pi<Real>()*pi<Real>()/12;\n    std::cout << std::setprecision(std::numeric_limits<Real>::max_digits10);\n\n    std::cout << \"Computed = \" << computed << \" = \" << std::hexfloat << computed <<  \"\\n\";\n    std::cout << std::defaultfloat;\n    std::cout << \"Expected = \" << expected << \" = \" << std::hexfloat << expected << \"\\n\";\n\n    // Compute with a specified number of terms:\n    // Make sure to reset g:\n    g = G<Real>();\n    computed = cohen_acceleration(g, 5);\n    std::cout << std::defaultfloat;\n    std::cout << \"Computed = \" << computed << \" = \" << std::hexfloat << computed << \" using 5 terms.\\n\";\n}\n", "meta": {"hexsha": "e16357d132a2af62e33c5a005b6e36b6b604e658", "size": 1352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cohen_acceleration.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/cohen_acceleration.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/example/cohen_acceleration.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 28.7659574468, "max_line_length": 104, "alphanum_fraction": 0.6109467456, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6811216731719669}}
{"text": "//\n//  eigen_geometry_util.cpp\n//  PointLineReloc\n//\n//  Created by jimmy on 2017-05-05.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"eigen_geometry_util.h\"\n#include <math.h>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing std::cout;\nusing std::endl;\n\nEigen::Matrix3d EigenGeometryUtil::vector2SkewSymmetricMatrix(const Eigen::Vector3d & v)\n{\n    // https://en.wikipedia.org/wiki/Skew-symmetric_matrix\n    Eigen::Matrix3d m = Eigen::Matrix3d::Zero();\n    double a = v.x();\n    double b = v.y();\n    double c = v.z();\n    m << 0, -c, b,\n    c, 0, -a,\n    -b, a, 0;\n    \n    return m;\n}\n\n\nnamespace EigenX {\n    \n    // @brief internal function. RPE report 2015 summer\n    static bool focalLengthEstimation(const double a, const double b,\n                                      const double c, const double d,\n                                      double& fl,\n                                      bool verbose = true)\n    {\n        double delta = (d*d *(a+b) - 2.0*c)*(d*d *(a+b) - 2.0*c) - 4.0 *(d*d*a*b-c*c)*(d*d-1.0);\n        if (delta < 0.0) {\n            if (verbose) {\n                printf(\"Error: sqrt a negative number.\\n\");\n                printf(\"delta is %f\\n\", delta);\n            }\n            return false;\n        }\n        \n        double numerator   = 2.0 * (d*d*a*b - c*c);\n        double denominator = 2.0*c - d*d *(a+b) + sqrt(delta);\n        if (denominator == 0.0) {\n            if (verbose) {\n                printf(\"Error: denominator is zero.\\n\");\n            }\n            \n            return false;\n        }\n        double fl_2 = numerator/denominator;\n        if (fl_2 <= 0.0) {\n            if (verbose) {\n                printf(\"Error: focal length is not a real number. f^2 is %f\\n\", fl_2);\n                printf(\"numerator, denominator is %f %f\\n\", numerator, denominator);\n            }\n            return false;\n        }\n        fl = sqrt(fl_2);\n        return true;\n    }\n    \n    void pointPanTilt(const Eigen::Vector2f& pp,\n                      const Eigen::Vector3f& ptz,\n                      const Eigen::Vector2f& point,\n                      Eigen::Vector2f& point_pan_tilt)\n    {\n        double dx = point.x() - pp.x();\n        double dy = point.y() - pp.y();\n        double fl = ptz.z();\n        double delta_pan = atan2(dx, fl) * 180.0/M_PI;\n        double delta_tilt = atan2(dy, fl) * 180.0/M_PI;\n        point_pan_tilt[0] = ptz[0] + delta_pan;\n        point_pan_tilt[1] = ptz[1] - delta_tilt; // oppositive direction of y\n    }\n    \n    void pointPanTilt(const Eigen::Vector2d& pp,\n                      const Eigen::Vector3d& ptz,\n                      const Eigen::Vector2d& point,\n                      Eigen::Vector2d& point_pan_tilt)\n    {\n        double dx = point.x() - pp.x();\n        double dy = point.y() - pp.y();\n        double fl = ptz.z();\n        double delta_pan = atan2(dx, fl) * 180.0/M_PI;\n        double delta_tilt = atan2(dy, fl) * 180.0/M_PI;\n        point_pan_tilt[0] = ptz[0] + delta_pan;\n        point_pan_tilt[1] = ptz[1] - delta_tilt; // oppositive direction of y        \n    }\n\n    static Eigen::Matrix3f matrixFromPanYTiltX(double pan, double tilt)\n    {\n        Eigen::Matrix3f m;\n        \n        pan  *= M_PI / 180.0;\n        tilt *= M_PI / 180.0;\n        \n        Eigen::Matrix3f R_tilt;\n        R_tilt(0 ,0) = 1;   R_tilt(0, 1) = 0;          R_tilt(0, 2) = 0;\n        R_tilt(1, 0) = 0;   R_tilt(1, 1) = cos(tilt);  R_tilt(1, 2) = sin(tilt);\n        R_tilt(2, 0) = 0;   R_tilt(2, 1) = -sin(tilt);  R_tilt(2, 2) = cos(tilt);\n        \n        Eigen::Matrix3f R_pan;\n        R_pan(0, 0) = cos(pan);   R_pan(0, 1) = 0;   R_pan(0, 2) = -sin(pan);\n        R_pan(1, 0) = 0;          R_pan(1, 1) = 1;   R_pan(1, 2) = 0;\n        R_pan(2, 0) = sin(pan);   R_pan(2, 1) = 0;   R_pan(2, 2) = cos(pan);\n        \n        m = R_tilt * R_pan;\n        return m;\n    }\n\n    \n    \n    bool ptzFromTwoPoints(const Eigen::Vector2f& pan_tilt1,\n                          const Eigen::Vector2f& pan_tilt2,\n                          const Eigen::Vector2f& point1,\n                          const Eigen::Vector2f& point2,\n                          const Eigen::Vector2f& pp,\n                          Eigen::Vector3f& ptz)\n    {\n        Eigen::Vector2f p1 = point1 - pp;\n        Eigen::Vector2f p2 = point2 - pp;\n       \n        // Step 1. focal length\n        double pan1  = pan_tilt1[0];\n        double tilt1 = pan_tilt1[1];\n        double pan2  = pan_tilt2[0];\n        double tilt2 = pan_tilt2[1];\n        \n        double a = p1.dot(p1);\n        double b = p2.dot(p2);\n        double c = p1.dot(p2);\n        Eigen::Vector3f z_axis = Eigen::Vector3f::Zero(3, 1);\n        z_axis[2] = 1.0f;\n        // rotate matrix of axis z\n        Eigen::Vector3f rotated_axis_z = matrixFromPanYTiltX(pan2 - pan1, tilt2 - tilt1) * z_axis;\n        double d = z_axis.dot(rotated_axis_z);  // angular difference of two angles\n        double fl = 0;\n        bool is_estimated = focalLengthEstimation(a, b, c, d, fl, false);\n        if (!is_estimated) {\n            return false;\n        }\n        \n        // Step 2. pan and tilt\n        double theta1 = pan1 - atan2(p1(0), fl)*180.0/M_PI;\n        double theta2 = pan2 - atan2(p2(0), fl)*180.0/M_PI;\n        ptz[0] = (theta1 + theta2)/2.0;\n        \n        double phi1 = tilt1 + atan2(p1(1), fl)*180.0/M_PI;  // oppositive direction as y is from top to down in image\n        double phi2 = tilt2 + atan2(p2(1), fl)*180.0/M_PI;\n        ptz[1] = (phi1 + phi2)/2.0;\n        ptz[2] = fl;\n        \n        return true;\n    }\n    \n    bool ptzFromTwoPoints(const Eigen::Vector2d& pan_tilt1,\n                          const Eigen::Vector2d& pan_tilt2,\n                          const Eigen::Vector2d& point1,\n                          const Eigen::Vector2d& point2,\n                          const Eigen::Vector2d& pp,\n                          Eigen::Vector3d& ptz)\n    {\n        Eigen::Vector3f ptz_temp;\n        bool is_ok = ptzFromTwoPoints(Eigen::Vector2f(pan_tilt1.x(), pan_tilt1.y()),\n                                      Eigen::Vector2f(pan_tilt2.x(), pan_tilt2.y()),\n                                      Eigen::Vector2f(point1.x(), point1.y()),\n                                      Eigen::Vector2f(point2.x(), point2.y()),\n                                      Eigen::Vector2f(pp.x(), pp.y()),\n                                      ptz_temp);\n        ptz[0] = ptz_temp[0];\n        ptz[1] = ptz_temp[1];\n        ptz[2] = ptz_temp[2];\n        return is_ok;        \n    }\n\n    \n}; // namespace EigenX", "meta": {"hexsha": "57785010b5eff4262e62008cad6c404df15b5ff1", "size": 6569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_stars_repo_name": "lood339/two_point_calib", "max_stars_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2018-04-22T10:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T07:35:07.000Z", "max_issues_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_issues_repo_name": "lood339/two_point_calib", "max_issues_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T06:33:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T06:11:14.000Z", "max_forks_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_forks_repo_name": "lood339/two_point_calib", "max_forks_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:25:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T06:16:42.000Z", "avg_line_length": 35.128342246, "max_line_length": 117, "alphanum_fraction": 0.4903333841, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6811216615198226}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <vector>\n\n// Returns in the inverse of a 4x4 homogeneous transform\nEigen::Matrix4d get_inverse_tf(Eigen::Matrix4d T);\n\n/*!\n   \\brief Enforce orthogonality conditions on the given rotation matrix such that det(R) == 1 and R.tranpose() * R = I\n   \\param R The input rotation matrix either 2x2 or 3x3, will be overwritten with a slightly modified matrix to\n   satisfy orthogonality conditions.\n*/\nvoid enforce_orthogonality(Eigen::MatrixXd &R);\n\n/*!\n   \\brief Returns the output of the cross operator.\n        For 3 x 1 input, cross(x) * y is equivalent to cross_product(x, y)\n        For 6 x 1 input, x = [rho, phi]^T. out = [cross(phi), rho; 0 0 0 1]\n   \\param x Input vector which can be 3 x 1 or 6 x 1.\n   \\return If the input if 3 x 1, the output is 3 x 3, if the input is 6 x 1, the output is 4 x 4.\n*/\nEigen::MatrixXd cross(Eigen::VectorXd x);\n\n/*!\n   \\brief This function converts from a lie vector to a 4 x 4 SE(3) transform.\n        Lie Vector xi = [rho, phi]^T (6 x 1) --> SE(3) T = [C, R; 0 0 0 1] (4 x 4)\n   \\param x Input vector is 6 x 1\n   \\return Output is 4 x SE(3) transform\n*/\nEigen::Matrix4d se3ToSE3(Eigen::MatrixXd xi);\n\n/*!\n   \\brief Removes motion distortion from a pointcloud.\n        Given a pointcloud, a timestamp for each point, a transform from the sensor to the origin,\n        and a ground truth data vector, this function adjusts the position of each point so as to remove\n        the motion distortion.\n   \\param pc input/output pointcloud, the position of points will be modified to remove distortion.\n   \\param times vector of timestamps for each point\n   \\param T_enu_sensor Global transform from the sensor frame to ENU at timestamp times[0].\n   \\param gt Vector of ground truth associated with this pointcloud:\n        GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z\n*/\nvoid removeMotionDistortion(Eigen::MatrixXd &pc, std::vector<float> &times, Eigen::Matrix4d T_enu_sensor,\n    std::vector<double> gt);\n\n/*!\n   \\brief Get the K closest keyframes to the specified location.\n   \\param loc [x, y] location of the query frame.\n   \\param frame_locs Vector specifying the location of the candidate keyframes.\n   \\param K The number of keyframes to retrieve. If frame_locs.size() < K, then less will be returned.\n   \\param closestK output vector of indices specifying the closest K keyframes, not in any particular order.\n*/\nvoid getClosestKFrames(std::vector<float> loc, std::vector<std::vector<float>> &frame_locs, uint K,\n    std::vector<int> & closestK);\n\n/*!\n   \\brief Calculates the translation and rotation difference between two 4x4 homogeneous transformations.\n        The two transformations should be doing the same thing, ex: T_map_sensor.\n*/\nvoid poseError(Eigen::Matrix4d T1, Eigen::Matrix4d T2, double &trans_error, double &rot_error);\n\n/*!\n   \\brief Given a 3x3 rotation matrix, this function extracts 3-2-1 yaw-pitch-roll angles.\n*/\nvoid rotToYawPitchRoll(Eigen::Matrix3d C, double &yaw, double &pitch, double &roll);\n\nvoid filterPointCloud(Eigen::MatrixXd &pc, double xmin, double xmax, double ymin, double ymax, double zmin,\n    double zmax);\n", "meta": {"hexsha": "40d49da9b21f7b4a76a3b426eae035f46e5d16e0", "size": 3151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/estimation.hpp", "max_stars_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_stars_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T01:17:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:51:30.000Z", "max_issues_repo_path": "include/estimation.hpp", "max_issues_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_issues_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "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/estimation.hpp", "max_forks_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_forks_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-02T15:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T16:59:35.000Z", "avg_line_length": 45.6666666667, "max_line_length": 118, "alphanum_fraction": 0.7197715011, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6811216545108129}}
{"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_rpy_hpp__\n#define __pinocchio_math_rpy_hpp__\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/math/comparison-operators.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace pinocchio\n{\n  namespace rpy\n  {\n    ///\n    /// \\brief Convert from Roll, Pitch, Yaw to rotation Matrix\n    ///\n    /// Given \\f$r, p, y\\f$, the rotation is given as \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n    /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n    /// around axis \\f$\\alpha\\f$.\n    ///\n    template<typename Scalar>\n    Eigen::Matrix<Scalar,3,3> rpyToMatrix(const Scalar r,\n                                          const Scalar p,\n                                          const Scalar y)\n    {\n      typedef Eigen::AngleAxis<Scalar> AngleAxis;\n      typedef Eigen::Matrix<Scalar,3,1> Vector3s;\n      return (AngleAxis(y, Vector3s::UnitZ())\n              * AngleAxis(p, Vector3s::UnitY())\n              * AngleAxis(r, Vector3s::UnitX())\n             ).toRotationMatrix();\n    }\n\n    ///\n    /// \\brief Convert from Roll, Pitch, Yaw to rotation Matrix\n    ///\n    /// Given a vector \\f$(r, p, y)\\f$, the rotation is given as \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n    /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n    /// around axis \\f$\\alpha\\f$.\n    ///\n    template<typename Vector3Like>\n    Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options>\n    rpyToMatrix(const Eigen::MatrixBase<Vector3Like> & rpy)\n    {\n      PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Vector3Like, rpy, 3, 1);\n      return rpyToMatrix(rpy[0], rpy[1], rpy[2]);\n    }\n\n    ///\n    /// \\brief Convert from Transformation Matrix to Roll, Pitch, Yaw\n    ///\n    /// Given a rotation matrix \\f$R\\f$, the angles \\f$r, p, y\\f$ are given\n    /// so that \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n    /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n    /// around axis \\f$\\alpha\\f$.\n    /// The angles are guaranteed to be in the ranges \\f$r\\in[-\\pi,\\pi]\\f$\n    /// \\f$p\\in[-\\frac{\\pi}{2},\\frac{\\pi}{2}]\\f$ \\f$y\\in[-\\pi,\\pi]\\f$,\n    /// unlike Eigen's eulerAngles() function\n    ///\n    /// \\warning the method assumes \\f$R\\f$ is a rotation matrix. If it is not, the result is undefined.\n    ///\n    template<typename Matrix3Like>\n    Eigen::Matrix<typename Matrix3Like::Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options>\n    matrixToRpy(const Eigen::MatrixBase<Matrix3Like> & R)\n    {\n      PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like, R, 3, 3);\n      assert(R.isUnitary() && \"R is not a unitary matrix\");\n\n      typedef typename Matrix3Like::Scalar Scalar;\n      typedef Eigen::Matrix<Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options> ReturnType;\n      static const Scalar pi = PI<Scalar>();\n\n      ReturnType res = R.eulerAngles(2,1,0).reverse();\n\n      if(res[1] < -pi/2)\n        res[1] += 2*pi;\n\n      if(res[1] > pi/2)\n      {\n        res[1] = pi - res[1];\n        if(res[0] < Scalar(0))\n          res[0] += pi;\n        else\n          res[0] -= pi;\n        // res[2] > 0 according to Eigen's eulerAngles doc, no need to check its sign\n        res[2] -= pi;\n      }\n\n      return res;\n    }\n  } // namespace rpy\n}\n#endif //#ifndef __pinocchio_math_rpy_hpp__\n", "meta": {"hexsha": "798b9e1237c9269a8913cc09de7c440a275f2aae", "size": 3323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/rpy.hpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "src/math/rpy.hpp", "max_issues_repo_name": "dengs08/pinocchio", "max_issues_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/rpy.hpp", "max_forks_repo_name": "dengs08/pinocchio", "max_forks_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-21T01:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:59:35.000Z", "avg_line_length": 34.2577319588, "max_line_length": 104, "alphanum_fraction": 0.5973517906, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6810720815530555}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, logit) {\n  using stan::math::logit;\n  EXPECT_FLOAT_EQ(0.0, logit(0.5));\n  EXPECT_FLOAT_EQ(5.0, logit(1.0/(1.0 + exp(-5.0))));\n}\n\nTEST(MathFunctions, logit_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::logit(nan));\n}\n", "meta": {"hexsha": "0e2dd449023aa8f132a0e03d496a9e02e6e7ce74", "size": 443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logit_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logit_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/logit_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0588235294, "max_line_length": 56, "alphanum_fraction": 0.6772009029, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.6810654958488386}}
{"text": "/**\n * @file exponentialintegrator_test.cc\n * @brief NPDE homework ExponentialIntegrator\n * @author Tobias Rohner\n * @date 13.04.2021\n * @copyright Developed ate ETH Zurich\n */\n\n#include \"../exponentialintegrator.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nnamespace ExponentialIntegrator::test {\n\nTEST(exponentialEulerStep, scalar) {\n  auto f = [](const Eigen::VectorXd &y) { return y; };\n  auto df = [](const Eigen::VectorXd &y) { return Eigen::MatrixXd::Ones(1, 1); };\n\n  Eigen::VectorXd y0(1);\n  y0[0] = 1;\n  const double y1 = std::exp(1);\n\n  const Eigen::VectorXd y = ExponentialIntegrator::exponentialEulerStep(y0, f, df, 1);\n\n  EXPECT_NEAR(y[0], y1, 1e-8);\n}\n\nTEST(exponentialEulerStep, vector) {\n  Eigen::MatrixXd A(2, 2);\n  A(0, 0) = 1;\n  A(0, 1) = 0;\n  A(1, 0) = 0;\n  A(1, 1) = 2;\n  auto f = [&](const Eigen::VectorXd &y) { return A * y; };\n  auto df = [&](const Eigen::VectorXd &y) { return A; };\n\n  Eigen::VectorXd y0(2);\n  y0[0] = 2;\n  y0[1] = 1;\n  Eigen::VectorXd y1(2);\n  y1[0] = std::exp(1) * y0[0];\n  y1[1] = std::exp(2) * y0[1];\n\n  const Eigen::VectorXd y = ExponentialIntegrator::exponentialEulerStep(y0, f, df, 1);\n\n  EXPECT_NEAR(y[0], y1[0], 1e-8);\n  EXPECT_NEAR(y[1], y1[1], 1e-8);\n}\n\n} // namespace ExponentialIntegrator::test\n", "meta": {"hexsha": "0f74e42bfff75be45249a3a5bbf45b53a1ccdf77", "size": 1259, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExponentialIntegrator/templates/test/exponentialintegrator_test.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": "homeworks/ExponentialIntegrator/templates/test/exponentialintegrator_test.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": "homeworks/ExponentialIntegrator/templates/test/exponentialintegrator_test.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": 23.7547169811, "max_line_length": 86, "alphanum_fraction": 0.629070691, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.8031737892899222, "lm_q1q2_score": 0.6810654653486028}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef VLEQ_HPP\n#define VLEQ_HPP\n\n#include <cstddef>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/matrix-inversion.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n// verified linear equation solver\n// for matrix-rhs\n// set r if you already have approximate inverse of a\n\ntemplate <class T>\nbool vleq(\n\tconst ub::matrix< interval<T> >& a,\n\tconst ub::matrix< interval<T> >& b,\n\tub::matrix<interval<T> >& x,\n\tconst ub::matrix<T>* r = NULL )\n{\n\tint i, j;\n\tint s1 = b.size1();\n\tint s2 = b.size2();\n\tub::matrix<T> R, E;\n\tub::matrix< interval<T> > EmRA;\n\tub::vector< interval<T> > xtmp(s1), btmp(s1), rtmp(s1);\n\tbool bo;\n\tT norm1, norm2, norm3, err;\n\n\tif (r == NULL) {\n\t\tbo = invert(mid(a), R);\n\t\tif (bo == false) return false;\n\t} else {\n\t\tR = *r;\n\t}\n\n\tE = ub::identity_matrix<T>(s1);\n\n\tEmRA = E - prod(R, a);\n\tnorm1 = max_norm(EmRA);\n\trop<T>::begin();\n\tnorm1 = rop<T>::sub_down(T(1.), norm1);\n\trop<T>::end();\n\n\tif (norm1 <= 0.) return false;\n\n\tx = prod(R, mid(b));\n\n\tnorm2 = max_norm(R);\n\n\tfor (i=0; i<s2; i++) {\n\t\tfor (j=0; j<s1; j++) {\n\t\t\txtmp(j) = x(j, i);\n\t\t\tbtmp(j) = b(j, i);\n\t\t}\n\t\trtmp = prod(a, xtmp) - btmp;\n\t\tnorm3 = max_norm(rtmp);\n\t\trop<T>::begin();\n\t\terr = rop<T>::div_up(rop<T>::mul_up(norm2, norm3), norm1);\n\t\trop<T>::end();\n\t\tfor (j=0; j<s1; j++) {\n\t\t\tx(j, i) += interval<T>(-err, err);\n\t\t}\n\t}\n\n\treturn true;\n}\n\n// verified linear equation solver\n// for vector-rhs\n// set r if you already have approximate inverse of a\n\ntemplate <class T>\nbool vleq(\n\tconst ub::matrix< interval<T> >& a,\n\tconst ub::vector< interval<T> >& b,\n\tub::vector<interval<T> >& x,\n\tconst ub::matrix<T>* r = NULL )\n{\n\tint s = b.size();\n\tint i;\n\tub::matrix< interval<T> > b1, x1;\n\tbool bo;\n\n\tb1.resize(s, 1);\n\tx1.resize(s, 1);\n\tx.resize(s);\n\n\tfor (i=0; i<s; i++) b1(i, 0) = b(i);\n\n\tbo = vleq(a, b1, x1, r);\n\tif (bo == false) return false;\n\n\tfor (i=0; i<s; i++) x(i) = x1(i, 0);\n\n\treturn true;\n}\n\n} // namespace kv\n\n#endif // VLEQ_HPP\n", "meta": {"hexsha": "32bec8415d4f941ea675a3b66a3d91081b11aeca", "size": 2141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/vleq.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/vleq.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/vleq.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": 18.9469026549, "max_line_length": 63, "alphanum_fraction": 0.5964502569, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6809724832605107}}
{"text": "/*\n * Copyright (c) 2016 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n */\n\n#include <gtest/gtest.h>\n#include <sstream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <boost/math/constants/constants.hpp>\n\n// Given inertia expressed at frame (p, a) and rotation matrix from\n// basis b to basis a, return the inertia expressed at frame (p, b)\nEigen::Matrix3d rotateInertia(const Eigen::Matrix3d &inertia_p_a,\n                              const Eigen::Matrix3d &R_a_b) {\n  return R_a_b.transpose() * inertia_p_a * R_a_b;\n}\n\n// Return the inertia of a point mass located at p\n// (expressed in the same frame as the p coordinates).\nEigen::Matrix3d pointMassInertia(double mass, const Eigen::Vector3d &p) {\n  return mass * (p.array().square().sum() * Eigen::Matrix3d::Identity() -\n                 (p * p.transpose()));\n}\n\nTEST(BodyMass, solidworks) {\n  // std::ofstream os(\"/tmp/out\");\n  auto &os = std::cout;\n\n  // a format which plays nicely with sphinx.\n  Eigen::IOFormat rst(4, 0, \", \", \"\\n\", \"  [\", \"]\", \"\\n\", \"\\n\");\n  // a format which plays nicely with urdf.\n  Eigen::IOFormat urdf(Eigen::StreamPrecision, Eigen::DontAlignCols);\n  Eigen::Array3d half_extents(0.2, 0.3, 0.4);\n  double mass = 2.;\n  double pi = boost::math::constants::pi<double>();\n  Eigen::Array3d half_extents2 = half_extents.square();\n  Eigen::Vector3d moments = mass / 3 * (half_extents2.sum() - half_extents2);\n\n  os << \"Let consider a box of mass \" << mass << \" kg and half-lengths (m)::\\n\"\n     << half_extents.transpose().format(rst) << \"\\n\"\n     << \"its principal moments of inertia are (kg m^2)::\\n\"\n     << moments.transpose().format(rst) << \" \\n\\n\";\n\n  os << \"Let name \\\"a\\\" the basis aligned with the box axis, and \\\"c\\\"\"\n        \" the box center (which is also its center of mass).\\n\"\n        \"The box rotational inertia matrix at center of mass, aligned with \"\n        \"basis a (ie. in the (c,a) frame) is::\\n\";\n  Eigen::Matrix3d inertia_c_a = moments.asDiagonal();\n  os << inertia_c_a.format(rst) << \"\\n\\n\";\n\n  os << \"let name \\\"b\\\" the basis defined by rotating of pi/6 the basis a \"\n        \"around the z-axis.\\n\"\n     << \"The corresponding rotation matrix is::\\n\";\n  Eigen::Matrix3d R_a_b;\n  double yaw_angle = pi / 6;\n  R_a_b = Eigen::AngleAxisd(yaw_angle, Eigen::Vector3d::UnitZ());\n  os << R_a_b.format(rst) << \"\\n\\n\";\n\n  os << \"The box rotational inertia matrix at center of mass, aligned with \"\n        \"basis b (ie. in the (c,b) frame) is::\\n\";\n  Eigen::Matrix3d inertia_c_b = rotateInertia(inertia_c_a, R_a_b);\n  os << inertia_c_b.format(rst) << \"\\n\"\n     << \"The principal axis of inertia in basis b are the columns::\\n\"\n     << R_a_b.transpose().format(rst) << \"\\n\\n\";\n\n  Eigen::Vector3d p_c_a = half_extents;\n  os << \"Let name \\\"p\\\" a corner of the box.\\n\"\n     << \"It's coordinates in the (c, a) frame are::\\n\"\n     << p_c_a.transpose().format(rst) << \"\\n\"\n     << \"The box rotational inertia matrix at p, aligned with basis a is::\\n\";\n  Eigen::Matrix3d inertia_p_a = pointMassInertia(mass, p_c_a) + inertia_c_a;\n  os << inertia_p_a.format(rst) << \"\\n\\n\";\n\n  os << \"The coordinates of p in the (c, b) frame are::\\n\";\n  Eigen::Vector3d p_c_b = R_a_b.transpose() * p_c_a;\n  os << p_c_b.transpose().format(rst) << \"\\n\\n\";\n\n  os << \"The box rotational inertia matrix in the (p, b) frame can be \"\n        \"computed from the one at (p, a)::\\n\";\n  Eigen::Matrix3d inertia_p_b = rotateInertia(inertia_p_a, R_a_b);\n  os << inertia_p_b.format(rst) << \"\\n\\n\"\n     << \"...or from the one at (c, b)::\\n\";\n  Eigen::Matrix3d inertia_p_b_bis = pointMassInertia(mass, p_c_b) + inertia_c_b;\n  os << inertia_p_b_bis.format(rst) << \"\\n\\n\";\n\n  std::stringstream sv_c_a;\n  sv_c_a << \"      <visual>\\n\"\n         << \"          <origin xyz=\\\"\" << (-p_c_b.transpose()).format(urdf)\n         << \"\\\" rpy=\\\"0 0 \" << -yaw_angle << \"\\\"/>\\n\"\n         << \"          <geometry>\\n\"\n         << \"              <box size=\\\"\" << (2 * half_extents).transpose()\n         << \"\\\"/>\\n\"\n         << \"          </geometry>\\n\"\n         << \"      </visual>\\n\";\n\n  std::stringstream si_c_b;\n  si_c_b << \"      <inertial>\\n\"\n         << \"          <mass value=\\\"\" << mass << \"\\\"/>\\n\"\n         << \"          <origin xyz=\\\"\" << (-p_c_b.transpose()).format(urdf)\n         << \"\\\"/>\\n\"\n         << \"          <inertia\"\n         << \" ixx=\\\"\" << inertia_c_b(0, 0) << \"\\\"\"\n         << \" ixy=\\\"\" << inertia_c_b(0, 1) << \"\\\"\"\n         << \" ixz=\\\"\" << inertia_c_b(0, 2) << \"\\\"\"\n         << \" iyy=\\\"\" << inertia_c_b(1, 1) << \"\\\"\"\n         << \" iyz=\\\"\" << inertia_c_b(1, 2) << \"\\\"\"\n         << \" izz=\\\"\" << inertia_c_b(2, 2) << \"\\\" />\\n\"\n         << \"      </inertial>\\n\";\n\n  std::stringstream si_c_a;\n  si_c_a << \"      <inertial>\\n\"\n         << \"          <mass value=\\\"\" << mass << \"\\\"/>\\n\"\n         << \"          <origin xyz=\\\"\" << (-p_c_b.transpose()).format(urdf)\n         << \"\\\" rpy=\\\"0 0 \" << -yaw_angle << \"\\\"/>\\n\"\n         << \"          <inertia\"\n         << \" ixx=\\\"\" << inertia_c_a(0, 0) << \"\\\"\"\n         << \" ixy=\\\"\" << inertia_c_a(0, 1) << \"\\\"\"\n         << \" ixz=\\\"\" << inertia_c_a(0, 2) << \"\\\"\"\n         << \" iyy=\\\"\" << inertia_c_a(1, 1) << \"\\\"\"\n         << \" iyz=\\\"\" << inertia_c_a(1, 2) << \"\\\"\"\n         << \" izz=\\\"\" << inertia_c_a(2, 2) << \"\\\" />\\n\"\n         << \"      </inertial>\\n\";\n\n  os << \"Let now assume one wants to model this box as an URDF link, using\"\n        \" frame (p, b) as the link origin.\\n\"\n        \"Our box visual can be displayed using the URDF \\\"box\\\" element,\"\n        \" placed in frame (c, a)::\\n\\n\" << sv_c_a.str() << \"\\n\";\n\n  os << \"Let now assume one wants to model this box as an URDF link, using\"\n        \" frame (p, b) as the link origin.\\n\"\n        \"The inertial URDF element can be defined in frame (c, b), resulting\"\n        \" in::\\n\\n\" << si_c_b.str() << \"\\n\\n\";\n\n  os << \"...or in frame (c, a), resulting in::\\n\\n\" << si_c_a.str() << \"\\n\";\n\n  os << \"The full URDF file being::\\n\\n\"\n     << \"  <robot name=\\\"MyBox\\\">\\n\"\n     << \"  <link name=\\\"Box\\\">\\n\" << sv_c_a.str() << si_c_b.str()\n     << \"  </link>\\n\"\n     << \"  </robot>\\n\";\n\n  EXPECT_TRUE(inertia_p_b_bis.isApprox(inertia_p_b));\n}\n", "meta": {"hexsha": "3d63ae2ab5c49fddd474a8ad756fb9197b11cb11", "size": 6178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/scenegraph/test_bodymass_solidworks.cpp", "max_stars_repo_name": "UCCS-Social-Robotics/libalmath", "max_stars_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-14T20:34:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T05:53:00.000Z", "max_issues_repo_path": "test/scenegraph/test_bodymass_solidworks.cpp", "max_issues_repo_name": "UCCS-Social-Robotics/libalmath", "max_issues_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T05:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:18:20.000Z", "max_forks_repo_path": "test/scenegraph/test_bodymass_solidworks.cpp", "max_forks_repo_name": "UCCS-Social-Robotics/libalmath", "max_forks_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-11T16:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T20:41:05.000Z", "avg_line_length": 42.3150684932, "max_line_length": 80, "alphanum_fraction": 0.548235675, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6809648979025049}}
{"text": "#include <cmath>\n#include <iostream>\n#include <boost/math/special_functions/hypergeometric_1F1.hpp>\n#include <boost/math/special_functions/hypergeometric_2F0.hpp>\n#include \"quicksvg/graph_fn.hpp\"\n#include \"quicksvg/plot_time_series.hpp\"\n\n\nusing boost::math::hypergeometric_1F1;\nusing boost::math::hypergeometric_2F0;\n\nint main() {\n\n    double a = -3.14159;\n    double b = 3.14159;\n    std::string title = \"sin(\ud835\udc65) and cos(\ud835\udc65)\";\n    std::string filename = \"examples/sine_and_cosine.svg\";\n    auto f = [](double x)->double { return std::sin(x); };\n    auto g = [](double x)->double { return std::cos(x); };\n    quicksvg::graph_fn sin_graph(a, b, title, filename);\n\n    sin_graph.add_fn(f);\n    sin_graph.add_fn(g, \"green\");\n\n    sin_graph.write_all();\n\n    auto onef1_1 = [](double x)->double { return hypergeometric_1F1(3, 7, x); };\n    a = -3;\n    b = 2;\n    title = \"\\u2081F\\u2081(3, 7, \ud835\udc65)\";\n    filename = \"examples/1F1_1.svg\";\n    quicksvg::graph_fn onef1_1graph(a, b, title, filename);\n    onef1_1graph.add_fn(onef1_1);\n    onef1_1graph.write_all();\n\n    auto onef1_2 = [](double x)->double { return hypergeometric_1F1(-2, 3, x); };\n    a = -3;\n    b = 2;\n    title = \"\\u2081F\\u2081(-2, 3, \ud835\udc65)\";\n    filename = \"examples/1F1_2.svg\";\n    quicksvg::graph_fn onef1_2graph(a, b, title, filename);\n    onef1_2graph.add_fn(onef1_2);\n    onef1_2graph.write_all();\n\n    auto onef1_3 = [](double x)->double { return hypergeometric_1F1(2, -2.5, x); };\n    a = -2;\n    b = 1;\n    title = \"\\u2081F\\u2081(2, -2.5, \ud835\udc65)\";\n    filename = \"examples/1F1_3.svg\";\n\n    quicksvg::graph_fn onef1_3graph(a, b, title, filename);\n    onef1_3graph.add_fn(onef1_3);\n    onef1_3graph.write_all();\n\n    auto onef1_4 = [](double x)->double { return hypergeometric_1F1(-2, -2.5, x); };\n    a = -4;\n    b = 1;\n    title = \"\\u2081F\\u2081(-2, -2.5, \ud835\udc65)\";\n    filename = \"examples/1F1_4.svg\";\n    quicksvg::graph_fn onef1_4graph(a, b, title, filename);\n    onef1_4graph.add_fn(onef1_4);\n    onef1_4graph.write_all();\n\n\n\n    std::vector<double> v(50);\n    std::vector<double> u(50);\n    double start_time = 0;\n    double time_step = 0.25;\n    for (size_t i = 0; i < v.size(); ++i) {\n      v[i] = std::sin(start_time + i*time_step);\n      u[i] = std::cos(start_time + i*time_step);\n    }\n\n    title = \"sine and cosine time series\";\n    filename = \"examples/sin_cos_time_series.svg\";\n\n    quicksvg::plot_time_series pts(start_time, time_step, title, filename);\n    pts.add_dataset(v);\n    pts.add_dataset(u, false, \"lime\", \"lightgreen\");\n    pts.write_all();\n\n}\n", "meta": {"hexsha": "edadd32614fc4cb6894866a6015a901a2b774199", "size": 2523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "NAThompson/quicksvg", "max_stars_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:07:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T00:07:53.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "NAThompson/quicksvg", "max_issues_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_issues_repo_licenses": ["MIT"], "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": "NAThompson/quicksvg", "max_forks_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T13:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T11:30:58.000Z", "avg_line_length": 30.0357142857, "max_line_length": 84, "alphanum_fraction": 0.6341656758, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6809093077367313}}
{"text": "#include <MishMesh/PolyMesh.h>\n\n#ifdef HAS_EIGEN\n#include <Eigen/Eigen>\n#endif\n\n/*\n * Fit vertices to a plane defined by a set of points with normals as described in\n * Ju, Tao, et al. \"Dual contouring of hermite data.\" Proceedings of the 29th annual conference on Computer graphics and interactive techniques. 2002.\n * and\n * Lindstrom, P. (2000, July). Out-of-core simplification of large polygonal models. In Proceedings of the 27th annual conference on Computer graphics and interactive techniques (pp. 259-262).\n */\n\nnamespace MishMesh {\n\tnamespace Meshing {\n\t\tenum SVDCutoffType {\n\t\t\tRELATIVE,\n\t\t\tABSOLUTE\n\t\t};\n\t\tconstexpr double SVD_CUTOFF_FACTOR = 0.1;\n\n\t\t/**\n\t\t * Fit a point to the average of a set of points and clip it to a bounding box.\n\t\t * @param The mesh.\n\t\t * @param vh The vertex handle for the point to fit.\n\t\t * @param points a set of points, that is used to calculcate the average.\n\t\t */\n\t\tvoid fit_vertex_average(MishMesh::PolyMesh &mesh,\n\t\t                        const MishMesh::PolyMesh::VertexHandle vh,\n\t\t                        const MishMesh::BBox<OpenMesh::Vec3d, 3> &bbox,\n\t\t                        const std::vector<OpenMesh::Vec3d> &points) {\n\t\t\tOpenMesh::Vec3d x = std::accumulate(points.begin(), points.end(), OpenMesh::Vec3d{0, 0, 0}) / points.size();\n\t\t\tmesh.set_point(vh, OpenMesh::Vec3d(x.data()));\n\t\t}\n\n#ifdef HAS_EIGEN\n\t\t/**\n\t\t * Fit a point to a plane defined by a set of points with normals.\n\t\t * @param The mesh.\n\t\t * @param vh The vertex handle for the point to fit.\n\t\t * @param bbox a bounding box that is used to clip the point when it lies outside.\n\t\t * @param points a set of points, that is used to calculcate the average.\n\t\t * @param normals The normals at the points in the points array.\n\t\t * @param clip If clip is true, the result will be clipped on the bounding box.\n\t\t * @param svd_cutoff_type For absolute cutoff, singular values smaller than svd_cutoff_factor\n\t\t *        are truncated and for relative cutoff singular values S_i with S_i/S_0 smaller than\n\t\t *        svd_cutoff_factor are truncated.\n\t\t * @param svd_cutoff_factor Threshold which singular values are truncated to avoid instable results,\n\t\t *        when determining the plane of the points.\n\t\t */\n\t\tvoid fit_vertex_svd(MishMesh::PolyMesh &mesh,\n\t\t                    const MishMesh::PolyMesh::VertexHandle vh,\n\t\t                    const MishMesh::BBox<OpenMesh::Vec3d, 3> &bbox,\n\t\t                    const std::vector<OpenMesh::Vec3d> &points,\n\t\t                    const std::vector<OpenMesh::Vec3d> &normals,\n\t\t                    const bool clip,\n\t\t                    const SVDCutoffType svd_cutoff_type,\n\t\t                    const double svd_cutoff_factor) {\n\t\t\tEigen::Matrix3d ATA;\n\t\t\tEigen::Vector3d ATb;\n\t\t\tATA.setZero();\n\t\t\tATb.setZero();\n\t\t\tassert(points.size() == normals.size());\n\t\t\tMishMesh::BBox<Eigen::Vector3d, 3> cube_bbox_eigen{Eigen::Vector3d(bbox.ltf.data()), Eigen::Vector3d(bbox.rbn.data())};\n\t\t\tfor(int i = 0; i < points.size(); i++) {\n\t\t\t\tEigen::Vector3d p_i(points[i].data());\n\t\t\t\tEigen::Matrix<double, 3, 1> n_i(normals[i].data());\n\t\t\t\tassert(1.0 - n_i.norm() < FLT_EPSILON);\n\t\t\t\tATA += n_i * n_i.transpose();\n\t\t\t\tassert(cube_bbox_eigen.contains(p_i));\n\t\t\t\tATb += n_i * (n_i.transpose().dot(p_i));\n\t\t\t}\n\n\t\t\tEigen::Vector3d cell_center = (cube_bbox_eigen.rbn + cube_bbox_eigen.ltf) / 2.0;\n\t\t\tEigen::JacobiSVD<Eigen::Matrix3d> svd(ATA, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\t\tsvd.compute(ATA);\n\t\t\tEigen::MatrixXd S = svd.singularValues().asDiagonal();\n\t\t\t// Invert the singular values diagonal matrix to calculate the pseudo inverse,\n\t\t\t// but cut off small singular values.\n\t\t\tfor(short j = 0; j < 3; j++) {\n\t\t\t\tif(svd_cutoff_type == SVDCutoffType::RELATIVE && S(j, j) / S(0, 0) < svd_cutoff_factor) {\n\t\t\t\t\t// Relative cutoff like in Lindstrom 2000\n\t\t\t\t\tS(j, j) = 0.0;\n\t\t\t\t} else if(svd_cutoff_type == SVDCutoffType::ABSOLUTE && S(j, j) < svd_cutoff_factor) {\n\t\t\t\t\t// Absolute cutoff like in Ju et al. 2002\n\t\t\t\t\tS(j, j) = 0.0;\n\t\t\t\t} else {\n\t\t\t\t\tS(j, j) = 1.0 / S(j, j);\n\t\t\t\t}\n\t\t\t}\n\t\t\tEigen::MatrixXd ATA_pinv = svd.matrixV() * S * svd.matrixU().transpose();\n\t\t\tEigen::Vector3d x = cell_center + ATA_pinv * (ATb - ATA * cell_center);\n\t\t\tif(clip) {\n\t\t\t\tx = cube_bbox_eigen.clip(x, 0.2);\n\t\t\t}\n\n\t\t\tmesh.set_point(vh, OpenMesh::Vec3d(x.data()));\n\t\t}\n#endif\n\t}\n}", "meta": {"hexsha": "97c9c8fcd42c4acf9b638965c5cec280c05b0e5f", "size": 4316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/meshing/vertexfit.hpp", "max_stars_repo_name": "aschier/MishMesh", "max_stars_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-15T11:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T02:30:47.000Z", "max_issues_repo_path": "src/meshing/vertexfit.hpp", "max_issues_repo_name": "aschier/MishMesh", "max_issues_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "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/meshing/vertexfit.hpp", "max_forks_repo_name": "aschier/MishMesh", "max_forks_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T13:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T13:25:28.000Z", "avg_line_length": 42.7326732673, "max_line_length": 192, "alphanum_fraction": 0.6501390176, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6808734386655196}}
{"text": "// Copyright \u00a9 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include <boost/math/distributions.hpp>\n#include <vinecopulib/misc/tools_eigen.hpp>\n\nnamespace vinecopulib {\n\nnamespace tools_stats {\n\n\n//! @brief Density function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated densities.\ninline Eigen::MatrixXd dnorm(const Eigen::MatrixXd &x)\n{\n    boost::math::normal dist;\n    auto f = [&dist](double y) { return boost::math::pdf(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Distribution function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated probabilities.\ninline Eigen::MatrixXd pnorm(const Eigen::MatrixXd &x)\n{\n    boost::math::normal dist;\n    auto f = [&dist](double y) { return boost::math::cdf(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Quantile function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated quantiles.\ninline Eigen::MatrixXd qnorm(const Eigen::MatrixXd &x)\n{\n    boost::math::normal dist;\n    auto f = [&dist](double y) { return boost::math::quantile(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Density function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated densities.\ninline Eigen::MatrixXd dt(const Eigen::MatrixXd &x, double nu)\n{\n    boost::math::students_t dist(nu);\n    auto f = [&dist](double y) { return boost::math::pdf(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Distribution function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated probabilities.\ninline Eigen::MatrixXd pt(const Eigen::MatrixXd &x, double nu)\n{\n    boost::math::students_t dist(nu);\n    auto f = [&dist](double y) { return boost::math::cdf(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Quantile function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated quantiles.\ninline Eigen::MatrixXd qt(const Eigen::MatrixXd &x, double nu)\n{\n    boost::math::students_t dist(nu);\n    auto f = [&dist](double y) { return boost::math::quantile(dist, y); };\n    return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\nEigen::MatrixXd simulate_uniform(const size_t& n, const size_t& d,\n                                 std::vector<int> seeds = std::vector<int>());\n\nEigen::MatrixXd simulate_uniform(const size_t& n, const size_t& d, bool qrng,\n                                  std::vector<int> seeds = std::vector<int>());\n\nEigen::VectorXd to_pseudo_obs_1d(Eigen::VectorXd x,\n                                 std::string ties_method = \"average\");\n\nEigen::MatrixXd to_pseudo_obs(Eigen::MatrixXd x,\n                              std::string ties_method = \"average\");\n\ndouble pairwise_mcor(const Eigen::Matrix<double, Eigen::Dynamic, 2>& x,\n                     const Eigen::VectorXd &weights = Eigen::VectorXd());\n\nEigen::MatrixXd dependence_matrix(const Eigen::MatrixXd &x,\n                                  const std::string &measure);\n\nEigen::MatrixXd ghalton(const size_t& n, const size_t& d,\n                        std::vector<int> seeds = std::vector<int>());\n\nEigen::MatrixXd sobol(const size_t& n, const size_t& d,\n                      std::vector<int> seeds = std::vector<int>());\n\nEigen::VectorXd pbvt(const Eigen::Matrix<double, Eigen::Dynamic, 2> &z,\n                     int nu, double rho);\n\nEigen::VectorXd pbvnorm(const Eigen::Matrix<double, Eigen::Dynamic, 2> &z,\n                        double rho);\n}\n\n}\n\n#include <vinecopulib/misc/implementation/tools_stats.ipp>\n", "meta": {"hexsha": "1fd66d50a375c306936e00b8d586c90a513acb40", "size": 4258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 33.7936507937, "max_line_length": 79, "alphanum_fraction": 0.6538280883, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6808734307047707}}
{"text": "#pragma once\n\n#include <armadillo>\n\nnamespace random_sinks {\n    arma::mat fwht(arma::mat X, bool apply_to_rows=true);\n\n    template<class T> inline T randchi(double df, uint m, uint n) { // T must be an armadillo Row, Col, or Mat type\n        return arma::sqrt(arma::chi2rnd<T>(df, m, n));\n    }\n\n    template<class T> inline T randchi(double df, uint n) { // T must be an armadillow Row or Col type\n        return arma::sqrt(arma::chi2rnd<T>(df, n));\n    }\n\n    inline double randchi(double df) {\n        return std::sqrt(arma::chi2rnd<double>(df));\n    }\n    \n    class RFF {\n        private:\n        arma::mat _w;\n        arma::rowvec _b;\n        double _gamma;\n        int _nfs, _dim;\n\n        public:\n        const arma::mat& weights;\n        const arma::rowvec& bias;\n\n        RFF(double gamma=1, int n_feats=100, int seed=-1);\n        void fit(const arma::mat& X);\n        arma::mat get_features(const arma::mat& X);\n    };\n\n    class fastfood {\n        private:\n        arma::rowvec _B, _G, _S, _b;\n        arma::uvec _P;\n        int _dim, _nfs, _d;\n        double _gamma;\n\n        public:\n        fastfood(double gamma=1, int n_feats=128, int seed=-1);\n        void fit(const arma::mat& X);\n        arma::mat get_features(arma::mat X);\n    };\n\n    class SORF {\n        private:\n        arma::rowvec _B1, _B2, _B3, _b;\n        int _dim, _d, _nfs;\n        double _gamma;\n\n        public:\n        SORF(double gamma=1, int n_feats=128, int seed=-1);\n        void fit(const arma::mat& X);\n        arma::mat get_features(arma::mat X);\n    };\n\n    void rSVD(arma::mat& U, arma::vec& s, arma::mat& V, const arma::mat& X, uint n_comps);\n    double powerSVD(arma::mat& U, arma::vec& s, arma::mat& V, const arma::mat& X, uint n_comps, uint max_iter=10, double tol=1e-8);\n\n    class tPCA {\n        private:\n        arma::mat _V;\n        arma::vec _s;\n        arma::rowvec _means;\n        int _dim, _n_comps;\n        bool _use_rSVD;\n\n        public:\n        const arma::mat& components;\n        const arma::vec& cov_eigenvals;\n        const int& n_components;\n\n        tPCA(uint n_components, std::string method=\"rSVD\");\n        void fit(arma::mat X, uint max_iter=10, double tol=1e-8, bool zero_mean=false);\n        arma::mat get_features(arma::mat X);\n        arma::mat get_projection(arma::mat X);\n        arma::mat inv_features(arma::mat X);\n    };\n\n    class gauss_nystrom {\n        private:\n        arma::mat _data, _V, _U;\n        arma::vec _s;\n        arma::rowvec  _stds, _means;\n        double _gamma;\n        int _dim, _nfs;\n        arma::mat _eval_kernel(arma::mat X);\n        arma::mat _eval_kernel();\n\n        public:\n        const arma::vec& kernel_singular_vals;\n        const arma::mat& kernel_left_vecs;\n        const arma::mat& kernel_right_vecs;\n        const int& n_features;\n        gauss_nystrom(uint n_feats=128, double gamma=1, int seed=-1);\n        void fit(arma::mat X, std::string method=\"powerSVD\", uint max_iter=20, double tol=1e-10);\n        arma::mat get_features(arma::mat X);\n    };\n}", "meta": {"hexsha": "d8fe211617aefea476a7dc7be74b050f6d4802b2", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/random_kitchen_sinks.hpp", "max_stars_repo_name": "arotem3/random-kitchen-sinks", "max_stars_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T18:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T04:15:08.000Z", "max_issues_repo_path": "include/random_kitchen_sinks.hpp", "max_issues_repo_name": "arotem3/random-kitchen-sinks", "max_issues_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "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/random_kitchen_sinks.hpp", "max_forks_repo_name": "arotem3/random-kitchen-sinks", "max_forks_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-02T09:55:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T09:55:33.000Z", "avg_line_length": 29.2718446602, "max_line_length": 131, "alphanum_fraction": 0.5751243781, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6808233642200094}}
{"text": "//####### Test module for gamma functions #############################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/gamma_functions\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <picsar_qed/physics/gamma_functions.hpp>\n\n#include <picsar_qed/physics/unit_conversion.hpp>\n#include <picsar_qed/math/vec_functions.hpp>\n\nusing namespace picsar::multi_physics::phys;\nusing namespace picsar::multi_physics::math;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-12;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-6;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n\nconst double me_c = electron_mass<double> * light_speed<double>;\nconst double lambda = 800.0e-9;\nconst double omega = 2.0*pi<double>*light_speed<double>/lambda;\n\n// ------------- Tests --------------\n\n//***Test normalized energy calculation for photons\n\ntemplate<typename RealType, unit_system UnitSystem>\nvoid test_gamma_photons(\n    vec3<double> t_p, double t_exp_res, double t_ref_quant = 1.0)\n{\n    const auto p =  vec3<RealType>{\n        static_cast<RealType>(t_p[0]),\n        static_cast<RealType>(t_p[1]),\n        static_cast<RealType>(t_p[2])}*\n        conv<quantity::momentum, unit_system::SI, UnitSystem, RealType>::fact();\n\n    const auto res = compute_gamma_photon<RealType, UnitSystem>(p, t_ref_quant);\n\n    const auto exp_res = static_cast<RealType>(t_exp_res);\n\n    if(exp_res != static_cast<RealType>(0.0))\n        BOOST_CHECK_SMALL((res-exp_res)/exp_res, tolerance<RealType>());\n    else\n        BOOST_CHECK_SMALL(res, tolerance<RealType>());\n}\n\nvoid test_gamma_photons_all_cases(\n    vec3<double> p, double gamma_exp)\n{\n    test_gamma_photons<double, unit_system::SI>(p, gamma_exp);\n    test_gamma_photons<double, unit_system::norm_lambda>(p, gamma_exp, lambda);\n    test_gamma_photons<double, unit_system::norm_omega>(p, gamma_exp, omega);\n    test_gamma_photons<double, unit_system::heaviside_lorentz>(p, gamma_exp, 1.0);\n    test_gamma_photons<float, unit_system::SI>(p, gamma_exp);\n    test_gamma_photons<float, unit_system::norm_lambda>(p, gamma_exp, lambda);\n    test_gamma_photons<float, unit_system::norm_omega>(p, gamma_exp, omega);\n    test_gamma_photons<float, unit_system::heaviside_lorentz>(p, gamma_exp, 1.0);\n}\n\n\nBOOST_AUTO_TEST_CASE( gamma_photons_1 )\n{\n    const double px = 83.759*me_c;\n    const double py = 139.311*me_c;\n    const double pz = -230.553*me_c;\n\n    const double gamma_exp = 282.09539275039566;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_photons_2 )\n{\n    const double px = 9.2627*me_c;\n    const double py = -25.4575*me_c;\n    const double pz = -10.2246*me_c;\n\n    const double gamma_exp = 28.955558407670193;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_photons_3 )\n{\n    const double px = -2314.45*me_c;\n    const double py = -2356.30*me_c;\n    const double pz = 546.28*me_c;\n\n    const double gamma_exp = 3347.723156251126;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_photons_4 )\n{\n    const double px = 0*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n\n    const double gamma_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_photons_5 )\n{\n    const double px = 0.001*me_c;\n    const double py = -0.002*me_c;\n    const double pz = 0.003*me_c;\n\n    const double gamma_exp = 0.0037416573867739412;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_photons_6 )\n{\n    const double px = -2314.45*me_c;\n    const double py = 0.0*me_c;\n    const double pz = 0.0*me_c;\n\n    const double gamma_exp = 2314.45;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_photons_all_cases(p, gamma_exp);\n}\n\n//*******************************\n\n//***Test Lorentz factor calculation for electrons and positrons\n\ntemplate<typename RealType, unit_system UnitSystem>\nvoid test_gamma_ele_pos(\n    vec3<double> t_p, double t_exp_res, double t_ref_quant = 1.0)\n{\n    const auto p =  vec3<RealType>{\n        static_cast<RealType>(t_p[0]),\n        static_cast<RealType>(t_p[1]),\n        static_cast<RealType>(t_p[2])}*\n        conv<quantity::momentum, unit_system::SI, UnitSystem, RealType>::fact();\n\n    const auto res = compute_gamma_ele_pos<RealType, UnitSystem>(p, t_ref_quant);\n\n    const auto exp_res = static_cast<RealType>(t_exp_res);\n\n    if(exp_res != static_cast<RealType>(0.0))\n        BOOST_CHECK_SMALL((res-exp_res)/exp_res, tolerance<RealType>());\n    else\n        BOOST_CHECK_SMALL(res, tolerance<RealType>());\n}\n\nvoid test_gamma_ele_pos_all_cases(\n    vec3<double> p, double gamma_exp)\n{\n    test_gamma_ele_pos<double, unit_system::SI>(p, gamma_exp);\n    test_gamma_ele_pos<double, unit_system::norm_lambda>(p, gamma_exp, lambda);\n    test_gamma_ele_pos<double, unit_system::norm_omega>(p, gamma_exp, omega);\n    test_gamma_ele_pos<double, unit_system::heaviside_lorentz>(p, gamma_exp, 1.0);\n    test_gamma_ele_pos<float, unit_system::SI>(p, gamma_exp);\n    test_gamma_ele_pos<float, unit_system::norm_lambda>(p, gamma_exp, lambda);\n    test_gamma_ele_pos<float, unit_system::norm_omega>(p, gamma_exp, omega);\n    test_gamma_ele_pos<float, unit_system::heaviside_lorentz>(p, gamma_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_1 )\n{\n    const double px = 24.3752*me_c;\n    const double py = -11.5710*me_c;\n    const double pz = -10.0841*me_c;\n\n    const double gamma_exp = 28.822343569703;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_2 )\n{\n    const double px = 4.015*me_c;\n    const double py = 197.287*me_c;\n    const double pz = 141.705*me_c;\n\n    const double  gamma_exp = 242.93947315946826;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_3 )\n{\n    const double px = -2534.83*me_c;\n    const double py = 1011.54*me_c;\n    const double pz = -793.04*me_c;\n\n    const double gamma_exp = 2842.0924935863713;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_4 )\n{\n    const double px = 0*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n\n    const double gamma_exp = 1.0;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_5 )\n{\n    const double px = 0.001*me_c;\n    const double py = -0.002*me_c;\n    const double pz = 0.003*me_c;\n\n    const double gamma_exp = 1.0000069999755001;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\nBOOST_AUTO_TEST_CASE( gamma_ele_pos_6 )\n{\n    const double px = -2534.83*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n\n    const double gamma_exp = 2534.830197251879;\n\n    const auto p = vec3<double>{px,py,pz};\n\n    test_gamma_ele_pos_all_cases(p, gamma_exp);\n}\n\n//*******************************\n", "meta": {"hexsha": "1c68e6c0c711b16b2be8a008cd2e90221fcb0a8a", "size": 7533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_physics/QED/QED_tests/test_picsar_gamma_functions.cpp", "max_stars_repo_name": "NeilZaim/picsar", "max_stars_repo_head_hexsha": "543b9822ca2f78c5b63d62a77fdf0491af5dd12a", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T17:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:20:30.000Z", "max_issues_repo_path": "multi_physics/QED/QED_tests/test_picsar_gamma_functions.cpp", "max_issues_repo_name": "NeilZaim/picsar", "max_issues_repo_head_hexsha": "543b9822ca2f78c5b63d62a77fdf0491af5dd12a", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:55:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T17:00:36.000Z", "max_forks_repo_path": "multi_physics/QED/QED_tests/test_picsar_gamma_functions.cpp", "max_forks_repo_name": "NeilZaim/picsar", "max_forks_repo_head_hexsha": "543b9822ca2f78c5b63d62a77fdf0491af5dd12a", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T13:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:51:38.000Z", "avg_line_length": 27.7970479705, "max_line_length": 82, "alphanum_fraction": 0.6995884774, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.680823357201999}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\tMatrixXf A(4, 4);\n\n\tfloat data[4][4] = {\n\t\t{1, 0, 0, 0},\n\t\t{0, 1, 0, 0},\n\t\t{0, 0, 1, 0},\n\t\t{0, 0, 0, 1}\n\t};\n\n\tfor (size_t row = 0; row < 4; row++) {\n\t\tfor (size_t col = 0; col < 4; col++)\n\t\t\tA(row, col) = data[row][col];\n\t}\n\n\tMatrixXf b(4, 2);\n\tfor (size_t row = 0; row < 4; row++) {\n\t\tb(row, 0) = 1;\n\t\tb(row, 1) = 2;\n\t}\n\n\tMatrixXf x = A.colPivHouseholderQr().solve(b);\n\n\tcout << x << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a3234011b8db958b748fdf73d58b10a242a8106d", "size": 509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_stars_repo_name": "CieloNeet/CG-project", "max_stars_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 289.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T09:07:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:00:25.000Z", "max_issues_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_issues_repo_name": "CieloNeet/CG-project", "max_issues_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-19T07:11:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T06:41:27.000Z", "max_forks_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_forks_repo_name": "CieloNeet/CG-project", "max_forks_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 249.0, "max_forks_repo_forks_event_min_datetime": "2020-02-01T08:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T14:52:58.000Z", "avg_line_length": 14.5428571429, "max_line_length": 47, "alphanum_fraction": 0.5186640472, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6808233467796964}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\n#include <cassert>\n#include <sstream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nstruct Point {\n    double x;\n    double y;\n    string word;\n};\n\nsize_t read_file(string filename, MatrixXd& points, vector<string>& words)\n{\n    vector<Point> output;\n    Point tmp;\n    string line;\n    ifstream infile(filename);\n    assert(infile.is_open());\n\n    while(getline(infile, line)) {\n        // read line in\n\n        // read parts of line\n        istringstream iss(line);\n        iss >> tmp.x >> tmp.y >> tmp.word;\n\n        // add point to list\n        output.push_back(tmp);\n    }\n\n\n    points.resize(2, output.size());\n    words.resize(output.size());\n    for(unsigned int ii=0; ii<output.size(); ii++) {\n        words[ii] = output[ii].word;\n        points(0, ii) = output[ii].x;\n        points(1, ii) = output[ii].y;\n    }\n\n    return output.size();\n}\n\n/**\n * @brief Computes the pseudo inverse with the SVD:\n *\n * A = USV*\n * A^-1 = VS^-1U*\n *\n * @param inmat\n * @param pinvtoler\n */\nMatrixXd pseudo_inverse(MatrixXd& inmat, double pinvtoler=1.e-6)\n{\n    JacobiSVD<MatrixXd> svd(inmat, ComputeThinU | ComputeThinV);\n\n    VectorXd s_inv = svd.singularValues();\n    cerr << endl << s_inv << endl;\n    for(unsigned int ii = 0; ii < s_inv.rows(); ii++) {\n        if(s_inv[ii] > pinvtoler) {\n            s_inv[ii] = 1.0/s_inv[ii];\n        } else {\n            s_inv[ii] = 0;\n        }\n    }\n    return svd.matrixV()*s_inv.asDiagonal()*svd.matrixU().transpose();\n}\n\n/**\n * @brief Solves\n *\n * YW = AXW\n * A = YW (XW)^1\n *\n * where columns of R are points in the reference (fixed) point set, A is an\n * affine matrix (2x3, where column 3 is the shift), M is an augmented matrix\n * with 1' in the bottom row and the top two rows containing coordinates in the\n * moving dataset -- one point per column and W being a correspondance matrix\n * such that correponding points in the R and M matrixes 1 is\n *\n * @param ref\n * @param moving\n * @param weights\n *\n * @return\n */\nvoid solve(const MatrixXd& ref_y, const MatrixXd& mov_x,\n        const VectorXd& weights, Matrix<double, 2, 3>& affine)\n{\n    // Create augmented moving matrix, with lowest row of 1s\n    MatrixXd aug_mov_x = MatrixXd::Ones(mov_x.rows() + 1, mov_x.cols());\n    aug_mov_x.topRows(2) = mov_x;\n\n    MatrixXd tmp = aug_mov_x*weights.asDiagonal();\n    MatrixXd pinv = pseudo_inverse(tmp);\n    affine = ref_y*weights.asDiagonal()*pinv;\n\n    // enforce rigid + scaling ???\n\n}\n\nint main(int argc, char** argv)\n{\n    if(argc != 3) {\n        cerr << \"Need to provide two input files!\" << endl;\n        return -1;\n    }\n\n    vector<string> ref_words;\n    MatrixXd ref_points;\n    read_file(argv[1], ref_points, ref_words);\n\n    vector<string> move_words;\n    MatrixXd move_points;\n    read_file(argv[2], move_points, move_words);\n\n    map<string, int> word_counts;\n    for(auto& word: ref_words) {\n        auto ret = word_counts.insert(pair<string,int>(word,0));\n        if(ret.second) {\n            // element not inserted, so it exists, already existed so just\n            // increment the old count\n            ret.first->second++;\n        }\n    }\n\n    for(auto& v: word_counts) {\n        cerr << v.first << \":\" << v.second << endl;\n    }\n\n    // Reorder points / duplicate / remove points that don't match. Also\n    // initialize weights to down-weight repeated matches\n    VectorXd weights = VectorXd::Ones(ref_points.cols());\n    MatrixXd matches(move_points.cols(), ref_points.cols());\n    for(unsigned int cc = 0; cc < ref_words.size(); cc++) {\n        for(unsigned int rr = 0; rr< move_words.size(); rr++) {\n            cerr << ref_words[cc] << \" vs \" << move_words[cc] << endl;\n            if(ref_words[cc] == move_words[rr]) {\n                matches(rr, cc) = 1;\n                //weights[cc] /= 2.;\n            } else {\n                matches(rr, cc) = 0;\n            }\n        }\n    }\n    MatrixXd move_points_match = move_points*matches;\n    MatrixXd err(ref_points.rows(), ref_points.cols());\n\n    cerr << \"Ref\" << endl << ref_points << endl;\n    cerr << \"Moving\" << endl << move_points_match << endl;\n    cerr << \"Matching\" << endl << matches << endl;\n    cerr << \"Weights\" << endl << weights << endl;\n\n    Matrix<double, 2, 3>  affine(2, 3);\n    affine << 1, 0, 0,\n              0, 1, 0;\n\n    for(int ii = 0; ii < 10; ii++) {\n        MatrixXd adjusted = affine.leftCols(2)*move_points +\n            affine.col(2)*MatrixXd::Ones(1, move_points.cols());\n        cerr << \"Adjusted \" << endl << adjusted << endl;\n\n        // Re-weight based on norms\n        err = ref_points - adjusted;\n        for(size_t rr = 0; rr < weights.rows(); rr++) {\n            weights[rr] = 1./max(0.0001, err.col(rr).norm());\n        }\n        cerr << \"Weights\" << endl << weights << endl;\n\n        cerr << \"Affine\" << endl << affine << endl;\n        solve(ref_points, move_points_match, weights, affine);\n\n    }\n}\n", "meta": {"hexsha": "213d9c2ce949d3ef7cb70d5fb0080f806a4795a6", "size": 4971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "point_match.cpp", "max_stars_repo_name": "micahcc/ctest", "max_stars_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "point_match.cpp", "max_issues_repo_name": "micahcc/ctest", "max_issues_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "point_match.cpp", "max_forks_repo_name": "micahcc/ctest", "max_forks_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_forks_repo_licenses": ["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.4640883978, "max_line_length": 79, "alphanum_fraction": 0.5853952927, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.680804208463726}}
{"text": "/*!=======================================================\n  |                                                     |\n  |                     tensor.cpp                      |\n  |                                                     |\n  -------------------------------------------------------\n  | The source file for a class definition that allows  |\n  | n-dimensional tensors. The data for the tensor is   |\n  | stored in a 2 dimensional array and there is logic  |\n  | which allows referencing to the correct indices to  |\n  | occur.                                              |\n  =======================================================\n  | Dependencies:                                       |\n  | Eigen: An implementation of various matrix          |\n  |        commands. The implementation of the data     |\n  |        matrix uses such a matrix.                   |\n  =======================================================*/\n  \n#include <functional>\n#include <iostream>\n#include <numeric>\n#include <vector>\n#include <Eigen/Dense>\n#include <tensor.h>\n\nnamespace tensor{\n    //!==\n    //!|\n    //!| Functions\n    //!|\n    //!==\n        \n    Tensor23 eye(){\n        /*!Return the second order identity tensor\n        \n        Populate the second order identity tensor.\n        This function is useful so that a consistent identity tensor can be used \n        with different storage schemes.*/\n        \n        //Initialize the matrix\n        \n        Tensor23 I({3,3});\n        \n        for(int i=0; i<3; i++){\n            I(i,i) = 1.;\n        }\n        return I;\n    }\n    Tensor43 FOT_eye(){\n        /*!Return the fourth order identity tensor\n        \n        Populate the fourth order identity tensor.\n        This function is useful so that a consistent identity tensor can be used\n        with different storage schemes.*/\n        \n        //Initialize the tensor\n        Tensor43 FOTI({3,3,3,3});\n        Tensor23 I    = eye(); //Get the second order identity tensor\n        \n        for(int i=0; i<3; i++){\n            for(int j=0; j<3; j++){\n                for(int k=0; k<3; k++){\n                    for(int l=0; l<3; l++){\n                        FOTI(i,j,k,l) = I(i,k)*I(j,l);\n                    }\n                }\n            }\n        }\n        \n        return FOTI;\n    }\n}", "meta": {"hexsha": "f868113e9289c45bb0578d5c838359a1ebc959a6", "size": 2293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tensor.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "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/cpp/tensor.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "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/cpp/tensor.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "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.2957746479, "max_line_length": 81, "alphanum_fraction": 0.4077627562, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6808041910557547}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include \"bayesian/graph.hpp\"\n#include \"bayesian/inference/belief_propagation.hpp\"\n\n// Pearl's Belief Propagation Algorithm -> Examples of application of algorithm\n// http://www.cse.unsw.edu.au/~cs9417ml/Bayes/Pages/PearlPropagation.html\n// 2 Samples\nbn::graph_t make_pearl_belief_propagation_graph()\n{\n    bn::graph_t graph;\n    auto vertex_r = graph.add_vertex();\n    auto vertex_s = graph.add_vertex();\n    auto vertex_w = graph.add_vertex();\n    auto vertex_h = graph.add_vertex();\n    auto edge_rw = graph.add_edge(vertex_r, vertex_w);\n    auto edge_rh = graph.add_edge(vertex_r, vertex_h);\n    auto edge_sh = graph.add_edge(vertex_s, vertex_h);\n\n    {\n        vertex_r->id = 1;\n        vertex_r->selectable_num = 2;\n        vertex_r->cpt.assign({}, vertex_r);\n\n        bn::condition_t const cond;\n        vertex_r->cpt[cond].second = {0.2, 0.8};\n    }\n    {\n        vertex_s->id = 2;\n        vertex_s->selectable_num = 2;\n        vertex_s->cpt.assign({}, vertex_s);\n\n        bn::condition_t const cond;\n        vertex_s->cpt[cond].second = {0.1, 0.9};\n    }\n    {\n        vertex_w->id = 3;\n        vertex_w->selectable_num = 2;\n        vertex_w->cpt.assign({vertex_r}, vertex_w);\n\n        bn::condition_t const cond0 = {{vertex_r, 0}};\n        bn::condition_t const cond1 = {{vertex_r, 1}};\n        vertex_w->cpt[cond0].second = {1.0, 0.0};\n        vertex_w->cpt[cond1].second = {0.2, 0.8};\n    }\n    {\n        vertex_h->id = 4;\n        vertex_h->selectable_num = 2;\n        vertex_h->cpt.assign({vertex_r, vertex_s}, vertex_h);\n\n        bn::condition_t const cond00 = {{vertex_r, 0}, {vertex_s, 0}};\n        bn::condition_t const cond01 = {{vertex_r, 0}, {vertex_s, 1}};\n        bn::condition_t const cond10 = {{vertex_r, 1}, {vertex_s, 0}};\n        bn::condition_t const cond11 = {{vertex_r, 1}, {vertex_s, 1}};\n        vertex_h->cpt[cond00].second = {1.0, 0.0};\n        vertex_h->cpt[cond01].second = {1.0, 0.0};\n        vertex_h->cpt[cond10].second = {0.9, 0.1};\n        vertex_h->cpt[cond11].second = {0.0, 1.0};\n    }\n\n    return graph;\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_pearl_part1 )\n{\n    bn::graph_t graph = make_pearl_belief_propagation_graph();\n    auto const vertex = graph.vertex_list();\n    std::vector<std::vector<double>> const teacher_r = {\n        { 0.200, 0.800 },\n        { 0.100, 0.900 },\n        { 0.360, 0.640 },\n        { 0.272, 0.728 }\n    };\n\n    bn::inference::belief_propagation bp(graph);\n    auto const result = bp();\n\n    for(std::size_t i = 0; i < vertex.size(); ++i)\n    {\n        matrix_type const data = result.at(vertex[i]);\n\n        BOOST_CHECK(data.height() == 1);\n\n        for(std::size_t j = 0; j < data.width(); ++j)\n        {\n            BOOST_CHECK_CLOSE(data[0][j], teacher_r[i][j], 0.01);\n        }\n    }\n}\n\n// \u591a\u5206\u306a\u3093\u304b\u9055\u3046\nBOOST_AUTO_TEST_CASE( belief_propagation_pearl_part2 )\n{\n    bn::graph_t graph = make_pearl_belief_propagation_graph();\n    auto const vertex = graph.vertex_list();\n    std::vector<std::vector<double>> const teacher_r = {\n        { 0.7353, 0.2647 },\n        { 0.3382, 0.6618 },\n        { 0.7882, 0.2118 },\n        { 1.0000, 0.0000 }\n    };\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[3]].resize(1, 2, 0);\n    precondition[vertex[3]][0][0] = 1;\n\n    bn::inference::belief_propagation bp(graph);\n    auto const result = bp(precondition);\n\n    for(std::size_t i = 0; i < vertex.size(); ++i)\n    {\n        matrix_type const data = result.at(vertex[i]);\n\n        BOOST_CHECK(data.height() == 1);\n\n        for(std::size_t j = 0; j < data.width(); ++j)\n        {\n            BOOST_CHECK_CLOSE(data[0][j], teacher_r[i][j], 0.1);\n        }\n    }\n}\n\n//\n// resume14:\n// 5 samples\n//\nbn::graph_t make_resume_graph()\n{\n    bn::graph_t graph;\n    auto const vertex_A = graph.add_vertex();\n    auto const vertex_B = graph.add_vertex();\n    auto const vertex_C = graph.add_vertex();\n    auto const vertex_D = graph.add_vertex();\n    auto const edge_AB = graph.add_edge(vertex_A, vertex_B);\n    auto const edge_BC = graph.add_edge(vertex_B, vertex_C);\n    auto const edge_CD = graph.add_edge(vertex_C, vertex_D);\n\n    {\n        bn::condition_t const cond;\n\n        vertex_A->id = 1;\n        vertex_A->selectable_num = 3;\n        vertex_A->cpt.assign({}, vertex_A);\n        vertex_A->cpt[cond].second = { 0.30, 0.60, 0.10 };\n    }\n    {\n        bn::condition_t const cond0 = {{vertex_A, 0}};\n        bn::condition_t const cond1 = {{vertex_A, 1}};\n        bn::condition_t const cond2 = {{vertex_A, 2}};\n\n        vertex_B->id = 2;\n        vertex_B->selectable_num = 3;\n        vertex_B->cpt.assign({vertex_A}, vertex_B);\n        vertex_B->cpt[cond0].second = { 0.20, 0.30, 0.50 };\n        vertex_B->cpt[cond1].second = { 0.30, 0.30, 0.40 };\n        vertex_B->cpt[cond2].second = { 0.80, 0.10, 0.10 };\n    }\n    {\n        bn::condition_t const cond0 = {{vertex_B, 0}};\n        bn::condition_t const cond1 = {{vertex_B, 1}};\n        bn::condition_t const cond2 = {{vertex_B, 2}};\n\n        vertex_C->id = 3;\n        vertex_C->selectable_num = 2;\n        vertex_C->cpt.assign({vertex_B}, vertex_C);\n        vertex_C->cpt[cond0].second = { 0.50, 0.50 };\n        vertex_C->cpt[cond1].second = { 0.70, 0.30 };\n        vertex_C->cpt[cond2].second = { 0.40, 0.60 };\n    }\n    {\n        bn::condition_t const cond0 = {{vertex_C, 0}};\n        bn::condition_t const cond1 = {{vertex_C, 1}};\n\n        vertex_D->id = 4;\n        vertex_D->selectable_num = 3;\n        vertex_D->cpt.assign({vertex_C}, vertex_D);\n        vertex_D->cpt[cond0].second = { 0.40, 0.30, 0.30 };\n        vertex_D->cpt[cond1].second = { 0.20, 0.60, 0.20 };\n    }\n\n    return graph;\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_resume_ex )\n{\n    std::vector<double> const teacher_C = { 0.570, 0.430 };\n\n    bn::graph_t graph = make_resume_graph();\n    auto const vertex = graph.vertex_list();\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[1]].resize(1, 3);\n    precondition[vertex[3]].resize(1, 3);\n    precondition[vertex[1]][0] = { 0.0, 0.0, 1.0 };\n    precondition[vertex[3]][0] = { 1.0, 0.0, 0.0 };\n\n    bn::inference::belief_propagation func(graph);\n    auto const result = func(precondition);\n\n    auto const data = result.at(vertex[2]);\n    BOOST_CHECK(data.height() == 1);\n\n    for(std::size_t i = 0; i < data.width(); ++i)\n    {\n        BOOST_CHECK_CLOSE(data[0][i], teacher_C[i], 3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_resume_sample1 )\n{\n    std::vector<double> const teacher_B = { 0.330, 0.170, 0.500 };\n\n    bn::graph_t graph = make_resume_graph();\n    auto const vertex = graph.vertex_list();\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[2]].resize(1, 2);\n    precondition[vertex[2]][0] = { 0.0, 1.0 };\n\n    bn::inference::belief_propagation func(graph);\n    auto const result = func(precondition);\n\n    auto const data = result.at(vertex[1]);\n    BOOST_CHECK(data.height() == 1);\n\n    for(std::size_t i = 0; i < data.width(); ++i)\n    {\n        BOOST_CHECK_CLOSE(data[0][i], teacher_B[i], 3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_resume_sample2 )\n{\n    std::vector<double> const teacher_B = { 0.310, 0.190, 0.500 };\n\n    bn::graph_t graph = make_resume_graph();\n    auto const vertex = graph.vertex_list();\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[0]].resize(1, 3);\n    precondition[vertex[2]].resize(1, 2);\n    precondition[vertex[0]][0] = { 0.0, 1.0, 0.0 };\n    precondition[vertex[2]][0] = { 0.0, 1.0 };\n\n    bn::inference::belief_propagation func(graph);\n    auto const result = func(precondition);\n\n    auto const data = result.at(vertex[1]);\n    BOOST_CHECK(data.height() == 1);\n\n    for(std::size_t i = 0; i < data.width(); ++i)\n    {\n        BOOST_CHECK_CLOSE(data[0][i], teacher_B[i], 3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_resume_sample3 )\n{\n    std::vector<double> const teacher_A = { 0.300, 0.600, 0.100 };\n\n    bn::graph_t graph = make_resume_graph();\n    auto const vertex = graph.vertex_list();\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[3]].resize(1, 3);\n    precondition[vertex[3]][0] = { 0.0, 0.0, 1.0 };\n\n    bn::inference::belief_propagation func(graph);\n    auto const result = func(precondition);\n\n    auto const data = result.at(vertex[0]);\n    BOOST_CHECK(data.height() == 1);\n\n    for(std::size_t i = 0; i < data.width(); ++i)\n    {\n        BOOST_CHECK_CLOSE(data[0][i], teacher_A[i], 3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( belief_propagation_resume_sample4 )\n{\n    std::vector<double> const teacher_B = { 0.200, 0.300, 0.500 };\n\n    bn::graph_t graph = make_resume_graph();\n    auto const vertex = graph.vertex_list();\n\n    std::unordered_map<bn::vertex_type, bn::matrix_type> precondition;\n    precondition[vertex[0]].resize(1, 3);\n    precondition[vertex[0]][0] = { 1.0, 0.0, 0.0 };\n\n    bn::inference::belief_propagation func(graph);\n    auto const result = func(precondition);\n\n    auto const data = result.at(vertex[1]);\n    BOOST_CHECK(data.height() == 1);\n\n    for(std::size_t i = 0; i < data.width(); ++i)\n    {\n        BOOST_CHECK_CLOSE(data[0][i], teacher_B[i], 3);\n    }\n}\n", "meta": {"hexsha": "52bd71c14a73b10e02890d09a91467d06cdc1973", "size": 9310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/bayesian/test/belief_propagation.cpp", "max_stars_repo_name": "godai0519/BayesianNetwork-Inference", "max_stars_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T07:25:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T19:43:20.000Z", "max_issues_repo_path": "libs/bayesian/test/belief_propagation.cpp", "max_issues_repo_name": "godai0519/BayesianNetwork", "max_issues_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-02-09T12:32:19.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T09:08:17.000Z", "max_forks_repo_path": "libs/bayesian/test/belief_propagation.cpp", "max_forks_repo_name": "godai0519/BayesianNetwork-Inference", "max_forks_repo_head_hexsha": "ab72b5fe96f1b648a98b8b659c4cafcfe96d8204", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2016-08-14T13:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T09:33:18.000Z", "avg_line_length": 30.8278145695, "max_line_length": 79, "alphanum_fraction": 0.6077336198, "num_tokens": 2811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6807491039846032}}
{"text": "/*\nauthor: Kris Gonzalez\ndate: 200118\nobjective: using cmake, compile code that uses eigen, opencv and gainput\n\nstat | descrip\ndone | hello world\ndone | compile with eigen\ndone | compile with opencv\ndone | compile with gainput\n\n*/\n\n#include <iostream>\n#include <Eigen/Dense>                  // eigen library\n#include <opencv2/core/core.hpp>        // cpp libraries\n#include <opencv2/imgcodecs.hpp>        // ...\n#include <opencv2/highgui/highgui.hpp>  // ...\n#include <opencv2/core/mat.hpp>         // ...\n#include <gainput/gainput.h>    // gainput library\n\nusing Eigen::MatrixXd;\n\nint main(){\n    std::printf(\"Eigen Matrix\\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 << m << std::endl;\n    \n    std::printf(\"OpenCV Matrix\\n\");\n    float a[3][3] = {{1,2,1},{7,9,6},{1,5,7}};\n    cv::Mat A(3,3,CV_32F);\n    A = cv::Mat(3,3,CV_32F,a);\n    std::cout << A.t() << '\\n'; // transpose operation here\n    \n    std::printf(\"Initialize gainput lib\\n\");\n    \n}\n", "meta": {"hexsha": "e5f19efadab36576499d5e885aa4f17bfb7b7c27", "size": 1028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_sandbox/cmake_multipleLibs/cmake_multiLib.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/cmake_multipleLibs/cmake_multiLib.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/cmake_multipleLibs/cmake_multiLib.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": 24.4761904762, "max_line_length": 72, "alphanum_fraction": 0.5807392996, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6806958254486261}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <time.h>\n#include <fstream>\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 N = 100; //matrix size; N x N\n    double rhoN = 6;\n    double max;\n    int k,l;\n\n    mat A = mat(N,N,fill::zeros); //indexes go from (0) to (N-1)\n    mat S = mat(N,N,fill::eye);\n    vec rho = vec(N,fill::zeros);\n    fvec eigen = fvec(N);\n\n\n    RHO_A_FILL(rho,A,N,rhoN);\n    Maxoff(A,N,k,l,max);\n    //A.print();\n    int iterations = 0;\n\n    double eps = 1E-10;\n\n    double tau, t, s, c, il, ik, kk, ll, s_ik, s_il;\n    double start, finish;\n\n    start = clock();                      //clock value before eigen solve\n    while(max > eps){\n        tau = (A(l,l)-A(k,k))/(2.*A(k,l));\n        if(tau>0){\n             t = 1.0/(tau + sqrt(1.0 + tau*tau));}\n        else{t = -1.0/( -tau + sqrt(1.0 + tau*tau));}\n     \n        //cosine and sine\n        c = 1./sqrt(1.+t*t);\n        s = t*c;\n     \n        //Jacobi rotating A round theta in N-dim space\n        for(int i = 0; i<N; i++){\n            if ((i != k) && (i !=l)){\n                ik = A(i,k)*c - A(i,l)*s;\n                il = A(i,l)*c + A(i,k)*s;\n                A(i,k) = ik;\n                A(k,i) = ik;\n                A(i,l) = il;\n                A(l,i) = il;\n                }\n            s_ik = S(i,k);\n            s_il = S(i,l);\n            S(i,k) = c*s_ik - s*s_il;\n            S(i,l) = c*s_il + s*s_ik; \n            }\n\n        kk = A(k,k)*c*c - 2.*A(k,l)*c*s + A(l,l)*s*s;\n        ll = A(l,l)*c*c + 2.*A(k,l)*c*s + A(k,k)*s*s;\n     \n        A(k,k) = kk;\n        A(l,l) = ll;\n        A(k,l) = 0;\n        A(l,k) = 0;\n\n        iterations++;\n        Maxoff(A,N,k,l,max);\n\n\n        } //end of while\n    finish = clock();                    //clock value after eigen solve\n\n    //[eigen] is now eigenvalues\n    for(int i = 0; i<N;i++){\n        eigen(i) = A(i,i);\n        }\n\n    eigen = sort(eigen);\n    eigen.print();\n\n    double time = (finish -start)/CLOCKS_PER_SEC/iterations;\n    \n    fstream outfile;\n    outfile.open(\"eigenvectors.dat\",ios::out);\n\n    for (int i = 0; i<N; i++){\n        for (int j = 0; j<N; j++){\n            if(j%N == 0){outfile<<endl;}                        \n            outfile << S(i,j)<<\" \";\n            }\n        }\n    outfile.close();\n\n\n\n    //fstream Outfile;\n    //Outfile.open(\"steps.dat\",ios::out);\n    //Outfile << \"N     epsilon    steps  step_time\"<<endl;\n\n    //Outfile <<N <<\" \"<<eps<<\" \"<<iterations<<\" \"<<time;\n    //Outfile<<endl;\n        \n    //Outfile.close();\n\n} //end of main\n\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN){\n    double h = rhoN/(N);\n    for(int i = 0; i < N;i++){\n        rho(i) = i*h;\n        A(i,i) = 2./(h*h)+(rho(i)*rho(i));\n        if(i<N-1){\n            A(i+1,i) = -1./(h*h);\n            A(i,i+1) = -1./(h*h);\n            }\n        }\n    }\n\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max){\n    max = 0;\n    for(int i = 0; i < N ; i++){\n        for(int j = i+1; j < N ; j++){\n            if ( A(i,j)*A(i,j) > max){\n                max =A(i,j)*A(i,j);\n                k = i; \n                l = j;\n                }\n            }\n        }\n    \n    }\n", "meta": {"hexsha": "9c798c917391b6df4d18c0a37658f5312fb350e9", "size": 3408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project2/code-joseph/jacobi.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.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.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": 24.8759124088, "max_line_length": 98, "alphanum_fraction": 0.4137323944, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.680695823818469}}
{"text": "//---------------------------------Spheral++----------------------------------//\n// QuadraticInterpolator\n//\n// Encapsulates the algorithm and data for parabolic interpolation in 1D\n// Assumes the results is interpolated as y_interp = a + b*x + c*x^2\n//\n// Created by JMO, Fri Dec  4 14:28:08 PST 2020\n//----------------------------------------------------------------------------//\n#include \"QuadraticInterpolator.hh\"\n\n#include <Eigen/Dense>\n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// Default constructor\n//------------------------------------------------------------------------------\nQuadraticInterpolator::QuadraticInterpolator():\n  mN1(),\n  mXmin(),\n  mXmax(),\n  mXstep(),\n  mcoeffs() {\n}\n\n//------------------------------------------------------------------------------\n// Construct with tabulated data\n//------------------------------------------------------------------------------\nQuadraticInterpolator::QuadraticInterpolator(const double xmin,\n                                             const double xmax,\n                                             const std::vector<double>& yvals):\n  mN1(),\n  mXmin(),\n  mXmax(),\n  mXstep(),\n  mcoeffs() {\n  this->initialize(xmin, xmax, yvals);\n}\n\n//------------------------------------------------------------------------------\n// Initialize the interpolation to fit the given data\n// Note, because we're doing a parabolic fit there are 2 fewer sets of coeficients\n// than the size of the table we're fitting.\n//------------------------------------------------------------------------------\nvoid\nQuadraticInterpolator::initialize(const double xmin,\n                                  const double xmax,\n                                  const std::vector<double>& yvals) {\n  const auto n = yvals.size();\n  REQUIRE(n > 2);      // Need at least 3 points to fit a parabola\n  REQUIRE(xmax > xmin);\n\n  mN1 = n - 3;  // Maximum index into arrays\n  mXmin = xmin;\n  mXmax = xmax;\n  mXstep = (xmax - xmin)/(n - 1);\n  mcoeffs.resize(3*(n - 2));\n\n  typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> EMatrix;\n  typedef Eigen::Matrix<double, 3, 1> EVector;\n\n  // We use simple least squares fitting for each 3-point interval, giving us an\n  // exact parabolic fit for those three points.\n  // Find the coefficient fits.\n  double x0, x1, x2;\n  EMatrix A;\n  EVector B, C;\n  for (auto i0 = 0u; i0 < n - 2; ++i0) {\n    const auto i1 = i0 + 1u;\n    const auto i2 = i0 + 2u;\n    CHECK(i2 < n);\n    x0 = xmin + i0*mXstep;\n    x1 = x0 + mXstep;\n    x2 = x1 + mXstep;\n    A << 1.0, x0, x0*x0,\n         1.0, x1, x1*x1,\n         1.0, x2, x2*x2;\n    B << yvals[i0], yvals[i1], yvals[i2];\n    C = A.inverse()*B;\n    mcoeffs[3*i0    ] = C(0);\n    mcoeffs[3*i0 + 1] = C(1);\n    mcoeffs[3*i0 + 2] = C(2);\n  }\n}\n\n//------------------------------------------------------------------------------\n// Destructor\n//------------------------------------------------------------------------------\nQuadraticInterpolator::~QuadraticInterpolator() {\n}\n\n}\n", "meta": {"hexsha": "8dbc227f2789387c70df50d0214db377335b17c9", "size": 3030, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_stars_repo_name": "jmikeowen/Spheral", "max_stars_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T08:58:33.000Z", "max_issues_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_issues_repo_name": "jmikeowen/Spheral", "max_issues_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T23:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:01:33.000Z", "max_forks_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_forks_repo_name": "jmikeowen/Spheral", "max_forks_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:12:39.000Z", "avg_line_length": 32.5806451613, "max_line_length": 82, "alphanum_fraction": 0.4409240924, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6806221989755404}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include \"all_topological_sorts.hpp\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace bglex;\n\nBOOST_AUTO_TEST_CASE(test1) {\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>\n      Graph;\n  Graph G(5);\n  boost::add_edge(0, 1, G);\n  boost::add_edge(1, 2, G);\n  boost::add_edge(1, 4, G);\n  boost::add_edge(3, 4, G);\n\n  vector<vector<int>> reference = {\n      {0, 1, 2, 3, 4}, {0, 1, 3, 4, 2}, {0, 1, 3, 2, 4}, {0, 3, 1, 2, 4},\n      {0, 3, 1, 4, 2}, {3, 0, 1, 2, 4}, {3, 0, 1, 4, 2}};\n\n  std::set<string> reference_str;\n  for (auto r : reference) {\n    string token = \"\";\n    for (auto v : r) {\n      token += to_string(v) + \",\";\n      reference_str.insert(token);\n    }\n  }\n\n  vector<vector<Graph::vertex_descriptor>> ts;\n  ts = bglex::all_topological_sorts<Graph>(G);\n\n  BOOST_CHECK_EQUAL(ts.size(), reference.size());\n  for (auto n = 0; n < ts.size(); n++) {\n    BOOST_CHECK_EQUAL(ts[n].size(), 5);\n    string token = \"\";\n    for (auto m = 0; m < ts[n].size(); m++) {\n      token += to_string(ts[n][m]) + \",\";\n    }\n    BOOST_CHECK(reference_str.find(token) != reference_str.end());\n  }\n}", "meta": {"hexsha": "f2ade01689d7b6b56531151335500cb66b294dad", "size": 1170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/all_topological_sorts.cpp", "max_stars_repo_name": "herenvarno/bglex", "max_stars_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_test/all_topological_sorts.cpp", "max_issues_repo_name": "herenvarno/bglex", "max_issues_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_test/all_topological_sorts.cpp", "max_forks_repo_name": "herenvarno/bglex", "max_forks_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_forks_repo_licenses": ["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.8571428571, "max_line_length": 75, "alphanum_fraction": 0.5871794872, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.680293175865626}}
{"text": "#include \"advent.hpp\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <array>\n#include <fmt/ranges.h>\n#include <fstream>\n#include <functional>\n#include <gsl/gsl_util>\n#include <iostream>\n#include <numeric>\n#include <ranges>\n#include <scn/scn.h>\n#include <vector>\n\nusing std::vector;\nusing std::ranges::sort;\nusing std::views::iota;\nusing std::views::transform;\n\nauto day07(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Error: no input.\");\n        return 1;\n    }\n\n    std::ifstream infile(argv[1]); // NOLINT\n    std::string str;\n\n    std::getline(infile, str);\n    vector<i64> pos; // positions\n    auto res = scn::scan_list(str, pos, ',');\n    ENSURE(res);\n    sort(pos);\n    auto const sz = std::ssize(pos);\n    auto med = sz % 2 == 0 ? pos[sz / 2 - 1] : gsl::narrow<i64>(std::midpoint(pos[sz / 2 - 1], pos[sz / 2]));\n    auto mean = std::accumulate(pos.begin(), pos.end(), double { 0 }) / gsl::narrow<double>(sz);\n    fmt::print(\"mean: {}, median: {}\\n\", mean, med);\n\n    // part 1\n    auto costs1 = pos | transform([&](auto p) { return std::abs(med - p); });\n    fmt::print(\"part 1: {} (pos = {})\\n\", std::accumulate(costs1.begin(), costs1.end(), i64 { 0 }), med);\n\n    // part 2\n    auto sum = [](auto n) { return n * (n + 1) / 2; };\n\n    i64 min_cost = std::numeric_limits<i64>::max();\n    i64 min_pos = 0;\n    for (auto i : iota(gsl::narrow<i64>(std::floor(mean-1)), gsl::narrow<i64>(std::ceil(mean+1)))) {\n        auto costs2 = pos | transform([&](auto p) { return sum(std::abs(i - p)); });\n        auto cost = std::accumulate(costs2.begin(), costs2.end(), i64 { 0 });\n        if (min_cost > cost) {\n            min_cost = cost;\n            min_pos = i;\n        }\n    }\n    fmt::print(\"part 2: {} (pos = {})\\n\", min_cost, min_pos);\n\n    return 0;\n}\n", "meta": {"hexsha": "f5d0a6e749f1828883fcaa1ccf01f9fe7100836a", "size": 1789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day07.cpp", "max_stars_repo_name": "foolnotion/aoc2021", "max_stars_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_stars_repo_licenses": ["MIT"], "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/day07.cpp", "max_issues_repo_name": "foolnotion/aoc2021", "max_issues_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_issues_repo_licenses": ["MIT"], "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/day07.cpp", "max_forks_repo_name": "foolnotion/aoc2021", "max_forks_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T23:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T23:05:48.000Z", "avg_line_length": 28.8548387097, "max_line_length": 109, "alphanum_fraction": 0.5640022359, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.680293173715851}}
{"text": "/*\n * Copyright (C) 2009 The Android Open Source Project\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 <jni.h>\n#include \"HelloEigen.h\"\n\n#include <iostream>\n#include <sstream>\n#include <Eigen/Dense>\n#include <string>\n\nusing namespace Eigen;\n\nstd::string helloMatrix(){\n  std::stringstream ss;\n  ss << __PRETTY_FUNCTION__ << std::endl;\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  ss << \"Here is the matrix m:\\n\" << m << std::endl;\n  VectorXd v(2);\n  v(0) = 4;\n  v(1) = v(0) - 1;\n  ss << \"Here is the vector v:\\n\" << v << std::endl;\n  return ss.str();\n}\nJNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloEigen_helloMatrix\n  (JNIEnv * env, jobject)\n{\n    return env->NewStringUTF( helloMatrix().c_str());\n}\n\n", "meta": {"hexsha": "f69c9975956d7af2833af2b93589663143e77c62", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_stars_repo_name": "liangpengcheng/tng", "max_stars_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-16T06:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-29T13:36:51.000Z", "max_issues_repo_path": "cmake/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_issues_repo_name": "liangpengcheng/tng", "max_issues_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "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/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_forks_repo_name": "liangpengcheng/tng", "max_forks_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-29T11:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-16T03:27:30.000Z", "avg_line_length": 26.9375, "max_line_length": 77, "alphanum_fraction": 0.6744006187, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6802517044950663}}
{"text": "#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include \"../incl/bellman_ford_test.h\"\n#include \"../incl/bellman_ford.h\"\n#include <iostream>\n\n/**\n * Running tests for the following graphs:\n * - regular small graph\n * - small graph with positive edges\n * - small graph with negative cycle\n * - random graph with 1000 nodes and 20*1000*log(1000) edges\n * - grid graph 100x100\n * Using my CHECK_BELLMAN_FORD() checker\n*/\nvoid testAll()\n{\n    std::cout << \"[i] Running all tests\" << std::endl;\n    std::cout << \"[i] Testing Graph with positive weights\" << std::endl;\n    testBF(createTestGraph());\n    std::cout << \"[i] Testing Graph with positive and negative weights\" << std::endl;\n    testBF(createPositiveTestGraph());\n    std::cout << \"[i] Testing Graph with negative cycle\" << std::endl;\n    testBF(createTestGraphWithNegativeCycle());\n    std::cout << \"[i] Random Graph\" << std::endl;\n    testBF(createRandomGraph(1000, 20*1000*log10(1000), -100, 10000));\n    std::cout << \"[i] Grid Graph\" << std::endl;\n    testBF(createGridGraph(100,-100, 10000));\n}\n\n/**\n * Running my bellman ford algorithm and the checker afterwords.\n * If problem occur program terminates.\n * Prints the appropriate message.\n*/\nvoid testBF(Graph G)\n{\n    const int INF = (std::numeric_limits < int >::max)();\n    int i;\n    // init\n    unsigned long  n_vertices = num_vertices(G);\n    std::vector<unsigned long> pred(n_vertices);\n    std::vector<long> dist(n_vertices, INF);\n    WeightMap weight = get(&EdgeProperties::weight, G);\n    // Running\n    bool r_rafa = bellmanFord(G, 0, weight, pred, dist);\n    CHECK_BELLMAN_FORD(G, 0, weight, pred, dist);\n    std::cout << \"[+] Test OK!\" << std::endl;\n}\n\n/**\n * Given a graph runs the 3 algorithms\n * (boost's, leda's and mine) @param(times) times.\n * On each iteration the algorithms are running from different start node.\n * If times=1 then the start node is always the firstone. \n * Prints the average times, and if a negative cycle detected.\n*/\nvoid benchmark(Graph g, int times)\n{\n    std::cout << \"[i] \" << times << \" time(s)\" << std::endl;\n    int i;\n    // setup\n    unsigned long  N = num_vertices(g);\n\n    // **************************************************** BOOST\n    // init\n    WeightMap weight_pmap = get(&EdgeProperties::weight, g);\n    std::vector<int> b_dist(N, (std::numeric_limits < short >::max)());\n    std::vector<std::size_t> b_pred(N);\n    // run\n    bool r_boost;\n    clock_t begin = clock();\n    for(i = 0; i<times ; ++i){\n        for (unsigned long i = 0; i < N; ++i) b_pred[i] = i;\n        int s = (times == 1) ? 0 : randomRange(0, (int)N);\n        b_dist[s] = 0;\n        r_boost = boost::bellman_ford_shortest_paths(\n            g, int(N), weight_pmap, \n            &b_pred[0], &b_dist[0], \n            boost::closed_plus<int>(),\n            std::less<int>(), \n            boost::default_bellman_visitor());\n        if(!r_boost) break;\n    }    \n    clock_t end = clock();\n    double elapsed_secs_boost = double(end-begin) / CLOCKS_PER_SEC / (i+1);\n    // Info\n    std::cout << \"      Average time boost: \" << elapsed_secs_boost << \" seconds\";\n    if(!r_boost) std::cout << \" (negative cycle)\" << std::endl;\n    else std::cout << std::endl;\n\n\n    // **************************************************** RAFA\n    // init\n    std::vector<unsigned long> pred(N);\n    std::vector<long> dist(N, (std::numeric_limits < short >::max)());\n    // run\n    begin = clock();\n    bool r_rafa;\n    for(i = 0; i<times ; ++i) {\n        int s = (times == 1) ? 0 : randomRange(0, (int)N);\n        r_rafa = bellmanFord(g, s, weight_pmap, pred, dist);\n    }\n    end = clock();\n    double elapsed_secs_rafa = double(end - begin) / CLOCKS_PER_SEC / times;\n    // Info\n    std::cout << \"      Average time rafa: \" << elapsed_secs_rafa << \" seconds\";\n    if(!r_rafa) std::cout << \" (negative cycle)\" << std::endl;\n    else std::cout << std::endl;\n}", "meta": {"hexsha": "230ff569ba129141a2acadc0ed8c49ff6ac10da2", "size": 3885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bellman_ford_test.cpp", "max_stars_repo_name": "rafaelglikis/bellman-ford-boost", "max_stars_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-08-15T19:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T05:41:43.000Z", "max_issues_repo_path": "src/bellman_ford_test.cpp", "max_issues_repo_name": "rafaelglikis/bellman-ford-boost", "max_issues_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_issues_repo_licenses": ["MIT"], "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/bellman_ford_test.cpp", "max_forks_repo_name": "rafaelglikis/bellman-ford-boost", "max_forks_repo_head_hexsha": "cff840e8daf45366503b58c11feb77fe14a667c3", "max_forks_repo_licenses": ["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.6422018349, "max_line_length": 85, "alphanum_fraction": 0.5951093951, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.6802516992352227}}
{"text": "/**\n* \\file random-matrix-example.cc\n*\n* \\author Tobias Waurick\n* \\date 21.06.17\n*\n* \n*/\n#include \"ns3/random-matrix.h\"\n#include \"ns3/core-module.h\"\n#include <iostream>\n#include <armadillo>\n#include <stdint.h>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char *argv[])\n{\n\tCommandLine cmd;\n\tuint32_t seed1 = 1,\n\t\t\tseed2 = 1;\n\tcmd.AddValue(\"seed1\", \"first seed\", seed1);\n\tcmd.AddValue(\"seed2\", \"second\", seed2);\n\tcmd.Parse(argc, argv);\n\n\tcout << \"########### 10x20 RANDOM IDENTITY MATRIX ###########\" << endl;\n\tIdentRandomMatrix ranMat(10, 20);\n\tCol<double> x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};\n\tRow<double> y = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\tmat test = ranMat;\n\n\tcout << \"-Seed: \" << seed1 << endl;\n\tranMat.Generate(seed1);\n\tcout << ranMat;\n\n\tcout << \"-Seed: \" << seed2 << endl;\n\tranMat.Generate(seed2);\n\tcout << ranMat;\n\n\tcout << \"-Multiplication: Mat * [1 2 3 ... 20]T\" << endl;\n\tcout << (ranMat * x);\n\n\tcout << \"-Multiplication: [1 2 3 .. 10]*Mat\" << endl;\n\tcout << (y * ranMat);\n\n\tcout << \"Rescaling to 5x10\" << endl;\n\tranMat.SetSize(5, 10);\n\tcout << ranMat;\n\tcout << \"########### 10x20 RANDOM GAUSSIAN MATRIX with mean 0 var 1###########\" << endl;\n\tGaussianRandomMatrix ranMat2(0, 1, 10, 20);\n\n\t\tcout << \"-Seed: \" << seed1 << endl;\n\tranMat2.Generate(seed1);\n\tcout << ranMat2;\n\n\tcout << \"-Seed: \" << seed2 << endl;\n\tranMat2.Generate(seed2);\n\tcout << ranMat2;\n\n\tcout << \"-Mean :\" << endl;\n\tcout << mean(mean(mat(ranMat2))) << endl;\n\tcout << \"-Variance :\" << endl;\n\ttest = mat(ranMat2);\n\ttest.reshape(200, 1);\n\tcout << var(test) << endl;\n\n\tcout << \"Normalized\" << endl;\n\tranMat2.NormalizeToM();\n\tcout << ranMat2;\n\tcout << \"-Mean :\" << endl;\n\tcout << mean(mean(mat(ranMat2))) << endl;\n\tcout << \"-Variance :\" << endl;\n\ttest = mat(ranMat2);\n\ttest.reshape(200, 1);\n\tcout << var(test) << endl;\n\n\tcout << \"Rescaling to 5x10\" << endl;\n\tranMat2.SetSize(5, 10);\n\tcout << ranMat2;\n\tcout << \"########### 10x20 RANDOM BERNOULLIMATRIX###########\" << endl;\n\tBernRandomMatrix ranMat3(10, 20);\n\t\tcout << \"-Seed: \" << seed1 << endl;\n\tranMat3.Generate(seed1);\n\tcout << ranMat3;\n\n\tcout << \"-Seed: \" << seed2 << endl;\n\tranMat3.Generate(seed2);\n\tcout << ranMat3;\n\n\tcout << \"Normalized\" << endl;\n\tranMat3.NormalizeToM();\n\tcout << ranMat3;\n\n\tcout << \"-Mean :\" << endl;\n\tcout << mean(mean(mat(ranMat3))) << endl;\n}", "meta": {"hexsha": "bf3694d83a438f3924dd8a16b4f5696c76c688a9", "size": 2353, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/compressed-sensing/examples/random-matrix-example.cc", "max_stars_repo_name": "HerrFroehlich/ns3-CompressedSensing", "max_stars_repo_head_hexsha": "f5e4e56aeea97794695ecef6183bdaa1b72fd1de", "max_stars_repo_licenses": ["MIT"], "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/compressed-sensing/examples/random-matrix-example.cc", "max_issues_repo_name": "HerrFroehlich/ns3-CompressedSensing", "max_issues_repo_head_hexsha": "f5e4e56aeea97794695ecef6183bdaa1b72fd1de", "max_issues_repo_licenses": ["MIT"], "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/compressed-sensing/examples/random-matrix-example.cc", "max_forks_repo_name": "HerrFroehlich/ns3-CompressedSensing", "max_forks_repo_head_hexsha": "f5e4e56aeea97794695ecef6183bdaa1b72fd1de", "max_forks_repo_licenses": ["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.2577319588, "max_line_length": 89, "alphanum_fraction": 0.5860603485, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6802194980076532}}
{"text": "#include \"MatrixSolver.hpp\"\n#include <Eigen/Dense>\n#include <cassert>\n#include <iostream>\n\nusing namespace Eigen;\n\nMatrixSolver::MatrixSolver(DecompositionType decompositionType)\n    : _decompositionType(decompositionType) {}\n\nvoid MatrixSolver::solve(const Eigen::MatrixXd &A, const Eigen::VectorXd &b,\n                         Eigen::VectorXd &x)\n{\n  if (_decompositionType == LU) {\n    PartialPivLU<MatrixXd> LU;\n    LU.compute(A);\n    x = LU.solve(b);\n  } else if (_decompositionType == QR) {\n    FullPivHouseholderQR<MatrixXd> QR;\n    QR.compute(A);\n    x = QR.solve(b);\n  } else if (_decompositionType == LU2) {\n    PartialPivLU<MatrixXd> LU;\n    LU.compute(A);\n    x = LU.solve(b);\n    VectorXd residual =\n        b -\n        A * x; // only really effective if we could go to higher precision here\n    x = x + LU.solve(residual);\n  } else {\n    assert(false); // Unsupported decomposition type, should be caught in configuration\n                   // already\n  }\n}\n", "meta": {"hexsha": "398a7c3e456177d74b47f24f34ae305d0b73840d", "size": 972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MatrixSolver.cpp", "max_stars_repo_name": "kimkroener/testing-boost-exercise", "max_stars_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MatrixSolver.cpp", "max_issues_repo_name": "kimkroener/testing-boost-exercise", "max_issues_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2022-01-29T01:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:49:23.000Z", "max_forks_repo_path": "src/MatrixSolver.cpp", "max_forks_repo_name": "kimkroener/testing-boost-exercise", "max_forks_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T16:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:22:19.000Z", "avg_line_length": 27.7714285714, "max_line_length": 87, "alphanum_fraction": 0.6430041152, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6802167434208}}
{"text": "/*\n * EigenDecomposition.hpp\n *\n *  Created on: 11/01/2011\n *      Author: jimali\n */\n\n#ifndef EIGENDECOMPOSITION_HPP_\n#define EIGENDECOMPOSITION_HPP_\n\n#if !defined(SWIG)\n#include <Eigen/Core>\n#include <vector>\n#endif\nnamespace rw { namespace math {\n    //! @brief Type representing a set of eigen values and eigen vectors.\n    template< class T = double > class EigenDecomposition\n    {\n      public:\n        /**\n         * @brief Construct new decomposition.\n         * @param vectors [in] the eigen vectors as columns in a matrix.\n         * @param values [in] the corresponding eigen values.\n         */\n        EigenDecomposition (Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > vectors,\n                            Eigen::Matrix< T, Eigen::Dynamic, 1 > values) :\n            _vectors (vectors),\n            _values (values)\n        {}\n\n        /**\n         * @brief returns all eigenvectors as columns in a matrix\n         * @return reference to the matrix.\n         */\n        const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >& getEigenVectors ()\n        {\n            return _vectors;\n        }\n\n        /**\n         * @brief returns the i'th eigenvector\n         * @return the eigen vector.\n         */\n        Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector (size_t i) { return _vectors.col (i); }\n\n        /**\n         * @brief return all eigenvalues\n         * @return the eigen values.\n         */\n        const Eigen::Matrix< T, Eigen::Dynamic, 1 >& getEigenValues () { return _values; }\n\n        /**\n         * @brief returns the i'th eigenvalue\n         * @return the eigenvalue.\n         */\n        T getEigenValue (size_t i) { return _values (i); }\n\n        //! @brief Sort function for ordering of eigen values and vectors.\n        struct MapSort\n        {\n          private:\n            Eigen::Matrix< T, Eigen::Dynamic, 1 >& _values;\n\n          public:\n            /**\n             * @brief Construct new sort function struct.\n             * @param values [in] the eigen values.\n             */\n            MapSort (Eigen::Matrix< T, Eigen::Dynamic, 1 >& values) : _values (values) {}\n\n            /**\n             * @brief Compare the eigen values with the given indices.\n             * @param i0 [in] index of first eigenvalue.\n             * @param i1 [in] index of second eigenvalue.\n             * @return true if first eigenvalue comes before the second (it is smaller), false\n             * otherwise.\n             */\n            bool operator() (const int& i0, const int& i1)\n            {\n                using namespace rw::math;\n                return _values (i0) < _values (i1);\n            }\n        };\n\n        /**\n         * @brief sorts the eigen vectors according to their eigen value. The vector with smallest\n         * eigen value has index 0\n         */\n        void sort ()\n        {\n            std::vector< int > map (_values.size ());\n            for (size_t i = 0; i < map.size (); i++)\n                map[i] = (int) i;\n\n            std::sort (map.begin (), map.end (), MapSort (_values));\n            // now the mapping determines how the new vectors are to be layed out\n            Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > vectors = _vectors;\n            Eigen::Matrix< T, Eigen::Dynamic, 1 > values               = _values;\n            for (size_t i = 0; i < map.size (); i++) {\n                _vectors.col (i) = vectors.col (map[i]);\n                _values (i)      = values (map[i]);\n            }\n        }\n\n      private:\n        Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > _vectors;\n        Eigen::Matrix< T, Eigen::Dynamic, 1 > _values;\n    };\n\n#if !defined(SWIG)\n    using EigenDecompositiond = EigenDecomposition< double >;\n    using EigenDecompositionf = EigenDecomposition< float >;\n#else\n#if SWIG_VERSION < 0x040000\n    SWIG_DECLARE_TEMPLATE (EigenDecomposition_d, rw::math::EigenDecomposition< double >);\n    ADD_DEFINITION (EigenDecomposition_d, EigenDecomposition)\n#else\n    SWIG_DECLARE_TEMPLATE (EigenDecomposition, rw::math::EigenDecomposition< double >);\n#endif\n    SWIG_DECLARE_TEMPLATE (EigenDecomposition_f, rw::math::EigenDecomposition< float >);\n#endif\n}}    // namespace rw::math\n\n#endif /* EIGENDECOMPOSITION_HPP_ */\n", "meta": {"hexsha": "8a67d3f5ee4ffa4de263617e57e2f4302574ace8", "size": 4228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/EigenDecomposition.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/EigenDecomposition.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/EigenDecomposition.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": 33.824, "max_line_length": 100, "alphanum_fraction": 0.5593661306, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.680017469700717}}
{"text": "#include <mpp.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <functional>\n#include <random>\n#include <cstddef>\n\nusing namespace mpp::hamiltonian;\nusing namespace mpp::chains;\nusing namespace boost::numeric::ublas;\n\ndouble log_posterior(vector<double> const & q){\n    double log_post_val(0);\n    for(std::size_t i=0;i<q.size();++i) {\n        log_post_val -= q(i)*q(i);\n    }\n    return log_post_val;\n}\n\nvector<double> grad_log_posterior(vector<double> const & q) {\n    vector<double> dq(q.size());\n    for(std::size_t i=0;i<q.size();++i) {\n        dq(i) = -q(i);\n    }\n    return dq;\n}\n\nint main() {\n    std::size_t const num_dims(10);\n    std::size_t const max_num_steps(10);\n    double const max_eps(1);\n    vector<double> inv_mass_mat(num_dims);\n    for(std::size_t i=0;i<num_dims;++i) {\n        inv_mass_mat(i) = double(1);\n    }\n\n    std::function<double(vector<double> const &)> lp = log_posterior;\n    std::function<\n        vector<double> (vector<double> const &) > glp = grad_log_posterior;\n\n    hmc_sampler<double>  hmc_spr(\n        lp,\n        glp,\n        num_dims,\n        max_num_steps,\n        max_eps,\n        inv_mass_mat\n    );\n\n    std::size_t const num_samples(1000);\n    std::mt19937 rng;\n    std::normal_distribution<double> nrm_dist;\n    vector<double> q_0(num_dims);\n    for(size_t i=0;i<num_dims;++i) {\n        q_0(i) = nrm_dist(rng);\n    }\n    mcmc_chain<double> chn = hmc_spr.run_sampler(num_samples,q_0);\n    std::string chn_file_name(\"./eg_classic_hmc.chain\");\n    chn.write_samples_to_csv(chn_file_name);\n\n    return 0;\n}\n", "meta": {"hexsha": "57ec25a854d261caecf69ec52283d49a57a4519c", "size": 1560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_stars_repo_name": "tbs1980/mpp", "max_stars_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_issues_repo_name": "tbs1980/mpp", "max_issues_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_forks_repo_name": "tbs1980/mpp", "max_forks_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1612903226, "max_line_length": 75, "alphanum_fraction": 0.6346153846, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6799981325967714}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <boost/math/tools/luroth_expansion.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::tools::luroth_expansion;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::constants::pi;\n\ntemplate<class Real>\nvoid test_integral()\n{\n    for (int64_t i = -20; i < 20; ++i) {\n        Real ii = i;\n        auto luroth = luroth_expansion<Real>(ii);\n        auto const & a = luroth.digits();\n        CHECK_EQUAL(size_t(1), a.size());\n        CHECK_EQUAL(i, a.front());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_halves()\n{\n    // x = n + 1/k => lur(x) = ((n; k - 1))\n    // Note that this is a bit different that Kalpazidou (examine the half-open interval of definition carefully).\n    // One way to examine this definition is correct for rationals (it never happens for irrationals)\n    // is to consider i + 1/3. If you follow Kalpazidou, then you get ((i, 3, 0)); a zero digit!\n    // That's bad since it destroys uniqueness and also breaks the computation of the geometric mean.\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(1)/Real(2);\n        auto luroth = luroth_expansion<Real>(x);\n        auto const & a = luroth.digits();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i, a.front());\n        CHECK_EQUAL(int64_t(1), a.back());\n    }\n\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(1)/Real(4);\n        auto luroth = luroth_expansion<Real>(x);\n        auto const & a = luroth.digits();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i, a.front());\n        CHECK_EQUAL(int64_t(3), a.back());\n    }\n\n    for (int64_t i = -20; i < 20; ++i) {\n        Real x = i + Real(1)/Real(8);\n        auto luroth = luroth_expansion<Real>(x);\n        auto const & a = luroth.digits();\n        CHECK_EQUAL(size_t(2), a.size());\n        CHECK_EQUAL(i, a.front());\n        CHECK_EQUAL(int64_t(7), a.back());\n    }\n    // 1/3 is a pain because it's not representable:\n    Real x = Real(1)/Real(3);\n    auto luroth = luroth_expansion<Real>(x);\n    auto const & a = luroth.digits();\n    CHECK_EQUAL(size_t(2), a.size());\n    CHECK_EQUAL(int64_t(0), a.front());\n    CHECK_EQUAL(int64_t(2), a.back());\n}\n\n\nint main()\n{\n    test_integral<float>();\n    test_integral<double>();\n    test_integral<long double>();\n    test_integral<cpp_bin_float_100>();\n\n    test_halves<float>();\n    test_halves<double>();\n    test_halves<long double>();\n    test_halves<cpp_bin_float_100>();\n\n    #ifdef BOOST_HAS_FLOAT128\n    test_integral<float128>();\n    test_halves<float128>();\n    #endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "ef8326aed8449358e361d69a49be4d44bfa94f14", "size": 3032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/luroth_expansion_test.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": "test/luroth_expansion_test.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": "test/luroth_expansion_test.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": 31.5833333333, "max_line_length": 114, "alphanum_fraction": 0.6319261214, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6799981272801835}}
{"text": "#include <stdio.h>\n#include <malloc.h>\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n#define VUL_DEFINE\n#include \"vul_timer.h\"\n\n#include <Eigen/SVD>\n\nusing namespace Eigen;\n\nint main( int argc, char **argv )\n{\n   if( argc < 3 ) {\n      printf( \"Usage: %s [path to image] [rank to reconstruct from] [iterations (optional)]\\n\", argv[ 0 ] );\n      exit(1);\n   }\n\n   int w, h, n;\n   unsigned char *data = stbi_load( argv[ 1 ], &w, &h, &n, 0 );\n   \n   // @TODO(thynn): Don't average into grayscale, do something useful (or each channel separately)\n\tMatrixXf A = MatrixXf( h, w );\n   for( int y = 0; y < h; ++y ) {\n      for( int x = 0; x < w; ++x ) {\n         float v = ( float )data[ ( y * w + x ) * n ] / 255.f;\n         for( int c = 1; c < n; ++c ) {\n            v += ( float )data[ ( y * w + x ) * n + c ] / 255.f;\n         }\n\t\t\tA( y, x ) = v / ( float )n;\n      }\n   }\n\n   char *eptr;\n   int rank = strtol( argv[ 2 ], &eptr, 10 );\n   int wrank = rank;\n\n   printf( \"Computing SVD of %s (%dx%d)\\n\", argv[ 1 ], w, h );\n   vul_timer *t = vul_timer_create( );\n\tJacobiSVD< MatrixXf > svd( A, ComputeThinU | ComputeThinV );\n   uint64_t mms = vul_timer_get_micros( t );\n   printf( \"Completed in %lu.%lus\\n\", mms / 1000000, mms % 1000000 );\n\n\tVectorXf sigma = svd.singularValues();\n   for( int i = 0; i < svd.rank(); ++i ) {\n      printf( \"S[%d]: %f\\n\", i, sigma[i] );\n   }\n\n   printf( \"Rank of decomposition %d, wanted at most %d\\n\", svd.rank(), wrank );\n\n\tMatrixXf B = svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();\n\n   unsigned char *odata = ( unsigned char* )malloc( sizeof( unsigned char ) * w * h * 3 );\n   for( int y = 0; y < h; ++y ) {\n      for( int x = 0; x < w; ++x ) {\n         float v = B( y, x ) * 255.f;\n         v = v < 0.f   ? 0.f \n           : v > 255.f ? 255.f \n           : v;\n         odata[ ( y * w + x ) * 3     ] = v;\n         odata[ ( y * w + x ) * 3 + 1 ] = v;\n         odata[ ( y * w + x ) * 3 + 2 ] = v;\n      }\n   }\n   stbi_write_bmp( \"out.bmp\", w, h, 3, odata );\n   printf( \"Wrote output to out.bmp.\\n\");\n   for( int y = 0; y < h; ++y ) {\n      for( int x = 0; x < w; ++x ) {\n         float v = A( y, x ) * 255.f;\n         v = v < 0.f   ? 0.f \n           : v > 255.f ? 255.f \n           : v;\n         odata[ ( y * w + x ) * 3     ] = v;\n         odata[ ( y * w + x ) * 3 + 1 ] = v;\n         odata[ ( y * w + x ) * 3 + 2 ] = v;\n      }\n   }\n   stbi_write_bmp( \"source.bmp\", w, h, 3, odata );\n   printf( \"Wrote input to source.bmp.\\n\");\n   \n   free( odata );\n   free( data );\n}\n", "meta": {"hexsha": "ab4b1d3c6a9d1a1bb5e322e852b4c5430886151d", "size": 2610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_stars_repo_name": "thynnmas/vul", "max_stars_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-03-07T22:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T11:53:26.000Z", "max_issues_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_issues_repo_name": "thynnmas/vul", "max_issues_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_forks_repo_name": "thynnmas/vul", "max_forks_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_forks_repo_licenses": ["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.3258426966, "max_line_length": 108, "alphanum_fraction": 0.4881226054, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6798971450843868}}
{"text": "#include <iostream>\n#include <vector>\n#include <limits>\n#include <cmath> \n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nusing namespace std;\n\n// Essentially, the tasks asks for the cost of the second best spanning tree.\n// Leia performs Prims MST algorithm. We need at least one edge different to the MST,\n// therefore, the best we can do is computing the second best spanning tree.\nvoid solve() {\n  // Tatooine is not needed for anything\n  int n, tatooine;\n  cin >> n >> tatooine;\n  \n  // Compute a MST (with any algorithm)\n  weighted_graph G(n);\n\n  int cost;\n  vector<vector<int>> costs(n, vector<int>(n));\n  for (int j = 0; j < n - 1; ++j) {\n    for (int k = 0; k < n - j - 1; ++k) {\n      int u = j;\n      int v = j + k + 1;\n      cin >> cost;\n      costs[u][v] = cost;\n      costs[v][u] = cost;\n      boost::add_edge(u, v, cost, G);\n    }\n  }\n  \n  // Use Kurskal (we could also use Prim...does not make any difference)\n  std::vector<edge_desc> mst;\n  boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst));\n  \n  // Extract neighbors from MST and compute MST Value\n  int mstValue = 0;\n  vector<vector<int>> neighbors(n);\n  vector<vector<int>> isMstEdge(n, vector<int>(n, false));\n  for (auto edge : mst) {\n    int u = boost::source(edge, G);\n    int v = boost::target(edge, G);\n    mstValue += costs[u][v];\n    neighbors[u].push_back(v);\n    neighbors[v].push_back(u);\n    isMstEdge[u][v] = true;\n    isMstEdge[v][u] = true;\n  }\n  \n  // Compute the most expensive edge for every u-v path in the MST\n  vector<vector<int>> uvMaxEdge(n, vector<int>(n, 0));\n  \n  for (int u = 0; u < n; ++u) {\n    vector<int> stack;\n    stack.push_back(u);\n    vector<int> visited(n, false);\n    visited[u] = true;\n  \n    while (!stack.empty()) {\n      int v = *stack.rbegin();\n      stack.pop_back();\n      \n      for (auto w : neighbors[v]) {\n        if (!visited[w]) {\n          visited[w] = true;\n          uvMaxEdge[u][w] = max(costs[v][w], uvMaxEdge[u][v]);\n          stack.push_back(w);\n        }\n      }\n    }\n  }\n  \n  // For all edges e = {u, v}, that are not in the MST, we will try adding e to the MST.\n  // This will introduce a cycle. We remove the most expensive edge of the cycle that is \n  // part of the MST. For this we can simply query the most expensive edge from u to v in the MST \n  // and remove it. The cost of the MST changes by delta = cost[u][v] - cost[most expensive edge].\n  // We simply find the best delta.\n  int minVal = numeric_limits<int>::max();\n  for (int u = 0; u < n; ++u) {\n    for (int v = u + 1; v < n; ++v) {\n      if (!isMstEdge[u][v]) {\n        int val = costs[u][v] - uvMaxEdge[u][v];\n        minVal = min(val, minVal);\n      }\n    }\n  }\n  \n  cout << mstValue + minVal << endl;\n}\n\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  while(t--) {\n    solve();\n  }\n}", "meta": {"hexsha": "72b3dc6b375da047d2487df012e830fb22463c36", "size": 3332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/return_of_the_jedi.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/return_of_the_jedi.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "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/return_of_the_jedi.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 30.8518518519, "max_line_length": 98, "alphanum_fraction": 0.618847539, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6798971450640904}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <array>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multi_array.hpp>\n#include <vector>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include \"mpfr/import_std_math.hpp\"\n#include \"quadrature/qhermitew.hpp\"\n#include \"spectral/hermitenw.hpp\"\n#include \"spectral/lagrange_polynomial.hpp\"\n\n\nnamespace boltzmann {\n\n/**\n * @brief Nodal <-> Hermite transformation matrices in 1d.\n *\n * @remark\n * the nodal basis consists of Lagrange polynomials at Hermite quadrature nodes.\n * The underlying Lagrange polynomials satisfy:\n *\n * \\f$ l_i(x_j) = 0 \\quad \\textrm{for } i  \\neq j \\f$\n *\n * and\n *\n * \\f$ l_i(x_i) = 1/sqrt(w_i) \\f$\n *\n * where \\f$w_i\\f$ are the Gauss-Hermite quadrature weights.\n *\n */\ntemplate <typename NUMERIC_T = double>\nclass H2N_1d\n{\n public:\n  typedef NUMERIC_T numeric_t;\n  //  typedef Eigen::Matrix<numeric_t, Eigen::Dynamic, Eigen::Dynamic> matrix_t;\n\n public:\n  /**\n   *\n   *\n   * @param H2N  hermite to nodal matrix\n   * @param N2H  nodal to hermite matrix\n   * @param K    max. polynomial degree\n   */\n  template <typename MATRIX>\n  static void create(MATRIX& H2N, MATRIX& N2H, const int K);\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\ntemplate <typename MATRIX>\nvoid\nH2N_1d<NUMERIC_T>::create(MATRIX& H2N, MATRIX& N2H, const int K)\n{\n  N2H.resize(K, K);\n  H2N.resize(K, K);\n  //  N2H_.resize(K,K);\n  QHermiteW quad(1, K);\n  HermiteNW<numeric_t> hermw(K);\n  hermw.compute(quad.pts());\n\n  for (int i = 0; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      const double wi = quad.wts(i);\n      H2N(i, j) = hermw.get(j)[i] * ::math::sqrt(wi);\n    }\n  }\n\n  N2H = H2N.transpose();\n}\n\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n/**\n * @brief Nodal <-> Hermite transformation matrices in 1d, nodes of the nodal basis can be\n * arbitrary.\n *\n * The nodes of the nodal basis are located at the nodes of the Gauss-Hermite quadrature rule\n * with weight function  \\f$ exp(-\\alpha r^2) \\f$.\n *\n * @remark\n * ATTENTION: H2N(a=1) is orthonormal, but this is not the case when \\f$ a \\neq 1\\f$!\n *\n *\n * If this class is used together with @a Hermite2Nodal (and alpha!=1), the transformation\n * `N->H` will give wrong results! Only use H->N.  TODO: update code such that BOTH forward AND\n * BACKWARD transformation works.\n *\n */\nclass H2NG_1d\n{\n public:\n  template <typename MATRIX>\n  static void create(MATRIX& H2N, MATRIX& N2H, const int K, const double alpha)\n  {\n    typedef Eigen::VectorXd vec_t;\n\n    H2N.resize(K, K);\n\n    QHermiteW quad4nodes(alpha, K);\n    QHermiteW quad(1, K);\n\n    // Lagrange Poly\n    vec_t xi = Eigen::Map<const vec_t>(quad4nodes.points_data(), K);\n    vec_t li(K);  // lambda's (barycentric interpolation)\n    vec_t yi(K);\n    vec_t x = Eigen::Map<const vec_t>(quad.points_data(), K);\n    vec_t w = Eigen::Map<const vec_t>(quad.weights_data(), K);\n    vec_t y(K);\n    // prepare barycentric interpol. weights\n    LagrangePolynomial<>::compute_weights(li, xi);\n    // evaluate hermite polynomials at quadrature points\n    HermiteNW<double> hermw(K);\n    hermw.compute(quad.pts());\n    const double ah4 = std::pow(alpha, 0.25);\n\n    Eigen::MatrixXd T(K, K);\n    for (int i = 0; i < K; ++i) {\n      yi.setZero();\n      yi[i] = 1.0;\n      LagrangePolynomial<>::evaluate(y, x, xi, yi, li);\n      const double sqrtwi = std::sqrt(w[i]);\n      for (int j = 0; j < K; ++j) {\n        double sum = 0;\n        // quadrature\n        for (int q = 0; q < K; ++q) {\n          sum += hermw.get(j)[q] * std::exp((x[i] * x[i] - x[q] * x[q]) / 2) * ah4 * y[q] * w[q] /\n                 sqrtwi;\n        }\n        T(i, j) = sum;\n      }\n    }\n\n    Eigen::MatrixXd M(K, K);\n    vec_t y1(K);\n    vec_t y2(K);\n    const double ah2 = std::sqrt(alpha);\n    // mass matrix (cf. notes in yellow notebook)\n    for (int i = 0; i < K; ++i) {\n      yi.setZero();\n      yi[i] = 1.0;\n      LagrangePolynomial<>::evaluate(y1, x, xi, yi, li);\n      for (int j = 0; j < K; ++j) {\n        yi.setZero();\n        yi[j] = 1.0;\n        LagrangePolynomial<>::evaluate(y2, x, xi, yi, li);\n        double sum = 0;\n        for (int q = 0; q < K; ++q) {\n          sum += std::exp((x[i] * x[i] + x[j] * x[j]) / 2 - x[q] * x[q]) * y1[q] * y2[q] /\n                 std::sqrt(w[i] * w[j]) * w[q];\n        }\n        M(i, j) = ah2 * sum;\n      }\n    }\n    H2N = M.inverse() * T;\n    N2H = T.transpose();\n  }\n};\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "6e56dc50f51c63365bd6b75c7be1ee020bd9e344", "size": 4755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/h2n_1d.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral/h2n_1d.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral/h2n_1d.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6453488372, "max_line_length": 98, "alphanum_fraction": 0.5509989485, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6798667007557146}}
{"text": "/*\n* Copyright (c) 2019 Nobuyuki Umetani\n*\n* This source code is licensed under the MIT license found in the\n* LICENSE file in the root directory of this source tree.\n*/\n\n/**\n * @brief demo for visualizing eigenmodes\n */\n\n#include <Eigen/Eigenvalues>\n#if defined(_WIN32) // windows\n#  define NOMINMAX   // to remove min,max macro\n#  include <windows.h>  // should put before glfw3.h\n#endif\n#define GL_SILENCE_DEPRECATION\n#include <GLFW/glfw3.h>\n\n#include \"delfem2/eigen/ls_dense.h\"\n#include \"delfem2/lsitrsol.h\"\n#include \"delfem2/mshprimitive.h\"\n#include \"delfem2/mshuni.h\"\n#include \"delfem2/points.h\"\n#include \"delfem2/femsolidlinear.h\"\n#include \"delfem2/glfw/viewer3.h\"\n#include \"delfem2/glfw/util.h\"\n#include \"delfem2/opengl/old/mshuni.h\"\n\nnamespace dfm2 = delfem2;\n\nvoid ShowEigen_SolidLinear_MeshQuad2(\n    const std::vector<double>& aXY,\n    const std::vector<unsigned int>& aQuad,\n    double elen)\n{\n  const unsigned int np = aXY.size() / 2;\n  Eigen::MatrixXd A(np * 2, np * 2);\n  A.setZero();\n\n  double emat[4][4][2][2];\n  dfm2::EMat_SolidLinear2_QuadOrth_GaussInt(emat, elen, elen, 1.0, 1.0, 2);\n  std::vector<unsigned int> tmp_buffer;\n  for (unsigned int iq = 0; iq < aQuad.size() / 4; ++iq) {\n    const unsigned int aIp[4] = {\n        aQuad[iq * 4 + 0], aQuad[iq * 4 + 1], aQuad[iq * 4 + 2], aQuad[iq * 4 + 3]};\n    delfem2::Merge<4,4,2,2,double>(A,aIp,aIp,emat,tmp_buffer);\n  }\n\n  {\n    auto B = A;\n    B(0,0) += 1.0;\n    B(1,1) += 1.0;\n    B(2,2) += 1.0;\n    B(3,3) += 1.0;\n    Eigen::VectorXd r(np*2), u(np*2), Ap(np*2), p(np*2);\n    r.setRandom();\n    std::vector<double> aConv = dfm2::Solve_CG(r,u,Ap,p,1.0e-5,300,B);\n    std::cout << aConv.size() << std::endl;\n  }\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> s(A);\n  const auto& evec = s.eigenvectors(); // somehow this takes time\n\n  //\n  delfem2::glfw::CViewer3 viewer;\n  delfem2::glfw::InitGLOld();\n  viewer.OpenWindow();\n\n  std::vector<double> aDisp(np*2,0.0);\n\n  for(unsigned int iframe=0;iframe<10;++iframe){\n    std::cout << s.eigenvalues()(iframe) << std::endl;\n    for(unsigned int i=0;i<np*2;++i){\n      aDisp[i] = evec(i,iframe);\n    }\n    for(unsigned int i=0;i<100;++i) {\n      viewer.DrawBegin_oldGL();\n      dfm2::opengl::DrawMeshQuad2D_EdgeDisp(\n          aXY.data(), aXY.size()/2,\n          aQuad.data(), aQuad.size()/4,\n          aDisp.data(),sin(i*0.1));\n      viewer.SwapBuffers();\n      glfwPollEvents();\n    }\n  }\n  glfwDestroyWindow(viewer.window);\n  glfwTerminate();\n}\n\nvoid ShowEigen_SolidLinear_MeshTri2(\n    const std::vector<double>& aXY,\n    const std::vector<unsigned int>& aTri)\n{\n  const unsigned int np = aXY.size()/2;\n  Eigen::MatrixXd A(np*2, np*2);\n  A.setZero();\n\n  std::vector<double> aDisp(np*2,0.0);\n  std::vector<unsigned int> tmp_buffer;\n  for(unsigned int it=0;it<aTri.size()/3;++it){\n    const unsigned int aIp[3] = {aTri[it*3+0], aTri[it*3+1], aTri[it*3+2]};\n    double disp[3][2]; dfm2::FetchData<3,2>(disp,aIp,aDisp.data());\n    double coord[3][2]; dfm2::FetchData<3,2>(coord,aIp,aXY.data());\n    double emat[3][3][2][2], eres[3][2];\n    dfm2::EMat_SolidStaticLinear_Tri2D(\n        eres,emat,\n        1,1,0,0,0,\n        disp,coord);\n    delfem2::Merge<3,3,2,2,double>(A,aIp,aIp,emat,tmp_buffer);\n  }\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> s(A);\n  const auto& evec = s.eigenvectors();\n  //\n  delfem2::glfw::CViewer3 viewer;\n  delfem2::glfw::InitGLOld();\n  viewer.OpenWindow();\n  for(unsigned int iframe=0;iframe<10;++iframe){\n    std::cout << s.eigenvalues()(iframe) << std::endl;\n    for(unsigned int i=0;i<np*2;++i){\n      aDisp[i] = evec(i,iframe);\n    }\n    for(unsigned int i=0;i<100;++i) {\n      viewer.DrawBegin_oldGL();\n      dfm2::opengl::DrawMeshTri2D_EdgeDisp(\n          aXY.data(), aXY.size()/2,\n          aTri.data(), aTri.size()/3,\n          aDisp.data(),sin(i*0.1));\n      viewer.SwapBuffers();\n      glfwPollEvents();\n    }\n  }\n  glfwDestroyWindow(viewer.window);\n  glfwTerminate();\n}\n\nint main()\n{\n  std::cout << \"Available :SIMD Instructions: \"<< Eigen::SimdInstructionSetsInUse() << std::endl;\n  //\n  std::vector<double> aXY;\n  std::vector<unsigned int> aQuad;\n  unsigned int nx = 10;\n  unsigned int ny = 5;\n  dfm2::MeshQuad2D_Grid(\n      aXY,aQuad,\n      nx,ny);\n  const double elen = 0.1;\n  {\n    dfm2::Scale_Points(aXY.data(), aXY.size() / 2, 2, elen);\n    dfm2::Translate_Points2(aXY,-0.5*nx*elen, -0.5*ny*elen);\n  }\n  ShowEigen_SolidLinear_MeshQuad2(aXY, aQuad, elen);\n  //\n  std::vector<unsigned int> aTri;\n  dfm2::convert2Tri_Quad(\n      aTri,\n      aQuad);\n  ShowEigen_SolidLinear_MeshTri2(aXY,aTri);\n}\n", "meta": {"hexsha": "4bf13d036e974387525b549ace2c526889560e0e", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_stars_repo_name": "mmer547/delfem2", "max_stars_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T17:03:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T17:03:36.000Z", "max_issues_repo_path": "examples_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_issues_repo_name": "mmer547/delfem2", "max_issues_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_issues_repo_licenses": ["MIT"], "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_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_forks_repo_name": "mmer547/delfem2", "max_forks_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_forks_repo_licenses": ["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.1419753086, "max_line_length": 97, "alphanum_fraction": 0.6288659794, "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.679859249752509}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <gauss/internal/scopedHostPtr.h>\n#include <gauss/linalg.h>\n#include <gauss/polynomial.h>\n\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\nconstexpr auto EPSILON = 1e-8;\n\nnamespace {\n\naf::array vandermonde(const af::array &x, int order, bool ascending) {\n    af::array result = af::array(x.dims(0), order, x.type());\n    gfor(af::seq i, order) { result(af::span, i) = af::pow(x, i); }\n    if (!ascending) {\n        result = af::flip(result, 1);\n    }\n    return result;\n}\n\n}  // namespace\n\naf::array gauss::polynomial::polyfit(const af::array &x, const af::array &y, int deg) {\n    int order = deg + 1;\n    af::array lhs = vandermonde(x, order, false);\n    const af::array &rhs = y;\n\n    af::array scale = af::max(af::sqrt(af::sum(lhs * lhs, 0)), EPSILON);\n\n    lhs /= af::tile(scale, static_cast<unsigned int>(lhs.dims(0)));\n\n    af::array c = gauss::linalg::lls(lhs, rhs);\n    c = af::transpose(c);\n    c /= af::tile(scale, static_cast<unsigned int>(c.dims(0)));\n    c = af::transpose(c);\n\n    return c;\n}\n\naf::array gauss::polynomial::roots(const af::array &pp) {\n    af::array result = af::array(pp.dims(0) - 1, pp.dims(1), af::dtype::c32);\n    for (int i = 0; i < pp.dims(1); i++) {\n        af::array p = pp(af::span, i);\n        // Strip leading and trailing zeros\n        p = p(p != 0);\n\n        p = (-1 * p(af::seq(1, static_cast<double>(p.dims(0)) - 1), af::span)) /\n            af::tile(p(0, af::span), static_cast<unsigned int>(p.dims(0)) - 1);\n\n        auto coeffs = gauss::utils::makeScopedHostPtr(p.as(af::dtype::f32).host<float>());\n\n        Eigen::VectorXf vec = Eigen::VectorXf::Ones(p.dims(0));\n        Eigen::MatrixXf diag = vec.asDiagonal();\n\n        Eigen::MatrixXf diag2(diag.rows(), diag.cols());\n        int rest = static_cast<int>(diag.rows()) - 1;\n        diag2.topRows(1) = Eigen::Map<Eigen::MatrixXf>(coeffs.get(), 1, p.dims(0));\n        diag2.bottomRows(rest) = diag.topRows(rest);\n\n        Eigen::VectorXcf eivals = diag2.eigenvalues();\n\n        result(af::span, i) = af::array(p.dims(0), (af::cfloat *)eivals.data());\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "037707ee2242b972cb1e5539aa44e21e1b19b627", "size": 2313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/polynomial.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/polynomial.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/polynomial.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "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.84, "max_line_length": 90, "alphanum_fraction": 0.5987894509, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.679859249752509}}
{"text": "#ifndef RANDOMNUMBERGENERATOR_HPP_\n#define RANDOMNUMBERGENERATOR_HPP_\n\n// for random sampling\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/math/distributions.hpp>\n#include <cstdlib>\n#include <mutex>\n#include <Eigen/Core>\n\n\ntemplate<typename Dtype>\nclass RandomNumberGenerator {\n\n public:\n\n  RandomNumberGenerator() {\n  }\n\n  ~RandomNumberGenerator() {\n  }\n\n  /* mean =0, std = 1*/\n  Dtype sampleNormal() {\n    auto dist = boost::random::normal_distribution<Dtype>(0.0, 1.0);\n    return dist(rngGenerator);\n  }\n\n  /* from -1 to 1*/\n  Dtype sampleUniform() {\n    auto dist = boost::uniform_real<Dtype>(-1, 1);\n    return dist(rngGenerator);\n  }\n\n  /* from 0 to 1*/\n  Dtype sampleUniform01() {\n    auto dist = boost::uniform_real<Dtype>(0, 1);\n    return dist(rngGenerator);\n  }\n\n  bool forXPercent(float epsilon) {\n    auto dist = boost::uniform_real<Dtype>(0, 1);\n    return dist(rngGenerator) < epsilon;\n  }\n\n  int intRand(const int &min, const int &max) {\n    {\n      std::uniform_int_distribution<int> distribution(min, max);\n      return distribution(rngGenerator);\n    }\n  }\n\n  /* weighted random sampling where the weights are given by 1, r, r^2, ... */\n  int intWeightedRand (const int &max, Dtype weightDecayFtr) {\n    Dtype sum = (Dtype(1) - std::pow(weightDecayFtr, max+1)) / (Dtype(1)-weightDecayFtr);\n    return std::ceil(log(Dtype(1) - sampleUniform01() * sum * (Dtype(1) - weightDecayFtr)) / log(weightDecayFtr)) - 1;\n  }\n\n  template<int dim>\n  void sampleVectorInNormalUniform(Dtype *vector) {\n    auto dist = boost::uniform_real<Dtype>(-1, 1);\n    for (int i = 0; i < dim; i++)\n      vector[i] = dist(rngGenerator);\n  }\n\n  template<int dim>\n  void sampleInUnitSphere(Dtype *vector) {\n    sampleVectorInNormalUniform<dim>(vector);\n    Dtype sum = 0.0f;\n\n    for (int i = 0; i < dim; i++)\n      sum += vector[i] * vector[i];\n\n    Dtype amplitudeOverSum = pow(std::abs(sampleUniform()), Dtype(1.0) / Dtype(dim)) / sqrtf(sum);\n\n    for (int i = 0; i < dim; i++)\n      vector[i] = vector[i] * amplitudeOverSum;\n  }\n\n  template<int dim>\n  void sampleOnUnitSphere(Dtype *vector) {\n    sampleVectorInNormalUniform<dim>(vector);\n    Dtype sum = 0.0f;\n\n    for (int i = 0; i < dim; i++)\n      sum += vector[i] * vector[i];\n\n    for (int i = 0; i < dim; i++)\n      vector[i] = vector[i] / sqrtf(sum);\n  }\n\n  template<typename Derived>\n  void shuffleSTDVector(std::vector<Derived> &order) {\n    boost::variate_generator<boost::mt19937 &, boost::uniform_int<> >\n        random_number_shuffler(rngGenerator, boost::uniform_int<>());\n    std::random_shuffle(order.begin(), order.end(), random_number_shuffler);\n  }\n\n  /* this method is opitmized for memory use. The column should be dynamic size */\n  template<typename Derived, int Rows, int Cols>\n  void shuffleColumns(Eigen::Matrix<Derived, Rows, Cols> &matrix) {\n    int colSize = int(matrix.cols());\n\n    /// sampling the order\n    std::vector<int> order;\n    std::vector<bool> needSuffling(colSize, true);\n\n    order.resize(colSize);\n    for (int i = 0; i < colSize; i++) order[i] = i;\n    shuffleSTDVector(order);\n    Eigen::Matrix<Derived, Rows, 1> memoryCol(matrix.rows());\n\n    int colID;\n\n    for (int colStartID = 0; colStartID < colSize; colStartID++) {\n      if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n      colID = colStartID;\n      memoryCol = matrix.col(colID);\n      do {\n        matrix.col(colID) = matrix.col(order[colID]);\n        needSuffling[colID] = false;\n        colID = order[colID];\n      } while (colStartID != order[colID]);\n      matrix.col(colID) = memoryCol;\n      needSuffling[colID] = false;\n    }\n  }\n\n  std::vector<unsigned> getNrandomSubsetIdx (unsigned nOfElem, unsigned nOfSubElem) {\n    std::vector<unsigned> memoryIdx(nOfSubElem);\n    ///// randomly sampling memory indeces\n    for (unsigned i = 0; i < nOfSubElem; i++) {\n      memoryIdx[i] = intRand(0, nOfElem - 1);\n      for (unsigned j = 0; j < i; j++) {\n        if (memoryIdx[i] == memoryIdx[j]) {\n          i--;\n          break;\n        }\n      }\n    }\n    return memoryIdx;\n  }\n\n  /*you can use this method to make the random samples the same*/\n  void seed(uint32_t seed) {\n    rngGenerator.seed(seed);\n  }\n\n private:\n  boost::random::mt19937 rngGenerator;\n\n};\n\n\n#endif /* RANDOMNUMBERGENERATOR_HPP_ */\n", "meta": {"hexsha": "f8b7d12fedfa0e14e002dca707db5c8525daac01", "size": 4331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/RandomNumberGenerator.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/RandomNumberGenerator.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/RandomNumberGenerator.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": 27.4113924051, "max_line_length": 118, "alphanum_fraction": 0.640036943, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6798592402820804}}
{"text": "#include <iostream>\r\n#include <armadillo>\r\n#include <test_class_one.h>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\nint main(int argc, char** argv) {\r\n\tTestClassOne cls;\r\n\tcout << cls.show() << endl;\r\n\t\r\n\tcout << \"Armadillo version: \" << arma_version::as_string() << endl;\r\n\tmat A = randn<mat>(4,4);\r\n\tmat B = randn<mat>(4,4);\r\n\tmat C = A * B;\r\n\tA.print(\"A:\");\r\n\tB.print(\"B:\");\r\n\tC.print(\"AxB:\");\r\n}", "meta": {"hexsha": "44e5943a5c3d1b6cfbd66f007544f0dcba7812ae", "size": 404, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cmake-basic/src/program1.cc", "max_stars_repo_name": "gentisaliu/playground", "max_stars_repo_head_hexsha": "e2d9ac389be8fe775a45365f9170c8f15a49193c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmake-basic/src/program1.cc", "max_issues_repo_name": "gentisaliu/playground", "max_issues_repo_head_hexsha": "e2d9ac389be8fe775a45365f9170c8f15a49193c", "max_issues_repo_licenses": ["MIT"], "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-basic/src/program1.cc", "max_forks_repo_name": "gentisaliu/playground", "max_forks_repo_head_hexsha": "e2d9ac389be8fe775a45365f9170c8f15a49193c", "max_forks_repo_licenses": ["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.2631578947, "max_line_length": 69, "alphanum_fraction": 0.599009901, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6798375116284001}}
{"text": "#pragma once\n#include \"shape.hpp\"\n#include <Eigen/Core>\n#include <tuple>\n\n//! The gradient of the shape function (on the reference element) for LINEAR FEM\n//!\n//! We have three shape functions\n//!\n//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientLambda(const int i, double x, double y) {\n\tstd::ignore = x;\n\tstd::ignore = y;\n\n\treturn Eigen::Vector2d(-1 + (i > 0) + (i == 1),\n\t                       -1 + (i > 0) + (i == 2));\n\treturn Eigen::Vector2d(0, 0); //remove when implemented\n}\n\n//----------------gradshapefunBegin----------------\n//! The gradient of the shape function (on the reference element) for QUADRATIC FEM\n//!\n//! We have six shape functions\n//!\n//! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientShapefun(const int i, double x, double y) {\n\t// Eigen::Vector2d value;\n\t// (write your solution here)\n\tassert(0 <= i && i <= 5);\n\tswitch (i) {\n\t\tcase 0:\n\t\t\treturn Eigen::Vector2d(-3 + 4 * x + 4 * y, -3 + 4 * x + 4 * y);\n\t\tcase 1:\n\t\t\treturn Eigen::Vector2d(4 * x - 1, 0);\n\t\tcase 2:\n\t\t\treturn Eigen::Vector2d(0, 4 * y - 1);\n\t\tcase 3:\n\t\t\treturn Eigen::Vector2d(4 - 8 * x - 4 * y, -4 * x);\n\t\tcase 4:\n\t\t\treturn Eigen::Vector2d(4 * y, 4 * x);\n\t\tcase 5:\n\t\t\treturn Eigen::Vector2d(-4 * y, 4 - 4 * x - 8 * y);\n\t\tdefault:\n\t\t\tthrow std::domain_error(\"i not in {0,1,2,3,4,5}\");\n\t}\n\t//return value;\n}\n//----------------gradshapefunEnd----------------\n", "meta": {"hexsha": "aa0c289814ecdc85e257a0f81c3820a5536940e7", "size": 1699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/grad_shape.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/grad_shape.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/grad_shape.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0566037736, "max_line_length": 89, "alphanum_fraction": 0.6103590347, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6798374973452256}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date aug-21\n * @license GPLv3, see 'LICENSE' file\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\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, version 3 of the License.\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, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Fft1\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_fft1, t_real, t_types)\n{\n\tusing namespace tl2_ops;\n\n\tusing t_cplx = std::complex<t_real>;\n\n\tstd::vector<t_cplx> invec{{\n\t\t1., 2., 3., 4., 5., 6. ,7. ,8 }};\n\n\tauto outvec_fft = tl2::fft<t_real, t_cplx, std::vector>(invec, 0, 0);\n\tauto outvec_dft = tl2::dft<t_real, t_cplx, std::vector>(invec, 0, 0);\n\n\tBOOST_TEST((outvec_fft.size() == outvec_dft.size()));\n\tfor(std::size_t i=0; i<std::min(outvec_dft.size(), outvec_fft.size()); ++i)\n\t{\n\t\tconst t_cplx& c1 = outvec_fft[i];\n\t\tconst t_cplx& c2 = outvec_dft[i];\n\t\t//std::cout << c1 << \"  \" << c2 << std::endl;\n\t\tBOOST_TEST((tl2::equals<t_cplx>(c1, c2, 1e-4)));\n\t}\n}\n", "meta": {"hexsha": "7d65126e732a03647277ae5bc884bdf7ee7fdabe", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/fft.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/fft.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/fft.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 33.5737704918, "max_line_length": 79, "alphanum_fraction": 0.6254882812, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6798355441502757}}
{"text": "#include <cassert>\n#include <cmath>\n\n#include <functional>\n#include <numeric>\n#include <sstream>\n\n#include <boost/multiprecision/gmp.hpp>\n\n#include <QtDebug>\n\n\nusing s64 = int64_t;\n\nusing namespace std;\n\nusing boost::multiprecision::mpq_rational;\n\nQDebug operator<<(QDebug d, const mpq_rational& r) {\n    d.nospace();\n    d.noquote();\n    stringstream s;\n    s << r;\n    d << QString::fromStdString(s.str());\n    return d.resetFormat();\n}\n\nQMap<int /*roll*/, s64 /*count*/> rolls(int sides, int repetitions) {\n\n    std::function<void(int , int, QMap<int, s64>*)> traverse = [&traverse, sides, repetitions](int sum, int rep, QMap<int, s64>* ret) {\n        if (rep == repetitions) {\n            if (ret->contains(sum) == false) {\n                (*ret)[sum] = 0;\n            }\n            (*ret)[sum] += 1;\n            return;\n        }\n\n        for (int i = 1; i <= sides; i += 1) {\n            traverse(sum + i, rep + 1, ret);\n        }\n    };\n\n    QMap<int, s64> ret;\n\n    traverse(0, 0, &ret);\n\n    return ret;\n}\n\nmpq_rational winProbability(int sides1, int reps1, int sides2, int reps2) {\n    auto rolls1 = rolls(sides1, reps1);\n    auto rolls2 = rolls(sides2, reps2);\n\n    auto values1 = rolls1.values();\n    auto values2 = rolls2.values();\n\n    s64 sum1 = accumulate(begin(values1), end(values1), 0);\n    s64 sum2 = accumulate(begin(values2), end(values2), 0);\n\n    mpq_rational ret(0);\n\n    QMap<int, s64>::const_iterator i = rolls2.constBegin();\n    while (i != rolls2.constEnd()) {\n        mpq_rational pickProbability(i.value(), sum1);\n\n        s64 winNumerator = 0;\n\n        QMap<int, s64>::const_iterator j = rolls1.constBegin();\n        while (j != rolls1.constEnd()) {\n\n            if (j.key() < i.key()) {\n                winNumerator += j.value();\n                //qDebug() << \"  +\" << j.key() << j.value() << winNumerator;\n            } else {\n                //qDebug() << \"  -\" << j.key();\n            }\n\n            ++j;\n        }\n\n        ret += pickProbability*mpq_rational(winNumerator, sum2);\n\n        //qDebug() << \"sum\" << i.key() << \", pick\" << pickProbability << \", win this\" << mpq_rational(winNumerator, sum2) << \", total\" << ret;\n\n        ++i;\n    }\n\n    return ret;\n}\n\nvoid testRolls();\nvoid test1();\n\nint main(int argc, char **args) {\n    Q_UNUSED(argc); Q_UNUSED(args);\n\n    testRolls();\n    test1();\n\n    return 0;\n}\n\nvoid testRolls() {\n\n    auto a31 = rolls(3, 1);\n        assert(a31.size() == 3);\n        assert(a31[1] == 1);\n        assert(a31[2] == 1);\n        assert(a31[3] == 1);\n\n    auto a22 = rolls(2, 2);\n        assert(a22.size() == 3);\n        assert(a22[2] == 1);\n        assert(a22[3] == 2);\n        assert(a22[4] == 1);\n\n    auto a49 = rolls(4, 9).values(); assert(accumulate(begin(a49), end(a49), 0) == 262144);\n    auto a66 = rolls(6, 6).values(); assert(accumulate(begin(a66), end(a66), 0) ==  46656);\n}\n\nvoid test1() {\n    qDebug() << winProbability(6, 6, 4, 9);\n}\n", "meta": {"hexsha": "d0082201219a366ebef5645dd13d7f9f37241af0", "size": 2919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project-euler/205/main.cpp", "max_stars_repo_name": "hydroo/coding-and-math-exercises", "max_stars_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-29T21:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T02:10:53.000Z", "max_issues_repo_path": "project-euler/205/main.cpp", "max_issues_repo_name": "hydroo/coding-and-math-exercises", "max_issues_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "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": "project-euler/205/main.cpp", "max_forks_repo_name": "hydroo/coding-and-math-exercises", "max_forks_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "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": 23.352, "max_line_length": 142, "alphanum_fraction": 0.5344295992, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6796559819964845}}
{"text": "#include <SFML/Graphics.hpp>\n#include <SFML/Window.hpp>\n#include <iostream>\n#include <Eigen/Dense>\n#include <algorithm>\nusing namespace sf;\nusing namespace std;\nusing namespace Eigen;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic > Mat;\n\nvoid reset(Mat& mat) {\n\t//initialize matrix to zero matrix\n\t//\ud589\ub82c\uc744 \uc601\ud589\ub82c\ub85c \ucd08\uae30\ud654\ud569\ub2c8\ub2e4.\n\tfor (int i = 0; i < mat.rows(); ++i)\n\t\tfor (int j = 0; j < mat.cols(); ++j)\n\t\t\tmat(i, j) = 0;\n}\n\nbool compare(pair<double, Mat> a, pair<double, Mat> b) {\n\t//compare function for sorting eigen values in descending order\n\t//\uace0\uc720\uac12\uc744 \ub0b4\ub9bc\ucc28\uc21c\uc73c\ub85c \uc815\ub82c\ud558\uae30 \uc704\ud55c \ube44\uad50\ud568\uc218\n\treturn a.first * a.first > b.first * b.first;\n}\n\nclass RGB {\npublic:\n\tenum { R, G, B };\n\tRGB() {\n\t}\n\tRGB(Mat red, Mat green, Mat blue) {\n\t\tsize = red.rows();\n\t\tmat[R] = red;\tmat[G] = green;\tmat[B] = blue;\n\t\tempty = false;\n\t}\n\tMat mat[3];\n\tint size;\n\tbool empty = true;\n\n\n\tvector<pair<double, Mat>> lists[3];\n\tbool processed[3] = { false,false,false };\n\tint added[3] = { -1,-1,-1 };\n\tvoid getEVDColor(int color, int rate) {\n\t\tif (!processed[color]) {\n\t\t\tSelfAdjointEigenSolver<Mat> eigensolver(mat[color]);\n\t\t\tif (eigensolver.info() != Success) abort();\n\t\t\tMat eigenValues = eigensolver.eigenvalues();\n\t\t\tMat eigenVectors = eigensolver.eigenvectors();\n\t\t\teigenVectors = eigenVectors.householderQr().householderQ();//\uc815\uaddc\uc9c1\uad50\ud654\n\t\t\tint num = eigenValues.rows();//\uace0\uc720\uac12\uc758 \uac1c\uc218\n\n\t\t\tfor (int i = 0; i < num; ++i) {\n\t\t\t\tpair<double, Mat> element;\n\t\t\t\telement.first = eigenValues(i);\n\t\t\t\telement.second = eigenVectors.col(i);\n\t\t\t\tlists[color].push_back(element);\n\t\t\t}\n\t\t\tsort(lists[color].begin(), lists[color].end(), compare);\n\t\t\tprocessed[color] = true;\n\t\t\tmat[color] = Mat(size, size);\n\t\t\treset(mat[color]);\n\t\t\tcout << endl;\n\t\t}\n\t\tif (added[color] <= rate) {\n\t\t\tfor (int i = added[color] + 1; i < rate; ++i) {\n\t\t\t\tmat[color] += (lists[color][i].first * (lists[color][i].second * lists[color][i].second.transpose()));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i = added[color]; i >= rate; --i) {\n\t\t\t\tmat[color] -= (lists[color][i].first * (lists[color][i].second * lists[color][i].second.transpose()));\n\t\t\t}\n\t\t}\n\t\tadded[color] = rate - 1;\n\t}\n};\n\nRGB getMatrixFromImage(Image& img) {\n\t//only square image available\n\t//it uses upper triangle part of the image only.\n\tif (img.getSize().x != img.getSize().y) return RGB();\n\tint size = img.getSize().x;\n\n\tMat red(size, size);\n\tMat green(size, size);\n\tMat blue(size, size);\n\tfor (int i = 0; i < size; ++i) {\n\t\tfor (int j = 0; j < size; ++j) {\n\t\t\tif (j < i) {\n\t\t\t\tred(i, j) = img.getPixel(i, j).r;\n\t\t\t\tgreen(i, j) = img.getPixel(i, j).g;\n\t\t\t\tblue(i, j) = img.getPixel(i, j).b;\n\t\t\t}\n\t\t\telse if (i == j) red(i, j) = 0;\n\t\t\telse {\n\t\t\t\tred(i, j) = img.getPixel(j, i).r;\n\t\t\t\tgreen(i, j) = img.getPixel(j, i).g;\n\t\t\t\tblue(i, j) = img.getPixel(j, i).b;\n\t\t\t}\n\t\t}\n\t}\n\treturn RGB(red, green, blue);\n}\n\nImage getImageFromRGB(RGB& rgb) {\n\tImage  result;\n\tresult.create(rgb.size, rgb.size);\n\tfor (int i = 0; i < rgb.size; ++i) {\n\t\tfor (int j = 0; j < rgb.size; ++j) {\n\t\t\tColor color;\n\t\t\tcolor.r = rgb.mat[RGB::R](i, j);\n\t\t\tcolor.g = rgb.mat[RGB::G](i, j);\n\t\t\tcolor.b = rgb.mat[RGB::B](i, j);\n\t\t\tresult.setPixel(i, j, color.toInteger() < 0 ? Color(0) : color);\n\t\t}\n\t}\n\treturn result;\n}\n\nint main() {\n\n\tstring input;\n\tcout << \"input image file name including extension>\";\n\tcin >> input;\n\n\tImage original;\n\toriginal.loadFromFile(input);\n\tif (original.getSize().x != original.getSize().y) {\n\t\tcout << \"only square image available\";\n\t\treturn -1;\n\t}\n\n\tRenderWindow window(VideoMode(original.getSize().x, original.getSize().y), \"Math channel Ssootube Eigen Value Decomposition\");\n\tRGB mat;\n\tmat = getMatrixFromImage(original);\n\tImage applied = getImageFromRGB(mat);\n\tTexture t; t.loadFromImage(applied);\n\tSprite output(t);\n\tint k = 0;\n\tcout << \"only upper triangular part of the image will be used.\" << endl;\n\twhile (window.isOpen()) {\n\t\tEvent e;\n\t\twhile (window.pollEvent(e)) {\n\t\t\tif (e.type == Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (e.type == Event::KeyPressed)\n\t\t\t\tif (e.key.code == Keyboard::Enter)\n\t\t\t\t{\n\t\t\t\t\twindow.clear();\n\t\t\t\t\twindow.draw(output);\n\t\t\t\t\twindow.display();\n\t\t\t\t\tif (k <= mat.size) {\n\t\t\t\t\t\tmat.getEVDColor(RGB::R, k);\n\t\t\t\t\t\tmat.getEVDColor(RGB::G, k);\n\t\t\t\t\t\tmat.getEVDColor(RGB::B, k++);\n\t\t\t\t\t}\n\t\t\t\t\tapplied = getImageFromRGB(mat);\n\t\t\t\t\tt.loadFromImage(applied);\n\t\t\t\t\toutput.setTexture(t);\n\t\t\t\t\tcout << \"press enter to continue. current rank:\" << ((k - 2 == -1) ? 0 : k - 2) << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t\t\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "a2ddcab95dde5553a3566cce88bf4903e4ffb3f9", "size": 4423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_stars_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-18T09:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T09:44:01.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_issues_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-27T17:39:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-27T17:39:05.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_forks_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-18T09:42:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T09:42:45.000Z", "avg_line_length": 26.3273809524, "max_line_length": 127, "alphanum_fraction": 0.6079583993, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6796325046741426}}
{"text": "#include <math.h>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n\n// From a graph's adjacency matrix, generate its probability matrix A\nEigen::MatrixXf probMatrix(Eigen::MatrixXf &R, float alpha);\n\n\n\n// Main body of improved Pagerank\nEigen::MatrixXf improvedPageRank(Eigen::MatrixXf &R, float alpha, float epsilon);\n", "meta": {"hexsha": "250f078f409ce1e2ec2fe89dc7b2d8168146ec23", "size": 314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pagerank.hpp", "max_stars_repo_name": "PurplePachyderm/ultimate-pagerank", "max_stars_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-19T11:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T11:46:49.000Z", "max_issues_repo_path": "include/pagerank.hpp", "max_issues_repo_name": "PurplePachyderm/ultimate-pagerank", "max_issues_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "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/pagerank.hpp", "max_forks_repo_name": "PurplePachyderm/ultimate-pagerank", "max_forks_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "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": 22.4285714286, "max_line_length": 81, "alphanum_fraction": 0.7547770701, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6796022228415586}}
{"text": "/**\n * @file pfasst/quadrature/interface.hpp\n * @since v0.3.0\n */\n#ifndef _PFASST__QUADRATURE__INTERFACE_HPP_\n#define _PFASST__QUADRATURE__INTERFACE_HPP_\n\n#include <cassert>\n#include <vector>\nusing namespace std;\n\n#include <Eigen/Dense>\ntemplate<typename scalar>\nusing Matrix = Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\ntemplate<typename scalar>\nusing Index = typename Matrix<scalar>::Index;\n\n#include \"pfasst/globals.hpp\"\n#include \"pfasst/interfaces.hpp\"\n#include \"pfasst/quadrature/polynomial.hpp\"\n\n\nnamespace pfasst\n{\n  namespace quadrature\n  {\n    /**\n     * Quadrature type descriptors.\n     * @since v0.3.0\n     */\n    enum class QuadratureType : int {\n        GaussLegendre   =  0  //!< @ref pfasst::quadrature::GaussLegendre \"Gauss-Legendre\" quadrature\n      , GaussLobatto    =  1  //!< @ref pfasst::quadrature::GaussLobatto \"Gauss-Lobatto\" quadrature\n      , GaussRadau      =  2  //!< @ref pfasst::quadrature::GaussRadau \"Gauss-Radau\" quadrature\n      , ClenshawCurtis  =  3  //!< @ref pfasst::quadrature::ClenshawCurtis \"Clenshaw-Curtis\" quadrature\n      , Uniform         =  4  //!< Uniform quadrature\n      , UNDEFINED       = -1\n    };\n\n\n    template<typename scalar>\n    static Polynomial<scalar> build_polynomial(const size_t node, const vector<scalar>& nodes)\n    {\n      const size_t num_nodes = nodes.size();\n      Polynomial<scalar> p(num_nodes + 1), p1(num_nodes + 1);\n      p[0] = 1.0;\n\n      for (size_t m = 0; m < num_nodes; ++m) {\n        if (m == node) { continue; }\n\n        // p_{m+1}(x) = (x - x_j) * p_m(x)\n        p1[0] = scalar(0.0);\n        for (size_t j = 0; j < num_nodes;     ++j) { p1[j + 1]  = p[j]; }\n        for (size_t j = 0; j < num_nodes + 1; ++j) { p1[j]     -= p[j] * nodes[m]; }\n        for (size_t j = 0; j < num_nodes + 1; ++j) { p[j]       = p1[j]; }\n      }\n\n      return p;\n    }\n\n\n    /**\n     * Compute quadrature matrix \\\\( Q \\\\) between two sets of nodes.\n     *\n     * Computing the quadrature matrix \\\\( Q \\\\) for polynomial-based integration from one set of\n     * quadrature nodes (@p from) to another set of quadrature nodes (@p to).\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] from first set of quadrature nodes\n     * @param[in] to second set of quadrature nodes\n     * @returns quadrature matrix \\\\( Q \\\\) with `to.size()` rows and `from.size()` colums\n     *\n     * @pre For correctness of the algorithm it is assumed, that both sets of nodes are in the range\n     *   \\\\( [0, 1] \\\\).\n     *\n     * @since v0.3.0\n     */\n    template<typename scalar>\n    static Matrix<scalar> compute_q_matrix(const vector<scalar>& from, const vector<scalar>& to)\n    {\n      const size_t to_size = to.size();\n      const size_t from_size = from.size();\n      assert(to_size >= 1 && from_size >= 1);\n\n      Matrix<scalar> q_mat = Matrix<scalar>::Zero(to_size, from_size);\n\n      for (size_t m = 0; m < from_size; ++m) {\n        Polynomial<scalar> p = build_polynomial(m, from);\n        // evaluate integrals\n        auto den = p.evaluate(from[m]);\n        auto P = p.integrate();\n        for (size_t j = 0; j < to_size; ++j) {\n          q_mat(j, m) = (P.evaluate(to[j]) - P.evaluate(scalar(0.0))) / den;\n        }\n      }\n\n      return q_mat;\n    }\n\n\n    /**\n     * Compute quadrature matrix \\\\( Q \\\\) for one set of nodes.\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] nodes quadrature nodes to compute \\\\( Q \\\\) matrix for\n     *\n     * @since v0.3.0\n     *\n     * @overload\n     */\n    template<typename scalar>\n    static Matrix<scalar> compute_q_matrix(const vector<scalar>& nodes)\n    {\n      return compute_q_matrix<scalar>(nodes, nodes);\n    }\n\n\n    /**\n     * Compute quadrature matrix \\\\( Q \\\\) from a given node-to-node quadrature matrix \\\\( S \\\\).\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] s_mat \\\\( S \\\\) matrix to compute \\\\( Q \\\\) from\n     * @see pfasst::quadrature::compute_s_matrix\n     *\n     * @since v0.3.0\n     *\n     * @overload\n     */\n    template<typename scalar>\n    static Matrix<scalar> compute_q_matrix(const Matrix<scalar>& s_mat)\n    {\n      Matrix<scalar> q_mat = Matrix<scalar>::Zero(s_mat.rows(), s_mat.cols());\n      q_mat.col(0) = s_mat.col(0);\n      for (Index<scalar> q_mat_col = 1; q_mat_col < q_mat.cols(); ++q_mat_col) {\n        q_mat.col(q_mat_col) = q_mat.col(q_mat_col - 1) + s_mat.col(q_mat_col);\n      }\n      return q_mat;\n    }\n\n\n    /**\n     * Compute node-to-node quadrature matrix \\\\( S \\\\) from a given quadrature matrix \\\\( Q \\\\).\n     *\n     * The \\\\( S \\\\) matrix provides a node-to-node quadrature where the \\\\( i \\\\)-th row of\n     * \\\\( S \\\\) represents a quadrature from the \\\\( i-1 \\\\)-th node to the \\\\( i \\\\)-th node.\n     *\n     * The procedure is simply subtracting the \\\\( i-1 \\\\)-th row of \\\\( Q \\\\) from the\n     * \\\\( i \\\\)-th row of \\\\( Q \\\\).\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] q_mat \\\\( Q \\\\) matrix to compute \\\\( S \\\\) of\n     * @returns \\\\( S \\\\) matrix\n     *\n     * @since v0.3.0\n     */\n    template<typename scalar>\n    static Matrix<scalar> compute_s_matrix(const Matrix<scalar>& q_mat)\n    {\n      Matrix<scalar> s_mat = Matrix<scalar>::Zero(q_mat.rows(), q_mat.cols());\n      s_mat.row(0) = q_mat.row(0);\n      for (Index<scalar> row = 1; row < s_mat.rows(); ++row) {\n        s_mat.row(row) = q_mat.row(row) - q_mat.row(row - 1);\n      }\n      return s_mat;\n    }\n\n\n    /**\n     * Compute node-to-node quadrature matrix \\\\( S \\\\) from two given sets of nodes\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] from first set of quadrature nodes\n     * @param[in] to second set of quadrature nodes\n     *\n     * @since v0.3.0\n     *\n     * @overload\n     */\n    template<typename scalar>\n    static Matrix<scalar> compute_s_matrix(const vector<scalar>& from, const vector<scalar>& to)\n    {\n      return compute_s_matrix(compute_q_matrix(from, to));\n    }\n\n\n    /**\n     * Compute vector \\\\( q \\\\) for integration from \\\\( 0 \\\\) to \\\\( 1 \\\\) for given set of nodes.\n     *\n     * This equals to the last row of the quadrature matrix \\\\( Q \\\\) for the given set of nodes.\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     * @param[in] nodes quadrature nodes to compute \\\\( Q \\\\) matrix for\n     * @pre For correctness of the algorithm it is assumed, that the nodes are in the range\n     *   \\\\( [0, 1] \\\\).\n     *\n     * @since v0.3.0\n     */\n    template<typename scalar>\n    static vector<scalar> compute_q_vec(const vector<scalar>& nodes)\n    {\n      const size_t num_nodes = nodes.size();\n      assert(num_nodes >= 1);\n\n      vector<scalar> q_vec = vector<scalar>(num_nodes, scalar(0.0));\n\n      for (size_t m = 0; m < num_nodes; ++m) {\n        Polynomial<scalar> p = build_polynomial(m, nodes);\n        // evaluate integrals\n        auto den = p.evaluate(nodes[m]);\n        auto P = p.integrate();\n        q_vec[m] = (P.evaluate(scalar(1.0)) - P.evaluate(scalar(0.0))) / den;\n      }\n\n      return q_vec;\n    }\n\n    /**\n     * Interface for quadrature handlers.\n     *\n     * Quadrature handlers provide \\\\( Q \\\\), \\\\( S \\\\) and \\\\( B \\\\) matrices respecting the left\n     * and right nodes, i.e. whether \\\\( 0 \\\\) and \\\\( 1 \\\\) are part of the nodes or not.\n     *\n     * Computation of the quadrature nodes and matrices (i.e. quadrature weights) is done on\n     * initialization.\n     *\n     * @tparam scalar precision of quadrature (i.e. `double`)\n     *\n     * @since v0.3.0\n     */\n    template<typename precision = pfasst::time_precision>\n    class IQuadrature\n    {\n      protected:\n        //! @{\n        static const bool LEFT_IS_NODE = false;\n        static const bool RIGHT_IS_NODE = false;\n\n        size_t num_nodes;\n        Matrix<precision> q_mat;\n        Matrix<precision> s_mat;\n        vector<precision> q_vec; // XXX: black spot\n        Matrix<precision> b_mat;\n        vector<precision> nodes;\n        //! @}\n\n      public:\n        //! @{\n        /**\n         * @throws invalid_argument if number of nodes is invalid for quadrature type\n         */\n        explicit IQuadrature(const size_t num_nodes);\n        /**\n         * @throws invalid_argument if number of nodes is invalid for quadrature type\n         */\n        IQuadrature();\n        virtual ~IQuadrature() = default;\n        //! @}\n\n        //! @{\n        virtual const Matrix<precision>& get_q_mat() const;\n        virtual const Matrix<precision>& get_s_mat() const;\n        virtual const Matrix<precision>& get_b_mat() const;\n        virtual const vector<precision>& get_q_vec() const;\n        virtual const vector<precision>& get_nodes() const;\n        virtual size_t get_num_nodes() const;\n\n        /**\n         * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n         *   required for quadrature of any kind\n         */\n        virtual bool left_is_node() const;\n        /**\n         * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n         *   required for quadrature of any kind\n         */\n        virtual bool right_is_node() const;\n        //! @}\n\n        /**\n         * Compute a rough estimate of the numerical error... XXX\n         */\n        precision expected_error() const;\n\n      protected:\n        //! @{\n        /**\n         * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n         *   required for quadrature of any kind\n         */\n        virtual void compute_nodes();\n        virtual void compute_weights();\n        //! @}\n    };\n  }  // ::pfasst::quadrature\n}  // ::pfasst\n\n#include \"pfasst/quadrature/interface_impl.hpp\"\n\n#endif  // _PFASST__QUADRATURE__INTERFACE_HPP_\n", "meta": {"hexsha": "04b2f5c4be3e6e664ef8642dd46c4ec3d947a536", "size": 9758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pfasst/quadrature/interface.hpp", "max_stars_repo_name": "memmett/PFASST", "max_stars_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T11:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T01:09:52.000Z", "max_issues_repo_path": "include/pfasst/quadrature/interface.hpp", "max_issues_repo_name": "memmett/PFASST", "max_issues_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-13T11:03:04.000Z", "max_forks_repo_path": "include/pfasst/quadrature/interface.hpp", "max_forks_repo_name": "memmett/PFASST", "max_forks_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T07:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T20:26:08.000Z", "avg_line_length": 32.4186046512, "max_line_length": 103, "alphanum_fraction": 0.5833162533, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6795213383003954}}
{"text": "/*\n * VELOCITY_RELATIONS_TEST.CPP Test fixtures for analytical profiles\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n#include <unsupported/Eigen/AutoDiff>\n\n#include \"definitions.h\"\n#include \"relations/stress.h\"\n#include \"relations/veer.h\"\n#include \"relations/velocity.h\"\n\n\nusing namespace es;\nusing namespace Eigen;\n\n\n// Test fixture for generating analytical profiles\nclass VelocityRelationsTest : public ::testing::Test {};\n\n\nTEST_F(VelocityRelationsTest, test_power_law_profile) {\n\n    // Basic test parameters\n    double z_ref = 60;\n    double u_ref = 10;\n    double alpha = 0.3;\n\n    // Check that it works for a z value of type double\n    double z_doub = 1.;\n    double speed2 = power_law_speed(z_doub, u_ref, z_ref, alpha);\n    std::cout << \"checked scalar double operation (U = \" << speed2 << \" m/s)\" << std::endl;\n\n    // Check that it works for a VectorXd input (vertically spaced z)\n    double low = 1;\n    double high = 100;\n    size_t n_bins = 100;\n    VectorXd z = VectorXd::LinSpaced(n_bins, low, high);\n    VectorXd speed = power_law_speed(z, u_ref, z_ref, alpha);\n    std::cout << \"checked VectorXd operation\" << std::endl;\n\n    // Check that it works for an AutoDiffScalar\n    // Also provides minimal example of how to get the derivative through the profile\n    typedef Eigen::AutoDiffScalar<Eigen::VectorXd> ADScalar;\n    ADScalar ads_z;\n    ADScalar ads_speed;\n    VectorXd dspeed_dz;\n    dspeed_dz.setZero(n_bins);\n\n    typedef Eigen::AutoDiffScalar<Eigen::VectorXd> ADScalar;\n    for (int k = 0; k < n_bins; k++) {\n        ads_z.value() = z[k];\n        ads_z.derivatives() = Eigen::VectorXd::Unit(1, 0);  // Also works once outside the loop without resetting the\n                                                            // derivative guess each step\n        ads_speed = power_law_speed(ads_z, u_ref, z_ref, alpha);\n        dspeed_dz[k] = ads_speed.derivatives()[0];\n    }\n    std::cout << \"checked AutoDiffScalar operation\" << std::endl;\n\n    // Print useful diagnostics values\n    std::cout << \"speed = [\"     << speed.transpose()     << \"];\" << std::endl;\n    std::cout << \"dspeed_dz = [\" << dspeed_dz.transpose() << \"];\" << std::endl;\n}\n\n\n//TEST_F(VelocityRelationsTest, test_most_profile) {\n//\n//    // von karman constant\n//    double kappa = 0.41;\n//    // zero plane offset distance (e.g. for forest canopies)\n//    double d = 0;\n//    // roughness length\n//    double z0 = 0.5;\n//    // Monin-Obukhov length\n//    double L = 20.;\n//\n//    // Check that it works for a z value of type double\n//    double z_doub = 1.;\n//    double speed2 = most_law_speed(z_doub, kappa, d, z0, L);\n//    std::cout << \"checked scalar double operation (U = \" << speed2 << \" m/s)\" << std::endl;\n//\n//    // Check that it works for a VectorXd input (vertically spaced z)\n//    double low = 1;\n//    double high = 100;\n//    size_t n_bins = 100;\n//    VectorXd z = VectorXd::LinSpaced(n_bins, low, high);\n//    VectorXd speed = most_law_speed(z, kappa, d, z0, L);\n//    std::cout << \"checked VectorXd operation\" << std::endl;\n//\n//    // Check that it works for an AutoDiffScalar\n//    // Also provides minimal example of how to get the derivative through the profile\n//    typedef Eigen::AutoDiffScalar<Eigen::VectorXd> ADScalar;\n//    ADScalar ads_z;\n//    ADScalar ads_speed;\n//    VectorXd dspeed_dz;\n//    dspeed_dz.setZero(n_bins);\n//    for (int k = 0; k < n_bins; k++) {\n//        ads_z.value() = z[k];\n//        ads_z.derivatives() = Eigen::VectorXd::Unit(1, 0);  // Also works once outside the loop without resetting the\n//        // derivative guess each step\n//        ads_speed = most_law_speed(ads_z, kappa, d, z0, L);\n//        dspeed_dz[k] = ads_speed.derivatives()[0];\n//    }\n//    std::cout << \"checked AutoDiffScalar operation\" << std::endl;\n//\n//    // Print useful diagnostics values\n//    std::cout << \"speed = [\"     << speed.transpose()     << \"];\" << std::endl;\n//    std::cout << \"dspeed_dz = [\" << dspeed_dz.transpose() << \"];\" << std::endl;\n//}\n\n\nTEST_F(VelocityRelationsTest, test_marusic_jones_profile) {\n\n    // Basic test parameters\n    double pi_j = 0.42;\n    double kappa = 0.41;\n    double delta = 1000.0;\n    double u_inf = 20.0;\n    double s = 23.6;\n    double u_tau = u_inf / s;\n    double z_0 = 0.0;\n\n    // Check that it works for a z value of type double\n    double z_doub = 1.0;\n    double speed1 = marusic_jones_speed(z_doub, pi_j, kappa, z_0, delta, u_inf, u_tau);\n    std::cout << \"checked scalar double operation (U = \" << speed1 << \" m/s)\" << std::endl;\n\n    // Check that it works for a VectorXd input (vertically spaced z)\n    double low = 1;\n    double high = 100;\n    size_t n_bins = 100;\n    VectorXd z = VectorXd::LinSpaced(n_bins, low, high);\n    VectorXd speed = marusic_jones_speed(z, pi_j, kappa, z_0, delta, u_inf, u_tau);\n    std::cout << \"checked VectorXd operation\" << std::endl;\n\n    // Check that it works for an AutoDiffScalar in z\n    // Also provides minimal example of how to get the derivative through the profile\n    typedef Eigen::AutoDiffScalar<Eigen::VectorXd> ADScalar;\n    ADScalar ads_z;\n    ADScalar ads_speed;\n    VectorXd dspeed_dz;\n    dspeed_dz.setZero(n_bins);\n    for (int k = 0; k < n_bins; k++) {\n        ads_z.value() = z[k];\n        ads_z.derivatives() = Eigen::VectorXd::Unit(1, 0);  // Also works once outside the loop without resetting the derivative guess each step\n        ads_speed = marusic_jones_speed(ads_z, pi_j, kappa, z_0, delta, u_inf, u_tau);\n//        std::cout << ads_speed.value() << std::endl;\n        dspeed_dz[k] = ads_speed.derivatives()[0];\n    }\n    std::cout << \"checked AutoDiffScalar operation\" << std::endl;\n\n    // Print useful diagnostics values\n    std::cout << \"speed = [\"     << speed.transpose()     << \"];\" << std::endl;\n    std::cout << \"dspeed_dz = [\" << dspeed_dz.transpose() << \"];\" << std::endl;\n\n    // Check it works for an AutoDiffScalar in z and pi_j\n    VectorXd partial_dspeed_dz, partial_dspeed_dpi, partial_dspeed_dpi_check;\n    ADScalar ads_pi_j, ads_speed_check1, ads_speed_check2;\n    partial_dspeed_dz.setZero(n_bins);\n    partial_dspeed_dpi.setZero(n_bins);\n    partial_dspeed_dpi_check.setZero(n_bins);\n    for (int k = 0; k < n_bins; k++) {\n\n        // Set the current values\n        ads_z.value() = z[k];\n        ads_pi_j.value() = pi_j;\n\n        // Initialise both derivative terms to unit vectors, telling us which term relates to which derivative\n        ads_z.derivatives() = Eigen::VectorXd::Unit(2,0);\n        ads_pi_j.derivatives() = Eigen::VectorXd::Unit(2,1);\n        ads_speed = marusic_jones_speed(ads_z, ads_pi_j, kappa, z_0, delta, u_inf, u_tau);\n        partial_dspeed_dz[k] = ads_speed.derivatives()[0];\n        partial_dspeed_dpi[k] = ads_speed.derivatives()[1];\n\n        // Run a check with a crude central differencer\n        ads_speed_check1 = marusic_jones_speed(ads_z, pi_j-0.01, kappa, z_0, delta, u_inf, u_tau);\n        ads_speed_check2 = marusic_jones_speed(ads_z, pi_j+0.01, kappa, z_0, delta, u_inf, u_tau);\n        ads_speed_check2 = (ads_speed_check2 - ads_speed_check1) / 0.02;\n        partial_dspeed_dpi_check[k] = ads_speed_check2.value();\n\n    }\n    std::cout << \"partial_dspeed_dpi       = [\" << partial_dspeed_dpi.transpose() << \"];\" << std::endl;\n    std::cout << \"partial_dspeed_dpi_check = [\" << partial_dspeed_dpi_check.transpose() << \"];\" << std::endl;\n}\n\n\nTEST_F(VelocityRelationsTest, test_lewkowicz_profile) {\n\n    // Basic test parameters\n    double pi_coles = 0.42;\n    double kappa = 0.41;\n    double delta = 1000.0;\n    double u_inf = 20.0;\n    double shear_ratio = 23.6;\n    double z_0 = 0.0;\n\n    // Check that it works for a z value of type double\n    double z_doub = 1.0;\n    double speed1 = lewkowicz_speed(z_doub, pi_coles, kappa, u_inf, shear_ratio, delta);\n    std::cout << \"checked scalar double operation (U = \" << speed1 << \" m/s)\" << std::endl;\n\n    // Check that it works for a ArrayXd input (vertically spaced z)\n    double low = 1;\n    double high = 100;\n    int n_bins = 10;\n    VectorXd z = VectorXd::LinSpaced(n_bins, low, high);\n    VectorXd speed = lewkowicz_speed(z, pi_coles, kappa, u_inf, shear_ratio, delta);\n    std::cout << \"checked VectorXd operation: \"<< speed.transpose() << std::endl;\n\n    // Check that it works for an AutoDiffScalar\n    // Also provides minimal example of how to get the derivative through the profile\n    typedef Eigen::AutoDiffScalar<Eigen::VectorXd> ADScalar;\n    ADScalar ads_z;\n    ADScalar ads_speed;\n    VectorXd dspeed_dz;\n    dspeed_dz.setZero(n_bins);\n    for (int k = 0; k < n_bins; k++) {\n        ads_z.value() = z[k];\n        ads_z.derivatives() = Eigen::VectorXd::Unit(1, 0);  // Also works once outside the loop without resetting the derivative guess each step\n        ads_speed = lewkowicz_speed(ads_z, pi_coles, kappa, u_inf, shear_ratio, delta);\n        dspeed_dz[k] = ads_speed.derivatives()[0];\n    }\n    std::cout << \"checked AutoDiffScalar<VectorXd> operation\" << std::endl;\n\n    // Print useful diagnostics values\n    std::cout << \"speed = [\"     << speed.transpose()     << \"];\" << std::endl;\n    std::cout << \"dspeed_dz = [\" << dspeed_dz.transpose() << \"];\" << std::endl;\n\n    // Print variables to plot comparison with MATLAB based equivalent calculation\n    //    std::cout << \"pi_j = \" << pi_j << \";\" << std::endl;\n    //    std::cout << \"kappa = \" << kappa << \";\" << std::endl;\n    //    std::cout << \"delta = \" << delta << \";\" << std::endl;\n    //    std::cout << \"s = \" << s << \";\" << std::endl;\n    //    std::cout << \"u_inf = \" << u_inf << \";\" << std::endl;\n    //    std::cout << \"z_0 = \" << z_0 << \";\" << std::endl;\n    //    std::cout << \"z = [\" << z << \"];\" << std::endl;\n\n}\n\n\nclass VeerRelationsTest : public ::testing::Test {};\n\n\nTEST_F(VeerRelationsTest, test_veer_profile) {\n\n//    // Elevation of site in degrees latitude\n//    double phi_latitude = 52;\n//\n//    Vector3d k;\n//    k << 0, 0, 2*omega_world*sind(phi_latitude);\n//\n//    VectorXd v_bar;\n//    v_bar << 10., 3.;\n\n    // Assume homogeneous, isotropic turbulence such that R13 = R23. Not valid, but OK for the sake of the unit test.\n\n}\n", "meta": {"hexsha": "b4f32279fb604d84f9cf4ddc00e0126b8a178349", "size": 10240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/relations_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/relations_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/relations_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "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.641509434, "max_line_length": 144, "alphanum_fraction": 0.628515625, "num_tokens": 2959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6794963870790918}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2019 Sean Crutchlow\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/**\n * @file utils_test.cpp\n * @brief Unit tests using Google Test framework to validate class\n *  implementation.\n * @author Sean Crutchlow <sean.GH1231@gmail.com>\n * @version 1.0\n */\n\n/// System\n#include <gtest/gtest.h>\n\n#include <cmath>\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n/// Library\n#include <Eigen/Dense>\n\n/// Project\n#include \"kalman_filter/utils.h\"\n\nnamespace kalman_filter {\nclass UtilsTest : public ::testing::Test {\n protected:\n  double error;\n\n  virtual void SetUp() {\n    error = 1e-6;\n  }\n\n  virtual void TearDown() {}\n\n  const bool Compare(const coord2D_t& _lhs,\n                     const coord2D_t& _rhs,\n                     const double _epsilon) {\n    if (std::abs(std::get<0>(_lhs) - std::get<0>(_rhs)) > _epsilon)\n      return false;\n    if (std::abs(std::get<1>(_lhs) - std::get<1>(_rhs)) > _epsilon)\n      return false;\n\n    return true;\n  }\n\n  const bool Compare(const coord3D_t& _lhs,\n                     const coord3D_t& _rhs,\n                     const double _epsilon) {\n    if (std::abs(std::get<0>(_lhs) - std::get<0>(_rhs)) > _epsilon)\n      return false;\n    if (std::abs(std::get<1>(_lhs) - std::get<1>(_rhs)) > _epsilon)\n      return false;\n    if (std::abs(std::get<2>(_lhs) - std::get<2>(_rhs)) > _epsilon)\n      return false;\n\n    return true;\n  }\n};\n\nTEST_F(UtilsTest, Cartesian2Polar) {\n  coord2D_t expected(5.0, 0.92729521800161);     /// r, theta\n  coord2D_t result = Cartesian2Polar(3.0, 4.0);  /// x, y\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Polar2Cartesian) {\n  coord2D_t expected(-2.0807341827357, 4.5464871341284);  /// x, y\n  coord2D_t result = Polar2Cartesian(5.0, 2.0);           /// r, theta\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cartesian2Spherical) {\n  coord3D_t expected(7.6426435217142,\n                     0.74847023342654,\n                     0.90806681890191);                     /// rho, theta, phi\n  coord3D_t result = Cartesian2Spherical(3.2, 4.1, 5.6);    /// x, y, z\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cartesian2Cylindrical) {\n  coord3D_t expected(5.3413481444295,\n                     0.90482708941579,\n                     5.7);                                    /// rho, theta, z\n  coord3D_t result = Cartesian2Cylindrical(3.3, 4.2, 5.7);    /// x, y, z\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Spherical2Cartesian) {\n  coord3D_t expected(-6.352477916,\n                      0.9055237668,\n                      3.265892074);                         /// x, y, z\n  coord3D_t result = Spherical2Cartesian(7.2, 3.0, 1.1);    /// rho, theta, phi\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cylindrical2Cartesian) {\n  coord3D_t expected(-2.802096119,\n                      2.566760086,\n                      4.8);                                 /// x, y, z\n  coord3D_t result = Cylindrical2Cartesian(3.8, 2.4, 4.8);  /// r, theta, z\n\n  EXPECT_TRUE(Compare(result, expected, error));\n}\n\n\nTEST_F(UtilsTest, Deg2Rad) {\n  double expected = 0.021537363;   /// radians\n  double result = Deg2Rad(1.234);  /// degrees\n\n  EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Rad2Deg) {\n  double expected = 70.702992;     /// degrees\n  double result = Rad2Deg(1.234);  /// radians\n\n  EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Feet2Meters) {\n  double expected = 0.3761232;         /// meters\n  double result = Feet2Meters(1.234);  /// feet\n\n  EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Meters2Feet) {\n  double expected = 4.0485564;         /// feet\n  double result = Meters2Feet(1.234);  /// meters\n\n  EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, CalcRMSE) {\n  Eigen::VectorXd e1(2), e2(2), a1(2), a2(2);\n  e1 << 0.00001234, 0.12340000;\n  e2 << 0.00999900, 0.99990000;\n  a1 << 0.00987600, 0.12000000;\n  a2 << 0.00001200, 0.98760000;\n\n\n  std::vector<Eigen::VectorXd> estimated = {e1, e2};\n  std::vector<Eigen::VectorXd> actual = {a1, a2};\n\n  Eigen::VectorXd expected(2);\n  expected << 0.009925522,\n              0.00902358;\n\n  Eigen::VectorXd result = CalcRMSE(estimated, actual);  /// meters\n\n  EXPECT_TRUE((result - expected).norm() < error);\n}\n}   //  namespace kalman_filter\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "bd58014f18b515948d84388c096ad51b2c4dfff3", "size": 5509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/utils_test.cpp", "max_stars_repo_name": "scr123/kalman_filter", "max_stars_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T18:44:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T18:44:17.000Z", "max_issues_repo_path": "test/utils_test.cpp", "max_issues_repo_name": "scr123/kalman_filter", "max_issues_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_issues_repo_licenses": ["MIT"], "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/utils_test.cpp", "max_forks_repo_name": "scr123/kalman_filter", "max_forks_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_forks_repo_licenses": ["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.4598930481, "max_line_length": 81, "alphanum_fraction": 0.638772917, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6794387909014795}}
{"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 of the matrix object \n    from the dlib C++ Library.\n*/\n\n\n#include <iostream>\n#include <dlib/matrix.h>\n\nusing namespace dlib;\nusing namespace std;\n\n// ----------------------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_matrix_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // Let's begin this example by using the library to solve a simple \n    // linear system.\n    // \n    // We will find the value of x such that y = M*x where\n    //\n    //      3.5\n    // y =  1.2\n    //      7.8\n    //\n    // and M is\n    //\n    //      54.2   7.4   12.1\n    // M =  1      2     3\n    //      5.9    0.05  1\n\n\n    // First let's declare these 3 matrices.\n    // This declares a matrix that contains doubles and has 3 rows and 1 column.\n    // Moreover, its size is a compile time constant since we put it inside the <>.\n    matrix<double,3,1> y;\n    // Make a 3 by 3 matrix of doubles for the M matrix.  In this case, M is\n    // sized at runtime and can therefore be resized later by calling M.set_size(). \n    matrix<double> M(3,3);\n    \n    // You may be wondering why someone would want to specify the size of a\n    // matrix at compile time when you don't have to.  The reason is two fold.\n    // First, there is often a substantial performance improvement, especially\n    // for small matrices, because it enables a number of optimizations that\n    // otherwise would be impossible.  Second, the dlib::matrix object checks\n    // these compile time sizes to ensure that the matrices are being used\n    // correctly.  For example, if you attempt to compile the expression y*y you\n    // will get a compiler error since that is not a legal matrix operation (the\n    // matrix dimensions don't make sense as a matrix multiplication).  So if\n    // you know the size of a matrix at compile time then it is always a good\n    // idea to let the compiler know about it.\n\n\n\n\n    // Now we need to initialize the y and M matrices and we can do so like this:\n    M = 54.2,  7.4,  12.1,\n        1,     2,    3,\n        5.9,   0.05, 1;\n\n    y = 3.5,  \n        1.2,    \n        7.8;\n\n\n    // The solution to y = M*x can be obtained by multiplying the inverse of M\n    // with y.  As an aside, you should *NEVER* use the auto keyword to capture\n    // the output from a matrix expression.  So don't do this: auto x = inv(M)*y; \n    // To understand why, read the matrix_expressions_ex.cpp example program.\n    matrix<double> x = inv(M)*y;\n\n    cout << \"x: \\n\" << x << endl;\n\n    // We can check that it really worked by plugging x back into the original equation \n    // and subtracting y to see if we get a column vector with values all very close\n    // to zero (Which is what happens.  Also, the values may not be exactly zero because \n    // there may be some numerical error and round off).\n    cout << \"M*x - y: \\n\" << M*x - y << endl;\n\n\n    // Also note that we can create run-time sized column or row vectors like so\n    matrix<double,0,1> runtime_sized_column_vector;\n    matrix<double,1,0> runtime_sized_row_vector;\n    // and then they are sized by saying\n    runtime_sized_column_vector.set_size(3);\n\n    // Similarly, the x matrix can be resized by calling set_size(num rows, num columns).  For example\n    x.set_size(3,4);  // x now has 3 rows and 4 columns.\n\n\n\n    // The elements of a matrix are accessed using the () operator like so:\n    cout << M(0,1) << endl;\n    // The above expression prints out the value 7.4.  That is, the value of\n    // the element at row 0 and column 1.\n\n    // If we have a matrix that is a row or column vector.  That is, it contains either \n    // a single row or a single column then we know that any access is always either \n    // to row 0 or column 0 so we can omit that 0 and use the following syntax.\n    cout << y(1) << endl;\n    // The above expression prints out the value 1.2\n\n\n    // Let's compute the sum of elements in the M matrix.\n    double M_sum = 0;\n    // loop over all the rows\n    for (long r = 0; r < M.nr(); ++r)\n    {\n        // loop over all the columns\n        for (long c = 0; c < M.nc(); ++c)\n        {\n            M_sum += M(r,c);\n        }\n    }\n    cout << \"sum of all elements in M is \" << M_sum << endl;\n\n    // The above code is just to show you how to loop over the elements of a matrix.  An \n    // easier way to find this sum is to do the following:\n    cout << \"sum of all elements in M is \" << sum(M) << endl;\n\n\n\n\n    // Note that you can always print a matrix to an output stream by saying:\n    cout << M << endl;\n    // which will print:\n    //   54.2  7.4 12.1 \n    //      1    2    3 \n    //    5.9 0.05    1 \n\n    // However, if you want to print using comma separators instead of spaces you can say:\n    cout << csv << M << endl;\n    // and you will instead get this as output:\n    //   54.2, 7.4, 12.1\n    //   1, 2, 3\n    //   5.9, 0.05, 1\n\n    // Conversely, you can also read in a matrix that uses either space, tab, or comma\n    // separated values by uncommenting the following:\n    // cin >> M;\n\n\n\n    // -----------------------------  Comparison with MATLAB ------------------------------\n    // Here I list a set of Matlab commands and their equivalent expressions using the dlib\n    // matrix.  Note that there are a lot more functions defined for the dlib::matrix.  See\n    // the HTML documentation for a full listing.\n\n    matrix<double> A, B, C, D, E;\n    matrix<int> Aint;\n    matrix<long> Blong;\n\n    // MATLAB: A = eye(3)\n    A = identity_matrix<double>(3);\n\n    // MATLAB: B = ones(3,4)\n    B = ones_matrix<double>(3,4);\n\n    // MATLAB: B = rand(3,4)\n    B = randm(3,4);\n\n    // MATLAB: C = 1.4*A\n    C = 1.4*A;\n\n    // MATLAB: D = A.*C\n    D = pointwise_multiply(A,C);\n\n    // MATLAB: E = A * B\n    E = A*B;\n\n    // MATLAB: E = A + C\n    E = A + C;\n\n    // MATLAB: E = A + 5\n    E = A + 5;\n\n    // MATLAB: E = E'\n    E = trans(E);  // Note that if you want a conjugate transpose then you need to say conj(trans(E))\n\n    // MATLAB: E = B' * B\n    E = trans(B)*B;\n\n    double var;\n    // MATLAB: var = A(1,2)\n    var = A(0,1); // dlib::matrix is 0 indexed rather than starting at 1 like Matlab.\n\n    // MATLAB: C = round(C)\n    C = round(C);\n\n    // MATLAB: C = floor(C)\n    C = floor(C);\n\n    // MATLAB: C = ceil(C)\n    C = ceil(C);\n\n    // MATLAB: C = diag(B)\n    C = diag(B);\n\n    // MATLAB: B = cast(A, \"int32\")\n    Aint = matrix_cast<int>(A);\n\n    // MATLAB: A = B(1,:)\n    A = rowm(B,0);\n\n    // MATLAB: A = B([1:2],:)\n    A = rowm(B,range(0,1));\n\n    // MATLAB: A = B(:,1)\n    A = colm(B,0);\n\n    // MATLAB: A = [1:5]\n    Blong = range(1,5);\n\n    // MATLAB: A = [1:2:5]\n    Blong = range(1,2,5);\n\n    // MATLAB: A = B([1:3], [1:2])\n    A = subm(B, range(0,2), range(0,1));\n    // or equivalently\n    A = subm(B, rectangle(0,0,1,2));\n\n\n    // MATLAB: A = B([1:3], [1:2:4])\n    A = subm(B, range(0,2), range(0,2,3));\n\n    // MATLAB: B(:,:) = 5\n    B = 5;\n    // or equivalently\n    set_all_elements(B,5);\n\n\n    // MATLAB: B([1:2],[1,2]) = 7\n    set_subm(B,range(0,1), range(0,1)) = 7;\n\n    // MATLAB: B([1:3],[2:3]) = A\n    set_subm(B,range(0,2), range(1,2)) = A;\n\n    // MATLAB: B(:,1) = 4\n    set_colm(B,0) = 4;\n\n    // MATLAB: B(:,[1:2]) = 4\n    set_colm(B,range(0,1)) = 4;\n\n    // MATLAB: B(:,1) = B(:,2)\n    set_colm(B,0) = colm(B,1);\n\n    // MATLAB: B(1,:) = 4\n    set_rowm(B,0) = 4;\n\n    // MATLAB: B(1,:) = B(2,:)\n    set_rowm(B,0) = rowm(B,1);\n\n    // MATLAB: var = det(E' * E)\n    var = det(trans(E)*E);\n\n    // MATLAB: C = pinv(E)\n    C = pinv(E);\n\n    // MATLAB: C = inv(E)\n    C = inv(E);\n\n    // MATLAB: [A,B,C] = svd(E)\n    svd(E,A,B,C);\n\n    // MATLAB: A = chol(E,'lower') \n    A = chol(E);\n\n    // MATLAB: var = min(min(A))\n    var = min(A);\n}\n\n// ----------------------------------------------------------------------------------------\n\n\n", "meta": {"hexsha": "a79c2bc626e4eef0e40e33bc2883f171430c2dc4", "size": 8005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/matrix_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/matrix_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/matrix_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": 28.2862190813, "max_line_length": 102, "alphanum_fraction": 0.5565271705, "num_tokens": 2439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.6794226001122651}}
{"text": "#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include<cstdlib>\n#include <time.h>\n\n#include <Eigen/Dense>\n\n\n// Splits a string into a vector, with a delimiter char\nstd::vector<std::string> split(std::string str, char delimeter);\n\n\n\n// Reads a neighbours list and generates the adjacency matrix\nEigen::MatrixXf parseNeighboursList(std::string path);\n\n\n\n// Reads an edges list and generates the adjacency matrix\nEigen::MatrixXf parseEdgesList(std::string path);\n\n\n\n// Generates a graph of size n with a probability p of edge spawn,\n// and saves it in path (as a neighbours list)\nvoid genNeighboursList(std::string path, unsigned n, float p);\n", "meta": {"hexsha": "4c42f078ecf64cc644a8ef6a27549cb2b7f1c709", "size": 669, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parser.hpp", "max_stars_repo_name": "PurplePachyderm/ultimate-pagerank", "max_stars_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-19T11:46:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-19T11:46:49.000Z", "max_issues_repo_path": "include/parser.hpp", "max_issues_repo_name": "PurplePachyderm/ultimate-pagerank", "max_issues_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "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/parser.hpp", "max_forks_repo_name": "PurplePachyderm/ultimate-pagerank", "max_forks_repo_head_hexsha": "1e426ead576135b93f839653fb7282b98c7eccdf", "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.0689655172, "max_line_length": 66, "alphanum_fraction": 0.7488789238, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.6793532805336092}}
{"text": "// g++ -O3 -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX\r\n\r\n#include <iostream>\r\n#include <Eigen/Core>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n#ifndef VECTYPE\r\n#define VECTYPE VectorXLd\r\n#endif\r\n\r\n#ifndef VECSIZE\r\n#define VECSIZE 1000000\r\n#endif\r\n\r\n#ifndef REPEAT\r\n#define REPEAT 1000\r\n#endif\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tVECTYPE I = VECTYPE::Ones(VECSIZE);\r\n\tVECTYPE m(VECSIZE,1);\r\n\tfor(int i = 0; i < VECSIZE; i++)\r\n\t{\r\n\t\tm[i] = 0.1 * i/VECSIZE;\r\n\t}\r\n\tfor(int a = 0; a < REPEAT; a++)\r\n\t{\r\n\t\tm = VECTYPE::Ones(VECSIZE) + 0.00005 * (m.cwise().square() + m/4);\r\n\t}\r\n\tcout << m[0] << endl;\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "e677501a9f4e3208a319249f359980076f929a0c", "size": 640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/bench/benchmarkXcwise.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/bench/benchmarkXcwise.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/bench/benchmarkXcwise.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 17.7777777778, "max_line_length": 70, "alphanum_fraction": 0.6109375, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6792885984350541}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2011\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_Zernike2_hpp__\n#define __Thea_Algorithms_Zernike2_hpp__\n\n// Currently Visual Studio 2010 fails to compile Boost multi_array in Debug mode: https://svn.boost.org/trac/boost/ticket/4874\n#if defined(_MSC_VER) && _MSC_VER >= 1600\n#  define THEA_NO_ZERNIKE\n#endif\n\n#ifndef THEA_NO_ZERNIKE\n\n#include \"../Common.hpp\"\n#include \"../IAddressableMatrix.hpp\"\n#include \"../MatVec.hpp\"\n#include <boost/multi_array.hpp>\n#include <complex>\n\nnamespace Thea {\nnamespace Algorithms {\n\n/**\n * Compute Zernike moments of a 2D distribution, represented as a matrix of density values. The density values may be\n * multidimensional, i.e. the matrix elements may be vectors or colors.\n *\n * This class adapts code for the LightField Descriptor from Ding-Yun Chen et al.,\n * http://3d.csie.ntu.edu.tw/~dynamic/3DRetrieval/index.html .\n */\nclass THEA_API Zernike2\n{\n  public:\n    /** The matrix type storing N-dimensional moments. Each column is a moment. */\n    template <int N, typename ScalarT> using MomentMatrix = Matrix< N, Eigen::Dynamic, std::complex<ScalarT> >;\n\n    /** %Options for generating Zernike moments. */\n    struct THEA_API Options\n    {\n      int angular_steps;  ///< Number of angular steps.\n      int radial_steps;   ///< Number of radial steps.\n      int lut_radius;     ///< Radius of Zernike basis function for lookup table.\n\n      /** Constructor. */\n      Options(int angular_steps_ = 12, int radial_steps_ = 3, int lut_radius_ = 50)\n      : angular_steps(angular_steps_), radial_steps(radial_steps_), lut_radius(lut_radius_)\n      {}\n\n      /** Get the set of default options. */\n      static Options const & defaults() { static Options const def; return def; }\n\n    }; // struct Options\n\n    /** Constructor. */\n    Zernike2(Options const & opts_ = Options::defaults());\n\n    /** Get the number of moments generated by a call to compute(). */\n    intx numMoments() const { return opts.angular_steps * opts.radial_steps; }\n\n    /**\n     * Compute Zernike moments of a 2D distribution, represented as a matrix of single- or multi-dimensional density values\n     * (such as reals, vectors or colors). If the density values have more than one dimension, they should allow array\n     * addressing (<code>operator[](intx i)</code>). The template parameter N, inferred from the last argument, must be the same\n     * as the number of dimensions of the input.\n     *\n     * @param distrib The distribution represented as an addressable matrix of density values.\n     * @param center_x The x-coordinate (column) of the center of the non-zero region of the distribution, in matrix\n     *   coordinates.\n     * @param center_y The y-coordinate (row) of the center of the non-zero region of the distribution, in matrix coordinates.\n     * @param radius The radius of the non-zero region of the distribution, measured from the center, in matrix coordinates. All\n     *   zero elements can be ignored when specifying this number.\n     * @param moments Used to return the Zernike moments, specified in \"angle-major, radius-minor\" order. Each moment is a\n     *   column of the matrix.\n     *\n     * @return The number of pixels that have non-zero values and were used to compute the moments.\n     */\n    template <int N, typename T, typename ScalarT>\n    intx compute(IAddressableMatrix<T> const & distrib, double center_x, double center_y, double radius,\n                 MomentMatrix<N, ScalarT> & moments) const;\n\n  private:\n    /** Generate lookup table for moments. */\n    void generateBasisLUT() const;\n\n    /**\n     * Check if an input element (type T) is zero. This is the generic implementation for multi-channel inputs. The\n     * single-channel case is separately specialized.\n    */\n    template <int N> struct IsZero\n    {\n      template <typename T> static bool check(T const & t)\n      {\n        for (int i = 0; i < N; ++i)\n          if (t[i] != 0) return false;\n\n        return true;\n      }\n    };\n\n    /**\n     * Add a scaled increment to a moment. This is the generic implementation for multi-channel inputs. The single-channel case\n     * is separately specialized.\n     */\n    template <int N, typename ScalarT> struct Accum\n    {\n      template <typename T>\n      static void add(T const & t, std::complex<double> const & x, typename MomentMatrix<N, ScalarT>::ColXpr acc)\n      {\n        for (intx i = 0; i < acc.size(); ++i)\n        {\n          acc[i].real(acc[i].real() + static_cast<ScalarT>(x.real() * t[i]));\n          acc[i].imag(acc[i].imag() - static_cast<ScalarT>(x.imag() * t[i]));\n        }\n      }\n    };\n\n    typedef boost::multi_array< std::complex<double>, 4 > LUT;  ///< Lookup table class.\n\n    Options opts;                ///< Set of options.\n    mutable LUT lut;             ///< Coefficient lookup table.\n    mutable bool lut_generated;  ///< Has the LUT been generated?\n\n}; // class Zernike2\n\n// Specializations for single-channel input.\ntemplate <>\nstruct Zernike2::IsZero<1>\n{\n  template <typename T> static bool check(T const & t)\n  {\n    return t != 0;\n  }\n};\n\ntemplate <typename ScalarT>\nstruct Zernike2::Accum<1, ScalarT>\n{\n  template <typename T>\n  static void add(T const & t, std::complex<double> const & x, typename MomentMatrix<1, ScalarT>::ColXpr & acc)\n  {\n    acc[0].real(acc[0].real() + static_cast<ScalarT>(x.real() * t));\n    acc[0].imag(acc[0].imag() - static_cast<ScalarT>(x.imag() * t));\n  }\n};\n\ntemplate <int N, typename T, typename ScalarT>\nintx\nZernike2::compute(IAddressableMatrix<T> const & distrib, double center_x, double center_y, double radius,\n                  Zernike2::MomentMatrix<N, ScalarT> & moments) const\n{\n  alwaysAssertM(radius > 0, \"Zernike2: Radius must be greater than zero\");\n\n  this->generateBasisLUT();\n\n  moments.resize(Eigen::NoChange, numMoments());\n  moments.setZero();\n\n  intx ncols = distrib.cols();\n  intx nrows = distrib.rows();\n\n  // Don't go outside the specified radius\n  intx min_x = std::max(0L,        (intx)std::ceil (center_x - radius));\n  intx max_x = std::min(ncols - 1, (intx)std::floor(center_x + radius));\n\n  intx min_y = std::max(0L,        (intx)std::ceil (center_y - radius));\n  intx max_y = std::min(nrows - 1, (intx)std::floor(center_y + radius));\n\n  double r_radius = opts.lut_radius / radius;\n\n  std::complex<double> x1, x2, x3;\n  double dx, dy, tx, ty;\n  intx ix, iy;\n  intx count = 0;\n  for (intx y = min_y; y <= max_y; ++y)\n  {\n    for (intx x = min_x; x <= max_x; ++x)\n    {\n      T const & density = distrib.at(y, x);\n      if (!IsZero<N>::check(density))\n      {\n        dx = x - center_x;\n        dy = y - center_y;\n        tx = dx * r_radius + opts.lut_radius;\n        ty = dy * r_radius + opts.lut_radius;\n        ix = (intx)tx;\n        iy = (intx)ty;\n        dx = tx - ix;\n        dy = ty - iy;\n\n        // Summation of basis function\n        for (intx p = 0; p < opts.angular_steps; ++p)\n        {\n          for (intx r = 0; r < opts.radial_steps; ++r)\n          {\n            x1 = lut[p][r][ix][iy    ] + (lut[p][r][ix + 1][iy    ] - lut[p][r][ix][iy    ]) * dx;\n            x2 = lut[p][r][ix][iy + 1] + (lut[p][r][ix + 1][iy + 1] - lut[p][r][ix][iy + 1]) * dx;\n            x3 = x1 + (x2 - x1) * dy;\n\n            Accum<N, ScalarT>::add(density, x3, moments.col(p * opts.radial_steps + r));\n          }\n        }\n\n        count++;\n      }\n    }\n  }\n\n  if (count > 0)\n    moments /= (ScalarT)count;\n\n  return count;\n}\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif // !defined(THEA_NO_ZERNIKE)\n\n#endif\n", "meta": {"hexsha": "4eb706234803b1699b82eef3079cbb20cc4539b4", "size": 7993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_stars_repo_name": "christinazavou/Thea", "max_stars_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_issues_repo_name": "christinazavou/Thea", "max_issues_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_forks_repo_name": "christinazavou/Thea", "max_forks_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 34.752173913, "max_line_length": 128, "alphanum_fraction": 0.6267984486, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6791742577127514}}
{"text": "//var_model.cpp\n\n#include <math.h>\n#include <algorithm>\n#include <functional>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n#include \"var_model.h\"\n\nusing namespace std;\nusing namespace boost::accumulators;\n\n//Define container for muliple criteria sorting\nstruct Container{\n                double _return; //returns\n                double _prob; //weighted prob,\n            };\n\nbool sortByReturn(const Container &lhs, const Container &rhs) { return lhs._return < rhs._return; }\n\nVaR::VaR(double _alpha):alpha(_alpha){}\n\n//copy constructor implementation\nVaR::VaR(const VaR& other):    \n\talpha(other.alpha)\n{}\n\ndouble VaR::getAlpha() const {return alpha;}\n\nvoid VaR::setAlpha(double _alpha) {alpha = _alpha;}\n\nParametricVaR::ParametricVaR(double _alpha, bool _logNormal):VaR(_alpha),logNormal(_logNormal)\n{}\n\n//copy constructor implementation\nParametricVaR::ParametricVaR(const ParametricVaR& other):\n\tVaR(other),logNormal(other.logNormal) \n{}\n\n\ndouble ParametricVaR::NormalVaR(double u, double sigma) const{\n\n\t\tdouble za;\n\n\t\tza =  boost::math::quantile(snd, getAlpha());\n\n\t\treturn (u + sigma * za);\n}\n\ndouble ParametricVaR::LogNormalVaR(double u, double sigma) const {\n\n\t\tdouble za;\n\n\t\tza =  boost::math::quantile(snd, getAlpha());\n\n\t\treturn -(1. - exp(u + sigma * za));\n}\n\nRiskMetricsVaR::RiskMetricsVaR(double _alpha, double _lambda, bool _logNormal)\n:ParametricVaR(_alpha, _logNormal), lambda(_lambda){}\n\n//copy constructor implementation\nRiskMetricsVaR::RiskMetricsVaR(const RiskMetricsVaR& other):\n\tParametricVaR(other), lambda(other.lambda)\n{}\n\ndouble RiskMetricsVaR::operator()(double _meanReturn,\n                                  double _sigmatminus1, double _returnt) const{\n\n    double sigmat = sqrt(lambda * _sigmatminus1 * _sigmatminus1 + (1. - lambda) * _returnt * _returnt);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmat) : NormalVaR(_meanReturn, sigmat);\n\n\treturn tmp >= 0 ? 0. : tmp;\n\n}\n\ndouble RiskMetricsVaR::operator()(double _meanReturn, const Vec& returns) const\n{\n\tdouble sigmaT = 0.;\n    size_t T(returns.size());\n\n    for(size_t i = 1; i < T;++i){\n        sigmaT = sqrt(lambda * sigmaT * sigmaT + (1. - lambda) * returns[i] * returns[i]);\n    }\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\ndouble RiskMetricsVaR::operator()(const Vec& returns) const\n{\n    double sigmaT = 0.;\n    double _meanReturn =0;\n    size_t T(returns.size());\n\n    for(size_t i = 1; i < T;++i){\n        sigmaT = sqrt(lambda * sigmaT * sigmaT + (1. - lambda) * returns[i] * returns[i]);\n        _meanReturn += returns[i];\n    }\n\n    _meanReturn =_meanReturn/(T-1);\n\n    double tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\nGarchVaR::GarchVaR(double _alpha, double _a, double _b,  double _c,bool _logRtns)\n:ParametricVaR(_alpha, _logRtns), a(_a), b(_b), c(_c){}\n\n//copy constructor implementation\nGarchVaR::GarchVaR(const GarchVaR& other):\t\n\tParametricVaR(other), a(other.a), b(other.b),c(other.c)\n{}\n\ndouble GarchVaR::operator()(double _meanReturn,\n                            double _sigmatminus1, double _returntminus1) const{\n\n    double sigmat = sqrt(a + c * _sigmatminus1 * _sigmatminus1 + b * _returntminus1 * _returntminus1);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmat) : NormalVaR(_meanReturn, sigmat);\n\n\treturn tmp >= 0 ? 0. : tmp;\n\n}\n\ndouble GarchVaR::operator()(double _meanReturn, const Vec& returns) const\n{\n\tdouble sigmaT = 0.;\n\n    for(size_t i = 0; i < returns.size();++i)\n        sigmaT += pow(c,static_cast<double>(i)) * returns[i] * returns[i];\n\n    sigmaT *= b;\n    sigmaT += a/(1.-c);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sqrt(sigmaT)) : NormalVaR(_meanReturn, sqrt(sigmaT));\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\ndouble GarchVaR::operator()(const Vec& returns) const\n{\n    double sigmaT = 0.;\n    double _meanReturn =0;\n    size_t T(returns.size());\n\n    for(size_t i = 0; i < T;++i){\n        sigmaT += pow(c,static_cast<double>(i)) * returns[i] * returns[i];\n        _meanReturn += returns[i];\n    }\n\n    sigmaT *= b;\n    sigmaT += a/(1.-c);\n    _meanReturn =_meanReturn/(T-1);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0 : tmp;\n}\n\nNoneParametricVaR::NoneParametricVaR(double _alpha):VaR(_alpha){}\n\nNoneParametricVaR::NoneParametricVaR(const NoneParametricVaR& other)\n:VaR(other)\n{}\n\nHistoricalVaR::HistoricalVaR(double _alpha, double _lambda, WeightingScheme _ws)\n:NoneParametricVaR(_alpha), lambda(_lambda), ws(_ws){}\n\n//copy constructor implementation\nHistoricalVaR::HistoricalVaR(const HistoricalVaR& other):\t\n\tNoneParametricVaR(other), lambda(other.lambda), ws(other.ws)\n{}\n\ndouble HistoricalVaR::operator()(double _sigmatminus1,\n                                 const Vec& returns) const\n{\n \tdouble T = returns.size();\n\n\tdouble alpha(getAlpha());\n\n\tunsigned int c(alpha * T);\n\tc == 0 ? c : c-= 1;\n\n\tdouble tmp;\n\n\tint input(ws);\n\n\tstd::vector<double> _returns(returns);\n\n\tswitch(input){\n\n\tcase 0:\n        {\n            // sort returns find cth arg - Histogram method\n            std::sort(_returns.begin(), _returns.end());\n\n            tmp = _returns[c];\n        }\n\n        break;\n\n\tcase 1:\n        {\n            std::vector<Container> prob(T);\n\n            double a = (1. - lambda)/(1. - pow(lambda, T));\n\n            for(size_t i = 0; i < T; ++i){\n                prob[i]._return = _returns[T -1 - i];\n                prob[i]._prob = a * pow(lambda, i);\n            }\n\n            // Sort Container by return function\n            std::sort(prob.begin(), prob.end(),sortByReturn);\n\n            double sumProb(0);\n\n            for(size_t i = 0; i < T; ++i){\n                sumProb += prob[i]._prob;\n\n                if(sumProb >= alpha){\n                    tmp = prob[i]._return;\n                    break;\n                }\n            }\n\n        }\n\n\n        break;\n\n    case 2:\n\n        {\n            std::vector<double> sigma;\n\n            sigma.push_back(_sigmatminus1 * _sigmatminus1); \n\n            for(size_t i = 1; i < T;++i)\n                sigma.push_back(lambda * sigma[i - 1] + (1. - lambda) * returns[i - 1] * returns[i - 1]);\n\n            double sigmaT(sigma.back()); \n\n            std::vector<double> _wgthRtns;\n\n            for(size_t i = 0; i < T; ++i){\n\n                if(sigma[i] <= 0) _wgthRtns.push_back(_returns[i]);\n                else _wgthRtns.push_back(sqrt(sigmaT / sigma[i]) * _returns[i] );\n            }\n\n\n            // sort returns find cth arg - Histogram method\n            std::sort(_wgthRtns.begin(), _wgthRtns.end());\n\n            tmp = _wgthRtns[c];\n        }\n\n        break;\n\n    default:\n        break;\n\n\t}\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\nExtremeValueVaR::ExtremeValueVaR(double _alpha):VaR(_alpha){}\n\n//copy constructor implementation\nExtremeValueVaR::ExtremeValueVaR(const ExtremeValueVaR& other):   \n\tVaR(other)\n{}\n\nPoTVaR::PoTVaR(double _u,double _beta, double _xi,double _alpha)\n: ExtremeValueVaR(_alpha),xi(_xi),beta(_beta),u(_u){\n\n}\n\n//copy constructor implementation\nPoTVaR::PoTVaR(const PoTVaR& other): \n\tExtremeValueVaR(other), xi(other.xi), beta(other.beta), u(other.u)\n{}\n\ndouble PoTVaR::operator()(const double& ratio) const\n{\n\tdouble a = 1./ratio * getAlpha();\n\n\treturn -(u +  beta * (pow(a,- xi) - 1.)/ xi );\n}\n\ndouble PoTVaR::expectedShortfall(const double& ratio) const\n{\n\treturn ((this->operator()(ratio) - (beta - xi * u)))/(1. - xi);\n\n}\n\ndouble PoTVaR::expectedShortfall(const Vec& returns) const{\n\n\tdouble ratio(0.);\n\n\tfor(size_t i =0;i < returns.size();++i){\n        if(returns[i] < 0)\n            if(-returns[i] > u) ratio +=1;\n\t}\n\n\tratio /= returns.size();\n    if(ratio < .05) ratio = .05;\n\n\n\treturn this->expectedShortfall(ratio);\n}\n\ndouble PoTVaR::operator()(const Vec& returns) const{\n\n\tdouble ratio(0.);\n\n\tfor(size_t i =0;i < returns.size();++i){\n        if(returns[i] < 0)\n            if(-returns[i] > u) ratio +=1;\n\t}\n\n\tratio /= returns.size();\n    if(ratio < .05) ratio = .05;\n\n\treturn this->operator()(ratio);\n}\n\n\n\n", "meta": {"hexsha": "b7b90050c0d16e2302d4314fcc73904d120fe31a", "size": 8137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/var_model.cpp", "max_stars_repo_name": "calvin456/VaR", "max_stars_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "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/var_model.cpp", "max_issues_repo_name": "calvin456/VaR", "max_issues_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "max_issues_repo_licenses": ["MIT"], "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/var_model.cpp", "max_forks_repo_name": "calvin456/VaR", "max_forks_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "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": 24.073964497, "max_line_length": 105, "alphanum_fraction": 0.6211134325, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.679174248610329}}
{"text": "//\n//  MathUtil.cpp\n//  edgeRuntime\n//\n//  Created by Abdelrahaman Aly on 04/02/14.\n//\n//\n\n//Library Headers\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n\n//Custom Headers\n#include \"List.h\"\n#include \"MathUtil.h\"\nusing namespace NTL;\nnamespace Utilities\n{\n    //less significative bit on the left always most significative bit on the right always\n    int * MathUtil::obtainBits(long number, int size)\n    {\n        int * bits= new int[size];\n        for (int i=0; i<size; i++)\n        {\n            \n            if (number&1)\n            {\n\n                bits[i]=1;\n            }\n            else\n            {\n                bits[i]=0;\n            }\n            \n            number>>=1;\n\n        }\n        return bits;\n    };\n    \n    //Calculates the lagrangian interpolation. Currently optimized for 3 players\n    long MathUtil::lagrangianInterpolation( long * values, int size)\n    {\n        //TODO: build the lagrangian interpolation\n\n        ZZ_p  result;\n        result=2*conv<ZZ_p>(values[0]) -conv<ZZ_p>(values[1]);\n        long resultLong =conv<long>(result);\n        return  resultLong;\n    };\n    \n    //calculates the complement 2 adding first aone and then decomposing into bits\n    int* MathUtil::obtainComplementTwo(long  value, int size)\n    {\n        value=~value;\n        value++;\n        return MathUtil::obtainBits(value, size);\n    };\n    \n    //obtains the additive of 2 mod values\n    long MathUtil::additionMod(long a, long b)\n    {\n        ZZ_p ap= conv<ZZ_p>(a);\n        ZZ_p bp= conv<ZZ_p>(b);\n        return conv<long>(a+b);\n    };\n    \n    //Obteins the multiplicative of 2 mod values\n    long MathUtil::multiplyMod(long a, long b)\n    {\n        ZZ_p ap= conv<ZZ_p>(a);\n        ZZ_p bp= conv<ZZ_p>(b);\n        return conv<long>(a*b);\n    };\n    \n    //An specification on generic multiplier of polynomials\n    ZZ_pX MathUtil::multiplyLagrangePolynomials(vec_ZZ_p x_v, ZZ_p x_j)\n    {\n\n        ZZ_p x_d= x_j-x_v[0];\n        ZZ_p a= 1/x_d;\n        ZZ_pX p;\n        p.SetLength(2);\n        p[0]= (-1)*x_v[0]*a;\n        p[1]= a;\n     \n        for (int k=1; k< x_v.length(); k++)\n        {\n            ZZ_p x_k =x_v[k];\n            x_d= x_j-x_k;\n            a= 1/x_d;\n            \n            ZZ_pX auxP;\n            auxP.SetLength(2);\n            auxP[0]= (-1)*x_k*a;\n            auxP[1]=a;\n            \n            p=p*auxP;\n        }\n        return p;\n    };\n    \n    //Interpolations:\n    ZZ_pX MathUtil::multiplyLagrangePolynomials(int x_s, int x_k,int x_j)\n    {\n        vec_ZZ_p values;\n        values.SetLength((x_k+1)-x_s -1);\n        int j=0;\n        for (int i = x_s; i<=x_k; i++)\n        {\n            if (i!= x_j) {\n               values[j]= conv<ZZ_p>(i);\n               j++;\n            }\n\n        }\n        return MathUtil::multiplyLagrangePolynomials(values, conv<ZZ_p>(x_j));\n    };\n    \n    int MathUtil::pow2roundup (int value)\n    {\n        int x=value;\n        if (x < 0)\n            return 0;\n        --x;\n        x |= x >> 1;\n        x |= x >> 2;\n        x |= x >> 4;\n        x |= x >> 8;\n        x |= x >> 16;\n        return x+1;\n    }\n}\n", "meta": {"hexsha": "a60e3257d7026de63c741eb96507034c93853675", "size": 3087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "edgeRuntime/MathUtil.cpp", "max_stars_repo_name": "abdelrahamanaly/mpcToolkit", "max_stars_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T15:08:05.000Z", "max_issues_repo_path": "edgeRuntime/MathUtil.cpp", "max_issues_repo_name": "abdelrahamanaly/mpcToolkit", "max_issues_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "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": "edgeRuntime/MathUtil.cpp", "max_forks_repo_name": "abdelrahamanaly/mpcToolkit", "max_forks_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T03:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:22:28.000Z", "avg_line_length": 22.8666666667, "max_line_length": 90, "alphanum_fraction": 0.4914156139, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6791742325054566}}
{"text": "#include <Eigen/Eigenvalues>\n#include <boost/timer/timer.hpp>\n#include <iostream>\n\n#include \"eigen-qp.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace EigenQP;\n/*\n *  min 0.5 x.Q.x + c.x\n *\n *  Ax <= b\n *  Ex = d\n *\n * See: http://etd.dtu.dk/thesis/220437/ep08_19.pdf\n */\n// #define NV_FIXED 8\n// #define NC_FIXED 16\n// #define NE_FIXED 3\n\n#define PROB_VARS 8\n#define PROB_INEQ 16\n#define PROB_EQ 3\n\n#define N_TEST   (1<<16)\n\ntemplate<typename Scalar, int NV_FIXED, int NC_FIXED, int NE_FIXED>\nvoid test()\n{\n\n    typedef Eigen::Matrix<Scalar,-1,-1> MatrixXs;\n    typedef Eigen::Matrix<Scalar,-1,1> VectorXs;\n\n    // Make a random problem\n    int num_vars = NV_FIXED;\n    int num_ineq = NC_FIXED;\n    int num_eq   = NE_FIXED;\n\n    // Random matrices\n    MatrixXs Q = MatrixXs::Random(num_vars,num_vars);\n    Q *= Q.adjoint()/sqrt(num_vars); // Make it pos def\n\n    VectorXs c = VectorXs::Random(num_vars);\n\n    MatrixXs A = MatrixXs::Random(num_ineq,num_vars);\n    VectorXs b = VectorXs::Random(num_ineq);\n\n    MatrixXs E = MatrixXs::Random(num_eq,num_vars);\n    VectorXs f = VectorXs::Random(num_eq);\n\n    VectorXs x_unc;\n    // Solve unconstrainted system\n    cout << \"Unconstrained...\" << endl;\n    {\n        boost::timer::auto_cpu_timer t;\n        for (int ii=0; ii < N_TEST; ii++)\n          x_unc = -Q.ldlt().solve(c);\n    }\n    VectorXs x(num_vars);\n    // Generate inequality constraints\n    b.array() = (A*x_unc).array() - 0.15;\n    // Inequality constrained problem\n    cout << \"quadprog, dynamic code\" << endl;\n    {\n        boost::timer::auto_cpu_timer t;\n        for (int ii=0; ii < N_TEST; ii++)\n            quadprog(Q,c,A,b,x);\n    }\n    cout << \"    error: \" << (x - x_unc).norm() << endl;\n    {\n        QPIneqSolver<Scalar,-1,-1> *solver;\n        cout <<\"QPIneqSolver, dynamic, obj creation\" << endl;\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n            {\n                solver = new QPIneqSolver<Scalar,-1,-1>(num_vars,num_ineq);\n                solver->solve(Q,c,A,b,x);\n            }\n        }\n        cout << \"    error: \" << (x - x_unc).norm() << endl;\n        cout << \"QPIneqSolver, dynamic, object reuse\" << endl;\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n                solver->solve(Q,c,A,b,x);\n        }\n        cout << \"    error: \" << (x - x_unc).norm() << endl;\n    }\n\n    // Fixed size\n    Matrix<Scalar, NV_FIXED,NV_FIXED> Q_fixed(Q);\n    Matrix<Scalar, NV_FIXED, 1> c_fixed(c);\n    Matrix<Scalar, NC_FIXED,NV_FIXED> A_fixed(A);\n    Matrix<Scalar, NC_FIXED,1> b_fixed(b);\n\n    // Q_fixed.setRandom();\n    // c_fixed.setRandom();\n    // A_fixed.setRandom();\n\n    x_unc = -Q_fixed.ldlt().solve(c_fixed);\n\n    b_fixed.array() = (A_fixed*x_unc).array() - 0.12;\n\n    Matrix<Scalar, NV_FIXED, 1> x_fixed;\n    cout << \"quadprog, fixed code\" << endl;\n    {\n        boost::timer::auto_cpu_timer t;\n        for (int ii=0; ii < N_TEST; ii++)\n            quadprog(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed);\n    }\n    cout << \"    error: \" << (x_fixed - x_unc).norm() << endl;\n    {\n        QPIneqSolver<Scalar,NV_FIXED,NC_FIXED> *solver;\n        cout << \"QPIneqSolver, fixed\" << endl;\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n            {\n                solver = new QPIneqSolver<Scalar,NV_FIXED,NC_FIXED>(num_vars,num_ineq);\n                solver->solve(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed);\n            }\n        }\n        cout << \"    error: \" << (x_fixed - x_unc).norm() << endl;\n        cout << \"QPIneqSolver, fixed, object reuse\" << endl;\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n                solver->solve(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed);       \n        }\n        cout << \"    error: \" << (x_fixed - x_unc).norm() << endl;\n    }\n\n    cout << \"QPEqSolver, equality constraints, dynamic\" << endl;\n    {\n        QPEqSolver<Scalar> solver(num_vars,num_eq);\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n                solver.solve(Q,c,E,f,x);\n        }\n    }\n\n    /*\n    // known to be broken\n    cout << \"quadprog, ineq/eq constraints, dynamic\" << endl;\n    {\n        //b = A*x - 0.12;\n        QPGenSolver<Scalar> solver(num_vars,num_ineq,num_eq);\n        {\n            boost::timer::auto_cpu_timer t;\n            for (int ii=0; ii < N_TEST; ii++)\n                solver.solve(Q,c,A,b,E,f,x);\n        }\n    }\n    */\n}\n\nint main(int argc, char ** argv)\n{\n    srand((unsigned int) time(0));\n    cout << \"TESTING DOUBLE\" << endl;\n    test<double,PROB_VARS,PROB_INEQ,PROB_EQ>();\n    cout << \"TESTING FLOAT\" << endl;\n    test<float,PROB_VARS,PROB_INEQ,PROB_EQ>();\n    return 0;\n}", "meta": {"hexsha": "4a2a9c9d19ebbd9a16fbd6cbaee534040dd02402", "size": 4823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "driver.cpp", "max_stars_repo_name": "jarredbarber/eigen-QP", "max_stars_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T20:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:40:24.000Z", "max_issues_repo_path": "driver.cpp", "max_issues_repo_name": "jarredbarber/eigen-QP", "max_issues_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T05:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-13T01:47:12.000Z", "max_forks_repo_path": "driver.cpp", "max_forks_repo_name": "jarredbarber/eigen-QP", "max_forks_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T15:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T06:43:00.000Z", "avg_line_length": 28.7083333333, "max_line_length": 87, "alphanum_fraction": 0.5535973461, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6790596872907131}}
{"text": "/**\n * \\file\n *\n * \\author Nicholas J. Curtis\n * \\date 04/29/2016\n *\n * \\brief Defines an interface for boost's runge_kutta_fehlberg78 solver\n *\n*/\n\n#ifndef RK78_TYPEDEFS_HPP\n#define RK78_TYPEDEFS_HPP\n\n#include <boost/numeric/odeint.hpp>\nusing namespace boost::numeric::odeint;\n\n//our code\nextern \"C\" {\n\t#include \"dydt.h\"\n\t#include \"header.h\"\n\t#include \"solver_options.h\"\n}\n\n#ifdef GENERATE_DOCS\nnamespace rk78 {\n#endif\n\n//! state vector\ntypedef std::vector< double > state_type;\n\n//! solver type\ntypedef runge_kutta_fehlberg78< state_type , double > stepper;\n\n//! controller type\ntypedef controlled_runge_kutta< stepper > controller;\n\n//stiffness measure for project\n//do a binary search to find the maximum available stepsize\n#ifdef LOG_OUTPUT\n//#define STIFFNESS_MEASURE\n#endif\n#ifdef STIFFNESS_MEASURE\n#include <boost/numeric/odeint/stepper/controlled_step_result.hpp>\n#endif\n\n/**\n   \\brief A wrapper class to evaluate the rhs function y' = f(y)\n   stores the state variable, and provides to dydt\n*/\nclass rhs_eval {\n\tdouble m_statevar;\npublic:\n\trhs_eval() {\n\t\tthis->m_statevar = -1;\n\t}\n\n\tvoid set_state_var(const double state_var)\n\t{\n\t\tthis->m_statevar = state_var;\n\t}\n\n\t//wrapper for the pyJac RHS fn\n\tvoid operator() (const state_type &y , state_type &fy , const double t) const\n\t{\n\t\tdydt(t, this->m_statevar, &y[0], &fy[0]);\n\t}\n};\n\n#ifdef GENERATE_DOCS\n}\n#endif\n\n#endif", "meta": {"hexsha": "b322b934733c90df80e5159e83832b6602db05a6", "size": 1377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rk78/rk78_typedefs.hpp", "max_stars_repo_name": "arghdos/accelerInt", "max_stars_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T12:35:45.000Z", "max_issues_repo_path": "rk78/rk78_typedefs.hpp", "max_issues_repo_name": "arghdos/accelerInt", "max_issues_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-03-02T19:15:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T10:50:14.000Z", "max_forks_repo_path": "rk78/rk78_typedefs.hpp", "max_forks_repo_name": "arghdos/accelerInt", "max_forks_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-01T01:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T13:57:17.000Z", "avg_line_length": 18.8630136986, "max_line_length": 78, "alphanum_fraction": 0.7269426289, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6790596794343284}}
{"text": "// Based on minimal example in https://github.com/CGAL/cgal/wiki/How-to-use-CGAL-with-CMake-or-your-own-build-system\n// but with Qt dependency removed\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/helpers.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Boolean_set_operations_2.h>\n\n// Just to ensure that Eigen's CMake configuration is correct\n#include <Eigen/Dense>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt K;\ntypedef K::Point_3 Point;\ntypedef CGAL::Surface_mesh<Point> Mesh;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\ntypedef Kernel::Point_2                                   Point_2;\ntypedef CGAL::Polygon_2<Kernel>                           Polygon_2;\n\nint main()\n{\n  Mesh m;\n  CGAL::make_icosahedron<Mesh, Point>(m);\n\n  // This part is based on Boolean_set_operations_2/do_intersect.cpp\n  Polygon_2 P;\n  P.push_back (Point_2 (-1,1));\n  P.push_back (Point_2 (0,-1));\n  P.push_back (Point_2 (1,1));\n  Polygon_2 Q;\n  Q.push_back(Point_2 (-1,-1));\n  Q.push_back(Point_2 (1,-1));\n  Q.push_back(Point_2 (0,1));\n\n  if ((CGAL::do_intersect (P, Q))) {\n    std::cout << \"The two polygons intersect in their interior.\" << std::endl;\n    return 0;\n  } else {\n    std::cout << \"The two polygons do not intersect, but should.\" << std::endl;\n    return 1;\n  }\n}\n", "meta": {"hexsha": "6843ef6437696465e22144fed7452b9cec75c333", "size": 1422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipe/test/test.cpp", "max_stars_repo_name": "Michsior14/cgal-cpp-feedstock", "max_stars_repo_head_hexsha": "38c76128123a603dd3f9a823720d7f39b5751dcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T14:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-21T14:06:10.000Z", "max_issues_repo_path": "recipe/test/test.cpp", "max_issues_repo_name": "Michsior14/cgal-cpp-feedstock", "max_issues_repo_head_hexsha": "38c76128123a603dd3f9a823720d7f39b5751dcc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-03-25T17:08:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:12:11.000Z", "max_forks_repo_path": "recipe/test/test.cpp", "max_forks_repo_name": "Michsior14/cgal-cpp-feedstock", "max_forks_repo_head_hexsha": "38c76128123a603dd3f9a823720d7f39b5751dcc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-21T14:06:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T19:30:11.000Z", "avg_line_length": 31.6, "max_line_length": 116, "alphanum_fraction": 0.7053445851, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6790151572240455}}
{"text": "#include \"NuiMatrixUtilities.h\"\n\n#include <Eigen/Geometry>\n\nnamespace NuiMatrixUtilities\n{\n\tVector3f rodrigues2(const Eigen::Matrix3f& matrix)\n\t{\n\t\tEigen::JacobiSVD<Eigen::Matrix3f> svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU);    \n\t\tEigen::Matrix3f R = svd.matrixU() * svd.matrixV().transpose();\n\n\t\tdouble rx = R(2, 1) - R(1, 2);\n\t\tdouble ry = R(0, 2) - R(2, 0);\n\t\tdouble rz = R(1, 0) - R(0, 1);\n\n\t\tdouble s = sqrt((rx*rx + ry*ry + rz*rz)*0.25);\n\t\tdouble c = (R.trace() - 1) * 0.5;\n\t\tc = c > 1. ? 1. : c < -1. ? -1. : c;\n\n\t\tdouble theta = acos(c);\n\n\t\tif( s < 1e-5 )\n\t\t{\n\t\t\tdouble t;\n\n\t\t\tif( c > 0 )\n\t\t\t\trx = ry = rz = 0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tt = (R(0, 0) + 1)*0.5;\n\t\t\t\trx = sqrt( std::max(t, 0.0) );\n\t\t\t\tt = (R(1, 1) + 1)*0.5;\n\t\t\t\try = sqrt( std::max(t, 0.0) ) * (R(0, 1) < 0 ? -1.0 : 1.0);\n\t\t\t\tt = (R(2, 2) + 1)*0.5;\n\t\t\t\trz = sqrt( std::max(t, 0.0) ) * (R(0, 2) < 0 ? -1.0 : 1.0);\n\n\t\t\t\tif( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0) )\n\t\t\t\t\trz = -rz;\n\t\t\t\ttheta /= sqrt(rx*rx + ry*ry + rz*rz);\n\t\t\t\trx *= theta;\n\t\t\t\try *= theta;\n\t\t\t\trz *= theta;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble vth = 1/(2*s);\n\t\t\tvth *= theta;\n\t\t\trx *= vth; ry *= vth; rz *= vth;\n\t\t}\n\t\treturn Eigen::Vector3d(rx, ry, rz).cast<float>();\n\t}\n}", "meta": {"hexsha": "7f9ae854f49403b6b34e6be505d3b25435fc5d81", "size": 1241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Foundation/NuiMatrixUtilities.cpp", "max_stars_repo_name": "hustztz/NatureUserInterfaceStudio", "max_stars_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:04:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-01T09:58:27.000Z", "max_issues_repo_path": "src/Foundation/NuiMatrixUtilities.cpp", "max_issues_repo_name": "hustztz/NatureUserInterfaceStudio", "max_issues_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_issues_repo_licenses": ["MIT"], "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/Foundation/NuiMatrixUtilities.cpp", "max_forks_repo_name": "hustztz/NatureUserInterfaceStudio", "max_forks_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-21T15:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T15:33:35.000Z", "avg_line_length": 23.4150943396, "max_line_length": 95, "alphanum_fraction": 0.4834810637, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6789639041621292}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestAxisAngle\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <cmath>\n#include \"minimath/geom3d_ops.hpp\"\n#include \"minimath/point3d.hpp\"\n#include \"minimath/rotation3d.hpp\"\n#include \"TestRotation3DUtils.h\"\n\nusing minimath::axisangle;\nusing minimath::rotation3d;\nusing minimath::rotation3dx;\nusing minimath::rotation3dy;\nusing minimath::rotation3dz;\n\nBOOST_AUTO_TEST_SUITE(TestAxisAngle)\n\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  axisangle<double> rot1, rot2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n  BOOST_CHECK(axisangle<double>() == axisangle<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  axisangle<double> rot1;\n  axisangle<double> rot2(rot1);\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  axisangle<double> rot1, rot2;\n  rot2 = rot1;\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testNullRotation)\n{\n  axisangle<double> rot;\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45X)\n{\n  axisangle<double> rot(p100, PI/4.); // 45 degree rotation about X\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., cos45, cos45));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -cos45, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90X)\n{\n  axisangle<double> rot(p100, PI/2.); // 90 degree rotation about X\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180X)\n{\n  axisangle<double> rot(p100, PI); // 180 degree rotation about X\n\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Y)\n{\n  axisangle<double> rot(p010, PI/4.); // 45 degree rotation about Y\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0., -cos45));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Y)\n{\n  axisangle<double> rot(p010, PI/2.); // 90 degree rotation about Y\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Y)\n{\n  axisangle<double> rot(p010, PI); // 180 degree rotation about Y\n\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Z)\n{\n  axisangle<double> rot(p001, PI/4.); // 45 degree rotation about Z\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, cos45, 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(-cos45, cos45, 0));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0, 0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Z)\n{\n  axisangle<double> rot(p001, PI/2.); // 90 degree rotation about Z\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Z)\n{\n  axisangle<double> rot(p001, PI); // 180 degree rotation about Z\n\n  pointxyzd pTest = rotation3d<double>(rot)*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rotation3d<double>(rot)*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rotation3d<double>(rot)*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DX)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(axisangle<double>(p100, PI/i) == rotation3dx<double>(PI/i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DY)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(axisangle<double>(p010, PI/i) == rotation3dy<double>(PI/i));\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DZ)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(axisangle<double>(p001, PI/i) == rotation3dz<double>(PI/i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  BOOST_CHECK(TestUtils::testInverseAxisAngle(p100));\n  BOOST_CHECK(TestUtils::testInverseAxisAngle(p010));\n  BOOST_CHECK(TestUtils::testInverseAxisAngle(p001));\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  BOOST_CHECK(TestUtils::testInvertAxisAngle(p100));\n  BOOST_CHECK(TestUtils::testInvertAxisAngle(p010));\n  BOOST_CHECK(TestUtils::testInvertAxisAngle(p001));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "bb2f9d5901efb14b94f35794e2487b742f8f5ada", "size": 5884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestAxisAngle.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestAxisAngle.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestAxisAngle.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 26.5045045045, "max_line_length": 76, "alphanum_fraction": 0.7051325629, "num_tokens": 1895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.678961006304527}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <Eigen/Dense>\n\nTEST (Eigen, dotProduct) {\n  Eigen::Vector3d v {0.1, 0.2, 0.3};\n  double expected = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n  ASSERT_EQ(v.norm(), expected);\n}\n", "meta": {"hexsha": "212092249b7eaa1b6b5216763553ed70e07a5905", "size": 216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen/dot_product_test.cpp", "max_stars_repo_name": "juugcatm/bazel_environment", "max_stars_repo_head_hexsha": "248cfb923ea83a270082883079af617e507cc760", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T16:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T06:20:35.000Z", "max_issues_repo_path": "examples/eigen/dot_product_test.cpp", "max_issues_repo_name": "juugcatm/bazel_environment", "max_issues_repo_head_hexsha": "248cfb923ea83a270082883079af617e507cc760", "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": "examples/eigen/dot_product_test.cpp", "max_forks_repo_name": "juugcatm/bazel_environment", "max_forks_repo_head_hexsha": "248cfb923ea83a270082883079af617e507cc760", "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": 21.6, "max_line_length": 66, "alphanum_fraction": 0.5833333333, "num_tokens": 85, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6789171060190605}}
{"text": "#ifndef EXPSUM_LSQR_HPP\n#define EXPSUM_LSQR_HPP\n\n#include <armadillo>\n\nnamespace expsum\n{\n///\n/// lsqr\n///\n/// `lsqr` solves a least squares problem\n///\n/// ``` math\n///   \\min \\| A\\bm{x} - \\bm{b} \\|_{2},\n/// ```\n///\n/// where ``$A \\in \\mathcal{C}^{m \\times n}, \\, \\bm{b} \\in \\mathcal{C}^{n} $``\n/// with ``$m \\geq n$``.\n///\n/// @param[in]  matvec A function object that compute matrix-vector product\n///   `y += A * x`\n/// @param[in]  matvec_trans A function object that compute matrix-vector\n///   product `y += A.t() * x`\n/// @param[inout] u A vector of length m. On input the right hand side vector\n///     ``$b$``, on exit, `u` is overwritten.\n/// @param[out] x A vector of length n. On input and initial guess of solution,\n///    on exit, the computed solution.\n/// @param[in] precond_solve Functor for applying preconditioner to a vector.\n/// @param[out] work A matrix of size ``$n \\times 3$`` used as workspace.\n/// @param[inout] iterations  On input the max number of iteration, on exit the\n///    number of performed iterations.\n/// @param[inout] tol_error  On input the tolerance error, on exit as estimation\n///    of the relative error.\n///\n\ntemplate <typename MatVec, typename MatVecTrans, typename VectorU,\n          typename VectorX, typename Preconditioner, typename MatrixWork>\nvoid lsqr(MatVec matvec, MatVecTrans matvec_trans, VectorU& u, VectorX& x,\n          const Preconditioner& apply_preconditioner, MatrixWork& work,\n          arma::uword& iterations, typename VectorX::pod_type& tol_error)\n{\n    using value_type = typename VectorX::elem_type;\n    using real_type  = typename VectorX::pod_type;\n    using size_type  = arma::uword;\n\n    using std::sqrt;\n    using std::real;\n    using std::abs;\n    using std::norm;\n\n    const real_type atol = tol_error;\n    const real_type btol = tol_error;\n\n    auto p = work.col(0);\n    auto v = work.col(1);\n    auto w = work.col(2);\n    //\n    // --- Initialization\n    //\n    x.zeros();\n    real_type alpha = real_type();\n    real_type beta  = arma::norm(u);\n    if (beta > real_type())\n    {\n        u *= real_type(1) / beta;         // normalize\n        matvec_trans(u, value_type(), p); // p <-- A.t() * u;\n        apply_preconditioner(p, v);       // v <-- M.inv() * p\n        alpha = sqrt(real(arma::cdot(v, p)));\n        if (alpha > real_type())\n        {\n            v *= real_type(1) / alpha; // normalize\n            w = v;\n        }\n    }\n\n    // Estimation of the norm of `A.t() * r`\n    real_type norm_Atr = alpha * beta;\n    if (norm_Atr == real_type())\n    {\n        // x = 0 is the exact solution\n        return;\n    }\n\n    real_type rhobar = alpha;\n    real_type phibar = beta;\n\n    // Estimations of the Frobenius norm of matrix A\n    real_type norm_A = real_type();\n    // Norm of r.h.s. vector b\n    real_type norm_b = beta;\n    // Estimation of the norm of residual vector `r = b - A * x`.\n    real_type norm_r = beta;\n    // Estimation of the norm of solution vector x.\n    real_type norm_x = real_type();\n\n    real_type cs2     = real_type(-1);\n    real_type sn2     = real_type();\n    real_type z       = real_type();\n    real_type norm_bb = real_type();\n    real_type norm_xx = real_type();\n\n    size_type iter = 0;\n    while (++iter <= iterations)\n    {\n        //\n        // --- Bidiagonalization\n        //\n        // Perform the next step of the bidiagonalization with M-weighted inner\n        // product.  `beta, u, alpha, v`. These satisfy the relations\n        //\n        // ``` math\n        //  \\beta_{i+1} \\bm{u}_{i+1}\n        //    &= A \\bm{v}_{i} - \\alpha_{i} \\bm{u}_{i},\n        //  \\alpha_{i+1} \\bm{v}_{i+1}\n        //    &= M^{-1} A^{H} \\bm{u}_{i+1} - \\beta_{i+1} \\bm{v}_{i},\n        //  \\alpha_{i+1} &= (\\bm{v}_{i+1}^{H} M \\bm{v}_{i+1}^{})^{1/2}\n        // ```\n        //\n        matvec(v, -alpha, u); // u <-- A * v - alpha * u\n        beta = arma::norm(u);\n        norm_bb += norm(alpha) + norm(beta);\n\n        if (beta > real_type())\n        {\n            u *= real_type(1) / beta;\n            matvec_trans(u, -beta, p);  // p <-- A.t() * u - beta * p\n            apply_preconditioner(p, v); // v <-- M.inv() * p\n            alpha = sqrt(real(arma::cdot(v, p)));\n            if (alpha > real_type())\n            {\n                v *= real_type(1) / alpha;\n            }\n        }\n        //\n        // --- Orthogonal transformation\n        //\n        // Construct and apply next orthogonal transformation (plane rotation)\n        // to eliminate the subdiagonal element (beta) of the lower-bidiagonal\n        // matrix, giving an upper-bidiagonal matrix. The explicit form of the\n        // transformation is given as\n        //\n        // [cs  sn][rhobar      0  phibar]   [rho   theta     phi ]\n        // [sn -cs][  beta  alpha       0] = [  0  rhobar' phibar']\n        //\n        real_type rho   = sqrt(norm(rhobar) + norm(beta));\n        real_type cs    = rhobar / rho;\n        real_type sn    = beta / rho;\n        real_type theta = sn * alpha;\n        rhobar          = -cs * alpha;\n        real_type phi   = cs * phibar;\n        phibar *= sn;\n        //\n        // Update vectors\n        //\n        // norm_dd += (w / rho).squaredNorm();\n        x += (phi / rho) * w;\n        w = v - (theta / rho) * w;\n        //\n        // Estimate norm of x using the result of plane rotation\n        //\n        real_type delta     = sn2 * rho;\n        real_type gamma_bar = -cs2 * rho;\n        real_type rhs       = phi - delta * z;\n        real_type zbar      = rhs / gamma_bar;\n        norm_x              = sqrt(norm_xx + norm(zbar));\n        real_type gamma     = sqrt(norm(gamma_bar) + norm(theta));\n        cs2                 = gamma_bar / gamma;\n        sn2                 = theta / gamma;\n        z                   = rhs / gamma;\n        norm_xx += norm(z);\n\n        //\n        // Test for convergence.\n        //\n        norm_A = sqrt(norm_bb);\n        // cond_A   = norm_A * sqrt(norm_dd);\n        norm_r   = phibar;\n        norm_Atr = phibar * alpha * abs(cs);\n        //\n        // Stop iteration if\n        //\n        // |A^{T} \\bm{r}|_{F} / |A^{T}|_F |\\bm{r}| < tol\n        //\n        // if (norm_Atr <= norm_A * norm_r * tol_error)\n        // {\n        //     break;\n        // }\n        if (norm_r <= btol * norm_b + atol * norm_A * norm_x)\n        {\n            break;\n        }\n    }\n\n    tol_error  = norm_r;\n    iterations = iter;\n}\n\n} // namespace expsum\n\n#endif /* EXPSUM_LSQR_HPP */\n", "meta": {"hexsha": "3e42c82a1591653d47997f5c0b54e016b97ac426", "size": 6414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/lsqr.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/fitting/lsqr.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/fitting/lsqr.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": 31.9104477612, "max_line_length": 80, "alphanum_fraction": 0.5219831618, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6789170972368549}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n    const decfloat ln_two = boost::math::constants::ln_two<decfloat>();\n    decfloat numerator = 1, denominator = ln_two;\n\n    for(int n = 1; n <= 17; n++) {\n        decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n        decfloat tenths_dig = floor((h - floor(h)) * 10);\n        std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h <<\n            (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n    }\n}\n", "meta": {"hexsha": "23a4a0b2955b84855fbc586652352b268b51df68", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/hickerson-series-of-almost-integers.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": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/hickerson-series-of-almost-integers.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++/hickerson-series-of-almost-integers.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": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 36.5263157895, "max_line_length": 97, "alphanum_fraction": 0.5936599424, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6788781674454225}}
{"text": "/**\n * @file uniformcubicspline.cc\n * @brief NPDE exam problem summer 2019 \"CLEmpiricFlux\" code\n * @author Oliver Rietmann\n * @date 18.07.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"uniformcubicspline.h\"\n\n#include <Eigen/Core>\n#include <cassert>\n\nnamespace {\n\ntemplate <typename T>\nconstexpr T Square(T x) {\n  return x * x;\n}\n\ntemplate <typename T>\nconstexpr T Cube(T x) {\n  return x * x * x;\n}\n\nconstexpr int getJ(double a, double b, unsigned int n, double u) {\n  return u < b ? (int)(n * ((u - a) / (b - a)) + 1.0) : n;\n}\n\nconstexpr double zeta(double a, double b, unsigned int n, double j) {\n  return a + j * (b - a) / n;\n}\n\n}  // namespace\n\nnamespace CLEmpiricFlux {\n\nUniformCubicSpline::UniformCubicSpline(double a, double b, Eigen::VectorXd f,\n                                       Eigen::VectorXd M)\n    : _n(f.size() - 1), _a(a), _b(b), _f(std::move(f)), _M(std::move(M)) {\n  assert(b >= a);\n  assert(_f.size() >= 2);\n  assert(_f.size() == _M.size());\n}\n\ndouble UniformCubicSpline::operator()(double u) const {\n  assert((u >= _a) && (u <= _b));\n  int j = getJ(_a, _b, _n, u);\n  double h = (_b - _a) / _n;\n  double tau = (u - zeta(_a, _b, _n, j - 1)) / h;\n\n  return _f(j) * tau + _f(j - 1) * (1.0 - tau) +\n         Square(h) / 6.0 *\n             (_M(j) * (Cube(tau) - tau) +\n              _M(j - 1) * (-Cube(tau) + 3.0 * Square(tau) - 2.0 * tau));\n}\n\ndouble UniformCubicSpline::derivative(double u) const {\n  assert((u >= _a) && (u <= _b));\n  int j = getJ(_a, _b, _n, u);\n  double h = (_b - _a) / _n;\n  double tau = (u - zeta(_a, _b, _n, j - 1)) / h;\n\n  return (_f(j) - _f(j - 1) +\n          Square(h) / 6.0 *\n              (_M(j) * (3.0 * Square(tau) - 1.0) +\n               _M(j - 1) * (-3.0 * Square(tau) + 6.0 * tau - 2.0))) *\n         (1.0 / h);\n}\n\n}  // namespace CLEmpiricFlux\n", "meta": {"hexsha": "14648973ae547b4d92c24e2708a116db92de1e32", "size": 1806, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.0833333333, "max_line_length": 77, "alphanum_fraction": 0.5348837209, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6788733129438796}}
{"text": "/*\n\tThe code below is a test case for a compressive sensing reconstruction algorithm applied to a single image from the MNIST dataset.\n\tEigen template library is used for easier matrix handling. URL: http://eigen.tuxfamily.org/index.php?title=Main_Page\n\t\t\t\t\t\t\t\t... for some examples see: eigen_testing.cpp\n\tWritten by: Karlo Sever\n*/\n\n//#include \"images_training_set.h\"\t\t// MNIST dataset\n//#include \"labels_training_set.h\"\n\n#include <iostream>\n#include \"test_img.h\"\t\t\t\t\t// Digit: 0\n#include \"eig_vect_matrix.h\"\t\t\t// Eigenvectors taken from the '0' dictionary\n#include \"measurement_matrix.h\"\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n#define DIM 784\n\n\n//Test image of digit '0' is of dimensions X_test[784,1] stored in X_test_img[784]\n//Measurement matrix is of dimensions phi[78,784] stored in phi_vect[78*784]\n//Measured signal y = phi*X_test is of dimensions [78,1]\n\nint main(void) {\n\tVectorXd X_test(DIM);\n\tfor (int i = 0; i < DIM; i++)\n\t\tX_test(i) = X_test_img[i];\n\n\tMatrixXd phi(78, DIM);\n\tint indx = 0;\n\tfor (int i = 0; i < 78; i++) {\n\t\tfor (int j = 0; j < DIM; j++) {\n\t\t\tphi(i, j) = phi_vect[indx++];\n\t\t\tprintf(\"%.6f\", phi(i, j));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tMatrixXd v0(DIM, DIM);\n\tindx = 0;\n\tfor (int i = 0; i < DIM; i++) {\n\t\tfor (int j = 0; j < DIM; j++) {\n\t\t\tv0(i, j) = eigv[indx++];\n\t\t}\n\t}\n\n\tfor (int i = 0; i < DIM; i++) {\n\t\tprintf(\"%6.2f\", X_test[i]);\n\t\tif (i % 28 == 0)\n\t\t\tprintf(\"\\n\");\n\t}\n\tstd::cout << \"\\nMeasured signal y... \\n\" << phi * X_test << std::endl;\n\n\t//MatrixXd A(DIM, DIM), B(DIM, 78);\n\t//A = v0.transpose()*phi.transpose()*phi*v0;\n\t//B = v0.transpose()*phi.transpose();\n\t//alpha_rec = A.inverse()*B*(phi*X_test);\n\n\tVectorXd alpha_rec(DIM), X_rec(DIM), recon(DIM);\n\tX_rec = phi.transpose()*(phi*X_test);\n\talpha_rec = v0.transpose()*X_rec;\t\t\t\t\t// Reconstruction coefficients\n\n\n\trecon = v0 * alpha_rec;\t\t\t\t\t\t\t\t// Reconstructed data\n\tstd::cout << \"\\n\\nReconstructed data...\\n\" << std::endl;\n\tfor (int i = 0; i < DIM; i++) {\n\t\tprintf(\"%6.2f \", recon[i]);\n\t\tif (i % 28 == 0) {\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "48d115e7934cef5eb47fe063b326f8f216eb0be7", "size": 2043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project/compressive_sensing_zedboard/src/main.cc", "max_stars_repo_name": "ispanja/Zedboard_compressive_sensing", "max_stars_repo_head_hexsha": "cf9e80fbc465d60ae4561c8b018ae7bd3cb0d7c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T12:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T12:39:42.000Z", "max_issues_repo_path": "project/compressive_sensing_zedboard/src/main.cc", "max_issues_repo_name": "ispanja/Zedboard_compressive_sensing", "max_issues_repo_head_hexsha": "cf9e80fbc465d60ae4561c8b018ae7bd3cb0d7c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/compressive_sensing_zedboard/src/main.cc", "max_forks_repo_name": "ispanja/Zedboard_compressive_sensing", "max_forks_repo_head_hexsha": "cf9e80fbc465d60ae4561c8b018ae7bd3cb0d7c4", "max_forks_repo_licenses": ["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.1923076923, "max_line_length": 131, "alphanum_fraction": 0.6211453744, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436483, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6787676277595731}}
{"text": "#include <Rcpp.h>\n\n//[[Rcpp::depends(RcppEigen)]]\n#include <RcppEigen.h>\n\n//[[Rcpp::depends(BH)]]\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"logLikelihoods.hpp\"\n#include \"AuxiliaryFunctions.hpp\"\n\ndouble logPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion)\n{\n    double eta = dispersion;\n    if (!(dispersion > 0))\n    {\n        eta = 2e-16;\n    }\n\n    const double logProbability = boost::math::lgamma(x + eta) - boost::math::lgamma(eta) -\n        boost::math::lgamma(x + 1) + x * (std::log(mean) - std::log(mean + eta)) + eta * (std::log(eta) -\n        std::log(mean + eta));\n\n    return logProbability;\n}\n\ndouble logInflatedTruncatedPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion,\n                                                    const double & p, const double & inflation, const double & truncation)\n{\n    const double logTruncatedProbability = (logPoissonGammaDistribution(x, mean, dispersion) -\n        std::log(1.0 - std::exp(dispersion * (std::log(dispersion) - std::log(mean + dispersion)))));\n\n    double logProbability;\n    if (x == inflation)\n    {\n        logProbability = std::log(p + std::exp(std::log(1.0 - p) + logTruncatedProbability));\n    }\n    else\n    {\n        logProbability = std::log(1.0 - p) + logTruncatedProbability;\n    }\n\n    return logProbability;\n}\n\n//[[Rcpp::export(.devianceResidualPoissonGammaDistribution)]]\ndouble devianceResidualPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion)\n{\n\t// if (std::abs(x - mean) < 2e-8)\n\t// {\n\t// \treturn 0.0;\n\t// }\n\n\tdouble eta = dispersion;\n\tif (!(dispersion > 0))\n\t{\n\t    eta = 2e-16;\n\t}\n\n\tdouble deviance_ma = (x + eta) * (std::log(mean + eta) - std::log(x + eta));\n    if (x > 0)\n    {\n        deviance_ma += x * (std::log(x) - std::log(mean));\n    }\n\n    return boost::math::sign(x - mean) * std::pow(2.0 * deviance_ma, 0.5);\n}\n\ndouble devianceResidualPG1(const double & x, const double & mean, const double & dispersion)\n{\n    double eta = dispersion;\n    if (!(dispersion > 0))\n    {\n        eta = 2e-16;\n    }\n\n    double deviance_ma = (x - mean) * std::log(eta + 1) / eta -\n        boost::math::lgamma((eta * x + mean) / eta) +\n        boost::math::lgamma(x * (eta + 1) / eta);\n\n    if (x > 0)\n    {\n        deviance_ma += boost::math::lgamma(x / eta) - boost::math::lgamma(mean / eta);\n    }\n\n    return boost::math::sign(x - mean) * std::pow(2.0 * deviance_ma, 0.5);\n}\n\n\ndouble logMultinomialCoefficient(const int & totalCounts, const Eigen::VectorXd & counts)\n{\n    std::size_t N = counts.size();\n\n    double logGammaCounts = 0;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        logGammaCounts += lgamma(counts[n] + 1);\n    }\n    return lgamma(totalCounts + 1) - logGammaCounts;\n}\n\ndouble logDirichletMultinomial(const Eigen::VectorXd & counts, const Eigen::VectorXd & alleleFrequencies)\n{\n    std::size_t N = alleleFrequencies.size();\n    int sumCounts = counts.sum();\n\n    double groupSum = 0.0;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        groupSum += counts[n] * std::log(alleleFrequencies[n]);\n\n    }\n\n    double resLogDirichletMultinomial = logMultinomialCoefficient(sumCounts, counts) + groupSum;\n    return resLogDirichletMultinomial;\n}\n\ndouble logDirichletMultinomialTheta(const Eigen::VectorXd & counts, const double & theta, const Eigen::VectorXd & alleleFrequencies)\n{\n    std::size_t N = alleleFrequencies.size();\n    int sumCounts = counts.sum();\n\n    double groupSum = 0.0;\n    double gamma_plus = 1/theta - 1;\n    for (std::size_t n = 0; n < N; n++)\n    {\n        double gamma_j = gamma_plus * alleleFrequencies[n];\n        groupSum += lgamma(counts[n] + gamma_j) - lgamma(gamma_j);\n    }\n\n    groupSum += (lgamma(gamma_plus) - lgamma(sumCounts + gamma_plus));\n\n    double resLogDirichletMultinomial = logMultinomialCoefficient(sumCounts, counts) + groupSum;\n    return resLogDirichletMultinomial;\n}\n\nEigen::VectorXd logLikelihoodAlleleCoverage(const Eigen::VectorXd & coverage, const std::vector<Eigen::MatrixXd> & expectedContributionMatrix,\n                                            const std::vector<Eigen::VectorXd> & alleleIndex, const Eigen::VectorXd partialSumAlleles,\n                                            const Eigen::VectorXd & sampleParameters, const Eigen::VectorXd & mixtureProportions,\n                                            const Eigen::VectorXd & markerImbalances)\n{\n    const std::size_t & M = alleleIndex.size();\n\n    const double & referenceMarkerAverage = sampleParameters[0];\n    const double & dispersion = sampleParameters[1];\n\n    Eigen::VectorXd logLikelihood = Eigen::VectorXd::Zero(M);\n    for (std::size_t m = 0; m < M; m++)\n    {\n        const Eigen::VectorXd & alleleIndex_m = alleleIndex[m];\n        const Eigen::MatrixXd & expectedContributionMatrix_m = expectedContributionMatrix[m];\n        const Eigen::VectorXd & expectedContribution = expectedContributionMatrix_m * mixtureProportions;\n\n        double logLikelihood_m = 0.0;\n        for (std::size_t a = 0; a < alleleIndex_m.size(); a++)\n        {\n            const std::size_t & n = partialSumAlleles[m] + alleleIndex_m[a];\n\n            double mu_ma = referenceMarkerAverage * markerImbalances[m] * expectedContribution[a];\n            if (expectedContribution[a] > 0)\n            {\n                logLikelihood_m += logPoissonGammaDistribution(coverage[n], mu_ma, mu_ma / dispersion);\n            }\n        }\n\n        logLikelihood[m] = logLikelihood_m;\n    }\n\n    return logLikelihood;\n}\n\nEigen::VectorXd logLikelihoodNoiseCoverage(const Eigen::VectorXd & coverage, const std::vector<Eigen::VectorXd> & noiseIndex,\n                                           const Eigen::VectorXd & partialSumAlleles,\n                                           const double & noiseLevel, const double & noiseDispersion, const double & p)\n{\n    const std::size_t & M = noiseIndex.size();\n\n    Eigen::VectorXd logLikelihood = Eigen::VectorXd::Zero(M);\n    for (std::size_t m = 0; m < M; m++)\n    {\n        const Eigen::VectorXd & noiseIndex_m = noiseIndex[m];\n        for (std::size_t a = 0; a < noiseIndex_m.size(); a++)\n        {\n            const std::size_t & n = partialSumAlleles[m] + noiseIndex_m[a];\n            logLikelihood[m] += logInflatedTruncatedPoissonGammaDistribution(coverage[n], noiseLevel, noiseDispersion, p, 1.0, 0.0);\n        }\n    }\n\n    return logLikelihood;\n}\n\n\nEigen::VectorXd logGenotypeProbabilityHWE(const Eigen::VectorXd & alleleFrequencies, const Eigen::MatrixXd & unknownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n    Eigen::VectorXd partialNumberOfAlleles = partialSumEigen(numberOfAlleles);\n\n    Eigen::VectorXd logPriorProbability = Eigen::VectorXd::Zero(numberOfMarkers);\n    for (std::size_t m = 0; m < numberOfMarkers; m++)\n    {\n        Eigen::MatrixXd profiles_m = unknownProfiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], unknownProfiles.cols());\n\n        Eigen::VectorXd profileCounts_m = profiles_m.rowwise().sum();\n        Eigen::VectorXd alleleFractions_m = alleleFrequencies.segment(partialNumberOfAlleles[m], numberOfAlleles[m]);\n\n        logPriorProbability[m] = logDirichletMultinomial(profileCounts_m, alleleFractions_m);\n    }\n\n    return logPriorProbability;\n}\n\n\nEigen::VectorXd logGenotypeProbabilityThetaCorrection(const Eigen::VectorXd & alleleFrequencies, const double & theta, const Eigen::MatrixXd & unknownProfiles, const Eigen::MatrixXd & knownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n    Eigen::MatrixXd profiles = bindColumns(knownProfiles, unknownProfiles);\n    std::size_t numberOfContributors = profiles.cols();\n    std::size_t numberOfKnownContributors = numberOfContributors - unknownProfiles.cols();\n\n    Eigen::VectorXd partialNumberOfAlleles = partialSumEigen(numberOfAlleles);\n    Eigen::VectorXd thetaCorrectedProbabilty = Eigen::VectorXd::Zero(numberOfMarkers);\n    for (std::size_t m = 0; m < numberOfMarkers; m++)\n    {\n        Eigen::MatrixXd profiles_m = profiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], numberOfContributors);\n\n        Eigen::VectorXd profileCounts = profiles_m.rowwise().sum();\n        Eigen::VectorXd alleleFractions_m = alleleFrequencies.segment(partialNumberOfAlleles[m], numberOfAlleles[m]);\n\n        double logProbabilityOfUnknownProfiles = logDirichletMultinomialTheta(profileCounts, theta, alleleFractions_m);\n        double logProbabilty_m = logProbabilityOfUnknownProfiles;\n\n        if (numberOfKnownContributors != 0)\n        {\n            Eigen::MatrixXd knownProfiles_m = knownProfiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], numberOfKnownContributors);\n\n            Eigen::VectorXd knownCounts = knownProfiles_m.rowwise().sum();\n\n            double logProbabilityOfKnownProfiles = logDirichletMultinomialTheta(knownCounts, theta, alleleFractions_m);\n            logProbabilty_m -= logProbabilityOfKnownProfiles;\n        }\n\n        thetaCorrectedProbabilty[m] = logProbabilty_m;\n    }\n\n    return thetaCorrectedProbabilty;\n}\n\nEigen::VectorXd logPriorGenotypeProbability(const Eigen::VectorXd & alleleFrequencies, const double & theta, const Eigen::MatrixXd & unknownProfiles, const Eigen::MatrixXd & knownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n    Eigen::VectorXd logPriorProbability;\n    if (theta == 0.0)\n    {\n        logPriorProbability = logGenotypeProbabilityHWE(alleleFrequencies, unknownProfiles, numberOfMarkers, numberOfAlleles);\n    }\n    else\n    {\n        logPriorProbability = logGenotypeProbabilityThetaCorrection(alleleFrequencies, theta, unknownProfiles, knownProfiles, numberOfMarkers, numberOfAlleles);\n    }\n\n    return logPriorProbability;\n}\n", "meta": {"hexsha": "f7c2d9f9e37ba39777de0ef0b5a6ddfa4141ebf6", "size": 9857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/logLikelihoods.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "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/logLikelihoods.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "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/logLikelihoods.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["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.7662835249, "max_line_length": 276, "alphanum_fraction": 0.6681546109, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.678767626157239}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"logs.h\"\n#include \"route.h\"\n#include \"track.h\"\n\n// The design structure of my test suite is to test every possible option for the direction of routes, for example:\n// - a route where the elevation increases\n// - a route where the elevation decreases\n// - a route where the elevation is stationary\n// - a route where the elevation increases and then decreases\n// - a route where the elevation decreases and then increases\n// - a route where there is only one point meaning an invalid argument should be thrown\n// - a route where the elevation does not change through oyt the route which lead to a flat surface route\n\n//how the check value hasve been worked out:\n// in a three dimension where the longitude and latitude are the vertical axies and the elevation is the horizontal axie\n// by using pythagoras rule a^2 = b^2 + c^2\n// where ( a ) is the gradient\n//       ( b ) is the difference between the elevation of two point\n//       ( c ) is the  distent between two point using the Law of haversines using the horizantal axies\n// the gardient will be zero if the (b) is equal to zero\n\n\n\nusing namespace GPS;\n\nBOOST_AUTO_TEST_SUITE( Route_MinGradient_n0719479 )\n\nconst bool isFileName = true;\n\n// uphill route AGM:\n// M is Pontianak with Position(0,109.322134,0) the vertical, horizontal units for this grid is 10 and 120000\n// as the route increases, the smallest gradient should be the smallest positive value between them\nBOOST_AUTO_TEST_CASE( uphill_route )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"going_up_a_hill_route_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), 169625, 0.1);\n}\n\n// downhill route MSY:\n// M is citycampus with Position(52.9581383,-1.1542364,53) the vertical, horizontal units for this grid is 10 and 120000\n// as the route decreases, the smallest gradient should be the biggest negative value between them\nBOOST_AUTO_TEST_CASE( downhill_route )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"going_down_a_hill_route_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -172816, 0.1 );\n}\n\n// uphill then downhill route AGMX:\n// M is citycampus with Position(52.9581383,-1.1542364,53) the vertical, horizontal units for this grid is 10 and 120000\n// as the route increases then decreases, the smallest gradient should be the biggest negative value between them\nBOOST_AUTO_TEST_CASE( up_down_hill_route )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"going_up_down_hill_route_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -269700, 0.1);\n}\n\n// downhill then uphill route MDI:\n// M is Pontianak with Position(0,109.322134,0) the vertical, horizontal units for this grid is 10 and 120000\n// as the route decreases then increases, the smallest gradient should be the biggest negative value between them\nBOOST_AUTO_TEST_CASE( down_up_hill_route )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"going_down_up_hill_route_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_CLOSE( route.minGradient(), -268,376, 0.1 );\n}\n\n// route containing only 1 point:\n// as there is only one point and the gradient cannot be calculated, an invalid arugment should be thrown\nBOOST_AUTO_TEST_CASE( one_point_location )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"one_point_location_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_THROW( route.minGradient() , std::invalid_argument );\n}\n\n//flat route LQRS:\n// M is Pontianak with Position(0,109.322134,0) the vertical, horizontal units for this grid is 10 and 120000\n// as the route is flat, the gradient should be zero\nBOOST_AUTO_TEST_CASE( flat_surface_route )\n{\n   Route route = Route(LogFiles::GPXRoutesDir + \"flat_route_n0719479\"+\".gpx\", isFileName);\n   BOOST_CHECK_EQUAL( route.minGradient(), 0 );\n}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e8115efdc2933854ac64e018bc28fccd6c3e7ba1", "size": 3829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx-tests/mingradient_n0719479.cpp", "max_stars_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_stars_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": "src/gpx-tests/mingradient_n0719479.cpp", "max_issues_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_issues_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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/gpx-tests/mingradient_n0719479.cpp", "max_forks_repo_name": "EdwinLangley/GPX-Route-and-Track", "max_forks_repo_head_hexsha": "e4de303c62c7e9dc92724e8f257f7960ff77c992", "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": 45.0470588235, "max_line_length": 120, "alphanum_fraction": 0.7612953774, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.678760205631241}}
{"text": "//####### Test module for chi functions #############################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/chi_functions\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <picsar_qed/physics/chi_functions.hpp>\n\n#include <picsar_qed/physics/unit_conversion.hpp>\n#include <picsar_qed/math/vec_functions.hpp>\n\nusing namespace picsar::multi_physics::phys;\nusing namespace picsar::multi_physics::math;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-12;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-6;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n\nconst double me_c = electron_mass<double> * light_speed<double>;\nconst double lambda = 800.0e-9;\nconst double omega = 2.0*pi<double>*light_speed<double>/lambda;\nconst double eref = 2.0*pi<double>*electron_mass<double>*\n    light_speed<double>*light_speed<double>/(lambda*elementary_charge<double>);\nconst double bref = eref/light_speed<double>;\n\n// ------------- Tests --------------\n\n//***Test chi calculation for photons\n\ntemplate<typename RealType, unit_system UnitSystem>\nvoid test_chi_photons(\n    vec3<double> t_p, vec3<double> t_em_e, vec3<double> t_em_b,\n    double t_exp_res, double t_ref_quant = 1.0)\n{\n    const auto p =  vec3<RealType>{\n        static_cast<RealType>(t_p[0]),\n        static_cast<RealType>(t_p[1]),\n        static_cast<RealType>(t_p[2])}*\n        conv<quantity::momentum, unit_system::SI, UnitSystem, RealType>::fact();\n\n    const auto em_e =  vec3<RealType>{\n        static_cast<RealType>(t_em_e[0]),\n        static_cast<RealType>(t_em_e[1]),\n        static_cast<RealType>(t_em_e[2])}*\n        conv<quantity::E, unit_system::SI, UnitSystem, RealType>::fact(1.0, t_ref_quant);\n\n    const auto em_b =  vec3<RealType>{\n        static_cast<RealType>(t_em_b[0]),\n        static_cast<RealType>(t_em_b[1]),\n        static_cast<RealType>(t_em_b[2])}*\n        conv<quantity::B, unit_system::SI, UnitSystem, RealType>::fact(1.0, t_ref_quant);\n\n    const auto res = chi_photon<RealType, UnitSystem>(p, em_e, em_b, t_ref_quant);\n\n    const auto exp_res = static_cast<RealType>(t_exp_res);\n\n    if(exp_res != static_cast<RealType>(0.0))\n        BOOST_CHECK_SMALL((res-exp_res)/exp_res, tolerance<RealType>());\n    else\n        BOOST_CHECK_SMALL(res, tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_1 )\n{\n    const double px = 83.759*me_c;\n    const double py = 139.311*me_c;\n    const double pz = -230.553*me_c;\n    const double ex = -166.145*eref;\n    const double ey = -78.231*eref;\n    const double ez = -278.856*eref;\n    const double bx = -279.174*bref;\n    const double by = -158.849*bref;\n    const double bz = -93.826*bref;\n\n    const double chi_exp = 0.3471118445206898;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_2 )\n{\n    const double px = 9.2627*me_c;\n    const double py = -25.4575*me_c;\n    const double pz = -10.2246*me_c;\n    const double ex = 2.9271*eref;\n    const double ey = 10.4293*eref;\n    const double ez = 3.6103*eref;\n    const double bx = 1.7439*bref;\n    const double by = 1.9778*bref;\n    const double bz = 17.8799*bref;\n\n    const double chi_exp = 0.0009041474058668584;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_3 )\n{\n    const double px = -2314.45*me_c;\n    const double py = -2356.30*me_c;\n    const double pz = 546.28*me_c;\n    const double ex = 1230.11*eref;\n    const double ey = 1638.02*eref;\n    const double ez = -2911.04*eref;\n    const double bx = -2203.66*bref;\n    const double by = 1243.79*bref;\n    const double bz = -2830.99*bref;\n\n    const double chi_exp = 57.22043983047014;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_4 )\n{\n    const double px = 0*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n    const double ex = 1230.11*eref;\n    const double ey = 1638.02*eref;\n    const double ez = -2911.04*eref;\n    const double bx = -2203.66*bref;\n    const double by = 1243.79*bref;\n    const double bz = -2830.99*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_5 )\n{\n    const double px = -2314.45*me_c;\n    const double py = -2356.30*me_c;\n    const double pz = 546.28*me_c;\n    const double ex = 0.0*eref;\n    const double ey = 0.0*eref;\n    const double ez = 0.0*eref;\n    const double bx = 0.0*bref;\n    const double by = 0.0*bref;\n    const double bz = 0.0*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_photons_6 )\n{\n    const double px = -2314.45*me_c;\n    const double py = 0.0*me_c;\n    const double pz = 0.0*me_c;\n    const double ex = 1230.11*eref;\n    const double ey = 0.0*eref;\n    const double ez = 0.0*eref;\n    const double bx = 0.0*bref;\n    const double by = 0.0*bref;\n    const double bz = 0.0*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_photons<double, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_photons<float, unit_system::SI>(p, em_e, em_b, chi_exp);\n    test_chi_photons<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_photons<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_photons<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\n//*******************************\n\n//***Test chi calculation for electrons and positrons\n\ntemplate<typename RealType, unit_system UnitSystem>\nvoid test_chi_ele_pos(\n    vec3<double> t_p, vec3<double> t_em_e, vec3<double> t_em_b,\n    double t_exp_res, double t_ref_quant = 1.0)\n{\n    const auto p =  vec3<RealType>{\n        static_cast<RealType>(t_p[0]),\n        static_cast<RealType>(t_p[1]),\n        static_cast<RealType>(t_p[2])}*\n        conv<quantity::momentum, unit_system::SI, UnitSystem, RealType>::fact();\n\n    const auto em_e =  vec3<RealType>{\n        static_cast<RealType>(t_em_e[0]),\n        static_cast<RealType>(t_em_e[1]),\n        static_cast<RealType>(t_em_e[2])}*\n        conv<quantity::E, unit_system::SI, UnitSystem, RealType>::fact(1.0, t_ref_quant);\n\n    const auto em_b =  vec3<RealType>{\n        static_cast<RealType>(t_em_b[0]),\n        static_cast<RealType>(t_em_b[1]),\n        static_cast<RealType>(t_em_b[2])}*\n        conv<quantity::B, unit_system::SI, UnitSystem, RealType>::fact(1.0, t_ref_quant);\n\n    const auto res = chi_ele_pos<RealType, UnitSystem>(p, em_e, em_b, t_ref_quant);\n\n    const auto exp_res = static_cast<RealType>(t_exp_res);\n\n    if(exp_res != static_cast<RealType>(0.0))\n        BOOST_CHECK_SMALL((res-exp_res)/exp_res, tolerance<RealType>());\n    else\n        BOOST_CHECK_SMALL(res, tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_1 )\n{\n    const double px = 24.3752*me_c;\n    const double py = -11.5710*me_c;\n    const double pz = -10.0841*me_c;\n    const double ex = 57.185*eref;\n    const double ey = -16.6555*eref;\n    const double ez = 22.4340*eref;\n    const double bx = 6.6911*bref;\n    const double by = -23.8724*bref;\n    const double bz = 13.9934*bref;\n\n    const double chi_exp = 0.002167166273468506;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_2 )\n{\n    const double px = 4.015*me_c;\n    const double py = 197.287*me_c;\n    const double pz = 141.705*me_c;\n    const double ex = 30.287*eref;\n    const double ey = 115.740*eref;\n    const double ez = 120.891*eref;\n    const double bx = -190.161*bref;\n    const double by = -129.115*bref;\n    const double bz = -57.002*bref;\n\n    const double  chi_exp = 0.16631811297207244;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_3 )\n{\n    const double px = -2534.83*me_c;\n    const double py = 1011.54*me_c;\n    const double pz = -793.04*me_c;\n    const double ex = 741.67*eref;\n    const double ey = -2359.97*eref;\n    const double ez = 1463.50*eref;\n    const double bx = 1477.19*bref;\n    const double by = -1448.33*bref;\n    const double bz = 1953.68*bref;\n\n    const double chi_exp = 16.011457274095676;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_4 )\n{\n    const double px = 0*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n    const double ex = 741.67*eref;\n    const double ey = -2359.97*eref;\n    const double ez = 1463.50*eref;\n    const double bx = 1477.19*bref;\n    const double by = -1448.33*bref;\n    const double bz = 1953.68*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_5 )\n{\n    const double px = -2534.83*me_c;\n    const double py = 1011.54*me_c;\n    const double pz = -793.04*me_c;\n    const double ex = 0*eref;\n    const double ey = 0*eref;\n    const double ez = 0*eref;\n    const double bx = 0*bref;\n    const double by = 0*bref;\n    const double bz = 0*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\nBOOST_AUTO_TEST_CASE( chi_ele_pos_6 )\n{\n    const double px = -2534.83*me_c;\n    const double py = 0*me_c;\n    const double pz = 0*me_c;\n    const double ex = 0*eref;\n    const double ey = 0*eref;\n    const double ez = 0*eref;\n    const double bx = 1477.19*bref;\n    const double by = 0*bref;\n    const double bz = 0*bref;\n\n    const double chi_exp = 0.0;\n\n    const auto p = vec3<double>{px,py,pz};\n    const auto em_e = vec3<double>{ex,ey,ez};\n    const auto em_b = vec3<double>{bx,by,bz};\n\n    test_chi_ele_pos<double, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<double, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<double, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<double, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::SI>(p, em_e, em_b, chi_exp, 1.0);\n    test_chi_ele_pos<float, unit_system::norm_lambda>(p, em_e, em_b, chi_exp, lambda);\n    test_chi_ele_pos<float, unit_system::norm_omega>(p, em_e, em_b, chi_exp, omega);\n    test_chi_ele_pos<float, unit_system::heaviside_lorentz>(p, em_e, em_b, chi_exp, 1.0);\n}\n\n//*******************************\n", "meta": {"hexsha": "3a0722eceb8249028ac410d2234ae5a5e5101373", "size": 18459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_physics/QED/QED_tests/test_picsar_chi_functions.cpp", "max_stars_repo_name": "ax3l/picsar", "max_stars_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T17:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:20:30.000Z", "max_issues_repo_path": "multi_physics/QED/QED_tests/test_picsar_chi_functions.cpp", "max_issues_repo_name": "ax3l/picsar", "max_issues_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:55:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T17:00:36.000Z", "max_forks_repo_path": "multi_physics/QED/QED_tests/test_picsar_chi_functions.cpp", "max_forks_repo_name": "ax3l/picsar", "max_forks_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T13:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:51:38.000Z", "avg_line_length": 40.6585903084, "max_line_length": 90, "alphanum_fraction": 0.6887155317, "num_tokens": 6007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.678665392192147}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <fstream>\n#include <iostream>\n#include <map>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel         K;\ntypedef K::Point_2                                                  Point;\n\ntypedef CGAL::Delaunay_triangulation_2<K>                           Triangulation;\n\ntypedef boost::graph_traits<Triangulation>::vertex_descriptor       vertex_descriptor;\ntypedef boost::graph_traits<Triangulation>::vertex_iterator         vertex_iterator;\ntypedef boost::graph_traits<Triangulation>::edge_descriptor         edge_descriptor;\n\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map<vertex_descriptor,int>                             VertexIndexMap;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map<VertexIndexMap>             VertexIdPropertyMap;\n\nint main(int argc,char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/points.xy\";\n  std::ifstream input(filename);\n  Triangulation tr;\n\n  Point p;\n  while(input >> p)\n    tr.insert(p);\n\n  // Associate indices to the vertices\n  VertexIndexMap vertex_id_map;\n  VertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n  int index = 0;\n\n  for(vertex_descriptor vd : vertices(tr))\n    vertex_id_map[vd] = index++;\n\n  // We use the default edge weight which is the squared length of the edge\n  // This property map is defined in graph_traits_Triangulation_2.h\n\n  // In the function call you can see a named parameter: vertex_index_map\n  std::list<edge_descriptor> mst;\n  boost::kruskal_minimum_spanning_tree(tr, std::back_inserter(mst),\n                                       vertex_index_map(vertex_index_pmap));\n\n  std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n  for(edge_descriptor ed : mst)\n  {\n    vertex_descriptor svd = source(ed, tr);\n    vertex_descriptor tvd = target(ed, tr);\n    Triangulation::Vertex_handle sv = svd;\n    Triangulation::Vertex_handle tv = tvd;\n    std::cout << \"[ \" << sv->point() << \"  |  \" << tv->point() << \" ] \" << std::endl;\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4de38c2adef5a9e759c915b5294d6a23a23d4dc4", "size": 2348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_triangulation_2/emst.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": "BGL/examples/BGL_triangulation_2/emst.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": "BGL/examples/BGL_triangulation_2/emst.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.5757575758, "max_line_length": 88, "alphanum_fraction": 0.6920783646, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6786578421570519}}
{"text": "// Copyright (c) by respective owners including Yahoo!, Microsoft, and\n// individual contributors. All rights reserved. Released under a BSD (revised)\n// license as described in the file LICENSE.\n\n#include \"test_common.h\"\n#include \"vw/core/vw_math.h\"\n\n#include <boost/test/test_tools.hpp>\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(math_factorial_tests)\n{\n  BOOST_CHECK_EQUAL(VW::math::factorial(0), 1);\n  BOOST_CHECK_EQUAL(VW::math::factorial(1), 1);\n  BOOST_CHECK_EQUAL(VW::math::factorial(2), 2);\n  BOOST_CHECK_EQUAL(VW::math::factorial(3), 6);\n  BOOST_CHECK_EQUAL(VW::math::factorial(4), 24);\n  BOOST_CHECK_EQUAL(VW::math::factorial(5), 120);\n  BOOST_CHECK_EQUAL(VW::math::factorial(10), 3628800);\n}\n\nBOOST_AUTO_TEST_CASE(math_number_of_combinations_with_repetition_tests)\n{\n  BOOST_CHECK_EQUAL(VW::math::number_of_combinations_with_repetition(1, 1), 1);\n  BOOST_CHECK_EQUAL(VW::math::number_of_combinations_with_repetition(5, 1), 5);\n  BOOST_CHECK_EQUAL(VW::math::number_of_combinations_with_repetition(1, 5), 1);\n  BOOST_CHECK_EQUAL(VW::math::number_of_combinations_with_repetition(5, 5), 126);\n  BOOST_CHECK_EQUAL(VW::math::number_of_combinations_with_repetition(10, 2), 55);\n}\n\nBOOST_AUTO_TEST_CASE(math_number_of_permutations_with_repetition_tests)\n{\n  BOOST_CHECK_EQUAL(VW::math::number_of_permutations_with_repetition(1, 1), 1);\n  BOOST_CHECK_EQUAL(VW::math::number_of_permutations_with_repetition(5, 1), 5);\n  BOOST_CHECK_EQUAL(VW::math::number_of_permutations_with_repetition(1, 5), 1);\n  BOOST_CHECK_EQUAL(VW::math::number_of_permutations_with_repetition(5, 5), 3125);\n  BOOST_CHECK_EQUAL(VW::math::number_of_permutations_with_repetition(10, 2), 100);\n}\n\nBOOST_AUTO_TEST_CASE(math_sign_tests)\n{\n  BOOST_CHECK_CLOSE(VW::math::sign(1.f), 1.f, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::math::sign(-1.f), -1.f, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::math::sign(0.f), -1.f, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::math::sign(0.1f), 1.f, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::math::sign(1000.f), 1.f, FLOAT_TOL);\n  BOOST_CHECK_CLOSE(VW::math::sign(-999.f), -1.f, FLOAT_TOL);\n}\n\nBOOST_AUTO_TEST_CASE(math_choose_tests)\n{\n  BOOST_CHECK_EQUAL(VW::math::choose(1, 1), 1);\n  BOOST_CHECK_EQUAL(VW::math::choose(4, 2), 6);\n  BOOST_CHECK_EQUAL(VW::math::choose(2, 4), 0);\n  BOOST_CHECK_EQUAL(VW::math::choose(0, 0), 1);\n  BOOST_CHECK_EQUAL(VW::math::choose(0, 1), 0);\n  BOOST_CHECK_EQUAL(VW::math::choose(1, 0), 1);\n}", "meta": {"hexsha": "b89e8b920d3f1289769bcaf6b4f37378181472d3", "size": 2417, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/unit_test/math_test.cc", "max_stars_repo_name": "HollowMan6/vowpal_wabbit", "max_stars_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4332.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:26:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-01T14:05:43.000Z", "max_issues_repo_path": "test/unit_test/math_test.cc", "max_issues_repo_name": "HollowMan6/vowpal_wabbit", "max_issues_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1004.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T12:00:54.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-30T22:13:42.000Z", "max_forks_repo_path": "test/unit_test/math_test.cc", "max_forks_repo_name": "HollowMan6/vowpal_wabbit", "max_forks_repo_head_hexsha": "eecdaccce568b53ed195bc4d50a6a582ab9a83d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1182.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T20:38:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T02:47:37.000Z", "avg_line_length": 41.6724137931, "max_line_length": 82, "alphanum_fraction": 0.7587918908, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6786578186337356}}
{"text": "#include <boost/dynamic_bitset.hpp>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n/**\n * Generate all prime numbers up to a limit\n * @param limit test for primality up to this limit, not including the limit\n * @return the prime numbers\n */\nstd::vector<unsigned long> getPrimes( unsigned long limit )\n{\n  std::vector<unsigned long> primes;\n  \n  // special cases\n  if ( limit <= 5 )\n  {\n    if ( limit > 2 )\n    {\n      primes.push_back( 2 );\n      if ( limit > 3 )\n      {\n\tprimes.push_back( 3 );\n      }\n    }      \n    return primes;\n  }\n  \n  // multiples of 2 and 3 will not be used, just add them by hand\n  primes.push_back( 2 );\n  primes.push_back( 3 );\n  \n  // crossed out nonprimes\n  boost::dynamic_bitset<> crossOut( limit );\n  \n  // add primes to result and cross out nonprimes\n  unsigned long crossOutLimit = static_cast<unsigned long>( sqrt( limit ) ) + 1;\n  unsigned long i = 5;\n  for ( ; i < crossOutLimit; i += 6 )\n  {\n    for ( unsigned long d = 0; d != 4; d += 2 )\n    {\n      unsigned long num = i + d;\n      if ( !crossOut.test( num ) )\n      {\n\tprimes.push_back( num );\n\tfor ( unsigned long j = num * num; j < limit; j += num )\n\t{\n\t  crossOut.set( j );\n\t}\n      }\n    }\n  }\n  \n  // add extra primes to result \n  for ( ; i < limit - 2; i += 6 )\n  {\n    for ( unsigned long d = 0; d != 4; d += 2 )\n    {\n      unsigned long num = i + d;\n      if ( !crossOut.test( num ) )\n      {\n\tprimes.push_back( num );\n      }\n    }\n  }\n  \n  // one may be missing\n  if ( i < limit && !crossOut.test( i ) )\n  {\n    primes.push_back( i );\n  }\n  \n  return primes;\n}\n\nint main()\n{\n  unsigned long limit = 10000000;\n  std::vector<unsigned long> primes = getPrimes( limit );\n  std::cout << \"Trere are \" << primes.size() << \" primes below \" << limit << \".\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "62c629e679535a00c8d61ec45a1e5289bc3e21ac", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_stars_repo_name": "tdiprima/code", "max_stars_repo_head_hexsha": "61a74f5f93da087d27c70b2efe779ac6bd2a3b4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2023.0, "max_stars_repo_stars_event_min_datetime": "2017-07-29T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:00:45.000Z", "max_issues_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_issues_repo_name": "unhacker/code", "max_issues_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-09-02T17:20:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:49:37.000Z", "max_forks_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_forks_repo_name": "unhacker/code", "max_forks_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 780.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T19:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:39:41.000Z", "avg_line_length": 21.3214285714, "max_line_length": 94, "alphanum_fraction": 0.5633724176, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6786537755437008}}
{"text": "#include <bits/stdc++.h>\n\n// Rational number\n// Positive/negative infinity can be allowed.\ntemplate <typename T, bool allow_infinity = false>\nstruct Rational {\n public:\n  // #include <boost/multiprecision/cpp_int.hpp>\n  // using multip = boost::multiprecision;\n  // using BigInt = boost::multiprecision::checked_int128_t;\n  using BigInt = __int128_t;\n\n  T nume, deno;\n\n  Rational() : nume(0), deno(1) {}\n\n  Rational(T n) : nume(n), deno(1) {}\n\n  Rational(BigInt n, BigInt d) {\n    if constexpr (allow_infinity) {\n      assert(d != 0 or n != 0);  // 0/0 is undefined\n    } else {\n      assert(d != 0);\n    }\n    if (allow_infinity and d == 0) {\n      n = (n < 0) ? -1 : 1;  // infinity\n    } else if (n == 0) {\n      d = 1;\n    } else {\n      const int sign = ((n < 0) xor (d < 0)) ? -1 : 1;\n      if (n < 0) n = -n;\n      if (d < 0) d = -d;\n      const auto g = gcd_(n, d);\n      if (g > 1) {\n        n /= g;\n        d /= g;\n      }\n      n *= sign;\n    }\n    nume = static_cast<T>(n);\n    deno = static_cast<T>(d);\n  }\n\n  Rational(const Rational &x) = default;\n  Rational(Rational &&x) = default;\n  Rational &operator=(const Rational &x) = default;\n  Rational &operator=(Rational &&x) = default;\n\n  // Cast to a floating point number.\n  template <typename Float>\n  explicit operator Float() const {\n    static_assert(std::is_floating_point<Float>::value);\n    return (Float)nume / (Float)deno;\n  }\n\n  Rational operator+() const { return *this; }\n  Rational operator-() const {\n    Rational ret;\n    ret.nume = -nume;\n    ret.deno = deno;\n    return ret;\n  }\n\n  friend bool operator==(const Rational &x, const Rational &y) {\n    return (x.nume == y.nume) and (x.deno == y.deno);\n  }\n  friend bool operator!=(const Rational &x, const Rational &y) {\n    return not(x == y);\n  }\n  friend bool operator<(const Rational &x, const Rational &y) {\n    if constexpr (allow_infinity) {\n      if (x.deno == 0 and y.deno == 0) return x.nume < y.nume;\n    }\n    return static_cast<BigInt>(x.nume) * y.deno <\n           static_cast<BigInt>(y.nume) * x.deno;\n  }\n  friend bool operator>(const Rational &x, const Rational &y) { return y < x; }\n  friend bool operator<=(const Rational &x, const Rational &y) {\n    return not(x > y);\n  }\n  friend bool operator>=(const Rational &x, const Rational &y) {\n    return not(x < y);\n  }\n\n  friend Rational operator+(const Rational &x, const Rational &y) {\n    if constexpr (allow_infinity) {\n      if (x.deno == 0 and y.deno == 0) {\n        assert(x.nume == y.nume);  // (infinity - infinity) is undefined\n        return x;\n      }\n      if (x.deno == 0) return x;\n      if (y.deno == 0) return y;\n    }\n    auto g = gcd_(x.deno, y.deno);\n    BigInt xd = x.deno / g;\n    BigInt yd = y.deno / g;\n    BigInt zn = x.nume * yd + y.nume * xd;\n    BigInt zd = xd * y.deno;\n    return Rational(std::move(zn), std::move(zd));\n  }\n  Rational &operator+=(const Rational &x) { return (*this = *this + x); }\n\n  friend Rational operator-(const Rational &x, const Rational &y) {\n    return x + (-y);\n  }\n  Rational &operator-=(const Rational &x) { return (*this = *this - x); }\n\n  friend Rational operator*(const Rational &x, const Rational &y) {\n    if (x.nume == 0 or y.nume == 0) return Rational(0);\n    auto g1 = gcd_(abs_(x.nume), y.deno);\n    auto g2 = gcd_(abs_(y.nume), x.deno);\n    return Rational(BigInt(x.nume / g1) * BigInt(y.nume / g2),\n                    BigInt(x.deno / g2) * BigInt(y.deno / g1));\n  }\n  Rational &operator*=(const Rational &x) { return (*this = *this * x); }\n\n  Rational inv() const { return Rational(deno, nume); }\n\n  friend Rational operator/(const Rational &x, const Rational &y) {\n    return x * y.inv();\n  }\n  Rational &operator/=(const Rational &x) { return (*this = *this / x); }\n\n  friend std::ostream &operator<<(std::ostream &os, const Rational &x) {\n    return os << x.nume << \"/\" << x.deno;\n  }\n\n private:\n  template <typename U>\n  static inline U abs_(const U &x) {\n    // return std::abs(x);\n    // return boost::multiprecision::abs(x);\n    return (x < 0) ? -x : x;\n  }\n  template <typename U>\n  static U gcd_(const U &a, const U &b) {\n    // return std::gcd(a, b);\n    return (b == 0) ? a : gcd_(b, a % b);\n  }\n};\nusing Rat = Rational<long long, false>;\n// using Rat = Rational<multip::checked_int128_t>; // for testing overflow\n\n// Parse a decimal number into a rational.\n// (e.g. \"0.2029\" => 2029/10000 )\nstd::istream &operator>>(std::istream &is, Rat &x) {\n  long long nume = 0, deno = 1;\n  char ch;\n  while (is.get(ch)) {\n    if (not std::isspace(ch)) break;\n  }\n  int sgn = 1;\n  if (ch == '-') {\n    sgn = -1;\n    is.get(ch);\n  }\n  bool in_frac = false;\n  while (true) {\n    if (not std::isdigit(ch)) {\n      is.unget();\n      break;\n    }\n    nume = (nume * 10) + int(ch - '0');\n    if (in_frac) deno *= 10;\n    if (not(is.get(ch))) break;\n    if (ch == '.') {\n      in_frac = true;\n      if (not(is.get(ch))) break;\n    }\n  }\n  x = Rat(nume * sgn, deno);\n  return is;\n}\n", "meta": {"hexsha": "ddf08ffc4abf4a9031ba93f020e8b9d914f19e95", "size": 4936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rational.hpp", "max_stars_repo_name": "keijak/hikidashi-cpp", "max_stars_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "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/rational.hpp", "max_issues_repo_name": "keijak/hikidashi-cpp", "max_issues_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "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/rational.hpp", "max_forks_repo_name": "keijak/hikidashi-cpp", "max_forks_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "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.367816092, "max_line_length": 79, "alphanum_fraction": 0.5709076175, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.6786537590500902}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n#include <set>\n#include <string>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n\nusing namespace std;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;\ntypedef boost::graph_traits<graph>::vertex_descriptor                       vertex_desc;\n\nbool perfect_matching(const graph &G) {\n  int n = boost::num_vertices(G);\n  vector<vertex_desc> mate_map(n);  // exterior property map\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\n  return 2 * matching_size == n;\n}\n\nvoid solve() {\n  \n  int n; cin >> n;\n  int c; cin >> c;\n  unsigned int f; cin >> f;\n  \n  graph G(n);\n\n  string x;\n  vector<set<string>> ch(n, set<string>());\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < c; ++j) {\n      cin >> x;\n      ch[i].insert(x);\n    }\n  }\n  \n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < i; ++j) {\n        vector<string> intersection;\n        set_intersection(ch[i].begin(), ch[i].end(), ch[j].begin(), ch[j].end(), back_inserter(intersection));\n        if (intersection.size() > f) {\n            boost::add_edge(i, j, G);\n        }\n    }\n  }\n\n  cout << (perfect_matching(G) ? \"not optimal\" : \"optimal\") << endl;\n}\n\nint main()\n{\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n  return 0;\n}", "meta": {"hexsha": "99cd476bd9e6984d85280c981887ec69ffd26793", "size": 1643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/buddy_selection.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/buddy_selection.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "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/buddy_selection.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 24.5223880597, "max_line_length": 110, "alphanum_fraction": 0.6098600122, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6786537590500901}}
{"text": "/** @file mvn_cdf.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief\n * \n */\n#include \"PriorHessian/mvn_cdf.h\"\n\n#include <cmath>\n#include <limits>\n\n#include <armadillo>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace {\n    const double sqrt2 = sqrt(2.);\n    const double inv_sqrt2 = 1./sqrt2;\n    const double inv_2pi = 1./(2.*arma::datum::pi);\n}\n\nnamespace prior_hessian {\n\n\n/** area of the lower tail of the unit normal curve below t. */\ndouble unit_normal_cdf( double t )\n{\n    if(t==-INFINITY) return 0;\n    if(t==INFINITY) return 1;\n    return std::max(std::min(.5*std::erfc(-t*::inv_sqrt2),1.0),0.0);\n}\n\ndouble unit_normal_icdf( double u )\n{\n    if(u<=0) return -INFINITY;\n    if(u>=1) return INFINITY;\n    return -::sqrt2*boost::math::erfc_inv(2*u);\n}\n\ndouble bounded(double x)\n{\n    return std::min(std::max(x,0.),1.);\n}\n\n/* Integrates the between y(x)=0 and y(x) = a*x, and right of h, to infinity\n * \n * when h=0 this is the triangle from the x-axis with angle arctan(a)\n * h - location of vertical line to integrate to the right from\n * a - slope of line above the x-axis\n * gh - normcdf(h);\n */\ndouble owen_t_integral(double h, double a, double gh)\n{\n    //Check pre-conditions\n    if(std::isnan(h)) throw ParameterValueError(\"a is NaN\");\n    if(!(gh >=0 && gh<=1)) throw ParameterValueError(\"gh is not in [0,1]\");\n    //Edge cases\n    if(h == INFINITY) return 0;\n    if(std::isnan(a)) throw ParameterValueError(\"a is NaN\");\n    if(a == 0) return 0;\n    if(h == 0) return std::atan(a)*::inv_2pi;\n    if(a == INFINITY) return  (h>0) ? .5*(1-gh) : .5*gh;\n    if(a==1) return .5*gh*(1-gh); //This formula works for h and -h by symmetry\n    //Use owens 2.4 and 2.5 to handle negative h and a\n    if(a<0 && h<0) return -owen_t_integral(-h,-a,1-gh);\n    if(a<0) return -owen_t_integral(h,-a,gh);\n    if(h<0) return owen_t_integral(-h,a,1-gh);\n    \n    assert(h>0 && std::isfinite(h));\n    assert(a>0 && std::isfinite(a));\n    //Use Owens 2.3 to invert a if >1.  This requires an additional normcdf call.\n    if(a>1) {\n        double ah = a*h;\n        double gah = unit_normal_cdf(ah);\n        double v1 = owen_t_integral(ah,1/a,gah);\n        return .5*(gh+gah) -gh*gah - v1;\n    }\n    \n    assert(a>0 && a<1);\n    \n    const int max_iter = 1000;\n    const double eps = 1E-10;\n    double theta = std::atan(a);\n    double asq = a*a;\n    double asq_powj = asq;\n    double h2 = h*h/2;\n    double e2h = std::exp(-h2);\n    if(e2h==0) return 0;\n    double Qj = 1;\n    double Sj = Qj;\n    double s = 1 - e2h; //First term of series.\n    for(int j=1; j<max_iter; j++) {\n        Qj *= h2/j;\n        Sj += Qj;\n        double sign = (j%2==0) ? 1 : -1;\n        double v = sign/(2*j+1) * (1-e2h*Sj) * asq_powj;\n        s += v;\n        if(fabs(v/s) < eps) return ::inv_2pi*(theta - a*s);\n        asq_powj *= asq;\n    }\n    std::ostringstream msg;\n    msg<<\"Power series failed to converge in max_iter=\"<<max_iter<<\" iterations. h=\"<<h<<\" a=\"<<a<<\" sum=\"<<s;\n    throw RuntimeConvergenceError(msg.str());\n}\n\ndouble owen_b_integral(double h,double k, double r)\n{\n    if(std::isnan(h)) throw ParameterValueError(\"h is NaN\");\n    if(std::isnan(k)) throw ParameterValueError(\"k is NaN\");\n    if(fabs(r)>1 || !std::isfinite(r)) throw ParameterValueError(\"r is not in interval [-1,1]\");\n    \n    if(h==-INFINITY || k==-INFINITY) return 0;\n    if(h==INFINITY && k==INFINITY) return 1;\n    if(fabs(r)==1) { //Degenerate case.\n        if(r>0) return unit_normal_cdf(std::min(h,k));\n        else return unit_normal_cdf(h) - unit_normal_cdf(-k);\n    }\n    assert(fabs(r)<1);\n    double sigma = sqrt(1-r*r);\n    double gh = unit_normal_cdf(h);\n    double ah = (k-r*h)/(h*sigma);\n    double bint;\n    if(h==k) {\n        if(h==0.) return .25+asin(r)*::inv_2pi;\n        bint = gh - 2*owen_t_integral(h,ah,gh);\n    } else if(h==-k) { \n        bint = .5 - 2*owen_t_integral(h,ah,gh);\n    } else {\n        double gk = unit_normal_cdf(k);\n        double ak = (h-r*k)/(k*sigma);\n        double t1 = owen_t_integral(h,ah,gh);\n        double t2 = owen_t_integral(k,ak,gk);\n        bint = .5*(gh+gk) - t1 - t2;\n    }\n    if( h*k < 0 || (h*k == 0 && (h<0 || k<0))) bint -= .5;\n    return std::min(std::max(bint,0.0),1.0);\n}\n\n\n\n\n/** compute the bivariate normal cdf integral\n * computes the probability for two normal variates X and Y\n *    whose correlation is R, that AH <= X and AK <= Y.\n * \n * Adapted to modern C++ with efficiency improvements by:\n * Mark Olah (mjo@cs.unm DOT edu)\n * 10/2018\n * \n * Reference:\n *    Thomas Donnelly,\n *    Algorithm 462: Bivariate Normal Distribution,\n *    Communications of the ACM,\n *    October 1973, Volume 16, Number 10, page 638.\n */    \ndouble donnelly_bvn_integral( double ah, double ak, double r )\n{\n    static double eps = 1.0E-15;\n    if (r<-1 || r>1) throw ParameterValueError(\"must have -1<=rho<=1\");\n    if ((ah==INFINITY) || (ak==INFINITY)) return 0;\n    if ((ah==-INFINITY) && (ak==-INFINITY)) return 1;\n    \n    double gh = unit_normal_cdf(-ah)/2.0;\n    double gk = unit_normal_cdf(-ak)/2.0;\n\n    if(r == 0.0) return bounded(4*gh*gk);\n\n    double b = 0.0; //return value\n    double rr = (1+r)*(1-r);\n    if(rr==0) { //Degenerate cases r=-1 r=0 r=1\n        if(r<0) {\n            if(ah+ak<0) b = 2*(gh+gk)-1;\n        } else {\n            if(ah-ak<0) b = 2*gk;\n            else b = 2*gh;\n        }\n        return bounded(b);\n    }\n\n    double sigma_inv = 1./sqrt(rr);\n    double con = arma::datum::pi * eps;\n    double wh;\n    double wk;\n    double gw;\n    int is;\n    if(ah == 0) {\n        if(ak == 0) return bounded(0.25+asin(r)*::inv_2pi); // (0,0)\n        //(0, !0)\n        b = gk;\n        wh = -ak;\n        wk = (ah/ak - r)*sigma_inv;\n        gw = 2*gk;\n        is = 1;\n    } else {\n        //  (!0, 0)\n        b = gh;             \n        wh = -ah;\n        wk = (ak/ah - r)*sigma_inv;\n        gw = 2*gh;\n        is = -1;\n        if(ak != 0) { // ( !0, !0)\n            b = gh+gk;\n            if (ah*ak < 0) b-= 0.5;\n        }\n    }\n//     std::cout<<\"NEW ah:\"<<ah<<\" ak:\"<<ak<<\" rho:\"<<r<<\" gh:\"<<gh<<\" gk:\"<<gk<<\"\\n\";\n//     std::cout<<\"NEW b:\"<<b<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n    for ( ; ; ) {\n        double sgn = -1.0;\n        double t = 0.0;\n//         std::cout<<\"n b:\"<<b<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n        if(wk != 0) {\n            if(fabs(wk) == 1) {\n                t = .5*wk*gw*(1-gw);\n                b += sgn*t;\n            } else {\n                if (fabs(wk) > 1) {\n                    sgn = -sgn;\n                    wh *= wk;\n                    double g2 = unit_normal_cdf(wh);\n                    wk = 1./wk;\n                    if(wk < 0) b += 0.5;\n                    b += -.5*(gw+g2) + gw*g2;\n//                     std::cout<<\"nn b: \"<<b<<\" gw:\"<<gw<<\" g2:\"<<g2<<\" t:\"<<t<<\" sgn:\"<<sgn<<\" wh:\"<<wh<<\" wk:\"<<wk<<\"\\n\";\n                }\n                double h2 = wh*wh;\n                double a2 = wk*wk;\n                double h4 = .5*h2;\n                double ex = exp(-h4);\n                double w2 = h4*ex;\n                double ap = 1.0;\n                double s2 = ap - ex;\n                double sp = ap;\n                double s1 = 0.0;\n                double sn = s1;\n                double conex = fabs(con/wk);\n\n                for ( ; ; ) {\n                    double cn = ap*s2/(sn+sp);\n                    s1 += cn;\n//                     std::cout<<\"NEW cn: \"<<cn<<\" s1:\"<<s1<<\" conex:\"<<conex<<\" sn:\"<<sn<<\" sp:\"<<sp<<\" s2:\"<<s2<<\" w2\"<<w2<<\" ap:\"<<ap<<\"\\n\";\n\n                    if(fabs(cn) <= conex) break;\n\n                    sn = sp;\n                    sp += 1.0;\n                    s2 -= w2;\n                    w2 *= h4/sp;\n                    ap *= -a2;\n                }\n                t = (atan(wk) - wk*s1) * ::inv_2pi;\n                b += sgn*t;\n            }\n        }\n        //Check for convergence\n//         std::cout<<\"N b:\"<<b<<\" is:\"<<is<<\" ak:\"<<ak<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n        if(0 <= is || ak == 0) return bounded(b);\n        wh = -ak;\n        wk = (ah/ak - r)*sigma_inv;\n        gw = 2*gk;\n        is = 1;\n    }\n    //never get here\n}\n\ndouble donnelly_bvn_integral_orig( double ah, double ak, double r )\n{\n    using std::max;\n    using std::min;\n    using std::fabs;\n  double a2;\n  double ap;\n  double b;\n  double cn;\n  double con;\n  double conex;\n  double ex;\n  double g2;\n  double gh;\n  double gk;\n  double gw;\n  double h2;\n  double h4;\n  int i;\n  static int idig = 15;\n  int is;\n  double rr;\n  double s1;\n  double s2;\n  double sgn;\n  double sn;\n  double sp;\n  double sqr;\n  double t;\n  static double twopi = 6.283185307179587;\n  double w2;\n  double wh;\n  double wk;\n\n  b = 0.0;\n\n  gh = unit_normal_cdf ( - ah ) / 2.0;\n  gk = unit_normal_cdf ( - ak ) / 2.0;\n\n  if ( r == 0.0 )\n  {\n    b = 4.00 * gh * gk;\n    b = max ( b, 0.0 );\n    b = min ( b, 1.0 );\n    return b;\n  }\n\n  rr = ( 1.0 + r ) * ( 1.0 - r );\n\n  if ( rr < 0.0 )\n  {\n    return -1;\n  }\n\n  if ( rr == 0.0 )\n  {\n    if ( r < 0.0 )\n    {\n      if ( ah + ak < 0.0 )\n      {\n        b = 2.0 * ( gh + gk ) - 1.0;\n      }\n    }\n    else\n    {\n      if ( ah - ak < 0.0 )\n      {\n        b = 2.0 * gk;\n      }\n      else\n      {\n        b = 2.0 * gh;\n      }\n    }\n    b = max ( b, 0.0 );\n    b = min ( b, 1.0 );\n    return b;\n  }\n\n  sqr = sqrt ( rr );\n\n  if ( idig == 15 )\n  {\n    con = twopi * 1.0E-15 / 2.0;\n  }\n  else\n  {\n    con = twopi / 2.0;\n    for ( i = 1; i <= idig; i++ )\n    {\n      con = con / 10.0;\n    }\n  }\n//\n//  (0,0)\n//\n  if ( ah == 0.0 && ak == 0.0 )\n  {\n    b = 0.25 + asin ( r ) / twopi;\n    b = max ( b, 0.0 );\n    b = min ( b, 1.0 );\n    return b;\n  }\n//\n//  (0,nonzero)\n//\n  else if ( ah == 0.0 && ak != 0.0 )\n  {\n    b = gk;\n    wh = -ak;\n    wk = ( ah / ak - r ) / sqr;\n    gw = 2.0 * gk;\n    is = 1;\n  }\n//\n//  (nonzero,0)\n//\n  else if ( ah != 0.0 && ak == 0.0 )\n  {\n    b = gh;\n    wh = -ah;\n    wk = ( ak / ah - r ) / sqr;\n    gw = 2.0 * gh;\n    is = -1;\n  }\n//\n//  (nonzero,nonzero)\n//\n  else\n  {\n    b = gh + gk;\n    if ( ah * ak < 0.0 )\n    {\n      b = b - 0.5;\n    }\n    wh = - ah;\n    wk = ( ak / ah - r ) / sqr;\n    gw = 2.0 * gh;\n    is = -1;\n  }\n//     std::cout<<\"OLD ah:\"<<ah<<\" ak:\"<<ak<<\" rho:\"<<r<<\" gh:\"<<gh<<\" gk:\"<<gk<<\"\\n\";\n//     std::cout<<\"OLD b:\"<<b<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n  for ( ; ; )\n  {\n    sgn = -1.0;\n    t = 0.0;\n//      std::cout<<\"O b:\"<<b<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n\n    if ( wk != 0.0 )\n    {\n      if ( fabs ( wk ) == 1.0 )\n      {\n        t = wk * gw * ( 1.0 - gw ) / 2.0;\n        b = b + sgn * t;\n      }\n      else\n      {\n        if ( 1.0 < fabs ( wk ) )\n        {\n          sgn = -sgn;\n          wh = wh * wk;\n          g2 = unit_normal_cdf ( wh );\n          wk = 1.0 / wk;\n\n          if ( wk < 0.0 )\n          {\n            b = b + 0.5;\n          }\n          b = b - ( gw + g2 ) / 2.0 + gw * g2;\n//             std::cout<<\"oo b: \"<<b<<\" gw:\"<<gw<<\" g2:\"<<g2<<\" t:\"<<t<<\" sgn:\"<<sgn<<\" wh:\"<<wh<<\" wk:\"<<wk<<\"\\n\";\n\n        }\n        h2 = wh * wh;\n        a2 = wk * wk;\n        h4 = h2 / 2.0;\n        ex = exp ( - h4 );\n        w2 = h4 * ex;\n        ap = 1.0;\n        s2 = ap - ex;\n        sp = ap;\n        s1 = 0.0;\n        sn = s1;\n        conex = fabs ( con / wk );\n\n        for ( ; ; )\n        {\n          cn = ap * s2 / ( sn + sp );\n          s1 = s1 + cn;\n//           std::cout<<\"OLD cn: \"<<cn<<\" s1:\"<<s1<<\" conex:\"<<conex<<\" sn:\"<<sn<<\" sp:\"<<sp<<\" s2:\"<<s2<<\" w2\"<<w2<<\" ap:\"<<ap<<\"\\n\";\n          if ( fabs ( cn ) <= conex )\n          {\n            break;\n          }\n          sn = sp;\n          sp = sp + 1.0;\n          s2 = s2 - w2;\n          w2 = w2 * h4 / sp;\n          ap = - ap * a2;\n        }\n        t = ( atan ( wk ) - wk * s1 ) / twopi;\n        b = b + sgn * t;\n      }\n    }\n//     std::cout<<\"0 b:\"<<b<<\" is:\"<<is<<\" ak:\"<<ak<<\" wh:\"<<wh<<\" wk:\"<<wk<<\" gw:\"<<gw<<\" is:\"<<is<<\"\\n\";\n        \n    if ( 0 <= is )\n    {\n      break;\n    }\n    if ( ak == 0.0 )\n    {\n      break;\n    }\n    wh = -ak;\n    wk = ( ah / ak - r ) / sqr;\n    gw = 2.0 * gk;\n    is = 1;\n  }\n\n  b = max ( b, 0.0 );\n  b = min ( b, 1.0 );\n\n  return b;\n}\n\n\n\n} /* namespace prior_hessian */\n", "meta": {"hexsha": "36bd54052b66c5a3afa172c28956eab63a114413", "size": 12231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mvn_cdf.cpp", "max_stars_repo_name": "markjolah/PriorHessianLib", "max_stars_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T07:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T07:40:29.000Z", "max_issues_repo_path": "src/mvn_cdf.cpp", "max_issues_repo_name": "markjolah/PriorHessianLib", "max_issues_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "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/mvn_cdf.cpp", "max_forks_repo_name": "markjolah/PriorHessianLib", "max_forks_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "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.6592741935, "max_line_length": 144, "alphanum_fraction": 0.43749489, "num_tokens": 4246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6786537568374407}}
{"text": "// Compile with:\n// clang++ -o demoGaussianMixtureClusterer5D demoGaussianMixtureClusterer5D.cpp -L../build/ -I ../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register\n//\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Core>\n#include \"File.h\"\n#include \"EuclideanMetric.h\"\n#include \"GaussianMixtureClusterer.h\"\n#include \"PrincipalComponentProjector.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint main()\n{\n    // Open the input file and read the data (synthetic sampling of a 5D parameter space)\n    \n    ifstream inputFile;\n    File::openInputFile(inputFile, \"kmeans_testsample5D.txt\");\n    \n    unsigned long Nrows;\n    int Ncols;\n\n    File::sniffFile(inputFile, Nrows, Ncols);\n    ArrayXXd data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\n    ArrayXXd sample = data.transpose();\n    inputFile.close();\n\n    \n    // Set up the K-means clusterer using a Euclidean metric\n\n    EuclideanMetric myMetric;\n    int minNclusters = 2;\n    int maxNclusters = 15;\n    int Ntrials = 20;\n    double relTolerance = 1.e-3;\n\n    bool printNdimensions = true;\n    PrincipalComponentProjector projector(printNdimensions);\n    bool featureProjectionActivated = false;\n    \n\n    GaussianMixtureClusterer gaussianMixtureClusterer(myMetric, projector, featureProjectionActivated, \n                                                      minNclusters, maxNclusters, Ntrials, relTolerance); \n\n \n    // Do the clustering, and get for each point the index of the cluster it belongs to\n\n    int optimalNclusters;\n    vector<int> clusterIndices(Nrows);\n    vector<int> clusterSizes;\n\n    optimalNclusters = gaussianMixtureClusterer.cluster(sample, clusterIndices, clusterSizes);\n    \n   \n    // Output the results \n    \n    cerr << \"Input number of clusters: 4\" << endl; \n    cerr << \"Optimal number of clusters: \" << optimalNclusters << endl << endl;\n    \n    ArrayXXd finalSample(Nrows,Ncols+1);\n    finalSample.block(0,0,Nrows,Ncols) = data;\n    \n    for (int n = 0; n < Nrows; ++n)\n    {\n        finalSample(n,Ncols) = clusterIndices[n];\n    }\n\n    ofstream outputFile;\n    File::openOutputFile(outputFile, \"clusterMembershipFromGMM5D.txt\");\n    outputFile << scientific << setprecision(4);\n    File::arrayXXdToFile(outputFile, finalSample);\n    outputFile.close();\n\n\n\n    // That's it!\n \n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9050cc37bb42d98dc51b5a46e9fc5c37ed032994", "size": 2369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demoGaussianMixtureClusterer5D.cpp", "max_stars_repo_name": "vishalbelsare/DIAMONDS", "max_stars_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/demoGaussianMixtureClusterer5D.cpp", "max_issues_repo_name": "vishalbelsare/DIAMONDS", "max_issues_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/demoGaussianMixtureClusterer5D.cpp", "max_forks_repo_name": "vishalbelsare/DIAMONDS", "max_forks_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_forks_repo_licenses": ["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.5465116279, "max_line_length": 169, "alphanum_fraction": 0.6834107218, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6785963605202981}}
{"text": "#include <Eigen/Dense>\n\n#include <chrono>\n#include <memory>\n#include <random>\n#include <vector>\n\n\n#include \"MatrixUtils.h\"\n\nvoid MatrixUtils::initializeRandomWeights(Eigen::MatrixXd& matrix,\n    const bool randomSeed) {\n\n    unsigned seed = 0;\n    if (randomSeed) {\n        seed = std::chrono::system_clock::now().time_since_epoch().count();\n    }\n\n    std::default_random_engine generator(seed);\n    std::normal_distribution<double> distribution(0.0, 1.0);\n\n    for (int i=0; i < matrix.cols(); ++i) {\n        for (int j=0; j < matrix.rows(); ++j) {\n            matrix(j, i) = distribution(generator);\n        }\n    }\n}\n", "meta": {"hexsha": "09d2cbdcfe5ee01b6a952f1da03da1f9500c6877", "size": 621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/MatrixUtils.cpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/MatrixUtils.cpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/core/MatrixUtils.cpp", "max_forks_repo_name": "samueljackson92/cynapse", "max_forks_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1785714286, "max_line_length": 75, "alphanum_fraction": 0.6247987118, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6785637253763858}}
{"text": "//#include <cmath>\n#include <iostream>\n#include <boost/math/special_functions/legendre.hpp>\n\n#include \"gauss_quad.hpp\"\n\nnamespace DGHydro {\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n// Constructor\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nGaussQuad::GaussQuad(int n) : n(n)\n{\n  if (n <= 0)\n    throw std::runtime_error(\"Can not create Gaussian Quadrature with a number of point that is not positive\");\n\n  FindAbscissae();\n  FindWeights();\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n// Destructor\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nGaussQuad::~GaussQuad()\n{\n  delete[] x;\n  delete[] w;\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid GaussQuad::FindAbscissae()\n{\n  if (x == nullptr) x = new double[n];\n\n  double dx = 2.0/(double) n;\n  double tol = 1.0e-12;\n\n  for (int i = 0; i < n; i++) {\n    // Divide up interval: each contains a single zero\n    double a = -1.0 + i*dx;\n    double b = -1.0 + (i + 1)*dx;\n\n    // Find zero by bisection\n    while (1) {\n      double c = 0.5*(a + b);\n\n      double f = boost::math::legendre_p(n, c);\n\n      if (f == 0.0 || 0.5*(b - a) < tol) {\n        x[i] = c;\n        break;\n      }\n\n      if (sgn(f) == sgn(boost::math::legendre_p(n, a))) {\n        a = c;\n      } else {\n        b = c;\n      }\n    }\n\n  }\n\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid GaussQuad::FindWeights()\n{\n  if (w == nullptr) w = new double[n];\n\n  for (int i = 0; i < n; i++) {\n    // Derivative of Legendre polynomial\n    double p_prime = n*(x[i]*boost::math::legendre_p(n, x[i]) -\n                        boost::math::legendre_p(n - 1, x[i]))/(x[i]*x[i]-1.0);\n    // Gaussian weight\n    w[i] = 2.0/(1 - x[i]*x[i])/p_prime/p_prime;\n  }\n}\n\n}\n", "meta": {"hexsha": "ac880b9f480081939a0c474f8e5de5b2b51a0dd7", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gauss_quad/gauss_quad.cpp", "max_stars_repo_name": "SijmeJan/DGHydro", "max_stars_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_stars_repo_licenses": ["MIT"], "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/gauss_quad/gauss_quad.cpp", "max_issues_repo_name": "SijmeJan/DGHydro", "max_issues_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_issues_repo_licenses": ["MIT"], "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/gauss_quad/gauss_quad.cpp", "max_forks_repo_name": "SijmeJan/DGHydro", "max_forks_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_forks_repo_licenses": ["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.2727272727, "max_line_length": 111, "alphanum_fraction": 0.3725585938, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6785637090905255}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3d v = Matrix3d::Random();\ncout << \"The matrix v is:\" << endl;\ncout << v << endl;\n\nVector3d v0(1, v(1,0), v(2,0));\ncout << \"The first Householder vector is: v_0 = \" << v0.transpose() << endl;\nVector3d v1(0, 1, v(2,1));\ncout << \"The second Householder vector is: v_1 = \" << v1.transpose()  << endl;\nVector3d v2(0, 0, 1);\ncout << \"The third Householder vector is: v_2 = \" << v2.transpose() << endl;\n\nVector3d h = Vector3d::Random();\ncout << \"The Householder coefficients are: h = \" << h.transpose() << endl;\n\nMatrix3d H0 = Matrix3d::Identity() - h(0) * v0 * v0.adjoint();\ncout << \"The first Householder reflection is represented by H_0 = \" << endl;\ncout << H0 << endl;\nMatrix3d H1 = Matrix3d::Identity() - h(1) * v1 * v1.adjoint();\ncout << \"The second Householder reflection is represented by H_1 = \" << endl;\ncout << H1 << endl;\nMatrix3d H2 = Matrix3d::Identity() - h(2) * v2 * v2.adjoint();\ncout << \"The third Householder reflection is represented by H_2 = \" << endl;\ncout << H2 << endl;\ncout << \"Their product is H_0 H_1 H_2 = \" << endl;\ncout << H0 * H1 * H2 << endl;\n\nHouseholderSequence<Matrix3d, Vector3d> hhSeq(v, h);\nMatrix3d hhSeqAsMatrix(hhSeq);\ncout << \"If we construct a HouseholderSequence from v and h\" << endl;\ncout << \"and convert it to a matrix, we get:\" << endl;\ncout << hhSeqAsMatrix << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "f653ca7da4143c3ea35345064e37d195fc7b806f", "size": 1467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HouseholderSequence_HouseholderSequence.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_HouseholderSequence_HouseholderSequence.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_HouseholderSequence_HouseholderSequence.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": 33.3409090909, "max_line_length": 78, "alphanum_fraction": 0.6475800954, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.678563706646538}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Vector3d v(-1,2,-3);\ncout << \"the absolute values:\" << endl << v.array().abs() << endl;\ncout << \"the absolute values plus one:\" << endl << v.array().abs()+1 << endl;\ncout << \"sum of the squares: \" << v.array().square().sum() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "cd12add24ee58467fae09192b91cc5f0df921545", "size": 385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array_const.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_MatrixBase_array_const.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_MatrixBase_array_const.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": 22.6470588235, "max_line_length": 77, "alphanum_fraction": 0.6155844156, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6785614919238384}}
{"text": "//\n// $Id: MatrixInverse.hpp 4146 2012-11-26 23:46:34Z pcbrefugee $\n//\n//\n// NB: Variations of this file appear in many open source projects,\n// with no copyright claims or license statements made in any of them.  \n// Assumed to be public domain, or at least as open as the boost license,\n// since the farthest back we can seem to trace it is the Boost Wiki at\n// http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Effective_UBLAS/Matrix_Inversion\n//\n\n#ifndef _MATRIXINVERSE_HPP_\n#define _MATRIXINVERSE_HPP_\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\nnamespace toppic {\n\nnamespace matrix_inverse {\n\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\nbool InvertMatrix(const boost::numeric::ublas::matrix<double>& input, \n                  boost::numeric::ublas::matrix<double>& inverse)\n{\n\n    using namespace boost::numeric::ublas;\n    typedef permutation_matrix<std::size_t> pmatrix;\n\n    // create a working copy of the input\n    matrix<double> A(input);\n    // create a permutation matrix for the LU-factorization\n    pmatrix pm(A.size1());\n\n    // perform LU-factorization\n    int res = lu_factorize(A,pm);\n    if( res != 0 ) return false;\n\n    // create identity matrix of \"inverse\"\n    inverse = identity_matrix<double>(A.size1());\n\n    // backsubstitute to get the inverse\n    lu_substitute(A, pm, inverse);\n\n    return true;\n}\n\n\n/**\n* Invert a matrix via gauss-jordan algorithm (PARTIAL PIVOT)\n*\n* @param m The matrix to invert. Must be square.\n* @param singular If the matrix was found to be singular, then this\n*        is set to true, else set to false.\n* @return If singular is false, then the inverted matrix is returned.\n*         Otherwise it contains random values.\n*/\n\n//#define T double /// for debug\nboost::numeric::ublas::matrix<double>\ngjinverse(const boost::numeric::ublas::matrix<double> &m, \n          bool &singular)\n{\n    using namespace boost::numeric::ublas;\n\n    const size_t size = m.size1();\n\n    // Cannot invert if non-square matrix or 0x0 matrix.\n    // Report it as singular in these cases, and return \n    // a 0x0 matrix.\n    if (size != m.size2() || size == 0)\n    {\n        singular = true;\n        matrix<double> A(0,0);\n        return A;\n    }\n\n    // Handle 1x1 matrix edge case as general purpose \n    // inverter below requires 2x2 to function properly.\n    if (size == 1)\n    {\n        matrix<double> A(1, 1);\n        if (m(0,0) == 0.0)\n        {\n            singular = true;\n            return A;\n        }\n        singular = false;\n        A(0,0) = 1/m(0,0);\n        return A;\n    }\n\n    // Create an augmented matrix A to invert. Assign the\n    // matrix to be inverted to the left hand side and an\n    // identity matrix to the right hand side.\n    matrix<double> A(size, 2*size);\n    matrix_range<matrix<double> > Aleft(A, \n        range(0, size), \n        range(0, size));\n    Aleft = m;\n    matrix_range<matrix<double> > Aright(A, \n        range(0, size), \n        range(size, 2*size));\n    Aright = identity_matrix<double>(size);\n\n    // Doing partial pivot\n    for (size_t k = 0; k < size; k++)\n    {\n        // Swap rows to eliminate zero diagonal elements.\n        for (size_t kk = 0; kk < size; kk++)\n        {\n            if ( A(kk,kk) == 0 ) // XXX: test for \"small\" instead\n            {\n                // Find a row(l) to swap with row(k)\n                int l = -1;\n                for (size_t i = kk+1; i < size; i++) \n                {\n                    if ( A(i,kk) != 0 )\n                    {\n                        l = i; \n                        break;\n                    }\n                }\n\n                // Swap the rows if found\n                if ( l < 0 ) \n                {\n                    std::cerr << \"Error:\" <<  __FUNCTION__ << \":\"\n                        << \"Input matrix is singular, because cannot find\"\n                        << \" a row to swap while eliminating zero-diagonal.\";\n                    singular = true;\n                    return Aleft;\n                }\n                else \n                {\n                    matrix_row<matrix<double> > rowk(A, kk);\n                    matrix_row<matrix<double> > rowl(A, l);\n                    rowk.swap(rowl);\n\n/*#if defined(DEBUG) || !defined(NDEBUG)\n                    std::cerr << __FUNCTION__ << \":\"\n                        << \"Swapped row \" << kk << \" with row \" << l \n                        << \":\" << A << \"\\n\";\n#endif*/\n                }\n            }\n        }\n\n        ///////////////////////////////////////////////////////////////////////////////////////////////////////// \n        // normalize the current row\n        for (size_t j = k+1; j < 2*size; j++)\n            A(k,j) /= A(k,k);\n        A(k,k) = 1;\n\n        // normalize other rows\n        for (size_t i = 0; i < size; i++)\n        {\n            if ( i != k )  // other rows  // FIX: PROBLEM HERE\n            {\n                if ( A(i,k) != 0 )\n                {\n                    for (size_t j = k+1; j < 2*size; j++)\n                        A(i,j) -= A(k,j) * A(i,k);\n                    A(i,k) = 0;\n                }\n            }\n        }\n\n/*#if defined(DEBUG) || !defined(NDEBUG)\n        std::cerr << __FUNCTION__ << \":\"\n            << \"GJ row \" << k << \" : \" << A << \"\\n\";\n#endif*/\n    }\n\n    singular = false;\n    return Aright;\n}\n\n}\n\n}\n\n#endif // _MATRIXINVERSE_HPP_\n", "meta": {"hexsha": "445436690dfbb834006122e9c9d7f69b657686ee", "size": 5735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_stars_repo_name": "toppic-suite/toppic-suite", "max_stars_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T23:48:38.000Z", "max_issues_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_issues_repo_name": "toppic-suite/toppic-suite", "max_issues_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-08-31T08:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:58:06.000Z", "max_forks_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_forks_repo_name": "toppic-suite/toppic-suite", "max_forks_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T19:25:07.000Z", "avg_line_length": 29.1116751269, "max_line_length": 114, "alphanum_fraction": 0.522929381, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6785528989817162}}
{"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_BEZIER_HPP\n#define SPRIG_CURVE_BEZIER_HPP\n\n#include <sprig/config/config.hpp>\n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include <boost/geometry/core/access.hpp>\n#include <sprig/detail/pow.hpp>\n\nnamespace sprig {\n\t//\n\t// bezier\n\t//\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\treturn Point(\n\t\t\tpow2(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 2 * t * (1 - t) * bg::get<0>(p1)\n\t\t\t\t+ pow2(t) * bg::get<0>(p2)\n\t\t\t\t,\n\t\t\tpow2(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 2 * t * (1 - t) * bg::get<1>(p1)\n\t\t\t\t+ pow2(t) * bg::get<1>(p2)\n\t\t\t);\n\t}\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\treturn Point(\n\t\t\tpow3(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 3 * t * pow2(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 3 * pow2(t) * (1 - t) * bg::get<0>(p2)\n\t\t\t\t+ pow3(t) * bg::get<0>(p3)\n\t\t\t\t,\n\t\t\tpow3(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 3 * t * pow2(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 3 * pow2(t) * (1 - t) * bg::get<1>(p2)\n\t\t\t\t+ pow3(t) * bg::get<1>(p3)\n\t\t\t);\n\t}\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3, Point const& p4) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\tusing sprout::detail::pow4;\n\t\treturn Point(\n\t\t\tpow4(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 4 * t * pow3(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 6 * pow2(t) * pow2(1 - t) * bg::get<0>(p2)\n\t\t\t\t+ 4 * pow3(t) * (1 - t) * bg::get<0>(p3)\n\t\t\t\t+ pow4(t) * bg::get<0>(p4)\n\t\t\t\t,\n\t\t\tpow4(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 4 * t * pow3(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 6 * pow2(t) * pow2(1 - t) * bg::get<1>(p2)\n\t\t\t\t+ 4 * pow3(t) * (1 - t) * bg::get<1>(p3)\n\t\t\t\t+ pow4(t) * bg::get<1>(p4)\n\t\t\t);\n\t}\n\ttemplate<typename T, typename Point>\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3, Point const& p4, Point const& p5) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\tusing sprout::detail::pow4;\n\t\tusing sprout::detail::pow5;\n\t\treturn Point(\n\t\t\tpow5(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 5 * t * pow4(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 10 * pow2(t) * pow3(1 - t) * bg::get<0>(p2)\n\t\t\t\t+ 10 * pow3(t) * pow2(1 - t) * bg::get<0>(p3)\n\t\t\t\t+ 5 * pow4(t) * (1 - t) * bg::get<0>(p4)\n\t\t\t\t+ pow5(t) * bg::get<0>(p5)\n\t\t\t\t,\n\t\t\tpow5(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 5 * t * pow4(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 10 * pow2(t) * pow3(1 - t) * bg::get<1>(p2)\n\t\t\t\t+ 10 * pow3(t) * pow2(1 - t) * bg::get<1>(p3)\n\t\t\t\t+ 5 * pow4(t) * (1 - t) * bg::get<1>(p4)\n\t\t\t\t+ pow5(t) * bg::get<1>(p5)\n\t\t\t);\n\t}\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_CURVE_BEZIER_HPP\n", "meta": {"hexsha": "275d2bafd16fe02f80679516f4277670a60041d4", "size": 3352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/curve/bezier.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/bezier.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/bezier.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": 31.9238095238, "max_line_length": 123, "alphanum_fraction": 0.5438544153, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.678370049287069}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <vector>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\nusing namespace std;\nusing namespace Eigen;\n\ndouble division(int a, int b)\n{\n   if( b == 0 )\n   {\n      throw \"Division by zero condition!\";\n   }\n   return (a/b);\n}\nint main()\n{\n\n    MatrixXd m(3, 3);\n\tm << 0.1, 0, 0,\n        0, 0.2, 0,\n        0, 0, 0.4;\n    RowVector3d x, u;\n    x << 0.5, 0.6, 0.7;\n    u << 0.3, 0.2, 0.5;\n    cout << m.determinant() << endl;\n    cout << m.inverse() << endl;\n    cout << m.row(0).size() << endl;\n\t\n    cout << pow(2 * 3.14159, m.row(0).size()/2.) << endl;\n\t\n\n    cout << x - u << endl;\n    cout << (x - u) * m.inverse() << endl;\n\tcout << exp(-0.5 * (x - u) * m.inverse() * (x - u).transpose()) << endl;\n\t/*\n\tVectorXd r(4);\n\tr = m.row(1);\n\t\n\tdouble* data = r;\n\tcout << data << endl;\n\tcout << r <<endl;\n\tcout << m.row(1) * m.row(2).transpose() << endl;\n\t*/\n    srand((unsigned)time(NULL));\n    cout << MatrixXd::Zero(3,3) << endl;\n\n    cout << MatrixXd::Random(3,3) << endl;\n    \n    cout << MatrixXd::Identity(3,3) << endl;\n\n    MatrixXd a = (x - u).transpose() * (x - u);\n    cout << a << endl;\n    \n\n    ArrayXXd b = a.array();\n    ArrayXXd c = MatrixXd::Identity(3,3);\n\n    cout << b << endl;\n    cout << c << endl;\n\n    cout << b * c << endl;\n    \n\n    MatrixXd* d = new MatrixXd[3];\n    for(int i = 0; i < 3; i++)\n    {\n        d[i] = MatrixXd::Identity(3,3);\n    }\n    d[0] /= 3;\n    cout << d[0] << endl;\n    cout << d[1] << endl;\n    cout << d[2] << endl;\n\n    \n    cout << \"!!!!!!!!!!!!!!!!!!!!\" << endl;\n\n    RowVectorXd e = RowVectorXd::Random(5);\n    cout << e << endl;\n    ArrayXd tmp = e;\n    e = tmp * tmp;\n    cout << e << endl;\n    cout << e.transpose()*e << endl;\n\treturn 0;\n    \n\n\n}", "meta": {"hexsha": "a4991987d191ade74d5e5f1a3deb92fc2404b069", "size": 1754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "hoyden/HMM-GMM-KMeans", "max_stars_repo_head_hexsha": "cae09fc6b9e964acffc2b44c713d1c013450519c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test.cpp", "max_issues_repo_name": "hoyden/HMM-GMM-KMeans", "max_issues_repo_head_hexsha": "cae09fc6b9e964acffc2b44c713d1c013450519c", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "hoyden/HMM-GMM-KMeans", "max_forks_repo_head_hexsha": "cae09fc6b9e964acffc2b44c713d1c013450519c", "max_forks_repo_licenses": ["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.4888888889, "max_line_length": 73, "alphanum_fraction": 0.4766248575, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6783566462867272}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace scpp::models\n{\n\ntemplate <typename T>\nvoid deg2rad(T &deg)\n{\n    deg *= M_PI / 180.;\n}\n\ntemplate <typename T>\nvoid rad2deg(T &rad)\n{\n    rad *= 180. / M_PI;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 1> quaternionToVector(const Eigen::Quaternion<T> &q)\n{\n    Eigen::Matrix<T, 4, 1> q_vec;\n    q_vec << q.w(), q.vec();\n    return q_vec;\n}\n\n// sequence x-y'-z'' is XYZ = Z''Y'X\ntemplate <typename T>\nEigen::Quaternion<T> eulerToQuaternionXYZ(const Eigen::Matrix<T, 3, 1> &eta)\n{\n    Eigen::Quaternion<T> q;\n    q = Eigen::AngleAxis<T>(eta.x(), Eigen::Matrix<T, 3, 1>::UnitX()) *\n        Eigen::AngleAxis<T>(eta.y(), Eigen::Matrix<T, 3, 1>::UnitY()) *\n        Eigen::AngleAxis<T>(eta.z(), Eigen::Matrix<T, 3, 1>::UnitZ());\n\n    return q;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> eulerRotationMatrixXY(const Eigen::Matrix<T, 2, 1> &eta)\n{\n    const T phi = eta.x();\n    const T theta = eta.y();\n\n    Eigen::Matrix<T, 3, 3> M;\n    M.row(0) << cos(theta), T(0.), sin(theta);\n    M.row(1) << sin(theta) * sin(phi), cos(phi), -sin(phi) * cos(theta);\n    M.row(2) << -sin(theta) * cos(phi), sin(phi), cos(phi) * cos(theta);\n\n    return M;\n}\n\n// sequence x-y-z is ZYX\ntemplate <typename T>\nEigen::Quaternion<T> eulerToQuaternionZYX(const Eigen::Matrix<T, 3, 1> &eta)\n{\n    Eigen::Quaternion<T> q;\n    q = Eigen::AngleAxis<T>(eta.z(), Eigen::Matrix<T, 3, 1>::UnitZ()) *\n        Eigen::AngleAxis<T>(eta.y(), Eigen::Matrix<T, 3, 1>::UnitY()) *\n        Eigen::AngleAxis<T>(eta.x(), Eigen::Matrix<T, 3, 1>::UnitX());\n    return q;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 1> quaternionToEulerXYZ(const Eigen::Quaternion<T> &q)\n{\n    const Eigen::Matrix<T, 3, 3> R = q.toRotationMatrix();\n    const T phi = atan2(-R(1, 2), R(2, 2));\n    const T theta = asin(R(0, 2));\n    const T psi = atan2(-R(0, 1), R(0, 0));\n    return Eigen::Matrix<T, 3, 1>(phi, theta, psi);\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 1> quaternionToEulerZYX(const Eigen::Quaternion<T> &q)\n{\n    const Eigen::Matrix<T, 3, 3> R = q.toRotationMatrix();\n    const T phi = atan2(R(1, 0), R(0, 0));\n    const T theta = asin(-R(2, 0));\n    const T psi = atan2(R(2, 1), R(2, 2));\n    return Eigen::Matrix<T, 3, 1>(psi, theta, phi);\n}\n\ntemplate <typename T>\nEigen::Quaternion<T> vectorToQuaternion(const Eigen::Matrix<T, 3, 1> &v)\n{\n    return Eigen::Quaternion<T>(std::sqrt(1. - v.squaredNorm()), v.x(), v.y(), v.z());\n}\n\ntemplate <typename T>\nEigen::Quaternion<T> vectorToQuaternion(const Eigen::Matrix<T, 4, 1> &v)\n{\n    return Eigen::Quaternion<T>(v(3), v(0), v(1), v(2));\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> rotationJacobianXYZ(const Eigen::Matrix<T, 3, 1> &eta)\n{\n    // const T phi = eta.x();\n    const T theta = eta.y();\n    const T psi = eta.z();\n\n    Eigen::Matrix<T, 3, 3> M;\n    M.row(0) << cos(psi), -sin(psi), T(0.);\n    M.row(1) << cos(theta) * sin(psi), cos(theta) * cos(psi), T(0.);\n    M.row(2) << -sin(theta) * cos(psi), sin(theta) * sin(psi), cos(theta);\n\n    return M / cos(theta);\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 2, 2> rotationJacobianXY(const Eigen::Matrix<T, 2, 1> &eta)\n{\n    const T theta = eta.y();\n\n    Eigen::Matrix<T, 2, 2> M;\n    M.row(0) << cos(theta), sin(theta);\n    M.row(1) << -sin(theta), cos(theta);\n\n    return M;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> omegaMatrix(const Eigen::Matrix<T, 3, 1> &w)\n{\n    Eigen::Matrix<T, 4, 4> omega;\n    omega << T(0.), -w(0), -w(1), -w(2),\n        w(0), T(0.), w(2), -w(1),\n        w(1), -w(2), T(0.), w(0),\n        w(2), w(1), -w(0), T(0.);\n\n    return omega;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> omegaMatrixReduced(const Eigen::Matrix<T, 3, 1> &q)\n{\n    Eigen::Matrix<T, 3, 3> omega;\n    const T qw = sqrt(1. - q.squaredNorm());\n    omega << qw, -q(2), q(1),\n        q(2), qw, -q(0),\n        -q(1), q(0), qw;\n\n    return omega;\n}\n\n} // namespace scpp::models", "meta": {"hexsha": "fad5c8e694fb0b6bb7454eb0b303efcee4840919", "size": 3887, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scpp_models/include/common.hpp", "max_stars_repo_name": "Zentrik/SCpp", "max_stars_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 110.0, "max_stars_repo_stars_event_min_datetime": "2019-01-30T05:39:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T11:31:27.000Z", "max_issues_repo_path": "scpp_models/include/common.hpp", "max_issues_repo_name": "Zentrik/SCpp", "max_issues_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-04-02T09:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T13:03:16.000Z", "max_forks_repo_path": "scpp_models/include/common.hpp", "max_forks_repo_name": "Zentrik/SCpp", "max_forks_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2019-07-11T06:58:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:05:48.000Z", "avg_line_length": 26.2635135135, "max_line_length": 86, "alphanum_fraction": 0.573964497, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6782556912666926}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#include <algorithm>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/gil/detail/math.hpp>\n#include <boost/gil/image.hpp>\n#include <boost/gil/image_processing/hough_transform.hpp>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/point.hpp>\n#include <boost/gil/rasterization/line.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <cmath>\n#include <cstddef>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nnamespace gil = boost::gil;\n\nconst std::ptrdiff_t width = 64;\n\nvoid translate(std::vector<gil::point_t>& points, std::ptrdiff_t intercept)\n{\n    std::transform(points.begin(), points.end(), points.begin(),\n                   [intercept](gil::point_t point)\n                   {\n                       return gil::point_t{point.x, point.y + intercept};\n                   });\n}\n\nvoid hough_line_test(std::ptrdiff_t height, std::ptrdiff_t intercept)\n{\n    const auto rasterizer = gil::bresenham_line_rasterizer{};\n    gil::gray8_image_t image(width, width, gil::gray8_pixel_t(0));\n    auto input = gil::view(image);\n    std::vector<gil::point_t> line_points(rasterizer.point_count(width, height));\n    rasterizer({0, 0}, {width - 1, height - 1}, line_points.begin());\n    translate(line_points, intercept);\n    for (const auto& p : line_points)\n    {\n        input(p) = 255;\n    }\n\n    double alpha = std::atan2(height, width);\n    const double theta = alpha + gil::detail::pi / 2;\n    const auto minimum_angle_step = gil::minimum_angle_step({width, height});\n    const double expected_alpha = std::round(alpha / minimum_angle_step) * minimum_angle_step;\n    const double expected_radius = std::round(intercept * std::cos(expected_alpha));\n    const double expected_theta = std::round(theta / minimum_angle_step) * minimum_angle_step;\n\n    const std::size_t half_step_count = 3;\n    const std::ptrdiff_t expected_index = 3;\n    const std::size_t accumulator_array_dimensions = half_step_count * 3 + 1;\n    auto radius_param =\n        gil::hough_parameter<std::ptrdiff_t>::from_step_count(expected_radius, 3, half_step_count);\n    auto theta_param = gil::make_theta_parameter(\n        expected_theta, minimum_angle_step * half_step_count, {width, height});\n    gil::gray32_image_t accumulator_array_image(\n        accumulator_array_dimensions, accumulator_array_dimensions, gil::gray32_pixel_t(0));\n    auto accumulator_array = gil::view(accumulator_array_image);\n    gil::hough_line_transform(input, accumulator_array, theta_param, radius_param);\n\n    auto max_element_iterator =\n        std::max_element(accumulator_array.begin(), accumulator_array.end());\n    gil::point_t candidates[] = {\n        {expected_index - 1, expected_index - 1}, {expected_index, expected_index - 1},\n        {expected_index + 1, expected_index - 1}, {expected_index - 1, expected_index},\n        {expected_index, expected_index},         {expected_index + 1, expected_index},\n        {expected_index - 1, expected_index + 1}, {expected_index, expected_index + 1},\n        {expected_index + 1, expected_index + 1}};\n    bool match_found = false;\n    for (std::size_t i = 0; i < 9; ++i)\n    {\n        if (*max_element_iterator == accumulator_array(candidates[i]))\n        {\n            match_found = true;\n            break;\n        }\n    }\n    BOOST_TEST(match_found);\n}\n\nint main()\n{\n    for (std::ptrdiff_t height = 1; height < width; ++height)\n    {\n        for (std::ptrdiff_t intercept = 1; intercept < width - height; ++intercept)\n        {\n            hough_line_test(height, intercept);\n        }\n    }\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "f0ed992fa33381f3224691f0ee587031b84c9c1b", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/image_processing/hough_line_transform.cpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "test/core/image_processing/hough_line_transform.cpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "test/core/image_processing/hough_line_transform.cpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 38.67, "max_line_length": 99, "alphanum_fraction": 0.6803723817, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6782556752936506}}
{"text": "//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n\n#include <limits>\n#include <vector>\n\nnamespace gil = boost::gil;\n\n// Demonstrates the use of a rasterizer to generate an image of a line\n// The various rasterizers available are defined in include/boost/gil/rasterization/circle.hpp,\n// include/boost/gil/rasterization/ellipse.hpp and include/boost/gil/rasterization/line.hpp\n// The rasterizer used implements the Bresenham's line algorithm. \n// Multiple images are created, all of the same size, but with areas of different sizes passed to the rasterizer, resulting in different lines.\n// See also:\n// rasterizer_circle.cpp - Demonstrates the use of a rasterizer to generate an image of a circle\n// rasterizer_ellipse.cpp - Demonstrates the use of a rasterizer to generate an image of an ellipse\n\n\nconst std::ptrdiff_t size = 256;\n\nvoid line_bresenham(std::ptrdiff_t width, std::ptrdiff_t height, const std::string& output_name)\n{\n    const auto rasterizer = gil::bresenham_line_rasterizer{};\n    std::vector<gil::point_t> line_points(rasterizer.point_count(width, height));\n\n    gil::gray8_image_t image(size, size);\n    auto view = gil::view(image);\n\n    rasterizer({0, 0}, {width - 1, height - 1}, line_points.begin());\n    for (const auto& point : line_points)\n    {\n        view(point) = std::numeric_limits<gil::uint8_t>::max();\n    }\n\n    gil::write_view(output_name, view, gil::png_tag{});\n}\n\nint main()\n{\n    line_bresenham(256, 256, \"line-bresenham-256-256.png\");\n    line_bresenham(256, 128, \"line-bresenham-256-128.png\");\n    line_bresenham(256, 1, \"line-bresenham-256-1.png\");\n    line_bresenham(1, 256, \"line-bresenham-1-256.png\");\n}\n", "meta": {"hexsha": "b1c3526f746c0d7f037693b541df17abbda5e8b9", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/rasterizer_line.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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/rasterizer_line.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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/rasterizer_line.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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.5094339623, "max_line_length": 143, "alphanum_fraction": 0.7291989664, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6780917062385892}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\n\nconst double eps = 0.0001;   // \u7528\u4e8e\u6d6e\u70b9\u6570\u6bd4\u8f83\u5927\u5c0f\nconst int sampleNum = 5000; // \u6837\u672c\u6570\u76ee,100\nconst int attriNum = 768;  // \u4e00\u4e2a\u6837\u672c\u7279\u5f81\u6570\u76ee,2\n\n\n/*\n// \u7528\u4e8e\u5bfc\u5165\u6570\u636e [\u8fd9\u4e2a\u51fd\u6570\u672c\u5e94\u8be5\u4eceLoadData\u4e2d\u8c03\u7528\u7684\uff0c\u4f46\u662f\u6211\u6ca1\u6210\u529f...]\ndouble** load(string filename, int m, int n){\n    // \u521d\u59cb\u5316\u6570\u7ec4\n    double** ans = (double **)malloc(m * sizeof(double *));\n    for(int i=0;i<m;i++)\n        ans[i] = (double *)malloc(n * sizeof(double));\n    \n    ifstream inFile(filename, ios::in);\n\tstring lineStr; //\u6bcf\u4e00\u884c\u7684\u7ed3\u679c\n    for(int i=0;i<m;i++){\n        getline(inFile, lineStr);\n        stringstream ss(lineStr);\n        string str;\n        for(int j=0;j<n;j++){\n            getline(ss, str, ',');\n            ans[i][j] = atof(str.c_str());\n        }\n    }\n    return ans;\n}\n\n// \u635f\u5931\u51fd\u6570\n// X_bar sampleNum * (attriNum+1), y sampleNum*1, theta (attriNum+1)\n// \u4f46\u5b9e\u9645\u4e0a\u8f93\u5165\u7684\u662f X sampleNum * attriNum\uff0c\u5728\u8ba1\u7b97\u7684\u65f6\u5019\u624b\u52a8\u52a0\u5165\u4e00\u9879 -1 \ndouble loss_theta(double ** X_bar,double ** y,double* theta){\n    double * tmp = new double[sampleNum]();\n    for(int i=0;i<sampleNum;i++){\n        double xTheta = 0;\n        for(int j=0;j<attriNum;j++){\n            xTheta += X_bar[i][j]*theta[j];\n        }\n        xTheta -= theta[attriNum];\n        tmp[i] = y[i][0]*xTheta;\n    }\n    double sum = 0;\n    for(int i=0;i<sampleNum;i++)\n        sum += log(1+exp(-tmp[i]));\n    return (double)sum/sampleNum;\n}\n\n// \u7528\u6765\u7edf\u8ba1\u51c6\u786e\u7387\ndouble score(double* orgLabel,double* newLabel){\n    int sum = 0;\n    for(int i=0;i<sampleNum;i++){\n        if((orgLabel[i]-newLabel[i])<eps)\n            sum+=1;\n    }\n    return (double)sum/sampleNum;\n}\n\n// \u7528\u6765\u6253\u5370\u4e00\u4e2a\u4e8c\u7ef4\u6570\u7ec4(\u6d4b\u8bd5\u7528)\nvoid printTest(double** tmp,int m,int n){\n    for(int i=0;i<m;i++){\n        for(int j=0;j<n;j++){\n            cout << tmp[i][j] << \" \";\n        }\n        cout << \"\\n\";\n    }\n}\n\n*/\n\n\n// \u9700\u8981\u6307\u5b9a\u6570\u636e\u7684\u884c\u548c\u5217\nMatrix<double, Dynamic, Dynamic> loadEigen(string filename, int m ,int n){\n    Matrix<double, Dynamic, Dynamic> ans = MatrixXd::Zero(m, n);;\n    ifstream inFile(filename, ios::in);\n\tstring lineStr; //\u6bcf\u4e00\u884c\u7684\u7ed3\u679c\n    for(int i=0;i<m;i++){\n        getline(inFile, lineStr);\n        stringstream ss(lineStr);\n        string str;\n        for(int j=0;j<n;j++){\n            getline(ss, str, ',');\n            ans(i,j) = atof(str.c_str());\n        }\n    }\n    return ans;\n}\n\n/*\ndef theta_gradient(X_bar,y,beta,alpha=0):\n    ans = np.zeros(beta.shape)+alpha*beta\n    for i in range(X_bar.shape[0]):\n        tmp = np.exp(beta.dot(X_bar[i]))\n        ans += X_bar[i]*(y[i]-tmp/(1+tmp))\n    return -ans\n*/\n\n\nMatrix<double,attriNum+1,1> theta_gradient(MatrixXd X_bar ,Matrix<double,sampleNum,1> Y,Matrix<double,attriNum+1,1> beta,double alpha){\n    Matrix<double,attriNum+1,1> ans = alpha * beta;\n    // ans.fill(0);\n    for(int i=0;i<sampleNum;i++){\n        // cout << X_bar.row(i).rows() << \"\\t\" << X_bar.row(i).cols() <<endl;\n        double tmp = exp(X_bar.row(i)*beta);\n        // cout << X_bar.row(i).transpose() << endl;\n        ans += X_bar.row(i).transpose()*(Y(i,0)-tmp/(1+tmp));\n    }\n    return -ans;\n}\n\n// // \u8bad\u7ec3\nvoid train(){\n\n}\n\n// // \u9884\u6d4b\nMatrix<double,sampleNum,1> predict(MatrixXd X_bar,Matrix<double,attriNum+1,1> beta){\n    Matrix<double,sampleNum,1> y_pred;\n    y_pred.fill(0);\n    for(int i=0;i<sampleNum;i++){\n        double tmp = 1/(1+exp(-X_bar.row(i)*beta));\n        // cout << tmp << endl;\n        if(tmp >0.5)\n           y_pred(i,0)= 1; // \u5426\u5219\u9ed8\u8ba4\u662f0\n    }\n    return y_pred;\n}\n\ndouble accuracy(Matrix<double,sampleNum,1> y_pred, Matrix<double,sampleNum,1> y){\n    int num = 0;\n    for(int i=0;i<sampleNum;i++)\n        if((y_pred(i,0)-y(i,0))<eps)\n            num+=1;\n    cout << num << \" correct out of \" <<sampleNum << endl;\n    return (double)num/sampleNum;\n}", "meta": {"hexsha": "9862e5d79f63d9c23c12d3247f6c9d834f2dcdaa", "size": 3759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "5.1/Machine Learning Algo/C++/LogisticRegression.hpp", "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": "5.1/Machine Learning Algo/C++/LogisticRegression.hpp", "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": "5.1/Machine Learning Algo/C++/LogisticRegression.hpp", "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": 26.1041666667, "max_line_length": 135, "alphanum_fraction": 0.5642458101, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6780916948980434}}
{"text": "#include \"Triangle.h\"\n#include \"Ray.h\"\n#include \"Intersection.h\"\n\n#include <Eigen/Dense>\n\nstd::unique_ptr<Intersection> Triangle::intersect(const Ray& ray) {\n    auto p = ray.p;\n    auto d = ray.d;\n\n    if (n.dot(d) > 0.0f) {\n        return nullptr;\n    } else {\n        // Use centroid as point on plane\n        auto pt = 1/3.0f*a + 1/3.0f*b + 1/3.0f*c;\n\n        // Find intersection t\n        float t = (pt-p).dot(n) / d.dot(n);\n\n        // Find intersection point\n        auto x = p + d*t;\n\n        // Perform intersection tests on half planes\n        bool hp0 = (b-a).cross(x-a).dot(n) >= 0;\n        bool hp1 = (c-b).cross(x-b).dot(n) >= 0;\n        bool hp2 = (a-c).cross(x-c).dot(n) >= 0;\n\n        // Check if point intersects all three halfplanes\n        if (hp0 && hp1 && hp2)\n            return std::unique_ptr<Intersection>(new Intersection(this, n, t));\n\n        return nullptr;\n    }\n}\n", "meta": {"hexsha": "272cd23b85f938da91d44e7f7fd344bcaaea8678", "size": 897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Triangle.cpp", "max_stars_repo_name": "fmenozzi/raytracer", "max_stars_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:51.000Z", "max_issues_repo_path": "src/Triangle.cpp", "max_issues_repo_name": "fmenozzi/raytracer", "max_issues_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_issues_repo_licenses": ["MIT"], "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/Triangle.cpp", "max_forks_repo_name": "fmenozzi/raytracer", "max_forks_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_forks_repo_licenses": ["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.6285714286, "max_line_length": 79, "alphanum_fraction": 0.5429208473, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6780808525165142}}
{"text": "//\n// Dynamics of Differential Drive circle robot. \n// Based on the dynamics in: http://arl.cs.utah.edu/pubs/ACC2014.pdf\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n# pragma once\n\n#include <experiments/simulators/simulator_utils.hh>\n\n#include <Eigen/Dense>\n\n#include <array>\n\nnamespace simulators\n{\nnamespace diffdrive\n{\n\ntemplate<int dim>\nusing Vector = Eigen::Matrix<double, dim, 1>;\n\nenum State\n{\n    POS_X = 0,\n    POS_Y,\n    THETA,\n    dTHETA,\n    dV_LEFT,\n    dV_RIGHT,\n    STATE_DIM\n};\n\nenum Control \n{\n    V_LEFT = 0,\n    V_RIGHT,\n    CONTROL_DIM\n};\n\n// Useful for holding the parameters of the Differential Drive robot, \n// including integration timestep.\n// Wheel distance defaults to 0.258 m, the width for the iRobot Create. \nclass DiffDrive\n{\npublic:\n    DiffDrive(const double dt, \n            const std::array<double, 2> &control_lims, // {-min_u, max_u}\n            const std::array<double, 4> &world_lims, // {-min_x, max_x, -min_y, max_y}\n            const double wheel_dist=0.258);\n    // Discrete time dynamics.\n    Vector<STATE_DIM> operator()(const Vector<STATE_DIM>& x, const Vector<CONTROL_DIM>& u);\n\n    double wheel_dist() { return wheel_dist_; }\n    double dt() { return dt_; }\nprivate:\n    double dt_;\n    std::array<double, 2> control_lims_;\n    std::array<double, 4> world_lims_;\n    double wheel_dist_;\n};\n\nVector<STATE_DIM> continuous_dynamics(const Vector<STATE_DIM>& x, const Vector<CONTROL_DIM>& u, \n                                    const double wheel_dist);\n} // namespace diffdrive\n} // namespace simulators\n", "meta": {"hexsha": "19409feddd5e8cccc7b08041b5d73b4e2812cc6a", "size": 1570, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/diffdrive.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/experiments/simulators/diffdrive.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/experiments/simulators/diffdrive.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 22.7536231884, "max_line_length": 96, "alphanum_fraction": 0.6662420382, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6780754932334784}}
{"text": "#define BOOST_TEST_MODULE Gpufit\n\n#include \"Gpufit/gpufit.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <array>\n\ntemplate<std::size_t SIZE>\nvoid generate_gauss_2d_elliptic(std::array< float, SIZE>& values)\n{\n    int const size_x = int(std::sqrt(SIZE));\n    int const size_y = size_x;\n\n    float const a = 4;\n    float const x0 = (float(size_x) - 1.f) / 2.f;\n    float const y0 = (float(size_y) - 1.f) / 2.f;\n    float const sx = 0.4f;\n    float const sy = 0.6f;\n    float const b = 1.f;\n\n    for (int point_index_y = 0; point_index_y < size_y; point_index_y++)\n    {\n        for (int point_index_x = 0; point_index_x < size_x; point_index_x++)\n        {\n            int const point_index = point_index_y * size_x + point_index_x;\n            float const argx = ((point_index_x - x0)*(point_index_x - x0)) / (2.f * sx * sx);\n            float const argy = ((point_index_y - y0)*(point_index_y - y0)) / (2.f* sy * sy);\n            float const ex = exp(-argx) * exp(-argy);\n            values[point_index] = a * ex + b;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_2D_Elliptic )\n{\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 25 } ;\n    std::array< float, n_points > data{};\n    generate_gauss_2d_elliptic(data);\n    std::array< float, n_points > weights{};\n    std::fill(weights.begin(), weights.end(), 1.f);\n    std::array< float, 6 > initial_parameters{ { 2.f, 1.8f, 2.2f, 0.5f, 0.5f, 0.f } };\n    float tolerance{ 0.001f };\n    int max_n_iterations{ 10 };\n    std::array< int, 6 > parameters_to_fit{ { 1, 1, 1, 1, 1, 1 } };\n    std::array< float, 6 > output_parameters;\n    int output_states;\n    float output_chi_square;\n    int output_n_iterations;\n\n    int const status\n            = gpufit\n            (\n                n_fits,\n                n_points,\n                data.data(),\n                weights.data(),\n                GAUSS_2D_ELLIPTIC,\n                initial_parameters.data(),\n                tolerance,\n                max_n_iterations,\n                parameters_to_fit.data(),\n                LSE,\n                0,\n                0,\n                output_parameters.data(),\n                &output_states,\n                &output_chi_square,\n                &output_n_iterations\n            ) ;\n\n    BOOST_CHECK( status == 0 ) ;\n}\n", "meta": {"hexsha": "072169c9c3417bc105e0834ec1e927d81d508bf6", "size": 2301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_stars_repo_name": "yongdengzhang/Gpufit", "max_stars_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_issues_repo_name": "yongdengzhang/Gpufit", "max_issues_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gpufit/tests/Gauss_Fit_2D_Elliptic.cpp", "max_forks_repo_name": "yongdengzhang/Gpufit", "max_forks_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T15:13:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T15:13:27.000Z", "avg_line_length": 30.68, "max_line_length": 93, "alphanum_fraction": 0.55410691, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6780754880742124}}
{"text": "/* boost random/triangle_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\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 * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: triangle_distribution.hpp 49314 2008-10-13 09:00:03Z johnmaddock $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n#define BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <cassert>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n// triangle distribution, with a smallest, b most probable, and c largest\n// value.\ntemplate<class RealType = double>\nclass triangle_distribution\n{\npublic:\n  typedef RealType input_type;\n  typedef RealType result_type;\n\n  explicit triangle_distribution(result_type a_arg = result_type(0),\n                                 result_type b_arg = result_type(0.5),\n                                 result_type c_arg = result_type(1))\n    : _a(a_arg), _b(b_arg), _c(c_arg)\n  {\n    assert(_a <= _b && _b <= _c);\n    init();\n  }\n\n  // compiler-generated copy ctor and assignment operator are fine\n  result_type a() const { return _a; }\n  result_type b() const { return _b; }\n  result_type c() const { return _c; }\n\n  void reset() { }\n\n  template<class Engine>\n  result_type operator()(Engine& eng)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    result_type u = eng();\n    if( u <= q1 )\n      return _a + p1*sqrt(u);\n    else\n      return _c - d3*sqrt(d2*u-d1);\n  }\n\n#if !defined(BOOST_NO_OPERATORS_IN_NAMESPACE) && !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)\n  template<class CharT, class Traits>\n  friend std::basic_ostream<CharT,Traits>&\n  operator<<(std::basic_ostream<CharT,Traits>& os, const triangle_distribution& td)\n  {\n    os << td._a << \" \" << td._b << \" \" << td._c;\n    return os;\n  }\n\n  template<class CharT, class Traits>\n  friend std::basic_istream<CharT,Traits>&\n  operator>>(std::basic_istream<CharT,Traits>& is, triangle_distribution& td)\n  {\n    is >> std::ws >> td._a >> std::ws >> td._b >> std::ws >> td._c;\n    td.init();\n    return is;\n  }\n#endif\n\nprivate:\n  void init()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    d1 = _b - _a;\n    d2 = _c - _a;\n    d3 = sqrt(_c - _b);\n    q1 = d1 / d2;\n    p1 = sqrt(d1 * d2);\n  }\n\n  result_type _a, _b, _c;\n  result_type d1, d2, d3, q1, p1;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n", "meta": {"hexsha": "819e0b61e6baf7e3a532fea71970bcce96aa379e", "size": 2608, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/triangle_distribution.hpp", "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": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T00:55:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T03:05:51.000Z", "max_issues_repo_path": "boost/random/triangle_distribution.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/random/triangle_distribution.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "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.568627451, "max_line_length": 91, "alphanum_fraction": 0.6679447853, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6780664328033973}}
{"text": "/**\n   Transformation between Polar-Laguerre and Hermite basis\n*/\n\n// system includes\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <boost/lexical_cast.hpp>\n#include <functional>\n#include <iostream>\n\n// own includes\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\n\nTEST(spectral, polar2hermite)\n{\n  std::vector<int> Ks = {4, 10, 20, 25, 36, 50, 80};\n\n  cout << \"Testing for K=\";\n  for_each(Ks.begin(), Ks.end(), [](int x) { cout << x << \" \"; });\n  cout << \"\\n\";\n\n  for (int K : Ks) {\n    typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n    hermite_basis_t hermite_basis;\n    SpectralBasisFactoryHN::create(hermite_basis, K, 2);\n\n    typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n    polar_basis_t polar_basis;\n    SpectralBasisFactoryKS::create(polar_basis, K, K, 2, true /* sorted */);\n\n    Polar2Hermite<polar_basis_t, hermite_basis_t> p2h(polar_basis, hermite_basis);\n\n    Eigen::VectorXd cp(polar_basis.n_dofs());\n    cp.setOnes();\n\n    Eigen::VectorXd ch(hermite_basis.n_dofs());\n    p2h.to_hermite(ch, cp);\n\n    Eigen::VectorXd cp2(polar_basis.n_dofs());\n    p2h.to_polar(cp2, ch);\n\n    double err = (cp2 - cp).cwiseAbs2().maxCoeff();\n    cout << \"err: \" << err << \"\\n\";\n    EXPECT_NEAR(err, 0, 1e-14) << \"K=\" << boost::lexical_cast<string>(K);\n  }\n}\n", "meta": {"hexsha": "01251256f624f7dede328b88c71c1b0280473bb3", "size": 1469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_polar2hermite.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gtest/gtest_polar2hermite.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_polar2hermite.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7169811321, "max_line_length": 82, "alphanum_fraction": 0.6923076923, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6780664151523786}}
{"text": "/*-----------------------------------------------------------------------------+    \r\nInterval Container Library\r\nAuthor: Joachim Faulhaber\r\nCopyright (c) 2007-2009: Joachim Faulhaber\r\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\r\n+------------------------------------------------------------------------------+\r\n   Distributed under the Boost Software License, Version 1.0.\r\n      (See accompanying file LICENCE.txt or copy at\r\n           http://www.boost.org/LICENSE_1_0.txt)\r\n+-----------------------------------------------------------------------------*/\r\n/** Example overlap_counter.cpp \\file overlap_counter.cpp\r\n\r\n    \\brief The most simple application of an interval map: \r\n           Counting the overlaps of added intervals.\r\n\r\n    The most basic application of an interval_map is a counter counting\r\n    the number of overlaps of intervals inserted into it.\r\n\r\n    On could call an interval_map an aggregate on overlap machine. A very basic\r\n    aggregation is summation of an integer. A interval_map<int,int> maps\r\n    intervals of int to ints. \r\n\r\n    If we insert a value pair (discrete_interval<int>(2,6), 1) into the interval_map, it\r\n    increases the content of all value pairs in the map by 1, if their interval\r\n    part overlaps with discrete_interval<int>(2,6).\r\n\r\n    \\include overlap_counter_/overlap_counter.cpp\r\n*/\r\n//[example_overlap_counter\r\n#include <iostream>\r\n#include <boost/icl/split_interval_map.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::icl;\r\n\r\n\r\n/* The most simple example of an interval_map is an overlap counter.\r\n   If intervals are added that are associated with the value 1,\r\n   all overlaps of added intervals are counted as a result in the\r\n   associated values. \r\n*/\r\ntypedef interval_map<int, int> OverlapCounterT;\r\n\r\nvoid print_overlaps(const OverlapCounterT& counter)\r\n{\r\n    for(OverlapCounterT::const_iterator it = counter.begin(); it != counter.end(); it++)\r\n    {\r\n        discrete_interval<int> itv  = (*it).first;\r\n        int overlaps_count = (*it).second;\r\n        if(overlaps_count == 1)\r\n            cout << \"in interval \" << itv << \" intervals do not overlap\" << endl;\r\n        else\r\n            cout << \"in interval \" << itv << \": \"<< overlaps_count << \" intervals overlap\" << endl;\r\n    }\r\n}\r\n\r\nvoid overlap_counter()\r\n{\r\n    OverlapCounterT overlap_counter;\r\n    discrete_interval<int> inter_val;\r\n\r\n    inter_val = discrete_interval<int>::right_open(4,8);\r\n    cout << \"-- adding   \" << inter_val << \" -----------------------------------------\" << endl;\r\n    overlap_counter += make_pair(inter_val, 1);\r\n    print_overlaps(overlap_counter);\r\n    cout << \"-----------------------------------------------------------\" << endl;\r\n\r\n    inter_val = discrete_interval<int>::right_open(6,9);\r\n    cout << \"-- adding   \" << inter_val << \" -----------------------------------------\" << endl;\r\n    overlap_counter += make_pair(inter_val, 1);\r\n    print_overlaps(overlap_counter);\r\n    cout << \"-----------------------------------------------------------\" << endl;\r\n\r\n    inter_val = discrete_interval<int>::right_open(1,9);\r\n    cout << \"-- adding   \" << inter_val << \" -----------------------------------------\" << endl;\r\n    overlap_counter += make_pair(inter_val, 1);\r\n    print_overlaps(overlap_counter);\r\n    cout << \"-----------------------------------------------------------\" << endl;\r\n    \r\n}\r\n\r\nint main()\r\n{\r\n    cout << \">>Interval Container Library: Sample overlap_counter.cpp <<\\n\";\r\n    cout << \"-----------------------------------------------------------\\n\";\r\n    overlap_counter();\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n\r\n// >>Interval Container Library: Sample overlap_counter.cpp <<\r\n// -----------------------------------------------------------\r\n// -- adding   [4,8) -----------------------------------------\r\n// in interval [4,8) intervals do not overlap\r\n// -----------------------------------------------------------\r\n// -- adding   [6,9) -----------------------------------------\r\n// in interval [4,6) intervals do not overlap\r\n// in interval [6,8): 2 intervals overlap\r\n// in interval [8,9) intervals do not overlap\r\n// -----------------------------------------------------------\r\n// -- adding   [1,9) -----------------------------------------\r\n// in interval [1,4) intervals do not overlap\r\n// in interval [4,6): 2 intervals overlap\r\n// in interval [6,8): 3 intervals overlap\r\n// in interval [8,9): 2 intervals overlap\r\n// -----------------------------------------------------------\r\n//]\r\n", "meta": {"hexsha": "87dfb6ce92ce81d6b190e1ca89a873441c29a747", "size": 4508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/overlap_counter_/overlap_counter.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": 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/boost/libs/icl/example/overlap_counter_/overlap_counter.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/icl/example/overlap_counter_/overlap_counter.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": 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": 41.3577981651, "max_line_length": 100, "alphanum_fraction": 0.5139751553, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6780288596970659}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/utility.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ndouble f(double) { /* cout << \"double\\n\"; */ return 1.0; }\ncomplex<double> f(complex<double>) \n{ \n    //cout << \"complex\\n\"; \n    return complex<double>(1.0, -1.0); \n}\n\n \nint main(int, char**)\n{\n    using namespace mtl; using mtl::io::tout;\n    unsigned size=4, row= size+1, col=size;\n\n    double tol(0.00001);\n    dense_vector<double>                vec(size), vec1(size);\n    dense2D<double>                     A(row, col),   Q(row, row),   R(row, col),   A_test(row, col),\n\t                                A_t(col, row), Q_t(col, col), R_t(col, row), A_t_test(col, row);\n    dense2D<complex<double> >                            dz(row, col), Qz(row, row), Rz(row, col);\n    dense2D<double, mat::parameters<col_major> >         dc(size, size);\n    compressed2D<double>                                 Ac(size, size), Qc(size, size), Rc(size, size), A_testc(size, size) ;\n    A= 0; \n\n    A[0][0]=1;    A[0][1]=1;    A[0][2]=1;\n    A[1][0]=3;    A[1][1]=-1;   A[1][2]=-2;\n    A[2][0]=1;    A[2][1]=7;    A[2][2]=1;\n    A[3][3]=-10;  A[4][0]=4;    A[4][2]=3;\n    tout<<\"A=\\n\"<< A <<\"\\n\";\n    laplacian_setup(Ac, 2,2);\n\n    \n    tout<<\"START-----dense2d---------row > col\\n\";\n  \n    dense2D<double> A1(A[iall][iall]), A2(A);\n    boost::tie(Q, R)= qr(A1);\n    tout<<\"R=\\n\"<< R <<\"\\n\";\n    tout<<\"Q=\\n\"<< Q <<\"\\n\";\n    A_test= Q*R-A2;\n    tout<<\"Q*R=\\n\"<< Q*R <<\"\\n\";\n\t\n    tout<< \"one_norm(Rest A)=\" << one_norm(A_test) << \"\\n\";\n    MTL_THROW_IF(one_norm(A_test) > tol, mtl::logic_error(\"wrong QR decomposition of matrix A\"));\n\n\t\n    tout<<\"START------dense2d-------row < col\\n\";\n\n    A_t= trans(A);\n    boost::tie(Q_t, R_t)= qr(A_t);\n    tout<<\"R_t=\\n\"<< R_t <<\"\\n\";\n    tout<<\"Q_t=\\n\"<< Q_t <<\"\\n\";\n    A_t_test= Q_t*R_t-A_t;\n    tout<<\"Q_t*R_t=\\n\"<< Q_t*R_t <<\"\\n\";\n\t\t\t\n    tout<< \"one_norm(Rest A')=\" << one_norm(A_t_test) << \"\\n\";\n    MTL_THROW_IF(one_norm(A_t_test) > tol, mtl::logic_error(\"wrong QR decomposition of matrix trans(A)\"));\n\t\n    tout<<\"START-------compressed2d-------row > col\\n\";\n#if 1\n    boost::tie(Qc, Rc)= qr(Ac);\n    tout<<\"R=\\n\"<< Rc <<\"\\n\";\n    tout<<\"Q=\\n\"<< Qc <<\"\\n\";\n    A_testc= Qc*Rc-Ac;\n    tout<<\"Q*R=\\n\"<< Qc*Rc <<\"\\n\";\n    tout<<\"A=\\n\"<< Ac <<\"\\n\";\n\t\n    tout<< \"one_norm(Rest A)=\" << one_norm(A_testc) << \"\\n\";\n    MTL_THROW_IF(one_norm(A_testc) > tol, mtl::logic_error(\"wrong QR decomposition of matrix A\")); \n#endif\n\n#if 0\n    dz[0][0]=complex<double>(1.0, 0.0);\n    dz[0][1]=complex<double>(1.0, 0.0);\n    dz[0][2]=complex<double>(1,0);\n    dz[1][0]=complex<double>(1,0);\n    dz[1][1]=complex<double>(-1,0);\n    dz[1][2]=complex<double>(-2,0);\n    dz[2][0]=complex<double>(1,0);\n    dz[2][1]=complex<double>(-2,0);\n    dz[2][2]=complex<double>(1,0);\n    dz[3][3]=complex<double>(-10,0);\n    tout<<\"MAtrix complex=\\n\"<< dz <<\"\\n\";\n\n    tout<<\"START-----complex---------\"<< dz[0][0] << \"\\n\";\n    //\n    boost::tie(Qz, Rz)= qr(dz);\n    // Rz= qr_zerl(dz).second;\n    // tout<<\"MAtrix  R=\"<< Rz <<\"\\n\";\n    // tout<<\"MAtrix  Q=\"<< Qz <<\"\\n\";\n    // tout<<\"MAtrix  A=Q*R--outside\"<< Qz*Rz <<\"\\n\";\n#endif\n    return 0;\n}\n\n", "meta": {"hexsha": "702ddeb88523a452464ab21b0d272fa03ca199f3", "size": 3608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/qr_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/qr_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/qr_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.9292035398, "max_line_length": 126, "alphanum_fraction": 0.5268847007, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6780288399789063}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n#include \"constants.hpp\"\n\nnamespace vgl {\ntemplate <typename T>\nvoid print_quat(Eigen::Quaternion<T> const& quat) {\n    std::cout << quat.w() << \" \" << quat.x() << \" \" << quat.y() << \" \" << quat.z() << std::endl;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 1> quat_to_euler_angles(Eigen::Quaternion<T> const& q) {\n    return 180.0 / math::pi<double> *\n           Eigen::Matrix<T, 3, 1>(\n               std::atan2(2.0 * (q.w() * q.x() + q.y() * q.z()), 1.0 - 2.0 * (q.x() * q.x() + q.y() * q.y())),\n               std::asin(2.0 * (q.w() * q.y() - q.x() * q.z())),\n               std::atan2(2.0 * (q.w() * q.z() + q.x() * q.y()), 1.0 - 2.0 * (q.y() * q.y() + q.z() * q.z())));\n}\n\nstruct Pose {\n    Pose() noexcept;\n    Pose(Eigen::Quaterniond const& R, Eigen::Vector3d const& t) noexcept;\n    Pose(Eigen::Matrix4d const& T) noexcept;\n    Pose inverse() const;\n    Eigen::Matrix4d to_matrix() const;\n    void from_matrix(Eigen::Matrix4d const& T);\n    void print();\n\n    Eigen::Quaterniond rotation = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0);\n    Eigen::Vector3d translation = Eigen::Vector3d(0.0, 0.0, 0.0);\n};\n} // namespace vgl\n", "meta": {"hexsha": "28b40865f81ab21e5818f45c783802fe565c53c0", "size": 1209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vgl/math/pose.hpp", "max_stars_repo_name": "alexsr/vgl", "max_stars_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T18:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T18:27:19.000Z", "max_issues_repo_path": "src/vgl/math/pose.hpp", "max_issues_repo_name": "alexsr/vgl", "max_issues_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_issues_repo_licenses": ["MIT"], "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/vgl/math/pose.hpp", "max_forks_repo_name": "alexsr/vgl", "max_forks_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 111, "alphanum_fraction": 0.5483870968, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6780288368232844}}
{"text": "#include <fstream>\n#include <iostream>\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nint main() {\n    double a11, a12, a13, a21, a22, a23, a31, a32, a33;\n    Eigen::Matrix3d Im;\n\n    std::cin >> a11 >> a12 >> a13\n             >> a21 >> a22 >> a23\n             >> a31 >> a32 >> a33;\n\n    if (std::cin.fail()) {\n        std::cerr << \"Invalid input. Expected 3x3 matrix in the form a11 a12 a13 a21 ... a33, separated by whitespace.\" << std::endl;\n        abort();\n    }\n\n    Im << a11, a12, a13,\n          a21, a22, a23,\n          a31, a32, a33;\n\n    // The inertia tensor should be a real symmetric matrix; real symmetric\n    // matrices are self-adjoint.\n    // A real symmetric n-dimensional matrix always possesses n real\n    // mutually orthogonal eigenvectors/eigenvalues.\n    // http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node66.html\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigenSolver(Im);\n\n    if (eigenSolver.info() != Eigen::Success) {\n        std::cerr << \"Failed to solve for principal axes of rotation. Invalid inertia tensor?\" << std::endl;\n        abort();\n    }\n\n    // http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node67.html\n    Eigen::Vector3d eigenvalues(eigenSolver.eigenvalues());\n    std::cout << eigenvalues[0] << \" \"\n              << eigenvalues[1] << \" \"\n              << eigenvalues[2] << std::endl;\n    Eigen::Quaterniond q(eigenSolver.eigenvectors());\n    q.normalize();\n    std::cout << q.w() << \" \"\n              << q.x() << \" \"\n              << q.y() << \" \"\n              << q.z() << \" \" << std::endl;\n}\n", "meta": {"hexsha": "b02aeceb15e617bd5a21533982d641412026ce64", "size": 1610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 32.2, "max_line_length": 133, "alphanum_fraction": 0.5745341615, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6779568775185626}}
{"text": "#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <angles/angles.h>\n#include <robot_kf/robot_kf.h>\n\n#include <iostream>\n\nusing namespace Eigen;\n\nnamespace robot_kf {\n\nKalmanFilter::KalmanFilter(void)\n    : x_(Vector3d::Zero())\n    , cov_x_(9999 * Matrix3d::Identity())\n    , A_(Matrix3d::Identity())\n    , Hgps_((Matrix<double, 2, 3>() << 1, 0, 0, 0, 1, 0).finished())\n    , Hcomp_((Matrix<double, 1, 3>() << 0, 0, 1).finished())\n{}\n\nKalmanFilter::~KalmanFilter(void)\n{}\n\nVector3d KalmanFilter::getState(void) const\n{\n    return x_;\n}\n\nMatrix3d KalmanFilter::getCovariance(void) const\n{\n    return cov_x_;\n}\n\nvoid KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation)\n{\n    /* This is non-linear in theta because of the x and y elements:\n     *      x = (r + l)/2 * cos(theta + (r - l) / (2s))\n     *      y = (r + l)/2 * sin(theta + (r - l) / (2s))\n     *  theta = (r - l)/(2s)\n     * We can linearize this around the current state estimate using the\n     * Jacobians A = Jac(f, x) and W = Jac(f, u).\n     */\n    double const dlinear = (enc[1] + enc[0]) / 2;\n    double const dtheta  = (enc[1] - enc[0]) / separation;\n    double const theta_halfway = x_[2] + dtheta / 2;\n\n    Matrix3d const A = (Matrix3d() <<\n        1, 0, -dlinear * sin(theta_halfway),\n        0, 1, +dlinear * cos(theta_halfway),\n        0, 0, 1).finished();\n    Matrix<double, 3, 2> const W = (Matrix<double, 3, 2>() <<\n        +dlinear * sin(theta_halfway) + 0.5 * cos(theta_halfway),\n        -dlinear * sin(theta_halfway) + 0.5 * cos(theta_halfway),\n        -dlinear * cos(theta_halfway) + 0.5 * sin(theta_halfway),\n        +dlinear * cos(theta_halfway) + 0.5 * sin(theta_halfway),\n        -1.0 / separation,\n        +1.0 / separation).finished();\n\n    x_ += (Vector3d() <<\n            dlinear * cos(theta_halfway),\n            dlinear * sin(theta_halfway),\n    //        0).finished();\n            dtheta).finished();\n    cov_x_ = A * cov_x_ * A.transpose() + W * cov_enc * W.transpose();\n    normalize_yaw();\n}\n\nvoid KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps)\n{\n    measure(gps, cov_gps, Hgps_);\n}\n\nvoid KalmanFilter::update_compass(double compass, double cov_compass)\n{\n    // Renormalize the compass heading so the filter behaves correctly when\n    // crossing +/-pi. This prevents the heading from slowly drifting the \"long\n    // way\" around the circle (i.e. through 0 instead of +/-pi).\n    if (x_[2] - compass > M_PI) {\n        compass = compass + 2 * M_PI;\n    } else if (x_[2] - compass < -M_PI) {\n        compass = compass - 2 * M_PI;\n    }\n\n    Matrix<double, 1, 1> mat_compass, mat_cov_compass;\n    mat_compass << compass;\n    mat_cov_compass << cov_compass;\n\n    measure(mat_compass, mat_cov_compass, Hcomp_);\n    normalize_yaw();\n} \n\ntemplate <int m>\nvoid KalmanFilter::predict(Matrix<double, m, 1> u, Matrix<double, 3, 3> cov_process,\n                           Matrix<double, 3, 3> A, Matrix<double, 3, m> B)\n{\n    x_ = A * x_ + B * u;\n    cov_x_ = A * cov_x_ * A.transpose() + cov_process;\n}\n\ntemplate <int m>\nvoid KalmanFilter::measure(Matrix<double, m, 1> z, Matrix<double, m, m> cov_z,\n                           Matrix<double, m, 3> H)\n{\n    Matrix<double, 3, m> const K = cov_x_ * H.transpose() * (H * cov_x_\n                                  * H.transpose() + cov_z).inverse();\n    x_ = x_ + K * (z - H * x_);\n    cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_;\n}\n\nvoid KalmanFilter::normalize_yaw(void) {\n    x_[2] = angles::normalize_angle(x_[2]);\n}\n\n};\n", "meta": {"hexsha": "73534674f8927c3d49c2c24a1fb06767f0d1dd21", "size": 3538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/robot_kf.cc", "max_stars_repo_name": "mkoval/robot_kf", "max_stars_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T07:44:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:23:19.000Z", "max_issues_repo_path": "src/robot_kf.cc", "max_issues_repo_name": "mkoval/robot_kf", "max_issues_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "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/robot_kf.cc", "max_forks_repo_name": "mkoval/robot_kf", "max_forks_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T07:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T06:49:40.000Z", "avg_line_length": 30.5, "max_line_length": 85, "alphanum_fraction": 0.5952515546, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6779220018052418}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <sys/stat.h>\n#include <igl/readPLY.h>\n#include <igl/writePLY.h>\n#include <igl/point_mesh_squared_distance.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n\nigl::AABB<Eigen::MatrixXd,3> tree;\n\nfloat icp_step(Eigen::MatrixXd *Vmov, Eigen::MatrixXd Vref, Eigen::MatrixXi Fref)\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n\n  int i;\n  float dist = 0;\n\n  // compute closest points\n  VectorXd sqrD;\n  VectorXi I;\n  MatrixXd Vout;\n\n  igl::point_mesh_squared_distance(*Vmov, Vref, Fref, sqrD, I, Vout);\n\n  // compute rotation and translation\n  MatrixXd C = Matrix3d::Constant(0);\n  VectorXd oout = Vout.colwise().sum()/Vout.rows();\n  VectorXd omov = (*Vmov).colwise().sum()/(*Vmov).rows();\n\n  for(i=0;i<(*Vmov).rows();i++)\n    C += ((*Vmov).row(i) - omov.transpose()).transpose()\n         * (Vout.row(i) - oout.transpose());\n\n  JacobiSVD<MatrixXd> svd(C, ComputeThinU|ComputeThinV);\n  Matrix3d U = svd.matrixU();\n  Matrix3d V = svd.matrixV().transpose();\n\n  MatrixXd R = U*V;\n  MatrixXd t = omov - R*oout;\n\n  // apply rotation and translation\n  (*Vmov)*=R;\n  (*Vmov).transpose().colwise() -= t.col(0);\n\n  // check convergence\n  // angle_dist = arccos((trace(P*Q')-1)/2), P, Q rotation matrices\n  // (here, Q=I)\n  // http://www.boris-belousov.net/2016/12/01/quat-dist/\n  dist = acos((R.trace()-1)/2.0);\n  dist = dist + t.norm();\n\n  return dist;\n}\n  \nint icp(Eigen::MatrixXd Vref, Eigen::MatrixXi Fref,\n        Eigen::MatrixXd *Vmov, Eigen::MatrixXi Fmov,\n        float *diff)\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n\n  int i;\n  float dist;\n  int maxiter = 100;\n  float tol = 1e-6;\n\n  // init distance AABB tree\n  tree.init(Vref, Fref);\n\n  float dist0=-1;\n\n  for(i=0;i<maxiter;i++)\n  {\n    dist = icp_step(Vmov, Vref, Fref);\n    if(dist0<0)\n    {\n        *diff = dist;\n        printf(\"initial distance: %g\\n\", *diff);\n    }\n    else\n        *diff = fabs(dist-dist0);\n\n    if(*diff < tol)\n        break;\n\n    dist0=dist;\n  }\n  printf(\"final distance: %g (after %i iterations)\\n\", *diff, i);\n\n  return i;\n}\n\nint main(int argc, char * argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n  \n  /*\n    Register mesh mov to mesh ref\n  */\n  char *path_ref = argv[1];\n  char *path_mov = argv[2];\n  char *path_result = argv[3];\n  float diff;\n\n  struct stat info;\n  if(stat(path_ref,&info))\n      printf(\"File %s not found\\n\", path_ref);\n  if(stat(path_mov,&info))\n      printf(\"File %s not found\\n\", path_mov);\n\n  MatrixXd Vmov; // Vmov is changed\n  MatrixXd Vref;\n  MatrixXi Fmov;\n  MatrixXi Fref;\n  MatrixXd TMP1;\n  MatrixXd TMP2;\n\n  igl::readPLY(path_ref, Vref, Fref, TMP1, TMP2);\n  std::cout<<\"Ref nv, nt: \"<<Vref.rows()<<\", \"<<Fref.rows()<<std::endl;\n\n  igl::readPLY(path_mov, Vmov, Fmov, TMP1, TMP2);\n  std::cout<<\"Mov nv, nt: \"<<Vmov.rows()<<\", \"<<Fmov.rows()<<std::endl;\n  \n  int iter = icp(Vref, Fref, &Vmov, Fmov, &diff);\n  if(path_result)\n  {\n      igl::writePLY(path_result, Vmov, Fmov);\n      printf(\"iterations: %i\\n\", iter);\n  }\n  else\n      printf(\"No output path provided, nothing saved\\n\");\n\n  return 0;\n}\n", "meta": {"hexsha": "a75b3e3ce46adf168fb658055971f3a255d1e227", "size": 3139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scratch/work_roberto/icp/main.cpp", "max_stars_repo_name": "katjaq/foldgraph", "max_stars_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-25T02:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-28T11:09:14.000Z", "max_issues_repo_path": "scratch/work_roberto/icp/main.cpp", "max_issues_repo_name": "katjaq/foldgraph", "max_issues_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T08:57:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T08:57:45.000Z", "max_forks_repo_path": "scratch/work_roberto/icp/main.cpp", "max_forks_repo_name": "katjaq/foldgraph", "max_forks_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T10:32:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T08:02:55.000Z", "avg_line_length": 22.1056338028, "max_line_length": 81, "alphanum_fraction": 0.6224912392, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6779219997419054}}
{"text": "#include <iostream>\n#include <stdexcept>\n\n#include <NTL/ZZ.h>\n\nusing namespace std;\nusing namespace NTL;\n\nvoid usage(char *progname) {\n\tcout << \"This program returns the message m corresponding to \"\n\t\t\"two ciphertexts c1 = m^e1 (mod n), c2 = m^e2 (mod n).\"\n\t\t<< endl;\n\tcout << \"Usage: \" << progname << \" n e1 c1 e2 c2\" << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 6) { usage(argv[0]); return 3; }\n\n\tZZ n, e1, c1, e2, c2, m, u, v, g;\n\tn = conv<ZZ>(argv[1]);\n\te1 = conv<ZZ>(argv[2]);\n\tc1 = conv<ZZ>(argv[3]);\n\te2 = conv<ZZ>(argv[4]);\n\tc2 = conv<ZZ>(argv[5]);\n\n\t// g = u*e1 + v*e2\n\tXGCD(g, u, v, e1, e2);\n\n\tif(g != 1) { throw domain_error(\"e1 and e2 aren't coprime.\"); }\n\n\tif(u < 0) {\n\t\tInvMod(c1, c1, n);\n\t\tu *= -1;\n\t}\n\tif(v < 0) {\n\t\tInvMod(c2, c2, n);\n\t\tv *= -1;\n\t}\n\n\tMulMod(m, PowerMod(c1, u, n), PowerMod(c2, v, n), n);\n\n\tcout << m << endl;\n}\n", "meta": {"hexsha": "31022a700c4f60c1e1b5ef0a1bfd0908792b062f", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common_modulus_external.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": "common_modulus_external.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": "common_modulus_external.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": 19.5227272727, "max_line_length": 64, "alphanum_fraction": 0.5483119907, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6779219997419054}}
{"text": "#ifndef UCB_MULTIARM_BANDIT_HPP\n#define UCB_MULTIARM_BANDIT_HPP\n\n#include <stdlib.h>\n#include <assert.h>\n#include <limits>\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n\nnamespace smmap\n{\n    template <typename Generator = std::mt19937_64>\n    class UCB1Normal\n    {\n        public:\n            UCB1Normal(size_t num_bandits = 1)\n                : num_arms_(num_bandits)\n                , total_reward_(num_arms_, 0.0)\n                , sum_of_squared_reward_(num_arms_, 0.0)\n                , num_pulls_(num_arms_, 0)\n                , total_pulls_(0)\n            {}\n\n            ssize_t selectArmToPull(Generator& generator) const\n            {\n                (void)generator;\n                if (total_pulls_ == 0UL)\n                {\n                    return 0L;\n                }\n\n                const double explore_threshold = 8.0 * std::log((double)total_pulls_ + 1.0);\n                double highest_ucb = -std::numeric_limits<double>::infinity();\n                ssize_t best_arm = -1;\n                size_t lowest_num_exploration_pulls = (size_t)(-1);\n\n                for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n                {\n                    if (num_pulls_[arm_ind] < explore_threshold)\n                    {\n                        if (num_pulls_[arm_ind] < lowest_num_exploration_pulls)\n                        {\n                            best_arm = arm_ind;\n                            lowest_num_exploration_pulls = num_pulls_[arm_ind];\n                        }\n                    }\n                }\n\n                // If we found an arm that qualifies for exploration, pull that arm\n                if (best_arm != -1)\n                {\n                    return best_arm;\n                }\n\n                for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n                {\n                    assert(num_pulls_[arm_ind] > 1);\n\n                    const double average_reward = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n                    const double term1_numer = (sum_of_squared_reward_[arm_ind] - (double)num_pulls_[arm_ind] * average_reward * average_reward);\n                    const double term1_denom = (double)(num_pulls_[arm_ind] - 1);\n                    const double term1 = std::abs(term1_numer)/term1_denom;\n                    const double term2 = std::log((double)total_pulls_) / (double)num_pulls_[arm_ind];\n                    const double ucb = average_reward + std::sqrt(16.0 * term1 * term2);\n\n                    assert(std::isfinite(ucb));\n\n                    if (ucb > highest_ucb)\n                    {\n                        highest_ucb = ucb;\n                        best_arm = (ssize_t)arm_ind;\n                    }\n                }\n\n                assert(best_arm >= 0);\n                return best_arm;\n            }\n\n            bool generateAllModelActions() const\n            {\n                return false;\n            }\n\n            void updateArms(const ssize_t arm_pulled, const double reward)\n            {\n                total_reward_[(size_t)arm_pulled] += reward;\n                sum_of_squared_reward_[(size_t)arm_pulled] += reward * reward;\n                num_pulls_[(size_t)arm_pulled]++;\n                total_pulls_++;\n            }\n\n            Eigen::VectorXd getMean() const\n            {\n                Eigen::VectorXd mean((ssize_t)num_arms_);\n                for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n                {\n                    mean((ssize_t)arm_ind) = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n                }\n                return mean;\n            }\n\n            Eigen::VectorXd getUCB() const\n            {\n                Eigen::VectorXd ucb((ssize_t)num_arms_);\n                for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n                {\n                    const double average_reward = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n                    const double term1_numer = (sum_of_squared_reward_[arm_ind] - (double)num_pulls_[arm_ind] * average_reward * average_reward);\n                    const double term1_denom = (double)(num_pulls_[arm_ind] - 1);\n                    const double term1 = std::abs(term1_numer)/term1_denom;\n                    const double term2 = std::log((double)total_pulls_) / (double)num_pulls_[arm_ind];\n                    ucb((ssize_t)arm_ind) = average_reward + std::sqrt(16.0 * term1 * term2);\n                }\n                return ucb;\n            }\n\n        private:\n            size_t num_arms_;\n\n            std::vector<double> total_reward_;\n            std::vector<double> sum_of_squared_reward_;\n            std::vector<size_t> num_pulls_;\n            size_t total_pulls_;\n    };\n}\n\n#endif // UCB_MULTIARM_BANDIT_HPP\n", "meta": {"hexsha": "c07c1e7a3848f54441c1042be895917c48026e35", "size": 4784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_stars_repo_name": "UM-ARM-Lab/mab_ms", "max_stars_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T12:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:43:27.000Z", "max_issues_repo_path": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_issues_repo_name": "UM-ARM-Lab/mab_ms", "max_issues_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "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": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_forks_repo_name": "UM-ARM-Lab/mab_ms", "max_forks_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T03:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:12:23.000Z", "avg_line_length": 36.8, "max_line_length": 145, "alphanum_fraction": 0.5052257525, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6779219973745209}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2018 Basil Fierz\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#include \"problems.h\"\n\n// C++ standard library\n#include <random>\n\n// Eigen library\n#include <Eigen/Dense>\n\n// VCL\n#include <vcl/math/polardecomposition.h>\n\nvoid createRandomProblems(\n\tsize_t nr_problems,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution<float> d;\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f M;\n\t\tM << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\t\tF.at<float>(i) = M;\n\n\t\tif (R)\n\t\t{\n\t\t\tEigen::Matrix3f Rot;\n\t\t\tVcl::Mathematics::PolarDecomposition(M, Rot, nullptr);\n\t\t\tR->template at<float>(i) = Rot;\n\t\t}\n\t}\n}\n\nvoid createSymmetricProblems(\n\tsize_t nr_problems,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution<float> d;\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f M;\n\t\tM << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\t\tEigen::Matrix3f MtM = M.transpose() * M;\n\t\tF.at<float>(i) = MtM;\n\n\t\tif (R)\n\t\t{\n\t\t\tEigen::Matrix3f Rot;\n\t\t\tVcl::Mathematics::PolarDecomposition(MtM, Rot, nullptr);\n\t\t\tR->template at<float>(i) = Rot;\n\t\t}\n\t}\n}\n\nvoid createRotationProblems(\n\tsize_t nr_problems,\n\tfloat max_angle,\n\tfloat max_compression,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution<float> d;\n\tstd::uniform_real_distribution<float> a{ -max_angle, max_angle };\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f X0;\n\t\tX0 << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\n\t\t// Rotation angle\n\t\tfloat angle = a(rng);\n\n\t\t// Rotation axis\n\t\tEigen::Matrix<float, 3, 1> rot_vec;\n\t\trot_vec << d(rng), d(rng), d(rng);\n\t\trot_vec.normalize();\n\n\t\t// Rotation matrix\n\t\tEigen::Matrix3f Rot = Eigen::AngleAxis<float>{ angle, rot_vec }.toRotationMatrix();\n\t\tif (R)\n\t\t\tR->template at<float>(i) = Rot;\n\n\t\tif (max_compression > 0)\n\t\t{\n\t\t\tEigen::Matrix<float, 3, 1> scaling;\n\t\t\tscaling << (1.0f - max_compression * d(rng)), (1.0f - max_compression * d(rng)), (1.0f - max_compression * d(rng));\n\n\t\t\tEigen::JacobiSVD<Eigen::Matrix3f> svd{ Rot, Eigen::ComputeFullU | Eigen::ComputeFullV };\n\t\t\tRot *= svd.matrixV() * scaling.asDiagonal() * svd.matrixV().transpose();\n\t\t}\n\n\t\tEigen::Matrix3f X = Rot * X0;\n\t\tF.at<float>(i) = X * X0.inverse();\n\t}\n}\n\nvoid computeEigenReferenceSolution(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& ATA,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& U,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& S)\n{\n\t// Compute reference using Eigen\n\tfor (int i = 0; i < static_cast<int>(nr_problems); i++)\n\t{\n\t\tVcl::Matrix3f A = ATA.at<float>(i);\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\tU.at<float>(i) = solver.eigenvectors();\n\t\tS.at<float>(i) = solver.eigenvalues();\n\t}\n}\n", "meta": {"hexsha": "57b833375c3ca620b95b254b4e6f162db5a499eb", "size": 4392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_stars_repo_name": "bfierz/vcl", "max_stars_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T09:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T13:00:17.000Z", "max_issues_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_issues_repo_name": "bfierz/vcl", "max_issues_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2015-05-14T09:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:09:06.000Z", "max_forks_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_forks_repo_name": "bfierz/vcl", "max_forks_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-04-18T06:16:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T08:00:12.000Z", "avg_line_length": 28.1538461538, "max_line_length": 118, "alphanum_fraction": 0.6739526412, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.6778636361002347}}
{"text": "/**\n * @file\n * @brief NPDE homework \"Handling degrees of freedom (DOFs) in LehrFEM++\"\n * @author Julien Gacon\n * @date March 1st, 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"lfppdofhandling.h\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <memory>\n\n#include \"lf/assemble/assemble.h\"\n#include \"lf/base/base.h\"\n#include \"lf/geometry/geometry.h\"\n#include \"lf/mesh/mesh.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nnamespace LFPPDofHandling {\n\n/* SAM_LISTING_BEGIN_1 */\nstd::array<std::size_t, 3> countEntityDofs(\n    const lf::assemble::DofHandler &dofhandler) {\n  std::array<std::size_t, 3> entityDofs;\n\n  for(int codim = 0; codim < 3; codim++) {\n    int n = 0;\n    for(auto& entity : dofhandler.Mesh()->Entities(codim)) {\n       n += dofhandler.NumInteriorDofs(*entity);\n    }\n    entityDofs[codim] = n;\n  }\n\n  return entityDofs;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::size_t countBoundaryDofs(const lf::assemble::DofHandler &dofhandler) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  // given an entity, bd\\_flags(entity) == true, if the entity is on the\n  // boundary\n  lf::mesh::utils::AllCodimMeshDataSet<bool> bd_flags(\n      lf::mesh::utils::flagEntitiesOnBoundary(mesh));\n  std::size_t no_dofs_on_bd = 0;\n\n      for(auto& entity : dofhandler.Mesh()->Entities(1)) {\n        if(bd_flags(*entity)) {\n          no_dofs_on_bd += dofhandler.NumInteriorDofs(*entity);\n        }\n      }\n\n      for(auto& entity : dofhandler.Mesh()->Entities(2)) {\n        if(bd_flags(*entity)) {\n          no_dofs_on_bd += dofhandler.NumInteriorDofs(*entity);\n        }\n      }\n\n  return no_dofs_on_bd;\n}\n/* SAM_LISTING_END_2 */\n\n// clang-format off\n/* SAM_LISTING_BEGIN_3 */\ndouble integrateLinearFEFunction(\n    const lf::assemble::DofHandler& dofhandler,\n    const Eigen::VectorXd& mu) {\n    double I = 0;\n\n    for(auto entity : dofhandler.Mesh()->Entities(0)) {\n      auto indices = dofhandler.GlobalDofIndices(*entity);\n\n      assert(dofhandler.NumLocalDofs(*entity) == 3);\n\n      double area = lf::geometry::Volume(*entity->Geometry());\n\n      for(auto dof_idx : indices) {\n        I += area * (mu[dof_idx]) / 3.;\n      }\n\n    }\n\n  return I;\n}\n/* SAM_LISTING_END_3 */\n// clang-format on\n\n/* SAM_LISTING_BEGIN_4 */\ndouble integrateQuadraticFEFunction(const lf::assemble::DofHandler &dofhandler,\n                                    const Eigen::VectorXd &mu) {\n  double I = 0;\n\n  for(auto entity : dofhandler.Mesh()->Entities(0)) {\n    auto indices = dofhandler.GlobalDofIndices(*entity);\n\n    assert(dofhandler.NumLocalDofs(*entity) == 6);\n\n    double area = lf::geometry::Volume(*entity->Geometry());\n\n    int i = 0;\n    for(auto dof_idx : indices) {\n\n      if(i >= 3) {\n        I += area * (mu[dof_idx]) / 3.;\n      }\n\n      i++;\n    }\n\n  }\n\n  return I;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd convertDOFsLinearQuadratic(\n    const lf::assemble::DofHandler &dofh_Linear_FE,\n    const lf::assemble::DofHandler &dofh_Quadratic_FE,\n    const Eigen::VectorXd &mu) {\n  if (dofh_Linear_FE.Mesh() != dofh_Quadratic_FE.Mesh()) {\n    throw \"Underlying meshes must be the same for both DOF handlers!\";\n  }\n  std::shared_ptr<const lf::mesh::Mesh> mesh =\n      dofh_Linear_FE.Mesh();                          // get the mesh\n  Eigen::VectorXd zeta(dofh_Quadratic_FE.NumDofs());  // initialise empty zeta\n  // safety guard: always set zero if you're not sure to set every entry later\n  // on for us this shouldn't be a problem, but just to be sure\n  zeta.setZero();\n\n  for (const auto *cell : mesh->Entities(0)) {\n    // check if the spaces are actually linear and quadratic\n    //====================\n    assert(dofh_Linear_FE.NumLocalDofs(*cell) == 3);\n    assert(dofh_Quadratic_FE.NumLocalDofs(*cell) == 6);\n    //====================\n    // get the global dof indices of the linear and quadratic FE spaces, note\n    // that the vectors obey the LehrFEM++ numbering, which we will make use of\n    // lin\\_dofs will have size 3 for the 3 dofs on the nodes and\n    // quad\\_dofs will have size 6, the first 3 entries being the nodes and\n    // the last 3 the edges\n    //====================\n    auto lin_indices = dofh_Linear_FE.GlobalDofIndices(*cell);\n    auto quad_indices = dofh_Quadratic_FE.GlobalDofIndices(*cell);\n\n    for(size_t i = 0; i < 3; i++) {\n      zeta[quad_indices[i]] = mu[lin_indices[i]];\n      zeta[quad_indices[i+3]] = 0.5 * (mu[lin_indices[i]] + mu[lin_indices[(i + 1) % 3]]);\n\n      i++;\n    }\n\n    // assign the coefficients of mu to the correct entries of zeta, use\n    // the previous subproblem 2-9.a\n    //====================\n  }\n  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "1405d7150b0b4697322d3b74dd32b433f82a1349", "size": 4692, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.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/LFPPDofHandling/mysolution/lfppdofhandling.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/LFPPDofHandling/mysolution/lfppdofhandling.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.6097560976, "max_line_length": 90, "alphanum_fraction": 0.6357630009, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6778154748585311}}
{"text": "#include <algorithm>\n#include <dissimilaritymatrix.h>\n\n#include <iostream>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid DissimilarityMatrix::setNumItems(int count)\n{\n    this->_numItems = count;\n}\n\nvoid DissimilarityMatrix::setDiffVal(int id_0, int id_1, double val)\n{\n    int a = std::min(id_0, id_1);\n    int b = std::max(id_0, id_1);\n\n    this->_diffVals[std::tuple<int, int>(a, b)] = val;\n}\n\ndouble DissimilarityMatrix::getDiffVal(int id_0, int id_1)\n{\n    int a = std::min(id_0, id_1);\n    int b = std::max(id_0, id_1);\n\n    return this->_diffVals[std::tuple<int, int>(a, b)];\n}\n\nstd::vector< std::shared_ptr<DataNode> > DissimilarityMatrix::getEigenDecomp(int order)\n{\n    std::vector< std::shared_ptr<DataNode> > ret;\n\n    MatrixXd A(this->_numItems, this->_numItems);\n\n    for (int i = 0; i < this->_numItems; ++i)\n    {\n        for (int j = 0; j < this->_numItems; ++j)\n        {\n            auto v = this->getDiffVal(i, j);\n            if (v < 0)\n            {\n                v = 10;\n            }\n\n            A(i, j) = v;\n        }\n    }\n\n     //cout << \"The dissimilarity matrix is:\" << endl << A << endl << endl;\n\n    // http://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html\n    SelfAdjointEigenSolver<MatrixXd> es(A);\n    MatrixXd V = es.eigenvectors();\n    // cout << \"The matrix of eigenvectors, V, is:\" << endl << V << endl << endl;\n\n    for (int i = 0; i < this->_numItems; ++i)\n    {\n        auto t = std::make_shared<DataNode>();\n        t->id = i;\n        for (int o = 0; o < order; ++o)\n        {\n            double v = (o < this->_numItems) ? V(i, o) : 0.0;\n            t->dataSet.push_back(v);\n        }\n        ret.push_back(t);\n    }\n\n    return ret;\n}\n\n", "meta": {"hexsha": "53bd7ec16302d8ab018a9aa6ba96733fd9c6ed18", "size": 1758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dissimilaritymatrix.cpp", "max_stars_repo_name": "arturo-mayorga/isomap", "max_stars_repo_head_hexsha": "83e1f2f83fa66395fa14753117dd05dc9c7aee81", "max_stars_repo_licenses": ["MIT"], "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/dissimilaritymatrix.cpp", "max_issues_repo_name": "arturo-mayorga/isomap", "max_issues_repo_head_hexsha": "83e1f2f83fa66395fa14753117dd05dc9c7aee81", "max_issues_repo_licenses": ["MIT"], "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/dissimilaritymatrix.cpp", "max_forks_repo_name": "arturo-mayorga/isomap", "max_forks_repo_head_hexsha": "83e1f2f83fa66395fa14753117dd05dc9c7aee81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-23T07:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-23T07:16:18.000Z", "avg_line_length": 23.7567567568, "max_line_length": 87, "alphanum_fraction": 0.5648464164, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6777944292698692}}
{"text": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <fstream>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"../include/core/config.hpp\"\n\n\nvoid eval_vshape_RT0_refEl(const double x, const double y,\n                           DenseMatrix& vshape)\n{\n    int ndofs = 3;\n    vshape.SetSize(ndofs, 2);\n    vshape(0,0) = x  ; vshape(0,1) = y-1;\n    vshape(1,0) = x  ; vshape(1,1) = y  ;\n    vshape(2,0) = x-1; vshape(2,1) = y;\n}\n\nvoid eval_gradvshape_RT0_refEl(const double, const double,\n                               DenseTensor& gradvshape)\n{\n    int ndofs = 3;\n    gradvshape.SetSize(2,2,ndofs);\n    gradvshape = 0;\n\n    gradvshape(0,0,0) = gradvshape(1,1,0) = 1;\n    gradvshape(0,0,1) = gradvshape(1,1,1) = 1;\n    gradvshape(0,0,2) = gradvshape(1,1,2) = 1;\n}\n\nclass RT1_refEl\n{\npublic:\n    RT1_refEl ()\n    {\n        double c = 1./3.;\n\n        Vector xi(2);\n        xi(0) = (1-1./sqrt(3))/2;\n        xi(1) = (1+1./sqrt(3))/2;\n\n        nodes.SetSize(8,2);\n        T.SetSize(8, 8);\n\n        // set nodes\n        nodes(0,0) = xi(0); nodes(0,1) = 0;\n        nodes(1,0) = xi(1); nodes(1,1) = 0;\n\n        nodes(2,0) = xi(1); nodes(2,1) = xi(0);\n        nodes(3,0) = xi(0); nodes(3,1) = xi(1);\n\n        nodes(4,0) = 0; nodes(4,1) = xi(1);\n        nodes(5,0) = 0; nodes(5,1) = xi(0);\n\n        nodes(6,0) = c; nodes(6,1) = c;\n        nodes(7,0) = c; nodes(7,1) = c;\n\n        // set matrix T\n        T = 0.0;\n\n        // dofs 0 and 1\n        for (int i=0; i<=1; i++)\n        {\n            T(1,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1);\n            T(3,i) = -(2*nodes(i,0)-1);\n            T(5,i) = -(2*nodes(i,1)-1);\n            T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,1) - c);\n            T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,1) - c);\n        }\n\n        // dofs 2 and 3\n        for (int i=2; i<=3; i++)\n        {\n            T(0,i) = T(1,i) = (2*(1 - nodes(i,0) - nodes(i,1))-1);\n            T(2,i) = T(3,i) = (2*nodes(i,0)-1);\n            T(4,i) = T(5,i) = (2*nodes(i,1)-1);\n            T(6,i) = (2*nodes(i,1)-1)*(nodes(i,0) + nodes(i,1) - 2*c);\n            T(7,i) = (2*nodes(i,0)-1)*(nodes(i,0) + nodes(i,1) - 2*c);\n        }\n\n        // dofs 4 and 5\n        for (int i=4; i<=5; i++)\n        {\n            T(0,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1);\n            T(2,i) = -(2*nodes(i,0)-1);\n            T(4,i) = -(2*nodes(i,1)-1);\n            T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,0) - c);\n            T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,0) - c);\n        }\n\n        // dofs 6 and 7\n        int i=6;\n        {\n            T(1,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1);\n            T(3,i) = -(2*nodes(i,0)-1);\n            T(5,i) = -(2*nodes(i,1)-1);\n            T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,1) - c);\n            T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,1) - c);\n\n            i++;\n            T(0,i) = -(2*(1 - nodes(i,0) - nodes(i,1))-1);\n            T(2,i) = -(2*nodes(i,0)-1);\n            T(4,i) = -(2*nodes(i,1)-1);\n            T(6,i) = -(2*nodes(i,1)-1)*(nodes(i,0) - c);\n            T(7,i) = -(2*nodes(i,0)-1)*(nodes(i,0) - c);\n        }\n\n        /*for (int k=0; k<T.NumRows(); k++) {\n            for (int l=0; l<T.NumCols(); l++)\n                std::cout << T(k,l) << \" \";\n            std::cout << \"\\n\";\n        }*/\n\n        Ti.Factor(T);\n\n        /*DenseMatrix invT;\n        Ti.GetInverseMatrix(invT);\n        for (int k=0; k<T.NumRows(); k++) {\n            for (int l=0; l<T.NumCols(); l++)\n                std::cout << invT(k,l) << \" \";\n            std::cout << \"\\n\";\n        }*/\n    }\n\n    void eval_vshape(const double x, const double y,\n                     DenseMatrix &vshape)\n    {\n        double c = 1./3.;\n\n        int ndofs = 8;\n        DenseMatrix vshape_buf(ndofs, 2);\n        vshape_buf = 0.0;\n\n        vshape_buf(0,0) = (2*(1-x-y)-1);\n        vshape_buf(1,1) = (2*(1-x-y)-1);\n\n        vshape_buf(2,0) = (2*x-1);\n        vshape_buf(3,1) = (2*x-1);\n\n        vshape_buf(4,0) = (2*y-1);\n        vshape_buf(5,1) = (2*y-1);\n\n        vshape_buf(6,0) = (2*y-1)*(x - c);\n        vshape_buf(6,1) = (2*y-1)*(y - c);\n        vshape_buf(7,0) = (2*x-1)*(x - c);\n        vshape_buf(7,1) = (2*x-1)*(y - c);\n\n        Ti.Mult(vshape_buf, vshape);\n    }\n\nprivate:\n    DenseMatrix nodes;\n    DenseMatrix T;\n    DenseMatrixInverse Ti;\n};\n\n\nTEST(RTspace, vshape_deg0_test1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem1\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    int j=0; // only 1 element in the mesh\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n\n        DenseMatrix vshape(3,2);\n        DenseMatrix true_vshape(3,2);\n\n        auto vshape_fn = [](Vector &x)\n        {\n            DenseMatrix vshape(3,2);\n            vshape(0,0) = x(0)-2;\n            vshape(0,1) = x(1);\n\n            vshape(1,0) = x(0)-2;\n            vshape(1,1) = x(1)-1;\n\n            vshape(2,0) = x(0);\n            vshape(2,1) = x(1);\n\n            vshape *= 0.5;\n\n            return vshape;\n        };\n\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcVShape(*trans, true_vshape);\n\n            Vector eip;\n            trans->Transform(ip, eip);\n            vshape = vshape_fn(eip);\n\n            /*std::cout << \"\\n\\nvshape:\" << std::endl;\n            for (int k=0; k<vshape.NumRows(); k++) {\n                for (int l=0; l<vshape.NumCols(); l++)\n                    std::cout << vshape(k,l) << \" \";\n                std::cout << \"\\n\";\n            }\n\n            std::cout << \"\\n\\nTrue vshape:\" << std::endl;\n            for (int k=0; k<vshape.NumRows(); k++) {\n                for (int l=0; l<vshape.NumCols(); l++)\n                    std::cout << true_vshape(k,l) << \" \";\n                std::cout << \"\\n\";\n            }*/\n\n            double TOL = 1E-10;\n            true_vshape -= vshape;\n            ASSERT_LE(true_vshape.FNorm(), TOL);\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\nTEST(RTspace, gradvshape_deg0)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem1\";\n    Mesh mesh(mesh_file.c_str());\n    assert(mesh.GetNE() == 1);\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    int ndofs = 3;\n    auto gradvshape_fn = [](Vector &)\n    {\n        DenseTensor gradvshape(2,2,3);\n        gradvshape = 0.0;\n        gradvshape(0,0,0) = 0.5; gradvshape(1,1,0) = 0.5;\n        gradvshape(0,0,1) = 0.5; gradvshape(1,1,1) = 0.5;\n        gradvshape(0,0,2) = 0.5; gradvshape(1,1,2) = 0.5;\n        return gradvshape;\n    };\n\n    int j=0;\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n\n        DenseTensor true_gradvshape(2,2,3);\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcGradVShape(*trans, true_gradvshape);\n\n            Vector eip;\n            trans->Transform(ip, eip);\n            auto gradvshape = gradvshape_fn(eip);\n            for (int m=0; m < ndofs; m++)\n            {\n                /*std::cout << \"\\n\\ngradvshape:\" << std::endl;\n                for (int k=0; k<gradvshape(m).NumRows(); k++) {\n                    for (int l=0; l<gradvshape(m).NumCols(); l++)\n                        std::cout << gradvshape(k,l,m) << \" \";\n                    std::cout << \"\\n\";\n                }\n\n                std::cout << \"\\n\\ntrue_gradvshape:\" << std::endl;\n                for (int k=0; k<gradvshape(m).NumRows(); k++) {\n                    for (int l=0; l<gradvshape(m).NumCols(); l++)\n                        std::cout << true_gradvshape(k,l,m) << \" \";\n                    std::cout << \"\\n\";\n                }*/\n\n                true_gradvshape(m) -= gradvshape(m);\n                double TOL = 1E-10;\n                ASSERT_LE(true_gradvshape(m).FNorm(), TOL);\n            }\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\nTEST(RTspace, vshape_deg1)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem2\";\n    Mesh mesh(mesh_file.c_str());\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(1, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    for (int j=0; j<1; j++)\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n\n        DenseMatrix vshape(8,2);\n        DenseMatrix true_vshape(8,2);\n\n        RT1_refEl rt1_refEl;\n\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            //fe->CalcVShape(trans->GetIntPoint(), true_vshape);\n            fe->CalcVShape(*trans, true_vshape);\n\n            DenseMatrix vshape_buf;\n            rt1_refEl.eval_vshape(ip.x, ip.y, vshape_buf);\n            MultABt(vshape_buf, trans->Jacobian(), vshape);\n            vshape *= (1./trans->Weight());\n\n            /*std::cout << \"\\n\\nvshape:\" << std::endl;\n            for (int k=0; k<vshape.NumRows(); k++) {\n                for (int l=0; l<vshape.NumCols(); l++)\n                    std::cout << vshape(k,l) << \" \";\n                std::cout << \"\\n\";\n            }\n\n            std::cout << \"\\n\\nTrue vshape:\" << std::endl;\n            for (int k=0; k<vshape.NumRows(); k++) {\n                for (int l=0; l<vshape.NumCols(); l++)\n                    std::cout << true_vshape(k,l) << \" \";\n                std::cout << \"\\n\";\n            }*/\n\n            double TOL = 1E-10;\n            true_vshape -= vshape;\n            ASSERT_LE(true_vshape.FNorm(), TOL);\n            //std::cout << \"\\nError: \" << true_vshape.FNorm() << std::endl;\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}\n\n\n/*TEST(RTspace, gradvshape_deg0)\n{\n    std::string input_dir = \"../input/\";\n    const std::string mesh_file = input_dir+\"tri_elem2\";\n    Mesh mesh(mesh_file.c_str());\n\n    FiniteElementCollection *hdiv_coll\n            = new RT_FECollection(0, mesh.Dimension());\n    FiniteElementSpace *R_space\n            = new FiniteElementSpace(&mesh, hdiv_coll);\n\n    int ndofs = 3;\n    int dim = 2;\n\n    auto gradvshape_fn = [](Vector &x)\n    {\n        DenseTensor gradvshape(3,2,2);\n        gradvshape = 0.0;\n        gradvshape(0,0,0) = 0.5; gradvshape(0,1,1) = 0.5;\n        gradvshape(1,0,0) = 0.5; gradvshape(1,1,1) = 0.5;\n        gradvshape(2,0,0) = 0.5; gradvshape(2,1,1) = 0.5;\n        return gradvshape;\n    };\n\n    for (int j=0; j<1; j++)\n    {\n        const FiniteElement *fe = R_space->GetFE(j);\n        ElementTransformation *trans\n                = R_space->GetElementTransformation(j);\n\n        const IntegrationRule *ir = &IntRules.Get(fe->GetGeomType(), 2);\n\n        //DenseTensor gradvshape(2,2,3);\n        DenseTensor true_gradvshape(2,2,3);\n\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            trans->SetIntPoint(&ip);\n            fe->CalcGradVShape(*trans, true_gradvshape);\n\n            DenseMatrix J, Jinv;\n            DenseTensor gradvshape_buf;\n            J = trans->Jacobian();\n            Jinv = trans->InverseJacobian();\n            eval_gradvshape_RT0_refEl(ip.x, ip.y, gradvshape_buf);\n\n            for (int m=0; m < ndofs; m++)\n            {\n                // apply Piola transformation\n                // gradvshape = |J|^{-1}*J * gradvshape_buf * invJ\n                DenseMatrix tempMat(dim, dim);\n                Mult(J, gradvshape_buf(m), tempMat);\n                Mult(tempMat, Jinv, gradvshape(m));\n                gradvshape(m) *= (1.0 / trans->Weight());\n\n                true_gradvshape(m) -= gradvshape(m);\n                double TOL = 1E-10;\n                ASSERT_LE(true_gradvshape(m).FNorm(), TOL);\n            }\n        }\n    }\n\n    delete hdiv_coll;\n    delete R_space;\n}*/\n", "meta": {"hexsha": "f5cd7fb74e0265518145505448a83ad93a286354", "size": 12720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_RTspace.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_RTspace.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_RTspace.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["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.1075514874, "max_line_length": 75, "alphanum_fraction": 0.4744496855, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810407096791, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6777791239257616}}
{"text": "#ifndef GEOUTILS_HPP\n#define GEOUTILS_HPP\n\n#include <Eigen/Eigen>\n#include <cfloat>\n#include <chrono>\n#include <cstdint>\n#include <set>\n\n#include \"quickhull.hpp\"\n#include \"sdlp.hpp\"\n\nnamespace geoutils\n{\n\n  // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n  // The outter_normal is assumed to be NORMALIZED\n  inline bool findInterior(const Eigen::MatrixXd &hPoly,\n                           Eigen::Vector3d &interior)\n  {\n    int m = hPoly.cols();\n\n    Eigen::MatrixXd A(m, 4);\n    Eigen::VectorXd b(m), c(4), x(4);\n    A.leftCols<3>() = hPoly.topRows<3>().transpose();\n    A.rightCols<1>().setConstant(1.0);\n    b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum().transpose();\n    c.setZero();\n    c(3) = -1.0;\n\n    double minmaxsd = sdlp::linprog(c, A, b, x);\n    interior = x.head<3>();\n\n    return minmaxsd < 0.0 && !std::isinf(minmaxsd);\n  }\n\n  inline double findInteriorDist(const Eigen::MatrixXd &hPoly,\n                                 Eigen::Vector3d &interior)\n  {\n    int m = hPoly.cols();\n\n    Eigen::MatrixXd A(m, 4);\n    Eigen::VectorXd b(m), c(4), x(4);\n    A.leftCols<3>() = hPoly.topRows<3>().transpose();\n    A.rightCols<1>().setConstant(1.0);\n    b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum().transpose();\n    c.setZero();\n    c(3) = -1.0;\n\n    double minmaxsd = sdlp::linprog(c, A, b, x);\n    interior = x.head<3>();\n\n    return -minmaxsd;\n  }\n\n  struct filterLess\n  {\n    inline bool operator()(const Eigen::Vector3d &l,\n                           const Eigen::Vector3d &r)\n    {\n      return l(0) < r(0) ||\n             (l(0) == r(0) &&\n              (l(1) < r(1) ||\n               (l(1) == r(1) &&\n                l(2) < r(2))));\n    }\n  };\n\n  inline void filterVs(const Eigen::MatrixXd &rV,\n                       const double &epsilon,\n                       Eigen::MatrixXd &fV)\n  {\n    double mag = std::max(fabs(rV.maxCoeff()), fabs(rV.minCoeff()));\n    double res = mag * std::max(fabs(epsilon) / mag, DBL_EPSILON);\n    std::set<Eigen::Vector3d, filterLess> filter;\n    fV = rV;\n    int offset = 0;\n    Eigen::Vector3d quanti;\n    for (int i = 0; i < rV.cols(); i++)\n    {\n      quanti = (rV.col(i) / res).array().round();\n      if (filter.find(quanti) == filter.end())\n      {\n        filter.insert(quanti);\n        fV.col(offset) = rV.col(i);\n        offset++;\n      }\n    }\n    fV = fV.leftCols(offset).eval();\n    return;\n  }\n\n  // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n  // The outter_normal is assumed to be NORMALIZED\n  // proposed epsilon is 1.0e-6\n  inline void enumerateVs(const Eigen::MatrixXd &hPoly,\n                          const Eigen::Vector3d &inner,\n                          Eigen::MatrixXd &vPoly,\n                          const double epsilon = 1.0e-6)\n  {\n    Eigen::RowVectorXd b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum() -\n                           inner.transpose() * hPoly.topRows<3>();\n    Eigen::MatrixXd A = hPoly.topRows<3>().array().rowwise() / b.array();\n\n    quickhull::QuickHull<double> qh;\n    double qhullEps = std::min(epsilon, quickhull::defaultEps<double>());\n    // CCW is false because the normal in quickhull towards interior\n    const auto cvxHull = qh.getConvexHull(A.data(), A.cols(), false, true, qhullEps);\n    const auto &idBuffer = cvxHull.getIndexBuffer();\n    int hNum = idBuffer.size() / 3;\n    Eigen::MatrixXd rV(3, hNum);\n    Eigen::Vector3d normal, point, edge0, edge1;\n    for (int i = 0; i < hNum; i++)\n    {\n      point = A.col(idBuffer[3 * i + 1]);\n      edge0 = point - A.col(idBuffer[3 * i]);\n      edge1 = A.col(idBuffer[3 * i + 2]) - point;\n      normal = edge0.cross(edge1); //cross in CW gives an outter normal\n      rV.col(i) = normal / normal.dot(point);\n    }\n    filterVs(rV, epsilon, vPoly);\n    vPoly = (vPoly.array().colwise() + inner.array()).eval();\n    return;\n  }\n\n  // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n  // The outter_normal is assumed to be NORMALIZED\n  // proposed epsilon is 1.0e-6\n  inline bool enumerateVs(const Eigen::MatrixXd &hPoly,\n                          Eigen::MatrixXd &vPoly,\n                          const double epsilon = 1.0e-6)\n  {\n    Eigen::Vector3d inner;\n    if (findInterior(hPoly, inner))\n    {\n      enumerateVs(hPoly, inner, vPoly, epsilon);\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n\n} // namespace geoutils\n\n#endif", "meta": {"hexsha": "383a0943b4f61f286488f863d45cb3c339a407d0", "size": 4433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/std-trees", "max_stars_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T08:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T09:54:28.000Z", "max_issues_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_issues_repo_name": "ZJU-FAST-Lab/std-trees", "max_issues_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:03:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:03:24.000Z", "max_forks_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_forks_repo_name": "ZJU-FAST-Lab/std-trees", "max_forks_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-03-12T06:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:18:02.000Z", "avg_line_length": 30.156462585, "max_line_length": 99, "alphanum_fraction": 0.5673358899, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6776621571002216}}
{"text": "#include <fstream>\n#include <iostream>\n#include <experimental/filesystem>\n#include <stdio.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include \"../tasks.hh\"\n#include \"../classes/BinnedTypedMatrix.hh\"\n\nnamespace fs = std::experimental::filesystem;\n\nusing namespace EMC;\n\nusing namespace boost::numeric::ublas;\n\nint EMC::invert(bool forceOverwrite, std::string input, std::string output) {\n\n\tif (!forceOverwrite && fs::exists(output)) {\n\t\tstd::cout << \"Output file already exists, use -f to force overwrite.\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream infile(input);\n\tBinnedTypedMatrix inputMatrix = BinnedTypedMatrix::readFromFile(infile);\n\tinfile.close();\n\n\tBinnedTypedMatrix newMat(inputMatrix.columnIndex, inputMatrix.rowIndex, inputMatrix.matType);\n\n\ttypedef permutation_matrix<std::size_t> pmatrix;\n\t// create a working copy of the input\n\tmatrix<ValueError> A(inputMatrix.m);\n\t// create a permutation matrix for the LU-factorization\n\tpmatrix pm(A.size1());\n\t// perform LU-factorization\n\tint res = lu_factorize(A,pm);\n\tif( res != 0 )\n\t\treturn false;\n\t// create identity matrix of \"inverse\"\n\tnewMat.m.assign(identity_matrix<ValueError>(A.size1()));\n\t// backsubstitute to get the inverse\n\tlu_substitute(A, pm, newMat.m);\n\n    std::ofstream outputF(output);\n    newMat.writeToFile(outputF);\n    outputF.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "45ae4b2bbc6a387c0e103fafce0bedae94b865e8", "size": 1588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tasks/invert.cpp", "max_stars_repo_name": "pixel-toolbox/error-matrix-calculation", "max_stars_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "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/tasks/invert.cpp", "max_issues_repo_name": "pixel-toolbox/error-matrix-calculation", "max_issues_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "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/tasks/invert.cpp", "max_forks_repo_name": "pixel-toolbox/error-matrix-calculation", "max_forks_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "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.3571428571, "max_line_length": 94, "alphanum_fraction": 0.7405541562, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6776621532488841}}
{"text": "\n#include <Eigen/Geometry>\n#include <iostream>\n\nint main()\n{\n  Eigen::Isometry3d original = Eigen::Isometry3d::Identity();\n  original.translate(1.414214*Eigen::Vector3d::UnitY());\n  original.rotate(Eigen::AngleAxisd(45.0*M_PI/180.0, Eigen::Vector3d::UnitZ()));\n\n  std::cout << \"original:\\n\" << original.matrix() << \"\\n\" << std::endl;\n\n  Eigen::Isometry3d cycle1 = Eigen::Isometry3d::Identity();\n  cycle1.translate(1.414214*Eigen::Vector3d::UnitY());\n  cycle1.rotate(Eigen::AngleAxisd(90*M_PI/180.0, Eigen::Vector3d::UnitX()));\n  cycle1.rotate(Eigen::AngleAxisd(45.0*M_PI/180.0, Eigen::Vector3d::UnitY()));\n\n  std::cout << \"cycle 1:\\n\" << cycle1.matrix() << \"\\n\" << std::endl;\n\n  Eigen::Isometry3d diff_front = cycle1 * original.inverse();\n  std::cout << \"diff_front:\\n\" << diff_front.matrix() << \"\\n\" << std::endl;\n\n  Eigen::Isometry3d diff_back = original.inverse() * cycle1;\n  std::cout << \"diff_back:\\n\" << diff_back.matrix() << \"\\n\" << std::endl;\n\n  Eigen::Isometry3d x_90 = Eigen::Isometry3d::Identity();\n  x_90.rotate(Eigen::AngleAxisd(90.0*M_PI/180.0, Eigen::Vector3d::UnitX()));\n  std::cout << \"x_90:\\n\" << x_90.matrix() << \"\\n\" << std::endl;\n}\n", "meta": {"hexsha": "055cf038209516f9d82d96cc87845841d713665d", "size": 1153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dart/matrix.cpp", "max_stars_repo_name": "mxgrey/sandbox", "max_stars_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "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": "dart/matrix.cpp", "max_issues_repo_name": "mxgrey/sandbox", "max_issues_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "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": "dart/matrix.cpp", "max_forks_repo_name": "mxgrey/sandbox", "max_forks_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "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.4333333333, "max_line_length": 80, "alphanum_fraction": 0.6539462272, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6776210815327447}}
{"text": "/*\nDemonstrate the Eigen automatic differentiation module by training a multilayer perceptron (fully-connected feedforward neural-network).\nPython3.8 and matplotlib are used for plotting the results.\nCompile with:\n    g++ eigen3_autodiff.cpp -o eigen3_autodiff -std=c++11 -O3 -ffast-math -I /usr/include/eigen3/ -I /usr/local/include/matplotlib-cpp.h -I /usr/include/python3.8 -l python3.8\n    ./eigen3_autodiff 0.01 5  # step hidden_layer1_size hidden_layer2_size ...\n*/\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/AutoDiff>\n#include \"matplotlibcpp.h\"\nnamespace pyplot = matplotlibcpp;\n\n////////////////////////////////////////////////// ALIASES\n\nusing Jet = Eigen::AutoDiffScalar<Eigen::VectorXd>;                // real number with many dual parts\nusing Jetvec = Eigen::Matrix<Jet, Eigen::Dynamic, 1>;              // vector of jets\nusing Jetmat = Eigen::Matrix<Jet, Eigen::Dynamic, Eigen::Dynamic>; // matrix of jets\n\n////////////////////////////////////////////////// HELPERS\n\n// Returns a random real uniform on [-1, 1]\ninline double randf();\n\n// Returns a vector of just the real parts of the given jet vector\ninline Eigen::VectorXd reals(Jetvec const& jv);\n\n// Pulls scalar data embedded in Eigen objects out to plain doubles\ninline std::vector<double> extract_values(std::vector<Eigen::Matrix<double, 1, 1>> const& vec_eig);\n\n////////////////////////////////////////////////// MAIN CLASS\n\nclass MLP {\n    std::vector<int> const dims; // network dimensionalities (input_size, hidden_layer1_size, ..., output_size)\n    std::vector<Jetmat> weights; // container of weight matrices\n    std::vector<Jetvec> biases; // container of bias vectors\n    std::vector<Jet*> params; // pointers to each individual parameter\n\npublic:\n    MLP(std::vector<int> const& dims) :\n        dims(dims),\n        weights(dims.size()-1),\n        biases(dims.size()-1) {\n        // Parse the dims architecture to count up the parameters\n        int n_params = 0;\n        for(int layer=0; layer<weights.size(); ++layer) {\n            weights[layer] = Jetmat(dims[layer+1], dims[layer]);\n            biases[layer] = Jetvec(dims[layer+1]);\n            n_params += weights[layer].size() + biases[layer].size();\n        }\n        // Initialize parameters with random reals and orthogonal basis on the duals\n        int param_id = 0;\n        for(Jetmat & W : weights) {\n            for(int col=0; col<W.cols(); ++col) {\n                for(int row=0; row<W.rows(); ++row) {\n                    W(row, col) = Jet(randf(), n_params, param_id); // (value, number_of_dual_parts, which_dual_part)\n                    params.push_back(&W(row, col));\n                    ++param_id;\n                }\n            }\n        }\n        for(Jetvec & b : biases) {\n            for(int row=0; row<b.rows(); ++row) {\n                b(row) = Jet(randf(), n_params, param_id);\n                params.push_back(&b(row));\n                ++param_id;\n            }\n        }\n        assert(params.size() == n_params);\n    }\n\n    ////////////////////////////////////////////////// GETTERS\n\n    inline std::vector<int> get_dims() const {\n        return dims;\n    }\n\n    inline std::vector<Jetmat> get_weights() const {\n        return weights;\n    }\n\n    inline std::vector<Jetvec> get_biases() const {\n        return biases;\n    }\n\n    ////////////////////////////////////////////////// WORKERS\n\n    // Returns the sigmoid function of a given scalar jet\n    inline Jet neuron(Jet const& x) const {\n        return pow(Jet(1)+exp(-x), -1);\n    }\n\n    // Returns the jet vector MLP output corresponding to the given real input vector\n    template <class D>\n    inline Jetvec feedforward(Eigen::MatrixBase<D> const& input) const {\n        Jetvec act = input.template cast<Jet>();\n        for(int layer=0; layer<weights.size()-1; ++layer) {\n            act = weights[layer]*act;\n            act += biases[layer]; // bit of Eigen weirdness, this has to be a separate statement\n            for(int i=0; i<act.size(); ++i) act(i) = neuron(act(i));\n        }\n        return weights[weights.size()-1]*act + biases[biases.size()-1]; // don't saturate last layer\n    }\n\n    // Calls feedforward on each input in an input set to produce the MLP's corresponding output set\n    template <class V>\n    inline std::vector<V> feedforward(std::vector<V> const& input_set) const {\n        std::vector<V> output_set;\n        for(V const& input : input_set) {\n            output_set.push_back(reals(feedforward(input)));\n        }\n        return output_set;\n    }\n\n    // Common quadratic cost function for a single input-output pair\n    template <class D>\n    Jet inline cost_function(Eigen::MatrixBase<D> const& input, Eigen::MatrixBase<D> const& output) const {\n        Jetvec err = output.template cast<Jet>() - feedforward(input);\n        return err.dot(err);\n    }\n\n    // Cost function summed over an entire input-output pair batch\n    template <class V>\n    Jet inline cost_function(std::vector<V> const& input_set, std::vector<V> const& output_set) const {\n        Jet cost(0);\n        for(int i=0; i<input_set.size(); ++i) {\n            cost += cost_function(input_set[i], output_set[i]);\n        }\n        return cost;\n    }\n\n    // Stochastic gradient descent\n    template <class V>\n    void train(std::vector<V> const& input_set, std::vector<V> const& output_set,\n               double step, double tol=1e-5, int max_epoch=10000) {\n        assert(input_set.size() == output_set.size());\n        std::cout << \"Training with step-size \" << step << \"...\" << std::endl;\n        std::vector<int> ordering;\n        for(int i=0; i<input_set.size(); ++i) ordering.push_back(i);\n        double last_epoch_cost = std::numeric_limits<double>::infinity();\n        int epoch = 0;\n        while(epoch < max_epoch) {\n            double epoch_cost = 0;\n            for(int i=0; i<input_set.size(); ++i) {\n                Jet cost = cost_function(input_set[ordering[i]], output_set[ordering[i]]);\n                epoch_cost += cost.value();\n                auto dp = (-step*cost.derivatives()).eval();\n                for(int i=0; i<params.size(); ++i) *params[i] += dp(i);\n            }\n            if(!(epoch % 100)) std::cout << \"    epoch \" << epoch << \": \" << epoch_cost << std::endl;\n            if(fabs(epoch_cost-last_epoch_cost) < tol) break;\n            std::random_shuffle(ordering.begin(), ordering.end());\n            last_epoch_cost = epoch_cost;\n            ++epoch;\n        }\n        std::cout << \"Finished training on epoch \" << epoch << \"/\" << max_epoch << std::endl;\n    }\n};\n\n////////////////////////////////////////////////// MAIN EXECUTABLE\n\nint main(int argc, char** argv) {\n    if(argc < 3) {\n        std::cout << \"Please pass in a step-size and the size of each hidden layer!\" << std::endl;\n        return 1;\n    }\n\n    // We will make a fixed set of data within this code for now for simplicity\n    using Edouble = Eigen::Matrix<double, 1, 1>;\n    std::vector<Edouble> input_set;\n    std::vector<Edouble> output_set;\n    for(double val=-10; val<=10; val+=0.3) input_set.push_back(Edouble(val));\n    for(Edouble const& input : input_set) output_set.push_back(Edouble(5*exp(-input(0)*input(0))) +\n                                                               Edouble(2.5*exp(-pow(input(0)-3, 2))) +\n                                                               Edouble(0.05*(randf())));\n\n    // Construct and train our MLP from user choices\n    std::vector<int> dims;\n    dims.push_back(input_set[0].size());\n    for(int i=2; i<argc; ++i) {\n        int dim = atoi(argv[i]);\n        assert(dim > 0);\n        dims.push_back(dim);\n    }\n    dims.push_back(output_set[0].size());\n    std::cout << \"MLP Layout: \";\n    for(int dim : dims) std::cout << dim << ' ';\n    std::cout << std::endl;\n    MLP mlp(dims);\n    mlp.train(input_set, output_set, atof(argv[1]));\n\n    // Evaluate fit\n    std::vector<Edouble> fine_input_set;\n    for(double val=-10; val<=10; val+=0.005) fine_input_set.push_back(Edouble(val));\n    auto mlp_output_set = mlp.feedforward(fine_input_set);\n    std::cout << \"Plotting results...\" << std::endl;\n    pyplot::named_plot(\"data\", extract_values(input_set), extract_values(output_set), \"g--\");\n    pyplot::named_plot(\"fit\", extract_values(fine_input_set), extract_values(mlp_output_set), \"k\");\n    pyplot::legend();\n    std::cout << \"Close plots to finish...\" << std::endl;\n    pyplot::show();\n\n    return 0;\n}\n\n////////////////////////////////////////////////// OTHER IMPLEMENTATION DETAILS\n\ninline double randf() {\n    return 2*Eigen::MatrixXd::Random(1, 1)(0) - 1;\n}\n\ninline Eigen::VectorXd reals(Jetvec const& jv) {\n    Eigen::VectorXd v(jv.size());\n    for(int i=0; i<v.size(); ++i) v(i) = jv(i).value();\n    return v;\n}\n\ninline std::vector<double> extract_values(std::vector<Eigen::Matrix<double, 1, 1>> const& vec_eig) {\n    std::vector<double> vec(vec_eig.size());\n    for(int i=0; i<vec.size(); ++i) vec[i] = vec_eig[i](0);\n    return vec;\n}\n", "meta": {"hexsha": "5533be6bfc1fc7d4141d1084f99253a71f2bfee0", "size": 8968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen3_autodiff.cpp", "max_stars_repo_name": "jnez71/misc", "max_stars_repo_head_hexsha": "397ac0b8e3bccec4daa73db8963bb0510eebebfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-12T21:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-02T16:05:08.000Z", "max_issues_repo_path": "tests/eigen3_autodiff.cpp", "max_issues_repo_name": "jnez71/misc", "max_issues_repo_head_hexsha": "397ac0b8e3bccec4daa73db8963bb0510eebebfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/eigen3_autodiff.cpp", "max_forks_repo_name": "jnez71/misc", "max_forks_repo_head_hexsha": "397ac0b8e3bccec4daa73db8963bb0510eebebfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-04-13T01:06:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-22T09:43:38.000Z", "avg_line_length": 40.0357142857, "max_line_length": 175, "alphanum_fraction": 0.5771632471, "num_tokens": 2220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6776210661314028}}
{"text": "//\n// Created by keszocze on 27.09.18.\n//\n\n#pragma once\n\n#include <map>\n#include <string>\n#include <vector>\n\n#include <cudd/cplusplus/cuddObj.hh>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"number_representation.hpp\"\n\nnamespace abo::util {\n\n/**\n * @brief Computes the label/number of the lowest terminal level of a given BDD (forest)\n * @param bdds BDDs in the forest\n * @return Lowest level in the forest\n */\nunsigned int terminal_level(const std::vector<std::vector<BDD>>& bdds);\n\n/**\n * @brief Evaluates the sum of a and b for an adder given as a BDD forest\n * @param adder BDD forest representing an adder\n * @param a The first summand\n * @param b The second summand\n * @param bits bit width of the adder\n * @return The value of a + b\n */\nlong eval_adder(const std::vector<BDD>& adder, long a, long b, int bits);\n\n/**\n * @brief Evaluates the function with the given input\n * @param function Representing an unsigned integer\n * @param input The inputs to the function (see cudd BDD.eval)\n * @return The value of function with the given input\n */\nlong eval(const std::vector<BDD>& function, std::vector<int> input);\n\n/**\n * @brief count_minterms Counts the number of minterms for each node in the given BDD in percent\n * (between 0 and 1). This counts how many percent of inputs that lead to a given node as an\n * intermediate result also lead to 1.\n * @param bdd The BDD for which the minters are counted\n * @return A map containing every node in the bdd and its minterm count\n */\nstd::map<DdNode*, double> count_minterms(const BDD& bdd);\n\n/**\n * @brief count_solutions For each node reachable from the given root, count the number of solutions\n * @param bdd The root node to search from\n * @return A map containing the number of solutions for each reachable node\n */\nstd::map<DdNode*, double> count_solutions(const BDD& bdd);\n\n/**\n * @brief random_satisfying_input Computes a random variable assignment that satisfies the function\n * given as a bdd\n * @param bdd The function that has to be satisfied by the assignment\n * @param minterm_count The minterm count for each node of the bdd, this must be computed by\n * count_minterms called on the bdd\n * @param max_level The maximum variable level that should be present in the variable assignment\n * @return A random variable assignment satisfying bdd. The vector consists of zeros and ones,\n * integers are only used for better compatibility with cudd functions\n */\nstd::vector<int> random_satisfying_input(const BDD& bdd,\n                                         const std::map<DdNode*, double>& minterm_count,\n                                         int max_level);\n\n//! Returns the value of the given ADD node if it is a constant node and zero otherwise\nunsigned int const_ADD_value(const ADD& add);\n\n/**\n * @brief add_terminal_values Finds all terminal values present in the given ADD and how often each\n * one is reached\n * @param add The function to compute the terminal values of\n * @return A list of terminal values and their frequencies. The first value of the pair is the\n * terminal node value (unique in the list), the second value is how often it is reached in the ADD\n */\nstd::vector<std::pair<double, unsigned long>> add_terminal_values(const ADD& add);\n\n/**\n * @brief bdd_forest_to_add Computes the ADD equivalent of a function represented by a BDD forest\n * @param mgr The cudd node manager to create the ADD in\n * @param bdds The function to convert to an ADD\n * @param num_rep The number format in which the bdds represent the function\n * @return The given function as an ADD\n */\nADD bdd_forest_to_add(const Cudd& mgr, const std::vector<BDD>& bdds,\n                      const NumberRepresentation num_rep\n                        = NumberRepresentation::BaseTwo);\n\n/**\n * @brief xor_difference_add Computes the bit-wise XOR between the two given functions and converts\n * the result to an ADD The conversion creates unsigned integer values\n * @param mgr The cudd node manager to create the ADD in\n * @param f The first function to compute the difference of\n * @param f_hat The second function. Must have the same length as f\n * @return The XOR difference as an ADD\n */\nADD xor_difference_add(const Cudd& mgr, const std::vector<BDD>& f,\n                       const std::vector<BDD>& f_hat);\n\n/**\n * @brief absolute_difference_add Computes the absolute difference between to functions represented\n * as BDDs and returns the result as an ADD\n * @param mgr The cudd node manager to create the ADD in\n * @param f The first function to compute the difference of\n * @param f_hat The second function. Must have the same length as f\n * @param num_rep The number representation used for the interpretation of the functions f and f_hat\n * @return A function computing the absolute difference between f and f_hat for each input\n * represented by an ADD\n */\nADD absolute_difference_add(const Cudd& mgr, const std::vector<BDD>& f,\n                            const std::vector<BDD>& f_hat,\n                            const NumberRepresentation num_rep);\n\n/**\n * @brief dump_dot A helper function for calling the dump dot method of cudd for a BDD forest\n * @param mgr The cudd node manager to use\n * @param bdd The function to dump as a dot file string\n * @param innames The names of the input variables to show in the dot file. May be left empty\n * @param outnames The names for each bit of the function to show in the dot file. May be left empty\n */\nvoid dump_dot(const Cudd& mgr, const std::vector<BDD>& bdd,\n              const std::vector<std::string>& innames = std::vector<std::string>(),\n              const std::vector<std::string>& outnames = std::vector<std::string>());\n\n/**\n * @brief dump_dot A helper function for calling the dump dot method of cudd for a single BDD\n * @param mgr The cudd node manager to use\n * @param bdd The function to dump as a dot file string\n * @param inames The names of the input variables to show in the dot file. May be left empty\n * @param funname The name of the function to show in the dot file output\n */\nvoid dump_dot(const Cudd& mgr, const BDD& bdd,\n              const std::vector<std::string>& inames = std::vector<std::string>(),\n              const std::string& funname = std::string());\n\n/**\n * @brief Retrives high-child of a BDD v\n * @param mgr The Cudd object manager\n * @param v\n * @return low(v)\n */\nBDD high(const Cudd& mgr, const BDD& v);\n\n/**\n * @brief Retrives low-child of a BDD v\n * @param mgr The Cudd object manager\n * @param v\n * @return low(v)\n */\nBDD low(const Cudd& mgr, const BDD& v);\n\n/**\n * @brief Creates a full adder of two BDDs and a carry BDD\n * @param f First summand BDD\n * @param g Second summand BDD\n * @param carry_in Carry BDD\n * @return Tuple of BDDs: Summ BDD and Carry BDD\n */\nstd::pair<BDD, BDD> full_adder(const BDD& f, const BDD& g, const BDD& carry_in);\n\n/**\n * @brief Creates a (vector of) BDDs that represent the difference between to given (vectors of)\n * BDDs\n *\n * The supplied BDDs are supposed to compute values represented in Two's Copmlement. The BDD\n * returned by this function computes the difference between the outputs of these BDDs, again\n * represented in Two's Complement.\n *\n * @param mgr The Cudd object manager\n * @param minuend Minuend in Two's Complement\n * @param subtrahend  Subtrahend in Two's Complement\n * @return BDD computing the difference of the outputs of the two supplied BDDs\n */\nstd::vector<BDD> bdd_subtract(const Cudd& mgr, const std::vector<BDD>& minuend,\n                              const std::vector<BDD>& subtrahend);\n\n/**\n * @brief Creates a (vector of) BDDs that represent the absolute difference between to given\n * (vectors of) BDDs\n *\n * The supplied BDDs are supposed to compute values represented in Two's Copmlement. The BDD\n * returned by this function computes the difference between the outputs of these BDDs. It will\n * always return an unsigned number, not a number in Two's complement.\n *\n * @param mgr The Cudd object manager\n * @param f Function in Two's Complement\n * @param g Funtion in Two's Complement\n * @param num_rep The number representation for f and g\n * @return BDD computing the absolute difference of the outputs of the two supplied BDDs\n */\nstd::vector<BDD> bdd_absolute_difference(const Cudd& mgr,\n                                         const std::vector<BDD>& f,\n                                         const std::vector<BDD>& g,\n                                         const NumberRepresentation num_rep);\n\n/**\n * @brief Creates the BDD representing the sum of two functions\n * @param mgr The Cudd object manager\n * @param f First summand\n * @param g Second summand\n * @return BDD representing f+g\n */\nstd::vector<BDD> bdd_add(const Cudd& mgr,\n                         const std::vector<BDD>& f,\n                         const std::vector<BDD>& g);\n\n/**\n * @brief Creates BDD representing abs(f). For unsigned numbers, the original function will be\n * returned\n * @param mgr The Cudd object manager\n * @param f Function in Two's Complement\n * @param num_rep The number representation for f\n * @return BDD representing abs(f)\n */\nstd::vector<BDD> bdd_abs(const Cudd& mgr, const std::vector<BDD>& f,\n                        const NumberRepresentation num_rep);\n\n/**\n * @brief Shifts a function f by a number of bits left or right\n *\n * The shifted result has the same number of bits as the input, bits that are shifted above or below\n * the original function bit range will be discarded\n *\n * @param mgr The Cudd object manager\n * @param f Function to shift\n * @param bits_to_shift Number of bits to shift. Can be both positive or negative\n * @return Shifted BDD\n */\nstd::vector<BDD> bdd_shift(const Cudd& mgr,\n                           const std::vector<BDD>& f,\n                           int bits_to_shift);\n\n/**\n * @brief Multiplies a bdd function with a constant\n * @param mgr The Cudd object manager\n * @param f Function that is to be multiplied. The function is interpreted as returning an unsigned\n * integer\n * @param factor Constant multiplication factor\n * @param num_extra_bits Additional bits used to make sure that the result can be stored (must be\n * less than sizeof(unsigned long) * 8)\n * @return BDD representing the function \"factor*f\" (extended by up to num_extra_bits)\n */\nstd::vector<BDD> bdd_multiply_constant(const Cudd& mgr,\n                                       const std::vector<BDD>& f,\n                                       double factor,\n                                       const unsigned int num_extra_bits = 16);\n\n/**\n * @brief Multiplies a bdd function with a constant large value\n * @param mgr The Cudd object manager\n * @param f Function that is to be multiplied. The function is interpreted as returning an unsigned\n * integer\n * @param factor Constant multiplication factor\n * @return BDD representing the function \"factor*f\"\n */\nstd::vector<BDD> bdd_multiply_constant(const Cudd& mgr,\n                                       const std::vector<BDD>& f,\n                                       boost::multiprecision::uint256_t factor);\n/**\n * @brief Checks if an input x exists such that int(f1(x)) >= int(f2(x))\n * @param mgr The Cudd object manager\n * @param f1 Function to compare in base two (interpreted as returning an unsigned integer)\n * @param f2 Function to compare in base two (interpreted as returning an unsigned integer)\n * @return {ge, e}\n * ge is true iff there exists an x such that int(f1(x)) >= int(f2(x))\n * e is true iff there exists an x such that int(f1(x)) = int(f2(x)), but no x exists with\n * int(f1(x)) > int(f2(x))\n */\nstd::pair<bool, bool> exists_greater_equals(const Cudd& mgr,\n                                            const std::vector<BDD>& f1,\n                                            const std::vector<BDD>& f2);\n\n/**\n * @brief Creates a BDD representing f >= g\n * @param mgr The Cudd object manager\n * @param f Function to compare in base two (interpreted as returning an unsigned integer)\n * @param g Function to compare in base two (interpreted as returning an unsigned integer)\n * @return BDD representing f >= g\n */\nBDD greater_equals(const Cudd& mgr,\n                   const std::vector<BDD>& f,\n                   const std::vector<BDD>& g);\n\n/**\n * @brief Creates a BDD representing f > g\n * @param mgr The Cudd object manager\n * @param f Function to compare in base two (interpreted as returning an unsigned integer)\n * @param g Function to compare in base two (interpreted as returning an unsigned integer)\n * @return BDD representing f > g\n */\nBDD greater_than(const Cudd& mgr,\n                const std::vector<BDD>& f,\n                const std::vector<BDD>& g);\n\n/**\n * @brief Computes a function g such that int(g(x)) = max(1, int(f(x)) for an unsigned function f\n * @param mgr The Cudd object manager\n * @param f The function to use. Is interpreted as unsigned integers\n * @return Function g as vector of BDDS of same length as f\n */\nstd::vector<BDD> bdd_max_one(const Cudd& mgr, const std::vector<BDD>& f);\n\n/**\n * @brief divide Computes a function h such that int(h(x)) = int(f(x)) / int(g(x))\n * @param mgr The Cudd object manager\n * @param f int(f(x)) = 0 must not be possible, f is interpreted as an unsigned integer\n * @param g is interpreted as an unsigned integer\n * @param extra_bits\n * @return\n */\nstd::vector<BDD> bdd_divide(const Cudd& mgr,\n                            const std::vector<BDD>& f,\n                            const std::vector<BDD>& g,\n                            unsigned int extra_bits);\n\n/**\n * @brief Converts an unsigned number to a BDD function representing that value\n * @param mgr The Cudd object manager\n * @param number The value the resulting function should return\n * @return A function that returns the given number for all inputs\n */\nstd::vector<BDD> number_to_bdds(const Cudd& mgr,\n                                const boost::multiprecision::uint256_t &number);\n\n} // namespace abo::util\n", "meta": {"hexsha": "4acc4e3126516fd06bc978b2e76393e2642e4435", "size": 13867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util/cudd_helpers.hpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "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/cudd_helpers.hpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "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/cudd_helpers.hpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 41.6426426426, "max_line_length": 100, "alphanum_fraction": 0.6820509122, "num_tokens": 3315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.6775748239556624}}
{"text": "#pragma once\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\n///////////////////////////////////////////////////////////////////////////////\n// Point - Edge\n\ntemplate <\n    typename DerivedP,\n    typename DerivedE0,\n    typename DerivedE1,\n    typename T = typename DerivedP::Scalar>\ninline T point_edge_closest_point(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1)\n{\n    auto e = e1 - e0;\n    return (p - e0).dot(e) / e.squaredNorm();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Edge - Edge\n\n/// Compute the barycentric coordinates of the closest points\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1,\n    typename T = typename DerivedEA0::Scalar>\ninline Vector2<T> edge_edge_closest_point(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1)\n{\n    assert(ea0.size() == 3);\n    assert(ea1.size() == 3);\n    assert(eb0.size() == 3);\n    assert(eb1.size() == 3);\n\n    auto eb_to_ea = ea0 - eb0;\n    auto ea = ea1 - ea0;\n    auto eb = eb1 - eb0;\n\n    Eigen::Matrix<T, 2, 2> coefMtr;\n    coefMtr(0, 0) = ea.squaredNorm();\n    coefMtr(0, 1) = coefMtr(1, 0) = -eb.dot(ea);\n    coefMtr(1, 1) = eb.squaredNorm();\n\n    Vector2<T> rhs;\n    rhs[0] = -eb_to_ea.dot(ea);\n    rhs[1] = eb_to_ea.dot(eb);\n\n    return coefMtr.ldlt().solve(rhs);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Point - Triangle\n\n/// Compute the barycentric coordinates of the closest point on the triangle.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2,\n    typename T = typename DerivedP::Scalar>\ninline Vector2<T> point_triangle_closest_point(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2)\n{\n    assert(p.size() == 3);\n    assert(t0.size() == 3);\n    assert(t1.size() == 3);\n    assert(t2.size() == 3);\n\n    Eigen::Matrix<T, 2, 3> basis;\n    basis.row(0) = RowVector3<T>(t1 - t0); // edge 0\n    basis.row(1) = RowVector3<T>(t2 - t0); // edge 1\n    Matrix2<T> A = basis * basis.transpose();\n    Vector2<T> b = basis * Vector3<T>(p - t0);\n    Vector2<T> x = A.ldlt().solve(b);\n    assert((A * x - b).norm() < 1e-10);\n    return x;\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "fddccf8bd39c46153c02ce466cf52d83a9afa5eb", "size": 2619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/friction/closest_point.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/friction/closest_point.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/friction/closest_point.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": 27.28125, "max_line_length": 79, "alphanum_fraction": 0.5799923635, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6774336935820096}}
{"text": "/*\n * File: fast_hankel_transform.hpp\n * Created Date: 2019-09-11\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Wednesday September 25th 2019 11:38:09 am\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\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 * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#ifndef FASTHANKELTRANSFORM_FASTHANKELTRANSFORM_H_\n#define FASTHANKELTRANSFORM_FASTHANKELTRANSFORM_H_\n\n#include <Eigen/Dense>\n#include <complex>\n\nclass FastHankelTransform {\npublic:\n  FastHankelTransform(int num_sample, double ux_, double uy_);\n  ~FastHankelTransform();\n  Eigen::VectorXd sampling();\n  void set_feval(const Eigen::Ref<const Eigen::VectorXd> &feval);\n  Eigen::VectorXd calculate();\n\nprivate:\n  double evaluate_alpha();\n  double evaluate_k0(double alpha);\n  void evaluate_phi();\n  void evaluate_j1();\n  const int num_sample_;\n  const double ux_;\n  const double uy_;\n  double alpha_;\n  double k0_;\n\n  Eigen::VectorXd x_;\n  Eigen::VectorXd f_;\n  std::complex<double> *phi_;\n  std::complex<double> *j1_;\n\n  bool x_updated_ = false;\n  bool f_updated_ = false;\n};\n\n#endif", "meta": {"hexsha": "c3faf60fb2100e174b70b1bd51fcfacf0da30a2b", "size": 2220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_hankel_transform.hpp", "max_stars_repo_name": "pan3rock/fast-hankel-transform", "max_stars_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T12:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T12:05:06.000Z", "max_issues_repo_path": "include/fast_hankel_transform.hpp", "max_issues_repo_name": "pan3rock/fast-hankel-transform", "max_issues_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_issues_repo_licenses": ["MIT"], "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/fast_hankel_transform.hpp", "max_forks_repo_name": "pan3rock/fast-hankel-transform", "max_forks_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T00:43:38.000Z", "avg_line_length": 31.2676056338, "max_line_length": 80, "alphanum_fraction": 0.7153153153, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.677403616218725}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/core/geometry/geometry_barycentric.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_geometry_util_compute_distance_to_triangle);\r\n\r\nBOOST_AUTO_TEST_CASE(inside_simplex_testing)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         V;\r\n  typedef math_types::real_type                            T;\r\n\r\n  V const a = V( 0.0, 0.0, 0.0);\r\n  V const b = V(-1.0, 0.0, 0.0);\r\n  V const c = V( 0.0, 1.0, 0.0);\r\n  V const d = V( -2.0, -2.0, 1.0);\r\n\r\n  // Test barycentric coordinates of a point lying on an edge\r\n  {\r\n    for(size_t i = 0;i<100;++i)\r\n    {\r\n      T WA = i*0.01;\r\n      T WB = 1.0 - WA;\r\n      V const p = WA*a + WB*b;\r\n      T wa = 10.0;\r\n      T wb = 10.0;\r\n      OpenTissue::geometry::barycentric_geometric( a, b, p, wa, wb );\r\n      BOOST_CHECK_CLOSE(wa, WA, 0.01 );\r\n      BOOST_CHECK_CLOSE(wb, WB, 0.01 );\r\n    }\r\n  }\r\n  // Test barycentric coordinates of a point lying on a triangle\r\n  {\r\n    for(size_t i = 1;i<10;++i)\r\n    for(size_t j = 1;j<10;++j)\r\n    for(size_t k = 1;k<10;++k)\r\n    {\r\n      T WA = i*0.1;\r\n      T WB = j*0.1;\r\n      T WC = k*0.1;\r\n      T W = WA + WB + WC;\r\n      WA /= W;\r\n      WB /= W;\r\n      WC /= W;\r\n      V const p = WA*a + WB*b + WC*c;\r\n      T wa = 10.0;\r\n      T wb = 10.0;\r\n      T wc = 10.0;\r\n      // geometric method\r\n      OpenTissue::geometry::barycentric_geometric( a, b, c, p, wa, wb, wc );\r\n      BOOST_CHECK_CLOSE(wa, WA, 0.01 );\r\n      BOOST_CHECK_CLOSE(wb, WB, 0.01 );\r\n      BOOST_CHECK_CLOSE(wc, WC, 0.01 );\r\n\r\n      wa = 10.0;\r\n      wb = 10.0;\r\n      wc = 10.0;\r\n      // algebraic method\r\n      OpenTissue::geometry::barycentric_algebraic( a, b, c, p, wa, wb, wc );\r\n      BOOST_CHECK_CLOSE(wa, WA, 0.01 );\r\n      BOOST_CHECK_CLOSE(wb, WB, 0.01 );\r\n      BOOST_CHECK_CLOSE(wc, WC, 0.01 );\r\n\r\n    }\r\n  }\r\n  // Test barycentric coordinates of a point lying in a tetrahedron\r\n  {\r\n    for(size_t i = 1;i<10;++i)\r\n    for(size_t j = 1;j<10;++j)\r\n    for(size_t k = 1;k<10;++k)\r\n    for(size_t m = 1;m<10;++m)\r\n    {\r\n      T WA = i*0.1;\r\n      T WB = j*0.1;\r\n      T WC = k*0.1;\r\n      T WD = m*0.1;\r\n      T W = WA + WB + WC + WD;\r\n      WA /= W;\r\n      WB /= W;\r\n      WC /= W;\r\n      WD /= W;\r\n      V const p = WA*a + WB*b + WC*c+ WD*d;\r\n      T wa = 10.0;\r\n      T wb = 10.0;\r\n      T wc = 10.0;\r\n      T wd = 10.0;\r\n      // Geometric method\r\n      OpenTissue::geometry::barycentric_geometric( a, b, c, d, p, wa, wb, wc, wd );\r\n      BOOST_CHECK_CLOSE(wa, WA, 0.01 );\r\n      BOOST_CHECK_CLOSE(wb, WB, 0.01 );\r\n      BOOST_CHECK_CLOSE(wc, WC, 0.01 );\r\n      BOOST_CHECK_CLOSE(wd, WD, 0.01 );\r\n\r\n      wa = 10.0;\r\n      wb = 10.0;\r\n      wc = 10.0;\r\n      wd = 10.0;\r\n      // algebraic method\r\n      OpenTissue::geometry::barycentric_algebraic( a, b, c, d, p, wa, wb, wc, wd );\r\n      BOOST_CHECK_CLOSE(wa, WA, 0.01 );\r\n      BOOST_CHECK_CLOSE(wb, WB, 0.01 );\r\n      BOOST_CHECK_CLOSE(wc, WC, 0.01 );\r\n      BOOST_CHECK_CLOSE(wd, WD, 0.01 );\r\n    }\r\n  }\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "9ec65ea821c8a101a6b5025c25d2db2d0b0862a7", "size": 3628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/geometry/barycentric/src/unit_barycentric.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/geometry/barycentric/src/unit_barycentric.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/geometry/barycentric/src/unit_barycentric.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 29.2580645161, "max_line_length": 84, "alphanum_fraction": 0.5548511577, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6774036112546091}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <string>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n \nusing namespace std;  \n\ntypedef mtl::compressed2D<double> m_type;\n\nvoid assemble_poisson2D(m_type& A, int n)\n{\n    m_type dia_block(n, n), off_block(n, n);\n    {\n\tmtl::mat::inserter<m_type> ins(dia_block);\n\tfor (int i= 0; i < n; i++) {\n\t    ins[i][i] << 4.0;\n\t    if (i > 0) ins[i][i-1] << -1.0;\n\t    if (i < n-1) ins[i][i+1] << -1.0;\n\t}\n    }\n    off_block= -1.0;\n    A.change_dim(n*n, n*n);\n    {\n\tmtl::mat::inserter<m_type> ins(A);\n\tfor (int i= 0; i < n; i++) {\n\t    ins[i*n][i*n] << dia_block;\n\t    if (i > 0) ins[i*n][i*n-n] << off_block;\n\t    if (i < n-1) ins[i*n][i*n+n] << off_block;\n\t}\n    }\n}\n\n//\n// Inverse iteration: is almost a literal copy from algorithm 9.1.2\n//\n// LinearSolver: BinaryFunction\n// EigenVector: GLAS dense vector\ntemplate <class LinearSolver, class EigenVector>\ndouble inverse_iteration( LinearSolver& solver, EigenVector& x, int m ) \n{\n    EigenVector y( size(x), 0.0 ) ;\n    double lambda = 0.0 ;\n    x /= two_norm(x) ;\n    for (int i=0; i<m; ++i) {\n\tsolver( x, y ) ;\n\tlambda = mtl::sum(x) / mtl::sum(y) ;\n\tx = y / two_norm(y) ;\n    }\n    return lambda ;\n}\n\n//\n// Inverse iteration: is almost a literal copy from algorithm 9.1.2\n//\n// LinearSolver: BinaryFunction\n// EigenVector: GLAS dense vector\ntemplate <class LinearSolver, class Matrix, class EigenVector>\ndouble condition( LinearSolver& solver, const Matrix& A, EigenVector& x, int m ) {\n  EigenVector y( size(x) ) ;\n  double lambda= 0.0 ;\n  x/= two_norm(x);\n  for (int i=0; i<m; ++i) {\n      y= A * x; \n      lambda = mtl::sum(y) / mtl::sum(x) ;\n      x = y / two_norm(y) ;\n  }\n  return std::abs(lambda / inverse_iteration(solver, x, m));\n}\n\ntemplate <typename Matrix>\nclass cg_solver\n{\npublic:\n    cg_solver(const Matrix& A) : A(A) {}\n\n    template <typename VectorIn, typename VectorOut>\n    void operator() (const VectorIn& v_in, VectorOut& v_out)\n    {\n\titl::pc::diagonal<Matrix>     P(A);\n\titl::cyclic_iteration<double>  iter(v_in, 500, 1.e-6);\n\n\tcg(A, v_out, v_in, P, iter);\n    }\n\nprivate:\n    const Matrix& A;\n};\n\nint main(int, char**)\n{\n    m_type A;\n    assemble_poisson2D(A, 10);\n\n    mtl::dense_vector<double>   x(num_rows(A));\n    mtl::seed<double>           seed;\n    random(x, seed);\n\n    cg_solver<m_type> sol(A);\n    double lambda= inverse_iteration(sol, x, 10);\n    cout << \"lambda is \" << lambda << '\\n';\n\n    double cond= condition(sol, A, x, 10);\n    cout << \"cond is \" << cond << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "b5e129f71d0091ce424d8ac55d3ca2e627f69e0e", "size": 3012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/inverse_poisson_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/inverse_poisson_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/inverse_poisson_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": 24.6885245902, "max_line_length": 94, "alphanum_fraction": 0.6145418327, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6773663018126879}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Statistical Analysis. \n * ****************************************************************************\n */\n\n#ifndef VISIONCORE_MATH_STATISTICS_HPP\n#define VISIONCORE_MATH_STATISTICS_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <VisionCore/Buffers/Buffer1D.hpp>\n#include <VisionCore/Buffers/Buffer2D.hpp>\n#include <VisionCore/Types/Polynomial.hpp>\n#include <VisionCore/Types/Gaussian.hpp>\n#include <VisionCore/Math/PolarSpherical.hpp>\n\n/**\n * @note:\n * http://rebcabin.github.io/blog/2013/01/22/covariance-matrices/\n */\n\nnamespace vc\n{\n\nnamespace math\n{\n    \n/**\n * Running mean, variation, std. deviation, count and min,max.\n */\ntemplate<typename T>\nclass RunningStats\n{\npublic:    \n    typedef T Scalar;\n    static constexpr int Rows = 1;\n    static constexpr int Cols = 1;\n    static constexpr int Dimension = Rows * Cols;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC inline RunningStats()\n    {\n        reset();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void reset()\n    {\n        cnt = 0;\n        minV = std::numeric_limits<T>::max();\n        maxV = -std::numeric_limits<T>::max();\n        sumX = sumXX = T(0.0);\n    }\n    \n    EIGEN_DEVICE_FUNC inline void operator()(const T& x)\n    {\n        using Eigen::numext::mini;\n        using Eigen::numext::maxi;\n      \n        // process\n        cnt++;\n        \n        sumX += x;\n        sumXX += (x * x);\n        \n        maxV = max(maxV, x); // NOTE what about weight?\n        minV = min(minV, x);\n    }\n    \n    EIGEN_DEVICE_FUNC inline std::size_t count() const \n    { \n        return cnt; \n    }\n    \n    EIGEN_DEVICE_FUNC inline T mean() const\n    {\n        if(cnt > 0)\n        {\n            return sumX / T(cnt);\n        }\n        else\n        {\n            return T(0.0);\n        }\n    }\n    \n    EIGEN_DEVICE_FUNC inline T variance() const\n    {        \n        if(cnt > 0)\n        {\n            const T bessel_correction = T(cnt) / T(cnt - 1);\n            const T cm = mean();\n            const T term1 = sumXX / T(cnt);\n            \n            return bessel_correction * (term1 - (cm*cm));\n        }\n        else\n        {\n            return T(0.0);\n        }\n    }\n        \n    EIGEN_DEVICE_FUNC inline T stddev() const \n    {\n        using Eigen::numext::sqrt;\n        return sqrt(variance());\n    }\n    \n    EIGEN_DEVICE_FUNC inline T running_sum() const { return sumX; }\n    \n    EIGEN_DEVICE_FUNC inline T min_value() const { return minV; }\n    EIGEN_DEVICE_FUNC inline T max_value() const { return maxV; }\n    \n    EIGEN_DEVICE_FUNC inline types::Gaussian<T> gaussian() const \n    { \n        return types::Gaussian<T>(mean(), variance()); \n    }\nprivate:\n    std::size_t cnt;\n    T sumX, sumXX;\n    T minV, maxV;\n};\n\n/**\n * Specialization for Eigen.\n */\ntemplate<typename _Scalar, int _Rows, int _Cols, int _Options>\nclass RunningStats<Eigen::Matrix<_Scalar, _Rows, _Cols, _Options>>\n{\npublic:    \n    typedef Eigen::Matrix<_Scalar, _Rows, _Cols, _Options> VectorType;\n    typedef _Scalar Scalar;\n    static constexpr int Rows = _Rows;\n    static constexpr int Cols = _Cols;\n    static constexpr int Dimension = Rows * Cols;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC inline RunningStats()\n    {\n        reset();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void reset()\n    {\n        cnt = 0;\n        minV = VectorType::Constant(std::numeric_limits<Scalar>::max());\n        maxV = VectorType::Constant(-std::numeric_limits<Scalar>::max());\n        sumX = VectorType::Zero();\n        sumXX = VectorType::Zero();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void operator()(const VectorType& x)\n    {\n        // process\n        cnt++;\n        \n        sumX += x;\n        sumXX += VectorType(x.array() * x.array());\n        \n        maxV = maxV.array().cwiseMax(x.array());\n        minV = minV.array().cwiseMin(x.array());\n    }\n    \n    EIGEN_DEVICE_FUNC inline std::size_t count() const \n    { \n        return cnt; \n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType mean() const\n    {\n        if(cnt > 0)\n        {\n            return sumX / Scalar(cnt);\n        }\n        else\n        {\n            return VectorType::Zero();\n        }\n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType variance() const\n    {\n        if(cnt > 0)\n        {\n            const Scalar bessel_correction = Scalar(cnt) / Scalar(cnt - 1);\n            const VectorType cm = mean();\n            const VectorType term1 = sumXX / Scalar(cnt);\n            \n            return bessel_correction * (term1 - VectorType(cm.array() * cm.array()));\n        }\n        else\n        {\n            return VectorType::Zero();\n        }\n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType stddev() const\n    {\n        return sqrt(variance().array());\n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType running_sum() const { return sumX; }\n    \n    EIGEN_DEVICE_FUNC inline VectorType min_value() const { return minV; }\n    EIGEN_DEVICE_FUNC inline VectorType max_value() const { return maxV; }\n    \n    EIGEN_DEVICE_FUNC inline types::Gaussian<VectorType> gaussian() const \n    { \n        return types::Gaussian<VectorType>(mean(), variance()); \n    }\nprivate:\n    std::size_t cnt;\n    VectorType sumX, sumXX, minV, maxV;\n};\n\n// ******************** RUNNING MULTIVARIATE *******************************\n\n/**\n * Multivariate analysis.\n */\ntemplate<typename T>\nclass MultivariateStats;\n\ntemplate<typename _Scalar, int Rows, int Options>\nclass MultivariateStats<Eigen::Matrix<_Scalar, Rows, 1, Options>>\n{\npublic:    \n    typedef Eigen::Matrix<_Scalar, Rows, 1, Options> VectorType;\n    typedef Eigen::Matrix<_Scalar, Rows, Rows, Options> CovarianceType;\n    typedef _Scalar Scalar;\n    static constexpr std::size_t Dimensions = Rows;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC inline MultivariateStats()\n    {\n        reset();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void reset()\n    {\n        cnt = 0;\n        minV = VectorType::Constant(std::numeric_limits<Scalar>::max());\n        maxV = VectorType::Constant(-std::numeric_limits<Scalar>::max());\n        sumX = VectorType::Zero();\n        sumXX = CovarianceType::Zero();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void operator()(const VectorType& x)\n    {\n        // process\n        cnt++;\n        \n        sumX += x;\n        \n        sumXX += (x * x.transpose());\n        \n        maxV = maxV.array().cwiseMax(x.array());\n        minV = minV.array().cwiseMin(x.array());\n    }\n    \n    EIGEN_DEVICE_FUNC inline std::size_t count() const \n    { \n        return cnt; \n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType mean() const\n    {\n        if(cnt > 0)\n        {\n            return sumX / Scalar(cnt);\n        }\n        else\n        {\n            return VectorType::Zero();\n        }\n    }\n    \n    EIGEN_DEVICE_FUNC inline CovarianceType covariance() const\n    {\n        if(cnt > 0)\n        {\n            const Scalar bessel_correction = Scalar(cnt) / Scalar(cnt - 1);\n            const VectorType m = mean();\n            return bessel_correction * ( (sumXX / Scalar(cnt)) - (m * m.transpose()) );\n        }\n        else\n        {\n            return CovarianceType::Zero();\n        }\n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType running_sum() const { return sumX; }\n    \n    EIGEN_DEVICE_FUNC inline VectorType min_value() const { return minV; }\n    EIGEN_DEVICE_FUNC inline VectorType max_value() const { return maxV; }\n    \n    EIGEN_DEVICE_FUNC inline types::MultivariateGaussian<Scalar,Rows> gaussian() const \n    { \n        return types::MultivariateGaussian<Scalar,Rows>(mean(), covariance()); \n    }\nprivate:\n    std::size_t cnt;\n    VectorType sumX, minV, maxV;\n    CovarianceType sumXX;\n};\n\n// ******************** ALLAN VARIANCE *******************************\n// From: http://www.leapsecond.com/tools/adev_lib.c\n\ntemplate<typename InputIterator>\ntypename std::iterator_traits<InputIterator>::value_type allanDeviation(std::size_t tau, \n                                                                        InputIterator itbegin, \n                                                                        InputIterator itend, \n                                                                        bool isoverlapping = false, \n                                                                        std::size_t* terms = nullptr)\n{\n    typedef typename std::iterator_traits<InputIterator>::value_type T;\n    using namespace std;\n    \n    std::size_t n = 0;\n    T sum = T(0.0);\n    const std::size_t stride = isoverlapping ? 1 : tau;\n    \n    for ( ; (itbegin + 2 * tau) < itend ; itbegin += stride) \n    {\n        const T v = *(itbegin + 2 * tau) - T(2.0) * *(itbegin + tau) + *itbegin;\n        sum += v * v;\n        n += 1;\n    }\n    \n    sum /= T(2.0);\n    \n    if(terms != nullptr) { *terms = n; }\n    \n    if (n < 3) { return T(0.0); }\n    \n    return sqrt(sum / n) / tau;\n}\n\ntemplate<typename InputIterator>\ntypename std::iterator_traits<InputIterator>::value_type hadamardDeviation(std::size_t tau, \n                                                                           InputIterator itbegin, \n                                                                           InputIterator itend, \n                                                                           bool isoverlapping = false, \n                                                                           std::size_t* terms = nullptr)\n{\n    typedef typename std::iterator_traits<InputIterator>::value_type T;\n    using namespace std;\n    \n    std::size_t n = 0;\n    T sum = T(0.0);\n    const std::size_t stride = isoverlapping ? 1 : tau;\n    \n    for ( ; (itbegin + 3 * tau) < itend; itbegin += stride) \n    {\n        const T v = *(itbegin + 3 * tau) - T(3.0) * *(itbegin + 2 * tau) + T(3.0) * *(itbegin + tau) - *itbegin;\n        sum += v * v;\n        n += 1;\n    }\n    \n    sum /= T(6.0);\n    \n    if(terms != nullptr) { *terms = n; }\n    \n    if (n < 3) { return T(0.0); }\n    \n    return sqrt(sum / n) / tau;\n}\n\ntemplate<typename InputIterator>\ntypename std::iterator_traits<InputIterator>::value_type modifiedAllanDeviation(std::size_t tau, \n                                                                                InputIterator itbegin, \n                                                                                InputIterator itend, \n                                                                                std::size_t* terms = nullptr)\n{\n    typedef typename std::iterator_traits<InputIterator>::value_type T;\n    using namespace std;\n    \n    std::size_t n = 0;\n    T sum = T(0.0), v = T(0.0);\n    \n    InputIterator orgbegin = itbegin;\n    \n    for ( ; (itbegin + 2 * tau) < itend && (std::size_t)std::distance(orgbegin, itbegin) < tau; ++itbegin) \n    {\n        v += *(itbegin + 2 * tau) - T(2.0) * *(itbegin + tau) + *itbegin;\n    }\n    \n    sum += v * v;\n    n += 1;\n    \n    itbegin = orgbegin;\n    \n    for ( ; (itbegin + 3 * tau) < itend; ++itbegin) \n    {\n        v += *(itbegin + 3 * tau) - T(3.0) * *(itbegin + 2 * tau) + T(3.0) * *(itbegin + tau) - *itbegin;\n        sum += v * v;\n        n += 1;\n    }\n    \n    sum /= T(2.0) * T(tau) * T(tau);\n    \n    if(terms != nullptr) { *terms = n; }\n    if(n < 3) { return T(0.0); }\n    \n    return sqrt(sum / n) / tau;\n}\n\ntemplate<typename InputIterator>\ntypename std::iterator_traits<InputIterator>::value_type timeDeviation(std::size_t tau, \n                                                                       InputIterator itbegin, \n                                                                       InputIterator itend, \n                                                                       std::size_t* terms = nullptr)\n{\n    typedef typename std::iterator_traits<InputIterator>::value_type T;\n    using namespace std;\n    return T(tau) * modifiedAllanDeviation(tau, itbegin, itend, terms) / sqrt(3.0);\n}\n\n// ******************** PEARSON PRODUCT MOMENT *******************************\n\n/**\n * Calculate r_xy from data.\n */\ntemplate<typename T>\nclass PearsonProductMoment;\n\ntemplate<typename Derived, typename BaseType>\nclass PearsonProductMomentBase\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC void reset()\n    {\n        stats_x.reset();\n        stats_x2.reset();\n        stats_y.reset();\n        stats_y2.reset();\n        stats_xy.reset();\n    }\n    \n    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsX() const { return stats_x; }\n    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsY() const { return stats_y; }\n    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsX2() const { return stats_x2; }\n    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsY2() const { return stats_y2; }\n    EIGEN_DEVICE_FUNC const RunningStats<BaseType>& statsXY() const { return stats_xy; }\nprotected:\n    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsX() { return stats_x; }\n    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsY() { return stats_y; }\n    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsX2() { return stats_x2; }\n    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsY2() { return stats_y2; }\n    EIGEN_DEVICE_FUNC RunningStats<BaseType>& statsXY() { return stats_xy; }\n    \nprivate:\n    RunningStats<BaseType> stats_x;\n    RunningStats<BaseType> stats_y;\n    RunningStats<BaseType> stats_xy;\n    RunningStats<BaseType> stats_x2;\n    RunningStats<BaseType> stats_y2;\n};\n\ntemplate<typename T>\nclass PearsonProductMoment : public PearsonProductMomentBase<PearsonProductMoment<T>, T>\n{\n    typedef PearsonProductMomentBase<PearsonProductMoment<T>, T> Base;\npublic:    \n    typedef T BaseType;\n    typedef types::Polynomial<BaseType,1> PolynomialT;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC inline PearsonProductMoment()\n    {\n        Base::reset();\n    }\n        \n    EIGEN_DEVICE_FUNC void operator()(const T& x, const T& y)\n    {\n        Base::statsX()(x);\n        Base::statsX2()(x*x);\n        Base::statsY()(y);\n        Base::statsY2()(y*y);\n        Base::statsXY()(x*y);\n    }\n    \n    EIGEN_DEVICE_FUNC BaseType result() const\n    {\n        using Eigen::numext::sqrt;\n        return (Base::statsXY().mean() - (Base::statsX().mean() * Base::statsY().mean())) / \n                sqrt( ( Base::statsX2().mean() - ( Base::statsX().mean() * Base::statsX().mean() ) ) * \n                      ( Base::statsY2().mean() - ( Base::statsY().mean() * Base::statsY().mean() ) ) );\n    }\n    \n    EIGEN_DEVICE_FUNC inline BaseType coefficientOfDetermination() const\n    {\n        BaseType r = result();\n        return r*r;\n    }\n    \n    EIGEN_DEVICE_FUNC inline PolynomialT lineEquation() const\n    {\n        PolynomialT ret;\n        BaseType b = result() * ( Base::statsY().stddev() / Base::statsX().stddev() );\n        BaseType a = Base::statsY().mean() - b * Base::statsX().mean();\n        ret.coeff() << a , b;\n        return ret;\n    }\n};\n\ntemplate<typename _Scalar, int _Rows, int _Cols>\nclass PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > : \n  public PearsonProductMomentBase<PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > , Eigen::Matrix<_Scalar, _Rows, _Cols>>\n{\n    typedef PearsonProductMomentBase<PearsonProductMoment<Eigen::Matrix<_Scalar, _Rows, _Cols> > , Eigen::Matrix<_Scalar, _Rows, _Cols>> Base;\npublic:\n    typedef Eigen::Matrix<_Scalar, _Rows, _Cols> BaseType;    \n    typedef types::Polynomial<BaseType,1> PolynomialT;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    EIGEN_DEVICE_FUNC inline PearsonProductMoment()\n    {\n        Base::reset();\n    }\n    \n    EIGEN_DEVICE_FUNC void operator()(const BaseType& x, const BaseType& y)\n    {\n        Base::statsX()(x);\n        Base::statsX2()(x.array() * x.array());\n        Base::statsY()(y);\n        Base::statsY2()(y.array() * y.array());\n        Base::statsXY()(x.array() * y.array());\n    }\n    \n    EIGEN_DEVICE_FUNC BaseType result() const\n    {\n        using Eigen::numext::sqrt;\n        \n        return (Base::statsXY().mean().array() - (Base::statsX().mean().array() * Base::statsY().mean().array())) / \n                sqrt( ( Base::statsX2().mean().array() - ( Base::statsX().mean().array() * Base::statsX().mean().array() ) ) * \n                      ( Base::statsY2().mean().array() - ( Base::statsY().mean().array() * Base::statsY().mean().array() ) ) );\n    }\n    \n    EIGEN_DEVICE_FUNC inline BaseType coefficientOfDetermination() const\n    {\n        BaseType r = result();\n        return r.array() * r.array();\n    }\n    \n    EIGEN_DEVICE_FUNC inline PolynomialT lineEquation()\n    {\n        PolynomialT ret;\n        BaseType b = result().array() * ( Base::statsY().stddev().array() / Base::statsX().stddev().array() );\n        BaseType a = Base::statsY().mean().array() - b.array() * Base::statsX().mean().array();\n        ret.coeff() << a , b;\n        return ret;\n    }\n};\n    \n}\n\n}\n\n#endif // VISIONCORE_MATH_STATISTICS_HPP\n", "meta": {"hexsha": "83ea2603e7cb8b121df490ead682c237bed42a9e", "size": 18613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Math/Statistics.hpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "include/VisionCore/Math/Statistics.hpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "include/VisionCore/Math/Statistics.hpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 30.9700499168, "max_line_length": 142, "alphanum_fraction": 0.5638532209, "num_tokens": 4517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6773393436017179}}
{"text": "//  boost sinc.hpp header file\n\n//  (C) Copyright Hubert Holin 2001. Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears\n//  in all copies. This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n\n// See http://www.boost.org for updates, documentation, and revision history.\n\n#ifndef BOOST_SINC_HPP\n#define BOOST_SINC_HPP\n\n\n#include <cmath>\n#include <limits>\n#include <string>\n#include <stdexcept>\n\n\n#include <boost/config.hpp>\n\n\n// These are the the \"Sinus Cardinal\" functions.\n\nnamespace boost\n{\n    namespace math\n    {\n#if        defined(__GNUC__) && (__GNUC__ < 3)\n        // gcc 2.x ignores function scope using declarations,\n        // put them in the scope of the enclosing namespace instead:\n        \n        using    ::std::abs;\n        using    ::std::sqrt;\n        using    ::std::sin;\n        \n        using    ::std::numeric_limits;\n#endif    /* defined(__GNUC__) && (__GNUC__ < 3) */\n        \n        // This is the \"Sinus Cardinal\" of index Pi.\n        \n        template<typename T>\n        inline T    sinc_pi(const T x)\n        {\n#ifdef    BOOST_NO_STDC_NAMESPACE\n            using    ::abs;\n            using    ::sin;\n            using    ::sqrt;\n#else    /* BOOST_NO_STDC_NAMESPACE */\n            using    ::std::abs;\n            using    ::std::sin;\n            using    ::std::sqrt;\n#endif    /* BOOST_NO_STDC_NAMESPACE */\n            \n            using    ::std::numeric_limits;\n            \n            static T const    taylor_0_bound = numeric_limits<T>::epsilon();\n            static T const    taylor_2_bound = sqrt(taylor_0_bound);\n            static T const    taylor_n_bound = sqrt(taylor_2_bound);\n            \n            if    (abs(x) >= taylor_n_bound)\n            {\n                return(sin(x)/x);\n            }\n            else\n            {\n                // approximation by taylor series in x at 0 up to order 0\n                T    result = static_cast<T>(1);\n                \n                if    (abs(x) >= taylor_0_bound)\n                {\n                    T    x2 = x*x;\n                    \n                    // approximation by taylor series in x at 0 up to order 2\n                    result -= x2/static_cast<T>(6);\n                    \n                    if    (abs(x) >= taylor_2_bound)\n                    {\n                        // approximation by taylor series in x at 0 up to order 4\n                        result += (x2*x2)/static_cast<T>(120);\n                    }\n                }\n                \n                return(result);\n            }\n        }\n        \n        \n#ifdef    BOOST_NO_TEMPLATE_TEMPLATES\n#else    /* BOOST_NO_TEMPLATE_TEMPLATES */\n        template<typename T, template<typename> class U>\n        inline U<T>    sinc_pi(const U<T> x)\n        {\n#ifdef    BOOST_NO_STDC_NAMESPACE\n            using    ::abs;\n            using    ::sin;\n            using    ::sqrt;\n#else    /* BOOST_NO_STDC_NAMESPACE */\n            using    ::std::abs;\n            using    ::std::sin;\n            using    ::std::sqrt;\n#endif    /* BOOST_NO_STDC_NAMESPACE */\n            \n            using    ::std::numeric_limits;\n            \n            static T const    taylor_0_bound = numeric_limits<T>::epsilon();\n            static T const    taylor_2_bound = sqrt(taylor_0_bound);\n            static T const    taylor_n_bound = sqrt(taylor_2_bound);\n            \n            if    (abs(x) >= taylor_n_bound)\n            {\n                return(sin(x)/x);\n            }\n            else\n            {\n                // approximation by taylor series in x at 0 up to order 0\n                U<T>    result = static_cast< U<T> >(1);\n                \n                if    (abs(x) >= taylor_0_bound)\n                {\n                    U<T>    x2 = x*x;\n                    \n                    // approximation by taylor series in x at 0 up to order 2\n                    result -= x2/static_cast<T>(6);\n                    \n                    if    (abs(x) >= taylor_2_bound)\n                    {\n                        // approximation by taylor series in x at 0 up to order 4\n                        result += (x2*x2)/static_cast<T>(120);\n                    }\n                }\n                \n                return(result);\n            }\n        }\n#endif    /* BOOST_NO_TEMPLATE_TEMPLATES */\n    }\n}\n\n#endif /* BOOST_SINC_HPP */\n", "meta": {"hexsha": "33c0083cd34b2d2b9a691f87765fb5214ecb892a", "size": 4458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/math/special_functions/sinc.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "src/3rd party/boost/boost/math/special_functions/sinc.hpp", "max_issues_repo_name": "OLR-xray/OLR-3.0", "max_issues_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "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/3rd party/boost/boost/math/special_functions/sinc.hpp", "max_forks_repo_name": "OLR-xray/OLR-3.0", "max_forks_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 31.6170212766, "max_line_length": 81, "alphanum_fraction": 0.4746523105, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6772747624738767}}
{"text": "/**\n * @file upwindfinitevolume_main.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 <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/gmsh_reader.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/refinement/refinement.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"upwindfinitevolume.h\"\n\nint main() {\n  /* SAM_LISTING_BEGIN_1 */\n#if SOLUTION\n  // Read in mesh\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory),\n                            CURRENT_SOURCE_DIR \"/mesh.msh\");\n\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader.mesh();\n\n  double eps = 1e-6;\n\n  auto v = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    return Eigen::Vector2d(1, 0.5 - x[1]);\n  };\n\n  auto u = [](Eigen::Vector2d x) -> double {\n    return std::sin(4 * M_PI * x[1]) * std::exp(-x[0]);\n  };\n\n  auto f = [&u, eps](Eigen::Vector2d x) -> double {\n    return eps * (1.0 - 16.0 * M_PI * M_PI) * u(x) - 2 * u(x) +\n           (0.5 - x[1]) * 4 * M_PI * std::cos(4.0 * M_PI * x[1]) *\n               std::exp(-x[0]);\n  };\n\n  // Convergence study\n  auto mesh_seq_p{\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh_p, 6)};\n  int num_meshes = mesh_seq_p->NumLevels();\n\n  std::vector<double> vec_l2error;\n  std::vector<double> vec_Ndofs;\n  for (int level = 0; level < num_meshes; ++level) {\n    // Get the current mesh\n    auto cur_mesh = mesh_seq_p->getMesh(level);\n\n    // Create a DOF Hander for the current mesh\n    const lf::assemble::UniformFEDofHandler cur_dofh(\n        cur_mesh, {{lf::base::RefEl::kPoint(), 1},\n                   {lf::base::RefEl::kSegment(), 0},\n                   {lf::base::RefEl::kTria(), 0},\n                   {lf::base::RefEl::kQuad(), 0}});\n    int N_dofs = cur_dofh.NumDofs();\n\n    lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n    UpwindFiniteVolume::ElementMatrixProvider my_mat_provider(v, eps);\n    lf::assemble::AssembleMatrixLocally(0, cur_dofh, cur_dofh, my_mat_provider,\n                                        A);\n\n    Eigen::VectorXd phi(N_dofs);\n    phi.setZero();\n    UpwindFiniteVolume::ElementVectorProvider my_vec_provider(f);\n    lf::assemble::AssembleVectorLocally(0, cur_dofh, my_vec_provider, phi);\n\n    // Dirichlet boundary condition\n    auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(cur_mesh, 2)};\n    auto my_selector = [&cur_dofh, &u, &bd_flags](unsigned int dof_idx) {\n      if (bd_flags(cur_dofh.Entity(dof_idx))) {\n        const lf::mesh::Entity &entity{cur_dofh.Entity(dof_idx)};\n        const lf::geometry::Geometry *geo_p = entity.Geometry();\n        const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n        Eigen::Vector2d corner = corners.col(0);\n        return std::make_pair(true, u(corner));\n      } else {\n        return std::make_pair(false, 42.0);\n      }\n    };\n    lf::assemble::FixFlaggedSolutionComponents<double>(my_selector, A, phi);\n\n    const Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n    // Numerical Solution\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n    solver.compute(A_crs);\n    if (solver.info() != Eigen::Success) {\n      printf(\"Decomposition Failed.\\n\");\n    }\n    Eigen::VectorXd sol_vec = solver.solve(phi);\n\n    // Exact Solution\n    Eigen::VectorXd exact_sol(N_dofs);\n    for (int i = 0; i < N_dofs; ++i) {\n      const lf::mesh::Entity &entity{cur_dofh.Entity(i)};\n      const lf::geometry::Geometry *geo_p = entity.Geometry();\n      const Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n      exact_sol[i] = u(corners.col(0));\n    }\n\n    // L2 Error\n    double l2_error = (sol_vec - exact_sol).norm() / N_dofs;\n    vec_l2error.push_back(l2_error);\n    vec_Ndofs.push_back(N_dofs);\n  }\n\n  for (int i = 0; i < vec_l2error.size(); ++i) {\n    if (i > 0) {\n      double conv_rate =\n          (std::log(vec_l2error.at(i - 1)) - std::log(vec_l2error.at(i))) /\n          (std::log(vec_Ndofs.at(i)) - std::log(vec_Ndofs.at(i - 1)));\n      std::cout << \"N_dofs: \" << vec_Ndofs.at(i)\n                << \"; L2 Error: \" << vec_l2error.at(i)\n                << \"; Conv. rate: \" << conv_rate << std::endl;\n    } else {\n      std::cout << \"N_dofs: \" << vec_Ndofs.at(i)\n                << \"; L2 Error: \" << vec_l2error.at(i) << std::endl;\n    }\n  }\n  /* SAM_LISTING_END_1 */\n\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "f8ae37e9e28c7c6dc41d9e1cead52d90cf62c672", "size": 4646, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/UpwindFiniteVolume/mastersolution/upwindfinitevolume_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/UpwindFiniteVolume/mastersolution/upwindfinitevolume_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/UpwindFiniteVolume/mastersolution/upwindfinitevolume_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": 32.4895104895, "max_line_length": 79, "alphanum_fraction": 0.6056823074, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6772432790336342}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\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. See accompanying LICENSE file.\n */\n/* Test_extractDigits.cpp - extracting digits.\n *   For a plaintext space modulo a prime-power $p^e$, extracting\n *   the base-$p$ representation of an encrypted values.\n */\n#include <NTL/ZZ.h>\nNTL_CLIENT\n#include <helib/EncryptedArray.h>\n#include <helib/polyEval.h>\n#include <helib/debugging.h>\n#include <helib/ArgMap.h>\n\nusing namespace helib;\n\nstatic bool noPrint = false;\nstatic bool debug = 0;\n\n\nint main(int argc, char *argv[])\n{\n  ArgMap amap;\n  long p = 5;\n  long r=0;\n  long m = 0;\n  bool dry = false;\n\n  amap.arg(\"p\", p, \"plaintext base\");\n  amap.arg(\"r\", r, \"lifting\");\n  amap.arg(\"m\", m, \"the cyclotomic ring\", \"heuristic\");\n  amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n  amap.arg(\"debug\", debug, \"extra debugging\");\n  amap.arg(\"dry\", dry, \"dry=1 for a dry-run\");\n\n  // get parameters from the command line\n  amap.parse(argc, argv);\n\n  if (p<2) exit(0);\n  double lBound = 30.0;\n  long bound = floor(lBound/log2((double)p));\n  if (r<2 || r>bound) r = bound;\n  long p2r = power_long(p,r); // p^r\n\n  long ll = NextPowerOfTwo(p);\n  long L = (r*ll*3 +2)*30; // how many levels do we need\n  if (m==0)\n    m = p+1; // FindM(/*secparam=*/80, L, /*c=*/4, p, /*d=*/1, 0, m);\n  setDryRun(dry);\n\n  if (!noPrint) {\n    if (dry) cout << \"dry run: \";\n    cout << \"m=\"<<m<<\", p=\"<<p<<\", r=\"<<r<<\", L=\"<<L<<endl;\n  }\n  Context context(m, p, r);\n  buildModChain(context, L, /*c=*/4);\n\n  SecKey secretKey(context);\n  const PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(); // A +-1/0 secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n\n  if (debug) {\n      dbgKey = &secretKey; // debugging key and ea\n      dbgEa = context.ea;\n  }\n#ifdef HELIB_DEBUG\n  dbgKey = &secretKey; // debugging key and ea\n  dbgEa = context.ea;\n#endif //HELIB_DEBUG\n\n  EncryptedArray ea(context);\n  vector<long> v;\n  vector<long> pDigits;\n  ea.random(v); // random values in the slots\n\n  Ctxt c(publicKey);\n  ea.encrypt(c, publicKey, v);\n  ea.decrypt(c, secretKey, pDigits);\n  if (ea.size()<=20 && !noPrint)\n    cout << \"plaintext=\"<<pDigits<<endl;\n\n\n  if (!noPrint)\n    cout << \"extracting \"<<r<<\" digits...\" << std::flush;\n  vector<Ctxt> digits;\n  extractDigits(digits, c);\n  if (!noPrint)\n    cout << \" done\\n\" << std::flush;\n\n  vector<long> tmp = v;\n  long pp = p2r;\n  for (long i=0; i<(long)digits.size(); i++) {\n#if 0\n// removed isCorrect() for now as it is incorrectly defined\n    if (!digits[i].isCorrect()) {\n      cout << \" BAD, potential decryption error for \"<<i<<\"th digit \";\n      CheckCtxt(digits[i], \"\");\n      exit(0);\n    }\n#endif\n    ea.decrypt(digits[i], secretKey, pDigits);\n    if (ea.size()<=20 && !noPrint)\n      cout << i << \"th digit=\"<<pDigits<<endl;\n\n    // extract the next digit from the plaintext, compare to pDigits\n    for (long j=0; j<(long)v.size(); j++) {\n      long digit = tmp[j] % p;\n      if (digit > p/2) digit -= p;\n      else if (digit < -p/2) digit += p;\n\n      // assert ((pDigits[j]-digit) % p == 0);\n      if ((pDigits[j]-digit) % pp != 0) {\n        cout << \"BAD\\n\";\n        if (!noPrint)\n          cout << \" error: v[\"<<j<<\"]=\"<<v[j]\n               << \" but \"<<i<<\"th digit comes \"<< pDigits[j]\n               << \" rather than \"<<digit<<endl<<endl;\n\texit(0);\n      }\n      tmp[j] -= digit;\n      tmp[j] /= p;\n    }\n    pp /= p;\n  }\n  cout << \"GOOD\\n\";\n}\n", "meta": {"hexsha": "b1256328c1c32a82a0239a0f47eeb69a749eb3d7", "size": 3959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/legacy_tests/Test_extractDigits.cpp", "max_stars_repo_name": "ShixiongQi/HElib", "max_stars_repo_head_hexsha": "9973ccc68a292d5c52388eca40eac08ae11d0263", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 992.0, "max_stars_repo_stars_event_min_datetime": "2019-04-07T01:05:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:42:36.000Z", "max_issues_repo_path": "misc/legacy_tests/Test_extractDigits.cpp", "max_issues_repo_name": "maliasadi/HElib", "max_issues_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 180.0, "max_issues_repo_issues_event_min_datetime": "2019-04-29T20:19:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:11:15.000Z", "max_forks_repo_path": "misc/legacy_tests/Test_extractDigits.cpp", "max_forks_repo_name": "maliasadi/HElib", "max_forks_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 289.0, "max_forks_repo_forks_event_min_datetime": "2019-04-08T15:22:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:27:52.000Z", "avg_line_length": 29.1102941176, "max_line_length": 78, "alphanum_fraction": 0.6062136903, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.6772432763320745}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n\nnamespace ppl {\nnamespace math {\n\ninline size_t padded_length(size_t N)\n{\n    return std::pow(2, std::ceil(std::log(N)/std::log(2.)));\n}\n\n/**\n * Computes autocorrelation of x where each column of x\n * is a component of a process and hence each row is a time point.\n * More mathematically, x(i,...) is the process value at time i.\n *\n * For more detail, see: \n * https://lingpipe-blog.com/2012/06/08/autocorrelation-fft-kiss-eigen/\n * https://github.com/stan-dev/math/blob/41e548e19da5675121c245b535d4019c8bbd754b/stan/math/prim/mat/fun/autocorrelation.hpp\n *\n * @tparam  T   underlying value type (usually double)\n * @param   x   process matrix\n */\ntemplate <class T>\ninline auto autocorrelation(const Eigen::MatrixBase<T>& x)\n{\n    using scalar_t = typename T::Scalar;\n    using complex_t = std::complex<scalar_t>;\n\n    size_t n_rows = x.rows();\n    size_t padded_len = 2*padded_length(n_rows);\n\n    Eigen::Matrix<scalar_t, Eigen::Dynamic, Eigen::Dynamic> out(x.rows(), x.cols());\n\n    Eigen::FFT<scalar_t> fft;\n\n    for (int i = 0; i < x.cols(); ++i) {\n\n        // create centered copy of x\n        Eigen::Matrix<scalar_t, Eigen::Dynamic, 1> x_cent(padded_len);\n        x_cent.setZero();\n        x_cent.head(n_rows) = x.col(i).array() - x.col(i).mean();\n\n        // FFT \n        Eigen::Matrix<complex_t, Eigen::Dynamic, 1> freq(padded_len);\n        fft.fwd(freq, x_cent);\n\n        // compute complex-norm element-wise\n        freq = freq.array().abs2();\n\n        // inverse FFT and trim to shape of x\n        Eigen::Matrix<complex_t, Eigen::Dynamic, 1> ifreq(padded_len);\n        fft.inv(ifreq, freq);\n\n        // get autocorrelation by normalizing by variance\n        out.col(i) = ifreq.head(n_rows).real() / (n_rows * n_rows * 2.);\n        out.col(i) /= out(0,i);\n\n    }\n\n    return out;\n}\n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "941c1e6f886fae224b07d90dc5b092d49141c8c7", "size": 1904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/autocorrelation.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/autocorrelation.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/autocorrelation.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 28.4179104478, "max_line_length": 124, "alphanum_fraction": 0.6428571429, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6772097402460495}}
{"text": "#include \"adapter_creator.hpp\"\n#include \"experiment_helpers.hpp\"\n#include <Eigen/SVD>\n#include <iostream>\n\nvoid create_random_pose(opengv::rotation_t & rotation, opengv::translation_t & position, const double & noise, const double & outlierFraction, const size_t & numberPoints, const int & numberCameras,opengv::bearingVectors_t & bearingVectors, std::vector<int> & camCorrespondences, opengv::points_t & points, opengv::translations_t & camOffsets, opengv::rotations_t & camRotations){\n  \n  //create a random camera-system\n  opengv::generateRandomCameraSystem( numberCameras, camOffsets, camRotations );\n  \n  //derive correspondences based on random point-cloud\n  Eigen::MatrixXd gt(3,numberPoints);\n  opengv::generateRandom2D3DCorrespondences(position, rotation, camOffsets, camRotations, numberPoints, noise, outlierFraction, bearingVectors, points, camCorrespondences, gt );\n  \n  //print the experiment characteristics\n  opengv::printExperimentCharacteristics(\n\t\t\t\t position, rotation, noise, outlierFraction );\n}\n\nvoid choose_best_transformation(const opengv::transformations_t &solutions, const opengv::transformation_t & ref, opengv::transformation_t & transformation_method){\n  double error = 1e7;\n  int index = 0;\n  for(int i = 0; i < solutions.size(); ++i){\n    if(error > (ref - solutions[i] ).norm()){\n      error = (ref - solutions[i] ).norm();\n      index = i;\n    }\n  }\n  transformation_method = solutions[index];\n }\n\nvoid choose_best_essential_matrix(const opengv::essentials_t & solutions, const opengv::essential_t & ref, opengv::essential_t & essential_matrix){\n  if(solutions.size() == 1){\n    essential_matrix = solutions[0];\n  }\n  double error = 1e7;\n  int index = 0;\n  for(int i = 0; i < solutions.size(); ++i){\n    if(error > (ref - solutions[i]).norm()){\n      error = (ref - solutions[i]).norm();\n      index = i;\n    }\n  }\n  essential_matrix = solutions[index];\n}\n\n\nopengv::essential_t calculate_essential_matrix(const opengv::translation_t & position, const opengv::rotation_t & rotation)\n{\n  //E transforms vectors from vp 2 to 1: x_1^T * E * x_2 = 0\n  //and E = (t)_skew*R\n  Eigen::Matrix3d t_skew = Eigen::Matrix3d::Zero();\n  t_skew(0,1) = -position[2];\n  t_skew(0,2) = position[1];\n  t_skew(1,0) = position[2];\n  t_skew(1,2) = -position[0];\n  t_skew(2,0) = -position[1];\n  t_skew(2,1) = position[0];\n  opengv::essential_t E = t_skew * rotation;\n  std::cout << \"the random essential matrix is:\" << std::endl;\n  std::cout << E << std::endl;\n  return E;\n}\n\n\nopengv::transformation_t calculate_transformation_from_essential_matrix(const opengv::essential_t & essential_matrix, const opengv::rotation_t &ref_rotation, const opengv::translation_t & ref_translation){\n  //Obtain matrices U and V\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(essential_matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n  Eigen::Matrix3d sing_values = Eigen::Matrix3d::Zero(3,3);\n  sing_values(0,0) = svd.singularValues()(0,0);\n  sing_values(1,1) = svd.singularValues()(1,0);\n\n  double detU = U.determinant();\n  if (detU < 0){\n    U = -U;\n  }\n  \n  double detV = V.determinant();\n  if (detV < 0){\n    V = -V;\n  }\n  \n  Eigen::Matrix3d Rz = Eigen::Matrix3d::Zero(3,3);\n  Rz(0,1) = -1;Rz(1,0) = 1; Rz(2,2) = 1;\n\n  \n  opengv::rotation_t r = U * Rz.transpose() * V.transpose();\n  Eigen::MatrixXd skew_t = U * Rz * sing_values * U.transpose();\n  Eigen::MatrixXd t = Eigen::MatrixXd::Zero(3,1);\n  t(0,0) = skew_t(2,1);t(1,0) = skew_t(0,2); t(2,0) = skew_t(1,0);\n  \n  if ( (r - ref_rotation).norm() > 1e-6){\n    r = U * Rz * V.transpose();\n  }\n  if( (t - ref_translation).norm() > 1e-6){\n    skew_t = U * Rz.transpose() * sing_values * U.transpose();\n    t(0,0) = skew_t(2,1);t(1,0) = skew_t(0,2); t(2,0) = skew_t(1,0);\n  }\n  \n  opengv::transformation_t result;\n  result.block<3,3>(0,0) = r;\n  result.block<3,1>(0,3) = t;\n  return result;\n}\n", "meta": {"hexsha": "e74067074564c4c5a7acbb16997b65e13fd278ab", "size": 3910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/adapter_creator.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "test/adapter_creator.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/adapter_creator.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 36.5420560748, "max_line_length": 380, "alphanum_fraction": 0.6777493606, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6772097252310884}}
{"text": "#include <Eigen/StdVector>\n\n#include <pcl/kdtree/kdtree_flann.h>\n#include <week_scanmatching/icp/icp.h>\n#include <Eigen/Core>\n\nnamespace scanmatcher\n{\nResult ICP::scanmatch(const pcl::PointCloud<pcl::PointXYZ>& input, const pcl::PointCloud<pcl::PointXYZ>& target,\n                      const Eigen::Isometry3d& prediction)\n{\n  // Transformation is sR(p_i) + t\n  Eigen::Isometry3d total_transform = Eigen::Isometry3d::Identity();\n  double error = std::numeric_limits<double>::infinity();\n\n  // TODO(Oswin) Parametrize this\n  int max_iterations = 500;\n  double threshold = 1e-5;\n  double correspondance_outlier_threshold = 0.5;\n\n  int num_input = input.points.size();\n\n  Eigen::Matrix3Xd aligned_input(3, num_input);\n  for (int i = 0; i < num_input; i++)\n  {\n    aligned_input.col(i) = input[i].getVector3fMap().cast<double>();\n  }\n\n  Eigen::Matrix3Xd target_corresp(3, num_input);\n\n  // Construct KD tree for target for finding closest points\n  pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;\n  pcl::PointCloud<pcl::PointXYZ>::Ptr target_ptr(new pcl::PointCloud<pcl::PointXYZ>);\n  *target_ptr = target;\n  kdtree.setInputCloud(target_ptr);\n\n  for (int i = 0; i < max_iterations; i++)\n  {\n    // TODO(Oswin) Make this a KD tree\n    std::vector<int> inlier_indices{};\n    for (int j = 0; j < num_input; j++)\n    {\n      pcl::PointXYZ pcl_point;\n      pcl_point.getVector3fMap() = aligned_input.col(j).cast<float>();\n      std::vector<int> closest_idx;\n      std::vector<float> distance;\n      kdtree.nearestKSearch(pcl_point, 1, closest_idx, distance);\n      auto closest_point = target[closest_idx.front()];\n      target_corresp.col(j) = closest_point.getVector3fMap().cast<double>();\n\n      if (std::sqrt(distance.front()) < correspondance_outlier_threshold)\n      {\n        inlier_indices.emplace_back(j);\n      }\n    }\n\n    int num_inliers = inlier_indices.size();\n    if (num_inliers < 4)\n    {\n      return { Eigen::Affine3d::Identity(), std::numeric_limits<double>::infinity() };\n    }\n    Eigen::Matrix3Xd inlier_input(3, num_inliers);\n    Eigen::Matrix3Xd inlier_corresp(3, num_inliers);\n\n    for (int idx = 0; idx < num_inliers; idx++)\n    {\n      int inlier_index = inlier_indices[idx];\n      inlier_input.col(idx) = aligned_input.col(inlier_index);\n      inlier_corresp.col(idx) = target_corresp.col(inlier_index);\n    }\n\n    Eigen::VectorXd weights = Eigen::VectorXd::Ones(num_inliers);\n    Eigen::Isometry3d transform = getRigidTransform(weights, inlier_input, inlier_corresp);\n    total_transform = transform * total_transform;\n\n    error = 0.0;\n    for (int j = 0; j < num_input; j++)\n    {\n      aligned_input.col(j) = transform * aligned_input.col(j);\n      error += (target_corresp.col(j) - aligned_input.col(j)).squaredNorm();\n    }\n    error /= num_input;\n\n    if (error < threshold)\n    {\n      break;\n    }\n  }\n\n  Eigen::Affine3d affine_transform{ total_transform };\n  return { affine_transform, error };\n}\n\nEigen::Isometry3d ICP::getRigidTransform(const Eigen::VectorXd& weights, const Eigen::Matrix3Xd& input,\n                                         const Eigen::Matrix3Xd& target) const\n{\n  const int dims = input.cols();\n\n  // 1: Compute weighted centroids of input and target\n  const double weights_sum_inverse = 1.0 / weights.sum();\n  const Eigen::Vector3d input_centroid =\n      (input.array().rowwise() * weights.array().transpose()).rowwise().sum() * weights_sum_inverse;\n  const Eigen::Vector3d target_centroid =\n      (target.array().rowwise() * weights.array().transpose()).rowwise().sum() * weights_sum_inverse;\n\n  // 2: Subtract centroids from input and target\n  const Eigen::Matrix3Xd input_prime = input.colwise() - input_centroid;\n  const Eigen::Matrix3Xd target_prime = target.colwise() - target_centroid;\n\n  // 3: Compute S = X W Y^T\n  const Eigen::MatrixXd s = target_prime * weights.asDiagonal() * input_prime.transpose();\n  const Eigen::JacobiSVD<Eigen::MatrixXd> svd(s, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::Matrix3d rotation_matrix = svd.matrixV() * svd.matrixU().transpose();\n\n  if (rotation_matrix.determinant() < 0)\n  {\n    Eigen::MatrixXd altered_v = svd.matrixV();\n    altered_v.col(dims) *= -1;\n    rotation_matrix = altered_v * svd.matrixU().transpose();\n  }\n\n  Eigen::Isometry3d transform{ rotation_matrix.transpose() };\n  transform.translation() = target_centroid - rotation_matrix * input_centroid;\n\n  return transform;\n}\n}  // namespace scanmatcher\n", "meta": {"hexsha": "6c1779d7f10e1f79f998e38f46ea743b1ed27238", "size": 4411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igvc_training_exercises/src/week_scanmatching/icp/icp.cpp", "max_stars_repo_name": "oswinso/ros_training_exercises", "max_stars_repo_head_hexsha": "33388d6d66e32a792583d534f20ef152030df84e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-09-28T21:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T18:30:01.000Z", "max_issues_repo_path": "code/igvc_training_exercises/src/week_scanmatching/icp/icp.cpp", "max_issues_repo_name": "RoboJackets/igvc-training", "max_issues_repo_head_hexsha": "cb236134db2cab9a99d5b8d0248f2d00deebf793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-09-07T19:41:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-01T15:11:21.000Z", "max_forks_repo_path": "code/igvc_training_exercises/src/week_scanmatching/icp/icp.cpp", "max_forks_repo_name": "RoboJackets/igvc-training", "max_forks_repo_head_hexsha": "cb236134db2cab9a99d5b8d0248f2d00deebf793", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 50.0, "max_forks_repo_forks_event_min_datetime": "2017-09-24T21:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T20:25:51.000Z", "avg_line_length": 34.4609375, "max_line_length": 112, "alphanum_fraction": 0.6817048288, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6772097181907766}}
{"text": "#include \"RasRandomNumber.h\"\n\n#include <chrono> // for seconds, milliseconds, nanoseconds, picoseconds\n#include <Eigen/Cholesky>\nusing namespace Eigen;\n\n\nunsigned RasRandomNumber::ras_now_nanoseconds(void)\n{\n    std::chrono::nanoseconds ns = std::chrono::duration_cast< std::chrono::nanoseconds >(std::chrono::system_clock::now().time_since_epoch());\n    return unsigned(ns.count() % 100000000)+std::rand();\n}\n\n\nstd::vector<std::vector<double> > RasRandomNumber::ras_mvnorm(unsigned long int n, std::vector<double> &mu, std::vector<std::vector<double> > &corr, unsigned seed)\n{\n    if (seed==0) seed=ras_now_nanoseconds();\n    std::default_random_engine generator(seed);\n    std::normal_distribution<double> distribution(0.0,1.0);\n    \n    // chol is cholesky decomposition, should be square\n    int ncol=(int)corr.size();\n    \n    MatrixXd A(ncol,ncol);\n    for (int i=0; i<ncol; i++)\n        for (int j=0; j<ncol; j++)\n            A(i,j)=corr[i][j];\n        \n    MatrixXd U = A.llt().matrixU();\n    std::vector<std::vector<double> > chol(ncol,std::vector<double> (ncol,0) );\n    for (int i=0; i<ncol; i++)\n        for (int j=0; j<ncol; j++)\n            chol[i][j]=U(i,j);\n    \n    \n    // initialization\n    std::vector<std::vector<double> > ret(n,std::vector<double> (ncol,0));\n    std::vector<std::vector<double> > z  (n,std::vector<double> (ncol,0));\n    \n    \n    for (unsigned long int i=0; i<n; i++){\n        for (int j=0; j<ncol; j++){\n            z[i][j] = distribution(generator); // standard normal rv\n        }\n    }\n    std::vector<std::vector<double> > C= RasMatrix::ras_prod_mat(z,chol);\n    for (unsigned long int i=0; i<n; i++){\n        for (int j=0; j<ncol; j++){\n            ret[i][j]=mu[j]+C[i][j];\n        }\n    }\n    return ret;\n}\n\n\n\nstd::vector<int> RasRandomNumber::ras_rpois(unsigned long int n, double lam, unsigned seed)\n{\n    if (seed==0) seed=ras_now_nanoseconds();\n    std::default_random_engine generator(seed);\n    std::poisson_distribution<int> distribution(lam);\n    \n    std::vector<int> number(n);\n    for (unsigned long int i=0; i<n; i++)\n        number[i] = distribution(generator);\n    return number;\n}\n\nint RasRandomNumber::ras_rpois(double lam, unsigned seed)\n{\n    //    std::default_random_engine generator(time(0));\n    if (seed==0) seed=ras_now_nanoseconds();\n    std::default_random_engine generator(seed);\n    std::poisson_distribution<int> distribution(lam);\n    \n    int number = distribution(generator);\n    return number;\n}\n\n\n\ndouble RasRandomNumber::ras_uniform(unsigned seed)\n{\n    if (seed==0) seed=ras_now_nanoseconds();\n    static std::default_random_engine re(seed);\n    static std::uniform_real_distribution<double> Dist(0,1);\n    return Dist(re);\n}\n\nstd::vector<unsigned long int> RasRandomNumber::ras_SampleWithoutReplacement(unsigned long int populationSize, unsigned long int sampleSize, unsigned seed)\n{\n    if (seed==0) seed=ras_now_nanoseconds();\n    static std::default_random_engine re(seed);\n    static std::uniform_real_distribution<double> Dist(0,1);\n\n    // Use Knuth's variable names\n    std::vector<unsigned long int> samples(sampleSize);\n    int n = sampleSize;\n    int N = populationSize;\n    \n    int t = 0; // total input records dealt with\n    int m = 0; // number of items selected so far\n    double u;\n    \n    while (m < n)\n    {\n        u = Dist(re); // call a uniform(0,1) random number generator\n        \n        if ( (N - t)*u >= n - m )\n        {\n            t++;\n        }\n        else\n        {\n            samples[m] = t;\n            t++; m++;\n        }\n    }\n    return samples;\n}\n\n\n", "meta": {"hexsha": "591d0fc25eb86823fe9994e3b9574eef653c561c", "size": 3574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RasRandomNumber.cpp", "max_stars_repo_name": "rtahmasbi/GeneEvolve", "max_stars_repo_head_hexsha": "84e908d99d440787e26a6bf304492b98cd7205df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-01-25T19:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T18:32:45.000Z", "max_issues_repo_path": "src/RasRandomNumber.cpp", "max_issues_repo_name": "rtahmasbi/GeneEvolve", "max_issues_repo_head_hexsha": "84e908d99d440787e26a6bf304492b98cd7205df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-01T23:19:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-15T21:48:50.000Z", "max_forks_repo_path": "src/RasRandomNumber.cpp", "max_forks_repo_name": "rtahmasbi/GeneEvolve", "max_forks_repo_head_hexsha": "84e908d99d440787e26a6bf304492b98cd7205df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-05T19:38:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T19:07:53.000Z", "avg_line_length": 29.0569105691, "max_line_length": 163, "alphanum_fraction": 0.6197537773, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.67720287491573}}
{"text": "#pragma once\n// gauss_jordan.hpp: Gauss-Jordan matrix inversion\n//\n// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPR-BLAS project, which is released under an MIT Open Source license.\n\n#include <boost/numeric/mtl/mtl.hpp>\n\nnamespace sw {\nnamespace hprblas {\n\ntemplate<typename Matrix>\nMatrix GaussJordanInversion(const Matrix& A) {\n\tusing Scalar = typename mtl::Collection<Matrix>::value_type;\n\n\tsize_t m = A.num_rows();\n\tsize_t n = A.num_cols();\n\tMatrix a(n, m), inv(m, n);\n\ta = A; // you need a deep copy\n\tinv = Scalar(1);\n\n\t// Performing elementary operations \n\tfor (unsigned i = 0; i < m; ++i) {\n\t\tif (a[i][i] == 0) {\n\t\t\tunsigned c = 1;\n\t\t\twhile (a[i + c][i] == 0 && (i + c) < n)\t++c;\n\t\t\tif ((i + c) == n) break;\n\n\t\t\tfor (unsigned j = i, k = 0; k < n; ++k) {\n\t\t\t\tstd::swap(a[j][k], a[j + c][k]);\n\t\t\t\tstd::cerr << \"TBD\" << std::endl; // need to create a permutation matrix\n\t\t\t}\n\t\t}\n\t\t// transform to diagonal matrix\n\t\tfor (unsigned j = 0; j < m; j++) {\n\t\t\tif (i != j) {\n\t\t\t\tScalar scale = a[j][i] / a[i][i];\n\t\t\t\tfor (unsigned k = 0; k < n; ++k) {\n\t\t\t\t\ta[j][k] = a[j][k] - a[i][k] * scale;\n\t\t\t\t\tinv[j][k] = inv[j][k] - inv[i][k] * scale;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//std::cout << i << \",\" << j << std::endl;\n\t\t\t//sw::hprblas::printMatrix(std::cout, \"a\", a);\n\t\t\t//sw::hprblas::printMatrix(std::cout, \"inv\", inv);\n\t\t}\n\t}\n\t// transform to identity matrix\n\tfor (unsigned i = 0; i < m; ++i) {\n\t\tScalar normalize = a[i][i];\n\t\ta[i][i] = Scalar(1);\n\t\tfor (unsigned j = 0; j < n; ++j) {\n\t\t\tinv[i][j] /= normalize;\n\t\t}\n\t}\n\t//printMatrix(std::cout, \"conversion\", a);\n\treturn inv;\n}\n\n} // namespace hprblas\n} // namespace sw", "meta": {"hexsha": "566b067cb81314b5a4d8e51f67deff5830c4f14d", "size": 1644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solvers/gauss_jordan.hpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "include/solvers/gauss_jordan.hpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "include/solvers/gauss_jordan.hpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 26.5161290323, "max_line_length": 97, "alphanum_fraction": 0.5638686131, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.677186239369435}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n\nTEST(AgradRev,expm1) {\n  AVAR a = 1.3;\n  AVAR f = expm1(a);\n  EXPECT_FLOAT_EQ(boost::math::expm1(1.3), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(std::exp(1.3), grad_f[0]);\n}  \n\nstruct expm1_fun {\n  template <typename T0>\n  inline T0\n  operator()(const T0& arg1) const {\n    return expm1(arg1);\n  }\n};\n\nTEST(AgradRev,expm1_NaN) {\n  expm1_fun expm1_;\n  test_nan(expm1_,false,true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 1.3;\n  test::check_varis_on_stack(expm1(a));\n}\n", "meta": {"hexsha": "73856f038dc3cd588d3e5d1b6922336cf8437e28", "size": 733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/expm1_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/expm1_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/expm1_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9428571429, "max_line_length": 52, "alphanum_fraction": 0.6848567531, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6771784297057246}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//      Copyright Christopher Kormanyos 2012 - 2015, 2020.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n//\n\n// This example uses Boost.Multiprecision to implement\n// a high-precision Gauss-Laguerre quadrature integration.\n// The quadrature is used to calculate the airy_ai(x) function\n// for real-valued x on the positive axis with x.ge.1.\n\n// In this way, the integral representation could be seen\n// as part of a scheme to calculate real-valued Airy functions\n// on the positive axis for medium to large argument.\n// A Taylor series or hypergeometric function (not part\n// of this example) could be used for smaller arguments.\n\n// This example has been tested with decimal digits counts\n// ranging from 21...301, by adjusting the parameter\n// local::my_digits10 at compile time.\n\n// The quadrature integral representaion of airy_ai(x) used\n// in this example can be found in:\n\n// A. Gil, J. Segura, N.M. Temme, \"Numerical Methods for Special\n// Functions\" (SIAM Press 2007), Sect. 5.3.3, in particular Eq. 5.110,\n// page 145. Subsequently, Gil et al's book cites the another work:\n// W. Gautschi, \"Computation of Bessel and Airy functions and of\n// related Gaussian quadrature formulae\", BIT, 42 (2002), pp. 110-118.\n\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <tuple>\n#include <vector>\n\n#include <boost/cstdfloat.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/noncopyable.hpp>\n\nnamespace gauss { namespace laguerre {\n\nnamespace util {\n\nvoid progress_bar(std::ostream& os, const float percent);\n\nvoid progress_bar(std::ostream& os, const float percent)\n{\n  std::stringstream strstrm;\n\n  strstrm.precision(1);\n\n  strstrm << std::fixed << percent << \"%\";\n\n  os << strstrm.str() << \"\\r\";\n\n  os.flush();\n}\n\n}\n\nnamespace detail\n{\n  template<typename T>\n  class laguerre_l_object BOOST_FINAL\n  {\n  public:\n    laguerre_l_object(const int n, const T a) noexcept\n      : order(n),\n        alpha(a),\n        p1   (0),\n        d2   (0) { }\n\n    laguerre_l_object& operator=(const laguerre_l_object& other)\n    {\n      if(this != other)\n      {\n        order = other.order;\n        alpha = other.alpha;\n        p1    = other.p1;\n        d2    = other.d2;\n      }\n\n      return *this;\n    }\n\n    T operator()(const T& x) const noexcept\n    {\n      // Calculate (via forward recursion):\n      // * the value of the Laguerre function L(n, alpha, x), called (p2),\n      // * the value of the derivative of the Laguerre function (d2),\n      // * and the value of the corresponding Laguerre function of\n      //   previous order (p1).\n\n      // Return the value of the function (p2) in order to be used as a\n      // function object with Boost.Math root-finding. Store the values\n      // of the Laguerre function derivative (d2) and the Laguerre function\n      // of previous order (p1) in class members for later use.\n\n        p1 = T(0);\n      T p2 = T(1);\n        d2 = T(0);\n\n      T j_plus_alpha = alpha;\n      T two_j_plus_one_plus_alpha_minus_x = (1 + alpha) - x;\n\n      const T my_two = 2;\n\n      for(int j = 0; j < order; ++j)\n      {\n        const T p0(p1);\n\n        // Set the value of the previous Laguerre function.\n        p1 = p2;\n\n        // Use a recurrence relation to compute the value of the Laguerre function.\n        p2 = ((two_j_plus_one_plus_alpha_minus_x * p1) - (j_plus_alpha * p0)) / (j + 1);\n\n        ++j_plus_alpha;\n        two_j_plus_one_plus_alpha_minus_x += my_two;\n      }\n\n      // Set the value of the derivative of the Laguerre function.\n      d2 = ((p2 * order) - (j_plus_alpha * p1)) / x;\n\n      // Return the value of the Laguerre function.\n      return p2;\n    }\n\n    const T previous  () const noexcept { return p1; }\n    const T derivative() const noexcept { return d2; }\n\n    static bool root_tolerance(const T& a, const T& b) noexcept\n    {\n      using std::fabs;\n\n      // The relative tolerance here is: ((a - b) * 2) / (a + b).\n      return ((fabs(a - b) * 2) < (fabs(a + b) * std::numeric_limits<T>::epsilon()));\n    }\n\n  private:\n    const   int order;\n    const   T   alpha;\n    mutable T   p1;\n    mutable T   d2;\n  };\n\n  template<typename T>\n  class abscissas_and_weights : private boost::noncopyable\n  {\n  public:\n    abscissas_and_weights(const int n, const T a) : order(n),\n                                                    alpha(a),\n                                                    xi   (),\n                                                    wi   ()\n    {\n      if(alpha < -20.0F)\n      {\n        // Users can decide to perform different range checking.\n        std::cout << \"Range error: the order of the Laguerre function must exceed -20.0.\"\n                  << std::endl;\n      }\n      else\n      {\n        calculate();\n      }\n    }\n\n    const std::vector<T>& abscissa_n() const noexcept { return xi; }\n    const std::vector<T>& weight_n  () const noexcept { return wi; }\n\n  private:\n    const int order;\n    const T   alpha;\n\n    std::vector<T> xi;\n    std::vector<T> wi;\n\n    abscissas_and_weights() : order(),\n                              alpha(),\n                              xi   (),\n                              wi   () { }\n\n    void calculate()\n    {\n      using std::abs;\n\n      std::cout << \"Finding the approximate roots...\" << std::endl;\n\n      std::vector<std::tuple<T, T>> root_estimates;\n\n      root_estimates.reserve(static_cast<typename std::vector<std::tuple<T, T>>::size_type>(order));\n\n      const laguerre_l_object<T> laguerre_root_object(order, alpha);\n\n      // Set the initial values of the step size and the running step\n      // to be used for finding the estimate of the first root.\n      T step_size  = 0.01F;\n      T step       = step_size;\n\n      T first_laguerre_root = 0.0F;\n\n      if(alpha < -1.0F)\n      {\n        // Iteratively step through the Laguerre function using a\n        // small step-size in order to find a rough estimate of\n        // the first zero.\n\n        const bool this_laguerre_value_is_negative = (laguerre_root_object(T(0)) < 0);\n\n        constexpr int j_max = 10000;\n\n        int j = 0;\n\n        while((j < j_max) && (this_laguerre_value_is_negative != (laguerre_root_object(step) < 0)))\n        {\n          // Increment the step size until the sign of the Laguerre function\n          // switches. This indicates a zero-crossing, signalling the next root.\n          step += step_size;\n\n          ++j;\n        }\n      }\n      else\n      {\n        // Calculate an estimate of the 1st root of a generalized Laguerre\n        // function using either a Taylor series or an expansion in Bessel\n        // function zeros. The Bessel function zeros expansion is from Tricomi.\n\n        // Here, we obtain an estimate of the first zero of cyl_bessel_j(alpha, x).\n\n        T j_alpha_m1;\n\n        if(alpha < 1.4F)\n        {\n          // For small alpha, use a short series obtained from Mathematica(R).\n          // Series[BesselJZero[v, 1], {v, 0, 3}]\n          // N[%, 12]\n          j_alpha_m1 = (((          T(0.09748661784476F)\n                          * alpha - T(0.17549359276115F))\n                          * alpha + T(1.54288974259931F))\n                          * alpha + T(2.40482555769577F));\n        }\n        else\n        {\n          // For larger alpha, use the first line of Eqs. 10.21.40 in the NIST Handbook.\n          const T alpha_pow_third(boost::math::cbrt(alpha));\n          const T alpha_pow_minus_two_thirds(T(1) / (alpha_pow_third * alpha_pow_third));\n\n          j_alpha_m1 = alpha * (((((                             + T(0.043F)\n                                    * alpha_pow_minus_two_thirds - T(0.0908F))\n                                    * alpha_pow_minus_two_thirds - T(0.00397F))\n                                    * alpha_pow_minus_two_thirds + T(1.033150F))\n                                    * alpha_pow_minus_two_thirds + T(1.8557571F))\n                                    * alpha_pow_minus_two_thirds + T(1.0F));\n        }\n\n        const T vf             = (  T(order * 4U)\n                                  + T(alpha * 2U)\n                                  + T(2U));\n        const T vf2            = vf * vf;\n        const T j_alpha_m1_sqr = j_alpha_m1 * j_alpha_m1;\n\n        first_laguerre_root = (j_alpha_m1_sqr * (   -T(0.6666666666667F)\n                                                 + ((T(0.6666666666667F) * alpha) * alpha)\n                                                 +  (T(0.3333333333333F) * j_alpha_m1_sqr) + vf2)) / (vf2 * vf);\n      }\n\n      bool this_laguerre_value_is_negative = (laguerre_root_object(T(0)) < 0);\n\n      // Re-set the initial value of the step-size based on the\n      // estimate of the first root.\n      step_size = first_laguerre_root / 2;\n      step      = step_size;\n\n      // Step through the Laguerre function using a step-size\n      // of dynamic width in order to find the zero crossings\n      // of the Laguerre function, providing rough estimates\n      // of the roots. Refine the brackets with a few bisection\n      // steps, and store the results as bracketed root estimates.\n\n      while(root_estimates.size() < static_cast<std::size_t>(order))\n      {\n        // Increment the step size until the sign of the Laguerre function\n        // switches. This indicates a zero-crossing, signalling the next root.\n        step += step_size;\n\n        if(this_laguerre_value_is_negative != (laguerre_root_object(step) < 0))\n        {\n          // We have found the next zero-crossing.\n\n          // Change the running sign of the Laguerre function.\n          this_laguerre_value_is_negative = (!this_laguerre_value_is_negative);\n\n          // We have found the first zero-crossing. Put a loose bracket around\n          // the root using a window. Here, we know that the first root lies\n          // between (x - step_size) < root < x.\n\n          // Before storing the approximate root, perform a couple of\n          // bisection steps in order to tighten up the root bracket.\n          std::uintmax_t a_couple_of_iterations = 4U;\n\n          const std::pair<T, T>\n            root_estimate_bracket = boost::math::tools::bisect(laguerre_root_object,\n                                                               step - step_size,\n                                                               step,\n                                                               laguerre_l_object<T>::root_tolerance,\n                                                               a_couple_of_iterations);\n\n          static_cast<void>(a_couple_of_iterations);\n\n          // Store the refined root estimate as a bracketed range in a tuple.\n          root_estimates.push_back(std::tuple<T, T>(std::get<0>(root_estimate_bracket),\n                                                    std::get<1>(root_estimate_bracket)));\n\n          if(    (root_estimates.size() == 1U)\n             || ((root_estimates.size() % 8U) == 0U)\n             ||  (root_estimates.size() == static_cast<std::size_t>(order)))\n          {\n            const float progress = (100.0F * static_cast<float>(root_estimates.size())) / static_cast<float>(order);\n\n            std::cout << \"root_estimates.size(): \"\n                      << root_estimates.size()\n                      << \", \"\n                      ;\n\n            util::progress_bar(std::cout, progress);\n          }\n\n          if(root_estimates.size() >= static_cast<std::size_t>(2U))\n          {\n            // Determine the next step size. This is based on the distance between\n            // the previous two roots, whereby the estimates of the previous roots\n            // are computed by taking the average of the lower and upper range of\n            // the root-estimate bracket.\n\n            const T r0 = (  std::get<0>(*(root_estimates.crbegin() + 1U))\n                          + std::get<1>(*(root_estimates.crbegin() + 1U))) / 2;\n\n            const T r1 = (  std::get<0>(*root_estimates.crbegin())\n                          + std::get<1>(*root_estimates.crbegin())) / 2;\n\n            const T distance_between_previous_roots = r1 - r0;\n\n            step_size = distance_between_previous_roots / 3;\n          }\n        }\n      }\n\n      const T norm_g =\n        ((alpha == 0) ? T(-1)\n                      : -boost::math::tgamma(alpha + order) / boost::math::factorial<T>(order - 1));\n\n      xi.reserve(root_estimates.size());\n      wi.reserve(root_estimates.size());\n\n      std::cout << std::endl;\n\n      // Calculate the abscissas and weights to full precision.\n      for(std::size_t i = static_cast<std::size_t>(0U); i < root_estimates.size(); ++i)\n      {\n        if(   ((i % 8U) == 0U)\n           || ( i == root_estimates.size() - 1U))\n        {\n          const float progress = (100.0F * static_cast<float>(i + 1U)) / static_cast<float>(root_estimates.size());\n\n          std::cout << \"Calculating abscissas and weights. Processed \"\n                    << (i + 1U)\n                    << \", \"\n                    ;\n\n          util::progress_bar(std::cout, progress);\n        }\n\n        // Calculate the abscissas using iterative root-finding.\n\n        // Select the maximum allowed iterations, being at least 20.\n        // The determination of the maximum allowed iterations is\n        // based on the number of decimal digits in the numerical\n        // type T.\n        constexpr int local_math_tools_digits10 =\n          static_cast<int>(static_cast<boost::float_least32_t>(boost::math::tools::digits<T>()) * BOOST_FLOAT32_C(0.301));\n\n        const std::uintmax_t number_of_iterations_allowed = (std::max)(20, local_math_tools_digits10 / 2);\n\n        std::uintmax_t number_of_iterations_used = number_of_iterations_allowed;\n\n        // Perform the root-finding using ACM TOMS 748 from Boost.Math.\n        const std::pair<T, T>\n          laguerre_root_bracket = boost::math::tools::toms748_solve(laguerre_root_object,\n                                                                    std::get<0>(root_estimates.at(i)),\n                                                                    std::get<1>(root_estimates.at(i)),\n                                                                    laguerre_l_object<T>::root_tolerance,\n                                                                    number_of_iterations_used);\n\n        static_cast<void>(number_of_iterations_used);\n\n        // Compute the Laguerre root as the average of the values from\n        // the solved root bracket.\n        const T laguerre_root = (  std::get<0>(laguerre_root_bracket)\n                                 + std::get<1>(laguerre_root_bracket)) / 2;\n\n        // Calculate the weight for this Laguerre root. Here, we calculate\n        // the derivative of the Laguerre function and the value of the\n        // previous Laguerre function on the x-axis at the value of this\n        // Laguerre root.\n        static_cast<void>(laguerre_root_object(laguerre_root));\n\n        // Store the abscissa and weight for this index.\n        xi.push_back(laguerre_root);\n        wi.push_back(norm_g / ((laguerre_root_object.derivative() * order) * laguerre_root_object.previous()));\n      }\n\n      std::cout << std::endl;\n    }\n  };\n\n  template<typename T>\n  struct airy_ai_object BOOST_FINAL\n  {\n  public:\n    airy_ai_object(const T& x)\n      : my_x     (x),\n        my_zeta  (((sqrt(x) * x) * 2) / 3),\n        my_factor(make_factor(my_zeta)) { }\n\n    T operator()(const T& t) const\n    {\n      using std::sqrt;\n\n      return my_factor / sqrt(boost::math::cbrt(2 + (t / my_zeta)));\n    }\n\n  private:\n    const T my_x;\n    const T my_zeta;\n    const T my_factor;\n\n    airy_ai_object() : my_x     (),\n                       my_zeta  (),\n                       my_factor() { }\n\n    static T make_factor(const T& z)\n    {\n      using std::exp;\n      using std::sqrt;\n\n      return 1 / ((sqrt(boost::math::constants::pi<T>()) * sqrt(boost::math::cbrt(z * 48))) * (exp(z) * boost::math::tgamma(T(5) / 6)));\n    }\n  };\n} // namespace detail\n\n} } // namespace gauss::laguerre\n\n\n// A float_type is created to handle the desired number of decimal digits from `cpp_dec_float` without using __expression_templates.\nstruct local\n{\n  static constexpr unsigned int my_digits10 = 101U;\n\n  typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<my_digits10>,\n                                        boost::multiprecision::et_off>\n  float_type;\n};\n\nstatic_assert(local::my_digits10 > 20U,\n                        \"Error: This example is intended to have more than 20 decimal digits\");\n\nint main()\n{\n  // Use Gauss-Laguerre quadrature integration to compute airy_ai(x / 7)\n  // with 7 <= x <= 120 and where x is incremented in steps of 1.\n\n  // During development of this example, we have empirically found\n  // the numbers of Gauss-Laguerre coefficients needed for convergence\n  // when using various counts of base-10 digits.\n\n  // Let's calibrate, for instance, the number of coefficients needed\n  // at the point x = 1.\n\n  // Empirical data lead to:\n  // Fit[{{21.0, 3.5}, {51.0, 11.1}, {101.0, 22.5}, {201.0, 46.8}}, {1, d, d^2}, d]\n  // FullSimplify[%]\n  // -1.28301 + (0.235487 + 0.0000178915 d) d\n\n  // We need significantly more coefficients at smaller real values than are needed\n  // at larger real values because the slope derivative of airy_ai(x) gets more\n  // steep as x approaches zero.\n\n  // This Gauss-Laguerre quadrature is designed for airy_ai(x) with real-valued x >= 1.\n\n  constexpr boost::float_least32_t d = static_cast<boost::float_least32_t>(std::numeric_limits<local::float_type>::digits10);\n\n  constexpr boost::float_least32_t laguerre_order_factor = -1.28301F + ((0.235487F + (0.0000178915F * d)) * d);\n\n  constexpr int laguerre_order = static_cast<int>(laguerre_order_factor * d);\n\n  std::cout << \"std::numeric_limits<local::float_type>::digits10: \" << std::numeric_limits<local::float_type>::digits10 << std::endl;\n  std::cout << \"laguerre_order: \" << laguerre_order << std::endl;\n\n  typedef gauss::laguerre::detail::abscissas_and_weights<local::float_type> abscissas_and_weights_type;\n\n  const abscissas_and_weights_type the_abscissas_and_weights(laguerre_order, local::float_type(-1) / 6);\n\n  bool result_is_ok = true;\n\n  for(std::uint32_t u = 7U; u < 121U; ++u)\n  {\n    const local::float_type x = local::float_type(u) / 7;\n\n    typedef gauss::laguerre::detail::airy_ai_object<local::float_type> airy_ai_object_type;\n\n    const airy_ai_object_type the_airy_ai_object(x);\n\n    const local::float_type airy_ai_value =\n      std::inner_product(the_abscissas_and_weights.abscissa_n().cbegin(),\n                         the_abscissas_and_weights.abscissa_n().cend(),\n                         the_abscissas_and_weights.weight_n().cbegin(),\n                         local::float_type(0U),\n                         std::plus<local::float_type>(),\n                         [&the_airy_ai_object](const local::float_type& this_abscissa,\n                                               const local::float_type& this_weight) -> local::float_type\n                         {\n                           return the_airy_ai_object(this_abscissa) * this_weight;\n                         });\n\n    static const local::float_type one_third = 1.0F / local::float_type(3U);\n\n    static const local::float_type one_over_pi_times_one_over_sqrt_three =\n      sqrt(one_third) * boost::math::constants::one_div_pi<local::float_type>();\n\n    const local::float_type sqrt_x = sqrt(x);\n\n    const local::float_type airy_ai_control =\n       (sqrt_x * one_over_pi_times_one_over_sqrt_three)\n      * boost::math::cyl_bessel_k(one_third, ((2.0F * x) * sqrt_x) * one_third);\n\n    std::cout << std::setprecision(std::numeric_limits<local::float_type>::digits10)\n              << \"airy_ai_value  : \"\n              << airy_ai_value\n              << std::endl;\n\n    std::cout << std::setprecision(std::numeric_limits<local::float_type>::digits10)\n              << \"airy_ai_control: \"\n              << airy_ai_control\n              << std::endl;\n\n    const local::float_type delta = fabs(1.0F - (airy_ai_control / airy_ai_value));\n\n    static const local::float_type tol(\"1E-\" + boost::lexical_cast<std::string>(std::numeric_limits<local::float_type>::digits10 - 7U));\n\n    result_is_ok &= (delta < tol);\n  }\n\n  std::cout << std::endl\n            << \"Total... result_is_ok: \"\n            << std::boolalpha\n            << result_is_ok\n            << std::endl;\n} // int main()\n\n/*\n\n\nPartial output:\n\n//[gauss_laguerre_quadrature_output_1\n\nstd::numeric_limits<local::float_type>::digits10: 101\nlaguerre_order: 2291\n\nFinding the approximate roots...\nroot_estimates.size(): 1, 0.0%\nroot_estimates.size(): 8, 0.3%\nroot_estimates.size(): 16, 0.7%\n...\nroot_estimates.size(): 2288, 99.9%\nroot_estimates.size(): 2291, 100.0%\n\n\nCalculating abscissas and weights. Processed 1, 0.0%\nCalculating abscissas and weights. Processed 9, 0.4%\n...\nCalculating abscissas and weights. Processed 2289, 99.9%\nCalculating abscissas and weights. Processed 2291, 100.0%\n//] [/gauss_laguerre_quadrature_output_1]\n\n//[gauss_laguerre_quadrature_output_2\n\nairy_ai_value  : 0.13529241631288141552414742351546630617494414298833070600910205475763353480226572366348710990874867334\nairy_ai_control: 0.13529241631288141552414742351546630617494414298833070600910205475763353480226572366348710990874868323\nairy_ai_value  : 0.11392302126009621102904231059693500086750049240884734708541630001378825889924647699516200868335286103\nairy_ai_control: 0.1139230212600962110290423105969350008675004924088473470854163000137882588992464769951620086833528582\n...\nairy_ai_value  : 3.8990420982303275013276114626640705170145070824317976771461533035231088620152288641360519429331427451e-22\nairy_ai_control: 3.8990420982303275013276114626640705170145070824317976771461533035231088620152288641360519429331426481e-22\n\nTotal... result_is_ok: true\n\n//] [/gauss_laguerre_quadrature_output_2]\n\n\n*/\n", "meta": {"hexsha": "08382a7ff734007b7f033f925d1c8abf33c3e111", "size": 22324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/multiprecision/example/gauss_laguerre_quadrature.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/gauss_laguerre_quadrature.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": "Libs/boost_1_76_0/libs/multiprecision/example/gauss_laguerre_quadrature.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "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": 36.2991869919, "max_line_length": 136, "alphanum_fraction": 0.5988174162, "num_tokens": 5662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6771784127733981}}
{"text": "//\n// Created by Amir Masoud Abdol on 2020-04-11\n//\n\n#include \"TestStrategy.h\"\n\n#include <boost/math/distributions/fisher_f.hpp>\n\nusing namespace sam;\nusing boost::math::fisher_f;\n\nvoid FTest::run(Experiment *experiment) {\n\n  static ResultType res;\n\n  // The first group is always the control group\n  for (int i{experiment->setup.nd()}, d{0}; i < experiment->setup.ng();\n       ++i, ++d %= experiment->setup.nd()) {\n\n    res =\n        f_test((*experiment)[d].stddev_, (*experiment)[d].nobs_,\n               (*experiment)[i].stddev_, (*experiment)[i].nobs_, params.alpha);\n\n    (*experiment)[i].stats_ = res.fstat;\n    (*experiment)[i].pvalue_ = res.pvalue;\n    (*experiment)[i].sig_ = res.sig;\n  }\n}\n\nFTest::ResultType FTest::f_test(float Sd1,   // Sample 1 std deviation\n                                unsigned Sn1, // Sample 1 size\n                                float Sd2,   // Sample 2 std deviation\n                                unsigned Sn2, // Sample 2 size\n                                float alpha) // Significance level\n{\n  // F-statistic:\n  double f_stats = (Sd1 / Sd2);\n\n  //\n  // Finally define our distribution, and get the probability:\n  //\n  fisher_f dist(Sn1 - 1, Sn2 - 1);\n  double p = cdf(dist, f_stats);\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\n  //\n  // Finally print out results of null and alternative hypothesis:\n  //\n  if ((ucv2 < f_stats) || (lcv2 > f_stats)) { // Alternative \"NOT REJECTED\"\n    return {.fstat = static_cast<float>(f_stats), .df1 = Sn1 - 1, .df2 = Sn2 - 1, .pvalue = static_cast<float>(p), .sig = true};\n  }\n\n  if (lcv > f_stats) {// Alternative \"NOT REJECTED\"\n    return {.fstat = static_cast<float>(f_stats), .df1 = Sn1 - 1, .df2 = Sn2 - 1, .pvalue = static_cast<float>(p), .sig = true};\n  }\n\n  if (ucv < f_stats) { // Alternative \"NOT REJECTED\"\n    return {.fstat = static_cast<float>(f_stats), .df1 = Sn1 - 1, .df2 = Sn2 - 1, .pvalue = static_cast<float>(p), .sig = true};\n  }\n\n  // Alternative \"Rejected\"\n  return {.fstat = static_cast<float>(f_stats), .df1 = Sn1 - 1, .df2 = Sn2 - 1, .pvalue = static_cast<float>(p), .sig = false};\n\n}\n", "meta": {"hexsha": "c264318e9981697087a8e1e966c05fefa5e49a1c", "size": 2237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TSFTest.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TSFTest.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/TSFTest.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": 32.4202898551, "max_line_length": 128, "alphanum_fraction": 0.5985695127, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6771596036019991}}
{"text": "#include <iostream>\n#include <Eigen/Dense>  // Dicht besetzte Matrizen ~ nicht volles Eigen3 Package, da sonst das Compilieren ewig dauert\n\t\t\t\t\t\t// Eigen3 liegt als rein header-basierte Bibliothek vor -> wird immer neu \u00fcbersetzt!\n\nusing namespace Eigen;\nusing namespace std;\n\n\n/*\n * Eigen3 l\u00e4sst es zu, dynamisch Matrizen/Vektoren zu erstellen, ohne deren Dimensionen hart zu coden\n * Das ist ansonsten nur m\u00f6glich, wenn man die Speicherverwaltung auf dem Heap selbst \u00fcbernimmt\n * (arbeiten mit new)\n *\n * Schleifen \u00fcber Komponenten zum Verrechnen nicht notwendig, alles im Hintergrund effizient implementiert\n */\n\n\n\nVector3d gib_ein_ergebnis_zurueck(Matrix3d const &mat,Vector3d const &vec){\n  /*\u00fc\n   * Uebergeben wird eine Referenz auf eine Matrix (ein Alias innerhalb der Methode), die innerhalb der Methode nicht ver\u00e4nderlich sein sollen.\n   * Vgl 'Constant Correctness'\n   *\n   * R\u00fcckgabe ist ein Objekt vom Typ Vector3d, dass sich aus der Verrechnung der beiden \u00dcbergabeparametern ergibt\n   * Der *-Operator wurde \u00fcberladen und gibt ein Objekt zur\u00fcck, dass den Datentyp anhand des aufrufenden Objekts und des damit zu verrechnenden Objekts ableitet!\n   * vgl Documentation (anschauen mit F3)\n   */\n\n  cout<<\"Ausgabe Vektor:\"<<vec<<endl;\n  return mat*vec;\n  // return vec*mat; // test ob er dann m\u00e4ckert/was passiert wenn die Dimensionen nicht passen\n  // Dann m\u00e4ckert der Compiler, da Eigen \u00fcber assertions checkt, ob die Dimensionen passen!\n\n}\n\nint main()\n{\n  Matrix3d m = Matrix3d::Random();  \t\t// dies ist eine static Methode der Matrix3d Klasse (kommt noch)\n  \t  // Matrix3d erstellt eine 3x3 Matrix; diese soll initialisiert werden mit den Werten des (tempor\u00e4r eristierenden) Objekts Matrix3d::Random()\n  \t  /*\n  \t   * MatrixXd -> X x X gro\u00dfe Matrix vom Type d = double\n  \t   * Konstruktor: Eigen::MatrixXd testMatrix(rows, columns);\n  \t   * Oder Zuweisung eines anderen, tempr\u00e4ren Objekts\n  \t   * Eigen3::MatrixXd m = Eigen3::MatrixXd::Random(rows, cols); // Matrix mit Random Values zwischen -1 und 1 vom typ double\n  \t   * Eigen3::MatrixXd m2 = Eigen3::MatrixXd::Constant(rows, cols, value);\n  \t   */\n\n  m = (m + Matrix3d::Constant(1.2)) * 50;\n  \t  // Rechnen mit gleichartigen Matrizen ist \u00e4hnlich wie in Mathematik m\u00f6glich. Die +, -, *, /, ... Operatoren sind entsprechend \u00fcberladen\n\n\n  /*\n  // debug\n  Matrix3d testMatrixConst = Matrix3d::Constant(1.2);\n  std::cout << \"This is testMatrixConst: \" << std::endl;\n  std::cout << testMatrixConst << std::endl;\n  // ::Constant(double) erstellt eine X dimensionale Matrix die in allen ihren Elementen die double-zahl stehen hat\n  */\n\n\n  cout << \"m =\" << endl << m << endl;\n\n  // Gleiches gilt f\u00fcr Vektoren\n  Vector3d V(1,2,3);  // Initialisierung der Komponeten mit (1,2,3)\n\n  cout << \"m * v =\" << endl << m * V << endl;\n\n  Vector3d vec;\n  vec = gib_ein_ergebnis_zurueck(m,V);\n\n  cout<<\"vec:\"<<vec<<endl;\n\n  double val=vec.transpose()*vec;\n  \t  // Vetoren und Matrizen sind als Objekte implementiert!\n  \t  // transpose ist eine Methode von Vector3d und transponiert den Vector\n  \t  // Sie liefert ein (tempor\u00e4res) Objekt vom selben Datentyp wie das Objekt mit dem die Methode aufgerufen wurde zur\u00fcck\n\n  cout<<\"Skalarprodukt:\"<<val<<\" oder mit .dot Methode: \"<<vec.dot(vec) <<endl;\n\n  // aeusser Produkt:\n  Matrix3d m2=vec*vec.transpose();\n\n  cout<<\"m2: \"<<endl;\n  cout<<m2<<endl;\n\n  return 0;\n\n}\n\n", "meta": {"hexsha": "a21d749e9ce84c0ea0288748b4925f859013cc41", "size": 3358, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "uebung3/loesung/eigen3_einfuehrung/test_eigen3/test_eigen.cxx", "max_stars_repo_name": "jWeb94/kit_wissenschaftliches_programmieren_fuer_ingenieure", "max_stars_repo_head_hexsha": "b7a6b1b6be62263a7b7955e0fd60e2bd55adac09", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uebung3/loesung/eigen3_einfuehrung/test_eigen3/test_eigen.cxx", "max_issues_repo_name": "jWeb94/kit_wissenschaftliches_programmieren_fuer_ingenieure", "max_issues_repo_head_hexsha": "b7a6b1b6be62263a7b7955e0fd60e2bd55adac09", "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": "uebung3/loesung/eigen3_einfuehrung/test_eigen3/test_eigen.cxx", "max_forks_repo_name": "jWeb94/kit_wissenschaftliches_programmieren_fuer_ingenieure", "max_forks_repo_head_hexsha": "b7a6b1b6be62263a7b7955e0fd60e2bd55adac09", "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": 37.3111111111, "max_line_length": 161, "alphanum_fraction": 0.7081596188, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835493924953, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.6771417914990259}}
{"text": "\ufeff/***\r\n\u56db\uff1a\u53ef\u53d8\u53c2\u6a21\u677f\r\n\uff082\uff09\u6298\u53e0\u8868\u8fbe\u5f0f:Fold Expressions\uff0cC++17\r\n\u76ee\u7684\uff1a\u8ba1\u7b97\u67d0\u4e2a\u503c\uff08\u8868\u8fbe\u5f0f\u7684\u7ed3\u679c\u5f53\u7136\u662f\u4e00\u4e2a\u503c\uff09\r\n\u8be5\u503c\u5f97\u7279\u6b8a\u6027\u5728\u4e8e\uff1a\u5b83\u4e0e\u6240\u6709\u53ef\u53d8\u53c2\u6709\u5173\uff0c\u800c\u4e0d\u662f\u4e0e\u5355\u72ec\u67d0\u4e2a\u53ef\u53d8\u53c2\u6709\u5173\u3002 \u9700\u8981\u6240\u6709\u53ef\u53d8\u53c2\u90fd\u53c2\u4e0e\u8ba1\u7b97\uff0c\u624d\u80fd\u6c42\u51fa\u8be5\u503c\u3002\r\n\u6298\u53e0\u8868\u8fbe\u5f0f\u6709\u56db\u79cd\u683c\u5f0f\uff1a\u4e00\u5143\u5de6\u6298\u3001\u4e00\u5143\u53f3\u6298\uff0c\u4e8c\u5143\u5de6\u6298\u3001\u4e8c\u5143\u53f3\u6298\r\n\u6ce8\u610f\uff0c\u6bcf\u79cd\u683c\u5f0f\u7684\u6298\u53e0\u8868\u8fbe\u5f0f\u90fd\u9700\u8981\u7528\u5706\u62ec\u53f7\u62ec\u4f4f\u3002\r\n\u5de6\u6298\uff1a\u5c31\u662f\u53c2\u6570\u4ece\u5de6\u4fa7\u5f00\u59cb\u8ba1\u7b97  \uff1b\r\n\u53f3\u6298\uff1a\u53c2\u6570\u4ece\u53f3\u4fa7\u5f00\u59cb\u8ba1\u7b97\r\n\r\n\uff082.1\uff09\u4e00\u5143\u5de6\u6298\uff08unary left fold\uff09\r\n\u683c\u5f0f\uff1a (... \u8fd0\u7b97\u7b26 \u4e00\u5305\u53c2\u6570)\r\n\u8ba1\u7b97\u65b9\u5f0f\uff1a((( \u53c2\u65701  \u8fd0\u7b97\u7b26  \u53c2\u65702\uff09 \u8fd0\u7b97\u7b26  \u53c2\u65703\uff09....\u8fd0\u7b97\u7b26 \u53c2\u6570N\uff09\r\n\uff082.2\uff09\u4e00\u5143\u53f3\u6298\uff08unary right fold\uff09\r\n\u683c\u5f0f\uff1a (\u4e00\u5305\u53c2\u6570 \u8fd0\u7b97\u7b26 ...)\r\n\u8ba1\u7b97\u65b9\u5f0f\uff1a( \u53c2\u65701  \u8fd0\u7b97\u7b26  ( ... (\u53c2\u6570N-1  \u8fd0\u7b97\u7b26  \u53c2\u6570N)))\r\n\uff082.3\uff09\u4e8c\u5143\u5de6\u6298\uff08binary left fold\uff09\r\n\u683c\u5f0f\uff1a(init \u8fd0\u7b97\u7b26 ... \u8fd0\u7b97\u7b26 \u4e00\u5305\u53c2\u6570)\r\n\u8ba1\u7b97\u65b9\u5f0f\uff1a(((init \u8fd0\u7b97\u7b26 \u53c2\u65701) \u8fd0\u7b97\u7b26 \u53c2\u65702) ... \u8fd0\u7b97\u7b26 \u53c2\u6570N)\r\ninit\u8868\u793a \u4e00\u4e2a\u521d\u59cb\u7684\u4e1c\u897f\uff0c\u5b83\u53ef\u80fd\u662f\u4e00\u4e2a\u503c\uff0c\u4e5f\u53ef\u80fd\u662f\u4e2a\u5176\u4ed6\u4e1c\u897f\u3002\r\n\uff082.4\uff09\u4e8c\u5143\u53f3\u6298\uff08binary right fold\uff09\r\n\u683c\u5f0f\uff1a(\u4e00\u5305\u53c2\u6570 \u8fd0\u7b97\u7b26 ... \u8fd0\u7b97\u7b26 init)\r\n\u8ba1\u7b97\u65b9\u5f0f\uff1a\uff08\u53c2\u65701 \u8fd0\u7b97\u7b26 \uff08...\uff08\u53c2\u6570N \u8fd0\u7b97\u7b26 init )))\r\n\r\n\uff083\uff09\u53ef\u53d8\u53c2\u8868\u8fbe\u5f0f\r\n\r\n***/\r\n\r\n#include <iostream>\r\n\r\n//#include <boost/type_index.hpp>\r\nusing namespace std;\r\n//#pragma warning(disable : 4996)\r\n\r\nnamespace _nmsp1\r\n{\r\n\ttemplate <typename... T>\r\n\tauto add_val(T... args)\r\n\t{\r\n\t\t//return (... + args); //\u5706\u62ec\u53f7\u4e0d\u80fd\u7701\u7565\uff0c\u5426\u5219\u51fa\u73b0\u7f16\u8bd1\u9519\u8bef\uff0c\u4e00\u5143\u5de6\u6298\r\n\t\treturn (args + ...); //\u4e00\u5143\u53f3\u6298\r\n\r\n\t}\r\n\ttemplate <typename... T>\r\n\tauto sub_val_left(T... args)\r\n\t{\r\n\t\treturn (... - args); //\u4e00\u5143\u5de6\u6298\r\n\t}\r\n\ttemplate <typename... T>\r\n\tauto sub_val_right(T... args)\r\n\t{\r\n\t\treturn (args - ...); //\u4e00\u5143\u53f3\u6298\r\n\t}\r\n\r\n\ttemplate <typename... T>\r\n\tauto sub_val_left_b(T... args)\r\n\t{\r\n\t\treturn (220 - ... - args); //\u4e8c\u5143\u5de6\u6298\uff1a220\u5c31\u662finit\r\n\t}\r\n\r\n\ttemplate <typename... T>\r\n\tvoid print_val_left_b(T... args)\r\n\t{\r\n\t\t(cout << ... << args); //\u4e00\u5143\u5de6\u6298\uff0c\u4f46init\u662fcout\uff0c\u8fd0\u7b97\u7b26\u4ee3\u8868\u7684\u662f <<\r\n\t}\r\n\r\n\ttemplate <typename... T>\r\n\tauto sub_val_right_b(T... args)\r\n\t{\r\n\t\treturn (args - ... - 220); //\u4e8c\u5143\u53f3\u6298\r\n\t}\r\n}\r\nnamespace _nmsp2\r\n{\r\n\ttemplate <typename... T>\r\n\tauto print_result(T const& ... args)\r\n\t{\r\n\t\t(cout << ... << args) << \" \u7ed3\u675f\" << endl;\r\n\t\treturn (... + args); //\u8ba1\u7b97\u4e00\u4e0b\u53c2\u6570\u548c\u503c\r\n\t}\r\n\r\n\ttemplate <typename... T>\r\n\tvoid  print_calc(T const& ... args)\r\n\t{\r\n\t\tcout << print_result(2 * args...) << endl;  //\u201c2 * args...\u201c\u5c31\u662f\u53ef\u53d8\u53c2\u8868\u8fbe\u5f0f\r\n\t\t                                   // print_result(2 * args...) \u7b49\u4ef7\u4e8e print_result(2 * 10, 2*20, 2*30,2*40)  ;\r\n\r\n\t\t//print_result(2 * args); //\u4e0d\u884c\r\n\t\t//print_result(args... * 2);  //\u4e0d\u884c\r\n\t\t//print_result(args * 2...); //\u4e0d\u884c\r\n\t\t//print_result(args * 2 ...); //\u53ef\u4ee5\r\n\t\t//print_result((args * 2) ...); //\u53ef\u4ee5\r\n\t\tprint_result(args + args...); //\u53ef\u4ee5\uff0c\u7b49\u4ef7\u4e8eprint_result(10+10,20+20,30+30,40+40);\r\n\r\n\t}\r\n\r\n}\r\n\r\nint main()\r\n{\r\n\t//cout << _nmsp1::add_val(10, 20, 30) << endl;\r\n\r\n\t//cout << _nmsp1::sub_val_left(10, 20, 30,40) << endl;  //-80\uff1a((10-20)-30)-40\r\n\t//cout << _nmsp1::sub_val_right(10, 20, 30, 40) << endl; //-20\uff1a10-(20-(30-40))\r\n\r\n\t//cout << _nmsp1::sub_val_left_b(10, 20, 30, 40) << endl; //120\uff1a(((220-10)-20)-30)-40\r\n\t//_nmsp1::print_val_left_b(10, \"abc\", 30, \"def\"); //10abc30def\r\n\t//cout << _nmsp1::sub_val_right_b(10, 20, 30, 40) << endl; //200\uff1a10-(20-\uff0830-\uff0840-220)))\r\n\r\n\r\n\t//cout << _nmsp2::print_result(10,20,30,40) << endl;\r\n\t_nmsp2::print_calc(10, 20, 30, 40);\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "aaa02e572a22c3af85bb17d96ad4f6d537df5ec2", "size": 2790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Templates/2/214.cpp", "max_stars_repo_name": "mallius/CppPrimer", "max_stars_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Templates/2/214.cpp", "max_issues_repo_name": "mallius/CppPrimer", "max_issues_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Templates/2/214.cpp", "max_forks_repo_name": "mallius/CppPrimer", "max_forks_repo_head_hexsha": "0285fabe5934492dfed0a9cf67ba5650982a5f76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T15:51:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T15:51:34.000Z", "avg_line_length": 24.0517241379, "max_line_length": 111, "alphanum_fraction": 0.5695340502, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.6771417853636144}}
{"text": "#include <fmt/core.h>\n#include <yaml-cpp/yaml.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Sparse>\n#include <boost/math/quadrature/gauss.hpp>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <optional>\n#include <vector>\n\n#include \"NumpySaver.hpp\"\n#include \"Timer.hpp\"\n#include \"bsplines.hpp\"\n\nusing namespace Eigen;\nusing std::cout, std::endl, std::cerr;\n\nconst char* devider = \"##########################################\";\n\ntemplate <int num_points>\ndouble matrix_B_element(int i, int j, std::vector<double>& knots, Index order) {\n  using boost::math::quadrature::gauss;\n\n  if (std::abs((int)i - (int)j) > order) return 0;\n\n  int imax = std::max(i, j);\n  int imin = std::min(i, j);\n\n  Index n = knots.size();\n\n  double sum = 0;\n\n  for (int k = std::max(0, imax - 1); k < std::min(imin + order + 1, n - 1);\n       k++) {\n    auto f = [&](const double& t) {\n      auto [values, idx] = bsplines::bsplines(t, knots, order);\n      return values[i + order - idx] * values[j + order - idx];\n    };\n    sum += gauss<double, num_points>::integrate(f, knots[k], knots[k + 1]);\n  }\n\n  return sum;\n}\n\ntemplate <int num_points>\ndouble matrix_H_element(int i, int j, std::vector<double>& knots, Index order,\n                        int l, int z,\n                        std::function<double(double)>& additional_pot) {\n  using boost::math::quadrature::gauss;\n  if (std::abs((int)i - (int)j) > order) return 0;\n\n  Index n = knots.size();\n  int imax = std::max(i, j);\n  int imin = std::min(i, j);\n\n  double sum = 0;\n\n  for (int k = std::max(0, imax - 1); k < std::min(imin + order + 1, n - 1);\n       k++) {\n    auto f = [&](const double& t) {\n      auto [values, idx] = bsplines::bsplines(t, knots, order);\n      auto [values_dd, idx_dd] = bsplines::ndx_bsplines(t, knots, order, 2);\n      double h_val = -values_dd[j - (idx - order)] / 2. +\n                     (l * (l + 1.) / (t * t * 2.) - z / t + additional_pot(t)) *\n                         values[j - (idx - order)];\n      return values[i - (idx - order)] * h_val;\n      ;\n    };\n\n    sum += gauss<double, num_points>::integrate(f, knots[k], knots[k + 1]);\n  }\n  return sum;\n}\n\ntemplate <int num_points>\nMatrixXd matrix_B(std::vector<double>& knots, Index order) {\n  Index n = knots.size();\n  MatrixXd mat(n - 3 + order, n - 3 + order);\n\n  for (int row = 0; row < mat.rows(); row++)\n    for (int col = 0; col < mat.cols(); col++)\n      mat(row, col) = matrix_B_element<num_points>(\n          row - order + 1, col - order + 1, knots, order);\n\n  return mat;\n}\n\ntemplate <int num_points>\nMatrixXd matrix_H(std::vector<double>& knots, Index order, int l, int z,\n                  std::function<double(double)>& additional_pot) {\n  Index n = knots.size();\n  MatrixXd mat(n - 3 + order, n - 3 + order);\n\n  for (int row = 0; row < mat.rows(); row++)\n    for (int col = 0; col < mat.cols(); col++)\n      mat(row, col) = matrix_H_element<num_points>(\n          row - order + 1, col - order + 1, knots, order, l, z, additional_pot);\n\n  return mat;\n}\n\ndouble evaluate_spline(const double& x, const std::vector<double>& knots,\n                       const VectorXd& weights, std::size_t order) {\n  auto n = knots.size();\n  assert(int(n + order) - 3 == weights.size());\n\n  auto [values, index] = bsplines::bsplines(x, knots, order);\n\n  double sum = 0;\n  for (std::size_t i = std::max(int(index) - 1, 0);\n       i <= std::min(index - 1 + order, n + order - 4); i++)\n    sum += values[i + 1 - index] * weights[i];\n\n  return sum;\n}\n\nSparseMatrix<double> matrix_poisson(const std::vector<double>& knots,\n                                    std::size_t order = 3) {\n  auto n = knots.size();\n\n  SparseMatrix<double> matrix(n + 1, n + order - 2);\n  matrix.reserve(order * (n + 1) - 2);\n\n  auto [deriv_0, _index] = bsplines::ndx_bsplines(knots[0], knots, order, 2);\n  for (int col = 0; col < int(order) - 1; col++)\n    matrix.insert(0, col) = deriv_0[col + 1];\n\n  for (int row = 1; row < int(n); row++) {\n    auto [deriv, index] = bsplines::ndx_bsplines(knots[row], knots, order, 2);\n    for (int col = row - 1; col < row - 1 + int(order); col++)\n      matrix.insert(row, col) = deriv[col - row + 2];\n  }\n\n  auto [deriv_last, __index] =\n      bsplines::ndx_bsplines(knots[n - 1], knots, order, 1);\n  matrix.insert(n, n + order - 3) = deriv_last[order];\n  matrix.insert(n, n + order - 4) = deriv_last[order - 1];\n\n  return matrix;\n}\n\ndouble rho_hydrogen_ground_state(double r, double e, double r_bohr = 1) {\n  return e / M_PI / (r_bohr * r_bohr * r_bohr) * std::exp(-2 * r / r_bohr);\n}\n\nVectorXd rhs_poisson(const std::vector<double>& knots,\n                     std::function<double(double)>& rho) {\n  auto n = knots.size();\n  VectorXd rhs(n + 1);\n  for (std::size_t i = 0; i < n; i++) {\n    rhs[i] = -knots[i] * 4 * M_PI * rho(knots[i]);\n  }\n\n  rhs[n] = 0;\n\n  return rhs;\n}\n\ndouble evaluate_spline_poisson(const double& x,\n                               const std::vector<double>& knots,\n                               const VectorXd& weights, std::size_t order = 3) {\n  assert(int(knots.size() + order) - 1 == weights.size());\n\n  auto [values, index] = bsplines::bsplines(x, knots, order);\n\n  double sum = 0;\n  for (std::size_t i = 0; i <= order; i++)\n    sum += values[i] * weights[index + i];\n\n  return sum;\n}\n\ndouble test_norm_r2(std::function<double(double)> f, double xmin, double xmax) {\n  using boost::math::quadrature::gauss;\n\n  std::function<double(double)> integrant = [&](double x) {\n    return f(x) * x * x;\n  };\n\n  double norm =\n      4 * M_PI * gauss<double, 10000>::integrate(integrant, xmin, xmax);\n\n  std::cout << \"Norm is \" << norm << endl;\n\n  return norm;\n}\n\ndouble test_norm_sqrt(std::function<double(double)> f, double xmin,\n                      double xmax) {\n  using boost::math::quadrature::gauss;\n  std::function<double(double)> integrant = [&](double x) {\n    double c = f(x);\n    return c * c;\n  };\n\n  double norm = gauss<double, 10000>::integrate(integrant, xmin, xmax);\n\n  std::cout << \"WVF Norm is \" << norm << endl;\n\n  return norm;\n}\n\nVectorXd evaluate_spline_poisson(const VectorXd& x,\n                                 const std::vector<double>& knots,\n                                 const VectorXd& weights,\n                                 std::size_t order = 3) {\n  auto n = x.size();\n  VectorXd ret(n);\n  for (Index i = 0; i < n; i++) {\n    ret[i] = evaluate_spline(x[i], knots, weights, order);\n  }\n  return ret;\n}\n\ntemplate <int order>\nstd::vector<double> normalization_constants_radial_wavefunctions(\n    std::vector<double>& knots, MatrixXd& eigenvectors) {\n  using boost::math::quadrature::gauss;\n\n  std::vector<double> returner;\n  returner.reserve(eigenvectors.cols());\n\n  int col;\n  std::function<double(double)> f = [&](double r) {\n    double v = evaluate_spline(r, knots, eigenvectors.col(col), order);\n    return v * v;\n  };\n\n  for (col = 0; col < eigenvectors.cols(); col++) {\n    double norm = 0;\n    for (std::size_t k = 0; k < knots.size() - 1; k++)\n      norm += gauss<double, 2 * order>::integrate(f, knots[k], knots[k + 1]);\n    returner.push_back(std::sqrt(norm));\n  }\n\n  return returner;\n}\n\n// int, int, int = N, n, l\ntemplate <int order>\nstd::tuple<double, std::size_t> solve(\n    std::vector<double>& knots_atom, std::vector<double>& knots_poisson,\n    std::vector<std::tuple<int, int, int>>& orbitals, int z,\n    std::string& basefilename, double mixture = 0.4, double tol = 1e-6,\n    std::size_t maxiter = 100) {\n  using namespace std;\n  using boost::math::quadrature::gauss;\n\n  constexpr int gauss_points = double(order) * 1.5;\n\n  size_t n_orbitals = orbitals.size();\n\n  auto matrix_poisson_ = matrix_poisson(knots_poisson);\n  // first do the (sparse) LU decomposition\n  Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>\n      solver_poisson;\n  solver_poisson.analyzePattern(matrix_poisson_);\n  solver_poisson.factorize(matrix_poisson_);\n\n  auto B = matrix_B<gauss_points>(knots_atom, order);\n\n  GeneralizedEigenSolver<MatrixXd> ges;\n\n  VectorXd old_orbital_energies = VectorXd::Zero(n_orbitals);\n  VectorXd orbital_energies = VectorXd::Ones(n_orbitals);\n\n  VectorXd weights_poisson = VectorXd::Zero(matrix_poisson_.cols() + 1);\n  VectorXd weights_poisson_old = VectorXd::Zero(matrix_poisson_.cols() + 1);\n\n  std::map<int, std::pair<MatrixXd, VectorXd>> l_map, l_map_old;\n\n  std::function rho = [&](double r) -> double {\n    if (r == 0) return 0;\n    double sum = 0;\n    for (auto& [N, n, l] : orbitals) {\n      if (!l_map.contains(l)) continue;\n      double pnl_r =\n          evaluate_spline(r, knots_atom, l_map[l].first.col(n - l - 1), order) /\n          r;\n      sum += N * pnl_r * pnl_r;\n    }\n    return sum / 4. / M_PI;\n  };\n\n  std::function rho_old = [&](double r) -> double {\n    if (r == 0) return 0;\n    double sum = 0;\n    for (auto& [N, n, l] : orbitals) {\n      if (!l_map_old.contains(l)) continue;\n      double pnl_r = evaluate_spline(r, knots_atom,\n                                     l_map_old[l].first.col(n - l - 1), order) /\n                     r;\n      sum += N * pnl_r * pnl_r;\n    }\n    return sum / 4. / M_PI;\n  };\n\n  std::function<double(double)> additional = [&](double r) -> double {\n    if (r == 0.0) return 0;\n    double old_exchange = -3. * pow(3. * rho_old(r) / 8. / M_PI, 1. / 3.);\n    double new_exchange = -3. * pow(3. * rho(r) / 8. / M_PI, 1. / 3.);\n    double old_direct =\n        evaluate_spline_poisson(r, knots_poisson, weights_poisson_old, order) /\n        r;\n    double new_direct =\n        evaluate_spline_poisson(r, knots_poisson, weights_poisson, order) / r;\n\n    return (1. - mixture) * (new_direct + new_exchange) +\n           mixture * (old_direct + old_exchange);\n  };\n\n  double energy = numeric_limits<double>::max();\n\n  std::size_t iter = 0;\n\n  while ((old_orbital_energies - orbital_energies).norm() > tol) {\n    iter++;\n    old_orbital_energies = orbital_energies;\n\n    std::map<int, std::pair<MatrixXd, VectorXd>> l_map_new;\n\n    for (size_t i = 0; i < n_orbitals; i++) {\n      auto& [N, n, l] = orbitals[i];\n\n      if (!l_map_new.contains(l)) {\n        auto H = matrix_H<gauss_points>(knots_atom, order, l, z, additional);\n\n        ges.compute(H, B);\n        VectorXcd eigenvalues = ges.eigenvalues();\n\n#ifndef NDEBUG\n        if (eigenvalues.imag().cwiseAbs().sum() > 10e-3) {\n          cerr << \"Error: Complex eigenvalues!\" << endl;\n        }\n#endif\n\n        VectorXd real_eigen = eigenvalues.real();\n\n        // sort the eigenvalues (and create an index list)\n        // https://stackoverflow.com/questions/39693909/sort-eigen-matrix-column-values-by-ascending-order-of-column-1-values\n        std::vector<int> indices(real_eigen.size());\n        std::iota(indices.begin(), indices.end(), 0);\n        std::sort(indices.begin(), indices.end(), [&](int A, int B) -> bool {\n          return real_eigen[A] < real_eigen[B];\n        });\n\n        std::sort(real_eigen.data(), real_eigen.data() + real_eigen.size());\n\n        MatrixXd unsorted_eigenvectors = ges.eigenvectors().real();\n        l_map_new[l] = std::pair(MatrixXd(unsorted_eigenvectors.rows(),\n                                          unsorted_eigenvectors.cols()),\n                                 real_eigen);\n\n        auto normalization_constants =\n            normalization_constants_radial_wavefunctions<order>(\n                knots_atom, unsorted_eigenvectors);\n\n        for (Index row = 0; row < unsorted_eigenvectors.rows(); row++)\n          for (Index col = 0; col < unsorted_eigenvectors.cols(); col++)\n            l_map_new[l].first(row, col) =\n                unsorted_eigenvectors(row, indices[col]) /\n                normalization_constants[indices[col]];\n\n        auto test = normalization_constants_radial_wavefunctions<order>(\n            knots_atom, l_map_new[l].first);\n      }\n      orbital_energies[i] = l_map_new[l].second[n - l - 1];\n    }\n\n    l_map_old = l_map;\n    l_map = l_map_new;\n\n    auto rhs = rhs_poisson(knots_poisson, rho);\n\n    weights_poisson_old = weights_poisson;\n    weights_poisson << 0, solver_poisson.solve(rhs);\n\n    if (iter >= maxiter) {\n      cerr << \"Reached maximum number of iterations!\" << endl;\n      break;\n    }\n  }\n  energy = 0;\n\n  function<double(double, int, int)> ee_interaction = [&](double x, int n,\n                                                          int l) {\n    double pnl_r =\n        evaluate_spline(x, knots_atom, l_map[l].first.col(n - l - 1), order);\n    return additional(x) * pnl_r * pnl_r;\n  };\n\n  for (size_t i = 0; i < n_orbitals; i++) {\n    auto& [N, n, l] = orbitals[i];\n    function<double(double)> integrant =\n        bind(ee_interaction, std::placeholders::_1, n, l);\n\n    double integral = 0;\n    for (size_t k = 0; k < knots_poisson.size() - 1; k++) {\n      integral += gauss<double, 2 * order>::integrate(\n          integrant, knots_poisson[k], knots_poisson[k + 1]);\n    }\n    energy += N * (orbital_energies[i] - .5 * integral);\n  }\n  cout << \"Orbital energies=\" << orbital_energies.transpose() << endl;\n  cout << \"Total energy = \" << energy << endl;\n\n  // exporting/plotting\n  VectorXd xx = VectorXd::LinSpaced(1000, 0, 10);\n  VectorXd rho_x = VectorXd(xx.size());\n  for (Index i = 0; i < xx.size(); i++) rho_x[i] = rho(xx[i]);\n  NumpySaver(fmt::format(\"build/output/{}_rho.npy\", basefilename))\n      << xx << rho_x;\n\n  return {energy, iter};\n}\n\ntemplate <int order>\nvoid solve_exp(int n_knots, double rmin, double rmax, double exp_fak,\n               std::string& basefilename, std::optional<double> plot, int l,\n               int z) {\n  std::vector<double> knots(n_knots);\n  for (int i = 0; i < n_knots; i++)\n    knots[i] = (rmax - rmin) *\n                   (std::exp(double(i) / double(n_knots - 1) * exp_fak) - 1.) /\n                   (std::exp(exp_fak) - 1) +\n               rmin;\n\n  solve<order>(knots, basefilename, plot, l, z);\n}\n\ntemplate <int order>\nvoid solve_lin(int n_knots, double rmin, double rmax, std::string& basefilename,\n               std::optional<double> plot, int l, int z) {\n  std::vector<double> knots(n_knots);\n  for (int i = 0; i < n_knots; i++)\n    knots[i] = double(i) / double(n_knots - 1) * (rmax - rmin) + rmin;\n\n  solve<order>(knots, basefilename, plot, l, z);\n}\n\nstd::vector<std::tuple<int, int, int>> to_tuples(\n    std::vector<std::vector<int>>& list) {\n  // how i wish map was a thing here...\n\n  std::vector<std::tuple<int, int, int>> orbitals;\n  orbitals.reserve(list.size());\n  for (auto& orbit : list)\n    orbitals.push_back(std::make_tuple(orbit[0], orbit[1], orbit[2]));\n  return orbitals;\n}\n\nint main() {\n  int n_knots = 50;\n  int n_knots_p = 1000;\n\n  std::vector<double> knots_atom(n_knots);\n  std::vector<double> knots_poisson(n_knots_p);\n\n  for (int i = 0; i < n_knots; i++)\n    knots_atom[i] = (1000. - 0.) *\n                        (std::exp(double(i) / double(n_knots - 1) * 10.) - 1.) /\n                        (std::exp(10.) - 1.) +\n                    0.;\n  for (int i = 0; i < n_knots_p; i++)\n    knots_poisson[i] =\n        (1000. - 0.) *\n            (std::exp(double(i) / double(n_knots_p - 1) * 10.) - 1.) /\n            (std::exp(10.) - 1.) +\n        0.;\n\n  Map<VectorXd> knots_map(knots_atom.data(), knots_atom.size());\n  Map<VectorXd> knots_map_p(knots_poisson.data(), knots_poisson.size());\n  NumpySaver(\"build/output/knots_poisson.npy\") << knots_map_p;\n  NumpySaver(\"build/output/knots_atom.npy\") << knots_map;\n\n  // Check the influence of the mixing factor\n  std::vector<std::tuple<int, int, int>> orbitals_Ne = {\n      {2, 1, 0}, {2, 2, 0}, {6, 2, 1}};  // N, n, l\n  std::vector<std::tuple<int, int, int>> orbitals_Nep = {\n      {2, 1, 0}, {2, 2, 0}, {5, 2, 1}};  // N, n, l\n\n  VectorXd etas = VectorXd::LinSpaced(50, 0, 1);\n  VectorXd iters(etas.size());\n  for (Index i = 0; i < etas.size(); i++) {\n    std::string name = fmt::format(\"eta_{}\", etas[i]);\n    auto [energy, iter] =\n        solve<3>(knots_atom, knots_poisson, orbitals_Ne, 10, name, etas[i]);\n    iters[i] = iter;\n  }\n  NumpySaver(\"build/output/etas.npy\") << etas << iters;\n\n  // iterate through ALL the elements\n  YAML::Node elements = YAML::LoadFile(\"build/output/pse.yaml\");\n\n  std::size_t num_elements = elements.size();\n\n  VectorXd zs(num_elements);\n  VectorXd es(num_elements);\n  VectorXd iterss(num_elements);\n  VectorXd es_ion(num_elements);\n  VectorXd iterss_ion(num_elements);\n\n  for (std::size_t i = 0; i < elements.size(); i++) {\n    YAML::Node element = elements[i];\n\n    auto z = element[\"Z\"].as<int>();\n    auto name = element[\"name\"].as<std::string>();\n    auto symbol = element[\"symbol\"].as<std::string>();\n    auto orbitals_ = element[\"orbitals\"].as<std::vector<std::vector<int>>>();\n    auto orbitals_ionized_ =\n        element[\"orbitals_ionized\"].as<std::vector<std::vector<int>>>();\n\n    auto orbitals = to_tuples(orbitals_);\n    auto orbitals_ionized = to_tuples(orbitals_ionized_);\n\n    cout << \"Element \" << name << \"(\" << i + 1 << \"/\" << elements.size() << \")\"\n         << endl;\n    zs[i] = z;\n\n    Timer t;\n    auto [energy, iter] =\n        solve<3>(knots_atom, knots_poisson, orbitals, z, symbol, .6);\n    cout << \"E=\" << energy << \" took \" << iter << \" iterations (\"\n         << t.elapsed_s() << \"s)\" << endl;\n\n    es[i] = energy;\n    iterss[i] = iter;\n\n    std::string symbol_ionized = symbol + \"+\";\n\n    t.reset();\n    auto [energy_ion, iter_ion] = solve<3>(\n        knots_atom, knots_poisson, orbitals_ionized, z, symbol_ionized, .4);\n    cout << \"E_{ion}=\" << energy_ion << \" took \" << iter_ion << \" iterations (\"\n         << t.elapsed_s() << \"s)\" << endl;\n\n    es_ion[i] = energy_ion;\n    iterss_ion[i] = iter_ion;\n    cout << endl;\n  }\n\n  NumpySaver(\"build/output/elements.npy\")\n      << zs << es << iterss << es_ion << iterss_ion;\n}\n", "meta": {"hexsha": "20b5b22cb38e36d8f2de4d7c7f0f6120a0b80031", "size": 17656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project06-PTE/pte.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": "Project06-PTE/pte.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": "Project06-PTE/pte.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": 32.2189781022, "max_line_length": 125, "alphanum_fraction": 0.5877322157, "num_tokens": 5327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.93812402119614, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6770846501926154}}
{"text": "#include \"Kernel.h\"\n#include <armadillo>\n#include <assert.h>\n#include <iostream>\n#include <math.h>\n\nusing namespace arma;\n\nKernel::Kernel(KernelType type) : kernelType(type) {\n  if (this->kernelType == LINEAR) {\n    KernelFunction = &Kernel::KernelLinear;\n  } else if (this->kernelType == RBF) {\n    KernelFunction = &Kernel::KernelRBF;\n  } /* else if (this->kernelType == POLY) {\n     KernelFunction = &Kernel::KernelPoly;\n   } else if (this->kernelType == SIGMOID) {\n     KernelFunction = &Kernel::kernel_sigmoid;\n   } else if (this->kernelType == KernelSigmoid) {\n     KernelFunction = &Kernel::kernel_precomputed;\n   }*/\n}\n\n/*\ndouble Kernel::KernelLinear(int i1, int i2) {\n  return this->KernelLinear(this->x.rows(i1).t(),this->x.rows(i2).t()); }\ndouble Kernel::KernelRBF(vec x, vec y) {\n  return this->KernelRBF(this->x.rows(i1).t(),this->x.rows(i2).t());\n}\n*/\ndouble Kernel::KernelLinear(vec &x1, vec &x2) const {\n  return arma::dot(x1, x2);\n}\ndouble Kernel::KernelRBF(vec &x1, vec &x2) const {\n  double temp =norm(x1 - x2);\n  return exp(-this->gamma * pow(temp,2.0));\n}\n", "meta": {"hexsha": "4c11ff162a289c5522a9d10d88d73be60ec4cb7b", "size": 1077, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/SVM/Kernel.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/SVM/Kernel.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/SVM/Kernel.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": 29.1081081081, "max_line_length": 73, "alphanum_fraction": 0.6592386258, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6770652180588117}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\ndouble categorical_cross_entropy(VectorXd, VectorXd);\n\nint main(){\n    using std::cout;\n    using std::endl;\n\n    VectorXd t = VectorXd::Zero(10);\n    VectorXd y = VectorXd::Zero(10);\n    double cross_entropy;\n\n    t(2) = 1;\n    y << 0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0;\n\n    cross_entropy = categorical_cross_entropy(t, y);\n    cout << \"cross entropy: \" << cross_entropy << endl;\n\n    return 0;\n}\n\ndouble categorical_cross_entropy(VectorXd t, VectorXd y){\n    double delta = 1.0e-7;\n    return -(t.array() * (y.array() + delta).log()).sum();\n}", "meta": {"hexsha": "896839f91f79df058faca66e4fbbe572523a84d7", "size": 627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/cross_entropy.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/cross_entropy.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/cross_entropy.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3928571429, "max_line_length": 60, "alphanum_fraction": 0.6267942584, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6770652037927678}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X + X.transpose();\ncout << \"Here is a random symmetric 5x5 matrix:\" << endl << A << endl << endl;\nTridiagonalization<MatrixXd> triOfA(A);\nMatrixXd Q = triOfA.matrixQ();\ncout << \"The orthogonal matrix Q is:\" << endl << Q << endl;\nMatrixXd T = triOfA.matrixT();\ncout << \"The tridiagonal matrix T is:\" << endl << T << endl << endl;\ncout << \"Q * T * Q^T = \" << endl << Q * T * Q.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b48c85e131f420f78cd2c01271b3b598d3c91e74", "size": 929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Tridiagonalization_Tridiagonalization_MatrixType.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 30.9666666667, "max_line_length": 224, "alphanum_fraction": 0.6523143165, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6770457023022523}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// A reference piece of code which computes matrix elements\n// of a reference sparse gauged operator with both a central difference\n// and a laplacian term component, to fill a dense\n// Eigen matrix, then computes the spectrum and prints\n// the Eigenvalues.\n\n// This code is for complex, indefinite matrices.\n// This code lives on github at github.com/weinbe2/eigens-with-eigen/\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\nusing namespace std; \nusing namespace Eigen;\n\n\n// This is just for convenience. By default, all matrices\n// in Eigen are column major. You can replace \"Dynamic\"\n// with a specific number to template just one size.\n// You can also ust use \"MatrixXcd\".\ntypedef Matrix<complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\n\n// Reference 1-D indefinite function.\nvoid indefinite_1d_gauge(complex<double>* out, complex<double>* in, const int L, const double m2, complex<double>* field);\n\nint main(int argc, char** argv)\n{  \n  complex<double> *in_cplx;\n  complex<double> *out_cplx;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // Basic information about the lattice.\n  const int length = 4;\n  const double mass = 0.001;\n\n  // Print the basic info.\n  std::cout << \"1D indefinite operator, length \" << length << \", mass \" << mass << \", periodic boundary conditions.\\n\";\n  std::cout << \"Change the length and mass by modifying the source.\\n\";\n\n  // Allocate a random phase field.\n  complex<double>* field = new complex<double>[length];\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n  std::uniform_real_distribution<> dist(-3.1415926535, 3.1415926535);\n  for (int i = 0; i < length; i++)\n  {\n    // As a sanity check, you can set these all equal to 1.0.\n    field[i] = exp(complex<double>(0.0, dist(generator)));\n  }\n  \n  // Allocate.\n  in_cplx = new complex<double>[length];\n  out_cplx = new complex<double>[length];\n\n  // Zero out.\n  for (int i = 0; i < length; i++)\n  {\n    in_cplx[i] = out_cplx[i] = 0.0;\n  }\n\n  /////////////////////////////\n  // COMPLEX, HERMITIAN CASE //\n  /////////////////////////////\n\n  std::cout << \"Complex, Indefinite case.\\n\\n\";\n\n  // Allocate a sufficiently gigantic matrix.\n  cMatrix mat_cplx = cMatrix::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_cplx[i-1] = 0.0;\n    }\n    in_cplx[i] = 1.0;\n\n    // Zero out the \"out\" vector. I defined \"laplace_1d_gauge\" to\n    // not require this, but I put this here for generality.\n    for (int j = 0; j < length; j++)\n      out_cplx[j] = 0.0;\n\n    // PUT YOUR MAT-VEC HERE.\n    indefinite_1d_gauge(out_cplx, in_cplx, length, mass, field);\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    complex<double>* mptr = &(mat_cplx(i*length));\n    \n    for (int j = 0; j < length; j++)\n    {\n      mptr[j] = out_cplx[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_cplx << \"\\n\";\n  }\n\n  // Get the eigenvalues and eigenvectors.\n  ComplexEigenSolver< cMatrix > eigsolve_cplx_indef(length);\n  eigsolve_cplx_indef.compute(mat_cplx);\n\n  // Remark: if you only want the eigenvalues, you can call\n  // eigsolve_cplx.compute(mat_cplx, EigenvaluesOnly);\n\n  // Print the eigenvalues.\n  cMatrix evals = eigsolve_cplx_indef.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      cMatrix evec = eigsolve_cplx_indef.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_cplx[j] = evec(j);\n      }\n    }\n  }\n\n  // Clean up.\n  delete[] field;\n  delete[] in_cplx;\n  delete[] out_cplx;\n\n  return 0;\n}\n\n\n\n// Reference 1-D indefinite function with both a central\n// difference and a Laplace-like term.\nvoid indefinite_1d_gauge(complex<double>* out, complex<double>* in, const int L, const double m2, complex<double>* field)\n{\n  // Loop over all sites, applying fields.\n  for (int i = 0; i < L; i++)\n  {\n    // 0.5's correspond to the central difference, 1.0's to the second derivative.\n    out[i] = (2+m2)*in[i] + conj(field[(i-1+L)%L])*(-0.5-1.0)*in[(i-1+L)%L] + field[i]*(0.5-1.0)*in[(i+1)%L];\n  }\n\n  // Done.\n  return;\n}\n\n", "meta": {"hexsha": "4ac03fdcc85569bd08e20c48742cec6cfb5a83c2", "size": 5203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigens-with-eigen/complex_indefinite/example_complex_indefinite.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/complex_indefinite/example_complex_indefinite.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/complex_indefinite/example_complex_indefinite.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": 29.5625, "max_line_length": 122, "alphanum_fraction": 0.641745147, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6769810188369422}}
{"text": "#include <armadillo>\n\n#include \"evaluate_covariance.hpp\"\n\nusing namespace arma;\n\n/*\nGet cross-covariance matrix between two location sets\n\nInput:\n    locationsX1: X coordinates of location set 1\n    locationsY1: Y coordinates of location set 1\n    locationsX2: X coordinates of location set 2\n    locationsY2: Y coordinates of location set 2\n    nLocations1: the number of locations in lcs1\n    nLocations2: the number of locations in lcs2\n    sill: sill parameter\n    range: range parameter\n    nugget: nugget parameter\n\nOutput:\n    covarianceMatrix: obtained covariances, of dimension nLocations2 * nLocations1\n*/\nvoid evaluate_cross_covariance(double *covarianceMatrix, double *locationsX1, double *locationsY1, double *locationsX2, double *locationsY2, const unsigned long &nLocations1, const unsigned long &nLocations2, const double &sill, const double &range, const double &nugget)\n{\n    for(unsigned long index1 = 0; index1 < nLocations1; index1++)\n        for(unsigned long index2 = 0; index2 < nLocations2; index2++)\n        {\n            double xDifference=locationsX1[index1]-locationsX2[index2];\n            double yDifference=locationsY1[index1]-locationsY2[index2];\n\n            double distance = sqrt( xDifference*xDifference + yDifference*yDifference );\n            if (distance < 1e-14)\n                covarianceMatrix[index1*nLocations2+index2] = sill + nugget;\n            else\n                covarianceMatrix[index1*nLocations2+index2] = sill*exp(-distance/range);\n        }\n}\n\n/*\nGet variance-covariance matrix for one location set\n\nInput:\n    locationsX: X coordinates\n    locationsY: Y coordinates\n    nLocations: the number of locations\n    sill: sill parameter\n    range: range parameter\n    nugget: nugget parameter\n\nOutput:\n    covarianceMatrix: obtained covariances, of dimension nLocations * nLocations\n*/\nvoid evaluate_variance_covariance(double *covarianceMatrix, double *locationsX, double *locationsY, const unsigned long &nLocations, const double &sill, const double &range, const double &nugget)\n{\n    double offDiagonal;\n    double diagonal = sill + nugget;\n    for(unsigned long index1 = 0; index1 < nLocations; index1++)\n    {\n        for(unsigned long index2 = 0; index2 < index1; index2++)\n        {\n            double xDifference=locationsX[index1]-locationsX[index2];\n            double yDifference=locationsY[index1]-locationsY[index2];\n\n            double distance = sqrt( xDifference*xDifference + yDifference*yDifference );\n            if (distance < 1e-14)\n                offDiagonal = sill + nugget;\n            else \n                offDiagonal = sill*exp(-distance/range);\n\n            covarianceMatrix[index1*nLocations+index2] = offDiagonal;\n            covarianceMatrix[index2*nLocations+index1] = offDiagonal;\n        }\n        covarianceMatrix[index1*nLocations+index1] = diagonal;\n    }\n}\n\n", "meta": {"hexsha": "024da3679f3133c7ebe3a2388e37de32129bce4b", "size": 2849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "serial_MRA/src/evaluate_covariance.cpp", "max_stars_repo_name": "hhuang90/MRA", "max_stars_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "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": "serial_MRA/src/evaluate_covariance.cpp", "max_issues_repo_name": "hhuang90/MRA", "max_issues_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-19T00:41:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T14:50:55.000Z", "max_forks_repo_path": "serial_MRA/src/evaluate_covariance.cpp", "max_forks_repo_name": "hhuang90/MRA", "max_forks_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T00:40:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T00:40:21.000Z", "avg_line_length": 36.5256410256, "max_line_length": 271, "alphanum_fraction": 0.6956826957, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6768366383845137}}
{"text": "#include <iostream>\n#include <vector>\n#include <limits>\n#include <cmath>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\n// For dijkstra\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\n\n\n// For max flow\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor>>>> graph;\n\nclass edge_adder {\n  graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n\n  void add_edge(int from, int to, long capacity) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const auto e = boost::add_edge(from, to, G).first;\n    const auto rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  }\n};\n\nusing namespace std;\n\n// Compute shortest distances\nvoid dijkstra(const weighted_graph &G, int s, vector<int>& dist_map) {\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\n// Is it possible for all agents to seek shelter for a given tMax?\nbool isFeasible(vector<vector<int>>& timeToShelter, int capacity, int timeToEnter, int tMax) {\n  int a = timeToShelter.size();\n  int s = timeToShelter[0].size();\n  \n  graph G(a + capacity * s + 2);\n  edge_adder adder(G);\n  int source = a + capacity * s;\n  int target = source + 1;\n  \n  for (int i = 0; i < a; ++i) { \n    adder.add_edge(source, i, 1);\n  }\n  \n  for (int j = 0; j < s; ++j) { \n    for (int c = 1; c <= capacity; ++c) {\n      adder.add_edge(a + (c - 1) * s + j, target, 1);\n    }\n  }\n   \n  \n  for (int i = 0; i < a; ++i) {\n    for (int j = 0; j < s; ++j) {\n      for (int c = 1; c <= capacity; ++c) {\n        if (timeToShelter[i][j] <= tMax - c * timeToEnter) {\n          adder.add_edge(i, a + (c - 1) * s + j, 1);\n        }\n      }\n    }\n  }\n  \n  long flow = boost::push_relabel_max_flow(G, source, target);\n  return flow == a;\n}\n\n// Use binary search to find the smallest t such that (isFeasible(t) == True)\nvoid solve() {\n    \n    int n, m, a, s, c, d;\n    cin >> n >> m >> a >> s >> c >> d;\n    \n    // Read skiing area\n    weighted_graph G(n);\n    char w;\n    int x, y, z;\n    for (int i = 0; i < m; ++i) {\n      cin >> w >> x >> y >> z;\n      \n      boost::add_edge(x, y, z, G);\n      if (w == 'L') {\n         boost::add_edge(y, x, z, G);\n      }\n    }\n    \n    // Read agent positions\n    vector<int> agents(a);\n    for (int i = 0; i < a; ++i) {\n      cin >> agents[i];\n    }\n    \n    // Read shelter positions\n    vector<int> shelters(s);\n    for (int j = 0; j < s; ++j) {\n      cin >> shelters[j];\n    }\n    \n    vector<vector<int>> distToShelter(a, vector<int>(s)); \n    for (int i = 0; i < a; ++i) {\n      vector<int> dist_map(n);\n      dijkstra(G, agents[i], dist_map);\n      for (int j = 0; j < s; ++j) {\n        distToShelter[i][j] = dist_map[shelters[j]];\n      }\n    }\n    \n    int low = 1;\n    int high = numeric_limits<int>::max() - 1;\n    \n    while (low != high) {\n      int t = low + (high - low) / 2;\n      if (isFeasible(distToShelter, c, d, t)) {\n        high = t;   \n      }\n      else {\n        low = t + 1;\n      }\n    }\n    \n    cout << low << endl;\n  \n}\n\nint main()\n{\n  ios_base::sync_with_stdio(false);\n  int t; cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "f61b824df898d3221b9aec9ee3d0fa5e884dd994", "size": 3933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/secret_service.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/secret_service.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "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/secret_service.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 26.22, "max_line_length": 94, "alphanum_fraction": 0.5758962624, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6768008243924474}}
{"text": "/**\n * @file\n * Test of rotation-chain example using Ceres autodiff, for comparison\n */\n#include <benchmark/benchmark.h>\n#include <ceres/ceres.h>\n#include <Eigen/Core>\n\n#include \"../bechmark_helpers.hpp\"\n\ntemplate <typename Scalar>\nusing Mat3 = Eigen::Matrix<Scalar, 3, 3, Eigen::RowMajor>;\n\ntemplate <typename Scalar>\nusing Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n\ntemplate <typename Scalar>\nusing Mat9 = Eigen::Matrix<Scalar, 9, 9, Eigen::RowMajor>;\n\ntemplate <typename Scalar>\nusing InVec3 = Eigen::Map<const Vec3<Scalar>>;\n\ntemplate <typename Scalar>\nusing OutVec3 = Eigen::Map<Vec3<Scalar>>;\n\ntemplate <typename Scalar>\nusing InMat3 = Eigen::Map<const Mat3<Scalar>>;\n\ntemplate <typename Scalar>\nusing OutMat3 = Eigen::Map<Mat3<Scalar>>;\n\nstruct ChainFunctor1 {\n    template <typename T>\n    bool operator()(const T *const x0, const T *const x1, T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * v1;\n        return true;\n    }\n};\n\nstruct ChainFunctor2 {\n    template <typename T>\n    bool operator()(const T *const x0, const T *const x1, const T *const x2, T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        InMat3<T> R2{x2};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * (R2 * v1);\n        return true;\n    }\n};\n\nstruct ChainFunctor3 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        InMat3<T> R2{x2};\n        InMat3<T> R3{x3};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * (R2 * (R3 * v1));\n        return true;\n    }\n};\n\nstruct ChainFunctor4 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        InMat3<T> R2{x2};\n        InMat3<T> R3{x3};\n        InMat3<T> R4{x4};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * (R2 * (R3 * (R4 * v1)));\n        return true;\n    }\n};\n\nstruct ChainFunctor5 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    const T *const x5,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        InMat3<T> R2{x2};\n        InMat3<T> R3{x3};\n        InMat3<T> R4{x4};\n        InMat3<T> R5{x5};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * (R2 * (R3 * (R4 * (R5 * v1))));\n        return true;\n    }\n};\n\nstruct ChainFunctor6 {\n    template <typename T>\n    bool operator()(const T *const x0,\n                    const T *const x1,\n                    const T *const x2,\n                    const T *const x3,\n                    const T *const x4,\n                    const T *const x5,\n                    const T *const x6,\n                    T *e) const {\n        InVec3<T> v1{x0};\n        InMat3<T> R1{x1};\n        InMat3<T> R2{x2};\n        InMat3<T> R3{x3};\n        InMat3<T> R4{x4};\n        InMat3<T> R5{x5};\n        InMat3<T> R6{x6};\n        OutVec3<T> v2{e};\n\n        v2 = R1 * (R2 * (R3 * (R4 * (R5 * (R6 * v1)))));\n        return true;\n    }\n};\n\n\nvoid BM_ceres_Chain1(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor1, 3, 3, 9>{new ChainFunctor1()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1;\n            double const *const inputs[] = {v1_vec[i].data(), R1_vec[i].value().data()};\n            double *jacobians[] = {J0.data(), J1.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n        }\n    }\n}\n\nvoid BM_ceres_Chain2(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n    auto R2_vec = randomMatrices<wave::RotationMd>(N);\n    auto R3_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor2, 3, 3, 9, 9>{new ChainFunctor2()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J2;\n\n            double const *const inputs[] = {\n              v1_vec[i].data(), R1_vec[i].value().data(), R2_vec[i].value().data()};\n            double *jacobians[] = {J0.data(), J1.data(), J2.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n        }\n    }\n}\n\nvoid BM_ceres_Chain3(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n    auto R2_vec = randomMatrices<wave::RotationMd>(N);\n    auto R3_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor3, 3, 3, 9, 9, 9>{new ChainFunctor3()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J2;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J3;\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().data(),\n                                            R2_vec[i].value().data(),\n                                            R3_vec[i].value().data()};\n            double *jacobians[] = {J0.data(), J1.data(), J2.data(), J3.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n        }\n    }\n}\n\nvoid BM_ceres_Chain4(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n    auto R2_vec = randomMatrices<wave::RotationMd>(N);\n    auto R3_vec = randomMatrices<wave::RotationMd>(N);\n    auto R4_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor4, 3, 3, 9, 9, 9, 9>{\n        new ChainFunctor4()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1, J2, J3, J4;\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().data(),\n                                            R2_vec[i].value().data(),\n                                            R3_vec[i].value().data(),\n                                            R4_vec[i].value().data()};\n            double *jacobians[] = {J0.data(), J1.data(), J2.data(), J3.data(), J4.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n            benchmark::DoNotOptimize(J4);\n        }\n    }\n}\n\nvoid BM_ceres_Chain5(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n    auto R2_vec = randomMatrices<wave::RotationMd>(N);\n    auto R3_vec = randomMatrices<wave::RotationMd>(N);\n    auto R4_vec = randomMatrices<wave::RotationMd>(N);\n    auto R5_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor5, 3, 3, 9, 9, 9, 9, 9>{\n        new ChainFunctor5()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1, J2, J3, J4, J5;\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().data(),\n                                            R2_vec[i].value().data(),\n                                            R3_vec[i].value().data(),\n                                            R4_vec[i].value().data(),\n                                            R5_vec[i].value().data()};\n            double *jacobians[] = {\n              J0.data(), J1.data(), J2.data(), J3.data(), J4.data(), J5.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n            benchmark::DoNotOptimize(J4);\n            benchmark::DoNotOptimize(J5);\n        }\n    }\n}\n\nvoid BM_ceres_Chain6(benchmark::State &state) {\n    const auto N = state.range(0);\n    state.SetComplexityN(N);\n\n    auto v1_vec = randomMatrices<Eigen::Vector3d>(N);\n    auto R1_vec = randomMatrices<wave::RotationMd>(N);\n    auto R2_vec = randomMatrices<wave::RotationMd>(N);\n    auto R3_vec = randomMatrices<wave::RotationMd>(N);\n    auto R4_vec = randomMatrices<wave::RotationMd>(N);\n    auto R5_vec = randomMatrices<wave::RotationMd>(N);\n    auto R6_vec = randomMatrices<wave::RotationMd>(N);\n\n    std::unique_ptr<ceres::CostFunction> cost_function{\n      new ceres::AutoDiffCostFunction<ChainFunctor6, 3, 3, 9, 9, 9, 9, 9, 9>{\n        new ChainFunctor6()}};\n\n    for (auto _ : state) {\n        for (auto i = N; i-- > 0;) {\n            Mat3<double> res;\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor> J0;\n            Eigen::Matrix<double, 3, 9, Eigen::RowMajor> J1, J2, J3, J4, J5, J6;\n\n            double const *const inputs[] = {v1_vec[i].data(),\n                                            R1_vec[i].value().data(),\n                                            R2_vec[i].value().data(),\n                                            R3_vec[i].value().data(),\n                                            R4_vec[i].value().data(),\n                                            R5_vec[i].value().data(),\n                                            R6_vec[i].value().data()};\n            double *jacobians[] = {J0.data(),\n                                   J1.data(),\n                                   J2.data(),\n                                   J3.data(),\n                                   J4.data(),\n                                   J5.data(),\n                                   J6.data()};\n            cost_function->Evaluate(inputs, res.data(), jacobians);\n\n            benchmark::DoNotOptimize(res);\n            benchmark::DoNotOptimize(J0);\n            benchmark::DoNotOptimize(J1);\n            benchmark::DoNotOptimize(J2);\n            benchmark::DoNotOptimize(J3);\n            benchmark::DoNotOptimize(J4);\n            benchmark::DoNotOptimize(J5);\n            benchmark::DoNotOptimize(J6);\n        }\n    }\n}\n\n\nBENCHMARK(BM_ceres_Chain1)->Arg(1000);\nBENCHMARK(BM_ceres_Chain2)->Arg(1000);\nBENCHMARK(BM_ceres_Chain3)->Arg(1000);\nBENCHMARK(BM_ceres_Chain4)->Arg(1000);\nBENCHMARK(BM_ceres_Chain5)->Arg(1000);\nBENCHMARK(BM_ceres_Chain6)->Arg(1000);\n\nWAVE_BENCHMARK_MAIN()\n", "meta": {"hexsha": "1e6984f798e7df135ae0fb3193396b88dc145944", "size": 12799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_bench.cpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_bench.cpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "benchmarks/rotate_chain/rotate_chain_ceres_bench.cpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 34.1306666667, "max_line_length": 90, "alphanum_fraction": 0.5238690523, "num_tokens": 3596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6766461371817682}}
{"text": "#ifndef RAI_CHOLINV_HPP\n#define RAI_CHOLINV_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace rai {\n\ntemplate<typename Derived, int n_>\nstatic inline void cholInv(Eigen::Matrix<Derived, n_, n_> &A, Eigen::Matrix<Derived, n_, n_> &AInv) {\n  unsigned short int i, j, k, n = (unsigned short int) (n_);\n  Derived sum;\n  Derived p[n];\n  memcpy(AInv.data(), A.data(), n * n * sizeof(Derived));\n\n  p[0] = std::sqrt(AInv(0, 0));\n\n  for (j = 1; j < n; j++)\n    AInv(j, 0) = AInv(0, j) / p[0];\n\n  for (i = 1; i < n; i++) {\n    sum = AInv(i, i);\n    for (k = i - 1; k >= 1; k--)\n      sum -= AInv(i, k) * AInv(i, k);\n    sum -= AInv(i, 0) * AInv(i, 0);\n    p[i] = std::sqrt(sum);\n    for (j = i + 1; j < n; j++) {\n      sum = AInv(i, j);\n      for (k = i - 1; k >= 1; k--)\n        sum -= AInv(i, k) * AInv(j, k);\n      sum -= AInv(i, 0) * AInv(j, 0);\n      AInv(j, i) = sum / p[i];\n    }\n  }\n\n  for (i = 0; i < n; i++) {\n    AInv(i, i) = 1.0 / p[i];\n    for (j = i + 1; j < n; j++) {\n      sum = 0.0;\n      for (k = i; k < j; k++) {\n        sum -= AInv(j, k) * AInv(k, i);\n      }\n      AInv(j, i) = sum / p[j];\n    }\n  }\n\n  for (i = 0; i < n; i++) {\n    AInv(i, i) *= AInv(i, i);\n    for (k = i + 1; k < n; k++)\n      AInv(i, i) += AInv(k, i) * AInv(k, i);\n\n    for (j = i + 1; j < n; j++) {\n      AInv(i, j) = AInv(j, i) * AInv(j, j);\n      for (k = j + 1; k < n; k++)\n        AInv(i, j) += AInv(k, i) * AInv(k, j);\n    }\n  }\n\n  for (i = 1; i < n; i++)\n    for (j = 0; j < i; j++)\n      AInv(i, j) = AInv(j, i);\n\n}\n}\n\n#endif //RAI_CHOLINV_HPP\n", "meta": {"hexsha": "77112074ca0ecc22e982bc1e507d5e028095f523", "size": 1545, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/raiCommon/math/inverseUsingCholesky.hpp", "max_stars_repo_name": "Wistral/raicommon", "max_stars_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_stars_repo_licenses": ["MIT"], "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/raiCommon/math/inverseUsingCholesky.hpp", "max_issues_repo_name": "Wistral/raicommon", "max_issues_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_issues_repo_licenses": ["MIT"], "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/raiCommon/math/inverseUsingCholesky.hpp", "max_forks_repo_name": "Wistral/raicommon", "max_forks_repo_head_hexsha": "f6f3623bfa3a80a9ede4e79afc37195af3fb8609", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T20:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T07:47:53.000Z", "avg_line_length": 23.0597014925, "max_line_length": 101, "alphanum_fraction": 0.4310679612, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6766461278527269}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n\n#include \"sampler.hpp\"\n\nnamespace rek {\n\nusing namespace Eigen;\nusing RowVector = Eigen::Matrix<double, Eigen::Dynamic, 1>;\n\nclass Solver {\n\n  /** Periodically check for convergence */\n  int blockSize_ = 1000;\n\n  constexpr static double tolerance_ = 10e-5;\n\n  bool hasConverged(SparseMatrix<double, RowMajor> &A,\n                    SparseMatrix<double, ColMajor> &AColMajor,\n                    const RowVector &x, const RowVector &b, const RowVector &z,\n                    double tolerance) const {\n\n    const RowVector residual = A * x - b + z;\n    const bool condOne = residual.norm() < tolerance;\n\n    // Early return\n    if (!condOne)\n      return false;\n\n    const RowVector zA = z.transpose() * AColMajor;\n    return zA.norm() < tolerance;\n  }\n\n  // FIXME: Is this necessary? Duplicate with hasConverged()\n  bool hasConvergedDense(Matrix<double, Dynamic, Dynamic, RowMajor> &A,\n                         Matrix<double, Dynamic, Dynamic, ColMajor> &AColMajor,\n                         const RowVector &x, const RowVector &b,\n                         const RowVector &z, double tolerance) const {\n\n    const RowVector residual = A * x - b + z;\n    const bool condOne = residual.norm() < tolerance;\n\n    // Early return\n    if (!condOne)\n      return false;\n\n    const RowVector zA = z.transpose() * AColMajor;\n    return zA.norm() < tolerance;\n  }\n\n  RowVector solve(SparseMatrix<double, RowMajor> &A,\n                  SparseMatrix<double, ColMajor> &AColMajor, const RowVector &b,\n                  long MaxIterations, double tolerance = tolerance_) const {\n    const long m = A.rows(), n = AColMajor.cols();\n    RowVector x(A.cols());\n    RowVector z(b);\n    RowVector rowNorms(A.rows());\n    RowVector columnNorms(A.cols());\n\n    x.setZero();\n\n    for (long i = 0; i < m; i++) {\n      rowNorms(i) = A.row(i).squaredNorm();\n    }\n\n    for (long j = 0; j < n; j++) {\n      columnNorms(j) = AColMajor.col(j).squaredNorm();\n    }\n\n    sample::AliasSampler rowSampler(rowNorms);\n    sample::AliasSampler colSampler(columnNorms);\n\n    // Initialize Alias samplers, O(n)\n    rowSampler.initSampler();\n    colSampler.initSampler();\n\n    for (long k = 0; k < MaxIterations; k++) {\n\n      // Check for convergence every blockSize_ iterations\n      if ((k + 1) % blockSize_ == 0 &&\n          hasConverged(A, AColMajor, x, b, z, tolerance))\n        break;\n\n      const long i_k = rowSampler.walkerSample();\n      const long j_k = colSampler.walkerSample();\n\n      double val = -AColMajor.col(j_k).dot(z) / columnNorms(j_k);\n      z += val * AColMajor.col(j_k);\n      val = A.row(i_k).dot(x);\n      val = (b(i_k) - z(i_k) - val) / rowNorms(i_k);\n\n      // TODO: .toDense() seems to be required here!\n      // FIXME: replace .toDense() with iteration over sparse i_k row\n      x += val * A.row(i_k).toDense();\n    }\n\n    return x;\n  }\n\n  /**\n   * Returns the solution to Ax=b using the Randomized Extended Kaczmarz method\n   *\n   * @param AColMajor Input dense matrix\n   * @param b Right hand side vector\n   * @param maxIterations Maximum number of iterations\n   * @param tolerance Accuracy tolerance, default tolerance_\n   * @return Returns an approximate solution to ||Ax - b||_2\n   */\n  RowVector solve(Matrix<double, Dynamic, Dynamic, ColMajor> &AColMajor,\n                  Matrix<double, Dynamic, Dynamic, RowMajor> &ARowMajor,\n                  const RowVector &b, long maxIterations,\n                  double tolerance = tolerance_) const {\n    const long m = ARowMajor.rows(), n = AColMajor.cols();\n    RowVector x(AColMajor.cols());\n    RowVector z(b);\n    RowVector rowNorms(AColMajor.rows());\n    RowVector columnNorms(AColMajor.cols());\n\n    x.setZero();\n\n    for (long i = 0; i < m; i++) {\n      rowNorms(i) = ARowMajor.row(i).squaredNorm();\n    }\n\n    for (long j = 0; j < n; j++) {\n      columnNorms(j) = AColMajor.col(j).squaredNorm();\n    }\n\n    for (long k = 0; k < maxIterations; k++) {\n\n      // Check for convergence every blockSize_ iterations\n      if ((k + 1) % blockSize_ == 0 &&\n          hasConvergedDense(ARowMajor, AColMajor, x, b, z, tolerance)) {\n        break;\n      }\n\n      // Extended Kaczmarz\n      const long i_k = k % m;\n      const long j_k = k % n;\n\n      double val = -z.dot(AColMajor.col(j_k)) / columnNorms(j_k);\n      z += val * AColMajor.col(j_k);\n      val = x.dot(ARowMajor.row(i_k));\n      val = (b(i_k) - z(i_k) - val) / rowNorms(i_k);\n\n      x += val * ARowMajor.row(i_k);\n    }\n    return x;\n  }\n\npublic:\n  Solver() = default;\n\n  RowVector solve(Matrix<double, Dynamic, Dynamic, ColMajor> &AColMajor,\n                  const RowVector &b, long MaxIterations) const {\n    // Duplicate input matrix to row major storage\n    Matrix<double, Dynamic, Dynamic, RowMajor> ARowMajor(AColMajor);\n    return solve(AColMajor, ARowMajor, b, MaxIterations);\n  }\n\n  /**\n   * Returns the solution to Ax=b using the Randomized Extended Kaczmarz method\n   *\n   * @param A Input sparse matrix in row major format\n   * @param b Right hand side vector\n   * @param maxIterations Maximum number of iterations\n   * @param tolerance Accuracy tolerance, default tolerance_\n   * @return Returns an approximate solution to ||Ax - b||_2\n   */\n  RowVector solve(SparseMatrix<double, RowMajor> &A,\n                  const Matrix<double, Dynamic, 1> &b, long maxIterations,\n                  double tolerance = tolerance_) const {\n    SparseMatrix<double, ColMajor> AColMajor(A.rows(), A.cols());\n\n    // Copy row major to column major sparse matrix\n    AColMajor.reserve(A.nonZeros());\n    for (long k = 0; k < A.outerSize(); ++k)\n      for (SparseMatrix<double, RowMajor>::InnerIterator it(A, k); it; ++it) {\n        AColMajor.insert(it.row(), it.col()) = it.value();\n      }\n\n    return solve(A, AColMajor, b, maxIterations, tolerance);\n  };\n\n  /**\n   * Returns the solution to Ax=b using the Randomized Extended Kaczmarz method\n   *\n   * @param A Input sparse matrix in column major format\n   * @param b Right hand side vector\n   * @param maxIterations Maximum number of iterations\n   * @param tolerance Accuracy tolerance, default tolerance_\n   * @return Returns an approximate solution to ||Ax - b||_2\n   */\n  RowVector solve(SparseMatrix<double, ColMajor> &AColMajor, const RowVector &b,\n                  long maxIterations, double tolerance = tolerance_) const {\n\n    SparseMatrix<double, RowMajor> A(AColMajor.rows(), AColMajor.cols());\n\n    // Copy column major to row major sparse matrix\n    A.reserve(AColMajor.nonZeros());\n    for (long k = 0; k < AColMajor.outerSize(); ++k)\n      for (SparseMatrix<double, ColMajor>::InnerIterator it(AColMajor, k); it;\n           ++it)\n        A.insert(it.row(), it.col()) = it.value();\n\n    return solve(A, AColMajor, b, maxIterations, tolerance);\n  };\n};\n\n} // namespace rek", "meta": {"hexsha": "9ce804edaf7a42e06c1da195af2919613e28e0fd", "size": 6825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver.hpp", "max_stars_repo_name": "zouzias/REK-CPP", "max_stars_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T06:50:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T08:48:25.000Z", "max_issues_repo_path": "src/solver.hpp", "max_issues_repo_name": "zouzias/REK-CPP", "max_issues_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "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/solver.hpp", "max_forks_repo_name": "zouzias/REK-CPP", "max_forks_repo_head_hexsha": "01eaaf4f5d05e7665595a8d3dc919632ba2940fa", "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": 32.0422535211, "max_line_length": 80, "alphanum_fraction": 0.6234432234, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404057671714, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6766097966197104}}
{"text": "/**\n * @file 1dwaveabsorbingbc.cc\n * @brief NPDE homework \"1DWaveAbsorbingBC\" code\n * @author Oliver Rietmann\n * @date 08.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"1dwaveabsorbingbc.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <utility>\n#include <vector>\n\nnamespace WaveAbsorbingBC1D {\n\nconstexpr double PI = 3.14159265358979323846;\n\n// Boundary data on the right-hand side (x = 1)\ndouble g(double t) { return 0 <= t && t <= PI ? std::sin(t) : 0.0; }\n\n/**\n * @brief Get the full (--> including both boundary points) Galerkin matrix A\n * @param N number of spacial nodes, including x=0, but excluding x=1\n * @param c speed of propagation\n * @param h (spacial) meshwidth\n * @return Full Galerkin matrix A of shape (N+1)x(N+1)\n */\n/* SAM_LISTING_BEGIN_7 */\nEigen::SparseMatrix<double> getA_full(unsigned int N, double c, double h) {\n  std::vector<Eigen::Triplet<double>> triplets;\n  triplets.reserve(3 * (N + 1) - 2);  // that many triplets needed\n  const double scale = c * c / h;\n  // store first row separately\n  triplets.push_back(Eigen::Triplet<double>(0, 0, scale));\n  triplets.push_back(Eigen::Triplet<double>(0, 1, -scale));\n  // loop over interior rows\n  for (unsigned i = 1; i < N; ++i) {\n    triplets.push_back(Eigen::Triplet<double>(i, i - 1, -scale));\n    triplets.push_back(Eigen::Triplet<double>(i, i, 2.0 * scale));\n    triplets.push_back(Eigen::Triplet<double>(i, i + 1, -scale));\n  }\n  // store last row separately\n  triplets.push_back(Eigen::Triplet<double>(N, N - 1, -scale));\n  triplets.push_back(Eigen::Triplet<double>(N, N, scale));\n  // Creat (N+1)x(N+1) sparse matrix in CRS format\n  Eigen::SparseMatrix<double> A(N + 1, N + 1);\n  A.setFromTriplets(triplets.begin(), triplets.end());\n  return A;\n}\n/* SAM_LISTING_END_7 */\n\n/**\n * @brief Get the full (--> including both boundary points) Galerkin matrix B\n * @param N number of spacial nodes, including x=0, but excluding x=1\n * @param c speed of propagation\n * @return Full Galerkin matrix B of size (N+1)x(N+1)\n */\n/* SAM_LISTING_BEGIN_8 */\nEigen::SparseMatrix<double> getB_full(unsigned int N, double c) {\n  Eigen::SparseMatrix<double> B(N + 1, N + 1);\n  // Just a single non-zero entry; we can afford to sete it directly\n  B.coeffRef(0, 0) = c;\n  return B;\n}\n/* SAM_LISTING_END_8 */\n\n/**\n * @brief Get the full (--> including both boundary points) Galerkin matrix M\n * @param N number of spacial nodes, including x=0, but excluding x=1\n * @param h (spacial) meshwidth\n * @return Full Galerkin matrix M of size (N+1)x(N+1)\n * Note that M is a diagonal matrix!\n */\n/* SAM_LISTING_BEGIN_9 */\nEigen::SparseMatrix<double> getM_full(unsigned int N, double h) {\n  Eigen::SparseMatrix<double> M(N + 1, N + 1);\n  M.setIdentity();  // Supposed to be efficient\n  M *= h;\n  // Modify two entries; efficiency does not matter much\n  M.coeffRef(0, 0) = h / 2;\n  M.coeffRef(N, N) = h / 2;\n  return M;\n}\n/* SAM_LISTING_END_9 */\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::MatrixXd waveLeapfrogABC(double c, double T, unsigned int N,\n                                unsigned int m) {\n  // N is also the number of cells of the mesh\n  double h = 1.0 / N;\n  // Obtain Galerkin matrices for truncated finite element space\n  // Note that the functions get*_full return the matrices for the full finite\n  // element space including the tent function located at x=1. Removing the last\n  // row and column of that matrix amounts to dropping that basis function.\n  // However, the efficiency of this block() operation in the case of sparse\n  // matrices is in doubt, in particular, since the result is assigned to\n  // another sparse matrix, which foils Eigen's expression template\n  // optimization. The use of \"auto\" would be highly advisable here!\n  Eigen::SparseMatrix<double> A = getA_full(N, c, h).block(0, 0, N, N);\n  Eigen::SparseMatrix<double> B = getB_full(N, c).block(0, 0, N, N);\n  Eigen::SparseMatrix<double> M = getM_full(N, h).block(0, 0, N, N);\n  // Matrix for returning solution\n  Eigen::MatrixXd R(m + 1, N + 1);\n  //====================\n  // Your code goes here\n  //====================\n  return R;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::pair<Eigen::VectorXd, Eigen::VectorXd> computeEnergies(\n    const Eigen::MatrixXd &full_solution, double c, double tau) {\n  int m = full_solution.rows() - 1;\n  int N = full_solution.cols() - 1;\n  double h = 1.0 / N;\n\n  Eigen::SparseMatrix<double> A = getA_full(N, c, h);\n  Eigen::SparseMatrix<double> M = getM_full(N, h);\n\n  Eigen::VectorXd E_pot(m + 1);\n  Eigen::VectorXd E_kin(m);\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return std::make_pair(E_pot, E_kin);\n}\n/* SAM_LISTING_END_2 */\n\n}  // namespace WaveAbsorbingBC1D\n", "meta": {"hexsha": "4ff7300ab838e452a417b31c1a51513c7c948c89", "size": 4754, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.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/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.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/1DWaveAbsorbingBC/templates/1dwaveabsorbingbc.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": 34.700729927, "max_line_length": 80, "alphanum_fraction": 0.6665965503, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6765935795114554}}
{"text": "#include \"enkf.hpp\"\n#include <Eigen/Core>\n#include <vector>\n#include <fstream>\n\nusing Vec = Eigen::VectorXd;\nusing Mat = Eigen::MatrixXd;\n\nVec Henon_Map(Vec& x, double& a, double& b){\n  auto xn = x[0];\n  auto yn = x[1];\n\n  x[0] = 1 - a * xn * xn + yn;\n  x[1] = b * xn;\n\n  return x;\n}\n\ndouble obs_err(){\n   std::random_device rd{};\n   std::mt19937 gen{rd()};\n   std::normal_distribution<> dis{0.0, std::sqrt(0.02)};\n\n   return dis(gen);\n}\n\nint main(int argc, char** argv){\n  using namespace fastmath;\n\n  std::function<Vec(Vec&, double&, double&)> fmap = Henon_Map;\n  int ensemble_size = 31;\n  auto initial_state = Vec::Zero(2);\n\n  Mat H(1,2);\n\n  H << 1.0, 0.0;\n\n  Vec true_state(2);\n  true_state << 0.0, 0.0;\n\n  Vec ensemble_mean = Vec::Zero(ensemble_size);\n\n  Mat ensemble_cov = 0.01 * Mat::Identity(2,2);\n\n  Mat obs_err_cov = 0.02 * Mat::Identity(1,1);\n\n  int n_assim_cycles = 100;\n\n  double a = 1.4, b = 0.3;\n  Mat state_mat(2, n_assim_cycles);\n  for(auto i = 0; i < n_assim_cycles; ++i){\n    true_state = Henon_Map(true_state, a, b);\n    state_mat.col(i) = true_state;\n  }\n\n  std::vector<double> filter_err, etkf_err;\n\n  auto enkf_runner = VectorEnKF<double, double>(fmap, H, initial_state,\n\t\t\t\t\t\tobs_err_cov, initial_state,\n\t\t\t\t\t\tensemble_cov, ensemble_size);\n\n  auto etkf_runner = VectorEnKF<double, double>(fmap, H, initial_state,\n\t\t\t\t\t\tobs_err_cov, initial_state,\n\t\t\t\t\t\tensemble_cov, ensemble_size);\n\n  Vec y(1);\n  double yval;\n  Vec analysis_mean;\n  for(auto i = 0; i < n_assim_cycles; ++i){\n    true_state = state_mat.col(i);\n    yval = true_state[0] + obs_err();\n    y[0] = yval;\n    enkf_runner.filter(y, a, b);\n    etkf_runner.filter(y, a, b);\n    analysis_mean = enkf_runner.state();\n    Vec etkf_mean = etkf_runner.state();\n    Vec err = true_state - analysis_mean;\n    filter_err.push_back(err.norm());\n    err = true_state - etkf_mean;\n    etkf_err.push_back(err.norm());\n  }\n\n  std::ofstream fwriter(\"hw7.csv\"), twriter(\"hw7etkf.csv\");\n  for(const auto& e : filter_err){\n    fwriter << e << '\\n';\n  }\n\n  for(const auto& e : etkf_err){\n    twriter << e << '\\n';\n  }\n\n  return 0;\n}\n  \n\n\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n  \n  \n", "meta": {"hexsha": "20a27b3973d25afa10c1b3e14211cc6435bec764", "size": 2122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enkf/include/hw7.cpp", "max_stars_repo_name": "DiffeoInvariant/Data-Assimilation", "max_stars_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "enkf/include/hw7.cpp", "max_issues_repo_name": "DiffeoInvariant/Data-Assimilation", "max_issues_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enkf/include/hw7.cpp", "max_forks_repo_name": "DiffeoInvariant/Data-Assimilation", "max_forks_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_forks_repo_licenses": ["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.0099009901, "max_line_length": 71, "alphanum_fraction": 0.6225259189, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6765762936838665}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <sophus/se3.hpp>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <vector>\n#include <cmath>\n// need pangolin for plotting trajectory\n#include <pangolin/pangolin.h>\nusing namespace std;\nusing namespace Eigen;\n\nstring gtFile = \"../groundtruth.txt\";\nstring estFile = \"../estimated.txt\";\n\nvoid DrawTrajectory(vector<Sophus::SE3d> poses1, vector<Sophus::SE3d> poses2) {\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n            .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n    while (pangolin::ShouldQuit() == false) {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n        for (size_t i = 0; i < poses1.size() - 1; i++) {\n            glColor3f(1, 0.0f, 0);\n            glBegin(GL_LINES);\n            auto p1 = poses1[i], p2 = poses1[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n        for (size_t i = 0; i < poses2.size() - 1; i++) {\n            glColor3f(0, 0.0f, 1);\n            glBegin(GL_LINES);\n            auto p1 = poses2[i], p2 = poses2[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n\n}\n\nint main(){\n    ifstream gtFin(gtFile);\n    ifstream estFin(estFile);\n    double error = 0;\n    int count = 0;\n    vector<Sophus::SE3d> poses_gt;\n    vector<Sophus::SE3d> poses_est;\n    while(!gtFin.eof() && !estFin.eof()){\n        double time, tx,ty,tz,qx,qy,qz,qw;\n        gtFin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n        Quaterniond q(qw,qx,qy,qz);\n        Vector3d t(tx,ty,tz);\n        Sophus::SE3d SE3_gt(q,t);\n        poses_gt.push_back(SE3_gt);\n        estFin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n        Quaterniond q2(qw,qx,qy,qz);\n        Vector3d t2(tx,ty,tz);\n        Sophus::SE3d SE3_est(q2,t2);\n        poses_est.push_back(SE3_est);\n        Sophus::SE3d SE3_differ = SE3_gt.inverse()*SE3_est;\n        typedef Eigen::Matrix<double, 6, 1> Vector6d;\n        Vector6d se3_differ = SE3_differ.log();\n        error += se3_differ.dot(se3_differ);\n        count++;\n    }\n    double RMSE = sqrt(error/count);\n    cout<<\"RMSE: \"<<RMSE<<endl;\n    DrawTrajectory(poses_gt,poses_est);\n    // DrawTrajectory(poses_est);\n    return 0;\n}", "meta": {"hexsha": "8f4379fd5de599bb110bd7e189aecef9636b25a4", "size": 3204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw3/q7.cpp", "max_stars_repo_name": "Yaozhuwa/slambook-homework", "max_stars_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T03:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T15:29:10.000Z", "max_issues_repo_path": "slamhw3/q7.cpp", "max_issues_repo_name": "Yaozhuwa/slambook-homework", "max_issues_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slamhw3/q7.cpp", "max_forks_repo_name": "Yaozhuwa/slambook-homework", "max_forks_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0309278351, "max_line_length": 86, "alphanum_fraction": 0.595505618, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6765733542126033}}
{"text": "/* Boost test/pi.cpp\r\n * test if the pi constant is correctly defined\r\n *\r\n * Copyright 2002-2003 Guillaume Melquiond, Sylvain Pion\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/test/minimal.hpp>\r\n#include \"bugs.hpp\"\r\n\r\n#define PI 3.14159265358979323846\r\n\r\ntypedef boost::numeric::interval<int>         I_i;\r\ntypedef boost::numeric::interval<float>       I_f;\r\ntypedef boost::numeric::interval<double>      I_d;\r\ntypedef boost::numeric::interval<long double> I_ld;\r\n\r\nusing boost::numeric::interval_lib::pi;\r\nusing boost::numeric::interval_lib::pi_half;\r\nusing boost::numeric::interval_lib::pi_twice;\r\n\r\nint test_main(int, char *[]) {\r\n  I_i  pi_i  = pi<I_i>();\r\n  I_f  pi_f  = pi<I_f>();\r\n  I_d  pi_d  = pi<I_d>();\r\n  I_ld pi_ld = pi<I_ld>();\r\n\r\n  BOOST_CHECK(in((int)   PI, pi_i));\r\n  BOOST_CHECK(in((float) PI, pi_f));\r\n  BOOST_CHECK(in((double)PI, pi_d));\r\n  BOOST_CHECK(subset(pi_i, widen(I_i((int)   PI), 1)));\r\n  BOOST_CHECK(subset(pi_f, widen(I_f((float) PI), (std::numeric_limits<float> ::min)())));\r\n  BOOST_CHECK(subset(pi_d, widen(I_d((double)PI), (std::numeric_limits<double>::min)())));\r\n\r\n  // We can't test the following equalities for interval<int>.\r\n  I_f pi_f_half = pi_half<I_f>();\r\n  I_f pi_f_twice = pi_twice<I_f>();\r\n\r\n  I_d pi_d_half = pi_half<I_d>();\r\n  I_d pi_d_twice = pi_twice<I_d>();\r\n\r\n  I_ld pi_ld_half = pi_half<I_ld>();\r\n  I_ld pi_ld_twice = pi_twice<I_ld>();\r\n\r\n  BOOST_CHECK(equal(2.0f * pi_f_half, pi_f));\r\n  BOOST_CHECK(equal(2.0  * pi_d_half, pi_d));\r\n  BOOST_CHECK(equal(2.0l * pi_ld_half, pi_ld));\r\n\r\n  BOOST_CHECK(equal(2.0f * pi_f, pi_f_twice));\r\n  BOOST_CHECK(equal(2.0  * pi_d, pi_d_twice));\r\n  BOOST_CHECK(equal(2.0l * pi_ld, pi_ld_twice));\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "1be62bebe93cc9fbaa3acb72a29ea964286986e8", "size": 1914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/interval/test/pi.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": 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/boost/libs/numeric/interval/test/pi.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/numeric/interval/test/pi.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": 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": 31.9, "max_line_length": 91, "alphanum_fraction": 0.6677115987, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6765733430451297}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <chrono>\n#include <Eigen/Dense>\n\nusing namespace std::chrono;\n \nusing namespace Eigen;\n \nint main()\n{\n\n  auto start = high_resolution_clock::now();\n  // C , Cn are the two price buffers used to propogate the Call value backwards in time\n  // delta, gamma and theta are intermediate differential terms\n  ArrayXd S(21), C(21), Cn(21), delta(19), gamma(19), theta(19);\n  \n  // set up spot grid\n  S(0) = 0;\n  double dx = 10;\n \n  for (size_t i = 1; i < S.size(); i++)\n  {\n    S(i) = S(i-1) + dx;\n  }\n\n  // simulation parameters\n  double K = 100;\n  double s = 0.2;\n  double r = 0.05;\n  double T = 1;\n  int nx = 20;\n  int nt = (int)(T/(0.9/std::pow(s*nx,2))) + 1;\n  double dt = T/nt;\n  \n  // Initialize C at the Maturity (boundary)\n  for (size_t i = 0; i < C.size(); i++)\n  {\n    C(i) = std::max(S(i)-K, 0.0);\n  }\n\n  // Propagate system backwards in time, \n  // apply descretized diff eqs and spatial boundary conditions\n  for (size_t i = 0; i < 10; i++)\n  {\n    delta = (0.5/dx)*(C.tail<19>() - C.head<19>());\n    gamma = (1/std::pow(dx,2))*(C.tail<19>() - 2*C.segment<19>(1) + C.head<19>());\n    theta = -(0.5*std::pow(s,2))*square(S.segment<19>(1))*gamma - r*S.segment<19>(1)*delta + r*C.segment<19>(1);\n    // Move C into Cn \n    Cn = std::move(C);\n    \n    C.segment<19>(1) = Cn.segment<19>(1) - dt*theta;\n    //spatial bc's\n    C(0) = Cn(0)*(1 - r*dt);\n    C(nx-1) = 2*C(nx-2) - C(nx-3);\n    \n  }\n  \n  // After function call\n  auto stop = high_resolution_clock::now();\n\n  auto duration = duration_cast<microseconds>(stop - start);\n  \n  std::cout << \"ran in: \" << duration.count() << \" microsecs \"<< std::endl;\n\n  std::cout << \"C: \" << C << std::endl;\n\n}", "meta": {"hexsha": "c16bc5b22a4ffb22085a505244bae6a2689c5d92", "size": 1719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2021/EigenFD/demo.cpp", "max_stars_repo_name": "kevingivens/Blog", "max_stars_repo_head_hexsha": "d9090b7b3f3ec7b4c156e72c8d033f7be79df971", "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": "2021/EigenFD/demo.cpp", "max_issues_repo_name": "kevingivens/Blog", "max_issues_repo_head_hexsha": "d9090b7b3f3ec7b4c156e72c8d033f7be79df971", "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": "2021/EigenFD/demo.cpp", "max_forks_repo_name": "kevingivens/Blog", "max_forks_repo_head_hexsha": "d9090b7b3f3ec7b4c156e72c8d033f7be79df971", "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": 24.9130434783, "max_line_length": 112, "alphanum_fraction": 0.5706806283, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6764255297048081}}
{"text": "#include <cstdio>\r\nusing namespace std;\r\n#include <armadillo>\r\n#include \"util.h\"\r\n\r\n\r\ndouble det(double* a, int n){\r\n\tint i, j, k, sign=0;\r\n\tdouble ret=1, t;\r\n    double *b = new double[n*n];\r\n\t//if (a.n!=a.m)\r\n\t//\treturn 0;\r\n\tfor (i=0; i<n; i++)\r\n\t\tfor (j=0; j<n; j++)\r\n\t\t\tb[i*n+j] = a[i*n+j];\r\n    \r\n\tfor (i=0; i<n; i++){\r\n\t\tif (zero(b[i*n+i])){\r\n\t\t\tfor (j=i+1; j<n; j++)\r\n\t\t\t\tif (!zero(b[j*n+i]))\r\n\t\t\t\t\tbreak;\r\n\t\t\t\r\n            if (j == n) {\r\n                delete[] b;\r\n\t\t\t\treturn 0;\r\n            }\r\n\t\t\t\r\n            for (k=i; k<n; k++)\r\n\t\t\t\tt = b[i*n+k], b[i*n+k]=b[j*n+k], b[j*n+k] = t;\r\n\t\t\tsign++;\r\n\t\t}\r\n        \r\n\t\tret *= b[i*n+i];\r\n\t\tfor (k=i+1; k<n; k++)\r\n\t\t\tb[i*n+k] /= b[i*n+i];\r\n\t\tfor (j=i+1; j<n; j++)\r\n\t\t\tfor (k=i+1; k<n; k++)\r\n\t\t\t\tb[j*n+k] -= b[j*n+i]*b[i*n+k];\r\n\t}\r\n    \r\n    delete[] b;\r\n    \r\n\tif (sign&1)\r\n\t\tret = -ret;\r\n\treturn ret;\r\n}\r\n\r\n\r\ndouble det_xxx(double *s, int n)\r\n{\r\n    int z, j, k;\r\n    double r, total = 0;\r\n    //int b[N][N];\r\n    double *b = new double[(n-1)*(n-1)];\r\n    if(n > 2)\r\n    {\r\n        for(z = 0; z<n; z++)\r\n        {\r\n            for(j=0; j<n-1; j++)\r\n            {\r\n                for(k=0; k<n-1; k++)\r\n                {\r\n                    if(k>=z)\r\n                        //b[j][k] = s[j+1][k+1];\r\n                        b[j*(n-1)+k] = s[(j+1)*n+(k+1)];\r\n                    else\r\n                        //b[j][k] = s[j+1][k];\r\n                        b[j*(n-1)+k] = s[(j+1)*n+k];\r\n                }\r\n            }\r\n\r\n                if(z%2 == 0)\r\n                    r = s[z] * det_xxx(b, n-1);\r\n                else\r\n                    r = (-1)*s[z]*det_xxx(b, n-1);\r\n                total = total + r;\r\n\r\n        }\r\n    }\r\n    else if(n == 2)\r\n    {\r\n        total = s[0]*s[n+1] - s[1]*s[n];\r\n    }\r\n    delete[] b;\r\n    return total;\r\n}\r\n\r\n\r\n/*\r\n * c:\u4e3ad+1\u4e2ad\u7ef4\u70b9\uff0c\r\n * d:\u7ef4\u6570\r\n * cc:\u8f93\u51fa\u5916\u5fc3\u5750\u6807\r\n */\r\nvoid circumcenter(double *c, int d, double *cc)\r\n{\r\n    //d+1\u9636\u884c\u5217\u5f0f\r\n    double *m = new double[(d+1)*(d+1)];\r\n    //\u884c\u5217\u5f0f\u7b2c\u4e00\u5217\u586b\u51451\r\n    for(int i=0; i<=d; i++)\r\n    {\r\n        m[i*(d+1)] = 1.0;\r\n    }\r\n    //\u5176\u4ed6\u586b\u5145\u8f93\u5165\u7684d+1\u4e2a\u70b9\u5750\u6807\r\n    for(int i=0; i<=d; i++)\r\n        for(int j=1; j<=d; j++)\r\n            m[i*(d+1)+j] = c[i*d+j-1];\r\n    \r\n    //\u884c\u5217\u5f0fm\u7684\u503c\r\n    //\u4f7f\u7528armadillo\u5e93\u8ba1\u7b97\u884c\u5217\u5f0f\u503c\r\n    //double D = arma::det(arma::mat(m, d+1, d+1, false));\r\n    //double D = det_xxx(m, d+1);\r\n    double D = det(m, d+1);\r\n    \r\n    // Dj[j]\u4e3a\u66ff\u6362m\u7684\u7b2cj+1\u5217\u540e\u7684\u884c\u5217\u5f0f\u7684\u503c\r\n    double *Dj = new double[d];\r\n    // \u7528\u4e8e\u66ff\u4ee3j+1\u5217\r\n    double *tt = new double[d+1];\r\n\r\n    //\u8ba1\u7b97tt\uff0c\u8be6\u60c5\u8bf7\u770b\u53c2\u8003\u6587\u732e\r\n    for(int i=0; i<=d; i++)\r\n    {\r\n        tt[i] = 0;\r\n    }\r\n\r\n    for(int i=0; i<=d; i++)\r\n    {\r\n        for(int j=0; j<d; j++)\r\n        {\r\n            tt[i] += c[i*d+j]*c[i*d+j];\r\n        }\r\n    }\r\n\r\n    for(int i=0; i<=d; i++)\r\n    {\r\n        tt[i] *= 0.5;\r\n    }\r\n\r\n    //Dj\r\n    for(int j=0; j<d; j++)\r\n    {\r\n        //\u66ff\u6362j+1\u5217\r\n        for(int i=0; i<=d; i++)\r\n        {\r\n            m[i*(d+1)+j+1] = tt[i];\r\n        }\r\n        \r\n        //\u884c\u5217\u5f0f\u503c\r\n        //\u4f7f\u7528armadillo\u5e93\u8ba1\u7b97\u884c\u5217\u5f0f\u503c\r\n        //Dj[j] = arma::det(arma::mat(m, d+1, d+1, false));\r\n        //Dj[j] = det_xxx(m, d+1);\r\n        Dj[j] = det(m, d+1);\r\n        \r\n        //\u6062\u590dj+1\u5217\r\n        for(int i=0; i<=d; i++)\r\n        {\r\n            m[i*(d+1)+j+1] = c[i*d+j];\r\n        }\r\n    }\r\n\r\n    //\u5916\u5fc3\u70b9\uff0c\u770b\u53c2\u8003\u6587\u732e\r\n    for(int j=0; j<d; j++)\r\n    {\r\n        cc[j] = Dj[j] / D;\r\n\r\n    }\r\n    delete[] m;\r\n    delete[] Dj;\r\n    delete[] tt;\r\n}\r\n\r\ndouble sq_distance(const double *pa, const double *pb, int d)\r\n{\r\n    double sq_dis = 0;\r\n    for(int i=0; i<d; i++)\r\n    {\r\n        sq_dis += (pa[i] - pb[i])*(pa[i] - pb[i]);\r\n    }\r\n    return sq_dis;\r\n}\r\n\r\nint sign(double v)\r\n{\r\n    if (v > 0) return 1;\r\n    if (v < 0) return -1;\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "d000f9dd71219018361709f1fe78c6e054277b84", "size": 3686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DelaunayVoronoi/util.cpp", "max_stars_repo_name": "wingyiu/ndelvor", "max_stars_repo_head_hexsha": "a7eeb7791b803b1c73ba2371b38648103b20232a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T01:46:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-07T01:46:05.000Z", "max_issues_repo_path": "DelaunayVoronoi/util.cpp", "max_issues_repo_name": "wingyiu/ndelvor", "max_issues_repo_head_hexsha": "a7eeb7791b803b1c73ba2371b38648103b20232a", "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": "DelaunayVoronoi/util.cpp", "max_forks_repo_name": "wingyiu/ndelvor", "max_forks_repo_head_hexsha": "a7eeb7791b803b1c73ba2371b38648103b20232a", "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": 19.5026455026, "max_line_length": 62, "alphanum_fraction": 0.3421052632, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6763973003520666}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/random_number_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include \"modprop/ModpropTypes.h\"\n\nnamespace percepto \n\n{\n\n/*! \\brief Simple multivariate normal sampling and PDF class. */\ntemplate <typename Engine = boost::mt19937, typename Scalar = double>\nclass MultivariateGaussian \n{\npublic:\n\n\ttypedef Scalar ScalarType;\n\ttypedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> VectorType;\n\ttypedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType;\n\n\ttypedef boost::normal_distribution<Scalar> UnivariateNormal;\n\ttypedef boost::variate_generator<Engine&, UnivariateNormal> RandAdapter;\n\t\n\t/*! \\brief Seeds the engine using a true random number. */\n\tMultivariateGaussian( const VectorType& u, const MatrixType& S )\n\t: _distribution( 0.0, 1.0 ), \n\t  _adapter( _generator, _distribution ),\n\t  _mean( u ), _covariance( S )\n\t{\n\t\tboost::random::random_device rng;\n\t\t_generator.seed( rng );\n\t\tInitialize();\n\t}\n    \n\t/*! \\brief Seeds the engine using a specified seed. */\n\tMultivariateGaussian( const VectorType& u, const MatrixType& S, unsigned long seed )\n\t: _distribution( 0.0, 1.0 ), \n\t  _adapter( _generator, _distribution ),\n\t  _mean( u ), _covariance( S )\n\t{\n\t\t_generator.seed( seed );\n\t\tInitialize();\n\t}\n    \n    void SetMean( const VectorType& u ) { _mean = u; }\n    void SetCovariance( const MatrixType& S )\n\t{\n\t\t_covariance = S;\n\t\tInitialize();\n\t}\n    \n\tconst VectorType& GetMean() const { return _mean; }\n\tconst MatrixType& GetCovariance() const { return _mean; }\n\tconst MatrixType& GetCholesky() const { return _L; }\n\t\n\t/*! \\brief Generate a sample truncated at a specified number of standard deviations. */\n\tVectorType Sample( double v = 3.0 )\n\t{\n\t\tVectorType samples( _mean.size() );\n\t\tfor( unsigned int i = 0; i < _mean.size(); i++ )\n\t\t{\n\t\t\tdouble s;\n\t\t\tdo\n\t\t\t{\n\t\t\t\ts = _adapter();\n\t\t\t}\n\t\t\twhile( std::abs( s ) > v );\n\t\t\tsamples(i) = s;\n\t\t}\n\t\t\n\t\treturn _mean + _L*samples;\n\t}\n\n\t/*! \\brief Evaluate the multivariate normal PDF for the specified sample. */\n    double EvaluateProbability( const VectorType& x ) const\n\t{\n\t\tVectorType diff = x - _mean;\n\t\tEigen::Matrix<Scalar, 1, 1> exponent = -0.5 * diff.dot( _LLT.solve( diff ) );\n\t\treturn _z * std::exp( exponent(0) );\n\t}\n    \nprotected:\n\t\n\tEngine _generator;\n\tUnivariateNormal _distribution;\n\tRandAdapter _adapter;\n\n\tVectorType _mean;\n\tMatrixType _covariance;\n\n\tMatrixType _L;\n\tEigen::LLT<MatrixType> _LLT;\n\n\tdouble _z; // Normali_zation constant;\n\t\n\tvoid Initialize()\n\t{\n\t\tassert( _mean.rows() == _covariance.rows() );\n\t\tassert( _mean.rows() == _covariance.cols() );\n\t\t_LLT = Eigen::LLT<MatrixType>( _covariance );\n\t\t_L = _LLT.matrixL();\n\t\t_z = std::pow( 2*M_PI, -_mean.size()/2.0 ) * std::pow( _covariance.determinant(), -0.5 );\n\t}\n\n};\n\n}\n", "meta": {"hexsha": "03ebf4aacd54a16ec5a80dd19b9082da21ac0a4c", "size": 2944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/utils/MultivariateGaussian.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/utils/MultivariateGaussian.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.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/modprop/utils/MultivariateGaussian.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.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.8245614035, "max_line_length": 91, "alphanum_fraction": 0.6891983696, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6762137862359574}}
{"text": "/**\n   Transformation between Polar-Laguerre and Hermite basis\n*/\n\n// system includes\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <boost/lexical_cast.hpp>\n#include <functional>\n#include <iostream>\n#include <vector>\n\n// own includes\n#include \"matrix/bc/impl/outflow_helper.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/nodal.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n\nusing namespace std;\n\n\nTEST(spectral, outflow)\n{\n  std::vector<int> Ks = {5, 10, 20, 30, 40, 42};\n  for(int K : Ks) {\n    Eigen::MatrixXd C(K, K);\n    double T = 1;\n\n    boltzmann::to_nodal(C, [T](double x, double y) { return std::exp(-(x * x + y * y) / 2 / T); });\n\n    double csum = C.sum();\n\n    boltzmann::QHermiteW quad(1.0, K);\n    Eigen::VectorXd hx = quad.vpts<1>();\n    Eigen::VectorXd hw = quad.vwts<1>();\n\n    boltzmann::impl::outflow_helper outflow(hw, hx);\n\n    // reference value: 2.50662827463100\n    double rho_ref = 2.50662827463100;\n    double rhop = outflow.compute(C);\n\n    EXPECT_NEAR(rhop, rho_ref, 1e-10) << \"outflow of maxwellian is wrong\";\n  }\n}\n", "meta": {"hexsha": "3356c07a7657da8fa62746d497f577a6dbbec0ca", "size": 1150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_outflow_helper.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gtest/gtest_outflow_helper.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_outflow_helper.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4680851064, "max_line_length": 99, "alphanum_fraction": 0.6773913043, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6762137828757098}}
{"text": "//\n// Created by Yohsuke Murase on 2020/06/04.\n//\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <map>\n#include <random>\n#include <cassert>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"StrategyN3M5.hpp\"\n\n// memory-1 species in strategy space discretized with `D`\n// memory-1 strategy is characterized by tuple (p_{c0}, p_{c1}, p_{c2}, p_{d0}, p_{d1}, p_{d2}),\n// where each of which denotes cooperation probability conditioned by the last Alice's action and the other players' defectors.\n// Each of which can take discrete values [0,1/D,2/D,...,D/D].\n// ID of a species is given by an integer with base-(D+1).\n// ID can take values [0, (D+1)^6-1]\n// ID=0 : AllD, ID=ID_MAX-1 : AllC\nclass Cprobs {\n public:\n  Cprobs(size_t id, size_t DIS) {\n    double dinv = 1.0 / DIS;\n    const size_t B = DIS+1;\n    c0 = (id % B) * dinv;\n    c1 = ((id/B) % B) * dinv;\n    c2 = ((id/B/B) % B) * dinv;\n    d0 = ((id/B/B/B) % B) * dinv;\n    d1 = ((id/B/B/B/B) % B) * dinv;\n    d2 = ((id/B/B/B/B/B) % B) * dinv;\n  }\n  double c0, c1, c2, d0, d1, d2;\n\n};\n\nclass Mem1Species {\n public:\n  static size_t N_M1_Species(size_t DIS) { return (DIS+1)*(DIS+1)*(DIS+1)*(DIS+1)*(DIS+1)*(DIS+1); }\n  Mem1Species(size_t _id, size_t _DIS) : id(_id), DIS(_DIS), prob(_id, _DIS) {\n    assert(id <= N_M1_Species(DIS));\n  }\n  size_t id;\n  size_t DIS;\n  Cprobs prob;\n\n  std::string ToString() const {\n    const size_t B = DIS+1;\n    size_t c0 = (id % B);\n    size_t c1 = ((id/B) % B);\n    size_t c2 = ((id/B/B) % B);\n    size_t d0 = ((id/B/B/B) % B);\n    size_t d1 = ((id/B/B/B/B) % B);\n    size_t d2 = ((id/B/B/B/B/B) % B);\n    std::ostringstream oss;\n    oss << c0 << '-' << c1 << '-' << c2 << '-' << d0 << '-' << d1 << '-' << d2 << '/' << DIS;\n    if (IsDefensible()) { oss << \"_D\"; }\n    if (IsEfficient()) { oss << \"_E\"; }\n    return oss.str();\n  }\n\n  std::vector<double> StationaryState(const Mem1Species& Bstr, const Mem1Species& Cstr, double error = 0.0) const {\n    Eigen::Matrix<double,8,8> A;\n\n    // state 0: ccc, state 1: ccd (last bit is A's history), ... 7: ddd\n    // calculate transition probability from j to i\n\n    for (size_t j = 0; j < 8; j++) {\n      Action last_a = (j & 1ul) ? D : C;\n      Action last_b = ((j>>1ul) & 1ul) ? D : C;\n      Action last_c = ((j>>2ul) & 1ul) ? D : C;\n\n      auto cooperation_prob = [](Action a, Action b, Action c, const Mem1Species& str) -> double {\n        if (a == C) {\n          if (b == C && c == C) { return str.prob.c0; }\n          else if (b == D && c == C) { return str.prob.c1; }\n          else if (b == C && c == D) { return str.prob.c1; }\n          else { return str.prob.c2; }\n        }\n        else {\n          if (b == C && c == C) { return str.prob.d0; }\n          else if (b == D && c == C) { return str.prob.d1; }\n          else if (b == C && c == D) { return str.prob.d1; }\n          else { return str.prob.d2; }\n        }\n      };\n      double c_A = cooperation_prob(last_a, last_b, last_c, *this);\n      double c_B = cooperation_prob(last_b, last_c, last_a, Bstr);\n      double c_C = cooperation_prob(last_c, last_a, last_b, Cstr);\n\n      c_A = (1.0 - error) * c_A + error * (1.0 - c_A);\n      c_B = (1.0 - error) * c_B + error * (1.0 - c_B);\n      c_C = (1.0 - error) * c_C + error * (1.0 - c_C);\n      A(0,j) = c_A * c_B * c_C;\n      A(1,j) = (1.0-c_A) * c_B * c_C;\n      A(2,j) = c_A * (1.0-c_B) * c_C;\n      A(3,j) = (1.0-c_A) * (1.0-c_B) * c_C;\n      A(4,j) = c_A * c_B * (1.0-c_C);\n      A(5,j) = (1.0-c_A) * c_B * (1.0-c_C);\n      A(6,j) = c_A * (1.0-c_B) * (1.0-c_C);\n      A(7,j) = (1.0-c_A) * (1.0-c_B) * (1.0-c_C);\n    }\n\n    for(int i=0; i<8; i++) {\n      A(i,i) -= 1.0;\n    }\n    for(int i=0; i<8; i++) {\n      A(8-1,i) += 1.0;  // normalization condition\n    }\n    Eigen::VectorXd b(8);\n    for(int i=0; i<8; i++) { b(i) = 0.0;}\n    b(8-1) = 1.0;\n    Eigen::VectorXd x = A.colPivHouseholderQr().solve(b);\n    std::vector<double> ans(8, 0.0);\n    for(int i=0; i<ans.size(); i++) {\n      ans[i] = x(i);\n    }\n\n    return ans;\n  }\n\n  double CooperationProb(StateN3M5 s) const {\n    size_t num_d = 0;\n    if (s.hb[0]) num_d++;\n    if (s.hc[0]) num_d++;\n    if (s.ha[0]) {  // A's last action is d\n      if (num_d == 2) { return prob.d2; }\n      else if (num_d == 1) { return prob.d1; }\n      else { return prob.d0; }  // num_d == 0\n    }\n    else {\n      if (num_d == 2) { return prob.c2; }\n      else if (num_d == 1) { return prob.c1; }\n      else { return prob.c0; } // num_d == 0\n    }\n  }\n\n  // returns false for mixed strategy\n  bool IsDefensible() const {\n    double tolerance = 1.0e-8;\n    if (prob.c0 > tolerance && prob.c0 < 1.0 - tolerance) { return false; }\n    if (prob.c1 > tolerance && prob.c1 < 1.0 - tolerance) { return false; }\n    if (prob.c2 > tolerance && prob.c2 < 1.0 - tolerance) { return false; }\n    if (prob.d0 > tolerance && prob.d0 < 1.0 - tolerance) { return false; }\n    if (prob.d1 > tolerance && prob.d1 < 1.0 - tolerance) { return false; }\n    if (prob.d2 > tolerance && prob.d2 < 1.0 - tolerance) { return false; }\n\n    // N = 2^{3}\n    const size_t N = 8;\n    typedef std::array<std::array<int, N>, N> d_matrix_t;\n    typedef std::bitset<3> b3_t;\n    d_matrix_t d;\n\n    // construct adjacency matrix\n    const int INF = N; // N is large enough since the path length is between -N/4 to N/4.\n    for (size_t i = 0; i < N; i++) {\n      for (size_t j = 0; j < N; j++) {\n        d[i][j] = INF;\n      }\n    }\n\n    for (size_t i = 0; i < N; i++) {\n      b3_t si(i);\n      bool a0 = si[0];\n      size_t nd0 = (si & std::bitset<3>(0b110)).count();\n      bool act_a = false;\n      if (a0) {\n        if (nd0 == 0) { act_a = (prob.d0 > 0.5 ? false : true); }\n        else if (nd0 == 1) { act_a = (prob.d1 > 0.5 ? false : true); }\n        else if (nd0 == 2) { act_a = (prob.d2 > 0.5 ? false : true); }\n        else { assert(false); }\n      }\n      else {\n        if (nd0 == 0) { act_a = (prob.c0 > 0.5 ? false : true); }\n        else if (nd0 == 1) { act_a = (prob.c1 > 0.5 ? false : true); }\n        else if (nd0 == 2) { act_a = (prob.c2 > 0.5 ? false : true); }\n        else { assert(false); }\n      }\n\n      // Get possible next states\n      std::array<b3_t,4> sjs = { 0b000, 0b010, 0b100, 0b110 };\n      for (auto sj: sjs) {\n        if (act_a) {\n          sj.set(0);\n          if(sj[1]) {  // A:D, B:D\n            d[i][sj.to_ulong()] = 0;\n          }\n          else {  // A: D, B: C\n            d[i][sj.to_ulong()] = 1;\n          }\n        }\n        else {\n          sj.reset(0);\n          if(sj[1]) {  // A:C, B:D\n            d[i][sj.to_ulong()] = -1;\n          }\n          else {  // A: C, B: C\n            d[i][sj.to_ulong()] = 0;\n          }\n        }\n      }\n      if (d[i][i] < 0) { return false; }\n    }\n\n    for (size_t k = 0; k < N; k++) {\n      for (size_t i = 0; i < N; i++) {\n        for (size_t j = 0; j < N; j++) {\n          d[i][j] = std::min(d[i][j], d[i][k] + d[k][j]);\n        }\n        if (d[i][i] < 0) { return false; }\n      }\n    }\n    return true;\n  }\n\n  bool IsEfficient() const {\n    auto ss = StationaryState(*this, *this, 0.0001);\n    return (ss[0] > 0.99);\n  }\n};\n\n\nclass Species { // either Mem1Species or StrategyN3M5\n public:\n  Species(size_t ID, size_t DIS) : m1(Mem1Species(0, DIS)), m5(std::bitset<StrategyN3M5::N>()){\n    const size_t N_M1 = Mem1Species::N_M1_Species(DIS);\n    if (ID < N_M1) {\n      is_m1 = true;\n      m1 = Mem1Species(ID, DIS);\n      m5 = StrategyN3M5(std::bitset<StrategyN3M5::N>());\n      name = m1.ToString();\n    }\n    else if (ID == N_M1) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN3M5::CAPRI3();\n      name = \"CAPRI3\";\n    }\n    else if (ID == N_M1 + 1) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN3M5::AON(3);\n      name = \"AON3\";\n    }\n    else if (ID == N_M1 + 2) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN3M5::FUSS_m3();\n      name = \"FUSS_m3\";\n    }\n    else {\n      throw std::runtime_error(\"must not happen\");\n    }\n  };\n  bool is_m1;\n  Mem1Species m1;\n  StrategyN3M5 m5;\n  std::string name;\n  std::string ToString() const { return name; }\n  std::vector<double> StationaryState(const Species &sb, const Species &sc, double error) const {\n    if (is_m1 && sb.is_m1 && sc.is_m1) {\n      return m1.StationaryState(sb.m1, sc.m1, error);\n    }\n    std::cerr << \"calculating stationary state: \" << name << ' ' << sb.name << ' ' << sc.name << std::endl;\n\n    typedef Eigen::Triplet<double> T;\n    std::vector<T> tripletVec;\n\n    for (size_t j = 0; j < StrategyN3M5::N; j++) {\n      // calculate transition probability from j to i\n      const StateN3M5 sj(j);\n      double c_a = _CooperationProb(sj);\n      double c_b = sb._CooperationProb(sj.StateFromB());\n      double c_c = sc._CooperationProb(sj.StateFromC());\n      // cooperation probability taking noise into account\n      c_a = (1.0 - error) * c_a + error * (1.0 - c_a);\n      c_b = (1.0 - error) * c_b + error * (1.0 - c_b);\n      c_c = (1.0 - error) * c_c + error * (1.0 - c_c);\n\n      for (size_t t = 0; t < 8; t++) {\n        Action act_a = (t & 1ul) ? D : C;\n        Action act_b = (t & 2ul) ? D : C;\n        Action act_c = (t & 4ul) ? D : C;\n        size_t i = sj.NextState(act_a, act_b, act_c).ID();\n        double p_a = (act_a == C) ? c_a : (1.0-c_a);\n        double p_b = (act_b == C) ? c_b : (1.0-c_b);\n        double p_c = (act_c == C) ? c_c : (1.0-c_c);\n        tripletVec.emplace_back(i, j, p_a * p_b * p_c);\n      }\n    }\n\n    const size_t S = StrategyN3M5::N;\n    Eigen::SparseMatrix<double> A(S, S);\n    A.setFromTriplets(tripletVec.cbegin(), tripletVec.cend());\n\n    // subtract unit matrix & normalization condition\n    std::vector<T> iVec;\n    for (int i = 0; i < S-1; i++) { iVec.emplace_back(i, i, -1.0); }\n    for (int i = 0; i < S-1; i++) { iVec.emplace_back(S-1, i, 1.0); }\n    Eigen::SparseMatrix<double> I(S, S);\n    I.setFromTriplets(iVec.cbegin(), iVec.cend());\n    A = A + I;\n    // std::cerr << \"  transition matrix has been created\" << std::endl;\n\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(S);\n    b(S-1) = 1.0;\n\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IncompleteLUT<double> > solver;\n    solver.compute(A);\n    Eigen::VectorXd x = solver.solve(b);\n\n    // std::cerr << \"#iterations:     \" << solver.iterations() << std::endl;\n    // std::cerr << \"estimated error: \" << solver.error() << std::endl;\n\n    std::vector<double> ans(S, 0.0);\n    for (int i = 0; i < S; i++) { ans[i] = x[i]; }\n    return ans;\n  }\n private:\n  double _CooperationProb(const StateN3M5 &s) const {\n    if (is_m1) { return m1.CooperationProb(s); }\n    else { return m5.ActionAt(s) == C ? 1.0 : 0.0; }\n  }\n\n public:\n  static std::vector<Species> Memory1Species(size_t discrete_level) {\n    std::vector<Species> ans;\n    size_t n = Mem1Species::N_M1_Species(discrete_level);\n    for (size_t i = 0; i < n; i++) {\n      ans.emplace_back(i, discrete_level);\n    }\n    return std::move(ans);\n  }\n  static std::vector<Species> ReactiveMem1Species(size_t discrete_level) {\n    std::vector<Species> ans;\n    size_t B = discrete_level + 1;\n    size_t n = Mem1Species::N_M1_Species(discrete_level);\n    size_t B3 = B * B * B;\n    for (size_t i = 0; i < n/B3; i++) {\n      size_t id = i * B3 + i;\n      ans.emplace_back(id, discrete_level);\n    }\n    return std::move(ans);\n  }\n};\n\n\nclass Ecosystem {\n public:\n  // Ecosystem(size_t discrete_level, bool with_capri) : DIS(discrete_level) {\n  //   N_M1 = Mem1Species::N_M1_Species(DIS);\n  //   if (with_capri) { N_SPECIES = N_M1 + 3; } // we add these three species CAPRI3, AON5, FUSS\n  //   else { N_SPECIES = N_M1; }\n  // };\n  Ecosystem(const std::vector<Species> &species_pool, double error) :pool(species_pool), N_SPECIES(species_pool.size()), e(error) {\n    CalculateSSCache();\n  };\n  size_t N_SPECIES;\n  std::vector<Species> pool;\n  const double e;\n  typedef std::vector<double> ss_cache_t;\n  std::vector<std::vector<ss_cache_t> > ss_cache;\n  // ss_cache[i][i] stores the stationary state when PG game is played by (i,i,i)\n  // ss_cache[i][j] stores the stationary state when PG game is played by (i,i,j)\n\n  void CalculateSSCache() {\n    ss_cache.resize(N_SPECIES);\n    for (size_t i = 0; i < N_SPECIES; i++) {\n      ss_cache[i].resize(N_SPECIES);\n    }\n\n#pragma omp parallel for schedule(dynamic,1)\n    for (size_t I=0; I < N_SPECIES * N_SPECIES; I++) {\n      size_t i = I / N_SPECIES;\n      size_t j = I % N_SPECIES;\n      ss_cache[i][j] = pool[i].StationaryState(pool[i], pool[j], e);\n    }\n  }\n\n  // payoff of species i and j when the game is played by (i,i,j)\n  std::array<double,2> PayoffVersus(size_t i, size_t j, double benefit, double cost) const {\n    std::array<double, 3> ans = Payoffs(ss_cache[i][j], benefit, cost);\n    assert( std::abs(ans[0] - ans[1]) < 0.00001 );\n    return {ans[0], ans[2]};\n  }\n\n  std::array<double,3> Payoffs(const ss_cache_t &ss, double benefit, double cost) const {\n    std::array<double, 3> ans = {0.0, 0.0, 0.0};\n    if (ss.size() == 8) {\n      for (size_t i = 0; i < 8; i++) {\n        double pa = 0.0, pb = 0.0, pc = 0.0;\n        if ((i & 1ul) == 0) {\n          pa -= cost;\n          pb += benefit / 2.0;\n          pc += benefit / 2.0;\n        }\n        if ((i & 2ul) == 0) {\n          pb -= cost;\n          pc += benefit / 2.0;\n          pa += benefit / 2.0;\n        }\n        if ((i & 4ul) == 0) {\n          pc -= cost;\n          pa += benefit / 2.0;\n          pb += benefit / 2.0;\n        }\n        ans[0] += ss[i] * pa;\n        ans[1] += ss[i] * pb;\n        ans[2] += ss[i] * pc;\n      }\n    }\n    else {\n      assert(ss.size() == StrategyN3M5::N);\n      for (size_t i = 0; i < StrategyN3M5::N; i++) {\n        StateN3M5 s(i);\n        double pa = 0.0, pb = 0.0, pc = 0.0;\n        if (!s.ha[0]) {\n          pa -= cost;\n          pb += benefit / 2.0;\n          pc += benefit / 2.0;\n        }\n        if (!s.hb[0]) {\n          pb -= cost;\n          pc += benefit / 2.0;\n          pa += benefit / 2.0;\n        }\n        if (!s.hc[0]) {\n          pc -= cost;\n          pa += benefit / 2.0;\n          pb += benefit / 2.0;\n        }\n        ans[0] += ss[i] * pa;\n        ans[1] += ss[i] * pb;\n        ans[2] += ss[i] * pc;\n      }\n    }\n    return ans;\n  }\n\n  // calculate the equilibrium distribution exactly by linear algebra\n  std::vector<double> CalculateEquilibrium(double benefit, double cost, uint64_t N, double sigma) const {\n    Eigen::MatrixXd A(N_SPECIES, N_SPECIES);\n    #pragma omp parallel for\n    for (size_t ii = 0; ii < N_SPECIES * N_SPECIES; ii++) {\n      size_t i = ii / N_SPECIES;\n      size_t j = ii % N_SPECIES;\n      if (i == j) { A(i, j) = 0.0; continue; }\n      double p = FixationProb(benefit, cost, N, sigma, i, j);\n      // std::cerr << \"Fixation prob of mutant (mutant,resident): \" << p << \" (\" << pool[i].ToString() << \", \" << pool[j].ToString() << \")\" << std::endl;\n      A(i, j) = p * (1.0 / N_SPECIES);\n    }\n\n    for (size_t j = 0; j < N_SPECIES; j++) {\n      double p_sum = 0.0;\n      for (size_t i = 0; i < N_SPECIES; i++) {\n        p_sum += A(i, j);\n      }\n      assert(p_sum <= 1.0);\n      A(j, j) = 1.0 - p_sum; // probability that the state doesn't change\n    }\n\n    size_t n_row = A.rows();\n\n    // subtract Ax = x => (A-I)x = 0\n    for (size_t i = 0; i < A.rows(); i++) {\n      A(i, i) -= 1.0;\n    }\n    // normalization condition\n    for (size_t i = 0; i < A.rows(); i++) {\n      A(A.rows()-1, i) += 1.0;\n    }\n\n    Eigen::VectorXd b(A.rows());\n    for(int i=0; i<A.rows()-1; i++) { b(i) = 0.0;}\n    b(A.rows()-1) = 1.0;\n    Eigen::VectorXd x = A.householderQr().solve(b);\n    std::vector<double> ans(A.rows());\n    double prob_total = 0.0;\n    for(int i=0; i<ans.size(); i++) {\n      ans[i] = x(i);\n      prob_total += x(i);\n      assert(x(i) > -0.000001);\n    }\n    assert(std::abs(prob_total - 1.0) < 0.00001);\n    return ans;\n  }\n\n  double FixationProb(double benefit, double cost, uint64_t N, double sigma, size_t mutant_idx, size_t resident_idx) const {\n    // rho_inv = \\sum_{i=0}^{N-1} exp(sigma[S]),\n    // where S is defined as\n    // S =  i/6(i^2\u22123iN+6i+3N^2\u221212N+11)s_{yyy}\n    //     \u2212i/6(i+1)(2i\u22123N+4)s_{yyx}\n    //     +i/6(i\u22121)(i+1)s_{yxx}\n    //     \u2212i/6(i^2\u22123i(N\u22121)+3N^2\u22126N+2)s_{xyy}\n    //     +i/6(i\u22121)(2i\u22123N+2))s_{xxy}\n    //     \u2212i/6(i^2\u22123i+2)s_{xxx}\n    // std::cerr << \"caclulating fixation prob for mutant \" << pool[mutant_idx].ToString() << \" against resident \" << pool[resident_idx].ToString() << std::endl;\n\n    double s_xxx = PayoffVersus(mutant_idx, mutant_idx, benefit, cost)[0];\n    double s_yyy = PayoffVersus(resident_idx, resident_idx, benefit, cost)[0];\n    auto xxy = PayoffVersus(mutant_idx, resident_idx, benefit, cost);\n    double s_xxy = xxy[0];\n    double s_yxx = xxy[1];\n    auto yyx = PayoffVersus(resident_idx, mutant_idx, benefit, cost);\n    double s_yyx = yyx[0];\n    double s_xyy = yyx[1];\n\n    // std::cerr << \"s_xxx: \" << s_xxx << \", s_xxy: \" << s_xxy << \", s_xyy: \" << s_xyy << std::endl;\n    // std::cerr << \"s_yyy: \" << s_yyy << \", s_yxx: \" << s_yxx << \", s_yyx: \" << s_yyx << std::endl;\n\n    double num_games = (N-1) * (N-2) / 2.0;\n    double rho_inv = 0.0;\n    for (int i=0; i < N; i++) {\n      double x = sigma / num_games * (i / 6.0) * (\n          (i*i - 3.0*i*N + 6.0*i + 3.0*N*N - 12.0*N + 11.0) * s_yyy\n          - (i+1.0) * (2.0*i - 3.0*N + 4) * s_yyx\n          + (i-1.0) * (i+1.0) * s_yxx\n          - (i*i - 3.0*i*(N-1.0) + 3.0*N*N - 6.0*N + 2.0) * s_xyy\n          + (i-1.0) * (2.0*i-3.0*N+2.0) * s_xxy\n          - (i*i - 3.0*i + 2.0) * s_xxx\n      );\n      rho_inv += std::exp(x);\n    }\n    return 1.0 / rho_inv;\n  }\n\n  void PrintAbundance(const std::vector<double> &eq_rate, const std::string &fname) const {\n    assert(eq_rate.size() == N_SPECIES);\n    typedef std::pair<size_t, double> SS;\n    auto compare_by_val = [](const SS &a, const SS &b) { return (a.second < b.second); };\n    std::multiset<SS, decltype(compare_by_val)> sorted_histo(compare_by_val);\n    for (size_t i = 0; i < eq_rate.size(); i++) {\n      sorted_histo.insert( std::make_pair(i, eq_rate[i]) );\n    }\n    std::ofstream fout(fname);\n    for (auto it = sorted_histo.rbegin(); it != sorted_histo.rend(); it++) {\n      fout << pool[it->first].ToString() << ' ' << it->second << std::endl;\n    }\n    fout.close();\n  }\n  std::vector<std::string> SpeciesNames() const {\n    std::vector<std::string> ans;\n    for(auto s: pool) {\n      ans.emplace_back( s.ToString() );\n    }\n    return std::move(ans);\n  }\n  double CooperationLevelSpecies(size_t i) const {\n    const ss_cache_t &ss = ss_cache[i][i];\n    if (ss.size() == 8) {\n      double level = 0.0;\n      for (size_t s = 0; s < 8; s++) {\n        size_t num_c = 3 - std::bitset<3>(s).count();\n        level += ss[s] * (num_c / 3.0);\n      };\n      return level;\n    }\n    else {\n      double level = 0.0;\n      for (size_t s = 0; s < StrategyN3M5::N; s++) {\n        StateN3M5 state(s);\n        size_t num_c = 3ul;\n        if (state.ha[0]) num_c -= 1;\n        if (state.hb[0]) num_c -= 1;\n        if (state.hc[0]) num_c -= 1;\n        level += ss[s] * (num_c / 3.0);\n      }\n      return level;\n    }\n  }\n  double CooperationLevel(const std::vector<double> &eq_rate) const {\n    assert(eq_rate.size() == N_SPECIES);\n    double ans = 0.0;\n    for (size_t i = 0; i < N_SPECIES; i++) {\n      double c_lev = CooperationLevelSpecies(i);\n      ans += eq_rate[i] * c_lev;\n    }\n    return ans;\n  }\n};\n\n\nint main(int argc, char *argv[]) {\n  Eigen::initParallel();\n  if( argc != 9 ) {\n    std::cerr << \"Error : invalid argument\" << std::endl;\n    std::cerr << \"  Usage : \" << argv[0] << \" <Nmax> <sigma> <error rate> <discrete_level> <0:reactive/1:full memory1> <1:capri3> <1:aon3> <1:fussm3>\" << std::endl;\n    return 1;\n  }\n\n  double cost = 1.0;\n  uint64_t Nmax = std::strtoull(argv[1], nullptr,0);\n  double sigma = std::strtod(argv[2], nullptr);\n  double e = std::strtod(argv[3], nullptr);\n  uint64_t discrete_level = std::strtoull(argv[4], nullptr,0);\n\n  unsigned long full_or_reactive = std::strtoul(argv[5], nullptr, 0);\n  unsigned long add_capri3 = std::strtoul(argv[6], nullptr, 0);\n  unsigned long add_aon3 = std::strtoul(argv[7], nullptr, 0);\n  unsigned long add_fussm3 = std::strtoul(argv[8], nullptr, 0);\n\n  std::vector<Species> pool = (full_or_reactive == 1 ? Species::Memory1Species(discrete_level) : Species::ReactiveMem1Species(discrete_level));\n  size_t N_M1 = Mem1Species::N_M1_Species(discrete_level);\n  if (add_capri3 == 1) {\n    pool.emplace_back(N_M1, discrete_level);\n  }\n  if (add_aon3) {\n    pool.emplace_back(N_M1+1, discrete_level);\n  }\n  if (add_fussm3) {\n    pool.emplace_back(N_M1+2, discrete_level);\n  }\n  Ecosystem eco(pool, e);\n\n  {\n    std::ofstream namout(\"species.txt\");\n    for(auto name: eco.SpeciesNames()) {\n      namout << name << std::endl;\n    }\n    namout << std::endl;\n  }\n\n  auto SweepOverBeta = [&eco,cost,sigma](size_t N)->std::vector<std::pair<double,double>> {\n    char fname1[100];\n    sprintf(fname1, \"abundance_%zu.dat\", N);\n    std::ofstream eqout(fname1);\n    std::vector<std::pair<double,double>> c_levels;\n    for (int i = 5; i <= 300; i+=5) {\n      double benefit = 1.0 + i / 100.0;\n      auto eq = eco.CalculateEquilibrium(benefit, cost, N, sigma);\n      eqout << benefit << ' ';\n      for (double x: eq) { eqout << x << ' '; }\n      eqout << std::endl;\n      double c_lev = eco.CooperationLevel(eq);\n      c_levels.push_back(std::make_pair(benefit, c_lev));\n    }\n    return c_levels;\n  };\n\n  std::vector<std::vector<std::pair<double,double>>> ans;\n  for (int N = 3; N <= Nmax; N++) {\n    auto a = SweepOverBeta(N);\n    ans.push_back(a);\n  }\n\n  std::ofstream fout(\"cooperation_level.dat\");\n  for (size_t i = 0; i < ans[0].size(); i++) {\n    fout << ans[0][i].first;\n    for (size_t j = 0; j < ans.size(); j++) {\n      fout << ' ' << ans[j][i].second;\n    }\n    fout << \"\\n\";\n  }\n  fout.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "7c3e1134ae055cdee9718139228d6f26dcd2375c", "size": 21796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main_evo_n3.cpp", "max_stars_repo_name": "yohm/sim_CAPRI_nplayers", "max_stars_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "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": "cpp/main_evo_n3.cpp", "max_issues_repo_name": "yohm/sim_CAPRI_nplayers", "max_issues_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "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": "cpp/main_evo_n3.cpp", "max_forks_repo_name": "yohm/sim_CAPRI_nplayers", "max_forks_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "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.0743550835, "max_line_length": 164, "alphanum_fraction": 0.5325289044, "num_tokens": 7638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6762137758842205}}
{"text": "/**\n * @file LinearAlgebra.hpp\n * @author bwu\n * @brief Model of vector and matrix concept in static dimension size, implement based on boost ublas\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_MATH_LINEARALGEBRA_HPP\n#define GENERIC_MATH_LINEARALGEBRA_HPP\n#include \"generic/common/Traits.hpp\"\n#include \"generic/common/Version.hpp\"\n#include \"MathUtility.hpp\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/hermitian.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <initializer_list>\n#include <cmath>\nnamespace generic{\nnamespace math{\n///@brief linear algebra related classes and functions\nnamespace la {\nusing namespace generic::common;\nusing namespace generic::math;\nusing namespace boost::numeric;\n\n///@brief constructs an unbounded array from initializer list\ntemplate <typename num_type>\ninline ublas::unbounded_array<num_type> makeUbArray(std::initializer_list<num_type> l) {\n    ublas::unbounded_array<num_type> res(l.size());\n    for(size_t i = 0; i < l.size(); ++i)\n        res[i] = *(l.begin() + i);\n    return res;\n}\n\n///@brief constructs an unbounded array from collection begin/end iterator\ntemplate <typename num_type, typename iterator>\ninline ublas::unbounded_array<num_type> makeUbArray(iterator begin, iterator end) {\n    size_t size = std::distance(begin, end);\n    ublas::unbounded_array<num_type> res(size);\n    for(size_t i = 0; i < size; ++i)\n        res[i] = *(begin + i);\n    return res;\n}\n\ntemplate <typename num_type, size_t M, size_t N> class Matrix;\ntemplate <typename num_type, size_t N>\nclass Vector\n{\npublic:\n    using data_type = ublas::vector<num_type>;\n    Vector() : m_data(N) { std::fill(m_data.begin(), m_data.end(), 0); }\n    Vector(num_type s) : m_data(N) { std::fill(m_data.begin(), m_data.end(), s); }\n    Vector(data_type data) : m_data(data) { m_data.resize(N, true); }\n    Vector(std::initializer_list<num_type> l) : m_data(makeUbArray(l)) { m_data.resize(N, true); }\n\n    template <typename... Args>\n    Vector(num_type first, num_type second, Args... args) : m_data(N) { Set(first, second, args...); }\n\n    bool operator== (const Vector<num_type, N> & v) { return  Same(*this, v); }\n    bool operator!= (const Vector<num_type, N> & v) { return !Same(*this, v); }\n\n    num_type & operator() (size_t dim) { return m_data(dim); }\n    const num_type & operator() (size_t dim) const { return m_data(dim); }\n\n    num_type & operator[] (size_t dim) { return m_data(dim); }\n    const num_type & operator[] (size_t dim) const { return m_data(dim); }\n\n    Vector operator+ (const Vector<num_type, N> & v) const;\n    Vector operator- () const;\n    Vector operator- (const Vector<num_type, N> & v) const;\n    Vector operator* (float_type<num_type> scale) const;\n    Vector operator/ (float_type<num_type> scale) const;   \n    Vector operator* (const Matrix<num_type, N, N> & m) const; \n\n    Vector & operator += (const Vector<num_type, N> & v);\n    Vector & operator -= (const Vector<num_type, N> & v);\n    Vector & operator *= (float_type<num_type> scale);\n    Vector & operator /= (float_type<num_type> scale);\n\n    void Swap(Vector<num_type, N> & v) { m_data.swap(v.Data()); }\n    Matrix<num_type, N, 1> T() const;\n    num_type Norm1() const;\n    float_type<num_type> Norm2() const;\n    num_type NormSquare() const;\n\n    data_type & Data() { return m_data; }\n    const data_type & Data() const { return m_data; }\n\n    template <typename... Args>\n    void Set(Args... args);\n\n    static bool Same(const Vector<num_type, N> & v1, const Vector<num_type, N> & v2);\nprivate:\n    data_type m_data;\n};\n\nstruct matrix_general_tag {};\nstruct matrix_identity_tag {};\nstruct matrix_diagonal_tag {};\nstruct matrix_upper_triangle_tag {};\nstruct matrix_lower_triangle_tag {};\nstruct matrix_symmetric_tag {};\nstruct matrix_hermitian_tag {};\nstruct matrix_transform2d_tag {};\nstruct matrix_transform3d_tag {};\nstruct matrix_unknown_tag {};\n\ntemplate <typename num_type, size_t M = 1, size_t N = 1>\nclass Matrix\n{\npublic:\n    using data_type = ublas::matrix<num_type>;\n    Matrix();\n\n    Matrix(num_type s);\n\n    template<typename matrix_tag, \n             typename std::enable_if<\n                      std::is_same<matrix_tag, matrix_diagonal_tag>::value  && M == N, bool>::type = true>\n    Matrix(num_type s, matrix_tag);\n\n    Matrix(data_type data) { data.resize(M, N, true); m_data = data; }\n\n    Matrix(const std::initializer_list<std::initializer_list<num_type> > & ll)\n    {\n        m_data.resize(M, N);\n        auto iter1 = ll.begin();\n        for(size_t i = 0; i < M && iter1 != ll.end(); ++i, ++iter1){\n            const std::initializer_list<num_type> & l = *iter1;\n            auto iter2 = l.begin();\n            for(size_t j = 0; j < N && iter2 != l.end(); ++j, ++iter2)\n                m_data(i, j) = *iter2;\n        }\n    }\n\n    template <typename... Args>\n    Matrix(Vector<num_type, N> first, Vector<num_type, N> second, Args... args);\n\n    bool operator== (const Matrix<num_type, M, N> & m) { return  Same(*this, m); }\n    bool operator!= (const Matrix<num_type, M, N> & m) { return !Same(*this, m); }\n\n    num_type & operator() (size_t row, size_t col);\n    const num_type & operator() (size_t row, size_t col) const;\n\n    Matrix operator+ (const Matrix<num_type, M, N> & m) const;\n    Matrix operator- () const;\n    Matrix operator- (const Matrix<num_type, M, N> & m) const;\n    Matrix operator* (float_type<num_type> scale) const;\n    Matrix operator/ (float_type<num_type> scale) const;\n    \n    Vector<num_type, N> operator* (const Vector<num_type, N> & v) const;\n\n    template <size_t O>\n    Matrix<num_type, M, O> operator* (const Matrix<num_type, N, O> & m) const;\n\n    Matrix & operator+= (const Matrix<num_type, M, N> & m);\n    Matrix & operator-= (const Matrix<num_type, M, N> & m);\n    Matrix & operator*= (float_type<num_type> scale);\n    Matrix & operator/= (float_type<num_type> scale);\n    Matrix & operator*= (const Matrix<num_type, N, N> & m);\n\n    Vector<num_type, N> Row(size_t row) const;\n    Vector<num_type, M> Col(size_t col) const;\n\n    void Swap(Matrix<num_type, M, N> & m) { m_data.swap(m.Data()); }\n    Matrix<num_type, N, M> T() const;\n    float_type<num_type> Norm2() const { return std::sqrt(NormSquare()); }\n    num_type NormSquare() const;\n\n    data_type & Data() { return m_data; }\n    const data_type & Data() const { return m_data; }\n\n    template <typename... Args>\n    void Set(Args... args);\n\n    static bool Same(const Matrix<num_type, M, N> & m1, const Matrix<num_type, M, N> & m2);\nprivate:\n    data_type m_data;\n};\n\ntemplate <typename num_type, size_t I, size_t N>\nstruct VectorSetter\n{\n    template <typename... Args>\n    static void Set(Vector<num_type, N> & v, num_type s, Args... args)\n    {\n        v[I] = s;\n        VectorSetter<num_type, I + 1, N>::Set(v, args...);\n    }\n};\n\ntemplate <typename num_type, size_t N>\nstruct VectorSetter<num_type, N, N>\n{\n    static void Set(Vector<num_type, N> &) {}\n};\n\n#if GENERIC_CURRENT_BOOST_LIBRARY_VER >= 172\ntemplate <typename num_type, size_t N>\ninline num_type Vector<num_type, N>::Norm1() const\n{\n    return norm_1(m_data);\n}\n\ntemplate <typename num_type, size_t N>\ninline float_type<num_type> Vector<num_type, N>::Norm2() const\n{\n    return norm_2(m_data);\n}\n\ntemplate <typename num_type, size_t N>\ninline num_type Vector<num_type, N>::NormSquare() const\n{\n    return norm_2_square(m_data);\n}\n#else\ntemplate <typename num_type, size_t N>\ninline num_type Vector<num_type, N>::Norm1() const\n{\n    num_type norm1(0);\n    for(size_t i = 0; i < N; ++i)\n        norm1 += std::abs(m_data[i]);\n    return norm1;\n}\n\ntemplate <typename num_type, size_t N>\ninline float_type<num_type> Vector<num_type, N>::Norm2() const\n{\n    return std::sqrt(float_type<num_type>(NormSquare()));\n}\n\ntemplate <typename num_type, size_t N>\ninline num_type Vector<num_type, N>::NormSquare() const\n{\n    num_type normSquare(0);\n    for(size_t i = 0; i < N; ++i)\n        normSquare += m_data[i] * m_data[i];\n    return normSquare;\n}\n#endif\n\ntemplate <typename num_type, size_t N>\ntemplate <typename... Args>\ninline void Vector<num_type, N>::Set(Args... args)\n{\n    VectorSetter<num_type, 0, N>::Set(*this, num_type(args)...);\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator+ (const Vector<num_type, N> & v) const\n{\n    return Vector<num_type, N>(m_data + v.Data());\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator- () const\n{\n    return Vector<num_type, N>(0) - *this;\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator- (const Vector<num_type, N> & v) const\n{\n    return Vector<num_type, N>(m_data - v.Data());\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator* (float_type<num_type> scale) const\n{\n    return Vector<num_type, N>(m_data * scale);\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator/ (float_type<num_type> scale) const\n{\n    return Vector<num_type, N>(m_data / scale);\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> Vector<num_type, N>::operator* (const Matrix<num_type, N, N> & m) const\n{\n    return Vector<num_type, N>(prod(m_data, m.Data()));\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> & Vector<num_type, N>::operator += (const Vector<num_type, N> & v)\n{\n    m_data += v.Data();\n    return *this;\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> & Vector<num_type, N>::operator -= (const Vector<num_type, N> & v)\n{\n    m_data -= v.Data();\n    return *this;\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> & Vector<num_type, N>::operator *= (float_type<num_type> scale)\n{\n    m_data *= scale;\n    return *this;\n}\n\ntemplate <typename num_type, size_t N>\ninline Vector<num_type, N> & Vector<num_type, N>::operator /= (float_type<num_type> scale)\n{\n    m_data /= scale;\n    return *this;\n}\n\ntemplate <typename num_type, size_t N>\ninline Matrix<num_type, N, 1> Vector<num_type, N>::T() const\n{\n    Matrix<num_type, N, 1> m;\n    for(size_t i = 0; i < N; ++i)\n        m(i, 0) = m_data(i);\n    return m;\n}\n\ntemplate <typename num_type, size_t N>\ninline bool Vector<num_type, N>::Same(const Vector<num_type, N> & v1, const Vector<num_type, N> & v2)\n{\n    return math::EQ((v1 - v2).NormSquare(), num_type(0));\n}\n\ntemplate <typename num_type, size_t I, size_t M, size_t N>\nstruct MatrixSetter\n{\n    template <typename... Args>\n    static void Set(Matrix<num_type, M, N> & m, Vector<num_type, N> v, Args... args)\n    {\n        for(size_t j = 0; j < N; ++j)\n            m(I, j) = v[j];\n        MatrixSetter<num_type, I + 1, M, N>::Set(m, args...);\n    }\n};\n\ntemplate <typename num_type, size_t M, size_t N>\nstruct MatrixSetter<num_type, M, M, N>\n{\n    static void Set(Matrix<num_type, M, N> &) {}\n};\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N>::Matrix() : m_data(M, N)\n{\n    for(size_t i = 0; i < M; ++i)\n        for(size_t j = 0; j < N; ++j)\n            m_data(i, j) = 0;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N>::Matrix(num_type s) : Matrix()\n{\n    for(size_t i = 0; i < M; ++i)\n        for(size_t j = 0; j < N; ++j)\n            m_data(i, j) = s;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ntemplate <typename matrix_tag, \n          typename std::enable_if<\n                   std::is_same<matrix_tag, matrix_diagonal_tag>::value && M == N, bool>::type>\ninline Matrix<num_type, M, N>::Matrix(num_type s, matrix_tag) : Matrix()\n{\n    for(size_t i = 0; i < M; ++i)\n        m_data(i, i) = s;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ntemplate <typename... Args>\ninline Matrix<num_type, M, N>::Matrix(Vector<num_type, N> first, Vector<num_type, N> second, Args... args)\n : m_data(M, N)\n{\n    Set(first, second, args...);\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline num_type & Matrix<num_type, M, N>::operator() (size_t row, size_t col) { return m_data(row, col); }\n\ntemplate <typename num_type, size_t M, size_t N>\ninline const num_type & Matrix<num_type, M, N>::operator() (size_t row, size_t col) const { return m_data(row, col); }\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> Matrix<num_type, M, N>::operator+ (const Matrix<num_type, M, N> & m) const\n{\n    return Matrix<num_type, M, N>(m_data + m.Data());\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> Matrix<num_type, M, N>::operator- () const\n{\n    return Matrix<num_type, M, N>(0) - *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> Matrix<num_type, M, N>::operator- (const Matrix<num_type, M, N> & m) const\n{\n    return Matrix<num_type, M, N>(m_data - m.Data());\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> Matrix<num_type, M, N>::operator* (float_type<num_type> scale) const\n{\n    return Matrix<num_type, M, N>(m_data * scale);\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> Matrix<num_type, M, N>::operator/ (float_type<num_type> scale) const\n{\n    return Matrix<num_type, M, N>(m_data / scale);\n}\ntemplate <typename num_type, size_t M, size_t N>\ninline Vector<num_type, N> Matrix<num_type, M, N>:: operator* (const Vector<num_type, N> & v) const\n{\n    return Vector<num_type, N>(prod(m_data, v.Data()));\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ntemplate <size_t O>\ninline Matrix<num_type, M, O> Matrix<num_type, M, N>::operator* (const Matrix<num_type, N, O> & m) const\n{\n    return Matrix<num_type, M, O>(prod(m_data, m.Data()));\n}  \n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> & Matrix<num_type, M, N>::operator += (const Matrix<num_type, M, N> & m)\n{\n    m_data += m.Data();\n    return *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> & Matrix<num_type, M, N>::operator -= (const Matrix<num_type, M, N> & m)\n{\n    m_data -= m.Data();\n    return *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> & Matrix<num_type, M, N>::operator *= (float_type<num_type> scale)\n{\n    m_data *= scale;\n    return *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> & Matrix<num_type, M, N>::operator /= (float_type<num_type> scale)\n{\n    m_data /= scale;\n    return *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Matrix<num_type, M, N> & Matrix<num_type, M, N>::operator *= (const Matrix<num_type, N, N> & m)\n{\n    m_data = prod(m_data, m.Data());\n    return *this;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Vector<num_type, N> Matrix<num_type, M, N>::Row(size_t row) const\n{\n    Vector<num_type, N> v;\n    for(size_t i = 0; i < N; ++i)\n        v[i] = m_data(row, i);\n    return v;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline Vector<num_type, M> Matrix<num_type, M, N>::Col(size_t col) const\n{\n    Vector<num_type, M> v;\n    for(size_t j = 0; j < M; ++j)\n        v[j] = m_data(j, col);\n    return v;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\nMatrix<num_type, N, M> Matrix<num_type, M, N>::T() const\n{\n    Matrix<num_type, N, M> mT;\n    for(size_t i = 0; i < M; ++i)\n        for(size_t j = 0; j < N; ++j)\n            mT(j, i) = m_data(i, j);\n    return mT;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ntemplate <typename... Args>\ninline void Matrix<num_type, M, N>::Set(Args... args)\n{\n    MatrixSetter<num_type, 0, M, N>::Set(*this, Vector<num_type, N>(args)...);\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline num_type Matrix<num_type, M, N>::NormSquare() const\n{\n    num_type res(0);\n    for(size_t i = 0; i < M; ++i)\n        for(size_t j = 0; j < N; ++j)\n            res += m_data(i, j) * m_data(i, j);\n    return res;\n}\n\ntemplate <typename num_type, size_t M, size_t N>\ninline bool Matrix<num_type, M, N>::Same(const Matrix<num_type, M, N> & m1, const Matrix<num_type, M, N> & m2)\n{\n    return math::EQ((m1 - m2).NormSquare(), num_type(0));\n}\n}//namespace la\n}//namespace math\n}//namespace generic\n#endif//GENERIC_MATH_LINEARALGEBRA_HPP", "meta": {"hexsha": "41a745117c4d54871c13f50e12c863ce55c99e05", "size": 16336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/LinearAlgebra.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "math/LinearAlgebra.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "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": "math/LinearAlgebra.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "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.4759152216, "max_line_length": 118, "alphanum_fraction": 0.6579333986, "num_tokens": 4712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6761988645170054}}
{"text": "#include \"polynomial.h\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <cmath>\n#include <stack>\n#include <array>\n#include <complex>\n\nusing namespace polynomial;\n\nPolynomial::Polynomial(const std::vector<double>& nums) {\n    /* Instantiate a polynomial from a list of coefficients in increasing order. You must include all terms, including\n     * a constant term at the beginning and terms with a 0 coefficient EX: x^2 = {0, 0, 1}\n     */\n\n    degree = nums.size() - 1; // subtract one because the polynomial vector also includes a constant term\n    coefs = nums;\n    // remove extra terms at the front if the coeficient is 0 to ensure stability with rest of the code\n    while (coefs.back() == 0 && degree > 0){\n        coefs.pop_back();\n        degree -= 1;\n    }\n}\n\nPolynomial::Polynomial(const std::vector<double>& x, const std::vector<double>& y, const int& order){\n    /* Fit an n-th degree polynomial of y as a function of x using least squares regression. Order is the degree\n     * of the resulting polynomial\n     */\n\n    //necessary assumptions in order to be able to do calculations\n    assert(x.size() == y.size());\n    assert(x.size() >= order + 1);\n\n    Eigen::MatrixXd X(x.size(), order+1);\n    Eigen::VectorXd Y = Eigen::VectorXd::Map(&y.front(), y.size());\n    Eigen::VectorXd result;\n\n    // populate matrix\n    for (size_t i = 0; i < x.size(); i++){\n        for (size_t j = 0; j < order + 1; j++){\n            X(i, j) = pow(x.at(i), j);\n        }\n    }\n    // solve matrix\n    result = X.householderQr().solve(Y);\n    // add coefficients to the coefs vector\n    for (int i = 0; i < order+1; i++){\n        coefs.push_back(result[i]);\n    }\n    degree = order;\n}\n\nPolynomial Polynomial::operator+(const double& num){\n    std::vector<double> new_coefs(coefs);\n    new_coefs[0] += num;\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::operator-(const double& num) {\n    std::vector<double> new_coefs(coefs);\n    new_coefs[0] -= num;\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::operator*(const double& num){\n    std::vector<double> new_coefs(degree+1);\n    std::transform(coefs.begin(), coefs.end(), new_coefs.begin(), [&num](double elm){return elm *= num;});\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::operator/(const double& num) {\n    assert(num != 0);\n    std::vector<double> new_coefs(degree+1);\n    std::transform(coefs.begin(), coefs.end(), new_coefs.begin(), [&num](double elm){return elm /= num;});\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::operator+(const Polynomial& other){\n    int new_degree = std::max(degree, other.degree);\n    std::vector<double> new_coefs(new_degree+1);\n    for (int i = 0; i <= degree; i++){\n        new_coefs[i] += coefs[i];\n    }\n    for (int i = 0; i <= other.degree; i++){\n        new_coefs[i] += other.coefs[i];\n    }\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::operator-(const Polynomial& other){\n    int new_degree = std::max(degree, other.degree);\n    std::vector<double> new_coefs(new_degree+1);\n    for (int i = 0; i <= degree; i++){\n        new_coefs[i] += coefs[i];\n    }\n    for (int i = 0; i <= other.degree; i++){\n        new_coefs[i] -= other.coefs[i];\n    }\n    return Polynomial(new_coefs);\n}\n\ndouble Polynomial::operator()(const double& x){\n    return val(x);\n}\n\ndouble Polynomial::val(const double& x){\n    /* Return the value of the polynomial at x\n     */\n    double res = coefs[0];\n    for (int i = 1; i <= degree; i++){\n        res += coefs[i] * pow(x, i);\n    }\n    return res;\n}\n\nstd::vector<double> Polynomial::roots(const double& real_threshold){\n    /* Return all real roots of the polynomial. The roots are calculated using the eigenvalues of the companion matrix\n     * and will be automatically sorted.\n     * @param real_threshold: The maximum imagninary threshold at which a root can still be considered real\n     */\n    std::vector<double> roots;\n\n    Eigen::MatrixXd companion(degree, degree);\n    companion.setZero();\n\n    companion(0, degree-1) = -(coefs[0] / coefs.back()); // intialize first row in companion matrix\n    for (int row = 1; row < degree; row++){ // initialize rest of companion matrix\n        companion(row, row-1) = 1;\n        companion(row, degree-1) = -(coefs[row] / coefs.back());\n    }\n\n    Eigen::EigenSolver<Eigen::MatrixXd> es(companion, false); // false because we do not need the eigenvectors, only the eigenvalues\n    for (std::complex<double> l : es.eigenvalues()){\n        if (abs(l.imag()) < real_threshold){\n            roots.push_back(l.real());\n        }\n    }\n    sort(roots.begin(), roots.end());\n    return roots;\n}\n\nstd::vector<double> Polynomial::roots(const double& lb, const double& ub, const double& real_threshold){\n    /* Return all real roots within the specified bounds, exclusive: (lb, ub)\n     */\n    std::vector<double> roots;\n\n    Eigen::MatrixXd companion(degree, degree);\n    companion.setZero();\n\n    companion(0, degree-1) = -(coefs[0] / coefs.back()); // intialize first row in companion matrix\n    for (int row = 1; row < degree; row++){ // initialize rest of companion matrix\n        companion(row, row-1) = 1;\n        companion(row, degree-1) = -(coefs[row] / coefs.back());\n    }\n\n    Eigen::EigenSolver<Eigen::MatrixXd> es(companion, false); // false because we do not need the eigenvectors, only the values\n    for (std::complex<double> l : es.eigenvalues()){\n        if (abs(l.imag()) < real_threshold && l.real() > lb && l.real() < ub){\n            roots.push_back(l.real());\n        }\n    }\n    sort(roots.begin(), roots.end());\n    return roots;\n}\n\nstd::vector<double> Polynomial::budans_roots(const double& lb, const double& ub, const int& newton_iter, const double& precision){\n    /* This polynomial root function uses budan's theorem to aproximate a range that each root lies within, then\n     * newtons method is used to find the exact value of the root. This method is faster than the other roots method when\n     * the polynomial has a degree higher than 10\n     * @param newton_iter is the number of iterations of newtons method, more iterations will increase precision of the roots\n     * @param precision is the maximum range in the budan's approximation of the roots. Higher precision will be better but more time consuming\n     */\n    // IT IS VERY HIGHLY RECOMMENDED YOU PASS BOUNDS TO THIS METHOD TO ENSURE IT DOES NOT OVERFLOW ON HIGH DEGREE POLYNOMIALS\n    std::vector<double> roots;\n    std::vector<Polynomial> eqs;\n    eqs.push_back(deriv()); // add the first derivative to the budan table\n    for (int i = 1; i < degree; i++){ // populate vector with the rest of the derivatives of the polynomial\n        eqs.push_back(eqs.back().deriv()); // get last polynomial, take its derivative, then add it to the end of the vector\n    }\n\n    // if degree is > 8, and bounds not passed, the doubles will overflow\n    double x1 = lb;\n    double x2 = ub;\n\n    std::vector<std::array<double, 2>> one_root_regions; // final regions, each with one root, note regions are half-open: (x1, x2]\n    std::stack<std::array<double, 2>> regions_stack;\n\n    regions_stack.push({x1, x2});\n    while (!regions_stack.empty()){\n        std::array<double, 2> reg = regions_stack.top();\n        double l = reg[0];\n        double r = reg[1];\n        regions_stack.pop();\n        int left_sign_switches = 0;\n        double last = val(l);\n        for (Polynomial p : eqs){\n            // increase count whenever the last and p.val(l) have opposite signs\n            double val = p.val(l);\n            if ((val > 0) && (last < 0)){\n                last = val;\n                left_sign_switches++;\n            }else if((val < 0) && (last > 0)){\n                last = val;\n                left_sign_switches++;\n            }else if(last == 0){\n                last = val;\n            }\n        }\n\n        int right_sign_switches = 0;\n        last = val(r);\n        for (Polynomial p : eqs){\n            // increase count whenever the last and p.val(r) have opposite signs\n            double val = p.val(r);\n            if ((val > 0) && (last < 0)){\n                last = val;\n                right_sign_switches++;\n            }else if((val < 0) && (last > 0)){\n                last = val;\n                right_sign_switches++;\n            }else if(last == 0){\n                last = val;\n            }\n        }\n\n        int s = left_sign_switches - right_sign_switches;\n        if (s == 0){ // no roots in region\n            continue;\n        }else if (s == 1){\n            if ((r - l) < precision){\n                one_root_regions.push_back(reg);\n            }else{\n                double m = (l + r)/2;\n                regions_stack.push({l, m});\n                regions_stack.push({m, r});\n            }\n        }else{ // if more then 1 roots in the region, split into left and rights sides then add both to the stack\n            if ((r - l) < (precision)){\n                continue;\n            }else{\n                double m = (l + r)/2;\n                regions_stack.push({l, m});\n                regions_stack.push({m, r});\n            }\n        }\n    }\n\n    for (std::array<double, 2> arr : one_root_regions){\n        double x = (arr[0] + arr[1]) / 2; // initial geuss is the midpoint of the region\n        for (int i = 0; i < newton_iter; i++){\n            x = x - (val(x) / eqs[0].val(x));\n        }\n        if (x > arr[0] && x <= arr[1]){\n            roots.push_back(x);\n        }\n    }\n    sort(roots.begin(), roots.end());\n    return roots;\n}\n\nPolynomial Polynomial::deriv(){\n    /* Take the derivative of the polynomial and return it as a new polynomial\n     */\n    std::vector<double> res_coefs(degree);\n    for (int i = 1; i <= degree; i++){\n        res_coefs[i-1] = coefs[i] * i;\n    }\n    return Polynomial(res_coefs);\n}\n\nPolynomial Polynomial::integ(){\n    /* Compute the indefinite integral of the polynomial, this does not include any integration constant\n     */\n    std::vector<double> new_coefs(degree+2);\n    for (int i = 0; i <= degree; i++){\n        new_coefs[i+1] = coefs[i] / (i+1);\n    }\n    return Polynomial(new_coefs);\n}\n\nPolynomial Polynomial::integ(const double& lbnd) {\n    /* Compute the indefinite integral of the polynomial, but scale it to be 0 at lbnd\n     */\n    std::vector<double> new_coefs(degree+2);\n    for (int i = 0; i <= degree; i++){\n        new_coefs[i+1] = coefs[i] / (i+1);\n    }\n    Polynomial temp(new_coefs);\n    return (temp - temp.val(lbnd));\n}\n\ndouble Polynomial::integ(const double& lb, const double& ub) {\n    /* Compute the definite integral of the polynomial from lb to ub\n     */\n    std::vector<double> new_coefs(degree+2);\n    for (int i = 0; i <= degree; i++){\n        new_coefs[i+1] = coefs[i] / (i+1);\n    }\n    Polynomial poly(new_coefs);\n    return poly.val(ub) - poly.val(lb);\n}\n\nstd::vector<double> Polynomial::solve(const double& num){\n    /* Solve for all occurrences of when the polynomial equals num, by default this uses the companion matrix method, so\n     * for very high degree polynomials you should consider using budan's method\n     */\n    std::vector<double> new_coefs = coefs;\n    new_coefs[0] -= num;\n    Polynomial temp(new_coefs);\n    return temp.roots();\n}\n\ndouble Polynomial::solve(const double& num, const double& lb, const double& ub, const int& newton_iter){\n    /* This version of solve is meant for when a function is strictly monotonic over the interval (lb, ub) and it is known\n     * that exactly one solution to exists within the bounds, for example solving a cdf function.\n     */\n    std::vector<double> new_coefs = coefs;\n    new_coefs[0] -= num;\n    Polynomial f(new_coefs);\n    Polynomial f_prime = f.deriv();\n    double x = (lb+ub)/2; // initial geuss is midpoint\n    for (int i = 0; i < newton_iter; i++){\n        x = x - (f.val(x) / f_prime.val(x));\n    }\n    return x;\n}\n\nvoid Polynomial::print() {\n    if (degree == 0){\n        std::cout << coefs[0] << std::endl;\n        return;\n    }\n    std::cout << coefs[degree] << \"x^\" << degree;\n    for (int i = degree-1; i > 0; i--){\n        if (coefs[i] > 0){\n            std::cout << \" + \";\n        }else{\n            std::cout << \" - \";\n        }\n        std::cout << abs(coefs[i]) << \"x^\" << i;\n    }\n    if (coefs[0] > 0){\n        std::cout << \" + \" << coefs[0] << std::endl;\n    }else{\n        std::cout << \" - \" << abs(coefs[0]) << std::endl;\n    }\n    return;\n}", "meta": {"hexsha": "1825641a2d912684d2d4ff6a84f43cd02431ab4b", "size": 12347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polynomial/polynomial.cpp", "max_stars_repo_name": "MontgomeryBohde/Polynomial", "max_stars_repo_head_hexsha": "7131c1ee828af6ce17bf3b4b7c24a9d587b44a6c", "max_stars_repo_licenses": ["MIT"], "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/polynomial.cpp", "max_issues_repo_name": "MontgomeryBohde/Polynomial", "max_issues_repo_head_hexsha": "7131c1ee828af6ce17bf3b4b7c24a9d587b44a6c", "max_issues_repo_licenses": ["MIT"], "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/polynomial.cpp", "max_forks_repo_name": "MontgomeryBohde/Polynomial", "max_forks_repo_head_hexsha": "7131c1ee828af6ce17bf3b4b7c24a9d587b44a6c", "max_forks_repo_licenses": ["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.4798850575, "max_line_length": 143, "alphanum_fraction": 0.594233417, "num_tokens": 3244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.6761988598652399}}
{"text": "/*\n * fit_test.cpp Test fixtures for fitting velocity profiles\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include \"gtest/gtest.h\"\n#include <unsupported/Eigen/AutoDiff>\n\n#include \"fit.h\"\n#include \"relations/velocity.h\"\n#include \"definitions.h\"\n\n#include \"cpplot.h\"\n\nusing namespace es;\nusing namespace Eigen;\n\n\n// Add the test environment\nextern ::testing::Environment* const environment;\n\n\n// Test fixture for the fitting process\nclass FitTest : public ::testing::Test {\n};\n\n// Unit tests for fitting routines\nTEST_F(FitTest, test_fit_power_law_speed){\n\n    // Basic profile parameters\n    double z_ref = 60;\n    double u_ref = 10;\n    double alpha_true = 0.3;\n\n    // Create a power law distribution with random noise added\n    Eigen::ArrayXd z = Eigen::ArrayXd::LinSpaced(20, 1, 200);\n    Eigen::ArrayXd u_original(20);\n    Eigen::ArrayXd u_noisy(20);\n    Eigen::ArrayXd u_fitted(20);\n    u_original = power_law_speed(z, u_ref, z_ref, alpha_true);\n    u_noisy = u_original + ArrayXd::Random(20);\n\n    // Fit to find the value of alpha\n    double alpha_fitted = fit_power_law_speed(z, u_noisy, z_ref, u_ref);\n    u_fitted = power_law_speed(z, u_ref, z_ref, alpha_fitted);\n\n    // Display original, noisy and fitted profiles on scatter plot\n    cpplot::Figure fig = cpplot::Figure();\n    cpplot::ScatterPlot p_original = cpplot::ScatterPlot();\n    cpplot::ScatterPlot p_noisy = cpplot::ScatterPlot();\n    cpplot::ScatterPlot p_fitted = cpplot::ScatterPlot();\n\n    p_original.y = z.matrix();\n    p_noisy.y = z.matrix();\n    p_fitted.y = z.matrix();\n\n    p_original.x = u_original;\n    p_noisy.x = u_noisy;\n    p_fitted.x = u_fitted;\n\n    fig.add(p_original);\n    fig.add(p_noisy);\n    fig.add(p_fitted);\n\n    fig.write(\"test_fit_power_law_speed.json\");\n\n    // Check that the fit worked\n    // TODO use a known seed for the random noise which is added to avoid occasional failure here\n    ASSERT_NEAR(alpha_fitted,  alpha_true, 0.15);\n}\n\n\n// Unit tests for fitting routines\nTEST_F(FitTest, test_fit_lewkowicz_speed){\n\n    // Basic profile parameters\n    double pi_coles = 0.42;\n    double kappa = KAPPA_VON_KARMAN;\n    double u_inf = 20;\n    double shear_ratio = 23.6;\n    double delta_c = 1000;\n\n    // Create a `correct` distribution with random noise added\n    Eigen::ArrayXd z = Eigen::ArrayXd::LinSpaced(40, 1, 400);\n    Eigen::ArrayXd u_original(40);\n    Eigen::ArrayXd u_noisy(40);\n    Eigen::ArrayXd u_fitted(40);\n    u_original = lewkowicz_speed(z, pi_coles, kappa, u_inf, shear_ratio, delta_c);\n    u_noisy = u_original + ArrayXd::Random(40) / 4;\n    std::cout << z.transpose() << std::endl <<std::endl;\n    std::cout << u_noisy.transpose() << std::endl <<std::endl;\n\n    // Fit to find the value of alpha\n    Eigen::Array<double, 5, 1> fitted = fit_lewkowicz_speed(z, u_noisy);\n    u_fitted = lewkowicz_speed(z, fitted(0), fitted(1), fitted(2), fitted(3), fitted(4));\n\n    // Sum of squares error, for exact and fitted\n    double lsq_error_noisy = pow(u_original-u_noisy, 2.0).sum();\n    double lsq_error_fitted = pow(u_fitted-u_noisy, 2.0).sum();\n    std::cout << \"Sqd error (correct - noisy): \" << lsq_error_noisy << std::endl;\n    std::cout << \"Sqd error (fitted - noisy) (should be lower): \" << lsq_error_fitted << std::endl;\n\n    // Display original, noisy and fitted profiles on scatter plot\n    cpplot::Figure fig = cpplot::Figure();\n    cpplot::Layout lay = cpplot::Layout();\n    cpplot::ScatterPlot p_original = cpplot::ScatterPlot();\n    cpplot::ScatterPlot p_noisy = cpplot::ScatterPlot();\n    cpplot::ScatterPlot p_fitted = cpplot::ScatterPlot();\n    lay.xLabel(\"u_bar (m/s)\");\n    lay.yLabel(\"z (m)\");\n    fig.setLayout(lay);\n\n    p_original.y = z.matrix();\n    p_original.name = \"Correct\";\n    p_noisy.y = z.matrix();\n    p_noisy.name = \"Added noise\";\n    p_fitted.y = z.matrix();\n    p_fitted.name = \"Fitted\";\n\n    p_original.x = u_original;\n    p_noisy.x = u_noisy;\n    p_fitted.x = u_fitted;\n\n    fig.add(p_original);\n    fig.add(p_noisy);\n    fig.add(p_fitted);\n\n    fig.write(\"test_fit_lewkowicz_speed.json\");\n\n    // Check that the fit worked\n    ASSERT_NEAR(fitted(0), pi_coles, 0.02);\n\n}\n\n", "meta": {"hexsha": "b1cc44ca624b41857ae87489f57ccc41a6cf80f5", "size": 4252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/fit_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/fit_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/fit_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "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.1560283688, "max_line_length": 99, "alphanum_fraction": 0.6716839135, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6761988480184974}}
{"text": "//\n// -----------------------------------------------\n// Provides Extreme Learning Machine algorithm.\n// -----------------------------------------------\n//\n// Refer to:\n// G.-B. Huang et al., \u201cExtreme Learning Machine for Regression and Multiclass Classification,\u201d IEEE TSMC, vol. 42, no. 2, pp. 513-529, 2012.\n//\n// Vladislavs D.\n//\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef ELM_H\n#define ELM_H\n\nint compare( const void *a, const void *b );\n\n//template <typename Derived>\nMatrixXd buildTargetMatrix( double *Y, int nLabels );\n\n// entry function to train the ELM model\n// INPUT: X, Y, nhn, C\n// OUTPUT: inW, bias, outW\ntemplate <typename Derived>\nint elmTrain( double *X, int dims, int nsmp, \n       \t      double *Y,\n\t      const int nhn, const double C,\n\t      MatrixBase<Derived> &inW, MatrixBase<Derived> &bias, MatrixBase<Derived> &outW ) {\n\n\t// map the samples into the matrix object\n\tMatrixXd mX = Map<MatrixXd>( X, dims, nsmp );\n\n\t// build target matrix\n\tMatrixXd mTargets = buildTargetMatrix( Y, nsmp );\n\n\t// generate random input weight matrix - inW\n\tinW = MatrixXd::Random( nhn, dims );\n\n\t// generate random bias vectors\n\tbias = MatrixXd::Random( nhn, 1 );\n\n\t// compute the pre-H matrix\n\tMatrixXd preH = inW * mX;\n\n\t// compute hidden neuron output\n\tMatrixXd H = (1 + (-preH.array()).exp()).cwiseInverse();\n\n\t// build matrices to solve Ax = b\n\tMatrixXd A = (MatrixXd::Identity(nhn,nhn)).array()*(1/C) + (H * H.transpose()).array();\n\tMatrixXd b = H * mTargets.transpose();\n\t\n\t// solve the output weights as a solution to a system of linear equations\n\toutW = A.llt().solve( b );\n\t\n\treturn 0;\n\n}\n\n// entry function to predict class labels using the trained ELM model on test data\n// INPUT : X, inW, bias, outW\n// OUTPUT : scores\ntemplate <typename Derived>\nint elmPredict( double *X, int dims, int nsmp,\n\t\tMatrixBase<Derived> &mScores,\n\t\tMatrixBase<Derived> &inW, MatrixBase<Derived> &bias, MatrixBase<Derived> &outW ) {\n\n\t// map the sample into the Eigen's matrix object\n\tMatrixXd mX = Map<MatrixXd>( X, dims, nsmp );\n\n\t// build the pre-H matrix\n\tMatrixXd preH = inW * mX + bias.replicate( 1, nsmp );\n\n\t// apply the activation function\n\tMatrixXd H = ( 1 + (-preH.array()).exp() ).cwiseInverse();\n\n\t// compute output scores\n\tmScores = (H.transpose() * outW).transpose();\n\n\treturn 0;\n}\n\n\n// --------------------------\n// Helper functions\n// --------------------------\n\n// compares two integer values\n//int compare( const void* a, const void *b ) {\n//\treturn ( *(int *) a - *(int *) b );\n//}\n\nint compare( const void *a, const void *b )\n{\n\tconst double *da = (const double *) a;\n\tconst double *db = (const double *) b;\n\treturn (*da > *db) - (*da < *db);\n}\n\n// builds 1-of-K target matrix from labels array\n//template <typename Derived>\nMatrixXd buildTargetMatrix( double *Y, int nLabels ) {\n\n\t// make a temporary copy of the labels array\n\tdouble *tmpY = new double[ nLabels ];\n\tfor ( int i = 0 ; i < nLabels ; i++ ) {\n\t\ttmpY[i] = Y[i];\n\t}\n\n\t// sort the array of labels\n\tqsort( tmpY, nLabels, sizeof(double), compare );\n\n\t// count unique labels\n\tint nunique = 1;\n\tfor ( int i = 0 ; i < nLabels - 1 ; i++ ) {\n\t\tif ( tmpY[i] != tmpY[i+1] )\n\t\t\tnunique++;\n\t}\n    \n    delete [] tmpY;\n\n\tMatrixXd targets( nunique, nLabels );\n\ttargets.fill( 0 );\n\n\n\t// fill in the ones\n\tfor ( int i = 0 ; i < nLabels ; i++ ) {\n\t\tint idx = Y[i] - 1;\n\t\ttargets( idx, i ) = 1;\n\t}\n\n\t// normalize the targets matrix values (-1/1)\n\ttargets *= 2;\n\ttargets.array() -= 1;\n\n\treturn targets;\n\n}\n\n#endif\n\n", "meta": {"hexsha": "80461be7ecf561165f9dd365b2d224470151aa4e", "size": 3555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "elml.hpp", "max_stars_repo_name": "ExtremeLearningMachines/elm-c-version", "max_stars_repo_head_hexsha": "bc7453a80aa7995b07e7401715844a61c97ec639", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-02-11T02:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T16:17:32.000Z", "max_issues_repo_path": "elml.hpp", "max_issues_repo_name": "ExtremeLearningMachines/elm-c-version", "max_issues_repo_head_hexsha": "bc7453a80aa7995b07e7401715844a61c97ec639", "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": "elml.hpp", "max_forks_repo_name": "ExtremeLearningMachines/elm-c-version", "max_forks_repo_head_hexsha": "bc7453a80aa7995b07e7401715844a61c97ec639", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-01-09T08:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T18:21:27.000Z", "avg_line_length": 24.1836734694, "max_line_length": 141, "alphanum_fraction": 0.6191279887, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.67616524829141}}
{"text": "#include <array>\n\n#include <language/api.hpp>\n#include <tensor/tensor.hpp>\n\n#include <boost/archive/text_oarchive.hpp>\n\nSCENARIO(\"General tensors\", \"[tensor]\") {\n\n    GIVEN(\" a tensor with two indices\") {\n\n        Construction::Tensor::Tensor T(\"T\", \"T\", Construction::Tensor::Indices::GetRomanSeries(2, {1,3}));\n\n        WHEN(\" printing the TeX code\") {\n            std::stringstream ss;\n            ss << T;\n            auto code = ss.str();\n\n            THEN(\" we get\") {\n                REQUIRE(code == \"T_{ab}\");\n            }\n\n        }\n\n        WHEN(\" symmetrizing a tensor\") {\n            auto tensor = Construction::Tensor::Tensor::EpsilonGamma(0,2, Construction::Tensor::Indices::GetRomanSeries(4, {1,3}));\n\n            REQUIRE(tensor.Symmetrize({ {\"a\", {1,3}}, {\"c\", {1,3}} }).ToString() == \"1/2 * (\\\\gamma_{ab}\\\\gamma_{cd} + \\\\gamma_{ad}\\\\gamma_{bc})\");\n        }\n\n        WHEN(\" evaluating the tensor components\") {\n\n            std::array<double, 9> components;\n\n            for (unsigned i=1; i<=3; ++i) {\n                for (unsigned j=1; j<=3; ++j) {\n                    components[3*(i-1)+j-1] = T(i,j).ToDouble();\n                }\n            }\n\n            THEN(\" all components should be zero\") {\n                for (unsigned i=0; i<9; i++) {\n                    REQUIRE(components[i] == 0);\n                }\n            }\n\n        }\n\n        WHEN(\" going out of scope, all memory is freed\") {\n\n        }\n\n        WHEN(\" serializing the tensor\") {\n\n            std::stringstream ss;\n            auto tensor = Construction::Tensor::Tensor::EpsilonGamma(1,2, Construction::Tensor::Indices::GetRomanSeries(7, {1,3}));\n\n            tensor.Serialize(ss);\n\n\t        std::string content = ss.str();\n\n            THEN(\" the deserialized tensor is correct\") {\n                std::stringstream is(content);\n                auto read = Construction::Tensor::Tensor::Deserialize(is);\n\n\t\t        REQUIRE(read);\n\n\t\t        REQUIRE(read->ToString() == tensor.ToString());\n            }\n\n            /*std::stringstream ss;\n            {\n                boost::archive::text_oarchive oa(ss);\n                oa << T;\n            }\n            std::cout << ss.str() << std::endl;*/\n\n        }\n\n    }\n\n}\n\n/**\n    Testing of the Levi-Civita symbol\n */\nSCENARIO(\"Epsilon tensor\", \"[epsilon-tensor]\") {\n\n    // Levi-Civita symbol in three dimensions, i.e. on a spatial slice\n    GIVEN(\" epsilon in three dimensions\") {\n        auto epsilon = Construction::Tensor::Tensor::Epsilon(Construction::Tensor::Indices::GetRomanSeries(3, {1,3}));\n\n        // Look at the indices\n        WHEN(\" looking at the indices\") {\n            auto indices = epsilon.GetIndices();\n\n            // Only allow three indices\n            THEN(\" we have exactly three\") {\n                REQUIRE(indices.Size() == 3);\n            }\n\n        }\n\n        WHEN(\" initializing the epsilon with all indices up\") {\n            auto indices = Construction::Tensor::Indices::GetRomanSeries(3, {1,3});\n            indices[0].SetContravariant(true);\n            indices[1].SetContravariant(true);\n            indices[2].SetContravariant(true);\n\n            REQUIRE(indices.ToString() == \"^{abc}\");\n\n            auto epsilon2 = Construction::Tensor::Tensor::Epsilon(indices);\n\n            THEN(\" we get the proper result\") {\n                REQUIRE(epsilon2.ToString() == \"\\\\epsilon^{abc}\");\n            }\n        }\n\n        // All index combinations\n        WHEN(\" looking at the tensor components with two or more indices being equal\") {\n            THEN(\" we get zero due to antisymmetry\") {\n                // Same indices\n                REQUIRE(epsilon(1,1,1) == 0.0);\n                REQUIRE(epsilon(2,2,2) == 0.0);\n                REQUIRE(epsilon(3,3,3) == 0.0);\n\n                REQUIRE(epsilon(1,1,2) == 0.0);\n                REQUIRE(epsilon(1,1,3) == 0.0);\n                REQUIRE(epsilon(1,2,1) == 0.0);\n                REQUIRE(epsilon(1,3,1) == 0.0);\n                REQUIRE(epsilon(2,1,1) == 0.0);\n                REQUIRE(epsilon(3,1,1) == 0.0);\n\n                REQUIRE(epsilon(2,2,1) == 0.0);\n                REQUIRE(epsilon(2,2,3) == 0.0);\n                REQUIRE(epsilon(2,1,2) == 0.0);\n                REQUIRE(epsilon(2,3,2) == 0.0);\n                REQUIRE(epsilon(1,2,2) == 0.0);\n                REQUIRE(epsilon(3,2,2) == 0.0);\n\n                REQUIRE(epsilon(3,3,1) == 0.0);\n                REQUIRE(epsilon(3,3,2) == 0.0);\n                REQUIRE(epsilon(3,1,3) == 0.0);\n                REQUIRE(epsilon(3,2,3) == 0.0);\n                REQUIRE(epsilon(1,3,3) == 0.0);\n                REQUIRE(epsilon(2,3,3) == 0.0);\n            }\n        }\n\n        WHEN(\" looking at the tensor components with cyclic permutations of (1,2,3)\") {\n            THEN(\" we get one\") {\n                REQUIRE(epsilon(1,2,3) == 1);\n                REQUIRE(epsilon(2,3,1) == 1);\n                REQUIRE(epsilon(3,1,2) == 1);\n            }\n        }\n\n        WHEN(\" looking at the tensor components with odd permutations of (1,2,3)\") {\n            THEN(\" we get minus one\") {\n                REQUIRE(epsilon(2,1,3) == -1);\n                REQUIRE(epsilon(3,2,1) == -1);\n                REQUIRE(epsilon(1,3,2) == -1);\n            }\n        }\n\n        WHEN(\" considering the type of the tensor\") {\n            THEN(\" IsEpsilon returns true\") {\n                REQUIRE(epsilon.IsEpsilon());\n            }\n\n            THEN(\" IsEpsilon returns true even after cast\") {\n                Construction::Tensor::Tensor t = epsilon;\n                REQUIRE(t.IsEpsilon());\n            }\n        }\n    }\n\n    GIVEN(\" epsilon in four dimensions\") {\n        auto epsilon = Construction::Tensor::Tensor::Epsilon(Construction::Tensor::Indices::GetRomanSeries(4,{0,3}));\n\n        // Look at the indices\n        WHEN(\" looking at the indices\") {\n            auto indices = epsilon.GetIndices();\n\n            // Only allow three indices\n            THEN(\" we have exactly four\") {\n                REQUIRE(indices.Size() == 4);\n            }\n\n            THEN(\" cyclic permutation is not 1\") {\n                REQUIRE(epsilon(1,2,3,0) == -1);\n            }\n\n        }\n\n    }\n\n}\n\nSCENARIO(\"Metric tensor\", \"[gamma-tensor]\") {\n\n    GIVEN(\" a spatial metric\") {\n        auto gamma = Construction::Tensor::Tensor::Gamma(Construction::Tensor::Indices::GetRomanSeries(2,{1,3}));\n\n        WHEN(\" considering the indices\") {\n            auto indices = gamma.GetIndices();\n\n            THEN(\" it should have two\") {\n                REQUIRE(indices.Size() == 2);\n            }\n\n            THEN(\" it should print to {ab}\") {\n                REQUIRE(indices.ToString() == \"_{ab}\");\n            }\n        }\n\n        WHEN(\" evaluating the components\") {\n\n            THEN(\" we have a diagonal tensor\") {\n                REQUIRE(gamma(1, 1) == 1);\n                REQUIRE(gamma(2, 2) == 1);\n                REQUIRE(gamma(3, 3) == 1);\n\n                REQUIRE(gamma(1, 2) == 0);\n                REQUIRE(gamma(1, 3) == 0);\n                REQUIRE(gamma(2, 1) == 0);\n                REQUIRE(gamma(2, 3) == 0);\n                REQUIRE(gamma(3, 1) == 0);\n                REQUIRE(gamma(3, 2) == 0);\n            }\n        }\n\n    }\n\n}\n\nSCENARIO(\"Epsilon Gamma\", \"[epsilon-gamma]\") {\n\n    GIVEN(\" a tensor with one epsilon and three gammas\") {\n        auto T = Construction::Tensor::Tensor::EpsilonGamma(1,3, Construction::Tensor::Indices::GetRomanSeries(9, {1,3}));\n\n        WHEN(\" printing the TeX code\") {\n            REQUIRE(T.ToString() == \"\\\\epsilon_{abc}\\\\gamma_{de}\\\\gamma_{fg}\\\\gamma_{hi}\");\n        }\n\n        WHEN(\" considering some components\") {\n            REQUIRE(T(1, 1, 2, 3, 1, 2, 1, 2, 1) == 0.0);\n            REQUIRE(T(1, 2, 3, 1, 1, 2, 2, 3, 3) == 1.0);\n            REQUIRE(T(1, 3, 2, 1, 1, 2, 2, 3, 3) == -1);\n        }\n\n        /*WHEN(\" serializing the tensor\") {\n\n            std::stringstream ss;\n\n            // Scope based output\n            {\n                boost::archive::binary_oarchive oa(ss);\n                oa << T;\n            }\n\n            std::string output = ss.str();\n            std::cout << T << std::endl;\n            std::cout << output << std::endl;\n\n            THEN(\" the deserialized tensor has the correct indices\") {\n\n                Construction::Tensor::Tensor t;\n\n                // Scope based input\n                {\n                    boost::archive::binary_iarchive ia(ss);\n                    ia >> t;\n                }\n\n                std::cout << t << std::endl;\n            }\n\n        }*/\n\n        WHEN(\" considering the canonicalization\") {\n            Construction::Tensor::Indices indices;\n            indices.Insert(Construction::Tensor::Index(\"a\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"c\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"b\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"g\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"f\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"e\", {1,3}));\n            indices.Insert(Construction::Tensor::Index(\"d\", {1,3}));\n\n            auto S = Construction::Tensor::Tensor::EpsilonGamma(1,2, indices);\n\n            THEN(\"We get the correct result\") {\n                auto canon = S.Canonicalize();\n                REQUIRE(canon.ToString() == \"-\\\\epsilon_{abc}\\\\gamma_{de}\\\\gamma_{fg}\");\n            }\n\n        }\n\n    }\n\n    GIVEN(\" a tensor with 1 epsilon and 1 gamma with non-standard indices\") {\n\n        Construction::Tensor::Indices indices;\n        indices.Insert(Construction::Tensor::Index(\"a\", {1,3}));\n        indices.Insert(Construction::Tensor::Index(\"c\", {1,3}));\n        indices.Insert(Construction::Tensor::Index(\"b\", {1,3}));\n        indices.Insert(Construction::Tensor::Index(\"e\", {1,3}));\n        indices.Insert(Construction::Tensor::Index(\"d\", {1,3}));\n\n        auto S = Construction::Tensor::Tensor::EpsilonGamma(1,1, indices);\n\n        WHEN(\" canonicalizing this tensor\") {\n            auto canon = S.Canonicalize();\n\n            REQUIRE(canon.ToString() == \"-\\\\epsilon_{abc}\\\\gamma_{de}\");\n        }\n    }\n\n}\n\n\nSCENARIO(\"Addition\", \"[tensor-addition]\") {\n\n    auto gamma = Construction::Tensor::Tensor::Gamma(Construction::Tensor::Indices::GetRomanSeries(2,{1,3}));\n    auto gamma2 = Construction::Tensor::Tensor::Gamma(Construction::Tensor::Indices::GetRomanSeries(2,{1,3}));\n\n    GIVEN(\" two tensors (twice the metric)\") {\n\n        auto a = gamma + gamma2;\n\n        WHEN(\" printing the TeX code\") {\n\n            THEN(\" get twice the metric \\\\gamma\") {\n                REQUIRE(a.ToString() == \"\\\\gamma_{ab} + \\\\gamma_{ab}\");\n            }\n        }\n\n        WHEN(\" simpliyifing\") {\n            THEN(\" we really get just twice the metric \\\\gamma\") {\n                auto b = a.Simplify();\n                REQUIRE(b.ToString() == \"2 * \\\\gamma_{ab}\");\n\n                auto c = (Construction::Tensor::Scalar::Variable(\"x\") * gamma + Construction::Tensor::Scalar::Variable(\"y\") * gamma2);\n                REQUIRE(c.Simplify().ToString() == \"(x + y) * \\\\gamma_{ab}\");\n\n                auto d = c.Simplify().RedefineVariables(\"x\");\n                REQUIRE(d.ToString() == \"x_1 * \\\\gamma_{ab}\");\n            }\n        }\n\n        WHEN(\" symmetrizing (manually)\") {\n            Construction::Tensor::Indices indices = { {\"b\", {1,3}}, {\"a\", {1,3}} };\n            auto permuted_gamma = Construction::Tensor::Tensor::Gamma({ { \"b\", {1,3} }, { \"a\", {1,3} } });\n\n            auto symmetrized = Construction::Tensor::Scalar(1,2) * ( gamma + permuted_gamma );\n            auto expanded = symmetrized.Expand();\n            auto simplified = expanded.Simplify();\n\n            THEN(\" we get the symmetrized expression when not simpliyifing\") {\n                REQUIRE(symmetrized.ToString() == \"1/2 * (\\\\gamma_{ab} + \\\\gamma_{ba})\");\n            }\n\n            THEN(\" the expanded term looks correct\") {\n                REQUIRE(expanded.ToString() == \"1/2 * \\\\gamma_{ab} + 1/2 * \\\\gamma_{ba}\");\n            }\n\n            THEN(\" we get the metric again after simplification\") {\n                REQUIRE(simplified.ToString() == \"\\\\gamma_{ab}\");\n            }\n        }\n\n        WHEN(\" considering the indices\") {\n            auto indices = a.GetIndices();\n\n            THEN(\" should also have two indices\") {\n                REQUIRE(indices.Size() == 2);\n            }\n\n            THEN(\" should be {ab}\") {\n                REQUIRE(indices.ToString() == \"_{ab}\");\n            }\n        }\n\n        WHEN(\" serializing an addition of two tensors\") {\n            auto tensor = Construction::Tensor::Scalar(\"x\") * Construction::Tensor::Tensor::EpsilonGamma(0, 3, Construction::Tensor::Indices::GetRomanSeries(6, {1,3})) +\n                     Construction::Tensor::Scalar(\"y\") * Construction::Tensor::Tensor::EpsilonGamma(2, 0, Construction::Tensor::Indices::GetRomanSeries(6, {1,3}));\n\n            std::string content;\n\n            // Serialize\n            {\n                std::stringstream ss;\n                tensor.Serialize(ss);\n                content = ss.str();\n            }\n\n            THEN(\" the deserialized gives the same tensor again\") {\n                std::stringstream ss(content);\n                auto deserialized = Construction::Tensor::Tensor::Deserialize(ss);\n\n                REQUIRE(deserialized);\n                REQUIRE(deserialized->ToString() == tensor.ToString());\n            }\n        }\n\n        WHEN(\" creating a delta tensor\") {\n            auto indices = Construction::Tensor::Indices::GetRomanSeries(2, {1,3});\n            indices[0].SetContravariant(true);\n            indices[1].SetContravariant(false);\n\n            REQUIRE(indices.ToString() == \"^{a}_{b}\");\n\n            REQUIRE(indices.ContainsIndex({\"a\", {1,3}}));\n\n            auto delta = Construction::Language::API::Delta(indices);\n\n            REQUIRE(delta.ToString() == \"\\\\delta^{a}_{b}\");\n        }\n\n        WHEN(\" calculating the trace of delta\") {\n            auto delta = Construction::Language::API::Delta({\n                {\"a\", {1,3}},\n                {\"a\", {1,3}}\n            });\n\n            REQUIRE(delta.ToString() == \"\\\\delta^{a}_{a}\");\n        }\n\n        WHEN(\" contracting two indices\") {\n            auto A = Construction::Tensor::Indices::GetRomanSeries(2, {1,3});\n            Construction::Tensor::Indices B = { {\"a\", {1,3}}, {\"c\", {1,3}}, {\"d\", {1,3}} };\n            B[0].SetContravariant(true);\n\n            REQUIRE(A.ToString() == \"_{ab}\");\n            REQUIRE(B.ToString() == \"^{a}_{cd}\");\n            REQUIRE(A.Contract(B).ToString() == \"_{bcd}\");\n\n            A[0].SetContravariant(true);\n            REQUIRE_THROWS(A.Contract(B));\n\n            B[0].SetContravariant(false);\n            REQUIRE(A.Contract(B).ToString() == \"_{bcd}\");\n\n            REQUIRE(A.Contract(Construction::Tensor::Indices::GetRomanSeries(2, {1,3}, 2)).ToString() == \"^{a}_{bcd}\");\n        }\n\n        WHEN(\" contracting with delta\") {\n            auto delta = Construction::Language::API::Delta({ {\"a\", {1,3}}, {\"d\", {1,3}}});\n            auto epsilon = Construction::Language::API::Epsilon(Construction::Tensor::Indices::GetRomanSeries(3, {1,3}));\n\n            REQUIRE(delta.ToString() == \"\\\\delta^{a}_{d}\");\n\n            auto contracted = delta * epsilon;\n\n            REQUIRE(contracted.ToString() == \"\\\\epsilon_{dbc}\");\n            //REQUIRE(contracted() == 3);\n        }\n\n        WHEN(\" adding them\") {\n\n            THEN(\" we get the double\") {\n                REQUIRE(a(1,1) == 2);\n                REQUIRE(a(1,2) == 0);\n                REQUIRE(a(1,3) == 0);\n                REQUIRE(a(2,1) == 0);\n                REQUIRE(a(2,2) == 2);\n                REQUIRE(a(2,3) == 0);\n                REQUIRE(a(3,1) == 0);\n                REQUIRE(a(3,2) == 0);\n                REQUIRE(a(3,3) == 2);\n            }\n\n        }\n\n    }\n\n}\n", "meta": {"hexsha": "b7956aa69e236b6a15ad7231309dfc537d03466b", "size": 15763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tensor/tensor.cpp", "max_stars_repo_name": "constructivegravity/construct", "max_stars_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-01T13:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T19:27:14.000Z", "max_issues_repo_path": "test/tensor/tensor.cpp", "max_issues_repo_name": "constructivegravity/construct", "max_issues_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-07-19T11:50:54.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-05T14:31:21.000Z", "max_forks_repo_path": "test/tensor/tensor.cpp", "max_forks_repo_name": "constructivegravity/construct", "max_forks_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-19T08:35:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T19:27:35.000Z", "avg_line_length": 32.9081419624, "max_line_length": 169, "alphanum_fraction": 0.490896403, "num_tokens": 3840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6761652459867362}}
{"text": "#pragma once\n#include <cstddef>\n#include <cmath>\n#include <Eigen/Dense>\n#include <fastad_bits/util/shape_traits.hpp>\n#include <fastad_bits/reverse/core/var_view.hpp>\n#include <autoppl/expression/constraint/transformer.hpp>\n#include <autoppl/util/value.hpp>\n#include <autoppl/util/ad_boost/cov_inv_transform.hpp>\n\nnamespace ppl {\nnamespace expr {\nnamespace constraint {\n\nstruct PosDef {\n\n    /**\n     * Returns the number of unconstrained parameters based on\n     * the rows (which is also cols) of a positive-definite matrix.\n     */\n    static constexpr size_t size(size_t rows)\n    { return (rows * (rows + 1)) / 2; }\n\n    /**\n     * Transforms from constrained (c) to unconstrained (uc).\n     */\n    template <class CType, class UCType>\n    static constexpr void transform(const CType& c,\n                                    UCType& uc)\n    {\n        using value_t = typename CType::Scalar;\n        using mat_t = Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic>;\n        Eigen::LLT<mat_t> llt(c);\n        mat_t lower = llt.matrixL();\n        lower.diagonal().array() = lower.diagonal().array().log();\n\n        size_t k = 0;\n        for (int j = 0; j < lower.cols(); ++j) {\n            for (int i = j; i < lower.rows(); ++i, ++k) {\n                uc(k) = lower(i,j); \n            }\n        }\n    }\n\n    /**\n     * Inverse transforms from unconstrained parameters (uc),\n     * which is vector-like in the sense that operator()(index) is defined,\n     * to constrained parameter (c), which is matrix-like.\n     * Lower should also be matrix-like supporting operator()(index, index)\n     * which is used a temporary storage for the transformation.\n     */\n    template <class LowerType, class UCType, class CType>\n    static constexpr void inv_transform(LowerType& lower,\n                                        const UCType& uc,\n                                        CType& c)\n    { ad::boost::cov_inv_transform(lower, uc, c); }\n};\n\n// Specialization: Positive-Definite (matrix)\ntemplate <class ValueType>\nstruct Transformer<ValueType, mat, PosDef>\n{\n    using value_t = ValueType;\n    using shape_t = mat;\n    using var_t = util::var_t<value_t, shape_t>;\n    using constraint_t = PosDef;\n    using uc_view_t = ad::util::shape_to_raw_view_t<value_t, vec>;\n    using view_t = ad::util::shape_to_raw_view_t<value_t, shape_t>;\n\n    // only continuous value types can be constrained\n    static_assert(util::is_cont_v<value_t>);\n\n    /**\n     * Constructs a Transformer object.\n     * It represents a positive-definite matrix, and hence\n     * ignores cols (second parameter) and treats rows as both rows and cols.\n     *\n     * @param   rows    number of constrained rows (and cols)\n     */\n    Transformer(size_t rows, \n                size_t,\n                constraint_t=constraint_t())\n        : uc_val_(nullptr, constraint_t::size(rows))\n        , c_val_(nullptr, rows, rows)\n        , lower_(nullptr, rows, rows)\n        , v_val_(nullptr)\n    {}\n\n    void transform() {\n        constraint_t::transform(c_val_, uc_val_);\n    }\n\n    /**\n     * Inverse transforms from unconstrained parameters to constrained parameters.\n     * Only the first visitor of the visit count will invoke the actual transformation.\n     * The reference count is used to reset the visit count if \n     * the visit count has reached refcnt.\n     *\n     * @return  viewer of constrained parameters\n     */\n    void inv_transform(size_t refcnt) { \n        ++*v_val_;\n        if (*v_val_ == 1) {\n            constraint_t::inv_transform(lower_, uc_val_, c_val_);\n        }\n        *v_val_ = *v_val_ % refcnt;\n    }\n\n    /**\n     * Inverse transform from unconstrained parameters to constrained parameters.\n     * This should not have any memory dependency through calling bind.\n     * It is expected that uc and c are vector-like \n     * in the sense that either row or column is 1.\n     * In debug mode, we check that uc and c have correct sizes.\n     *\n     * @param   uc  vector of unconstrained parameters to transform\n     * @param   c   vector of constrained parameters to populate\n     */\n    //template <class UCVecType, class CVecType>\n    //void inv_transform(const UCVecType& uc,\n    //                   CVecType& c) const\n    //{\n    //    assert(static_cast<size_t>(uc.size()) == size_uc());\n    //    assert(static_cast<size_t>(c.size()) == size_c());\n    //    assert(uc.rows() == 1 || uc.cols() == 1);\n    //    assert(c.rows() == 1 || c.cols() == 1);\n\n    //    using vec_t = Eigen::Matrix<value_t, Eigen::Dynamic, 1>;\n    //    using mat_t = Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic>;\n    //    mat_t uc_vec = uc;\n    //    mat_t c_vec = c;\n    //    mat_t lower(rows_c(), rows_c());\n    //    lower.setZero();\n    //    Eigen::Map<vec_t> uc_mp(uc_vec.data(), uc.size());\n    //    Eigen::Map<mat_t> c_mp(c_vec.data(), rows_c(), rows_c());\n    //    constraint_t::inv_transform(lower, uc_vec, c_mp);\n    //    c = c_vec;\n    //}\n\n    /**\n     * Creates an AD expression representing the inverse transform.\n     * User must ensure that this gets called exactly refcnt number of times.\n     *\n     * @param   uc_val      beginning of unconstrained parameter values\n     * @param   uc_adj      beginning of unconstrained parameter adjoints\n     * @param   c_val       beginning of constrained value region.\n     *                      The first size_c() elements will be used as temporary region\n     *                      to compute a lower-triangular matrix.\n     * @param   v_val       beginning of visit count\n     * @param   refcnt      total reference count to determine when to loop visit count back to 0\n     */\n    template <class CurrPtrPack, class PtrPack>\n    auto inv_transform_ad(const CurrPtrPack& curr_pack,\n                          const PtrPack&,\n                          size_t refcnt) const {\n        ad::VarView<value_t, ad::vec> uc_view(curr_pack.uc_val, \n                                              curr_pack.uc_adj, \n                                              size_uc());\n        return ad::boost::CovInvTransformNode(uc_view, \n                                              curr_pack.c_val,\n                                              curr_pack.c_val + size_c(), \n                                              rows_c(), \n                                              curr_pack.v_val, \n                                              refcnt);\n    }\n\n    /**\n     * Creates an AD expression representing the log-jacobian of inverse transform.\n     * In general, this may need to reuse computed values from inverse transform.\n     * User must guarantee that inverse transform AD expression that is bound to the same\n     * resources as the return value of this function is evaluated before.\n     */\n    template <class CurrPtrPack, class PtrPack>\n    auto logj_inv_transform_ad(const CurrPtrPack& curr_pack,\n                               const PtrPack&) const {\n        ad::VarView<value_t, ad::vec> uc_view(curr_pack.uc_val, \n                                              curr_pack.uc_adj, \n                                              size_uc());\n        return ad::boost::LogJCovInvTransformNode(uc_view, rows_c());\n    }\n\n    /**\n     * Initializes unconstrained values such that constrained (pos-def) matrix is identity.\n     * This is equivalent to simply setting the unconstrained values to 0,\n     * since diagonal is first exponentiated and the Cholesky decomposition of identity is identity.\n     */\n    template <class GenType, class ContDist>\n    void init(GenType&, ContDist&) {\n        uc_val_.setZero();\n    }\n\n    void activate_refcnt(size_t) const {}\n\n    var_t& get_c() { return util::get(c_val_); }\n    const var_t& get_c() const { return util::get(c_val_); }\n\n    /**\n     * Returns the dimension information for the viewers of unconstrained\n     * and constrained parameters.\n     */\n    constexpr size_t size_uc() const { return uc_val_.size(); }\n    constexpr size_t rows_uc() const { return uc_val_.rows(); }\n    constexpr size_t cols_uc() const { return 1; }\n    constexpr size_t size_c() const { return c_val_.size(); }\n    constexpr size_t rows_c() const { return c_val_.rows(); }\n    constexpr size_t cols_c() const { return c_val_.cols(); }\n\n    /**\n     * Returns the number of elements required to bind and compute \n     * unconstrained, constrained parameters and visit count.\n     */\n    constexpr size_t bind_size_uc() const { return size_uc(); }\n    constexpr size_t bind_size_c() const { return 2*size_c(); }\n    constexpr size_t bind_size_v() const { return 1; }\n\n    /**\n     * Binds unconstrained viewer to unconstrained region (viewed as a vector),\n     * constrained viewer to constrained region (viewed as a matrix),\n     * and internal visit count to visit count region.\n     */\n    template <class CurrPtrPack, class PtrPack>\n    void bind(const CurrPtrPack& curr_pack,\n              const PtrPack&) \n    {\n        util::bind(uc_val_, curr_pack.uc_val, rows_uc(), cols_uc());\n        util::bind(lower_, curr_pack.c_val, rows_c(), cols_c());\n        util::bind(c_val_, curr_pack.c_val + size_c(), rows_c(), cols_c());\n        util::bind(v_val_, curr_pack.v_val, 1, 1);\n    }\n\nprivate:\n    uc_view_t uc_val_;\n    view_t c_val_;\n    view_t lower_;  // temporary lower-triangular matrix\n    size_t* v_val_;\n};\n\n} // namespace constraint\n} // namespace expr\n\nconstexpr inline auto pos_def()\n{\n    return expr::constraint::PosDef();\n}\n\n} // namespace ppl\n", "meta": {"hexsha": "276a4860448ea1b88c50d20c0b52ca27bc927c73", "size": 9432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/expression/constraint/pos_def.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/expression/constraint/pos_def.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/expression/constraint/pos_def.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 38.1862348178, "max_line_length": 100, "alphanum_fraction": 0.6037955895, "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6761505951031237}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n\n#include <sophus/se3.hpp>\n\nusing namespace std;\nusing namespace Eigen;\nusing Sophus::SE3d;\nusing Sophus::SO3d;\n\n/************************************************\n  * \uc774 \ud504\ub85c\uadf8\ub7a8\uc740 \ud3ec\uc988 \uadf8\ub798\ud504 \ucd5c\uc801\ud654\ub97c \uc704\ud574 g2o \uc194\ubc84\ub97c \uc0ac\uc6a9\ud558\ub294 \ubc29\ubc95\uc744 \ubcf4\uc5ec\uc90d\ub2c8\ub2e4.\n  * sphere.g2o\ub294 \uc778\uc704\uc801\uc73c\ub85c \uc0dd\uc131\ub41c \ud3ec\uc988 \uadf8\ub798\ud504\uc774\ubbc0\ub85c \ucd5c\uc801\ud654\ud574 \ubcf4\uaca0\uc2b5\ub2c8\ub2e4.\n  * \uc804\uccb4 \uadf8\ub798\ud504\ub294 load \ud568\uc218\ub97c \ud1b5\ud574 \uc9c1\uc811 \uc77d\uc744 \uc218 \uc788\uc9c0\ub9cc \ub354 \uae4a\uc740 \uc774\ud574\ub97c \uc704\ud574 \uc77d\uae30 \ucf54\ub4dc\ub97c \uc9c1\uc811 \uad6c\ud604\ud569\ub2c8\ub2e4.\n  * \uc774 \uc139\uc158\uc5d0\uc11c\ub294 lie \ub300\uc218\ud559\uc744 \uc0ac\uc6a9\ud558\uc5ec \ud3ec\uc988 \uadf8\ub798\ud504\ub97c \ud45c\ud604\ud558\uba70 \ub178\ub4dc\uc640 \uac00\uc7a5\uc790\ub9ac\uc758 \ubc29\uc2dd\uc740 \uc0ac\uc6a9\uc790 \uc815\uc758\uc785\ub2c8\ub2e4.\n * **********************************************/\n\ntypedef Matrix<double, 6, 6> Matrix6d;\n\n// \uc8fc\uc5b4\uc9c4 \uc624\ub958\uc5d0 \ub300\ud55c J_R^{-1}\uc758 \uadfc\uc0ac\uac12 \ucc3e\uae30\nMatrix6d JRInv(const SE3d &e) {\n    Matrix6d J;\n    J.block(0, 0, 3, 3) = SO3d::hat(e.so3().log());\n    J.block(0, 3, 3, 3) = SO3d::hat(e.translation());\n    J.block(3, 0, 3, 3) = Matrix3d::Zero(3, 3);\n    J.block(3, 3, 3, 3) = SO3d::hat(e.so3().log());\n    // J = J * 0.5 + Matrix6d::Identity();\n    J = Matrix6d::Identity();    // try Identity if you want\n    return J;\n}\n\n// lie \ub300\uc218 edge\ntypedef Matrix<double, 6, 1> Vector6d;\n\nclass VertexSE3LieAlgebra : public g2o::BaseVertex<6, SE3d> {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\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        setEstimate(SE3d(\n            Quaterniond(data[6], data[3], data[4], data[5]),\n            Vector3d(data[0], data[1], data[2])\n        ));\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    virtual void setToOriginImpl() override {\n        _estimate = SE3d();\n    }\n\n    // \uc67c\ucabd \uacf1\ud558\uae30 \uc5c5\ub370\uc774\ud2b8\n    virtual void oplusImpl(const double *update) override {\n        Vector6d upd;\n        upd << update[0], update[1], update[2], update[3], update[4], update[5];\n        _estimate = SE3d::exp(upd) * _estimate;\n    }\n};\n\n// \ub450 lie \ub300\uc218 \ub178\ub4dc \uc0ac\uc774\uc758 edge\nclass EdgeSE3LieAlgebra : public g2o::BaseBinaryEdge<6, SE3d, VertexSE3LieAlgebra, VertexSE3LieAlgebra> {\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\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        Quaterniond q(data[6], data[3], data[4], data[5]);\n        q.normalize();\n        setMeasurement(SE3d(q, Vector3d(data[0], data[1], data[2])));\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        return true;\n    }\n\n    virtual bool write(ostream &os) const override {\n        VertexSE3LieAlgebra *v1 = static_cast<VertexSE3LieAlgebra *> (_vertices[0]);\n        VertexSE3LieAlgebra *v2 = static_cast<VertexSE3LieAlgebra *> (_vertices[1]);\n        os << v1->id() << \" \" << v2->id() << \" \";\n        SE3d 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 << endl;\n        return true;\n    }\n\n    // \uc624\ub958 \uacc4\uc0b0\uc740 \ucc45\uc758 \uc720\ub3c4\uc640 \uc77c\uce58\ud569\ub2c8\ub2e4.\n    virtual void computeError() override {\n        SE3d v1 = (static_cast<VertexSE3LieAlgebra *> (_vertices[0]))->estimate();\n        SE3d v2 = (static_cast<VertexSE3LieAlgebra *> (_vertices[1]))->estimate();\n        _error = (_measurement.inverse() * v1.inverse() * v2).log();\n    }\n\n    // \uc57c\ucf54\ube44\uc548 \uacc4\uc0b0\n    virtual void linearizeOplus() override {\n        SE3d v1 = (static_cast<VertexSE3LieAlgebra *> (_vertices[0]))->estimate();\n        SE3d v2 = (static_cast<VertexSE3LieAlgebra *> (_vertices[1]))->estimate();\n        Matrix6d J = JRInv(SE3d::exp(_error));\n        // J\ub97c I\ub85c \uadfc\uc0ac\ud558\ub824\uace0 \ud569\ub2c8\uae4c?\n        _jacobianOplusXi = -J * v2.inverse().Adj();\n        _jacobianOplusXj = J * v2.inverse().Adj();\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 \uc124\uc815\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 6>> BlockSolverType;\n    typedef g2o::LinearSolverEigen<BlockSolverType::PoseMatrixType> LinearSolverType;\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n    g2o::SparseOptimizer optimizer;     // \uadf8\ub798\ud504 \ubaa8\ub378\n    optimizer.setAlgorithm(solver);   // \uc194\ubc84 \uc124\uc815\n    optimizer.setVerbose(true);       // \ub514\ubc84\uadf8 \ucd9c\ub825 \ucf1c\uae30\n\n    int vertexCnt = 0, edgeCnt = 0; // \uc815\uc810\uacfc \ubaa8\uc11c\ub9ac\uc758 \uc218\n\n    vector<VertexSE3LieAlgebra *> vectices;\n    vector<EdgeSE3LieAlgebra *> edges;\n    while (!fin.eof()) {\n        string name;\n        fin >> name;\n        if (name == \"VERTEX_SE3:QUAT\") {\n            // 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            vectices.push_back(v);\n            if (index == 0)\n                v->setFixed(true);\n        } else if (name == \"EDGE_SE3:QUAT\") {\n            // SE3-SE3 edge\n            EdgeSE3LieAlgebra *e = new EdgeSE3LieAlgebra();\n            int idx1, idx2;     // \uc5f0\uacb0\ub41c \ub450 \uc815\uc810\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(30);\n\n    cout << \"saving optimization results ...\" << endl;\n\n    // \uc0ac\uc6a9\uc790 \uc815\uc758 \uc815\uc810\uc774 g2o\uc5d0 \ub4f1\ub85d\ub418\uc9c0 \uc54a\uace0 \uc0ac\uc6a9\ub418\uae30 \ub54c\ubb38\uc5d0 \uad6c\ud604\ud558\ub824\uba74 \uc5ec\uae30\uc5d0 \uc800\uc7a5\ud558\uc2ed\uc2dc\uc624.\n    // SE3 \uc815\uc810\uacfc \uac00\uc7a5\uc790\ub9ac\ub85c \uc704\uc7a5\ud558\uc5ec g2o_viewer\uac00 \uc778\uc2dd\ud560 \uc218 \uc788\ub3c4\ub85d \ud569\ub2c8\ub2e4.\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    return 0;\n}\n", "meta": {"hexsha": "f5da91dc4335e5adc85d4e322e350a4450e43195", "size": 7049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch10/pose_graph_g2o_lie_algebra.cpp", "max_stars_repo_name": "Refstop/VSLAM_Example", "max_stars_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "Refstop/VSLAM_Example", "max_issues_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "Refstop/VSLAM_Example", "max_forks_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_forks_repo_licenses": ["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.5666666667, "max_line_length": 108, "alphanum_fraction": 0.5518513264, "num_tokens": 2265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6761505910375424}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/MPRealSupport>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <iomanip>\n#include <iostream>\n\n#include \"gauss_hermite_quadrature.hpp\"\n#include \"spectral/mpfr/import_std_math.hpp\"\n\n//#include <quadmath.h>\n\nnamespace mp = boost::multiprecision;  // Reduce the typing a bit later...\n\nusing namespace mpfr;\n\ntypedef mp::mpfr_float_backend<100000> mfloat_t;\ntypedef mp::number<mfloat_t> mpfr_float_t;\n\nusing namespace std;\n\nvoid GaussHermiteQuadrature::init(int ndigits)\n{\n  mpreal::set_default_prec(ndigits);\n  typedef mpreal mfloat_t;\n  //  typedef double mfloat_t;\n  typedef Eigen::Matrix<mfloat_t, Eigen::Dynamic, Eigen::Dynamic> MatrixXmp;\n  MatrixXmp A(N, N);\n  A.fill(0);\n  for (int i = 0; i < N - 1; ++i) {\n    const double beta = ::math::sqrt(1.0 * (i + 1)) / ::math::sqrt(2.0);\n    A(i, i + 1) = beta;\n    A(i + 1, i) = beta;\n  }\n\n  Eigen::SelfAdjointEigenSolver<MatrixXmp> eigensolver;\n  // Eigen::EigenSolver<MatrixXmp> eigensolver;\n  eigensolver.compute(A, Eigen::ComputeEigenvectors);\n  const double pi = boost::math::constants::pi<double>();\n  const double m = ::math::sqrt(pi);\n  // compute weights\n  const auto V = eigensolver.eigenvectors();\n\n  if (V.rows() == 0) {\n    cerr << \"abort\";\n    exit(-1);\n  }\n  std::vector<double> weights(N);\n  for (int i = 0; i < N; ++i) {\n    // eigenvectors are normalized by eigen\n    weights[i] = (V(0, i) * V(0, i) * m).toDouble();\n  }\n\n  const auto w = eigensolver.eigenvalues();\n  std::vector<double> points(N);\n  for (int i = 0; i < N; ++i) {\n    points[i] = w(i).toDouble();\n  }\n\n  // sort\n  std::vector<std::pair<double, double> > pairs(N);\n  for (int i = 0; i < N; ++i) {\n    pairs[i] = std::make_pair(points[i], weights[i]);\n  }\n\n  std::sort(pairs.begin(), pairs.end());\n\n  for (int i = 0; i < N; ++i) {\n    pts_[i] = pairs[i].first;\n    wts_[i] = pairs[i].second;\n  }\n}\n", "meta": {"hexsha": "67fce6dd66000c14da9b29b385db90af22fac8e4", "size": 1992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectral/quadrature/gauss_hermite_quadrature.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "spectral/quadrature/gauss_hermite_quadrature.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "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": "spectral/quadrature/gauss_hermite_quadrature.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 26.56, "max_line_length": 76, "alphanum_fraction": 0.6460843373, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6761505869719607}}
{"text": "#pragma once\n\n#include <vector>\n#include <Eigen/Core>\n\nnamespace bold\n{\n  enum class HalfHull\n  {\n    Top,\n    Bottom\n  };\n\n  // TODO is it better to specify the side as a template parameter to compile away conditions?\n  // TODO below doesn't seem to work with ushort... is the problem being unsigned, or integral?\n\n  template<typename T>\n  class HalfHullBuilder\n  {\n    typedef Eigen::Matrix<T,2,1> Vector2;\n\n  public:\n    /** Calculates half of a convex hull along a line of points.\n     *\n     * Inputs are assumed to be ordered in increasing x direction, with no duplicate x values.\n     */\n    std::vector<Vector2> findHalfHull(std::vector<Vector2> const& input, HalfHull side)\n    {\n      int n = input.size(),\n          k = 0;\n\n      std::vector<Vector2> hull(n);\n\n      if (side == HalfHull::Bottom)\n      {\n        for (int i = 0; i < n; i++)\n        {\n          while (k >= 2 && cross(hull[k-2], hull[k-1], input[i]) <= 0)\n            k--;\n\n          hull[k++] = input[i];\n        }\n      }\n      else\n      {\n        for (int i = 0; i < n; i++)\n        {\n          while (k >= 2 && cross(hull[k-2], hull[k-1], input[i]) >= 0)\n            k--;\n\n          hull[k++] = input[i];\n        }\n      }\n\n      hull.resize(k);\n\n      return hull;\n    }\n\n  private:\n    static T cross(Vector2 const& O, Vector2 const& A, Vector2 const& B)\n    {\n      return (A.x() - O.x()) * (B.y() - O.y()) - (A.y() - O.y()) * (B.x() - O.x());\n    }\n  };\n}\n", "meta": {"hexsha": "c0077d3e790c5d4f9c2f3ebd2ae919e8af456672", "size": 1442, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/halfhullbuilder.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/halfhullbuilder.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/halfhullbuilder.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5223880597, "max_line_length": 95, "alphanum_fraction": 0.5152565881, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6761343948525972}}
{"text": "\n#include <NTL/lzz_pX.h>\n#include <helib/NumbTh.h>\n#include <helib/ArgMap.h>\n\nNTL_CLIENT\n\nvoid compute_a_vals(Vec<long>& a, long p, long e)\n// computes a[m] = a(m)/m! for m = p..(e-1)(p-1)+1,\n// as defined by Chen and Han.\n// a.length() is set to (e-1)(p-1)+2\n\n{\n   long p_to_e = power_long(p, e);\n   long p_to_2e = power_long(p, 2*e);\n\n   long len = (e-1)*(p-1)+2;\n\n   zz_pPush push(p_to_2e);\n\n   zz_pX x_plus_1_to_p = power(zz_pX(INIT_MONO, 1) + 1, p);\n   zz_pX denom = InvTrunc(x_plus_1_to_p - zz_pX(INIT_MONO, p), len);\n   zz_pX poly = MulTrunc(x_plus_1_to_p, denom, len);\n   poly *= p;\n\n   a.SetLength(len);\n\n   long m_fac = 1;\n   for (long m = 2; m < p; m++) {\n      m_fac = MulMod(m_fac, m, p_to_2e);\n   }\n\n   for (long m = p; m < len; m++) {\n      m_fac = MulMod(m_fac, m, p_to_2e);\n      long c = rep(coeff(poly, m));\n      long d = GCD(m_fac, p_to_2e);\n      if (d == 0 || d > p_to_e || c % d != 0) Error(\"cannot divide\");\n      long m_fac_deflated = (m_fac / d) % p_to_e;\n      long c_deflated = (c / d) % p_to_e;\n      a[m] = MulMod(c_deflated, InvMod(m_fac_deflated, p_to_e), p_to_e);\n   }\n\n}\n\nint main(int argc, char **argv)\n{\n   ArgMap amap;\n\n   long p = 2;\n   amap.arg(\"p\", p);\n\n   long e = 2;\n   amap.arg(\"e\", e);\n\n   amap.parse(argc, argv);\n\n   Vec<long> a;\n\n   compute_a_vals(a, p, e);\n\n   long p_to_e = power_long(p, e);\n   long len = (e-1)*(p-1)+2;\n\n   zz_pPush push(p_to_e);\n\n   zz_pX poly(0);\n   zz_pX term(1);\n   zz_pX X(INIT_MONO, 1);\n\n   poly = 0;\n   term = 1;\n\n   for (long m = 0; m < p; m++) {\n      term *= (X-m);\n   }\n\n   for (long m = p; m < len; m++) {\n      poly += term * a[m];\n      term *= (X-m);\n   }\n\n   cout << poly << \"\\n\";\n\n   for (long i = 0; i < 1000; i++) {\n      zz_p x;\n      random(x);\n      zz_p fx = eval(poly, x);\n      if (fx + (rep(x) % p) != x) Error(\"bad eval\");\n   }\n}\n", "meta": {"hexsha": "f3f9614e6cacd379bf968dd2c3c410bdd0223908", "size": 1824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/MagicPoly.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "misc/MagicPoly.cpp", "max_issues_repo_name": "felipeturing/HElib", "max_issues_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T09:26:24.000Z", "max_forks_repo_path": "misc/MagicPoly.cpp", "max_forks_repo_name": "felipeturing/HElib", "max_forks_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 20.043956044, "max_line_length": 72, "alphanum_fraction": 0.5285087719, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384732, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.6760462473589256}}
{"text": "#include <vector>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"gtest/gtest.h\"\n#include \"filtering.h\"\n#include \"hmm.h\"\n#include \"discrete_distribution.h\"\n\n#include \"hmm_example/hmm_matrices.h\"\n#include \"hmm_example/hmm_sequence.h\"\n\nusing namespace rtHMM;\nusing namespace std;\n\n\n/* TODO:\n *\n * The following things still need test cases:\n *\n *   - Forward algorithm with continuous distribution (like gaussian).\n *     Actually, this shouldn't be a problem if the distribution works properly\n *\n */\n\nTEST(filtering_test, test_discrete_emission)\n{\n    dense_vector prior{STATE_COUNT};\n    dense_matrix trans{STATE_COUNT, STATE_COUNT};\n    dense_matrix obs{STATE_COUNT, ALPHABET_SIZE};\n    prior << PRIOR;\n    trans << TRANSITION;\n    obs << OBSERVATION;\n\n    hmm model{prior, trans, obs};\n    filtering fltr{model};\n\n    size_t obs_seq[] = TEST_SEQUENCE;\n\n    double correct_fwd_vars[][STATE_COUNT] = FILTERING_RESULTS;\n\n    for (size_t j = 0; j < STATE_COUNT; ++j) {\n        double fwd_val = fltr.distribution()[j];\n        ASSERT_NEAR(correct_fwd_vars[0][j], fwd_val, 0.00001);\n    }\n\n    for (size_t i = 0; i < TEST_SEQUENCE_LENGTH; ++i) {\n        fltr.add_observation(obs_seq[i]);\n        for (size_t j = 0; j < STATE_COUNT; ++j) {\n            double fwd_val = fltr.distribution()[j];\n            ASSERT_NEAR(correct_fwd_vars[i + 1][j], fwd_val, 0.00001);\n        }\n    }\n\n    ASSERT_NEAR(exp(SEQUENCE_LOGPROB), fltr.sequence_probability(), 0.00001);\n    ASSERT_NEAR(SEQUENCE_LOGPROB, fltr.sequence_log_probability(), 0.00001);\n}\n", "meta": {"hexsha": "a9d76a593d232a3b9a3dceeaedffbb3a3ec078e4", "size": 1539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/filtering_test.cpp", "max_stars_repo_name": "fdlm/rtHMM", "max_stars_repo_head_hexsha": "11db9fe499bb85c6637dd582134be61c992397d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T21:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T06:08:02.000Z", "max_issues_repo_path": "test/filtering_test.cpp", "max_issues_repo_name": "fdlm/rtHMM", "max_issues_repo_head_hexsha": "11db9fe499bb85c6637dd582134be61c992397d7", "max_issues_repo_licenses": ["MIT"], "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/filtering_test.cpp", "max_forks_repo_name": "fdlm/rtHMM", "max_forks_repo_head_hexsha": "11db9fe499bb85c6637dd582134be61c992397d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-23T03:10:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T03:10:25.000Z", "avg_line_length": 27.0, "max_line_length": 79, "alphanum_fraction": 0.6796621183, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6759704853945228}}
{"text": "#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace client{\n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n\n  struct hundreds_ : qi::symbols<char, unsigned>{\n    hundreds_(){\n      add\n        (\"C\"    , 100)\n        (\"CC\"   , 200)\n        (\"CCC\"  , 300)\n        (\"CD\"   , 400)\n        (\"D\"    , 500)\n        (\"DC\"   , 600)\n        (\"DCC\"  , 700)\n        (\"DCCC\" , 800)\n        (\"CM\"   , 900)\n      ;\n    }\n  }hundreds;\n\n  struct tens_ : qi::symbols<char, unsigned>{\n    tens_(){\n      add\n        (\"X\"    , 10)\n        (\"XX\"   , 20)\n        (\"XXX\"  , 30)\n        (\"XL\"   , 40)\n        (\"L\"    , 50)\n        (\"LX\"   , 60)\n        (\"LXX\"  , 70)\n        (\"LXXX\" , 80)\n        (\"XC\"   , 90)\n      ;\n    }\n  }tens;\n\n  struct ones_ : qi::symbols<char, unsigned>{\n    ones_(){\n      add\n        (\"I\"    , 1)\n        (\"II\"   , 2)\n        (\"III\"  , 3)\n        (\"IV\"   , 4)\n        (\"V\"    , 5)\n        (\"VI\"   , 6)\n        (\"VII\"  , 7)\n        (\"VIII\" , 8)\n        (\"IX\"   , 9)\n      ;\n    }\n  }ones;\n\n  template <typename Iterator>\n    struct roman : qi::grammar<Iterator, unsigned()>{\n      roman() : roman::base_type(start){\n        using qi::eps;\n        using qi::lit;\n        using qi::_val;\n        using qi::_1;\n        using ascii::char_;\n\n        start = eps     [_val = 0] >>\n          (\n            +lit('M')   [_val += 1000]\n            || hundreds [_val += _1]\n            || tens     [_val += _1]\n            || ones     [_val += _1]\n          )\n        ;\n      }\n\n      qi::rule<Iterator, unsigned()> start;\n    };\n}\n\nint main(){\n  typedef std::string::const_iterator iterator_type;\n  typedef client::roman<iterator_type> roman;\n\n  roman roman_parser;\n\n  std::string str;\n  unsigned result;\n  while(std::getline(std::cin, str)){\n    if(str.empty() || str[0] == 'q' || str[0] == 'Q')\n      break;\n\n    std::string::const_iterator iter = str.begin();\n    std::string::const_iterator end = str.end();\n    bool r = parse(iter, end, roman_parser, result);\n\n    if(r && iter == end){\n      std::cout << \"Parsing succeeded\\n\";\n      std::cout << \"result = \" << result << std::endl;\n    }\n    else{\n      std::string rest(iter, end);\n      std::cout << \"Parsing fail\\n\";\n      std::cout << \"stopped at: \\\": \" << rest << \"\\\"\\n\";\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "faeb9f7a92bc9b9aa7fb898b2cf74a01c90014b8", "size": 2417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/qi/roman.cpp", "max_stars_repo_name": "2858199552/parser", "max_stars_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T12:37:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T17:32:08.000Z", "max_issues_repo_path": "examples/qi/roman.cpp", "max_issues_repo_name": "2858199552/parser", "max_issues_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_issues_repo_licenses": ["MIT"], "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/qi/roman.cpp", "max_forks_repo_name": "2858199552/parser", "max_forks_repo_head_hexsha": "da05013dbc080ade3eec6af7bbfa017c3e0b4b9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T05:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T05:20:41.000Z", "avg_line_length": 21.5803571429, "max_line_length": 56, "alphanum_fraction": 0.4555233761, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6758984620004382}}
{"text": "// Copyright (c) 2020 Marcus Valtonen \u00d6rnhag\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#include \"roots.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nnamespace HomLib {\n    Eigen::VectorXcd roots(const Eigen::VectorXd& coeffs) {\n        // Create companion matrix\n        int N = coeffs.size() - 1;\n        Eigen::MatrixXd companion_mat(N, N);\n        companion_mat.setZero();\n\n        for (int i = 0; i < N; i++) {\n             for (int j = 0; j < N; j++) {\n                if (i == j + 1) {\n                    companion_mat(i, j) = 1.0;\n                }\n                if (j == N - 1) {\n                    companion_mat(i, j) = -coeffs[N - i] / coeffs[0];\n                }\n            }\n        }\n\n        // Compute roots via eigenvalues of companion matrix\n        Eigen::VectorXcd eigvals = companion_mat.eigenvalues();\n\n        return eigvals;\n    }\n}  // namespace HomLib\n", "meta": {"hexsha": "27c61281b8f77786676affedca5807a32c9b3b18", "size": 1928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helpers/roots.cpp", "max_stars_repo_name": "marcusvaltonen/HomLib", "max_stars_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T18:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:37:37.000Z", "max_issues_repo_path": "src/helpers/roots.cpp", "max_issues_repo_name": "marcusvaltonen/HomLib", "max_issues_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_issues_repo_licenses": ["MIT"], "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/helpers/roots.cpp", "max_forks_repo_name": "marcusvaltonen/HomLib", "max_forks_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T19:59:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T19:59:02.000Z", "avg_line_length": 39.3469387755, "max_line_length": 81, "alphanum_fraction": 0.6488589212, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6757442287737336}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// tutorial1.cc\n//                     \t\t  Pressio\n//                             Copyright 2019\n//    National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#include \"pressio/solvers_linear.hpp\"\n#include \"pressio/solvers_nonlinear.hpp\"\n#include <Eigen/Core>\n\nstruct MyRosenbrockSystem\n{\n  using scalar_type = double;\n  using state_type  = Eigen::VectorXd;\n  using residual_type = state_type;\n  using jacobian_type = Eigen::MatrixXd;\n\n  residual_type createResidual() const{ return residual_type(6);   }\n  jacobian_type createJacobian() const{ return jacobian_type(6, 4);}\n\n  void residual(const state_type& x, residual_type & res) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    const auto & x4 = x(3);\n    res(0) = 10.*(x4 - x3*x3);\n    res(1) = 10.*(x3 - x2*x2);\n    res(2) = 10.*(x2 - x1*x1);\n    res(3) = (1.-x1);\n    res(4) = (1.-x2);\n    res(5) = (1.-x3);\n  }\n\n  void jacobian(const state_type & x, jacobian_type & JJ) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    JJ.setZero();\n\n    JJ(0,2) = -20.*x3;\n    JJ(0,3) = 10.;\n    JJ(1,1) = -20.*x2;\n    JJ(1,2) = 10.;\n    JJ(2,0) = -20.*x1;\n    JJ(2,1) = 10.;\n    JJ(3,0) = -1.;\n    JJ(4,1) = -1.;\n    JJ(5,2) = -1.;\n  }\n};\n\nint main()\n{\n  namespace plog   = pressio::log;\n  namespace pls    = pressio::linearsolvers;\n  namespace pnonls = pressio::nonlinearsolvers;\n  plog::initialize(pressio::logto::terminal);\n  plog::setVerbosity({plog::level::info});\n\n  using problem_t = MyRosenbrockSystem;\n  problem_t problem;\n\n  using state_t   = typename problem_t::state_type;\n  state_t x(4);\n  x(0) = -0.05; x(1) = 1.1; x(2) = 1.2; x(3) = 1.5;\n\n  using hessian_t = Eigen::MatrixXd;\n  using lin_tag      = pls::direct::HouseholderQR;\n  using lin_solver_t = pls::Solver<lin_tag, hessian_t>;\n  lin_solver_t linSolver;\n\n  auto gnSolver = pnonls::create_gauss_newton(problem, x, linSolver);\n  gnSolver.setTolerance(1e-5);\n  gnSolver.solve(problem, x);\n\n  // check solution\n  std::cout << \"Computed solution: \\n \"\n            << \"[\" << x(0) << \" \" << x(1) << \" \" << x(2) << \" \" << x(3) << \" \" << \"] \\n\"\n            << \"Expected solution: \\n \"\n            << \"[1.0000000156741, 0.99999999912477, 0.99999999651993, 0.99999998889888]\"\n            << std::endl;\n\n  plog::finalize();\n  return 0;\n}\n", "meta": {"hexsha": "0470e6a3c588f8949a2174f9c6bdd6a7454322cc", "size": 4285, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorials/nonlinsolvers_gn_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_gn_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_gn_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": 32.9615384615, "max_line_length": 88, "alphanum_fraction": 0.6354725788, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6757442232714905}}
{"text": "// Copyright (c) 2020 CS126SP20. All rights reserved.\n\n#define CATCH_CONFIG_MAIN\n\n#include <catch2/catch.hpp>\n#include <cinder/Rand.h>\n#include <Linear Algebra/computations.h>\n#include <Eigen/Dense>\n\n\n\nTEST_CASE(\"Random sanity test\", \"[random]\") {\n  const float random = cinder::randFloat();\n  REQUIRE(0. <= random);\n  REQUIRE(random <= 1.);\n}\n\nTEST_CASE(\"Computation tests\") {\n    Eigen::Matrix3d test_mat;\n    test_mat << 1, 2, 3,\n            4, 5, 6,\n            7, 8, 9;\n    Eigen::Matrix3d test_mat2;\n    test_mat2 << 1, 2, 3,\n            4, 5, 6,\n            7, 8, 9;\n    std::stringstream ss;\n    std::stringstream os;\n\n    SECTION(\"RREF\") {\n        REQUIRE(Computations::ComputeRREF(test_mat).size() == test_mat.size());\n    }\n    SECTION(\"Permutations\") {\n        REQUIRE(Computations::ComputePermutationMatrix(test_mat).size() == test_mat.size());\n    }\n    SECTION(\"Multiplication\") {\n        REQUIRE(Computations::ComputeDotProduct(test_mat, test_mat2, 3) == 285);\n    }\n    SECTION(\"Determinant\") {\n        REQUIRE(Computations::ComputeDeterminant(test_mat) == 0);\n    }\n    SECTION(\"Matrix Content\") {\n        ss << test_mat;\n        std::string str = \"1 2 3\\n\"\n                          \"4 5 6\\n\"\n                          \"7 8 9\";\n        REQUIRE(ss.str() == str);\n    }\n    SECTION(\"Multiplication Size\") {\n        REQUIRE(Computations::ComputeMultiply(test_mat, test_mat2).size() == 9);\n    }\n}", "meta": {"hexsha": "4700bf83aee2840752979fdf1593f187029dac22", "size": 1412, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test.cc", "max_stars_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_stars_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test.cc", "max_issues_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_issues_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test.cc", "max_forks_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_forks_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_forks_repo_licenses": ["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": 92, "alphanum_fraction": 0.5814447592, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.675705791326219}}
{"text": "#include <fstream>\n\n#include <boost/graph/graph_traits.hpp>\n#include <CGAL/property_map.h>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/boost/graph/graph_traits_Linear_cell_complex_for_combinatorial_map.h>\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef Kernel::Point_3                Point;\ntypedef Kernel::Vector_3               Vector;\n\ntypedef CGAL::Linear_cell_complex_traits<3, Kernel> LCC_traits;\ntypedef CGAL::Linear_cell_complex_for_bgl_combinatorial_map_helper\n          <2, 3, LCC_traits>::type LCC;\n\ntemplate<typename HalfedgeGraph, \n         typename PointMap, \n         typename NormalMap>\nvoid calculate_face_normals(const HalfedgeGraph& g, \n                            PointMap pm, \n                            NormalMap nm) \n{\n  typedef boost::graph_traits<HalfedgeGraph> GraphTraits;\n  typedef typename GraphTraits::face_iterator face_iterator;\n  typedef typename GraphTraits::halfedge_descriptor halfedge_descriptor;\n  typedef typename boost::property_traits<PointMap>::value_type point;\n  typedef typename boost::property_traits<NormalMap>::value_type normal;\n\n  face_iterator fb, fe;\n  for(boost::tie(fb, fe) = faces(g); fb != fe; ++fb)\n  {\n    halfedge_descriptor edg = halfedge(*fb, g);\n    halfedge_descriptor edgb = edg;\n\n    point p0 = pm[target(edg, g)];\n    edg = next(edg, g);\n    point p1 = pm[target(edg, g)];\n    edg = next(edg, g);\n    point p2 = pm[target(edg, g)];\n    edg = next(edg, g);\n      \n    if(edg == edgb) {\n      // triangle\n      nm[*fb] = CGAL::unit_normal(p1, p2, p0);\n    } else {\n      // not a triangle\n      normal n(CGAL::NULL_VECTOR);\n\n      do {\n        n = n + CGAL::normal(p1, p2, p0);\n        p0 = p1;\n        p1 = p2;\n        \n        edg = next(edg, g);\n        p2 = pm[target(edg, g)];\n      } while(edg != edgb);\n      \n      nm[*fb] = n / CGAL::sqrt(n.squared_length());\n    }\n  }\n}\n\nint main(int argc, char** argv)\n{\n  typedef boost::property_map<LCC, CGAL::face_index_t>::const_type\n                 Face_index_map;\n\n  LCC lcc;\n  CGAL::read_off((argc>1)?argv[1]:\"cube.off\", lcc);\n  \n  // Ad hoc property_map to store normals. Face_index_map is used to\n  // map face_descriptors to a contiguous range of indices. See\n  // http://www.boost.org/libs/property_map/doc/vector_property_map.html\n  // for details.\n  boost::vector_property_map<Vector, Face_index_map> \n    normals(get(CGAL::face_index, lcc));\n\n  calculate_face_normals(\n    lcc // Graph\n    , get(CGAL::vertex_point, lcc) // map from vertex_descriptor to point\n    , normals // map from face_descriptor to Vector_3\n    );\n\n  std::cout << \"Normals\" << std::endl;\n  for(LCC::Attribute_range<2>::type::iterator it=lcc.attributes<2>().begin();\n      it!=lcc.attributes<2>().end(); ++it)\n  { \n    // Facet_iterator is a face_descriptor, so we can use it as the\n    // key here\n    std::cout << normals[it] << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f66b35526fa8e2d15408b572bd2ba11acc582d5b", "size": 2873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/BGL_LCC/normals_lcc.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/BGL_LCC/normals_lcc.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/BGL_LCC/normals_lcc.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": 29.9270833333, "max_line_length": 84, "alphanum_fraction": 0.6435781413, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6757057725669334}}
{"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 <array>\n#include <Eigen/Core>\n#include \"custom_data_types.hpp\"\n#include \"pressio/ops.hpp\"\n\nstruct MyRosenbrockSystem\n{\n  using scalar_type   = double;\n  using state_type    = Eigen::VectorXd;\n  using residual_type = CustomVector<scalar_type>;\n  using jacobian_type = CustomMatrix<scalar_type>;\n\n  residual_type createResidual() const{ return residual_type(6);   }\n  jacobian_type createJacobian() const{ return jacobian_type(6, 4);}\n\n  void residual(const state_type& x, residual_type & res) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    const auto & x4 = x(3);\n    res(0) = 10.*(x4 - x3*x3);\n    res(1) = 10.*(x3 - x2*x2);\n    res(2) = 10.*(x2 - x1*x1);\n    res(3) = (1.-x1);\n    res(4) = (1.-x2);\n    res(5) = (1.-x3);\n  }\n\n  void jacobian(const state_type & x, jacobian_type & JJ) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    JJ.fill(0.);\n\n    JJ(0,2) = -20.*x3;\n    JJ(0,3) = 10.;\n    JJ(1,1) = -20.*x2;\n    JJ(1,2) = 10.;\n    JJ(2,0) = -20.*x1;\n    JJ(2,1) = 10.;\n    JJ(3,0) = -1.;\n    JJ(4,1) = -1.;\n    JJ(5,2) = -1.;\n  }\n};\n\nnamespace pressio{\ntemplate<class T> struct Traits<CustomVector<T>>{\n  using scalar_type = T;\n};\n\ntemplate<class T> struct Traits<CustomMatrix<T>>{\n  using scalar_type = T;\n};\n\nnamespace ops{\ntemplate<class T>\nCustomVector<T> clone(const CustomVector<T> & src){ return src; }\n\ntemplate<class T>\nCustomMatrix<T> clone(const CustomMatrix<T> & src){ return src; }\n\ntemplate<class T>\nvoid set_zero(CustomVector<T> & o){ o.fill(0); }\n\ntemplate<class T>\nvoid set_zero(CustomMatrix<T> & o){ o.fill(0); }\n\ntemplate<class T>\nT norm2(const CustomVector<T> & v)\n{\n  T norm{0};\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    norm += v(i)*v(i);\n  }\n  return std::sqrt(norm);\n}\n\ntemplate<class HessianType, class T>\nvoid product(pressio::transpose, pressio::nontranspose,\n       const T alpha,\n       const CustomMatrix<T> & A,\n       const T beta,\n       HessianType & H)\n{\n  for (std::size_t i=0; i<A.extent(1); ++i){\n    for (std::size_t j=0; j<A.extent(1); ++j)\n    {\n      H(i,j) *= beta;\n      for (std::size_t k=0; k<A.extent(0); ++k){\n        H(i,j) += alpha * A(k,i) * A(k,j);\n      }\n    }\n  }\n}\n\ntemplate<class GradientType, class T>\nvoid product(pressio::transpose,\n       const T alpha,\n       const CustomMatrix<T> & A,\n       const CustomVector<T> & b,\n       const T beta,\n       GradientType & g)\n{\n  for (std::size_t i=0; i<g.rows(); ++i){\n    g(i) *= beta;\n    for (std::size_t k=0; k<A.extent(0); ++k){\n      g(i) += alpha * A(k,i) * b(k);\n    }\n  }\n}\n\ntemplate<class HessianType, class T>\nHessianType product(pressio::transpose, pressio::nontranspose,\n                    T alpha,\n                    const CustomMatrix<T> & A)\n{\n  HessianType H(A.extent(1), A.extent(1));\n  product(pressio::transpose(), pressio::nontranspose(), alpha, A, (T)0, H);\n  return H;\n}\n\ntemplate<class T>\nvoid update(CustomVector<T> & v, T a, const CustomVector<T> & v1, T b)\n{\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    v(i) = v(i)*a + b*v1(i);\n  }\n}\n\ntemplate<class T>\nvoid scale(CustomVector<T> & v, T factor){\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    v(i) = v(i)*factor;\n  }\n}\n}}//end namespace pressio::ops\n\n\n#include \"pressio/solvers_linear.hpp\"\n#include \"pressio/solvers_nonlinear.hpp\"\n\nint main()\n{\n  namespace plog   = pressio::log;\n  namespace pls    = pressio::linearsolvers;\n  namespace pnonls = pressio::nonlinearsolvers;\n  plog::initialize(pressio::logto::terminal);\n  plog::setVerbosity({plog::level::info});\n\n  using problem_t = MyRosenbrockSystem;\n  problem_t problem;\n\n  using state_t   = Eigen::VectorXd;\n  state_t x(4);\n  x[0] = -0.05; x[1] = 1.1; x[2] = 1.2; x[3] = 1.5;\n\n  using hessian_t    = Eigen::MatrixXd;\n  using lin_tag      = pls::direct::HouseholderQR;\n  using lin_solver_t = pls::Solver<lin_tag, hessian_t>;\n  lin_solver_t linSolver;\n\n  auto gnSolver = pnonls::create_gauss_newton(problem, x, linSolver);\n  gnSolver.setTolerance(1e-5);\n  gnSolver.solve(problem, x);\n\n  // check solution\n  std::cout << \"Computed solution: \\n \"\n            << \"[\" << x(0) << \" \" << x(1) << \" \" << x(2) << \" \" << x(3) << \" \" << \"] \\n\"\n            << \"Expected solution: \\n \"\n            << \"[1.0000000156741, 0.99999999912477, 0.99999999651993, 0.99999998889888]\"\n            << std::endl;\n\n  plog::finalize();\n  return 0;\n}\n", "meta": {"hexsha": "6c40f78beafda1f936fc751ae062f7b10edc9d9a", "size": 6494, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorials/nonlinsolvers_gn_2.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_gn_2.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_gn_2.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": 28.6079295154, "max_line_length": 88, "alphanum_fraction": 0.622420696, "num_tokens": 1888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6756888346746918}}
{"text": "#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n#include <utils_typedef.h>\n#include <utils/math.h>\n#include <cpuext/sse2.h>\n\n\nconstexpr bool consteval_throw_if_fails( auto x ) { throw; return false; }\n#define CONSTEXPR_TEST( a ) \\\n  if( !(a) ) throw \n    //return consteval_throw_if_fails(a)\n\nusing traits_list = boost::mpl::list<float,double,int8_t,int16_t,int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t>;\nusing float_list = boost::mpl::list<float,double>;\n//-----------------------------------------------------------------------------------------------------\ntemplate<typename value_type>\nconsteval auto test_utils_math_abs()\n  {\n  CONSTEXPR_TEST( math::abs<value_type>(0) == 0 );\n  CONSTEXPR_TEST( math::abs<value_type>(1) == 1 );\n  CONSTEXPR_TEST( math::abs(std::numeric_limits<value_type>::max()) == std::numeric_limits<value_type>::max() );\n  \n  if constexpr (std::is_signed_v<value_type> )\n    {\n    CONSTEXPR_TEST( math::abs(-(std::numeric_limits<value_type>::max()-1)) == std::numeric_limits<value_type>::max()-1);\n    CONSTEXPR_TEST( math::abs<value_type>(-0) == 0 );\n    CONSTEXPR_TEST( math::abs<value_type>(-1) == 1 );\n    }\n\n  return true;\n  }\n  \nBOOST_AUTO_TEST_CASE_TEMPLATE( utils_math_abs, value_type, traits_list )\n  {\n  constexpr auto test_result(test_utils_math_abs<value_type>());\n  static_assert(test_result);\n  BOOST_TEST(test_result);\n  }\n//-----------------------------------------------------------------------------------------------------\nconsteval auto test_utils_math_bits_reverse()\n  {\n    {\n    uint8_t val = 0b10100010;\n    uint8_t exp = 0b01000101;\n    uint8_t res =math::reverse_bits( val );\n    CONSTEXPR_TEST( res == exp );\n    }\n    {\n    uint8_t val = 0b10000000;\n    uint8_t exp = 0b00000001;\n    uint8_t res =math::reverse_bits( val );\n    CONSTEXPR_TEST( res == exp );\n    }\n    {\n    uint8_t val = 0b10100001;\n    uint8_t exp = 0b10000101;\n    uint8_t res =math::reverse_bits( val );\n    CONSTEXPR_TEST( res == exp );\n    }\n    {\n    uint8_t val = 0b00000000;\n    uint8_t exp = 0b00000000;\n    uint8_t res =math::reverse_bits( val );\n    CONSTEXPR_TEST( res == exp );\n    }\n    {\n    uint8_t val = 0b11111111;\n    uint8_t exp = 0b11111111;\n    uint8_t res =math::reverse_bits( val );\n    CONSTEXPR_TEST( res == exp );\n    }\n  return true;\n  }\n  \nBOOST_AUTO_TEST_CASE( utils_math_bits_reverse)\n  {\n  constexpr auto test_result(test_utils_math_bits_reverse());\n  static_assert(test_result);\n  BOOST_TEST(test_result);\n  }\n\nusing sse2::m128d_t;\n//-----------------------------------------------------------------------------------------------------\n#if !defined(__clang__)\n#define outcome_constexpr constexpr\n#else\n#define outcome_constexpr const\n#endif\n//-----------------------------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE( cpuext_sse2_haddpd)\n  {\n    {\n    outcome_constexpr m128d_t cnst_res = sse2::hadd_pd( m128d_t{} , m128d_t{} );\n    m128d_t const rtres = _mm_hadd_pd( m128d_t{} , m128d_t{} );\n    BOOST_TEST( cnst_res[0] == rtres[0] );\n    BOOST_TEST( cnst_res[1] == rtres[1] );\n    }\n    {\n    double constexpr x0 = 10.1234;double constexpr y0 = -10.791234;\n    double constexpr x1 = 20.41234;double constexpr y1 = 40.61234;\n    \n    outcome_constexpr m128d_t cnst_res = sse2::hadd_pd( m128d_t{x0,x1} , m128d_t{y0,y1} );\n    m128d_t const rtres = _mm_hadd_pd( m128d_t{x0,x1} , m128d_t{y0,y1} );\n    BOOST_TEST( cnst_res[0] == rtres[0] );\n    BOOST_TEST( cnst_res[1] == rtres[1] );\n    }\n  }\n//-----------------------------------------------------------------------------------------------------\ntemplate<typename value_type>\nconsteval auto test_math_consteval_sqrt()\n  {\n    {\n    constexpr value_type sqrt_ce = math::consteval_sqrt<value_type>(value_type(0)); //38.1635927291968\n    CONSTEXPR_TEST( sqrt_ce < value_type(0.00001) );\n    }\n    {\n    constexpr value_type expected = value_type(1.4142135623731);\n    constexpr value_type sqrt_ce = math::consteval_sqrt<value_type>(2); //1.4142135623731\n    CONSTEXPR_TEST( math::abs<value_type>(sqrt_ce - expected) < value_type(0.00001) );\n    }\n    {\n    constexpr value_type expected = value_type(38.1635927291968);\n    constexpr value_type sqrt_ce = math::consteval_sqrt<value_type>(value_type(1456.45981)); //38.1635927291968\n    CONSTEXPR_TEST( math::abs<value_type>(sqrt_ce - expected) < value_type(0.00001) );\n    }\n    \n  return true;\n  }\n  \nBOOST_AUTO_TEST_CASE_TEMPLATE( math_consteval_sqrt, value_type, float_list)\n  {\n  constexpr auto test_result(test_math_consteval_sqrt<value_type>());\n  static_assert(test_result);\n  BOOST_TEST(test_result);\n  }\n\n//-----------------------------------------------------------------------------------------------------\ntemplate<typename value_type>\nconsteval auto test_math_consteval_floor()\n  {\n    {\n    constexpr value_type expected = 0;\n    constexpr value_type result = math::floor<value_type>(value_type(0.00000043821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 0;\n    constexpr value_type result = math::floor<value_type>(value_type(0.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 1;\n    constexpr value_type result = math::floor<value_type>(value_type(1.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 1999999;\n    constexpr value_type result = math::floor<value_type>(value_type(1999999.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = -2000000;\n    constexpr value_type result = math::floor<value_type>(value_type(-1999999.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = -1;\n    constexpr value_type result = math::floor<value_type>(value_type(-0.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = -1;\n    constexpr value_type result = math::floor<value_type>(value_type(-0.0000043821));\n    CONSTEXPR_TEST( result == expected );\n    }\n  return true;\n  }\n  \nBOOST_AUTO_TEST_CASE_TEMPLATE( math_consteval_floor, value_type, float_list)\n  {\n  constexpr auto test_result(test_math_consteval_floor<value_type>());\n  static_assert(test_result);\n  BOOST_TEST(test_result);\n  }\n//-----------------------------------------------------------------------------------------------------\ntemplate<typename value_type>\nconsteval auto test_math_consteval_ceil()\n  {\n    {\n    constexpr value_type expected = 1;\n    constexpr value_type result = math::ceil<value_type>(value_type(0.00000043821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 1;\n    constexpr value_type result = math::ceil<value_type>(value_type(0.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 2;\n    constexpr value_type result = math::ceil<value_type>(value_type(1.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 2000000;\n    constexpr value_type result = math::ceil<value_type>(value_type(1999999.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = -1999999;\n    constexpr value_type result = math::ceil<value_type>(value_type(-1999999.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 0;\n    constexpr value_type result = math::ceil<value_type>(value_type(-0.43821));\n    CONSTEXPR_TEST( result == expected );\n    }\n    {\n    constexpr value_type expected = 0;\n    constexpr value_type result = math::ceil<value_type>(value_type(-0.0000043821));\n    CONSTEXPR_TEST( result == expected );\n    }\n  return true;\n  }\n  \nBOOST_AUTO_TEST_CASE_TEMPLATE( math_consteval_ceil, value_type, float_list)\n  {\n  constexpr auto test_result(test_math_consteval_ceil<value_type>());\n  static_assert(test_result);\n  BOOST_TEST(test_result);\n  }\n", "meta": {"hexsha": "f65ea6c6a5ff6bd50ed24df86e67fc7088fdabc8", "size": 8017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "unit_tests/math_ut.cc", "max_stars_repo_name": "arturbac/small_vectors", "max_stars_repo_head_hexsha": "9e1f72e3683fb44d65b9454757348ec5221bf376", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-19T21:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T21:37:14.000Z", "max_issues_repo_path": "unit_tests/math_ut.cc", "max_issues_repo_name": "arturbac/small_vectors", "max_issues_repo_head_hexsha": "9e1f72e3683fb44d65b9454757348ec5221bf376", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/math_ut.cc", "max_forks_repo_name": "arturbac/small_vectors", "max_forks_repo_head_hexsha": "9e1f72e3683fb44d65b9454757348ec5221bf376", "max_forks_repo_licenses": ["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.114893617, "max_line_length": 122, "alphanum_fraction": 0.6331545466, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6756888254440828}}
{"text": "#include <string>\r\n#include <vector>\r\n#include <armadillo>\r\n#include <iostream>\r\n#include <math.h>\r\n#include <random>\r\n#include \"ppgFilter.h\"\r\n\r\nusing namespace std;\r\n\r\n#define PI 3.14159265\r\n#define videofre 50\r\n#define signallength 10\r\n\r\narma::vec signalGenerator(float fre)\r\n{\r\n\tvector<float> signal;\r\n\tarma::vec transSignal(videofre*signallength, arma::fill::zeros);\r\n\tfor (int i = 0; i < videofre*signallength; i++)\r\n\t{\r\n\t\ttransSignal[i] = (sin(2 * PI * fre *i / videofre));\r\n\t}\r\n\t\r\n\treturn transSignal;\r\n}\r\n\r\nbool findPeaks_Test(arma::vec signal, int count, float fre)\r\n{\r\n\tFilter *testFilter = new Filter(videofre*signallength);\r\n\r\n\tvector<int> indMax(testFilter->findPeaks(signal, count));\r\n\tvector<int> signal_period;\r\n\tfor (int i = 1; i < indMax.size(); i++)\r\n\t{\r\n\t\tsignal_period.push_back(indMax[i] - indMax[i - 1]);\r\n\t}\r\n\tbool result = true;\r\n\tfor (int j = 1; j < signal_period.size(); j++)\r\n\t{\r\n\t\tif (abs((videofre / fre) - signal_period[j]) > 1)\r\n\t\t{\r\n\t\t\tresult = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nint main()\r\n{\r\n\tfloat fre;\r\n\tint pass = 0;\r\n\tint fail = 0;\r\n\tint total = 1000;\r\n\tstd::default_random_engine e;\r\n\te.seed(time(0));\r\n\tuniform_real_distribution<float> u(1, 2);\r\n\tfor (int i = 0; i < total; i++)\r\n\t{\r\n\t\tfre = u(e);\r\n\r\n\t\tarma::vec testSignal(signalGenerator(fre));\r\n\t\tbool test = findPeaks_Test(testSignal, videofre*signallength, fre);\r\n\t\tif (test == 1) {\r\n\t\t\tcout << \"Test \" << i+1 << \" pass!\" << endl;\r\n\t\t\tpass++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tcout << \"Test \" << i + 1 << \" fail!\" << endl;\r\n\t\t\tfail++;\r\n\t\t}\r\n\t}\r\n\r\n\tcout << endl << \"Special Test1:\";\r\n\tarma::vec specialSignal(videofre*signallength, arma::fill::ones);\r\n\r\n\tbool test1 = findPeaks_Test(specialSignal, videofre*signallength, 0);\r\n\tif (test1 == 1) {\r\n\t\tcout << \" pass!\" << endl;\r\n\t\tpass++;\r\n\t}\r\n\telse {\r\n\t\tcout << \" fail!\" << endl;\r\n\t\tfail++;\r\n\t}\r\n\r\n\tfor (int i = videofre * signallength / 2; i < videofre*signallength; i++) {\r\n\t\tspecialSignal[i] += i;\r\n\t}\r\n\tcout << \"Special Test2:\";\r\n\tbool test2 = findPeaks_Test(specialSignal, videofre*signallength, 0);\r\n\tif (test2 == 1) {\r\n\t\tcout << \" pass!\" << endl;\r\n\t\tpass++;\r\n\t}\r\n\telse {\r\n\t\tcout << \" fail!\" << endl;\r\n\t\tfail++;\r\n\t}\r\n\r\n\tfor (int i = 0; i < videofre*signallength/2; i++) {\r\n\t\tspecialSignal[i] += videofre*signallength/2-i;\r\n\t}\r\n\tcout << \"Special Test3:\";\r\n\tbool test3 = findPeaks_Test(specialSignal, videofre*signallength, 0);\r\n\tif (test3 == 1) {\r\n\t\tcout << \" pass!\" << endl;\r\n\t\tpass++;\r\n\t}\r\n\telse {\r\n\t\tcout << \" fail!\" << endl;\r\n\t\tfail++;\r\n\t}\r\n\t\r\n\tcout << \"----------\" << endl;\r\n\tcout << \"Total: \" << pass << \"/\" << total+3 << \" passed!\" << endl;\r\n\t\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "17be06ff213b70e5bedf764686083415cfcc42a3", "size": 2634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/findpeakTest.cpp", "max_stars_repo_name": "ppghou/ppgdetector", "max_stars_repo_head_hexsha": "f43d00e736e1ca2db191a3501cc72a050f65fcd2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-08T16:15:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T16:46:48.000Z", "max_issues_repo_path": "src/test/findpeakTest.cpp", "max_issues_repo_name": "SuXY15/ppgdetector", "max_issues_repo_head_hexsha": "093ffb89a9a95d2d36ac8cc20770b898995addcd", "max_issues_repo_licenses": ["MIT"], "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/findpeakTest.cpp", "max_forks_repo_name": "SuXY15/ppgdetector", "max_forks_repo_head_hexsha": "093ffb89a9a95d2d36ac8cc20770b898995addcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-15T16:55:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-17T07:34:18.000Z", "avg_line_length": 21.7685950413, "max_line_length": 77, "alphanum_fraction": 0.5808656036, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6756172550338294}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include <cmath>\n#include <map>\n#include <utility>\n#include \"ear/helpers/assert.hpp\"\n\nnamespace ear {\n  namespace hoa {\n\n    /// Associated Legendre function P_n^m(x), omitting the (-1)^m\n    /// Condon-Shortley phase term.\n    inline double Alegendre(int n, int m, double x) {\n      return std::pow(-1.0, m) * boost::math::legendre_p(n, m, x);\n    }\n\n    /// Ambisonics Channel Number for order n and degree m.\n    inline int to_acn(int n, int m) { return n * n + n + m; }\n\n    /// Get the order n and degree m from a given Ambisonics Channel Number.\n    inline std::pair<int, int> from_acn(int acn) {\n      int n = (int)std::sqrt(acn);\n      int m = acn - n * n - n;\n      return {n, m};\n    }\n\n    // HOA normalisation functions corresponding to BS.2076-1 section 10.2\n\n    enum class NormType {\n      N3D,\n      SN3D,\n      FuMa,\n    };\n\n    inline double norm_N3D(int n, int abs_m) {\n      return std::sqrt((2.0 * n + 1.0) *\n                       boost::math::factorial<double>(n - abs_m) /\n                       boost::math::factorial<double>(n + abs_m));\n    }\n\n    inline double norm_SN3D(int n, int abs_m) {\n      return std::sqrt(boost::math::factorial<double>(n - abs_m) /\n                       boost::math::factorial<double>(n + abs_m));\n    }\n\n    inline double norm_FuMa(int n, int abs_m) {\n      static const std::map<std::pair<int, int>, double> conversion_factors = {\n          {{0, 0}, 1.0 / std::sqrt(2.0)},\n          {{1, 0}, 1.0},\n          {{1, 1}, 1.0},\n          {{2, 0}, 1.0},\n          {{2, 1}, 2.0 / std::sqrt(3.0)},\n          {{2, 2}, 2.0 / std::sqrt(3.0)},\n          {{3, 0}, 1.0},\n          {{3, 1}, std::sqrt(45.0 / 32.0)},\n          {{3, 2}, 3.0 / std::sqrt(5.0)},\n          {{3, 3}, std::sqrt(8.0 / 5.0)}};\n\n      return conversion_factors.at({n, abs_m}) * norm_SN3D(n, abs_m);\n    }\n\n    using norm_f_t = double(int, int);\n\n    inline norm_f_t &get_norm(NormType norm_type) {\n      switch (norm_type) {\n        case NormType::N3D:\n          return norm_N3D;\n        case NormType::SN3D:\n          return norm_SN3D;\n        case NormType::FuMa:\n          return norm_FuMa;\n        default:\n          throw ear::internal_error(\"invalid value for norm_type\");\n      }\n    }\n\n    /// Spherical harmonic values for a given normalisation according to\n    /// BS.2076-1 section 10.1.\n    ///\n    /// Here, az and el are the ADM azimuths and\n    /// elevations converted to radians, rather than the HOA coordinate system.\n    /// The only difference is that the elevation goes up from the equator, so\n    /// we use sin rather than cos in the elevation term.\n    template <typename NormT>\n    double sph_harm(int n, int m, double az, double el, NormT norm) {\n      double scale;\n      if (m > 0)\n        scale = std::sqrt(2.0) * std::cos(m * az);\n      else if (m < 0)\n        scale = -std::sqrt(2.0) * std::sin(m * az);\n      else\n        scale = 1;\n\n      return norm(n, std::abs(m)) * Alegendre(n, std::abs(m), std::sin(el)) *\n             scale;\n    }\n\n    /// get a matrix of HOA coefficients at the given positions\n    template <typename NormT>\n    Eigen::MatrixXd calc_Y_virt(Eigen::Matrix<double, Eigen::Dynamic, 3> points,\n                                Eigen::VectorXi n, Eigen::VectorXi m,\n                                NormT norm) {\n      ear_assert(n.size() == m.size(), \"n and m must be the same size\");\n\n      Eigen::MatrixXd Y_virt(n.size(), points.rows());\n      for (Eigen::Index point_i = 0; point_i < points.rows(); point_i++) {\n        for (Eigen::Index coeff_i = 0; coeff_i < n.size(); coeff_i++) {\n          double az = -std::atan2(points(point_i, 0), points(point_i, 1));\n          double el =\n              std::atan2(points(point_i, 2),\n                         std::hypot(points(point_i, 0), points(point_i, 1)));\n          Y_virt(coeff_i, point_i) =\n              sph_harm(n(coeff_i), m(coeff_i), az, el, norm);\n        }\n      }\n\n      return Y_virt;\n    }\n\n    /// get a matrix of point-source panning values at the given points, given\n    /// a function from a 3-vector to an optional vector of coefficients\n    template <typename PanningFuncT>\n    Eigen::MatrixXd calc_G_virt(Eigen::Matrix<double, Eigen::Dynamic, 3> points,\n                                PanningFuncT panning_function) {\n      Eigen::Index n_speakers =\n          panning_function(Eigen::Vector3d{0, 1, 0}).get().size();\n\n      Eigen::MatrixXd G_virt(n_speakers, points.rows());\n      for (Eigen::Index point_i = 0; point_i < points.rows(); point_i++)\n        G_virt.col(point_i) = panning_function(points.row(point_i)).get();\n\n      return G_virt;\n    }\n\n    /// normalize a decode matrix such that the mean output power for the given\n    /// input vectors is 1\n    inline void normalize_decode_matrix(Eigen::MatrixXd &D,\n                                        Eigen::MatrixXd Y_virt) {\n      D *= std::sqrt(Y_virt.cols()) / (D * Y_virt).norm();\n    }\n\n    /// Vector which when multiplied with a HOA signal converts it from\n    /// norm_from to norm_to\n    template <typename NormToT, typename NormFromT>\n    inline Eigen::VectorXd normalisation_conversion(Eigen::VectorXi n,\n                                                    Eigen::VectorXi m,\n                                                    NormToT norm_to,\n                                                    NormFromT norm_from) {\n      ear_assert(n.size() == m.size(), \"n and m must be the same size\");\n\n      Eigen::VectorXd conversion(n.size());\n      for (Eigen::Index coeff_i = 0; coeff_i < n.size(); coeff_i++)\n        conversion(coeff_i) = norm_to(n(coeff_i), std::abs(m(coeff_i))) /\n                              norm_from(n(coeff_i), std::abs(m(coeff_i)));\n\n      return conversion;\n    }\n\n    /// Decoder matrix design using the AllRAD[0] technique.\n    /// [0] F. Zotter and M. Frank, \"All-round ambisonic panning and decoding,\"\n    /// JAES, vol. 60, no. 10, pp. 807-820, 2012.\n    /// http://www.aes.org/e-lib/browse.cfm?elib=16554\n    template <typename PanningFuncT, typename NormT>\n    Eigen::MatrixXd allrad_design(\n        Eigen::Matrix<double, Eigen::Dynamic, 3> points,\n        PanningFuncT panning_function, Eigen::VectorXi n, Eigen::VectorXi m,\n        NormT norm) {\n      Eigen::MatrixXd Y_virt = calc_Y_virt(points, n, m, norm_N3D);\n      Eigen::MatrixXd D_virt = Y_virt.transpose() / points.rows();\n      Eigen::MatrixXd G_virt = calc_G_virt(points, panning_function);\n\n      Eigen::MatrixXd D = G_virt * D_virt;\n\n      normalize_decode_matrix(D, Y_virt);\n\n      D *= normalisation_conversion(n, m, norm_N3D, norm).asDiagonal();\n\n      return D;\n    }\n\n    /// load spherical-t-design points used to be used for AllRAD design\n    Eigen::Matrix<double, Eigen::Dynamic, 3> load_points();\n\n  }  // namespace hoa\n}  // namespace ear\n", "meta": {"hexsha": "2857a87016178dd3f9423cf103a7d49b99b97a7a", "size": 6893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hoa/hoa.hpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/hoa/hoa.hpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/hoa/hoa.hpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 36.4708994709, "max_line_length": 80, "alphanum_fraction": 0.5746409401, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.675617240107592}}
{"text": "//\r\n// $Id$\r\n//\r\n//\r\n// Darren Kessner <darren@proteowizard.org>\r\n//\r\n// Copyright 2009 Spielberg Family Center for Applied Proteomics\r\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#include \"LeastSquaresCalibrator.hpp\"\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/vector_proxy.hpp>\r\nnamespace ublas = boost::numeric::ublas;\r\n\r\n\r\nusing namespace std;\r\nusing pwiz::data::CalibrationParameters;\r\n\r\n\r\nnamespace pwiz {\r\nnamespace calibration {\r\n\r\n\r\nclass LeastSquaresCalibratorImpl : public LeastSquaresCalibrator\r\n{\r\n    public:\r\n    LeastSquaresCalibratorImpl(const vector<double>& trueMasses,\r\n                               const vector<double>& observedFrequencies);\r\n\r\n    virtual void calibrate();\r\n    virtual const CalibrationParameters& parameters() const {return parameters_;}\r\n    virtual double error() const {return error_;}\r\n\r\n    private:\r\n    const vector<double>& trueMasses_;\r\n    const vector<double>& observedFrequencies_;\r\n    CalibrationParameters parameters_;\r\n    double error_;\r\n\r\n    void calculateSums(double& sum_f2m2,\r\n                       double& sum_f3m2, \r\n                       double& sum_f4m2, \r\n                       double& sum_fm, \r\n                       double& sum_f2m);\r\n    \r\n    void calculateParametersFromSums(double sum_f2m2,\r\n                                     double sum_f3m2, \r\n                                     double sum_f4m2, \r\n                                     double sum_fm, \r\n                                     double sum_f2m);\r\n \r\n    void calculateError();\r\n};\r\n\r\n\r\nauto_ptr<LeastSquaresCalibrator> LeastSquaresCalibrator::create(const vector<double>& trueMasses,\r\n                                                        const vector<double>& observedFrequencies)\r\n{\r\n    return auto_ptr<LeastSquaresCalibrator>(new LeastSquaresCalibratorImpl(trueMasses, observedFrequencies));\r\n}\r\n\r\n\r\nLeastSquaresCalibratorImpl::LeastSquaresCalibratorImpl(const vector<double>& trueMasses,\r\n                                                       const vector<double>& observedFrequencies)\r\n:   trueMasses_(trueMasses),\r\n    observedFrequencies_(observedFrequencies),\r\n    error_(-1)\r\n{\r\n    if (trueMasses.size() != observedFrequencies.size())\r\n        throw logic_error(\"[LeastSquaresCalibratorImpl::LeastSquaresCalibratorImpl()] Data size mismatch.\");\r\n}\r\n\r\n\r\nvoid LeastSquaresCalibratorImpl::calibrate()\r\n{\r\n    // observed frequencies {fi}\r\n    // true masses {mi}\r\n    // calibration function m_AB(f) = A/f + B/f^2\r\n    // error function E(A,B) = sum [(m_AB(fi) - mi)/mi]^2  (sum of squared relative deviations)\r\n    // dE/dA == 0 == dE/dB gives:\r\n    //   ( sum[1/(fi^2*mi^2)]  sum[1/(fi^3*mi^2)] ) (A) == ( sum[1/(fi*mi)]   ) \r\n    //   ( sum[1/(fi^3*mi^2)]  sum[1/(fi^4*mi^2)] ) (B) == ( sum[1/(fi^2*mi)] ) \r\n\r\n    double sum_f2m2 = 0;\r\n    double sum_f3m2 = 0;\r\n    double sum_f4m2 = 0;\r\n    double sum_fm = 0;\r\n    double sum_f2m = 0;\r\n\r\n    calculateSums(sum_f2m2, sum_f3m2, sum_f4m2, sum_fm, sum_f2m);\r\n    calculateParametersFromSums(sum_f2m2, sum_f3m2, sum_f4m2, sum_fm, sum_f2m);\r\n    calculateError();\r\n}\r\n\r\n\r\nvoid LeastSquaresCalibratorImpl::calculateSums(double& sum_f2m2,\r\n                                               double& sum_f3m2, \r\n                                               double& sum_f4m2, \r\n                                               double& sum_fm, \r\n                                               double& sum_f2m)\r\n{\r\n    sum_f2m2 = 0;\r\n    sum_f3m2 = 0;\r\n    sum_f4m2 = 0;\r\n    sum_fm = 0;\r\n    sum_f2m = 0;\r\n    \r\n    vector<double>::const_iterator mit = trueMasses_.begin();\r\n    vector<double>::const_iterator fit = observedFrequencies_.begin();\r\n\r\n    for (; mit!=trueMasses_.end(); ++mit, ++fit)\r\n    {\r\n        double m = *mit; \r\n        double f = *fit; \r\n        double m2 = m*m;\r\n        double f2 = f*f;\r\n        double f3 = f2*f;\r\n        double f4 = f3*f;\r\n    \r\n        sum_f2m2 += 1/(f2*m2);\r\n        sum_f3m2 += 1/(f3*m2);\r\n        sum_f4m2 += 1/(f4*m2);\r\n        sum_fm += 1/(f*m);\r\n        sum_f2m += 1/(f2*m);\r\n    }\r\n}\r\n\r\n\r\nvoid LeastSquaresCalibratorImpl::calculateParametersFromSums(double sum_f2m2,\r\n                                                             double sum_f3m2, \r\n                                                             double sum_f4m2, \r\n                                                             double sum_fm, \r\n                                                             double sum_f2m)\r\n{\r\n    ublas::matrix<double> M(2,2);\r\n    ublas::vector<double> p(2);\r\n\r\n    M(0,0) = sum_f2m2;\r\n    M(0,1) = M(1,0) = sum_f3m2;\r\n    M(1,1) = sum_f4m2;\r\n    p(0) = sum_fm;\r\n    p(1) = sum_f2m;\r\n\r\n    ublas::permutation_matrix<size_t> pm(2);\r\n    int singular = lu_factorize(M, pm);\r\n    if (singular)\r\n        throw runtime_error(\"[LeastSquaresCalibratorImpl::calculateParametersFromSums()] Matrix is singular.\");\r\n\r\n    lu_substitute(M, pm, p);\r\n\r\n    parameters_.A = p[0];\r\n    parameters_.B = p[1];\r\n}\r\n\r\n\r\nvoid LeastSquaresCalibratorImpl::calculateError()\r\n{\r\n    // calculate root mean squared relative deviation\r\n\r\n    double sum = 0;\r\n    vector<double>::const_iterator mit = trueMasses_.begin();\r\n    vector<double>::const_iterator fit = observedFrequencies_.begin();\r\n\r\n    for (; mit!=trueMasses_.end(); ++mit, ++fit)\r\n    {\r\n        double m_true = *mit; \r\n        double m_calc = parameters_.mz(*fit); \r\n        double term = (m_calc - m_true)/m_true; \r\n        sum += term*term; \r\n    } \r\n\r\n    error_ = sqrt(sum/trueMasses_.size());\r\n}\r\n\r\n\r\n} // namespace calibration\r\n} // namespace pwiz\r\n\r\n", "meta": {"hexsha": "61006a8edf553710df3bf5a8f9bc957723f7b558", "size": 6382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/calibration/LeastSquaresCalibrator.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/analysis/calibration/LeastSquaresCalibrator.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/analysis/calibration/LeastSquaresCalibrator.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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.91, "max_line_length": 112, "alphanum_fraction": 0.5722344093, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6756172379026467}}
{"text": "#include <Eigen/Core>\r\n#include <unsupported/Eigen/SpecialFunctions>\r\n#include <iostream>\r\nusing namespace Eigen;\r\nint main()\r\n{\r\n  Array4d v(0.5,10,0,-1);\r\n  std::cout << v.lgamma() << std::endl;\r\n}", "meta": {"hexsha": "0faad8d8ca3e695d50a8ac40a6a3a58a8137ea33", "size": 199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Cwise_lgamma.cpp", "max_stars_repo_name": "nins-k/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-24T17:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:02:38.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Cwise_lgamma.cpp", "max_issues_repo_name": "nins-k/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_issues_repo_licenses": ["MIT"], "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-3.3/doc/examples/Cwise_lgamma.cpp", "max_forks_repo_name": "nins-k/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "841a4aea5570ae4e036a12ba36ee499dba518881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-24T13:35:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T14:40:05.000Z", "avg_line_length": 22.1111111111, "max_line_length": 46, "alphanum_fraction": 0.6582914573, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.675601802311482}}
{"text": "#include <ros/ros.h>\r\n#include <visualization_msgs/Marker.h>\r\n#include <vector>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <Eigen/Dense>\r\n#include <tms_msg_ss/Beacon.h>\r\n#include \"kalman-Ndof.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n#define N 4\r\n\r\nros::Subscriber beacon_sub;\r\nros::Publisher marker_pub;\r\n\r\ntypedef struct {\r\n\tVector3d loc;\r\n\tdouble r;\r\n} beacon;\r\n\r\nvector<beacon> rasp_pis;\r\nbeacon rasp_pi[N];\r\nKalman *kalman;\r\n\r\n#define SD_DIST 0.1 // Error of beacon [m]\r\n#define sqr(var) ((var)*(var))\r\n#define dist2(var1, var2) (sqr(var1[0]-var2[0])+sqr(var1[1]-var2[1])+sqr(var1[2]-var2[2])) // square of distance\r\n\r\n#define REPEAT_LIMIT 1000\r\n\r\n//#define LOGGING\r\n// #define DEBUG 1\r\n\r\nVector3d calc_position(vector<beacon> beacons, Vector3d initpos)\r\n{\r\n\tVector3d pos(0, 0, 0);\r\n\tint n = beacons.size();\r\n\r\n\tMatrixXd A(n, 3);\r\n\tVectorXd L(n);\r\n\tMatrixXd SigmaL(n, n);\r\n\tMatrixXd K(n, n);\r\n\tMatrixXd Sigma(n, n);\r\n\tVectorXd Error(3);\r\n\tdouble gain = 0.01;//0.1;\r\n\r\n\tpos = initpos;\r\n\tint repeat = 0;\r\n\r\n\twhile (1) {\r\n\t\trepeat++;\r\n\t\tif(repeat>REPEAT_LIMIT)\r\n\t\t\tbreak;\r\n\t\tA.setZero();\r\n\t\tL.setZero();\r\n\t\tSigmaL.setZero();\r\n\t\tSigma.setZero();\r\n\r\n\t\tK.setZero();\r\n\t\tError.setZero();\r\n\r\n\t\tfor (int i = 0; i<n; i++) {\r\n\t\t\tdouble distance = dist2(beacons[i].loc, pos);\r\n\r\n\t\t\tA(i, 0) = pos[0] - beacons[i].loc[0];\r\n\t\t\tA(i, 1) = pos[1] - beacons[i].loc[1];\r\n\t\t\tA(i, 2) = pos[2] - beacons[i].loc[2];\r\n\r\n\t\t\tL(i) = (sqr(beacons[i].r) - dist2(beacons[i].loc, pos)) / 2.0;\r\n\r\n\t\t\tK(i, i) = beacons[i].r;\r\n\t\t\tSigma(i, i) = sqr(SD_DIST);\r\n\t\t}\r\n\r\n\t\tSigmaL = K * Sigma * K.transpose();\r\n\r\n\t\tMatrix3d Covariance;\r\n\t\tCovariance = (A.transpose() * SigmaL.inverse() * A).inverse();\r\n\t\tError = Covariance * A.transpose() * SigmaL.inverse() * L;\r\n\r\n\t\t#ifdef LOGGING\r\n\t\tstd::ofstream outf(\"test.txt\");\r\n\t\tstatic int testCount = 1;\r\n\t\toutf << \"[\" << testCount++ << \"]\" << std::endl << std::endl;\r\n\t\toutf << \"Covariance = \" << std::endl << Covariance << std::endl << std::endl;\r\n\t\toutf << \"det(S-1) = \" << std::endl << (SigmaL.inverse()).determinant() << std::endl << std::endl;\r\n\t\toutf << \"det(S) = \" << std::endl << SigmaL.determinant() << std::endl << std::endl;\r\n\t\toutf << \"det(Covariance) = \" << std::endl << Covariance.determinant() << std::endl << std::endl;\r\n\t\toutf << \"A.transpose() = \" << std::endl << A.transpose() << std::endl << std::endl;\r\n\t\toutf << \"SigmaL = \" << std::endl << SigmaL << std::endl << std::endl;\r\n\t\toutf << \"Error = \" << std::endl << Error << std::endl << std::endl;\r\n\t\toutf << \"SigmaL -1 = \" << std::endl << SigmaL.inverse() << std::endl << std::endl;\r\n\t\toutf << \"L = \" << std::endl << L << std::endl << std::endl;\r\n\r\n\t\toutf << \"C * at = \" << std::endl << Covariance * A.transpose() << std::endl << std::endl;\r\n\t\toutf << \"C * at * SigmaL-1 = \" << std::endl << Covariance * A.transpose() * SigmaL.inverse() << std::endl << std::endl;\r\n\t\toutf << \"C * at * SigmaL-1 * L = \" << std::endl << Covariance * A.transpose() * SigmaL.inverse() * L << std::endl << std::endl;\r\n\t\toutf.flush();\r\n\r\n\t\toutf.close();\r\n\t\t#endif\r\n\r\n\t\tif (sqrt(sqr(Error(0)) + sqr(Error(1)) + sqr(Error(2))) > 1000.0) {\r\n\t\t\treturn Vector3d(0,0,0); // \ufffdv\ufffdZ\ufffd\ufffd\ufffd\ufffd\ufffdU\r\n\t\t}\r\n\r\n\t\t// reNew parent position\r\n\t\tpos[0] += gain * Error(0);\r\n\t\tpos[1] += gain * Error(1);\r\n\t\tpos[2] += gain * Error(2);\r\n\r\n#if DEBUG\r\n\t\tcout << \"Error \" << sqrt(sqr(Error(0)) + sqr(Error(1)) + sqr(Error(2))) << endl;\r\n\t\tcout << \"Pos \" << std::endl << pos << std::endl << std::endl;\r\n\t\tcout << \"Covariance = \" << std::endl << Covariance << std::endl << std::endl;\r\n#endif\r\n\r\n\t\t// do repeat until (dx,dy,dz) is under than 1 mm\r\n\t\tif (sqrt(sqr(Error(0)) + sqr(Error(1)) + sqr(Error(2))) < 0.001) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn pos;\r\n\r\n}\r\n\r\nvoid drawRaspi(beacon pi,int id,float r,float g,float b,float a)\r\n{\r\n\tuint32_t shape = visualization_msgs::Marker::SPHERE;\r\n\tvisualization_msgs::Marker marker;\r\n\tmarker.header.frame_id = \"/world_link\";\r\n\tmarker.header.stamp = ros::Time::now();\r\n\tmarker.ns = \"beacon\";\r\n\tmarker.id = id;\r\n\tmarker.type = shape;\r\n\tmarker.action = visualization_msgs::Marker::ADD;\r\n\r\n\tmarker.pose.position.x = pi.loc[0];\r\n\tmarker.pose.position.y = pi.loc[1];\r\n\tmarker.pose.position.z = pi.loc[2];\r\n\r\n\tmarker.scale.x = marker.scale.y = marker.scale.z = pi.r*2;\r\n\r\n\tmarker.color.r = r;\r\n\tmarker.color.g = g;\r\n\tmarker.color.b = b;\r\n\tmarker.color.a = a;\r\n\tmarker.lifetime = ros::Duration();\r\n\tmarker_pub.publish(marker);\r\n}\r\n\r\nvoid drawPos(Vector3d pos,int id,float r,float g,float b,float a)\r\n{\r\n\tuint32_t shape = visualization_msgs::Marker::SPHERE;\r\n\tvisualization_msgs::Marker marker;\r\n\tmarker.header.frame_id = \"/world_link\";\r\n\tmarker.header.stamp = ros::Time::now();\r\n\tmarker.ns = \"beacon\";\r\n\tmarker.id = id;\r\n\tmarker.type = shape;\r\n\tmarker.action = visualization_msgs::Marker::ADD;\r\n\r\n\tmarker.pose.position.x = pos[0];\r\n\tmarker.pose.position.y = pos[1];\r\n\tmarker.pose.position.z = pos[2];//0.8\r\n\r\n\tmarker.scale.x = marker.scale.y = 0.2;\r\n\tmarker.scale.z = 0.2;//1.6\r\n\r\n\tmarker.color.r = r;\r\n\tmarker.color.g = g;\r\n\tmarker.color.b = b;\r\n\tmarker.color.a = a;\r\n\tmarker.lifetime = ros::Duration();\r\n\tmarker_pub.publish(marker);\r\n}\r\n\r\nros::Time last_time;\r\nros::Time now;\r\nVector3d pos(8,3,0.8);\r\nVector3d last_pos(8,3,0.8);\r\nVector3d kf_pos(8,3,0.8);\r\nvoid Callback(const tms_msg_ss::Beacon &msg)\r\n{\r\n\tif(msg.pi_id<N)\r\n\t\trasp_pi[msg.pi_id].r = msg.distance;\r\n\r\n\tROS_INFO(\"%f %f %f %f\",rasp_pi[0].r,rasp_pi[1].r,rasp_pi[2].r,rasp_pi[3].r);\r\n\r\n  drawRaspi(rasp_pi[0],0,1.0,0.0,0.0,0.2);\r\n\tdrawRaspi(rasp_pi[1],1,0.0,1.0,0.0,0.2);\r\n\tdrawRaspi(rasp_pi[2],2,0.0,1.0,1.0,0.2);\r\n\tdrawRaspi(rasp_pi[3],3,1.0,1.0,0.0,0.2);\r\n\r\n\trasp_pis.clear();\r\n\trasp_pis.push_back(rasp_pi[0]);\r\n\trasp_pis.push_back(rasp_pi[1]);\r\n\trasp_pis.push_back(rasp_pi[2]);\r\n\trasp_pis.push_back(rasp_pi[3]);\r\n\r\n\tlast_pos = pos;\r\n\tROS_INFO(\"calc\");\r\n\tpos = calc_position(rasp_pis, pos);\r\n\tROS_INFO(\"calcend\");\r\n\tROS_INFO(\"pos:(%f,%f,%f)\",pos[0],pos[1],pos[2]);\r\n\r\n\tif(pos[0]==0&&pos[1]==0&&pos[2]==0){\r\n\t\treturn;\r\n\t}\r\n\r\n\tlast_time = now;\r\n\tnow = ros::Time::now();\r\n\tdouble delta_t = (now.sec+now.nsec*0.000000001)-(last_time.sec+last_time.nsec*0.000000001);\r\n\tROS_INFO(\"callback:%f\",delta_t);\r\n\r\n\tdrawPos(pos,10,1.0,1.0,1.0,1.0);\r\n\r\n\tdouble velX = (pos[0]-last_pos[0])/delta_t;\r\n\tdouble velY = (pos[1]-last_pos[1])/delta_t;\r\n\tdouble velZ = (pos[2]-last_pos[2])/delta_t;\r\n\r\n\tstatic int count = 0;\r\n\r\n\tif(kalman == NULL)\r\n\t\treturn;\r\n\r\n\tif(count==0)\r\n\t{\r\n\t\tcount++;\r\n\t\treturn;\r\n\t}\r\n\telse if(count==1)\r\n\t{\r\n\t\tkalman->init(0.1,1.0,0.1);//(0.1,0.1,1.0);\r\n\t\tdouble C[3][6];\r\n\t\tmemset(C,0,sizeof(C));\r\n\t\tC[0][0]=C[1][1]=C[2][2]=1;\r\n\t\tkalman->setC((double *)&C);\r\n\t\tkalman->setX(0,pos[0]);\r\n\t\tkalman->setX(1,pos[1]);\r\n\t\tkalman->setX(2,pos[2]);\r\n\t\tkalman->setX(3,velX);\r\n\t\tkalman->setX(4,velY);\r\n\t\tkalman->setX(5,velZ);\r\n\r\n\t\tcount++;\r\n\t}\r\n\r\n\tdouble A[3][6];\r\n\tmemset(A,0,sizeof(A));\r\n\tA[0][0]=A[1][1]=A[2][2]=1;\r\n\tA[0][3]=A[1][4]=A[2][5]=delta_t;\r\n\r\n\tdouble obs[6]={pos[0],pos[1],pos[2],velX,velY,velZ};\r\n\tdouble input[3]={0,0,0};\r\n\r\n\tkalman->update(obs,input);\r\n\r\n\tkf_pos[0]=kalman->getX(0);\r\n\tkf_pos[1]=kalman->getX(1);\r\n\tkf_pos[2]=kalman->getX(2);\r\n\r\n\r\n\tROS_INFO(\"kf_pos:(%f,%f,%f)\",kf_pos[0],kf_pos[1],kf_pos[2]);\r\n\r\n\tdrawPos(kf_pos,11,1.0,0.0,0.0,1.0);\r\n}\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tros::init(argc, argv, \"tms_ss_beacon\");\r\n\tros::NodeHandle nh;\r\n\r\n\tkalman = new Kalman(6,6,3);\r\n\r\n\tnow = ros::Time::now();\r\n\r\n\tbeacon_sub = nh.subscribe(\"/tms_ss_beacon\",1,&Callback);\r\n\tmarker_pub = nh.advertise<visualization_msgs::Marker>(\"visualization_marker\",1);\r\n\r\n\tROS_INFO(\"READY\");\r\n\r\n\trasp_pi[0].loc << 7.66, 5.62, 0.82;\r\n\trasp_pi[1].loc << 10.12, 3.90, 0.58;\r\n\trasp_pi[2].loc << 8.74, 0.31, 0.92;\r\n\trasp_pi[3].loc << 5.65, 1.66, 0.73;\r\n\r\n\trasp_pi[0].r = 3;\r\n\trasp_pi[1].r = 1.5;\r\n\trasp_pi[2].r = 2;\r\n\trasp_pi[3].r = 4;\r\n\r\n\tros::spin();\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "47a0094453e6b49c8c555c7ac1aeb3b846fa06eb", "size": 7795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_ss/tms_ss_beacon/src/main.cpp", "max_stars_repo_name": "robotpilot/ros_tms", "max_stars_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T06:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T07:49:37.000Z", "max_issues_repo_path": "tms_ss/tms_ss_beacon/src/main.cpp", "max_issues_repo_name": "robotpilot/ros_tms", "max_issues_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 114.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T06:42:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T05:54:04.000Z", "max_forks_repo_path": "tms_ss/tms_ss_beacon/src/main.cpp", "max_forks_repo_name": "robotpilot/ros_tms", "max_forks_repo_head_hexsha": "3d6b6579e89aa9cb216cd3cb6157fabc553c18f1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-03-27T08:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-08T13:05:31.000Z", "avg_line_length": 25.8970099668, "max_line_length": 130, "alphanum_fraction": 0.5916613214, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6754899844061262}}
{"text": "// Copyright Nick Thompson 2017.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <string>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/legendre_stieltjes.hpp>\n\nusing boost::math::legendre_p;\nusing boost::math::legendre_p_zeros;\nusing boost::math::legendre_p_prime;\nusing boost::math::legendre_stieltjes;\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::multiprecision::cpp_dec_float_100;\n\ntemplate<class Real>\nvoid gauss_kronrod_rule(size_t order)\n{\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    std::cout << std::fixed;\n    auto gauss_nodes = boost::math::legendre_p_zeros<Real>(order);\n    auto E = legendre_stieltjes<Real>(order + 1);\n    std::vector<Real> gauss_weights(gauss_nodes.size(), std::numeric_limits<Real>::quiet_NaN());\n    std::vector<Real> gauss_kronrod_weights(gauss_nodes.size(), std::numeric_limits<Real>::quiet_NaN());\n    for (size_t i = 0; i < gauss_nodes.size(); ++i)\n    {\n        Real node = gauss_nodes[i];\n        Real lp = legendre_p_prime<Real>(order, node);\n        gauss_weights[i] = 2/( (1-node*node)*lp*lp);\n        // P_n(x) = (2n)!/(2^n (n!)^2) pi_n(x), where pi_n is the monic Legendre polynomial.\n        gauss_kronrod_weights[i] = gauss_weights[i] + static_cast<Real>(2)/(static_cast<Real>(order+1)*legendre_p_prime(order, node)*E(node));\n    }\n\n    std::cout << \"static const std::vector<Real> gauss_nodes {\\n\";\n    for (auto const & node : gauss_nodes)\n    {\n        std::cout << \"    boost::lexical_cast<Real>(\\\"\" << node << \"\\\"),\\n\";\n    }\n    std::cout << \"};\\n\\n\";\n\n    std::cout << \"static const std::vector<Real> gauss_weights {\\n\";\n    for (auto const & weight : gauss_weights)\n    {\n        std::cout << \"    boost::lexical_cast<Real>(\\\"\" << weight << \"\\\"),\\n\";\n    }\n    std::cout << \"};\\n\\n\";\n\n    std::cout << \"static const std::vector<Real> gauss_kronrod_weights {\\n\";\n    for (auto const & weight : gauss_kronrod_weights)\n    {\n        std::cout << \"    boost::lexical_cast<Real>(\\\"\" << weight << \"\\\"),\\n\";\n    }\n    std::cout << \"};\\n\\n\";\n\n    auto kronrod_nodes = E.zeros();\n    std::vector<Real> kronrod_weights(kronrod_nodes.size());\n    for (size_t i = 0; i < kronrod_weights.size(); ++i)\n    {\n        Real node = kronrod_nodes[i];\n        kronrod_weights[i] = static_cast<Real>(2)/(static_cast<Real>(order+1)*legendre_p(order, node)*E.prime(node));\n    }\n\n    std::cout << \"static const std::vector<Real> kronrod_nodes {\\n\";\n    for (auto node : kronrod_nodes)\n    {\n        std::cout << \"    boost::lexical_cast<Real>(\\\"\" << node << \"\\\"),\\n\";\n    }\n    std::cout << \"};\\n\\n\";\n\n    std::cout << \"static const std::vector<Real> kronrod_weights {\\n\";\n    for (auto const & weight : kronrod_weights)\n    {\n        std::cout << \"    boost::lexical_cast<Real>(\\\"\" << weight << \"\\\"),\\n\";\n    }\n    std::cout << \"};\\n\\n\";\n\n}\n\nint main()\n{\n    //std::cout << \"Gauss-Kronrod 7-15 Rule:\\n\";\n    //gauss_kronrod_rule<cpp_dec_float_100>(7);\n\n    //std::cout << \"\\n\\nGauss-Kronrod 10-21 Rule:\\n\";\n    //gauss_kronrod_rule<cpp_dec_float_100>(10);\n\n    std::cout << \"\\n\\nGauss-Kronrod 15-31 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(15);\n    /*\n    std::cout << \"\\n\\nGauss-Kronrod 20-41 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(20);\n\n    std::cout << \"\\n\\nGauss-Kronrod 25-51 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(25);\n\n    std::cout << \"\\n\\nGauss-Kronrod 30-61 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(30);\n\n    std::cout << \"\\n\\nGauss-Kronrod 35-71 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(35);\n\n    std::cout << \"\\n\\nGauss-Kronrod 40-81 Rule:\\n\";\n    gauss_kronrod_rule<cpp_dec_float_100>(40);*/\n}\n", "meta": {"hexsha": "00ceba277119ecc5cc60eaff22c87dd0137211c0", "size": 4009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/legendre_stieltjes_example.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/legendre_stieltjes_example.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/legendre_stieltjes_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.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": 36.1171171171, "max_line_length": 142, "alphanum_fraction": 0.6415564979, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6753618529823494}}
{"text": "//include libraries for image io, kernel definition and convolution\n#include <boost/gil/image.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/extension/io/jpeg.hpp>\n#include <boost/gil/extension/numeric/kernel.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n//This example demonstrates the use of simple 1d kernel for detection of horizontal \n//and vertical edges.This difference kernel is [-.05,0,0.05] whose convolution gives\n// the difference between neighbouring pixels as the value of pixel. Edges have sharp\n//changes in intensities so difference between neighbouring pixels will be more. Hence\n//pixels with higher intensity(brighter pixels) depict the presence of an edge.\n\nint main() {\n    using namespace boost::gil;\n    // if(argc!=2){\n    //     std::cerr<<\"Usage: simple_filter <image_path>\";\n    //     return -1;\n    // }\n    rgb8_image_t img;\n    \n    read_image(\"test.jpg\", img, jpeg_tag{});\n\n    \n    gray8_image_t convolved(img.dimensions());\n    gray8_image_t convolved2(img.dimensions());\n\n    // difference kernel\n    float sharpen_1[]={-0.05f,0.0f,0.05f};\n    \n\n    \n    kernel_1d<float> kernel2(sharpen_1,3,1);\n    //compute horizontal edges\n    convolve_rows<gray32f_pixel_t>(color_converted_view<gray8_pixel_t>(const_view(img)),kernel2,view(convolved));\n    //compute vertical edges\n    convolve_cols<gray32f_pixel_t>(color_converted_view<gray8_pixel_t>(const_view(img)),kernel2,view(convolved2));\n    \n    write_view(\"sharpen-convolution2.jpg\", view(convolved), jpeg_tag{});\n    write_view(\"sharpen-convolution3.jpg\",view(convolved2),jpeg_tag{});\n    return 0;\n}\n", "meta": {"hexsha": "9e7f675631b37dc008c7a391e18263532f097ba8", "size": 1610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/simple_filter.cpp", "max_stars_repo_name": "sid19991/gil", "max_stars_repo_head_hexsha": "6802a26c0f7f34bc7b3bbb5365dd307408fcb8b6", "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/simple_filter.cpp", "max_issues_repo_name": "sid19991/gil", "max_issues_repo_head_hexsha": "6802a26c0f7f34bc7b3bbb5365dd307408fcb8b6", "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/simple_filter.cpp", "max_forks_repo_name": "sid19991/gil", "max_forks_repo_head_hexsha": "6802a26c0f7f34bc7b3bbb5365dd307408fcb8b6", "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": 38.3333333333, "max_line_length": 114, "alphanum_fraction": 0.7260869565, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6753389309588982}}
{"text": "/*=================================================================\n* Transform vertices (n*3) with a 3D affine transform\n* \n* according to David Legland's matlab toolbox: geom3d \n* \n* Junjie Cao, 2013, jjcao1231@gmail.com\n*\n=================================================================*/\n\n#include <mex.h>\n#include <Eigen/Dense>\n#include <vector>\n\nEigen::MatrixXd transform_point3d(Eigen::MatrixXd& verts, Eigen::Matrix4d& trans)\n{\n\tint NP  = verts.rows();\n\tEigen::MatrixXd res(NP,4);\n\tres.col(0) = verts.col(0);\n\tres.col(1) = verts.col(1);\n\tres.col(2) = verts.col(2);\n\tres.col(3) = Eigen::VectorXd::Ones(NP,1);\n\t//std::cout << res << std::endl;\n\n\t//std::cout << trans * res.row(0).transpose() << std::endl;\n\tres = res * trans.transpose();\n\t//std::cout << res << std::endl;\n\tres.conservativeResize(NP, 3);\n\t \n\treturn res;\n}\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])\n{  \n\t////////////////// parse input\n\tif ( nrhs != 2)\n\t\tmexErrMsgTxt(\"2 arguments needed!\");\n\n\tdouble *verts_, *trans_;\n\tverts_ = mxGetPr(prhs[0]);\n\ttrans_ = mxGetPr(prhs[1]);\n\tint nverts = mxGetM(prhs[0]);\n\tif ( mxGetN(prhs[0]) != 3)\n\t\tmexErrMsgTxt(\"center must be n*3 matrix!\");\n\tif ( mxGetN(prhs[1]) != 4 && mxGetM(prhs[1]) != 4)\n\t\tmexErrMsgTxt(\"vector must be 4*4 matrix!\");\n\t\n\tEigen::MatrixXd verts = Eigen::Map<Eigen::MatrixXd>(verts_, nverts, 3);\n\tEigen::Matrix4d trans = Eigen::Map<Eigen::Matrix4d>(trans_);\n\n\t/////////////////////////////\n\tEigen::MatrixXd newverts = transform_point3d(verts,trans);\n\n\t//////////////////////// output\n\tplhs[0] = mxCreateDoubleMatrix(nverts,3,mxREAL);\n\tdouble *newverts_ = mxGetPr(plhs[0]);\n\tEigen::Map<Eigen::MatrixXd>(newverts_, nverts, 3) = newverts;  \n}\n\n", "meta": {"hexsha": "ce8a49862366c5231f7526930690699b7313cabe", "size": 1704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/3d-transformation/transform_point3d.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/transform_point3d.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/transform_point3d.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": 29.3793103448, "max_line_length": 81, "alphanum_fraction": 0.58157277, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.675338928870531}}
{"text": "#ifndef TESTPSEUDOINVERSESVD_HPP_\n#define TESTPSEUDOINVERSESVD_HPP_\n\n#include <cxxtest/TestSuite.h>\n#include <Eigen/Dense>\n\n#include <cppmath/matrix/PseudoInverseSVD.hpp>\n\nclass TestPseudoInverseSVD: public CxxTest::TestSuite\n{\npublic:\n    void test_compute()\n    {\n        const Eigen::MatrixXd::Index rows = 42;\n        const Eigen::MatrixXd::Index cols = 7;\n\n        // Generate system of linear equations\n        Eigen::MatrixXd A( rows, cols );\n        A.setRandom();\n        Eigen::VectorXd x( cols );\n        x.setRandom();\n        Eigen::VectorXd b = A * x;\n\n        cppmath::PseudoInverseSVD< Eigen::MatrixXd > pinv( A );\n        const Eigen::MatrixXd& Ainv = pinv.compute();\n        Eigen::VectorXd xs = Ainv * b;\n        Eigen::VectorXd diff = x - xs;\n        TS_ASSERT_LESS_THAN( diff.squaredNorm(), 1e-6 );\n    }\n\n    void test_computeArg()\n    {\n        const Eigen::MatrixXd::Index rows = 23;\n        const Eigen::MatrixXd::Index cols = 23;\n\n        // Generate system of linear equations\n        Eigen::MatrixXd A( rows, cols );\n        A.setRandom();\n        Eigen::VectorXd x( cols );\n        x.setRandom();\n        Eigen::VectorXd b = A * x;\n\n        cppmath::PseudoInverseSVD< Eigen::MatrixXd > pinv( A );\n        Eigen::MatrixXd Ainv;\n        pinv.compute( &Ainv );\n        Eigen::VectorXd xs = Ainv * b;\n        Eigen::VectorXd diff = x - xs;\n        TS_ASSERT_LESS_THAN( diff.squaredNorm(), 1e-6 );\n    }\n\n    void test_multiply()\n    {\n        const Eigen::MatrixXd::Index rows = 3;\n        const Eigen::MatrixXd::Index cols = 2;\n\n        // Generate system of linear equations\n        Eigen::MatrixXd A( rows, cols );\n        A.setRandom();\n        Eigen::VectorXd x( cols );\n        x.setRandom();\n        Eigen::VectorXd b = A * x;\n\n        cppmath::PseudoInverseSVD< Eigen::MatrixXd > pinv( A );\n        Eigen::VectorXd xs = pinv * b;\n        Eigen::VectorXd diff = x - xs;\n        TS_ASSERT_LESS_THAN( diff.squaredNorm(), 1e-6 );\n    }\n\n    void test_identity1()\n    {\n        const Eigen::MatrixXd::Index rows = 7;\n        const Eigen::MatrixXd::Index cols = 7;\n\n        // Generate system of linear equations\n        Eigen::MatrixXd A( rows, cols );\n        A.setRandom();\n\n        cppmath::PseudoInverseSVD< Eigen::MatrixXd > pinv( A );\n        Eigen::MatrixXd I = pinv * A;\n        TS_ASSERT( I.isIdentity() );\n    }\n\n    void test_identity2()\n    {\n        const Eigen::MatrixXd::Index rows = 7;\n        const Eigen::MatrixXd::Index cols = 7;\n\n        // Generate system of linear equations\n        Eigen::MatrixXd A( rows, cols );\n        A.setIdentity();\n\n        cppmath::PseudoInverseSVD< Eigen::MatrixXd > pinv( A );\n        const Eigen::MatrixXd& I = pinv.compute();\n        TS_ASSERT( I.isIdentity() );\n    }\n};\n\n#endif  // TESTPSEUDOINVERSESVD_HPP_\n", "meta": {"hexsha": "07985cf2ceddb38a7a4ba0ef69713f24c2a2ed86", "size": 2791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/matrix/TestPseudoInverseSVD.hpp", "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": "test/matrix/TestPseudoInverseSVD.hpp", "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": "test/matrix/TestPseudoInverseSVD.hpp", "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": 28.1919191919, "max_line_length": 63, "alphanum_fraction": 0.5858115371, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6753389227924231}}
{"text": "\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"Functions.hpp\"\n#include \"Types.h\"\n#include \"NeuralNetwork.h\"\n#include \"MatrixUtils.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\nNeuralNetwork::NeuralNetwork(const std::vector<int>& layout,\n    const std::string& funcName, const bool randomSeed) : m_layout(layout) {\n    createLayers(randomSeed);\n    createActivationFunction(funcName);\n}\n\nvoid NeuralNetwork::createLayers(const bool randomSeed) {\n    // create layers. Ignore the first as this is the size of the input.\n    m_weights.reserve(m_layout.size()-1);\n\n    for (int i=1; i < m_layout.size(); ++i) {\n        // size of matrix is defined by the number of nodes (rows) and the\n        // size of the output vector from the previous layer (cols)\n        Eigen::MatrixXd weights = Eigen::MatrixXd::Zero(m_layout[i-1], m_layout[i]);\n        // initialise matrix with random numbers drawn from Gaussian with\n        // zero mean and unit variance\n        MatrixUtils::initializeRandomWeights(weights, randomSeed);\n\n        m_weights.push_back(weights);\n    }\n}\n\nvoid NeuralNetwork::createActivationFunction(const std::string& funcName) {\n    auto functions = FunctionFactory::create(funcName);\n    m_activation_func = functions.first;\n    m_activation_deriv = functions.second;\n}\n\nvoid NeuralNetwork::train(MatrixXd input, MatrixXd expected,\n    int maxIter, double alpha) {\n\n    //weight learning rate by number of examples in batch\n    alpha *= (1.0/input.rows());\n\n    for (int i=0; i <= maxIter; ++i) {\n\n        MatrixXd output = feedForward(input);\n        auto errors = backPropagate(output, expected);\n        updateWeights(errors, alpha);\n\n        if (i % 100 == 0) {\n            std::cout << \"Epoch \" << i << std::endl;\n        }\n    }\n\n}\n\nMatrixXd NeuralNetwork::feedForward(MatrixXd input) {\n    // Remove cached vectors from previous run\n    m_zVectors.clear();\n    m_activations.clear();\n\n    MatrixXd activation = input;\n    m_activations.push_back(activation);\n\n    for (int index=0; index < m_layout.size()-1; ++index) {\n        // compute weighted input for this layer\n        MatrixXd weights = m_weights[index];\n        MatrixXd z = activation * weights;\n        // cache result of weight-input combination for backprop\n        m_zVectors.push_back(z);\n        // compute the activation of function from the weighted input\n        activation = z.unaryExpr(m_activation_func);\n        // cache activation result of the weight-input combination for backprop\n        m_activations.push_back(activation);\n    }\n\n    m_activations.pop_back();  // remove last activation\n\n    return activation.transpose();\n}\n\nstd::vector<MatrixXd> NeuralNetwork::backPropagate(MatrixXd output,\n    MatrixXd actual) {\n\n    if (checkIfMatriciesSizeMatch(output, actual)) {\n        std::string msg = \"Output and actual vectors must match in size.\";\n        throw std::runtime_error(msg);\n    }\n\n    if (checkIfFeedForwardPerformed()) {\n        std::string msg = \"Backpropagation may only be run after feed forward.\";\n        throw std::runtime_error(msg);\n    }\n\n    std::vector<MatrixXd> errors;\n\n    // compute error for last layer of network\n    MatrixXd cost = quadratic_cost_derivative(output, actual);\n\n    MatrixXd sigmaPrime = getSigmaPrime();\n    MatrixXd a = getActivation();\n\n    MatrixXd delta = cost.transpose().cwiseProduct(sigmaPrime);\n    MatrixXd wError = delta.transpose() * a;\n\n    errors.push_back(wError);\n\n    // compute error in previous layers of network\n    for (int index = m_weights.size()-2; index >= 0; --index) {\n        MatrixXd weights = m_weights[index+1];\n        sigmaPrime = getSigmaPrime();\n        a = getActivation();\n\n        delta = (weights * delta.transpose()).cwiseProduct(sigmaPrime.transpose());\n        wError = delta * a;\n\n        errors.push_back(wError);\n    }\n\n    std::reverse(errors.begin(), errors.end());\n\n    return errors;\n}\n\nvoid NeuralNetwork::updateWeights(const std::vector<Eigen::MatrixXd>& errors,\n    double alpha) {\n\n    for (int i=0; i < m_weights.size(); ++i) {\n        MatrixXd wError = errors[i].transpose();\n        m_weights[i] = m_weights[i] - alpha * wError;\n    }\n}\n\nEigen::MatrixXd NeuralNetwork::getSigmaPrime() {\n    if (m_zVectors.empty()) {\n        std::runtime_error(\"Z value cache is empty.\");\n    }\n\n    MatrixXd z = m_zVectors.back();\n    m_zVectors.pop_back();  // remove z vector from cache\n    return z.unaryExpr(m_activation_deriv);\n}\n\nEigen::MatrixXd NeuralNetwork::getActivation() {\n    if (m_activations.empty()) {\n        std::runtime_error(\"Activation cache is empty.\");\n    }\n\n    MatrixXd a = m_activations.back();\n    m_activations.pop_back();\n    return a;\n}\n\nvoid NeuralNetwork::printWeights() {\n    for (int i =0; i < m_weights.size(); ++i) {\n        std::cout << \"Layer \" << i << \"------------------------\" << std::endl;\n        std::cout << m_weights[i] << std::endl;\n    }\n    std::cout << \"-------------------------------\" << std::endl;\n}\n", "meta": {"hexsha": "eea710b906a44edc35de17daac67ce1e11107285", "size": 5082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/NeuralNetwork.cpp", "max_stars_repo_name": "samueljackson92/cynapse", "max_stars_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/NeuralNetwork.cpp", "max_issues_repo_name": "samueljackson92/cynapse", "max_issues_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T16:31:03.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-30T07:06:21.000Z", "max_forks_repo_path": "src/core/NeuralNetwork.cpp", "max_forks_repo_name": "samueljackson92/cynapse", "max_forks_repo_head_hexsha": "29bd5a50edb8b5413aca094341a52cb4c85b186c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5465116279, "max_line_length": 84, "alphanum_fraction": 0.6507280598, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6753061869105655}}
{"text": "#include <iostream>\n#include <armadillo>\n\n\narma::sp_mat generateLinkMatrix(std::size_t nNodes, std::size_t maxEdgesPerNode) {\n\n\tarma::sp_mat linkMatrix{nNodes, nNodes};\n\tfor(int i=0; i<nNodes ; ++i){\n\t\tstd::size_t nLinks = rand() % (maxEdgesPerNode+1);\n\n\t\tstd::vector<std::size_t> pos;\n\t\tfor(int j=0; j<nNodes; ++j){\n\t\t\tpos.push_back(j);\n\t\t}\n\t\tpos.erase(std::begin(pos) + i);\n\t\t\n\t\tfor(int j=0; j<nLinks; ++j){\n\t\t\tstd::size_t index = rand() % pos.size();\n\t\t\tlinkMatrix(pos[index],i) = 1/static_cast<double>(nLinks); \n\t\t\tpos.erase(std::begin(pos)+index);\n\t\t}\n\t}\n\n\treturn linkMatrix;\n};\n\narma::vec rankSites(const arma::sp_mat& linkMatrix, const float& p) {\n\n\tarma::vec v = arma::ones<arma::vec>(linkMatrix.n_cols);\n\tdouble epsilon = 10e-10;\n\twhile (true) {\n\t\tauto previous = v;\n\t\tv = (p/linkMatrix.n_cols) * v + (1-p) * (linkMatrix * v);\n\t\tif (all((v-previous) < epsilon)){\n\t\t\tbreak;\n\t\t}\n\t}\t\n\n\treturn v;\n}\n\ndouble lerp(const double& value, \n\t\t\tconst double& minIn, double maxIn, \n\t\t\tconst double& minOut, const double& maxOut) {\n\treturn minOut + (value + minIn) * (maxOut - minOut)/(maxIn - minIn);\n\n}\nvoid makeGraph(const arma::sp_mat& linkMatrix, const arma::vec& rank) {\n\tusing namespace arma;\n\n\tstd::cout << \"digraph {\" << std::endl;\n\tstd::cout << \"\\tnode [style=\\\"filled\\\"]\" << std::endl;\n\tfor(int i=0; i< linkMatrix.n_cols; ++i) {\n\t\tsp_mat::const_iterator it     = linkMatrix.begin_col(i);\n\t\tsp_mat::const_iterator it_end = linkMatrix.end_col(i);\n\t\tstd::cout << \"\\t\" << i << \" [\"; \n\t\tstd::cout << \"fontsize=\" << \"\\\"\"<< lerp(rank[i], rank.min(), rank.max(), 10, 300)<< \"pt\\\"\";\n\t\tif(rank[i] == rank.max()) \n\t\t\tstd::cout << \" fillcolor=\" << \"\\\"green\\\"\";\n\t\tstd::cout << \"]\" << std::endl;\n\t\tfor(; it != it_end; ++it) {\n\t\t\tstd::cout << \"\\t\" << i << \"->\" << it.row() << std::endl;\n\t\t}\n\t}\n\tstd::cout << \"}\" << std::endl;\n}\n\nint main(int argc, char* argv[]) {\n\tsrand (time(NULL));\n\tarma::sp_mat A = generateLinkMatrix(atoi(argv[1]), atoi(argv[2]));\n\n\tarma::vec v = rankSites(A, atof(argv[3]));\n\n\tmakeGraph(A,v);\n}\n", "meta": {"hexsha": "d5c93b25cd06b8df7cfd30e9e3b7e7b51454ade7", "size": 2009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/page-rank.cpp", "max_stars_repo_name": "Grillo-0/PageRank-Demo", "max_stars_repo_head_hexsha": "91494d67a56941294bf89c485296da042709fdd8", "max_stars_repo_licenses": ["MIT"], "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/page-rank.cpp", "max_issues_repo_name": "Grillo-0/PageRank-Demo", "max_issues_repo_head_hexsha": "91494d67a56941294bf89c485296da042709fdd8", "max_issues_repo_licenses": ["MIT"], "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/page-rank.cpp", "max_forks_repo_name": "Grillo-0/PageRank-Demo", "max_forks_repo_head_hexsha": "91494d67a56941294bf89c485296da042709fdd8", "max_forks_repo_licenses": ["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.4342105263, "max_line_length": 93, "alphanum_fraction": 0.6012941762, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.675255765229293}}
{"text": "/* ! Example file that integrates the Lorenz system, showing how the structs defined in make_dace_compatible_with_odeint.hpp work.\n*/\n\n#include <dace/dace_s>\n#include <boost/numeric/odeint.hpp>\n#include <iostream>\n\nusing DACE;\nusing boost::numeric::odeint;\n\ntemplate <typename vectorType, typename timeType>\nvoid lorenz(const AlgebraicVector< vectorType >& x, AlgebraicVector< vectorType >& dxdt, const timeType& t)\n{\n    const double sigma = 10.0;\n    const double R = 28.0;\n    const double b = 8.0 / 3.0;\n    \n    dxdt.resize( x.size() );\n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R  * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];    \n}\n\nint main()\n{\n    /* Initialise DACE */\n    DACE::DA::init(8, 3); // 8th order, three variables\n  \n    /* Initial condition */\n    AlgebraicVector<DA> x({10.0, 5.0, 5.0});\n    x += 0.1 * DA::identity(3);\n\n    /* Define stepper type */\n    typedef runge_kutta_dopri5< AlgebraicVector<DA>, double ,AlgebraicVector<DA>,\n                              double, vector_space_algebra > stepper; // Notice vector_space_algebra!\n    int steps = integrate_adaptive( make_controlled<stepper>( 1E-10 , 1E-10 ), lorenz, x ,\n                                    0.0, 10.0, 0.1 );\n    std::cout << x << std::endl;\n    std::cout << \"steps: \" << steps << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "d0c09ffe7d5379722825b1472e74dd7068bcb8be", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/odeint/odeint_lorenz_example.cpp", "max_stars_repo_name": "tylerjackoliver/dace", "max_stars_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "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": "tools/odeint/odeint_lorenz_example.cpp", "max_issues_repo_name": "tylerjackoliver/dace", "max_issues_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "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": "tools/odeint/odeint_lorenz_example.cpp", "max_forks_repo_name": "tylerjackoliver/dace", "max_forks_repo_head_hexsha": "61ed32beb7a301175fa4a7c73ed7e1872dfb8e09", "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.0697674419, "max_line_length": 130, "alphanum_fraction": 0.5973053892, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6752557604091937}}
{"text": "\n#include <alglib/graph/directed_graph.h>\n#include <alglib/graph/shortest_path/dijkstra.h>\n\nusing namespace std;\nusing namespace alglib::graph;\n\n\nint main() {\n\n    using graph_type = directed_graph<int, int>;\n\n    // vertex_type = int; edge_attribute_type = int = weight\n    directed_graph<int, int> G;\n\n    for(int i = 0; i < 10; i++)\n        G.add_vertex(i);\n\n    G.add_edge(1, 3, 4);\n    G.add_edge(3, 5, 6);\n    G.add_edge(1, 5, 7);\n\n    dijkstra<graph_type> dijk (G, 1);\n\n    cout << dijk.shortest_dist_to (5) << endl;\n\n    vector<int> path;\n\n    dijk.shortest_path_to (5, back_inserter (path));\n    \n    cout << \"Shortest path is: \\n\";\n    for (int v : path)\n        cout << v << \"\\t\";\n    cout << endl;\n}\n", "meta": {"hexsha": "2815ca8e3787f352ff0386f74655d303ad0ebd12", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/dijkstra.cpp", "max_stars_repo_name": "divkakwani/alglib", "max_stars_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T13:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T12:30:03.000Z", "max_issues_repo_path": "test/graph/dijkstra.cpp", "max_issues_repo_name": "divkakwani/alglib", "max_issues_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/graph/dijkstra.cpp", "max_forks_repo_name": "divkakwani/alglib", "max_forks_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T14:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:30:28.000Z", "avg_line_length": 19.7777777778, "max_line_length": 60, "alphanum_fraction": 0.6011235955, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6752557515626767}}
{"text": "#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"cert-err58-cpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <optional>\n#include \"util/geometry/geometry.hpp\"\n#include \"util/geometry/Polygon.hpp\"\n\nusing aima::util::geometry::LineSegment;\nusing aima::util::geometry::Point;\nusing aima::util::geometry::Polygon;\nusing namespace boost::unit_test::data;\nusing boost::unit_test_framework::depends_on;\n\nnamespace aima::util::geometry {\n    std::ostream& boost_test_print_type( std::ostream& out, const std::optional<Point>& point ) {\n        if ( point ) {\n            out << *point;\n        }\n        else {\n            out << \"()\";\n        }\n        return out;\n    }\n}\n\nBOOST_AUTO_TEST_SUITE( geometry )\n\n    std::tuple<Point, LineSegment, bool> isOnSegmentData[]{\n            {\n                    Point{ 1, 1 },\n                    LineSegment{{ 0, 0 },\n                                { 2, 2 }},\n                    true\n            },\n            {\n                    Point{ 0, 0 },\n                    LineSegment{{ 0, 0 },\n                                { 0, 1 }},\n                    true\n            },\n            {\n                    Point{ 0, 0 },\n                    LineSegment{{ 1, 1 },\n                                { 2, 2 }},\n                    false\n            }\n    };\n\n    BOOST_DATA_TEST_CASE( isOnSegment, make( isOnSegmentData ), point, segment, expected ) {\n        BOOST_CHECK_EQUAL( aima::util::geometry::isOnSegment( point, segment ), expected );\n    }\n\n\n    using IntersectTestData = std::tuple<LineSegment, LineSegment, std::optional<Point>>[];\n\n    IntersectTestData lineIntersectData{\n            {\n                    LineSegment{{ 0,  0 },\n                                { .5, .5 }},\n                    LineSegment{{ 0, 2 },\n                                { 2, 0 }},\n                    Point{ 1, 1 }\n            },\n            {\n                    LineSegment{{ 1, 0 },\n                                { 3, 2 }},\n                    LineSegment{{ 1, 2 },\n                                { 3, 0 }},\n                    Point{ 2, 1 }\n            },\n            {\n                    LineSegment{{ 0, 0 },\n                                { 0, 1 }},\n                    LineSegment{{ 1, 0 },\n                                { 1, 1 }},\n                    std::nullopt\n            },\n            {\n                    LineSegment{{ 0, 0 },\n                                { 0, 1 }},\n                    LineSegment{{ 0, 3 },\n                                { 0, 2 }},\n                    std::nullopt\n            }\n    };\n\n    BOOST_DATA_TEST_CASE( lineIntersect, make( lineIntersectData ), p, q, expected ) {\n        BOOST_CHECK_EQUAL( aima::util::geometry::lineIntersect( p, q ), expected );\n    }\n\n\n    IntersectTestData segmentIntersectData{\n            {\n                    LineSegment{{ 0,  0 },\n                                { .5, .5 }},\n                    LineSegment{{ 0, 2 },\n                                { 2, 0 }},\n                    std::nullopt\n            },\n            {\n                    LineSegment{{ 0, 1 },\n                                { 1, 1 }},\n                    LineSegment{{ 0, 2 },\n                                { 1, 0 }},\n                    Point{ .5, 1 },\n            }\n    };\n\n    BOOST_TEST_DECORATOR( *depends_on( \"geometry/lineIntersect\" ))\n    BOOST_TEST_DECORATOR( *depends_on( \"geometry/isOnSegment\" ))\n\n    BOOST_DATA_TEST_CASE( segmentIntersect, make( segmentIntersectData ), p, q, expected ) {\n        BOOST_CHECK_EQUAL( aima::util::geometry::segmentIntersect( p, q ), expected );\n    }\n\n\n    std::tuple<Polygon, LineSegment, bool> isCutByData[]{\n            {\n                    Polygon{{{ 1, 1 }, { 1, 0 }, { 0, 0 }, { 0, 1 }}},\n                    LineSegment{{ 1, 0 },\n                                { 0, 2 }},\n                    true\n            }\n    };\n\n    BOOST_TEST_DECORATOR( *depends_on( \"geometry/segmentIntersect\" ))\n\n    BOOST_DATA_TEST_CASE( isCutBy, make( isCutByData ), polygon, lineSegment, expected ) {\n        BOOST_CHECK_EQUAL( aima::util::geometry::isCutBy( polygon, lineSegment ), expected );\n    }\n\nBOOST_AUTO_TEST_SUITE_END() // NOLINT(cert-err58-cpp)\n\n#pragma clang diagnostic pop", "meta": {"hexsha": "86545d9b6be295daaadf94086e492c32e5542b2a", "size": 4299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/PathFinder/geometry.cpp", "max_stars_repo_name": "Person-93/aima-cpp", "max_stars_repo_head_hexsha": "08d062dcb971edeaddb9a10083cf6da5a1b869f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/src/PathFinder/geometry.cpp", "max_issues_repo_name": "Person-93/aima-cpp", "max_issues_repo_head_hexsha": "08d062dcb971edeaddb9a10083cf6da5a1b869f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/src/PathFinder/geometry.cpp", "max_forks_repo_name": "Person-93/aima-cpp", "max_forks_repo_head_hexsha": "08d062dcb971edeaddb9a10083cf6da5a1b869f7", "max_forks_repo_licenses": ["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.3795620438, "max_line_length": 97, "alphanum_fraction": 0.429867411, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6752200724667372}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <algorithm>\n\ntypedef boost::adjacency_list<\n    boost::vecS,\n    boost::vecS,\n    boost::undirectedS,\n    boost::no_property,\n    boost::property<boost::edge_weight_t, int>>\n    Graph;\ntypedef boost::graph_traits<Graph>::edge_descriptor Edge;\n\nvoid testcase()\n{\n  int n, m;\n  std::cin >> n >> m;\n  assert(n >= 0 && n <= 100);\n  assert(m >= 0 && m <= n * (n - 1) / 2);\n\n  Graph G(n);\n  for (int i = 0; i < m; i++)\n  {\n    int a, b, w;\n    std::cin >> a >> b >> w;\n    boost::add_edge(a, b, w, G);\n  }\n\n  std::vector<Edge> spanning_tree;\n  boost::kruskal_minimum_spanning_tree(G, std::back_inserter(spanning_tree));\n\n  auto weights = boost::get(boost::edge_weight, G);\n  int sum_of_weights = 0;\n  for (auto edge : spanning_tree)\n  {\n    sum_of_weights += weights[edge];\n  }\n\n  std::vector<int> distances(n);\n  boost::dijkstra_shortest_paths(G, boost::vertex(0, G), boost::distance_map(boost::make_iterator_property_map(distances.begin(), boost::get(boost::vertex_index, G))));\n\n  std::cout\n      << sum_of_weights\n      << \" \"\n      << *std::max_element(distances.begin(), distances.end())\n      << \"\\n\";\n}\n\nint main()\n{\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  {\n    testcase();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "55c427d8f1e72ced70ce70af93cecfafa9d9a462", "size": 1430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-04/first-steps-with-bgl/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-04/first-steps-with-bgl/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-04/first-steps-with-bgl/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["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.6984126984, "max_line_length": 168, "alphanum_fraction": 0.627972028, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.675189479118324}}
{"text": "#define _USE_MATH_DEFINES\n#include \"gmmtree.h\"\n#include <Eigen/Eigenvalues>\n#include <cmath>\n\nusing namespace probreg;\n\nnamespace {\nstatic const Float eps = 1.0e-15;\n\nFloat gaussianPdf(const Vector3& x, const Vector3& mu, const Matrix3& cov) {\n    const Vector3 d = x - mu;\n    const Float det = cov.determinant();\n    if (det < eps) return 0.0;\n    const Float c = 1.0 / (std::pow(det, 0.5) * std::pow(2.0 * M_PI, x.size() * 0.5));\n    const Float ep = -0.5 * d.transpose() * cov.inverse() * d;\n    return c * std::exp(ep);\n}\n\nFloat logLikelihood(const NodeParamArray& nodes, const Matrix3X& points, Integer j0, Integer jn) {\n    Float q = 0.0;\n    for (Integer i = 0; i < points.cols(); ++i) {\n        Float tmp = 0.0;\n        for (Integer j = j0; j < jn; ++j) {\n            if (std::get<0>(nodes[j]) < eps) continue;\n            tmp += std::get<0>(nodes[j]) *\n                   gaussianPdf(points.col(i), std::get<1>(nodes[j]), std::get<2>(nodes[j]));\n        }\n        q += std::log(std::max(tmp, eps));\n    }\n    return q;\n}\n\nFloat complexity(const Matrix3& cov) {\n    Eigen::SelfAdjointEigenSolver<Matrix3> es(cov);\n    auto lmds = es.eigenvalues();\n    std::sort(lmds.data(), lmds.data() + lmds.size(), std::greater<Float>());\n    return lmds[2] / lmds.sum();\n}\n\nInteger child(Integer j) { return (j + 1) * N_NODE; }\n\nInteger level(Integer l) { return N_NODE * (std::pow(N_NODE, l) - 1) / (N_NODE - 1); }\n\nvoid accumulate(NodeParam& moments, Float gamma, const Vector& z) {\n    if (gamma < eps) return;\n    std::get<0>(moments) += gamma;\n    std::get<1>(moments) += gamma * z;\n    std::get<2>(moments) += gamma * z * z.transpose();\n}\n\nNodeParam mlEstimator(const NodeParam& moments, Integer n_points, Float lambda_d) {\n    NodeParam node;\n    std::get<0>(node) = std::get<0>(moments) / n_points;\n    if (std::get<0>(moments) < lambda_d) {\n        std::get<0>(node) = 0;\n        std::get<1>(node).fill(0.0);\n        std::get<2>(node) = Matrix3::Identity();\n    } else {\n        std::get<1>(node) = std::get<1>(moments) / std::get<0>(moments);\n        std::get<2>(node) =\n            std::get<2>(moments) / std::get<0>(moments) - std::get<1>(node) * std::get<1>(node).transpose();\n    }\n    return node;\n}\n\n}  // namespace\n\nNodeParamArray probreg::buildGmmTree(const Matrix3X& points,\n                                     Integer max_tree_level,\n                                     Float lambda_s,\n                                     Float lambda_d) {\n    const Integer n_total = N_NODE * (1 - std::pow(N_NODE, max_tree_level)) / (1 - N_NODE);\n    NodeParamArray nodes(n_total);\n    auto idxs = (n_total * Vector::Random(n_total)).array().abs().cast<Integer>();\n    Float sig2 = 0.0;\n    for (Integer i = 0; i < points.cols(); ++i) {\n        sig2 += (points.colwise() - points.col(i)).colwise().squaredNorm().sum();\n    }\n    sig2 /= points.cols() * points.cols() * points.rows() * N_NODE;\n    for (Integer j = 0; j < n_total; ++j) {\n        std::get<0>(nodes[j]) = 1.0 / N_NODE;\n        std::get<1>(nodes[j]) = points.col(idxs[j]);\n        std::get<2>(nodes[j]) = Matrix3::Identity() * sig2;\n    }\n    VectorXi parent_idx = -VectorXi::Ones(points.cols());\n    VectorXi current_idx = VectorXi::Zero(points.cols());\n\n    for (Integer l = 0; l < max_tree_level; ++l) {\n        Float prev_q = 0.0;\n        while (true) {\n            const NodeParamArray params =\n                gmmTreeEstep(points, nodes, parent_idx, current_idx, max_tree_level);\n            gmmTreeMstep(params, l, nodes, points.cols(), lambda_d);\n            const Float q = logLikelihood(nodes, points, level(l), level(l + 1));\n            if (std::abs(q - prev_q) < lambda_s) {\n                break;\n            }\n            prev_q = q;\n        }\n        parent_idx = current_idx;\n    }\n    return nodes;\n}\n\nNodeParamArray probreg::gmmTreeEstep(const Matrix3X& points,\n                                     const NodeParamArray& nodes,\n                                     const VectorXi& parent_idx,\n                                     VectorXi& current_idx,\n                                     Integer max_tree_level) {\n    const Integer n_total = N_NODE * (1 - std::pow(N_NODE, max_tree_level)) / (1 - N_NODE);\n    NodeParamArray moments(n_total);\n    for (Integer j = 0; j < n_total; ++j) {\n        std::get<0>(moments[j]) = 0.0;\n        std::get<1>(moments[j]).fill(0.0);\n        std::get<2>(moments[j]).fill(0.0);\n    }\n\n    for (Integer i = 0; i < points.cols(); ++i) {\n        const Integer j0 = child(parent_idx[i]);\n        Vector gamma = Vector::Zero(N_NODE);\n        for (Integer j = j0; j < j0 + N_NODE; ++j) {\n            gamma[j - j0] = std::get<0>(nodes[j]) *\n                            gaussianPdf(points.col(i), std::get<1>(nodes[j]), std::get<2>(nodes[j]));\n        }\n        const Float den = gamma.sum();\n        if (den > eps) {\n            gamma /= den;\n        }\n        else {\n            gamma.fill(0.0);\n        }\n        for (Integer j = j0; j < j0 + N_NODE; ++j) {\n            accumulate(moments[j], gamma[j - j0], points.col(i));\n        }\n        Integer max_j;\n        gamma.maxCoeff(&max_j);\n        current_idx[i] = j0 + max_j;\n    }\n    return moments;\n}\n\nvoid probreg::gmmTreeMstep(\n    const NodeParamArray& params, Integer l, NodeParamArray& nodes, Integer n_points, Float lambda_d) {\n    const Integer lb = level(l);\n    const Integer le = level(l + 1);\n\n    for (Integer j = lb; j < le; ++j) {\n        nodes[j] = mlEstimator(params[j], n_points, lambda_d);\n    }\n}\n\nNodeParamArray probreg::gmmTreeRegEstep(const Matrix3X& points,\n                                        const NodeParamArray& nodes,\n                                        Integer max_tree_level,\n                                        Float lambda_c) {\n    const Integer n_total = N_NODE * (1 - std::pow(N_NODE, max_tree_level)) / (1 - N_NODE);\n    NodeParamArray moments(n_total);\n    for (Integer j = 0; j < n_total; ++j) {\n        std::get<0>(moments[j]) = 0.0;\n        std::get<1>(moments[j]).fill(0.0);\n        std::get<2>(moments[j]).fill(0.0);\n    }\n\n    for (Integer i = 0; i < points.cols(); ++i) {\n        Integer search_id = -1;\n        Vector gamma = Vector::Zero(N_NODE);\n        for (Integer l = 0; l < max_tree_level; ++l) {\n            const Integer j0 = child(search_id);\n            for (Integer j = j0; j < j0 + N_NODE; ++j) {\n                gamma[j - j0] = std::get<0>(nodes[j]) *\n                                gaussianPdf(points.col(i), std::get<1>(nodes[j]), std::get<2>(nodes[j]));\n            }\n            const Float den = gamma.sum();\n            if (den > eps) {\n                gamma /= den;\n            } else {\n                gamma.fill(0.0);\n            }\n            gamma.maxCoeff(&search_id);\n            search_id += j0;\n            if (complexity(std::get<2>(nodes[search_id])) <= lambda_c) break;\n            accumulate(moments[search_id], gamma[search_id - j0], points.col(i));\n        }\n    }\n    return moments;\n}\n", "meta": {"hexsha": "e73803234d53bc9550224915e9db624c3c1d9772", "size": 6949, "ext": "cc", "lang": "C++", "max_stars_repo_path": "probreg/cc/gmmtree.cc", "max_stars_repo_name": "KentaKawamata/probreg", "max_stars_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probreg/cc/gmmtree.cc", "max_issues_repo_name": "KentaKawamata/probreg", "max_issues_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_issues_repo_licenses": ["MIT"], "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/gmmtree.cc", "max_forks_repo_name": "KentaKawamata/probreg", "max_forks_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T08:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T08:29:05.000Z", "avg_line_length": 36.9627659574, "max_line_length": 108, "alphanum_fraction": 0.5279896388, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9566342012360933, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.675178084508939}}
{"text": "/**\n * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1.\n *\n * @author FirstSanny\n */\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <utility>\n#include <vector>\n#include <climits>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include \"Dijkstra.h\"\n\n// Constants\nnamespace {\n\nconst char* FILEEND = \".gph\";\n\n}\n\n// declaring print\nusing std::cout;\nusing std::endl;\nusing std::cerr;\nusing std::string;\n\n// declaring types\nnamespace po = boost::program_options;\nusing Graph = boost::adjacency_list<boost::listS, boost::vecS,\n  boost::undirectedS, boost::no_property,\n  boost::property<boost::edge_weight_t, double>> ;\nusing VertexDescriptor = boost::graph_traits < Graph >::vertex_descriptor;\nusing Directions = std::vector<VertexDescriptor >;\nusing Edge = std::pair<int, int >;\nusing Edges = std::vector<Edge >;\nusing Weights = std::vector<double >;\n\npo::variables_map parseCommandLine(po::options_description desc, int argn,\n\t\tchar* argv[]) {\n\tdesc.add_options()(\"help\", \"produce help message\")(\"algo,m\",\n\t\t\tpo::value<int>(),\n\t\t\t\"algorithm to solve shortest Path. \\n 1 - libary (boost)\\n 2 - own Algo\")(\n\t\t\t\"input-file\", po::value<string>(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\tpo::variables_map vm;\n\tpo::store(\n\t\t\tpo::command_line_parser(argn, argv).options(desc).positional(p).run(),\n\t\t\tvm);\n\tpo::notify(vm);\n\treturn vm;\n}\n\nchar parseAlgoOption(const po::variables_map& vm, char useOwnAlgo) {\n\tif (vm.count(\"algo\")) {\n\t\tuseOwnAlgo = vm[\"algo\"].as<int>();\n\t\tuseOwnAlgo--;\n\t}\n\tif (useOwnAlgo != 1 && useOwnAlgo != 0) {\n\t\tcout << \"No valid Option was given for Algorithm! Fallback: algo from libary\" << endl;\n\t\tuseOwnAlgo = 0;\n\t}\n\tif (useOwnAlgo) {\n\t\tcout << \"Using own algorithm...\" << endl;\n\t} else {\n\t\tcout << \"Using algorithm from boost-libary...\" << endl;\n\t}\n\treturn useOwnAlgo;\n}\n\n/** Reading in a Graphfile, computes the longest shortest path */\nint main(int argn, char *argv[]) {\n\tboost::timer::auto_cpu_timer t;\n\tif (argn <= 1) {\n\t\tcerr << \"ERROR : There was no filename\" << endl;\n\t\treturn 1;\n\t}\n\n\tpo::options_description desc(\"Allowed options\");\n\tpo::variables_map vm = parseCommandLine(desc, argn, argv);\n\n\tif (vm.count(\"help\")) {\n\t    cout << desc << \"\\n\";\n\t    return 1;\n\t}\n\tchar useOwnAlgo = 0;\n\tuseOwnAlgo = parseAlgoOption(vm, useOwnAlgo);\n\n\tstd::ifstream fileStream;\n\tif(vm.count(\"input-file\") == 0){\n\t\tcerr << \"No input-file was given!\" << endl;\n\t\treturn 1;\n\t}\n\n\tstring filename = vm[\"input-file\"].as<string >();\n\tfilename += FILEEND;\n\tcout << \"Going to parse the file \" << filename << endl;\n\tfileStream.open(filename.c_str(), std::ios::in);\n\n\tif ( (fileStream.rdstate()) != 0 ){\n\t\tstd::perror(\"ERROR : Encoutered Problem opening file\");\n\t\treturn 1;\n\t}\n\n\tstring line;\n\n\tunsigned int edgeCount;\n\tunsigned int vertexCount;\n\n\tif(std::getline(fileStream, line)){\n\t\tsscanf(line.c_str(), \"%d %d\", &vertexCount, &edgeCount);\n\t\tcout << \"Vertexcount: \" << vertexCount << endl;\n\t\tcout << \"Edgecount: \" << edgeCount << endl;\n\t\tline.clear();\n\t\tvertexCount++;\n\t} else {\n\t\tcerr << \"ERROR : File was empty\" << endl;\n\t\treturn 1;\n\t}\n\n\tEdges* edges = new Edges(edgeCount);\n\tWeights* weights = new Weights(edgeCount);\n\n\tcout << \"Reading edges...\" << endl;\n\twhile (getline(fileStream, line)) {\n\t\tint start;\n\t\tint end;\n\t\tdouble weight;\n\t\tint count = sscanf(line.c_str(), \"%d %d %lf\", &start, &end, &weight);\n\t\tif (count != 3) {\n\t\t\tline.clear();\n\t\t\tcontinue;\n\t\t}\n\t\tedges->push_back(std::make_pair(start, end));\n\t\tweights->push_back(weight);\n\t\tline.clear();\n\t}\n\n\tWeights weightsForShortestpath;\n\n\tif(useOwnAlgo){\n\t\tcout << \"Compute shortest paths via Dijkstra(own)...\" << endl;\n\t\tDijkstra* d = new Dijkstra();\n\t\tweightsForShortestpath = d->dijkstra(vertexCount, *edges, *weights, 1);\n\t\tdelete d;\n\t} else {\n\n\t\tcout << \"Creating graph...\" << endl;\n\t\tGraph g{edges->begin(), edges->end(), weights->begin(), vertexCount};\n\n\t\tDirections* directions = new std::vector<VertexDescriptor>(vertexCount);\n\t\tcout << \"Compute shortest paths via Dijkstra(boost)...\" << endl;\n\t\tWeights* weightMapPointer = new Weights(vertexCount);\n\t\tboost::dijkstra_shortest_paths(g, 1,\n\t\t\tboost::predecessor_map(//\n\t\t\t\t\tboost::make_iterator_property_map(directions->begin(), boost::get(boost::vertex_index, g))) //\n\t\t\t\t.distance_map(//\n\t\t\t\t\tboost::make_iterator_property_map(weightMapPointer->begin(), boost::get(boost::vertex_index, g))));\n\t\tweightsForShortestpath = *weightMapPointer;\n\t\tdelete weightMapPointer;\n\t\tdelete directions;\n\t}\n\n\tcout << \"Search longest shortest path...\" << endl;\n\tint vertex = 1;\n\tdouble distance = 0.;\n\n\tfor(unsigned int i=2; i<vertexCount; i++){\n\t\tif(weightsForShortestpath[i]>distance){\n\t\t\tdistance = weightsForShortestpath[i];\n\t\t\tvertex = i;\n\t\t}\n\t}\n\n\tcout << \"RESULT VERTEX \" << vertex << endl;\n\tcout << \"RESULT DIST \" << std::fixed << std::setprecision(2) << distance << endl;\n\n\tdelete edges;\n\tdelete weights;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "516c926ff1b5c2368d79076d0632244279c2a621", "size": 5147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sanny/ex5/src/c/ex5.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Sanny/ex5/src/c/ex5.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Sanny/ex5/src/c/ex5.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.2328042328, "max_line_length": 149, "alphanum_fraction": 0.6745677093, "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.675126848279375}}
{"text": "/* Boost test/pow.cpp\n * test the pow function\n *\n * Copyright 2002-2003 Guillaume Melquiond\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#include <boost/numeric/interval.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include \"bugs.hpp\"\n\nbool test_pow(double al, double au, double bl, double bu, int p) {\n  typedef boost::numeric::interval<double> I;\n  I b = pow(I(al, au), p);\n  return b.lower() == bl && b.upper() == bu;\n}\n\nint main() {\n  BOOST_TEST(test_pow(2, 3, 8, 27, 3));\n  BOOST_TEST(test_pow(2, 3, 16, 81, 4));\n  BOOST_TEST(test_pow(-3, 2, -27, 8, 3));\n  BOOST_TEST(test_pow(-3, 2, 0, 81, 4));\n  BOOST_TEST(test_pow(-3, -2, -27, -8, 3));\n  BOOST_TEST(test_pow(-3, -2, 16, 81, 4));\n\n  BOOST_TEST(test_pow(2, 4, 1./64, 1./8, -3));\n  BOOST_TEST(test_pow(2, 4, 1./256, 1./16, -4));\n  BOOST_TEST(test_pow(-4, -2, -1./8, -1./64, -3));\n  BOOST_TEST(test_pow(-4, -2, 1./256, 1./16, -4));\n\n  BOOST_TEST(test_pow(2, 3, 1, 1, 0));\n  BOOST_TEST(test_pow(-3, 2, 1, 1, 0));\n  BOOST_TEST(test_pow(-3, -2, 1, 1, 0));\n\n# ifdef BOOST_BORLANDC\n  ::detail::ignore_warnings();\n# endif\n  return boost::report_errors();\n}\n", "meta": {"hexsha": "78c043286cb4480f0ec5750e5ad87a95680ad394", "size": 1229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/pow.cpp", "max_stars_repo_name": "samd2/interval", "max_stars_repo_head_hexsha": "53ba1b16e8353583b3fb77cacac2e322b9b87b25", "max_stars_repo_licenses": ["BSL-1.0"], "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": "test/pow.cpp", "max_issues_repo_name": "samd2/interval", "max_issues_repo_head_hexsha": "53ba1b16e8353583b3fb77cacac2e322b9b87b25", "max_issues_repo_licenses": ["BSL-1.0"], "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": "test/pow.cpp", "max_forks_repo_name": "samd2/interval", "max_forks_repo_head_hexsha": "53ba1b16e8353583b3fb77cacac2e322b9b87b25", "max_forks_repo_licenses": ["BSL-1.0"], "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": 28.5813953488, "max_line_length": 66, "alphanum_fraction": 0.6338486574, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.6751013242730932}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n\nTEST(AgradRev, atan2_var_var) {\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a, b);\n  EXPECT_FLOAT_EQ(atan2(1.2, 3.9), f.val());\n\n  AVEC x = createAVEC(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9), g[1]);\n}\n\nTEST(AgradRev, atan2_dvd) {\n  AVAR sigma = 1;\n  AVEC x = createAVEC(sigma);\n  AVAR f = atan2(1.0, sigma) / 3.14;\n  VEC g;\n  f.grad(x, g);\n\n  AVAR sigma1 = 1;\n  AVEC x1 = createAVEC(sigma1);\n  AVAR f1 = atan2(1.0, sigma1);\n  VEC g1;\n  f1.grad(x1, g1);\n\n  EXPECT_FLOAT_EQ(3.14 * g[0], g1[0]);\n}\nTEST(AgradRev, atan2_var_var__integration) {\n  double c = 5.0;\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a, b) * c;\n  EXPECT_FLOAT_EQ(atan2(1.2, 3.9) * c, f.val());\n\n  AVEC x = createAVEC(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9) * c, g[0]);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9) * c, g[1]);\n}\n\nTEST(AgradRev, atan2_var_double) {\n  AVAR a = 1.2;\n\n  double b = 3.9;\n  AVAR f = atan2(a, b);\n  EXPECT_FLOAT_EQ(atan2(1.2, 3.9), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(3.9 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n}\n\nTEST(AgradRev, atan2_double_var) {\n  double a = 1.2;\n  AVAR b = 3.9;\n  AVAR f = atan2(a, b);\n  EXPECT_FLOAT_EQ(atan2(1.2, 3.9), f.val());\n\n  AVEC x = createAVEC(b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(-1.2 / (1.2 * 1.2 + 3.9 * 3.9), g[0]);\n}\n\nstruct atan2_fun {\n  template <typename T0, typename T1>\n  inline typename stan::return_type<T0, T1>::type operator()(\n      const T0& arg1, const T1& arg2) const {\n    return atan2(arg1, arg2);\n  }\n};\n\nTEST(AgradRev, atan2_nan) {\n  atan2_fun atan2_;\n  test_nan(atan2_, 3.0, 5.0, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 1.2;\n  AVAR b = 3.9;\n  test::check_varis_on_stack(stan::math::atan2(a, b));\n  test::check_varis_on_stack(stan::math::atan2(a, 3.9));\n  test::check_varis_on_stack(stan::math::atan2(1.2, b));\n}\n", "meta": {"hexsha": "7c6a425b681c85e8fde358072a20f1e507359cd6", "size": 2198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/scal/fun/atan2_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/rev/scal/fun/atan2_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/rev/scal/fun/atan2_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3829787234, "max_line_length": 61, "alphanum_fraction": 0.6005459509, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6751013212811023}}
{"text": "/*******************************************************************************\n* Copyright 2016 ROBOTIS CO., LTD.\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/* Authors: Hye-Jong KIM */\n\n#ifndef OMMATH_HPP_\n#define OMMATH_HPP_\n\n#include \"../../include/open_manipulator/OMDebug.hpp\"\n\n#include <Eigen.h>        // Calls main Eigen matrix class library\n#include <Eigen/LU>       // Calls inverse, determinant, LU decomp., etc.\n\n#include <math.h>\n\n#define DEG2RAD (M_PI / 180.0)\n#define RAD2DEG (180.0 / M_PI)\n\nclass OMMath\n{\n public:\n  OMMath(){}\n  ~OMMath(){}\n\n  float sign(float number)\n  {\n    if (num >= 0.0)\n    {\n      return 1.0;\n    }\n    else\n    {\n      return -1.0;\n    }\n  }\n\n  Eigen::Vector3f makeEigenVector3(float v1, float v2, float v3)\n  {\n    Eigen::Vector3f temp;\n    temp << v1, v2, v3;\n    return temp;\n  }\n\n  Eigen::Matrix3f makeEigenMatrix3(float m11, float m12, float m13, float m21, float m22, float m23, float m31, float m32, float m33)\n  {\n    Eigen::Matrix3f temp;\n    temp << m11, m12, m13, m21, m22, m23, m31, m32, m33;\n    return temp;\n  }\n  \n  Eigen::Matrix3f makeRotationMatrix(float roll, float pitch, float yaw)\n  {\n    Eigen::Matrix3f rotation_matrix;\n    Eigen::Matrix3f roll_matrix;\n    Eigen::Matrix3f pitch_matrix;\n    Eigen::Matrix3f yaw_matrix;\n\n    roll_matrix  << 1.000,  0.000,     0.000,\n                    0.000,  cos(roll), sin(roll),\n                    0.000, -sin(roll), cos(roll);\n\n    pitch_matrix << cos(pitch),  0.000, sin(pitch),\n                    0.000,       1.000, 0.000,\n                    -sin(pitch), 0.000, cos(pitch);\n\n    yaw_matrix   << cos(yaw), -sin(yaw), 0.000,\n                    sin(yaw), cos(yaw),  0.000,\n                    0.000,    0.000,     1.000;\n    \n    rotation_matrix = roll_matrix * pitch_matrix * yaw_matrix;\n\n    return rotation_matrix;\n  }\n\n  Eigen::Matrix3f makeRotationMatrix(Eigen::Vector3f rotation_vector)\n  {\n    Eigen::Matrix3f rotation_matrix;\n    rotation_matrix = makeRotationMatrix(rotation_vector(0), rotation_vector(1), rotation_vector(2));\n    return rotation_matrix;\n  }\n  \n  Eigen::Vector3f makeRotationVector(Eigen::Matrix3f rotation_matrix)\n  {\n    Eigen::Matrix3f R = rotation_matrix;\n    Eigen::Vector3f l = Eigen::Vector3f::Zero();\n    Eigen::Vector3f rotation_vector = Eigen::Vector3f::Zero();\n\n    float theta = 0.0;\n    float diag  = 0.0;\n    bool diagonal_matrix = true;\n\n    l << R(2,1) - R(1,2),\n         R(0,2) - R(2,0),\n         R(1,0) - R(0,1);\n    theta = atan2(l.norm(), R(0,0) + R(1,1) + R(2,2) - 1);\n    diag  = R(0,0) + R(1,1) + R(2,2);\n\n    for (int8_t i = 0; i < 3; i++)\n    {\n      for (int8_t j = 0; j < 3; j++)\n      {\n        if (i != j)\n        {\n          if (R(i, j) != 0)\n          {\n            diagonal_matrix = false;\n          }\n        }\n      }\n    }\n    if (R == Eigen::Matrix3f::Identity())\n    {\n      rotation_vector = Eigen::Vector3f::Zero();\n    }\n    else if (diagonal_matrix == true)\n    {\n      rotation_vector << R(0,0) + 1, R(1,1) + 1, R(2,2) + 1;\n      rotation_vector = rotation_vector * M_PI_2;\n    }\n    else\n    {\n      rotation_vector = theta * (l / l.norm());\n    }\n    return rotation_vector;\n  }\n\n  Eigen::Matrix3f skewSymmetricMatrix(Eigen::Vector3f v)\n  {\n    Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n\n    skew_symmetric_matrix <<    0,  -v(2),  v(1),\n                            v(2),      0, -v(0),\n                            -v(1),   v(0),     0;\n\n    return skew_symmetric_matrix;\n  }\n\n  Eigen::Matrix3f rodriguesRotationMatrix(Eigen::Vector3f axis, float angle)\n  {\n    Eigen::Matrix3f skew_symmetric_matrix = Eigen::Matrix3f::Zero();\n    Eigen::Matrix3f rotation_matrix = Eigen::Matrix3f::Zero();\n    Eigen::Matrix3f Identity_matrix = Eigen::Matrix3f::Identity();\n\n    skew_symmetric_matrix = skewSymmetricMatrix(axis);\n    rotation_matrix = Identity_matrix +\n                      skew_symmetric_matrix * sin(angle) +\n                      skew_symmetric_matrix * skew_symmetric_matrix * (1 - cos(angle));\n\n    return rotation_matrix;\n  }\n  \n  Eigen::Vector3f differentialPosition(Eigen::Vector3f desired_position, Eigen::Vector3f present_position)\n  {\n    Eigen::Vector3f differential_position;\n    differential_position = desired_position - present_position;\n\n    return differential_position;\n  }\n\n  Eigen::Vector3f differentialOrientation(Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n  {\n    Eigen::Vector3f differential_orientation;\n    differential_orientation = present_orientation * makeRotationVector(present_orientation.transpose() * desired_orientation);\n\n    return differential_orientation;\n  }\n\n\n  Eigen::VectorXf differentialPose(Eigen::Vector3f desired_position, Eigen::Vector3f present_position, Eigen::Matrix3f desired_orientation, Eigen::Matrix3f present_orientation)\n  {\n    Eigen::Vector3f differential_position;\n    Eigen::Vector3f differential_orientation;\n    Eigen::VectorXf  differential_pose(6);\n\n    differential_position = differentialPosition(desired_position, present_position);\n    differential_orientation = differentialOrientation(desired_orientation, present_orientation)\n    differential_pose << differential_position(0),\n                         differential_position(1),\n                         differential_position(2),\n                         differential_orientation(0),\n                         differential_orientation(1),\n                         differential_orientation(2);\n    return differential_pose;\n  }\n};\n\n#endif // OMMATH_HPP_\n", "meta": {"hexsha": "892ed07feddc9d397e02712c67c41ed0fe2bff78", "size": 6091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arduino/opencr_arduino/opencr/libraries/OpenManipulator/include/open_manipulator/OMMath.hpp", "max_stars_repo_name": "yemiaobing/opencr", "max_stars_repo_head_hexsha": "8700d276f60cb72db4f1ed85deff26a5f96ce7b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T05:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-09T05:56:55.000Z", "max_issues_repo_path": "arduino/opencr_arduino/opencr/libraries/OpenManipulator/include/open_manipulator/OMMath.hpp", "max_issues_repo_name": "yemiaobing/opencr", "max_issues_repo_head_hexsha": "8700d276f60cb72db4f1ed85deff26a5f96ce7b6", "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": "arduino/opencr_arduino/opencr/libraries/OpenManipulator/include/open_manipulator/OMMath.hpp", "max_forks_repo_name": "yemiaobing/opencr", "max_forks_repo_head_hexsha": "8700d276f60cb72db4f1ed85deff26a5f96ce7b6", "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.3034825871, "max_line_length": 176, "alphanum_fraction": 0.6148415695, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6750977223933293}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file linear_algebra.hpp\n * \\date January 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <vector>\n\nnamespace fl\n{\n/**\n * \\ingroup linear_algebra\n *\n * \\brief Blockweise matrix inversion using the Sherman-Morrision-Woodbury\n * indentity given that \\f$\\Sigma^{-1}_{aa}\\f$ of\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1}\n * \\f$\n *\n * is already available.\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1} =\n * \\begin{pmatrix} \\Lambda_{aa} & \\Lambda_{ab} \\\\\n *                 \\Lambda_{ba} & \\Lambda_{bb} \\end{pmatrix} = \\Lambda\n * \\f$\n *\n * \\param [in]  A_inv   \\f$ \\Sigma^{-1}_{aa} \\f$\n * \\param [in]  B       \\f$ \\Sigma_{ab} \\f$\n * \\param [in]  C       \\f$ \\Sigma_{ba} \\f$\n * \\param [in]  D       \\f$ \\Sigma_{bb} \\f$\n * \\param [out] L_A     \\f$ \\Lambda_{aa} \\f$\n * \\param [out] L_B     \\f$ \\Lambda_{ab} \\f$\n * \\param [out] L_C     \\f$ \\Lambda_{ba} \\f$\n * \\param [out] L_D     \\f$ \\Lambda_{bb} \\f$\n */\ntemplate <typename MatrixAInv,\n          typename MatrixB,\n          typename MatrixC,\n          typename MatrixD,\n          typename MatrixLA,\n          typename MatrixLB,\n          typename MatrixLC,\n          typename MatrixLD>\ninline void smw_inverse(const MatrixAInv& A_inv,\n                        const MatrixB& B,\n                        const MatrixC& C,\n                        const MatrixD& D,\n                        MatrixLA& L_A,\n                        MatrixLB& L_B,\n                        MatrixLC& L_C,\n                        MatrixLD& L_D)\n{\n    auto&& AinvB = (A_inv * B).eval();\n\n    L_D = (D - C * AinvB).inverse();\n    L_C = -(L_D * C * A_inv).eval();\n    L_A = A_inv - AinvB * L_C;\n    L_B = L_C.transpose();\n}\n\n/**\n * \\ingroup linear_algebra\n *\n * \\brief Blockweise matrix inversion using the Sherman-Morrision-Woodbury\n * indentity given that \\f$\\Sigma^{-1}_{aa}\\f$ of\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1}\n * \\f$\n *\n * is already available.\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1} =\n * \\begin{pmatrix} \\Lambda_{aa} & \\Lambda_{ab} \\\\\n *                 \\Lambda_{ba} & \\Lambda_{bb} \\end{pmatrix} = \\Lambda\n * \\f$\n *\n * \\param [in]  A_inv   \\f$ \\Sigma^{-1}_{aa} \\f$\n * \\param [in]  B       \\f$ \\Sigma_{ab} \\f$\n * \\param [in]  C       \\f$ \\Sigma_{ba} \\f$\n * \\param [in]  D       \\f$ \\Sigma_{bb} \\f$\n * \\param [out] L_A     \\f$ \\Lambda_{aa} \\f$\n * \\param [out] L_B     \\f$ \\Lambda_{ab} \\f$\n * \\param [out] L_C     \\f$ \\Lambda_{ba} \\f$\n * \\param [out] L_D     \\f$ \\Lambda_{bb} \\f$\n * \\param [out] L       \\f$ \\Lambda \\f$\n */\ntemplate <typename MatrixAInv,\n          typename MatrixB,\n          typename MatrixC,\n          typename MatrixD,\n          typename MatrixLA,\n          typename MatrixLB,\n          typename MatrixLC,\n          typename MatrixLD,\n          typename ResultMatrix>\ninline void smw_inverse(const MatrixAInv& A_inv,\n                        const MatrixB& B,\n                        const MatrixC& C,\n                        const MatrixD& D,\n                        MatrixLA& L_A,\n                        MatrixLB& L_B,\n                        MatrixLC& L_C,\n                        MatrixLD& L_D,\n                        ResultMatrix& L)\n{\n    smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D);\n\n    L.resize(L_A.rows() + L_C.rows(), L_A.cols() + L_B.cols());\n\n    L.block(0, 0, L_A.rows(), L_A.cols()) = L_A;\n    L.block(0, L_A.cols(), L_B.rows(), L_B.cols()) = L_B;\n    L.block(L_A.rows(), 0, L_C.rows(), L_C.cols()) = L_C;\n    L.block(L_A.rows(), L_A.cols(), L_D.rows(), L_D.cols()) = L_D;\n}\n\n/**\n * \\ingroup linear_algebra\n *\n * \\brief Blockweise matrix inversion using the Sherman-Morrision-Woodbury\n * indentity given that \\f$\\Sigma^{-1}_{aa}\\f$ of\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1}\n * \\f$\n *\n * is already available.\n *\n * \\f$\n *  \\begin{pmatrix} \\Sigma_{aa} & \\Sigma_{ab} \\\\\n *                  \\Sigma_{ba} & \\Sigma_{bb} \\end{pmatrix}^{-1} =\n * \\begin{pmatrix} \\Lambda_{aa} & \\Lambda_{ab} \\\\\n *                 \\Lambda_{ba} & \\Lambda_{bb} \\end{pmatrix} = \\Lambda\n * \\f$\n *\n * \\param [in]  A_inv   \\f$ \\Sigma^{-1}_{aa} \\f$\n * \\param [in]  B       \\f$ \\Sigma_{ab} \\f$\n * \\param [in]  C       \\f$ \\Sigma_{ba} \\f$\n * \\param [in]  D       \\f$ \\Sigma_{bb} \\f$\n * \\param [out] L       \\f$ \\Lambda \\f$\n */\ntemplate <typename MatrixAInv,\n          typename MatrixB,\n          typename MatrixC,\n          typename MatrixD,\n          typename ResultMatrix>\ninline void smw_inverse(const MatrixAInv& A_inv,\n                        const MatrixB& B,\n                        const MatrixC& C,\n                        const MatrixD& D,\n                        ResultMatrix& L)\n{\n    MatrixAInv L_A;\n    MatrixB L_B;\n    MatrixC L_C;\n    MatrixD L_D;\n\n    smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D, L);\n}\n\n///**\n// * \\ingroup linear_algebra\n// *\n// * \\brief Normalizes the values of input vector such that their sum is equal\n// to\n// * the specified \\c sum. For instance, any convex combination requires that\n// the\n// * weights of the weighted sum sums up to 1.\n// */\n// template <typename T>\n// inline std::vector<T> normalize(const std::vector<T>& input, T sum)\n//{\n//    T old_sum = 0;\n//    for(size_t i = 0; i < input.size(); i++)\n//    {\n//        old_sum += input[i];\n//    }\n//    T factor = sum/old_sum;\n\n//    std::vector<T> output(input.size());\n//    for(size_t i = 0; i < input.size(); i++)\n//    {\n//        output[i] = factor*input[i];\n//    }\n\n//    return output;\n//}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Constructs the quaternion matrix for the specified quaternion vetcor\n *\n * \\param q_xyzw  Quaternion vector\n *\n * \\return Matrix representation of the quaternion vector\n */\ninline Eigen::Matrix<double, 4, 3> quaternion_matrix(\n    const Eigen::Matrix<double, 4, 1>& q_xyzw)\n{\n    Eigen::Matrix<double, 4, 3> Q;\n    Q << q_xyzw(3), q_xyzw(2), -q_xyzw(1), -q_xyzw(2), q_xyzw(3), q_xyzw(0),\n        q_xyzw(1), -q_xyzw(0), q_xyzw(3), -q_xyzw(0), -q_xyzw(1), -q_xyzw(2);\n\n    return 0.5 * Q;\n}\n\n/**\n * \\ingroup linear_algebra\n * \\todo DOC\n * \\todo Implement numerically robust version and test it\n */\ntemplate <typename RegularMatrix, typename SquareRootMatrix>\nvoid square_root(const RegularMatrix& regular_matrix,\n                 SquareRootMatrix& square_root)\n{\n    square_root = regular_matrix.llt().matrixL();\n\n//    typedef Eigen::Matrix<typename RegularMatrix::Scalar,\n//                          RegularMatrix::SizeAtCompileTime,\n//                          1> Vector;\n\n//    Eigen::LDLT<RegularMatrix> ldlt;\n//    ldlt.compute(regular_matrix);\n//    Vector D_sqrt = ldlt.vectorD();\n//    for (int i = 0; i < D_sqrt.rows(); ++i)\n//    {\n//        D_sqrt(i) = std::sqrt(std::fabs(D_sqrt(i)));\n//    }\n\n//    return ldlt.transpositionsP().transpose() * (Matrix)ldlt.matrixL() *\n//           D_sqrt.asDiagonal();\n}\n\n/**\n * \\ingroup linear_algebra\n * \\todo DOC\n */\ntemplate <typename RegularMatrix>\nvoid sqrt_diagonal(const RegularMatrix& regular_matrix,\n                   RegularMatrix& square_root)\n{\n    square_root = regular_matrix;\n    for (size_t i = 0; i < square_root.rows(); ++i)\n    {\n        square_root(i, i) = std::sqrt(square_root(i, i));\n    }\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Computes the square root of each element of the regular_matrix\n */\ntemplate <typename RegularMatrix, typename SquareRootVector>\nvoid sqrt_diagonal_vector(const RegularMatrix& diagonal_vector,\n                          SquareRootVector& square_root)\n{\n    square_root = diagonal_vector;\n    for (size_t i = 0; i < square_root.rows(); ++i)\n    {\n        square_root(i, 0) = std::sqrt(square_root(i, 0));\n    }\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Inverts a diagonal matrix represented by a vector. The result is again\n *        a vector of the inverted diagonal elements.\n */\ntemplate <typename SrcDiagonalMatrix, typename DestDiagonalMatrix>\nvoid invert_diagonal_vector(const SrcDiagonalMatrix& diagonal,\n                            DestDiagonalMatrix& diagonal_inverse)\n{\n    diagonal_inverse = diagonal.array().cwiseInverse();\n\n    //    diagonal_inverse.resize(diagonal.size());\n    //    for (int i = 0; i < diagonal.size(); ++i)\n    //    {\n    //        diagonal_inverse(i) = 1./diagonal(i);\n    //    }\n}\n\n/**\n * \\ingroup linear_algebra\n *\n * \\brief Computes the Frobenius norm of a given real matrix.\n *\n * The Frobenius norm is given by\n *\n * \\f$\n *   \\| A \\|_F := \\sqrt{\\sum\\limits_{i=1}^m \\sum\\limits_{j=1}^n |a_{ij} |^2 }\n * \\f$\n */\ntemplate <typename Derived>\ndouble frobenius_norm(const Eigen::MatrixBase<Derived>& a)\n{\n    return std::sqrt(a.array().abs().square().sum());\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Checks whether two matrices of the same size are similiar w.r.t. some\n * \\f$\\epsilon\\f$.\n *\n * The similarity check is performed based on the Frobenius Norm\n * (\\ref frobenius_norm):\n *\n * For any real matrix set \\f$M \\subseteq \\mathbb{R}^{m\\times n} \\f$\n *\n * \\f$ \\text{are_similar}: (M \\times M) \\mapsto \\{0, 1\\}\\f$\n *\n * \\f$ \\text{are_similar}(a, b)\n *     := \\mathbf{1}_{[0, \\epsilon)}\\left(\\| a - b \\|_F\\right)\\f$\n * with \\f$ a, b \\in M\\f$ and the indicator function\n *\n * \\f$ \\mathbf{1}_{[0, \\epsilon)}(x) :=\n *     \\begin{cases} 1 & x \\in [0, \\epsilon)\n *                  \\\\ 0, & \\text{otherwise} \\end{cases}\\f$\n */\n// template <typename DerivedA, typename DerivedB>\n// bool are_similar(const Eigen::MatrixBase<DerivedA>& a,\n//                 const Eigen::MatrixBase<DerivedB>& b,\n//                 const double epsilon = 1.e-6)\n//{\n//    return frobenius_norm(a - b) < epsilon;\n//}\n\ntemplate <typename DerivedA, typename DerivedB>\nbool are_similar(const Eigen::MatrixBase<DerivedA>& a,\n                 const Eigen::MatrixBase<DerivedB>& b,\n                 const double epsilon = 1.e-6)\n{\n    // return (a - b).cwiseAbs().maxCoeff() < epsilon;\n    return frobenius_norm(a - b) < epsilon;\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Robust decomposition of M = L*L^T for positive semidefinite matrices\n */\ntemplate <typename Scalar, int Size>\nEigen::Matrix<Scalar, Size, Size> matrix_sqrt(\n    Eigen::Matrix<Scalar, Size, Size> M)\n{\n    typedef Eigen::Matrix<Scalar, Size, Size> Matrix;\n    typedef Eigen::Matrix<Scalar, Size, 1> Vector;\n\n    Eigen::LDLT<Matrix> ldlt;\n    ldlt.compute(M);\n    Vector D_sqrt = ldlt.vectorD();\n    for (int i = 0; i < D_sqrt.rows(); ++i)\n    {\n        D_sqrt(i) = std::sqrt(std::fabs(D_sqrt(i)));\n    }\n\n    return ldlt.transpositionsP().transpose() * (Matrix)ldlt.matrixL() *\n           D_sqrt.asDiagonal();\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Checks wheather the specified dense matrix has a diagonal form\n *\n * \\return true if diagonal, false otherwise\n */\ntemplate <typename Derived>\nbool is_diagonal(const Eigen::MatrixBase<Derived>& m)\n{\n    Derived z = m;\n    z -= z.diagonal().asDiagonal();\n\n    return z.isZero();\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Robust AX=B solver where X is a vector or a matrix\n */\ntemplate <typename MatrixA, typename VectorsB>\nVectorsB solve(\n    const Eigen::MatrixBase<MatrixA>& A,\n    const VectorsB& B,\n    typename std::enable_if<VectorsB::RowsAtCompileTime == 1>::type* = 0)\n{\n    // householderQr() was not providing always a solution\n    // VectorsB x = A.householderQr().solve(B).eval();\n\n    assert(A.cols() == B.rows());\n    assert(A.cols() == 1);\n    assert(A.rows() == 1);\n\n    VectorsB x = B / A(0);\n    return x;  // RVO\n}\n\n/**\n * \\ingroup linear_algebra\n * \\brief Robust AX=B solver where X is a vector or a matrix\n */\ntemplate <typename MatrixA, typename VectorsB>\nVectorsB solve(\n    const Eigen::MatrixBase<MatrixA>& A,\n    const VectorsB& B,\n    typename std::enable_if<(VectorsB::RowsAtCompileTime != 1)>::type* = 0)\n{\n    // householderQr() was not providing always a solution\n    // VectorsB x = A.householderQr().solve(B).eval();\n\n    assert(A.cols() == B.rows());\n\n    VectorsB x = A.colPivHouseholderQr().solve(B).eval();\n    return x;  // RVO\n}\n}\n", "meta": {"hexsha": "cc18e9c6f51b4b5dadf45bf7173dd40b2f641269", "size": 12745, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/util/math/linear_algebra.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/util/math/linear_algebra.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/util/math/linear_algebra.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 28.9002267574, "max_line_length": 80, "alphanum_fraction": 0.5784229109, "num_tokens": 3752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6750799903130524}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MODULE tanh_sinh_quadrature_test\n\n#include <boost/config.hpp>\n#include <boost/detail/workaround.hpp>\n\n#if !defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) && !defined(BOOST_NO_SFINAE_EXPR)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(disable:4127)  // Conditional expression is constant\n#endif\n\n#if !defined(TEST1) && !defined(TEST2) && !defined(TEST3) && !defined(TEST4) && !defined(TEST5) && !defined(TEST6) && !defined(TEST7) && !defined(TEST8)\\\n    && !defined(TEST1A) && !defined(TEST1B) && !defined(TEST2A) && !defined(TEST3A) && !defined(TEST6A) && !defined(TEST9)\n#  define TEST1\n#  define TEST2\n#  define TEST3\n#  define TEST4\n#  define TEST5\n#  define TEST6\n#  define TEST7\n#  define TEST8\n#  define TEST1A\n#  define TEST1B\n#  define TEST2A\n#  define TEST3A\n#  define TEST6A\n#  define TEST9\n#endif\n\nusing std::expm1;\nusing std::atan;\nusing std::tan;\nusing std::log;\nusing std::log1p;\nusing std::asinh;\nusing std::atanh;\nusing std::sqrt;\nusing std::isnormal;\nusing std::abs;\nusing std::sinh;\nusing std::tanh;\nusing std::cosh;\nusing std::pow;\nusing std::exp;\nusing std::sin;\nusing std::cos;\nusing std::string;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::multiprecision::cpp_dec_float_50;\nusing boost::multiprecision::cpp_dec_float_100;\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::math::sinc_pi;\nusing boost::math::quadrature::tanh_sinh;\nusing boost::math::quadrature::detail::tanh_sinh_detail;\nusing boost::math::constants::pi;\nusing boost::math::constants::half_pi;\nusing boost::math::constants::two_div_pi;\nusing boost::math::constants::two_pi;\nusing boost::math::constants::half;\nusing boost::math::constants::third;\nusing boost::math::constants::half;\nusing boost::math::constants::third;\nusing boost::math::constants::catalan;\nusing boost::math::constants::ln_two;\nusing boost::math::constants::root_two;\nusing boost::math::constants::root_two_pi;\nusing boost::math::constants::root_pi;\n\ntemplate <class T>\nvoid print_levels(const T& v, const char* suffix)\n{\n   std::cout << \"{\\n\";\n   for (unsigned i = 0; i < v.size(); ++i)\n   {\n      std::cout << \"      { \";\n      for (unsigned j = 0; j < v[i].size(); ++j)\n      {\n         std::cout << v[i][j] << suffix << \", \";\n      }\n      std::cout << \"},\\n\";\n   }\n   std::cout << \"   };\\n\";\n}\n\ntemplate <class T>\nvoid print_complement_indexes(const T& v)\n{\n   std::cout << \"\\n   {\";\n   for (unsigned i = 0; i < v.size(); ++i)\n   {\n      unsigned index = 0;\n      while (v[i][index] >= 0)\n         ++index;\n      std::cout << index << \", \";\n   }\n   std::cout << \"};\\n\";\n}\n\ntemplate <class T>\nvoid print_levels(const std::pair<T, T>& p, const char* suffix = \"\")\n{\n   std::cout << \"   static const std::vector<std::vector<Real> > abscissa = \";\n   print_levels(p.first, suffix);\n   std::cout << \"   static const std::vector<std::vector<Real> > weights = \";\n   print_levels(p.second, suffix);\n   std::cout << \"   static const std::vector<unsigned > indexes = \";\n   print_complement_indexes(p.first);\n}\n\ntemplate <class Real>\nstd::pair<std::vector<std::vector<Real>>, std::vector<std::vector<Real>> > generate_constants(unsigned max_index, unsigned max_rows)\n{\n   using boost::math::constants::half_pi;\n   using boost::math::constants::two_div_pi;\n   using boost::math::constants::pi;\n   auto g = [](Real t) { return tanh(half_pi<Real>()*sinh(t)); };\n   auto w = [](Real t) { Real cs = cosh(half_pi<Real>() * sinh(t));  return half_pi<Real>() * cosh(t) / (cs * cs); };\n   auto gc = [](Real t) { Real u2 = half_pi<Real>() * sinh(t);  return 1 / (exp(u2) *cosh(u2)); };\n   auto g_inv = [](float x)->float { return asinh(two_div_pi<float>()*atanh(x)); };\n   auto gc_inv = [](float x)\n   {\n      float l = log(sqrt((2 - x) / x));\n      return log((sqrt(4 * l * l + pi<float>() * pi<float>()) + 2 * l) / pi<float>());\n   };\n\n   std::vector<std::vector<Real>> abscissa, weights;\n\n   std::vector<Real> temp;\n\n   float t_crossover = gc_inv(0.5f);\n\n   Real h = 1;\n   for (unsigned i = 0; i < max_index; ++i)\n   {\n      temp.push_back((i < t_crossover) ? g(i * h) : -gc(i * h));\n   }\n   abscissa.push_back(temp);\n   temp.clear();\n\n   for (unsigned i = 0; i < max_index; ++i)\n   {\n      temp.push_back(w(i * h));\n   }\n   weights.push_back(temp);\n   temp.clear();\n\n   for (unsigned row = 1; row < max_rows; ++row)\n   {\n      h /= 2;\n      for (Real t = h; t < max_index - 1; t += 2 * h)\n         temp.push_back((t < t_crossover) ? g(t) : -gc(t));\n      abscissa.push_back(temp);\n      temp.clear();\n   }\n   h = 1;\n   for (unsigned row = 1; row < max_rows; ++row)\n   {\n      h /= 2;\n      for (Real t = h; t < max_index - 1; t += 2 * h)\n         temp.push_back(w(t));\n      weights.push_back(temp);\n      temp.clear();\n   }\n\n   return std::make_pair(abscissa, weights);\n}\n\ntemplate <class Real>\nconst tanh_sinh<Real>& get_integrator()\n{\n   static const tanh_sinh<Real> integrator(15);\n   return integrator;\n}\n\ntemplate <class Real>\nReal get_convergence_tolerance()\n{\n   return boost::math::tools::root_epsilon<Real>();\n}\n\n\ntemplate<class Real>\nvoid test_linear()\n{\n    std::cout << \"Testing linear functions are integrated properly by tanh_sinh on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10*boost::math::tools::epsilon<Real>();\n    auto integrator = get_integrator<Real>();\n    auto f = [](const Real& x)\n    {\n       return 5*x + 7;\n    };\n    Real error;\n    Real L1;\n    Real Q = integrator.integrate(f, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, 9.5, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);\n    Q = integrator.integrate(f, (Real) 1, (Real) 0, get_convergence_tolerance<Real>(), &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, -9.5, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);\n    Q = integrator.integrate(f, (Real) 1, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    BOOST_CHECK_EQUAL(Q, Real(0));\n}\n\n\ntemplate<class Real>\nvoid test_quadratic()\n{\n    std::cout << \"Testing quadratic functions are integrated properly by tanh_sinh on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10*boost::math::tools::epsilon<Real>();\n    auto integrator = get_integrator<Real>();\n    auto f = [](const Real& x) { return 5*x*x + 7*x + 12; };\n    Real error;\n    Real L1;\n    Real Q = integrator.integrate(f, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, (Real) 17 + half<Real>()*third<Real>(), tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, (Real) 17 + half<Real>()*third<Real>(), tol);\n}\n\n\ntemplate<class Real>\nvoid test_singular()\n{\n    std::cout << \"Testing integration of endpoint singularities on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10*boost::math::tools::epsilon<Real>();\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n    auto f = [](const Real& x) { return log(x)*log(1-x); };\n    Real Q = integrator.integrate(f, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Real Q_expected = 2 - pi<Real>()*pi<Real>()*half<Real>()*third<Real>();\n\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n}\n\n\n// Examples taken from\n//http://crd-legacy.lbl.gov/~dhbailey/dhbpapers/quadrature.pdf\ntemplate<class Real>\nvoid test_ca()\n{\n    std::cout << \"Testing integration of C(a) on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real error;\n    Real L1;\n\n    auto integrator = get_integrator<Real>();\n    auto f1 = [](const Real& x) { return atan(x)/(x*(x*x + 1)) ; };\n    Real Q = integrator.integrate(f1, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Real Q_expected = pi<Real>()*ln_two<Real>()/8 + catalan<Real>()*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    auto f2 = [](Real x)->Real { Real t0 = x*x + 1; Real t1 = sqrt(t0); return atan(t1)/(t0*t1); };\n    Q = integrator.integrate(f2, (Real) 0 , (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = pi<Real>()/4 - pi<Real>()/root_two<Real>() + 3*atan(root_two<Real>())/root_two<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    auto f5 = [](Real t)->Real { return t*t*log(t)/((t*t - 1)*(t*t*t*t + 1)); };\n    Q = integrator.integrate(f5, (Real) 0 , (Real) 1);\n    Q_expected = pi<Real>()*pi<Real>()*(2 - root_two<Real>())/32;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n\n    // Oh it suffers on this one.\n    auto f6 = [](Real t)->Real { Real x = log(t); return x*x; };\n    Q = integrator.integrate(f6, (Real) 0 , (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = 2;\n\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 50*tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, 50*tol);\n\n\n    // Although it doesn't get to the requested tolerance on this integral, the error bounds can be queried and are reasonable:\n    tol = sqrt(boost::math::tools::epsilon<Real>());\n    auto f7 = [](const Real& t) { return sqrt(tan(t)); };\n    Q = integrator.integrate(f7, (Real) 0 , (Real) half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = pi<Real>()/root_two<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    auto f8 = [](const Real& t) { return log(cos(t)); };\n    Q = integrator.integrate(f8, (Real) 0 , half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = -pi<Real>()*ln_two<Real>()*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, -Q_expected, tol);\n}\n\n\ntemplate<class Real>\nvoid test_three_quadrature_schemes_examples()\n{\n    std::cout << \"Testing integral in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n\n    auto integrator = get_integrator<Real>();\n    // Example 1:\n    auto f1 = [](const Real& t) { return t*boost::math::log1p(t); };\n    Q = integrator.integrate(f1, (Real) 0 , (Real) 1);\n    Q_expected = half<Real>()*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n\n    // Example 2:\n    auto f2 = [](const Real& t) { return t*t*atan(t); };\n    Q = integrator.integrate(f2, (Real) 0 , (Real) 1);\n    Q_expected = (pi<Real>() -2 + 2*ln_two<Real>())/12;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 2 * tol);\n\n    // Example 3:\n    auto f3 = [](const Real& t) { return exp(t)*cos(t); };\n    Q = integrator.integrate(f3, (Real) 0, half_pi<Real>());\n    Q_expected = boost::math::expm1(half_pi<Real>())*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // Example 4:\n    auto f4 = [](Real x)->Real { Real t0 = sqrt(x*x + 2); return atan(t0)/(t0*(x*x+1)); };\n    Q = integrator.integrate(f4, (Real) 0 , (Real) 1);\n    Q_expected = 5*pi<Real>()*pi<Real>()/96;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // Example 5:\n    auto f5 = [](const Real& t) { return sqrt(t)*log(t); };\n    Q = integrator.integrate(f5, (Real) 0 , (Real) 1);\n    Q_expected = -4/ (Real) 9;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // Example 6:\n    auto f6 = [](const Real& t) { return sqrt(1 - t*t); };\n    Q = integrator.integrate(f6, (Real) 0 , (Real) 1);\n    Q_expected = pi<Real>()/4;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n}\n\n\ntemplate<class Real>\nvoid test_integration_over_real_line()\n{\n    std::cout << \"Testing integrals over entire real line in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    auto f1 = [](const Real& t) { return 1/(1+t*t);};\n    Q = integrator.integrate(f1, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = pi<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    auto f2 = [](const Real& t) { return exp(-t*t*half<Real>()); };\n    Q = integrator.integrate(f2, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = root_two_pi<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol * 2);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol * 2);\n\n    // This test shows how oscillatory integrals are approximated very poorly by this method:\n    //std::cout << \"Testing sinc integral: \\n\";\n    //Q = integrator.integrate(boost::math::sinc_pi<Real>, -std::numeric_limits<Real>::infinity(), std::numeric_limits<Real>::infinity(), &error, &L1);\n    //std::cout << \"Error estimate of sinc integral: \" << error << std::endl;\n    //std::cout << \"L1 norm of sinc integral \" << L1 << std::endl;\n    //Q_expected = pi<Real>();\n    //BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n\n    auto f4 = [](const Real& t) { return 1/cosh(t);};\n    Q = integrator.integrate(f4, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = pi<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n}\n\ntemplate<class Real>\nvoid test_right_limit_infinite()\n{\n    std::cout << \"Testing right limit infinite for tanh_sinh in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    // Example 11:\n    auto f1 = [](const Real& t) { return 1/(1+t*t);};\n    Q = integrator.integrate(f1, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = half_pi<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n\n    // Example 12\n    auto f2 = [](const Real& t) { return exp(-t)/sqrt(t); };\n    Q = integrator.integrate(f2, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = root_pi<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 1000*tol);\n\n    auto f3 = [](const Real& t) { return exp(-t)*cos(t); };\n    Q = integrator.integrate(f3, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = half<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n\n    auto f4 = [](const Real& t) { return 1/(1+t*t); };\n    Q = integrator.integrate(f4, 1, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = pi<Real>()/4;\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n}\n\ntemplate<class Real>\nvoid test_left_limit_infinite()\n{\n    std::cout << \"Testing left limit infinite for tanh_sinh in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    auto integrator = get_integrator<Real>();\n\n    // Example 11:\n    auto f1 = [](const Real& t) { return 1/(1+t*t);};\n    Q = integrator.integrate(f1, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), Real(0));\n    Q_expected = half_pi<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n}\n\n\n// A horrible function taken from\n// http://www.chebfun.org/examples/quad/GaussClenCurt.html\ntemplate<class Real>\nvoid test_horrible()\n{\n    std::cout << \"Testing Trefenthen's horrible integral on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    // We only know the integral to double precision, so requesting a higher tolerance doesn't make sense.\n    Real tol = 10 * std::numeric_limits<float>::epsilon();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    auto f = [](Real x)->Real { return x*sin(2*exp(2*sin(2*exp(2*x) ) ) ); };\n    Q = integrator.integrate(f, (Real) -1, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    // NIntegrate[x*Sin[2*Exp[2*Sin[2*Exp[2*x]]]], {x, -1, 1}, WorkingPrecision -> 130, MaxRecursion -> 100]\n    Q_expected = boost::lexical_cast<Real>(\"0.33673283478172753598559003181355241139806404130031017259552729882281\");\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    // Over again without specifying the bounds:\n    Q = integrator.integrate(f, get_convergence_tolerance<Real>(), &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n}\n\n// Some examples of tough integrals from NR, section 4.5.4:\ntemplate<class Real>\nvoid test_nr_examples()\n{\n    std::cout << \"Testing singular integrals from NR 4.5.4 on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    auto f1 = [](Real x)->Real\n    {\n       return (sin(x * half<Real>()) * exp(-x) / x) / sqrt(x);\n    };\n    Q = integrator.integrate(f1, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = sqrt(pi<Real>()*(sqrt((Real) 5) - 2));\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 25*tol);\n\n    auto f2 = [](Real x)->Real { return pow(x, -(Real) 2/(Real) 7)*exp(-x*x); };\n    Q = integrator.integrate(f2, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>());\n    Q_expected = half<Real>()*boost::math::tgamma((Real) 5/ (Real) 14);\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol * 6);\n\n}\n\n// Test integrand known to fool some termination schemes:\ntemplate<class Real>\nvoid test_early_termination()\n{\n    std::cout << \"Testing Clenshaw & Curtis's example of integrand which fools termination schemes on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    auto f1 = [](Real x)->Real { return 23*cosh(x)/ (Real) 25 - cos(x) ; };\n    Q = integrator.integrate(f1, (Real) -1, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = 46*sinh((Real) 1)/(Real) 25 - 2*sin((Real) 1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    // Over again with no bounds:\n    Q = integrator.integrate(f1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n}\n\n// Test some definite integrals from the CRC handbook, 32nd edition:\ntemplate<class Real>\nvoid test_crc()\n{\n    std::cout << \"Testing CRC formulas on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = 10 * boost::math::tools::epsilon<Real>();\n    Real Q;\n    Real Q_expected;\n    Real error;\n    Real L1;\n    auto integrator = get_integrator<Real>();\n\n    // CRC Definite integral 585\n    auto f1 = [](Real x)->Real { Real t = log(1/x); return x*x*t*t*t; };\n    Q = integrator.integrate(f1, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = (Real) 2/ (Real) 27;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // CRC 636:\n    auto f2 = [](Real x)->Real { return sqrt(cos(x)); };\n    Q = integrator.integrate(f2, (Real) 0, (Real) half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n    //Q_expected = pow(two_pi<Real>(), 3*half<Real>())/pow(boost::math::tgamma((Real) 1/ (Real) 4), 2);\n    Q_expected = boost::lexical_cast<Real>(\"1.198140234735592207439922492280323878227212663215651558263674952946405214143915670835885556489793389375907225\");\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // CRC Section 5.5, integral 585:\n    for (int n = 0; n < 3; ++n) {\n        for (int m = 0; m < 3; ++m) {\n            auto f = [&](Real x)->Real { return pow(x, Real(m))*pow(log(1/x), Real(n)); };\n            Q = integrator.integrate(f, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n            // Calculation of the tgamma function is not exact, giving spurious failures.\n            // Casting to cpp_bin_float_100 beforehand fixes most of them.\n            cpp_bin_float_100 np1 = n + 1;\n            cpp_bin_float_100 mp1 = m + 1;\n            Q_expected = boost::lexical_cast<Real>((tgamma(np1)/pow(mp1, np1)).str());\n            BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n        }\n    }\n\n    // CRC Section 5.5, integral 591\n    // The parameter p allows us to control the strength of the singularity.\n    // Rapid convergence is not guaranteed for this function, as the branch cut makes it non-analytic on a disk.\n    // This converges only when our test type has an extended exponent range as all the area of the integral\n    // occurs so close to 0 (or 1) that we need abscissa values exceptionally small to find it.\n    // \"There's a lot of room at the bottom\".\n    // We also use a 2 argument functor so that 1-x is evaluated accurately:\n    if (std::numeric_limits<Real>::max_exponent > std::numeric_limits<double>::max_exponent)\n    {\n       for (Real p = Real (-0.99); p < 1; p += Real(0.1)) {\n          auto f = [&](Real x, Real cx)->Real\n          {\n             //return pow(x, p) / pow(1 - x, p);\n             return cx < 0 ? exp(p * (log(x) - boost::math::log1p(-x))) : pow(x, p) / pow(cx, p);\n          };\n          Q = integrator.integrate(f, (Real)0, (Real)1, get_convergence_tolerance<Real>(), &error, &L1);\n          Q_expected = 1 / sinc_pi(p*pi<Real>());\n          BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 10 * tol);\n       }\n    }\n    // There is an alternative way to evaluate the above integral: by noticing that all the area of the integral\n    // is near zero for p < 0 and near 1 for p > 0 we can substitute exp(-x) for x and remap the integral to the\n    // domain (0, INF).  Internally we need to expand out the terms and evaluate using logs to avoid spurious overflow, \n    // this gives us\n    // for p > 0:\n    for (Real p = Real(0.99); p > 0; p -= Real(0.1)) {\n       auto f = [&](Real x)->Real\n       {\n          return exp(-x * (1 - p) + p * log(-boost::math::expm1(-x)));\n       };\n       Q = integrator.integrate(f, 0, boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n       Q_expected = 1 / sinc_pi(p*pi<Real>());\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 10 * tol);\n    }\n    // and for p < 1:\n    for (Real p = Real (-0.99); p < 0; p += Real(0.1)) {\n       auto f = [&](Real x)->Real\n       {\n          return exp(-p * log(-boost::math::expm1(-x)) - (1 + p) * x);\n       };\n       Q = integrator.integrate(f, 0, boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n       Q_expected = 1 / sinc_pi(p*pi<Real>());\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 10 * tol);\n    }\n\n    // CRC Section 5.5, integral 635\n    for (int m = 0; m < 10; ++m) {\n        auto f = [&](Real x)->Real { return 1/(1 + pow(tan(x), m)); };\n        Q = integrator.integrate(f, (Real) 0, half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n        Q_expected = half_pi<Real>()/2;\n        BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    }\n\n    // CRC Section 5.5, integral 637:\n    //\n    // When h gets very close to 1, the strength of the singularity gradually increases until we\n    // no longer have enough exponent range to evaluate the integral....\n    // We also have to use the 2-argument functor version of the integrator to avoid\n    // cancellation error, since the singularity is near PI/2.\n    //\n    Real limit = std::numeric_limits<Real>::max_exponent > std::numeric_limits<double>::max_exponent\n       ? .95f : .85f;\n    for (Real h = Real(0.01); h < limit; h += Real(0.1)) {\n        auto f = [&](Real x, Real xc)->Real { return xc > 0 ? pow(1/tan(xc), h) : pow(tan(x), h); };\n        Q = integrator.integrate(f, (Real) 0, half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n        Q_expected = half_pi<Real>()/cos(h*half_pi<Real>());\n        BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    }\n    // CRC Section 5.5, integral 637:\n    //\n    // Over again, but with argument transformation, we want:\n    //\n    // Integral of tan(x)^h over (0, PI/2)\n    //\n    // Note that the bulk of the area is next to the singularity at PI/2,\n    // so we'll start by replacing x by PI/2 - x, and that tan(PI/2 - x) == 1/tan(x)\n    // so we now have:\n    //\n    // Integral of 1/tan(x)^h over (0, PI/2)\n    //\n    // Which is almost the ideal form, except that when h is very close to 1\n    // we run out of exponent range in evaluating the integral arbitrarily close to 0.\n    // So now we substitute exp(-x) for x: this stretches out the range of the\n    // integral to (-log(PI/2), +INF) with the singularity at +INF giving:\n    //\n    // Integral of exp(-x)/tan(exp(-x))^h over (-log(PI/2), +INF)\n    //\n    // We just need a way to evaluate the function without spurious under/overflow\n    // in the exp terms.  Note that for small x: tan(x) ~= x, so making this\n    // substitution and evaluating by logs we have:\n    //\n    // exp(-x)/tan(exp(-x))^h ~= exp((h - 1) * x)  for x > -log(epsilon);\n    //\n    // Here's how that looks in code:\n    //\n    for (Real i = 80; i < 100; ++i) {\n       Real h = i / 100;\n       auto f = [&](Real x)->Real \n       { \n          if (x > -log(boost::math::tools::epsilon<Real>()))\n             return exp((h - 1) * x);\n          else\n          {\n             Real et = exp(-x);\n             // Need to deal with numeric instability causing et to be greater than PI/2:\n             return et >= boost::math::constants::half_pi<Real>() ? 0 : et * pow(1 / tan(et), h);\n          }\n       };\n       Q = integrator.integrate(f, -log(half_pi<Real>()), boost::math::tools::max_value<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n       Q_expected = half_pi<Real>() / cos(h*half_pi<Real>());\n       BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 5 * tol);\n    }\n\n    // CRC Section 5.5, integral 670:\n\n    auto f3 = [](Real x)->Real { return sqrt(log(1/x)); };\n    Q = integrator.integrate(f3, (Real) 0, (Real) 1, get_convergence_tolerance<Real>(), &error, &L1);\n    Q_expected = root_pi<Real>()/2;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n}\n\ntemplate <class Real>\nvoid test_sf()\n{\n   using std::sqrt;\n   // Test some special functions that we already know how to evaluate:\n   std::cout << \"Testing special functions on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n   Real tol = 10 * boost::math::tools::epsilon<Real>();\n   auto integrator = get_integrator<Real>();\n\n   // incomplete beta:\n   if (std::numeric_limits<Real>::digits10 < 37) // Otherwise too slow\n   {\n      Real a(100), b(15);\n      auto f = [&](Real x)->Real { return boost::math::ibeta_derivative(a, b, x); };\n      BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f, 0, Real(0.25)), boost::math::ibeta(100, 15, Real(0.25)), tol * 10);\n      // Check some really extreme versions:\n      a = 1000;\n      b = 500;\n      BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f, 0, 1), Real(1), tol * 15);\n      //\n      // This is as extreme as we can get in this domain: otherwise the function has all it's \n      // area so close to zero we never get in there no matter how many levels we go down:\n      //\n      a = Real(1) / 15;\n      b = 30;\n      BOOST_CHECK_CLOSE_FRACTION(integrator.integrate(f, 0, 1), Real(1), tol * 25);\n   }\n\n   Real x = 2, y = 3, z = 0.5, p = 0.25;\n   // Elliptic integral RC:\n   Real Q = integrator.integrate([&](const Real& t)->Real { return 1 / (sqrt(t + x) * (t + y)); }, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>()) / 2;\n   BOOST_CHECK_CLOSE_FRACTION(Q, boost::math::ellint_rc(x, y), tol);\n   // Elliptic Integral RJ:\n   BOOST_CHECK_CLOSE_FRACTION(Real((Real(3) / 2) * integrator.integrate([&](Real t)->Real { return 1 / (sqrt((t + x) * (t + y) * (t + z)) * (t + p)); }, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>())), boost::math::ellint_rj(x, y, z, p), tol);\n\n   z = 5.5;\n   if (std::numeric_limits<Real>::digits10 > 40)\n      tol *= 200;\n   else if (!std::numeric_limits<Real>::is_specialized)\n      tol *= 3;\n   // tgamma expressed as an integral:\n   BOOST_CHECK_CLOSE_FRACTION(integrator.integrate([&](Real t)->Real { using std::pow; using std::exp; return t > 10000 ? Real(0) : Real(pow(t, z - 1) * exp(-t)); }, 0, std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>()),\n      boost::math::tgamma(z), tol);\n   BOOST_CHECK_CLOSE_FRACTION(integrator.integrate([](const Real& t)->Real {  using std::exp; return exp(-t*t); }, std::numeric_limits<Real>::has_infinity ? -std::numeric_limits<Real>::infinity() : -boost::math::tools::max_value<Real>(), std::numeric_limits<Real>::has_infinity ? std::numeric_limits<Real>::infinity() : boost::math::tools::max_value<Real>()),\n      boost::math::constants::root_pi<Real>(), tol);\n}\n\ntemplate <class Real>\nvoid test_2_arg()\n{\n   BOOST_MATH_STD_USING\n   std::cout << \"Testing 2 argument functors on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n   Real tol = 10 * boost::math::tools::epsilon<Real>();\n\n   auto integrator = get_integrator<Real>();\n\n   //\n   // There are a whole family of integrals of the general form\n   // x(1-x)^-N ; N < 1\n   // which have all the interesting behaviour near the 2 singularities\n   // and all converge, see: http://www.wolframalpha.com/input/?i=integrate+(x+*+(1-x))%5E-1%2FN+from+0+to+1\n   //\n   Real Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return tc < 0 ? 1 / sqrt(t * (1-t)) : 1 / sqrt(t * tc);\n   }, 0, 1);\n   BOOST_CHECK_CLOSE_FRACTION(Q, boost::math::constants::pi<Real>(), tol);\n   Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return tc < 0 ? 1 / boost::math::cbrt(t * (1-t)) : 1 / boost::math::cbrt(t * tc);\n   }, 0, 1);\n   BOOST_CHECK_CLOSE_FRACTION(Q, boost::math::pow<2>(boost::math::tgamma(Real(2) / 3)) / boost::math::tgamma(Real(4) / 3), tol * 4);\n   //\n   // We can do the same thing with ((1+x)(1-x))^-N ; N < 1\n   //\n   Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return t < 0 ? 1 / sqrt(-tc * (1-t)) : 1 / sqrt((t + 1) * tc);\n   }, -1, 1);\n   BOOST_CHECK_CLOSE_FRACTION(Q, boost::math::constants::pi<Real>(), tol);\n   Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return t < 0 ? 1 / sqrt(-tc * (1-t)) : 1 / sqrt((t + 1) * tc);\n   });\n   BOOST_CHECK_CLOSE_FRACTION(Q, boost::math::constants::pi<Real>(), tol);\n   Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return t < 0 ? 1 / boost::math::cbrt(-tc * (1-t)) : 1 / boost::math::cbrt((t + 1) * tc);\n   }, -1, 1);\n   BOOST_CHECK_CLOSE_FRACTION(Q, sqrt(boost::math::constants::pi<Real>()) * boost::math::tgamma(Real(2) / 3) / boost::math::tgamma(Real(7) / 6), tol * 10);\n   Q = integrator.integrate([&](const Real& t, const Real & tc)->Real\n   {\n      return t < 0 ? 1 / boost::math::cbrt(-tc * (1-t)) : 1 / boost::math::cbrt((t + 1) * tc);\n   });\n   BOOST_CHECK_CLOSE_FRACTION(Q, sqrt(boost::math::constants::pi<Real>()) * boost::math::tgamma(Real(2) / 3) / boost::math::tgamma(Real(7) / 6), tol * 10);\n   //\n   // These are taken from above, and do not get to full precision via the single arg functor:\n   //\n   auto f7 = [](const Real& t, const Real& tc) { return t < 1 ? sqrt(tan(t)) : sqrt(1/tan(tc)); };\n   Real error, L1;\n   Q = integrator.integrate(f7, (Real)0, (Real)half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n   Real Q_expected = pi<Real>() / root_two<Real>();\n   BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n   BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n   auto f8 = [](const Real& t, const Real& tc) { return t < 1 ? log(cos(t)) : log(sin(tc)); };\n   Q = integrator.integrate(f8, (Real)0, half_pi<Real>(), get_convergence_tolerance<Real>(), &error, &L1);\n   Q_expected = -pi<Real>()*ln_two<Real>()*half<Real>();\n   BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n   BOOST_CHECK_CLOSE_FRACTION(L1, -Q_expected, tol);\n}\n\ntemplate <class Complex>\nvoid test_complex()\n{\n   typedef typename Complex::value_type value_type;\n   //\n   // Integral version of the confluent hypergeometric function:\n   // https://dlmf.nist.gov/13.4#E1\n   //\n   value_type tol = 10 * boost::math::tools::epsilon<value_type>();\n   Complex a(2, 3), b(3, 4), z(0.5, -2);\n\n   auto f = [&](value_type t)\n   {\n      return exp(z * t) * pow(t, a - value_type(1)) * pow(value_type(1) - t, b - a - value_type(1));\n   };\n\n   auto integrator = get_integrator<value_type>();\n   auto Q = integrator.integrate(f, value_type(0), value_type(1), get_convergence_tolerance<value_type>());\n   //\n   // Expected result computed from http://www.wolframalpha.com/input/?i=1F1%5B(2%2B3i),+(3%2B4i);+(0.5-2i)%5D+*+gamma(2%2B3i)+*+gamma(1%2Bi)+%2F+gamma(3%2B4i)\n   //\n   Complex expected(boost::lexical_cast<value_type>(\"-0.2911081612888249710582867318081776512805281815037891183828405999609246645054069649838607112484426042883371996\"),\n      boost::lexical_cast<value_type>(\"0.4507983563969959578849120188097153649211346293694903758252662015991543519595834937475296809912196906074655385\"));\n\n   value_type error = abs(expected - Q);\n   BOOST_CHECK_LE(error, tol);\n\n   //\n   // Sin Integral https://dlmf.nist.gov/6.2#E9\n   //\n   auto f2 = [z](value_type t)\n   {\n      return -exp(-z * cos(t)) * cos(z * sin(t));\n   };\n   Q = integrator.integrate(f2, value_type(0), boost::math::constants::half_pi<value_type>(), get_convergence_tolerance<value_type>());\n\n   expected = Complex(boost::lexical_cast<value_type>(\"0.8893822921008980697856313681734926564752476188106405688951257340480164694708337246829840859633322683740376134733\"),\n      -boost::lexical_cast<value_type>(\"2.381380802906111364088958767973164614925936185337231718483495612539455538280372745733208000514737758457795502168\"));\n   expected -= boost::math::constants::half_pi<value_type>();\n\n   error = abs(expected - Q);\n   BOOST_CHECK_LE(error, tol);\n}\n\n\nBOOST_AUTO_TEST_CASE(tanh_sinh_quadrature_test)\n{\n#ifdef GENERATE_CONSTANTS\n   //\n   // Generate pre-computed coefficients:\n   std::cout << std::setprecision(35);\n   print_levels(generate_constants<cpp_bin_float_100>(10, 8), \"L\");\n\n#else\n\n#ifdef TEST1\n\n    test_right_limit_infinite<float>();\n    test_left_limit_infinite<float>();\n    test_linear<float>();\n    test_quadratic<float>();\n    test_singular<float>();\n    test_ca<float>();\n    test_three_quadrature_schemes_examples<float>();\n    test_horrible<float>();\n    test_integration_over_real_line<float>();\n    test_nr_examples<float>();\n#endif\n#ifdef TEST1A\n    test_early_termination<float>();\n    test_2_arg<float>();\n#endif\n#ifdef TEST1B\n    test_crc<float>();\n#endif\n#ifdef TEST2\n    test_right_limit_infinite<double>();\n    test_left_limit_infinite<double>();\n    test_linear<double>();\n    test_quadratic<double>();\n    test_singular<double>();\n    test_ca<double>();\n    test_three_quadrature_schemes_examples<double>();\n    test_horrible<double>();\n    test_integration_over_real_line<double>();\n    test_nr_examples<double>();\n    test_early_termination<double>();\n    test_sf<double>();\n    test_2_arg<double>();\n#endif\n#ifdef TEST2A\n    test_crc<double>();\n#endif\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n\n#ifdef TEST3\n    test_right_limit_infinite<long double>();\n    test_left_limit_infinite<long double>();\n    test_linear<long double>();\n    test_quadratic<long double>();\n    test_singular<long double>();\n    test_ca<long double>();\n    test_three_quadrature_schemes_examples<long double>();\n    test_horrible<long double>();\n    test_integration_over_real_line<long double>();\n    test_nr_examples<long double>();\n    test_early_termination<long double>();\n    test_sf<long double>();\n    test_2_arg<long double>();\n#endif\n#ifdef TEST3A\n    test_crc<long double>();\n\n#endif\n#endif\n\n#ifdef TEST4\n    test_right_limit_infinite<cpp_bin_float_quad>();\n    test_left_limit_infinite<cpp_bin_float_quad>();\n    test_linear<cpp_bin_float_quad>();\n    test_quadratic<cpp_bin_float_quad>();\n    test_singular<cpp_bin_float_quad>();\n    test_ca<cpp_bin_float_quad>();\n    test_three_quadrature_schemes_examples<cpp_bin_float_quad>();\n    test_horrible<cpp_bin_float_quad>();\n    test_nr_examples<cpp_bin_float_quad>();\n    test_early_termination<cpp_bin_float_quad>();\n    test_crc<cpp_bin_float_quad>();\n    test_sf<cpp_bin_float_quad>();\n    test_2_arg<cpp_bin_float_quad>();\n\n#endif\n#ifdef TEST5\n\n    test_sf<cpp_bin_float_50>();\n    test_sf<cpp_bin_float_100>();\n    test_sf<boost::multiprecision::number<boost::multiprecision::cpp_bin_float<150> > >();\n\n#endif\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#ifdef TEST6\n\n    test_right_limit_infinite<boost::math::concepts::real_concept>();\n    test_left_limit_infinite<boost::math::concepts::real_concept>();\n    test_linear<boost::math::concepts::real_concept>();\n    test_quadratic<boost::math::concepts::real_concept>();\n    test_singular<boost::math::concepts::real_concept>();\n    test_ca<boost::math::concepts::real_concept>();\n    test_three_quadrature_schemes_examples<boost::math::concepts::real_concept>();\n    test_horrible<boost::math::concepts::real_concept>();\n    test_integration_over_real_line<boost::math::concepts::real_concept>();\n    test_nr_examples<boost::math::concepts::real_concept>();\n    test_early_termination<boost::math::concepts::real_concept>();\n    test_sf<boost::math::concepts::real_concept>();\n    test_2_arg<boost::math::concepts::real_concept>();\n#endif\n#ifdef TEST6A\n    test_crc<boost::math::concepts::real_concept>();\n\n#endif\n#endif\n#ifdef TEST7\n    test_sf<cpp_dec_float_50>();\n#endif\n#if defined(TEST8) && defined(BOOST_HAS_FLOAT128)\n\n    test_right_limit_infinite<boost::multiprecision::float128>();\n    test_left_limit_infinite<boost::multiprecision::float128>();\n    test_linear<boost::multiprecision::float128>();\n    test_quadratic<boost::multiprecision::float128>();\n    test_singular<boost::multiprecision::float128>();\n    test_ca<boost::multiprecision::float128>();\n    test_three_quadrature_schemes_examples<boost::multiprecision::float128>();\n    test_horrible<boost::multiprecision::float128>();\n    test_integration_over_real_line<boost::multiprecision::float128>();\n    test_nr_examples<boost::multiprecision::float128>();\n    test_early_termination<boost::multiprecision::float128>();\n    test_crc<boost::multiprecision::float128>();\n    test_sf<boost::multiprecision::float128>();\n    test_2_arg<boost::multiprecision::float128>();\n\n#endif\n#ifdef TEST9\n    test_complex<std::complex<double> >();\n    test_complex<std::complex<float> >();\n#endif\n\n\n#endif\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "f66962ba493b23fe90c3cb6575dd0567e20f5985", "size": 41306, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tanh_sinh_quadrature_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/tanh_sinh_quadrature_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/tanh_sinh_quadrature_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 41.5135678392, "max_line_length": 359, "alphanum_fraction": 0.6517455091, "num_tokens": 12015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6750439223708551}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef NL_PROBLEM_PENDULUM_HPP_\n#define NL_PROBLEM_PENDULUM_HPP_\n\n#include <cbr_math/math.hpp>\n\n#include <Eigen/Dense>\n#include <cstdint>\n#include <functional>\n#include <limits>\n\n\ntemplate<typename T1, typename T2>\nauto pendulum_dynamics(const Eigen::MatrixBase<T1> & x, const Eigen::MatrixBase<T2> & u)\n{\n  // Define nx, nu\n  constexpr auto nx = T1::RowsAtCompileTime;\n  constexpr auto nu = T2::RowsAtCompileTime;\n\n  // Initialize Parameters\n  constexpr double l = 1.;\n  constexpr double m = 1.;\n  constexpr double b = 0.2;\n  constexpr double gr = 9.81;\n\n  using T = typename decltype(x * u.transpose())::EvalReturnType::Scalar;\n\n  // xDot = f(x) + g(x)*u\n  Eigen::Matrix<typename T1::Scalar, nx, 1> f;\n  Eigen::Matrix<typename T1::Scalar, nx, nu> g;\n\n  // Define States\n  const auto & theta = x[0];\n  const auto & thetaDot = x[1];\n\n  // Dynamics\n  f[0] = thetaDot;\n  f[1] = -(gr / l) * sin(theta) - b / (m * l * l) * thetaDot;\n  g[0] = 0.;\n  g[1] = 1 / (m * l * l);\n\n  return (f + g * u).eval();\n}\n\n\nstruct NlOcpPendulum\n{\n  constexpr static std::size_t nx = 2;\n  constexpr static std::size_t nu = 1;\n  constexpr static bool xl_always_feasible = false;\n\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using deriv_t = Eigen::Matrix<double, nx, 1>;\n  using input_t = Eigen::Matrix<double, nu, 1>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n\n  const Q_t Q = (state_t() << 20.0, 1.0).finished().asDiagonal();\n  const Q_t QT = (state_t() << 20.0, 1.0).finished().asDiagonal();\n  const R_t R = (R_t() << 0.1).finished();\n\n  template<typename T1, typename T2>\n  auto get_f(const Eigen::MatrixBase<T1> & x, const Eigen::MatrixBase<T2> & u) const\n  {\n    static_assert(\n      T1::RowsAtCompileTime == nx &&\n      T1::ColsAtCompileTime == 1,\n      \"First argument must be an nx*1 Eigen Matrix\");\n\n    static_assert(\n      T2::RowsAtCompileTime == nu &&\n      T2::ColsAtCompileTime == 1,\n      \"Second argument must be an nu*1 Eigen Matrix\");\n\n    return pendulum_dynamics<T1, T2>(x, u);\n  }\n\n  void get_state_lb(double, Eigen::Ref<state_t> state_lb) const\n  {\n    const double kInfinity = std::numeric_limits<double>::infinity();\n    state_lb <<\n      -kInfinity,\n      -cbr::deg2rad(200.0);\n  }\n\n  void get_state_ub(double, Eigen::Ref<state_t> state_ub) const\n  {\n    const double kInfinity = std::numeric_limits<double>::infinity();\n    state_ub <<\n      kInfinity,\n      cbr::deg2rad(200.0);\n  }\n\n  void get_input_lb(double, Eigen::Ref<input_t> input_lb) const\n  {\n    input_lb << -0.1;\n  }\n\n  void get_input_ub(double, Eigen::Ref<input_t> input_ub) const\n  {\n    input_ub << 0.1;\n  }\n\n  const Q_t & get_Q(double) const {return Q;}\n  const R_t & get_R(double) const {return R;}\n  const Q_t & get_QT() const {return QT;}\n};\n\n#endif  // NL_PROBLEM2_HPP_\n", "meta": {"hexsha": "ce586898b8e44c7f03a89d63ad83cb4c9ab9d498", "size": 2904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/pendulum_problem.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "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/pendulum_problem.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "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/pendulum_problem.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["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.6991150442, "max_line_length": 88, "alphanum_fraction": 0.6491046832, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6749950373868187}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/position_from_two_rays.h\"\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <glog/logging.h>\n#include <vector>\n\nnamespace theia {\n\n// We use the reprojection error constraint:\n//\n//   rotated_feature = [x - cx; y - cy] / (z - cz)\n//\n// where the 3D point is [x y z]^t and the unknown position is [cx cy cz].\n// This constraint can be rearranged into a linear system:\n//\n//   [1  0  -u] * c = [x - u * z]\n//   [0  1  -v]     = [y - v * z]\n//\n// where rotated_feature = [u v]. By stacking this constraint for both features\n// we obtain a 4x3 linear system whose solution is the camera position.\nbool PositionFromTwoRays(const Eigen::Vector2d& rotated_feature1,\n                         const Eigen::Vector3d& point1,\n                         const Eigen::Vector2d& rotated_feature2,\n                         const Eigen::Vector3d& point2,\n                         Eigen::Vector3d* position) {\n  CHECK_NOTNULL(position);\n  // Create the left hand side of the linear system above.\n  Eigen::Matrix<double, 4, 3> lhs;\n  lhs.block<2, 2>(0, 0).setIdentity();\n  lhs.block<2, 2>(2, 0).setIdentity();\n  lhs.block<2, 1>(0, 2) = -rotated_feature1;\n  lhs.block<2, 1>(2, 2) = -rotated_feature2;\n\n  // Create the right hand side of the linear system above.\n  Eigen::Vector4d rhs;\n  rhs.head<2>() = point1.head<2>() - rotated_feature1 * point1.z();\n  rhs.tail<2>() = point2.head<2>() - rotated_feature2 * point2.z();\n\n  Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 4, 3> > linear_solver(lhs);\n  // If the linear solver is not well-conditioned then the position cannot be\n  // reliably computed.\n  if (linear_solver.rank() != 3) {\n    return false;\n  }\n\n  *position = linear_solver.solve(rhs);\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "54d2d9abd1dbd954a870b41bbe3bacfac4325521", "size": 3546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/position_from_two_rays.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "src/theia/sfm/pose/position_from_two_rays.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "src/theia/sfm/pose/position_from_two_rays.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 41.2325581395, "max_line_length": 79, "alphanum_fraction": 0.6951494642, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6749950284438643}}
{"text": "/*\n * Copyright 2009-2012 Karsten Ahnert\n * Copyright 2009-2012 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#include <iostream>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n/* define ublas::vector<double> as resizeable \n * this is not neccessarily required because this definition already \n * exists in util/ublas_wrapper.hpp.\n * However, for completeness and educational purpose it is repeated here.\n */\n\n//[ ublas_resizeable\ntypedef boost::numeric::ublas::vector< double > state_type;\n\nnamespace boost { namespace numeric { namespace odeint {\n\ntemplate<>\nstruct is_resizeable< state_type >\n{\n    typedef boost::true_type type;\n    const static bool value = type::value;\n};\n\n} } }\n//]\n\nvoid lorenz( const state_type &x , state_type &dxdt , const double t )\n{\n    const double sigma( 10.0 );\n    const double R( 28.0 );\n    const double b( 8.0 / 3.0 );\n    \n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nusing namespace boost::numeric::odeint;\n\n//[ublas_main\nint main()\n{\n    state_type x(3);\n    x[0] = 10.0; x[1] = 5.0 ; x[2] = 0.0;\n    typedef runge_kutta4< state_type , double , state_type , double , vector_space_algebra > stepper;\n    integrate_const( stepper() , lorenz , x ,\n                     0.0 , 10.0 , 0.1 );\n}\n//]\n", "meta": {"hexsha": "c3394d55fbd64bdfd3145c00eaf0465770117bd1", "size": 1481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/ublas/lorenz_ublas.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/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/ublas/lorenz_ublas.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/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/ublas/lorenz_ublas.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": 24.6833333333, "max_line_length": 101, "alphanum_fraction": 0.6488858879, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6749496521374896}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <LBFGS.h>\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing namespace LBFGSpp;\n\nclass Rosenbrock\n{\nprivate:\n    int n;\n    ptrdiff_t ncalls;\n\npublic:\n    Rosenbrock(int n_) : n(n_), ncalls(0) {}\n    double operator()(const VectorXd& x, VectorXd& grad)\n    {\n//        std::cout << x << std::endl;\n        ncalls += 1;\n\n        double fx = 0.0;\n        for(int i = 0; i < n; i += 2)\n        {\n            double t1 = 1.0 - x[i];\n            double t2 = 10 * (x[i + 1] - x[i] * x[i]);\n            grad[i + 1] = 20 * t2;\n            grad[i]     = -2.0 * (x[i] * grad[i + 1] + t1);\n            fx += t1 * t1 + t2 * t2;\n        }\n        assert( ! std::isnan(fx) );\n        return fx;\n    }\n\n    const ptrdiff_t get_ncalls() {\n      return ncalls;\n    }\n};\n\nint main()\n{\n    LBFGSParam<double> param;\n    param.    linesearch = LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE;\n    param.max_linesearch = 128;\n\n    LBFGSSolver<double, LineSearchBacktracking > solver_backtrack(param);\n    LBFGSSolver<double, LineSearchBracketing   > solver_bracket  (param);\n    LBFGSSolver<double, LineSearchNocedalWright> solver_nocedal  (param);\n\n    const int tests_per_n = 1024;\n\n    for( int n=2; n <= 24; n += 2 )\n    {\n        std::cout << \"n = \" << n << std::endl;\n        Rosenbrock fun_backtrack(n),\n                   fun_bracket  (n),\n                   fun_nocedal  (n);\n        int niter_backtrack = 0,\n            niter_bracket   = 0,\n            niter_nocedal   = 0;\n        for( int test=0; test < tests_per_n; test++ )\n        {\n            VectorXd x, x0 = VectorXd::Random(n);\n\n            double fx;\n\n            x = x0; niter_backtrack += solver_backtrack.minimize(fun_backtrack, x, fx); assert( ( (x.array() - 1.0).abs() < 1e-4 ).all() );\n            x = x0; niter_bracket   += solver_bracket  .minimize(fun_bracket  , x, fx); assert( ( (x.array() - 1.0).abs() < 1e-4 ).all() );\n            x = x0; niter_nocedal   += solver_nocedal  .minimize(fun_nocedal  , x, fx); assert( ( (x.array() - 1.0).abs() < 1e-4 ).all() );\n        }\n        std::cout << \"  Average #calls:\" << std::endl;\n        std::cout << \"  LineSearchBacktracking : \" << (fun_backtrack.get_ncalls() / tests_per_n) << \" calls, \" << (niter_backtrack / tests_per_n) << \" iterations\" << std::endl;\n        std::cout << \"  LineSearchBracketing   : \" << (fun_bracket  .get_ncalls() / tests_per_n) << \" calls, \" << (niter_bracket   / tests_per_n) << \" iterations\" << std::endl;\n        std::cout << \"  LineSearchNocedalWright: \" << (fun_nocedal  .get_ncalls() / tests_per_n) << \" calls, \" << (niter_nocedal   / tests_per_n) << \" iterations\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "0fd7defdc3eae151a9285028d5c15ca0aa5f8a89", "size": 2689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example-rosenbrock-comparison.cpp", "max_stars_repo_name": "mpayrits/LBFGSpp", "max_stars_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-08-05T06:18:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:30:01.000Z", "max_issues_repo_path": "examples/example-rosenbrock-comparison.cpp", "max_issues_repo_name": "mpayrits/LBFGSpp", "max_issues_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2017-06-24T18:51:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T04:42:49.000Z", "max_forks_repo_path": "examples/example-rosenbrock-comparison.cpp", "max_forks_repo_name": "mpayrits/LBFGSpp", "max_forks_repo_head_hexsha": "b28f6969787b748cd32acfc8e6c684e6d00b5b9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2016-08-26T22:11:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T16:25:55.000Z", "avg_line_length": 34.0379746835, "max_line_length": 176, "alphanum_fraction": 0.5444403124, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6749496380497195}}
{"text": "/* Boost libs/numeric/odeint/performance/openmp/osc_chain_1d_system.hpp\n\n Copyright 2013 Karsten Ahnert\n Copyright 2013 Mario Mulansky\n Copyright 2013 Pascal Germroth\n\n stronlgy nonlinear hamiltonian lattice\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#ifndef SYSTEM_HPP\n#define SYSTEM_HPP\n\n#include <vector>\n#include <cmath>\n#include <iostream>\n\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/numeric/odeint/external/mpi/mpi.hpp>\n\nnamespace checked_math {\n    inline double pow( double x , double y )\n    {\n        if( x==0.0 )\n            // 0**y = 0, don't care for y = 0 or NaN\n            return 0.0;\n        using std::pow;\n        using std::abs;\n        return pow( abs(x) , y );\n    }\n}\n\ndouble signed_pow( double x , double k )\n{\n    using boost::math::sign;\n    return checked_math::pow( x , k ) * sign(x);\n}\n\nstruct osc_chain {\n    const double m_kap, m_lam;\n    osc_chain( const double kap , const double lam )\n        : m_kap( kap ) , m_lam( lam ) { }\n\n    void operator()( const boost::numeric::odeint::mpi_state< std::vector<double> > &q ,\n                           boost::numeric::odeint::mpi_state< std::vector<double> > &dpdt ) const\n    {\n        const bool have_left = q.world.rank() > 0;\n        const bool have_right = q.world.rank() + 1 < q.world.size();\n        double q_left = 0, q_right = 0;\n        boost::mpi::request r_left, r_right;\n        if(have_left)\n        {\n            q.world.isend(q.world.rank() - 1, 0, q().front());\n            r_left = q.world.irecv(q.world.rank() - 1, 0, q_left);\n        }\n        if(have_right)\n        {\n            q.world.isend(q.world.rank() + 1, 0, q().back());\n            r_right = q.world.irecv(q.world.rank() + 1, 0, q_right);\n        }\n\n        double coupling_lr = 0;\n        if(have_left)\n        {\n            r_left.wait();\n            coupling_lr = signed_pow( q_left - q()[0] , m_lam-1 );\n        }\n        const size_t N = q().size();\n        for(size_t i = 0 ; i < N-1 ; ++i)\n        {\n            dpdt()[i] = -signed_pow( q()[i] , m_kap-1 ) + coupling_lr;\n            coupling_lr = signed_pow( q()[i] - q()[i+1] , m_lam-1 );\n            dpdt()[i] -= coupling_lr;\n        }\n        dpdt()[N-1] = -signed_pow( q()[N-1] , m_kap-1 ) + coupling_lr;\n        if(have_right)\n        {\n            r_right.wait();\n            dpdt()[N-1] -= signed_pow( q()[N-1] - q_right , m_lam-1 );\n        }\n    }\n    //]\n};\n\n#endif\n", "meta": {"hexsha": "697208458676262f9957ee7c487e0522aa1b35b3", "size": 2524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/mpi/osc_chain_1d_system.hpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "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": "boost/boost_1_56_0/libs/numeric/odeint/performance/mpi/osc_chain_1d_system.hpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/mpi/osc_chain_1d_system.hpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 28.3595505618, "max_line_length": 97, "alphanum_fraction": 0.5534865293, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6749496331997551}}
{"text": "#include \"derivatives.h\"\r\n#include <boost/math/tools/numerical_differentiation.hpp>\r\n#include <nlopt.h>\r\n#include <math.h>\r\n\r\nusing namespace arma;\r\n\r\n\r\ndouble optim::compute_first_derivative(std::function<double(const double&)> f, const double & x)\r\n{\r\n\tdouble error_estimate;\r\n\treturn boost::math::tools::finite_difference_derivative<decltype(f),double,6>(f, x,&error_estimate);\r\n}\r\n\r\n\r\nvec optim::compute_gradient(ObjectiveFunction feval, const vec & x)\r\n{\r\n\tvec g(x.size());\r\n\tfor (arma::uword i = 0; i < g.size(); ++i) {\r\n\t\tauto f_i = [&](const double& s) {\r\n\t\t\tvec v = x;\r\n\t\t\tv[i] = s;\r\n\t\t\treturn feval(v);\r\n\t\t};\r\n\r\n\t\tg[i] = compute_first_derivative(f_i, x[i]);\r\n\t}\r\n\treturn g;\r\n}\r\n\r\nmat optim::compute_hessian(ObjectiveFunction feval, const vec & x)\r\n{\r\n\t{\r\n\t\tusing namespace std::placeholders;\r\n\r\n\t\tint N = x.size();\r\n\t\tmat H(N, N);\r\n\t\tauto fij = [&x,&feval](double i, double j, double xi, double xj) {\r\n\t\t\tvec v = x;\r\n\t\t\tdouble di = xi - x[i];\r\n\t\t\tdouble dj = xj - x[j];\r\n\t\t\tv[i] += di;\r\n\t\t\tv[j] += dj;\r\n\t\t\treturn feval(v);\r\n\t\t};\r\n\t\t\r\n\t\tfor (int i = 0; i < N; ++i) {\t\t\t\r\n\t\t\t\r\n\t\t\tfor (int j = i; j < N; ++j) {\r\n\t\t\t\t\r\n\t\t\t\tauto di = [fij, i, j,x](const double xj) {return compute_first_derivative(std::bind(fij, i, j, _1, xj),x[i]); };\r\n\t\t\t\tauto dij = compute_first_derivative(di, x[j]);\r\n\t\t\t\tH(i, j) = dij;\r\n\t\t\t\tif (i != j) {\r\n\t\t\t\t\tH(j, i) = H(i, j);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn H;\r\n\r\n\t}\r\n}\r\n\r\nmat optim::compute_jacobian(ObjectiveVectorFunction feval, const vec & x)\r\n{\r\n\tint N = x.size();\r\n\tmat J(N, N);\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tauto g = compute_gradient([&feval, i](decltype(x) v) {return feval(v)[i]; },x);\r\n\t\tfor (int j = 0; j < N; ++j) {\r\n\t\t\tJ(i, j) = g[j];\r\n\t\t}\r\n\t}\r\n\treturn J;\r\n\t\r\n}\r\n", "meta": {"hexsha": "b6965adaa8df88cf050288f191ee08a77bc4971c", "size": 1709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optim/derivatives.cpp", "max_stars_repo_name": "frannuca/quantumframe", "max_stars_repo_head_hexsha": "d95d4d36d9dfa6bfd527bb40428d070273164843", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optim/derivatives.cpp", "max_issues_repo_name": "frannuca/quantumframe", "max_issues_repo_head_hexsha": "d95d4d36d9dfa6bfd527bb40428d070273164843", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optim/derivatives.cpp", "max_forks_repo_name": "frannuca/quantumframe", "max_forks_repo_head_hexsha": "d95d4d36d9dfa6bfd527bb40428d070273164843", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-26T19:18:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T19:18:27.000Z", "avg_line_length": 22.1948051948, "max_line_length": 117, "alphanum_fraction": 0.5576360445, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6749496237770998}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2009\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_LinearLeastSquares2_hpp__\n#define __Thea_Algorithms_LinearLeastSquares2_hpp__\n\n#include \"../Common.hpp\"\n#include \"../Array.hpp\"\n#include \"../Line2.hpp\"\n#include \"../MatVec.hpp\"\n#include \"CentroidN.hpp\"\n#include \"Iterators.hpp\"\n#include \"PointTraitsN.hpp\"\n#include <Eigen/Eigenvalues>\n\nnamespace Thea {\nnamespace Algorithms {\n\n/** Fitting linear models to 2D data by minimizing sum-of-squared-errors. */\ntemplate <typename T, typename Enable = void>\nclass /* THEA_API */ LinearLeastSquares2\n{\n  public:\n    /**\n     * Linear least-squares fitting of a line to a set of 2D objects. InputIterator must dereference to type T or pointer-to-T.\n     *\n     * @param begin The first object in the set.\n     * @param end One position beyond the last object in the set.\n     * @param line Used to return the best-fit line.\n     * @param centroid If non-null, used to return the centroid of the objects, which is computed in the process of finding the\n     *   best-fit line.\n     *\n     * @return The sum of squared fitting errors.\n     */\n    template <typename InputIterator>\n    static double fitLine(InputIterator begin, InputIterator end, Line2 & line, Vector2 * centroid = nullptr);\n\n}; // class LinearLeastSquares2\n\n// Fitting lines to sets of objects that map to single points in 2-space.\ntemplate <typename T>\nclass /* THEA_API */ LinearLeastSquares2<T, typename std::enable_if< IsNonReferencedPointN<T, 2>::value >::type>\n{\n  public:\n    template <typename InputIterator>\n    static double fitLine(InputIterator begin, InputIterator end, Line2 & line, Vector2 * centroid = nullptr)\n    {\n      Vector2d center = CentroidN<T, 2>::compute(begin, end);\n      Matrix2d m = Matrix2d::Zero();\n      for (auto iter = makeRefIterator(begin); iter != makeRefIterator(end); ++iter)\n      {\n        Vector2d diff = Vector2d(PointTraitsN<T, 2>::getPosition(*iter)) - center;\n\n        m(0, 0) += (diff.y() * diff.y());\n        m(0, 1) -= (diff.x() * diff.y());\n        m(1, 1) += (diff.x() * diff.x());\n      }\n\n      m(1, 0) = m(0, 1);\n\n      Eigen::SelfAdjointEigenSolver eigensolver;\n      if (eigensolver.computeDirect(m).info() != Eigen::Success)\n \u00a0      throw Error(\"LinearLeastSquares2: Could not eigensolve covariance matrix\");\n\n      // Eigenvalues are non-negative (covariance matrix is non-negative definite) and in increasing order\n      line = Line2::fromPointAndDirection(Vector2(center), Vector2(eigensolver.eigenvectors().col(0)));\n      if (centroid) *centroid = center;\n      return eigensolver.eigenvalues()[0];\n    }\n\n}; // class LinearLeastSquares2<Point2>\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "ffb70fe0a4aa6ac1dcb3065ea8d076177344d103", "size": 3186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/LinearLeastSquares2.hpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/LinearLeastSquares2.hpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/LinearLeastSquares2.hpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 36.2045454545, "max_line_length": 127, "alphanum_fraction": 0.6581920904, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6749492017031397}}
{"text": "//\n//  holo_gain.cpp\n//  autd3\n//\n//  Created by Seki Inoue on 7/6/16.\n//\n//\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <complex>\n#include <vector>\n#include <boost/assert.hpp>\n#include \"privdef.hpp\"\n#include \"autd3.hpp\"\n#include <boost/random.hpp>\n#include <Eigen/Eigen>\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#define REPEAT_SDP (10)\n#define LAMBDA_SDP (0.8)\n\nnamespace hologainimpl {\n    // TODO: use cache and interpolate. don't use exp\n    std::complex<float> transfer(Eigen::Vector3f trans_pos, Eigen::Vector3f trans_norm, Eigen::Vector3f target_pos) {\n        Eigen::Vector3f diff = trans_pos-target_pos;\n        float dist = diff.norm();\n        float cos = diff.dot(trans_norm)/dist/trans_norm.norm();\n        \n        //1.11   & 1.06  &  0.24 &  -0.12  &  0.035\n        float directivity = 1.11 *sqrt((2*0+1)/(4*M_PI))*1 + 1.06*sqrt((2*1+1)/(4*M_PI))*cos + 0.24*sqrt((2*2+1)/(4*M_PI))/2*(3*cos*cos-1)  -0.12*sqrt((2*3+1)/(4*M_PI))/2*cos*(5*cos*cos-3) + 0.035*sqrt((2*4+1)/(4*M_PI))/8*(35*cos*cos*cos*cos-30*cos*cos+3);\n        \n        std::complex<float> g = directivity/dist*exp(std::complex<float>(-dist*1.15e-4, -2*M_PI/ULTRASOUND_WAVELENGTH*dist));\n        return g;\n    }\n    \n    void removeRow(Eigen::MatrixXcf& matrix, unsigned int rowToRemove)\n    {\n        unsigned int numRows = matrix.rows()-1;\n        unsigned int numCols = matrix.cols();\n        \n        if( rowToRemove < numRows )\n            matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols);\n        \n        matrix.conservativeResize(numRows,numCols);\n    }\n    \n    void removeColumn(Eigen::MatrixXcf& matrix, unsigned int colToRemove)\n    {\n        unsigned int numRows = matrix.rows();\n        unsigned int numCols = matrix.cols()-1;\n        \n        if( colToRemove < numCols )\n            matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove);\n        \n        matrix.conservativeResize(numRows,numCols);\n    }\n}\n\nautd::GainPtr autd::HoloGainSdp::Create(Eigen::MatrixX3f foci, Eigen::VectorXf amp) {\n    std::shared_ptr<HoloGainSdp> ptr = std::shared_ptr<HoloGainSdp>(new HoloGainSdp());\n    ptr->_foci = foci;\n    ptr->_amp = amp;\n    return ptr;\n}\n\nvoid autd::HoloGainSdp::build() {\n    if (this->built()) return;\n    if (this->geometry() == nullptr) BOOST_ASSERT_MSG(false, \"Geometry is required to build Gain\");\n\n    //const double pinvtoler=1.e-7;\n    const float alpha = 1e-3;\n    \n    const int M = (int)_foci.rows();\n    const int N = (int)this->geometry()->numTransducers();\n    \n    Eigen::MatrixXcf P = Eigen::MatrixXcf::Zero(M, M);\n    Eigen::VectorXcf p = Eigen::VectorXcf::Zero(M);\n    Eigen::MatrixXcf B = Eigen::MatrixXcf(M,N);\n    Eigen::VectorXcf q = Eigen::VectorXcf(N);\n    \n    boost::random::mt19937 rng( static_cast<unsigned int>(time(0)) );\n    boost::random::uniform_real_distribution<> range(0,1);\n    boost::random::variate_generator< boost::random::mt19937, boost::random::uniform_real_distribution<> > mt(rng, range);\n    \n    for (int i = 0; i < M; i++) {\n        p(i) = _amp(i)*exp(std::complex<float>(0,2*M_PI*mt()));\n        P(i,i) = _amp(i);\n        \n        Eigen::Vector3f q = _foci.row(i);\n        for (int j = 0; j < N; j++) {\n            B(i,j) = hologainimpl::transfer(\n                        this->geometry()->position(j),\n                        this->geometry()->direction(j),\n                        q);\n        }\n    }\n    \n    Eigen::JacobiSVD<Eigen::MatrixXcf> svd(B, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::JacobiSVD<Eigen::MatrixXcf>::SingularValuesType singularValues_inv= svd.singularValues();\n    for ( long i=0; i < singularValues_inv.size(); ++i) {\n        singularValues_inv(i) =  singularValues_inv(i) / (singularValues_inv(i) *singularValues_inv(i)  + alpha*alpha);\n    }\n    Eigen::MatrixXcf pinvB = (svd.matrixV()*singularValues_inv.asDiagonal()*svd.matrixU().adjoint());\n    \n    Eigen::MatrixXcf MM = P*(Eigen::MatrixXcf::Identity(M, M) - B*pinvB)*P;\n    Eigen::MatrixXcf X = Eigen::MatrixXcf::Identity(M, M);\n    for (int i = 0; i < REPEAT_SDP; i++) {\n        unsigned int ii = mt()*M;\n        \n        Eigen::MatrixXcf Xc = X;\n        hologainimpl::removeRow(Xc, ii);\n        hologainimpl::removeColumn(Xc, ii);\n        Eigen::VectorXcf MMc = MM.col(ii);\n        MMc.block(ii,0,MMc.rows()-1-ii,1) = MMc.block(ii+1,0,MMc.rows()-1-ii,1);\n        MMc.conservativeResize(MMc.rows()-1, 1);\n        \n        Eigen::VectorXcf x = Xc*MMc;\n        std::complex<float> gamma = x.adjoint()*MMc;\n        if (gamma.real()>1e-9) {\n            x = -x*sqrt(LAMBDA_SDP/gamma.real());\n            X.block(ii,0,1,ii) = x.block(0,0,ii,1).adjoint().eval();\n            X.block(ii,ii+1, 1, M-ii-1) = x.block(ii,0,M-1-ii,1).adjoint().eval();\n            X.block(0,ii,ii,1) = x.block(0,0,ii,1).eval();\n            X.block(ii+1,ii, M-ii-1, 1) = x.block(ii,0,M-1-ii,1).eval();\n        }else {\n            X.block(ii,0,1,ii) = Eigen::VectorXcf::Zero(ii).adjoint();\n            X.block(ii,ii+1, 1, M-ii-1) = Eigen::VectorXcf::Zero(M-1).adjoint();\n            X.block(0,ii,ii,1) = Eigen::VectorXcf::Zero(ii);\n            X.block(ii+1,ii, M-ii-1, 1) = Eigen::VectorXcf::Zero(M-1);\n        }\n        \n    }\n    \n    Eigen::ComplexEigenSolver<Eigen::MatrixXcf> ces(X);\n    Eigen::VectorXcf evs = ces.eigenvalues();\n    float abseiv = 0;\n    int idx = 0;\n    for (int j = 0; j < evs.rows(); j++) {\n        float eiv = abs(evs(j));\n        if (abseiv < eiv) {\n            abseiv = eiv;\n            idx = j;\n        }\n    }\n    \n    Eigen::VectorXcf u = ces.eigenvectors().col(idx);\n    q = pinvB*P*u;\n    \n    this->_data.clear();\n    const int ndevice = this->geometry()->numDevices();\n    for (int i = 0; i < ndevice; i++) {\n        this->_data[this->geometry()->deviceIdForDeviceIdx(i)].resize(NUM_TRANS_IN_UNIT);\n    }\n    \n    //float maxCoeff = sqrt(q.cwiseAbs2().maxCoeff());\n    for (int j = 0; j < N; j++) {\n        float famp = 1.0;//abs(q(j))/maxCoeff;\n        float fphase = arg(q(j)) / (2*M_PI) + 0.5;\n        uint8_t amp = famp*255, phase = (1-fphase)*255;\n        this->_data[this->geometry()->deviceIdForTransIdx(j)][j%NUM_TRANS_IN_UNIT] = ((uint16_t)amp << 8) + phase;\n    }\n}\n", "meta": {"hexsha": "1ef5fd73f0286bd30e4bfbd2820bf39305862775", "size": 6277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "client/lib/holo_gain.cpp", "max_stars_repo_name": "shinolab/autd_old", "max_stars_repo_head_hexsha": "68b9b65b34eb3020e286eae1d5d2222e7de79292", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-12-01T07:21:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-02T15:13:51.000Z", "max_issues_repo_path": "client/lib/holo_gain.cpp", "max_issues_repo_name": "shinolab/autd_old", "max_issues_repo_head_hexsha": "68b9b65b34eb3020e286eae1d5d2222e7de79292", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "client/lib/holo_gain.cpp", "max_forks_repo_name": "shinolab/autd_old", "max_forks_repo_head_hexsha": "68b9b65b34eb3020e286eae1d5d2222e7de79292", "max_forks_repo_licenses": ["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.813253012, "max_line_length": 256, "alphanum_fraction": 0.5859487016, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.951863227517834, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6748892469091535}}
{"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 * estimate_plane.cpp\n *\n *  Created on: Dec 28, 2020\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab.\n */\n\n\n#include \"mrob/estimate_plane.hpp\"\n#include <Eigen/Eigenvalues>\n\nusing namespace mrob;\n\nMat41 estimate_plane_centered(const Eigen::Ref<const MatX> X);\n\nMat41 mrob::estimate_plane(const Eigen::Ref<const MatX> X)\n{\n    // Initialization\n    assert(X.cols() == 3  && \"Estimate_plane: Incorrect sizing, we expect Nx3\");\n    assert(X.rows() >= 3  && \"Estimate_plane: Incorrect sizing, we expect at least 3 correspondences (not aligned)\");\n\n    // Plane estimation, centered approach\n    return estimate_plane_centered(X);\n}\n\n//local function, we also will test the homogeneous plane estimation\nMat41 estimate_plane_centered(const Eigen::Ref<const MatX> X)\n{\n    uint_t N = X.rows();\n    // Calculate center of points:\n    Mat13 c =  X.colwise().sum();\n    c /= (double)N;\n\n\n    MatX qx = X.rowwise() - c;\n    Mat3 C = qx.transpose() * qx;\n\n\n    Eigen::SelfAdjointEigenSolver<Mat3> eigs;\n    eigs.computeDirect(C);\n\n    Mat31 normal = eigs.eigenvectors().col(0);\n\n    matData_t d = - c*normal;\n\n    Mat41 plane;\n    plane << normal, d;\n    // error = eigs.eigenvalues()(0);\n    return plane;\n\n}\n\n\n\nMat31 mrob::estimate_normal(const Eigen::Ref<const MatX> X)\n{\n    Mat41 res = estimate_plane(X);\n    return res.head(3);\n}\n\n\nMat31 mrob::estimate_centroid(const Eigen::Ref<const MatX> X)\n{\n    // Initialization\n    assert(X.cols() == 3  && \"Estimate_centroid: Incorrect sizing, we expect Nx3\");\n    assert(X.rows() >= 3  && \"Estimate_centroid: Incorrect sizing, we expect at least 3 correspondences (not aligned)\");\n\n    uint_t N = X.rows();\n    Mat13 c =  X.colwise().sum();\n    c /= (double)N;\n    return c;\n}\n", "meta": {"hexsha": "101d2847a913dc8dbc0be0658fa4b07223e3adea", "size": 2409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/estimate_plane.cpp", "max_stars_repo_name": "iakov/mrob", "max_stars_repo_head_hexsha": "fdbb0cf1b2a0e32eb9bad655e54222c85279a91d", "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/estimate_plane.cpp", "max_issues_repo_name": "iakov/mrob", "max_issues_repo_head_hexsha": "fdbb0cf1b2a0e32eb9bad655e54222c85279a91d", "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/estimate_plane.cpp", "max_forks_repo_name": "iakov/mrob", "max_forks_repo_head_hexsha": "fdbb0cf1b2a0e32eb9bad655e54222c85279a91d", "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": 27.375, "max_line_length": 120, "alphanum_fraction": 0.6749688667, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6748686435319182}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n// test that math functions operating on integers return doubles and not ints\n\nint main()\n{\n  Array<double,1> a(10);\n  Array<int,1> b(10);\n  b=tensor::i;\n  a=sqrt(b);\n\n  cout << a ; \n  BZTEST(a(2)==sqrt(2));\n  BZTEST(a(5)==sqrt(5));\n  \n  a=sqrt(tensor::i); \n  cout << a ; \n  BZTEST(a(2)==sqrt(2));\n  BZTEST(a(5)==sqrt(5));\n\n  // we can't really test that the powN and abs are not cast to\n  // doubles because it's not really visible from the outside.\n\n  return 0;\n}\n\n", "meta": {"hexsha": "027c28deb960b11d430493723d63b41822328557", "size": 543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/int-math-func.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/int-math-func.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/int-math-func.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": 18.1, "max_line_length": 77, "alphanum_fraction": 0.6298342541, "num_tokens": 179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6748686415389668}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <utility>\n\n#include \"../../includes/convex_hull_gift_wrapping.hpp\"\n\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\nusing bg::dsv;\n\nint main()\n{\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::multi_point<point_t> mpoint_t;\n\n    mpoint_t mpt1, hull;\n    bg::read_wkt(\"MULTIPOINT(0 0,6 0,2 2,4 2,5 3,5 5,-2 2)\", mpt1);\n\n    algo1::GiftWrapping(mpt1, hull);\n\n    std::cout << \"Dataset: \" << dsv(mpt1) << std::endl;\n    std::cout << \"Convex hull: \" << dsv(hull) << std::endl;\n\n    return 0;\n}\n\n/*\nOutput:\nDataset: ((0, 0), (6, 0), (2, 2), (4, 2), (5, 3), (5, 5), (-2, 2))\nConvex hull: ((-2, 2), (0, 0), (6, 0), (5, 5), (-2, 2))\n*/", "meta": {"hexsha": "480045f02400a442128bc7f8dac3c4f556842671", "size": 845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/convex_hull/example_small.cpp", "max_stars_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_stars_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_stars_repo_licenses": ["MIT"], "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/convex_hull/example_small.cpp", "max_issues_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_issues_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_issues_repo_licenses": ["MIT"], "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/convex_hull/example_small.cpp", "max_forks_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_forks_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_forks_repo_licenses": ["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.2368421053, "max_line_length": 67, "alphanum_fraction": 0.5952662722, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6748527487320828}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main() {\n  Matrix2d a;\n  a << 1, 2,\n      3, 4;\n  MatrixXd b(2, 2);\n  b << 2, 3,\n      1, 4;\n  std::cout << \"a + b =\\n\" << a + b << std::endl;\n  std::cout << \"a - b =\\n\" << a - b << std::endl;\n  std::cout << \"Doing a += b;\" << std::endl;\n  a += b;\n  std::cout << \"Now a =\\n\" << a << std::endl;\n  Vector3d v(1, 2, 3);\n  Vector3d w(1, 0, 0);\n  std::cout << \"-v + w - v =\\n\" << -v + w - v << std::endl;\n}\n", "meta": {"hexsha": "92bfdcc5ceae9ec9ab2f4a4f8788684502660f29", "size": 474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/tut_arithmetic_add_sub.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_add_sub.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_add_sub.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": 21.5454545455, "max_line_length": 59, "alphanum_fraction": 0.4514767932, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6748527391044087}}
{"text": "/* Boost.Flyweight example of flyweight-based memoization.\n *\n * Copyright 2006-2008 Joaquin M Lopez Munoz.\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 * See http://www.boost.org/libs/flyweight for library home page.\n */\n\n#include <boost/flyweight.hpp>\n#include <boost/flyweight/key_value.hpp>\n#include <boost/flyweight/no_tracking.hpp>\n#include <boost/noncopyable.hpp>\n#include <iostream>\n\nusing namespace boost::flyweights;\n\n/* Memoized calculation of Fibonacci numbers */\n\n/* This class takes an int n and calculates F(n) at construction time */\n\nstruct compute_fibonacci;\n\n/* A Fibonacci number can be modeled as a key-value flyweight\n * We choose the no_tracking policy so that the calculations\n * persist for future use throughout the program. See\n * Tutorial: Configuring Boost.Flyweight: Tracking policies for\n * further information on tracking policies.\n */\n\ntypedef flyweight<key_value<int,compute_fibonacci>,no_tracking> fibonacci;\n\n/* Implementation of compute_fibonacci. Note that the construction\n * of compute_fibonacci(n) uses fibonacci(n-1) and fibonacci(n-2),\n * which effectively memoizes the computation.\n */\n\nstruct compute_fibonacci:private boost::noncopyable\n{\n  compute_fibonacci(int n):\n    result(n==0?0:n==1?1:fibonacci(n-2).get()+fibonacci(n-1).get())\n  {}\n\n  operator int()const{return result;}\n  int result;\n};\n\nint main()\n{\n  /* list some Fibonacci numbers */\n\n  for(int n=0;n<40;++n){\n    std::cout<<\"F(\"<<n<<\")=\"<<fibonacci(n)<<std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "618c5f2f029b437087d9cdc2b7a44af6b5a10f20", "size": 1607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/flyweight/example/fibonacci.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/flyweight/example/fibonacci.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/flyweight/example/fibonacci.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.2372881356, "max_line_length": 74, "alphanum_fraction": 0.7342874922, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6748500655973905}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing std::cout;\nusing std::endl;\n\nMatrixXd CalculateJacobian(const VectorXd& x_state);\n\nint main() {\n  /**\n   * Compute the Jacobian Matrix\n   */\n\n  // predicted state example\n  // px = 1, py = 2, vx = 0.2, vy = 0.4\n  VectorXd x_predicted(4);\n  x_predicted << 1, 2, 0.2, 0.4;\n\n  MatrixXd Hj = CalculateJacobian(x_predicted);\n\n  cout << \"Hj:\" << endl << Hj << endl;\n\n  return 0;\n}\n\nMatrixXd CalculateJacobian(const VectorXd& x_state) {\n\n  MatrixXd Hj(3, 4);\n  // recover state parameters\n  float px = x_state(0);\n  float py = x_state(1);\n  float vx = x_state(2);\n  float vy = x_state(3);\n\n  // TODO: YOUR CODE HERE\n  const float denom2 = px * px + py * py;\n  const float denom = std::sqrt(denom2);\n  const float denom3 = denom * denom2;\n\n  // check division by zero\n  if (std::abs(px - py) <= 1e-8) {\n    cout << \"CalculateJacobian () - Error - Division by Zero\" << endl;\n    return Hj;\n  }\n\n  // compute the Jacobian matrix\n  Hj(0, 0) = px / denom;\n  Hj(0, 1) = py / denom;\n  Hj(0, 2) = Hj(0, 3) = 0.0f;\n  Hj(1, 0) = -py / denom2;\n  Hj(1, 1) = px / denom2;\n  Hj(1, 2) = Hj(1, 3) = 0.0f;\n  Hj(2, 0) = py * (vx * py - vy * px) / denom3;\n  Hj(2, 1) = px * (vy * px - vx * py) / denom3;\n  Hj(2, 2) = px / denom;\n  Hj(2, 3) = py / denom;\n\n  return Hj;\n}", "meta": {"hexsha": "6523cf5fd77fccd08a9af0543bfce88c8998b846", "size": 1357, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SFND_Kalman_Filter/EKF_Prep/jacobian_matrix/main.cc", "max_stars_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_stars_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T07:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:42:13.000Z", "max_issues_repo_path": "SFND_Kalman_Filter/EKF_Prep/jacobian_matrix/main.cc", "max_issues_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_issues_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SFND_Kalman_Filter/EKF_Prep/jacobian_matrix/main.cc", "max_forks_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_forks_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-09-29T05:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T18:26:53.000Z", "avg_line_length": 21.8870967742, "max_line_length": 70, "alphanum_fraction": 0.5865880619, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6748500437037168}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/algo/factorial.h\" // header to test\n\nusing namespace biosim;\n\nBOOST_AUTO_TEST_SUITE(suite_factorial)\n\nBOOST_AUTO_TEST_CASE(factorial) {\n  BOOST_CHECK(std::isinf(math::algo::factorial(-1)));\n  BOOST_CHECK(math::algo::factorial(0) == 1.0);\n  BOOST_CHECK(math::algo::factorial(1) == 1.0);\n  BOOST_CHECK(math::algo::factorial(2) == 2.0);\n  BOOST_CHECK(math::algo::factorial(25) == 15511210043330985984000000.0L);\n  BOOST_CHECK_CLOSE(math::algo::factorial(1754), 1.97926189010501005367e+4930L, 1e-20);\n  BOOST_CHECK(std::isinf(math::algo::factorial(1755)));\n}\n\nBOOST_AUTO_TEST_CASE(binomial_coefficient) {\n  BOOST_CHECK(math::algo::binomial_coefficent(0, 0) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(1, 0) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(1, 1) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(2, 0) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(2, 1) == 2);\n  BOOST_CHECK(math::algo::binomial_coefficent(2, 2) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(3, 0) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(3, 1) == 3);\n  BOOST_CHECK(math::algo::binomial_coefficent(3, 2) == 3);\n  BOOST_CHECK(math::algo::binomial_coefficent(3, 3) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(4, 0) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(4, 1) == 4);\n  BOOST_CHECK(math::algo::binomial_coefficent(4, 2) == 6);\n  BOOST_CHECK(math::algo::binomial_coefficent(4, 3) == 4);\n  BOOST_CHECK(math::algo::binomial_coefficent(4, 4) == 1);\n\n  BOOST_CHECK(math::algo::binomial_coefficent(0, 1) == 0);\n  BOOST_CHECK(math::algo::binomial_coefficent(0, 2) == 0);\n  BOOST_CHECK(math::algo::binomial_coefficent(49, 6) == 13983816);\n  BOOST_CHECK(math::algo::binomial_coefficent(2.5, 2) == 1.875);\n  BOOST_CHECK(math::algo::binomial_coefficent(-1, 2) == 1);\n  BOOST_CHECK(math::algo::binomial_coefficent(-1, 3) == -1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "405c3370393794a8a6ec406a50dae71f37276e08", "size": 1941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/algo/factorial.cpp", "max_stars_repo_name": "shze/biosim", "max_stars_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/algo/factorial.cpp", "max_issues_repo_name": "shze/biosim", "max_issues_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/algo/factorial.cpp", "max_forks_repo_name": "shze/biosim", "max_forks_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_forks_repo_licenses": ["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.1333333333, "max_line_length": 87, "alphanum_fraction": 0.7135497166, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6748136169892506}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n/*\nThis program demonstrates the use of the fluid decomposition toolbox\nto compute a summary of spectral features of an audio file\n*/\n\n#include <AudioFile/IAudioFile.h>\n#include <Eigen/Core>\n#include <algorithms/public/DCT.hpp>\n#include <algorithms/public/Loudness.hpp>\n#include <algorithms/public/MelBands.hpp>\n#include <algorithms/public/STFT.hpp>\n#include <algorithms/public/SpectralShape.hpp>\n#include <algorithms/public/MultiStats.hpp>\n#include <algorithms/public/YINFFT.hpp>\n#include <data/FluidIndex.hpp>\n#include <data/TensorTypes.hpp>\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n\nfluid::RealVector computeStats(fluid::RealMatrixView   matrix,\n                               fluid::algorithm::MultiStats stats)\n{\n  fluid::index      dim = matrix.cols();\n  fluid::RealMatrix tmp(dim, 7);\n  fluid::RealVector result(dim * 7);\n  stats.process(matrix.transpose(), tmp);\n  for (int j = 0; j < dim; j++)\n  {\n    result(fluid::Slice(j * 7, 7)) = tmp.row(j);\n  }\n  return result;\n}\n\nvoid printRow(std::string name, fluid::RealVectorView vals)\n{\n  using namespace std;\n  cout << setw(10) << name;\n  for (auto v : vals) { cout << setw(10) << setprecision(5) << v; }\n  cout << endl;\n}\n\nint main(int argc, char* argv[])\n{\n  using namespace fluid;\n  using namespace fluid::algorithm;\n  using fluid::index;\n  using std::cout;\n  using std::endl;\n  using std::setw;\n\n  if (argc <= 1)\n  {\n    cout << \"usage: describe input_file.wav\\n\";\n    return 1;\n  }\n  const char* inputFile = argv[1];\n\n  HISSTools::IAudioFile file(inputFile);\n\n  index nSamples = file.getFrames();\n  auto  samplingRate = file.getSamplingRate();\n\n  if (!file.isOpen())\n  {\n    cout << \"Input file could not be opened\\n\";\n    return -2;\n  }\n\n  index nBins = 513;\n  index fftSize = 2 * (nBins - 1);\n  index hopSize = 1024;\n  index windowSize = 1024;\n  index halfWindow = windowSize / 2;\n  index nBands = 40;\n  index nCoefs = 13;\n  index minFreq = 20;\n  index maxFreq = 5000;\n\n  STFT          stft{windowSize, fftSize, hopSize};\n  MelBands      bands{nBands, fftSize};\n  DCT           dct{nBands, nCoefs};\n  YINFFT        yin;\n  SpectralShape shape;\n  Loudness      loudness{windowSize};\n  MultiStats    stats;\n\n  bands.init(minFreq, maxFreq, nBands, nBins, samplingRate, windowSize);\n  dct.init(nBands, nCoefs);\n  stats.init(0, 0, 50, 100);\n  loudness.init(windowSize, samplingRate);\n\n  RealVector in(nSamples);\n  file.readChannel(in.data(), nSamples, 0);\n  RealVector padded(in.size() + windowSize + hopSize);\n  index      nFrames = floor((padded.size() - windowSize) / hopSize);\n  RealMatrix pitchMat(nFrames, 2);\n  RealMatrix loudnessMat(nFrames, 2);\n  RealMatrix mfccMat(nFrames, nCoefs);\n  RealMatrix shapeMat(nFrames, 7);\n  std::iota(padded.begin(), padded.end(), 0);\n  padded(Slice(halfWindow, in.size())) = in;\n\n  for (int i = 0; i < nFrames; i++)\n  {\n    ComplexVector  frame(nBins);\n    RealVector     magnitude(nBins);\n    RealVector     mels(nBands);\n    RealVector     mfccs(nCoefs);\n    RealVector     pitch(2);\n    RealVector     shapeDesc(7);\n    RealVector     loudnessDesc(2);\n    RealVectorView window = padded(fluid::Slice(i * hopSize, windowSize));\n    stft.processFrame(window, frame);\n    stft.magnitude(frame, magnitude);\n    bands.processFrame(magnitude, mels, false, false, true);\n    dct.processFrame(mels, mfccs);\n    mfccMat.row(i) = mfccs;\n    yin.processFrame(magnitude, pitch, minFreq, maxFreq, samplingRate);\n    pitchMat.row(i) = pitch;\n    shape.processFrame(magnitude, shapeDesc, samplingRate);\n    shapeMat.row(i) = shapeDesc;\n    loudness.processFrame(window, loudnessDesc, true, true);\n    loudnessMat.row(i) = loudnessDesc;\n  }\n  RealVector  pitchStats = computeStats(pitchMat, stats);\n  RealVector  loudnessStats = computeStats(loudnessMat, stats);\n  RealVector  shapeStats = computeStats(shapeMat, stats);\n  RealVector  mfccStats = computeStats(mfccMat, stats);\n  std::string colNames[] = {\"Descriptor\", \"mean\", \"stdev\", \"skew\",\n                            \"kurt\",       \"low\",  \"mid\",   \"high\"};\n  std::string shapeDescs[] = {\"Centroid\", \"Spread\",   \"Skewness\", \"Kurtosis\",\n                              \"Rolloff\",  \"Flatness\", \"Crest\"};\n  for (auto n : colNames) cout << setw(10) << n;\n  cout << endl;\n  printRow(\"Pitch\", pitchStats(Slice(0, 7)));\n  printRow(\"Pitch Conf.\", pitchStats(Slice(7, 7)));\n  printRow(\"Loudness\", loudnessStats(Slice(0, 7)));\n  printRow(\"True Peak\", loudnessStats(Slice(7, 7)));\n  for (int i = 0; i < 7; i++)\n    printRow(shapeDescs[i], shapeStats(Slice(i * 7, 7)));\n  for (int i = 0; i < 13; i++)\n    printRow(\"MFCC\" + std::to_string(i), mfccStats(Slice(i * 7, 7)));\n  return 0;\n}\n", "meta": {"hexsha": "d4b2dfe5da0bf38266fffb8dc2d3c12094830d57", "size": 5034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/describe.cpp", "max_stars_repo_name": "robclouth/flucoma-core", "max_stars_repo_head_hexsha": "aead0c20814ea6ede3c38dd0cbe257c7cf5ad4e0", "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/describe.cpp", "max_issues_repo_name": "robclouth/flucoma-core", "max_issues_repo_head_hexsha": "aead0c20814ea6ede3c38dd0cbe257c7cf5ad4e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "examples/describe.cpp", "max_forks_repo_name": "robclouth/flucoma-core", "max_forks_repo_head_hexsha": "aead0c20814ea6ede3c38dd0cbe257c7cf5ad4e0", "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.2692307692, "max_line_length": 77, "alphanum_fraction": 0.668057211, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248242542283, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.6747779675348691}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_HESSIAN_MATRIX_UTILITIES_INCLUDE\n#define MTL_HESSIAN_MATRIX_UTILITIES_INCLUDE\n\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/operation/entry_similar.hpp>\n\nnamespace mtl { namespace matrix {\n\n/// Fills a matrix A with A[i][j] = factor * (i + j)\n/** Intended for dense matrices.\n    Works on sparse matrices with inserter but is very expensive. **/\ntemplate <typename Matrix, typename Value>\nvoid hessian_setup(Matrix& A, Value factor)\n{\n    typedef typename Collection<Matrix>::value_type    value_type;\n    typedef typename Collection<Matrix>::size_type     size_type;\n    \n    inserter<Matrix> ins(A, num_cols(A));\n    \n    for (size_type r= 0; r < num_rows(A); r++)\n\tfor (size_type c= 0; c < num_cols(A); c++)\n\t    ins[r][c] << factor * (value_type(r) + value_type(c));\n}\n\nnamespace impl {\n\n    /*\n    - Check matrix product C = A * B with:\n      - A is MxN, B is NxL, C is MxL\n      - with matrices a_ij = i+j, b_ij = 2(i+j); \n      - c_ij = 1/3 N (1 - 3i - 3j + 6ij - 3N + 3iN + 3jN + 2N^2).\n\n    */\n    // Not really generic\n    template <typename Value>\n    double inline hessian_product_i_j (Value i, Value j, Value N)\n    {\n        return 1.0/3.0 * N * (1.0 - 3*i - 3*j + 6*i*j - 3*N + 3*i*N + 3*j*N + 2*N*N);\n    }\n        \n    template <typename Value>\n    inline bool similar_values(Value x, Value y) \n    {\n        using std::abs; using std::max;\n        return abs(x - y) / max(abs(x), abs(y)) < 0.000001;\n    }\n\n    template <typename Matrix>\n    void inline check_entry(Matrix const& C, unsigned long r, unsigned long c, \n\t\t\t    unsigned long reduced_dim, double factor)\n    {\n\tif (!entry_similar(C, r, c, factor * hessian_product_i_j(r, c, reduced_dim), 0.00001)) {\n\t    std::cerr << \"Result in C[\" << r << \"][\" << c << \"] should be \" \n\t\t      << factor * hessian_product_i_j(r, c, reduced_dim)\n\t\t      << \" but is \" << C[r][c] << \"\\n\";\n\t    MTL_THROW(unexpected_result());\n\t}\n    }\n\n} // impl       \n\n\n/// Check if matrix C is A * B with A and B set by hessian_setup\n/** C has dimensions M x L and reduced_dim is N, see hessian_setup. **/\ntemplate <typename Matrix>\nvoid check_hessian_matrix_product(Matrix const& C, typename Matrix::size_type reduced_dim, double factor= 1.0)\n{\n    if (num_rows(C) * num_cols(C) == 0) return; // otherwise out of range\n\n    impl::check_entry(C, 0, 0, reduced_dim, factor);\n    impl::check_entry(C, 0, num_cols(C)-1, reduced_dim, factor);\n    impl::check_entry(C, num_rows(C)-1, 0, reduced_dim, factor);\n    impl::check_entry(C, num_rows(C)-1, num_cols(C)-1, reduced_dim, factor);\n    impl::check_entry(C, num_rows(C)/2, num_cols(C)/2, reduced_dim, factor);\n}\n\n} // namespace matrix;\n\nusing matrix::hessian_setup;\nusing matrix::check_hessian_matrix_product;\n\n} // namespace mtl\n\n#endif // MTL_HESSIAN_MATRIX_UTILITIES_INCLUDE\n", "meta": {"hexsha": "55ce0a53e52805f0d4d0e9d7bbd9b7accff6d102", "size": 3403, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/hessian_setup.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/matrix/hessian_setup.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "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/mtl4/boost/numeric/mtl/matrix/hessian_setup.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["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.6930693069, "max_line_length": 110, "alphanum_fraction": 0.6553041434, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6746924257684435}}
{"text": "// gnuplot-c++ includes\n#include <gnuplot-iostream.h>\n\n// MLearn includes\n#include <MLearn/Core>\n#include <MLearn/Regression/GPRegressor/GPRegressor.h>\n\n// STL includes\n#include <vector>\n#include <array>\n#include <chrono>\n#include <string>\n#include <cmath>\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n// Boost includes\n#include <boost/program_options.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#define N_TRAIN_POINTS 50 // n_points along the time\n#define N_TEST_POINTS 500 // n_points along the time\n#define N_SAMPLES 1 // n of curves to sample\n\ntypedef double float_type;\n\nfloat_type test_function(const float_type& value){\n\treturn std::sin(value)*value + std::exp(-value*value);\n}\n\n\nint main(int argc, char** argv){\n\tstd::srand((unsigned int) time(0));\n\n\tGnuplot gp;\n\n\tusing namespace MLearn;\n\tusing namespace Regression;\n\tnamespace po = boost::program_options;\n\n\ttypedef MLMatrix<float_type> Matrix;\n\ttypedef MLVector<float_type> Vector;\n\n\t// Create command line options\n\tpo::options_description \n\tdesc(\"This is a demo showing gaussian process regression.\");\n\n\tdesc.add_options()\n\t\t(\"help\", \"Show the help\")\n\t\t(\"noise\", po::value<float_type>(), \"Noise variance (default: 0.0).\");\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm); \n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tfloat_type noise = 0;\n\tif (vm.count(\"noise\")){\n\t\tnoise = vm[\"noise\"].as<float_type>();\n\t}\n\n\t// noise\n\tboost::normal_distribution<float_type> dist;\n\tboost::random::mt19937 \n\t\tgenerator(std::chrono::system_clock::now().time_since_epoch().count());\n\n\t// train points\n\tMatrix X_train = Matrix::Random(1, N_TRAIN_POINTS);\n\tMatrix X_test(1, N_TEST_POINTS);\n\tX_test.row(0) = Vector::LinSpaced(N_TEST_POINTS, -6.0, 6.0);\n\tX_train.array() *= 12.0;\n\tX_train.array() -= 6.0;\n\tVector y_train(N_TRAIN_POINTS);\n\tVector y_real(N_TEST_POINTS);\n\tfor (int i = 0; i < N_TRAIN_POINTS; ++i){\n\t\ty_train[i] = test_function(X_train(0, i)) + noise*dist(generator); \n\t}\n\tfor (int i = 0; i < N_TEST_POINTS; ++i){\n\t\ty_real[i] = test_function(X_test(0, i)); \n\t}\n\n\t// Define GPRegressor\n\ttypedef Kernel<KernelType::RBF, float_type> KT;\n\tRegression::GPRegressor<KT, float_type> regressor;\n\tregressor.fit(X_train, y_train, noise);\n\tVector y_pred = regressor.predict(X_test);\n\tMatrix samples_pred = regressor.sample(5);\n\tMatrix confidence_intervals = regressor.confidence_interval(0.95);\n\n\tgp << \"set multiplot\\n\";\n\tgp << \"set xrange [-6:6]\\nset yrange [-6:6]\\n\";\n\tstd::vector<std::pair<float_type, float_type>> train_pts;\n\tstd::vector<std::pair<float_type, float_type>> real_pts;\n\tstd::vector<std::pair<float_type, float_type>> test_pts;\n\tstd::vector<std::pair<float_type, float_type>> sample_pts_1;\n\tstd::vector<std::pair<float_type, float_type>> sample_pts_2;\n\tstd::vector<std::pair<float_type, float_type>> sample_pts_3;\n\tstd::vector<std::tuple<float_type, float_type, float_type>> ci;\n\tfor(uint i = 0; i < N_TRAIN_POINTS; ++i) {\n\t\ttrain_pts.push_back(std::make_pair(X_train(0, i), y_train[i]));\n\t}\n\tfor(uint i = 0; i < N_TEST_POINTS; ++i) {\n\t\ttest_pts.push_back(std::make_pair(X_test(0, i), y_pred[i]));\n\t\treal_pts.push_back(std::make_pair(X_test(0, i), y_real[i]));\n\n\t\tsample_pts_1.push_back(std::make_pair(X_test(0, i), samples_pred(i,0)));\n\t\tsample_pts_2.push_back(std::make_pair(X_test(0, i), samples_pred(i,1)));\n\t\tsample_pts_3.push_back(std::make_pair(X_test(0, i), samples_pred(i,2)));\n\n\t\tci.push_back(std::make_tuple(\n\t\t\tX_test(0, i), confidence_intervals(0,i), confidence_intervals(1,i)\n\t\t));\n\t}\n\tgp << \"plot '-' u 1:2:3 with filledcurves lc rgb \\\"grey\\\" notitle,\"\n\t\t  \"'-' with points lc rgb \\\"black\\\" notitle,\" \n\t\t  \"'-' with lines lc rgb \\\"black\\\" title \\\"Mean fn\\\", \"\n\t\t  \"'-' with lines lc rgb \\\"blue\\\" title \\\"Real fn\\\", \"\n\t\t  \"'-' with lines lc rgb \\\"red\\\" notitle, \"\n\t\t  \"'-' with lines lc rgb \\\"cyan\\\" notitle, \"\n\t\t  \"'-' with lines lc rgb \\\"orange\\\" notitle\\n\";\n\tgp.send1d(ci);\n\tgp.send1d(train_pts);\n\tgp.send1d(test_pts);\n\tgp.send1d(real_pts);\n\tgp.send1d(sample_pts_1);\n\tgp.send1d(sample_pts_2);\n\tgp.send1d(sample_pts_3);\n\treturn 0;\n}", "meta": {"hexsha": "f7b98c9888a985c8c410fecbf20ed041ce682a3f", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demo_regression/gp_regression.cpp", "max_stars_repo_name": "phineasng/MLearn", "max_stars_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-14T19:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-05T02:29:35.000Z", "max_issues_repo_path": "demos/demo_regression/gp_regression.cpp", "max_issues_repo_name": "phineasng/MLearn", "max_issues_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-01-23T17:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T22:43:30.000Z", "max_forks_repo_path": "demos/demo_regression/gp_regression.cpp", "max_forks_repo_name": "phineasng/MLearn", "max_forks_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T18:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-23T18:17:14.000Z", "avg_line_length": 30.5588235294, "max_line_length": 74, "alphanum_fraction": 0.698026949, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6746599577451694}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXcf A = MatrixXcf::Random(4,4);\ncout << \"Here is a random 4x4 matrix, A:\" << endl << A << endl << endl;\nComplexSchur<MatrixXcf> schurOfA(A, false); // false means do not compute U\ncout << \"The triangular matrix T is:\" << endl << schurOfA.matrixT() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ebde6d82863240ce25c0ef9cbf0bfcee72b33596", "size": 414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_ComplexSchur_matrixT.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_ComplexSchur_matrixT.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_ComplexSchur_matrixT.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": 24.3529411765, "max_line_length": 76, "alphanum_fraction": 0.6690821256, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.674659952875278}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of gaussian_rbf class.\n */\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\nTEST_CASE(\"num_collect::interp::kernel::gaussian_rbf\") {\n    using num_collect::interp::kernel::gaussian_rbf;\n\n    SECTION(\"calculate\") {\n        const auto rbf = gaussian_rbf<double>();\n        constexpr double arg = 1.234;\n        const double value = std::exp(-arg * arg);\n        REQUIRE_THAT(rbf(arg), Catch::Matchers::WithinRel(value));\n    }\n}\n", "meta": {"hexsha": "04dd870933a40748fd13bbfaa916523e2c931f52", "size": 1193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/gaussian_rbf_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/interp/kernel/gaussian_rbf_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/interp/kernel/gaussian_rbf_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1388888889, "max_line_length": 75, "alphanum_fraction": 0.7150041911, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.6746508163328089}}
{"text": "/*\n    This file is part of beautiful-bullet.\n\n    Copyright (c) 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef BEAUTIFUL_BULLET_TOOLS_MATH_HPP\n#define BEAUTIFUL_BULLET_TOOLS_MATH_HPP\n\n#include <Eigen/Geometry>\n\nnamespace beautiful_bullet {\n    namespace tools {\n        Eigen::Matrix<double, 6, 1> lieAlgebraSE3(const Eigen::Vector3d& position, const Eigen::Matrix3d& orientation)\n        {\n            Eigen::AngleAxisd aa(orientation);\n\n            Eigen::Vector3d omega = aa.angle() * aa.axis();\n\n            Eigen::Matrix3d omega_skew;\n            omega_skew << 0, -omega(2), omega(1),\n                omega(2), 0, -omega(0),\n                -omega(1), omega(0), 0;\n\n            double theta = omega.norm(), A = std::sin(theta) / theta, B = (1 - std::cos(theta)) / std::pow(theta, 2);\n\n            return (Eigen::Matrix<double, 6, 1>() << (Eigen::Matrix3d::Identity() - 0.5 * omega_skew + (1 - 0.5 * A / B) / std::pow(theta, 2) * omega_skew * omega_skew) * position, omega).finished();\n        }\n\n        // Check here if this can be improved\n        Eigen::MatrixXd pseudoInverse(const Eigen::MatrixXd& M)\n        {\n            double epsilon = std::numeric_limits<double>::epsilon();\n\n            Eigen::JacobiSVD<Eigen::MatrixXd> svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n            Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType sing_vals = svd.singularValues();\n\n            double tolerance = epsilon * std::max(M.cols(), M.rows()) * sing_vals.array().abs()(0);\n            Eigen::MatrixXd S = Eigen::MatrixXd::Zero(M.rows(), M.cols());\n\n            for (size_t i = 0; i < sing_vals.size(); i++)\n                if (std::fabs(sing_vals(i)) > tolerance)\n                    S(i, i) = 1.0 / sing_vals(i);\n\n            return svd.matrixV() * S.transpose() * svd.matrixU().adjoint();\n        }\n    } // namespace tools\n\n} // namespace beautiful_bullet\n\n#endif // BEAUTIFUL_BULLET_TOOLS_MATH_HPP", "meta": {"hexsha": "57f89529936b2283cb26e6213d982c471bd2b4b4", "size": 3025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/beautiful_bullet/tools/math.hpp", "max_stars_repo_name": "nash169/beautiful-bullet", "max_stars_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_stars_repo_licenses": ["MIT"], "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/beautiful_bullet/tools/math.hpp", "max_issues_repo_name": "nash169/beautiful-bullet", "max_issues_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_issues_repo_licenses": ["MIT"], "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/beautiful_bullet/tools/math.hpp", "max_forks_repo_name": "nash169/beautiful-bullet", "max_forks_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_forks_repo_licenses": ["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.2142857143, "max_line_length": 199, "alphanum_fraction": 0.6538842975, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6745753488547017}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pblas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n#include \"../../rmse.hpp\"\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating blockcyclic matrix from file\n    auto bm1 = make_blockcyclic_matrix_load<float> (\"./sample_4x4\");\n    auto bm2 = bm1;\n  \n    // slicing rows\n    auto row1 = make_row_vector<float> (bm1,0);\n    auto row2 = make_row_vector<float> (bm1,1);\n    auto row3 = make_row_vector<float> (bm1,2);\n    auto row4 = make_row_vector<float> (bm1,3);\n\n    // row3-of-bm1 = 5*bm2*row1-of-bm1\n    gemv<float>(bm2,row1,row3,'N',5.0);\n\n    // row4-of-bm1 = 2*trans(bm2)*row2-of-bm1 + 3*row4-of-bm1\n    gemv<float>(bm2,row2,row4,'T',2.0,3.0);\n    bm1.save(\"./out\");\n\n    double tol = 0.01;\n    auto out = make_rowmajor_matrix_local_load<float> (\"./out\");\n    auto ref = make_rowmajor_matrix_local_load<float> (\"./ref_4x4\");\n    BOOST_CHECK (calc_rms_err<float> (out.val, ref.val) < tol);\n    system(\"rm -f ./out\");\n}\n\n", "meta": {"hexsha": "0500b98556d1fc03ae041982025397642b7973a7", "size": 1148, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test8.7-2/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test8.7-2/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test8.7-2/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 28.0, "max_line_length": 68, "alphanum_fraction": 0.6611498258, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6745753387660446}}
{"text": "#define ARMA_DONT_USE_WRAPPER\n#include <armadillo>\n#include <iostream>\n#include <string>\n#include <regex>\n#include <math.h>\n\nusing namespace std;\n\ndouble check_input();\nstring check_file();\n\n\nint main(int argc, const char **argv) {\n    int m, n, c, e;\n    double aux;\n    string a, b, w, bias;\n    arma::mat A;\n    arma::mat B;\n    arma::mat W, b1;\n    cout<<\"Numero de entradas, \";\n    n = (int)check_input();\n    cout<<\"Numero de salidas, \";\n    m = (int)check_input();\n    cout<<\"Numero de categorias, \";\n    c = (int)check_input();\n    cout<<\"Numero de ejemplos por categoria, \";\n    e = (int)check_input();\n\n\n    A.set_size(n*e + m, c);\n    W.set_size(m,n);\n    b1.set_size(m, 1);\n    for(int j=0; j<c; j++)\n    {\n      cout<<\"Categoria: \"<<j+1<<endl;\n      for(int i=0; i < n*e + m; i++)\n      {\n        if(i<=n*e)\n        {\n          cout<<\"Ejemplo \"<<(int)(floor(i/n + 1))<<\"(\"<<i+1<<\"): \";\n          aux = check_input();\n          A(i,j)= aux;\n        }\n        else\n        {\n          cout<<\"Target(\" <<j+1<<\"): \";\n          aux = check_input();\n          A(i,j)= aux;\n        }\n      }\n    }\n\n    cout<<\"Matriz de pesos\"<<endl;\n    for(int i=0; i<m; i++){\n      for(int j=0; j<n; j++)\n      {\n        cout<<\"W(\"<<i+1<<\",\"<<j+1<<\"), \";\n        aux = check_input();\n        W(i,j)=aux;\n      }\n    }\n\n    cout<<\"Bias\"<<endl;\n    for(int i=0; i<m; i++)\n    {\n      cout<<\"b(\"<<i+1<<\",0), \";\n      aux = check_input();\n      b1(i,0)=aux;\n    }\n   \n    cout << \"A:\\n\" << A <<\"\\n\";\n\n    B << n << m << c << e << arma::endr; \n    cout << \"B:\\n\" << B << \"\\n\";\n\n    cout << \"W:\\n\" << W << \"\\n\";\n\n    cout << \"b:\\n\" << b1 << \"\\n\";\n    \n\n    a =  check_file();\n    b = check_file();\n    w = check_file();\n    bias = check_file();\n    // Save matrices A and B:\n    A.save(a , arma::arma_ascii);\n    B.save(b , arma::arma_ascii);\n    W.save(w, arma::arma_ascii);\n    b1.save(bias, arma::arma_ascii);\n\n    return 0;\n}\n\ndouble check_input(){\n  string str;\n  regex regex_pattern(\"-?[0-9]+\\\\.?([0-9]+)?\");\n  do\n  {\n    cout << \"Valor num\u00e9rico: \";\n    cin >> str;\n    cout << endl;\n  }while(!regex_match(str,regex_pattern));\n\n  return stod(str);\n}\n\nstring check_file(){\n  string str;\n  regex regex_pattern(\"([a-zA-Z]|[0-9]|\\\\_)*\\\\.txt\");\n  do{\n    cout << \"Nombre de archivo .txt: \";\n    cin >> str;\n    cout << endl;\n  }while(!regex_match(str,regex_pattern));\n  return str;\n}\n", "meta": {"hexsha": "2d7b767ba1bb7609e59e03b0f609320b81c43c1a", "size": 2371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "txtGen/generator.cpp", "max_stars_repo_name": "leguiart/Perceptron", "max_stars_repo_head_hexsha": "bb7db2309268968577497d76d59d220fc9e1f027", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "txtGen/generator.cpp", "max_issues_repo_name": "leguiart/Perceptron", "max_issues_repo_head_hexsha": "bb7db2309268968577497d76d59d220fc9e1f027", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "txtGen/generator.cpp", "max_forks_repo_name": "leguiart/Perceptron", "max_forks_repo_head_hexsha": "bb7db2309268968577497d76d59d220fc9e1f027", "max_forks_repo_licenses": ["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.093220339, "max_line_length": 67, "alphanum_fraction": 0.4753268663, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742806, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6744267190946241}}
{"text": "// spectra_example_symm.cpp\r\n//\r\n// extracted from spectra/README.md:\r\n//\r\n// \"Below is an example that demonstrates the use of the eigen solver\r\n// for symmetric matrices.\"\r\n//\r\n// g++ -O2 -I${EIGEN3_DIR}/include/eigen3 -I${SPECTRA_DIR}/include spectra_example_symm.cpp -o spectra_example_symm\r\n\r\n#include <Eigen/Core>\r\n#include <SymEigsSolver.h>  // Also includes <MatOp/DenseSymMatProd.h>\r\n#include <iostream>\r\n\r\nusing namespace Spectra;\r\n\r\nint main()\r\n{\r\n    // We are going to calculate the eigenvalues of M\r\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 10);\r\n    Eigen::MatrixXd M = A + A.transpose();\r\n\r\n    // Construct matrix operation object using the wrapper class DenseGenMatProd\r\n    DenseSymMatProd<double> op(M);\r\n\r\n    // Construct eigen solver object, requesting the largest three eigenvalues\r\n    SymEigsSolver< double, LARGEST_ALGE, DenseSymMatProd<double> > eigs(&op, 3, 6);\r\n\r\n    // Initialize and compute\r\n    eigs.init();\r\n    int nconv = eigs.compute();\r\n\r\n    // Retrieve results\r\n    Eigen::VectorXd evalues;\r\n    if(eigs.info() == SUCCESSFUL)\r\n        evalues = eigs.eigenvalues();\r\n\r\n    std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "e748b6aab7f14b115f1ddc84bcc3cd18ddf870d5", "size": 1206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/linear_algebra/spectra_example_symm.cpp", "max_stars_repo_name": "nd-nuclear-theory/spncci", "max_stars_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-17T22:58:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T22:58:31.000Z", "max_issues_repo_path": "programs/linear_algebra/spectra_example_symm.cpp", "max_issues_repo_name": "nd-nuclear-theory/spncci", "max_issues_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-16T03:16:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-16T19:46:18.000Z", "max_forks_repo_path": "programs/linear_algebra/spectra_example_symm.cpp", "max_forks_repo_name": "nd-nuclear-theory/spncci", "max_forks_repo_head_hexsha": "18b30e63ca62bfeea9bfadaf2bad3bfb166ce3e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T17:26:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T17:04:07.000Z", "avg_line_length": 29.4146341463, "max_line_length": 116, "alphanum_fraction": 0.6699834163, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6744267175358222}}
{"text": "#pragma once\n#include <cstdint>\n#include <NTL/ZZ.h>\n#include <NTL/RR.h>\n#include <NTL/matrix.h>\n\n/* binomials are precomputed up to MAX_N-choose-MAX_T */\n#define MAX_N 2000\n#define MAX_T 300\n\n#define LOW_K_MAX_N 10000\n#define LOW_K_MAX_T 10\n\nconst NTL::RR nat_log_2 = NTL::log(NTL::RR(2));\n\nstatic inline NTL::RR log2_RR(NTL::RR v){\n    return NTL::log(v)/nat_log_2;\n}\n\nNTL::Mat<NTL::ZZ> binomial_table; /*contains all binomials up to MAX_N-choose-MAX_T */\nNTL::Mat<NTL::ZZ> low_k_binomial_table; /*contains all binomials up to LOW_K_MAX_N-choose-LOW_K_MAX_T */\n\nNTL::RR pi;\n/*NOTE: NTL allows to access matrices as 1- based with Matlab notation */\nvoid InitBinomials(){\n    std::cerr << \"Precomputing n-choose-t up to n: \" << MAX_N << \n                                              \" t: \" << MAX_T << std::endl;\n    binomial_table.SetDims(MAX_N+1,MAX_T+1);\n    binomial_table[0][0] = NTL::ZZ(1);\n    for (unsigned i = 1 ; i <= MAX_N; i++){\n        binomial_table[i][0] = NTL::ZZ(1);\n        binomial_table[i][1] = NTL::ZZ(i);\n        for(unsigned j=2 ; (j <= i) && (j <= MAX_T) ; j++){\n            binomial_table[i][j] = binomial_table[i][j-1] * NTL::ZZ(i-j+1) / NTL::ZZ(j);\n        }\n    }\n    std::cerr << \"Precomputing low n-choose-t up to n: \" << LOW_K_MAX_N << \n                                                       \" t: \" << LOW_K_MAX_T << std::endl;\n    low_k_binomial_table.SetDims(LOW_K_MAX_N+1,LOW_K_MAX_T+1);\n    low_k_binomial_table[0][0] = NTL::ZZ(1);\n    for (unsigned i = 0 ; i <= LOW_K_MAX_N; i++){\n        low_k_binomial_table[i][0] = NTL::ZZ(1);\n        low_k_binomial_table[i][1] = NTL::ZZ(i);\n        for(unsigned j=2 ; (j <= i) && (j <= LOW_K_MAX_T) ; j++){\n            low_k_binomial_table[i][j] = low_k_binomial_table[i][j-1] * NTL::ZZ(i-j+1) / NTL::ZZ(j);\n        }\n    }\n    std::cerr << \"done\" << std::endl;\n    pi = NTL::ComputePi_RR();\n}\n\n\n\nNTL::RR lnFactorial(NTL::RR n){\n    /* log of Stirling series approximated to the fourth term \n     * n log(n) - n + 1/2 log(2 \\pi n) + log(- 139/(51840 n^3) +\n     * + 1/(288 n^2) + 1/(12 n) + 1) */\n    return n * NTL::log(n) - n + 0.5 * NTL::log(2*pi*n) + \n           NTL::log( - NTL::RR(139)/(n*n*n * 51840) + \n           NTL::RR(1)/(n*n*288) + \n           NTL::RR(1)/(n*12) + \n           1);\n}\n\nNTL::RR lnBinom(NTL::RR n, NTL::RR k){\n    if ( (k == NTL::RR(0) ) || (k == n) ) {\n        return NTL::RR(0);\n    }\n    return lnFactorial(n) - (lnFactorial(k) + lnFactorial(n-k) );\n}\n\n\nNTL::ZZ binomial_wrapper(long n, long k){\n    if(k>n) return NTL::ZZ(0);\n    /* employ memoized if available */\n    if ((n <= MAX_N) && (k < MAX_T)){\n        return binomial_table[n][k];\n    }\n    if ((n <= LOW_K_MAX_N) && (k < LOW_K_MAX_T)){\n        return low_k_binomial_table[n][k];\n    }\n    \n    /* shortcut computation for fast cases (k < 10) where \n     * Stirling may not provide good approximations */\n    if (k < 10) {\n        NTL::ZZ result = NTL::ZZ(1);\n        for(int i = 1 ; i <= k; i++){\n            result = (result * (n+1-i))/i;\n        }\n        return result;\n    }\n    /*Fall back to Stirling*/\n    return NTL::conv<NTL::ZZ>( NTL::exp( lnBinom(NTL::RR(n),NTL::RR(k)) ));\n}\n", "meta": {"hexsha": "35c0378859875931696543b7f7196ca5edd13477", "size": 3150, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "binomials.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": "binomials.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": "binomials.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": 33.1578947368, "max_line_length": 104, "alphanum_fraction": 0.5412698413, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6743726769686366}}
{"text": "/**\n * @file\n * @author lkoppel\n * Defines an Eigen expression for the \"cross-product\" or \"hat\" matrix of a 3-vector\n */\n\n#ifndef WAVE_GEOMETRY_CROSSMATRIX_HPP\n#define WAVE_GEOMETRY_CROSSMATRIX_HPP\n\n#include <Eigen/Geometry>\n\nnamespace wave {\n\n/**\n * An Eigen expression for the skew-symmetric \"cross-product\" or \"hat\" matrix of a\n * 3-vector. This matrix applies the cross product:\n *\n * @f[ a \\times b = \\text{CrossMatrix}(a) b @f]\n *\n * In different works, `CrossMatrix(a)` might be written as @f$ a^{\\times} @f$ or\n * @f$ \\hat{a} @f$ .\n *\n * @tparam VecType the type of the vector expression\n */\n// The implementation of an Eigen expression here was guided by\n// https://eigen.tuxfamily.org/dox/TopicNewExpressionType.html\ntemplate <class VecType>\nclass CrossMatrix : public Eigen::Matrix<typename VecType::Scalar, 3, 3> {\n public:\n    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VecType, 3);\n    using MatrixType = Eigen::Matrix<typename VecType::Scalar, 3, 3>;\n    using Nested = typename Eigen::internal::ref_selector<CrossMatrix>::type;\n    using VecTypeNested = typename Eigen::internal::ref_selector<VecType>::type;\n\n    using Scalar = typename VecType::Scalar;\n\n    EIGEN_STRONG_INLINE\n    explicit CrossMatrix(const VecType &vec)\n        : MatrixType{(MatrixType{} << Scalar{0},\n                      -vec(2),\n                      vec(1),\n                      vec(2),\n                      Scalar{0},\n                      -vec(0),\n                      -vec(1),\n                      vec(0),\n                      Scalar{0})\n                       .finished()},\n          vec{vec} {}\n\n    using NegativeReturnType = CrossMatrix<typename VecType::NegativeReturnType>;\n\n    EIGEN_DEVICE_FUNC\n    inline NegativeReturnType operator-() const {\n        return NegativeReturnType{-this->vec};\n    }\n\n\n    VecTypeNested vec;\n};\n\n\n/** Produce a cross matrix*/\ntemplate <class VecType>\ninline auto crossMatrix(const Eigen::MatrixBase<VecType> &vec) -> CrossMatrix<VecType> {\n    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VecType, 3);\n    return CrossMatrix<VecType>(vec.derived());\n}\n\ntemplate <class VecType>\ninline auto crossMatrix(const Eigen::MatrixBase<VecType> &&vec) -> CrossMatrix<VecType> {\n    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VecType, 3);\n    return CrossMatrix<VecType>(std::move(vec.derived()));\n}\n\n// Forward declaration\ntemplate <typename Scalar, int N>\nclass IdentityMatrix;\n\n}  // namespace wave\n\nnamespace Eigen {\n\n/** Left-multiply a fixed-size 3-vector by a cross-matrix\n *\n * Performs a cross product\n */\ntemplate <\n  typename VecType,\n  typename OtherType,\n  std::enable_if_t<OtherType::RowsAtCompileTime == 3 && OtherType::ColsAtCompileTime == 1,\n                   int> = 0>\nEIGEN_DEVICE_FUNC inline auto operator*(const wave::CrossMatrix<VecType> &crossMat,\n                                        const Eigen::MatrixBase<OtherType> &rhs) {\n    return crossMat.vec.cross(rhs);\n}\n\n/** Right-multiply a fixed-size 3-vector by a cross-matrix\n *\n * Performs a cross product\n */\ntemplate <\n  typename VecType,\n  typename OtherType,\n  std::enable_if_t<OtherType::ColsAtCompileTime == 3 && OtherType::RowsAtCompileTime == 1,\n                   int> = 0>\nEIGEN_DEVICE_FUNC inline auto operator*(const Eigen::MatrixBase<OtherType> &lhs,\n                                        const wave::CrossMatrix<VecType> &crossMat) {\n    return lhs.cross(crossMat.vec);\n}\n\n/**\n * Left-multiply a 3*N matrix by a cross-matrix\n *\n * This operation is equivalent to taking the cross product of each row in the l.h.s.\n * matrix with the negative original vector\n *\n * Only enabled for static matrices\n */\ntemplate <\n  typename VecType,\n  typename OtherType,\n  std::enable_if_t<OtherType::RowsAtCompileTime == 3 && OtherType::ColsAtCompileTime != 1,\n                   int> = 0>\nEIGEN_DEVICE_FUNC inline auto operator*(const wave::CrossMatrix<VecType> &crossMat,\n                                        const Eigen::MatrixBase<OtherType> &rhs) {\n    return rhs.colwise().cross(-crossMat.vec);\n}\n\n/**\n * Left-multiply a 3*N matrix by a cross-matrix of a negative\n *\n * This operation is equivalent to taking the cross product of each row in the l.h.s.\n * matrix with the original vector\n *\n * This special case cuts down one instruction(?), but more importantly simplifies the\n * expression graph output.\n */\ntemplate <\n  typename VecType,\n  typename OtherType,\n  std::enable_if_t<OtherType::RowsAtCompileTime == 3 && OtherType::ColsAtCompileTime != 1,\n                   int> = 0>\nEIGEN_DEVICE_FUNC inline auto operator*(\n  const wave::CrossMatrix<Eigen::CwiseUnaryOp<\n    Eigen::internal::scalar_opposite_op<typename internal::traits<VecType>::Scalar>,\n    VecType>> &crossMat,\n  const Eigen::MatrixBase<OtherType> &rhs) {\n    return rhs.derived().colwise().cross(crossMat.vec.nestedExpression());\n}\n\n\n/**\n * Right-multiply an N*3 matrix by a cross-matrix\n *\n * This operation is equivalent to taking the cross product of the original vector with\n * each column in the r.h.s. matrix, and negating it since a x b = -(b x a).\n *\n * Only enabled for static matrices\n */\ntemplate <\n  typename OtherType,\n  typename VecType,\n  std::enable_if_t<OtherType::ColsAtCompileTime == 3 && OtherType::RowsAtCompileTime != 1,\n                   int> = 0>\nEIGEN_DEVICE_FUNC inline auto operator*(const Eigen::MatrixBase<OtherType> &lhs,\n                                        const wave::CrossMatrix<VecType> &crossMat) {\n    return lhs.rowwise().cross(crossMat.vec);\n}\n\n/**\n * Multiply two cross-matrices\n * (needed to disambiguate)\n */\ntemplate <typename Lhs, typename Rhs>\nEIGEN_DEVICE_FUNC inline auto operator*(const wave::CrossMatrix<Lhs> &lhs,\n                                        const wave::CrossMatrix<Rhs> &rhs) {\n    return lhs.rowwise().cross(rhs.vec);\n}\n\n/**\n * Multiply an Identity expression by a CrossMatrix expression\n * (Provided to break tie between the other specializations)\n */\n// @todo generalize - this won't scale well if we add more expressions with operator*\n// @todo Check scalar mixing?\ntemplate <typename VecType, typename Scalar>\nEIGEN_DEVICE_FUNC inline const wave::CrossMatrix<VecType> &operator*(\n  const wave::IdentityMatrix<Scalar, 3> &, const wave::CrossMatrix<VecType> &cross) {\n    return cross;\n}\n\n/**\n * Multiply an CrossMatrix expression by an Identity expression\n * (Provided to break tie between the other specializations)\n */\n// @todo generalize - this won't scale well if we add more expressions with operator*\n// @todo Check scalar mixing?\ntemplate <typename VecType, typename Scalar>\nEIGEN_DEVICE_FUNC inline const wave::CrossMatrix<VecType> &operator*(\n  const wave::CrossMatrix<VecType> &cross, const wave::IdentityMatrix<Scalar, 3> &) {\n    return cross;\n}\n\nnamespace internal {\n\n// Static attributes of our CrossMatrix expression\n// See https://eigen.tuxfamily.org/dox/TopicNewExpressionType.html\ntemplate <class VecType>\nstruct traits<::wave::CrossMatrix<VecType>> {\n    using StorageKind = Eigen::Dense;\n    using XprKind = Eigen::MatrixXpr;\n    using StorageIndex = typename VecType::StorageIndex;\n    using Scalar = typename VecType::Scalar;\n    enum {\n        Flags = Eigen::AutoAlign,\n        RowsAtCompileTime = 3,\n        ColsAtCompileTime = 3,\n        MaxRowsAtCompileTime = 3,\n        MaxColsAtCompileTime = 3\n    };\n};\n\n\n}  // namespace internal\n}  // namespace Eigen\n\n#endif  // WAVE_GEOMETRY_CROSSMATRIX_HPP\n", "meta": {"hexsha": "563a1a81fed0e80e6e7f96e352a04e7c33cd8142", "size": 7373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/wave/geometry/src/util/math/CrossMatrix.hpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "include/wave/geometry/src/util/math/CrossMatrix.hpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "include/wave/geometry/src/util/math/CrossMatrix.hpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 32.1965065502, "max_line_length": 90, "alphanum_fraction": 0.6762511868, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6743726671172624}}
{"text": "#ifndef BUSV_POINTS\n#define BUSV_POINTS\n\n#include <boost/array.hpp>\n#include <cmath>\n\nnamespace busv{\n\ntemplate <typename T>\ninline T sqr(T a){\n\treturn a*a;\n}\n\ntemplate <typename T>\nclass Point{\n\tpublic:\n\t\tPoint(const T* data){\n\t\t\ta[0] = data[0];\n\t\t\ta[1] = data[1];\n\t\t\ta[2] = data[2];\n\t\t}\n\t\tT distance(const Point<T>& other) const{\n\t\t\treturn std::sqrt(\n\t\t\t\tsqr(this->a[0] - other.a[0]) +\n\t\t\t\tsqr(this->a[1] - other.a[1]) +\n\t\t\t\tsqr(this->a[2] - other.a[2])\n\t\t\t);\n\t\t}\n\t\tT sqrDistance(const Point<T>& other) const{\n\t\t\treturn\n\t\t\t\tsqr(this->a[0] - other.a[0]) +\n\t\t\t\tsqr(this->a[1] - other.a[1]) +\n\t\t\t\tsqr(this->a[2] - other.a[2])\n\t\t}\n\t\tT capHeight(const Point<T>& other) const{\n\t\t}\n\tprivate:\n\t\tT c[3];\n\t\tT r;\n};\n\n}\n\n#endif\n\n", "meta": {"hexsha": "4e3d5062677e4ed5e8a0f3268eeb85c70c93f20d", "size": 719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/inex_unfinished/points.hpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "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/alpha_shapes/inex_unfinished/points.hpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "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/alpha_shapes/inex_unfinished/points.hpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["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.6304347826, "max_line_length": 45, "alphanum_fraction": 0.5716272601, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735663, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6743726493260527}}
{"text": "\ufeff/*\nBKSVD implemented by C++ based on https://github.com/cpmusco/bksvd\nAuthor: ItakEjgo@SUSTech\n*/\n\n#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <random>\n#include <ctime>\n\n#define EIGEN_USE_MKL_ALL\n\nusing namespace std;\nusing namespace Eigen;\n\n\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> MatrixXd_row;\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> MatrixXd_col;\n\nstruct bksvd_output {\n\tMatrixXd U;\t\t// an orthogonal matrix whose columns are approximate top k left singular vectors for A\n\tMatrixXd S;\t\t// a diagonal matrix whose entries are A's approximate top k singular values\n\tMatrixXd V;\t\t// an orthogonal matrix whose columns are approximate top k right singular vectors for A\n};\n\nstatic default_random_engine e(233666);\nstatic normal_distribution<double> m_n(0, 1);\n\n//\tfunction bksvd\n\nbksvd_output bksvd(MatrixXd &A, int k = 6, int iter = 3, int bsize = 6, bool center = false) {\n\tbksvd_output result;\n\t\n\tk = min(k, (int)min(A.rows(), A.cols()));\n\tbsize = k;\n\n\tif (k < 1 || iter < 1 || bsize < k) {\n\t\tcerr << \"bksvd: BadInput, Oner or more inputs outside required range\" << endl;\n\t}\n\n\t//\tCalculate row mean if rows should be centered.\n\tMatrixXd u = MatrixXd::Zero(1, A.cols());\n\tif (center) {\n\t\tfor (int i = 0; i < A.cols(); i++) {\n\t\t\tu(0, i) = A.col(i).mean();\n\t\t}\n\t}\n\tMatrixXd l = MatrixXd::Ones(A.rows(), 1);\n\n\t//\tWe want to iterate on the smaller dimension of A.\n\tint n, ind;\n\tif (A.rows() <= A.cols()) {\n\t\tn = A.rows();\n\t\tind = 1;\n\t}\n\telse {\n\t\tn = A.cols();\n\t\tind = 2;\n\t}\n\tbool tpose = false;\n\tif (ind == 1) {\n\t\ttpose = true;\n\t\tl = u.transpose(); u.setOnes(1, A.rows());\n\t\tA.transposeInPlace();\n\t}\n\n\t//\tAllocate space for Krylov subspace.\n\tMatrixXd K = MatrixXd::Zero(A.cols(), bsize * iter);\n\t//\tRandom block initialization.\n\tMatrixXd block = MatrixXd::Zero(A.cols(), bsize).unaryExpr([](double dummy) {return m_n(e); });\n\n\tHouseholderQR<MatrixXd> qr;\n\tqr.compute(block);\n\tblock.noalias() = qr.householderQ() * MatrixXd::Identity(A.cols(), bsize);\n\n\t//\tPreallocate space for temporary products.\n\tMatrixXd T = MatrixXd::Zero(A.cols(), bsize);\n\n\t//\tConstruct and orthonormalize Krlov Subspace.\n\t//\tOrthogonalize at each step using economy size QR decomposition\n\tfor (int i = 1; i <= iter; i++) {\n\t\tT.noalias() = A * block;\n\t\tT.noalias() -= l * (u * block);\n\t\t//T = A * block - l * (u * block);\n\t\tblock.noalias() = A.transpose() * T;\n\t\tblock.noalias() -= u.transpose() * (l.transpose() * T);\n\t\t//block = A.transpose() * T - u.transpose() * (l.transpose() * T);\n\t\tHouseholderQR<MatrixXd> tmp_qr;\n\t\ttmp_qr.compute(block);\n\t\tblock.noalias() = tmp_qr.householderQ() * MatrixXd::Identity(block.rows(), block.cols());;\n\t\tK.middleCols((i - 1)*bsize, bsize) = block;\n\t}\n\n\t//\tRayleigh-Ritz postprocessing with economy size dense SVD.\n\tHouseholderQR<MatrixXd> tmp_qr;\n\t\n\ttmp_qr.compute(K);\n\tMatrixXd Q = tmp_qr.householderQ() * MatrixXd::Identity(K.rows(), K.cols());\n\n\tT.noalias() = A * Q;\n\tT.noalias() -= l * (u * Q);\n\t//T = A * Q - l * (u * Q);\n\t\n\tBDCSVD<MatrixXd> svd(T, ComputeThinU | ComputeThinV);    //\tFor large scale Matrix\n\t//JacobiSVD<MatrixXd>svd(T, ComputeThinU | ComputeThinV); // For small scale Matrix\n\t\t\n\tMatrixXd Ut = svd.matrixU(), Vt = svd.matrixV();\n\tMatrixXd St = svd.singularValues().asDiagonal();\n\tresult.S = St.block(0, 0, k, k);\n\tif (!tpose) {\n\t\tresult.U = Ut.leftCols(k);\n\t\tresult.V = Q * Vt.leftCols(k);\n\t}\n\telse {\n\t\tresult.V = Ut.leftCols(k);\n\t\tresult.U = Q * Vt.leftCols(k);\n\t}\n\treturn result;\n}\n\n//\tusing reference\n\nvoid bksvd(bksvd_output &result, MatrixXd &A, int k = 6, int iter = 3, int bsize = 6, bool center = false) {\n\n\tk = min(k, (int)min(A.rows(), A.cols()));\n\tbsize = k;\n\n\tif (k < 1 || iter < 1 || bsize < k) {\n\t\tcerr << \"bksvd: BadInput, Oner or more inputs outside required range\" << endl;\n\t}\n\n\t//\tCalculate row mean if rows should be centered.\n\tMatrixXd u = MatrixXd::Zero(1, A.cols());\n\tif (center) {\n\t\tfor (int i = 0; i < A.cols(); i++) {\n\t\t\tu(0, i) = A.col(i).mean();\n\t\t}\n\t}\n\tMatrixXd l = MatrixXd::Ones(A.rows(), 1);\n\n\t//\tWe want to iterate on the smaller dimension of A.\n\tint n, ind;\n\tif (A.rows() <= A.cols()) {\n\t\tn = A.rows();\n\t\tind = 1;\n\t}\n\telse {\n\t\tn = A.cols();\n\t\tind = 2;\n\t}\n\tbool tpose = false;\n\tif (ind == 1) {\n\t\ttpose = true;\n\t\tl = u.transpose(); u.setOnes(1, A.rows());\n\t\tA.transposeInPlace();\n\t}\n\n\t//\tAllocate space for Krylov subspace.\n\tMatrixXd K = MatrixXd::Zero(A.cols(), bsize * iter);\n\t//\tRandom block initialization.\n\tMatrixXd block = MatrixXd::Zero(A.cols(), bsize).unaryExpr([](double dummy) {return m_n(e); });\n\n\tHouseholderQR<MatrixXd> qr;\n\tqr.compute(block);\n\t/*block.noalias() = qr.householderQ() * MatrixXd::Identity(A.cols(), bsize);*/\n\tblock = qr.householderQ() * MatrixXd::Identity(A.cols(), bsize);\n\n\t//\tPreallocate space for temporary products.\n\tMatrixXd T = MatrixXd::Zero(A.cols(), bsize);\n\n\t//\tConstruct and orthonormalize Krlov Subspace.\n\t//\tOrthogonalize at each step using economy size QR decomposition\n\tfor (int i = 1; i <= iter; i++) {\n\t\t/*T.noalias() = A * block;\n\t\tT.noalias() -= l * (u * block);*/\n\t\tT = A * block - l * (u * block);\n\t\t/*block.noalias() = A.transpose() * T;\n\t\tblock.noalias() -= u.transpose() * (l.transpose() * T);*/\n\t\tblock = A.transpose() * T - u.transpose() * (l.transpose() * T);\n\t\tHouseholderQR<MatrixXd> tmp_qr;\n\t\ttmp_qr.compute(block);\n\t\t/*block.noalias() = tmp_qr.householderQ() * MatrixXd::Identity(block.rows(), block.cols());*/\n\t\tblock = tmp_qr.householderQ() * MatrixXd::Identity(block.rows(), block.cols());\n\t\tK.middleCols((i - 1)*bsize, bsize) = block;\n\t}\n\n\t//\tRayleigh-Ritz postprocessing with economy size dense SVD.\n\tHouseholderQR<MatrixXd> tmp_qr;\n\n\ttmp_qr.compute(K);\n\tMatrixXd Q = tmp_qr.householderQ() * MatrixXd::Identity(K.rows(), K.cols());\n\n\t/*T.noalias() = A * Q;\n\tT.noalias() -= l * (u * Q);*/\n\tT = A * Q - l * (u * Q);\n\n\tBDCSVD<MatrixXd> svd(T, ComputeThinU | ComputeThinV);    //\tFor large scale Matrix\n\t//JacobiSVD<MatrixXd>svd(T, ComputeThinU | ComputeThinV); // For small scale Matrix\n\n\tMatrixXd Ut = svd.matrixU(), Vt = svd.matrixV();\n\tMatrixXd St = svd.singularValues().asDiagonal();\n\tresult.S = St.block(0, 0, k, k);\n\tif (!tpose) {\n\t\tresult.U = Ut.leftCols(k);\n\t\tresult.V = Q * Vt.leftCols(k);\n\t}\n\telse {\n\t\tresult.V = Ut.leftCols(k);\n\t\tresult.U = Q * Vt.leftCols(k);\n\t}\n}\n\n//\tfunction sisvd\n\nbksvd_output sisvd(MatrixXd A, int k = 6, int iter = 3, int bsize = 6, bool center = false) {\n\tbksvd_output result;\n\n\tstatic default_random_engine e((unsigned int)time(0));\n\tstatic normal_distribution<double> m_n(0, 1);\n\t\n\tk = min(k, (int)min(A.rows(), A.cols()));\n\tbsize = k;\n\tif (k < 1 || iter < 1 || bsize < k) {\n\t\tcerr << \"sisvd:BadInput, one or more inputs outside required range\" << endl;\n\t}\n\n\t//\tCalculate row mean if rows should be centered.\n\tMatrixXd u = MatrixXd::Zero(1, A.cols());\n\tif (center) {\n\t\tfor (int i = 0; i < A.cols(); i++) {\n\t\t\tu(0, i) = A.col(i).mean();\n\t\t}\n\t}\n\tMatrixXd l = MatrixXd::Ones(A.rows(), 1);\n\n\t//\tWe want to iterate on the smaller dimension of A.\n\tint n, ind;\n\tif (A.rows() <= A.cols()) {\n\t\tn = A.rows();\n\t\tind = 1;\n\t}\n\telse {\n\t\tn = A.cols();\n\t\tind = 2;\n\t}\n\tbool tpose = false;\n\tif (ind == 1) {\n\t\ttpose = true;\n\t\tl = u.transpose(); u.setOnes(1, A.rows());\n\t\tA.transposeInPlace();\n\t}\n\n\t//\tRandom block initialization.\n\tMatrixXd block = MatrixXd::Zero(A.cols(), bsize).unaryExpr([](double dummy) {return m_n(e); });\n\n\tHouseholderQR<MatrixXd> qr;\n\tqr.compute(block);\n\tblock = qr.householderQ() * MatrixXd::Identity(A.cols(), bsize);\n\n\t//\tPreallocate space for temporary products.\n\tMatrixXd T = MatrixXd::Zero(A.cols(), bsize);\n\n\t//\tRun power iteration, orthogonalizing at each step using economy size QR.\n\tfor (int i = 1; i <= iter; i++) {\n\t\tT = A * block - l * (u * block);\n\t\tblock = A.transpose() * T - u.transpose() * (l.transpose() * T);\n\t\tHouseholderQR<MatrixXd> tmp_qr;\n\t\ttmp_qr.compute(block);\n\t\tblock = tmp_qr.householderQ() * MatrixXd::Identity(block.rows(), block.cols());\n\t}\n\n\t//\tRayleigh-Ritz postprocessing with economy size dense SVD.\n\tT = A * block - l * (u * block);\n\t//JacobiSVD<MatrixXd>svd(T, ComputeFullU | ComputeFullV);\n\tBDCSVD<MatrixXd> svd(T, ComputeThinU | ComputeThinV);\n\tMatrixXd Ut = svd.matrixU(), Vt = svd.matrixV();\n\tMatrixXd St = svd.singularValues().asDiagonal();\n\tresult.S = St.block(0, 0, k, k);\n\tif (!tpose) {\n\t\tresult.U = Ut.leftCols(k);\n\t\tresult.V = block * Vt.leftCols(k);\n\t}\n\telse {\n\t\tresult.V = Ut.leftCols(k);\n\t\tresult.U = block * Vt.leftCols(k);\n\t}\n\treturn result;\n}\n\nint main(){\n\t//ofstream fout;\n\t//fout.open(\"Matrix_A.txt\");\n\t//MatrixXd A = MatrixXd::Zero(10000, 161).unaryExpr([](double dummy) {return m_n(e); });\n\t////MatrixXd_row A = MatrixXd::Zero(1000, 1000).unaryExpr([](double dummy) {return m_n(e); });\n\t//fout << A << endl;\n\n\tMatrixXd A = MatrixXd::Zero(10000, 161);\n\tifstream fin; fin.open(\"MatrixA.txt\");\n\tdouble val;\n\tfor (int i = 0; i < 10000; i++) {\n\t\tfor (int j = 0; j < 161; j++) {\n\t\t\tfin >> val;\n\t\t\tA(i, j) = val;\n\t\t}\n\t}\n\t\n\tMatrixXd B = A;\n\tbksvd_output result1, result2;\n\tclock_t start, end;\n\tstart = clock();\n\t//result1 = bksvd(A,10);\n\tend = clock();\n\tprintf(\"Time used = :%.5f second(s)\\n\", (double)(end - start) / CLOCKS_PER_SEC);\n\n\tstart = clock();\n\tbksvd(result2, A, 10);\n\tend = clock();\n\tprintf(\"Time used = :%.5f second(s)\\n\", (double)(end - start) / CLOCKS_PER_SEC);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "cd1852e2606edebea2645f35e6e95ceeb4b752eb", "size": 9244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BKSVD_CPP/BKSVD_CPP/BKSVD_CPP.cpp", "max_stars_repo_name": "ItakEjgo/BKSVD_CPP", "max_stars_repo_head_hexsha": "c626f264a82a226a211d9f31a40be5fa250ec843", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BKSVD_CPP/BKSVD_CPP/BKSVD_CPP.cpp", "max_issues_repo_name": "ItakEjgo/BKSVD_CPP", "max_issues_repo_head_hexsha": "c626f264a82a226a211d9f31a40be5fa250ec843", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BKSVD_CPP/BKSVD_CPP/BKSVD_CPP.cpp", "max_forks_repo_name": "ItakEjgo/BKSVD_CPP", "max_forks_repo_head_hexsha": "c626f264a82a226a211d9f31a40be5fa250ec843", "max_forks_repo_licenses": ["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.7080745342, "max_line_length": 108, "alphanum_fraction": 0.6325183903, "num_tokens": 2956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6742936223585857}}
{"text": "/*=============================================================================\nCopyright (c) 2016 Paul W. Bible\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n==============================================================================*/\n#ifndef JACCARD_SET_SIMILARITY\n#define JACCARD_SET_SIMILARITY\n\n#include <ggtk/SetUtilities.hpp>\n#include <ggtk/TermSetSimilarityInterface.hpp>\n\n#include <boost/unordered_set.hpp>\n\n/*! \\class JaccardSetSimilarity\n\t\\brief A class to calculate jaccard similarity between 2 sets.\n\n\tThis class calculates jaccard set similarity between two sets of terms.\n\n*/\nclass JaccardSetSimilarity : public TermSetSimilarityInterface{\n\npublic:\n\n\t//! Constructor\n\t/*!\n\t\tCreates the JaccardSetSimilarity class.\n\t*/\n\tJaccardSetSimilarity(){\n\t}\n\n\n\t//! A method for calculating term set to term set similarity for GO terms;\n\t/*!\n\t\tThis method returns the Jaccard set similarity.\n\t*/\n\tinline double calculateSimilarity(const boost::unordered_set<std::string> &termsA, const boost::unordered_set<std::string> &termsB){\n\n\t\t//return 0 if a set is empty\n\t\tif(termsA.size() == 0 || termsB.size() == 0){\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t//get iterators\n\t\tboost::unordered_set<std::string>::iterator shortSetIter;\n\n\t\tboost::unordered_set<std::string> _union = SetUtilities::set_union(termsA,termsB);\n\t\tboost::unordered_set<std::string> _intersection = SetUtilities::set_intersection(termsA,termsB);\n\n\t\tif(_union.size() == 0){\n\t\t\treturn 0.0;\n\t\t}else{\n\t\t\treturn (double)_intersection.size()/_union.size();\n\t\t}\n\t}\n\n};\n#endif\n", "meta": {"hexsha": "80db5fdebbec83783d9c8e97e9b5ffd2c21c3d98", "size": 1623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ggtk/JaccardSetSimilarity.hpp", "max_stars_repo_name": "paulbible/ggtk", "max_stars_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T04:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-27T20:51:59.000Z", "max_issues_repo_path": "ggtk/JaccardSetSimilarity.hpp", "max_issues_repo_name": "paulbible/ggtk", "max_issues_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T05:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T19:47:01.000Z", "max_forks_repo_path": "ggtk/JaccardSetSimilarity.hpp", "max_forks_repo_name": "paulbible/ggtk", "max_forks_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-08T21:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T21:30:32.000Z", "avg_line_length": 27.5084745763, "max_line_length": 133, "alphanum_fraction": 0.6697473814, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6742936164060276}}
{"text": "#include \"epipolar.h\"\n#include <Eigen/SVD>\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include \"permutation_sampler.h\"\n#include \"srrg_geometry/geometry3d.h\"\n\nnamespace srrg2_core{\n  namespace epipolar {\n    using Matrix3_2f = Eigen::Matrix<float, 3, 2>;\n    using Matrix9f   = Eigen::Matrix<float,9,9>;\n    using Matrix3_9f = Eigen::Matrix<float, 3, 9>;\n    using Vector9f   = Eigen::Matrix<float, 9, 1>;\n    \n    float triangulatePoint(Vector3f& p,\n                           const Line3f& a,\n                           const Line3f& b,\n                           Vector2f& s) {\n      const float epsilon=1e-9;\n      Matrix3_2f D;\n      D.col(0)=-a.direction;\n      D.col(1)=b.direction;\n      Matrix2f DtD=D.transpose()*D;\n      if (fabs(DtD.determinant())<=epsilon)\n        return -3.;\n      s=DtD.inverse()*D.transpose()*(a.point-b.point);\n      if (s(0)<0)\n        return -1.;\n      if (s(1)<0)\n        return -2;\n      Vector3f pa=a.point+a.direction*s(0);\n      Vector3f pb=b.point+b.direction*s(1);\n      p=0.5*(pa+pb);\n      return (pa-pb).norm();\n    }\n\n    float triangulatePoint(Vector3f& p,\n                           const Line3f& a,\n                           const Line3f& b) {\n      Vector2f s;\n      return triangulatePoint(p,a,b,s);\n    }\n\n    int triangulateDirections(Vector3fVector& points,\n                              std::vector<float>& results,\n                              const Isometry3f& iso1,\n                              const Isometry3f& iso2,\n                              const Vector3fVector& directions1,\n                              const Vector3fVector& directions2){\n      assert(directions1.size()==directions2.size() && \"directions size mismatch\");\n      size_t size=directions1.size();\n      points.resize(size);\n      results.resize(size);\n      Line3f l1(iso1.translation(), Vector3f::Zero());\n      Line3f l2(iso2.translation(), Vector3f::Zero());\n      int good=0;\n      for (size_t i=0; i<size; ++i) {\n        l1.direction = iso1.linear()*directions1[i];\n        l2.direction = iso2.linear()*directions2[i];\n        results[i]=triangulatePoint(points[i], l1, l2);\n        if (results[i]>=0)\n          ++good;\n      }\n      return good;\n    }\n\n\n    void projectPointsOnSphere(Vector3fVector& dirs,\n                               const Isometry3f& iso,\n                               const Vector3fVector& points){\n      dirs.resize(points.size());\n      Isometry3f invT=iso.inverse();\n      for (size_t i=0; i<points.size(); ++i) {\n        dirs[i]=(invT*points[i]);\n        dirs[i].normalize();\n      }\n    }\n\n    Matrix3f iso2essential(const Eigen::Isometry3f& iso){\n      const Vector3f t=iso.translation();\n      return iso.linear().transpose()*geometry3d::skew(t);\n    }\n\n    void essential2iso(Isometry3f iso[2],\n                       const Matrix3f& E) {\n      Matrix3f W;\n      W << 0, -1, 0,\n        1, 0, 0,\n        0, 0, 1;\n      Eigen::JacobiSVD<Matrix3f> svd(E, Eigen::ComputeFullU|Eigen::ComputeFullV);\n      Eigen::Matrix3f R=svd.matrixV()*W*svd.matrixU().transpose();\n      if(R.determinant()<0) {\n        svd=Eigen::JacobiSVD<Matrix3f>(-E, Eigen::ComputeFullU|Eigen::ComputeFullV);\n        R=svd.matrixV()*W*svd.matrixU().transpose();\n      }\n      iso[0].setIdentity();\n      iso[0].linear()=R;\n      Matrix3f t_cross=R*E;\n      iso[0].translation()=Vector3f(t_cross(2,1)-t_cross(1,2),\n                                    t_cross(0,2)-t_cross(2,0),\n                                    t_cross(1,0)-t_cross(0,1));\n\n      iso[1].setIdentity();\n      R=svd.matrixV()*W.transpose()*svd.matrixU().transpose();\n      iso[1].linear()=R;\n      t_cross=R*E;\n      iso[1].translation()=Vector3f(t_cross(2,1)-t_cross(1,2),\n                                    t_cross(0,2)-t_cross(2,0),\n                                    t_cross(1,0)-t_cross(0,1));\n    }\n    \n    float eightPointEstimate(Matrix3f& dest,\n                             const Vector3fVector& dirs1,\n                             const Vector3fVector& dirs2) {\n      using Matrix9f=Eigen::Matrix<float, 9,9>;\n      using Vector9f=Eigen::Matrix<float, 9,1>;\n      Matrix9f H;\n      H.setZero();\n      assert(dirs1.size()==dirs2.size() && \"dir size mismatch\");\n      for (size_t i=0; i<dirs1.size(); ++i) {\n        const Vector3f& d1=dirs1[i];\n        const Vector3f& d2=dirs2[i];\n        Vector9f a;\n        int k=0;\n        for (int c=0; c<3; ++c)\n          for (int r=0; r<3; ++r, ++k) {\n            a[k]=d1(c)*d2(r);\n          }\n        H.noalias()+=a*a.transpose();\n      }\n      Eigen::SelfAdjointEigenSolver<Eigen::Matrix<float, 9,9> > eig(H);\n      \n      // std::cerr << \"H: \" << std::endl;\n      // std::cerr << H << std::endl;\n\n      // std::cerr << \"eigenvectors: \" << std::endl;\n      // std::cerr << eig.eigenvectors() << std::endl;\n\n      // std::cerr << \"eigenvalues: \" << std::endl;\n      // std::cerr << eig.eigenvalues() << std::endl;\n      int k=0;\n      for (int c=0; c<3; ++c){\n        for (int r=0; r<3; ++r, ++k) {\n          dest(r,c)=eig.eigenvectors()(k,0);\n        }\n      }\n      return eig.eigenvalues()(0);\n    }\n\n    float estimateTransformFromDirections(Isometry3f& iso,\n                                          const Vector3fVector& dirs1,\n                                          const Vector3fVector& dirs2) {\n      assert(dirs1.size()==dirs2.size() && \"dir size mismatch\");\n      Matrix3f E;\n      float lambda=eightPointEstimate(E, dirs1, dirs2);\n      Isometry3f iso_v[2];\n      essential2iso(iso_v,E);\n      Vector3fVector temp_pts(dirs1.size());\n      std::vector<float> temp_errors;\n      int best_points=0;\n      for (int sol=0; sol<2; ++sol) {\n        Isometry3f temp_iso=iso_v[sol];\n        int temp_good = triangulateDirections(temp_pts,\n                                              temp_errors, \n                                              Isometry3f::Identity(),\n                                              temp_iso,\n                                              dirs1, dirs2);\n        if (temp_good>best_points) {\n          iso=temp_iso;\n        }\n        temp_iso.translation()=-temp_iso.translation();\n        temp_good = triangulateDirections(temp_pts,\n                                          temp_errors,\n                                          Isometry3f::Identity(),\n                                          temp_iso,\n                                          dirs1, dirs2);\n        if (temp_good>best_points) {\n          iso=temp_iso;\n        }\n      }\n      return lambda;\n    }\n\n    int scoreEssential(std::vector<float>& errors,\n                       const Matrix3f& E,\n                       const Vector3fVector& dirs1,\n                       const Vector3fVector& dirs2,\n                       const float inlier_threshold) {\n      int num_inliers=0;\n      assert(dirs1.size()==dirs2.size());\n      const size_t s=dirs1.size();\n      errors.resize(s);\n      for (size_t i=0; i<s; ++i) {\n        errors[i]=dirs2[i].transpose()*E*dirs1[i];\n        if (fabs(errors[i])<inlier_threshold)\n          ++num_inliers;\n      }\n      return num_inliers;\n    }\n\n    int estimateEssentialRANSACEightPts(Matrix3f& E,\n                                        std::vector<float>& errors,\n                                        const Vector3fVector& dirs1,\n                                        const Vector3fVector& dirs2,\n                                        float inlier_threshold,\n                                        int num_rounds,\n                                        const std::vector<double>& weights_) {\n      assert(dirs1.size()==dirs2.size() && \"dir size mismatch\");\n      size_t s=dirs1.size();\n      assert(s>=8 && \"not enough correspondences for 8 pt estimate\");\n      int best_num_inliers=0;\n      Vector3fVector dirs1_current(8);\n      Vector3fVector dirs2_current(8);\n      std::vector<float> errors_current(s);\n      std::vector<double> weights(s, 1.f);\n      if (weights_.size()) {\n        assert(weights.size()==s && \"weights size mismatch\");\n        weights=weights_;\n      }\n      PermutationSampler sampler(weights);\n      for (int round_num=0; round_num<num_rounds; ++round_num) {\n        // std::cerr << \"RANSAC:, round: \" << round_num << \"[ \";\n        for (size_t i=0; i<8; ++i) {\n          double r=drand48()*sampler.getSum();\n          int idx=sampler.sampleWithRemoval(r);\n          dirs1_current[i]=dirs1[idx];\n          dirs2_current[i]=dirs2[idx];\n          // std::cerr << idx << \" \";\n        }\n        Matrix3f E_current;\n        E_current.setZero();\n        eightPointEstimate(E_current, dirs1_current, dirs2_current);\n        int current_inliers=scoreEssential(errors_current, E_current, dirs1, dirs2, inlier_threshold);\n        // std::cerr << \"], inliers: \" << current_inliers << std::endl;\n        if (current_inliers>best_num_inliers) {\n          E=E_current;\n          errors=errors_current;\n          best_num_inliers=current_inliers;\n        }\n        sampler.recoverWeights();\n      }\n      return best_num_inliers;\n    }\n    /*\n    void estimateRotation(Matrix3f R,\n                          Vector3fVector& dirs1,\n                          Vector3fVector& dirs2) {\n      assert (dirs1.size()==dirs2.size() &&\" dirs size differ\");\n      assert (dirs1.size()>3 &&\" too few points\");\n      Matrix9f H;\n      H.setZero();\n      Vector9f b;\n      b.setZero();\n      Vector9f x;\n      x.setZero();\n      Matrix3_9f J;\n      J.setZero();\n      Vector3f e;\n      for (size_t i=0; i<dirs1.size(); ++i) {\n        const Vector3f& d1=dirs1[i];\n        const Vector3f& d2=dirs2[i];\n        J.block<3,1>(0,0)=d1.transpose();\n        J.block<3,1>(1,3)=d1.transpose();\n        J.block<3,1>(2,6)=d1.transpose();\n        H+=J.transpose()*J;\n        e=-d2;\n      }\n     \n    }\n    \n    float  estimateRotationTwoPts(Matrix3f& R,\n                            const Vector3fVector& dirs1,\n                            const Vector3fVector& dirs2,\n                            const float s_min,\n                            const float epsilon) {\n      using namespace std;\n      R.setIdentity();\n      assert (dirs1.size()==dirs2.size() &&\" dirs size differ\");\n      assert (dirs1.size()>= 2 &&\" need at least 2 dirs\");\n      Vector3f v1=dirs1[0].cross(dirs1[1]);\n      Vector3f v2=dirs2[0].cross(dirs2[1]);\n      R1.col(0)=dirs1[0];\n      R2.col(0)=dirs2[0];\n      // construct two rotation matrices\n      float n1=v1.norm();\n      float n2=v2.norm();\n      if(n1<s_min || n2<s_min) {\n        return -1;\n      }\n      if (fabs(n1-n2)>epsilon) {\n        return -2;\n      }\n      Matrix9f \n      float e=0;\n      for (size_t i=0; i<2; ++i) {\n        e+=(R*dirs1[i]-dirs2[i]).squaredNorm();\n      }\n      return e;\n    }\n    */\n  }\n}\n", "meta": {"hexsha": "1052e1ca3da35a91c366e4825a6157760cde5d79", "size": 10654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "srrg2_core/src/srrg_geometry/epipolar.cpp", "max_stars_repo_name": "srrg-sapienza/srrg2_core", "max_stars_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-11T14:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T09:01:15.000Z", "max_issues_repo_path": "srrg2_core/src/srrg_geometry/epipolar.cpp", "max_issues_repo_name": "srrg-sapienza/srrg2_core", "max_issues_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-07T17:25:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-15T07:36:10.000Z", "max_forks_repo_path": "srrg2_core/src/srrg_geometry/epipolar.cpp", "max_forks_repo_name": "srrg-sapienza/srrg2_core", "max_forks_repo_head_hexsha": "56c1f8305f2a9918b7e7c581d83d394ffb7ea50e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T08:17:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T05:07:07.000Z", "avg_line_length": 35.1617161716, "max_line_length": 102, "alphanum_fraction": 0.5064764408, "num_tokens": 2823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6742854138664681}}
{"text": "#define BOOST_TEST_MODULE KHash Unit Test\n\n#include <cstdint>\n\n#include <boost/test/included/unit_test.hpp>\n\n#include \"hash.hpp\"\n#include \"prime.hpp\"\n\nnamespace hash\n{\n\nstruct k_universal_tester final\n{\n    void test_trivial()\n    {\n        // integer hash is trivial and perfect\n        BOOST_REQUIRE_EQUAL(k_universal<uint8_t>::basic(item), item);\n    }\n\n    void test_hash(uint8_t k, uint8_t trials)\n    {\n        hash::k_universal_family<uint8_t> kuf(k, 50);\n\n        for (uint8_t t = 1; t <= trials; ++t)\n        {\n            auto h = kuf();\n            uint64_t re = h(item), exp = 0, acc = 1;\n            for (uint32_t i : h.as)\n            {\n                exp += i * acc;\n                acc *= item;\n            }\n            exp =(exp + h.a * acc) %  prime::mersennes::mersenne31.p;\n            BOOST_CHECK_EQUAL(re, exp);\n        }\n    }\nprivate:\n    static constexpr uint8_t item = 3;\n};\n\n}\n\nstruct k_universal_test_fixture\n{\n    hash::k_universal_tester tester;\n};\n\nBOOST_FIXTURE_TEST_SUITE(KUniversal, k_universal_test_fixture)\n\nBOOST_AUTO_TEST_CASE(Trivial)\n{\n    tester.test_trivial();\n}\n\nBOOST_AUTO_TEST_CASE(Hashing)\n{\n    for (uint8_t k = 1; k <= 10; ++k)\n        tester.test_hash(k, 10);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "972fc6cae3d285fe60e010928a7253ee27a6077c", "size": 1242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignment/B/hash_test.cpp", "max_stars_repo_name": "laitingsheng/2019S2-COMP90056", "max_stars_repo_head_hexsha": "adc65917942ce0057cd51602f700c8a7e09cfaea", "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": "Assignment/B/hash_test.cpp", "max_issues_repo_name": "laitingsheng/2019S2-COMP90056", "max_issues_repo_head_hexsha": "adc65917942ce0057cd51602f700c8a7e09cfaea", "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": "Assignment/B/hash_test.cpp", "max_forks_repo_name": "laitingsheng/2019S2-COMP90056", "max_forks_repo_head_hexsha": "adc65917942ce0057cd51602f700c8a7e09cfaea", "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": 19.7142857143, "max_line_length": 69, "alphanum_fraction": 0.5966183575, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6742742834206898}}
{"text": "//\n//  cvx_gl_homography.cpp\n//  CalibMeMatching\n//\n//  Created by jimmy on 2017-07-30.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"cvx_gl_homography.h\"\n#include <iostream>\n\n// Eigen\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\nusing std::cout;\nusing std::endl;\n\nnamespace cvx_gl {\n    \n    namespace  {\n        // @brief estimate homography from single-image correspondences\n        struct PointLineHomographyFunctor\n        {\n            typedef double Scalar;\n            \n            typedef Eigen::VectorXd InputType;\n            typedef Eigen::VectorXd ValueType;\n            typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> JacobianType;\n            \n            enum {\n                InputsAtCompileTime = Eigen::Dynamic,\n                ValuesAtCompileTime = Eigen::Dynamic\n            };\n            \n            const vector<Vector2d> src_pts_;\n            const vector<Vector2d> dst_pts_;\n            const vector<Eigen::ParametrizedLine<double, 2> > src_lines_;\n            const vector<Vector2d> dst_line_pts_;\n            \n            int m_inputs;\n            int m_values;\n            \n            PointLineHomographyFunctor(const vector<Vector2d> & src_pts,\n                                       const vector<Vector2d> & dst_pts,\n                                       const vector<Eigen::ParametrizedLine<double, 2> > & src_lines,\n                                       const vector<Vector2d> & dst_line_pts):\n            src_pts_(src_pts),\n            dst_pts_(dst_pts),\n            src_lines_(src_lines),\n            dst_line_pts_(dst_line_pts)\n            \n            {\n                m_inputs = 9;\n                m_values = (int)src_pts.size() * 2 + (int)src_lines.size();\n                assert(m_values >= 9);\n            }\n            \n            \n            int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fx) const\n            {\n                Eigen::Matrix3d h;\n                for (int i = 0; i<9; i++) {\n                    h(i/3, i%3) = x[i];\n                }\n                h.normalize();\n                Eigen::Matrix3d inv_h = h.inverse();\n                \n                // point to point correspondence\n                int idx = 0;\n                for (int i = 0; i<src_pts_.size(); i++) {\n                    Eigen::Vector3d p(src_pts_[i].x(), src_pts_[i].y(), 1.0);\n                    Eigen::Vector3d q = h * p;\n                    assert(q.z() != 0);\n                    q /= q.z();\n                    \n                    fx[idx++] = dst_pts_[i].x() - q.x();\n                    fx[idx++] = dst_pts_[i].y() - q.y();\n                }\n                \n                // point to line distance, from destination to source\n                for (int i = 0; i<src_lines_.size(); i++) {\n                    Eigen::Vector3d p(dst_line_pts_[i].x(), dst_line_pts_[i].y(), 1.0);\n                    Eigen::Vector3d q = inv_h * p;\n                    assert(q.z() != 0);\n                    q /= q.z();\n                    \n                    double dist = src_lines_[i].distance(Eigen::Vector2d(q.x(), q.y()));\n                    fx[idx++] = dist;\n                }\n                return 0;\n            }\n            \n            int inputs() const { return m_inputs; }  // inputs is the dimension of x.\n            int values() const { return m_values; }   // \"values\" is the number of fx and\n            \n            void getResult(const Eigen::VectorXd &x, Eigen::Matrix3d & result) const\n            {\n                for (int i = 0; i<9; i++) {\n                    result(i/3, i%3) = x[i];\n                }\n                result.normalize();\n            }\n        };\n    }\n    \n    \n    bool estimateHomography(const vector<Vector2d> & src_pts,\n                            const vector<Vector2d> & dst_pts,\n                            const vector<Eigen::ParametrizedLine<double, 2> > & src_lines,\n                            const vector<Vector2d> & dst_line_pts,\n                            const Eigen::Matrix3d& init_homo,\n                            Eigen::Matrix3d& final_homo)\n    {\n        assert(src_pts.size() == dst_pts.size());\n        assert(src_lines.size() == dst_line_pts.size());\n        \n        int num = (int)src_pts.size() * 2 + (int)src_lines.size();\n        if (num <= 9) {\n            return false;\n        }\n        \n        PointLineHomographyFunctor opt_functor(src_pts, dst_pts, src_lines, dst_line_pts);\n        Eigen::NumericalDiff<PointLineHomographyFunctor> numerical_dif_functor(opt_functor);\n        Eigen::LevenbergMarquardt<Eigen::NumericalDiff<PointLineHomographyFunctor>, double> lm(numerical_dif_functor);\n        lm.parameters.ftol = 1e-6;\n        lm.parameters.xtol = 1e-6;\n        lm.parameters.maxfev = 100;\n        \n        Eigen::VectorXd x(9);\n        for (int i = 0; i<9; i++) {\n            x[i] = init_homo(i/3, i%3);\n        }\n        \n        Eigen::LevenbergMarquardtSpace::Status status = lm.minimize(x);\n        std::cout << \"status: \" << status << std::endl;\n        \n        opt_functor.getResult(x, final_homo);\n        \n        return true;\n    }\n    \n    namespace {\n        \n        struct MultiFramePointLineHomographyFunctor {\n            typedef double Scalar;\n            typedef Eigen::VectorXd InputType;\n            typedef Eigen::VectorXd ValueType;\n            typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> JacobianType;\n            \n            enum {\n                InputsAtCompileTime = Eigen::Dynamic,\n                ValuesAtCompileTime = Eigen::Dynamic\n            };\n            \n            const vector<vector<Vector2d> > src_pts_;\n            const vector<vector<Vector2d> > dst_pts_;\n            const vector<vector<Eigen::ParametrizedLine<double, 2> > > src_lines_;\n            const vector<vector<Vector2d> > dst_line_pts_;\n            const vector<Eigen::Matrix3d> model_to_image_homos_;\n            \n            int m_inputs;\n            int m_values;\n            \n            MultiFramePointLineHomographyFunctor(const vector<vector<Vector2d> > & src_pts,\n                                                 const vector<vector<Vector2d> > & dst_pts,\n                                                 const vector<vector<Eigen::ParametrizedLine<double, 2> > > & src_lines,\n                                                 const vector<vector<Vector2d> > & dst_line_pts,\n                                                 const vector<Eigen::Matrix3d>& model_to_image_homos):\n            src_pts_(src_pts),\n            dst_pts_(dst_pts),\n            src_lines_(src_lines),\n            dst_line_pts_(dst_line_pts),\n            model_to_image_homos_(model_to_image_homos)\n            {\n                m_inputs = 9;\n                m_values = 0;//(int)src_pts.size() * 2 + (int)src_lines.size();\n                assert(src_pts_.size() == dst_pts_.size());\n                assert(src_pts_.size() == src_lines_.size());\n                assert(src_lines_.size() == dst_line_pts_.size());\n                assert(src_pts_.size() == model_to_image_homos_.size());\n                \n                // point-to-point provides 2 constraint\n                // point-on-line provides 1 constraint\n                for (int i = 0; i<src_pts_.size(); i++) {\n                    m_values += (int)src_pts_[i].size() * 2 + (int)src_lines_[i].size();\n                }\n                assert(m_values >= 9);\n            }\n            \n            int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fx) const\n            {\n                Eigen::Matrix3d h;\n                for (int i = 0; i<9; i++) {\n                    h(i/3, i%3) = x[i];\n                }\n                h.normalize();\n                \n                // point to point correspondence\n                int idx = 0;\n                for (int i = 0; i<src_pts_.size(); i++) {\n                    // source image --> model --> destination image\n                    Eigen::Matrix3d cur_h = h * model_to_image_homos_[i].inverse();\n                    for (int j = 0; j<src_pts_[i].size(); j++) {\n                        Eigen::Vector3d p(src_pts_[i][j].x(), src_pts_[i][j].y(), 1.0);\n                        Eigen::Vector3d q = cur_h * p;\n                        assert(q.z() != 0);\n                        q /= q.z();\n                        \n                        fx[idx++] = dst_pts_[i][j].x() - q.x();\n                        fx[idx++] = dst_pts_[i][j].y() - q.y();\n                    }\n                }\n                \n                // point to line distance, from destination to source\n                for (int i = 0; i<src_lines_.size(); i++) {\n                    // source image --> model --> destination image\n                    // note from destination to source\n                    Eigen::Matrix3d cur_h_inv = (h * model_to_image_homos_[i].inverse()).inverse();\n                    for (int j = 0; j<src_lines_[i].size(); j++) {\n                        Eigen::Vector3d p(dst_line_pts_[i][j].x(), dst_line_pts_[i][j].y(), 1.0);\n                        Eigen::Vector3d q = cur_h_inv * p;\n                        assert(q.z() != 0);\n                        q /= q.z();\n                        \n                        double dist = src_lines_[i][j].distance(Eigen::Vector2d(q.x(), q.y()));\n                        fx[idx++] = dist;\n                    }\n                }\n                return 0;\n            }\n            \n            int inputs() const { return m_inputs; }  // inputs is the dimension of x.\n            int values() const { return m_values; }   // \"values\" is the number of fx and\n            \n            void getResult(const Eigen::VectorXd &x, Eigen::Matrix3d & result) const\n            {\n                for (int i = 0; i<9; i++) {\n                    result(i/3, i%3) = x[i];\n                }\n                result.normalize();\n            }\n        };\n    }\n    \n    bool estimateHomography(const vector<vector<Vector2d> > & src_pts,\n                            const vector<vector<Vector2d> > & dst_pts,\n                            const vector<vector<Eigen::ParametrizedLine<double, 2> > > & src_lines,\n                            const vector<vector<Vector2d> > & dst_line_pts,\n                            const vector<Eigen::Matrix3d>& model_to_image_homos,\n                            const Eigen::Matrix3d& init_homo,\n                            Eigen::Matrix3d& refined_homo)\n    {\n        assert(src_pts.size() == dst_pts.size());\n        assert(src_lines.size() == dst_line_pts.size());\n        \n        int num = 0;\n        for (int i = 0; i<src_pts.size(); i++) {\n            num += (int)src_pts[i].size() * 2 + (int)src_lines[i].size();\n        }\n        if (num <= 9) {\n            return false;\n        }\n        \n        MultiFramePointLineHomographyFunctor opt_functor(src_pts, dst_pts, src_lines, dst_line_pts, model_to_image_homos);\n        Eigen::NumericalDiff<MultiFramePointLineHomographyFunctor> numerical_dif_functor(opt_functor);\n        Eigen::LevenbergMarquardt<Eigen::NumericalDiff<MultiFramePointLineHomographyFunctor>, double> lm(numerical_dif_functor);\n        lm.parameters.ftol = 1e-6;\n        lm.parameters.xtol = 1e-6;\n        lm.parameters.maxfev = 100;\n        \n        \n        Eigen::VectorXd x(9);\n        for (int i = 0; i<9; i++) {\n            x[i] = init_homo(i/3, i%3);\n        }\n        \n        Eigen::LevenbergMarquardtSpace::Status status = lm.minimize(x);\n        std::cout << \"status: \" << status << std::endl;\n        \n        opt_functor.getResult(x, refined_homo);\n        return true;\n    }\n    \n} // namespace\n", "meta": {"hexsha": "2704e772f76c3350ed190967047e7aed80574b50", "size": 11636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boundle_adjustment/cvx_gl/cvx_gl_homography.cpp", "max_stars_repo_name": "lood339/CalibMe", "max_stars_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-07T10:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T10:52:45.000Z", "max_issues_repo_path": "src/boundle_adjustment/cvx_gl/cvx_gl_homography.cpp", "max_issues_repo_name": "lood339/CalibMe", "max_issues_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "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/boundle_adjustment/cvx_gl/cvx_gl_homography.cpp", "max_forks_repo_name": "lood339/CalibMe", "max_forks_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "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.543554007, "max_line_length": 128, "alphanum_fraction": 0.4728429013, "num_tokens": 2640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240211961401, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6741306555139451}}
{"text": "#ifndef EXPSUM_EXPONENTIAL_SUM_HPP\n#define EXPSUM_EXPONENTIAL_SUM_HPP\n\n#include <cassert>\n#include <iosfwd>\n#include <stdexcept>\n\n#include <armadillo>\n\nnamespace expsum\n{\n\ntemplate <typename ResultT, typename ParamT = ResultT>\nclass exponential_sum;\n\n//\n// Univariate function expressed as an exponential sum\n//\ntemplate <typename ResultT, typename ParamT>\nclass exponential_sum\n{\npublic:\n    using result_type      = ResultT;\n    using argument_type    = typename arma::get_pod_type<ResultT>::result;\n    using parameter_type   = ParamT;\n    using size_type        = arma::uword;\n    using parameter_vector = arma::Col<parameter_type>;\n\nprivate:\n    template <bool>\n    struct eval_dispacher\n    {\n    };\n\n    using eval_default      = eval_dispacher<false>;\n    using eval_as_real_func = eval_dispacher<true>;\n\n    parameter_vector exponent_; // exponents\n    parameter_vector weight_;   // weights\n\npublic:\n    constexpr static const bool is_real_function =\n        arma::is_real<result_type>::value;\n\n    // Default constructor\n    exponential_sum() = default;\n\n    // Create `n` term exponential sum\n    exponential_sum(size_type n) : exponent_(n), weight_(n)\n    {\n    }\n\n    // Create from the vectors of exponents and weights\n    template <typename V1, typename V2>\n    exponential_sum(\n        const V1& exponents, const V2& weights,\n        typename std::enable_if<(arma::is_arma_type<V1>::value &&\n                                 arma::is_arma_type<V2>::value)>::type* = 0)\n        : exponent_(exponents), weight_(weights)\n    {\n        assert(exponents.is_vec() && weights.is_vec());\n        assert(exponents.n_elem == weights.n_elem);\n    }\n\n    // Default copy constructor\n    exponential_sum(const exponential_sum&) = default;\n\n    // Default move constructor\n    exponential_sum(exponential_sum&&) = default;\n\n    // Default destructor\n    ~exponential_sum() = default;\n\n    // Default copy assignment operator\n    exponential_sum& operator=(const exponential_sum&) = default;\n\n    // Default move assignment operator\n    exponential_sum& operator=(exponential_sum&&) = default;\n\n    //\n    // Get the number of terms\n    //\n    size_type size() const\n    {\n        return exponent_.size();\n    }\n    //\n    // Return true if container is empty\n    //\n    bool empty() const\n    {\n        return exponent_.empty();\n    }\n    //\n    // Evaluate value at the given point\n    //\n    result_type operator()(const argument_type& x) const\n    {\n        return eval_impl(\n            x, eval_dispacher<(arma::is_real<result_type>::value &&\n                               arma::is_complex<parameter_type>::value)>());\n    }\n    //\n    // Get const reference to the vector of exponents\n    //\n    const parameter_vector& exponent() const\n    {\n        return exponent_;\n    }\n    //\n    // Get const reference to the `i`-th exponent\n    //\n    const parameter_type& exponent(size_type i) const\n    {\n        return exponent_(i);\n    }\n    //\n    // Get reference to the `i`-th exponent\n    //\n    parameter_type& exponent(size_type i)\n    {\n        return exponent_(i);\n    }\n    //\n    // Get const reference to the vector of weights\n    //\n    const parameter_vector& weight() const\n    {\n        return weight_;\n    }\n    //\n    // Get const reference to the `i`-th weight\n    //\n    const parameter_type& weight(size_type i) const\n    {\n        return weight_(i);\n    }\n    //\n    // Get reference to the `i`-th weight\n    //\n    parameter_type& weight(size_type i)\n    {\n        return weight_(i);\n    }\n    //\n    // Change the container size\n    //\n    void resize(size_type n)\n    {\n        exponent_.set_size(n);\n        weight_.set_size(n);\n    }\n    //\n    // Set new exponents and weights\n    //\n    template <typename V1, typename V2>\n    typename std::enable_if<(arma::is_arma_type<V1>::value &&\n                             arma::is_arma_type<V2>::value)>::type\n    set(const V1& new_exponents, const V2& new_weights)\n    {\n        assert(new_exponents.is_vec() && new_weights.is_vec() &&\n               new_exponents.n_elem == new_weights.n_elem);\n        exponent_ = new_exponents;\n        weight_   = new_weights;\n    }\n    //\n    // Remove terms with small weights\n    //\n    void remove_small_terms(argument_type tolerance)\n    {\n        const auto max_weight = arma::max(arma::abs(weight_));\n        const auto selected =\n            arma::find(arma::abs(weight_) > max_weight * tolerance);\n        parameter_vector tmp_e(exponent_(selected));\n        parameter_vector tmp_w(weight_(selected));\n        exponent_ = std::move(tmp_e);\n        weight_   = std::move(tmp_w);\n    }\n    //\n    // Output to ostream\n    //\n    template <typename Ch, typename Tr>\n    void print(std::basic_ostream<Ch, Tr>& os) const\n    {\n        os << size() << '\\n'; // number of terms\n        for (size_type i = 0; i < size(); ++i)\n        {\n            os << exponent(i) << '\\t' << weight(i) << '\\n';\n        }\n    }\n\nprivate:\n    result_type eval_impl(const argument_type& x, eval_default) const\n    {\n        return arma::sum(arma::exp(-x * exponent_) % weight_);\n    }\n\n    result_type eval_impl(const argument_type& x, eval_as_real_func) const\n    {\n        return std::real(arma::sum(arma::exp(-x * exponent_) % weight_));\n    }\n\n    // Sort by absolute value of exponent\n    void sort()\n    {\n        arma::uvec index = arma::linspace<arma::uvec>(0, size() - 1, size());\n        std::sort(std::begin(index), std::end(index),\n                  [this](size_type i, size_type j) {\n                      return std::abs(exponent(i)) < std::abs(exponent(j));\n                  });\n        parameter_vector tmp(exponent_(index));\n        exponent_ = tmp;\n        tmp       = weight_(index);\n        weight_   = std::move(tmp);\n    }\n};\n\n// Ostream operator\ntemplate <typename Ch, typename Tr, typename ResultT, typename ParamT>\nstd::basic_ostream<Ch, Tr>&\noperator<<(std::basic_ostream<Ch, Tr>& os,\n           const exponential_sum<ResultT, ParamT>& fn)\n{\n    fn.print(os);\n    return os;\n}\n\n//=============================================================================\n// Function multiplication\n//=============================================================================\n//\n// Multiply two exponential sum functions.\n//\ntemplate <typename T1, typename P1, typename T2, typename P2>\nauto multiply(const exponential_sum<T1, P1>& x,\n              const exponential_sum<T2, P2>& y)\n    -> exponential_sum<decltype(T1() + T2()), decltype(P1() + P2())>\n{\n    using result_type =\n        exponential_sum<decltype(T1() + T2()), decltype(P1() + P2())>;\n    using size_type = typename result_type::size_type;\n\n    result_type z(x.size() * y.size());\n\n    size_type k = 0;\n    for (size_type j = 0; j < y.size(); ++j)\n    {\n        for (size_type i = 0; i < x.size(); ++i, ++k)\n        {\n            z.exponent(k) = x.exponent(i) + y.exponent(j);\n            z.weight(k)   = x.weight(i) * y.weight(j);\n        }\n    }\n\n    return z;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_EXPONENTIAL_SUM_HPP */\n", "meta": {"hexsha": "6741a00f6644d2de2af2a54c97c58fa5c1943641", "size": 7006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/exponential_sum.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/exponential_sum.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/exponential_sum.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": 26.8429118774, "max_line_length": 79, "alphanum_fraction": 0.5853554096, "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.674117191720743}}
{"text": "/*\n * Copyright 2017 Mahdi Khanalizadeh\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 HEADER_EXT_VECTOR4_HPP_INCLUDED\n#define HEADER_EXT_VECTOR4_HPP_INCLUDED\n\n#include <cmath>\n\n#include <boost/operators.hpp>\n\nnamespace ext\n{\n\n\ttemplate <typename T>\n\tclass Vector4 :\n\t\tboost::equality_comparable<Vector4<T>,\n\t\tboost::additive<Vector4<T>,\n\t\tboost::multiplicative<Vector4<T>, T\n\t\t>>>\n\t{\n\tpublic:\n\t\tusing Type = T;\n\n\t\tType x;\n\t\tType y;\n\t\tType z;\n\t\tType w;\n\n\t\tVector4() : x{0}, y{0}, z{0}, w{0} {}\n\t\tVector4(Type x_, Type y_, Type z_, Type w_) : x{x_}, y{y_}, z{z_}, w{w_} {}\n\t\ttemplate <typename U>\n\t\tVector4(Vector4<U> const& v) : x{v.x}, y{v.y}, z{v.z}, w{v.w} {}\n\t};\n\n\tusing Vector4f = Vector4<float>;\n\tusing Vector4d = Vector4<double>;\n\tusing Vector4ld = Vector4<long double>;\n\n\ttemplate <typename T>\n\tbool operator==(Vector4<T> const& v1, Vector4<T> const& v2)\n\t{\n\t\treturn v1.x == v2.x && v1.y == v2.y && v1.z == v2.z && v1.w == v2.w;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T>& operator+=(Vector4<T>& v1, Vector4<T> const& v2)\n\t{\n\t\tv1.x += v2.x;\n\t\tv1.y += v2.y;\n\t\tv1.z += v2.z;\n\t\tv1.w += v2.w;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T>& operator-=(Vector4<T>& v1, Vector4<T> const& v2)\n\t{\n\t\tv1.x -= v2.x;\n\t\tv1.y -= v2.y;\n\t\tv1.z -= v2.z;\n\t\tv1.w -= v2.w;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T>& operator*=(Vector4<T>& v, T t)\n\t{\n\t\tv.x *= t;\n\t\tv.y *= t;\n\t\tv.z *= t;\n\t\tv.w *= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T>& operator/=(Vector4<T>& v, T t)\n\t{\n\t\tv.x /= t;\n\t\tv.y /= t;\n\t\tv.z /= t;\n\t\tv.w /= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T> operator+(Vector4<T> const& v)\n\t{\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector4<T> operator-(Vector4<T> const& v)\n\t{\n\t\treturn {-v.x, -v.y, -v.z, -v.w};\n\t}\n\n\ttemplate <typename T>\n\tT dot(Vector4<T> const& v1, Vector4<T> const& v2)\n\t{\n\t\treturn v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w;\n\t}\n\n\ttemplate <typename T>\n\tT norm(Vector4<T> const& v)\n\t{\n\t\treturn std::sqrt(dot(v, v));\n\t}\n\n\ttemplate <typename T>\n\tVector4<T> normalize(Vector4<T> const& v)\n\t{\n\t\treturn v / norm(v);\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_VECTOR4_HPP_INCLUDED\n", "meta": {"hexsha": "33c6a5fdaad5895cfc3d1afa5113920b8288b387", "size": 2657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/vector4.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/vector4.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/vector4.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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.2824427481, "max_line_length": 77, "alphanum_fraction": 0.6236356793, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.6740590058876865}}
{"text": "#include <iostream>\n\n#include <boost/format.hpp>\n#include <gtest/gtest.h>\n\n#include <divide_conquer_strategy.hpp>\n\nTEST(divide_conquer_strategy, find_max_subarray) {\n    {\n        std::vector<int> v{-1, 1, 2, 3, 4, -5};\n        auto max_subarray = my::find_max_subarray(v.begin(), v.end());\n        EXPECT_EQ(v[1], *max_subarray.begin);\n        EXPECT_EQ(v[5], *max_subarray.end);\n        EXPECT_EQ(10, max_subarray.sum);\n    }\n    {\n        std::vector<int> v{13, -3, -25, 20, -3,  -16, -23, 18,\n                           20, -7, 12,  -5, -22, 15,  -4,  7};\n        auto max_subarray = my::find_max_subarray(v.begin(), v.end());\n        EXPECT_EQ(v[7], *max_subarray.begin);\n        EXPECT_EQ(v[11], *max_subarray.end);\n        EXPECT_EQ(43, max_subarray.sum);\n    }\n}\n\nTEST(divide_conquer_strategy, square_matrix_mul) {\n    my::matrix<int> m1{4, 4, 2};\n    int v{1};\n    m1.for_each([&](auto i, auto j) { m1.set_elem(i, j, v++); });\n\n    my::print_matrix(m1);\n\n    {\n        auto m = my::matrix_mul_slow(m1, m1);\n        my::print_matrix(m);\n    }\n\n    my::print_matrix(m1);    \n    {\n        auto m = m1 * m1;\n        my::print_matrix(m);\n    }\n}\n", "meta": {"hexsha": "3792a2d5bee5f65fc9dff127bdba865925109d84", "size": 1151, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/divide_conquer_strategy.cc", "max_stars_repo_name": "yydcnjjw/my-algorithm", "max_stars_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/divide_conquer_strategy.cc", "max_issues_repo_name": "yydcnjjw/my-algorithm", "max_issues_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/divide_conquer_strategy.cc", "max_forks_repo_name": "yydcnjjw/my-algorithm", "max_forks_repo_head_hexsha": "ca10befe988ae448eeda7452900fb01d2712d359", "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.1590909091, "max_line_length": 70, "alphanum_fraction": 0.551694179, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.6740430740984124}}
{"text": "#include <tansa/algorithm.h>\n\n#include <vector>\n#include <iostream>\n#include <cfloat>\n\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace tansa {\n\nvoid RigidPointCorrespondenceSolver::arrange(const vector<Vector3d> &bs, const vector<int> &c, vector<Vector3d> *out) {\n\tout->resize(c.size());\n\tfor(unsigned i = 0; i < c.size(); i++) {\n\t\t(*out)[i] = bs[c[i]];\n\t}\n}\n\n\nbool RigidPointCorrespondenceSolver::solve(const vector<Vector3d> &as, const vector<Vector3d> &bs, vector<int> *c, bool ideal) {\n\n\tif(as.size() != bs.size() && ideal) {\n\t\tprintf(\"Both sets must be complete!\\n\");\n\t\treturn false;\n\t}\n\n\n\t/* Compute set centers */\n\tVector3d cA = centroid(as), cB = centroid(bs);\n\n\tMatrixXd Ac(as.size(), 3), Bc(bs.size(), 3);\n\tfor(unsigned i = 0; i < as.size(); i++){\n\t\tAc.block<1,3>(i, 0) = as[i] - cA; // TODO: Don't these need to be tranposed\n\t\tBc.block<1,3>(i, 0) = bs[i] - cB;\n\t}\n\n\n\t// Get the eigenvalues and eigenvectors of the scatter matrices\n\tVector3d dA, dB;\n\tMatrixXd Qa(as.size(), 3), Qb(bs.size(), 3);\n\tdecompose_eigenstructure(Ac * Ac.transpose(), &dA, &Qa);\n\tdecompose_eigenstructure(Bc * Bc.transpose(), &dB, &Qb);\n\n\n\t// There will potentially be sign inconsistency in the eigenvectors\n\t// Therefore we must consider all possible permutations on the signs of one of the eigenvectors\n\t// We put the permutation that results in the lowest error\n\t// TODO: If we wanted a quick and 'ok' solution, we could take the absolute value of both eigenvector sets and simplify this to only one sign iteration\n\t// TODO: Ratio test best and second best matches\n\tdouble minCost = DBL_MAX;\n\tvector<int> minCorresp;\n\tvector<int> corresp(as.size(), -1);\n\tfor(unsigned it = 0; it < 8; it++) {\n\t\tRowVector3d signA(it & 0b001? 1 : -1, it & 0b010? 1 : -1, it & 0b100? 1 : -1);\n\t\tcout << signA << endl;\n\n\t\t// Make a copy of Qa with the currently proposed signs\n\t\tMatrixXd Qai(Qa.rows(), Qa.cols());\n\t\tfor(unsigned i = 0; i < Qa.rows(); i++) {\n\t\t\tQai.row(i) = Qa.row(i).cwiseProduct(signA);\n\t\t}\n\n\t\tdouble cost = ideal? solve_ideal(Qai, Qb, &corresp) : solve_general(dA, Qai, dB, Qb, &corresp);\n\t\tif(cost < minCost) {\n\t\t\tminCorresp = corresp;\n\t\t\tminCost = cost;\n\t\t}\n\t}\n\n\n\t*c = minCorresp;\n\treturn true;\n}\n\nvoid RigidPointCorrespondenceSolver::decompose_eigenstructure(const MatrixXd &M, Vector3d *d, MatrixXd *Q) {\n\t// Gets the eigenvalues/vectors in increasing order\n\tSelfAdjointEigenSolver<MatrixXd> eig(M);\n\n\tMatrixXd vecs = eig.eigenvectors();\n\tVectorXd vals = eig.eigenvalues();\n\n\t// We assume that we are given one of the scatter matrices which will definitely be positive semi-definite (so no negative eigenvalues)\n\t// Take last three values/vectors\n\tfor(unsigned i = 0; i < 3; i++) {\n\t\tunsigned idx = vecs.cols() - i - 1;\n\t\tQ->col(i) = vecs.col(idx);\n\t\t(*d)(i) = vals(idx);\n\t}\n}\n\ndouble RigidPointCorrespondenceSolver::solve_ideal(const MatrixXd &Qa, const MatrixXd &Qb, std::vector<int> *c) {\n\n// TODO:\n\t// MatrixXd P = Qa * Qb.transpose(); // eigA.eigenvectors() * eigB.eigenvectors().transpose();\n\n\t// 'Feature vector' are the columns of these\n\t//cout << Qa.transpose() << endl << endl;\n\t//cout << Qb.transpose() << endl << endl;\n\n\t// Determine column permutation matrix based on best matches\n\t//MatrixXd P = MatrixXd::Zero(as.size(), bs.size());\n\t// TODO: What if two i indices have the same best\n\tdouble cost = 0;\n\tfor(unsigned i = 0; i < Qa.rows(); i++) {\n\n\t\tdouble bestE = DBL_MAX;\n\t\tint bestJ = 0;\n\n\t\tfor(unsigned j = 0; j < Qb.rows(); j++) {\n\t\t\tdouble e = (Qa.block<1,3>(i, 0) - Qb.block<1,3>(j, 0)).squaredNorm();\n\n\t\t\tif(e < bestE) {\n\t\t\t\tbestE = e;\n\t\t\t\tbestJ = j;\n\t\t\t}\n\t\t}\n\n\t\t(*c)[i] = bestJ;\n\t\tcost += bestE;\n\n\t\t//P(bestJ, i) = 1;\n\t}\n\n\t//if(P.rank() != as.size()) {\n\t//\t// the matches were probably not sufficiently distinct\n\t//\t// TODO: Ratio test?\n\t//\n\t//\t\tcout << \"failed\" << endl;\n\t//\t}\n\n\n\treturn cost;\n}\n\n\ndouble RigidPointCorrespondenceSolver::solve_general(const Vector3d &dA, const MatrixXd &Qa, const Vector3d &dB, const MatrixXd &Qb, std::vector<int> *c) {\n\n\tMatrixXd h(Qa.rows(), Qb.rows()); // Affinity matrix\n\n\tfor(int i = 0; i < h.rows(); i++) {\n\t\tfor(int j = 0; j < h.cols(); j++) {\n\n\t\t\tdouble s = 0;\n\t\t\tfor(int k = 0; k < 3; k++) {\n\t\t\t\t// Eigenvalues corresponding to the vectors\n\t\t\t\tdouble dAk = dA(k),\n\t\t\t\t\t   dBk = dB(k);\n\n\t\t\t\tdouble pik = Qa(i, k),\n\t\t\t\t\t   qjk = Qb(j, k);\n\n\t\t\t\ts += dAk * dBk * pow(abs(pik - qjk), 2);\n\t\t\t}\n\n\t\t\t// We do not need the negative sign as in the paper if the assignment algorithm is minimizing\n\t\t\th(i, j) = s; // -s;\n\t\t}\n\t}\n\n\tAssignmentSolver as;\n\treturn as.solve(h, c);\n\n\n\t// TODO: Also implement the outlier rejection method\n}\n\n\n\n}\n", "meta": {"hexsha": "d5fe3a863ff307d401cab19c55ac20dc360e0065", "size": 4619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/rigid_point_correspondence_solver.cpp", "max_stars_repo_name": "jeremypbrowne/tansa", "max_stars_repo_head_hexsha": "e6044af397f99b9b985ed56015e9e0be13d4b026", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2017-01-18T17:17:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T17:24:08.000Z", "max_issues_repo_path": "src/algorithm/rigid_point_correspondence_solver.cpp", "max_issues_repo_name": "jeremypbrowne/tansa", "max_issues_repo_head_hexsha": "e6044af397f99b9b985ed56015e9e0be13d4b026", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2016-12-04T13:26:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-29T22:49:13.000Z", "max_forks_repo_path": "src/algorithm/rigid_point_correspondence_solver.cpp", "max_forks_repo_name": "jeremypbrowne/tansa", "max_forks_repo_head_hexsha": "e6044af397f99b9b985ed56015e9e0be13d4b026", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-03-11T01:53:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-09T07:53:57.000Z", "avg_line_length": 26.8546511628, "max_line_length": 155, "alphanum_fraction": 0.6410478459, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6739923039299166}}
{"text": "#pragma once\n#include <armadillo>\n\nusing namespace arma;\n\nnamespace TimeSeries {\n\nconstexpr double pmSd = 3.0;\nconstexpr double minPr = 1.0E-4;\n\nstruct DiscreteRV {\n  vec support;\n  vec probabilities;\n};\n\nstruct MvNormal {\n  vec mean;\n  mat varCovar;\n};\n\n/*\n * Normal helpers\n */\nDiscreteRV\ndiscretizeNormal(const double mean,\n    const double sigma,\n    const uword n_elem = 21,\n    const double pmSigma = pmSd,\n    bool cutTails = true);\nvec discretizeNormal(vec grid,\n    const double mean,\n    const double sigma,\n    bool cutTails = true);\n\n/*\n *\n * AR(1) process\n *\n */\nclass AR {\n  public:\n  inline double\n  intercept() const\n  {\n    return m_intercept;\n  }\n  inline double\n  rho() const\n  {\n    return m_rho;\n  }\n  inline double\n  sigma() const\n  {\n    return m_sigma;\n  }\n  inline double\n  stationaryMean() const\n  {\n    return m_intercept / (1.0 - m_rho);\n  }\n  inline double\n  stationarySigma() const\n  {\n    return m_sigma / std::sqrt(1.0 - m_rho * m_rho);\n  }\n  inline bool\n  stationaryQ() const\n  {\n    return std::abs(m_rho) < 1.0;\n  }\n\n  AR(double intercept, double rho, double sigma)\n      : m_intercept(intercept)\n      , m_rho(rho)\n      , m_sigma(sigma)\n  {\n  }\n\n  private:\n  double m_intercept;\n  double m_rho;\n  double m_sigma;\n};\n\n/*\n *\n * VAR(1) process\n *\n */\nclass VAR {\n  public:\n  inline uword\n  size() const\n  {\n    return m_size;\n  }\n  inline const vec&\n  intercept() const\n  {\n    return m_intercept;\n  }\n  inline const mat&\n  rho() const\n  {\n    return m_rho;\n  }\n  inline const mat&\n  sigma() const\n  {\n    return m_sigma;\n  }\n\n  const MvNormal conditional(vec& current) const;\n  vec& stationaryMean();\n  mat& stationarySigma();\n  bool stationaryQ();\n  void print();\n\n  VAR(vec intercept, mat rho, mat sigma)\n      : m_intercept(intercept)\n      , m_rho(rho)\n      , m_sigma(sigma)\n  {\n    m_size = intercept.n_elem;\n  }\n\n  private:\n  uword m_size;\n  vec m_intercept;\n  mat m_rho;\n  mat m_sigma;\n\n  vec m_statMean;\n  mat m_statSigma;\n  bool is_stationary;\n\n  void findStationary();\n};\n\n/*\n *\n * Orthogonalized VAR(1) and \"rotation\" matirx\n *\n */\nenum OrthoMethod { //\n  SVD,\n  Cholesky\n};\n\nclass OrthogonalizedVAR {\n  public:\n  inline const VAR&\n  getVAR() const\n  {\n    return m_ortho;\n  }\n  inline const VAR&\n  getOriginalVAR() const\n  {\n    return m_original;\n  }\n  inline const mat&\n  getSupportRotationMatrix() const\n  {\n    return LL;\n  }\n\n  OrthogonalizedVAR(VAR original, OrthoMethod method = OrthoMethod::Cholesky)\n      : m_original(original)\n      , m_ortho(original)\n  {\n    const mat mEye = eye(original.size(), original.size());\n    mat Atilde = original.intercept();\n    mat Btilde = original.rho();\n    mat GG = original.sigma();\n    vec DD = ones(original.size());\n    mat diagDD = mEye;\n    LL = mEye;\n\n    switch (method) {\n    case OrthoMethod::SVD: {\n      mat VV;\n      svd(LL, DD, VV, GG);\n\n      Atilde = LL.t() * original.intercept();\n      Btilde = LL.t() * original.rho() * LL;\n      diagDD = diagmat(DD);\n      break;\n    }\n    case OrthoMethod::Cholesky: {\n      LL = chol(GG, \"lower\");\n      mat invLL = inv(LL);\n\n      Atilde = invLL * original.intercept();\n      Btilde = invLL * original.rho() * LL;\n      break;\n    }\n    default: {\n      cout << \"Unknown method.\" << endl;\n      exit(1);\n    }\n    }\n\n    m_ortho = VAR(Atilde, Btilde, diagDD);\n  }\n\n  private:\n  VAR m_original;\n  VAR m_ortho;\n  mat LL;\n};\n\n/*\n *\n * Markov Chain\n *\n */\nrowvec\nstationaryDistribution(const mat& transitionMatrix);\n\nuvec simulateChain(const mat& transitionMatrix,\n    const uword initState,\n    const uword simSz);\n\nclass MarkovChain {\n  public:\n  inline uword\n  size() const\n  {\n    return m_size;\n  }\n\n  inline rowvec&\n  support()\n  {\n    return m_support;\n  }\n  inline const rowvec&\n  support() const\n  {\n    return m_support;\n  }\n\n  inline mat&\n  transition()\n  {\n    return m_tran;\n  }\n  inline const mat&\n  transition() const\n  {\n    return m_tran;\n  }\n\n  void save(std::string fname) const;\n  void print() const;\n\n  const rowvec& stationary();\n\n  MarkovChain() { }\n  MarkovChain(rowvec support, mat transition)\n      : m_support(support)\n      , m_tran(transition)\n  {\n    m_size = support.n_elem;\n  }\n  MarkovChain(const AR process,\n      const uword sz = 21,\n      const double pmMCsd = pmSd,\n      bool expSupport = false);\n\n  private:\n  uword m_size;\n  rowvec m_support;\n  rowvec m_stationary;\n  mat m_tran;\n};\n\n/*\n *\n * Discrete approximation of VAR(1)\n *\n */\nclass DiscreteVAR {\n  public:\n  inline uword\n  size() const\n  {\n    return m_size;\n  }\n  inline uword\n  flatSize() const\n  {\n    return m_flatSize;\n  }\n  inline uword\n  midIx() const\n  {\n    return m_midIx;\n  }\n  inline const vec\n  grid(uword varIx) const\n  {\n    return m_grids.col(varIx);\n  }\n  inline const rowvec\n  gridValues(uword ix) const\n  {\n    return m_grids.row(ix);\n  }\n  inline const mat\n  transition() const\n  {\n    return m_tran;\n  }\n  void save(std::string fname) const;\n  void print() const;\n\n  DiscreteVAR(const VAR var,\n      const uword supportSize,\n      bool trimGrids = true,\n      OrthoMethod mm = OrthoMethod::Cholesky)\n      : m_var(var)\n  {\n    m_supportSizes.set_size(m_var.size());\n    m_supportSizes.fill(supportSize);\n    impl(trimGrids, mm);\n  }\n\n  DiscreteVAR(const VAR var,\n      const uvec gridSizes,\n      bool trimGrids = true,\n      OrthoMethod mm = OrthoMethod::Cholesky)\n      : m_var(var)\n      , m_supportSizes(gridSizes)\n  {\n    impl(trimGrids, mm);\n  }\n\n  private:\n  VAR m_var;\n\n  uword m_size;\n  uword m_flatSize;\n  uword m_midIx;\n\n  mat m_grids;\n  uvec m_supportSizes;\n  mat m_tran;\n\n  void impl(bool trimGrids, OrthoMethod mm);\n};\n\n/*\n *\n * Discrete approximation to VAR(1) with common AR(1) stochastic volatility,\n * Basal-Yaron-like.\n *\n */\nclass DiscreteStochVolVAR {\n  public:\n  inline uword\n  size() const\n  {\n    return m_size;\n  }\n  inline uword\n  flatSize() const\n  {\n    return m_flatSize;\n  }\n  inline uword\n  midIx() const\n  {\n    return m_midIx;\n  }\n  inline const mat\n  transition() const\n  {\n    return m_tran;\n  }\n  inline const vec\n  grid(uword iIx) const\n  {\n    return m_grids.col(iIx);\n  }\n  inline const rowvec\n  gridValues(uword ix) const\n  {\n    return m_grids.row(ix);\n  }\n  void save(std::string fname) const;\n  void print() const;\n\n  DiscreteStochVolVAR(const VAR var,\n      const AR vol,\n      const uvec gridSizes,\n      const uword volGridSize,\n      bool trimGrids = true)\n      : m_var(var)\n      , m_vol(vol)\n      , m_supportSizes(gridSizes)\n      , m_volGridSize(volGridSize)\n  {\n    impl(trimGrids);\n  };\n\n  private:\n  VAR m_var;\n  AR m_vol;\n\n  uword m_size;\n  uword m_flatSize;\n  uword m_midIx;\n\n  mat m_grids;\n  mat m_tran;\n  uvec m_supportSizes;\n  uword m_volGridSize;\n\n  void impl(bool trimGrids);\n};\n\nvoid trimMarkovChain(mat& grids, mat& transition);\n\n} // namespace TimeSeries\n", "meta": {"hexsha": "d2b2ad8d8ad507eae5bedb7e2c39dc15c7281d76", "size": 6786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "TimeSeries.hpp", "max_stars_repo_name": "gabrielgggg/DiscretizeVAR", "max_stars_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "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": "TimeSeries.hpp", "max_issues_repo_name": "gabrielgggg/DiscretizeVAR", "max_issues_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "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": "TimeSeries.hpp", "max_forks_repo_name": "gabrielgggg/DiscretizeVAR", "max_forks_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T11:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T11:28:29.000Z", "avg_line_length": 15.8551401869, "max_line_length": 77, "alphanum_fraction": 0.6258473327, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6739922947808072}}
{"text": "#include \"mex.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include \"drakeMexUtil.h\"\n#include \"Polynomial.h\"\n\nusing namespace Eigen;\nusing namespace std;\n/*\n * c++ version of\n *     function xdot = dynamicsRHS(~,~,x,~)\n */\n\ntemplate <typename DerivedA, typename DerivedB>\nvoid dynamicsRHS(const MatrixBase<DerivedA> &x, MatrixBase<DerivedB> &xdot) \n{\n  xdot << x(1), -x(0)-x(1)*(x(0)*x(0)-1);\n}        \n        \nvoid mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] ) \n{\n  if (mxIsDouble(prhs[2])) {\n    Map<Vector2d> x(mxGetPrSafe(prhs[2]));\n    plhs[0] = mxCreateDoubleMatrix(2,1,mxREAL);\n    Map<Vector2d> xdot(mxGetPr(plhs[0]));\n    dynamicsRHS(x,xdot);\n  } else if (isa(prhs[2],\"msspoly\")) {\n    auto x = msspolyToEigen(prhs[2]);\n    Matrix< Polynomiald, 2, 1> xdot;\n    dynamicsRHS(x,xdot);\n//    cout << xdot << endl;\n    plhs[0] = eigenToMSSPoly<2,1>(xdot);\n//    plhs[0] = mxCreateDoubleMatrix(2,1,mxREAL);\n  } else {\n    mexErrMsgIdAndTxt(\"Drake:VanDerPolCpp:UnknownType\",\"don't know how to handle the datatype passed in for x (yet)\");\n  }\n}\n", "meta": {"hexsha": "febd442ef627b90a49b129864c5e16088935dec5", "size": 1092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/examples/@VanDerPolCpp/dynamicsRHS.cpp", "max_stars_repo_name": "jhu-asco/drake", "max_stars_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/examples/@VanDerPolCpp/dynamicsRHS.cpp", "max_issues_repo_name": "jhu-asco/drake", "max_issues_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "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": "drake/examples/@VanDerPolCpp/dynamicsRHS.cpp", "max_forks_repo_name": "jhu-asco/drake", "max_forks_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 28.0, "max_line_length": 118, "alphanum_fraction": 0.6446886447, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6739922926968567}}
{"text": "/*Copyright (c) 2020 James Gayvert\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#include <iostream>\n#include <vector>\n#include <math.h>\n#include \"overlap.h\"\n#include <cstdlib>\n#include \"utils.h\"\n#include \"BasisSet.h\"\n#include \"gto_ordering.h\"\n#include <Eigen/Dense>\n\n//overlap between pair of gaussians\ndouble gauss_integral(double exp_a,std::array<size_t, 3> cart_a,std::array<double,3> coord_a,\n\t\tdouble exp_b,std::array<size_t, 3> cart_b, std::array<double,3> coord_b)\n{\n\tstd::vector<double> integrals;\n\tfor(int i=0;i<3;i++)\n\t{\n\t\tdouble dist = coord_a[i]-coord_b[i];\n\t\tdouble res = mcmurchie_davidson(exp_a,exp_b,0,cart_a[i],cart_b[i],dist);\n\t\tintegrals.push_back(res);\n\t}\n\tdouble int_tot = 1.0;\n\tfor (unsigned int i=0;i<integrals.size();i++)\n\t{\n\t\tint_tot*=integrals[i];\n\t}\n\treturn int_tot*pow(M_PIl/(exp_a+exp_b),1.5);\n}\n\n//recursive formula for cartesian overlap distributions\ndouble mcmurchie_davidson(double exp_a, double exp_b, int t, int angmom_a, int angmom_b, double dist)\n{\n\tdouble p = exp_a + exp_b;\n\tdouble q = exp_a*exp_b/p;\n\tif (t<0 || t>(angmom_a+angmom_b))\n\t{\n\t\treturn 0.0;\n\t}\n\telse if(angmom_a==angmom_b && angmom_b==0)\n\t{\n\t\treturn exp(-q*dist*dist);\n\t}\n\telse if(angmom_b==0)\n\t{\n\t\t//decrement angmom_a\n\t\treturn(\n\t\t\t\t(1/(2*p))*mcmurchie_davidson(exp_a,exp_b,t-1,angmom_a-1,angmom_b,dist)   -\n\t\t\t\t(q*dist/exp_a)*mcmurchie_davidson(exp_a,exp_b,t,angmom_a-1,angmom_b,dist) +\n\t\t\t\t(t+1)*mcmurchie_davidson(exp_a,exp_b,t+1,angmom_a-1,angmom_b,dist));\n\t}\n\telse\n\t{\n\t\t//decrement angmom_b\n\t\treturn(\n\t\t\t\t(1/(2*p))*mcmurchie_davidson(exp_a,exp_b,t-1,angmom_a,angmom_b-1,dist)+\n\t\t\t\t(q*dist/exp_b)*mcmurchie_davidson(exp_a,exp_b,t,angmom_a,angmom_b-1,dist)+\n\t\t\t\t(t+1)*mcmurchie_davidson(exp_a,exp_b,t+1,angmom_a,angmom_b-1,dist));\n\t}\n}\n\n//overlap between two normalized, contracted gaussians\ndouble overlap_integral(Shell a, std::array<size_t,3> cart_a, Shell b,\n\t\tstd::array<size_t,3> cart_b)\n{\n\tdouble res = 0.0;\n\tfor(size_t i=0;i<a.num_prims;i++)\n\t{\n\t\tfor(size_t j=0;j<b.num_prims;j++)\n\t\t{\n\t\t\tres+=a.coeffs[i]*b.coeffs[j]*\n\t\t\tgauss_integral(a.exps[i],cart_a,a.origin,b.exps[j],cart_b,b.origin);\n\t\t}\n\t}\n\treturn res;\n}\n\nEigen::MatrixXd shell_overlap(Shell shell_a, Shell shell_b)\n{\n\tEigen::MatrixXd block(shell_a.num_carts(),shell_b.num_carts());\n\tstd::vector<std::array<size_t,3>> order_a = opencap_carts_ordering(shell_a.l);\n\tstd::vector<std::array<size_t,3>> order_b = opencap_carts_ordering(shell_b.l);\n\tfor(size_t i=0;i<shell_a.num_carts();i++)\n\t{\n\t\tstd::array<size_t,3> a_cart = order_a[i];\n\t\tfor(size_t j=0;j<shell_b.num_carts();j++)\n\t\t{\n\t\t\tstd::array<size_t,3> b_cart = order_b[j];\n\t\t\tblock(i,j) = overlap_integral(shell_a,a_cart, shell_b, b_cart);\n\t\t}\n\t}\n\treturn block;\n}\n\nvoid compute_analytical_overlap(BasisSet bs, Eigen::MatrixXd &Smat)\n{\n\tunsigned int row_idx = 0;\n\tfor(auto&shell1:bs.basis)\n\t{\n\t\tunsigned int col_idx = 0;\n\t\tfor(auto&shell2: bs.basis)\n\t\t{\n\t\t\tSmat.block(row_idx,col_idx,shell1.num_carts(),shell2.num_carts()) = shell_overlap(shell1,shell2);\n            col_idx += shell2.num_carts();\n\t\t}\n\t\trow_idx += shell1.num_carts();\n\t}\n}\n\n\n\n", "meta": {"hexsha": "939c34fb7b757d0e86dea994ef3286689dfde220", "size": 4048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/overlap.cpp", "max_stars_repo_name": "trex47/opencap", "max_stars_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencap/src/overlap.cpp", "max_issues_repo_name": "trex47/opencap", "max_issues_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencap/src/overlap.cpp", "max_forks_repo_name": "trex47/opencap", "max_forks_repo_head_hexsha": "fd641133b2abaab22c13912d97fe1fe64b132dd7", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 101, "alphanum_fraction": 0.7248023715, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6739830458261519}}
{"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 *  A Non-linear filter with one state and constant noises\n */\n\n// Use the Unscented filter scheme from Bayes++\n#include \"BayesFilter/unsFlt.hpp\"\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\nusing namespace Bayesian_filter;\nusing namespace Bayesian_filter_matrix;\n\n\n/*\n * Simple Prediction model\n */\nclass Simple_predict : public Linear_predict_model\n{\npublic:\n\tSimple_predict() : Linear_predict_model(1,1)\n\t// Construct a constant model\n\t{\n\t\t\t\t// Stationary Prediction model (Identity)\n\t\tFx(0,0) = 1.;\n\t\t\t\t// Constant Noise model with a large variance\n\t\tq[0] = 2.;\n\t\tG(0,0) = 1.;\n\t}\n};\n\n/*\n * Nonlinear Observation model\n * Observation is distance from origin squared\n */\nclass Nonlinear_observe : public Uncorrelated_additive_observe_model\n{\npublic:\n\tNonlinear_observe () : Uncorrelated_additive_observe_model(1), hx(1)\n\t// Construct a noise model\n\t{\n\t\t\t\t// Constant Observation Noise model with variance of one\n\t\tZv[0] = 1.;\n\t}\n\tconst FM::Vec& h(const FM::Vec& x) const\n\t{\n\t\thx[0] = x[0]*x[0];\n\t\treturn hx;\n\t}\n\tprivate:\n\t\tmutable FM::Vec hx;\n};\n\n\n/*\n * Filter a simple example\n */\nint main()\n{\n\t// Global setup for test output\n\tcout.flags(ios::fixed); cout.precision(4);\n\n\t// Construct simple Prediction and Observation models\n\tSimple_predict my_predict;\n\tNonlinear_observe my_observe;\n\n\t// Use an 'Unscented' filter scheme with one state\n\tUnscented_scheme my_filter(1);\n\n\t// Setup the initial state and covariance\n\tVec x_init (1); SymMatrix X_init (1, 1);\n\tx_init[0] = 10.;\t\t// Start at 10 with no uncertainty\n\tX_init(0,0) = 0.;\n\tmy_filter.init_kalman (x_init, X_init);\n\n\tcout << \"Initial  \" << my_filter.x << my_filter.X << endl;\n\n\t// Predict the filter forward\n\tmy_filter.predict (my_predict);\n\tmy_filter.update();\t\t// Update the filter, so state and covariance are available\n\n\tcout << \"Predict  \" << my_filter.x << my_filter.X << endl;\n\n\t// Make an observation\n\tVec z(1);\n\tz[0] = 11.;\t\t\t\t// Observe that we should be at 11\n\tmy_filter.observe (my_observe, z);\n\tmy_filter.update();\t\t// Update the filter to state and covariance are available\n\n\tcout << \"Filtered \" << my_filter.x << my_filter.X << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "aba22b7f5e6ee4074c73f291bdf87fb1b7e284e0", "size": 2392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NonLinearSimple/simpleNonLinearExample.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": "NonLinearSimple/simpleNonLinearExample.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": "NonLinearSimple/simpleNonLinearExample.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": 23.4509803922, "max_line_length": 81, "alphanum_fraction": 0.6998327759, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6739830387845763}}
{"text": "#include <state_estimation/filters/kalman_filter.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nvoid KalmanFilter::myPredict(const Eigen::VectorXd& u, double dt) {\n    system_model_->update(filter_state_.x, u, dt);\n\n    const Eigen::VectorXd Ax = system_model_->A() * filter_state_.x;\n    const Eigen::VectorXd Bu = system_model_->B() * u;\n    filter_state_.x = system_model_->addVectors(Ax, Bu);\n\n    filter_state_.covariance =\n        system_model_->A() * filter_state_.covariance * system_model_->A().transpose() +\n        system_model_->P() * system_model_->Rp() * system_model_->P().transpose() +\n        system_model_->V() * system_model_->Rc() * system_model_->V().transpose();\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"KF predicition update:\" << std::endl\n              << \"A=\" << std::endl\n              << printMatrix(system_model_->A()) << std::endl\n              << \"B=\" << std::endl\n              << printMatrix(system_model_->B()) << std::endl\n              << \"P=\" << std::endl\n              << printMatrix(system_model_->P()) << std::endl\n              << \"V=\" << std::endl\n              << printMatrix(system_model_->V()) << std::endl\n              << \"x=\" << filter_state_.x.transpose() << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\nvoid KalmanFilter::myCorrect(const Eigen::VectorXd& z,\n                             measurement_models::LinearMeasurementModel* model, double dt) {\n    // Update our measurement model\n    model->update(filter_state_.x, dt);\n\n    // Compute the Kalman gain\n    const Eigen::MatrixXd cov_C_T = filter_state_.covariance * model->C().transpose();\n    const Eigen::MatrixXd K = cov_C_T * (model->C() * cov_C_T + model->covariance()).inverse();\n\n    // Update the state and covariance with the measurement\n    const Eigen::MatrixXd I =\n        Eigen::MatrixXd::Identity(filter_state_.x.rows(), filter_state_.x.rows());\n    const Eigen::VectorXd z_pred = model->C() * filter_state_.x;\n    const Eigen::VectorXd dx = K * model->subtractVectors(z, z_pred);\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx);\n    filter_state_.covariance = (I - K * model->C()) * filter_state_.covariance;\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"KF measurement update:\" << std::endl\n              << \"C=\" << std::endl\n              << printMatrix(model->C()) << std::endl\n              << \"Q=\" << std::endl\n              << printMatrix(model->covariance()) << std::endl\n              << \"K=\" << std::endl\n              << printMatrix(K) << std::endl\n              << \"x=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\n}  // namespace state_estimation\n", "meta": {"hexsha": "f862184bc45b1fcda8093396d463c5f6cc172a5d", "size": 2880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/kalman_filter.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/filters/kalman_filter.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/filters/kalman_filter.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": 42.9850746269, "max_line_length": 95, "alphanum_fraction": 0.6017361111, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6739830196023068}}
{"text": "#include \"helper/bearing_vector.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nvoid create_bearing_vectors(const Mat33_t& rot_1, const Vec3_t& trans_1, const Mat33_t& rot_2, const Vec3_t& trans_2,\n                            const eigen_alloc_vector<Vec3_t>& landmarks, Mat33_t& E_21,\n                            eigen_alloc_vector<Vec3_t>& bearings_1, eigen_alloc_vector<Vec3_t>& bearings_2,\n                            double noise_stddev) {\n    const auto num_landmarks = landmarks.size();\n\n    // E\u884c\u5217\u3092\u6c42\u3081\u308b\n\n    const Mat33_t rot_21 = rot_2 * rot_1.inverse();\n    const Vec3_t trans_21 = trans_2 - rot_21 * trans_1;\n\n    Mat33_t skew_21;\n    skew_21 << 0, -trans_21(2), trans_21(1),\n               trans_21(2), 0, -trans_21(0),\n               -trans_21(1), trans_21(0), 0;\n\n    E_21 = skew_21 * rot_21;\n\n    // bearing vectors\u3092\u6c42\u3081\u308b\n\n    bearings_1.resize(num_landmarks);\n    bearings_2.resize(num_landmarks);\n    for (unsigned int i = 0; i < num_landmarks; ++i) {\n        const Vec3_t& lm = landmarks.at(i);\n\n        const Vec3_t lm_in_1 = rot_1 * lm + trans_1;\n        const Vec3_t lm_in_2 = rot_2 * lm + trans_2;\n\n        bearings_1.at(i) = lm_in_1.normalized();\n        bearings_2.at(i) = lm_in_2.normalized();\n    }\n\n    if (noise_stddev == 0.0) {\n        return;\n    }\n\n    // \u30ce\u30a4\u30ba\u3092\u8ffd\u52a0\n\n    std::random_device rand_dev;\n    std::mt19937 mt(rand_dev());\n    std::normal_distribution<> rand(0, noise_stddev);\n\n    for (unsigned int i = 0; i < num_landmarks; ++i) {\n        bearings_1.at(i) += Vec3_t{rand(mt), rand(mt), rand(mt)};\n        bearings_1.at(i).normalized();\n        bearings_2.at(i) += Vec3_t{rand(mt), rand(mt), rand(mt)};\n        bearings_2.at(i).normalized();\n    }\n}\n", "meta": {"hexsha": "01fcfa828cb729f251ca388f0f4fba599a8d5e91", "size": 1685, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/helper/bearing_vector.cc", "max_stars_repo_name": "Huweijian/openvslam", "max_stars_repo_head_hexsha": "98b6ee709a1bbb7cbbdda8bd169c7376f6761126", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-15T15:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T07:40:12.000Z", "max_issues_repo_path": "test/helper/bearing_vector.cc", "max_issues_repo_name": "Huweijian/openvslam", "max_issues_repo_head_hexsha": "98b6ee709a1bbb7cbbdda8bd169c7376f6761126", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "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/helper/bearing_vector.cc", "max_forks_repo_name": "Huweijian/openvslam", "max_forks_repo_head_hexsha": "98b6ee709a1bbb7cbbdda8bd169c7376f6761126", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-24T08:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-24T08:42:22.000Z", "avg_line_length": 30.6363636364, "max_line_length": 117, "alphanum_fraction": 0.6041543027, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6739467882125239}}
{"text": "/**\n *@file main.cpp\n */\n\n#include <fstream>\n#include <armadillo>\n#include \"HermitePolynomials.h\"\n#include \"Solution1DHO.h\"\n#include \"Orthonormality.h\"\n\n\n/**\n * @mainpage Calcul de l'\u00e9quation schr\u00f6dinger d'oscillateur harmonique \u00e0 une dimension\n *\n * # Equation de Schr\u00f6dinger\n * \\f[\\left(\\frac{\\hat{p}_{(z)}^2}{2m} + \\frac{1}{2}m\\omega^2\\hat{z}^2\\right)\\psi_n = E_n\\psi_n.\\f]\n *\n * # Solution forme de la fonction d'onde\n * \\f[\\psi_n(z) = \\frac{1}{\\sqrt{2^n n!}}\\left(\\frac{m\\omega}{\\pi\\hbar}\\right)^{1/4}e^{-\\frac{m\\omega z^2}{2\\hbar}}H_n\\left(\\sqrt{\\frac{m\\omega}{\\hbar}} . z\\right).\\f]\n */\n\n/**\n *La fonction principale\n *\n *Cette fonction a pour but de tester.\n *\n *@return la fonction toujours retourne 0.\n */\n\nint main()\n{\n    int i,j;\n    int a=-4, b=4, N=100;\n    int n=0;\n\n    Solution1DHO ex = Solution1DHO();\n\n    arma::mat A = arma::linspace(-4,4,100);\n    std::cout << \"Tracer la fonction d\\'onde pour n = \" << \"[\" << a << \" ,\" << b << \"] pour N =\" << N << std::endl<< std::endl;\n    ex.solutionToFile(0, A.t());\n    ex.drawSolution();\n\n\n    n = 4;\n    std::cout.precision(50);\n    for (i = 1; i<n; i++)\n    {\n        for (j = 1; j<n; j++)\n        {\n            std::cout << \"Test Orthonormality n = \" << i << \" m = \" << j << \" quadrature: \" << Orthonormality::quadrature(i, j) << std::endl;\n        }\n    }\n    std::cout << std::endl << std::endl;\n\n    N = 1000000;\n    n = 2;\n    for (i = 0; i<=n; i++)\n    {\n\n        std::cout<< \"La plage de valeur z: (-2,2) n: \"<< i << std::endl;\n        std::cout<< \"Nombre d'\u00e9chantillons: N = 1000000\" << std::endl;\n        std::cout<< \"E\" << i << \" (1-5): \";\n        arma::mat res;\n        res = ex.energy(i, -2, 2, N);\n        std::cout<< res.rows(0,4) << std::endl;\n\n        std::cout<<  \"E\" << i << \" (500100-500104): \" ;\n        std::cout<< res.rows(500099,500103) << std::endl;\n\n        std::cout<< \"E\" << i << \" (999995-1000000): \" ;\n        std::cout<< res.rows(999994,999999) << std::endl;\n\n    }\n\n\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "2dee224dbbe08ec0cb82d8edb7981507c596dddb", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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": 24.4567901235, "max_line_length": 167, "alphanum_fraction": 0.5189298334, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.8128673246376009, "lm_q1q2_score": 0.6738172851490475}}
{"text": "#include \"util.hpp\"\n#include <armadillo>\n\n\nnamespace util{\n  /*\n    For a discrete probability distribution Pi = p(i), returns the index\n    of an element randomly selected by sampling the distribution.\n\n    Examples:\n    * sample_discrete({0.5, 0.5}) returns 0 or 1 with probability 0.5\n    * sample_discrete({0.0, 0.0, 1.0}) returns 2 with probability 1.0\n\n    Note:\n    While there does exist std::discrete_distribution, I think that the\n    below implementation is superior in that it does not require\n    instantiating a new distribution for every round.\n  */\n  arma::uword sample_discrete(const arma::vec &p){\n    /*\n      Sanity checks; require:\n      * Pi >= 0 forall i\n      * Sum(Pi) == 1\n      */\n    std::string die = \"\";\n    const double eps = 1e-12;\n    if (p.has_nan()){die = \"P is malformed; it contains NaN!\";}\n    if (arma::any(p < -1 * eps)){die = \"P cannot have negative elements!\";}\n    if (std::abs(arma::sum(p) - 1) > eps){ die = \"P is not normed!\";}\n\n    if (die != \"\"){\n      p.t().print(\"P\");\n      throw std::logic_error(die);\n    }\n\n    const double zeta = arma::randu();\n    return as_scalar(arma::find(arma::cumsum(p) > zeta, 1));\n  }\n\n\n  // return a uvec with filled with the indices [a,b) like Python's\n  // range(); contrast arma::span(a,b) -> [a,b]\n  arma::uvec range(arma::uword a, arma::uword b){\n    if (a > b){\n      throw std::logic_error(\"cannot compute range with a > b\");\n    }\n\n    arma::uword N = b - a;\n    arma::uvec R(N, arma::fill::zeros);\n    for (arma::uword i = 0; i < N; i++){\n      R(i) = i + a;\n    }\n\n    return R;\n  }\n\n  // variant for [0, n)\n  arma::uvec range(arma::uword n){ return range(0, n); }\n\n\n  /*\n    std::hypot() for complex<double>\n\n    returns sqrt(|a|^2 + |b|^2)\n\n    I'm not sure what is the \"best\" sequence for the real() operations.\n    The present choice---to call real() twice, once after each\n    multiplication---was made because that's the first time the\n    operands mathematically lie on the real line. Waiting longer seemed\n    to invite the accumulation of small numerical deviations.\n  */\n  double hypot(std::complex<double> a, std::complex<double> b){\n    return std::sqrt(std::real(std::conj(a)*a) + std::real(std::conj(b)*b) );\n  }\n\n\n  arma::vec center_of_mass(const arma::mat &R, const arma::vec &m){\n    // R.B.: sum(A,1) gives the sum of the elements of each row of A\n    return arma::sum(R.each_row() % m.t(), 1) / arma::sum(m);\n  }\n\n  /*\n    For the (3xN) configuration space vectors A, B, compute the sum of\n    the cross products of the vectors in each column: Sum(Ai X Bi)\n  */\n  arma::vec sum_cross(const arma::mat &A, const arma::mat &B){\n    if ((A.n_cols != B.n_cols) || (3 != A.n_rows) || (3 != B.n_rows)){\n      throw std::logic_error(\"Invalid dimension!\");\n    }\n\n    arma::vec sum(3, arma::fill::zeros);\n\n    for (arma::uword i = 0; i < A.n_cols; i++){\n      sum += arma::cross(A.col(i), B.col(i));\n    }\n\n    return sum;  \n  }\n\n\n  /*\n    Implements Algorithm 3 from:\n    Loring, T. A. Computing a logarithm of a unitary matrix with\n    general spectrum. Numer. Linear Algebr. Appl. 2014, 21, 744\u2212760\n\n    It is required that the input matrix be approximately unitary.\n  */\n  arma::mat logmat_unitary(const arma::mat &U){\n    return arma::real(logmat_unitary(\n      arma::cx_mat(U, arma::zeros(arma::size(U)))\n                                     ));\n  }\n\n\n  arma::cx_mat logmat_unitary(const arma::cx_mat &U){\n    arma::cx_mat Q,T;\n    if ((arma::norm(U.t() * U - arma::eye(arma::size(U))) > 0.75) ||\n        !arma::schur(Q, T, U)){\n      std::cerr << \"Matrix deviates too much from unitary \"\n        \"or Schur Decomposition failed; \"\n        \"falling back to arma::logmat()\" << std::endl;\n      return arma::logmat(U);\n    }\n\n    arma::cx_mat D(arma::size(U), arma::fill::zeros);\n    D.diag() = arma::log(T.diag() / arma::abs(T.diag()));\n    arma::cx_mat L = Q * D * Q.t();\n\n    return L;\n  }\n\n\n  /*\n    Replace U with the closest unitary matrix according to the\n    transformation U' = (UU^T)^(-1/2)U.\n\n    For a thorough discussion, see:\n    https://en.wikipedia.org/wiki/Kabsch_algorithm\n    https://en.wikipedia.org/wiki/Polar_decomposition\n  */\n  void unitarize(arma::mat &U){\n    // arma::cx_mat R; arma::cx_vec s;\n    // arma::eig_gen(s, R, U*U.t());\n    // U = arma::real(R * diagmat(arma::pow(s, -0.5)) * R.t()) * U;\n\n    /*\n      These algorithms are equivalent but the below has better numerical\n      stability properties; namely the above returns 2*I for the\n      identity (I) rather than I itself.\n    */\n\n    arma::mat W,V; arma::vec s;\n    arma::svd(W,s,V,U);\n    U = W*V.t();\n  }\n}\n", "meta": {"hexsha": "fae50dd4926c9646e44b1ad84637ac18b3429c99", "size": 4604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util.cpp", "max_stars_repo_name": "INAQS/inaqs", "max_stars_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "src/util.cpp", "max_issues_repo_name": "INAQS/inaqs", "max_issues_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.cpp", "max_forks_repo_name": "INAQS/inaqs", "max_forks_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3248407643, "max_line_length": 77, "alphanum_fraction": 0.5977410947, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.6738172692068378}}
{"text": "#include <iostream>\n#include <cassert>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <CGAL/Triangulation_data_structure_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<int, K> Vb;\ntypedef CGAL::Triangulation_face_base_2<K> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Triangulation;\n\n// Note: the order that patterns evaluated in is important.\n// I don't fully understand why this specific order should work though.\nconst std::vector<std::vector<std::vector<int>>> patterns_by_k = {\n    {},\n    {},\n    {{0, 2}},\n    {{0, 1, 1}, {0, 3}, {0, 0, 2}},\n    {{0, 1, 0, 1}, {0, 2, 1}, {0, 4}, {0, 0, 2}, {0, 0, 1, 1}, {0, 0, 0, 2}},\n};\n\nstd::vector<int> determine_component_sizes(const Triangulation &triangulation, double s)\n{\n  const int n = triangulation.number_of_vertices();\n\n  boost::disjoint_sets_with_storage<> disjoint_sets(n);\n  for (auto it = triangulation.finite_edges_begin(); it != triangulation.finite_edges_end(); it++)\n  {\n    if (triangulation.segment(it).squared_length() < s)\n    {\n      int i1 = it->first->vertex((it->second + 1) % 3)->info();\n      int i2 = it->first->vertex((it->second + 2) % 3)->info();\n      disjoint_sets.union_set(i1, i2);\n    }\n  }\n\n  std::vector<int> component_sizes(n, 0);\n  for (int i = 0; i < n; i++)\n  {\n    component_sizes.at(disjoint_sets.find_set(i))++;\n  }\n\n  return component_sizes;\n}\n\nint count_max_families(const std::vector<int> &component_sizes, int k)\n{\n  const int max_counted_size = 4;\n  assert(k <= max_counted_size);\n  assert(k >= 1 && k <= 4);\n\n  std::vector<int> counts_by_size(max_counted_size + 1);\n  for (const int size : component_sizes)\n  {\n    counts_by_size.at(std::min(size, max_counted_size))++;\n  }\n\n  for (int i = 0; i <= max_counted_size; i++)\n  {\n    DEBUG(3, \"counts_by_size.at(\" << i << \") = \" << counts_by_size.at(i));\n  }\n\n  int f = 0;\n  for (int i = k; i <= max_counted_size; i++)\n  {\n    f += counts_by_size.at(i);\n    counts_by_size.at(i) = 0;\n  }\n\n  for (const std::vector<int> &pattern : patterns_by_k.at(k))\n  {\n    int matches = std::numeric_limits<int>::max();\n    for (int i = 0; i < int(pattern.size()); i++)\n    {\n      int required = pattern.at(i);\n      assert(required >= 0);\n      if (required > 0)\n      {\n        matches = std::min(matches, counts_by_size.at(i) / required);\n      }\n    }\n\n    if (matches > 0)\n    {\n      for (int i = 0; i < int(pattern.size()); i++)\n      {\n        const int used_count = pattern.at(i) * matches;\n        assert(counts_by_size.at(i) >= used_count);\n        counts_by_size.at(i) -= used_count;\n      }\n      f += matches;\n    }\n  }\n\n  DEBUG(3, \"f \" << f);\n\n  return f;\n}\n\nlong find_upper_bound(std::function<bool(long)> is_match)\n{\n  assert(is_match(0));\n  int base = 0;\n  while (is_match(1L << base))\n  {\n    base++;\n  }\n\n  long low = base == 0 ? 0 : 1L << (base - 1);\n  long high = 1L << base;\n  while (low < high)\n  {\n    long mid = (low + high) / 2;\n    if (is_match(mid))\n    {\n      low = mid + 1;\n    }\n    else\n    {\n      high = mid;\n    }\n  }\n\n  assert(is_match(low - 1) && !is_match(low));\n  return low - 1;\n}\n\nvoid testcase()\n{\n  int n, k, f_0;\n  double s_0;\n  std::cin >> n >> k >> f_0 >> s_0;\n  assert(n >= 2 && n <= 9e4 && k >= 1 && k <= 4 && f_0 >= 2 && k * f_0 <= n && s_0 >= 0 && s_0 <= (1L << 50));\n\n  std::vector<std::pair<K::Point_2, int>> tent_locations;\n  for (int i = 0; i < n; i++)\n  {\n    double x, y;\n    std::cin >> x >> y;\n    assert(abs(x) < (1 << 24) && abs(y) < (1 << 24));\n    tent_locations.push_back(std::make_pair(K::Point_2(x, y), i));\n  }\n\n  Triangulation triangulation;\n  triangulation.insert(tent_locations.begin(), tent_locations.end());\n\n  double s = find_upper_bound([&triangulation, f_0, k](long s_query) {\n    return count_max_families(determine_component_sizes(triangulation, s_query), k) >= f_0;\n  });\n\n  int f = count_max_families(determine_component_sizes(triangulation, s_0), k);\n\n  std::cout << s << \" \" << f << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::fixed << std::setprecision(0);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "da52c30405b254307545302abb8158901e4fd8b3", "size": 4644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-11/hand/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-11/hand/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-11/hand/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["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.5164835165, "max_line_length": 110, "alphanum_fraction": 0.6007751938, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760996, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6737237209276147}}
{"text": "#include <Eigen/Core>\n\nEigen::Vector3d reflect(const Eigen::Vector3d & in, const Eigen::Vector3d & n)\n{\n  ////////////////////////////////////////////////////////////////////////////\n  Eigen::Vector3d r = in - 2 * (in.dot(n)) * n; // reflection direction vector\n  return r.normalized();\n  ////////////////////////////////////////////////////////////////////////////\n}\n", "meta": {"hexsha": "5893c15b1b1632a098c55ff56d00368d6e6bced9", "size": 368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reflect.cpp", "max_stars_repo_name": "ericpko/computer-graphics-ray-tracing", "max_stars_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_stars_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-ray-tracing", "max_issues_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_issues_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-ray-tracing", "max_forks_repo_head_hexsha": "033293a94a5076c79c1fc7d3dac8931fdab6a44c", "max_forks_repo_licenses": ["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.8, "max_line_length": 78, "alphanum_fraction": 0.3831521739, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6736845792821224}}
{"text": "#include \"finiteelement.h\"\r\n\r\n#include <Eigen/Eigen>\r\n\r\n\r\nFiniteElement::FiniteElement(const Eigen::MatrixXd& V, const Eigen::VectorXi& indices, const Eigen::VectorXi& faces, double shear, double bulk)\r\n: Element(V, indices, faces), _volume(1.0), _shear(shear), _bulk(bulk)\r\n{\r\n}\r\n\r\nFiniteElement::~FiniteElement()\r\n{\r\n\r\n}\r\n\r\nvoid FiniteElement::compute(const Eigen::MatrixXd& V, const Eigen::MatrixXd& ext)\r\n{\r\n\tconst Eigen::MatrixXd x = extract(V);\r\n\tconst Eigen::MatrixXd f = extract(ext);\r\n\r\n\t_F = compute_F(x);\r\n\t_E = compute_E(_F);\r\n\t_energy = compute_U(_E) - f.cwiseProduct(x - _X).sum();\r\n\r\n\tassert(_energy >= 0.0 && \"Energy should always be positive.\");\r\n\r\n\tconst Tensor dFdx = compute_dFdx(x);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(_E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(_F);\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\tconst Eigen::MatrixXd dUdx = compute_dUdx(dUdF, dFdx);\r\n\t_G = dUdx - f;\r\n\r\n#ifdef COMPUTE_FINITE_DIFFERENCE\r\n\t_fG = diffTestG(x, 0.0001) - f;\r\n#endif\r\n}\r\n\r\ndouble FiniteElement::diffTest(const Eigen::MatrixXd& V, double h)\r\n{\r\n\tEigen::MatrixXd x = extract(V);\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst double e = compute_U(E);\r\n\r\n\t// Compute first derivatives\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\tconst Tensor dFdx = compute_dFdx(x);\r\n\r\n\tconst Eigen::MatrixXd hdUdE = diffTestdUdE(E, h);\r\n\tconst Eigen::MatrixXd hdEdF = diffTestdEdF(F, h);\r\n\tconst Tensor hdFdx = diffTestdFdx(x, h);\r\n\r\n\t// Compute gradient\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\tconst Eigen::MatrixXd dUdx = compute_dUdx(dUdF, dFdx);\r\n\r\n\tconst Eigen::MatrixXd hdUdF = diffTestdUdF(F, h);\r\n\tconst Eigen::MatrixXd hdUdx = diffTestdUdx(x, h);\r\n\r\n\t// Compute second derivatives\r\n\tconst Eigen::MatrixXd ddFddx = compute_ddFddx(x);\r\n\tconst Eigen::MatrixXd ddEddF = compute_ddEddF(F);\r\n\tconst Tensor ddUddE = compute_ddUddE(E);\r\n\r\n\tconst Eigen::MatrixXd hddEddF = diffTestddEddF(F, h);\r\n\tconst Tensor hddUddE = diffTestddUddE(E, h);\r\n\r\n\t// Compute Hessian\r\n\tconst Eigen::MatrixXd ddUdEdF = compute_ddUdEdF(dEdF, ddUddE);\r\n\tconst Eigen::MatrixXd ddUddF = compute_ddUddF(dEdF, ddUdEdF, ddEddF, dUdE);\r\n\tconst Eigen::MatrixXd ddUdFdx = compute_ddUdFdx(dFdx, ddUddF);\r\n\tconst Tensor ddUddx = compute_ddUddx(dFdx, ddUdFdx, ddFddx, dUdF);\r\n\r\n\t//const Tensor ddUdFdxT = diffTestddUdFdxT(x, h);\r\n\r\n\tconst Eigen::MatrixXd hddUdEdF = diffTestddUdEdF(F, h);\r\n\tconst Eigen::MatrixXd hddUddF = diffTestddUddF(F, h);\r\n\tconst Eigen::MatrixXd hddUdFdx = diffTestddUdFdx(x, h);\r\n\tconst Tensor hddUddx = diffTestddUddx(x, h);\r\n\r\n\t//std::cout << \"....................\" << std::endl;\r\n\t//std::cout << ddUddx.flatten() << std::endl;\r\n\t//std::cout << \"- - - - - - - -\" << std::endl;\r\n\t//std::cout << hddUddx.flatten() << std::endl;\r\n\t//std::cout << ddUddx.toString() << std::endl;\r\n\t//std::cout << \"- - - - - - - -\" << std::endl;\r\n\t//std::cout << hddUddx.toString() << std::endl;\r\n\r\n\tdouble err = 0.0;\r\n\t//err += (dFdx - hdFdx).squaredNorm();\r\n\t//err += (dEdF - hdEdF).squaredNorm();\r\n\t//err += (dUdE - hdUdE).squaredNorm();\r\n\t//err += (dUdF - hdUdF).squaredNorm();\r\n\terr += (dUdx - hdUdx).squaredNorm();\r\n\t//err += (ddEddF - hddEddF).squaredNorm();\r\n\t//err += (ddUddE - hddUddE).squaredNorm();\r\n\t//err += (ddUddF - hddUddF).squaredNorm();\r\n\t//err += (ddUdFdx - hddUdFdx).squaredNorm();\r\n\t//err += (ddUddx - hddUddx).squaredNorm();\r\n\r\n\treturn err;\r\n}\r\n\r\n/////////////////////////////////////////////////////\r\n\r\n\r\n\r\nTensor FiniteElement::diffTestdFdx(const Eigen::MatrixXd& x, double h) const\r\n{\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\r\n\tTensor fF(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hx = x;\r\n\t\t\thx(i, j) += h;\r\n\r\n\t\t\tconst Rotation hF = compute_F(hx);\r\n\t\t\tfF[i][j] = (hF - F) / h;\r\n\t\t}\r\n\t}\r\n\treturn fF;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestdEdF(const Eigen::MatrixXd& F, double h) const\r\n{\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\r\n\tTensor fE(F.rows(), F.cols());\r\n\tfor (int i = 0; i < F.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < F.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hF = F;\r\n\t\t\thF(i, j) += h;\r\n\r\n\t\t\tconst Rotation hE = compute_E(hF);\r\n\t\t\tfE[i][j] = (hE - E) / h;\r\n\t\t}\r\n\t}\r\n\treturn fE * Eigen::MatrixXd::Identity(F.rows(), F.cols());\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestdUdE(const Eigen::MatrixXd& E, double h) const\r\n{\r\n\tconst double e = compute_U(E);\r\n\r\n\tEigen::MatrixXd fU = Eigen::MatrixXd::Zero(E.rows(), E.cols());\r\n\tfor (int i = 0; i < E.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < E.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hE = E;\r\n\t\t\thE(i, j) += h;\r\n\r\n\t\t\tfU(i, j) = (compute_U(hE) - e) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestdUdF(const Eigen::MatrixXd& F, double h) const\r\n{\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst double e = compute_U(E);\r\n\r\n\tEigen::MatrixXd fU = Eigen::MatrixXd::Zero(F.rows(), F.cols());\r\n\tfor (int i = 0; i < F.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < F.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hF = F;\r\n\t\t\thF(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tfU(i, j) = (compute_U(hE) - e) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestdUdx(const Eigen::MatrixXd& x, double h) const\r\n{\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst double e = compute_U(E);\r\n\r\n\tEigen::MatrixXd fU = Eigen::MatrixXd::Zero(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hx = x;\r\n\t\t\thx(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hF = compute_F(hx);\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tfU(i, j) = (compute_U(hE) - e) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\n\r\nEigen::MatrixXd FiniteElement::diffTestddEddF(const Eigen::MatrixXd& F, double h) const\r\n{\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\r\n\tTensor fE(F.rows(), F.cols());\r\n\tfor (int i = 0; i < F.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < F.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hF = F;\r\n\t\t\thF(i, j) += h;\r\n\r\n\t\t\tconst Rotation hdEdF = compute_dEdF(hF);\r\n\t\t\tfE[i][j] = (hdEdF - dEdF) / h;\r\n\t\t}\r\n\t}\r\n\treturn fE * Eigen::MatrixXd::Identity(F.rows(), F.cols());\r\n}\r\n\r\nTensor FiniteElement::diffTestddUddE(const Eigen::MatrixXd& E, double h) const\r\n{\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\r\n\tTensor fU(E.rows(), E.cols());\r\n\tfor (int i = 0; i < E.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < E.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hE = E;\r\n\t\t\thE(i, j) += h;\r\n\r\n\t\t\tconst Rotation hdUdE = compute_dUdE(hE);\r\n\t\t\tfU[i][j] = (hdUdE - dUdE) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestddUdEdF(const Eigen::MatrixXd& F, double h) const\r\n{\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\r\n\tTensor fU(F.rows(), F.cols());\r\n\tfor (int i = 0; i < F.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < F.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hF = F;\r\n\t\t\thF(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdE = compute_dUdE(hE);\r\n\t\t\tfU(i, j) = (hdUdE - dUdE) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU * Eigen::MatrixXd::Identity(F.rows(), F.cols());\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestddUddF(const Eigen::MatrixXd& F, double h) const\r\n{\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\r\n\tTensor fU(F.rows(), F.cols());\r\n\tfor (int i = 0; i < F.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < F.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hF = F;\r\n\t\t\thF(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdE = compute_dUdE(hE);\r\n\t\t\tconst Eigen::MatrixXd hdEdF = compute_dEdF(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdF = compute_dUdF(hdUdE, hdEdF);\r\n\t\t\tfU(i, j) = (hdUdF - dUdF) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU * Eigen::MatrixXd::Identity(F.rows(), F.cols());\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::diffTestddUdFdx(const Eigen::MatrixXd& x, double h) const\r\n{\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\r\n\tTensor fU(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hx = x;\r\n\t\t\thx(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hF = compute_F(hx);\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdE = compute_dUdE(hE);\r\n\t\t\tconst Eigen::MatrixXd hdEdF = compute_dEdF(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdF = compute_dUdF(hdUdE, hdEdF);\r\n\t\t\tfU(i, j) = (hdUdF - dUdF) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU * Eigen::MatrixXd::Identity(F.rows(), F.cols());\r\n}\r\n\r\nTensor FiniteElement::diffTestddUdFdxT(const Eigen::MatrixXd& x, double h) const\r\n{\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\r\n\tTensor fU(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hx = x;\r\n\t\t\thx(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hF = compute_F(hx);\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdE = compute_dUdE(hE);\r\n\t\t\tconst Eigen::MatrixXd hdEdF = compute_dEdF(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdF = compute_dUdF(hdUdE, hdEdF);\r\n\t\t\tfU(i, j) = (hdUdF - dUdF) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\nTensor FiniteElement::diffTestddUddx(const Eigen::MatrixXd& x, double h) const\r\n{\r\n\tconst Eigen::MatrixXd F = compute_F(x);\r\n\tconst Eigen::MatrixXd E = compute_E(F);\r\n\tconst Eigen::MatrixXd dUdE = compute_dUdE(E);\r\n\tconst Eigen::MatrixXd dEdF = compute_dEdF(F);\r\n\tconst Tensor dFdx = compute_dFdx(x);\r\n\tconst Eigen::MatrixXd dUdF = compute_dUdF(dUdE, dEdF);\r\n\tconst Eigen::MatrixXd dUdx = compute_dUdx(dUdF, dFdx);\r\n\r\n\tTensor fU(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tEigen::MatrixXd hx = x;\r\n\t\t\thx(i, j) += h;\r\n\r\n\t\t\tconst Eigen::MatrixXd hF = compute_F(hx);\r\n\t\t\tconst Eigen::MatrixXd hE = compute_E(hF);\r\n\t\t\tconst Eigen::MatrixXd hdUdE = compute_dUdE(hE);\r\n\t\t\tconst Eigen::MatrixXd hdEdF = compute_dEdF(hF);\r\n\t\t\tconst Tensor hdFdx = compute_dFdx(hx);\r\n\t\t\tconst Eigen::MatrixXd hdUdF = compute_dUdF(hdUdE, hdEdF);\r\n\t\t\tconst Eigen::MatrixXd hdUdx = compute_dUdx(hdUdF, hdFdx);\r\n\t\t\tfU(i, j) = (hdUdx - dUdx) / h;\r\n\t\t}\r\n\t}\r\n\treturn fU;\r\n}\r\n\r\n/////////////////////////////////////////////////////\r\n\r\n\r\nTensor FiniteElement::compute_dFdx(const Eigen::MatrixXd& x) const\r\n{\r\n\tTensor out(x.rows(), x.cols());\r\n\tfor (int i = 0; i < x.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < x.cols(); j++)\r\n\t\t{\r\n\t\t\tout[i][j] = compute_dFdx(x, i, j);\r\n\t\t}\r\n\t}\r\n\treturn out;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::compute_dUdx(const Eigen::MatrixXd& dUdF, const Tensor& dFdx) const\r\n{\r\n\treturn dFdx * dUdF;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::compute_dUdF(const Eigen::MatrixXd& dUdE, const Eigen::MatrixXd& dEdF) const\r\n{\r\n\treturn dEdF.transpose() * dUdE;\r\n}\r\n\r\n\r\nTensor FiniteElement::compute_ddUddx(const Tensor& dFdx, const Eigen::MatrixXd& ddUdFdx, const Eigen::MatrixXd& ddFddx, const Eigen::MatrixXd& dUdF) const\r\n{\r\n\treturn dFdx.mult(ddUdFdx);// +ddFddx.transpose() * dUdF; // dFdx was constant, second derivative should therefore be 0\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::compute_ddUdFdx(const Tensor& dFdx, const Eigen::MatrixXd& ddUddF) const\r\n{\r\n\treturn dFdx * ddUddF;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::compute_ddUddF(const Eigen::MatrixXd& dEdF, const Eigen::MatrixXd& ddUdEdF, const Eigen::MatrixXd& ddEddF, const Eigen::MatrixXd& dUdE) const\r\n{\r\n\treturn dEdF.transpose() * ddUdEdF + ddEddF.transpose() * dUdE;\r\n}\r\n\r\nEigen::MatrixXd FiniteElement::compute_ddUdEdF(const Eigen::MatrixXd& dEdF, const Tensor& ddUddE) const\r\n{\r\n\treturn ddUddE * dEdF.transpose();\r\n}\r\n\r\n/////////////////////////////////////////////////////", "meta": {"hexsha": "a3cbae77a0785a480d3773b8a9833fb122e2de76", "size": 12172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/finiteelement.cpp", "max_stars_repo_name": "AngryLizard/BendyPrint", "max_stars_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_stars_repo_licenses": ["MIT"], "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/finiteelement.cpp", "max_issues_repo_name": "AngryLizard/BendyPrint", "max_issues_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_issues_repo_licenses": ["MIT"], "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/finiteelement.cpp", "max_forks_repo_name": "AngryLizard/BendyPrint", "max_forks_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_forks_repo_licenses": ["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.64, "max_line_length": 173, "alphanum_fraction": 0.6159217877, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.673684567310671}}
{"text": "#ifndef EUCLIDEAN_HPP\n#define EUCLIDEAN_HPP\n\n#include <algorithm>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <tuple>\n\n#include \"big_int_type.hpp\"\n\nbig_int gcd(big_int a, big_int b);\n\nbig_int gcd_iter(big_int num1, big_int num2);\n\nbig_int euclides_extended(big_int a, big_int b, big_int &x, big_int &y);\n\n#endif", "meta": {"hexsha": "16c8c848723c27d128d848864f0ec2cd651f7db3", "size": 320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/euclidean.hpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/euclidean.hpp", "max_issues_repo_name": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/euclidean.hpp", "max_forks_repo_name": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 72, "alphanum_fraction": 0.775, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6736561725811414}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"Optimizer/ceres/LocalParameterization.h\"\n#include \"Math.h\"\n\nnamespace VISFS {\nnamespace Optimizer {\n\nbool PoseLocalParameterization::Plus(const double * x, const double * delta, double * x_plus_delta) const {\n    Eigen::Map<const Eigen::Vector3d> _p(x);\n    Eigen::Map<const Eigen::Quaterniond> _q(x + 3);\n    Eigen::Map<const Eigen::Vector3d> dp(delta);\n    Eigen::Quaterniond dq = deltaQ(Eigen::Map<const Eigen::Vector3d>(delta + 3));\n\n    Eigen::Map<Eigen::Vector3d> p(x_plus_delta);\n    Eigen::Map<Eigen::Quaterniond> q(x_plus_delta + 3);\n\n    p = _p + dp;\n    q = (dq * _q).normalized();\n    \n    return true;\n}\n\nbool PoseLocalParameterization::ComputeJacobian(const double * x, double * jacobian) const {\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> j(jacobian);\n    j.topRows<6>().setIdentity();\n    j.bottomRows<1>().setZero();\n\n    return true;\n}\n\nbool PointLocalParameterization::Plus(const double * x, const double * delta, double * x_plus_delta) const {\n    Eigen::Map<const Eigen::Vector3d> _p(x);\n    Eigen::Map<const Eigen::Vector3d> dp(delta);\n\n    Eigen::Map<Eigen::Vector3d> p(x_plus_delta);\n    p = _p + dp;\n    \n    return true;\n}\n\nbool PointLocalParameterization::ComputeJacobian(const double * x, double * jacobian) const {\n    Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> j(jacobian);\n    j.topRows<3>().setIdentity();\n\n    return true;\n}\n\n}\t// Optimizer\n}\t// VISFS", "meta": {"hexsha": "03d2f0e6633b4f2498ba34688507555d7fd8df33", "size": 1475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "corelib/src/Optimizer/ceres/LocalParameterization.cpp", "max_stars_repo_name": "supersaiyajinggod/VISFS", "max_stars_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T13:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T13:31:11.000Z", "max_issues_repo_path": "corelib/src/Optimizer/ceres/LocalParameterization.cpp", "max_issues_repo_name": "supersaiyajinggod/VISFS", "max_issues_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "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": "corelib/src/Optimizer/ceres/LocalParameterization.cpp", "max_forks_repo_name": "supersaiyajinggod/VISFS", "max_forks_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "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.9215686275, "max_line_length": 108, "alphanum_fraction": 0.6766101695, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6736561588044109}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nusing namespace boost::numeric::ublas;\n\n#include <random>\n#include <stdio.h>\n\nvoid fill_u(matrix<double> & U, vector<double> & d) {\n  U.clear();\n  d.clear();\n\n  std::default_random_engine generator;\n  std::uniform_real_distribution<double> distribution(0.0,1.0);\n\n\n\n  for (unsigned i=0; i < U.size1(); ++i) {\n    U(i,i) = 1.0;\n    for (unsigned j=i+1; j < U.size2(); ++j) {\n      U(i,j) = distribution(generator);\n    }\n  }\n\n  for (unsigned i=0; i < d.size(); ++i) {\n    d(i) = distribution(generator);\n  }\n\n}\n\nvoid udu(matrix<double> &M, matrix<double> &U, vector<double> &d, unsigned int state_size) {\n  // this method stolen from pykalman.sqrt.bierman by Daniel Duckworth (BSD license)\n  /*Construct the UDU' decomposition of a positive, semidefinite matrix M\n\n    Parameters\n    ----------\n    M : [n, n] array\n        Matrix to factorize\n\n    Returns\n    -------\n    UDU : UDU_decomposition of size n\n        UDU' representation of M\n  */\n\n  unsigned int n = state_size;\n\n  // make M upper triangular: not sure if this is necessary?\n  for (unsigned i=0; i < n; ++i) {\n    for (unsigned j=0; j < i; ++j) {\n      M(i,j) = 0;\n    }\n  }\n\n  d.clear();\n  U.clear();\n  for (unsigned i=0; i < n; ++i) {\n    U(i,i) = 1;\n  }\n\n  for (unsigned j=n; j >= 2; --j) {\n    d(j - 1) = M(j - 1, j - 1);\n    double alpha = 0.0;\n    double beta = 0.0;\n    if (d(j - 1) > 0) {\n      alpha = 1.0 / d(j - 1);\n    } else {\n      if (fabs(d(j-1) > 1e-5) ) {\n\tprintf(\"WARNING: nonpositive d[%d] %f in udu decomp\\n\", j-1, d(j-1));\n\texit(-1);\n      }\n      d(j-1) = 0.0;\n      alpha = 0.0;\n    }\n    for (unsigned k=1; k < j; ++k) {\n      beta = M(k - 1, j - 1);\n      U(k - 1, j - 1) = alpha * beta;\n\n      // M[0:k, k - 1] = M[0:k, k - 1] - beta * U[0:k, j - 1]\n      for (unsigned kk=0; kk < k; ++kk) {\n\tM(kk, k - 1) = M(kk, k - 1) - beta * U(kk, j - 1);\n      }\n    }\n  }\n  d(0) = M(0, 0);\n\n  if (d(0) < 0) {\n    printf(\"ERROR: udu decomposition on non-posdef matrix with M(0,0)=%f\\n\", M(0,0));\n    exit(-1);\n  }\n}\n\nvoid udu_ptr(matrix<double> &M_mat, matrix<double> &U_mat, vector<double> &d_vec, unsigned int state_size) {\n\n  unsigned int n = M_mat.size1();\n  double *M = &(M_mat(0,0));\n  double *U = &(U_mat(0,0));\n  double *d = &(d_vec(0));\n\n  // this method stolen from pykalman.sqrt.bierman by Daniel Duckworth (BSD license)\n  /*Construct the UDU' decomposition of a positive, semidefinite matrix M\n\n    Parameters\n    ----------\n    M : [n, n] array\n        Matrix to factorize\n\n    Returns\n    -------\n    UDU : UDU_decomposition of size n\n        UDU' representation of M\n  */\n\n\n\n  // make M upper triangular: not sure if this is necessary?\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned idx=i*n; idx < i*n+i; ++idx) {\n      M[idx] = 0;\n    }\n  }\n\n  // initialize U as the identity\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned idx=i*n; idx < i*n+state_size; ++idx) {\n      U[idx] = 0;\n    }\n  }\n  for (unsigned i=0; i < state_size; ++i) {\n    U[i*n+i] = 1;\n  }\n\n  for (unsigned j=state_size-1; j >= 1; --j) {\n    d[j] = M[j*n+j];\n    double alpha = 0.0;\n    double beta = 0.0;\n    if (d[j] > 0) {\n      alpha = 1.0 / d[j];\n    } else {\n      if (fabs(d[j] > 1e-5) ) {\n\tprintf(\"WARNING: nonpositive d[%d] %f in udu decomp\\n\", j, d[j]);\n\texit(-1);\n      }\n      d[j] = 0.0;\n      alpha = 0.0;\n    }\n    for (unsigned k=0; k < j; ++k) {\n      beta = M[k*n+ j ];\n      U[k*n+ j] = alpha * beta;\n      for (unsigned kk=0; kk <= k; ++kk) {\n\tM[kk*n+ k] = M[kk*n+k] - beta * U[kk*n+j];\n      }\n    }\n  }\n  d[0] = M[0];\n\n  if (d[0] < 0) {\n    printf(\"ERROR: udu decomposition on non-posdef matrix with M(0,0)=%f\\n\", M[0]);\n    exit(-1);\n  }\n}\n\n\nvoid compute_explicit_cov(matrix<double> &U,\n\t\t\t  vector<double> &d,\n\t\t\t  matrix<double> &mtmp,\n\t\t\t  matrix<double> &P) {\n\n  unsigned int n = d.size();\n\n  // construct the cov matrix\n  for (unsigned i=0; i < n; ++i) {\n    subrange(mtmp, 0, n, i, i+1) = subrange(U, 0, n, i, i+1);\n    subrange(mtmp, 0, n, i, i+1) *= d(i);\n  }\n  noalias(subrange(P, 0, n, 0, n))\t\t\\\n    = prod(subrange(mtmp, 0, n, 0, n),\n\t   trans(subrange(U, 0, n, 0, n)));\n}\n\nvoid cov_by_hand(matrix<double> &U,\n\t\t vector<double> &d,\n\t\t matrix<double> &mtmp,\n\t\t matrix<double> &P) {\n  unsigned int n = d.size();\n\n  for (unsigned i=0; i < n; ++i) {\n    for (unsigned j=0; j < n; ++j) {\n      double accum = 0;\n      for (unsigned k=0; k < n; ++k) {\n\taccum += U(i, k)* U(j,k) * d(k);\n      }\n      P(i,j) = accum;\n    }\n  }\n}\n\n\n#include <cblas.h>\nvoid cov_atlas(matrix<double> &U,\n\t       vector<double> &d,\n\t       matrix<double> &mtmp,\n\t       matrix<double> &P,\n\t       int state_size,\n\t       int prev_state_size) {\n  unsigned int n = d.size();\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned j=0; j < prev_state_size; ++j) {\n      mtmp(i,j) = U(i,j) * d(j);\n    }\n  }\n\n  cblas_dgemm(CblasRowMajor,\n\t      CblasNoTrans,\n\t      CblasTrans,\n\t      state_size,  prev_state_size, state_size, 1.0,\n\t      &(mtmp(0,0)), mtmp.size2(),\n\t      &(U(0,0)), U.size2(),\n\t      0.0, &(P(0,0)), P.size2());\n\n\n  /*\nProblem with the triangular case:\n    After transition, U is not triangular in general. In fact it's not square in general...\n   */\n}\n\nvoid write_mat_col(const char *fname, const matrix<double> & m) {\n\n  FILE *f = fopen(fname, \"w\");\n  if (f == NULL)\n    {\n      printf(\"Error opening file!\\n\");\n      exit(1);\n    }\n\n  for(unsigned i=0; i < m.size1(); ++i) {\n    for(unsigned j=0; j < m.size2(); ++j) {\n      fprintf(f, \"%.12f \", m(i,j));\n    }\n    fprintf(f, \"\\n\");\n  }\n  fprintf(f, \"\\n\");\n\n  fclose(f);\n}\n\nbool matrix_eq(matrix<double> &m1, matrix<double> &m2, double tol) {\n  for(unsigned i=0; i < m1.size1(); ++i) {\n    for(unsigned j=0; j < m1.size2(); ++j) {\n      if (fabs(m1(i,j) - m2(i,j)) > tol) {\n\tprintf(\"unequal\\n\");\n\treturn false;\n      }\n    }\n  }\n  printf(\"equal\\n\");\n  return true;\n}\n\nint main() {\n\n  int n = 150;\n  int iters = 100;\n\n  matrix<double> U(n, n);\n  matrix<double> P(n, n);\n  matrix<double> tmp(n, n);\n  vector<double> d(n);\n  fill_u(U, d);\n\n  printf(\"filled\\n\");\n\n  matrix<double> U_out(n, n);\n  vector<double> d_out(n);\n\n\n  matrix<double> P_true(n, n);\n  matrix<double> P_hand(n, n);\n  matrix<double> P_atlas(n, n);\n  //compute_explicit_cov(U, d, tmp, P_true);\n  //cov_by_hand(U, d, tmp, P_hand);\n  //cov_atlas(U, d, tmp, P_atlas, n, n);\n  //matrix_eq(P_true, P_atlas, 1e-8);\n\n  /*\n  write_mat_col(\"P_true.txt\", P_true);\n  write_mat_col(\"P_hand.txt\", P_hand);\n  write_mat_col(\"P_atlas.txt\", P_atlas);\n  */\n  cov_atlas(U, d, tmp, P, n, n);\n  P_true = P;\n  for (unsigned i=0; i < iters; ++i) {\n    udu_ptr(P, U_out, d_out, n);\n    //P = P_true;\n    //udu_ptr(&(P(0,0)), &(U_out(0,0)), &(d_out(0)),\n    //\t    n, n);\n\n    //printf(\"udu\\n\");\n    P = P_true;\n  }\n\n  bool eq = matrix_eq(U_out, U, 1e-8);\n\n\n  return 0;\n\n}\n", "meta": {"hexsha": "0d65dadfdbcaec2636f9e2be2ab6ecf1a9f48857", "size": 6966, "ext": "cc", "lang": "C++", "max_stars_repo_path": "experiments/matrices.cc", "max_stars_repo_name": "davmre/sigvisa", "max_stars_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "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": "experiments/matrices.cc", "max_issues_repo_name": "davmre/sigvisa", "max_issues_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "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": "experiments/matrices.cc", "max_forks_repo_name": "davmre/sigvisa", "max_forks_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "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.3987138264, "max_line_length": 108, "alphanum_fraction": 0.5347401665, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6736561539991095}}
{"text": "#include <iostream>\n#include <Eigen\\Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int argc, char** argv) {\n\n\t// Constructor\n\tMatrixXf a(10, 15);\n\tVector3d b(5, 6, 7);\n\n\t// Coefficient accessors\n\t{\n\t\tMatrixXd m(2, 2);\n\t\tm(0, 0) = 3;\n\t\tm(1, 0) = 2.5;\n\t\tm(0, 1) = -1;\n\t\tm(1, 1) = m(1, 0) + m(0, 1);\n\t}\n\n\t{\n\t\t// Comma-initialization\n\t\tMatrix3f m;\n\t\tm << 1, 2, 3,\n\t\t\t4, 5, 6,\n\t\t\t7, 8, 9;\n\t}\n\t{\n\t\t// Resizing\n\t\tMatrixXd m(2, 5);\n\t\tm.resize(4, 3);\n\t\tcout << \"The matrix m is of size \" << m.rows() << \"x\" << m.cols() << endl; // 4x3\n\t\tcout << \"It has \" << m.size() << \" coefficients\" << endl; // 12\n\t\tVectorXd v(2);\n\t\tv.resize(5);\n\t\tcout << \"The vector v is of size \" << v.size() << endl; // 5\n\t\tcout << \"As a matrix, v is of size \" << v.rows() << \"x\" << v.cols() << endl; //5x1 \n\n\t}\n\n\t// assignment and resizing\n\t{\n\t\tMatrixXf a(2, 2); // size 2x2\n\t\tMatrixXf b(3, 3);\n\t\ta = b; \n\t\tcout << a.size() << endl; // 3x3\n\t}\n\n\t{\n\t\t// addition and subtraction\n\t\tMatrix2d a;\n\t\ta << 1, 2, \n\t\t\t 3, 4;\n\t\tMatrixXd b(2, 2);\n\t\tb << 2, 3,\n\t\t\t 1, 4;\n\t\tcout << \"a = \\n\" << a << endl << \"b = \\n\" << b << endl;\n\t\tcout << \"a + b = \\n\" << a + b << endl;\n\t\tcout << \"a - b = \\n\" << a - b << endl;\n\t\tcout << \"Doing a += b.\" << endl;\n\t\ta += b;\n\t\tcout << \"Now a = \\n\" << a << endl;\n\t\tVector3d v(1, 2, 3);\n\t\tVector3d w(1, 0, 0);\n\t\tcout << \"-v + w - v = \\b\" << -v + w - v << endl;\n\t}\n\t{\n\t\t// scalar multiplication and division\n\t\tMatrix2d a;\n\t\ta << 1, 2,\n\t\t\t 3, 4;\n\t\tVector3d v(1, 2, 3);\n\t\tcout << \"a = \\n\" << a << endl << \"v = \\n\" << v << endl;\n\t\tcout << \"a * 2.5 = \\n\" << a * 2.5 << endl;\n\t\tcout << \"0.1 * v = \\n\" << 0.1 * v << endl;\n\t\tcout << \"Doing v*= 2; \" << endl;\n\t\tv *= 2;\n\t\tcout << \"Now v =\\n\" << v << endl;\n\t}\n\n\t{\n\t\t// transposition and conjugation\n\t\tMatrixXcf a = MatrixXcf::Random(2, 2);\n\t\tcout << \"Here is the matrix a\\n\" << a << endl;\n\t\tcout << \"Here is the matrix a^T\\n\" << a.transpose() << endl;\n\t\tcout << \"Here is the conjugate of a\\n\" << a.conjugate() << endl;\n\t\tcout << \"Here is the matrix a^*\\n\" << a.adjoint() << endl;\n\t}\n\t{\n\t\t// transpose and adjoint return a proxy object without doing the actual transpotition\n\t\tMatrix2i a; a << 1, 2, 3, 4;\n\t\tcout << \"a = \\n\" << a << endl;\n\t\tMatrix2i b = a.transpose(); // this is ok\n\t\tcout << \"b = \\n\" << b << endl;\n\t\t//a = a.transpose(); // !!! do NOT do this. This is the aliasing issue and automatically detected in debug.\n\t\t//cout << \"a doesn't change after a = a.tranpose(). a = \\n\" << a << endl;\n\t\t// Should use the transposeInPlace()\n\t\ta.transposeInPlace();\n\t\tcout << \"a.transposeInPlace() = \\n\" << a << endl;\n\t}\n\t{\n\t\t// Matrix multiplication\n\t\tMatrix2d mat;\n\t\tmat << 1, 2,\n\t\t\t   3, 4;\n\t\tVector2d u(-1, 1), v(2, 0);\n\t\tcout << \"Here is mat * mat: \\n\" << mat * mat << endl;\n\t\tcout << \"Here is mat * u: \\n\" << mat * u << endl;\n\t\tcout << \"Here is u^T * mat: \\n\" << u.transpose()*mat << endl;\n\t\tcout << \"Here is u^T * v: \\n\" << u.transpose() * v << endl;\n\t\tcout << \"Here is u * v^T: \\n\" << u * v.transpose() << endl;\n\t\tcout << \"Let's multiply mat by itself \" << endl;\n\t\tmat *= mat;\n\t\tcout << \"Now mat is mat: \\n\" << mat << endl;\n\t}\n\t{\n\t\t// Dot product\n\t\tVector3d v(1, 2, 3);\n\t\tVector3d w(0, 1, 2);\n\t\tcout << \"Dot product: \" << v.dot(w) << endl;\n\t\tdouble dp = v.adjoint() * w;\n\t\tcout << \"Dot product via a matrix product: \" << dp << endl;\n\t\tcout << \"Cross product: \\n\" << v.cross(w) << endl;\n\t}\n\n\t{\n\t\t// basic arithmetic reduction operations\n\t\tEigen::Matrix2d mat;\n\t\tmat << 1, 2, 3, 4;\n\t\tcout << \"mat = \" << mat << endl;\n\t\tcout << \"mat.sum()  = \" << mat.sum() << endl;\n\t\tcout << \"mat.prod() = \" << mat.prod() << endl;\n\t\tcout << \"mat.mean() = \" << mat.mean() << endl;\n\t\tcout << \"mat.minCoeff() = \" << mat.minCoeff() << endl;\n\t\tcout << \"mat.maxCoeff() = \" << mat.maxCoeff() << endl;\n\t\tcout << \"mat.trace() = \" << mat.trace() << endl;\n\n\t\tMatrix3f m = Matrix3f::Random();\n\t\tstd::ptrdiff_t i, j;\n\t\tfloat minOfM = m.minCoeff(&i, &j);\n\t\tcout << \"m = \\n\" << m << endl;\n\t\tcout << \"minOfM = \" << minOfM << \" at i \" << i << \" j \" << j << endl;\n\n\t\tRowVector4i v = RowVector4i::Random();\n\t\tint maxOfV = v.maxCoeff(&i);\n\t\tcout << \"v = \\n\" << v << endl;\n\t\tcout << \"maxOfV = \" << maxOfV << \" at i = \" << i << endl;\n\n\t}\n\n\n\tsystem(\"pause\");\n\treturn 0;\n}", "meta": {"hexsha": "4cd83819d93d7c8351cf65b66da1874927adf8db", "size": 4171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/matrix_manipulation/matrix_manipulation.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/eigen/eigen/matrix_manipulation/matrix_manipulation.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/eigen/eigen/matrix_manipulation/matrix_manipulation.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.9096774194, "max_line_length": 109, "alphanum_fraction": 0.5020378806, "num_tokens": 1640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6736239258390939}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Eigen/Dense>\n#include <mkl_lapacke.h>\n#include <nasoq/clapacke/clapacke.h>\n\n\nusing MatrixXd = Eigen::MatrixXd;\nusing RowMatrixXd = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n\ntemplate<typename Derived>\nvoid fill_matrix(Derived& out_matrix) {\n\tusing Int = typename Eigen::DenseIndex;\n\tfor(Int i = 0; i < out_matrix.rows(); ++i) {\n\t\tfor(Int j = 0; j < out_matrix.cols(); ++j) {\n\t\t\tout_matrix(i,j) = i + j*j;\n\t\t}\n\t}\n}\n\ntemplate<typename Derived>\nvoid fill_spd(Derived& out_matrix) {\n\tusing Int = typename Eigen::DenseIndex;\n\tInt n = out_matrix.rows();\n\tREQUIRE(n == out_matrix.cols());\n\n\tfor(Int i = 0; i < n; ++i) {\n\t\tfor(Int j = 0; j < n; ++j) {\n\t\t\t// out_matrix(i,j) = 1.0 / (i + j + 1); // Hilbert matrix\n\t\t\tout_matrix(i,j) = 1.0 / (2*n - i - j - 1); // Hilbert matrix with reversed indices\n\t\t}\n\t}\n}\n\n//----------------------------------------------------------------------------//\n\nTEST_CASE(\"nasoq::clapacke::LAPACKE_dsytrf\") {\n\tconst int n = 4;\n\n\t// reference matrix\n\tMatrixXd A(n, n);\n\tfill_spd(A);\n\n\t// Note that the factorizations aren't required to be unique since the\n\t// pivoting is allowed to differ, so we compare against MLK my using\n\t// `LAPACKE_dsytri` to compute the inverse of `A` from the factorization.\n\n\tSECTION(\"col-major\") {\n\t\tSECTION(\"upper\") {\n\t\t\tMatrixXd A0(n, n);\n\t\t\tfill_spd(A0);\n\t\t\tMatrixXd A1 = A0;\n\t\t\tEigen::ArrayXi ipiv0(n), ipiv1(n);\n\n\t\t\tint ret0 = LAPACKE_dsytrf(LAPACK_COL_MAJOR, 'U', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dsytrf(LAPACK_COL_MAJOR, 'U', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK(ret0 == ret1);\n\n\t\t\tLAPACKE_dsytri(LAPACK_COL_MAJOR, 'U', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tLAPACKE_dsytri(LAPACK_COL_MAJOR, 'U', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK( A0.isApprox(A1) );\n\t\t}\n\n\t\tSECTION(\"lower\") {\n\t\t\tMatrixXd A0(n, n);\n\t\t\tfill_spd(A0);\n\t\t\tMatrixXd A1 = A0;\n\t\t\tEigen::ArrayXi ipiv0(n), ipiv1(n);\n\n\t\t\tint ret0 = LAPACKE_dsytrf(LAPACK_COL_MAJOR, 'L', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dsytrf(LAPACK_COL_MAJOR, 'L', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK(ret0 == ret1);\n\n\t\t\tLAPACKE_dsytri(LAPACK_COL_MAJOR, 'L', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tLAPACKE_dsytri(LAPACK_COL_MAJOR, 'L', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK( A0.isApprox(A1) );\n\t\t}\n\t}\n\n\tSECTION(\"row-major\") {\n\t\tSECTION(\"upper\") {\n\t\t\tRowMatrixXd A0(n, n);\n\t\t\tfill_spd(A0);\n\t\t\tRowMatrixXd A1 = A0;\n\t\t\tEigen::ArrayXi ipiv0(n), ipiv1(n);\n\n\t\t\tint ret0 = LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'U', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'U', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK(ret0 == ret1);\n\n\t\t\tLAPACKE_dsytri(LAPACK_ROW_MAJOR, 'U', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tLAPACKE_dsytri(LAPACK_ROW_MAJOR, 'U', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK( A0.isApprox(A1) );\n\t\t}\n\n\t\tSECTION(\"lower\") {\n\t\t\tRowMatrixXd A0(n, n);\n\t\t\tfill_spd(A0);\n\t\t\tRowMatrixXd A1 = A0;\n\t\t\tEigen::ArrayXi ipiv0(n), ipiv1(n);\n\n\t\t\tint ret0 = LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'L', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dsytrf(LAPACK_ROW_MAJOR, 'L', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK(ret0 == ret1);\n\n\t\t\tLAPACKE_dsytri(LAPACK_ROW_MAJOR, 'L', n, A0.data(), A0.outerStride(), ipiv0.data());\n\t\t\tLAPACKE_dsytri(LAPACK_ROW_MAJOR, 'L', n, A1.data(), A1.outerStride(), ipiv1.data());\n\t\t\tCHECK( A0.isApprox(A1) );\n\t\t}\n\t}\n}\n\n\nTEST_CASE(\"nasoq::clapacke::LAPACKE_dlapmt\") {\n\tconst int m = 5;\n\tconst int n = 7;\n\n\tEigen::VectorXi K(n);\n\tfor(int i = 0; i < n; ++i) {\n\t\tK[i] = n - i; // 1-based reversed indices\n\t}\n\n\tSECTION(\"col-major\") {\n\t\tMatrixXd X0(m, n);\n\t\tfill_matrix(X0);\n\t\tMatrixXd X1 = X0;\n\n\t\tint ldx = static_cast<int>(X0.outerStride());\n\t\tdouble* x0 = X0.data();\n\t\tdouble* x1 = X1.data();\n\t\tint* k = K.data();\n\n\t\tSECTION(\"forward\") {\n\t\t\tint ret0 = LAPACKE_dlapmt(LAPACK_COL_MAJOR, 1, m, n, x0, ldx, k);\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dlapmt(LAPACK_COL_MAJOR, 1, m, n, x1, ldx, k);\n\t\t\tCHECK(ret0 == ret1);\n\t\t\tCHECK(X0 == X1);\n\t\t}\n\t\tSECTION(\"backward\") {\n\t\t\tint ret0 = LAPACKE_dlapmt(LAPACK_COL_MAJOR, 0, m, n, x0, ldx, k);\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dlapmt(LAPACK_COL_MAJOR, 0, m, n, x1, ldx, k);\n\t\t\tCHECK(ret0 == ret1);\n\t\t\tCHECK(X0 == X1);\n\t\t}\n\t}\n\n\tSECTION(\"row-major\") {\n\t\tRowMatrixXd X0(m, n);\n\t\tfill_matrix(X0);\n\t\tRowMatrixXd X1 = X0;\n\n\t\tint ldx = static_cast<int>(X0.outerStride());\n\t\tdouble* x0 = X0.data();\n\t\tdouble* x1 = X1.data();\n\t\tint* k = K.data();\n\n\t\tSECTION(\"forward\") {\n\t\t\tint ret0 = LAPACKE_dlapmt(LAPACK_ROW_MAJOR, 1, m, n, x0, ldx, k);\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dlapmt(LAPACK_ROW_MAJOR, 1, m, n, x1, ldx, k);\n\t\t\tCHECK(ret0 == ret1);\n\t\t\tCHECK(X0 == X1);\n\t\t}\n\t\tSECTION(\"backward\") {\n\t\t\tint ret0 = LAPACKE_dlapmt(LAPACK_ROW_MAJOR, 0, m, n, x0, ldx, k);\n\t\t\tint ret1 = nasoq::clapacke::LAPACKE_dlapmt(LAPACK_ROW_MAJOR, 0, m, n, x1, ldx, k);\n\t\t\tCHECK(ret0 == ret1);\n\t\t\tCHECK(X0 == X1);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "948dc790c87990cfdf1f23247391dfb62087465c", "size": 5161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_clapacke.cpp", "max_stars_repo_name": "HasKha/nasoq", "max_stars_repo_head_hexsha": "24dac16ee887aa78eaff162a62cbb418b7f115dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2020-07-01T19:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T22:22:50.000Z", "max_issues_repo_path": "tests/test_clapacke.cpp", "max_issues_repo_name": "HasKha/nasoq", "max_issues_repo_head_hexsha": "24dac16ee887aa78eaff162a62cbb418b7f115dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-08-17T23:32:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T16:34:02.000Z", "max_forks_repo_path": "tests/test_clapacke.cpp", "max_forks_repo_name": "HasKha/nasoq", "max_forks_repo_head_hexsha": "24dac16ee887aa78eaff162a62cbb418b7f115dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T08:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:12:30.000Z", "avg_line_length": 30.0058139535, "max_line_length": 115, "alphanum_fraction": 0.6270102693, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6735504668086529}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n#include \"bayes_classifier.h\"\nusing namespace std;\nusing namespace Eigen;\n\nconst int NO_ERRORS = 0;\n//const char CORRECT = 'X';\n//const char INCORRECT = '-';\n\ntypedef struct\n{\n    string actual_class;\n    string classified_as;\n    bool correctly_classified;\n} ClassificationItem;\n\ntypedef struct\n{\n    int num_correct;\n    int num_incorrect;\n    int false_males;\n    int false_females;\n    vector< ClassificationItem > tested_data;\n} Results;\n\n\nint loadData( MatrixXd& class_1_data, MatrixXd& class_2_data,\n              const char* data_filename, const int num_features );\n\nVectorXd computeMeanVector( const MatrixXd& data );\n\nMatrixXd computeCovarianceMatrix( const MatrixXd& data, const VectorXd mean_vector );\n\nMatrixXd mergeDataMatrices( const MatrixXd& class_1_data, const MatrixXd& class_2_data );\n\nResults classifyTestData( const MatrixXd& class_1_test_data,\n                          const MatrixXd& class_2_test_data,\n                          vector< BayesClassifier >& classifiers );\n\nvoid outputResults( const char* output_filename, const Results& results );\n\n\nint main( int argc, char** argv )\n{\n    int program_success = NO_ERRORS;\n    MatrixXd class_1_data;\n    MatrixXd class_2_data;\n    MatrixXd test_data;\n    BayesClassifier male_image_class;\n    BayesClassifier female_image_class;\n    vector< BayesClassifier > classifiers( 2 );\n    Results results;\n\n    if( argc == 1 )\n    {\n        cout << \"Usage: project4  num_features_to_keep training_data_filename\" << endl\n             << \"testing_filenam output_filename\" << endl;\n    }\n\n    puts( \"Loading Training Data...\" );\n    loadData( class_1_data, class_2_data, argv[2], atoi( argv[1] ) );\n\n    puts( \"Training Bayes Classifiers...\" );\n    classifiers[0].set_class_name( \"Male Image\" );\n    classifiers[0].train_classifier( class_1_data );\n    classifiers[0].set_prior_probability( 0.5 );\n\n    classifiers[1].set_class_name( \"Female Image\" );\n    classifiers[1].train_classifier( class_2_data );\n    classifiers[1].set_prior_probability( 0.5 );\n\n//double y=0;\n//for( int i = 0; i < class_1_data.cols(); i++ )\n//{\n//    cout << class_1_data( 0, i ) << '\\t';\n//    y += class_1_data( 0, i );\n//}\n\n//cout << endl << ( y / (double) class_1_data.cols() ) << endl;\n//  classifiers[0].reportClassifierInfo();\n//    classifiers[1].reportClassifierInfo();\n\n    puts( \"Loading Testing Data...\" );\n    loadData( class_1_data, class_2_data, argv[3], atoi( argv[1] ) ); // re-using objects\n\n    puts( \"Classifying Test Data...\" );\n    results = classifyTestData( class_1_data, class_2_data, classifiers );\n\n    puts( \"Outputting results...\" );\n    outputResults( argv[4], results );\n\n    return program_success;\n}\n\n\nint loadData( MatrixXd& class_1_data, MatrixXd& class_2_data,\n              const char* data_filename, const int num_features )\n{\n    ifstream fin;\n    vector< VectorXd > feature_data;\n    VectorXd temp_vector;\n    vector< int > labels;\n    int label;\n    double value;\n    int num_in_class_1 = 0;\n    int num_in_class_2 = 0;\n    char buffer[1000];\n    int i = 0;\n    int j = 0;\n    int k = 0;\n\n    temp_vector.resize( num_features, 1 );\n\n    fin.clear();\n    fin.open( data_filename );\n\n    fin >> label;\n    while( fin.good() )\n    {\n        labels.push_back( label );\n        if( label == -1 )\n        {\n            num_in_class_1++;\n        }\n        else if( label == +1 ) // possibly unnecessary test, only expect -1/+1\n        {\n            num_in_class_2++;\n        }\n\n        for( j = 0; j < num_features; j++ )\n        {\n            fin.getline( buffer, 999, ':' ); // eat the index information\n            fin >> value;\n            temp_vector( j ) = value;\n        }\n\n        feature_data.push_back( temp_vector );\n        fin.getline( buffer, 999, '\\n' ); // eat any excess features' values\n        i++;\n\n        fin >> label;\n    }\n\n    fin.close();\n\n    assert( ( num_in_class_1 + num_in_class_2 ) == labels.size() );\n\n    class_1_data.resize( num_features, num_in_class_1 );\n    class_2_data.resize( num_features, num_in_class_2 );\n\n    for( i = 0, j = 0, k = 0; i < feature_data.size(); i++ )\n    {\n        if( labels[i] == -1 )\n        {\n            class_1_data.col( j ) = feature_data[i].transpose().eval();\n            j++;\n        }\n        else if( labels[i] == +1 )\n        {\n            class_2_data.col( k ) = feature_data[i];\n            k++;\n        }\n    }\n\n    return 0; \n}\n\nVectorXd computeMeanVector( const MatrixXd& data )\n{\n    VectorXd mean_vector;\n    int j = 0;\n\n    mean_vector.resize( data.rows(), 1 );\n    mean_vector *= 0;\n\n    for( j = 0; j < data.cols(); j++ )\n    {\n        mean_vector += data.col( j );\n    }\n    mean_vector /= data.cols();\n\n    return mean_vector;\n}\n\nMatrixXd computeCovarianceMatrix( const MatrixXd& data, const VectorXd mean_vector )\n{\n    MatrixXd covariance_matrix;\n    MatrixXd A_matrix;\n    int j = 0;\n\n    covariance_matrix.resize( mean_vector.size(), mean_vector.size() );\n    A_matrix.resize( data.rows(), data.cols() );\n\n    for( j = 0; j < data.cols(); j++ )\n    {\n        A_matrix.col( j ) = data.col( j ) - mean_vector;\n    }\n\n    covariance_matrix = A_matrix * A_matrix.transpose().eval();\n    covariance_matrix *= data.cols();\n\n    return covariance_matrix;\n}\n\n\nMatrixXd mergeDataMatrices( const MatrixXd& class_1_data, const MatrixXd& class_2_data )\n{\n    assert( class_1_data.rows() == class_2_data.rows() );\n\n    MatrixXd merged_data;\n    int j = 0;\n    int k = 0;\n\n    merged_data.resize( class_1_data.rows(), ( class_1_data.cols() + class_2_data.cols() ) );\n\n    for( k = 0, j = 0; k < class_1_data.cols(); k++, j++ )\n    {\n        merged_data.col( j ) = class_1_data.col( k );\n    }\n\n    for( k = 0; k < class_2_data.cols(); k++, j++ )\n    {\n        merged_data.col( j ) = class_1_data.col( k );\n    }\n\n    return merged_data;\n}\n\n\nResults classifyTestData( const MatrixXd& class_1_test_data,\n                          const MatrixXd& class_2_test_data,\n                          vector< BayesClassifier >& classifiers )\n{\n    Results results;\n        results.num_correct = 0;\n        results.num_incorrect = 0;\n        results.false_males = 0;\n        results.false_females = 0;\n        results.tested_data.resize( class_1_test_data.cols() + class_2_test_data.cols() );\n    ClassificationItem temp;\n    int i = 0;\n    int j = 0;\n\n    for( i = 0, j = 0; j < class_1_test_data.cols(); i++, j++ )\n    {\n        results.tested_data[i].actual_class = classifiers[0].class_name();\n        results.tested_data[i].classified_as = BayesClassifier::assignToClass( class_1_test_data.col( j ), classifiers );\n        results.tested_data[i].correctly_classified = ( results.tested_data[i].actual_class == results.tested_data[i].classified_as );\n\n        if( results.tested_data[i].correctly_classified )\n        {\n            results.num_correct++;\n        }\n        else\n        {\n            results.num_incorrect++;\n\n            if( results.tested_data[i].classified_as == classifiers[0].class_name() )\n            {\n                results.false_males++;\n            }\n            else if( results.tested_data[i].classified_as == classifiers[1].class_name() ) // likely could just be an else\n            {\n                results.false_females++;\n            }\n        }\n    }\n\n    for( j = 0; j < class_2_test_data.cols(); i++, j++ )\n    {\n        results.tested_data[i].actual_class = classifiers[1].class_name();\n        results.tested_data[i].classified_as = BayesClassifier::assignToClass( class_2_test_data.col( j ), classifiers );\n        results.tested_data[i].correctly_classified = ( results.tested_data[i].actual_class == results.tested_data[i].classified_as );\n\n        if( results.tested_data[i].correctly_classified )\n        {\n            results.num_correct++;\n        }\n        else\n        {\n            results.num_incorrect++;\n\n            if( results.tested_data[i].classified_as == classifiers[0].class_name() )\n            {\n                results.false_males++;\n            }\n            else if( results.tested_data[i].classified_as == classifiers[1].class_name() ) // likely could just be an else\n            {\n                results.false_females++;\n            }\n        }\n    }\n\n    return results;\n}\n\n\nvoid outputResults( const char* output_filename, const Results& results )\n{\n    ofstream fout;\n    int i = 0;\n\n    fout.clear();\n    fout.open( output_filename );\n\n    fout << \"Accuracy:             \" << (double) results.num_correct / (double) (results.num_correct + results.num_incorrect) << endl\n         << \"Number of Test Items: \" << results.num_correct + results.num_incorrect << endl\n         << \"Number Correct:       \" << results.num_correct << endl\n         << \"Number Incorrect:     \" << results.num_incorrect << endl\n         << \"Number False Males:   \" << results.false_males << endl\n         << \"Number False Females: \" << results.false_females << endl\n         << endl;\n\n    fout << \"Actual Class, Classified As, Correctly Classified (0 = No, 1 = Yes)\" << endl;\n    for( i = 0; i < results.tested_data.size(); i++ )\n    {\n        fout << results.tested_data[i].actual_class << \", \" << results.tested_data[i].classified_as << \", \" << results.tested_data[i].correctly_classified << endl;\n    }\n\n    fout.close();\n}\n\n\n", "meta": {"hexsha": "4b2aae813adfeeb8706baca7285a697c919f6f0e", "size": 9396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_4/code/project_4_bayes_classification_driver.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": "CS479/Project_4/code/project_4_bayes_classification_driver.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": "CS479/Project_4/code/project_4_bayes_classification_driver.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": 28.4727272727, "max_line_length": 163, "alphanum_fraction": 0.6046189868, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6735446928122419}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n \n#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <algorithm>\n\n#include <iostream>\n\n#include <boost/random/normal_distribution.hpp>\n\n#include <dpMM/distribution.hpp>\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\nusing std::min;\n\n#ifdef BOOST_OLD\nusing boost::normal_distribution;\n#else\nusing boost::random::normal_distribution;\n#endif\n\ntemplate<typename T>\nclass Normal : public Distribution<T>\n{\npublic:\n  uint32_t  D_;\n  Matrix<T,Dynamic,1> mu_;\n\n  Normal(const Matrix<T,Dynamic,1>& mu, const Matrix<T,Dynamic,Dynamic>& Sigma,\n      boost::mt19937 *pRndGen);\n  Normal(const Matrix<T,Dynamic,Dynamic>& Sigma, boost::mt19937 *pRndGen);\n  Normal(uint32_t D, boost::mt19937 *pRndGen);\n  Normal(const Normal<T>& other);\n  ~Normal();\n\n  T logPdf(const Matrix<T,Dynamic,Dynamic>& x) const;\n  T logPdfSlower(const Matrix<T,Dynamic,Dynamic>& x) const;\n  T logPdf(const Matrix<T,Dynamic,Dynamic>& scatter, \n      const Matrix<T,Dynamic,1>& mean, T count) const;\n  T logPdfSlower(const Matrix<T,Dynamic,Dynamic>& scatter, \n      const Matrix<T,Dynamic,1>& mean, T count) const;\n  T logPdf(const Matrix<T,Dynamic,Dynamic>& scatter, T count) const;\n\n  Matrix<T,Dynamic,1> sample();\n\n  void print() const;\n\n  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return Sigma_;};\n  void setSigma(const Matrix<T,Dynamic,Dynamic>& Sigma)\n  { Sigma_ = Sigma; SigmaLDLT_.compute(Sigma_); \n    logDetSigma_ = ((Sigma_.eigenvalues()).array().log().sum()).real();};\n  T logDetSigma() const {return logDetSigma_;};\n  const LDLT<Matrix<T,Dynamic,Dynamic> >& SigmaLDLT() const {return SigmaLDLT_;};\n\nprivate:\n\n  Matrix<T,Dynamic,Dynamic> Sigma_;\n  // helpers for fast computation\n  T logDetSigma_;\n  LDLT<Matrix<T,Dynamic,Dynamic> > SigmaLDLT_;\n\n  normal_distribution<> gauss_;\n};\n\ntypedef Normal<double> Normald;\ntypedef Normal<float> Normalf;\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClusters(\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K);\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClusters(\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K)\n{\n  uint32_t N = x.cols();\n  uint32_t D = x.rows();\n  boost::mt19937 rndGen(9119);\n\n  Matrix<T,Dynamic,Dynamic> Sigma = Matrix<T,Dynamic,Dynamic>::Identity(D,D);\n  Sigma *= 5.0;\n  Normal<T> meanPrior(Sigma,&rndGen);\n\n  Sigma *= 1.0/20.;\n  Matrix<T,Dynamic,Dynamic> mus(D,K);\n  for(uint32_t k=0; k<K; ++k)\n  {\n    mus.col(k) = meanPrior.sample();\n    Normal<T> gauss_k(mus.col(k),Sigma,&rndGen);\n    for (uint32_t i=k*(N/K); i<min(N,(k+1)*(N/K)+N%K); ++i) \n    {\n      x.col(i) = gauss_k.sample();\n      z(i) = k;\n    }\n  }\n  return mus;\n};\n\n", "meta": {"hexsha": "a21dc025716a81690379b6eb7bcdaa4c3c935c7a", "size": 2779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/normal.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/normal.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "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/dpMM/normal.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 26.4666666667, "max_line_length": 81, "alphanum_fraction": 0.6919755308, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6735241019607138}}
{"text": "//\n//  IglUtils.hpp\n//  OptCuts\n//\n//  Created by Minchen Li on 8/30/17.\n//\n\n#ifndef IglUtils_hpp\n#define IglUtils_hpp\n\n#include \"TriMesh.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n#include <fstream>\n\nnamespace OptCuts {\n    \n    // a static class implementing basic geometry processing operations that are not provided in libIgl\n    class IglUtils {\n    public:\n        static void computeGraphLaplacian(const Eigen::MatrixXi& F, Eigen::SparseMatrix<double>& graphL);\n        \n        // graph laplacian with half-weighted boundary edge, the computation is also faster\n        static void computeUniformLaplacian(const Eigen::MatrixXi& F, Eigen::SparseMatrix<double>& graphL);\n        \n        static void computeMVCMtr(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::SparseMatrix<double>& MVCMtr);\n        \n        static void fixedBoundaryParam_MVC(Eigen::SparseMatrix<double> A, const Eigen::VectorXi& bnd,\n                                           const Eigen::MatrixXd& bnd_uv, Eigen::MatrixXd& UV_Tutte);\n        \n        static void mapTriangleTo2D(const Eigen::Vector3d v[3], Eigen::Vector2d u[3]);\n        static void computeDeformationGradient(const Eigen::Vector3d v[3], const Eigen::Vector2d u[3], Eigen::Matrix2d& F);\n        \n        // to a circle with the perimeter equal to the length of the boundary on the mesh\n        static void map_vertices_to_circle(const Eigen::MatrixXd& V, const Eigen::VectorXi& bnd, Eigen::MatrixXd& UV);\n        \n        static void mapScalarToColor_bin(const Eigen::VectorXd& scalar, Eigen::MatrixXd& color, double thres);\n        static void mapScalarToColor(const Eigen::VectorXd& scalar, Eigen::MatrixXd& color,\n                                     double lowerBound, double upperBound, int opt = 0);\n        \n        static void addBlockToMatrix(Eigen::SparseMatrix<double>& mtr, const Eigen::MatrixXd& block,\n                                     const Eigen::VectorXi& index, int dim);\n        static void addBlockToMatrix(const Eigen::MatrixXd& block, const Eigen::VectorXi& index, int dim,\n                                     Eigen::VectorXd* V, Eigen::VectorXi* I = NULL, Eigen::VectorXi* J = NULL);\n        static void addDiagonalToMatrix(const Eigen::VectorXd& diagonal, const Eigen::VectorXi& index, int dim,\n                                     Eigen::VectorXd* V, Eigen::VectorXi* I = NULL, Eigen::VectorXi* J = NULL);\n        static void addBlockToMatrix(const Eigen::MatrixXd& block,\n                                     const Eigen::VectorXi& index, int dim,\n                                     Eigen::MatrixXd& mtr);\n        static void addDiagonalToMatrix(const Eigen::VectorXd& diagonal,\n                                        const Eigen::VectorXi& index, int dim,\n                                        Eigen::MatrixXd& mtr);\n        \n        template<typename Scalar, int rows, int cols>\n        static void symmetrizeMatrix(Eigen::Matrix<Scalar, rows, cols>& mtr) {\n            if(rows != cols) {\n                return;\n            }\n            \n            for(int rowI = 0; rowI < rows; rowI++) {\n                for(int colI = rowI + 1; colI < cols; colI++) {\n                    double &a = mtr(rowI, colI), &b = mtr(colI, rowI);\n                    a = b = (a + b) / 2.0;\n                }\n            }\n        }\n        \n        // project a symmetric real matrix to the nearest SPD matrix\n        template<typename Scalar, int size>\n        static void makePD(Eigen::Matrix<Scalar, size, size>& symMtr) {\n            Eigen::SelfAdjointEigenSolver<Eigen::Matrix<Scalar, size, size>> eigenSolver(symMtr);\n            if(eigenSolver.eigenvalues()[0] >= 0.0) {\n                return;\n            }\n            Eigen::DiagonalMatrix<Scalar, size> D(eigenSolver.eigenvalues());\n            int rows = ((size == Eigen::Dynamic) ? symMtr.rows() : size);\n            int i = 0;\n            for(; i < rows; i++) {\n                if(D.diagonal()[i] < 0.0) {\n                    D.diagonal()[i] = 0.0;\n                }\n                else {\n                    break;\n                }\n            }\n//            D.diagonal().segment(0, i).array() += 1.0e-3 * D.diagonal()[i];\n            symMtr = eigenSolver.eigenvectors() * D * eigenSolver.eigenvectors().transpose();\n        }\n        \n        static void writeSparseMatrixToFile(const std::string& filePath, const Eigen::SparseMatrix<double>& mtr, bool MATLAB = false);\n        static void writeSparseMatrixToFile(const std::string& filePath, const Eigen::VectorXi& I, const Eigen::VectorXi& J,\n                                            const Eigen::VectorXd& V, bool MATLAB = false);\n        static void loadSparseMatrixFromFile(const std::string& filePath, Eigen::SparseMatrix<double>& mtr);\n        \n        static void sparseMatrixToTriplet(const Eigen::SparseMatrix<double>& mtr,\n                                          Eigen::VectorXi& I, Eigen::VectorXi& J, Eigen::VectorXd& V);\n        static void sparseMatrixToTriplet(const Eigen::SparseMatrix<double>& mtr, Eigen::VectorXd& V);\n        \n        static const std::string rtos(double real);\n        \n        static double computeRotAngle(const Eigen::RowVector2d& from, const Eigen::RowVector2d& to);\n        \n        // test wether 2D segments ab intersect with cd\n        static bool Test2DSegmentSegment(const Eigen::RowVector2d& a, const Eigen::RowVector2d& b,\n                                         const Eigen::RowVector2d& c, const Eigen::RowVector2d& d,\n                                         double eps = 0.0);\n        \n        static void addThickEdge(Eigen::MatrixXd& V, Eigen::MatrixXi& F, Eigen::MatrixXd& UV,\n                                 Eigen::MatrixXd& seamColor, const Eigen::RowVector3d& color,\n                                 const Eigen::RowVector3d& v0, const Eigen::RowVector3d& v1,\n                                 double halfWidth, double texScale, bool UVorSurface = false,\n                                 const Eigen::RowVector3d& normal = Eigen::RowVector3d());\n        \n        static void saveMesh_Seamster(const std::string& filePath,\n                                      const Eigen::MatrixXd& V, const Eigen::MatrixXi& F);\n        \n        static void smoothVertField(const TriMesh& mesh, Eigen::VectorXd& field);\n    };\n    \n}\n\n#endif /* IglUtils_hpp */\n", "meta": {"hexsha": "bf18494eacede3cbcf0f6adcbc00929419b736cd", "size": 6312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/IglUtils.hpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "src/Utils/IglUtils.hpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "src/Utils/IglUtils.hpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 50.496, "max_line_length": 134, "alphanum_fraction": 0.5678073511, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6734964151991574}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/models/exactbachelierimpliedvolatility.hpp>\n\n#include <ql/math/comparison.hpp>\n\n#include <boost/math/distributions/normal.hpp>\n\nnamespace QuantExt {\n\nusing namespace QuantLib;\n\nnamespace {\n\nstatic boost::math::normal_distribution<double> normal_dist;\nReal phi(const Real x) { return boost::math::pdf(normal_dist, x); }\nReal Phi(const Real x) { return boost::math::cdf(normal_dist, x); }\n\nReal PhiTilde(const Real x) { return Phi(x) + phi(x) / x; }\n\nReal inversePhiTilde(const Real PhiTildeStar) {\n    QL_REQUIRE(PhiTildeStar < 0.0, \"inversePhiTilde(\" << PhiTildeStar << \"): negative argument required\");\n    Real xbar;\n    if (PhiTildeStar < -0.001882039271) {\n        Real g = 1.0 / (PhiTildeStar - 0.5);\n        Real xibar = (0.032114372355 - g * g * (0.016969777977 - g * g * (2.6207332461E-3 - 9.6066952861E-5 * g * g))) /\n                     (1.0 - g * g * (0.6635646938 - g * g * (0.14528712196 - 0.010472855461 * g * g)));\n        xbar = g * (0.3989422804014326 + xibar * g * g);\n    } else {\n        Real h = std::sqrt(-std::log(-PhiTildeStar));\n        xbar = (9.4883409779 - h * (9.6320903635 - h * (0.58556997323 + 2.1464093351 * h))) /\n               (1.0 - h * (0.65174820867 + h * (1.5120247828 + 6.6437847132E-5 * h)));\n    }\n    Real q = (PhiTilde(xbar) - PhiTildeStar) / phi(xbar);\n    Real xstar =\n        xbar + 3.0 * q * xbar * xbar * (2.0 - q * xbar * (2.0 + xbar * xbar)) /\n                   (6.0 + q * xbar * (-12.0 + xbar * (6.0 * q + xbar * (-6.0 + q * xbar * (3.0 + xbar * xbar)))));\n    return xstar;\n}\n\n} // namespace\n\nReal exactBachelierImpliedVolatility(Option::Type optionType, Real strike, Real forward, Real tte, Real bachelierPrice,\n                                     Real discount) {\n\n    Real theta = optionType == Option::Call ? 1.0 : -1.0;\n\n    // compound bechelierPrice, so that effectively discount = 1\n\n    bachelierPrice /= discount;\n\n    // handle case strike = forward\n\n    if (std::abs(strike - forward) < 1E-15) {\n        return bachelierPrice / (std::sqrt(tte) * phi(0.0));\n    }\n\n    // handle case strike != forward\n\n    Real timeValue = bachelierPrice - std::max(theta * (forward - strike), 0.0);\n\n    if (std::abs(timeValue) < 1E-15)\n        return 0.0;\n\n    QL_REQUIRE(timeValue > 0.0, \"exactBachelierImpliedVolatility(theta=\"\n                                    << theta << \",strike=\" << strike << \",forward=\" << forward << \",tte=\" << tte\n                                    << \",price=\" << bachelierPrice << \"): option price implies negative time value (\"\n                                    << timeValue << \")\");\n\n    Real PhiTildeStar = -std::abs(timeValue / (strike - forward));\n    Real xstar = inversePhiTilde(PhiTildeStar);\n    Real impliedVol = std::abs((strike - forward) / (xstar * std::sqrt(tte)));\n\n    return impliedVol;\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "abd6f39446076710b436ea42c9d2421a20d365bb", "size": 3583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/models/exactbachelierimpliedvolatility.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/models/exactbachelierimpliedvolatility.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/models/exactbachelierimpliedvolatility.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 38.1170212766, "max_line_length": 120, "alphanum_fraction": 0.6223834775, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6734964092924973}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// Zdenek Prusa and Peter L. Soendergaard,\n// Real-time spectrogram inversion using phase gradient heap integration\n// Proceedings of DAFX 2016\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../public/STFT.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass RTPGHI\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXcd = Eigen::ArrayXcd;\n\n  void init(index fftSize)\n  {\n    mBins = fftSize / 2 + 1;\n    mPrevMag = ArrayXd::Zero(mBins);\n    mPrevLogMag = ArrayXd::Zero(mBins);\n    mPrevPrevLogMag = ArrayXd::Zero(mBins);\n    mPrevPhase = ArrayXd::Zero(mBins);\n    mPrevPrevPhase = ArrayXd::Zero(mBins);\n    mPrevPhaseDeltaT = ArrayXd::Zero(mBins);\n    mBinIndices = ArrayXd::LinSpaced(mBins, 0, mBins - 1);\n  }\n\n  void processFrame(RealVectorView in, ComplexVectorView out, index winSize,\n                    index fftSize, index hopSize, double tolerance)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    using namespace std::complex_literals;\n    double  gamma = 0.25645 * pow(winSize, 2); // assumes Hann window\n    ArrayXd mag = asEigen<Array>(in);\n    ArrayXd logMag = mag.max(epsilon).log();\n    ArrayXd futureLogMag = logMag;\n    ArrayXd currentLogMag = mPrevLogMag;\n    ArrayXd prevLogMag = mPrevPrevLogMag;\n\n    ArrayXd phaseDeltaT =\n        getPhaseDeltaT(currentLogMag, gamma, fftSize, hopSize);\n    ArrayXd phaseDeltaF =\n        getPhaseDeltaF(prevLogMag, futureLogMag, gamma, fftSize, hopSize);\n    double absTol =\n        log(tolerance) + max(currentLogMag.maxCoeff(), prevLogMag.maxCoeff());\n    ArrayXd todo = (currentLogMag > absTol).cast<double>();\n    index   numTodo = todo.sum();\n    ArrayXd phaseEst = pi + ArrayXd::Random(mBins) * pi;\n\n    vector<pair<double, index>> heap;\n\n    for (index i = 0; i < mBins; i++)\n    {\n      if (prevLogMag(i) > absTol) heap.push_back({prevLogMag(i), i});\n    }\n    make_heap(heap.begin(), heap.end());\n\n    while (numTodo > 0 && heap.size() > 0)\n    {\n      pop_heap(heap.begin(), heap.end());\n      index _m = heap.back().second;\n      heap.pop_back();\n\n      // use indices 0..mBins for prev frame\n      // mBins ... 2 * mBins  for current frame\n      if (_m < mBins && todo[_m] > 0)\n      {\n        index m = _m;\n        phaseEst[m] =\n            mPrevPhase[m] + 0.5 * (phaseDeltaT[m] + mPrevPhaseDeltaT[m]);\n        heap.push_back({currentLogMag[m], m + mBins});\n        push_heap(heap.begin(), heap.end());\n        todo[m] = 0;\n        numTodo--;\n      }\n      else if (_m >= mBins)\n      {\n        index m = _m - mBins;\n        if (m < mBins - 1 && todo[m + 1] > 0)\n        {\n          phaseEst[m + 1] =\n              phaseEst[m] + 0.5 * (phaseDeltaF[m] + phaseDeltaF[m + 1]);\n          heap.push_back({currentLogMag[m + 1], _m + 1});\n          push_heap(heap.begin(), heap.end());\n          todo[m + 1] = 0;\n          numTodo--;\n        }\n        if (m > 0 && todo[m - 1] > 0)\n        {\n          phaseEst[m - 1] =\n              phaseEst[m] - 0.5 * (phaseDeltaF[m] + phaseDeltaF[m - 1]);\n          heap.push_back({currentLogMag[m - 1], _m - 1});\n          push_heap(heap.begin(), heap.end());\n          todo[m - 1] = 0;\n          numTodo--;\n        }\n      }\n    }\n\n    ArrayXd finalPhase =\n        phaseEst - ArrayXd::LinSpaced(mBins, 0, 1) * pi * (winSize - 1) / 2;\n    ArrayXcd result = mPrevMag * (1i * finalPhase).exp();\n    mPrevPrevLogMag = mPrevLogMag;\n    mPrevLogMag = logMag;\n    mPrevPhase = phaseEst;\n    mPrevPhaseDeltaT = phaseDeltaT;\n    mPrevMag = mag;\n    out = asFluid(result);\n  }\n\nprivate:\n  Eigen::ArrayXd getPhaseDeltaT(Eigen::Ref<ArrayXd> logMag, double gamma,\n                                index fftSize, index hopSize)\n  {\n    ArrayXd deltaT = ArrayXd::Zero(mBins);\n    deltaT.segment(1, mBins - 2) =\n        logMag.segment(2, mBins - 2) - logMag.segment(0, mBins - 2);\n    deltaT = deltaT * 0.5 * hopSize * fftSize / gamma;\n    deltaT = deltaT + twoPi * hopSize * mBinIndices / fftSize;\n    return deltaT;\n  }\n\n  Eigen::ArrayXd getPhaseDeltaF(ArrayXd prevLogMag, ArrayXd nextLogMag,\n                                double gamma, index fftSize, index hopSize)\n  {\n    return 0.5 * (nextLogMag - prevLogMag) * (-gamma / (hopSize * fftSize));\n  }\n\n  index   mBins;\n  ArrayXd mBinIndices;\n  ArrayXd mPrevMag;\n  ArrayXd mPrevLogMag;\n  ArrayXd mPrevPrevLogMag;\n  ArrayXd mPrevPhase;\n  ArrayXd mPrevPhaseDeltaT;\n  ArrayXd mPrevPrevPhase;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "a90093c60623e4a3305a2c51e0f4452c6108d0fe", "size": 4984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/RTPGHI.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/RTPGHI.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/RTPGHI.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": 30.9565217391, "max_line_length": 78, "alphanum_fraction": 0.6195826645, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107861416413, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.673474421226428}}
{"text": "// Filename: eigenvalue_example.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense_vector<double>                    eig;\n\n    double array[][4]= {{1,  1,   1,  0},\n                        {1, -1,  -2,  0},\n                        {1, -2,   1,  0},\n                        {0,  0,   0, 10}};\n    dense2D<double> A(array);\n    std::cout << \"A=\\n\" << A << \"\\n\";\n\n    eig= eigenvalue_symmetric(A,22);\n    std::cout<<\"eigenvalues  =\"<< eig <<\"\\n\";\n    \n    eig= 0;\n    eig= qr_sym_imp(A);\n    std::cout<<\"eigenvalues  =\"<< eig <<\"\\n\";\n    \n    eig= 0;\n    eig= qr_algo(A, 5);  // only 5 qr iterations (Q-R-changes)\n    std::cout<<\"eigenvalues  =\"<< eig <<\"\\n\";\n \n    return 0;\n}\n", "meta": {"hexsha": "e088c58080d4e759c04088cca8b8f44e91c21371", "size": 762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/eigenvalue_symmetric_example.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/examples/eigenvalue_symmetric_example.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/examples/eigenvalue_symmetric_example.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.8125, "max_line_length": 62, "alphanum_fraction": 0.4619422572, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6734744111904354}}
{"text": "#include \"zmpUtil.h\"\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXd expm(const MatrixXd& A) {\n  MatrixXd F;\n  MatrixExponential<MatrixXd>(A).compute(F);\n  return F;\n}\n\nExponentialPlusPiecewisePolynomial<double> s1Trajectory(const TVLQRData &sys, const PiecewisePolynomial<double> &zmp_trajectory,const Ref<const MatrixXd> &S) {\n  size_t n = static_cast<size_t>(zmp_trajectory.getNumberOfSegments());\n  int d = zmp_trajectory.getSegmentPolynomialDegree(0);\n  int k = d + 1;\n\n  for (size_t i = 1; i < n; i++) {\n    assert(zmp_trajectory.getSegmentPolynomialDegree(i) == d);\n  }\n\n  VectorXd dt(n);\n  std::vector<double> breaks = zmp_trajectory.getSegmentTimes();\n\n  for (size_t i = 0; i < n; i++) {\n    dt(i) = breaks[i + 1] - breaks[i];\n  }  \n  \n  MatrixXd zmp_tf = zmp_trajectory.value(zmp_trajectory.getEndTime());\n  PiecewisePolynomial<double> zbar_pp = zmp_trajectory - zmp_tf;\n\n  Matrix2d R1i = sys.R1.inverse();\n  MatrixXd NB = sys.N.transpose() + sys.B.transpose() * S; //2 x 4\n  Matrix4d A2 = NB.transpose() * R1i * sys.B.transpose() - sys.A.transpose();\n  MatrixXd B2 = 2 * (sys.C.transpose() - NB.transpose() * R1i * sys.D) * sys.Qy; //4 x 2\n  Matrix4d A2i = A2.inverse();\n\n  MatrixXd alpha = MatrixXd::Zero(4, n);\n\n  vector<MatrixXd> beta;\n  VectorXd s1dt;\n  \n  for (size_t i = 0; i < n ; i++) {\n    beta.push_back(MatrixXd::Zero(4, k));\n  }\n\n  for (int j = static_cast<int>(n) - 1; j >= 0; j--) { \n\n    auto poly_mat = zbar_pp.getPolynomialMatrix(j);\n    size_t nq = poly_mat.rows();\n    MatrixXd poly_coeffs = MatrixXd::Zero(nq, k);\n\n    for (size_t x = 0; x < nq; x++) {\n      poly_coeffs.row(x) = poly_mat(x).getCoefficients().transpose();\n    }    \n    \n    beta[j].col(k - 1) = -A2i * B2 * poly_coeffs.col(k - 1);\n    \n    for (int i = k - 2; i >= 0; i--) {\n      beta[j].col(i) = A2i * ((i+1) * beta[j].col(i + 1) - B2 * poly_coeffs.col(i));\n    }\n    \n    if (j == n - 1) {\n      s1dt = VectorXd::Zero(4);\n    } else {\n      s1dt = alpha.col(j+1) + beta[j + 1].col(0);\n    }\n\n    VectorXd dtpow(k);\n    for (size_t p = 0; p < k; p++) { \n      dtpow(p) = pow(dt(j), static_cast<int>(p));\n    }\n    \n    alpha.col(j) = expm(A2*dt(j)).inverse() * (s1dt - beta[j]*dtpow);\n  }\n  \n  vector<PiecewisePolynomial<double>::PolynomialMatrix> polynomial_matrices;\n  for (int segment = 0; segment < n ; segment++) {\n    PiecewisePolynomial<double>::PolynomialMatrix polynomial_matrix(4, 1);\n    for(int row = 0; row < 4; row++) {\n      polynomial_matrix(row) = Polynomial<double>(beta[segment].row(row));\n    }\n    polynomial_matrices.push_back(polynomial_matrix);\n  }\n\n  PiecewisePolynomial<double> pp_part = PiecewisePolynomial<double>(polynomial_matrices, breaks);\n  auto s1traj = ExponentialPlusPiecewisePolynomial<double>(Matrix4d::Identity(), A2, alpha, pp_part);\n  return s1traj;\n}\n", "meta": {"hexsha": "2eecc87bb2113570fd3c2885dbaf4b59c1d0731e", "size": 2869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/systems/controllers/zmpUtil.cpp", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/systems/controllers/zmpUtil.cpp", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "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": "drake/systems/controllers/zmpUtil.cpp", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 31.5274725275, "max_line_length": 159, "alphanum_fraction": 0.6357615894, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6734744055423149}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_prod_row.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_prod_row);\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n\n  matrix_type A;\n  vector_type x;\n  vector_type y;\n  vector_type tst;\n\n  A.resize(10,10,false);\n  x.resize(10,false);\n  y.resize(10,false);\n  tst.resize(10,false);\n\n  OpenTissue::math::Random<double> value(0.0,1.0);\n\n  for(size_t iteration = 0;iteration<100;++iteration)\n  {\n    for(size_t i=0;i<A.size1();++i)\n    {\n      x(i) = value();\n      y(i) = value();\n      for(size_t j=0;j<A.size2();++j)\n        A(i,j) = value();\n    }\n    ublas::noalias(tst) = ublas::prod(A,x);  \n    double tol = 0.01;\n    for(size_t i=0;i<A.size1();++i)\n    {\n      y(i) = OpenTissue::math::big::prod_row( A,x,i);\n      BOOST_CHECK_CLOSE( double( y(i) ), double( tst(i) ), tol );\n    }\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "709cc8159dac95d974918cf105658ae15c2b7c56", "size": 1521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/prod_row/src/unit_prod_row.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/big/prod_row/src/unit_prod_row.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/big/prod_row/src/unit_prod_row.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 26.6842105263, "max_line_length": 78, "alphanum_fraction": 0.6929651545, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6734393324699086}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <limits>\n#include <stdexcept>\n#include <cmath>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, acosh) {\n  using stan::math::acosh;\n  EXPECT_FLOAT_EQ(0, acosh(1));\n  EXPECT_FLOAT_EQ(0.96242365, acosh(1.5));\n  EXPECT_FLOAT_EQ(3.0797991, acosh(10.9));\n}\n\nTEST(MathFunctions, acosh_exception) {\n  using stan::math::acosh;\n  EXPECT_THROW(acosh(0.5), std::domain_error);\n}\n\nTEST(MathFunctions, acosh_inf_return) {\n  EXPECT_EQ(std::numeric_limits<double>::infinity(),\n            stan::math::acosh(std::numeric_limits<double>::infinity()));\n}\n\nTEST(MathFunctions, acosh_nan) {\n  using stan::math::acosh;\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::acosh(std::numeric_limits<double>::quiet_NaN()));\n}\n", "meta": {"hexsha": "6d5e81742f7f325dd9d3107a53b2d72708ef016b", "size": 816, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/acosh_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/acosh_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/acosh_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2, "max_line_length": 76, "alphanum_fraction": 0.7071078431, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6734393324699086}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include<Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseCholesky>\n#include<Eigen/SparseQR>\n#include <Eigen/OrderingMethods>\n\n\n\n#include <chrono>\n#include <time.h>\n\n#include \"parameters.h\"\n#include \"Set_2DAV_diags.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing Eigen::SparseMatrix;\nusing Eigen::BiCGSTAB;\nusing Eigen::MatrixXd;\nusing Eigen::SimplicialCholeskyLDLT;\n\n\ntypedef Eigen::Triplet<double> Trp;  //TrpripleTrps are objecTrp s of form: row index, column index, value.  used to fill sparse matrices\n\nint main()\n{\n\n    std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();  //start clock timer\n\n    VectorXd x(num_elements), b(num_elements);\n    SparseMatrix<double> A(num_elements,num_elements);\n    //The creation of these 2 matrices is super slow!So\n    MatrixXd epsilon = MatrixXd::Ones(num_cell+1,num_cell+1);  //NOTE: this is num_cell+1*num_cell+1 (NOT num_elements^2), 1 element per each physical grid pt. make matrix of ones\n    MatrixXd netcharge = MatrixXd::Zero(num_cell+1,num_cell+1);  //make matrix of zeroes\n\n    std::vector<double> main_diag (num_elements+1);\n    std::vector<double> upper_diag(num_elements);\n    std::vector<double> lower_diag(num_elements);\n    std::vector<double> far_lower_diag(num_elements-N+1);\n    std::vector<double> far_upper_diag(num_elements-N+1);\n\n    std::vector<double> V(num_elements+1); //vector for solution, electric potential\n    std::vector<double> rhs(num_elements+1);\n\n    //fill A and b\n    //Define boundary conditions and initial conditions\n    double Va = 1.;\n    double V_bottomBC = 0.;\n    double V_topBC= Va/Vt;\n\n    //Initial conditions\n    double diff = (V_topBC - V_bottomBC)/num_cell;\n    int index = 0;\n    for (int j = 1;j<=N;j++){//  %corresponds to z coord\n        index++;\n        V[index] = diff*j;\n        for (int i = 2;i<=N;i++){//  %elements along the x direction assumed to have same V\n            index++;\n            V[index] = V[index-1];\n        }\n    }\n\n    //side BCs, insulating BC's\n    std::vector<double> V_leftBC(N+1);\n    std::vector<double> V_rightBC(N+1);\n\n    for(int i = 1;i<=N;i++){\n        V_leftBC[i] = V[(i-1)*N +  1];\n        V_rightBC[i] = V[i*N];\n    }\n\n\n    //Set up matrix equation\n    main_diag = set_main_Vdiag(epsilon, main_diag);\n    upper_diag = set_upper_Vdiag(epsilon, upper_diag);\n    lower_diag = set_lower_Vdiag(epsilon, lower_diag);\n    far_upper_diag = set_far_upper_Vdiag(epsilon, far_upper_diag);\n    far_lower_diag = set_far_lower_Vdiag(epsilon, far_lower_diag);\n\n\n    //setup rhs of Poisson eqn.\n    int index2 = 0;\n    for(int j = 1;j<=N;j++){\n        if(j==1){\n            for(int i = 1;i<=N;i++){\n                index2++;                //THIS COULD BE MODIFIES TO a switch ,case statement--> might be cleaner\n                if(i==1){\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*(V_leftBC[1] + V_bottomBC);\n                }else if(i == N)\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*(V_rightBC[1] + V_bottomBC);\n                else\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*V_bottomBC;\n            }\n        }else if(j==N){\n            for(int i = 1; i<=N;i++){\n                index2++;\n                if(i==1)\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*(V_leftBC[N] + V_topBC);\n                else if(i == N)\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*(V_rightBC[N] + V_topBC);\n                else\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*V_topBC;\n            }\n        }else{\n            for(int i = 1;i<=N;i++){\n                index2++;\n                if(i==1)\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*V_leftBC[j];\n                else if(i == N)\n                    rhs[index2] = netcharge(i,j) + epsilon(i,j)*V_rightBC[j];\n                else\n                    rhs[index2] = netcharge(i,j);\n            }\n        }\n    }\n\n   //setup the triplet list for sparse matrix\n   \n    std::vector<Trp> triplet_list(5*num_elements);   //approximate the size that need         // list of non-zeros coefficients in triplet form(row index, column index, value)\n    int trp_cnt = 0;\n    for(int i = 1; i< main_diag.size(); i++){\n        b(i-1) = rhs[i];   //fill VectorXd  rhs of the equation\n          triplet_list[trp_cnt] = {i-1, i-1, main_diag[i]};\n          trp_cnt++;\n        //triplet_list.push_back(Trp(i-1,i-1,main_diag[i]));;   //triplets for main diag\n    }\n    for(int i = 1;i< upper_diag.size();i++){\n        triplet_list[trp_cnt] = {i-1, i, upper_diag[i]};\n        trp_cnt++;\n        //triplet_list.push_back(Trp(i-1, i, upper_diag[i]));  //triplets for upper diagonal\n     }\n     for(int i = 1;i< lower_diag.size();i++){\n         triplet_list[trp_cnt] = {i, i-1, lower_diag[i]};\n         trp_cnt++;\n        // triplet_list.push_back(Trp(i, i-1, lower_diag[i]));\n     }\n     for(int i = 1;i< far_upper_diag.size();i++){\n         triplet_list[trp_cnt] = {i-1, i-1+N, far_upper_diag[i]};\n         trp_cnt++;\n         //triplet_list.push_back(Trp(i-1, i-1+N, far_upper_diag[i]));\n         triplet_list[trp_cnt] = {i-1+N, i-1, far_lower_diag[i]};\n         trp_cnt++;\n         //triplet_list.push_back(Trp(i-1+N, i-1, far_lower_diag[i]));\n      }\n\n\n    A.setFromTriplets(triplet_list.begin(), triplet_list.end());    //A is our sparse matrix\n\n    //using conjugate gradient--> this is faster than BiCGSTAB\n/*\n    Eigen::ConjugateGradient<SparseMatrix<double>, Eigen::UpLoType::Lower|Eigen::UpLoType::Upper > cg;\n    cg.compute(A);\n   x = cg.solve(b);\n    std::cout << \"#iterations:     \" << cg.iterations() << std::endl;\n     std::cout << \"estimated error: \" << cg.error()      << std::endl;\n\n*/\n\n  /*  //using sparse LU\n     Eigen::SparseLU<SparseMatrix<double>>  sLU;\n    sLU.analyzePattern(A);\n    sLU.factorize(A);\n    x = sLU.solve(b);\n    */\n\n   //using Sparse Cholesky  (THIS SEEMS TO BE THE FASTEST for the 2D Poisson problem)\n    Eigen::SimplicialLDLT<SparseMatrix<double>, Eigen::UpLoType::Lower, Eigen::AMDOrdering<int>> SCholesky; //Note using NaturalOrdering is much much slower\n    SCholesky.analyzePattern(A);\n    SCholesky.factorize(A);\n    x = SCholesky.solve(b);\n\n\n    //NOTE, for repeat solves, I might not need to keep factorizing! Can just subtitute in the new rhs every time, and use solve()\n\n\n\n    /*\n    //using SparseQR  (is very slow, compared to others for large matrices).\n    Eigen::SparseQR<SparseMatrix<double>, Eigen::COLAMDOrdering<int>> SQR;  //NOTE: this ordering parameter is needed for this to work\n    SQR.analyzePattern(A);\n    SQR.factorize(A);\n    x = SQR.solve(b);\n    */\n\n    //using BiCGSTAB: this is probably useful for non-symmetric matrices, i.e. not Poisson equation which is symmetric. In that case, Cholesky might not work.\n\n    BiCGSTAB<SparseMatrix<double>, Eigen::IncompleteLUT<double>> solver;  //BiCGStab solver object\n    solver.compute(A);  //this computes the preconditioner\n    x = solver.solve(b);\n    std::cout << \"#iterations:     \" << solver.iterations() << std::endl;\n    std::cout << \"estimated error: \" << solver.error()      << std::endl;\n\n\n    std::cout << x <<std::endl;  //they have an overloaded << for seeing result!\n\n\n    std::chrono::high_resolution_clock::time_point finish = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> time = std::chrono::duration_cast<std::chrono::duration<double>>(finish-start);\n    std::cout << \"1 Va CPU time = \" << time.count() << std::endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "faefc548545264e5afa9059608e2e44fb45301db", "size": 7598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Poisson_2D/C++/with_Eigen/main.cpp", "max_stars_repo_name": "tgolubev/Poisson_eqn_solvers", "max_stars_repo_head_hexsha": "1d8c6e0cfbadb96d8d0c55d611c404664903aaef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-30T13:38:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-30T13:38:05.000Z", "max_issues_repo_path": "Poisson_2D/C++/with_Eigen/main.cpp", "max_issues_repo_name": "tgolubev/Poisson_eqn_solvers", "max_issues_repo_head_hexsha": "1d8c6e0cfbadb96d8d0c55d611c404664903aaef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Poisson_2D/C++/with_Eigen/main.cpp", "max_forks_repo_name": "tgolubev/Poisson_eqn_solvers", "max_forks_repo_head_hexsha": "1d8c6e0cfbadb96d8d0c55d611c404664903aaef", "max_forks_repo_licenses": ["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.8834951456, "max_line_length": 179, "alphanum_fraction": 0.6076599105, "num_tokens": 2113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6734097948363481}}
{"text": "/**\n * @file semimprk.cc\n * @brief NPDE homework SemImpRK code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"semimprk.h\"\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace SemImpRK {\n\n/* SAM_LISTING_BEGIN_0 */\ndouble CvgRosenbrock() {\n  double cvgRate = 0.0;\n  // Use polyfit to estimate the rate of convergence\n  // for SolveRosenbrock.\n#if SOLUTION\n  // Final time\n  const double T = 10.0;\n  // Timestep sizes h=2^{-k} for which discretization erorrs should be computed\n  const Eigen::ArrayXd K = Eigen::ArrayXd::LinSpaced(7, 4, 10);\n  // Initial state vector\n  Eigen::Vector2d y0(1., 1.);\n\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  // Lambda functions giving the right-hand side function f\n  // and its Jacobian df\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  // timestep size h=2^{-12} (=> M = T*2^{12}) used to compute a reference\n  // solution\n  const int M_ref = T * std::pow(2, 12);\n  // Reference solution\n  std::vector<Eigen::VectorXd> solref = SolveRosenbrock(f, df, y0, M_ref, T);\n  // Arrays for recording error norms and numbers of timesteps\n  Eigen::ArrayXd Error(K.size());\n  Eigen::ArrayXd M(K.size());\n  // Loop over all temporal meshes\n  for (unsigned int i = 0; i < K.size(); ++i) {\n    // h = 2^{-k} => M = T*h = T*2^k\n    M(i) = T * std::pow(2, K[i]);\n\n    // Compute solution\n    std::vector<Eigen::VectorXd> sol = SolveRosenbrock(f, df, y0, M(i), T);\n\n    // Compute error\n    double maxerr = 0;\n    for (unsigned int j = 0; j < sol.size(); ++j) {\n      maxerr = std::max(maxerr, (sol[j] - solref[j * M_ref / M(i)]).norm());\n    }\n    Error(i) = maxerr;\n  }\n  // Print Error table\n  std::cout << std::setw(15) << \"M\" << std::setw(16) << \"maxerr \\n\";\n  for (int i = 0; i < M.size(); ++i) {\n    std::cout << std::setw(15) << M(i) << std::setw(15) << Error(i)\n              << std::endl;\n  }\n  // Estimate convergence rate using linear regression provided by the auxiliary\n  // function polyfit()\n  cvgRate = -polyfit(M.log(), Error.log(), 1)(0);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return cvgRate;\n}\n/* SAM_LISTING_END_0 */\n\n}  // namespace SemImpRK\n", "meta": {"hexsha": "70974e26df559bb476a990edb159050a06fb8717", "size": 2741, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/SemImpRK/mastersolution/semimprk.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/SemImpRK/mastersolution/semimprk.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/SemImpRK/mastersolution/semimprk.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": 29.1595744681, "max_line_length": 80, "alphanum_fraction": 0.5902955126, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6733822870636721}}
{"text": "\n// inverting A\n// using getrf() & getri() \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef std::complex<double> cmpx; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::matrix<cmpx, ublas::column_major> cm_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\ntypedef ublas::matrix<cmpx, ublas::row_major> cm_t;\n#endif\n\nint main() {\n\n  cout << endl; \n  cout << \"real matrix:\" << endl << endl; \n\n  size_t n = 5; \n  m_t a (n, 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  print_m (a, \"A\"); \n  cout << endl; \n\n  m_t aa (a);  // copy of a, for later use\n\n  std::vector<int> ipiv (n);   // pivot vector \n  atlas::lu_factor (a, ipiv);  // alias for getrf()\n  atlas::lu_invert (a, ipiv);  // alias for getri() \n\n  m_t i1 (n, n), i2 (n, n);  \n  atlas::gemm (a, aa, i1);   // i1 should be (almost) identity matrix\n  atlas::gemm (aa, a, i2);   // i2 should be (almost) identity matrix\n\n  print_m (i1, \"I = A^(-1) * A\");  \n  cout << endl; \n  print_m (i2, \"I = A * A^(-1)\"); \n  cout << endl; \n  \n  cout << endl; \n\n  //////////////////////////////////////////////////////\n\n  cout << \"complex matrix:\" << endl << endl; \n  cm_t ca (3, 3); \n\n  ca (0, 0) = cmpx (3, 0);\n  ca (0, 1) = cmpx (4, 2);\n  ca (0, 2) = cmpx (-7, 5);\n  ca (1, 0) = cmpx (4, -2);\n  ca (1, 1) = cmpx (-5, 0);\n  ca (1, 2) = cmpx (0, -3);\n  ca (2, 0) = cmpx (-7, -5);\n  ca (2, 1) = cmpx (0, 3);\n  ca (2, 2) = cmpx (2, 0);\n  print_m (ca, \"CA\"); \n  cout << endl; \n\n  cm_t caa (ca); \n  \n  std::vector<int> ipiv2 (3); \n  \n  int ierr = atlas::getrf (ca, ipiv2);\n  if (ierr == 0) {\n    atlas::getri (ca, ipiv2); \n    cm_t ii (3, 3); \n    atlas::gemm (ca, caa, ii);\n    print_m (ii, \"I = CA^(-1) * CA\"); \n    cout << endl; \n    atlas::gemm (caa, ca, ii);\n    print_m (ii, \"I = CA * CA^(-1)\"); \n    cout << endl; \n  }\n  else\n    cout << \"matrix is singular\" << endl; \n  \n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "a30d11b49b540a0181d7b7934554f334c6805d92", "size": 2519, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_getri.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "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": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_getri.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_getri.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "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": 23.7641509434, "max_line_length": 69, "alphanum_fraction": 0.5474394601, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6733156469856149}}
{"text": "#ifndef __CAD_UTIL_HH__\n#define __CAD_UTIL_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (CAD Utility functions from Rocket6G)\nLIBRARY DEPENDENCY:\n      ((../src/cad_utility.cpp))\n*******************************************************************************/\n#include <tuple>\n#include \"math_utility.hh\"\n#include <armadillo>\n\nnamespace cad {\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     */\n\n\n    double distance(const double &lon1,\n                    const double &lat1,\n                    const double &lon2,\n                    const double &lat2);\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     *\n     * @author 030414 Created from FORTRAN by Peter H Zipfel\n     * @author 170121 Create Armadillo Version by soncyang\n     */\n    std::tuple<double, double, double> geo84_in(arma::vec3 SBII,\n                                                arma::mat33 TEI);\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     */\n    std::tuple<double, double, double> geo84vel_in(arma::vec3 SBII,\n                                                   arma::vec3 VBII,\n                                                   arma::mat33 TEI);\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    std::tuple<double, double, double> geoc_in(arma::vec3 SBII,\n                                               const double &time);\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     */\n    std::tuple<double, double, double>  geoc_ine(arma::vec3 SBIE);\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     */\n    arma::vec3 grav84(arma::vec3 SBII, const double &time);\n\n    /**\n     * @brief Returns the inertial displacement vector from longitude, latitude and\n     *      altitude\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 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] time = simulation time - sec\n     *\n     * @author 030411 Created from FORTRAN by Peter H Zipfel\n     * @author 170121 Create Armadillo Version by soncyanga\n     */\n    arma::vec3 in_geo84(const double lon,\n                        const double lat,\n                        const double alt,\n                        arma::mat33 TEI);\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     */\n    arma::vec3 in_geoc(const double &lon,\n                       const double &lat,\n                       const double &alt,\n                       const double &time);\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     */\n    int 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\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     */\n    int kepler(arma::vec3 &SPII,\n               arma::vec3 &VPII,\n               arma::vec3 SBII,\n               arma::vec3 VBII,\n               const double &tgo);\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     */\n    int kepler1(arma::vec3 &SPII,\n                arma::vec3 &VPII,\n                arma::vec3 SBII,\n                arma::vec3 VBII,\n                const double &tgo);\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     */\n    std::tuple<double, double> kepler1_ucs(const double &z);\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     */\n    int 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\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[out] lon = geodetic longitude - rad\n     * @param[out] lat = geodetic latitude - rad\n     * @param[out] alt = altitude above ellipsoid - m\n     *\n     * @author 030424 Created by Peter H Zipfel\n     * @author 170121 Create Armadillo Version by sonicyang\n     */\n    arma::mat33 tdi84(const double &lon,\n                               const double &lat,\n                               const double &alt,\n                               arma::mat33 TEI);\n\n    arma::mat33 tde84(const double &lon,\n                               const double &lat,\n                               const double &alt);\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     */\n    arma::mat33 tei(const double &time);\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     */\n    arma::mat33 tge(const double &lon, const double &lat);\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     */\n    arma::mat33 tgi84(const double &lon,\n                      const double &lat,\n                      const double &alt,\n                      arma::mat33 TEI);\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     */\n    arma::mat33 tip(const double &incl,\n                    const double &lon_anode,\n                    const double &arg_peri);\n}  // namespace cad\n#endif  // __CAD_UTIL_HH__\n", "meta": {"hexsha": "75d9cd0e6d0f7311dede4035d82bb5bb8bf4ba49", "size": 13751, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/cad/include/cad_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/cad/include/cad_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/cad/include/cad_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": 38.6264044944, "max_line_length": 90, "alphanum_fraction": 0.5657770344, "num_tokens": 3595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6733026520183043}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry> //Eigen Geometry module\n\n//----------------------------use Eigen Geometry module-------------------------\n// Eigen/Geometry \u63d0\u4f9b\u4e86\u5404\u79cd\u65cb\u8f6c\u548c\u5e73\u79fb\u7684\u8868\u793a\n\nint main(int argc, char const *argv[])\n{\n   // set a 3x3 indentity matrix\n   Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n\n   //-------------------get Rotation Matrix given theta,n-----------------------\n   // \u521b\u5efarotation\u52a8\u4f5c\n   //   rot(theta,n) rot 45 degree about z-axis\n   //   \u7c7b\u578b Eigen::AngleAxisd rot(),\n   //     \u62ec\u53f7\u91cc\u9762\u53ef\u4ee5\u662f\uff08theta, n\uff09, \u4e5f\u53ef\u4ee5\u662fquaternion q\uff0c\u5e94\u8be5\u8fd8\u80fd\u662f\u5f88\u591a\u5176\u4ed6\u7c7b\u578b\u7684\n   //   \u65cb\u8f6c\u5411\u91cf\u4f7f\u7528 AngleAxis, \u5b83\u5e95\u5c42\u4e0d\u76f4\u63a5\u662fMatrix\uff0c\u4f46\u8fd0\u7b97\u53ef\u4ee5\u5f53\u4f5c\u77e9\u9635\uff08\u56e0\u4e3a\u91cd\u8f7d\u4e86\u8fd0\u7b97\u7b26\uff09\n   Eigen::AngleAxisd rot(M_PI / 4, Eigen::Vector3d(0, 0, 1));\n   //   Eigen::AngleAxisd rot_2(q); //q\u5728\u4e0b\u9762\u5b9a\u4e49\u8fd9\u91cc\u7528\u4e0d\u4e86\n   // two ways to see the rotation matrix from rot\uff0c\u90fd\u53ef\u4ee5\u8fd4\u56de\u4e00\u4e2amatrix\n   // 1. rot.matrix()\n   // 2. rot.toRotationMatrix()\n   R = rot.matrix();           //\u7b49\u4ef7\n   R = rot.toRotationMatrix(); //\u7b49\u4ef7\n   cout << \"rotation matrix =\\n\" << R << \"\\n\" << endl;\n\n   // \u5750\u6807\u8f6c\u6362\n   // \u521d\u59cbvector p\n   Eigen::Vector3d p(1, 0, 0);        //\u8fd9\u91cc\u7528\u4e86\u62ec\u53f7\u521d\u59cb\u5316\uff0c\u6ca1\u6709\u8d4b\u503c\u64cd\u4f5c\n   // p' = rot * p -> p\u5728\u65cb\u8f6c\u540e\u7684\u5750\u6807\u91cc\u9762\u7684\u503c\n   Eigen::Vector3d p_prime = rot * p; //rot.matrix()*p, rot\u53ef\u4ee5\u76f4\u63a5\u8fdb\u884c\u8fd0\u7b97\uff08\u56e0\u4e3a\u91cd\u8f7d\u4e86\u8fd0\u7b97\u7b26\uff09\n                                      //\u4e5f\u53ef\u4ee5\u7528 p_prime = R * p   line23\n   cout << \"vector p (1,0,0) after rotation = \" << p_prime.transpose() << \"\\n\" << endl;\n\n   //-----------------------------Euler Angle-----------------------------------\n   // \u53ef\u4ee5\u5c06\u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u8f6c\u6362\u6210\u6b27\u62c9\u89d2\uff0c\u6b27\u62c9\u89d2\u75283\u4e2a\u91cf\u8868\u793a3\u4e2a\u81ea\u7531\u5ea6\n   // \u6b27\u62c9\u89d2\u5c06\u4e00\u4e2a\u4e00\u6b21\u6027\u7684rotation matrix\u5206\u89e3\u6210\u4e09\u6b21\u65cb\u8f6c\uff0c\u8fd4\u56de\u6bcf\u6b21\u65cb\u8f6c\u5bf9\u5e94\u7684\u89d2\u5ea6\n   // \u6240\u67093\u7ef4matrix\u90fd\u53ef\u4ee5\u4f7f\u7528.eulerAngles(0,1,2)\uff0c\u7c7b\u578b\u4e3aAngleAxisd\u7684\uff0c\u6bd4\u5982rot\u4e0d\u80fd\u4f7f\u7528(line19)\n   Eigen::Vector3d euler_angles // \u8fd4\u56de\u4e00\u4e2a3x1\u7684\u5411\u91cf\n      = R.eulerAngles(2, 1, 0); // ZYX\u987a\u5e8f\uff0c\u5373roll pitch yaw\u987a\u5e8f\n   cout << \"yaw pitch roll = \" << euler_angles.transpose() << \"\\n\" << endl;\n\n   //------------------------Transformation Matrix------------------------------\n   // T = | R | t |\n   //     | 0 | 1 |\n   // given R\uff0ct\uff0ccreate transformation matrix\uff08\u6b27\u5f0f\u53d8\u6362\u77e9\u9635\uff09\n   Eigen::Vector3d   t(1, 2, 4);                        //\u521d\u59cb\u5316t\uff0c\u6ca1\u6709\u8d4b\u503c\u64cd\u4f5c\n   Eigen::Isometry3d T = Eigen::Isometry3d::Identity(); //\u867d\u7136\u662f3d\uff0c\u4f46\u662f\u662f4x4\u7684\u77e9\u9635\n   T.rotate(R);                                         //\u628a R \u653e\u5230 T \u91cc\u9762\n   T.pretranslate(t);                                   //\u628a t \u653e\u5230 T \u91cc\u9762\n   cout << \"Transform matrix = \\n\" << T.matrix() << \"\\n\" << endl;\n\n   // \u5750\u6807\u8f6c\u6362\n   p_prime = T * p; //\u8fd9\u91ccT\u662f4x4\uff0c\u800cp\u662f3x1\u3002\u5b9e\u9645\u64cd\u4f5c\u662f p'=Rp+t\n   cout << \"p' after transformation matrix is \"\n        << p_prime.transpose() << \"\\n\" << endl;\n\n   //-------------------------------Quaternion---------------------------------\n   // \u5c06 rotation matrix R \u8f6c\u53d8\u4e3a Quaternion q\n   // \u7528Eigen::Quaternion()\n   // \u62ec\u53f7\u91cc\u7684\u53c2\u6570\u7c7b\u578b\u53ef\u4ee5\u662fMatrix3d,\u6bd4\u5982R\uff0c\u4e5f\u53ef\u4ee5\u662fAngleAxisd\uff0c\u6bd4\u5982rot\n   Eigen::Quaterniond q = Eigen::Quaterniond(rot);\n   // \u8bf7\u6ce8\u610fcoeffs\u7684\u987a\u5e8f\u662f(x,y,z,w),w\u4e3a\u5b9e\u90e8\uff0c\u524d\u4e09\u8005\u4e3a\u865a\u90e8\n   cout << \"quaternion = \\n\" << q.coeffs() << \"\\n\" << endl;\n\n   // \u5750\u6807\u8f6c\u6362\n   p_prime = q * p; //\u8fd9\u91cc\u7684\u5b9e\u9645\u64cd\u4f5c\u662f p'=qpq^(-1)\n   cout << \"p' after Quaternion transformation is \"\n        << p_prime.transpose() << \"\\n\" << endl;\n\n   //----\u5bf9\u4e8e\u4eff\u5c04\u548c\u5c04\u5f71\u53d8\u6362\uff0c\u4f7f\u7528 Eigen::Affine3d \u548c Eigen::Projective3d \u5373\u53ef\uff0c\u7565-----\n\n   return 0;\n}\n", "meta": {"hexsha": "6aa907e440d7d3c6adb06234859b9b51237add0f", "size": 3096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libEigenGeometry/main.cpp", "max_stars_repo_name": "Qilko/VisualSLAM", "max_stars_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T02:35:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T17:52:55.000Z", "max_issues_repo_path": "libEigenGeometry/main.cpp", "max_issues_repo_name": "Qilko/VisualSLAM", "max_issues_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libEigenGeometry/main.cpp", "max_forks_repo_name": "Qilko/VisualSLAM", "max_forks_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_forks_repo_licenses": ["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.1898734177, "max_line_length": 87, "alphanum_fraction": 0.5394056848, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6733026346711387}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <time.h>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\n\nclass dpmeans\n{\n\npublic:\n\tdpmeans(const Ref<const MatrixXf>& X);  //X is n x d\n\t~dpmeans() {};\n\n\tfloat kpp_init(const Ref<const MatrixXf>& X, int k);\n\tVectorXi dpmeans_fit(const Ref<const MatrixXf>& X);\n\tfloat compute_nmi(const Ref<const VectorXi>& z1, const Ref<const VectorXi>& z2);\n\tvoid display_params();\n\nprivate:\n\tint K; //infered automatically\n\tint K_init; //for lambda k++ initiliazation\n\tint n; //number of points\n\tint d; //dimension\n\n\tVectorXi z;   //assignments\n\tMatrixXf mu;  //K x d means\n\tVectorXf nk;  //number of points in cluster k\n\tVectorXf pik; //mixture proportions\n\tfloat lambda; //dp-means hyper-parameter\n    \n\tint max_iter;\n\tvector<double> obj;\n\tvector<double> em_time;\n\t\n};\n", "meta": {"hexsha": "0c95dcb6713abd9d458f494106dfd6247c30dc06", "size": 819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "machine_learning/dpmeans/dpmeans.hpp", "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/dpmeans/dpmeans.hpp", "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/dpmeans/dpmeans.hpp", "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": 20.475, "max_line_length": 81, "alphanum_fraction": 0.7094017094, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.673241530167342}}
{"text": "/**\n * license is free\n * \\file    ontheline.cpp\n * \\author  hiratake26to@gmail.com\n * \\date    2017-10-11 JST\n */\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n\n/**\n * \\brief mouse pointer is on the line\n * \\param xa  x of equipment A\n * \\param ya  y of equipment A\n * \\param xb  x of equipment B\n * \\param yb  y of equipment B\n * \\param xc  x of mouse pointer\n * \\param yc  y of mouse pointer\n * \\param r   line width\n */\nbool isOnTheLine(int xa, int ya, int xb, int yb, int xc, int yc, int r);\n\nint main() {\n  /*    0 1 2 3 4 \n   * 0  _ _ _ _ _\n   * 1  _ _ _ B _\n   * 2  _ _ @ _ _\n   * 3  _ @ _ _ _\n   * 4  A _ _ _ _\n   */\n  bool result;\n  result = isOnTheLine(0, 4, 3, 1, 2, 2, 1);\n  std::cout << \"result : \" << result << std::endl;\n  std::cout << \"--------------------------\" << std::endl;\n  result = isOnTheLine(0, 4, 3, 1, 3, 2, 1);\n  std::cout << \"result : \" << result << std::endl;\n  std::cout << \"--------------------------\" << std::endl;\n  result = isOnTheLine(0, 4, 3, 1, 4, 3, 1);\n  std::cout << \"result : \" << result << std::endl;\n  std::cout << \"--------------------------\" << std::endl;\n  result = isOnTheLine(0, 4, 3, 1, 4, 0, 0);\n  std::cout << \"result : \" << result << std::endl;\n  return 0;\n}\n\nbool isOnTheLine(int xa, int ya, int xb, int yb, int xc, int yc, int r)\n{\n  namespace ublas = boost::numeric::ublas;\n\n  // point C is mouse pointer\n  // point X is point at the intersection of AB with CX\n  // vector CX is perpendicular line from C to line AB\n  ublas::vector<double> v_AB(2);\n  ublas::vector<double> v_nAB(2); // nAB is unit vector of AB\n  ublas::vector<double> v_AC(2);\n  ublas::vector<double> v_AX(2);\n  ublas::vector<double> v_CX(2);\n  double len_AB;                  // length of vector AB\n  double len_AX;                  // length of vector AX\n  double len_CX;                  // length of vector CX\n\n  // vector AB\n  v_AB[0] = xb - xa; // AB.x\n  v_AB[1] = yb - ya; // AB.y\n  // length of AB\n  len_AB = ublas::norm_2(v_AB);\n\n  // unit vector nAB\n  v_nAB = v_AB / len_AB;\n\n  // vector AC\n  v_AC[0] = xc - xa; // AC.x\n  v_AC[1] = yc - ya; // AC.y\n\n  // length of AX\n  len_AX = ublas::inner_prod(v_AC, v_nAB); // (AC,nAB)\n  // vector AX\n  v_AX = v_nAB * len_AX; // AX = nAB*|AX|\n\n  // vector CX\n  v_CX = v_AX - v_AC;\n  // length of CX\n  len_CX = ublas::norm_2(v_CX);\n\n  // debug log\n  std::cout << \"length of AB    : \" << len_AB << std::endl;\n  std::cout << \"length of AX    : \" << len_AX << std::endl;\n  std::cout << \"dist from C to X: \" << len_CX << std::endl;\n  std::cout << \"check length CX : \"\n    << ((len_CX < r)?\"true\":\"false\") << std::endl;\n  std::cout << \"check length AX : \"\n    << ((len_AX < len_AB)?\"true\":\"false\") << std::endl;\n\n  bool pointer_isOnLine = (len_CX < r) && (len_AX <= len_AB);\n\n  return pointer_isOnLine;\n}\n", "meta": {"hexsha": "73ca5dfab71e0b17d2d290fcc37b81b02ad760ab", "size": 2786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ontheline.cpp", "max_stars_repo_name": "hiratake26to/tg_ontheline", "max_stars_repo_head_hexsha": "e471378eff39ea1fd134d0f155a6f159a30462b3", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ontheline.cpp", "max_issues_repo_name": "hiratake26to/tg_ontheline", "max_issues_repo_head_hexsha": "e471378eff39ea1fd134d0f155a6f159a30462b3", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ontheline.cpp", "max_forks_repo_name": "hiratake26to/tg_ontheline", "max_forks_repo_head_hexsha": "e471378eff39ea1fd134d0f155a6f159a30462b3", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7216494845, "max_line_length": 72, "alphanum_fraction": 0.5484565686, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.673241525825901}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <math.h>\r\n#include <iostream>\r\n#include <vector>\r\n#include <array>\r\n#include \"heatEquation.hpp\"\r\n#include \"TriDiagMatrix.hpp\"\r\n#include \"MassMatrix.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <fstream>\r\n#include <string>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\nvoid HeatEquation::SetSpaceTimeMesh( SpaceMesh smesh, TimeMesh tmesh, const std::string outputFileName )\r\n{\r\n    mpsmesh = smesh;\r\n    mptmesh = tmesh;\r\n    mpcurrenTimeStep = 0;\r\n}\r\n\r\nvoid HeatEquation::Solve()\r\n{\r\nAnalyticSolutionVec();\r\nmpPreviousSolution = mpAnalyticSolution;\r\n\r\nint m = mptmesh.NumberOfTimeSteps();\r\nfor(int j = 0; j<m; j++)\r\n{\r\nmpcurrenTimeStep = j+1;\r\nmpcurrentMeshIndex = j;\r\nstiff.BuildStiffnessMatrix( mpsmesh );\r\nstiff.MultiplyByScalar( mptmesh.ReadTimeMesh(mpcurrentMeshIndex) );\r\nmass.BuildMassMatrix(mpsmesh);\r\nLHS.AddTwoMatrices( mass, stiff );\r\n\r\nmass.MatrixVectorMultiplier( mpPreviousSolution, mpRHS );\r\n\r\nLHS.MatrixSolver( mpRHS, mpx );\r\n\r\nmpPreviousSolution = mpx;\r\n\r\n}\r\n}\r\n\r\n\r\n\r\n\r\nvoid HeatEquation::AnalyticSolutionVec( )\r\n{\r\n    mpAnalyticSolution.clear();\r\n     for (int i = 0; i<mpsmesh.meshsize()-1; i++)\r\n{\r\n\r\n    mpAnalyticSolution.push_back(ContinuousAnalyticSolution( mpsmesh.ReadSpaceNode(i+1),\r\n                                                                        mptmesh.ReadTimeStep(mpcurrenTimeStep)));\r\n}\r\n}\r\n\r\n\r\n    //the if statements deal with what happens if you are in the first interval\r\n    //in this case the first value of u is given by the boundary condition\r\n    //all the other elements can be fixed for x = 0\r\n    //this function only works for the static case if the mesh changes everything is fucked\r\ndouble HeatEquation::PiecewiseU( double x, SpaceMesh currentsmesh, std::vector<double> U )\r\n{\r\n    std::array<double, 2> firstpoint;\r\n    std::array<double, 2> secondpoint;\r\n\r\n    int upperindex = currentsmesh.IndexAbove( x );\r\n\r\n    auto boundaryconditionU0 = 0;\r\n    auto boundarycondition1Un = 0;\r\n\r\n    if((upperindex==1)||(upperindex==0))\r\n    {\r\n    firstpoint.at(0)= currentsmesh.ReadSpaceNode(0);\r\n    firstpoint.at(1) = boundaryconditionU0;\r\n\r\n    secondpoint[0] = currentsmesh.ReadSpaceNode(1);\r\n    secondpoint.at(1) = U.at(0);\r\n    }\r\n    else if (upperindex == currentsmesh.meshsize())\r\n    {\r\n    firstpoint.at(0)= currentsmesh.ReadSpaceNode(upperindex-1);\r\n    firstpoint.at(1) = U.at(upperindex-2);\r\n\r\n    secondpoint[0] = currentsmesh.ReadSpaceNode(upperindex);\r\n    secondpoint.at(1) = boundarycondition1Un;\r\n    }\r\n    else\r\n    {\r\n    firstpoint.at(0)= currentsmesh.ReadSpaceNode(upperindex-1);\r\n    firstpoint.at(1) = U.at(upperindex-2);\r\n\r\n    secondpoint[0] = currentsmesh.ReadSpaceNode(upperindex);\r\n    secondpoint.at(1) = U.at(upperindex-1);\r\n    }\r\n\r\n    long double m = (firstpoint[1]-secondpoint[1])/(firstpoint[0]-secondpoint[0]);\r\n\r\n    return m*(x - firstpoint[0])+firstpoint[1];\r\n}\r\n\r\n\r\ndouble HeatEquation::ContinuousAnalyticSolution( double x, double t )\r\n{\r\n     return 6*exp(-t)*sin(M_PI*x);\r\n}\r\n\r\n\r\nvoid HeatEquation::BuildErrorMesh()\r\n{\r\nmpErrorMesh.clear();\r\n\r\nauto SquaredError = [&](double x)\r\n    { return pow(PiecewiseU(x, mpsmesh, mpx)-ContinuousAnalyticSolution(x, mptmesh.ReadTimeStep(mpcurrenTimeStep)), 2); };\r\n\r\ndouble Q;\r\nfor(int i=0; i<mpsmesh.meshsize(); i++)\r\n{\r\nQ = gauss<double, 7>::integrate(SquaredError, mpsmesh.ReadSpaceNode(i), mpsmesh.ReadSpaceNode(i+1));\r\nmpErrorMesh.push_back( Q );\r\n}\r\n\r\n}\r\n\r\ndouble HeatEquation::GlobalSpaceError()\r\n{\r\n    BuildErrorMesh();\r\n    double globalError=0;\r\n    for(auto k: mpErrorMesh)\r\n        globalError = globalError + k;\r\n\r\n    std::cout << sqrt(globalError);\r\n    std::cout << \" \\n\";\r\n    return sqrt(globalError);\r\n}\r\n\r\nvoid HeatEquation::PrintErrorMesh()\r\n{\r\n    BuildErrorMesh();\r\n    PrintVector(mpErrorMesh);\r\n}\r\n\r\n\r\nvoid HeatEquation::PrintSolution( )\r\n{\r\n        BuildErrorMesh();\r\n        AnalyticSolutionVec();\r\n\r\n        std::cout << \"FEM Approximation:     \";\r\n        PrintVector(mpx);\r\n        std::cout << \"Analytic Solution:     \";\r\n        PrintVector(mpAnalyticSolution);\r\n        std::cout << \"Error Mesh:            \";\r\n        PrintVector(mpErrorMesh);\r\n        std::cout << \"Global Error           \";\r\n        GlobalSpaceError();\r\n}\r\n\r\nvoid HeatEquation::PrintVector( std::vector<double> aVector)\r\n{\r\n        for (auto k: aVector)\r\n        std::cout << k << \", \";\r\n        std::cout << \" \\n\";\r\n}\r\n\r\nvoid HeatEquation::AddVectors(std::vector<double>func1, std::vector<double> func2, std::vector<double>& result)\r\n{\r\n    if(func1.size()==func2.size())\r\n    {\r\n    result.clear();\r\n     for ( int i=0; i<func1.size(); i++ )\r\n     {\r\n         result.push_back(func1.at(i)+func2.at(i));\r\n     }\r\n    }\r\n    else\r\n    {\r\n        std::cout<< \" your vectors are different sizes\";\r\n        std::cout<<\"\\n\";\r\n    }\r\n}\r\n\r\nvoid HeatEquation::VectorTimesScalar( std::vector<double>& func1, double scalar)\r\n{\r\n         for ( int i=0; i<func1.size(); i++ )\r\n     {\r\n         func1.at(i)= scalar*func1.at(i);\r\n     }\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "d75be4a64e3f16cd5f625ee739e1af92179d583c", "size": 5088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Simple Heat Equation solver class/heatEquation.cpp", "max_stars_repo_name": "thabomiles/FEMHeatEquation", "max_stars_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simple Heat Equation solver class/heatEquation.cpp", "max_issues_repo_name": "thabomiles/FEMHeatEquation", "max_issues_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_issues_repo_licenses": ["MIT"], "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 Heat Equation solver class/heatEquation.cpp", "max_forks_repo_name": "thabomiles/FEMHeatEquation", "max_forks_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_forks_repo_licenses": ["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.696969697, "max_line_length": 123, "alphanum_fraction": 0.6330581761, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6732415159910506}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n//\r\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>, Olga Diamanti <olga.diam@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla Public License\r\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\r\n// obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"rotation_matrix_from_directions.h\"\r\n#include <Eigen/Geometry>\r\n#include <iostream>\r\n\r\ntemplate <typename Scalar>\r\nIGL_INLINE Eigen::Matrix<Scalar, 3, 3> igl::rotation_matrix_from_directions(\r\n  const Eigen::Matrix<Scalar, 3, 1> v0,\r\n  const Eigen::Matrix<Scalar, 3, 1> v1)\r\n{\r\n  Eigen::Matrix<Scalar, 3, 3> rotM;\r\n  const double epsilon=1e-8;\r\n  Scalar dot=v0.normalized().dot(v1.normalized());\r\n  ///control if there is no rotation\r\n  if ((v0-v1).norm()<epsilon)\r\n  {\r\n    rotM = Eigen::Matrix<Scalar, 3, 3>::Identity();\r\n    return rotM;\r\n  }\r\n  if ((v0+v1).norm()<epsilon)\r\n  {\r\n    rotM = -Eigen::Matrix<Scalar, 3, 3>::Identity();\r\n    rotM(0,0) = 1.;\r\n    std::cerr<<\"igl::rotation_matrix_from_directions: rotating around x axis by 180o\"<<std::endl;\r\n    return rotM;\r\n  }\r\n  ///find the axis of rotation\r\n  Eigen::Matrix<Scalar, 3, 1> axis;\r\n  axis=v0.cross(v1);\r\n  axis.normalize();\r\n\r\n  ///construct rotation matrix\r\n  Scalar u=axis(0);\r\n  Scalar v=axis(1);\r\n  Scalar w=axis(2);\r\n  Scalar phi=acos(dot);\r\n  Scalar rcos = cos(phi);\r\n  Scalar rsin = sin(phi);\r\n\r\n  rotM(0,0) =      rcos + u*u*(1-rcos);\r\n  rotM(1,0) =  w * rsin + v*u*(1-rcos);\r\n  rotM(2,0) = -v * rsin + w*u*(1-rcos);\r\n  rotM(0,1) = -w * rsin + u*v*(1-rcos);\r\n  rotM(1,1) =      rcos + v*v*(1-rcos);\r\n  rotM(2,1) =  u * rsin + w*v*(1-rcos);\r\n  rotM(0,2) =  v * rsin + u*w*(1-rcos);\r\n  rotM(1,2) = -u * rsin + v*w*(1-rcos);\r\n  rotM(2,2) =      rcos + w*w*(1-rcos);\r\n\r\n  return rotM;\r\n}\r\n\r\n#ifdef IGL_STATIC_LIBRARY\r\n// Explicit template instantiation\r\ntemplate Eigen::Matrix<double, 3, 3, 0, 3, 3> igl::rotation_matrix_from_directions<double>(const Eigen::Matrix<double, 3, 1, 0, 3, 1>, const Eigen::Matrix<double, 3, 1, 0, 3, 1>);\r\n#endif\r\n", "meta": {"hexsha": "59196b4594b56ccac723d3e1a56be9c17b82ecab", "size": 2116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/rotation_matrix_from_directions.cpp", "max_stars_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_stars_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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": "igl/rotation_matrix_from_directions.cpp", "max_issues_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_issues_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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": "igl/rotation_matrix_from_directions.cpp", "max_forks_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_forks_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "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.0625, "max_line_length": 180, "alphanum_fraction": 0.6228733459, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.8056321866478978, "lm_q1q2_score": 0.6730924289049619}}
{"text": "#include \"src/metric/pnorm_metric.h\"\n\n\n#include <exception>\n\n#include <armadillo>\n\n#include \"gtest/gtest.h\"\n#include \"gmock/gmock.h\"\n\nnamespace ocr {\n\tclass PNormMetricTests : public testing::Test {\n\tpublic:\n\t\tvoid SetUp() {\n\n\t\t}\n\n\t\tvoid TearDown() {\n\n\t\t}\n\t};\n\n\tTEST_F(PNormMetricTests, Constructor_EmptyParam_Valid) {\n\t\tEXPECT_NO_THROW({ocr::PNorm();});\n\t}\n\n\tTEST_F(PNormMetricTests, Constructor_PosNumberParam_Valid) {\n\t\tEXPECT_NO_THROW({ocr::PNorm(1);});\n\t\tEXPECT_NO_THROW({ocr::PNorm(2);});\n\t}\n\n\tTEST_F(PNormMetricTests, Constructor_ZeroParam_Invalid) {\n\t\tEXPECT_THROW({ocr::PNorm(0);}, std::invalid_argument);\n\t}\n\n\tTEST_F(PNormMetricTests, Distance_EuclideanParam_Test) {\n\t\tocr::PNorm euclidean_metric = ocr::PNorm(2);\n\t\tEXPECT_EQ(0, euclidean_metric.distance({0,0,0},{0,0,0}));\n\t\tEXPECT_EQ(0, euclidean_metric.distance({1,1},{1,1}));\n\t\tEXPECT_EQ(2, euclidean_metric.distance({0,0,0,0},{1,1,1,1}));\n\t\tEXPECT_EQ(2, euclidean_metric.distance({1,0,1,0},{0,1,0,1}));\n\t}\n\n\tTEST_F(PNormMetricTests, Distance_ManhattanParam_Test) {\n\t\tocr::PNorm manhattan_metric = ocr::PNorm(1);\n\t\tEXPECT_EQ(0, manhattan_metric.distance({0,0,0},{0,0,0}));\n\t\tEXPECT_EQ(0, manhattan_metric.distance({1,1},{1,1}));\n\t\tEXPECT_EQ(4, manhattan_metric.distance({0,0,0,0},{1,1,1,1}));\n\t\tEXPECT_EQ(4, manhattan_metric.distance({1,0,1,0},{0,1,0,1}));\n\t}\n\n}", "meta": {"hexsha": "4b01fe65d2d66f63144460632f939c1f61869ef2", "size": 1326, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/metric/pnorm_metric.cc", "max_stars_repo_name": "amadavan/OCR", "max_stars_repo_head_hexsha": "05c323593302c9183005b067cdf1d48864727f29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/metric/pnorm_metric.cc", "max_issues_repo_name": "amadavan/OCR", "max_issues_repo_head_hexsha": "05c323593302c9183005b067cdf1d48864727f29", "max_issues_repo_licenses": ["MIT"], "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/metric/pnorm_metric.cc", "max_forks_repo_name": "amadavan/OCR", "max_forks_repo_head_hexsha": "05c323593302c9183005b067cdf1d48864727f29", "max_forks_repo_licenses": ["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.5, "max_line_length": 63, "alphanum_fraction": 0.7013574661, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6730809688918511}}
{"text": "#ifndef BURKARDT_ODE_HPP\n#define BURKARDT_ODE_HPP\n\n// ODE test problem set from\n//   https://people.sc.fsu.edu/~burkardt/f_src/test_ode/test_ode.html\n//   https://people.sc.fsu.edu/~burkardt/f_src/test_ode/test_ode.f90\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\nclass P01 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = - x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P02 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = - x(0)* x(0)*x(0) / 2.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P03 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = - cos(t) * x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P04 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = x(0) * (20. - x(0)) / 80.;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P05 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = (x(0) - t) / (x(0) + t);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 4.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P06 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = 2. * x(0) * (1. - x(1));\n\t\ty(1) = - x(1) * (1. - x(0));\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 1.;\n\t\tx(1) = 3.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P07 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(3);\n\n\t\ty(0) = -x(0) + x(1);\n\t\ty(1) = x(0) - 2. * x(1) + x(2);\n\t\ty(2) = x(1) - x(2);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(3);\n\t\tx(0) = 2.;\n\t\tx(1) = 0.;\n\t\tx(2) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P08 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(3);\n\n\t\ty(0) = -x(0);\n\t\ty(1) = x(0) - x(1) * x(1);\n\t\ty(2) = x(1) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(3);\n\t\tx(0) = 1.;\n\t\tx(1) = 0.;\n\t\tx(2) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P09 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(3);\n\n\t\tT norm;\n\n\t\tnorm = sqrt(x(0)*x(0) + x(1)*x(1));\n\n\t\ty(0) = - x(1) - x(0) * x(2) / norm;\n\t\ty(1) = x(0) - x(1) * x(2) / norm;\n\t\ty(2) = x(0) / norm;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(3);\n\t\tx(0) = 3.;\n\t\tx(1) = 0.;\n\t\tx(2) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P10 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(3);\n\n\t\ty(0) = x(1) * x(2);\n\t\ty(1) = - x(0) * x(2);\n\t\ty(2) = -0.51 * x(0) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(3);\n\t\tx(0) = 0.;\n\t\tx(1) = 1.;\n\t\tx(2) = 1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P11 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(10);\n\t\tint i;\n\n\t\ty(0) = - x(0);\n\t\tfor (i=1; i<9; i++) {\n\t\t\ty(i) = x(i-1) - x(i);\n\t\t}\n\t\ty(9) = - x(8);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(10);\n\t\tx(0) = 1.;\n\t\tfor (i=1; i<10; i++) {\n\t\t\tx(i) = 0.;\n\t\t}\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P12 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(10);\n\t\tint i;\n\n\t\ty(0) = - x(0);\n\t\tfor (i=1; i<9; i++) {\n\t\t\ty(i) = (double)i * x(i-1) - (double)(i+1) * x(i);\n\t\t}\n\t\ty(9) = - 9. * x(8);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(10);\n\t\tx(0) = 1.;\n\t\tfor (i=1; i<10; i++) {\n\t\t\tx(i) = 0.;\n\t\t}\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P13 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(10);\n\t\tint i;\n\n\t\ty(0) = - 2. * x(0) + x(1);\n\t\tfor (i=1; i<9; i++) {\n\t\t\ty(i) = x(i-1) - 2. * x(i) + x(i+1);\n\t\t}\n\t\ty(9) = x(8) - 2. * x(9);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(10);\n\t\tx(0) = 1.;\n\t\tfor (i=1; i<10; i++) {\n\t\t\tx(i) = 0.;\n\t\t}\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P14 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(51);\n\t\tint i;\n\n\t\ty(0) = - 2. * x(0) + x(1);\n\t\tfor (i=1; i<50; i++) {\n\t\t\ty(i) = x(i-1) - 2. * x(i) + x(i+1);\n\t\t}\n\t\ty(50) = x(49) - 2. * x(50);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tint i;\n\n\t\tx.resize(51);\n\t\tx(0) = 1.;\n\t\tfor (i=1; i<51; i++) {\n\t\t\tx(i) = 0.;\n\t\t}\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P15 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(30);\n\t\tconst double k2 = 2.95912208286;\n\t\tconst double m[6] = {\n\t\t\t1.00000597682,\n\t\t\t0.954786104043e-03,\n\t\t\t0.285583733151e-03,\n\t\t\t0.437273164546e-04,\n\t\t\t0.517759138449e-04,\n\t\t\t0.277777777778e-05\n\t\t};\n\t\tint i, i3, j, l, ll, mm;\n\t\tT p;\n\t\tT q[5][5];\n\t\tT r[5];\n\n\t\ti = 0;\n\t\tfor (l=3; l<=15; l+=3) {\n\t\t\ti++;\n\t\t\tp = x(l-3)*x(l-3) + x(l-2)*x(l-2) + x(l-1)*x(l-1);\n\t\t\tr[i-1] = 1. / (p * sqrt(p));\n\t\t\tj = 0;\n\t\t\tfor (ll=3; ll<=15; ll+=3) {\n\t\t\t\tj++;\n\t\t\t\tif (ll != l) {\n\t\t\t\t\tp = (x(l-3) - x(ll-3)) * (x(l-3) - x(ll-3))\n\t\t\t\t\t+ (x(l-2) - x(ll-2)) * (x(l-2) - x(ll-2))\n\t\t\t\t\t+ (x(l-1) - x(ll-1)) * (x(l-1) - x(ll-1));\n\t\t\t\t\tq[i-1][j-1] = 1. / (p * sqrt(p));\n\t\t\t\t\tq[j-1][i-1] = q[i-1][j-1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ti3 = 0;\n\t\tfor (i=1; i<=5; i++) {\n\t\t\ti3 += 3;\n\t\t\tfor (ll = i3-2; ll <= i3; ll++) {\n\t\t\t\tmm = ll - i3;\n\t\t\t\ty(ll-1) = x(ll+14);\n\t\t\t\tp = 0.;\n\t\t\t\tfor (j=1; j<=5; j++) {\n\t\t\t\t\tmm += 3;\n\t\t\t\t\tif (j != i) {\n\t\t\t\t\t\tp += m[j-1] * (x(mm-1) * (q[i-1][j-1] - r[j-1]) - x(ll-1) * q[i-1][j-1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ty(ll+14) = k2 * ( - (m[0] + m[i]) * x(ll-1) * r[i-1] + p);\n\t\t\t}\n\t\t}\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tx.resize(30);\n\n\t\tx(0) = 3.42947415189;\n\t\tx(1) = 3.35386959711;\n\t\tx(2) = 1.35494901715;\n\t\tx(3) = 6.64145542550;\n\t\tx(4) = 5.97156957878;\n\t\tx(5) = 2.18231499728;\n\t\tx(6) = 11.2630437207;\n\t\tx(7) = 14.6952576794;\n\t\tx(8) = 6.27960525067;\n\t\tx(9) = -30.1552268759;\n\t\tx(10) = 1.65699966404;\n\t\tx(11) = 1.43785752721;\n\t\tx(12) = -21.1238353380;\n\t\tx(13) = 28.4465098142;\n\t\tx(14) = 15.3882659679;\n\t\tx(15) = -0.557160570446;\n\t\tx(16) = 0.505696783289;\n\t\tx(17) = 0.230578543901;\n\t\tx(18) = -0.415570776342;\n\t\tx(19) = 0.365682722812;\n\t\tx(20) = 0.169143213293;\n\t\tx(21) = -0.325325669158;\n\t\tx(22) = 0.189706021964;\n\t\tx(23) = 0.0877265322780;\n\t\tx(24) = -0.0240476254170;\n\t\tx(25) = -0.287659532608;\n\t\tx(26) = -0.117219543175;\n\t\tx(27) = -0.176860753121;\n\t\tx(28) = -0.216393453025;\n\t\tx(29) = -0.0148647893090;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n\nclass P16 {\n\tpublic:\n\tdouble delta;\n\n\tP16(double _delta = 0.1) : delta(_delta) {}\n\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(4);\n\t\tT tmp;\n\n\t\ttmp = sqrt(x(0) * x(0) + x(1) * x(1));\n\t\ty(0) = x(2);\n\t\ty(1) = x(3);\n\t\ty(2) = - x(0) / (tmp * tmp * tmp);\n\t\ty(3) = - x(1) / (tmp * tmp * tmp);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\t\tx.resize(4);\n\t\tx(0) = 1. - delta;\n\t\tx(1) = 0.;\n\t\tx(2) = 0.;\n\t\tx(3) = sqrt((1. + delta)/(1. - delta));\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// P17-P20\u306fP16\u306e\u521d\u671f\u5024\u9055\u3044\u3002\n// P16, P17\u306f\u89e3\u3051\u308b\u304c\u3001P18-P20\u306f\u53b3\u3057\u3044\u3002\n\nclass P17 : public P16 {\n\tpublic:\n\tP17(double _delta = 0.3) {delta = _delta;}\n};\n\nclass P18 : public P16 {\n\tpublic:\n\tP18(double _delta = 0.5) {delta = _delta;}\n};\n\nclass P19 : public P16 {\n\tpublic:\n\tP19(double _delta = 0.7) {delta = _delta;}\n};\n\nclass P20 : public P16 {\n\tpublic:\n\tP20(double _delta = 0.9) {delta = _delta;}\n};\n\nclass P21 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = - ( 1. - 0.25 / ((t + 1.) * (t + 1.))) * x(0) - 1. / (t + 1.) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 0.6713967071418030;\n\t\tx(1) = 0.09540051444747446;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P22 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = (1. - x(0) * x(0)) * x(1) - x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 2.;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P23 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = x(0) * x(0) * x(0) / 6. - x(0) + 2. * sin(2.78535 * t);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 0.;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P24 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = 0.032 - 0.4 * x(1) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 30.;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\nclass P25 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = sqrt(1. + x(1) * x(1)) / (25. - t);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 0.;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// Lotka-Volterra Predator-Prey Equations\nclass P31 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\t\tconst double a = 5.;\n\t\tconst double b = 1.;\n\t\tconst double c = 0.5;\n\t\tconst double d = 2.;\n\n\t\ty(0) = (a - b * x(1)) * x(0);\n\t\ty(1) = (c * x(0) - d) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 2.;\n\t\tx(1) = 2.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 10.;\n\t}\n};\n\n// The Lorenz System\nclass P32 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(3);\n\t\tconst double beta = 8./3.;\n\t\tconst double rho = 28.;\n\t\tconst double sigma = 10.;\n\n\t\ty(0) = sigma * (x(1) - x(0));\n\t\ty(1) = rho * x(0) - x(1) - x(0) * x(2);\n\t\ty(2) = - beta * x(2) + x(0) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(3);\n\t\tx(0) = 2.;\n\t\tx(1) = 2.;\n\t\tx(2) = 21.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// The Van der Pol equation\nclass P33 {\n\tpublic:\n\n\tdouble delta;\n\n\tP33(double _delta = 1.) : delta(_delta) {}\n\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = delta * (1. - x(0) * x(0)) * x(1) - x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 2.;\n\t\tx(1) = 2.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// The Linearized Damped Pendulum\nclass P34 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\t\tconst double g = 32.;\n\t\tconst double k = 1.;\n\t\tconst double l = 1.;\n\t\tconst double m = 1.;\n\n\t\ty(0) = x(1);\n\t\ty(1) = - (g / l) * x(0) - (k / m) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 2.;\n\t\tx(1) = 2.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// The Nonlinear Damped Pendulum\nclass P35 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\t\tconst double g = 32.;\n\t\tconst double k = 1.;\n\t\tconst double l = 1.;\n\t\tconst double m = 1.;\n\n\t\ty(0) = x(1);\n\t\ty(1) = - (g / l) * sin(x(0)) - (k / m) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 2.;\n\t\tx(1) = 2.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 20.;\n\t}\n};\n\n// Duffing's Equation\nclass P36 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = x(0) * (1. - x(0) * x(0));\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 0.5;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 100.;\n\t}\n};\n\n// Duffing's Equation with Damping and Forcing\nclass P37 {\n\tpublic:\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(2);\n\t\tconst double a = 0.3;\n\t\tconst double k = 0.2;\n\t\tconst double w = 1.;\n\n\t\ty(0) = x(1);\n\t\ty(1) = x(0) * (1. - x(0) * x(0)) - k * x(1) + a * cos(w * t);\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(2);\n\t\tx(0) = 0.5;\n\t\tx(1) = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 100.;\n\t}\n};\n\n// Shampine's Ball of Flame\nclass P38 {\n\tpublic:\n\tdouble delta;\n\n\tP38(double _delta = 0.01) : delta(_delta) {}\n\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = x(0) * x(0) * (1. - x(0));\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = delta;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 2./delta;\n\t}\n};\n\n// Polking's first order ODE\nclass P39 {\n\tpublic:\n\n\tdouble a;\n\tdouble b;\n\n\tP39(double _a = 1., double _b = 0.) : a(_a), b(_b) {}\n\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = x(0) * x(0) - a * t + b;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = 0.5;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = 0.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = (b + 9.) / a;\n\t}\n};\n\n// the Kee problem\nclass P40 {\n\tpublic:\n\n\tdouble eps;\n\n\tP40(double _eps = 0.01) : eps(_eps) {}\n\n\ttemplate <class T> ub::vector<T> operator() (ub::vector<T> x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = x(0) * (x(0) - t) / eps;\n\n\t\treturn y;\n\t}\n\n\ttemplate<class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >& x) {\n\n\t\tx.resize(1);\n\t\tx(0) = -1.;\n\t}\n\n\ttemplate<class T>\n\tvoid start_time(kv::interval<T>& x) {\n\n\t\tx = -1.;\n\t}\n\n\ttemplate<class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\n\t\tx = 1.;\n\t}\n};\n\n#endif // BURKARDT_ODE_HPP\n", "meta": {"hexsha": "6032b0fd4875b4c4ae8a687dc5a778a09780ec91", "size": 18427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/burkardt-ode.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": "example/burkardt-ode.hpp", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "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": "example/burkardt-ode.hpp", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "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": 15.5240101095, "max_line_length": 79, "alphanum_fraction": 0.5283551311, "num_tokens": 7418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6730809586122836}}
{"text": "///////////////////////////////////\n#include <boost/test/unit_test.hpp>\n///////////////////////////\n#include \"distancefixture.h\"\n/////////////////////////\n#include <indivtree.h>\n#include <clusterize_kmeans.h>\n/////////////////////////////////\n#include <boost/foreach.hpp>\n//////////////////////\nusing namespace std;\nusing namespace info;\n/////////////////////////////\nBOOST_FIXTURE_TEST_SUITE(IndivTreeTestSuite, DistanceFixture)\n;\nBOOST_AUTO_TEST_CASE(testIndivTreeMean) {\n\tINumIndivProvider *pProvider = m_pnumprovider.get();\n\tBOOST_REQUIRE(pProvider != nullptr);\n\tsize_t nbClusters = 5;\n\tLinkMode mode = LinkMode::linkMean;\n\tIndivsTree oTree;\n\toTree.process(pProvider, nbClusters, mode);\n\tints_size_t_map xMap;\n\toTree.get_map(xMap);\n\tsize_t n = xMap.size();\n\tBOOST_CHECK(n == m_nbrows);\n\tIndivsTree::valuemaps_vector oCenters;\n\toTree.get_centers(oCenters);\n\tBOOST_CHECK(oCenters.size() == nbClusters);\n\t//int nx = 0;\n\t//BOOST_TEST_MESSAGE(\"LINK MEAN\");\n\tBOOST_FOREACH(const DbValueMap &oMap, oCenters)\n\t{\n\t\tstd::string ss;\n\t\tthis->write_point(oMap, ss);\n\t\t//BOOST_TEST_MESSAGE(\"Cluster \" << nx++ << \":\\t\" << ss);\n\t}\n\t/*\n\tstd::string sx;\n\tthis->write_indis_map(xMap,sx);\n\tBOOST_TEST_MESSAGE(sx);\n\t*/\n} //testInfoGlobalClusterize\nBOOST_AUTO_TEST_CASE(testIndivTreeMin) {\n\tINumIndivProvider *pProvider = m_pnumprovider.get();\n\tBOOST_REQUIRE(pProvider != nullptr);\n\tsize_t nbClusters = 5;\n\tLinkMode mode = LinkMode::linkMin;\n\tIndivsTree oTree;\n\toTree.process(pProvider, nbClusters, mode);\n\tints_size_t_map xMap;\n\toTree.get_map(xMap);\n\tsize_t n = xMap.size();\n\tBOOST_CHECK(n == m_nbrows);\n\tIndivsTree::valuemaps_vector oCenters;\n\toTree.get_centers(oCenters);\n\tBOOST_CHECK(oCenters.size() == nbClusters);\n\t//int nx = 0;\n\t//BOOST_TEST_MESSAGE(\"LINK MAX\");\n\tBOOST_FOREACH(const DbValueMap &oMap, oCenters)\n\t{\n\t\tstd::string ss;\n\t\tthis->write_point(oMap, ss);\n\t\t//BOOST_TEST_MESSAGE(\"Cluster \" << nx++ << \":\\t\" << ss);\n\t}\n\t/*\n\tstd::string sx;\n\tthis->write_indis_map(xMap, sx);\n\tBOOST_TEST_MESSAGE(sx);\n\t*/\n} //testInfoGlobalClusterize\nBOOST_AUTO_TEST_CASE(testIndivTreeMax) {\n\tINumIndivProvider *pProvider = m_pnumprovider.get();\n\tBOOST_REQUIRE(pProvider != nullptr);\n\tsize_t nbClusters = 5;\n\tLinkMode mode = LinkMode::linkMax;\n\tIndivsTree oTree;\n\toTree.process(pProvider, nbClusters, mode);\n\tints_size_t_map xMap;\n\toTree.get_map(xMap);\n\tsize_t n = xMap.size();\n\tBOOST_CHECK(n == m_nbrows);\n\tIndivsTree::valuemaps_vector oCenters;\n\toTree.get_centers(oCenters);\n\tBOOST_CHECK(oCenters.size() == nbClusters);\n\t//int nx = 0;\n\t//BOOST_TEST_MESSAGE(\"LINK MIN\");\n\tBOOST_FOREACH(const DbValueMap &oMap, oCenters)\n\t{\n\t\tstd::string ss;\n\t\tthis->write_point(oMap, ss);\n\t\t//BOOST_TEST_MESSAGE(\"Cluster \" << nx++ << \":\\t\" << ss);\n\t}\n\t/*\n\tstd::string sx;\n\tthis->write_indis_map(xMap, sx);\n\tBOOST_TEST_MESSAGE(sx);\n\t*/\n} //testInfoGlobalClusterize\nBOOST_AUTO_TEST_CASE(testClusterizeKMeansWithSeed) {\n\t//BOOST_TEST_MESSAGE(\"ClusterizeKMeansSeed\");\n\tINumIndivProvider *pProvider = m_pnumprovider.get();\n\tBOOST_REQUIRE(pProvider != nullptr);\n\tLinkMode mode = LinkMode::linkMin;\n\tsize_t nbClusters = 5;\n\tIndivsTree oTree;\n\toTree.process(pProvider, nbClusters, mode);\n\tIndivsTree::valuemaps_vector oCenters;\n\toTree.get_centers(oCenters);\n\tBOOST_CHECK(oCenters.size() == nbClusters);\n\tsize_t nbMaxIters = 100;\n\tClusterizeKMeans oMeans(pProvider, nbClusters);\n\tBOOST_REQUIRE(oMeans.is_valid());\n\tbool bRet = oMeans.compute(oCenters,nbMaxIters);\n\tBOOST_REQUIRE(bRet);\n\tdouble fIntra = 0, fInter = 0, fCrit = 0;\n\tbRet = oMeans.intra_inertia(fIntra);\n\tBOOST_CHECK(bRet);\n\tBOOST_CHECK(fIntra > 0);\n\tbRet = oMeans.inter_inertia(fInter);\n\tBOOST_CHECK(bRet);\n\tBOOST_CHECK(fInter > 0);\n\tbRet = oMeans.criteria(fCrit);\n\tBOOST_CHECK(bRet);\n\tBOOST_CHECK(fCrit > 0);\n\t//BOOST_TEST_MESSAGE(\"Criteria: \" << fCrit << \"\\tIntra: \" << fIntra << \"\\tInter: \" << fInter);\n\tconst indivclusters_vector & oClusters = oMeans.clusters();\n\tBOOST_FOREACH(const IndivCluster &oCluster, oClusters)\n\t{\n\t\tstd::string ss;\n\t\tthis->write_point(oCluster.center(), ss);\n\t  //BOOST_TEST_MESSAGE(\"Cluster: \" << oCluster.index() << \"\\t\" << ss);\n\t}// oCluster\n\tints_size_t_map xMap = oMeans.get_map();\n\tstd::string sx;\n\tthis->write_indis_map(xMap, sx);\n\t//BOOST_TEST_MESSAGE(sx);\n} //testClusterizeKMeans\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "5e4c44b36e1c5fe21c5f080dedc20e382a90c478", "size": 4264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_testdtatdata/tests/test_indivtreecpp.cpp", "max_stars_repo_name": "boubad/CygProjects", "max_stars_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "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_testdtatdata/tests/test_indivtreecpp.cpp", "max_issues_repo_name": "boubad/CygProjects", "max_issues_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "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_testdtatdata/tests/test_indivtreecpp.cpp", "max_forks_repo_name": "boubad/CygProjects", "max_forks_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "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.4571428571, "max_line_length": 95, "alphanum_fraction": 0.7042682927, "num_tokens": 1214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6730809524316865}}
{"text": "//\n// Copyright (c) 2019-2020 CNRS INRIA\n//\n\n#include <boost/python.hpp>\n\n#include \"pinocchio/bindings/python/fwd.hpp\"\n#include \"pinocchio/bindings/python/utils/namespace.hpp\"\n#include \"pinocchio/math/rpy.hpp\"\n\nnamespace pinocchio\n{\n  namespace python\n  {\n    namespace bp = boost::python;\n\n    Eigen::Matrix3d rpyToMatrix_proxy(const Eigen::Vector3d & rpy)\n    {\n      return pinocchio::rpy::rpyToMatrix(rpy);\n    }\n\n    Eigen::Vector3d matrixToRpy_proxy(const Eigen::Matrix3d & R)\n    {\n      return pinocchio::rpy::matrixToRpy(R);\n    }\n\n    Eigen::Matrix3d rotate(const std::string & axis, const double ang)\n    {\n      if(axis.length() != 1U)\n          throw std::invalid_argument(std::string(\"Invalid axis: \").append(axis));\n      Eigen::Vector3d u;\n      u.setZero();\n      const char axis_ = axis[0];\n      switch(axis_)\n      {\n        case 'x': u[0] = 1.; break;\n        case 'y': u[1] = 1.; break;\n        case 'z': u[2] = 1.; break;\n        default: throw std::invalid_argument(std::string(\"Invalid axis: \").append(1U,axis_));\n      }\n\n      return Eigen::AngleAxisd(ang, u).matrix();\n    }\n\n    void exposeRpy()\n    {\n      using namespace Eigen;\n      using namespace pinocchio::rpy;\n\n      {\n        // using the rpy scope\n        bp::scope current_scope = getOrCreatePythonNamespace(\"rpy\");\n\n        bp::def(\"rpyToMatrix\",\n                static_cast<Matrix3d (*)(const double, const double, const double)>(&rpyToMatrix),\n                bp::args(\"roll\", \"pitch\", \"yaw\"),\n                \"Given (r, p, y), the rotation is given as R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a\");\n\n        bp::def(\"rpyToMatrix\",\n                &rpyToMatrix_proxy,\n                bp::arg(\"rpy\"),\n                \"Given (r, p, y), the rotation is given as R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a\");\n\n        bp::def(\"matrixToRpy\",\n                &matrixToRpy_proxy,\n                bp::arg(\"R\"),\n                \"Given a rotation matrix R, the angles (r, p, y) are given so that R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a.\"\n                \" The angles are guaranteed to be in the ranges: r in [-pi,pi],\"\n                \" p in[-pi/2,pi/2], y in [-pi,pi]\");\n\n        bp::def(\"rotate\",\n                &rotate,\n                bp::args(\"axis\", \"ang\"),\n                \"Rotation matrix corresponding to a rotation about x, y or z\"\n                \" e.g. R = rot('x', pi / 4): rotate pi/4 rad about x axis\");\n      }\n      \n    }\n    \n  } // namespace python\n} // namespace pinocchio\n", "meta": {"hexsha": "283b2d4b6a0ca8a24b3364ef22f98b8541b6751f", "size": 2667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/python/math/expose-rpy.cpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "bindings/python/math/expose-rpy.cpp", "max_issues_repo_name": "dengs08/pinocchio", "max_issues_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bindings/python/math/expose-rpy.cpp", "max_forks_repo_name": "dengs08/pinocchio", "max_forks_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-21T01:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:59:35.000Z", "avg_line_length": 31.3764705882, "max_line_length": 107, "alphanum_fraction": 0.5526809149, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7956580976404297, "lm_q1q2_score": 0.6730809503822011}}
{"text": "// Copyright 2020 Josh Pieper, jjp@pobox.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#include \"base/fit_plane.h\"\n\n#include <boost/test/auto_unit_test.hpp>\n\nusing mjmech::base::FitPlane;\n\nBOOST_AUTO_TEST_CASE(BasicFitPlane, * boost::unit_test::tolerance(1e-4)) {\n  {\n    std::vector<Eigen::Vector3d> points = {\n      { -2, -2, -1 },\n      { -2, 2, -1 },\n      { 2, -2, 1 },\n      { 2, 2, 1 },\n    };\n\n    const auto result = FitPlane(points);\n    BOOST_TEST(std::abs(result.c - 0.0) < 0.001);\n    BOOST_TEST(result.a == 0.5);\n    BOOST_TEST(result.b == 0.0);\n  }\n\n  {\n    std::vector<Eigen::Vector3d> points = {\n      { -2, -2, 0 },\n      { -2, 2, 2 },\n      { 2, -2, 0 },\n      { 2, 2, 2 },\n    };\n\n    const auto result = FitPlane(points);\n    BOOST_TEST(result.c == 1.0);\n    BOOST_TEST(result.a == 0.0);\n    BOOST_TEST(result.b == 0.5);\n  }\n}\n", "meta": {"hexsha": "56fe748e8ad1703e164ab2159e6d75c40d07d335", "size": 1366, "ext": "cc", "lang": "C++", "max_stars_repo_path": "base/test/fit_plane_test.cc", "max_stars_repo_name": "rkb-1/quad", "max_stars_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2017-01-18T15:12:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:28:11.000Z", "max_issues_repo_path": "base/test/fit_plane_test.cc", "max_issues_repo_name": "rkb-1/quad", "max_issues_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-11T14:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T16:49:57.000Z", "max_forks_repo_path": "base/test/fit_plane_test.cc", "max_forks_repo_name": "rkb-1/quad", "max_forks_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T09:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T16:20:35.000Z", "avg_line_length": 27.32, "max_line_length": 75, "alphanum_fraction": 0.6207906296, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7956580927949806, "lm_q1q2_score": 0.6730809401026331}}
{"text": "#pragma once\n#include <cmath>\n#include <autoppl/math/math.hpp>\n#include <autoppl/util/traits/dist_expr_traits.hpp>\n#include <fastad_bits/util/type_traits.hpp>\n#include <Eigen/Dense>\n\n// MSVC does not seem to support M_PI\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace ppl {\nnamespace math {\n\nusing dist_value_t = util::dist_value_t;\n\n/////////////////////////////////\n// Compile-time Constants\n/////////////////////////////////\n\ninline constexpr double SQRT_TWO_PI = \n    2.506628274631000502415765284811045;\ninline constexpr double LOG_SQRT_TWO_PI =\n    0.918938533204672741780329736405617;\n\n/////////////////////////////////\n// Normal Density\n/////////////////////////////////\n\n// sss\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<MeanType> &&\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_pdf(const XType& x, \n                               const MeanType& mean, \n                               const SigmaType& sigma)\n{\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z = (x - mean) / sigma;\n    return std::exp(-0.5 * z * z) / (sigma * SQRT_TWO_PI);\n}\n\n// vss\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MeanType> &&\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_pdf(const Eigen::MatrixBase<XType>& x, \n                               const MeanType& mean, \n                               const SigmaType& sigma)\n{\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z_sq = (x.array() - mean).matrix().squaredNorm() / (sigma * sigma);\n    return std::exp(-0.5 * z_sq) / std::pow(sigma * SQRT_TWO_PI, x.size());\n}\n\n// vvs\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_pdf(const Eigen::MatrixBase<XType>& x, \n                               const Eigen::MatrixBase<MeanType>& mean, \n                               const SigmaType& sigma)\n{\n    static_assert(ad::util::is_eigen_vector_v<MeanType>);\n    assert(x.size() == mean.size());\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z_sq = (x.array() - mean.array()).matrix().squaredNorm() / (sigma * sigma);\n    return std::exp(-0.5 * z_sq) / std::pow(sigma * SQRT_TWO_PI, x.size());\n}\n\n// vsv, vsm\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MeanType>\n        > >\ninline dist_value_t normal_pdf(const Eigen::MatrixBase<XType>& x, \n                               const MeanType& mean, \n                               const Eigen::MatrixBase<SigmaType>& sigma)\n{\n    if constexpr (ad::util::is_eigen_vector_v<SigmaType>) {\n        assert(x.size() == sigma.size());\n        if ((sigma.array() <= 0).any()) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = ((x.array() - mean)/sigma.array()).matrix().squaredNorm();\n        return std::exp(-0.5 * z_sq) / (std::pow(SQRT_TWO_PI, x.size()) * sigma.array().prod());\n\n    } else if constexpr (ad::util::is_eigen_matrix_v<SigmaType>) {\n        assert(x.size() == sigma.rows());\n        Eigen::LLT<Eigen::MatrixXd> llt(sigma);\n        if (llt.info() != Eigen::Success) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = llt.matrixL().solve((x.array() - mean).matrix()).squaredNorm();\n        dist_value_t det = llt.matrixL().determinant();\n        return std::exp(-0.5 * z_sq) / (std::pow(SQRT_TWO_PI, x.size()) * det);\n    }\n}\n\n// vvv, vvm\ntemplate <class XType\n        , class MeanType\n        , class SigmaType>\ninline dist_value_t normal_pdf(const Eigen::MatrixBase<XType>& x, \n                               const Eigen::MatrixBase<MeanType>& mean, \n                               const Eigen::MatrixBase<SigmaType>& sigma)\n{\n    static_assert(ad::util::is_eigen_vector_v<MeanType>);\n\n    if constexpr (ad::util::is_eigen_vector_v<SigmaType>) {\n        assert(x.size() == sigma.size());\n        assert(x.size() == mean.size());\n        if ((sigma.array() <= 0).any()) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = ((x.array() - mean.array())/sigma.array()).matrix().squaredNorm();\n        return std::exp(-0.5 * z_sq) / (std::pow(SQRT_TWO_PI, x.size()) * sigma.array().prod());\n    }\n\n    else if constexpr (ad::util::is_eigen_matrix_v<SigmaType>) {\n        assert(x.size() == sigma.rows());\n        assert(x.size() == mean.size());\n        Eigen::LLT<Eigen::MatrixXd> llt(sigma);\n        if (llt.info() != Eigen::Success) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = llt.matrixL().solve((x.array() - mean.array()).matrix()).squaredNorm();\n        dist_value_t det = llt.matrixL().determinant();\n        return std::exp(-0.5 * z_sq) / (std::pow(SQRT_TWO_PI, x.size()) * det);\n    }\n}\n\n// sss\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<MeanType> &&\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_log_pdf(const XType& x, \n                                   const MeanType& mean, \n                                   const SigmaType& sigma)\n{\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z = (x - mean) / sigma;\n    return -0.5 * z * z - std::log(sigma) - LOG_SQRT_TWO_PI;\n}\n\n// vss\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MeanType> &&\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_log_pdf(const Eigen::MatrixBase<XType>& x, \n                           const MeanType& mean, \n                           const SigmaType& sigma)\n{\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z_sq = (x.array() - mean).matrix().squaredNorm() / (sigma * sigma);\n    return -0.5 * z_sq - (x.size() * (std::log(sigma) + LOG_SQRT_TWO_PI));\n}\n\n// vvs\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<SigmaType> \n        > >\ninline dist_value_t normal_log_pdf(const Eigen::MatrixBase<XType>& x, \n                           const Eigen::MatrixBase<MeanType>& mean, \n                           const SigmaType& sigma)\n{\n    static_assert(ad::util::is_eigen_vector_v<MeanType>);\n    assert(x.size() == mean.size());\n    if (sigma <= 0) return math::neg_inf<dist_value_t>;\n    dist_value_t z_sq = (x.array() - mean.array()).matrix().squaredNorm() / (sigma * sigma);\n    return -0.5 * z_sq - (x.size() * (std::log(sigma) + LOG_SQRT_TWO_PI));\n}\n\n// vsv, vsm\ntemplate <class XType\n        , class MeanType\n        , class SigmaType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MeanType>\n        > >\ninline dist_value_t normal_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                   const MeanType& mean, \n                                   const Eigen::MatrixBase<SigmaType>& sigma)\n{\n    if constexpr (ad::util::is_eigen_vector_v<SigmaType>) {\n        assert(x.size() == sigma.size());\n        if ((sigma.array() <= 0).any()) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = ((x.array() - mean)/sigma.array()).matrix().squaredNorm();\n        return -0.5 * z_sq - (x.size() * LOG_SQRT_TWO_PI) - std::log(sigma.array().prod());\n    }\n\n    else if constexpr (ad::util::is_eigen_matrix_v<SigmaType>) {\n        assert(x.size() == sigma.rows());\n        Eigen::LLT<Eigen::MatrixXd> llt(sigma);\n        if (llt.info() != Eigen::Success) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = llt.matrixL().solve((x.array() - mean).matrix()).squaredNorm();\n        dist_value_t det = llt.matrixL().determinant();\n        return -0.5 * z_sq - (x.size() * LOG_SQRT_TWO_PI) - std::log(det);\n    }\n}\n\n// vvv, vvm\ntemplate <class XType\n        , class MeanType\n        , class SigmaType>\ninline dist_value_t normal_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                   const Eigen::MatrixBase<MeanType>& mean, \n                                   const Eigen::MatrixBase<SigmaType>& sigma)\n{\n    if constexpr (ad::util::is_eigen_vector_v<SigmaType>) {\n        assert(x.size() == sigma.size());\n        assert(x.size() == mean.size());\n        if ((sigma.array() <= 0).any()) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = ((x.array() - mean.array())/sigma.array()).matrix().squaredNorm();\n        return -0.5 * z_sq - (x.size() * LOG_SQRT_TWO_PI) - std::log(sigma.array().prod());\n    }\n\n    else if constexpr (ad::util::is_eigen_matrix_v<SigmaType>) {\n        assert(x.size() == sigma.rows());\n        assert(x.size() == mean.size());\n        Eigen::LLT<Eigen::MatrixXd> llt(sigma);\n        if (llt.info() != Eigen::Success) return math::neg_inf<dist_value_t>;\n        dist_value_t z_sq = llt.matrixL().solve((x.array() - mean.array()).matrix()).squaredNorm();\n        dist_value_t det = llt.matrixL().determinant();\n        return -0.5 * z_sq - (x.size() * LOG_SQRT_TWO_PI) - std::log(det);\n    }\n}\n\n/////////////////////////////////\n// Cauchy Density\n/////////////////////////////////\n\n// sss\ntemplate <class XType\n        , class LocType\n        , class ScaleType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<LocType> &&\n            std::is_arithmetic_v<ScaleType> \n        > >\ninline dist_value_t cauchy_log_pdf(const XType& x, \n                                   const LocType& loc, \n                                   const ScaleType& scale)\n{\n    auto diff = x - loc;\n    return (scale > 0) ? -std::log(scale + diff * diff / scale) : neg_inf<double>;\n} \n\n// vss\ntemplate <class XType\n        , class LocType\n        , class ScaleType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<LocType> &&\n            std::is_arithmetic_v<ScaleType> \n        > >\ninline dist_value_t cauchy_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                   const LocType& loc, \n                                   const ScaleType& scale)\n{\n    bool cond = scale > 0.;\n    auto diff = x.array() - loc;\n    return cond ? -(scale + (1./scale) * diff * diff).log().sum() : \n                  neg_inf<double>;\n} \n\n// vvs\ntemplate <class XType\n        , class LocType\n        , class ScaleType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<ScaleType> \n        > >\ninline dist_value_t cauchy_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const Eigen::MatrixBase<LocType>& loc, \n                                    const ScaleType& scale)\n{\n    bool cond = scale > 0.;\n    auto diff = x.array() - loc.array();\n    return cond ? -(scale + (1./scale) * diff * diff).log().sum() : neg_inf<double>;\n}\n\n// vsv\ntemplate <class XType\n        , class LocType\n        , class ScaleType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<LocType> \n        > >\ninline dist_value_t cauchy_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const LocType& loc, \n                                    const Eigen::MatrixBase<ScaleType>& scale)\n{\n    bool cond = (scale.array() > 0.).all();\n    auto diff = x.array() - loc;\n    auto gamma = scale.array();\n    return cond ? -(gamma + (1./gamma) * diff * diff).log().sum() : neg_inf<double>;\n} \n\n// vvv\ntemplate <class XType\n        , class LocType\n        , class ScaleType>\ninline dist_value_t cauchy_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const Eigen::MatrixBase<LocType>& loc, \n                                    const Eigen::MatrixBase<ScaleType>& scale)\n{\n    bool cond = (scale.array() > 0.).all();\n    auto diff = x.array() - loc.array();\n    auto gamma = scale.array();\n    return cond ? -(gamma + (1./gamma) * diff * diff).log().sum() : neg_inf<double>;\n}\n\n/////////////////////////////////\n// Uniform Density\n/////////////////////////////////\n\n// sss\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<MinType> &&\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_pdf(const XType& x, \n                                const MinType& min, \n                                const MaxType& max)\n{\n    return (min < x && x < max) ? 1. / (max - min) : 0;\n} \n\n// vss\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MinType> &&\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_pdf(const Eigen::MatrixBase<XType>& x, \n                                const MinType& min, \n                                const MaxType& max)\n{\n    bool cond = (min < x.array()).all() && (x.array() < max).all();\n    return cond ? std::pow(1./(max-min), x.size()) : 0;\n} \n\n// vvs\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_pdf(const Eigen::MatrixBase<XType>& x, \n                                const Eigen::MatrixBase<MinType>& min, \n                                const MaxType& max)\n{\n    bool cond = (min.array() < x.array()).all() && (x.array() < max).all();\n    return cond ? (1./(max-min.array())).prod() : 0;\n} \n\n// vsv\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MinType> \n        > >\ninline dist_value_t uniform_pdf(const Eigen::MatrixBase<XType>& x, \n                                const MinType& min, \n                                const Eigen::MatrixBase<MaxType>& max)\n{\n    bool cond = (min < x.array()).all() && (x.array() < max.array()).all();\n    return cond ? (1./(max.array()-min)).prod() : 0;\n} \n\n// vvv\ntemplate <class XType\n        , class MinType\n        , class MaxType>\ninline dist_value_t uniform_pdf(const Eigen::MatrixBase<XType>& x, \n                                const Eigen::MatrixBase<MinType>& min, \n                                const Eigen::MatrixBase<MaxType>& max)\n{\n    bool cond = (min.array() < x.array()).all() && (x.array() < max.array()).all();\n    return cond ? (1./(max.array()-min.array())).prod() : 0;\n}\n\n// sss\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<MinType> &&\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_log_pdf(const XType& x, \n                                    const MinType& min, \n                                    const MaxType& max)\n{\n    return (min < x && x < max) ? -std::log(max - min) : neg_inf<double>;\n} \n\n// vss\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MinType> &&\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const MinType& min, \n                                    const MaxType& max)\n{\n    bool cond = (min < x.array()).all() && (x.array() < max).all();\n    return cond ? \n        static_cast<dist_value_t>(x.size())*(-std::log(max-min)) : \n        neg_inf<double>;\n} \n\n// vvs\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MaxType> \n        > >\ninline dist_value_t uniform_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const Eigen::MatrixBase<MinType>& min, \n                                    const MaxType& max)\n{\n    bool cond = (min.array() < x.array()).all() && (x.array() < max).all();\n    return cond ? -(max-min.array()).log().sum() : neg_inf<double>;\n}\n\n// vsv\ntemplate <class XType\n        , class MinType\n        , class MaxType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<MinType> \n        > >\ninline dist_value_t uniform_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const MinType& min, \n                                    const Eigen::MatrixBase<MaxType>& max)\n{\n    bool cond = (min < x.array()).all() && (x.array() < max.array()).all();\n    return cond ? -(max.array()-min).log().sum() : neg_inf<double>;\n} \n\n// vvv\ntemplate <class XType\n        , class MinType\n        , class MaxType>\ninline dist_value_t uniform_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                    const Eigen::MatrixBase<MinType>& min, \n                                    const Eigen::MatrixBase<MaxType>& max)\n{\n    bool cond = (min.array() < x.array()).all() && (x.array() < max.array()).all();\n    return cond ? -(max.array()-min.array()).log().sum() : neg_inf<double>;\n}\n\n/////////////////////////////////\n// Bernoulli Density\n/////////////////////////////////\n\n/**\n * Bernoulli pdf and log pdf (pmf actually).\n * It is defined to clip when p is out of the range [0,1],\n * i.e. if p < 0, then we take p = 0 and\n * if p > 1, then we take p = 1.\n */\n\n// ss\ntemplate <class XType\n        , class PType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<PType>\n        > >\ninline dist_value_t bernoulli_pdf(const XType& x, \n                                  const PType& p)\n{\n    if (p <= 0) return (x == 0) + 0.;\n    else if (p >= 1) return (x == 1) + 0.;\n\n    if (x == 1) return p;\n    else if (x == 0) return 1. - p;\n    else return 0.0;\n} \n\n// vs\ntemplate <class XType\n        , class PType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<PType>\n        > >\ninline dist_value_t bernoulli_pdf(const Eigen::MatrixBase<XType>& x, \n                                  const PType& p)\n{\n    double pdf = 1.;\n    for (int i = 0; i < x.size(); ++i) {\n        pdf *= bernoulli_pdf(x(i), p);\n    }\n    return pdf;\n} \n\n// vv\ntemplate <class XType\n        , class PType>\ninline dist_value_t bernoulli_pdf(const Eigen::MatrixBase<XType>& x, \n                                  const Eigen::MatrixBase<PType>& p)\n{\n    assert(x.size() == p.size());\n    double pdf = 1.;\n    for (int i = 0; i < x.size(); ++i) {\n        pdf *= bernoulli_pdf(x(i), p(i));\n    }\n    return pdf;\n}\n\n// ss\ntemplate <class XType\n        , class PType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<XType> &&\n            std::is_arithmetic_v<PType>\n        > >\ninline dist_value_t bernoulli_log_pdf(const XType& x, \n                                      const PType& p)\n{\n    if (p <= 0) {\n        if (x == 0) return 0.;\n        else return neg_inf<PType>;\n    }\n    else if (p >= 1) {\n        if (x == 1) return 0.;\n        else return neg_inf<PType>;\n    }\n\n    if (x == 1) return std::log(p);\n    else if (x == 0) return std::log(1. - p);\n    else return neg_inf<PType>;\n} \n\n// vs\ntemplate <class XType\n        , class PType\n        , class = std::enable_if_t<\n            std::is_arithmetic_v<PType>\n        > >\ninline dist_value_t bernoulli_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                      const PType& p)\n{\n    double logpdf = 0.;\n    for (int i = 0; i < x.size(); ++i) {\n        logpdf += bernoulli_log_pdf(x(i), p);\n    }\n    return logpdf;\n} \n\n// vv\ntemplate <class XType\n        , class PType>\ninline dist_value_t bernoulli_log_pdf(const Eigen::MatrixBase<XType>& x, \n                                      const Eigen::MatrixBase<PType>& p)\n{\n    assert(x.size() == p.size());\n    double logpdf = 0.;\n    for (int i = 0; i < x.size(); ++i) {\n        logpdf += bernoulli_log_pdf(x(i), p(i));\n    }\n    return logpdf;\n}\n\n/////////////////////////////////\n// Wishart Density\n// Note: drops unnecessary constant terms\n/////////////////////////////////\ntemplate <class XType\n        , class VType\n        , class NType>\ninline dist_value_t wishart_log_pdf(const Eigen::MatrixBase<XType>& x,\n                                    const Eigen::MatrixBase<VType>& v,\n                                    const NType& n)\n{\n    Eigen::LLT<Eigen::MatrixXd> x_llt(x);\n    Eigen::LLT<Eigen::MatrixXd> v_llt(v);\n    auto log_det_x = std::log(x_llt.matrixL().determinant());\n    auto log_det_v = std::log(v_llt.matrixL().determinant());\n    auto tr = v_llt.solve(x).trace();\n    dist_value_t p = v.rows();\n    return (n - p - 1.) * log_det_x - 0.5 * tr - n * log_det_v;\n}\n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "7a8a998149bacee814556cae611d3746bb641e02", "size": 21004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/density.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/density.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/density.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 33.7142857143, "max_line_length": 99, "alphanum_fraction": 0.5385164731, "num_tokens": 5528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947163538935, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6730556451507719}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"LCPSolve.h\"\n\n\nvoid printResult(LCP sol, const int &testNum) {\n    std::cout << \"---Test #\" << testNum << \"---\" << std::endl;\n    std::cout << \"M = \\n\" << sol.M << std::endl;\n    std::cout << \"q = \" << sol.q.transpose() << std::endl;\n    std::cout << \"z = \" << sol.z.transpose() << std::endl;\n    std::cout << \"w = \" << sol.w.transpose() << std::endl;\n    std::cout << \"Exit condition: \" << sol.exitCond << std::endl << std::endl;\n}\n\nvoid displayPassRate(const bool &result, int &nTestComplete, int &nTestPassed) {\n    nTestComplete++;\n    if (result) {\n        nTestPassed++;\n    }\n    double passRate = (nTestPassed/nTestComplete) * 100;\n    std::cout << \"Pass Rate: \" << passRate << \" %\\n\" << std::endl;\n}\n\nbool test_1() {\n    Eigen::Matrix<double, 2, 2> M {\n        {2, -1},\n        {-1, 1}\n    };\n    Eigen::Vector<double, 2> q {-3, 1};\n    LCP sol = LCPSolve(M, q);\n\n    Eigen::Vector<double, 2> zTruth {2.0, 1.0};\n    double eps = 0.001;\n    std::cout << \"Running Test 1...\" << std::endl;\n    if ((sol.z - zTruth).norm() < eps) {\n        std::cout << \"Test 1 Passed\" << std::endl;\n        return true;\n    } else {\n        std::cout << \"Test 1 Failed\" << std::endl;\n        return false;\n    }\n}\n\nbool test_2() {\n    Eigen::Matrix<double, 3, 3> M {\n        {2, -1, 3},\n        {-1, 1, 6},\n        {1, 5, -2}\n    };\n    Eigen::Vector<double, 3> q {-2, 5, -1};\n    LCP sol = LCPSolve(M, q);\n\n    Eigen::Vector<double, 3> zTruth {1, 0, 0};\n    double eps = 0.001;\n    std::cout << \"Running Test 2...\" << std::endl;\n    if ((sol.z - zTruth).norm() < eps) {\n        std::cout << \"Test 2 Passed\" << std::endl;\n        return true;\n    } else {\n        std::cout << \"Test 2 Failed\" << std::endl;\n        return false;\n    }\n}\n\nbool test_3() {\n    Eigen::Matrix<double, 4, 4> M {\n            {1, 5, -3, 4},\n            {1, -4, -5, -4},\n            {-3, 3, -4, 4},\n            {4, 9, 0, 1}\n        };\n    Eigen::Vector<double, 4> q {-3, 4, 5, 1};\n    LCP sol = LCPSolve(M, q);\n    \n    Eigen::Vector<double, 4> zTruth {1.5294, 0.64705, 0.58823, 0};\n    double eps = 0.001;\n    std::cout << \"Running Test 3...\" << std::endl;\n    if ((sol.z - zTruth).norm() < eps) {\n        std::cout << \"Test 3 Passed\" << std::endl;\n        return true;\n    } else {\n        std::cout << \"Test 3 Failed\" << std::endl;\n        return false;\n    }\n}\n\nbool test_4() {\n    // Secondary ray.\n    Eigen::Matrix<double, 3, 3> M {\n        {2, -1, 3},\n        {-1, 1, 6},\n        {1, 5, -2}\n    };\n    Eigen::Vector<double, 3> q {-2, 5, -1.5};\n    LCP sol = LCPSolve(M, q);\n\n    Eigen::Vector<double, 3> zTruth {0, 0, 0.1};\n    double eps = 0.001;\n    std::cout << \"Running Test 4...\" << std::endl;\n    if ((sol.z - zTruth).norm() < eps) {\n        std::cout << \"Test 4 Passed\" << std::endl;\n        return true;\n    } else {\n        std::cout << \"Test 4 Failed\" << std::endl;\n        return false;\n    }\n}\n\nbool test_5() {\n    Eigen::Matrix<double, 2, 2> M {\n        {1, -5},\n        {2, 1}\n    };\n    Eigen::Vector<double, 2> q {-4, 3};\n    LCP sol = LCPSolve(M, q);\n\n    Eigen::Vector<double, 2> zTruth {4, 0};\n    double eps = 0.001;\n    std::cout << \"Running Test 5...\" << std::endl;\n    if ((sol.z - zTruth).norm() < eps) {\n        std::cout << \"Test 5 Passed\" << std::endl;\n        return true;\n    } else {\n        std::cout << \"Test 5 Failed\" << std::endl;\n        return false;\n    }\n}\n\nint main() {\n    // Setup percentage display.\n    int nTestComplete = 0;\n    int nTestPassed = 0;\n    bool result;\n\n    // Run tests.\n    std::cout << \"Running LCPSolve Tests...\\n\" << std::endl;\n\n    // Test 1.\n    result = test_1();\n    displayPassRate(result, nTestComplete, nTestPassed);\n\n    // Test 2.\n    result = test_2();\n    displayPassRate(result, nTestComplete, nTestPassed);\n\n    // Test 3.\n    result = test_3();\n    displayPassRate(result, nTestComplete, nTestPassed);\n\n    // Test 4.\n    result = test_4();\n    displayPassRate(result, nTestComplete, nTestPassed);\n\n    // Test 5.\n    result = test_5();\n    displayPassRate(result, nTestComplete, nTestPassed);\n\n    return 0;\n}", "meta": {"hexsha": "5acf2ec5bdd73999f1bb2b5715ef7dc9266b9976", "size": 4111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests.cpp", "max_stars_repo_name": "Tom-Forsyth/LCPSolve", "max_stars_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_stars_repo_licenses": ["MIT"], "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/tests.cpp", "max_issues_repo_name": "Tom-Forsyth/LCPSolve", "max_issues_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/tests.cpp", "max_forks_repo_name": "Tom-Forsyth/LCPSolve", "max_forks_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_forks_repo_licenses": ["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.8553459119, "max_line_length": 80, "alphanum_fraction": 0.5027973729, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6729787883720264}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include <array>\n\n\nint main() {\n   \n   Eigen::Vector3d v1, v2;  \n   std::vector<int> v3, v4;\n   std::array<int,3> v5 {1, 2, 3};\n   std::array<int,3> v6;\n   int i;\n\n   // using eigen:\n   v1 << 1.0, 2.0, 3.0;\n   v2 = v1;\n   v1(0) = 4.0;\n\n   std::cout << \"using eigen\" << std::endl;\n   std::cout << v1.transpose() << std::endl;\n   std::cout << v2.transpose() << std::endl;\n\n   // using vector:\n   v3 = {1, 2, 3};\n   v4 = v3;\n   v3[0] = 4;\n\n   std::cout << \" \" << std::endl;\n   std::cout << \"using vector\" << std::endl;\n   for (i=0; i<=2; i=i+1) {\n      std::cout << v3[i] ;\n   }\n   std::cout << \" \" << std::endl;\n   for (i=0; i<=2; i=i+1) {\n      std::cout << v3[i] ;\n   }\n   std::cout << \" \" << std::endl;\n\n   // using array (the library. built in errors can't use \"=\"):\n   v6 = v5;   \n   v5[0] = 4;\n\n   std::cout << \" \" << std::endl;\n   std::cout << \"using array (the library):\" << std::endl;\n   for (i=0; i<=2; i=i+1) {\n      std::cout << v5[i] ;\n   }\n   std::cout << \" \" << std::endl;\n   for (i=0; i<=2; i=i+1) {\n      std::cout << v6[i] ;\n   }\n   std::cout << \" \" << std::endl;\n\n}\n", "meta": {"hexsha": "0f16d752513bc1fb31e86f3e8134bde67c7bdebb", "size": 1144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cp_assignment_fortran_python_cpp/arrays/arrays.cpp", "max_stars_repo_name": "ElenaKusevska/exercises", "max_stars_repo_head_hexsha": "d10b5670fbc6003977e038c352e41907fff0cc79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cp_assignment_fortran_python_cpp/arrays/arrays.cpp", "max_issues_repo_name": "ElenaKusevska/exercises", "max_issues_repo_head_hexsha": "d10b5670fbc6003977e038c352e41907fff0cc79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cp_assignment_fortran_python_cpp/arrays/arrays.cpp", "max_forks_repo_name": "ElenaKusevska/exercises", "max_forks_repo_head_hexsha": "d10b5670fbc6003977e038c352e41907fff0cc79", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 63, "alphanum_fraction": 0.4615384615, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6729581983389333}}
{"text": "\n/*\n\t* Generates the basis { i  sigma_1 , i sigma_2 ......, i sigma_n }\n\t* Where sigma_i is a generalized pauli matrix\n*/\n\n#define _PAULI\n#ifdef _PAULI\n\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <armadillo>\n#include <complex>\n\nusing namespace arma;\nusing std::vector;\n\nclass Pauli\n{\n\tpublic:\n\n\t\tPauli(int matSize);\n\t\t~Pauli();\n\n\t\tvector<cx_mat> pauliBasisObject;\n\t\t//cx_mat lieBracket(cx_mat A, cx_mat B);\n\n\tprivate:\n\n\t\t//size of matrix - n x n matrices\n\t\tlong n;\n\t\t//dimension of space\n\t\tlong dimension;\n\t\tint kD(int r, int s);\n\n\t\tcx_double cmplxI = cx_double(0.0, 1.0);\n\t\tcx_mat E(int r, int s);\n\n\t\t//generating methods\n\t\tPauli& sigmaTypeOne();\n\t\tPauli& sigmaTypeTwo();\n\t\tPauli& sigmaTypeThree();\n\n};\n\n#include \"Pauli.cpp\"\n#endif\n", "meta": {"hexsha": "8782c6399b08eaacf08ab96d4bb0f29b291a92ae", "size": 755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/Pauli.hpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "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/Pauli.hpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "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/Pauli.hpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["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.4081632653, "max_line_length": 67, "alphanum_fraction": 0.6728476821, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6729581802880003}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"polytope.hpp\"\n#include \"oblog.hpp\"\n\nusing Eigen::MatrixXd;\n\nTEST(TESTEigen, basicTest) {\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 << m << std::endl;\n\n\n  OB::Transform t;\n  std::cout << \"Size of isometry: \" << sizeof(t) << std::endl;;\n  OB::Matrix3 rot = t.rotation();\n  OB::Vector trans = t.translation();\n  std::cout << \" rotation: \" << rot << std::endl;\n  std::cout << \" translation: \" << trans << std::endl;\n  //spdlog::info(\" translation: {}\", trans);\n  //spdlog::info(\" rotation: {}\", v);\n\n  std::cout.precision(17);\n\n  OB::Real valor = 7;\n  OB::Real otro = 7;\n  std::cout << \"valor: \"<< valor << \" isApprox \" << otro<< \" ->  \" << Eigen::internal::isApprox(valor, otro) << std::endl;\n  otro = 7.00000000001;\n  std::cout << \"valor: \"<< valor << \" isApprox \" << otro<< \" ->  \" << Eigen::internal::isApprox(valor, otro) << std::endl;\n  otro = 7.000000000001;\n  std::cout << \"valor: \"<< valor << \" isApprox \" << otro<< \" ->  \" << Eigen::internal::isApprox(valor, otro) << std::endl;\n  otro = 6.99999999999;\n  std::cout << \"valor: \"<< valor << \" isApprox \" << otro<< \" ->  \" << Eigen::internal::isApprox(valor, otro) << std::endl;\n  otro = 6.999999999999;\n  std::cout << \"valor: \"<< valor << \" isApprox \" << otro<< \" ->  \" << Eigen::internal::isApprox(valor, otro) << std::endl;\n\n  // for is_zero\n  valor = 0.0001;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n  valor = 1;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n  valor = 0;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n  valor = 0.00000000001;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n  valor = 0.000000000001;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n\n\n  valor = -0.00000000001;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n  valor = -0.000000000001;\n  std::cout << \"valor: \" << valor << \" is_zero -> \" << Eigen::internal::isMuchSmallerThan(valor, static_cast<OB::Real>(1.0)) << std::endl;;\n\n}\n\n\nTEST(TESTEigen, matrixInizialization) {\n  Eigen::Vector3d v1;\n  v1 << 1,2,3;\n  Eigen::Vector3d v2;\n  v2 << 4,5,6;\n  Eigen::Vector3d v3;\n  v3 << 7,8,9;\n\n  Eigen::Matrix3d matrix;\n  matrix << v1, v2, v3;\n  std::cout << \"Matrix \" << matrix << std::endl;\n}\n", "meta": {"hexsha": "787203db3683bdf3fe6143b7393fc38e78c710b9", "size": 2827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "obvclip/tests/test_eigen.cpp", "max_stars_repo_name": "javierdelapuente/tfm_ode_bullet", "max_stars_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T11:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T11:22:13.000Z", "max_issues_repo_path": "obvclip/tests/test_eigen.cpp", "max_issues_repo_name": "javierdelapuente/tfm_ode_bullet", "max_issues_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "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": "obvclip/tests/test_eigen.cpp", "max_forks_repo_name": "javierdelapuente/tfm_ode_bullet", "max_forks_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "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": 37.6933333333, "max_line_length": 139, "alphanum_fraction": 0.5829501238, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6728265676680582}}
{"text": "#pragma once // header guard\n\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues>\n\n#include <cmath>\n\n//! Shortcut for container vector of nodes/weights\nusing vector = Eigen::VectorXd;\n\n//! Structure containing a Quadrature rule on [-1,1], comprised of weights and nodes\nstruct QuadRule {\n    vector weights;\n    vector nodes;\n};\n\n//! \\brief Golub-Welsh implementation 5.3.35\n//! \\param[in] n number of Gauss nodes\n//! \\return structure QuadRule containing nodes and wights of gauss Quadrature\nQuadRule gauleg(unsigned int n);\n", "meta": {"hexsha": "08f9e630ab1e2a166ad6818f03a6350a7a111621", "size": 527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS11/templates_ps11/gauleg.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/PS11/templates_ps11/gauleg.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/PS11/templates_ps11/gauleg.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": 25.0952380952, "max_line_length": 84, "alphanum_fraction": 0.7381404175, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.672824484690742}}
{"text": "// Copyright Paul Bristow 2012.\n// Copyright John Maddock 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/*! \\brief Examples of using the enhanced math constants.\n    \\details This allows for access to constants via functions like @c pi(),\n    and also via namespaces, @c using @c namespace boost::math::double_constants;\n    called simply @c pi.\n*/\n\n#include <boost/math/constants/constants.hpp>\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <limits>\nusing std::numeric_limits;\n\n/*! \\brief Examples of a template function using constants.\n    \\details This example shows using of constants from function calls like @c pi(),\n    rather than the 'cute' plain @c pi use in non-template applications.\n\n    \\tparam Real radius parameter that can be a built-in like float, double,\n      or a user-defined type like multiprecision.\n    \\returns Area = pi * radius ^ 2\n*/\n\n//[math_constants_eg1\ntemplate<class Real>\nReal area(Real r)\n{\n  using namespace boost::math::constants;\n\n  return pi<Real>() * r * r;\n}\n//] [/math_constants_eg1]\n\nint main()\n{\n  \n  { // Boost.Math constants using function calls like pi().\n    // using namespace boost::math::constants;\n \n   using boost::math::constants::pi;\n   using boost::math::constants::one_div_two_pi;\n\n  cout.precision(numeric_limits<double>::max_digits10);\n  cout << \"double pi =  boost::math::double_constants::pi = \" << pi<double>() << endl;\n  //   double pi =  boost::math::double_constants::pi = 3.1415926535897931\n  double r = 1.234567890123456789;\n  double d = pi<double>() * r * r;\n\n  cout << \"d = \" << d << \", r = \" << r << endl;\n\n  float rf = 0.987654321987654321f;\n\n  float pif = boost::math::constants::pi<float>();\n  cout << \"pidf =  boost::math::constants::pi() = \" << pif << endl;\n  //   pidf =  boost::math::float_constants::pi = 3.1415927410125732\n\n    //float df = pi * rf * rf; // conversion from 'const double' to 'float', possible loss of data\n  float df = pif * rf * rf;\n\n  cout << \"df = \" << df << \", rf = \" << rf << endl;\n\n  cout << \"one_div_two_pi \" << one_div_two_pi<double>() << endl;\n\n  using boost::math::constants::one_div_two_pi;\n\n  cout << \"one_div_root_two_pi \" << one_div_two_pi<double>() << endl;\n  }\n\n  { // Boost math new constants using namespace selected values, like pi.\n\n    //using namespace boost::math::float_constants;\n    using namespace boost::math::double_constants;\n\n    double my2pi = two_pi; // Uses boost::math::double_constants::two_pi;\n\n    cout << \"double my2pi = \" << my2pi << endl;\n    \n    using boost::math::float_constants::e;\n    float my_e = e;\n    cout << \"float my_e  \" << my_e << endl;\n\n    double my_pi = boost::math::double_constants::pi;\n    cout << \"double my_pi = boost::math::double_constants::pi =  \" << my_pi << endl;\n\n    // If you try to use two namespaces, this may, of course, create ambiguity:\n    // it is not too difficult to do this inadvertently.\n    using namespace boost::math::float_constants;\n    //cout << pi << endl; // error C2872: 'pi' : ambiguous symbol\n\n  }\n  {\n\n//[math_constants_ambiguity\n     // If you use more than one namespace, this will, of course, create ambiguity:\n     using namespace boost::math::double_constants;\n     using namespace boost::math::constants;\n\n      //double my_pi = pi(); // error C2872: 'pi' : ambiguous symbol\n      //double my_pi2 = pi; // Context does not allow for disambiguation of overloaded function\n\n     // It is also possible to create ambiguity inadvertently,\n     // perhaps in other peoples code,\n     // by making the scope of a namespace declaration wider than necessary,\n     // therefore is it prudent to avoid this risk by localising the scope of such definitions.\n//] [/math_constants_ambiguity]\n\n  }\n\n  { // You can, of course, use both methods of access if both are fully qualified, for examples:\n\n    //cout.precision(std::numeric_limits<double>::max_digits10);// Ideally.\n    cout.precision(2 + std::numeric_limits<double>::digits * 3010/10000); // If no max_digits10.\n\n    double my_pi1 = boost::math::constants::pi<double>();\n    double my_pid = boost::math::double_constants::pi;\n    cout << \"boost::math::constants::pi<double>() = \" << my_pi1 << endl\n         << \"boost::math::double_constants::pi = \" << my_pid << endl;\n\n    // cout.precision(std::numeric_limits<float>::max_digits10); // Ideally.\n    cout.precision(2 + std::numeric_limits<double>::digits * 3010/10000); // If no max_digits10.\n    float my_pif = boost::math::float_constants::pi;\n    cout << \"boost::math::float_constants::pi = \" << my_pif << endl;\n\n  }\n\n  { // Use with templates\n\n    // \\warning it is important to be very careful with the type provided as parameter.\n    // For example, naively providing an @b integer instead of a floating-point type can be disastrous.\n    // cout << \"Area = \" << area(2) << endl; // warning : 'return' : conversion from 'double' to 'int', possible loss of data\n    // Failure to heed this warning can lead to very wrong answers!\n    //  Area = 12 !!  = 3 * 2 * 2 \n//[math_constants_template_integer_type\n    //cout << \"Area = \" << area(2) << endl; //   Area = 12!\n    cout << \"Area = \" << area(2.) << endl;  //   Area = 12.566371\n\n    // You can also avoid this by being explicit about the type of @c area.\n    cout << \"Area = \" << area<double>(2) << endl;\n\n//] [/math_constants_template_integer_type]\n\n\n  }\n  {\n    using  boost::math::constants::pi;\n    double my_pi3 = pi<double>();\n    //double my_pi4 = pi<>(); cannot find template type.\n    //double my_pi4 = pi();\n\n  }\n\n} // int main()\n\n/*[constants_eq1_output\n\nOutput:\n\n  double pi =  boost::math::double_constants::pi = 3.1415926535897931\n  d = 4.7882831840285398, r = 1.2345678901234567\n  pidf =  boost::math::constants::pi() = 3.1415927410125732\n  df = 3.0645015239715576, rf = 0.98765432834625244\n  one_div_two_pi 0.15915494309189535\n  one_div_root_two_pi 0.15915494309189535\n  double my2pi = 6.2831853071795862\n  float my_e  2.7182817459106445\n  double my_pi = boost::math::double_constants::pi =  3.1415926535897931\n  boost::math::constants::pi<double>() = 3.1415926535897931\n  boost::math::double_constants::pi = 3.1415926535897931\n  boost::math::float_constants::pi = 3.1415927410125732\n  Area = 12.566370614359172\n  Area = 12.566370614359172\n\n\n] [/constants_eq1_output]\n*/\n", "meta": {"hexsha": "47cad122dd9d5ce6e3fbaf6399e318e055370ffe", "size": 6408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/constants_eg1.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/constants_eg1.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/constants_eg1.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": 34.6378378378, "max_line_length": 125, "alphanum_fraction": 0.6697877653, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173801068221, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.6727544098010217}}
{"text": "/**\n * @file propagator.h\n * @brief NPDE homework NonLinSchroedingerEquation code\n * @author Oliver Rietmann\n * @date 04.05.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"propagator.h\"\n\n#include <cmath>\n#include <complex>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\nnamespace NonLinSchroedingerEquation {\n\n// KineticPropagator\n/* SAM_LISTING_BEGIN_1 */\nKineticPropagator::KineticPropagator(const SparseMatrixXd &A,\n                                     const SparseMatrixXcd &M, double tau) {\n  // Defeats the rationale of expression templates, but acceptable here, because\n  // executed only once in the constructor.\n  B_plus_ = M + 0.5 * tau * A.cast<std::complex<double>>();\n  SparseMatrixXcd B_minus = M - 0.5 * tau * A.cast<std::complex<double>>();\n  // This is the expensive step: LU-factorization of a big sparse matrix.\n  // Precomputation is essential\n  solver_.compute(B_minus);\n}\n\nEigen::VectorXcd KineticPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  // Cheap elimination steps operating on the LU-factors. Effort is almost O(N)\n  // thanks to sophisticated fill-in avoiding techniques employed by the sparse\n  // solvers.\n  return solver_.solve(B_plus_ * mu);\n}\n/* SAM_LISTING_END_1 */\n\n// InteractionPropagator\n/* SAM_LISTING_BEGIN_2 */\nInteractionPropagator::InteractionPropagator(double tau) {\n  // We know that the discrete evolution operator for the non-linear part of the\n  // method-of-lines ODE boils down to componentwise multiplication of the\n  // vector with a single phase shift. Thus, this phase shift can be\n  // precomputed, here by means of a lambda function\n  phase_multiplier_ = [tau](std::complex<double> z) {\n    const std::complex<double> i(0, 1);\n    return std::exp(-i * tau * std::norm(z)) * z;\n  };\n}\n\nEigen::VectorXcd InteractionPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  // Eigen's way of applying a function to all components of a vector.\n  return mu.unaryExpr(phase_multiplier_);\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nSplitStepPropagator::SplitStepPropagator(const SparseMatrixXd &A,\n                                         const SparseMatrixXcd &M, double tau)\n    : kineticPropagator_(A, M, 0.5 * tau), interactionPropagator_(tau) {}\n\nEigen::VectorXcd SplitStepPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  Eigen::VectorXcd nu(mu.size());\n  nu = kineticPropagator_(mu);\n  nu = interactionPropagator_(nu);\n  nu = kineticPropagator_(nu);\n  return nu;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace NonLinSchroedingerEquation\n", "meta": {"hexsha": "133495d71fbb62267b13aaa1fd88e1976f3801b7", "size": 2585, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NonLinSchroedingerEquation/mastersolution/propagator.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": "homeworks/NonLinSchroedingerEquation/mastersolution/propagator.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": "homeworks/NonLinSchroedingerEquation/mastersolution/propagator.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.141025641, "max_line_length": 80, "alphanum_fraction": 0.7098646035, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.8376199694135332, "lm_q1q2_score": 0.6727544028456285}}
{"text": "#pragma once\n\n#include <ros/ros.h>\n#include <math.h> \n#include <iostream>\n// #include <Eigen/Core>\n// #include <Eigen/LU>\n#include <geometry_msgs/PoseStamped.h>\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_listener.h>\n#include <cav_msgs/TrajectoryPlan.h>\n\n\n\n\n\n\n\nnamespace platoon_control\n{\n\n\n    class PurePursuit\n    {\n\n\n    public:\n    \tPurePursuit() = default;\n\n    \tdouble calculateSteer(const cav_msgs::TrajectoryPlanPoint& tp);\n\n\t\t// geometry pose\n\t\tgeometry_msgs::Pose current_pose_;\n\n    private:\n\n\t\t// calculate the lookahead distance from next trajectory point\n\t\tdouble getLookaheadDist(const cav_msgs::TrajectoryPlanPoint& tp) const;\n\n\t\t// calculate yaw angle of the vehicle\n\t\tdouble getYaw() const;\n\n\t\t// calculate alpha angle\n\t\tdouble getAlpha(double lookahead, std::vector<double> v1, std::vector<double> v2) const;\n\n\t\t// calculate steering direction\n\t\tint getSteeringDirection(std::vector<double> v1, std::vector<double> v2) const;\n\n\t\t// calculate command velocity from trajecoty point\n\t\tdouble getVelocity(const cav_msgs::TrajectoryPlanPoint& tp, double delta_pos) const;\n\t\t\n\t\t// vehicle wheel base\n\t\tdouble wheelbase_ = 2.7;\n\n\t\t// coefficient for smooth steering\n\t\tdouble Kdd_ = 4.5;\n\n\t\tdouble prev_steering = 0.0;\n\n\t\t\n\t\t// previous trajectory point\n\t\tcav_msgs::TrajectoryPlanPoint tp0;\n\n\t\t// helper function (if needed)\n\t\t// inline double deg2rad(double deg) const\n\t\t// {\n\t\t// \treturn deg * M_PI / 180;\n\t\t// }  // convert degree to radian\n\n\n    };\n}", "meta": {"hexsha": "9d516d131d1ebb44b7be6c7b4a7e920f786d5fda", "size": 1483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "platooning_control/include/pure_pursuit.hpp", "max_stars_repo_name": "harderthan/carma-platform", "max_stars_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_stars_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "platooning_control/include/pure_pursuit.hpp", "max_issues_repo_name": "harderthan/carma-platform", "max_issues_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_issues_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "platooning_control/include/pure_pursuit.hpp", "max_forks_repo_name": "harderthan/carma-platform", "max_forks_repo_head_hexsha": "29921896a761a866db9cfee473f02a481d8bb9c9", "max_forks_repo_licenses": ["Apache-2.0", "CC-BY-4.0", "MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T21:05:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T21:05:20.000Z", "avg_line_length": 20.5972222222, "max_line_length": 90, "alphanum_fraction": 0.7120701281, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580401, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.672609765328399}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <boost/math/constants/constants.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::pair<long double, long double> coordonnee;\n\nnamespace {\n    long double norme(const coordonnee &v) {\n        return std::hypot(v.first, v.second);\n    }\n\n    std::vector<coordonnee> convertion(const std::vector<coordonnee> &v) {\n        if (v.empty())\n            return v;\n\n        std::vector<coordonnee> resultat{\n                std::make_pair(v.front().first - v.back().first, v.front().second - v.back().second)};\n        for (size_t k = 1; k < v.size(); ++k) {\n            auto p = std::make_pair(v.at(k).first - v.at(k - 1).first, v.at(k).second - v.at(k - 1).second);\n            auto n = norme(p);\n            p.first /= n;\n            p.second /= n;\n            resultat.push_back(p);\n        }\n\n        return resultat;\n    }\n\n    std::vector<coordonnee> S(size_t n) {\n        std::vector<coordonnee> s;\n        for (size_t k = 0; k < n; ++k) {\n            const long double x = (2.0L * k - 1L) / n + M_PIl;\n            s.emplace_back(std::cos(x), std::sin(x));\n        }\n\n        return s;\n    }\n\n    long double produit_scalaire(const coordonnee &v1, const coordonnee &v2) {\n        return (v1.first * v2.first + v1.second * v2.second) / (norme(v1) * norme(v2));\n    }\n}\n\nENREGISTRER_PROBLEME(228, \"Minkowski Sums\") {\n    // Let Sn be the regular n-sided polygon \u2013 or shape \u2013 whose vertices vk (k\u2009=\u20091,2,\u2026,n) have coordinates:\n    //\n    // \t\t\tx_k = cos( 2*(k-1)/n \u00d7 180\u00b0 )\n    // \t\t\ty_k = sin( 2*(k-1)/n \u00d7 180\u00b0 )\n    //\n    // Each Sn is to be interpreted as a filled shape consisting of all points on the perimeter and in the interior.\n    //\n    // The Minkowski sum, S+T, of two shapes S and T is the result of adding every point in S to every point in T, where\n    // point addition is performed coordinate-wise: (u,\u2009v) + (x,\u2009y) = (u+x,\u2009v+y).\n    //\n    // For example, the sum of S3 and S4 is the six-sided shape shown in pink below:\n    //\n    //\t\t\t\t\t\t\tpicture showing S_3 + S_4\n    //\n    // How many sides does S1864\u2009+\u2009S1865\u2009+\u2009\u2026\u2009+\u2009S1909 have?\n    std::set<coordonnee, std::function<bool(const coordonnee &v1, const coordonnee &v2)>> minkowski(\n            [](const coordonnee &v1, const coordonnee &v2) {\n                if (std::abs(1.0L - produit_scalaire(v1, v2)) < 0.0000000000001L)\n                    return false;\n\n                return v1 < v2;\n            });\n\n    for (size_t n = 1864; n <= 1909; ++n) {\n        auto Sn = convertion(S(n));\n        minkowski.insert(Sn.begin(), Sn.end());\n    }\n\n    nombre resultat = minkowski.size();\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "af05db322759e622ed4ee2c83f97f38e6050a12a", "size": 2652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme2xx/probleme228.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/probleme228.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/probleme228.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.0, "max_line_length": 120, "alphanum_fraction": 0.5622171946, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6726097618179062}}
{"text": "#ifndef NEURALNET_HPP\n#define NEURALNET_HPP\n\n\n#include <eigen3/Eigen/Eigen> \n#include <iostream> \n#include <vector>\n#include <string>\n#include <boost/range/combine.hpp>\n#include <fstream>\n\nclass LayerDense {\n    public:\n        int n_inputs; // number of inputs\n        int n_neurons; // number of neurons\n\n        Eigen::MatrixXd inputs; // inputs\n        Eigen::MatrixXd weights;\n        Eigen::MatrixXd weight_momentums;\n        Eigen::VectorXd biases;\n        Eigen::VectorXd bias_momentums;\n        Eigen::MatrixXd output;\n\n        Eigen::MatrixXd dweights; // derivative wrt weights\n        Eigen::VectorXd dbiases; // derivative wrt biases\n        Eigen::MatrixXd dinputs; // derivative wrt inputs\n\n        // constructor\n        LayerDense(int n_inputs, int n_neurons) {\n            this->weights = Eigen::MatrixXd::Random(n_inputs,n_neurons) * 0.01; // initialize weights\n            this->weights = weights;\n            this->biases = Eigen::VectorXd::Zero(n_neurons); // initialize biases\n            this->n_inputs = n_inputs;\n            this->n_neurons = n_neurons;\n            this->weight_momentums = Eigen::MatrixXd::Zero(n_inputs,n_neurons); // weight momentum\n            this->bias_momentums = Eigen::VectorXd::Zero(n_neurons); // bias momentum\n        } \n\n        // Member functions declaration\n        void forward(const Eigen::MatrixXd &inputs);\n        void backward(const Eigen::MatrixXd &dvalues);\n};\n\nclass ActivationRelu {\n    public:\n        Eigen::MatrixXd inputs; // inputs\n        Eigen::MatrixXd dinputs; // derivative wrt inputs\n        Eigen::MatrixXd output;\n\n        // Member functions declaration\n        void forward(const Eigen::MatrixXd &inputs);\n        void backward(const Eigen::MatrixXd &dvalues);\n};\n\n\nclass ActivationSoftmax {\n    public:\n        Eigen::MatrixXd inputs; // inputs\n        Eigen::MatrixXd dinputs; // derivative wrt inputs\n        Eigen::MatrixXd output;\n\n        // Member functions declaration\n        void forward(const Eigen::MatrixXd &inputs);\n        void backward(const Eigen::MatrixXd &dvalues);\n};\n\nclass CrossEntropyLoss {\n    public:\n        Eigen::MatrixXd dinputs;\n\n        // Member functions declaration\n        Eigen::VectorXd forward(const Eigen::MatrixXd &y_pred, const Eigen::VectorXi &y_true);\n        double calculate(const Eigen::MatrixXd &output, const Eigen::VectorXi &y);\n        void backward(const Eigen::MatrixXd &dvalues, const Eigen::VectorXi &y_true);\n};\n\nclass StochasticGradientDescent {\n    public:\n        double learning_rate; // learning rate\n        double decay; // decay\n        double momentum; // momentum\n        double iterations; // initialize number of iterations to 0\n\n        // constructor\n        StochasticGradientDescent(double learning_rate, double decay, double momentum) {\n            this->learning_rate = learning_rate;\n            this->decay = decay;\n            this->momentum = momentum;\n            this->iterations = 0.0;\n        } \n\n        // Member functions declaration\n        void pre_update_params(double start_learning_rate);\n        void update_params(LayerDense &layer);\n        void post_update_params();\n};\n\nEigen::MatrixXd load_matrix_data(std::string fileToOpen);\nEigen::VectorXi load_vector_data(std::string fileToOpen);\n\n#endif // NEURALNET_HPP\n", "meta": {"hexsha": "d75256139250baa1367f827c90944e9c5fd8feba", "size": 3289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NeuralNet.hpp", "max_stars_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_stars_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNet.hpp", "max_issues_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_issues_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNet.hpp", "max_forks_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_forks_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_forks_repo_licenses": ["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.2450980392, "max_line_length": 101, "alphanum_fraction": 0.6524779568, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6726097530386612}}
{"text": "#include \"drake/math/discrete_lyapunov_equation.h\"\n\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/common/test_utilities/expect_no_throw.h\"\n\nnamespace drake {\nnamespace math {\nnamespace {\n\nusing Eigen::MatrixXd;\n\nconst double kTolerance = 5 * std::numeric_limits<double>::epsilon();\n\nvoid SolveRealLyapunovEquationAndVerify(const Eigen::Ref<const MatrixXd>& A,\n                                        const Eigen::Ref<const MatrixXd>& Q) {\n  MatrixXd X{RealDiscreteLyapunovEquation(A, Q)};\n  // Check that X is symmetric.\n  EXPECT_TRUE(\n      CompareMatrices(X, X.transpose(), 0, MatrixCompareType::absolute));\n  // Check that X is the solution to the discrete time ARE.\n  EXPECT_TRUE(CompareMatrices(A.transpose() * X * A - X, -Q,\n                              5 * kTolerance * Q.norm(),\n                              MatrixCompareType::absolute));\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, ThrowInvalidSizedMatricesTest) {\n  // This tests if the exceptions are thrown for invalidly sized matrices. A and\n  // Q need to be square and of same size.\n  const int n{1}, m{2};\n\n  // non-square A\n  MatrixXd A1(n, m);\n  A1 << 1, 1;\n  MatrixXd Q1(m, m);\n  Q1 << 1, 1, 1, 1;\n\n  // non-square Q\n  MatrixXd A2(m, m);\n  A2 << 1, 1, 1, 1;\n  MatrixXd Q2(n, m);\n  Q2 << 1, 1;\n\n  // not-same sized\n  MatrixXd A3(m, m);\n  A3 << 1, 1, 1, 1;\n  MatrixXd Q3(n, n);\n  Q3 << 1;\n\n  std::vector<MatrixXd> As{A1, A2, A3};\n  std::vector<MatrixXd> Qs{Q1, Q2, Q3};\n\n  for (int i = 0; i < static_cast<int>(As.size()); ++i) {\n    EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(As[i], Qs[i]));\n  }\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, ThrowEigenValuesATest) {\n  // Given the Eigenvalues of @param A as lambda_1, ..., lambda_n, then the\n  // solution is unique if and only if lambda_i * lambda_j != 1 for all  i, j.\n  // (see Barraud, A.Y., \"A numerical algorithm to solve A\u1d40XA - X = Q,\" IEEE\u00ae\n  // Trans. Auto. Contr., AC-22, pp. 883-885, 1977.)\n  // This tests if an exception is thrown if the eigenvalues violate this\n  // requirement.\n  const int n{3};\n  // pair of eigenvalues that multiplies to 1\n  MatrixXd A1(n, n);\n  A1 << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n  // pairs of eigenvalues that multiply to \u00b1i, i.e should not throw\n  MatrixXd A2(n, n);\n  A2 << 0.5, 0, 0, 0, 0, 2.0, 0, -2.0, 0;\n  // pair of eigenvalues whose product is within tol of 1\n  MatrixXd A3(n, n);\n  A3 << 1 + 1e-6, 0, 0, 0, 0.5, 0, 0, 0, 1 - 1e-6;\n  // no pair of eigenvalues whose product is within tol of 1\n  MatrixXd A4(n, n);\n  A4 << 1 + 1e-6, 0, 0, 0, 1 + 1e-6, 0, 0, 0, 1 + 1e-6;\n  MatrixXd Q(n, n);\n  Q << 1, 0, 0, 0, 1, 0, 0, 0, 1;\n\n  EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(A1, Q));\n  DRAKE_EXPECT_NO_THROW(RealDiscreteLyapunovEquation(A2, Q));\n  EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(A3, Q));\n  DRAKE_EXPECT_NO_THROW(RealDiscreteLyapunovEquation(A4, Q));\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve1by1Test) {\n  // This is a simple 1-by-1 test case, it tests the internal 1-by-1 solver.\n  const int n{1};\n  MatrixXd A(n, n);\n  A << 0.5;\n  MatrixXd Q(n, n);\n  Q << 1;\n  MatrixXd X(n, n);\n  X << 4.0 / 3.0;\n\n  EXPECT_TRUE(\n      CompareMatrices(internal::Solve1By1RealDiscreteLyapunovEquation(A, Q), X,\n                      kTolerance, MatrixCompareType::absolute));\n\n  SolveRealLyapunovEquationAndVerify(A, Q);\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve2by2Test) {\n  // This is a simple 2-by-2 test case, which tests the internal 2-by-2 solver.\n  // The result is compared to the one generated by Matlab's dlyap function.\n  const int n{2};\n  MatrixXd A(n, n);\n  A << 0.5, -0.5, 0, 0.25;\n  MatrixXd X(n, n);\n  X << 4.0, 0, 0, 2.0 + 1.0 / 7.5;\n\n  MatrixXd Q_internal(n, n);\n  Q_internal << 3, 1, NAN, 1;\n  EXPECT_TRUE(CompareMatrices(\n      internal::Solve2By2RealDiscreteLyapunovEquation(A, Q_internal), X,\n      kTolerance, MatrixCompareType::absolute));\n\n  MatrixXd Q(n, n);\n  Q << 3, 1, 1, 1;\n  EXPECT_TRUE(CompareMatrices(RealDiscreteLyapunovEquation(A, Q), X, kTolerance,\n                              MatrixCompareType::absolute));\n  SolveRealLyapunovEquationAndVerify(A.transpose(), Q);\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve3by3Test1) {\n  // Tests if a 3-by-3 problem is reduced.\n  const int n{3};\n  MatrixXd A(n, n);\n  A << -0.5 * MatrixXd::Identity(n, n);\n  MatrixXd Q(n, n);\n  Q << MatrixXd::Identity(n, n);\n\n  SolveRealLyapunovEquationAndVerify(A, Q);\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve3by3Test2) {\n  // The system has eigenvalues: lambda_1/2  = -0 +/- 0.5i\n  // and lambda_3 = -0.5. Therefore, there exists a 2-by-2 block on the\n  // diagonal.\n  // The compared solution is generated by matlab's dlyap function.\n\n  int n{3};\n  MatrixXd A(n, n);\n  A << 0.5, 0, 0, 0, 0, 0.5, 0, -0.5, 0;\n  MatrixXd Q(n, n);\n  Q << MatrixXd::Identity(n, n);\n  MatrixXd X(n, n);\n  X << (4.0 / 3.0) * MatrixXd::Identity(n, n);\n\n  EXPECT_TRUE(CompareMatrices(RealDiscreteLyapunovEquation(A, Q), X, kTolerance,\n                              MatrixCompareType::absolute));\n  SolveRealLyapunovEquationAndVerify(A, Q);\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve4by4Test1) {\n  // The system has eigenvalues: lambda_1/2  = -0.4500 +/- 0.7794i\n  // and lambda_3/4 = -0.9.\n\n  const int n{4};\n  MatrixXd A(n, n);\n  A << -0.9, 0, 0, 0, 0, 0, 0.9, 0, 0, -0.9, -0.9, 0, 0, 0, 0, -0.9;\n  MatrixXd Q(n, n);\n  Q << MatrixXd::Identity(n, n);\n  SolveRealLyapunovEquationAndVerify(A, Q);\n}\n\nGTEST_TEST(RealDiscreteLyapunovEquation, Solve4by4Test2) {\n  // The system has eigenvalues: lambda_1/2  = 0.3 +/- 0.4i\n  // and lambda_3/4 = 0.4 +/- 0.5i\n\n  const int n{4};\n  MatrixXd A(n, n);\n  A << 0.3, 0, 0, 0.4, 0, 0.4, 0.5, 0, 0, -0.5, 0.4, 0, -0.4, 0, 0, 0.3;\n  MatrixXd Q(n, n);\n  Q << MatrixXd::Identity(n, n);\n  SolveRealLyapunovEquationAndVerify(A, Q);\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "0c2299151f3cc19d2e5fe05fe0551cbe7d80f95d", "size": 5944, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/discrete_lyapunov_equation_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/test/discrete_lyapunov_equation_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "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": "math/test/discrete_lyapunov_equation_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 31.4497354497, "max_line_length": 80, "alphanum_fraction": 0.6426648721, "num_tokens": 2211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.672538573602071}}
{"text": "//\n// Created by haohanwang on 1/24/16.\n//\n\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <queue>\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef ALGORITHMS_MODEL_HPP\n#define ALGORITHMS_MODEL_HPP\n\n\ntypedef unsigned int model_id_t;\n\nstruct modelResult{\n    string rowStr;\n    string colStr;\n    MatrixXf beta;\n};\n\nclass Model {\nprotected:\n    MatrixXf X;\n    MatrixXf beta;\n    MatrixXf y;\n    bool logisticFlag;\n    static float sigmoid(float x){return 1.0 / (1.0 + exp(-x));}\n    void checkLogisticRegression();\npublic:\n    void imputation();\n    virtual void setX(const MatrixXf&);\n    virtual void setY(const MatrixXf&);\n    virtual void setAttributeMatrix(const string&, MatrixXf*);\n    void initBeta();\n    void initBeta(MatrixXf);\n    void updateBeta(MatrixXf);\n    MatrixXf getX();\n    MatrixXf getBeta();\n    MatrixXf getY();\n    modelResult getClusteringResult(); // Scheduler needs to run model.getClusteringResult() for the result, instead of getBeta();\n\n    MatrixXf predict();\n    MatrixXf predict(MatrixXf);\n    \n    virtual void assertReadyToRun(){};\n    virtual MatrixXf derivative();\n    virtual MatrixXf proximal_derivative();\n    virtual MatrixXf proximal_operator(MatrixXf, float);\n\n    virtual float cost();\n\n    Model();\n    Model(const unordered_map<string, string>&);\n    Model(MatrixXf, VectorXf);\n\n    virtual ~Model(){};\n};\n\n\n#endif //ALGORITHMS_MODEL_HPP\n", "meta": {"hexsha": "a3ce91dcee1924903d492ca44acc155c71d362cf", "size": 1400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Models/Model.hpp", "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/Models/Model.hpp", "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/Models/Model.hpp", "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": 21.875, "max_line_length": 130, "alphanum_fraction": 0.6964285714, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347124, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6725356596654395}}
{"text": "#include \"kalman_filter.hpp\"\n#include <Eigen/QR>\nnamespace biggles\n{\n\nmatrix4x2f kalman_gain(const matrix2f& R, const matrix4f& Pred, const matrix2x4f& B) {\n    matrix4x2f LHS = Pred*B.transpose();\n    matrix2f S = B*LHS + R;\n    S = enforce_symmetry(S);\n    if (not is_symmetric(S)) {\n        OK1(S);\n        OK1(R);\n        OK1(B*LHS);\n        BOOST_ASSERT(is_symmetric(S));\n    }\n    matrix2x4f gain_transposed = S.transpose().colPivHouseholderQr().solve(LHS.transpose());\n    return gain_transposed.transpose();\n}\n\n//template<typename InputIterator>\nvoid kalman_filter::reinitialise(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    // set the dynamic drag associated with this filter\n    dynamic_drag_ = dynamic_drag;\n\n    // remove any existing solution\n    prediction_states_and_covs_.clear();\n    correction_states_and_covs_.clear();\n\n    BOOST_ASSERT(last_time_stamp >= first_time_stamp);\n    BOOST_ASSERT(first != last);\n\n    // shortcut the entire filter if we have nothing to generate\n    if(first_time_stamp == last_time_stamp)\n        return;\n\n    // the state evolution matrix: X_{k+1} = A X_k + <noise>\n    Eigen::Matrix4f A(Eigen::Matrix4f::Identity());\n    A(0,1) = A(2,3) = dynamic_drag_; // <- off-diagonal velocity integration\n\n\n    //// covariance matrix of the state noise\n    //Eigen::Matrix4f Q(Eigen::Matrix4f::Zero());\n    //Q(0,0) = Q(2,2) = 1e-1f * 1e-1f * detail::speed_of_light_ * detail::speed_of_light_;\n    //Q(1,1) = Q(3,3) = 1e-2f * 1e-2f * detail::speed_of_light_ * detail::speed_of_light_;\n\n    // the observation matrix: Y_k = B X_k + <noise>\n    Eigen::Matrix<float, 2, 4> B( Eigen::Matrix<float, 2, 4>::Zero());\n    B(0,0) = B(1,2) = 1.f;\n\n    // initial state\n    Eigen::Vector4f mu;\n    mu << 64.f, 0.f, 64.f, 0.f;\n    //mu << x(*first), 0.f, y(*first), 0.f;\n    //std::cout << mu << std::endl;\n\n    // initial error\n    //const float image_size(128.f);\n    //const float s2(4.f*image_size*image_size);\n    //const float s2(1e-1f * detail::speed_of_light_ * 1e-1f * detail::speed_of_light_);\n    //const float s2(powf(2.f, 16.f));\n    const float s2(powf(2.f, 16.f));\n    Eigen::Matrix4f Sigma(s2 * Eigen::Matrix4f::Identity());\n    Sigma(1,1) = Sigma(3,3) = 1e-2f * detail::speed_of_light_ * detail::speed_of_light_;\n\n    // prediction_states_and_covs_ is mu_{t|t-1} and Sigma_{t|t-1}\n    // correction_states_and_covs_ is mu_{t|t} and Sigma_{t|t}\n    // forward loop\n    // BOOST_ASSERT(Q.determinant() > 0.f);\n    for(time_stamp time_stamp = first_time_stamp; time_stamp < last_time_stamp; ++time_stamp)\n    {\n        // prediction\n        Eigen::Vector4f predict_mu = A * mu;\n        Eigen::Matrix4f predict_Sigma = A * Sigma * A.transpose() + Q;\n\n        // record the predictions mu_{t|t-1} and Sigma_{t|t-1}\n        /*\n        if (not (predict_Sigma.determinant() > 0)) {\n            OK(Sigma.determinant());\n            OK(Q.determinant());\n        }\n        */\n        prediction_states_and_covs_.push_back(state_covariance_pair(predict_mu, predict_Sigma));\n\n        // do we have an observation for this time step?\n        if((first == last) || (t(*first) != time_stamp))\n        {\n            // no observation for this time stamp, simply evolve state\n            mu = predict_mu;\n            Sigma = predict_Sigma;\n        }\n        else\n        {\n            // we have an observation, woo! Retrieve it and increment observation iterator.\n            const observation& obs(*first);\n            ++first;\n\n            // extract observation location\n            Eigen::Vector2f obs_vec;\n            obs_vec << x(obs), y(obs);\n\n            // update\n            matrix4x2f K = kalman_gain(R, predict_Sigma, B);\n                //predict_Sigma * B.transpose() * (B * predict_Sigma * B.transpose() + R).inverse();\n\n            mu = predict_mu + K * (obs_vec - B * predict_mu);\n            //Eigen::Matrix4f proto_sigma = predict_Sigma - K * B * predict_Sigma;\n            Eigen::Matrix4f raw_sigma = predict_Sigma - K * B * predict_Sigma;\n            Sigma = enforce_symmetry(raw_sigma);\n            if (not is_symmetric(Sigma)) {\n                OK1((K * B));\n                OK1(K * B * predict_Sigma);\n                OK(is_symmetric(K * B * predict_Sigma));\n                OK(measure_asymmetry(K * B * predict_Sigma));\n            }\n        }\n\n        if (not is_symmetric(Sigma) and measure_asymmetry(Sigma) > 0.f) {\n            OK(\"1\");\n            OK1(Sigma);\n            OK(measure_asymmetry(Sigma));\n            OK1(predict_Sigma);\n            OK1(R);\n            BOOST_ASSERT(is_symmetric(Sigma));\n        }\n\n        // record the corrections mu_{t|t} and Sigma_{t|t}\n        correction_states_and_covs_.push_back(state_covariance_pair(mu, Sigma));\n    }\n\n    // check we generated the expected number of states\n    BOOST_ASSERT(prediction_states_and_covs_.size() == static_cast<size_t>(last_time_stamp - first_time_stamp));\n    BOOST_ASSERT(prediction_states_and_covs_.size() > 0);\n    BOOST_ASSERT(correction_states_and_covs_.size() == static_cast<size_t>(last_time_stamp - first_time_stamp));\n    BOOST_ASSERT(correction_states_and_covs_.size() > 0);\n\n    // last element of prediction_states_and_covs_ is (mu_{T|T-1}, Sigma_{T|T-1})\n    // last element of correction_states_and_covs_ is (mu_{T|T}, Sigma_{T|T})\n    // where T is last_time_stamp\n}\n\n\n\n} // namespace biggles\n", "meta": {"hexsha": "019d7e3f13a306691abcc530ea18f41bf3ab6e24", "size": 5600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "biggles/kalman_filter.cpp", "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": "biggles/kalman_filter.cpp", "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": "biggles/kalman_filter.cpp", "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": 37.5838926174, "max_line_length": 112, "alphanum_fraction": 0.6055357143, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6725356562893047}}
{"text": "\n/***************************************************************************\n\nThe MIT License (MIT)\n\nCopyright (c) 2013-2017 Joel E. Merritt\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//  This module defines the GNSolver (Gauss-Newton Solver) class whose\n//  objects solve the camera resection (calibration) described in\n//  main.cpp.\n\n#include \"g_n_solver.h\"\n\n#include <iostream>\n#include <Eigen/Dense>\n\n\n//\n//  Member Function: GNSolver::GetErr2\n//\n//  Return the length squared of input vector.\n//\n//  Input parameters:\n//  a -- vector to calculate length squared\n//\n\ndouble GNSolver::GetErr2(Eigen::VectorXd const &a) const\n{\n  double ret = 0.0;\n  for(int i = 0;i < a.size();i++)\n  {\n    ret += a[i] * a[i];\n  }\n\n  return ret;\n}\n\n\n//\n//  Member Function: GNSolver::EvalRFunctionVector\n//\n//  Return the vector containing the outputs of the r functions.\n//\n//  Input parameters:\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\nEigen::VectorXd GNSolver::EvalRFunctionVector(FunctionObjectList const &r,\n                                              Eigen::VectorXd const &beta)\n                                              const\n{\n  int num_conds = r.size();\n  Eigen::VectorXd ret(num_conds);\n\n  for(int i = 0;i < num_conds;i++)\n  {\n    ret[i] = r[i](beta);\n  }\n\n  return ret;\n}\n\n\n//\n//  Member Function: GNSolver::GetPartialD\n//\n//  Return the partial derivative (partial d)r[i] / (partial d)beta[j].\n//\n//  Input parameters:\n//  i    -- row index\n//  j    -- column index\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\ndouble GNSolver::GetPartialD(int i, int j, FunctionObjectList const &r,\n                             Eigen::VectorXd const &beta) const\n{\n  double epsilon = 0.001;\n\n  Eigen::VectorXd beta_epsilon = beta;\n  beta_epsilon[j] += epsilon;\n\n  double ret = r[i](beta);\n  double ret_epsilon = r[i](beta_epsilon);\n\n  double partd = (ret - ret_epsilon) / epsilon;\n\n  return partd;\n}\n\n\n//\n//  Member Function: GNSolver::Jacobian\n//\n//  Return the Jacobian matrix of vector function r.\n//\n//  Input parameters:\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\nEigen::MatrixXd GNSolver::Jacobian(FunctionObjectList const &r,\n                                   Eigen::VectorXd const &beta) const\n{\n  int num_conds = r.size();\n  Eigen::MatrixXd ret(num_conds, beta.size());\n\n  for(int i = 0;i < num_conds;i++)\n  {\n    for(int j = 0;j < beta.size();j++)\n    {\n      ret(i, j) = GetPartialD(i, j, r, beta);\n    }\n  }\n\n  return ret;\n}\n\n\n//\n//  Member Function: GNSolver::CalcErr2\n//\n//  Return the error of vector function r.\n//\n//  Input parameters:\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\ndouble GNSolver::CalcErr2(FunctionObjectList const &r,\n                          Eigen::VectorXd const &beta) const\n{\n  Eigen::VectorXd vcol = EvalRFunctionVector(r, beta);\n\n  return GetErr2(vcol);\n}\n\n\n//\n//  Member Function: GNSolver::CalcDiff\n//\n//  Return the calculated difference to adjust the beta vector.\n//\n//  The Gauss-Newton algorithm calculates successive approximations of\n//  the beta vector by the following equation:\n//\n//  beta_next = beta_current - (J^T*J)^-1*J^T * r(beta_current)\n//\n//  where:\n//  beta_next is the next iteration of the beta vector\n//  beta_current is the current iteration of the beta vector\n//  J is the Jacobian matrix\n//  J^T is the transpose of the Jacobian matrix\n//  r is the r vector of functions to be minimized\n//\n//  CalcDiff calculates and returns this part:\n//\n//  (J^T*J)^-1*J^T * r(beta_current)\n//\n//  Input parameters:\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\nEigen::VectorXd GNSolver::CalcDiff(FunctionObjectList const &r,\n                                   Eigen::VectorXd const &beta) const\n{\n  Eigen::MatrixXd ejf = Jacobian(r, beta);\n\n  Eigen::MatrixXd ejft = ejf.transpose();\n  Eigen::MatrixXd ejf2 = ejft * ejf;\n  Eigen::MatrixXd ejf3 = ejf2.inverse() * ejft;\n\n  Eigen::MatrixXd vcol = EvalRFunctionVector(r, beta);\n\n  return ejf3 * vcol;\n}\n\n\n//\n//  Member Function: GNSolver::operator()\n//\n//  Return the optimized beta vector.\n//\n//  The main solver, iterates to improve the beta vector, including\n//  \"dialing back\" the next iteration of the beta vector until it\n//  produces less error than the current beta vector.\n//\n//  Input parameters:\n//  r    -- vector containing the functions to evaluate\n//  beta -- vector containing camera parameters to optimize, fed into\n//          each r function\n//\n\nEigen::VectorXd GNSolver::operator()(FunctionObjectList const &r,\n                                     Eigen::VectorXd &beta) const\n{\n  std::cout << \"Entering Solve\" << std::endl;\n\n  double err2_min;\n  // iterate loop\n  for(int j = 0;j < 100;j++)\n  {\n    std::cout << \"iteration \" << j << std::endl;\n\n    std::cout << \"BETA\" << std::endl;\n    std::cout << beta << std::endl;\n    std::cout << std::endl;\n\n    double err2 = CalcErr2(r, beta);\n    Eigen::VectorXd ediff = CalcDiff(r, beta);\n\n    std::cout << \"err2 (orig) \" << err2 << std::endl;\n\n    double atten = 1.0;\n    err2_min = err2;\n    Eigen::VectorXd beta_min = beta;\n    for(int j1 = 0;j1 < 20;j1++)\n    {\n      Eigen::VectorXd beta_next = atten * ediff + beta;\n\n      double err2_next = CalcErr2(r, beta_next);\n      std::cout << \"j1 \" << j1 << \" atten \" << atten << \" err2_next \" <<\n          err2_next << std::endl;\n      if(err2_next < err2_min)\n      {\n        err2_min = err2_next;\n        beta_min = beta_next;\n        atten *= 0.7;\n      }\n      else\n      {\n        atten *= 0.7;\n      }\n    }\n\n    beta = beta_min;\n\n    // stop iterating if the error is almost zero\n    if(err2_min < 0.0000001)\n    {\n      std::cout << \"solved\" << std::endl;\n\n      break;\n    }\n\n    // stop iterating if the error has decreased minimally\n    if(err2_min / err2 > 0.99999)\n    {\n      std::cout << \"converged\" << std::endl;\n\n      break;\n    }\n  } // iterate\n\n  std::cout << \"**********OUTPUT************\" << std::endl;\n  std::cout << \"BETA\" << std::endl;\n  std::cout << beta << std::endl;\n  std::cout << std::endl;\n  std::cout << \"err2_min \" << err2_min << std::endl;\n\n  return beta;\n}\n\n", "meta": {"hexsha": "aed18cab486ee58a97804b6dcd3059d172c08af8", "size": 7628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g_n_solver.cpp", "max_stars_repo_name": "joel1fx/camera-resection", "max_stars_repo_head_hexsha": "b407dfc0fecbfed623f37f178087b202fc6b9310", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-25T20:22:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T20:22:35.000Z", "max_issues_repo_path": "g_n_solver.cpp", "max_issues_repo_name": "joel1fx/camera-resection", "max_issues_repo_head_hexsha": "b407dfc0fecbfed623f37f178087b202fc6b9310", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "g_n_solver.cpp", "max_forks_repo_name": "joel1fx/camera-resection", "max_forks_repo_head_hexsha": "b407dfc0fecbfed623f37f178087b202fc6b9310", "max_forks_repo_licenses": ["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.1232876712, "max_line_length": 78, "alphanum_fraction": 0.624934452, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6725282653406115}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\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\r\n//! \\file\r\n//!\\brief Test for a successful bare-metal configuration of fixed_point using a 16-bit negatable type.\r\n\r\n// For further mathematical details pertaining to this file,\r\n// see C.M. Kormanyos, 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 BOOST_TEST_MODULE test_negatable_basic_metal_config_16bit\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n// Configure Boost.Fixed_point for a bare-metal system.\r\n\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\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename RealValueType,\r\n           typename RealFunctionType>\r\n  RealValueType first_derivative(const RealValueType& x,\r\n                                 const RealValueType& dx,\r\n                                 RealFunctionType real_function)\r\n  {\r\n    // Evaluate first derivative of real_function using\r\n    // a three-point central-difference rule of O(dx^6).\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} // namespace local\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_basic_metal_config_16bit)\r\n{\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) / 10U;\r\n  const fixed_point_type b = fixed_point_type(34) / 10U;\r\n  const fixed_point_type c = fixed_point_type(56) / 10U;\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 step size is set to a value\r\n  // of approximately 1/8.\r\n\r\n  const fixed_point_type d =\r\n    local::first_derivative(fixed_point_type(1) / 2U,  // x\r\n                            fixed_point_type(1) / 4U,  // 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\r\n  // The expected result is ((2 * a) + b) = (1.2 + 3.4) = 4.6 (exact).\r\n  // We obtain a fixed-point result of approximately 4.594.\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  // This is the test of the result that has been used\r\n  // on the bare-metal system.\r\n  const bool result_is_ok = ((d > (fixed_point_type(45) / 10U)) && (d < (fixed_point_type(47) / 10U)));\r\n\r\n  BOOST_CHECK_EQUAL(result_is_ok, true);\r\n\r\n  // Now we perform a second test of the result based on a\r\n  // close-fraction test. We do not use BOOST_CHECK_CLOSE_FRACTION()\r\n  // here becasue that would require I/O streaming, which is\r\n  // disabled in this bare-metal configuration.\r\n  const fixed_point_type fraction = fabs(d / (fixed_point_type(46) / 10U));\r\n  const fixed_point_type delta    = fabs(1 - fraction);\r\n  const fixed_point_type tol      = ldexp(fixed_point_type(1), fixed_point_type::resolution + 2);\r\n\r\n  const bool result_is_within_tolerance = (delta <= tol);\r\n\r\n  BOOST_CHECK_EQUAL(result_is_within_tolerance, true);\r\n}\r\n", "meta": {"hexsha": "b8a6a2d1840d4dce10f6a6d4869b68e89284fd1b", "size": 4299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_basic_bare_metal_config_16bit.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": "test/test_negatable_basic_bare_metal_config_16bit.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": "test/test_negatable_basic_bare_metal_config_16bit.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": 41.3365384615, "max_line_length": 104, "alphanum_fraction": 0.6350314027, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6725282592462758}}
{"text": "#include <iostream>\n#include <boost/numeric/odeint.hpp>\n#include \"gnuplot-iostream.h\"\n#include \"sysfunc_exercise2_2_b.h\"\n\n\nnamespace odeint = boost::numeric::odeint;\n\nint main(int argc, char const *argv[])\n{\n    // Odeint\n    std::vector<double> position;\n    {\n        system_function::state_type x; // a vector with size 3. [x; x_dot; x_dot_dot]\n        //x = {1,1,1, 1};                    // start at x=1, 1, 1, 1;\n        x = {1, -1, 1, -1};\n        size_t steps = odeint::integrate(system_function::harmonic_oscillator,\n                                         x, 0.0, 10.0, 0.1,\n                                         system_function::push_back_state_and_time);\n\n        for (size_t i = 0; i <= steps; i++)\n        {\n            position.push_back(system_function::m_states[i][0]);\n        }\n    }\n\n    // GNU Plot\n    {\n        /* output */\n        Gnuplot gp;\n        gp << \"plot '-' using 1:2 with linespoint\" << std::endl;\n        gp.send1d(std::make_tuple(system_function::m_times, position));\n    }\n    return 0;\n}\n", "meta": {"hexsha": "ff80344b6d1978047fa927318b43bb0ba4166aee", "size": 1030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW/hw2/src/exercise2_2_b.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/hw2/src/exercise2_2_b.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/hw2/src/exercise2_2_b.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": 28.6111111111, "max_line_length": 85, "alphanum_fraction": 0.5281553398, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6724742823181922}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\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#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\ntemplate<class T>\nclass func {\npublic:\n  typedef T real_t;\n  func(real_t a) : a_(a) {}\n  real_t operator()(real_t x) const {\n    using std::abs; using std::cos; using std::log;\n    auto s = abs(a_ * a_ - 2 * a_ * cos(x) + 1);\n    return (s > 0) ? log(s) : real_t(0);\n  }\n  real_t result() const {\n    using std::abs; using std::log;\n    using boost::math::constants::pi;\n    return (abs(a_) < 1) ? real_t(0) : (2 * pi<real_t>() * log(abs(a_)));\n  }\nprivate:\n  real_t a_;\n};\n\nint main() {\n  using std::abs; using std::sqrt;\n  typedef boost::multiprecision::cpp_dec_float_50 real_t;\n  const real_t pi = boost::math::constants::pi<real_t>();\n\n  boost::math::quadrature::tanh_sinh<real_t> integrator;\n  real_t termination = sqrt(std::numeric_limits<real_t>::epsilon());\n  real_t error, L1;\n  size_t levels;\n  \n  real_t values[5] = { 0.5, 1 - 1e-6, 1, 1 + 1e-6, 1.5 };\n  for (auto a : values) {\n    func<real_t> f(a);\n    real_t q = integrator.integrate(f, 0, pi, termination, &error, &L1, &levels);\n\n    std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n              << \"value of a: \" << a << std::endl\n              << \"result: \" << q << std::endl\n              << \"estimated error: \" << error << std::endl\n              << \"real error: \" << abs(q - f.result()) << std::endl\n              << \"L1 * error: \" << L1 * error << std::endl\n              << \"levels: \" << levels << std::endl;\n  }\n}\n", "meta": {"hexsha": "44a517304e084dee5022bccbaa8f04820fc0b7c9", "size": 2012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tanh_sinh/example1_fp50.cpp", "max_stars_repo_name": "wistaria/boost-examples", "max_stars_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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": "tanh_sinh/example1_fp50.cpp", "max_issues_repo_name": "wistaria/boost-examples", "max_issues_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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": "tanh_sinh/example1_fp50.cpp", "max_forks_repo_name": "wistaria/boost-examples", "max_forks_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "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.5333333333, "max_line_length": 92, "alphanum_fraction": 0.5596421471, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6724742704111583}}
{"text": "/* Copyright (c) 2017, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n \n#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <algorithm>\n#include <random>\n\n#include <iostream>\n\n#define LOG_2PI 1.8378770664093453\n\ntemplate<typename T, int D>\nclass Normal\n{\n public:\n\n  Normal();\n  Normal(const Eigen::Matrix<T,D,1>& mu, const Eigen::Matrix<T,D,D>& Sigma);\n  Normal(const Eigen::Matrix<T,D,D>& Sigma);\n  Normal(const Normal<T,D>& other);\n  ~Normal();\n\n  T logPdf(const Eigen::Matrix<T,D,D>& x) const;\n  T logPdfSlower(const Eigen::Matrix<T,D,D>& x) const;\n  T logPdf(const Eigen::Matrix<T,D,D>& scatter, \n      const Eigen::Matrix<T,D,1>& mean, T count) const;\n  T logPdfSlower(const Eigen::Matrix<T,D,D>& scatter, \n      const Eigen::Matrix<T,D,1>& mean, T count) const;\n  T logPdf(const Eigen::Matrix<T,D,D>& scatter, T count) const;\n\n  Eigen::Matrix<T,D,1> sample(std::mt19937& rnd);\n\n  void print() const;\n\n  const Eigen::Matrix<T,D,D>& Sigma() const {return Sigma_;};\n  void setSigma(const Eigen::Matrix<T,D,D>& Sigma)\n  { Sigma_ = Sigma; SigmaLDLT_.compute(Sigma_); \n    logDetSigma_ = ((Sigma_.eigenvalues()).array().log().sum()).real();};\n  T logDetSigma() const {return logDetSigma_;};\n  const Eigen::LDLT<Eigen::Matrix<T,D,D> >& SigmaLDLT() const {return SigmaLDLT_;};\n\n  Eigen::Matrix<T,D,1> mu_;\n  Eigen::Matrix<T,D,D> Sigma_;\nprivate:\n\n  // helpers for fast computation\n  T logDetSigma_;\n  Eigen::LDLT<Eigen::Matrix<T,D,D> > SigmaLDLT_;\n\n  std::normal_distribution<T> gauss_;\n};\n\ntemplate<typename T, int D>\nNormal<T,D>::Normal(const Eigen::Matrix<T,D,1>& mu, const Eigen::Matrix<T,D,D>& Sigma)\n  : mu_(mu), Sigma_(Sigma), SigmaLDLT_(Sigma_), gauss_(0,1)\n{\n  // equivalent to log(det(Sigma)) but more stable for small values\n  logDetSigma_ = ((Sigma_.eigenvalues()).array().log().sum()).real();\n};\n\ntemplate<typename T, int D>\nNormal<T,D>::Normal(const Eigen::Matrix<T,D,D>& Sigma)\n  : mu_(Eigen::Matrix<T,D,1>::Zero()), Sigma_(Sigma), SigmaLDLT_(Sigma_) , gauss_(0,1)\n{\n  // equivalent to log(det(Sigma)) but more stable for small values\n  logDetSigma_ = ((Sigma_.eigenvalues()).array().log().sum()).real();\n};\n\ntemplate<typename T, int D>\nNormal<T,D>::Normal()\n  : mu_(Eigen::Matrix<T,D,1>::Zero()), Sigma_(Eigen::Matrix<T,D,D>::Identity()), SigmaLDLT_(Sigma_), gauss_(0,1)\n{\n  // equivalent to log(det(Sigma)) but more stable for small values\n  logDetSigma_ = ((Sigma_.eigenvalues()).array().log().sum()).real();\n};\n\ntemplate<typename T, int D>\nNormal<T,D>::Normal(const Normal<T,D>& other)\n  : mu_(other.mu_), Sigma_(other.Sigma_),\n  logDetSigma_(other.logDetSigma_), SigmaLDLT_(Sigma_) , gauss_(0,1)\n{};\n\ntemplate<typename T, int D>\nNormal<T,D>::~Normal()\n{}\n\ntemplate<typename T, int D>\nT Normal<T,D>::logPdf(const Eigen::Matrix<T,D,D>& x) const\n{\n  return -0.5*(LOG_2PI*D + logDetSigma_ +((x-mu_).transpose()*SigmaLDLT_.solve(x-mu_)).sum() );\n}\n\ntemplate<typename T, int D>\nT Normal<T,D>::logPdfSlower(const Eigen::Matrix<T,D,D>& x) const\n{\n  return -0.5*(LOG_2PI*D + logDetSigma_\n//      +((x-mu_).transpose()*Sigma_.inverse()*(x-mu_)).sum() );\n  +((x-mu_).transpose()*Sigma_.fullPivHouseholderQr().solve(x-mu_)).sum() );\n}\n\ntemplate<typename T, int D>\nT Normal<T,D>::logPdf(const Eigen::Matrix<T,D,D>& scatter, \n      const Eigen::Matrix<T,D,1>& mean, T count) const\n{\n\tEigen::Matrix<T,1,D> meanT = mean.transpose();\n\tEigen::Matrix<T,D,D> CovMu= SigmaLDLT_.solve(mu_);\t\n\treturn -0.5*((LOG_2PI*D + logDetSigma_)*count \n\t\t+ count*(mu_.transpose()*CovMu).sum() \n\t\t-2.*count*(meanT*CovMu).sum()\n\t\t+(SigmaLDLT_.solve(scatter + mean*meanT*count)).trace());\n\n  //return -0.5*((LOG_2PI*D + logDetSigma_)*count\n  //    + count*(mu_.transpose()*SigmaLDLT_.solve(mu_)).sum() \n  //    -2.*count*(mean.transpose()*SigmaLDLT_.solve(mu_)).sum()\n  //    +(SigmaLDLT_.solve(scatter + mean*mean.transpose()*count )).trace());\n}\n\ntemplate<typename T, int D>\nT Normal<T,D>::logPdfSlower(const Eigen::Matrix<T,D,D>& scatter, \n      const Eigen::Matrix<T,D,1>& mean, T count) const\n{\n\tEigen::Matrix<T,1,D> meanT = mean.transpose();\n\tEigen::Matrix<T,D,D> CovMu= \n    Sigma_.fullPivHouseholderQr().solve(mu_);\n\treturn -0.5*((LOG_2PI*D + logDetSigma_)*count \n\t\t+ count*(mu_.transpose()*CovMu).sum() \n\t\t-2.*count*(meanT*CovMu).sum()\n\t\t+(Sigma_.fullPivHouseholderQr().solve(\n      scatter + mean*meanT*count)).trace());\n}\n\ntemplate<typename T, int D>\nT Normal<T,D>::logPdf(const Eigen::Matrix<T,D,D>& scatter, T count) const\n{\n  assert(false);\n//  cout<<count*(mu_.transpose()*SigmaLDLT_.solve(mu_)).sum()<<endl;\n//  cout<<(SigmaLDLT_.solve(scatter)).trace()<<endl;\n  return -0.5*((LOG_2PI*D + logDetSigma_)*count\n      + count*(mu_.transpose()*SigmaLDLT_.solve(mu_)).sum() \n      +(SigmaLDLT_.solve(scatter)).trace());\n}\n\ntemplate<typename T, int D>\nEigen::Matrix<T,D,1> Normal<T,D>::sample(std::mt19937& rnd)\n{\n  // populate the mean\n  Eigen::Matrix<T,D,1> x(D);\n  for (uint32_t d=0; d<D; d++)\n    x[d] = gauss_(rnd); //gsl_ran_gaussian(r,1);\n  Eigen::Matrix<T,D,D> sqrtD = Eigen::Matrix<T,D,D>::Zero(D,D); \n  sqrtD.diagonal() = SigmaLDLT_.vectorD();\n  sqrtD = sqrtD.array().sqrt();\n  return (SigmaLDLT_.matrixL()*sqrtD*SigmaLDLT_.matrixU())*x + mu_;\n};\n\n", "meta": {"hexsha": "32f1bb3d83bdb6b6835ab3c5f958b1589afd9985", "size": 5229, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/tdp/sampling/normal.hpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "include/tdp/sampling/normal.hpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "include/tdp/sampling/normal.hpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 32.68125, "max_line_length": 112, "alphanum_fraction": 0.6620768789, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.672452072791908}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2018-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_DIFF_HPP\n#define NYARUGA_UTIL_DIFF_HPP\n\n#pragma once\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <cmath>\n#include <limits>\n#include <nyaruga_util/get_arg_type.hpp>\n#include <type_traits>\n\nnamespace nyaruga {\n\nnamespace util {\n\nusing num_t =\n   boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000>>;\n\n// \u5fae\u5206\u3057\u307e\u3059\n// 7 \u70b9\u8fd1\u4f3c\u3067\u3059\ntemplate <typename Number = num_t, typename F>\nconstexpr auto diff(F && f) noexcept\n{\n   return [f](auto && x) noexcept(noexcept(f(x))) -> Number {\n      auto h = 1e-7;\n      if constexpr (std::is_same_v<Number, num_t>)\n         h = DBL_EPSILON;\n\n      auto&& y1 = f(static_cast<Number>(x + h));\n      auto&& y2 = f(static_cast<Number>(x - h));\n      auto&& y3 = f(static_cast<Number>(x + 2 * h));\n      auto&& y4 = f(static_cast<Number>(x - 2 * h));\n      auto&& y5 = f(static_cast<Number>(x + 3 * h));\n      auto&& y6 = f(static_cast<Number>(x - 3 * h));\n\n      return (y5 - 9 * y3 + 45 * y1 - 45 * y2 + 9 * y4 - y6) /\n                           (60 * h);\n   };\n}\n\n// 5 \u70b9\u8fd1\u4f3c\u3067\u3059\ntemplate <typename Number = num_t, typename F>\nconstexpr auto diff_fast(F && f) noexcept\n{\n   return [f](auto && x) noexcept(noexcept(f(x))) -> Number\n   {\n      auto h = 1e-7;\n      if constexpr (std::is_same_v<Number, num_t>)\n         h = DBL_EPSILON;\n\n      auto && y1 = f(static_cast<Number>(x + h));\n      auto && y2 = f(static_cast<Number>(x - h));\n      auto && y3 = f(static_cast<Number>(x + 2 * h));\n      auto && y4 = f(static_cast<Number>(x - 2 * h));\n\n      return (y4 - 8 * y2 + 8 * y1 - y3) / (12 * h);\n   };\n}\n\n} // namespace util\n\n} // namespace nyaruga\n\n#endif // #ifndef NYARUGA_UTIL_DIFF_HPP", "meta": {"hexsha": "403a866f20f4d20df962be1c34b30d1fc1befb6d", "size": 1871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/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/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/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.6301369863, "max_line_length": 81, "alphanum_fraction": 0.60181721, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6724520595624527}}
{"text": "/*\n * Copyright (c) Nuno Alves de Sousa 2019\n *\n * Use, modification and distribution is subject to the Boost Software License,\n * Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n#include <iostream>\n#include <cstdlib>\n#include <cstdint>\n#include <algorithm>\n\n#include <celero/Celero.h>\n\n#include <Eigen/Eigen>\n\n#include <mkl.h>\n\n#include <random_vector.hpp>\n#include <debug.hpp>\n\nvoid dgemmTest()\n{\n    const int m = 3;\n    const int n = 3;\n\n    std::cout << \"Generating random data...\\n\\n\";\n    auto randomDoubles = makeRandomVector(m*n, 0.0, 2.0);\n\n    // Eigen initialization\n    Eigen::MatrixXd eA;\n    eA = Eigen::Map<Eigen::MatrixXd>(randomDoubles.data(), m, n);\n\n    std::cout << \"Eigen matrix:\\n\";\n    EIGEN_DEBUG(eA);\n\n    // MKL initialization\n    auto mA = static_cast<double*>(mkl_malloc(m*n*sizeof(double), 64));\n    auto mC = static_cast<double*>(mkl_malloc(m*n*sizeof(double), 64));\n    if (mA == nullptr || mC == nullptr) {\n        std::cerr << \"error: memory allocation failed. Aborting...\";\n        mkl_free(mA);\n        mkl_free(mC);\n        return;\n    }\n    std::copy(randomDoubles.begin(), randomDoubles.end(), mA);\n    std::fill(mC, mC + n*m, 0);\n\n    std::cout << \"\\nMKL matrices:\\n\";\n    MKL_DEBUG(mA, m, n);\n    MKL_DEBUG(mC, m, n);\n\n    std::cout << \"\\nEigen A * A\\n\";\n    std::cout << eA * eA << '\\n';\n\n    std::cout << \"\\nMKL A * A\\n\";\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, n, 1, mA, m, mA, m, 1, mC, m);\n    MKL_DEBUG(mC, m, n);\n\n    // Cleanup\n    mkl_free(mA);\n    mkl_free(mC);\n}\n\nvoid maddTest()\n{\n    const int m = 5;\n    const int n = 5;\n\n    std::cout << \"Generating random data...\\n\\n\";\n    auto randomDoubles = makeRandomVector(m*n, 0.0, 2.0);\n\n    // Eigen initialization\n    Eigen::MatrixXd eA;\n    eA = Eigen::Map<Eigen::MatrixXd>(randomDoubles.data(), m, n);\n\n    // MKL initialization\n    auto mA = static_cast<double*>(mkl_malloc(m*n*sizeof(double), 64));\n    auto mB = static_cast<double*>(mkl_malloc(m*n*sizeof(double), 64));\n    auto mC = static_cast<double*>(mkl_malloc(m*n*sizeof(double), 64));\n    if (mA == nullptr || mB == nullptr || mC == nullptr) {\n        std::cerr << \"error: memory allocation failed. Aborting...\";\n        mkl_free(mA);\n        mkl_free(mB);\n        mkl_free(mC);\n        return;\n    }\n    std::copy(randomDoubles.begin(), randomDoubles.end(), mA);\n    std::copy(randomDoubles.begin(), randomDoubles.end(), mB);\n    std::fill(mC, mC + m*n, 0);\n\n    std::cout << \"\\nMKL matrices:\\n\";\n    MKL_DEBUG(mA, m, n);\n    MKL_DEBUG(mB, m, n);\n    MKL_DEBUG(mC, m, n);\n\n    std::cout << \"\\nEigen A + A\\n\";\n    std::cout << eA + eA << '\\n';\n\n    // Arrays A and B cannot overlap\n    std::cout << \"MKL dmatadd C = A + B\\n\";\n    mkl_domatadd('C', 'N', 'N', m, n, 1, mA, m, 1, mB, m, mC, m);\n    MKL_DEBUG(mC, m, n);\n\n    MKL_DEBUG(mA, m, n);\n\n    std::cout << \"MKL daxpy A = A + A\\n\";\n    cblas_daxpy(m*n, 1, mA, 1, mA, 1);\n    MKL_DEBUG(mA, m, n);\n\n    std::cout << \"MKL vdAss B = B + B\\n\";\n    vdAdd(m*n, mB, mB, mB);\n    MKL_DEBUG(mB, m, n);\n\n    // Cleanup\n    mkl_free(mA);\n    mkl_free(mB);\n    mkl_free(mC);\n}\n\nint main()\n{\n//    dgemmTest();\n    maddTest();\n}", "meta": {"hexsha": "a3d6ba37a4346115f29d5b7d8b3a50f8e71a2406", "size": 3215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test.cpp", "max_stars_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_stars_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test.cpp", "max_issues_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_issues_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test.cpp", "max_forks_repo_name": "seriouslyhypersonic/benchmark_eigen_mkl", "max_forks_repo_head_hexsha": "c2dde3a3ce9c51dd428746400de8e8d2802dc6c0", "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.72, "max_line_length": 95, "alphanum_fraction": 0.5810264386, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6724520584401502}}
{"text": "#pragma once\n#ifndef _MATHUTIL_H\n#define _MATHUTIL_H\n\n#include <assert.h>\n\n#include <random>\n#include <limits>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/calib3d.hpp>\n\nnamespace mut\n{\n   const double PI = 3.14159265358979323846;\n   const float PI_F = 3.14159265358979f;\n   const double NaN = std::numeric_limits<double>::quiet_NaN();\n   const double NaN_F = std::numeric_limits<float>::quiet_NaN();\n\n   static Eigen::Quaterniond rotate_between(const Eigen::Vector3d &from, const Eigen::Vector3d &to,\n                                            const Eigen::Vector3d &fallbackAxis = Eigen::Vector3d(0, 0, 0))\n   //-----------------------------------------------------------------------------------------------\n   {\n      Eigen::Quaterniond q;\n      Eigen::Vector3d v0 = from;\n      Eigen::Vector3d v1 = to;\n      v0.normalize();\n      v1.normalize();\n\n      double d = v0.dot(v1);\n      if (d >= 1.0f)\n         return Eigen::Quaterniond(1, 0, 0, 0);\n\n      if (d < (1e-6f - 1.0f))\n      {\n         if (fallbackAxis != Eigen::Vector3d(0, 0, 0))\n            q = Eigen::AngleAxis<double>(PI, fallbackAxis);\n         else\n         {\n            // Generate an axis\n            Eigen::Vector3d axis = Eigen::Vector3d(1, 0, 0).cross(from);\n            if (axis.norm() < 0.000000001) // pick another if colinear\n               axis = Eigen::Vector3d(0, 1, 0).cross(from);\n            axis.normalize();\n            q = Eigen::AngleAxis<double>(PI, axis);\n         }\n      }\n      else\n      {\n         double s = sqrt((1 + d) * 2);\n         double invs = 1 / s;\n\n         Eigen::Vector3d c = v0.cross(v1);\n\n         q.x() = c.x() * invs;\n         q.y() = c.y() * invs;\n         q.z() = c.z() * invs;\n         q.w() = s * 0.5f;\n         q.normalize();\n      }\n      return q;\n   }\n\n   template<typename T> static inline bool near_zero(T v, T epsilon);\n\n   template<> bool near_zero(long double v, long double epsilon) { return (fabsl(v) <= epsilon); }\n\n   template<> bool near_zero(double v, double epsilon) { return (fabs(v) <= epsilon); }\n\n   template<> bool near_zero(float v, float epsilon) { return (fabsf(v) <= epsilon); }\n\n   inline static double radiansToDegrees(double radians) { return (radians * 180.0 / PI); }\n\n   inline static float radiansToDegrees(float radians) { return (radians * 180.0f / PI_F); }\n\n   inline static double degreesToRadians(double degrees) { return (degrees * PI / 180.0); }\n\n   inline static float degreesToRadians(float degrees) { return (degrees * PI_F / 180.0f); }\n\n   template<typename T>\n   inline static void normalize(T &v)\n//-----------------------------------------------\n   {\n      auto magnitude = v.dot(v);\n      if (magnitude > 1.0e-8)\n         v /= sqrt(magnitude);\n   }\n\n   template<typename T>\n   inline static void unchecked_normalize(T &v)\n   { v /= sqrt(v.dot(v)); }\n\n   inline static Eigen::Matrix3d skew33d(Eigen::Vector3d v3)\n  //-----------------------------------------------\n   {\n      double a = v3[0], b = v3[1], c = v3[2];\n      Eigen::Matrix3d X;\n      X << 0, -c, b, c, 0, -a, -b, a, 0;\n      return X;\n   }\n\n   inline static Eigen::Vector3d solve_homogeneous(Eigen::Matrix3d A)\n//---------------------------------------------------------------------------------------------------------------------------\n   {\n//   std::cout << \"Ax = 0:\" << std::endl << A << std::endl;\n      Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::FullPivHouseholderQRPreconditioner>\n            svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      auto U = svd.matrixU();\n      auto V = svd.matrixV();\n//   std::cout << \"U: \" << U << std::endl << \"S: \" << svd.singularValues() << std::endl << \"V: \" << V << std::endl;\n      return V.col(V.cols() - 1);\n   }\n\n\n   inline static Eigen::Vector3d ray(const Eigen::Matrix3d &KI, double x, double y, double z = 1,\n                                                bool is_homogenouous = false, bool is_normalize = false)\n//----------------------------------------------------------------------------------\n   {\n      Eigen::Vector3d v(x, y, z);\n      Eigen::Vector3d ray = KI * v;\n      if (is_homogenouous)\n         ray /= ray[2];\n      if (is_normalize)\n         ray.normalize();\n      return ray;\n   }\n\n   inline static Eigen::Vector3d ray(const Eigen::Matrix3d &KI, Eigen::Vector3d v, bool is_homogenouous = false,\n                                                bool is_normalize = false)\n//--------------------------------------------------------------------------------------------------\n   {\n      Eigen::Vector3d ray = KI * v;\n      if (is_homogenouous)\n         ray /= ray[2];\n      if (is_normalize)\n         ray.normalize();\n      //Eigen::Vector3d p  = KI.inverse()*Eigen::Vector3d(1128,592);\n      return ray;\n   }\n\n   inline static Eigen::Vector3d ray(const Eigen::Matrix3d &KI, cv::Point3d pt, bool is_homogenouous = false,\n                                                bool is_normalize = false)\n   //-----------------------------------------------------------------------------------------------------------------------\n   {\n      Eigen::Vector3d v(pt.x, pt.y, pt.z);\n      Eigen::Vector3d ray = KI * v;\n      if (is_homogenouous)\n         ray /= ray[2];\n      if (is_normalize)\n         ray.normalize();\n      return ray;\n   }\n\n   inline static void yawpitchroll(const Eigen::Vector3d train, const Eigen::Vector3d query,\n                                   double& roll_degrees, double& pitch_degrees, double &yaw_degrees)\n   //----------------------------------------------------------------------------------------\n   {\n      Eigen::Quaterniond Q = rotate_between(query, train);\n      Eigen::Matrix3d R = Q.toRotationMatrix();\n      Eigen::Vector3d euler = R.eulerAngles(0, 1, 2);\n      roll_degrees = radiansToDegrees(euler[0]);\n      pitch_degrees = radiansToDegrees(euler[1]);\n      yaw_degrees = radiansToDegrees(euler[2]);\n\n      std::cout << std::fixed << std::setprecision(8) << train.transpose() << \" -> \"  << query.transpose()\n                << \": Roll \" << mut::radiansToDegrees(euler[0]) << \" Pitch \" << mut::radiansToDegrees(euler[1])\n                << \" Yaw \" << mut::radiansToDegrees(euler[2]) << std::endl << R << std::endl;\n\n      Q.setFromTwoVectors(query, train);\n      R = Q.toRotationMatrix();\n      euler = R.eulerAngles(0, 1, 2);\n      std::cout << std::fixed << std::setprecision(8) << train.transpose() << \" -> \"  << query.transpose()\n                << \": Roll \" << mut::radiansToDegrees(euler[0]) << \" Pitch \" << mut::radiansToDegrees(euler[1])\n                << \" Yaw \" << mut::radiansToDegrees(euler[2]) << std::endl << R << std::endl;\n   }\n\n   static Eigen::Vector3d quaternion_to_euler_angle(Eigen::Quaterniond Q)\n   //--------------------------------------------------------------------\n   {\n      double w = Q.w();\n      double x = Q.x();\n      double y = Q.y();\n      double z = Q.z();\n\n      double ysqr = y * y;\n\n      double t0 = +2.0 * (w * x + y * z);\n      double t1 = +1.0 - 2.0 * (x * x + ysqr);\n      double X = atan2(t0, t1);\n\n      double t2 = +2.0 * (w * y - z * x);\n      t2 = (t2 > +1.0) ? +1.0 : t2;\n      t2 = (t2 < -1.0) ? -1.0 : t2;\n      double Y = asin(t2);\n\n      double t3 = +2.0 * (w * z + x * y);\n      double t4 = +1.0 - 2.0 * (ysqr + z * z);\n      double Z = atan2(t3, t4);\n\n      return Eigen::Vector3d(X, Y, Z);\n   }\n\n   static cv::Vec3f rotation2Euler(cv::Mat &R)\n   //-----------------------------------------\n   {\n      Eigen::Matrix3d ER;\n      cv::cv2eigen(R, ER);\n      Eigen::Vector3d euler = ER.eulerAngles(0, 1, 2);\n      return cv::Vec3f(euler[0], euler[1], euler[2]);\n   }\n\n   static Eigen::Quaterniond euler2Quaternion(const double roll, const double pitch, const double yaw )\n   //-------------------------------------------------------------------------------------------\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      Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\n      return q;\n   }\n\n   static cv::Vec3d ocvMultMatVec(const cv::Mat &P, double x, double y, double z)\n   //---------------------------------------------------------------------------\n   {\n      cv::Mat V(1, 3, CV_64FC1);\n      double *pV = V.ptr<double>(0);\n      pV[0] = x;\n      pV[1] = y;\n      pV[2] = z;\n      cv::Mat R = P * V.t();\n      R = R.t();\n      pV = R.ptr<double>(0);\n      return cv::Vec3d(pV[0], pV[1], pV[2]);\n   }\n\n   static cv::Vec3d ocvMultMatVec(const cv::Mat &P, cv::Vec3d v)\n   //------------------------------------------------------------\n   {\n      cv::Mat V(1, 3, CV_64FC1);\n      double *pV = V.ptr<double>(0);\n      pV[0] = v[0];\n      pV[1] = v[1];\n      pV[2] = v[2];\n      cv::Mat R = P * V.t();\n      R = R.t();\n      pV = R.ptr<double>(0);\n      return cv::Vec3d(pV[0], pV[1], pV[2]);\n   }\n\n   static inline cv::Vec3d toOcvRotationVec(Eigen::Quaterniond Q)\n   //-----------------------------------------------------\n   {\n      Eigen::AngleAxisd aa(Q);\n      Eigen::Vector3d v = aa.angle()*aa.axis();\n/*\n      auto R = Q.toRotationMatrix();\n      cv::Mat OR;\n      cv::eigen2cv(R, OR);\n      cv::Vec3d vv;\n      cv::Rodrigues(OR, vv);\n      std::cout << v.transpose() << \" \" << vv.t() << std::endl;\n*/\n      return cv::Vec3d(v[0], v[1], v[2]);\n   }\n\n   static inline Eigen::Quaterniond toQuaternion(cv::InputArray m)\n   //-----------------------------------------------------\n   {\n      cv::Mat R;\n      cv::Rodrigues(m, R);\n      Eigen::Matrix3d ER;\n      cv::cv2eigen(R, ER);\n      return Eigen::Quaterniond(ER);\n   }\n\n   static void decode_quaternion(const Eigen::Quaterniond qin, Eigen::Vector3d& axis, double& angle)\n   //-------------------------------------------------------------------------------------\n   {\n      Eigen::Quaterniond Q = qin;\n      if (Q.w() > 1)\n         Q.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised\n      angle = 2 * acos(Q.w());\n      double s = sqrt(1 - Q.w()*Q.w()); // assuming quaternion normalised then w is less than 1, so term always positive.\n      if (s >= 0.001)\n      { // test to avoid divide by zero, s is always positive due to sqrt\n         // if s close to zero then direction of axis not important\n         axis[0] = Q.x(); // if it is important that axis is normalised then replace with x=1; y=z=0;\n         axis[1] = Q.y();\n         axis[2] = Q.z();\n      }\n      else\n      {\n         axis[0] = Q.x() / s;\n         axis[1] = Q.y() / s;\n         axis[2] = Q.z() / s;\n         axis.normalize();\n      }\n   }\n\n   static void essential_decompose(const Eigen::Matrix3d& essential_matrix, Eigen::Matrix3d* rotation1,\n                            Eigen::Matrix3d* rotation2, Eigen::Vector3d* translation)\n   //------------------------------------------------------------------------------------------\n   {\n      Eigen::Matrix3d d;\n      d << 0, 1, 0, -1, 0, 0, 0, 0, 1;\n\n      const Eigen::JacobiSVD<Eigen::Matrix3d> svd(\n            essential_matrix, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      Eigen::Matrix3d U = svd.matrixU();\n      Eigen::Matrix3d V = svd.matrixV();\n      if (U.determinant() < 0) {\n         U.col(2) *= -1.0;\n      }\n\n      if (V.determinant() < 0) {\n         V.col(2) *= -1.0;\n      }\n\n      // Possible configurations.\n      *rotation1 = U * d * V.transpose();\n      *rotation2 = U * d.transpose() * V.transpose();\n      *translation = U.col(2).normalized();\n   }\n\n\n   inline double essential_check(const Eigen::Matrix3d R, const double tx, const double ty, const double tz,\n                                 const double xt, const double yt, const double xq,  const double yq)\n   {\n      return  -R(0, 0)*ty*xt - R(0, 1)*ty*yt - R(0, 2)*ty + R(1, 0)*tx*xt + R(1, 1)*tx*yt +\n               R(1, 2)*tx + xq*(-R(1, 0)*tz*xt - R(1, 1)*tz*yt - R(1, 2)*tz + R(2, 0)*ty*xt +\n               R(2, 1)*ty*yt + R(2, 2)*ty) - yq*(-R(0, 0)*tz*xt - R(0, 1)*tz*yt - R(0, 2)*tz +\n               R(2, 0)*tx*xt + R(2, 1)*tx*yt + R(2, 2)*tx);\n   }\n\n   static bool check_essential(Eigen::Matrix3d R, Eigen::Vector3d T, double epsilon =0.0000001)\n   //------------------------------------------------------------------------------------\n   {\n      Eigen::Matrix3d E = skew33d(T)*R;\n//      std::cout << R << std::endl << E << std::endl;\n      if (! near_zero(E.determinant(), epsilon))\n         return false;\n      Eigen::Matrix3d EET = E*E.transpose();\n      Eigen::Matrix3d constraint = 2*EET*E - EET.trace()*E;\n//      std::cout << constraint << std::endl;\n      struct ZeroVisit\n      {\n         double total = 0;\n         void init(const double& value, Eigen::Index i, Eigen::Index j) {}\n         void operator() (const double& value, Eigen::Index i, Eigen::Index j) { total += value; }\n      } visitor;\n      constraint.visit(visitor);\n      if (! near_zero(visitor.total, epsilon))\n         return false;\n\n      Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::FullPivHouseholderQRPreconditioner>\n            svd(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      auto U = svd.matrixU();\n      auto V = svd.matrixV();\n      auto S = svd.singularValues().asDiagonal().toDenseMatrix();\n//      std::cout << \"U: \" << U << std::endl << \"S: \" << S << std::endl << \"V: \" << V << std::endl;\n      if (!near_zero(S(2, 2), epsilon))\n         return false;\n   //   if ( (!near_zero(S(0, 0) - 1, 0.0000001)) || (!near_zero(S(1, 1) - 1, 0.0000001)) )\n   //   {\n   //      S(0, 0) = S(1, 1) = 1.0;\n   //      S(2, 2) = 0.0;\n   //      auto A = U*S*V.transpose();\n   //      std::cout << A << std::endl;\n   //   }\n      return true;\n   }\n\n   // or just R = Eigen::Quaterniond::UnitRandom().toRotationMatrix();\n   static void randomRotationMatrix(std::mt19937* generator, std::uniform_real_distribution<double>* distribution,\n                                    Eigen::Matrix3d& R)\n//-------------------------------------------------------------------------------------------------------------\n   {\n      double x = (*distribution)(*generator);\n      double y = (*distribution)(*generator);\n      double z = (*distribution)(*generator);\n      double theta = std::acos(2*x - 1);\n      double phi = 2*mut::PI*y;\n\n      double r  = sqrt(z);\n      double Vx = sin(phi) * r;\n      double Vy = cos(phi) * r;\n      double Vz = sqrt(2.f - z);\n\n      double st = sin(theta);\n      double ct = cos(theta);\n      double Sx = Vx * ct - Vy * st;\n      double Sy = Vx * st + Vy * ct;\n\n      R(0,0) = Vx * Sx - ct;\n      R(0,1) = Vx * Sy - st;\n      R(0,2) = Vx * Vz;\n      R(1,0) = Vy * Sx + st;\n      R(1,1) = Vy * Sy - ct;\n      R(1,2) = Vy * Vz;\n      R(2,0) = Vz * Sx;\n      R(2,1) = Vz * Sy;\n      R(2,2) = 1.0 - z;\n\n      assert(mut::near_zero(R.determinant() - 1.0, 0.000001));\n   }\n\n   static void random_vector3d_fixed_norm_kludge(const double norm_sqrt, Eigen::Vector3d& v)\n   //-------------------------------------------------------------------------------\n   {\n      std::random_device rand_device;\n      std::mt19937 rand_generator;\n      std::unique_ptr<std::uniform_real_distribution<double>> distribution;\n      std::uniform_int_distribution<int> index_distr(0,2);\n      std::vector<double> pot;\n\n      distribution.reset(new std::uniform_real_distribution<double>(0, norm_sqrt));\n      double one = ((*distribution)(rand_generator));\n      distribution.reset(new std::uniform_real_distribution<double>(0, std::max(norm_sqrt - one, 0.0)));\n      double two = ((*distribution)(rand_generator));\n      double three = std::max(norm_sqrt - one - two, 0.0);\n      pot.clear();\n      pot.push_back(one); pot.push_back(two); pot.push_back(three);\n      int i1 = index_distr(rand_generator), i2 = index_distr(rand_generator), i3;\n      while (i2 == i1) i2 = index_distr(rand_generator);\n      switch (i1)\n      {\n         case 0: if (i2 == 1) i3 = 2; else i3 = 1; break;\n         case 1: if (i2 == 0) i3 = 2; else i3 = 0; break;\n         case 2: if (i2 == 0) i3 = 1; else i3 = 0; break;\n      }\n      v[0] = pot[i1]; v[1] = pot[i2]; v[2] = pot[i3];\n   }\n\n/*\nint essential_best_pose(const Eigen::Matrix3d& essential_matrix,\n                        const std::vector<FeatureCorrespondence>& normalized_correspondences,\n                        Eigen::Matrix3d* rotation, Eigen::Vector3d* position)\n{\n   Eigen::Matrix3d rotation1, rotation2;\n   Eigen::Vector3d translation;\n   essential_decompose(essential_matrix, &rotation1, &rotation2, &translation);\n   const std::vector<Eigen::Matrix3d> rotations = {rotation1, rotation1, rotation2, rotation2};\n   const std::vector<Eigen::Vector3d> positions = {\n         -rotations[0].transpose() * translation,\n         -rotations[1].transpose() * -translation,\n         -rotations[2].transpose() * translation,\n         -rotations[3].transpose() * -translation};\n\n   // From the 4 candidate poses, find the one with the most triangulated points\n   // in front of the camera.\n   std::vector<int> points_in_front_of_cameras(4, 0);\n   for (int i = 0; i < 4; i++) {\n      for (const auto& correspondence : normalized_correspondences) {\n         if (IsTriangulatedPointInFrontOfCameras(\n               correspondence, rotations[i], positions[i])) {\n            ++points_in_front_of_cameras[i];\n         }\n      }\n   }\n\n   // Find the pose with the most points in front of the camera.\n   const auto& max_element = std::max_element(points_in_front_of_cameras.begin(),\n                                              points_in_front_of_cameras.end());\n   const int max_index =\n         std::distance(points_in_front_of_cameras.begin(), max_element);\n\n   // Set the pose.\n   *rotation = rotations[max_index];\n   *position = positions[max_index];\n   return *max_element;\n}\n*/\n}\n#endif\n", "meta": {"hexsha": "60e830ef065fa89dc85064cabceba58b263e2ebb", "size": 17855, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/pose/math.hh", "max_stars_repo_name": "donaldmunro/PlanarTrainer", "max_stars_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T06:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T06:34:11.000Z", "max_issues_repo_path": "src/pose/math.hh", "max_issues_repo_name": "donaldmunro/PlanarTrainer", "max_issues_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose/math.hh", "max_forks_repo_name": "donaldmunro/PlanarTrainer", "max_forks_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_forks_repo_licenses": ["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.966873706, "max_line_length": 125, "alphanum_fraction": 0.5072528703, "num_tokens": 4994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6724450591252418}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include <polyfem/LineQuadrature.hpp>\n#include <polyfem/TriQuadrature.hpp>\n#include <polyfem/TetQuadrature.hpp>\n#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <catch.hpp>\n////////////////////////////////////////////////////////////////////////////////\n\nusing namespace polyfem;\n\nconst double pi = 3.14159265358979323846264338327950288419717;\n\n////////////////////////////////////////////////////////////////////////////////\n\nnamespace {\n\n// double p01_exact() {\n// \treturn pi * pi / 6.0;\n// }\n\n// Eigen::VectorXd p01_fun(const Eigen::MatrixXd &x) {\n// \tEigen::VectorXd f = 1.0 / (1.0 - x.row(0).array() * x.row(1).array());\n// \treturn f;\n// }\n\n// Eigen::AlignedBox2d p01_lim() {\n// \tEigen::AlignedBox2d box;\n// \tbox.min().setConstant(0.0);\n// \tbox.max().setConstant(1.0);\n// \treturn box;\n// }\n\n} // anonymous namespace\n\n////////////////////////////////////////////////////////////////////////////////\n\nTEST_CASE(\"weights\", \"[quadrature]\") {\n\t// Segment\n\tfor (int order = 1; order <= 64; ++order) {\n\t\tLineQuadrature tri;\n\t\tQuadrature quadr;\n\t\ttri.get_quadrature(order, quadr);\n\t\tREQUIRE(quadr.weights.sum() == Approx(1.0).margin(1e-12));\n\t\tREQUIRE(quadr.points.minCoeff() >= 0.0);\n\t\tREQUIRE(quadr.points.maxCoeff() <= 1.0);\n\t}\n\n\t// Triangle\n\tfor (int order = 1; order < 16; ++order) {\n\t\tTriQuadrature tri;\n\t\tQuadrature quadr;\n\t\ttri.get_quadrature(order, quadr);\n\t\tREQUIRE(quadr.weights.sum() == Approx(0.5).margin(1e-12));\n\t\tREQUIRE(quadr.points.minCoeff() >= 0.0);\n\t\tREQUIRE(quadr.points.maxCoeff() <= 1.0);\n\t}\n\n\t// Tetrahedron\n\tfor (int order = 1; order < 16; ++order) {\n\t\tTetQuadrature tri;\n\t\tQuadrature quadr;\n\t\ttri.get_quadrature(order, quadr);\n\t\tREQUIRE(quadr.weights.sum() == Approx(1.0/6.0).margin(1e-12));\n\t\tREQUIRE(quadr.points.minCoeff() >= 0.0);\n\t\tREQUIRE(quadr.points.maxCoeff() <= 1.0);\n\t}\n}\n\n//TEST_CASE(\"triangle\", \"[quadrature]\") {\n//\tfor (int order = 1; order < 10; ++order) {\n//\t\tQuadrature quadr;\n//\t\tTriQuadrature tri;\n//\t\ttri.get_quadrature(order, quadr);\n//\t}\n//\n//\t// REQUIRE(poly_fem::determinant(mat) == Approx(mat.determinant()).margin(1e-12));\n//}\n", "meta": {"hexsha": "c56601371dd3afc5f5882582c37fa39d6189d99b", "size": 2204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_quadrature.cpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "tests/test_quadrature.cpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "tests/test_quadrature.cpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 27.2098765432, "max_line_length": 85, "alphanum_fraction": 0.5589836661, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6724048839755778}}
{"text": "#include <Eigen/Dense>\n#include \"../matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\ntemplate <typename Vector>\nstd::pair<Eigen::MatrixXd, Eigen::MatrixXd> meshgrid(const Vector& x, const Vector& y) {\n  const unsigned m = x.size(), n = y.size();\n  // todo fix type\n  Eigen::MatrixXd X(m, n), Y(m, n);\n  for (unsigned i = 0; i < m; ++i) {\n    for (unsigned j = 0; j < n; ++ j) {\n      X(i, j) = *(x.data() + i);\n      Y(i, j) = *(y.data() + j);\n    }\n  }\n  std::pair<Eigen::MatrixXd, Eigen::MatrixXd> res = std::make_pair(X, Y);\n  return res;\n}\n\nvoid plot_contour() {\n  const unsigned n = 100;\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(n, 0, 1),\n                  y = Eigen::VectorXd::LinSpaced(n, 0, 1);\n  std::pair<Eigen::MatrixXd, Eigen::MatrixXd> XY = meshgrid(x, y);\n  Eigen::MatrixXd Z = XY.first + 2 * XY.second;\n\n  plt::contour(XY.first, XY.second, Z);\n  plt::show();\n\n}\n\nint main() {\n  plot_contour();\n  return 0;\n}\n", "meta": {"hexsha": "f8f3b170a866d954a1f04d4d5ef38ea80ccae450", "size": 931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation_code/src/matplotlib-cpp/examples/contour.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/contour.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/contour.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": 25.8611111111, "max_line_length": 88, "alphanum_fraction": 0.5864661654, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6723682757972255}}
{"text": "#include <cslibs_kdl/residual_vector_kalman.h>\n#include <cslibs_kdl/kdl_conversion.h>\n#include <Eigen/Dense>\nResidualVectorKalman::ResidualVectorKalman():\n    n_(0)\n{\n\n}\n\nvoid ResidualVectorKalman::setDimensions(std::size_t n)\n{\n    n_ = n;\n    eye_ = Eigen::MatrixXd::Identity(n,n);\n}\nvoid ResidualVectorKalman::initialize(std::size_t n, const Eigen::VectorXd& state)\n{\n    state_ = state;\n    n_ = n;\n    eye_ = Eigen::MatrixXd::Identity(n_,n_);\n    cov_ = Eigen::MatrixXd::Identity(n_,n_);\n}\n\nvoid ResidualVectorKalman::initialize(const std::vector<double> &state)\n{\n    cslibs_kdl::convert(state, state_);\n    n_ = state.size();\n    eye_ = Eigen::MatrixXd::Identity(n_,n_);\n    cov_ = Eigen::MatrixXd::Identity(n_,n_);\n}\n\nvoid ResidualVectorKalman::setCovarianceProcess(const Eigen::MatrixXd& Q)\n{\n    cov_state_ = Q;\n}\n\nvoid ResidualVectorKalman::setCovarianceMeasurment(const Eigen::MatrixXd &R)\n{\n    cov_measurment_ = R;\n}\n\nEigen::VectorXd ResidualVectorKalman::update(Eigen::VectorXd& measurement)\n{\n\n    Eigen::MatrixXd cov_pri = cov_ + cov_measurment_;\n\n    Eigen::MatrixXd K = cov_pri * (cov_pri + cov_state_).inverse();\n    state_ += K *(measurement - state_);\n    cov_ = (eye_ - K)*cov_pri;\n\n    return state_;\n\n}\n\nvoid ResidualVectorKalman::update(const std::vector<double>& measurement, std::vector<double>& result)\n{\n    Eigen::VectorXd meas;\n    cslibs_kdl::convert(measurement, meas);\n    Eigen::VectorXd res = update(meas);\n    cslibs_kdl::convert(res, result);\n}\n\nEigen::MatrixXd ResidualVectorKalman::getCovariance() const\n{\n    return cov_;\n}\n", "meta": {"hexsha": "f986f97ec6f483e1f72ac07cdf3c2518fa9a17c8", "size": 1566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cslibs_kdl/src/residual_vector_kalman.cpp", "max_stars_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_stars_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T04:45:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T09:29:11.000Z", "max_issues_repo_path": "cslibs_kdl/src/residual_vector_kalman.cpp", "max_issues_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_issues_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "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": "cslibs_kdl/src/residual_vector_kalman.cpp", "max_forks_repo_name": "cogsys-tuebingen/cslibs_kdl", "max_forks_repo_head_hexsha": "a71ab9a1f6f7b854d17d4fdc0c4d7b01c72bec65", "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.7272727273, "max_line_length": 102, "alphanum_fraction": 0.7043422733, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6723186566609047}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\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// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_RANDOM_NORMAL_DISTRIBUTION_HPP\n#define BOOST_COMPUTE_RANDOM_NORMAL_DISTRIBUTION_HPP\n\n#include <limits>\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/function.hpp>\n#include <boost/compute/types/builtin.hpp>\n#include <boost/compute/type_traits/make_vector_type.hpp>\n\nnamespace boost {\nnamespace compute {\n\n/// \\class normal_distribution\n/// \\brief Produces random, normally-distributed floating-point numbers.\n///\n/// The following example shows how to setup a normal distribution to\n/// produce random \\c float values centered at \\c 5:\n///\n/// \\snippet test/test_normal_distribution.cpp generate\n///\n/// \\see default_random_engine, uniform_real_distribution\ntemplate<class RealType = float>\nclass normal_distribution\n{\npublic:\n    typedef RealType result_type;\n\n    /// Creates a new normal distribution producing numbers with the given\n    /// \\p mean and \\p stddev.\n    normal_distribution(RealType mean = 0.f, RealType stddev = 1.f)\n        : m_mean(mean),\n          m_stddev(stddev)\n    {\n    }\n\n    /// Destroys the normal distribution object.\n    ~normal_distribution()\n    {\n    }\n\n    /// Returns the mean value of the distribution.\n    result_type mean() const\n    {\n        return m_mean;\n    }\n\n    /// Returns the standard-deviation of the distribution.\n    result_type stddev() const\n    {\n        return m_stddev;\n    }\n\n    /// Returns the minimum value of the distribution.\n    result_type min() const\n    {\n        return -std::numeric_limits<RealType>::infinity();\n    }\n\n    /// Returns the maximum value of the distribution.\n    result_type max() const\n    {\n        return std::numeric_limits<RealType>::infinity();\n    }\n\n    /// Generates normally-distributed floating-point numbers and stores\n    /// them to the range [\\p first, \\p last).\n    template<class OutputIterator, class Generator>\n    void generate(OutputIterator first,\n                  OutputIterator last,\n                  Generator &generator,\n                  command_queue &queue)\n    {\n        typedef typename make_vector_type<RealType, 2>::type RealType2;\n\n        size_t count = detail::iterator_range_size(first, last);\n\n        vector<uint_> tmp(count, queue.get_context());\n        generator.generate(tmp.begin(), tmp.end(), queue);\n\n        BOOST_COMPUTE_FUNCTION(RealType2, box_muller, (const uint2_ x),\n        {\n            const RealType x1 = x.x / (RealType) (UINT_MAX - 1);\n            const RealType x2 = x.y / (RealType) (UINT_MAX - 1);\n\n            const RealType z1 = sqrt(-2.f * log2(x1)) * cos(2.f * M_PI_F * x2);\n            const RealType z2 = sqrt(-2.f * log2(x1)) * sin(2.f * M_PI_F * x2);\n\n            return (RealType2)(MEAN, MEAN) + (RealType2)(z1, z2) * (RealType2)(STDDEV, STDDEV);\n        });\n\n        box_muller.define(\"MEAN\", boost::lexical_cast<std::string>(m_mean));\n        box_muller.define(\"STDDEV\", boost::lexical_cast<std::string>(m_stddev));\n        box_muller.define(\"RealType\", type_name<RealType>());\n        box_muller.define(\"RealType2\", type_name<RealType2>());\n\n        transform(\n            make_buffer_iterator<uint2_>(tmp.get_buffer(), 0),\n            make_buffer_iterator<uint2_>(tmp.get_buffer(), count / 2),\n            make_buffer_iterator<RealType2>(first.get_buffer(), 0),\n            box_muller,\n            queue\n        );\n    }\n\nprivate:\n    RealType m_mean;\n    RealType m_stddev;\n};\n\n} // end compute namespace\n} // end boost namespace\n\n#endif // BOOST_COMPUTE_RANDOM_NORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "edf969c57b20c1eee83c74c6ffdf07ddd14a16c0", "size": 3937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/compute/random/normal_distribution.hpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T17:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T17:12:33.000Z", "max_issues_repo_path": "include/boost/compute/random/normal_distribution.hpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/compute/random/normal_distribution.hpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.496, "max_line_length": 95, "alphanum_fraction": 0.633985268, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6723073469530801}}
{"text": "#include <common_robotics_utilities/conversions.hpp>\n\n#include <vector>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace conversions\n{\nEigen::Quaterniond QuaternionFromRPY(const double R,\n                                     const double P,\n                                     const double Y)\n{\n  const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n  const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n  const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n  const Eigen::Quaterniond quat(roll * pitch * yaw);\n  return quat;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Quaterniond QuaternionFromUrdfRPY(const double R,\n                                         const double P,\n                                         const double Y)\n{\n  const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n  const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n  const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n  const Eigen::Quaterniond quat(yaw * pitch * roll);\n  return quat;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromRotationMatrix(\n    const Eigen::Matrix3d& rot_matrix)\n{\n  // Use XYZ angles\n  const Eigen::Vector3d euler_angles = rot_matrix.eulerAngles(0, 1, 2);\n  return euler_angles;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat)\n{\n  return EulerAnglesFromRotationMatrix(quat.toRotationMatrix());\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans)\n{\n  return EulerAnglesFromRotationMatrix(trans.rotation());\n}\n\nEigen::Isometry3d TransformFromXYZRPY(const double x,\n                                      const double y,\n                                      const double z,\n                                      const double roll,\n                                      const double pitch,\n                                      const double yaw)\n{\n  const Eigen::Isometry3d transform\n      = Eigen::Translation3d(x, y, z) * QuaternionFromRPY(roll, pitch, yaw);\n  return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation,\n                                   const Eigen::Vector3d& rotation)\n{\n  const Eigen::Isometry3d transform\n      = static_cast<Eigen::Translation3d>(translation)\n            * QuaternionFromRPY(rotation.x(), rotation.y(), rotation.z());\n  return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components)\n{\n  if (components.size() == 6)\n  {\n    return Eigen::Translation3d(components(0),\n                                components(1),\n                                components(2))\n           * QuaternionFromRPY(components(3),\n                               components(4),\n                               components(5));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"VectorXd source vector is not 6 elements in size\");\n  }\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfXYZRPY(const double x,\n                                          const double y,\n                                          const double z,\n                                          const double roll,\n                                          const double pitch,\n                                          const double yaw)\n{\n  const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z)\n                                      * QuaternionFromUrdfRPY(roll, pitch, yaw);\n  return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::Vector3d& translation,\n                                       const Eigen::Vector3d& rotation)\n{\n  const Eigen::Isometry3d transform\n      = static_cast<Eigen::Translation3d>(translation)\n          * QuaternionFromUrdfRPY(rotation.x(), rotation.y(), rotation.z());\n  return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::VectorXd& components)\n{\n  if (components.size() == 6)\n  {\n    return Eigen::Translation3d(components(0),\n                                components(1),\n                                components(2))\n           * QuaternionFromUrdfRPY(components(3),\n                                   components(4),\n                                   components(5));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"VectorXd source vector is not 6 elements in size\");\n  }\n}\n\nEigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform)\n{\n  Eigen::VectorXd components = Eigen::VectorXd::Zero(6);\n  const Eigen::Vector3d translation = transform.translation();\n  const Eigen::Vector3d rotation\n      = EulerAnglesFromRotationMatrix(transform.rotation());\n  components << translation, rotation;\n  return components;\n}\n\nEigen::Vector3d StdVectorDoubleToEigenVector3d(\n    const std::vector<double>& vector)\n{\n  if (vector.size() == 3)\n  {\n    return Eigen::Vector3d(vector.at(0), vector.at(1), vector.at(2));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"Vector3d source vector is not 3 elements in size\");\n  }\n}\n\nEigen::VectorXd StdVectorDoubleToEigenVectorXd(\n    const std::vector<double>& vector)\n{\n  Eigen::VectorXd eigen_vector(vector.size());\n  for (size_t idx = 0; idx < vector.size(); idx++)\n  {\n    const double val = vector.at(idx);\n    eigen_vector(static_cast<ssize_t>(idx)) = val;\n  }\n  return eigen_vector;\n}\n\nstd::vector<double> EigenVector3dToStdVectorDouble(\n    const Eigen::Vector3d& point)\n{\n  return std::vector<double>{point.x(), point.y(), point.z()};\n}\n\nstd::vector<double> EigenVectorXdToStdVectorDouble(\n    const Eigen::VectorXd& eigen_vector)\n{\n  std::vector<double> vector(static_cast<size_t>(eigen_vector.size()));\n  for (size_t idx = 0; idx < vector.size(); idx++)\n  {\n    const double val = eigen_vector(static_cast<ssize_t>(idx));\n    vector.at(idx) = val;\n  }\n  return vector;\n}\n\n// Takes <x, y, z, w> as is the ROS custom!\nEigen::Quaterniond StdVectorDoubleToEigenQuaterniond(\n    const std::vector<double>& vector)\n{\n  if (vector.size() == 4)\n  {\n    return Eigen::Quaterniond(\n        vector.at(3), vector.at(0), vector.at(1), vector.at(2));\n  }\n  else\n  {\n    throw std::invalid_argument(\n          \"Quaterniond source vector is not 4 elements in size\");\n  }\n}\n\n// Returns <x, y, z, w> as is the ROS custom!\nstd::vector<double> EigenQuaterniondToStdVectorDouble(\n    const Eigen::Quaterniond& quat)\n{\n  return std::vector<double>{quat.x(), quat.y(), quat.z(), quat.w()};\n}\n}  // namespace conversions\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "45776e4f23c38eb0ff5f5354bf15e2b9b9b30a23", "size": 6544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common_robotics_utilities/conversions.cpp", "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": "src/common_robotics_utilities/conversions.cpp", "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": "src/common_robotics_utilities/conversions.cpp", "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": 30.5794392523, "max_line_length": 80, "alphanum_fraction": 0.611094132, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6722180922883615}}
{"text": "#include <fmt/core.h>\n#include <yaml-cpp/yaml.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <boost/math/quadrature/gauss.hpp>\n#include <iostream>\n#include <numeric>\n#include <optional>\n#include <vector>\n\n#include \"NumpySaver.hpp\"\n#include \"bsplines.hpp\"\n\nusing namespace Eigen;\nusing std::cout, std::endl, std::cerr;\n\nconst char* devider = \"##########################################\";\n\ntemplate <int num_points>\ndouble matrix_B_element(int i, int j, std::vector<double>& knots, Index order) {\n  using boost::math::quadrature::gauss;\n\n  if (std::abs((int)i - (int)j) > order) return 0;\n\n  int imax = std::max(i, j);\n  int imin = std::min(i, j);\n\n  Index n = knots.size();\n\n  double sum = 0;\n\n  for (int k = std::max(0, imax - 1); k < std::min(imin + order + 1, n - 1);\n       k++) {\n    auto f = [&](const double& t) {\n      auto [values, idx] = bsplines::bsplines(t, knots, order);\n      return values[i + order - idx] * values[j + order - idx];\n    };\n    sum += gauss<double, num_points>::integrate(f, knots[k], knots[k + 1]);\n  }\n\n  return sum;\n}\n\ntemplate <int num_points>\ndouble matrix_H_element(int i, int j, std::vector<double>& knots, Index order,\n                        int l, int z) {\n  using boost::math::quadrature::gauss;\n  if (std::abs((int)i - (int)j) > order) return 0;\n\n  Index n = knots.size();\n  int imax = std::max(i, j);\n  int imin = std::min(i, j);\n\n  double sum = 0;\n\n  for (int k = std::max(0, imax - 1); k < std::min(imin + order + 1, n - 1);\n       k++) {\n    auto f = [&](const double& t) {\n      auto [values, idx] = bsplines::bsplines(t, knots, order);\n      auto [values_dd, idx_dd] = bsplines::ndx_bsplines(t, knots, order, 2);\n      double h_val =\n          -values_dd[j - (idx - order)] / 2. +\n          (l * (l + 1.) / (t * t * 2.) - z / t) * values[j - (idx - order)];\n      return values[i - (idx - order)] * h_val;\n      ;\n    };\n\n    sum += gauss<double, num_points>::integrate(f, knots[k], knots[k + 1]);\n  }\n  return sum;\n}\n\ntemplate <int num_points>\nMatrixXd matrix_B(std::vector<double>& knots, Index order) {\n  Index n = knots.size();\n  MatrixXd mat(n - 3 + order, n - 3 + order);\n\n  for (int row = 0; row < mat.rows(); row++)\n    for (int col = 0; col < mat.cols(); col++)\n      mat(row, col) = matrix_B_element<num_points>(\n          row - order + 1, col - order + 1, knots, order);\n\n  return mat;\n}\n\ntemplate <int num_points>\nMatrixXd matrix_H(std::vector<double>& knots, Index order, int l, int z) {\n  Index n = knots.size();\n  MatrixXd mat(n - 3 + order, n - 3 + order);\n\n  for (int row = 0; row < mat.rows(); row++)\n    for (int col = 0; col < mat.cols(); col++)\n      mat(row, col) = matrix_H_element<num_points>(\n          row - order + 1, col - order + 1, knots, order, l, z);\n\n  return mat;\n}\n\ndouble evaluate_spline(const double& x, const std::vector<double>& knots,\n                       const VectorXd& weights, std::size_t order) {\n  auto n = knots.size();\n  assert(int(n + order) - 3 == weights.size());\n\n  auto [values, index] = bsplines::bsplines(x, knots, order);\n\n  double sum = 0;\n  for (std::size_t i = std::max(int(index) - 1, 0);\n       i <= std::min(index - 1 + order, n + order - 4); i++)\n    sum += values[i + 1 - index] * weights[i];\n\n  return sum;\n}\n\ntemplate <int order>\nvoid solve(std::vector<double>& knots, std::string& basefilename,\n           std::optional<double> plot_max, int l, int z) {\n  constexpr int gauss_points = order * 1.5;\n  int n_knots = knots.size();\n\n  cout << \"knots = \";\n  for (auto k : knots) cout << k << \", \";\n  cout << endl;\n\n  auto B = matrix_B<gauss_points>(knots, order);\n  auto H = matrix_H<gauss_points>(knots, order, l, z);\n\n  if (knots.size() < 20) {\n    cout << \"B=\\n\" << B << \"\\n\\n\";\n    cout << \"H=\\n\" << H << endl;\n  }\n\n  GeneralizedEigenSolver<MatrixXd> ges;\n  ges.compute(H, B);\n  VectorXcd eigenvalues = ges.eigenvalues();\n  VectorXd real_eigen = eigenvalues.real();\n\n  // sort the eigenvalues (and create an index list)\n  std::vector<int> indices(real_eigen.size());\n  std::iota(indices.begin(), indices.end(), 0);\n\n  std::sort(indices.begin(), indices.end(), [&](int A, int B) -> bool {\n    return real_eigen[A] < real_eigen[B];\n  });\n  std::sort(real_eigen.data(), real_eigen.data() + real_eigen.size());\n\n  if (eigenvalues.imag().cwiseAbs().sum() > 10e-10) {\n    cerr << \"Error: Complex eigenvalues!\" << endl;\n  }\n\n  cout << \"Eigenvalues: \" << real_eigen.transpose() << endl;\n\n  MatrixXd eigenvectors = ges.eigenvectors().real();\n\n  NumpySaver(fmt::format(\"build/output/{}_eigenvalues.npy\", basefilename))\n      << real_eigen;\n  NumpySaver(fmt::format(\"build/output/{}_knots.npy\", basefilename)) << knots;\n\n  NumpySaver eigvec_saver(\n      fmt::format(\"build/output/{}_eigenvectors.npy\", basefilename));\n  for (int col = 0; col < eigenvectors.cols(); col++)\n    eigvec_saver << eigenvectors.col(indices[col]);\n\n  if (auto xmax = plot_max) {\n    ArrayXd x = ArrayXd::LinSpaced(1000, 0, *xmax);\n    MatrixXd points(x.size(), eigenvectors.cols());\n    for (int row = 0; row < x.size(); row++)\n      for (int col = 0; col < points.cols(); col++)\n        points(row, col) = evaluate_spline(\n            x[row], knots, eigenvectors.col(indices[col]), order);\n\n    NumpySaver plot_saver(\n        fmt::format(\"build/output/{}_plot_points.npy\", basefilename));\n    plot_saver << x;\n    for (int col = 0; col < points.cols(); col++) plot_saver << points.col(col);\n  }\n}\n\ntemplate <int order>\nvoid solve_exp(int n_knots, double rmin, double rmax, double exp_fak,\n               std::string& basefilename, std::optional<double> plot, int l,\n               int z) {\n  std::vector<double> knots(n_knots);\n  for (int i = 0; i < n_knots; i++)\n    knots[i] = (rmax - rmin) *\n                   (std::exp(double(i) / double(n_knots - 1) * exp_fak) - 1.) /\n                   (std::exp(exp_fak) - 1) +\n               rmin;\n\n  solve<order>(knots, basefilename, plot, l, z);\n}\n\ntemplate <int order>\nvoid solve_lin(int n_knots, double rmin, double rmax, std::string& basefilename,\n               std::optional<double> plot, int l, int z) {\n  std::vector<double> knots(n_knots);\n  for (int i = 0; i < n_knots; i++)\n    knots[i] = double(i) / double(n_knots - 1) * (rmax - rmin) + rmin;\n\n  solve<order>(knots, basefilename, plot, l, z);\n}\n\nint main() {\n  YAML::Node configs = YAML::LoadFile(\"config.yaml\");\n\n  constexpr int order = 3;\n\n  for (std::size_t i = 0; i < configs.size(); i++) {\n    YAML::Node config = configs[i];\n\n    std::optional<double> plot;\n\n    if (auto p_node = config[\"plot_xmax\"]) {\n      try {\n        auto val = p_node.as<double>();\n        if (val > 0) plot.emplace(val);\n      } catch (const YAML::TypedBadConversion<double>&) {\n        auto boolval = p_node.as<bool>();\n        if (boolval) plot.emplace(10);\n      }\n    }\n\n    auto l = config[\"l\"].as<int>();\n    auto z = config[\"Z\"].as<int>();\n    auto basefilename = config[\"name\"].as<std::string>();\n\n    fmt::print(\"\\n\\n{0}\\n# Simulation '{1}' {2}/{3}\\n{0}\\n\", devider,\n               basefilename, i + 1, configs.size());\n\n    YAML::Node knot_node = config[\"knots\"];\n    auto type = knot_node.Type();\n    // single value\n    if (type == YAML::NodeType::Sequence) {\n      auto knots = knot_node.as<std::vector<double>>();\n      solve<order>(knots, basefilename, plot, l, z);\n    } else if (type == YAML::NodeType::Map) {\n      auto rmin = knot_node[\"rmin\"].as<double>();\n      auto rmax = knot_node[\"rmax\"].as<double>();\n      auto N = knot_node[\"N\"].as<size_t>();\n      auto type = knot_node[\"type\"].as<std::string>();\n      if (type == \"linear\") {\n        solve_lin<order>(N, rmin, rmax, basefilename, plot, l, z);\n      } else if (type == \"exponential\") {\n        auto expfac = knot_node[\"expfac\"].as<double>();\n        solve_exp<order>(N, rmin, rmax, expfac, basefilename, plot, l, z);\n      } else {\n        throw std::runtime_error(\n            \"'type' of knots must either be 'linear' or 'exponential'.\");\n      }\n    } else {\n      throw std::runtime_error(\n          \"Range node must either be list, scalar or a map defining \"\n          \"'type', 'N', 'rmin' and 'rmax'.\");\n    }\n  }\n}", "meta": {"hexsha": "b405b0fea4e3c4b8a9592d201a4db76db35ce876", "size": 8088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project05-BSplinesHAtom/bsplineshatom.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": "Project05-BSplinesHAtom/bsplineshatom.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": "Project05-BSplinesHAtom/bsplineshatom.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.59375, "max_line_length": 80, "alphanum_fraction": 0.5830860534, "num_tokens": 2447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6722180867765062}}
{"text": "/** Test cases for Segment class.\n *\n */\n\n#include \"utils/random.h\"\n\n#ifndef LINK_STATIC\n#define BOOST_TEST_DYN_LINK\n#endif\n#define BOOST_TEST_MODULE RandomTest\n#include <boost/test/unit_test.hpp>\n\n#include <iostream>\n#include <random>\n#include <map>\n#include <string>\n#include <iomanip>\n\nusing namespace utils::random;\nusing namespace std;\n\n\nclass RandomAnalyzer {\npublic:\n    RandomAnalyzer (const std::vector<double>& random_numbers) : \n    m_random_numbers(random_numbers) {\n        analyze();\n    }\n\npublic:\n    double max () { return m_max; }\n    double min () { return m_min; }\n    double mean () { return m_mean; }\n    double std_dev () { return m_std_dev; }\n    size_t N () { return m_N; }\n\n    double distribution_error(double expected_frequency) {\n        std::vector<double> freqs (m_hist.size(), expected_frequency);\n        return distribution_error(freqs);\n    }\n\n    double distribution_error(const std::vector<double>& expected_frequency) {\n        assert (m_hist.size() == expected_frequency.size());\n        double dist_error = 0;\n\n        double span = m_max - m_min;\n        for (int i = 1; i < m_hist.size() - 1; i += 1) {\n            int x = i + m_min;\n            cout << \"freq[\" << i << \"] = \" << m_hist[x] << endl;\n            cout << \"expected_freq[\" << i << \"] = \" << expected_frequency[i] << endl;\n            dist_error += std::abs((m_hist[x] - expected_frequency[i])\n                          / expected_frequency[i]*100);\n        }\n        dist_error /= span;\n        cout << \"Dist error: \" << dist_error << endl;\n\n        return dist_error;\n    }\n\nprivate:\n    void analyze() {\n        m_N = m_random_numbers.size();\n        m_max = utils::stds::max(m_random_numbers);\n        m_min = utils::stds::min(m_random_numbers);\n        m_mean = utils::stds::mean(m_random_numbers);\n        m_std_dev = utils::stds::std_dev(m_random_numbers);\n\n        for (int i = m_min; i <= m_max; i += 1) {\n            m_hist[i] = 0;\n        }\n\n        for (int n = 0; n < m_N; n += 1) {\n            m_hist[std::round(m_random_numbers[n])] += 1;\n        }\n    }\n\nprivate:\n    std::vector<double> m_random_numbers;\n    size_t m_N = 0;\n    double m_min = std::nan(\"NaN\");\n    double m_max = std::nan(\"NaN\");\n    double m_mean = std::nan(\"NaN\");\n    double m_std_dev = std::nan(\"NaN\");\n    std::map<int, int> m_hist;\n};\n\nBOOST_AUTO_TEST_CASE(UniformRandom_generates_uniform_distribution)\n{\n    int N = 1000000;\n    double min = -8, max = 12, span;\n    // While calculating histogram, -8 to -7.5 will be assigned to freq[-8]\n    // similarly, 11.5 to 12 will be assigned to 12. Thus, -8 and 12 will \n    // have half of actual frequency.\n    span = max - min; \n    double expected_freq = N/span;\n\n    UniformRandom rnd_generator (min, max);\n    std::vector<double> random_numbers;\n    random_numbers.reserve(N);\n    for (int i = 0; i < N; i += 1) {\n        random_numbers.push_back(rnd_generator.generate());\n    }\n\n    RandomAnalyzer analyzer (random_numbers);\n    BOOST_CHECK_EQUAL(std::round(analyzer.min()), min);\n    BOOST_CHECK_EQUAL(std::round(analyzer.max()), max);\n    BOOST_CHECK(analyzer.distribution_error(expected_freq) < 1);\n}\n\nBOOST_AUTO_TEST_CASE(Random_returns_a_vector_of_numbers)\n{\n    size_t N = 1000000;\n    double min = -8, max = 12;\n\n    UniformRandom uniform_random (min, max);\n    auto random_numbers = uniform_random.generate(N);\n    RandomAnalyzer analyzer (random_numbers);\n\n    BOOST_REQUIRE_EQUAL(random_numbers.size(), N);\n\n    double expected_average = (max+min)/2;\n    BOOST_CHECK_CLOSE(expected_average, analyzer.mean(), 1);\n}\n\nBOOST_AUTO_TEST_CASE(NormalRandom_generates_random_numbers_with_correct_stddev_and_mean)\n{\n    size_t N = 1000000;\n    double std_dev = 10, mean = 5;\n\n    NormalRandom random (std_dev, mean);\n    auto random_numbers = random.generate(N);\n    RandomAnalyzer analyzer (random_numbers);\n\n    BOOST_REQUIRE_EQUAL(random_numbers.size(), N);\n\n    BOOST_CHECK_CLOSE(mean, analyzer.mean(), 1);\n    BOOST_CHECK_CLOSE(std_dev, analyzer.std_dev(), 1);\n}\n\nBOOST_AUTO_TEST_CASE(NormalRandom_generates_random_numbers_with_correct_min_max)\n{\n    size_t N = 1000000;\n    double std_dev = 10, mean = 0;\n    double min = -10, max = 20;\n\n    NormalRandom random (std_dev, mean, min, max);\n    auto random_numbers = random.generate(N);\n    RandomAnalyzer analyzer (random_numbers);\n\n    BOOST_REQUIRE_EQUAL(random_numbers.size(), N);\n\n    BOOST_CHECK_CLOSE(analyzer.min(), min, 1);\n    BOOST_CHECK_CLOSE(analyzer.max(), max, 1);\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteRandom_generates_uniform_distribution_with_given_weights)\n{\n    int N = 1000000;\n    double min = -8, max = 11, span;\n    span = max - min + 1;\n    double expected_freq = N/span;\n\n    std::vector<double> domain = utils::stds::linspace(min, max, size_t(span));\n    std::vector<double> weights (span, expected_freq);\n\n    DiscreteRandom rnd_generator (domain, weights);\n    std::vector<double> random_numbers = rnd_generator.generate(N);\n\n    RandomAnalyzer analyzer (random_numbers);\n    BOOST_CHECK_EQUAL(std::round(analyzer.min()), min);\n    BOOST_CHECK_EQUAL(std::round(analyzer.max()), max);\n    BOOST_CHECK(analyzer.distribution_error(expected_freq) < 1);\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteRandom_generates_uniform_distribution_with_given_weight_function)\n{\n    struct UniformWeight : public DiscreteRandom::WeightFunction {\n        UniformWeight (double weight) : m_weight(weight) {}\n        double operator () (const double& value) const {\n            return m_weight;\n        }\n\n        double m_weight;\n    };\n\n    int N = 1000000;\n    double min = -8, max = 11, span;\n    span = max - min + 1;\n    double expected_freq = N/span; \n\n    std::vector<double> domain = utils::stds::linspace(min, max, size_t(span));\n\n    DiscreteRandom rnd_generator (domain, UniformWeight(expected_freq));\n    std::vector<double> random_numbers = rnd_generator.generate(N);\n\n    RandomAnalyzer analyzer (random_numbers);\n    BOOST_CHECK_EQUAL(std::round(analyzer.min()), min);\n    BOOST_CHECK_EQUAL(std::round(analyzer.max()), max);\n    BOOST_CHECK(analyzer.distribution_error(expected_freq) < 1);\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteRandom_generates_uniform_distribution_with_given_min_max_count)\n{\n    struct UniformWeight : public DiscreteRandom::WeightFunction {\n        UniformWeight (double weight) : m_weight(weight) {}\n        double operator () (const double& value) const {\n            return m_weight;\n        }\n\n        double m_weight;\n    };\n\n    int N = 1000000;\n    double min = -8, max = 11, span;\n    span = max - min + 1;\n    double expected_freq = N/span;\n\n    DiscreteRandom rnd_generator (min, max, size_t(span), UniformWeight(expected_freq));\n    std::vector<double> random_numbers = rnd_generator.generate(N);\n\n    RandomAnalyzer analyzer (random_numbers);\n    BOOST_CHECK_EQUAL(std::round(analyzer.min()), min);\n    BOOST_CHECK_EQUAL(std::round(analyzer.max()), max);\n    BOOST_CHECK(analyzer.distribution_error(expected_freq) < 1);\n}\n\nBOOST_AUTO_TEST_CASE(DiscreteCosineRandom_generates_cosine_distribution_with_given_min_max_count)\n{\n    int N = 1000000;\n    double min = -pi/2, max = pi/2;\n    size_t count = 100;\n\n    auto domain = utils::stds::linspace(min, max, count);\n    DiscreteCosineRandom rnd_generator (domain);\n    std::vector<double> random_numbers = rnd_generator.generate(N);\n\n    RandomAnalyzer analyzer (random_numbers);\n    BOOST_CHECK_CLOSE(analyzer.min(), min, 5);\n    BOOST_CHECK_CLOSE(analyzer.max(), max, 5);\n    BOOST_CHECK_EQUAL(std::round(analyzer.mean()), 0);\n    //BOOST_CHECK(analyzer.distribution_error(expected_freq) < 1);\n}\n\n", "meta": {"hexsha": "96ad6321b08cd2a55dd6ebe3e4a3b03f4718b05c", "size": 7577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/test_random.cpp", "max_stars_repo_name": "masumhabib/quest", "max_stars_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T20:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T02:08:22.000Z", "max_issues_repo_path": "tests/unit_tests/test_random.cpp", "max_issues_repo_name": "masumhabib/quest", "max_issues_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-10-06T03:00:24.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T06:43:32.000Z", "max_forks_repo_path": "tests/unit_tests/test_random.cpp", "max_forks_repo_name": "masumhabib/quest", "max_forks_repo_head_hexsha": "afef1166b361236144be83f07303a3ec0d5c187c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T04:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-03T04:09:25.000Z", "avg_line_length": 31.0532786885, "max_line_length": 97, "alphanum_fraction": 0.6703180678, "num_tokens": 1869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.672200847718591}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <capnp/message.h>\n#include <capnp/serialize-packed.h>\n#include <Eigen/Dense>\n\n#include \"cereal/gen/cpp/log.capnp.h\"\n\n#include \"locationd_yawrate.h\"\n\n\nvoid Localizer::update_state(const Eigen::Matrix<double, 1, 2> &C, const double R, double current_time, double meas) {\n  double dt = current_time - prev_update_time;\n\n  if (dt < 0) {\n    dt = 0;\n  } else {\n    prev_update_time = current_time;\n  }\n\n  x = A * x;\n  P = A * P * A.transpose() + dt * Q;\n\n  double y = meas - C * x;\n  double S = R + C * P * C.transpose();\n  Eigen::Vector2d K = P * C.transpose() * (1.0 / S);\n  x = x + K * y;\n  P = (I - K * C) * P;\n}\n\nvoid Localizer::handle_sensor_events(capnp::List<cereal::SensorEventData>::Reader sensor_events, double current_time) {\n  for (cereal::SensorEventData::Reader sensor_event : sensor_events){\n    if (sensor_event.getSensor() == 5 && sensor_event.getType() == 16) {\n      sensor_data_time = current_time;\n      double meas = -sensor_event.getGyroUncalibrated().getV()[0];\n      update_state(C_gyro, R_gyro, current_time, meas);\n    }\n  }\n}\n\nvoid Localizer::handle_camera_odometry(cereal::CameraOdometry::Reader camera_odometry, double current_time) {\n  double R = pow(5 * camera_odometry.getRotStd()[2], 2);\n  double meas = camera_odometry.getRot()[2];\n  update_state(C_posenet, R, current_time, meas);\n\n  auto trans = camera_odometry.getTrans();\n  posenet_speed = sqrt(trans[0]*trans[0] + trans[1]*trans[1] + trans[2]*trans[2]);\n  camera_odometry_time = current_time;\n}\n\nvoid Localizer::handle_controls_state(cereal::ControlsState::Reader controls_state, double current_time) {\n  steering_angle = controls_state.getAngleSteers() * DEGREES_TO_RADIANS;\n  car_speed = controls_state.getVEgo();\n  controls_state_time = current_time;\n}\n\n\nLocalizer::Localizer() {\n  // States: [yaw rate, gyro bias]\n  A <<\n    1, 0,\n    0, 1;\n\n  Q <<\n    pow(.1, 2.0), 0,\n    0, pow(0.05/ 100.0, 2.0),\n  P <<\n    pow(10000.0, 2.0), 0,\n    0, pow(10000.0, 2.0);\n\n  I <<\n    1, 0,\n    0, 1;\n\n  C_posenet << 1, 0;\n  C_gyro << 1, 1;\n  x << 0, 0;\n\n  R_gyro = pow(0.025, 2.0);\n}\n\nvoid Localizer::handle_log(cereal::Event::Reader event) {\n  double current_time = event.getLogMonoTime() / 1.0e9;\n\n  // Initialize update_time on first update\n  if (prev_update_time < 0) {\n    prev_update_time = current_time;\n  }\n\n  auto type = event.which();\n  switch(type) {\n  case cereal::Event::CONTROLS_STATE:\n    handle_controls_state(event.getControlsState(), current_time);\n    break;\n  case cereal::Event::CAMERA_ODOMETRY:\n    handle_camera_odometry(event.getCameraOdometry(), current_time);\n    break;\n  case cereal::Event::SENSOR_EVENTS:\n    handle_sensor_events(event.getSensorEvents(), current_time);\n    break;\n  default:\n    break;\n  }\n}\n\n\nextern \"C\" {\n  void *localizer_init(void) {\n    Localizer * localizer = new Localizer;\n    return (void*)localizer;\n  }\n\n  void localizer_handle_log(void * localizer, const unsigned char * data, size_t len) {\n    const kj::ArrayPtr<const capnp::word> view((const capnp::word*)data, len);\n    capnp::FlatArrayMessageReader msg(view);\n    cereal::Event::Reader event = msg.getRoot<cereal::Event>();\n\n    Localizer * loc = (Localizer*) localizer;\n    loc->handle_log(event);\n  }\n\n  double localizer_get_yaw(void * localizer) {\n    Localizer * loc = (Localizer*) localizer;\n    return loc->x[0];\n  }\n  double localizer_get_bias(void * localizer) {\n    Localizer * loc = (Localizer*) localizer;\n    return loc->x[1];\n  }\n\n  double * localizer_get_state(void * localizer) {\n    Localizer * loc = (Localizer*) localizer;\n    return loc->x.data();\n  }\n\n  void localizer_set_state(void * localizer, double * state) {\n    Localizer * loc = (Localizer*) localizer;\n    memcpy(loc->x.data(), state, 4 * sizeof(double));\n  }\n\n  double localizer_get_t(void * localizer) {\n    Localizer * loc = (Localizer*) localizer;\n    return loc->prev_update_time;\n  }\n\n  double * localizer_get_P(void * localizer) {\n    Localizer * loc = (Localizer*) localizer;\n    return loc->P.data();\n  }\n\n  void localizer_set_P(void * localizer, double * P) {\n    Localizer * loc = (Localizer*) localizer;\n    memcpy(loc->P.data(), P, 16 * sizeof(double));\n  }\n}\n", "meta": {"hexsha": "8b25a2a7cf5b3ad9dce0990659ea784fdf41753d", "size": 4189, "ext": "cc", "lang": "C++", "max_stars_repo_path": "selfdrive/locationd/locationd_yawrate.cc", "max_stars_repo_name": "919bot/Tessa", "max_stars_repo_head_hexsha": "9b48ff9020e8fb6992fc78271f2720fd19e01093", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2018-10-06T19:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T13:43:03.000Z", "max_issues_repo_path": "selfdrive/locationd/locationd_yawrate.cc", "max_issues_repo_name": "919bot/Tessa", "max_issues_repo_head_hexsha": "9b48ff9020e8fb6992fc78271f2720fd19e01093", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-12-08T19:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-01T13:54:26.000Z", "max_forks_repo_path": "selfdrive/locationd/locationd_yawrate.cc", "max_forks_repo_name": "919bot/Tessa", "max_forks_repo_head_hexsha": "9b48ff9020e8fb6992fc78271f2720fd19e01093", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 73.0, "max_forks_repo_forks_event_min_datetime": "2018-12-03T19:34:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-27T05:10:23.000Z", "avg_line_length": 26.6815286624, "max_line_length": 119, "alphanum_fraction": 0.6641203151, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.672134764014814}}
{"text": "// Copyright Yamaha 2021\r\n// MIT License\r\n// https://github.com/yamaha-bps/cbr_math/blob/master/LICENSE\r\n\r\n#ifndef CBR_MATH__INTERP__SPLINE_HPP_\r\n#define CBR_MATH__INTERP__SPLINE_HPP_\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <utility>\r\n#include <vector>\r\n#include <array>\r\n\r\n#include \"piecewise_poly.hpp\"\r\n\r\nnamespace cbr\r\n{\r\n\r\nclass Spline\r\n{\r\nprotected:\r\n  using row_t = Eigen::Matrix<double, 1, Eigen::Dynamic>;\r\n  using matrix_t = Eigen::MatrixXd;\r\n\r\npublic:\r\n  /**\r\n   * @brief Create a scalar-valued spline\r\n   *\r\n   * @tparam T1 PiecewisePoly::row_t\r\n   * @tparam T2 PiecewisePoly::matrix_t\r\n   * @param x breakpoints of shape 1xN\r\n   * @param y values of shape DxN where D \\in {1, 2, 3}\r\n   *\r\n   * D=1: y contains values\r\n   * D=2: y contains values, 1st derivatives\r\n   * D=3: y contains values, 1st derivatives, 2nd derivatives\r\n   */\r\n  template<typename T1, typename T2>\r\n  static PiecewisePoly fit(\r\n    T1 && x,\r\n    const Eigen::DenseBase<T2> & y)\r\n  {\r\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\r\n\r\n    if (x.size() < 2) {\r\n      throw std::invalid_argument(\"x be of size > 1\");\r\n    }\r\n\r\n    if (x.size() != y.cols()) {\r\n      throw std::invalid_argument(\"The number of columns of ys must be equal to the size of x.\");\r\n    }\r\n\r\n    if (!(y.rows() > 0 && y.rows() < 4)) {\r\n      throw std::invalid_argument(\"y must have between 1 and 3 rows.\");\r\n    }\r\n\r\n    matrix_t coeffs = generateCoeffs(x, y);\r\n\r\n    if (y.rows() == 1 && x.size() == 3) {\r\n      Eigen::Matrix<double, 1, 2> bp{x[0], x[2]};\r\n      return PiecewisePoly(std::move(bp), std::move(coeffs));\r\n    } else {\r\n      return PiecewisePoly(std::forward<T1>(x), std::move(coeffs));\r\n    }\r\n  }\r\n\r\n  /**\r\n   * @brief Create a vector-valued spline\r\n   *\r\n   * @tparam T1 PiecewisePoly::row_t\r\n   * @tparam T2 container_t<PiecewisePoly::matrix_t>\r\n   * @param x breakpoints of shape 1xN\r\n   * @param y values of shape MxDxN where M is number of value dimensions and D \\in {1, 2, 3}\r\n   *\r\n   * D=1: y[m] contains values for m:th dimension\r\n   * D=2: y[m] contains values, 1st derivatives for m:th dimension\r\n   * D=3: y[m] contains values, 1st, 2nd derivatives for m:th dimension\r\n   */\r\n  template<typename T1, typename T2>\r\n  static PiecewisePolyND fitND(\r\n    T1 && x,\r\n    const T2 & ys)\r\n  {\r\n    static_assert(is_eigen_dense_v<T1>, \"x must be an Eigen::DenseBase object.\");\r\n\r\n    if (x.size() < 2) {\r\n      throw std::invalid_argument(\"x must be of size > 1\");\r\n    }\r\n\r\n    if constexpr (is_eigen_dense_v<T2>) {\r\n      if (ys.rows() < 1) {\r\n        throw std::invalid_argument(\"Number of rows of ys must be > 0.\");\r\n      }\r\n\r\n      if (x.size() != ys.cols()) {\r\n        throw std::invalid_argument(\"The number of columns of ys must be equal to the size of x.\");\r\n      }\r\n\r\n      std::vector<matrix_t> coefLists;\r\n      coefLists.reserve(static_cast<std::size_t>(ys.rows()));\r\n\r\n      for (Eigen::Index i = 0; i < ys.rows(); i++) {\r\n        coefLists.push_back(generateCoeffs(x, ys.row(i)));\r\n      }\r\n\r\n      return PiecewisePolyND(std::forward<T1>(x), std::move(coefLists));\r\n    } else {\r\n      static_assert(\r\n        is_eigen_dense_v<typename T2::value_type>,\r\n        \"ys must be a container of Eigen::DenseBase objects\");\r\n\r\n      if (ys.size() < 1) {\r\n        throw std::invalid_argument(\"Number of elements of ys must be > 0.\");\r\n      }\r\n\r\n      const auto ni = ys[0].rows();\r\n      if (!(ni > 0 && ni < 4)) {\r\n        throw std::invalid_argument(\"Each element of ys must have between 1 and 3 rows.\");\r\n      }\r\n      for (const auto & y : ys) {\r\n        if (y.rows() != ni) {\r\n          throw std::invalid_argument(\r\n                  \"Each element of ys must have the same number of rows.\");\r\n        }\r\n      }\r\n\r\n      std::vector<matrix_t> coefLists;\r\n      coefLists.reserve(ys.size());\r\n      for (const auto & y : ys) {\r\n        coefLists.push_back(generateCoeffs(x, y));\r\n      }\r\n\r\n      if (ni == 1 && x.size() == 3) {\r\n        Eigen::Matrix<double, 1, 2> bp{x[0], x[2]};\r\n        return PiecewisePolyND(std::move(bp), std::move(coefLists));\r\n      } else {\r\n        return PiecewisePolyND(std::forward<T1>(x), std::move(coefLists));\r\n      }\r\n    }\r\n  }\r\n\r\nprotected:\r\n  template<typename T1, typename T2>\r\n  static matrix_t generateCoeffs(\r\n    const Eigen::DenseBase<T1> & x,\r\n    const Eigen::DenseBase<T2> & y)\r\n  {\r\n    if (x.size() != y.cols()) {\r\n      throw std::invalid_argument(\r\n              \"The number of columns of each element of ys must be equal to the size of x.\");\r\n    }\r\n\r\n    matrix_t coeffs;\r\n\r\n    const Eigen::Index nx = x.size();\r\n    const Eigen::Index nj = nx - 1;\r\n    const Eigen::Index ni = y.rows();\r\n\r\n    if (ni == 1) {\r\n      if (nx == 2) {  // If only 2 points, linear interpolation\r\n        coeffs.resize(2, 1);\r\n        coeffs(1, 0) = y(0, 0);\r\n        coeffs(0, 0) = (y(0, 1) - y(0, 0)) / (x[1] - x[0]);\r\n\r\n      } else if (nx == 3) {  // If only 3 points, quadratic interpolation\r\n        coeffs.resize(3, 1);\r\n\r\n        Eigen::Matrix3d A = Eigen::Matrix3d::Zero();\r\n        Eigen::Vector3d b = Eigen::Vector3d::Zero();\r\n\r\n        A(0, 2) = 1.;\r\n\r\n        A(1, 0) = powFast<2>(x[1] - x[0]);\r\n        A(1, 1) = (x[1] - x[0]);\r\n        A(1, 2) = 1.;\r\n\r\n        A(2, 0) = powFast<2>(x[2] - x[0]);\r\n        A(2, 1) = (x[2] - x[0]);\r\n        A(2, 2) = 1.;\r\n\r\n        b[0] = y(0, 0);\r\n        b[1] = y(0, 1);\r\n        b[2] = y(0, 2);\r\n\r\n        Eigen::FullPivLU<Eigen::Matrix3d> dec(A);\r\n        coeffs = dec.solve(b);\r\n\r\n      } else {  // If more than 3 points, piecewise cubic interpolation\r\n        coeffs.resize(4, nj);\r\n        Eigen::MatrixXd A = Eigen::MatrixXd::Zero(4 * nj, 4 * nj);\r\n        Eigen::VectorXd b = Eigen::VectorXd::Zero(4 * nj);\r\n\r\n        // Function continuity\r\n        Eigen::Index i0 = 0;\r\n        for (Eigen::Index i = 0; i < nx - 1; i++) {\r\n          A(2 * i, 4 * i) = powFast<3>(x[i + 1] - x[i]);\r\n          A(2 * i, 4 * i + 1) = powFast<2>(x[i + 1] - x[i]);\r\n          A(2 * i, 4 * i + 2) = (x[i + 1] - x[i]);\r\n          A(2 * i, 4 * i + 3) = 1.;\r\n          A(2 * i + 1, 4 * i + 3) = 1.;\r\n\r\n          b[2 * i] = y(0, i + 1);\r\n          b[2 * i + 1] = y(0, i);\r\n        }\r\n\r\n        // First derivative continuity\r\n        i0 += 2 * (nx - 1);\r\n        for (Eigen::Index i = 0; i < nx - 2; i++) {\r\n          A(i0 + i, 4 * i) = 3. * powFast<2>(x[i + 1] - x[i]);\r\n          A(i0 + i, 4 * i + 1) = 2. * (x[i + 1] - x[i]);\r\n          A(i0 + i, 4 * i + 2) = 1.;\r\n          A(i0 + i, 4 * i + 6) = -1.;\r\n        }\r\n\r\n        // Second derivatives continuity\r\n        i0 += (nx - 2);\r\n        for (Eigen::Index i = 0; i < nx - 2; i++) {\r\n          A(i0 + i, 4 * i) = 6. * (x[i + 1] - x[i]);\r\n          A(i0 + i, 4 * i + 1) = 2.;\r\n          A(i0 + i, 4 * i + 5) = -2.;\r\n        }\r\n\r\n        // Not-a-knot conditions\r\n        i0 += (nx - 2);\r\n        A(i0, 0) = 6.;\r\n        A(i0, 4) = -6.;\r\n        A(i0 + 1, 4 * (nx - 3)) = 6.;\r\n        A(i0 + 1, 4 * (nx - 3) + 4) = -6.;\r\n\r\n        // Solve linear system\r\n        Eigen::FullPivLU<Eigen::MatrixXd> dec(A);\r\n        Eigen::Map<Eigen::VectorXd> coeffsMap(coeffs.data(), 4 * nj);\r\n        coeffsMap = dec.solve(b);\r\n      }\r\n\r\n    } else if (ni == 2) {\r\n      coeffs.resize(4, nj);\r\n      for (Eigen::Index i = 0; i < nj; i++) {\r\n        Eigen::Matrix4d A = Eigen::Matrix4d::Zero();\r\n        Eigen::Vector4d b = Eigen::Vector4d::Zero();\r\n\r\n        // Function continuity\r\n        A(0, 0) = powFast<3>((x[i + 1] - x[i]));\r\n        A(0, 1) = powFast<2>((x[i + 1] - x[i]));\r\n        A(0, 2) = (x[i + 1] - x[i]);\r\n        A(0, 3) = 1.;\r\n        A(1, 3) = 1.;\r\n        b[0] = y(0, i + 1);\r\n        b[1] = y(0, i);\r\n\r\n        // First derivatives continuity\r\n        A(2, 0) = 3. * powFast<2>((x[i + 1] - x[i]));\r\n        A(2, 1) = 2. * (x[i + 1] - x[i]);\r\n        A(2, 2) = 1.;\r\n        A(3, 2) = 1.;\r\n        b[2] = y(1, i + 1);\r\n        b[3] = y(1, i);\r\n\r\n        // Solve linear system\r\n        Eigen::FullPivLU<Eigen::MatrixXd> dec(A);\r\n        coeffs.col(i) = dec.solve(b);\r\n      }\r\n\r\n    } else if (ni == 3) {\r\n      coeffs.resize(6, nj);\r\n      for (Eigen::Index i = 0; i < nj; i++) {\r\n        Eigen::Matrix<double, 6, 6> A = Eigen::Matrix<double, 6, 6>::Zero();\r\n        Eigen::Matrix<double, 6, 1> b = Eigen::Matrix<double, 6, 1>::Zero();\r\n\r\n        // Function continuity\r\n        A(0, 0) = powFast<5>((x[i + 1] - x[i]));\r\n        A(0, 1) = powFast<4>((x[i + 1] - x[i]));\r\n        A(0, 2) = powFast<3>((x[i + 1] - x[i]));\r\n        A(0, 3) = powFast<2>((x[i + 1] - x[i]));\r\n        A(0, 4) = (x[i + 1] - x[i]);\r\n        A(0, 5) = 1.;\r\n        A(1, 5) = 1.;\r\n        b[0] = y(0, i + 1);\r\n        b[1] = y(0, i);\r\n\r\n        // First derivatives continuity\r\n        A(2, 0) = 5. * powFast<4>((x[i + 1] - x[i]));\r\n        A(2, 1) = 4. * powFast<3>((x[i + 1] - x[i]));\r\n        A(2, 2) = 3. * powFast<2>((x[i + 1] - x[i]));\r\n        A(2, 3) = 2. * (x[i + 1] - x[i]);\r\n        A(2, 4) = 1.;\r\n        A(3, 4) = 1.;\r\n        b[2] = y(1, i + 1);\r\n        b[3] = y(1, i);\r\n\r\n        // Second derivatives continuity\r\n        A(4, 0) = 20. * powFast<3>((x[i + 1] - x[i]));\r\n        A(4, 1) = 12. * powFast<2>((x[i + 1] - x[i]));\r\n        A(4, 2) = 6. * (x[i + 1] - x[i]);\r\n        A(4, 3) = 2.;\r\n        A(5, 3) = 2.;\r\n        b[4] = y(2, i + 1);\r\n        b[5] = y(2, i);\r\n\r\n        // Solve linear system\r\n        Eigen::FullPivLU<Eigen::Matrix<double, 6, 6>> dec(A);\r\n        coeffs.col(i) = dec.solve(b);\r\n      }\r\n\r\n    } else {\r\n      throw std::invalid_argument(\"y as an unsupported number of rows. Should never happen!\");\r\n    }\r\n    return coeffs;\r\n  }\r\n};\r\n\r\n}  // namespace cbr\r\n\r\n#endif  // CBR_MATH__INTERP__SPLINE_HPP_\r\n", "meta": {"hexsha": "789e9bc6d923a04be18d71f7556279af2d676477", "size": 9672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_math/interp/spline.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/spline.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/spline.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.7047619048, "max_line_length": 100, "alphanum_fraction": 0.4771505376, "num_tokens": 3327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6721072439013125}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Copyright Paul A. Bristow 2010\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// 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#include <iostream>\r\nusing std::cout; using std::endl;\r\n\r\n// Setting (approximate) precision 25 bits in a single function call using make_policy.\r\n\r\n//[policy_ref_snip11\r\n\r\n#include <boost/math/distributions/normal.hpp>\r\nusing boost::math::normal_distribution;\r\n\r\nusing namespace boost::math::policies;\r\n\r\nconst int bits = 25; // approximate precision.\r\n\r\ndouble q = quantile(\r\n      normal_distribution<double, policy<digits2<bits> > >(), \r\n      0.05); // 5% quantile.\r\n\r\n//] //[/policy_ref_snip11]\r\n\r\nint main()\r\n{\r\n  std::streamsize p = 2 + (bits * 30103UL) / 100000UL; \r\n  // Approximate number of significant decimal digits for 25 bits.\r\n  cout.precision(p); \r\n  cout << bits << \" binary bits is approoximately equivalent to \" << p << \" decimal digits \" << endl;\r\n  cout << \"quantile(normal_distribution<double, policy<digits2<25> > >(), 0.05  = \"\r\n     << q << endl; // -1.64485\r\n}\r\n\r\n/*\r\nOutput:\r\n  25 binary bits is approoximately equivalent to 9 decimal digits \r\n  quantile(normal_distribution<double, policy<digits2<25> > >(), 0.05  = -1.64485363\r\n  */\r\n\r\n", "meta": {"hexsha": "112d2c031a0b0f87a03656bc147022eef1283b5a", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_ref_snip11.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": 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/boost/libs/math/example/policy_ref_snip11.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/policy_ref_snip11.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": 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": 31.9565217391, "max_line_length": 102, "alphanum_fraction": 0.6795918367, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6721072410753268}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_ARITHMETIC_CROSS_PRODUCT_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ARITHMETIC_CROSS_PRODUCT_HPP\n\n\n#include <cstddef>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename P1, typename P2, std::size_t Dimension>\nstruct cross_product\n{\n    // We define cross product only for 2d (see Wolfram) and 3d.\n    // In Math, it is also well-defined for 7-dimension.\n    // Generalisation of cross product to n-dimension is defined as\n    // wedge product but it is not direct analogue to binary cross product.\n};\n\ntemplate <typename P1, typename P2>\nstruct cross_product<P1, P2, 2>\n{\n    typedef P1 return_type;\n\n    static inline return_type apply(P1 const& p1, P2 const& p2)\n    {\n        assert_dimension<P1, 2>();\n        assert_dimension<P2, 2>();\n\n        // For 2-dimensions, analog of the cross product U(x,y) and V(x,y) is\n        // Ux * Vy - Uy * Vx\n        // which is returned as 0-component (or X) of 2d vector, 1-component is undefined.\n        return_type v;\n        set<0>(v, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n        return v;\n    }\n};\n\ntemplate <typename P1, typename P2>\nstruct cross_product<P1, P2, 3>\n{\n    typedef P1 return_type;\n\n    static inline return_type apply(P1 const& p1, P2 const& p2)\n    {\n        assert_dimension<P1, 3>();\n        assert_dimension<P2, 3>();\n\n        return_type v;\n        set<0>(v, get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2));\n        set<1>(v, get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2));\n        set<2>(v, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n        return v;\n    }\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n// TODO: This is a simple draft. If relevant, it can be extended to:\n// - accept vectors of different coordinate_type, but common coordinate_system\n// - if vectors are of mixed 2d and 3d, lower dimension is used\n// - define result_type that will generate type of vector based on:\n// -- select_coordinate_type\n// -- selection of lower dimension\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details Both vectors shall be of the same type.\n         This type also determines type of result vector.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n */\ntemplate <typename P1, typename P2>\ninline P1 cross_product(P1 const& p1, P2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<P1>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<P2>) );\n\n    return detail::cross_product\n        <\n            P1, P2,\n            dimension<P1>::type::value\n        >::apply(p1, p2);\n}\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ARITHMETIC_CROSS_PRODUCT_HPP\n", "meta": {"hexsha": "879ef8a20da7ee714158d22ef94b18dfea0f8cd5", "size": 3331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/arithmetic/cross_product.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/arithmetic/cross_product.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "3party/boost/boost/geometry/extensions/arithmetic/cross_product.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 30.009009009, "max_line_length": 90, "alphanum_fraction": 0.6823776644, "num_tokens": 941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6719937065578773}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/opencv.hpp>\n\n#include \"Utils.h\"\n#include <vector>\n\nusing namespace std;\n\nint main(int argc, char **argv)\n{\n    cv::Mat cv_mat1 = (cv::Mat_<double>(3, 1) << 1, 2, 3), cv_mat2;\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> eigen_mat;\n\n    cv::cv2eigen(cv_mat1, eigen_mat);\n    eigen2cv(eigen_mat, cv_mat2);\n    cout << \"cv mat: \" << cv_mat1.t() << \" --> \"              //\n         << \"eigen mat: \" << eigen_mat.transpose() << \" --> \" //\n         << \"cv mat2: \" << cv_mat2.t()                        //\n         << endl;\n\n    // MatrixXd m = Eigen::Map<MatrixXd>(reinterpret_cast<double*>(a.data),a.rows,a.cols);\n\n    return 0;\n}\n", "meta": {"hexsha": "8d8fa0fa2f4dbcfb318128d48605482b2666e2f1", "size": 736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/cv2eigen.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/cv2eigen.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/cv2eigen.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": 27.2592592593, "max_line_length": 90, "alphanum_fraction": 0.5611413043, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6719936966058605}}
{"text": "#ifndef UTILS_H\n#define UTILS_H\n\n#define _USE_MATH_DEFINES\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n\n// Clamp a to be within lim1 and lim2\ndouble clamp(double a, double lim1, double lim2);\n// Scales input to be between (0 to 1) based on input limits\ndouble scaleFactor(double f, double tl, double tu);\n// Converts a rotation matrix to Euler angles (RzRyRx) convention\nEigen::Vector3d Rotation2Euler(const Eigen::Matrix3d& R);\n// Computes an iterative inverse kinematics solution\n// Eigen::VectorXd IterativeInverseKinematics(std::function<Eigen::VectorXd(const Eigen::VectorXd&)> FK_func, std::function<Eigen::MatrixXd(const Eigen::VectorXd&)> J_FK_func, const Eigen::VectorXd& x_target, const Eigen::VectorXd& theta_init);\n// Computes an iterative inverse kinematics solution with holonomic constraints\n// Eigen::VectorXd IterativeConstrainedInverseKinematics(std::function<Eigen::VectorXd(const Eigen::VectorXd&)> y_func, std::function<Eigen::MatrixXd(const Eigen::VectorXd&)> J_y_func, std::function<Eigen::VectorXd(const Eigen::VectorXd&)> hol_func, std::function<Eigen::MatrixXd(const Eigen::VectorXd&)> J_hol_func, const Eigen::VectorXd& y_target, const Eigen::VectorXd& q_init);\n// Convert from euler angles to rotation matrix using the ZYX convention \nEigen::Matrix3d Euler2Rotation(const Eigen::Vector3d& euler);\n// Convert from angular velocity to euler rates using the ZYX convention \nEigen::Vector3d AngularVelocity2EulerRates(const Eigen::Vector3d& euler, const Eigen::Vector3d& w);\n// Convert from to euler rates to angular velocity using the ZYX convention \nEigen::Vector3d EulerRates2AngularVelocity(const Eigen::Vector3d& euler, const Eigen::Vector3d& euler_rates);\n// Computes skew-symmetric matrix from Vector3d\nEigen::Matrix3d skew(const Eigen::Vector3d& v);\n\n#endif // UTILS_H", "meta": {"hexsha": "29a7c951e4e94662a98a64b58590b7d13d7a27c7", "size": 1837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/utils.hpp", "max_stars_repo_name": "UMich-CURLY/husky_inekf", "max_stars_repo_head_hexsha": "548741a95be190e93a599ed4c5185bacf279abe3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-11-27T20:18:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T05:56:08.000Z", "max_issues_repo_path": "include/utils/utils.hpp", "max_issues_repo_name": "UMich-CURLY/husky_inekf", "max_issues_repo_head_hexsha": "548741a95be190e93a599ed4c5185bacf279abe3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-12-04T10:50:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T18:39:08.000Z", "max_forks_repo_path": "include/utils/utils.hpp", "max_forks_repo_name": "UMich-CURLY/husky_inekf", "max_forks_repo_head_hexsha": "548741a95be190e93a599ed4c5185bacf279abe3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T22:40:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:35:47.000Z", "avg_line_length": 63.3448275862, "max_line_length": 381, "alphanum_fraction": 0.7887860642, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6719936755619611}}
{"text": "/* boost random/beta_distribution.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2014\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id$\r\n */\r\n\r\n#ifndef BOOST_RANDOM_BETA_DISTRIBUTION_HPP\r\n#define BOOST_RANDOM_BETA_DISTRIBUTION_HPP\r\n\r\n#include <cassert>\r\n#include <istream>\r\n#include <iosfwd>\r\n#include <boost/random/detail/operators.hpp>\r\n#include <boost/random/gamma_distribution.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The beta distribution is a real-valued distribution which produces\r\n * values in the range [0, 1].  It has two parameters, alpha and beta.\r\n *\r\n * It has \\f$\\displaystyle p(x) = \\frac{x^{\\alpha-1}(1-x)^{\\beta-1}}{B(\\alpha, \\beta)}\\f$.\r\n */\r\ntemplate<class RealType = double>\r\nclass beta_distribution {\r\npublic:\r\n    typedef RealType result_type;\r\n    typedef RealType input_type;\r\n\r\n    class param_type {\r\n    public:\r\n        typedef beta_distribution distribution_type;\r\n\r\n        /**\r\n         * Constructs a @c param_type from the \"alpha\" and \"beta\" parameters\r\n         * of the distribution.\r\n         *\r\n         * Requires: alpha > 0, beta > 0\r\n         */\r\n        explicit param_type(RealType alpha_arg = RealType(1.0),\r\n                            RealType beta_arg = RealType(1.0))\r\n          : _alpha(alpha_arg), _beta(beta_arg)\r\n        {\r\n            assert(alpha_arg > 0);\r\n            assert(beta_arg > 0);\r\n        }\r\n\r\n        /** Returns the \"alpha\" parameter of the distribtuion. */\r\n        RealType alpha() const { return _alpha; }\r\n        /** Returns the \"beta\" parameter of the distribution. */\r\n        RealType beta() const { return _beta; }\r\n\r\n        /** Writes a @c param_type to a @c std::ostream. */\r\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\r\n        { os << parm._alpha << ' ' << parm._beta; return os; }\r\n\r\n        /** Reads a @c param_type from a @c std::istream. */\r\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\r\n        { is >> parm._alpha >> std::ws >> parm._beta; return is; }\r\n\r\n        /** Returns true if the two sets of parameters are the same. */\r\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\r\n        { return lhs._alpha == rhs._alpha && lhs._beta == rhs._beta; }\r\n        \r\n        /** Returns true if the two sets of parameters are the different. */\r\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\r\n\r\n    private:\r\n        RealType _alpha;\r\n        RealType _beta;\r\n    };\r\n\r\n    /**\r\n     * Constructs an @c beta_distribution from its \"alpha\" and \"beta\" parameters.\r\n     *\r\n     * Requires: alpha > 0, beta > 0\r\n     */\r\n    explicit beta_distribution(RealType alpha_arg = RealType(1.0),\r\n                               RealType beta_arg = RealType(1.0))\r\n      : _alpha(alpha_arg), _beta(beta_arg)\r\n    {\r\n        assert(alpha_arg > 0);\r\n        assert(beta_arg > 0);\r\n    }\r\n    /** Constructs an @c beta_distribution from its parameters. */\r\n    explicit beta_distribution(const param_type& parm)\r\n      : _alpha(parm.alpha()), _beta(parm.beta())\r\n    {}\r\n\r\n    /**\r\n     * Returns a random variate distributed according to the\r\n     * beta distribution.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng) const\r\n    {\r\n        RealType a = gamma_distribution<RealType>(_alpha, RealType(1.0))(urng);\r\n        RealType b = gamma_distribution<RealType>(_beta, RealType(1.0))(urng);\r\n        return a / (a + b);\r\n    }\r\n\r\n    /**\r\n     * Returns a random variate distributed accordint to the beta\r\n     * distribution with parameters specified by @c param.\r\n     */\r\n    template<class URNG>\r\n    RealType operator()(URNG& urng, const param_type& parm) const\r\n    {\r\n        return beta_distribution(parm)(urng);\r\n    }\r\n\r\n    /** Returns the \"alpha\" parameter of the distribution. */\r\n    RealType alpha() const { return _alpha; }\r\n    /** Returns the \"beta\" parameter of the distribution. */\r\n    RealType beta() const { return _beta; }\r\n\r\n    /** Returns the smallest value that the distribution can produce. */\r\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return RealType(0.0); }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\r\n    { return RealType(1.0); }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const { return param_type(_alpha, _beta); }\r\n    /** Sets the parameters of the distribution. */\r\n    void param(const param_type& parm)\r\n    {\r\n        _alpha = parm.alpha();\r\n        _beta = parm.beta();\r\n    }\r\n\r\n    /**\r\n     * Effects: Subsequent uses of the distribution do not depend\r\n     * on values produced by any engine prior to invoking reset.\r\n     */\r\n    void reset() { }\r\n\r\n    /** Writes an @c beta_distribution to a @c std::ostream. */\r\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, beta_distribution, wd)\r\n    {\r\n        os << wd.param();\r\n        return os;\r\n    }\r\n\r\n    /** Reads an @c beta_distribution from a @c std::istream. */\r\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, beta_distribution, wd)\r\n    {\r\n        param_type parm;\r\n        if(is >> parm) {\r\n            wd.param(parm);\r\n        }\r\n        return is;\r\n    }\r\n\r\n    /**\r\n     * Returns true if the two instances of @c beta_distribution will\r\n     * return identical sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(beta_distribution, lhs, rhs)\r\n    { return lhs._alpha == rhs._alpha && lhs._beta == rhs._beta; }\r\n    \r\n    /**\r\n     * Returns true if the two instances of @c beta_distribution will\r\n     * return different sequences of values given equal generators.\r\n     */\r\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(beta_distribution)\r\n\r\nprivate:\r\n    RealType _alpha;\r\n    RealType _beta;\r\n};\r\n\r\n} // namespace random\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_BETA_DISTRIBUTION_HPP\r\n", "meta": {"hexsha": "4480ed7fba47d9319899d99a7311189f1060e0cf", "size": 6084, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/random/beta_distribution.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/random/beta_distribution.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/random/beta_distribution.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 32.8864864865, "max_line_length": 91, "alphanum_fraction": 0.6198224852, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6719648402436733}}
{"text": "#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <cmath>\n#include <cassert>\n#include <chrono>\n#include \"writer.hpp\"\n\nusing namespace std::chrono;\nusing Real= double;\nusing SparseMatrix= Eigen::SparseMatrix<Real>;\nusing Triplet= Eigen::Triplet<Real>;\nusing Vector= Eigen::VectorXd;\n\ntemplate <typename T>\nclass Rho\n{\n    public:\n        Rho(const T x_0, const T y_0, const T dx)\n         : x_0(x_0), y_0(y_0), dx(dx) {}\n        T operator() (const T x, const T y)\n        {   \n           if (!set && abs(x - x_0) < dx / 2 && abs(y - y_0) < dx / 2)\n           {\n               set= true;\n               return (T)1.0 / dx / dx;\n           }\n           else\n           {\n               return (T)0.0;\n           }\n        }\n    private:\n        const T x_0, y_0, dx;\n        bool set{false};\n};\n\nvoid CreatePoissonMatrix(SparseMatrix& A, const int N)\n{\n    A.resize(N * N, N * N); // resize for unrolling RHS vector\n    std::vector<Triplet> triplets; // to build sparse matrix A from\n    triplets.reserve(N * N * 5); // each row of A in general has 5 entries - will be somewhat too large\n    for (int i= 0; i < N * N; i++)\n    {\n        triplets.push_back(Triplet(i, i, 4)); // main diagonal\n        if (i > 0 && i % N != 0)\n            triplets.push_back(Triplet(i, i - 1, -1)); // left off-diagonal: i-1\n        if (i < N * N - 1 && (i + 1) % N != 0 || i == 0) \n            triplets.push_back(Triplet(i, i + 1, -1)); // right off-diagonal: i+1\n        if (i < N * N - N)\n            triplets.push_back(Triplet(i, i + N, -1)); // j+1\n        if (i > N - 1)\n            triplets.push_back(Triplet(i, i - N, -1)); // j-1\n    }\n    A.setFromTriplets(triplets.begin(), triplets.end());\n}\n\ntemplate <class F, typename T>\nvoid CreateRHSVector(Vector& RHS, const int N, const T dx, F& rho)\n{\n    RHS.resize(N * N); // unroll grid into vector\n    \n    auto x= [&dx](T i) {return (i + 1) * dx;};    \n    auto y= [&dx](T j) {return (j + 1) * dx;};    \n\n    const T dx2{dx * dx};\n\n    for (int j= 0; j < N; j++) // row major storage\n        for (int i= 0; i < N; i++)\n            RHS[j * N + i]= dx2 * rho(x(i), y(j));\n}\n\ntemplate <typename T>\nVector SolveJacobi(const SparseMatrix& A, const Vector& RHS, const int N,\n                   const T treshold, const int iterations)\n{\n    Vector x= Vector::Zero((N + 2) * (N + 2));\n    Vector x_0= Vector::Ones(N * N);\n    Vector x_1;\n\n    int i{0};\n    T l2_norm{1.0};\n\n    high_resolution_clock::time_point t_0= high_resolution_clock::now();\n    const SparseMatrix D(A.diagonal().asDiagonal());\n    const SparseMatrix D_inv(D.diagonal().asDiagonal().inverse());\n    const SparseMatrix R= A - D;\n\n    const Vector D_inv_x_RHS= D_inv * RHS; // to speed up calculations during loop\n    const SparseMatrix D_inv_x_R= D_inv * R;\n\n    while (l2_norm > treshold && i++ < iterations)\n    {\n        x_1= D_inv_x_RHS - D_inv_x_R * x_0; // x_1= D_inv * (RHS - R * x_0)\n        l2_norm= (x_1 - x_0).norm();\n        x_0= x_1;\n    }\n    high_resolution_clock::time_point t_1= high_resolution_clock::now();\n    std::cout << \"Jacobi relaxation solver: Success\" \n              << \" after \" << i << \" iterations in \"\n              << duration_cast<milliseconds>(t_1 - t_0).count() <<\" ms\" << std::endl;\n\n    for (int j= 1; j <= N; j++)\n        for (int i= 1; i <= N; i++)\n                x[j * (N + 2) + i]= x_1[(j - 1) * N + (i - 1)];\n    return x;\n}\n\ntemplate <typename T>\nVector SolveGaussSeidel(const SparseMatrix& A, const Vector& RHS, const int N,\n                        const T treshold, const int iterations)\n{\n    Vector x= Vector::Zero((N + 2) * (N + 2));\n    Vector x_0= Vector::Ones(N * N);\n    Vector x_1;\n\n    int i{0};\n    T l2_norm{1.0};\n    \n    high_resolution_clock::time_point t_0= high_resolution_clock::now();\n    const SparseMatrix L= A.triangularView<Eigen::Lower>();\n    const SparseMatrix U= A.triangularView<Eigen::StrictlyUpper>();\n\n    Eigen::SparseLU<SparseMatrix> solver; // to get L^{-1} \n    solver.compute(L);\n    SparseMatrix I(N * N, N * N); I.setIdentity();\n    const SparseMatrix L_inv= solver.solve(I);\n\n    const Vector L_inv_x_RHS= L_inv * RHS; // to speed up calculations during loop\n    const SparseMatrix L_inv_x_U= L_inv * U;\n\n    while (l2_norm > treshold && i++ < iterations)\n    {\n        x_1= L_inv_x_RHS - L_inv_x_U * x_0; // x_1= L_inv * (RHS - U * x_0)\n        l2_norm= (x_1 - x_0).norm();\n        x_0= x_1;\n    }\n    high_resolution_clock::time_point t_1= high_resolution_clock::now();\n    std::cout << \"Gauss-Seidel solver: Success\" \n              << \" after \" << i << \" iterations in \" \n              << duration_cast<milliseconds>(t_1 - t_0).count() <<\" ms\" << std::endl;\n\n    for (int j= 1; j <= N; j++)\n        for (int i= 1; i <= N; i++)\n                x[j * (N + 2) + i]= x_1[(j - 1) * N + (i - 1)];\n    return x;\n}\n\ntemplate <typename T>\nVector SolveConjugateGradient(const SparseMatrix& A, const Vector& RHS, const int N,\n                              const T treshold, const int iterations, const bool use_jacobi_precond=false)\n{\n    Vector x= Vector::Zero((N + 2) * (N + 2)); // to hold final solution w/ boundary conditions\n    Vector x_= Vector::Zero(N * N); // for iterative calculations\n    SparseMatrix M_inv= SparseMatrix(N * N, N * N); M_inv.setIdentity(); // no preconditioner\n    if (use_jacobi_precond)\n        M_inv= A.diagonal().asDiagonal().inverse(); // Jacobi preconditioner\n    Vector r_0, r_1; // residuals r\n    Vector p, Ap; // \"direction vectors\" p\n    Vector z_0, z_1; // preconditioned residuals z\n    T alpha, beta; // Richardson iteration scaling parameters\n\n    int i{0};\n\n    high_resolution_clock::time_point t_0= high_resolution_clock::now();\n    r_0= RHS - A * x_;\n    z_0= M_inv * r_0;\n    p= z_0;\n\n    for ( ; i++ < iterations; )\n    {  \n        Ap= A * p;\n        alpha= r_0.dot(z_0) / p.dot(Ap);\n        x_= x_ + alpha * p;\n        r_1= r_0 - alpha * Ap;\n        if (r_1.norm() < treshold) break; // convergence test\n        z_1= M_inv * r_1;\n        beta= z_1.dot(r_1) / z_0.dot(r_0);\n        p= z_1 + beta * p;\n        r_0= r_1;\n        z_0= z_1;\n    }\n\n    high_resolution_clock::time_point t_1= high_resolution_clock::now();\n    std::cout << ((use_jacobi_precond == false) ? \"Conjugate gradient solver: Success\"\n                                                : \"Conjugate gradient solver w/ Jacobi preconditioner: Success\" )\n              << \" after \" << i << \" iterations in \" \n              << duration_cast<milliseconds>(t_1 - t_0).count() <<\" ms\" << std::endl;\n\n    for (int j= 1; j <= N; j++)\n        for (int i= 1; i <= N; i++)\n                x[j * (N + 2) + i]= x_[(j - 1) * N + (i - 1)];\n    return x; \n}\n\nVector SolveEigenCG(const SparseMatrix& A, const Vector& RHS, const int N)\n{\n    Vector x= Vector::Zero((N + 2) * (N + 2)); // to fill with solution\n    \n    high_resolution_clock::time_point t_0= high_resolution_clock::now();\n    Eigen::ConjugateGradient<SparseMatrix, Eigen::Lower|Eigen::Upper> solver;\n    solver.compute(A);\n    assert (solver.info() == Eigen::Success);\n    Vector x_inner= solver.solve(RHS); // solve inner grid\n    high_resolution_clock::time_point t_1= high_resolution_clock::now();\n    std::cout << \"Eigen CG solver: Success in \"\n              << duration_cast<milliseconds>(t_1 - t_0).count() <<\" ms\" << std::endl;\n    for (int j= 1; j <= N; j++)\n        for (int i= 1; i <= N; i++)\n                x[j * (N + 2) + i]= x_inner[(j - 1) * N + (i - 1)];\n    return x;\n}\n\nVector SolveCholesky(const SparseMatrix& A, const Vector& RHS, const int N)\n{\n    Vector x= Vector::Zero((N + 2) * (N + 2)); // to fill with solution\n    \n    high_resolution_clock::time_point t_0= high_resolution_clock::now();\n    Eigen::SparseLU<SparseMatrix> solver;\n    solver.compute(A);\n    assert (solver.info() == Eigen::Success);\n    Vector x_inner= solver.solve(RHS); // solve inner grid\n    high_resolution_clock::time_point t_1= high_resolution_clock::now();\n    std::cout << \"Eigen Cholesky solver: Success in \"\n              << duration_cast<milliseconds>(t_1 - t_0).count() <<\" ms\" << std::endl;\n    for (int j= 1; j <= N; j++)\n        for (int i= 1; i <= N; i++)\n                x[j * (N + 2) + i]= x_inner[(j - 1) * N + (i - 1)];\n    return x;\n}\n\nint main(int argc, char* argv[])\n{\n     if (argc < 4 || argc > 4 || argv[1] == \"-h\") // check cl args and give some help\n    {  \n        std::cerr << \"Usage: \" << argv[0] << \"\\n\\t\"\n                  << \" N(int): grid parameter: number of points per axis\" << \"\\n\\t\"\n                  << \" x_0(Real): x coord of point charge in 0..1\" << \"\\n\\t\"\n                  << \" y_0(Real): y coord of point charge in 0..1\" << \"\\n\\t\"\n                  << std::endl << std::endl;\n        return 1;\n    }\n\n    const int N{atoi(argv[1])};\n    const Real dx{(Real)1.0 / (Real)(N + 1)};\n    const Real x_0{atof(argv[2])}, y_0{atof(argv[3])};\n\n    const Real treshold{0.0001};\n    const int iterations{10000};\n\n    SparseMatrix A;\n    Vector RHS;\n    Vector RHS2;\n    Rho rho{x_0, y_0, dx};\n    Rho rho2{1.0 - x_0, 1.0 - y_0, dx};\n    CreatePoissonMatrix(A, N);\n    CreateRHSVector(RHS, N, dx, rho);\n    CreateRHSVector(RHS2, N, dx, rho2);\n    RHS = (RHS + RHS2) / 2;\n    Vector x_cholesky= SolveCholesky(A, RHS, N);\n    Vector x_eigen_cg= SolveEigenCG(A, RHS, N);\n    // Vector x_jacobi= SolveJacobi(A, RHS, N, treshold, iterations);\n    // Vector x_gauss_seidel= SolveGaussSeidel(A, RHS, N, treshold, iterations);\n    Vector x_conjugate_gradient= SolveConjugateGradient(A, RHS, N, treshold, iterations);\n    Vector x_conjugate_gradient_precon= SolveConjugateGradient(A, RHS, N, treshold, iterations, true); \n    // std::cout << \"L2 difference Cholesky - Jacobi: \" << (x_cholesky - x_jacobi).norm() << std::endl\n            //   << \"L2 difference Cholseky - Gauss-Seidel: \" << (x_cholesky - x_jacobi).norm() << std::endl;\n    std::cout << \"L2 difference Cholesky - Conjugate Gradient: \" << (x_cholesky - x_conjugate_gradient).norm() << std::endl;\n    std::cout << \"L2 difference Eigen CG - Conjugate Gradient: \" << (x_eigen_cg - x_conjugate_gradient).norm() << std::endl;\n    std::cout << \"L2 difference Eigen CG - Conjugate Gradient Precon: \" << (x_eigen_cg - x_conjugate_gradient_precon).norm() << std::endl;\n    writeToFile(\"x_cholesky.txt\", x_cholesky);\n    writeToFile(\"x_eigen_cg.txt\", x_eigen_cg);\n    // writeToFile(\"x_jacobi.txt\", x_jacobi);\n    // writeToFile(\"x_gauss_seidel.txt\", x_gauss_seidel);\n    writeToFile(\"x_conjugate_gradient.txt\", x_conjugate_gradient);\n    writeToFile(\"x_conjugate_gradient_precon.txt\", x_conjugate_gradient_precon);\n    // writeToFile(\"x_diff_chol_jaco.txt\", (x_cholesky - x_jacobi));\n    // writeToFile(\"x_diff_chol_gaus.txt\", (x_cholesky - x_gauss_seidel));\n    writeToFile(\"x_diff_chol_conj.txt\", (x_cholesky - x_conjugate_gradient));\n    return 0;\n}", "meta": {"hexsha": "4b1f08fd911d41961650ba751a429dbee4dc25e3", "size": 10815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ex12/main.cpp", "max_stars_repo_name": "BeatHubmann/18H-ICP", "max_stars_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ex12/main.cpp", "max_issues_repo_name": "BeatHubmann/18H-ICP", "max_issues_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex12/main.cpp", "max_forks_repo_name": "BeatHubmann/18H-ICP", "max_forks_repo_head_hexsha": "2ad1bcef73f3f43d832031cf45c4909341176ebd", "max_forks_repo_licenses": ["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.3510638298, "max_line_length": 138, "alphanum_fraction": 0.5783633842, "num_tokens": 3421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.671964821353542}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include <boost/array.hpp>\n#include <vector>\n\nusing namespace boost::numeric::odeint;\n\n/* The type of container used to hold the state vector */\ntypedef boost::array<double, 3> state_type;\n\nvoid lorenz(const state_type &x, state_type &dxdt, const double t)\n{\n    double sigma = 10.0;\n    double R = 28.0;\n    double b = 8.0 / 3.0;\n\n    dxdt[0] = sigma * (x[1] - x[0]);\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\n// An example of observer to record steps in the integration\nstruct boost_array_observer\n{\n    std::vector<state_type> &m_states;\n    std::vector<double> &m_times;\n\n    boost_array_observer(std::vector<state_type> &states, std::vector<double> &times)\n        : m_states(states), m_times(times) {}\n\n    void operator()(const state_type &x, double t)\n    {\n        m_states.push_back(x);\n        m_times.push_back(t);\n    }\n};\n\nint main()\n{\n    // this time, let the num of steps be known\n    const auto n_steps = 1000;\n\n    // System state initialization with initial condition\n    state_type x = {0.0, 1.0, 0.1};\n\n    // Containers to store solution\n    std::vector<state_type> x_sol;\n    std::vector<double> times;\n\n    // Set stepper\n    runge_kutta4<state_type> rk4;\n\n    // Integrate over time\n    auto t_init = 0.0;\n    auto t_final = 10.0;\n    auto dt = 0.001;\n    auto steps = integrate_const(\n        rk4,\n        lorenz,\n        x,\n        t_init,\n        t_final,\n        dt,\n        boost_array_observer(x_sol, times));\n\n    // Displaying result on terminal\n    for (size_t i = 0; i <= steps; i++)\n    {\n        std::cout << times[i] << '\\t' << x_sol[i][0] << '\\t' << x_sol[i][1] << '\\t' << x_sol[i][2] << '\\n';\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "959e5ddf2aa40428bb082aec00ac130c1cfb2660", "size": 1738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/standalones/lorenz_example.cpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "examples/boost/standalones/lorenz_example.cpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "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/boost/standalones/lorenz_example.cpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 23.8082191781, "max_line_length": 107, "alphanum_fraction": 0.5897583429, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6719279741493285}}
{"text": "/*\n * neonGX - Transformations.hpp\n *\n * Copyright (c) 2016, cynecx\n *\n * This file is part of neonGX and is distributed under a modified\n * BSD 3-Clause License. See LICENSE.txt for details.\n *\n */\n\n#ifndef NEONGX_TRANSFORMATIONS_H\n#define NEONGX_TRANSFORMATIONS_H\n\n#include <cmath>\n#include <neonGX/Core/Math/Primitives.hpp>\n#include <neonGX/Core/Math/Matrix.hpp>\n#include <boost/math/constants/constants.hpp>\n\n//#define USE_CONSTANT_CACHING\n\nnamespace neonGX {\n\n  enum class ConstantCacheType {\n    sin,\n    cos,\n    tan\n  };\n\n  float ConstantCache(ConstantCacheType type, float val);\n\n  template <typename T>\n  static constexpr T PI = boost::math::constants::pi<T>();\n\n  inline constexpr float DegreeToRadian(float degree) {\n    return degree * PI<float> / 180.0f;\n  }\n\n  inline constexpr float RadianToDegree(float radian) {\n    return radian * 180.0f / PI<float>;\n  }\n\n  inline constexpr Matrix3 GetTranslationMatrix(float tx, float ty) {\n    return {\n        1.0f, 0.0f, tx,\n        0.0f, 1.0f, ty,\n        0.0f, 0.0f, 1.0f\n    };\n  }\n\n  inline constexpr Matrix3 GetTranslationMatrix(const FPoint& point) {\n    return GetTranslationMatrix(point.x, point.y);\n  }\n\n  inline constexpr Matrix3 GetScalingMatrix(float sx, float sy) {\n    return {\n        sx, 0.0f, 0.0f,\n        0.0f, sy, 0.0f,\n        0.0f, 0.0f, 1.0f\n    };\n  }\n\n  inline constexpr Matrix3 GetScalingMatrix(const FPoint& point) {\n    return GetScalingMatrix(point.x, point.y);\n  }\n\n  inline Matrix3 GetRotationMatrix(float q) {\n#ifdef USE_CONSTANT_CACHING\n    float qsin = ConstantCache(ConstantCacheType::sin, q);\n    float qcos = ConstantCache(ConstantCacheType::cos, q);\n#else\n    float qsin = sin(q);\n    float qcos = cos(q);\n#endif\n\n    return {\n        qcos, -qsin, 0.0f,\n        qsin, qcos, 0.0f,\n        0.0f, 0.0f, 1.0f\n    };\n  }\n\n  inline Matrix3 GetSkewingMatrix(float x, float y) {\n#ifdef USE_CONSTANT_CACHING\n    float xtan = ConstantCache(ConstantCacheType::tan, x);\n    float ytan = ConstantCache(ConstantCacheType::tan, y);\n#else\n    float xtan = tan(x);\n    float ytan = tan(y);\n#endif\n\n    return {\n        1.0f, xtan, 0.0f,\n        ytan, 1.0f, 0.0f,\n        0.0f, 0.0f, 1.0f\n    };\n  }\n\n  inline Matrix3 GetSkewingMatrix(const FPoint& point) {\n    return GetSkewingMatrix(point.x, point.y);\n  }\n\n  inline constexpr Matrix3 GetIdentityTransform() {\n    return {\n        1.0f, 0.0f, 0.0f,\n        0.0f, 1.0f, 0.0f,\n        0.0f, 0.0f, 1.0f\n    };\n  }\n\n  inline Matrix3 GetToClipspaceTransform(const FSize& destFrame,\n                                         const FPoint& sourcePoint,\n                                         bool swapHeightSign) {\n    // (Position / Resolution) * 2 - 1\n    auto toClipspace = Matrix3{\n        2.0f / destFrame.width, 0.0f, -1.0f,\n        0.0f, (swapHeightSign ? -2.0f : 2.0f) / destFrame.height,\n          (swapHeightSign ? 1.0f : -1.0f),\n        0.0f, 0.0f, 1.0f\n    };\n\n    return toClipspace * GetTranslationMatrix(-sourcePoint.x, -sourcePoint.y);\n  }\n\n} // end namespace neonGX\n\n#endif // !NEONGX_TRANSFORMATIONS_H\n", "meta": {"hexsha": "fd02e2acbef753c42514898a8e7970483716b640", "size": 3043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/neonGX/Core/Math/Transformation.hpp", "max_stars_repo_name": "cynecx/neonGX", "max_stars_repo_head_hexsha": "6bf90ba01dbb15320ccfdecb49db4d4093c6d394", "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/neonGX/Core/Math/Transformation.hpp", "max_issues_repo_name": "cynecx/neonGX", "max_issues_repo_head_hexsha": "6bf90ba01dbb15320ccfdecb49db4d4093c6d394", "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/neonGX/Core/Math/Transformation.hpp", "max_forks_repo_name": "cynecx/neonGX", "max_forks_repo_head_hexsha": "6bf90ba01dbb15320ccfdecb49db4d4093c6d394", "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.9606299213, "max_line_length": 78, "alphanum_fraction": 0.6276700624, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475746920261, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6718824920950855}}
{"text": "#ifndef RADIUMENGINE_VECTOR_HPP\n#define RADIUMENGINE_VECTOR_HPP\n\n/// This file contains typedefs and basic vector classes and functions\n\n#include <Core/RaCore.hpp>\n\n#include <functional>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/AlignedVector3>\n\n#include <Core/Math/Math.hpp>\n\n// General config\n// Use this to force vec3 to be aligned for vectorization (FIXME not working yet)\n// #define CORE_USE_ALIGNED_VEC3\n\nnamespace Ra\n{\n    namespace Core\n    {\n        //\n        // Common vector types\n        //\n        typedef Eigen::Matrix< Scalar, Eigen::Dynamic, 1 > VectorN;\n        typedef Eigen::VectorXf                            VectorNf;\n        typedef Eigen::VectorXd                            VectorNd;\n\n        typedef Eigen::Matrix<Scalar, 4, 1> Vector4;\n        typedef Eigen::Vector4f             Vector4f;\n        typedef Eigen::Vector4d             Vector4d;\n\n#ifndef CORE_USE_ALIGNED_VEC3\n        typedef Eigen::Matrix<Scalar, 3, 1> Vector3;\n        typedef Eigen::Vector3f             Vector3f;\n        typedef Eigen::Vector3d             Vector3d;\n#else\n        typedef Eigen::AlignedVector3<Scalar> Vector3;\n        typedef Eigen::AlignedVector3<float> Vector3f;\n        typedef Eigen::AlignedVector3<double> Vector3d;\n#endif\n\n        typedef Eigen::Matrix<Scalar, 2, 1> Vector2;\n        typedef Eigen::Vector2f             Vector2f;\n        typedef Eigen::Vector2d             Vector2d;\n\n        typedef Eigen::VectorXi VectorNi;\n        typedef Eigen::Vector2i Vector2i;\n        typedef Eigen::Vector3i Vector3i;\n        typedef Eigen::Vector4i Vector4i;\n\n\n        typedef Eigen::Matrix<uint, Eigen::Dynamic, 1> VectorNui;\n        typedef Eigen::Matrix<uint, 2, 1>              Vector2ui;\n        typedef Eigen::Matrix<uint, 3, 1>              Vector3ui;\n        typedef Eigen::Matrix<uint, 4, 1>              Vector4ui;\n\n        //\n        // Common matrix types\n        //\n\n        typedef Eigen::Matrix< Scalar, Eigen::Dynamic, Eigen::Dynamic > MatrixN;\n        typedef Eigen::Matrix<Scalar, 4, 4> Matrix4;\n        typedef Eigen::Matrix<Scalar, 3, 3> Matrix3;\n        typedef Eigen::Matrix<Scalar, 2, 2> Matrix2;\n\n        typedef Eigen::MatrixXf MatrixNf;\n        typedef Eigen::Matrix4f Matrix4f;\n        typedef Eigen::Matrix3f Matrix3f;\n        typedef Eigen::Matrix2f Matrix2f;\n\n        typedef Eigen::MatrixXd MatrixNd;\n        typedef Eigen::Matrix4d Matrix4d;\n        typedef Eigen::Matrix3d Matrix3d;\n        typedef Eigen::Matrix2d Matrix2d;\n\n        typedef Eigen::Matrix< uint, Eigen::Dynamic, Eigen::Dynamic > MatrixNui;\n\n        //typedef Eigen::DiagonalMatrix< Scalar, Eigen::Dynamic > Diagonal;\n        typedef Eigen::SparseMatrix< Scalar > Diagonal; // Not optimized for Diagonal matrices, but the operations between Sparse and Diagonal are not defined\n        typedef Eigen::SparseMatrix< Scalar > Sparse;\n\n        //\n        // Transforms and rotations\n        //\n\n        typedef Eigen::Quaternion<Scalar> Quaternion;\n        typedef Eigen::Quaternionf        Quaternionf;\n        typedef Eigen::Quaterniond        Quaterniond;\n\n        typedef Eigen::Transform<Scalar, 3, Eigen::Affine> Transform;\n        typedef Eigen::Affine3f                            Transformf;\n        typedef Eigen::Affine3d                            Transformd;\n\n        typedef Eigen::AlignedBox<Scalar, 3> Aabb;\n        typedef Eigen::AlignedBox3f          Aabbf;\n        typedef Eigen::AlignedBox3d          Aabbd;\n\n        typedef Eigen::AngleAxis<Scalar> AngleAxis;\n        typedef Eigen::AngleAxisf        AngleAxisf;\n        typedef Eigen::AngleAxisd        AngleAxisd;\n\n        typedef Eigen::Translation<Scalar, 3> Translation;\n        typedef Eigen::Translation3f         Translationf;\n        typedef Eigen::Translation3d         Translationd;\n\n        inline void print( const MatrixN& matrix );\n\n        //\n        // Geometry types\n        //\n\n        typedef Eigen::ParametrizedLine< Scalar, 2 > Line2;\n        typedef Eigen::ParametrizedLine< Scalar, 3 > Line3;\n        typedef Eigen::Hyperplane< Scalar, 3 >       Plane3;\n\n        // Todo : storage transform using quaternions ?\n\n        //\n        // Misc types\n        //\n        typedef Vector4  Color;\n        typedef Vector4f Colorf;\n        typedef Vector4d Colord;\n\n        //\n        // Vector Functions\n        //\n        namespace Vector\n        {\n\n            /// Component-wise floor() function on a floating-point vector.\n            template<typename Vector>\n            inline Vector floor( const Vector& v );\n\n            /// Component-wise ceil() function on a floating-point vector.\n            template<typename Vector>\n            inline Vector ceil( const Vector& v );\n\n            /// Component-wise trunc() function on a floating-point vector\n            template<typename Vector>\n            inline Vector trunc( const Vector& v );\n\n            /// Component-wise clamp() function on a floating-point vector.\n            template<typename Vector>\n            inline Vector clamp( const Vector& v, const Vector& min, const Vector& max );\n\n            /// Component-wise clamp() function on a floating-point vector.\n            template<typename Vector>\n            inline Vector clamp( const Vector& v, const Scalar& min, const Scalar& max );\n\n            /// Vector range check, works for any numeric vector.\n            template<typename Vector_>\n            inline bool checkRange( const Vector_& v, const Scalar& min, const Scalar& max );\n\n            /// Call std::isnormal on vector entries.\n            template< typename Vector_ >\n            inline bool checkInvalidNumbers(Eigen::Ref<const Vector_> v,\n                                             const bool FAIL_ON_ASSERT = false);\n\n            /// Get two vectors orthogonal to a given vector.\n            inline void getOrthogonalVectors( const Vector3& fx, Eigen::Ref<Vector3> fy, Eigen::Ref<Vector3> fz );\n\n            /// Get the angle between two vectors. Works for types where the cross product is\n            /// defined (i.e. 2D and 3D vectors).\n            template<typename Vector_>\n            inline Scalar angle( const Vector_& v1, const Vector_& v2 );\n\n            /// Get the spherical linear interpolation between two unit non-colinear vectors.\n            /// works for types where the cross-product is defined (i.e. 2D and 3D vectors).\n            template<typename Vector_>\n            inline Vector_ slerp( const Vector_& v1, const Vector_& v2, Scalar t );\n\n            /// @return the projection of point on the plane define by plane and planeNormal\n            inline Vector3 projectOnPlane(const Vector3& planePos, const Vector3& planeNormal, const Vector3& point);\n\n            /// Get the cotangent of the angle between two vectors. Works for vector types where\n            /// dot and cross product is defined (2D or 3D vectors).\n            template <typename Vector_>\n            inline Scalar cotan( const Vector_& v1, const Vector_& v2);\n\n            /// Get the cosine of the angle between two vectors.\n            template <typename Vector_>\n            inline Scalar cos( const Vector_& v1, const Vector_& v2);\n\n            /// Normalize a vector and returns its norm before normalization.\n            /// If the vector's norm is 0, the vector's components will be overwritten by NaNs\n            template< typename Vector_ >\n            inline Scalar getNormAndNormalize(Vector_& v);\n\n            /// Normalize a vector and returns its norm before normalization.\n            /// If the vector's norm is 0, the vector remains null\n            template< typename Vector_ >\n            inline Scalar getNormAndNormalizeSafe(Vector_& v);\n\n        }\n\n        namespace MatrixUtils\n        {\n            inline Matrix4 lookAt(const Vector3& position, const Vector3& target, const Vector3& up);\n            inline Matrix4 perspective(Scalar fovy, Scalar aspect, Scalar near, Scalar zfar);\n            inline Matrix4 orthographic(Scalar left, Scalar right, Scalar bottom, Scalar top, Scalar near, Scalar zfar);\n\n            /// Call std::isnormal on matrix entry.\n            /// Dense version\n            template< typename Matrix_ >\n            inline bool checkInvalidNumbers(Eigen::Ref<const Matrix_> matrix,\n                                             const bool FAIL_ON_ASSERT = false);\n\n        }\n\n        //\n        // Quaternion functions\n        //\n        namespace QuaternionUtils\n        {\n            // Define functions for multiplying a quaternion by a scalar\n            // and adding two quaternions. While Quaternion is supposed to\n            // represent a unit quaternion (thus a valid rotation), these functions\n            // are useful for linear interpolation of quaternions.\n\n            /// Returns the quaternion q multipled by a scalar factor of k.\n            inline Quaternion scale(const Quaternion& q, const Scalar k);\n\n            /// Returns the sum of two quaternions.\n            inline Quaternion add(const Quaternion& q1, const Quaternion& q2);\n\n            /// Returns the sum of two quaternions, resolving antipodality by flipping\n            /// the sign of q2 if q1.q2 is negative. This operation is usually\n            /// denoted as a circled + sign, forming the basis of the QLERP algorithm.\n            /// See \"Spherical Blend Skinning\" (Kavan & Zara 2005) for more details.\n            inline Quaternion addQlerp(const Quaternion& q1, const Quaternion& q2);\n\n            // Note : the .inl file also define operator+ for quaternions\n            // and operator * and / between quaternions and scalar.\n\n            /// Decompose a given rotation Qin into a swing rotation and a twist rotation.\n            /// Qswing is a rotation whose axis lies in the XY plane and Qtwist is a rotation about axis Z.\n            /// such as Qin = Qswing * Qtwist\n            /// If the rotation is already around axis z, Qswing will be set to identity\n            /// and Qtwist equal to Qin\n            inline void getSwingTwist(const Quaternion& in, Quaternion& swingOut, Quaternion& twistOut);\n\n            /// Call std::isnormal on quaternion entries.\n            template< typename Quaternion_ >\n            inline bool checkInvalidNumbers(Eigen::Ref<const Quaternion_> q,\n                                             const bool FAIL_ON_ASSERT = false) {\n                return MatrixUtils::checkInvalidNumbers( q.coeffs(), FAIL_ON_ASSERT );\n            }\n        }\n\n\n        // Use this macro in the public: section of a class\n        // when declaring objects containing Vector or Matrices.\n        // http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html\n#define  RA_CORE_ALIGNED_NEW EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n        /// Use this parameter for aligning structures with Eigen members in it\n#define  RA_DEFAULT_ALIGN EIGEN_MAX_ALIGN_BYTES\n\n    }\n} // end namespace Ra::Core\n\n#include <Core/Math/LinearAlgebra.inl>\n\n#endif// RADIUMENGINE_VECTOR_HPP\n\n", "meta": {"hexsha": "e37468abb8841b99df651a69b69dd7dbb87ee198", "size": 10978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Math/LinearAlgebra.hpp", "max_stars_repo_name": "nmellado/Radium-Engine", "max_stars_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "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/Core/Math/LinearAlgebra.hpp", "max_issues_repo_name": "nmellado/Radium-Engine", "max_issues_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "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/Core/Math/LinearAlgebra.hpp", "max_forks_repo_name": "nmellado/Radium-Engine", "max_forks_repo_head_hexsha": "6e42e4be8d14bcd496371a5f58d483f7d03f9cf4", "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.8104089219, "max_line_length": 158, "alphanum_fraction": 0.6179631991, "num_tokens": 2350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6717799091324514}}
{"text": "#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <numeric>\n\n#include \"operationVector.h\" // ceci va chercher le fichier qui contient les operations sur les vecteurs\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nmatrix<double> Beta(matrix<double> Obs, matrix<double> M, std::vector<double> pie) {\n\n// \tObs est la matrice des observations\n// \tM est la matrice de transition\n// \tpie est le vecteur de probabilite initiale\n\n\n\tconst size_t m = Obs.size2(); // Nombre detat, de cases\n\tconst size_t n = Obs.size1(); // Nombre dobservation, duree de la partie\n\n//\tmatrix Alpha = matrix(NbLigne= n, NbCol= m);  Initialisation de la matric Alpha de tailler n*m\n\tmatrix<double> Beta(n, m);\n\tmatrix<double> bet(1,m);\n\t\n\tfill(bet, [&](int l, int c){\n\t\treturn 1.0/m;\n\t});\n\t\n\t\n\tfor (int i = 0; i < m; ++i) {\n\n\t\tBeta(n-1, i) = 0; // Si je comprend bien, la derniere ligne est la n-1 ?\n\t}\n\n\tdouble log1surc = log(sum(bet));\n\tmatrix<double> Bet{1, m};\n\n\tmatrix<double> Tligne = trans(ligne(Obs,n-1));\n\tBet = prod(M,Tligne);\n\tBet = trans(Bet);\n\tfor (int i = 0; i < m; ++i) {\n\n\t\tBeta(n-2, i) = log(Bet(0,i))+log1surc;\n\t}\n\n\tlog1surc = log1surc + log(sum(Bet));\n\t\n\t\n\t Bet /= sum(Bet);\n\t\n\t//for (int i = 0; i < m; ++i) {\n\n\t//\tBet(0, i) = Bet(0,i)/sum(Bet);\n\t//}\n\n\n\n\tfor (int i = 3; i < n+1 ; ++i) { // J'ai changer la partie \"i < n, ++j\" pour \"i < n ; ++i\"\n\t\t\n\t\tTligne = trans(ligne(Obs,n-i+1));\n\t\t\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tTligne(j, 0) = Tligne(j, 0) * Bet(0, j);\n\t\t}\n\t\t\n\t\tBet = prod(M, Tligne); // prod est le produit matriciel\n\t\tBet = trans(Bet);\n\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tBeta(n-i, j) = log(Bet(0, j)) + log1surc;\n\t\t}\n\n\t\tlog1surc += log(sum(Bet));\n\t\t\n\t\t//for (int i = 0; i < m; ++i) {\n\n\t\t//\tBet(0, i) = Bet(0,i)/sum(Bet);\n\t\t//}\n\t\t\n\t\t Bet /= sum(Bet);\n\n\n\n\t}\n\t\n\treturn Beta;\n\n}\n", "meta": {"hexsha": "3424586de027cb1b8c9f920918d2db930cd056ef", "size": 1815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beta.cpp", "max_stars_repo_name": "Louis-Alexandre/Captain-Markov", "max_stars_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-29T09:47:49.000Z", "max_issues_repo_path": "src/beta.cpp", "max_issues_repo_name": "Louis-Alexandre/Captain-Markov", "max_issues_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_issues_repo_licenses": ["MIT"], "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/beta.cpp", "max_forks_repo_name": "Louis-Alexandre/Captain-Markov", "max_forks_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_forks_repo_licenses": ["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.625, "max_line_length": 104, "alphanum_fraction": 0.582369146, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6716466632653991}}
{"text": "//    Copyright 2017 Rainer Gemulla\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/** \\file\n *\n * Illustrates matrix factorization with alternating least squares. We first creates factors and\n * then a data matrix\n * from these factors. THis process ensures that we know the best factorization of the input.\n * We then try to reconstruct the factors.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\n#include <mf/loss/nzsl.h>\n#include <mf/loss/l2.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 1000000;\n\tdouble sigma = 1; // standard deviation\n\tdouble lambda = 1/sigma/sigma;\n\tmf_size_type r = 10;\n\n\t// parameters for ALS\n\tunsigned epochs = 20;\n\tAlsRegularizer regularizer = ALS_L2;\n\ttypedef SumLoss<NzslLoss, L2Loss> Loss;\n\ttypedef NzRmseLoss TestLoss;\n\tLoss loss((NzslLoss()), L2Loss(lambda));\n\tTestLoss testLoss;\n\tmf_size_type testNnz = nnz/100;\n\n\tBalanceType type = BALANCE_L2;;\n\tBalanceMethod method = BALANCE_SIMPLE;\n\n\t// generate original factors by sampling from a normal(0,sigma) distribution\n\tRandom32 random; // note: this takes a default seed (not randomized!)\n\tDenseMatrix wIn(size1, r);\n\tDenseMatrixCM hIn(r, size2);\n\tgenerateRandom(wIn, random, boost::normal_distribution<>(0, sigma));\n\tgenerateRandom(hIn, random, boost::normal_distribution<>(0, sigma));\n\n\t// generate a sparse matrix by selecting random entries from the generated factors\n\t// and add small Gaussian noise\n\tSparseMatrix v;\n\tgenerateRandom(v, nnz, wIn, hIn, random);\n\taddRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\tv.sort();\n\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\tSparseMatrixCM vc;\n\tcopyCm(v, vc);\n\n\t// create a test matrix (without noise)\n\tSparseMatrix vTest;\n\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t// generate initial factors by sampling from a uniform[-0.5,0.5] distribution\n\tDenseMatrix w(size1, r);\n\tDenseMatrixCM h(r, size2);\n\tgenerateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));\n\tgenerateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));\n\n\t// print the test loss\n\tLOG4CXX_INFO(logger, \"Initial test loss: \"\n\t\t\t<< testLoss(FactorizationData<>(vTest,w,h)));\n\n\tFactorizationData<> testJob(vTest,w,h);\n\n\t// initialize\n\tFactorizationData<> data(v, w, h, 1, &vc);\n\tTrace trace;\n\t// here add fields to Trace\n\t//trace.addField(\"balancing-type\", type);\n\t//trace.addField(\"balancing-method\", method);\n\tTimer t;\n\n\t// run ALS to try to reconstruct the original factors\n\tt.start();\n//\talsNzsl(data, epochs, trace, lambda, regularizer, rescale);\n\talsNzsl(data, epochs, trace, lambda, regularizer, type, method ,&testJob);\n\tt.stop();\n\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t// print the test loss\n\tLOG4CXX_INFO(logger, \"Final test loss: \"\n\t\t\t<< testLoss(FactorizationData<>(vTest,w,h)));\n\n\t// write trace to an R file\n\tstring typeString, methodString;\n\tswitch (type) {\n\tcase BALANCE_NONE:\n\t\ttypeString = \"None\";\n\t\tbreak;\n\tcase BALANCE_L2:\n\t\ttypeString = \"L2\";\n\t\tbreak;\n\tcase BALANCE_NZL2:\n\t\ttypeString = \"Nzl2\";\n\t\tbreak;\n\t}\n\tswitch (method) {\n\tcase BALANCE_SIMPLE:\n\t\tmethodString = \"Simple\";\n\t\tbreak;\n\tcase BALANCE_OPTIMAL:\n\t\tmethodString = \"Optimal\";\n\t\tbreak;\n\t}\n\tstring filename = \"/tmp/als-trace.R\";\n\tLOG4CXX_INFO(logger, \"Writing trace to \" << filename);\n\ttrace.toRfile(filename, \"als\");\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "4b6ffb16b08c614a1d596762e414ad2f9889c9fd", "size": 4616, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/als.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/als.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "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": "examples/mf/als.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 30.5695364238, "max_line_length": 98, "alphanum_fraction": 0.7079722704, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6715914975312813}}
{"text": "#include <Eigen/Dense>\n#include <thirdparty/HighFive/include/highfive/H5Easy.hpp>\n\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nint main() {\n  H5Easy::File file(\"test.h5\", H5Easy::File::Overwrite);\n\n  Matrix2d m;\n  m << 1.0, 2.0,\n       3.0, 4.0;\n\n  H5Easy::dump(file, \"/tmp/m\", m);\n\n  Matrix2d m2 = H5Easy::load<Matrix2d>(file, \"/tmp/m\");\n\n  log_info(\"m is\", m);\n  log_info(\"m2 is\", m2);\n}\n", "meta": {"hexsha": "3070280debadf32cf7f7e6f9235e19eb325e3f13", "size": 436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/test_hdf5_eigen.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/test_hdf5_eigen.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/test_hdf5_eigen.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": 18.1666666667, "max_line_length": 58, "alphanum_fraction": 0.6422018349, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6715914868861712}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2012\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_PcaN_hpp__\n#define __Thea_Algorithms_PcaN_hpp__\n\n#include \"../Common.hpp\"\n#include \"../Math.hpp\"\n#include \"../MatVec.hpp\"\n#include \"IteratorModifiers.hpp\"\n#include \"PointTraitsN.hpp\"\n#include \"CentroidN.hpp\"\n#include <Eigen/Eigenvalues>\n\nnamespace Thea {\nnamespace Algorithms {\n\n/** Principal component analysis of N-D data. */\ntemplate <typename T, int N, typename ScalarT = Real, typename Enable = void>\nclass /* THEA_API */ PcaN\n{\n  public:\n    typedef Vector<N, ScalarT> VectorT;  ///< N-D vector used to represent points and directions.\n\n    /**\n     * Compute the PCA axes of a set of N-D objects. InputIterator must dereference to type T or pointer-to-T.\n     *\n     * @param begin The first object in the set.\n     * @param end One position beyond the last object in the set.\n     * @param eigenvalues The eigenvalues of the covariance matrix, ordered from largest to smallest.\n     * @param eigenvectors The unit-length eigenvectors of the covariance matrix, ordered from largest to smallest eigenvalue.\n     * @param centroid If non-null, used to return the centroid of the objects, which is computed during PCA.\n     */\n    template <typename InputIterator> static void compute(InputIterator begin, InputIterator end,\n                                                          ScalarT eigenvalues[N], VectorT eigenvectors[N],\n                                                          VectorT * centroid = nullptr);\n\n}; // class PcaN\n\n// Principal component analysis of objects that map to single points in 2-space.\ntemplate <typename T, typename ScalarT>\nclass PcaN<T, 2, ScalarT, typename std::enable_if< IsNonReferencedPointN<T, 2>::value >::type>\n{\n  public:\n    typedef Vector<2, ScalarT> VectorT;\n\n    template <typename InputIterator> static void compute(InputIterator begin, InputIterator end,\n                                                          ScalarT eigenvalues[2], VectorT eigenvectors[2],\n                                                          VectorT * centroid = nullptr)\n    {\n      typedef Matrix<2, 2, ScalarT> MatrixT;\n\n      // Compute centroid\n      VectorT ctr = CentroidN<T, 2>::compute(begin, end);\n\n      // Construct covariance matrix\n      MatrixT cov(0, 0, 0, 0);\n      intx n = 0;\n      for (auto i = makeRefIterator(begin); i != makeRefIterator(end); ++i, ++n)\n      {\n        VectorT p = PointTraitsN<T, 2, ScalarT>::getPosition(*i) - ctr;\n\n        for (int r = 0; r < 2; ++r)\n          for (int c = 0; c < 2; ++c)\n            cov(r, c) += (p[r] * p[c]);\n      }\n\n      if (n < 2)\n      {\n        eigenvalues[0]  = eigenvalues[1]  = 0;\n        eigenvectors[0] = eigenvectors[1] = VectorT::Zero();\n        return;\n      }\n\n      cov /= (n - 1);\n\n      // Find eigenvalues of covariance matrix (TODO: Test this)\n      ScalarT trc = cov(0, 0) + cov(1, 1);\n      ScalarT det = cov(0, 0) * cov(1, 1) - cov(0, 1) * cov(1, 0);\n      ScalarT dsc = 0.25f * trc * trc - det;\n\n      // This should never happen: cov is a real symmetric matrix\n      alwaysAssertM(dsc < 0, \"Pca2: Covariance matrix has complex eigenvalues\");\n\n      ScalarT sqd = std::sqrt(dsc);\n      eigenvalues[0] = 0.5f * trc + sqd;\n      eigenvalues[1] = 0.5f * trc - sqd;\n\n      if (cov(1, 0) > Math::eps<ScalarT>())\n      {\n        eigenvectors[0] = VectorT(eigenvalues[0] - cov(1, 1), cov(1, 0)).normalized();\n        eigenvectors[1] = VectorT(eigenvalues[2] - cov(1, 1), cov(1, 0)).normalized();\n      }\n      else\n      {\n        eigenvectors[0] = VectorT(1, 0);\n        eigenvectors[1] = VectorT(0, 1);\n      }\n\n      if (centroid)\n        *centroid = ctr;\n    }\n\n}; // class PcaN<Point2>\n\n// Principal component analysis of objects that map to single points in 3-space.\ntemplate <typename T, typename ScalarT>\nclass PcaN<T, 3, ScalarT, typename std::enable_if< IsNonReferencedPointN<T, 3>::value >::type>\n{\n  public:\n    typedef Vector<3, ScalarT> VectorT;\n\n    template <typename InputIterator> static void compute(InputIterator begin, InputIterator end,\n                                                          ScalarT eigenvalues[3], VectorT eigenvectors[3],\n                                                          VectorT * centroid = nullptr)\n    {\n      typedef Matrix<3, 3, ScalarT> MatrixT;\n\n      // Compute centroid\n      VectorT ctr = CentroidN<T, 3, ScalarT>::compute(begin, end);\n\n      // Construct covariance matrix\n      MatrixT cov = MatrixT::Zero();\n      intx n = 0;\n      for (auto i = makeRefIterator(begin); i != makeRefIterator(end); ++i, ++n)\n      {\n        VectorT p = PointTraitsN<T, 3, ScalarT>::getPosition(*i) - ctr;\n\n        for (int r = 0; r < 3; ++r)\n          for (int c = 0; c < 3; ++c)\n            cov(r, c) += (p[r] * p[c]);\n      }\n\n      if (n < 2)\n      {\n        eigenvalues[0]  = eigenvalues[1]  = eigenvalues[2]  = 0;\n        eigenvectors[0] = eigenvectors[1] = eigenvectors[2] = VectorT::Zero();\n        return;\n      }\n\n      cov /= (n - 1);\n\n      // Find eigenvalues of covariance matrix\n      Eigen::SelfAdjointEigenSolver<MatrixT> eigensolver;\n      if (eigensolver.computeDirect(cov).info() != Eigen::Success)\n        throw Error(\"Pca3: Could not eigensolve covariance matrix\");\n\n      for (int i = 0; i < 3; ++i)\n      {\n        eigenvalues[i]  = eigensolver.eigenvalues()[i];\n        eigenvectors[i] = eigensolver.eigenvectors().col(i).normalized();\n      }\n\n      if (centroid)\n        *centroid = ctr;\n    }\n\n}; // class PcaN<Point3>\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "5d992e8953c54fbd099723924e22f0c65d0e8ae1", "size": 6028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/PcaN.hpp", "max_stars_repo_name": "christinazavou/Thea", "max_stars_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "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": "Code/Source/Algorithms/PcaN.hpp", "max_issues_repo_name": "christinazavou/Thea", "max_issues_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Source/Algorithms/PcaN.hpp", "max_forks_repo_name": "christinazavou/Thea", "max_forks_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "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.4457142857, "max_line_length": 126, "alphanum_fraction": 0.5781353683, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6715692553812862}}
{"text": "/*\n   bern_modp_util.cpp:  number-theoretic utility functions\n\n   Copyright (C) 2008, 2009, David Harvey\n\n   This file is part of the bernmm package (version 1.1).\n\n   bernmm is released under a BSD-style license. See the README file in\n   the source distribution for details.\n*/\n\n\n#include <NTL/ZZ.h>\n#include \"bern_modp_util.h\"\n\n\nNTL_CLIENT;\n\n\nnamespace bernmm {\n\n\nlong PowerMod(long a, long ee, long n, mulmod_t ninv)\n{\n   long x, y;\n\n   unsigned long e;\n\n   if (ee < 0)\n      e = - ((unsigned long) ee);\n   else\n      e = ee;\n\n   x = 1;\n   y = a;\n   while (e) {\n      if (e & 1) x = MulMod(x, y, n, ninv);\n      y = MulMod(y, y, n, ninv);\n      e = e >> 1;\n   }\n\n   if (ee < 0) x = InvMod(x, n);\n\n   return x;\n}\n\n\n\nvoid Factorisation::helper(long k, long m)\n{\n   if (m == 1)\n      return;\n\n   for (long i = k + 1; i * i <= m; i++)\n   {\n      if (m % i == 0)\n      {\n         // found a factor\n         factors.push_back(i);\n         // remove that factor entirely\n         for (m /= i; m % i == 0; m /= i);\n         // recurse\n         helper(i, m);\n         return;\n      }\n   }\n\n   // no more factors\n   factors.push_back(m);\n}\n\n\nFactorisation::Factorisation(long n)\n{\n   this->n = n;\n   helper(1, n);\n}\n\n\nPrimeTable::PrimeTable(long bound)\n{\n   long size = (bound - 1) / ULONG_BITS + 1;   // = ceil(bound / ULONG_BITS)\n   data.resize(size);\n\n   for (long i = 2; i * i < bound; i++)\n      if (is_prime(i))\n         for (long j = 2*i; j < bound; j += i)\n            set(j);\n}\n\n\nlong order(long x, long p, mulmod_t pinv, const Factorisation& F)\n{\n   // in the loop below, m is always some multiple of the order of x\n   long m = p - 1;\n\n   // try to remove factors from m until we can't remove any more\n   for (size_t i = 0; i < F.factors.size(); i++)\n   {\n      long q = F.factors[i];\n\n      while (m % q == 0)\n      {\n         long mm = m / q;\n         if (PowerMod(x, mm, p, pinv) != 1)\n            break;\n         m = mm;\n      }\n   }\n\n   return m;\n}\n\n\n\nlong primitive_root(long p, mulmod_t pinv, const Factorisation& F)\n{\n   if (p == 2)\n      return 1;\n\n   long g = 2;\n   for (; g < p; g++)\n      if (order(g, p, pinv, F) == p - 1)\n         return g;\n\n   // no generator exists!?\n   abort();\n}\n\n\n\n};    // end namespace\n\n\n// end of file ================================================================\n", "meta": {"hexsha": "31318af1575e203dbc673078af7f339905f2d817", "size": 2310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sage/rings/bernmm/bern_modp_util.cpp", "max_stars_repo_name": "hsm207/sage", "max_stars_repo_head_hexsha": "020bd59ec28717bfab9af44d2231c53da1ff99f1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1742.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T07:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:32:52.000Z", "max_issues_repo_path": "src/sage/rings/bernmm/bern_modp_util.cpp", "max_issues_repo_name": "hsm207/sage", "max_issues_repo_head_hexsha": "020bd59ec28717bfab9af44d2231c53da1ff99f1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T19:17:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:59:30.000Z", "max_forks_repo_path": "src/sage/rings/bernmm/bern_modp_util.cpp", "max_forks_repo_name": "dimpase/sage", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 495.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T10:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T22:06:11.000Z", "avg_line_length": 16.9852941176, "max_line_length": 79, "alphanum_fraction": 0.5012987013, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6715692431257345}}
{"text": "#pragma once\n\n// C++ standard library\n#include <vector>\n\n// Armadillo\n#include <armadillo>\n\nnamespace mant {\n  arma::mat::fixed<2, 2> rotationMatrix2d(\n      const double angle);\n\n  arma::mat::fixed<3, 3> rotationMatrix3d(\n      const double rollAngle,\n      const double pitchAngle,\n      const double yawAngle);\n\n  std::vector<arma::vec::fixed<2>> circleCircleIntersections(\n      const arma::vec::fixed<2>& firstCenter,\n      const double firstRadius,\n      const arma::vec::fixed<2>& secondCenter,\n      const double secondRadius);\n\n  std::vector<arma::vec::fixed<3>> circleSphereIntersections(\n      const arma::vec::fixed<3>& circleCenter,\n      const double circleRadius,\n      const arma::vec::fixed<3>& circleNormal,\n      const arma::vec::fixed<3>& sphereCenter,\n      const double sphereRadius);\n}\n", "meta": {"hexsha": "d639fd10ff4d546ce044aa4a2768177f42ef8fa7", "size": 809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/geometry.hpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "include/mantella_bits/geometry.hpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "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/mantella_bits/geometry.hpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["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.0967741935, "max_line_length": 61, "alphanum_fraction": 0.6761433869, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6715692423957039}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n */\n\n#include \"GeometricBasics.h\"\n\n#include <Eigen/Dense>\n\n#include \"BaseLib/Logging.h\"\n#include \"Point3d.h\"\n\nnamespace MathLib\n{\ndouble orientation3d(MathLib::Point3d const& p,\n                     MathLib::Point3d const& a,\n                     MathLib::Point3d const& b,\n                     MathLib::Point3d const& c)\n{\n    auto const pp = Eigen::Map<Eigen::Vector3d const>(p.getCoords());\n    auto const pa = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const pb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const pc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n\n    Eigen::Vector3d const u = pp - pa;\n    Eigen::Vector3d const v = pp - pb;\n    Eigen::Vector3d const w = pp - pc;\n    return u.cross(v).dot(w);\n}\n\ndouble calcTetrahedronVolume(MathLib::Point3d const& a,\n                             MathLib::Point3d const& b,\n                             MathLib::Point3d const& c,\n                             MathLib::Point3d const& d)\n{\n    auto const va = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const vb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const vc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    auto const vd = Eigen::Map<Eigen::Vector3d const>(d.getCoords());\n    Eigen::Vector3d const w = vb - va;\n    Eigen::Vector3d const u = vc - va;\n    Eigen::Vector3d const v = vd - va;\n    return std::abs(u.cross(v).dot(w)) / 6.0;\n}\n\ndouble calcTriangleArea(MathLib::Point3d const& a, MathLib::Point3d const& b,\n                        MathLib::Point3d const& c)\n{\n    auto const va = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const vb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const vc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    Eigen::Vector3d const u = vc - va;\n    Eigen::Vector3d const v = vb - va;\n    Eigen::Vector3d const w = u.cross(v);\n    return 0.5 * w.norm();\n}\n\nbool isPointInTetrahedron(MathLib::Point3d const& p, MathLib::Point3d const& a,\n                          MathLib::Point3d const& b, MathLib::Point3d const& c,\n                          MathLib::Point3d const& d, double eps)\n{\n    double const d0(MathLib::orientation3d(d, a, b, c));\n    // if tetrahedron is not coplanar\n    if (std::abs(d0) > std::numeric_limits<double>::epsilon())\n    {\n        bool const d0_sign(d0 > 0);\n        // if p is on the same side of bcd as a\n        double const d1(MathLib::orientation3d(d, p, b, c));\n        if (!(d0_sign == (d1 >= 0) || std::abs(d1) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of acd as b\n        double const d2(MathLib::orientation3d(d, a, p, c));\n        if (!(d0_sign == (d2 >= 0) || std::abs(d2) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of abd as c\n        double const d3(MathLib::orientation3d(d, a, b, p));\n        if (!(d0_sign == (d3 >= 0) || std::abs(d3) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of abc as d\n        double const d4(MathLib::orientation3d(p, a, b, c));\n        return d0_sign == (d4 >= 0) || std::abs(d4) < eps;\n    }\n    return false;\n}\n\nbool isPointInTriangle(MathLib::Point3d const& p,\n                       MathLib::Point3d const& a,\n                       MathLib::Point3d const& b,\n                       MathLib::Point3d const& c,\n                       double eps_pnt_out_of_plane,\n                       double eps_pnt_out_of_tri,\n                       MathLib::TriangleTest algorithm)\n{\n    switch (algorithm)\n    {\n        case MathLib::GAUSS:\n            return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                        eps_pnt_out_of_tri);\n        case MathLib::BARYCENTRIC:\n            return barycentricPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                              eps_pnt_out_of_tri);\n        default:\n            ERR(\"Selected algorithm for point in triangle testing not found, \"\n                \"falling back on default.\");\n    }\n    return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                eps_pnt_out_of_tri);\n}\n\nbool gaussPointInTriangle(MathLib::Point3d const& q,\n                          MathLib::Point3d const& a,\n                          MathLib::Point3d const& b,\n                          MathLib::Point3d const& c,\n                          double eps_pnt_out_of_plane,\n                          double eps_pnt_out_of_tri)\n{\n    auto const pa = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const pb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const pc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    Eigen::Vector3d const v = pb - pa;\n    Eigen::Vector3d const w = pc - pa;\n\n    Eigen::Matrix2d mat;\n    mat(0, 0) = v.squaredNorm();\n    mat(0, 1) = v[0] * w[0] + v[1] * w[1] + v[2] * w[2];\n    mat(1, 0) = mat(0, 1);\n    mat(1, 1) = w.squaredNorm();\n    Eigen::Vector2d y(\n        v[0] * (q[0] - a[0]) + v[1] * (q[1] - a[1]) + v[2] * (q[2] - a[2]),\n        w[0] * (q[0] - a[0]) + w[1] * (q[1] - a[1]) + w[2] * (q[2] - a[2]));\n\n    y = mat.partialPivLu().solve(y);\n\n    const double lower(eps_pnt_out_of_tri);\n    const double upper(1 + lower);\n\n    if (-lower <= y[0] && y[0] <= upper && -lower <= y[1] && y[1] <= upper &&\n        y[0] + y[1] <= upper)\n    {\n        MathLib::Point3d const q_projected(std::array<double, 3>{\n            {a[0] + y[0] * v[0] + y[1] * w[0], a[1] + y[0] * v[1] + y[1] * w[1],\n             a[2] + y[0] * v[2] + y[1] * w[2]}});\n        if (MathLib::sqrDist(q, q_projected) <= eps_pnt_out_of_plane)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool barycentricPointInTriangle(MathLib::Point3d const& p,\n                                MathLib::Point3d const& a,\n                                MathLib::Point3d const& b,\n                                MathLib::Point3d const& c,\n                                double eps_pnt_out_of_plane,\n                                double eps_pnt_out_of_tri)\n{\n    if (std::abs(MathLib::orientation3d(p, a, b, c)) > eps_pnt_out_of_plane)\n    {\n        return false;\n    }\n\n    auto const vp = Eigen::Map<Eigen::Vector3d const>(p.getCoords());\n    auto const va = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const vb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const vc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    Eigen::Vector3d const pa = va - vp;\n    Eigen::Vector3d const pb = vb - vp;\n    Eigen::Vector3d const pc = vc - vp;\n    double const area_x_2(calcTriangleArea(a, b, c) * 2);\n\n    double const alpha((pb.cross(pc).norm()) / area_x_2);\n    if (alpha < -eps_pnt_out_of_tri || alpha > 1 + eps_pnt_out_of_tri)\n    {\n        return false;\n    }\n    double const beta((pc.cross(pa).norm()) / area_x_2);\n    if (beta < -eps_pnt_out_of_tri || beta > 1 + eps_pnt_out_of_tri)\n    {\n        return false;\n    }\n    double const gamma(1 - alpha - beta);\n    return !(gamma < -eps_pnt_out_of_tri || gamma > 1 + eps_pnt_out_of_tri);\n}\n\nbool isPointInTriangleXY(MathLib::Point3d const& p,\n                         MathLib::Point3d const& a,\n                         MathLib::Point3d const& b,\n                         MathLib::Point3d const& c)\n{\n    // criterion: p-a = u0 * (b-a) + u1 * (c-a); 0 <= u0, u1 <= 1, u0+u1 <= 1\n    Eigen::Matrix2d mat;\n    mat(0, 0) = b[0] - a[0];\n    mat(0, 1) = c[0] - a[0];\n    mat(1, 0) = b[1] - a[1];\n    mat(1, 1) = c[1] - a[1];\n    Eigen::Vector2d y;\n    y << p[0] - a[0], p[1] - a[1];\n\n    y = mat.partialPivLu().solve(y);\n\n    // check if u0 and u1 fulfills the condition\n    return 0 <= y[0] && y[0] <= 1 && 0 <= y[1] && y[1] <= 1 && y[0] + y[1] <= 1;\n}\n\nbool dividedByPlane(const MathLib::Point3d& a, const MathLib::Point3d& b,\n                    const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n    for (unsigned x = 0; x < 3; ++x)\n    {\n        const unsigned y = (x + 1) % 3;\n        const double abc =\n            (b[x] - a[x]) * (c[y] - a[y]) - (b[y] - a[y]) * (c[x] - a[x]);\n        const double abd =\n            (b[x] - a[x]) * (d[y] - a[y]) - (b[y] - a[y]) * (d[x] - a[x]);\n\n        if ((abc > 0 && abd < 0) || (abc < 0 && abd > 0))\n        {\n            return true;\n        }\n    }\n    return false;\n}\n\nbool isCoplanar(const MathLib::Point3d& a, const MathLib::Point3d& b,\n                const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n    auto const pa = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const pb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const pc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    auto const pd = Eigen::Map<Eigen::Vector3d const>(d.getCoords());\n\n    Eigen::Vector3d const ab = pb - pa;\n    Eigen::Vector3d const ac = pc - pa;\n    Eigen::Vector3d const ad = pd - pa;\n\n    auto const eps_squared =\n        std::pow(std::numeric_limits<double>::epsilon(), 2);\n    if (ab.squaredNorm() < eps_squared || ac.squaredNorm() < eps_squared ||\n        ad.squaredNorm() < eps_squared)\n    {\n        return true;\n    }\n\n    // In exact arithmetic <ac*ad^T, ab> should be zero\n    // if all four points are coplanar.\n    const double sqr_scalar_triple(std::pow(ac.cross(ad).dot(ab), 2));\n    // Due to evaluating the above numerically some cancellation or rounding\n    // can occur. For this reason a normalisation factor is introduced.\n    const double normalisation_factor =\n        (ab.squaredNorm() * ac.squaredNorm() * ad.squaredNorm());\n\n    // tolerance 1e-11 is chosen such that\n    // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-6) are considered as\n    // coplanar\n    // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-5) are considered as not\n    // coplanar\n    return (sqr_scalar_triple / normalisation_factor < 1e-11);\n}\n\n}  // end namespace MathLib\n", "meta": {"hexsha": "b9893d29205d357d602e98f32610ea908c033aca", "size": 10125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathLib/GeometricBasics.cpp", "max_stars_repo_name": "ufz/ogs", "max_stars_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2015-03-20T22:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:37:21.000Z", "max_issues_repo_path": "MathLib/GeometricBasics.cpp", "max_issues_repo_name": "ufz/ogs", "max_issues_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3015.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:55:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T01:09:17.000Z", "max_forks_repo_path": "MathLib/GeometricBasics.cpp", "max_forks_repo_name": "ufz/ogs", "max_forks_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 250.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T15:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:37:20.000Z", "avg_line_length": 37.0879120879, "max_line_length": 80, "alphanum_fraction": 0.544691358, "num_tokens": 3116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6714628691979088}}
{"text": "/*\n * Copyright Nick Thompson, 2017\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#define BOOST_TEST_MODULE chebyshev_test\n\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/chebyshev.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/array.hpp>\n\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::chebyshev_t;\nusing boost::math::chebyshev_t_prime;\nusing boost::math::chebyshev_u;\n\ntemplate<class Real>\nvoid test_polynomials()\n{\n    std::cout << \"Testing explicit polynomial representations of the Chebyshev polynomials on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n\n    Real x = -2;\n    Real tol = 100*std::numeric_limits<Real>::epsilon();\n    if (tol > std::numeric_limits<float>::epsilon())\n       tol *= 10;   // float results have much larger error rates.\n    while (x < 2)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(0, x), Real(1), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(1, x), x, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(2, x), 2*x*x - 1, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(3, x), x*(4*x*x-3), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(4, x), 8*x*x*(x*x - 1) + 1, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t(5, x), x*(16*x*x*x*x - 20*x*x + 5), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n\n    x = -2;\n    tol = 10*tol;\n    while (x < 2)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_u(0, x), Real(1), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_u(1, x), 2*x, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_u(2, x), 4*x*x - 1, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_u(3, x), 4*x*(2*x*x - 1), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n}\n\n\ntemplate<class Real>\nvoid test_derivatives()\n{\n    std::cout << \"Testing explicit polynomial representations of the Chebyshev polynomial derivatives on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n\n    Real x = -2;\n    Real tol = 1000*std::numeric_limits<Real>::epsilon();\n    while (x < 2)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(0, x), Real(0), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(1, x), Real(1), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(2, x), 4*x, tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(3, x), 3*(4*x*x - 1), tol);\n        BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(4, x), 16*x*(2*x*x - 1), tol);\n        // This one makes the tolerance have to grow too large; the Chebyshev recurrence is more stable than naive polynomial evaluation anyway.\n        //BOOST_CHECK_CLOSE_FRACTION(chebyshev_t_prime(5, x), 5*(4*x*x*(4*x*x - 3) + 1), tol);\n        x += 1/static_cast<Real>(1<<7);\n    }\n}\n\ntemplate<class Real>\nvoid test_clenshaw_recurrence()\n{\n    using boost::math::chebyshev_clenshaw_recurrence;\n    boost::array<Real, 5> c0 = { {2, 0, 0, 0, 0} };\n    // Check the size = 1 case:\n    boost::array<Real, 1> c01 = { {2} };\n    // Check the size = 2 case:\n    boost::array<Real, 2> c02 = { {2, 0} };\n    boost::array<Real, 4> c1 = { {0, 1, 0, 0} };\n    boost::array<Real, 4> c2 = { {0, 0, 1, 0} };\n    boost::array<Real, 5> c3 = { {0, 0, 0, 1, 0} };\n    boost::array<Real, 5> c4 = { {0, 0, 0, 0, 1} };\n    boost::array<Real, 6> c5 = { {0, 0, 0, 0, 0, 1} };\n    boost::array<Real, 7> c6 = { {0, 0, 0, 0, 0, 0, 1} };\n\n    Real x = -1;\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    if (tol > std::numeric_limits<float>::epsilon())\n       tol *= 100;   // float results have much larger error rates.\n    while (x <= 1)\n    {\n        Real y = chebyshev_clenshaw_recurrence(c0.data(), c0.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(0, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c01.data(), c01.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(0, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c02.data(), c02.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(0, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c1.data(), c1.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(1, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c2.data(), c2.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(2, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c3.data(), c3.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(3, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c4.data(), c4.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(4, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c5.data(), c5.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(5, x), tol);\n\n        y = chebyshev_clenshaw_recurrence(c6.data(), c6.size(), x);\n        BOOST_CHECK_CLOSE_FRACTION(y, chebyshev_t(6, x), tol);\n\n        x += static_cast<Real>(1)/static_cast<Real>(1 << 7);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(chebyshev_test)\n{\n    test_clenshaw_recurrence<float>();\n    test_clenshaw_recurrence<double>();\n    test_clenshaw_recurrence<long double>();\n\n    test_polynomials<float>();\n    test_polynomials<double>();\n    test_polynomials<long double>();\n    test_polynomials<cpp_bin_float_quad>();\n\n    test_derivatives<float>();\n    test_derivatives<double>();\n    test_derivatives<long double>();\n    test_derivatives<cpp_bin_float_quad>();\n}\n", "meta": {"hexsha": "c06f7a6ad1de060c669c318359eb26458a16b706", "size": 5747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/chebyshev_test.cpp", "max_stars_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_stars_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "libs/math/test/chebyshev_test.cpp", "max_issues_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_issues_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "libs/math/test/chebyshev_test.cpp", "max_forks_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_forks_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 38.8310810811, "max_line_length": 172, "alphanum_fraction": 0.6549504089, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6714519697480966}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   License for the specific language governing rights and limitations under\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#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\ntypedef Eigen::MatrixXd DenseMatrix;\ntypedef std::complex<double> Complex;\ntypedef Eigen::Matrix2cd ComplexDenseMatrix;\n\nnamespace\n{\n  DenseMatrix matrix1()\n  {\n    DenseMatrix m(3, 3);\n    for (int i = 0; i < m.rows(); ++ i)\n      for (int j = 0; j < m.cols(); ++ j)\n        m(i, j) = 3.0 * i + j;\n    return m;\n  }\n  DenseMatrix matrixNonSquare()\n  {\n    DenseMatrix m (3, 4);\n    for (int i = 0; i < m.rows(); ++ i)\n      for (int j = 0; j < m.cols(); ++ j)\n        m(i, j) = 3.0 * i + j;\n    return m;\n  }\n  const DenseMatrix Zero(DenseMatrix::Zero(3,3));\n}\n\n#define PRINT_MATRIX(x) //std::cout << #x << \" = \\n\" << (x) << std::endl\n\nTEST(EigenDenseMatrixTest, CanCreateBasicMatrix)\n{\n  DenseMatrix m(matrix1());\n  PRINT_MATRIX(m);\n}\n\nTEST(EigenDenseMatrixTest, CanPrintInLegacyFormat)\n{\n  DenseMatrix m(matrix1());\n  std::ostringstream o;\n  o << 0.5*m;\n  std::string legacy = o.str();\n  EXPECT_EQ(\"  0 0.5   1\\n1.5   2 2.5\\n  3 3.5   4\", legacy);\n}\n\nTEST(EigenDenseMatrixTest, CanDetermineSize)\n{\n  DenseMatrix m(matrixNonSquare());\n  EXPECT_EQ(3, m.rows());\n  EXPECT_EQ(4, m.cols());\n}\n\nTEST(EigenDenseMatrixTest, CanCopyConstruct)\n{\n  DenseMatrix m(matrixNonSquare());\n  DenseMatrix m2(m);\n  EXPECT_EQ(m, m2);\n  m(1,2) += 1;\n  EXPECT_NE(m, m2);\n}\n\nTEST(EigenDenseMatrixTest, CanAssign)\n{\n  DenseMatrix m(matrixNonSquare());\n\n  DenseMatrix m2(3,4);\n  m2.setZero();\n  EXPECT_NE(m, m2);\n  m2 = m;\n  EXPECT_EQ(m, m2);\n  m(1,2) += 1;\n  EXPECT_NE(m, m2);\n}\n\nTEST(EigenDenseMatrixUnaryOperationTests, CanNegate)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(-m);\n\n  DenseMatrix n = - -m;\n  EXPECT_EQ(m, n);\n  EXPECT_EQ(m + (-m), Zero);\n}\n\nTEST(EigenDenseMatrixUnaryOperationTests, CanScalarMultiply)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(2*m);\n  PRINT_MATRIX(m*2);\n  EXPECT_EQ(2*m, m*2);\n}\n\nTEST(EigenDenseMatrixUnaryOperationTests, CanTranspose)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(m.transpose());\n\n  EXPECT_EQ(m, m.transpose().transpose());\n}\n\nTEST(EigenDenseMatrixBinaryOperationTests, CanMultiply)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(m * m);\n  EXPECT_EQ(Zero * m, Zero);\n}\n\nTEST(EigenDenseMatrixBinaryOperationTests, CanAdd)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(m + m);\n  EXPECT_EQ(m + m, 2*m);\n}\n\nTEST(EigenDenseMatrixBinaryOperationTests, CanSubtract)\n{\n  DenseMatrix m(matrix1());\n\n  PRINT_MATRIX(m);\n  PRINT_MATRIX(m - m);\n  EXPECT_EQ(m - m, Zero);\n}\n\nTEST(EigenDenseComplexMatrixTests, CanMultiply)\n{\n  ComplexDenseMatrix A, B, C_expect, C_actual;\n\n  A << Complex(1, 1), Complex(2, 3),\n         Complex(3, 2), Complex(4, 4);\n  B << Complex(4, 4), Complex(3, 2),\n         Complex(2, 3), Complex(1, 1);\n  C_expect << Complex(-5, 20), Complex(0, 10),\n                Complex(0, 40), Complex(5, 20);\n\n  C_actual = A * B;\n\n  ASSERT_TRUE(C_actual.isApprox(C_expect, 1e-6));\n}\n\nnamespace std\n{\n  bool operator<(const Complex& lhs, const Complex& rhs)\n  {\n    return norm(lhs) < norm(rhs);\n  }\n}\n\nTEST(EigenDenseComplexMatrixTests, MinMax)\n{\n  ComplexDenseMatrix A, B, C;\n\n  A << Complex(1, 1), Complex(2, 3),\n    Complex(3, 2), Complex(4, 4);\n  B << Complex(4, 4), Complex(3, 2),\n    Complex(2, 3), Complex(-1, -1);\n  C << Complex(0, 0), Complex(1, 0), Complex(-1, 0), Complex(0.5,0.5);\n\n  EXPECT_EQ(Complex(1, 1), A.minCoeff());\n  EXPECT_EQ(Complex(4, 4), A.maxCoeff());\n  EXPECT_EQ(Complex(-1, -1), B.minCoeff());\n  EXPECT_EQ(Complex(4, 4), B.maxCoeff());\n  EXPECT_EQ(Complex(0, 0), C.minCoeff());\n  EXPECT_EQ(Complex(-1, 0), C.maxCoeff());\n}\n", "meta": {"hexsha": "dbe464e5beaa394afc42c4331effeec25fb15c3b", "size": 4956, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Datatypes/Tests/EigenDenseMatrixTests.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/Datatypes/Tests/EigenDenseMatrixTests.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/Datatypes/Tests/EigenDenseMatrixTests.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": 24.2941176471, "max_line_length": 78, "alphanum_fraction": 0.6707021792, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.7956580927949807, "lm_q1q2_score": 0.6714519678175719}}
{"text": "#ifndef CANNON_MATH_BARYCENTRIC_COORDS_H\n#define CANNON_MATH_BARYCENTRIC_COORDS_H \n\n/*!\n * \\file cannon/math/barycentric_coords.hpp\n * \\brief File containing free functions relating to barycentric coordinate\n * calculation.\n */\n\n/*!\n * \\namespace cannon::math\n * \\brief Namespace containing mathematical utilities.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace math {\n\n    /*!\n     * \\brief Function to compute barycentric coordinates for a query point on\n     * triangle defined by its three vertices. See\n     * https://en.wikipedia.org/wiki/Barycentric_coordinate_system\n     *\n     * \\param v0 First vertex\n     * \\param v1 Second vertex\n     * \\param v2 Third vertex\n     * \\param p Query point\n     *\n     * \\returns Barycentric coordinates for the query point.\n     */\n    Vector3d compute_barycentric_coords(const Vector3d& v0, const Vector3d& v1,\n        const Vector3d& v2, const Vector3d& p);\n\n  } // namespace math\n} // namespace cannon\n#endif /* ifndef CANNON_MATH_BARYCENTRIC_COORDS_H */\n", "meta": {"hexsha": "03e391ccbda542be26d63c74e0c5afdd953ad4df", "size": 1040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/barycentric_coords.hpp", "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": "cannon/math/barycentric_coords.hpp", "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": "cannon/math/barycentric_coords.hpp", "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": 26.0, "max_line_length": 79, "alphanum_fraction": 0.7125, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6714519657730464}}
{"text": "#include \"gen_relpose_5p1pt.h\"\n\n#include \"PoseLib/misc/essential.h\"\n#include \"PoseLib/solvers/relpose_5pt.h\"\n\n#include <Eigen/Dense>\n\nnamespace poselib {\n\nint gen_relpose_5p1pt(const std::vector<Eigen::Vector3d> &p1, const std::vector<Eigen::Vector3d> &x1,\n                      const std::vector<Eigen::Vector3d> &p2, const std::vector<Eigen::Vector3d> &x2,\n                      std::vector<CameraPose> *output) {\n\n    output->clear();\n    relpose_5pt(x1, x2, output);\n\n    for (size_t k = 0; k < output->size(); ++k) {\n        CameraPose &pose = (*output)[k];\n\n        // the translation is given by\n        //  t = p2 - R_5pt*p1 + gamma * t_5pt = a + gamma * b\n\n        // we need to solve for gamma using our extra correspondence\n        //  R * (p1 + lambda_1 * x1) + a + gamma * b = lambda_2 * x2 + p2\n\n        Eigen::Matrix3d R = pose.R();\n        Eigen::Vector3d a = p2[0] - R * p1[0];\n        Eigen::Vector3d b = pose.t;\n\n        // vector used to eliminate lambda1 and lambda2\n        Eigen::Vector3d w = x2[5].cross(R * x1[5]);\n\n        const double c0 = w.dot(p2[5] - R * p1[5] - a);\n        const double c1 = w.dot(b);\n\n        const double gamma = c0 / c1;\n\n        pose.t = a + gamma * b;\n        // TODO: Cheirality check for the last point\n    }\n\n    return output->size();\n}\n\n} // namespace poselib", "meta": {"hexsha": "efc10abfe2117d146564d73e4364d4b3118da4d9", "size": 1317, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PoseLib/solvers/gen_relpose_5p1pt.cc", "max_stars_repo_name": "MikhailTerekhov/PoseLib", "max_stars_repo_head_hexsha": "8f1a2d92c3955bc1e2ce455d4009f9df98ceb697", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T12:12:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:12:59.000Z", "max_issues_repo_path": "PoseLib/solvers/gen_relpose_5p1pt.cc", "max_issues_repo_name": "wuyuanmm/PoseLib", "max_issues_repo_head_hexsha": "35cf8989ddbe721209e8d314eaa94447ab2bd504", "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": "PoseLib/solvers/gen_relpose_5p1pt.cc", "max_forks_repo_name": "wuyuanmm/PoseLib", "max_forks_repo_head_hexsha": "35cf8989ddbe721209e8d314eaa94447ab2bd504", "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.2666666667, "max_line_length": 101, "alphanum_fraction": 0.569476082, "num_tokens": 417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6714500327401222}}
{"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * UCSD Software ORCVIO\n * Copyright (C) 2021 \n * All rights reserved.\n */\n\n#include <gtest/gtest.h>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"orcvio/utils.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace orcvio;\n\nTEST(MathUtilsTest, skewSymmetric) {\n    Vector3d w(1.0, 2.0, 3.0);\n    Matrix3d w_hat = utils::skewSymmetric(w);\n    Vector3d zero_vector = w_hat * w;\n\n    FullPivLU<Matrix3d> lu_helper(w_hat);\n    EXPECT_EQ(lu_helper.rank(), 2);\n    EXPECT_DOUBLE_EQ(zero_vector.norm(), 0.0);\n    return;\n}\n\n\nint main(int argc, char** argv) {\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "cdf99f3cc6d4721ab272db9163954c90a0e58e90", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math_utils_test.cpp", "max_stars_repo_name": "shanmo/OrcVIO-Stereo", "max_stars_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T14:23:44.000Z", "max_issues_repo_path": "test/math_utils_test.cpp", "max_issues_repo_name": "shanmo/OrcVIO-Stereo", "max_issues_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-30T17:09:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T23:41:52.000Z", "max_forks_repo_path": "test/math_utils_test.cpp", "max_forks_repo_name": "shanmo/OrcVIO-Stereo", "max_forks_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 46, "alphanum_fraction": 0.6867647059, "num_tokens": 197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.671370452522962}}
{"text": "//! [mandelbrot-all]\n#include <chrono>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n#include <boost/simd/pack.hpp>\n#include <boost/simd/memory/allocator.hpp>\n\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/if_inc.hpp>\n#include <boost/simd/function/enumerate.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\ntypedef float T;\nnamespace bs = boost::simd;\nusing pack_t = bs::pack<T>;\nusing pack_i = bs::pack<int>;\nusing pack_l = bs::as_logical_t<pack_t>;\n\nstruct mandelbrot{\n  int size, max_iter;\n  T x_min, x_max, y_min, y_max, x_range, y_range;\n  std::vector<int, bs::allocator<int>> iterations;\n\n  mandelbrot(int size_, int max_iter_) : size(size_), max_iter(max_iter_){\n    x_min = -2.5;\n    x_max = 1;\n    y_min = -1;\n    y_max = 1;\n    x_range = x_max - x_min;\n    y_range = y_max - y_min;\n    iterations.resize(size * size);\n  }\n\n  void evaluate_scalar(){\n    for(int i = 0; i < size; ++i){\n      T x0 = T(i) / T(size) * x_range + x_min;\n      for(int j = 0; j < size; ++j){\n\tint iteration  = 0;\n\tT y0 = T(j) / T(size) * y_range + y_min;\n\tT x = 0;\n\tT y = 0;\n\twhile(x * x + y * y < 4 && iteration < max_iter){\n\t  T x_temp = x * x - y * y + x0;\n\t  y = 2 * x * y + y0;\n\t  x = x_temp;\n\t  ++iteration ;\n\t}\n\titerations[j + i * size] = iteration;\n      }\n    }\n  }\n\n  //! [mandelbrot-simd]\n  void evaluate_simd(){\n    pack_t step =  bs::enumerate<pack_t>(0);\n    for(int i = 0; i < size; ++i){\n      pack_t x0 {T(i) / T(size) * x_range + x_min};\n      pack_t fac { y_range / T(size) };\n      pack_t y_min_t {y_min};\n      for(int j = 0; j < size; j += pack_t::static_size){\n\tint iteration  = 0;\n\n\tpack_t y0 = (step + j )* fac + y_min_t;\n\tpack_t x {0};\n\tpack_t y {0};\n\tpack_i iter {0};\n\tpack_l mask;\n\tdo{\n\t  pack_t x2 = x * x;\n\t  pack_t y2 = y * y;\n\n\t  y = 2 * x * y + y0;\n\t  x = x2 - y2 + x0;\n\t  mask = x2 + y2 < 4;\n\t  ++iteration;\n          iter = bs::if_inc(mask, iter);\n\t} while(bs::any(mask) && iteration < max_iter);\n\tbs::aligned_store(iter, &iterations[j + i * size]);\n      }\n    }\n  }\n  //! [mandelbrot-simd]\n\n  void display() {\n    cv::Mat display;\n    cv::Mat A(size, size, CV_32SC1, iterations.data());\n    A.convertTo(display, CV_8UC1, 255.0 / 1000.0);\n    cv::applyColorMap(display, display, cv::COLORMAP_JET);\n    cv::imshow(\"Mandelbrot\", display);\n    cv::waitKey(0);\n  }\n};\n\nint main(int argc, char** argv)\n{\n  namespace chr = std::chrono;\n  using hrc = chr::high_resolution_clock;\n\n  int size = 1024;\n  int max_iteration = 1000;\n  mandelbrot image(size, max_iteration);\n  auto t0 = hrc::now();\n  image.evaluate_scalar();\n  auto t1 = hrc::now();\n  std::cout << \" scalar \" << chr::duration_cast<chr::milliseconds>(t1 - t0).count() << std::endl;\n\n  t0 = hrc::now();\n  image.evaluate_simd();\n  t1 = hrc::now();\n  std::cout << \" simd \" << chr::duration_cast<chr::milliseconds>(t1 - t0).count() << std::endl;\n  image.display();\n}\n//! [mandelbrot-all]\n", "meta": {"hexsha": "4c9854dbd9abb3f31703b53bfb2d9078126bf290", "size": 2987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/mandelbrot.cpp", "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": "doc/examples/mandelbrot.cpp", "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": "doc/examples/mandelbrot.cpp", "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": 25.1008403361, "max_line_length": 97, "alphanum_fraction": 0.6026113157, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6713428970300918}}
{"text": "// Compiled on https://wandbox.org/\n#include \"utils.hpp\"\n\n#include <iostream>\n#include <algorithm>\n#include <boost/math/special_functions.hpp>\n\n#define K 10\n#define PI (acos(-1) / 2.0)\n\nvoid bessels()\n{\n\tdouble v = rand_between<double>(-K, K);\n\tdouble x = rand_between<double>(-K, K);\n\tunsigned int n = rand_int(0, K);\n\n\tdouble i = boost::math::cyl_bessel_i((x < 0) ? floor(v) : v, x);\n\tdouble j = boost::math::cyl_bessel_j((x < 0) ? floor(v) : v, x);\n\tdouble k = boost::math::cyl_bessel_k(v, abs(x)); // x > 0\n\tdouble neumann = boost::math::cyl_neumann(v, abs(x)); // x > 0\n\n\tdouble sph = boost::math::sph_bessel(n, abs(x)); // unsigned int, x > 0\n\tdouble sph_nm = boost::math::sph_neumann(n, abs(x)); // unsigned int, x > 0\n\n\tprint(\"cyl_bessel_i\", (x < 0) ? floor(v) : v, x, i);\n\tprint(\"cyl_bessel_j\", (x < 0) ? floor(v) : v, x, j);\n\tprint(\"cyl_bessel_k\", v, abs(x), k);\n\tprint(\"cyl_neumann\", v, abs(x), neumann);\n\n\tprint(\"sph_bessel\", n, abs(x), sph);\n\tprint(\"sph_neumann\", n, abs(x), sph_nm);\n}\n\nvoid betas()\n{\n\tdouble x = rand_between<double>(0, K);\n\tdouble y = rand_between<double>(0, K);\n\n\tprint(\"beta\", x, y, boost::math::beta(x, y));\n}\n\nvoid ellints()\n{\n\tdouble k = rand_between<double>(-1, 1);\n\tdouble phi = rand_between<double>(-PI, PI);\n\tdouble v = rand_between<double>(0, 1 / (pow(sin(phi), 2.0)));\n\n\tdouble first = boost::math::ellint_1(k, phi);\n\tdouble second = boost::math::ellint_2(k, phi);\n\tdouble third = boost::math::ellint_3(k, v, phi);\n\n\tprint(\"ellint_1\", k, phi, first);\n\tprint(\"ellint_2\", k, phi, second);\n\tprint(\"ellint_3\", k, v, phi, third);\n}\n\nvoid expints()\n{\n\tdouble x = rand_between<double>(-K, K);\n\n\tprint(\"expint\", x, boost::math::expint(x));\n}\n\nvoid hermites()\n{\n\tunsigned int n = rand_int(0, K);\n\tdouble x = rand_between<double>(-K, K);\n\n\tprint(\"hermite\", n, x, boost::math::hermite(n, x));\n}\n\nvoid laguerres()\n{\n\tunsigned int n = rand_int(0, K);\n\tunsigned int m = rand_int(0, K);\n\tdouble x = rand_between<double>(-K, K);\n\n\tdouble ret = boost::math::laguerre(n, m, x);\n\tprint(\"assoc_laguerre\", n, m, x, ret);\n}\n\nvoid legendres()\n{\n\tunsigned int n = rand_int(0, K);\n\tunsigned int m = rand_int(0, K);\n\tdouble x = rand_between<double>(-1, 1);\n\n\tdouble ret = boost::math::legendre_p(n, m, x);\n\tprint(\"assoc_legendre\", n, m, x, ret);\n}\n\nvoid zetas()\n{\n\tdouble x = rand_between<double>(-K, K);\n\n\tprint(\"riemann_zeta\", x, boost::math::zeta(x));\n}\n\nint main()\n{\n\tstd::cout << \"[\" << std::endl;\n\t{\n\t\trepeat(bessels);\n\t\trepeat(betas);\n\t\trepeat(ellints);\n\t\trepeat(expints);\n\t\trepeat(hermites);\n\t\trepeat(laguerres);\n\t\trepeat(legendres);\n\t\trepeat(zetas);\n\t\tstd::cout << \"\\t[\\\"clamp\\\", 1, 6, 5, 5]\" << std::endl;\n\t};\n\tstd::cout << \"]\" << std::endl;\n\n\tsystem(\"pause\");\n\treturn 0;\n}", "meta": {"hexsha": "a051b54a6b19ab6734bee95fa6463ad56ae8c48a", "size": 2700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/numeric/special_maths/main.cpp", "max_stars_repo_name": "ValtoLibraries/TSTL", "max_stars_repo_head_hexsha": "508dac69b9ad8312e25df194dd46d6e7c66d6e31", "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/tests/numeric/special_maths/main.cpp", "max_issues_repo_name": "ValtoLibraries/TSTL", "max_issues_repo_head_hexsha": "508dac69b9ad8312e25df194dd46d6e7c66d6e31", "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/tests/numeric/special_maths/main.cpp", "max_forks_repo_name": "ValtoLibraries/TSTL", "max_forks_repo_head_hexsha": "508dac69b9ad8312e25df194dd46d6e7c66d6e31", "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.0769230769, "max_line_length": 76, "alphanum_fraction": 0.6188888889, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6712993670638175}}
{"text": "// test_regression.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestRegression)\n\n\n    double get_rand(double min_val, double max_val) {\n        /*\n            Returns random double value from interval [min_val, max_val]\n        */\n        return (max_val - min_val) * ( (double)rand() / (double)RAND_MAX ) + min_val;\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_linear_regression)\n    {\n        const int N = 101;\n        const double eps = 1.e-2;\n        int i;\n        double a, b, k, c, step, x, *X = new double[N], *Y = new double[N], *predicted_kc = new double[2];\n        \n        k = -3;    \n        c = 2;\n        \n        // segment [a, b]\n        a = 0;\n        b = 1;\n\n        // Generating random values for regression\n        step = (b - a) / double(N - 1);\n        for (i = 0; i < N; i++, x += step) {\n            X[i] = rand() % 2 == 0 ? x + eps: x - eps;\n            Y[i] = rand() % 2 == 0 ? (k * X[i] + c) + eps * get_rand(1, 3) : (k * X[i] + c) - eps * get_rand(1, 3);\n        }\n\n        // Get predicted linear regression line\n        predicted_kc = Numerary::linear_regression(X, Y, N);\n\n        \n        BOOST_CHECK(fabs(predicted_kc[0] - k) < 1.e-3);\n        BOOST_CHECK(fabs(predicted_kc[1] - c) < 1.e-3);\n\n        delete[] X;\n        delete[] Y;\n        delete[] predicted_kc;\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "352e5aa31f8aae0542643af3f6840030b40e5578", "size": 1430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_regression.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_regression.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_regression.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 25.0877192982, "max_line_length": 115, "alphanum_fraction": 0.5111888112, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6712993567873122}}
{"text": "//\n// ExpansionHunter\n// Copyright (c) 2020 Illumina, Inc.\n//\n// Author: Konrad Scheffler <kscheffler@illumina.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// These utility functions were copied from source code of Strelka Small Variant Caller.\n\n#pragma once\n\n#include <boost/math/special_functions/log1p.hpp>\n\n// returns log(1+x), switches to log1p function when abs(x) is small\nstatic double log1p_switch(const double x)\n{\n    // TODO Justify this switch point. Related discussion:\n    // http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n    static const double smallx_thresh(0.01);\n\n    if (std::abs(x) < smallx_thresh)\n    {\n        return boost::math::log1p(x);\n    }\n    else\n    {\n        return std::log(1 + x);\n    }\n}\n\n// Returns the equivalent of log(exp(x1)+exp(x2))\nstatic double getLogSum(double x1, double x2)\n{\n    if (x1 < x2)\n        std::swap(x1, x2);\n    return x1 + log1p_switch(std::exp(x2 - x1));\n}", "meta": {"hexsha": "61b8c36017aa8cc5fcde9d64eaa10785fd200957", "size": 1468, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ehunter/core/LogSum.hh", "max_stars_repo_name": "bw2/ExpansionHunter", "max_stars_repo_head_hexsha": "6a6005a4bae2c49f56ec8997a301b70a75b042b6", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_stars_count": 122.0, "max_stars_repo_stars_event_min_datetime": "2017-01-06T16:19:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T00:05:50.000Z", "max_issues_repo_path": "ehunter/core/LogSum.hh", "max_issues_repo_name": "bw2/ExpansionHunter", "max_issues_repo_head_hexsha": "6a6005a4bae2c49f56ec8997a301b70a75b042b6", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2017-01-04T00:23:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T12:55:52.000Z", "max_forks_repo_path": "ehunter/core/LogSum.hh", "max_forks_repo_name": "bw2/ExpansionHunter", "max_forks_repo_head_hexsha": "6a6005a4bae2c49f56ec8997a301b70a75b042b6", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T13:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T17:34:11.000Z", "avg_line_length": 29.9591836735, "max_line_length": 88, "alphanum_fraction": 0.6961852861, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.671219337347155}}
{"text": "#include \"iostream\"\nusing namespace std;\n\n#include <ctime>\n// include Core and Dense compuation parts from Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n# define MATRIX_SIZE 50\n\n/**************************************************\n * Exercise 5\n * Suppose there is a large Eigen matrix, we want to know the value in the top\n * left 3 x 3 blocks, and then assign it to Identity 3\u00d73.\n * *************************************************/\n\n\nint main(int argc, char** argv){\n    // the large matrix\n    Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_NN = MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); \n\n    // Extract the top-left 3*3\n    Matrix3d matrix_33;\n    for (int i = 0; i < 3; i++){\n        for (int j = 0; j < 3; j++){\n            matrix_33(i, j) = matrix_NN(i, j);\n        }\n    }\n    // print it out\n    cout << \"The top left 3*3 matrix is: \" << endl << matrix_33 << endl;\n\n    // assign an Identity to it\n    for (int i = 0; i < 3; i++){\n        for (int j = 0; j < 3; j++){\n            if(i == j){\n                matrix_NN(i, j) = 1;\n            }\n            else{\n                matrix_NN(i, j) = 0;\n            }\n        }\n    }\n\n}\n\n\n", "meta": {"hexsha": "8d4397f5b6d3460cd4c0c09719de5e4988fa9125", "size": 1177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/exercises/assignIdentity.cpp", "max_stars_repo_name": "henryxuy/slam-codeInBook-en", "max_stars_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/exercises/assignIdentity.cpp", "max_issues_repo_name": "henryxuy/slam-codeInBook-en", "max_issues_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/exercises/assignIdentity.cpp", "max_forks_repo_name": "henryxuy/slam-codeInBook-en", "max_forks_repo_head_hexsha": "ec3c8ec8d5facfdeb0832be121de105cea73790b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0204081633, "max_line_length": 101, "alphanum_fraction": 0.4978759558, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6712193373471549}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/affine.hpp>\n#include <kv/autodif.hpp>\n#include <kv/interval-vector.hpp>\n\n/*\n * comparison of interval, affine, mean value form\n * in evaluation of a 5 variable function.\n * The function is taken from http://ci.nii.ac.jp/naid/110003291707\n */\n\nnamespace ub = boost::numeric::ublas;\ntypedef kv::interval<double> itv;\n\nstruct Func {\n\ttemplate <class T> T operator()(const ub::vector<T>& t) {\n\t\tT f1, f2, y;\n\n\t\tf1 = (-10. - 13.2 * t[0] + 0.5 * t[1] - 0.4 * t[2] + 7.3 * t[3] + 4.4 * t[4]);\n\t\tf2 = (0.8 + 10.5 * t[0] + 5.9 * t[1] + 7.5 * t[2] - 14.5 * t[3] + 1.3 * t[4]);\n\n\t\ty = f1 * f2 - ((-113.7) * f2 + (-49.8) * f1) + 5660.;\n\t\treturn y;\n\t}\n};\n\nint main()\n{\n\tint i;\n\tub::vector<itv> I;\n\tFunc f;\n\n\tstd::cout.precision(17);\n\n\tI.resize(5);\n\n\tI[0] = itv(8.7, 8.8);\n\tI[1] = itv(-9.4, -9.3);\n\tI[2] = itv(-4.6, -4.5);\n\tI[3] = itv(3.5, 3.6);\n\tI[4] = itv(-2.9, -2.8);\n\n\n\t// interval arithmetic\n\n\tstd::cout << \"interval: \" << f(I) << \"\\n\";\n\n\t// affine arithmetic\n\n\t// ub::vector< kv::affine<double> > a;\n\tub::vector< kv::affine<itv::base_type> > a;\n\n\ta.resize(5);\n\tfor (i=0; i<5; i++) a(i) = I(i);\n\tstd::cout << \"affine: \" << to_interval(f(a)) << \"\\n\";\n\n\t// mean value form\n\n\tub::vector<itv> c, fdi;\n\titv fc, fi;\n\n\tc = mid(I);\n\tfc = f(c);\n\tkv::autodif<itv>::split(f(kv::autodif<itv>::init(I)), fi, fdi);\n\n\tstd::cout << \"mvf: \" << fc + inner_prod(fdi, I - c) << \"\\n\";\n}\n", "meta": {"hexsha": "3cbf20127d620c27bcee4ea9960d2eb88565920b", "size": 1527, "ext": "cc", "lang": "C++", "max_stars_repo_path": "example/test-evalrange.cc", "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": "example/test-evalrange.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "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": "example/test-evalrange.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "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": 21.2083333333, "max_line_length": 80, "alphanum_fraction": 0.5586116568, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.671219330123217}}
{"text": "/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n */\n\n#include <almath/tools/almath.h>\n#include <almath/tools/altrigonometry.h>\n\n#include <cmath>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/algorithm/clamp.hpp>\n\nnamespace AL\n{\n  namespace Math\n  {\n\n    void modulo2PIInPlace(float& pAngle)\n    {\n      pAngle = std::fmod(pAngle, AL::Math::_2_PI_);\n\n      if (pAngle>AL::Math::PI)\n      {\n        pAngle = pAngle - AL::Math::_2_PI_;\n      }\n      else if (pAngle<-AL::Math::PI)\n      {\n        pAngle = pAngle + AL::Math::_2_PI_;\n      }\n    }\n\n    float modulo2PI(float pAngle)\n    {\n      float result = pAngle;\n      modulo2PIInPlace(result);\n      return result;\n    }\n\n    float meanAngle(const std::vector<float> &pAngles) {\n      const std::vector<float> weights(pAngles.size(), 1.f);\n      return weightedMeanAngle(pAngles, weights);\n    }\n\n    float weightedMeanAngle(const std::vector<float> &pAngles,\n                            const std::vector<float> &pWeights) {\n      if (pAngles.size() != pWeights.size()) {\n        throw std::runtime_error(\"Angles and weights must have the same size.\");\n      }\n      Math::Position2D sumPosition;\n      std::vector<float>::const_iterator a = pAngles.begin();\n      std::vector<float>::const_iterator w = pWeights.begin();\n      float weightSum = 0.f;\n      for (; a != pAngles.end(); ++a, ++w) {\n        if (*w <= 0.f) {\n          throw std::runtime_error(\"All weights must be strictly positive.\");\n        }\n        weightSum += *w;\n        sumPosition += *w * Math::Position2D(std::cos(*a), std::sin(*a));\n      }\n      if (sumPosition.norm() < 1e-3f) {\n        throw std::runtime_error(\"No defined mean.\");\n      }\n      return Math::modulo2PI(std::atan2(sumPosition.y, sumPosition.x));\n    }\n\n    bool clipData(\n      const float& pMin,\n      const float& pMax,\n      float& pData)\n    {\n      const float saved = pData;\n      pData = boost::algorithm::clamp(saved, pMin, pMax);\n      return saved != pData;\n    }\n\n    bool clipData(\n      const float& pMin,\n      const float& pMax,\n      std::vector<float>& pData)\n    {\n      bool isClipped = false;\n      for (unsigned int i=0; i<pData.size(); ++i)\n      {\n        if (clipData(pMin, pMax, pData[i]))\n        {\n          isClipped = true;\n        }\n      }\n      return isClipped;\n    }\n\n    bool clipData(\n      const float& pMin,\n      const float& pMax,\n      std::vector<std::vector<float> >& pData)\n    {\n      bool isClipped = false;\n      for (unsigned int i=0; i<pData.size(); ++i)\n      {\n        if (clipData(pMin, pMax, pData[i]))\n        {\n          isClipped = true;\n        }\n      }\n      return isClipped;\n    }\n\n\n    void changeReferencePose2D(\n        const float&  pTheta,\n        const Pose2D& pPosIn,\n        Pose2D&       pPosOut)\n    {\n      const float cs = std::cos(pTheta);\n      const float sn = std::sin(pTheta);\n      pPosOut.x = cs*pPosIn.x - sn*pPosIn.y;\n      pPosOut.y = sn*pPosIn.x + cs*pPosIn.y;\n      pPosOut.theta = pPosIn.theta;\n    }\n\n\n    void changeReferencePose2DInPlace(\n        const float& pTheta,\n        Pose2D&      pPosOut)\n    {\n      const float cs = std::cos(pTheta);\n      const float sn = std::sin(pTheta);\n      const float xOld = pPosOut.x;\n      const float yOld = pPosOut.y;\n\n      pPosOut.x = cs*xOld - sn*yOld;\n      pPosOut.y = sn*xOld + cs*yOld;\n    }\n\n\n    Position3D position3DFromPosition6D(const Position6D& pPosition6D)\n    {\n      return Position3D(pPosition6D.x, pPosition6D.y, pPosition6D.z);\n    }\n\n\n    Position6D position6DFromVelocity6D(const Velocity6D& pVel)\n    {\n      return Position6D(\n            pVel.xd,\n            pVel.yd,\n            pVel.zd,\n            pVel.wxd,\n            pVel.wyd,\n            pVel.wzd);\n    }\n\n    Position3D operator*(\n      const Rotation&   pRot,\n      const Position3D& pPos)\n    {\n      return Position3D(\n            pRot.r1_c1*pPos.x + pRot.r1_c2*pPos.y + pRot.r1_c3*pPos.z,\n            pRot.r2_c1*pPos.x + pRot.r2_c2*pPos.y + pRot.r2_c3*pPos.z,\n            pRot.r3_c1*pPos.x + pRot.r3_c2*pPos.y + pRot.r3_c3*pPos.z);\n    }\n\n    Position3D operator*(\n        const Quaternion& pQuat,\n        const Position3D& pPos)\n    {\n      Position3D result;\n      result.x = pQuat.w * pQuat.w * pPos.x + 2.0f *pQuat.y * pQuat.w * pPos.z;\n      result.x += - 2.0f * pQuat.z * pQuat.w * pPos.y + pQuat.x * pQuat.x * pPos.x;\n      result.x += 2.0f * pQuat.y * pQuat.x * pPos.y + 2.0f * pQuat.z * pQuat.x * pPos.z;\n      result.x += - pQuat.z * pQuat.z * pPos.x - pQuat.y * pQuat.y * pPos.x;\n\n      result.y = 2.0f * pQuat.x * pQuat.y * pPos.x + pQuat.y * pQuat.y * pPos.y;\n      result.y += 2.0f * pQuat.z * pQuat.y * pPos.z + 2.0f * pQuat.w * pQuat.z * pPos.x;\n      result.y += - pQuat.z * pQuat.z * pPos.y + pQuat.w * pQuat.w * pPos.y;\n      result.y += - 2.0f * pQuat.x * pQuat.w * pPos.z - pQuat.x * pQuat.x * pPos.y;\n\n      result.z = 2.0f * pQuat.x * pQuat.z * pPos.x + 2.0f * pQuat.y * pQuat.z * pPos.y;\n      result.z += pQuat.z * pQuat.z * pPos.z - 2.0f * pQuat.w * pQuat.y * pPos.x;\n      result.z += - pQuat.y * pQuat.y * pPos.z + 2.0f * pQuat.w * pQuat.x * pPos.y;\n      result.z += - pQuat.x * pQuat.x * pPos.z + pQuat.w * pQuat.w * pPos.z;\n      return result;\n    }\n\n    Velocity6D operator*(\n      const float       pVal,\n      const Position6D& pPos)\n    {\n      return Velocity6D(\n            pVal * pPos.x,\n            pVal * pPos.y,\n            pVal * pPos.z,\n            pVal * pPos.wx,\n            pVal * pPos.wy,\n            pVal * pPos.wz);\n    }\n\n    Velocity3D operator*(\n      const float       pVal,\n      const Position3D& pPos)\n    {\n      return Velocity3D(\n            pVal * pPos.x,\n            pVal * pPos.y,\n            pVal * pPos.z);\n    }\n\n    Velocity3D operator*(\n      const Rotation&   pRot,\n      const Velocity3D& pVel)\n    {\n      return Velocity3D(\n            pRot.r1_c1*pVel.xd + pRot.r1_c2*pVel.yd + pRot.r1_c3*pVel.zd,\n            pRot.r2_c1*pVel.xd + pRot.r2_c2*pVel.yd + pRot.r2_c3*pVel.zd,\n            pRot.r3_c1*pVel.xd + pRot.r3_c2*pVel.yd + pRot.r3_c3*pVel.zd);\n    }\n\n    AL::Math::Rotation rotationFromAngleDirection(\n      const float&                pTheta,\n      const AL::Math::Position3D& pPos)\n    {\n      return AL::Math::rotationFromAngleDirection(\n            pTheta,\n            pPos.x,\n            pPos.y,\n            pPos.z);\n    }\n\n\n    void position2DFromPose2DInPlace(\n        const Pose2D& pPose2D,\n        Position2D&   pPosition2D)\n    {\n      pPosition2D.x = pPose2D.x;\n      pPosition2D.y = pPose2D.y;\n    }\n\n\n    Position2D position2DFromPose2D(const Pose2D& pPose2D)\n    {\n      return Position2D(pPose2D.x, pPose2D.y);\n    }\n\n\n    void position6DFromPose2DInPlace(\n        const Pose2D& pPose2D,\n        Position6D&   pPosition6D)\n    {\n      pPosition6D.x  = pPose2D.x;\n      pPosition6D.y  = pPose2D.y;\n      pPosition6D.z  = 0.0f;\n      pPosition6D.wx = 0.0f;\n      pPosition6D.wy = 0.0f;\n      pPosition6D.wz = pPose2D.theta;\n    }\n\n\n    Position6D position6DFromPose2D(const Pose2D& pPose2D)\n    {\n      return Position6D(\n            pPose2D.x,\n            pPose2D.y,\n            0.0f,\n            0.0f,\n            0.0f,\n            pPose2D.theta);\n    }\n\n\n    void position6DFromPosition3DInPlace(\n        const Position3D& pPosition3D,\n        Position6D&       pPosition6D)\n    {\n      pPosition6D.x  = pPosition3D.x;\n      pPosition6D.y  = pPosition3D.y;\n      pPosition6D.z  = pPosition3D.z;\n      pPosition6D.wx = 0.0f;\n      pPosition6D.wy = 0.0f;\n      pPosition6D.wz = 0.0f;\n    }\n\n    Position6D position6DFromPosition3D(const Position3D& pPosition3D)\n    {\n      return Position6D(pPosition3D.x,\n                        pPosition3D.y,\n                        pPosition3D.z,\n                        0.0f,\n                        0.0f,\n                        0.0f);\n    }\n\n    void pose2DFromPosition6DInPlace(\n        const Position6D& pPosition6D,\n        Pose2D&           pPose2D)\n    {\n      pPose2D.x     = pPosition6D.x;\n      pPose2D.y     = pPosition6D.y;\n      pPose2D.theta = pPosition6D.wz;\n    }\n\n\n    Pose2D pose2DFromPosition6D(const Position6D& pPosition6D)\n    {\n      return Pose2D(pPosition6D.x, pPosition6D.y, pPosition6D.wz);\n    }\n\n\n    void pose2DFromPosition2DInPlace(\n        const Position2D& pPosition2D,\n        const float       pAngle,\n        Pose2D&           pPose2D)\n    {\n      pPose2D.x     = pPosition2D.x;\n      pPose2D.y     = pPosition2D.y;\n      pPose2D.theta = pAngle;\n    }\n\n\n    Pose2D pose2DFromPosition2D(const Position2D& pPosition2D,\n                                const float       pAngle)\n    {\n      return Pose2D(pPosition2D.x, pPosition2D.y, pAngle);\n    }\n\n\n    Position2D operator*(\n      const Pose2D&     pVal,\n      const Position2D& pPos)\n    {\n      return Position2D(\n            pVal.x + std::cos(pVal.theta)*pPos.x - std::sin(pVal.theta)*pPos.y,\n            pVal.y + std::sin(pVal.theta)*pPos.x + std::cos(pVal.theta)*pPos.y);\n    }\n\n    void quaternionFromRotation3D(\n        const Rotation3D& pRot3D,\n        Quaternion& pQuaternion)\n    {\n      const float cx = std::cos(0.5f*pRot3D.wx);\n      const float cy = std::cos(0.5f*pRot3D.wy);\n      const float cz = std::cos(0.5f*pRot3D.wz);\n      const float sx = std::sin(0.5f*pRot3D.wx);\n      const float sy = std::sin(0.5f*pRot3D.wy);\n      const float sz = std::sin(0.5f*pRot3D.wz);\n\n      pQuaternion.w = cz * cy * cx + sz * sy * sx;\n      pQuaternion.x = cz * cy * sx - sz * sy * cx;\n      pQuaternion.y = cz * sy * cx + cy * sz * sx;\n      pQuaternion.z = cy * sz * cx - cz * sy * sx;\n    }\n\n    Quaternion quaternionFromRotation3D(\n        const Rotation3D& pRot3D)\n    {\n      Quaternion lQuat;\n      quaternionFromRotation3D(pRot3D, lQuat);\n      return lQuat;\n    }\n\n    void rotationFromQuaternion(\n        const Quaternion& pQua,\n        Rotation& pRot)\n    {\n      pRot.r1_c1 = 1.0f - 2.0f*(std::pow(pQua.y, 2) + std::pow(pQua.z, 2));\n      pRot.r1_c2 = 2.0f*(pQua.x*pQua.y - pQua.z*pQua.w);\n      pRot.r1_c3 = 2.0f*(pQua.x*pQua.z + pQua.y*pQua.w);\n\n      pRot.r2_c1 = 2.0f*(pQua.x*pQua.y + pQua.z*pQua.w);\n      pRot.r2_c2 = 1.0f - 2.0f*(std::pow(pQua.x, 2) + std::pow(pQua.z, 2));\n      pRot.r2_c3 = 2.0f*(pQua.y*pQua.z - pQua.x*pQua.w);\n\n      pRot.r3_c1 = 2.0f*(pQua.x*pQua.z - pQua.y*pQua.w);\n      pRot.r3_c2 = 2.0f*(pQua.y*pQua.z + pQua.x*pQua.w);\n      pRot.r3_c3 = 1.0f - 2.0f*(std::pow(pQua.x, 2) + std::pow(pQua.y, 2));\n    }\n\n    Rotation rotationFromQuaternion(\n        const Quaternion& pQua)\n    {\n      Rotation lRot;\n      rotationFromQuaternion(pQua, lRot);\n      return lRot;\n    }\n\n\n    void rotation3DFromQuaternion(\n        const AL::Math::Quaternion& pQuaternion,\n        AL::Math::Rotation3D& pRot3D)\n    {\n      //rotationFromQuaternion\n      AL::Math::Rotation lRot;\n      rotationFromQuaternion(pQuaternion, lRot);\n\n      pRot3D.wz = std::atan2(lRot.r2_c1, lRot.r1_c1);\n      const float sy = std::sin(pRot3D.wz);\n      const float cy = std::cos(pRot3D.wz);\n      pRot3D.wy = std::atan2(-lRot.r3_c1, cy*lRot.r1_c1+sy*lRot.r2_c1);\n      pRot3D.wx = std::atan2(sy*lRot.r1_c3-cy*lRot.r2_c3, cy*lRot.r2_c2-sy*lRot.r1_c2);\n    }\n\n    Rotation3D rotation3DFromQuaternion(\n        const Quaternion& pQuaternion)\n    {\n      Rotation3D lRotation3D;\n      rotation3DFromQuaternion(pQuaternion, lRotation3D);\n      return lRotation3D;\n    }\n\n    void quaternionPosition3DFromPosition6D(\n        const Position6D& pPos6D,\n        Quaternion& pQua,\n        Position3D& pPos3D)\n    {\n      quaternionFromRotation3D(\n            AL::Math::Rotation3D(pPos6D.wx, pPos6D.wy, pPos6D.wz),\n            pQua);\n\n      pPos3D.x = pPos6D.x;\n      pPos3D.y = pPos6D.y;\n      pPos3D.z = pPos6D.z;\n    }\n\n\n    void pointMassRotationalInertia(\n        float pMass,\n        const Position3D& pPos,\n        std::vector<float>& pInertia)\n    {\n      const float x2 = boost::math::pow<2>(pPos.x);\n      const float y2 = boost::math::pow<2>(pPos.y);\n      const float z2 = boost::math::pow<2>(pPos.z);\n      pInertia.resize(9);\n      pInertia[0] = pMass * (y2 + z2);\n      pInertia[4] = pMass * (x2 + z2);\n      pInertia[8] = pMass * (x2 + y2);\n      pInertia[1] = pInertia[3] = - pMass * pPos.x * pPos.y;\n      pInertia[2] = pInertia[6] = - pMass * pPos.x * pPos.z;\n      pInertia[5] = pInertia[7] = - pMass * pPos.y * pPos.z;\n    }\n  } // namespace Math\n} // namespace AL\n\n", "meta": {"hexsha": "9febabb952400a3852f6b1ff516df7719d257cd7", "size": 12448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/almath.cpp", "max_stars_repo_name": "UCCS-Social-Robotics/libalmath", "max_stars_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-14T20:34:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T05:53:00.000Z", "max_issues_repo_path": "src/tools/almath.cpp", "max_issues_repo_name": "UCCS-Social-Robotics/libalmath", "max_issues_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T05:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:18:20.000Z", "max_forks_repo_path": "src/tools/almath.cpp", "max_forks_repo_name": "UCCS-Social-Robotics/libalmath", "max_forks_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-11T16:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T20:41:05.000Z", "avg_line_length": 28.036036036, "max_line_length": 88, "alphanum_fraction": 0.5609736504, "num_tokens": 4146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6712142923410106}}
{"text": "// Copyright John Maddock 2006.\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// test_lognormal.cpp\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp> // Boost.Test\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <boost/math/distributions/lognormal.hpp>\n    using boost::math::lognormal_distribution;\n#include <boost/math/tools/test.hpp>\n#include \"test_out_of_range.hpp\"\n\n#include <iostream>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n#include <limits>\n  using std::numeric_limits;\n#include <cassert>\n\ntemplate <class RealType>\nvoid check_lognormal(RealType loc, RealType scale, RealType x, RealType p, RealType q, RealType tol)\n{\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         lognormal_distribution<RealType>(loc, scale),       // distribution.\n         x),                                            // random variable.\n         p,                                             // probability.\n         tol);                                          // %tolerance.\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         complement(\n            lognormal_distribution<RealType>(loc, scale),    // distribution.\n            x)),                                        // random variable.\n         q,                                             // probability complement.\n         tol);                                          // %tolerance.\n   BOOST_CHECK_CLOSE(\n      ::boost::math::quantile(\n         lognormal_distribution<RealType>(loc, scale),       // distribution.\n         p),                                            // probability.\n         x,                                             // random variable.\n         tol);                                          // %tolerance.\n   BOOST_CHECK_CLOSE(\n      ::boost::math::quantile(\n         complement(\n            lognormal_distribution<RealType>(loc, scale),    // distribution.\n            q)),                                        // probability complement.\n         x,                                             // random variable.\n         tol);                                          // %tolerance.\n}\n\ntemplate <class RealType>\nvoid test_spots(RealType)\n{\n \n   // Basic sanity checks.\n   RealType tolerance = 5e-3 * 100;\n   // Some tests only pass at 1e-4 because values generated by\n   // http://faculty.vassar.edu/lowry/VassarStats.html\n   // give only 5 or 6 *fixed* places, so small values have fewer digits.\n\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n\n   using std::exp;\n\n   //\n   // These test values were generated for the normal distribution\n   // using the online calculator at http://faculty.vassar.edu/lowry/VassarStats.html\n   // and then exponentiating the random variate x.\n   //\n\n   check_lognormal(\n      static_cast<RealType>(0),     // location\n      static_cast<RealType>(5),     // scale\n      static_cast<RealType>(1),     // x\n      static_cast<RealType>(0.5),   // p\n      static_cast<RealType>(0.5),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(2),     // location\n      static_cast<RealType>(2),     // scale\n      static_cast<RealType>(exp(1.8)),     // x\n      static_cast<RealType>(0.46017),   // p\n      static_cast<RealType>(1-0.46017),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(2),     // location\n      static_cast<RealType>(2),     // scale\n      static_cast<RealType>(exp(2.2)),     // x\n      static_cast<RealType>(1-0.46017),   // p\n      static_cast<RealType>(0.46017),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(2),     // location\n      static_cast<RealType>(2),     // scale\n      static_cast<RealType>(exp(-1.4)),     // x\n      static_cast<RealType>(0.04457),   // p\n      static_cast<RealType>(1-0.04457),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(2),     // location\n      static_cast<RealType>(2),     // scale\n      static_cast<RealType>(exp(5.4)),     // x\n      static_cast<RealType>(1-0.04457),   // p\n      static_cast<RealType>(0.04457),   // q\n      tolerance);\n\n   check_lognormal(\n      static_cast<RealType>(-3),     // location\n      static_cast<RealType>(5),     // scale\n      static_cast<RealType>(exp(-5.0)),     // x\n      static_cast<RealType>(0.34458),   // p\n      static_cast<RealType>(1-0.34458),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(-3),     // location\n      static_cast<RealType>(5),     // scale\n      static_cast<RealType>(exp(-1.0)),     // x\n      static_cast<RealType>(1-0.34458),   // p\n      static_cast<RealType>(0.34458),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(-3),     // location\n      static_cast<RealType>(5),     // scale\n      static_cast<RealType>(exp(-9.0)),     // x\n      static_cast<RealType>(0.11507),   // p\n      static_cast<RealType>(1-0.11507),   // q\n      tolerance);\n   check_lognormal(\n      static_cast<RealType>(-3),     // location\n      static_cast<RealType>(5),     // scale\n      static_cast<RealType>(exp(3.0)),     // x\n      static_cast<RealType>(1-0.11507),   // p\n      static_cast<RealType>(0.11507),   // q\n      tolerance);\n\n   //\n   // Tests for PDF\n   //\n   tolerance = boost::math::tools::epsilon<RealType>() * 5 * 100; // 5 eps as a percentage\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n   BOOST_CHECK_CLOSE(\n      pdf(lognormal_distribution<RealType>(), static_cast<RealType>(1)),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L), // 1/sqrt(2*pi)\n      tolerance);\n   BOOST_CHECK_CLOSE(\n      pdf(lognormal_distribution<RealType>(3), exp(static_cast<RealType>(3))),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L) / exp(static_cast<RealType>(3)),\n      tolerance);\n   BOOST_CHECK_CLOSE(\n      pdf(lognormal_distribution<RealType>(3, 5), exp(static_cast<RealType>(3))),\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L / (5 * exp(static_cast<RealType>(3)))),\n      tolerance);\n   //\n   // Spot checks for location = -5, scale = 6,\n   // use relation to normal to test:\n   //\n   for(RealType x = -15; x < 5; x += 0.125)\n   {\n      BOOST_CHECK_CLOSE(\n         pdf(lognormal_distribution<RealType>(-5, 6), exp(x)),\n         pdf(boost::math::normal_distribution<RealType>(-5, 6), x) / exp(x),\n         tolerance);\n   }\n\n   //\n   // These test values were obtained by punching numbers into\n   // a calculator, using the formulas at http://mathworld.wolfram.com/LogNormalDistribution.html\n   //\n   tolerance = (std::max)(\n      boost::math::tools::epsilon<RealType>(),\n      static_cast<RealType>(boost::math::tools::epsilon<double>())) * 5 * 100; // 5 eps as a percentage\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n   lognormal_distribution<RealType> dist(8, 3);\n   RealType x = static_cast<RealType>(0.125);\n\n   BOOST_MATH_STD_USING // ADL of std math lib names.\n\n   // mean:\n   BOOST_CHECK_CLOSE(\n      mean(dist)\n      , static_cast<RealType>(268337.28652087445695647967378715L), tolerance);\n   // variance:\n   BOOST_CHECK_CLOSE(\n      variance(dist)\n      , static_cast<RealType>(583389737628117.49553037857325892L), tolerance);\n   // std deviation:\n   BOOST_CHECK_CLOSE(\n    standard_deviation(dist)\n    , static_cast<RealType>(24153462.228594009489719473727471L), tolerance);\n   // hazard:\n   BOOST_CHECK_CLOSE(\n    hazard(dist, x)\n    , pdf(dist, x) / cdf(complement(dist, x)), tolerance);\n   // cumulative hazard:\n   BOOST_CHECK_CLOSE(\n    chf(dist, x)\n    , -log(cdf(complement(dist, x))), tolerance);\n   // coefficient_of_variation:\n   BOOST_CHECK_CLOSE(\n    coefficient_of_variation(dist)\n    , standard_deviation(dist) / mean(dist), tolerance);\n   // mode:\n   BOOST_CHECK_CLOSE(\n    mode(dist)\n    , static_cast<RealType>(0.36787944117144232159552377016146L), tolerance);\n\n   BOOST_CHECK_CLOSE(\n    median(dist)\n    , static_cast<RealType>(exp(dist.location())), tolerance);\n\n   BOOST_CHECK_CLOSE(\n    median(dist),\n    quantile(dist, static_cast<RealType>(0.5)), tolerance);\n\n   // skewness:\n   BOOST_CHECK_CLOSE(\n    skewness(dist)\n    , static_cast<RealType>(729551.38304660255658441529235697L), tolerance);\n   // kurtosis:\n   BOOST_CHECK_CLOSE(\n    kurtosis(dist)\n    , static_cast<RealType>(4312295840576303.2363383232038251L), tolerance);\n   // kurtosis excess:\n   BOOST_CHECK_CLOSE(\n    kurtosis_excess(dist)\n    , static_cast<RealType>(4312295840576300.2363383232038251L), tolerance);\n\n   RealType expected_entropy = 8 + log(boost::math::constants::two_pi<RealType>()*boost::math::constants::e<RealType>()*9)/2;\n   BOOST_CHECK_CLOSE(\n    entropy(dist)\n    , expected_entropy, tolerance);\n\n   BOOST_CHECK_CLOSE(\n    range(dist).first\n    , static_cast<RealType>(0), tolerance);\n\n   //\n   // Special cases:\n   //\n   BOOST_CHECK(pdf(dist, 0) == 0);\n   BOOST_CHECK(cdf(dist, 0) == 0);\n   BOOST_CHECK(cdf(complement(dist, 0)) == 1);\n   BOOST_CHECK(quantile(dist, 0) == 0);\n   BOOST_CHECK(quantile(complement(dist, 1)) == 0);\n\n   //\n   // Error checks:\n   //\n   BOOST_MATH_CHECK_THROW(lognormal_distribution<RealType>(0, 0), std::domain_error);\n   BOOST_MATH_CHECK_THROW(lognormal_distribution<RealType>(2, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(pdf(dist, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(cdf(dist, -1), std::domain_error);\n   BOOST_MATH_CHECK_THROW(cdf(complement(dist, -1)), std::domain_error);\n   BOOST_MATH_CHECK_THROW(quantile(dist, 1), std::overflow_error);\n   BOOST_MATH_CHECK_THROW(quantile(complement(dist, 0)), std::overflow_error);\n   check_out_of_range<lognormal_distribution<RealType> >(1, 2);\n\n} // template <class RealType>void test_spots(RealType)\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n\n   // Check that can generate lognormal distribution using the two convenience methods:\n   boost::math::lognormal myf1(1., 2); // Using typedef\n   lognormal_distribution<> myf2(1., 2); // Using default RealType double.\n\n  // Test range and support using double only,\n  // because it supports numeric_limits max for a pseudo-infinity.\n  BOOST_CHECK_EQUAL(range(myf2).first, 0); // range 0 to +infinity\n  BOOST_CHECK_EQUAL(range(myf2).second, (std::numeric_limits<double>::max)());\n  BOOST_CHECK_EQUAL(support(myf2).first, 0); // support 0 to + infinity.\n  BOOST_CHECK_EQUAL(support(myf2).second, (std::numeric_limits<double>::max)());\n\n    // Basic sanity-check spot values.\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#if !BOOST_WORKAROUND(BOOST_BORLANDC, BOOST_TESTED_AT(0x0582))\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::endl;\n#endif\n\n   \n} // BOOST_AUTO_TEST_CASE( test_main )\n\n/*\nRunning 1 test case...\nTolerance for type float is 0.5 %\nTolerance for type float is 5.96046e-005 %\nTolerance for type float is 5.96046e-005 %\nTolerance for type double is 0.5 %\nTolerance for type double is 1.11022e-013 %\nTolerance for type double is 1.11022e-013 %\nTolerance for type long double is 0.5 %\nTolerance for type long double is 1.11022e-013 %\nTolerance for type long double is 1.11022e-013 %\nTolerance for type class boost::math::concepts::real_concept is 0.5 %\nTolerance for type class boost::math::concepts::real_concept is 1.11022e-013 %\nTolerance for type class boost::math::concepts::real_concept is 1.11022e-013 %\n*** No errors detected\n*/\n\n\n", "meta": {"hexsha": "74010651beac45d34dc33f6afc557a43387d0c2c", "size": 12236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_lognormal.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/test_lognormal.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/test_lognormal.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 38.2375, "max_line_length": 125, "alphanum_fraction": 0.6358287022, "num_tokens": 3226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6711100041027952}}
{"text": "#include \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <random>\n#include <utility>\n\n#include <sys/resource.h>\n#include <sys/time.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nconstexpr size_t batch_size = 1;\nconstexpr size_t input_size = 1;\n\n/* use squared error as loss function */\nfloat loss_function( const float target, const float actual )\n{\n  return ( target - actual ) * ( target - actual );\n}\n\n/* partial derivative of loss with respect to neural network output */\nfloat compute_pd_loss_wrt_output( const float target, const float actual )\n{\n  return -2 * ( target - actual );\n}\n\n/* actual function we want the neural network to learn */\nfloat true_function( const float input )\n{\n  return 3 * input + 1;\n}\n\nconstexpr float learning_rate = 0.001;\n\nvoid program_body()\n{\n  /* remove limit on stack size */\n  const rlimit limits { RLIM_INFINITY, RLIM_INFINITY };\n  CheckSystemCall( \"setrlimit\", setrlimit( RLIMIT_STACK, &limits ) );\n\n  /* seed C RNG for Eigen random weight initialization */\n  srand( Timer::timestamp_ns() );\n\n  /* construct neural network on heap */\n  auto nn = make_unique<Network<float, batch_size, input_size, 1>>();\n  nn->layer0.weights()( 0 ) = 1;\n  nn->layer0.biases()( 0 ) = 1;\n\n  double x_value = rand() % 30;\n  // while ( true ) {\n  for ( auto i = 0; i < 100; i++ ) {\n    cout << \"Weight = \" << nn->layer0.weights()( 0 ) << \", bias = \" << nn->layer0.biases()( 0 ) << \"\\n\";\n\n    /* step 1: construct a unique problem instance */\n    Matrix<float, batch_size, input_size> input, ground_truth_output;\n\n    input( 0, 0 ) = x_value;\n    ground_truth_output( 0, 0 ) = true_function( x_value );\n\n    // x_value++; /* use a different problem instance next time */\n    x_value = rand() % 40;\n\n    cout << \"problem instance: \" << input( 0, 0 ) << \" => \" << ground_truth_output( 0, 0 ) << \"\\n\";\n\n    /* step 2: forward propagate and calculate loss function */\n    nn->apply( input );\n\n    cout << \"NN maps \" << input( 0, 0 ) << \" => \" << nn->output()( 0, 0 ) << \"\\n\";\n\n    cout << \"loss when \" << ground_truth_output( 0, 0 ) << \" desired, \" << nn->output()( 0, 0 )\n         << \" produced = \" << loss_function( nn->output()( 0, 0 ), ground_truth_output( 0, 0 ) ) << \"\\n\";\n\n    /* step 3: backpropagate error */\n    nn->computeDeltas();\n    nn->evaluateGradients( input );\n\n    const float pd_loss_wrt_output\n      = compute_pd_loss_wrt_output( ground_truth_output( 0, 0 ), nn->output()( 0, 0 ) );\n\n    /* perturb weight */\n    nn->layer0.weights()( 0 ) -= learning_rate * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 0 );\n    nn->layer0.biases()( 0 ) -= learning_rate * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 1 );\n    // nn -> layer0.weights()(0) -= learning_rate * pd_loss_wrt_output;\n    // nn -> layer0.biases()(0) -= learning_rate * pd_loss_wrt_output * nn->layer0.biases()(0);\n\n    cout << \"\\n\";\n\n    cout << \"pd_loss_wrt_output = \" << pd_loss_wrt_output << \"\\n\";\n    cout << \"pd_output_wrt_weight = \" << nn->getEvaluatedGradient( 0, 0 ) << \"\\n\";\n    cout << \"pd_output_wrt_bias = \" << nn->getEvaluatedGradient( 0, 1 ) << \"\\n\";\n\n    cout << \"\\n\";\n\n    cout << \"perturb weight: \" << -pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 0 ) << \"\\n\";\n    cout << \"perturb bias: \" << -pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 1 ) << \"\\n\";\n\n    cout << \"\\n\";\n  }\n\n#if 0\n  /* input and output */\n  for ( int i = 0; i < 10; i++ ) {\n    Matrix<float, batch_size, input_size> in, out;\n    int v = rand() % 100 + 1;\n    in( 0 ) = (float)v;\n    out( 0 ) = 3 * v + 1 + (float)rand() / ( RAND_MAX );\n    input.push_back( in );\n    output.push_back( out );\n  }\n  for ( int round = 0; round < 100; round++ ) {\n    for ( int i = 0; i < 10; i++ ) {\n      nn->apply( input[i] );\n      cout << \"right after apply: \" << input[i]( 0 ) << \"  \" << output[i]( 0 ) << endl;\n\n      // cout << \"output: \" << nn->output() << \"\\n\";\n\n      // const float loss = ( 100 - nn->output()( 0 ) ) * ( 100 - nn->output()( 0 ) );\n      const float loss = getLoss( output[i]( 0 ), nn->output()( 0 ) );\n\n      nn->computeDeltas();\n      nn->evaluateGradients( input[i] );\n\n      // const float pd_loss_output = -2 * ( 100 - nn->output()( 0 ) );\n      const float pd_loss_output = get_pd_loss_output( output[i]( 0 ), nn->output()( 0 ) );\n\n      cout << \"partial derivative of output wrt weight = \" << nn->getEvaluatedGradient( 0, 0 ) << \"\\n\";\n      cout << \"partial derivative of output wrt bias = \" << nn->getEvaluatedGradient( 0, 1 ) << \"\\n\";\n\n      cout << \"loss: \" << loss << \"\\n\";\n\n      cout << \"partial derivative of loss wrt output = \" << pd_loss_output << \"\\n\";\n\n      cout << \"partial derivative of loss wrt weight = \" << pd_loss_output * nn->getEvaluatedGradient( 0, 0 )\n           << \"\\n\";\n      cout << \"partial derivative of loss wrt bias = \" << pd_loss_output * nn->getEvaluatedGradient( 0, 1 ) << \"\\n\";\n      cout << \"weight = \" << nn->layer0.weights()( 0 ) << endl;\n      cout << \"biase = \" << nn->layer0.biases()( 0 ) << endl;\n\n      const float learning_rate = .0001;\n\n      nn->layer0.weights()( 0 ) *= ( 1 - learning_rate * pd_loss_output * nn->getEvaluatedGradient( 0, 0 ) );\n      nn->layer0.biases()( 0 ) *= ( 1 - learning_rate * pd_loss_output * nn->getEvaluatedGradient( 0, 1 ) );\n    }\n  }\n\n  // testing\n  cout << \"start testing results\" << endl;\n  Matrix<float, batch_size, input_size> test_input, test_output;\n  for ( int i = 0; i < 10; i++ ) {\n    int v = rand() % 100 + 1;\n    test_input( 0 ) = (float)v;\n    test_output( 0 ) = 3 * v + 1;\n    cout << \"input: \" << test_input( 0 ) << \", output: \" << test_output( 0 ) << endl;\n    nn->apply( test_input );\n    auto nnOutput = nn->output();\n    cout << \"nn output: \" << nnOutput << endl;\n  }\n#endif\n}\n\nint main( int argc, char*[] )\n{\n  try {\n    if ( argc <= 0 ) {\n      abort();\n    }\n\n    program_body();\n\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "e1a94f096b78c4f89248627322cc3cc6301815a6", "size": 5981, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/linear_predictor/simple-test.cc", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/frontend/linear_predictor/simple-test.cc", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "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/frontend/linear_predictor/simple-test.cc", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "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.2277777778, "max_line_length": 116, "alphanum_fraction": 0.5830128741, "num_tokens": 1819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6711099900799674}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/LU>\nusing namespace std;\n\ntemplate<typename MatrixType>\ntypename MatrixType::RealScalar matrix_l1_norm(const MatrixType& m) {\n  return m.cwiseAbs().colwise().sum().maxCoeff();\n}\n\ntemplate<typename MatrixType> void lu_non_invertible()\n{\n  typedef typename MatrixType::RealScalar RealScalar;\n  /* this test covers the following files:\n     LU.h\n  */\n  Index rows, cols, cols2;\n  if(MatrixType::RowsAtCompileTime==Dynamic)\n  {\n    rows = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE);\n  }\n  else\n  {\n    rows = MatrixType::RowsAtCompileTime;\n  }\n  if(MatrixType::ColsAtCompileTime==Dynamic)\n  {\n    cols = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE);\n    cols2 = internal::random<int>(2,EIGEN_TEST_MAX_SIZE);\n  }\n  else\n  {\n    cols2 = cols = MatrixType::ColsAtCompileTime;\n  }\n\n  enum {\n    RowsAtCompileTime = MatrixType::RowsAtCompileTime,\n    ColsAtCompileTime = MatrixType::ColsAtCompileTime\n  };\n  typedef typename internal::kernel_retval_base<FullPivLU<MatrixType> >::ReturnType KernelMatrixType;\n  typedef typename internal::image_retval_base<FullPivLU<MatrixType> >::ReturnType ImageMatrixType;\n  typedef Matrix<typename MatrixType::Scalar, ColsAtCompileTime, ColsAtCompileTime>\n          CMatrixType;\n  typedef Matrix<typename MatrixType::Scalar, RowsAtCompileTime, RowsAtCompileTime>\n          RMatrixType;\n\n  Index rank = internal::random<Index>(1, (std::min)(rows, cols)-1);\n\n  // The image of the zero matrix should consist of a single (zero) column vector\n  VERIFY((MatrixType::Zero(rows,cols).fullPivLu().image(MatrixType::Zero(rows,cols)).cols() == 1));\n\n  // The kernel of the zero matrix is the entire space, and thus is an invertible matrix of dimensions cols.\n  KernelMatrixType kernel = MatrixType::Zero(rows,cols).fullPivLu().kernel();\n  VERIFY((kernel.fullPivLu().isInvertible()));\n\n  MatrixType m1(rows, cols), m3(rows, cols2);\n  CMatrixType m2(cols, cols2);\n  createRandomPIMatrixOfRank(rank, rows, cols, m1);\n\n  FullPivLU<MatrixType> lu;\n\n  // The special value 0.01 below works well in tests. Keep in mind that we're only computing the rank\n  // of singular values are either 0 or 1.\n  // So it's not clear at all that the epsilon should play any role there.\n  lu.setThreshold(RealScalar(0.01));\n  lu.compute(m1);\n\n  MatrixType u(rows,cols);\n  u = lu.matrixLU().template triangularView<Upper>();\n  RMatrixType l = RMatrixType::Identity(rows,rows);\n  l.block(0,0,rows,(std::min)(rows,cols)).template triangularView<StrictlyLower>()\n    = lu.matrixLU().block(0,0,rows,(std::min)(rows,cols));\n\n  VERIFY_IS_APPROX(lu.permutationP() * m1 * lu.permutationQ(), l*u);\n\n  KernelMatrixType m1kernel = lu.kernel();\n  ImageMatrixType m1image = lu.image(m1);\n\n  VERIFY_IS_APPROX(m1, lu.reconstructedMatrix());\n  VERIFY(rank == lu.rank());\n  VERIFY(cols - lu.rank() == lu.dimensionOfKernel());\n  VERIFY(!lu.isInjective());\n  VERIFY(!lu.isInvertible());\n  VERIFY(!lu.isSurjective());\n  VERIFY_IS_MUCH_SMALLER_THAN((m1 * m1kernel), m1);\n  VERIFY(m1image.fullPivLu().rank() == rank);\n  VERIFY_IS_APPROX(m1 * m1.adjoint() * m1image, m1image);\n\n  m2 = CMatrixType::Random(cols,cols2);\n  m3 = m1*m2;\n  m2 = CMatrixType::Random(cols,cols2);\n  // test that the code, which does resize(), may be applied to an xpr\n  m2.block(0,0,m2.rows(),m2.cols()) = lu.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n\n  // test solve with transposed\n  m3 = MatrixType::Random(rows,cols2);\n  m2 = m1.transpose()*m3;\n  m3 = MatrixType::Random(rows,cols2);\n  lu.template _solve_impl_transposed<false>(m2, m3);\n  VERIFY_IS_APPROX(m2, m1.transpose()*m3);\n  m3 = MatrixType::Random(rows,cols2);\n  m3 = lu.transpose().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.transpose()*m3);\n\n  // test solve with conjugate transposed\n  m3 = MatrixType::Random(rows,cols2);\n  m2 = m1.adjoint()*m3;\n  m3 = MatrixType::Random(rows,cols2);\n  lu.template _solve_impl_transposed<true>(m2, m3);\n  VERIFY_IS_APPROX(m2, m1.adjoint()*m3);\n  m3 = MatrixType::Random(rows,cols2);\n  m3 = lu.adjoint().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.adjoint()*m3);\n}\n\ntemplate<typename MatrixType> void lu_invertible()\n{\n  /* this test covers the following files:\n     LU.h\n  */\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  Index size = MatrixType::RowsAtCompileTime;\n  if( size==Dynamic)\n    size = internal::random<Index>(1,EIGEN_TEST_MAX_SIZE);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  FullPivLU<MatrixType> lu;\n  lu.setThreshold(RealScalar(0.01));\n  do {\n    m1 = MatrixType::Random(size,size);\n    lu.compute(m1);\n  } while(!lu.isInvertible());\n\n  VERIFY_IS_APPROX(m1, lu.reconstructedMatrix());\n  VERIFY(0 == lu.dimensionOfKernel());\n  VERIFY(lu.kernel().cols() == 1); // the kernel() should consist of a single (zero) column vector\n  VERIFY(size == lu.rank());\n  VERIFY(lu.isInjective());\n  VERIFY(lu.isSurjective());\n  VERIFY(lu.isInvertible());\n  VERIFY(lu.image(m1).fullPivLu().isInvertible());\n  m3 = MatrixType::Random(size,size);\n  m2 = lu.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  MatrixType m1_inverse = lu.inverse();\n  VERIFY_IS_APPROX(m2, m1_inverse*m3);\n\n  RealScalar rcond = (RealScalar(1) / matrix_l1_norm(m1)) / matrix_l1_norm(m1_inverse);\n  const RealScalar rcond_est = lu.rcond();\n  // Verify that the estimated condition number is within a factor of 10 of the\n  // truth.\n  VERIFY(rcond_est > rcond / 10 && rcond_est < rcond * 10);\n\n  // test solve with transposed\n  lu.template _solve_impl_transposed<false>(m3, m2);\n  VERIFY_IS_APPROX(m3, m1.transpose()*m2);\n  m3 = MatrixType::Random(size,size);\n  m3 = lu.transpose().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.transpose()*m3);\n\n  // test solve with conjugate transposed\n  lu.template _solve_impl_transposed<true>(m3, m2);\n  VERIFY_IS_APPROX(m3, m1.adjoint()*m2);\n  m3 = MatrixType::Random(size,size);\n  m3 = lu.adjoint().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.adjoint()*m3);\n\n  // Regression test for Bug 302\n  MatrixType m4 = MatrixType::Random(size,size);\n  VERIFY_IS_APPROX(lu.solve(m3*m4), lu.solve(m3)*m4);\n}\n\ntemplate<typename MatrixType> void lu_partial_piv()\n{\n  /* this test covers the following files:\n     PartialPivLU.h\n  */\n  typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;\n  Index size = internal::random<Index>(1,4);\n\n  MatrixType m1(size, size), m2(size, size), m3(size, size);\n  m1.setRandom();\n  PartialPivLU<MatrixType> plu(m1);\n\n  VERIFY_IS_APPROX(m1, plu.reconstructedMatrix());\n\n  m3 = MatrixType::Random(size,size);\n  m2 = plu.solve(m3);\n  VERIFY_IS_APPROX(m3, m1*m2);\n  MatrixType m1_inverse = plu.inverse();\n  VERIFY_IS_APPROX(m2, m1_inverse*m3);\n\n  RealScalar rcond = (RealScalar(1) / matrix_l1_norm(m1)) / matrix_l1_norm(m1_inverse);\n  const RealScalar rcond_est = plu.rcond();\n  // Verify that the estimate is within a factor of 10 of the truth.\n  VERIFY(rcond_est > rcond / 10 && rcond_est < rcond * 10);\n\n  // test solve with transposed\n  plu.template _solve_impl_transposed<false>(m3, m2);\n  VERIFY_IS_APPROX(m3, m1.transpose()*m2);\n  m3 = MatrixType::Random(size,size);\n  m3 = plu.transpose().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.transpose()*m3);\n\n  // test solve with conjugate transposed\n  plu.template _solve_impl_transposed<true>(m3, m2);\n  VERIFY_IS_APPROX(m3, m1.adjoint()*m2);\n  m3 = MatrixType::Random(size,size);\n  m3 = plu.adjoint().solve(m2);\n  VERIFY_IS_APPROX(m2, m1.adjoint()*m3);\n}\n\ntemplate<typename MatrixType> void lu_verify_assert()\n{\n  MatrixType tmp;\n\n  FullPivLU<MatrixType> lu;\n  VERIFY_RAISES_ASSERT(lu.matrixLU())\n  VERIFY_RAISES_ASSERT(lu.permutationP())\n  VERIFY_RAISES_ASSERT(lu.permutationQ())\n  VERIFY_RAISES_ASSERT(lu.kernel())\n  VERIFY_RAISES_ASSERT(lu.image(tmp))\n  VERIFY_RAISES_ASSERT(lu.solve(tmp))\n  VERIFY_RAISES_ASSERT(lu.determinant())\n  VERIFY_RAISES_ASSERT(lu.rank())\n  VERIFY_RAISES_ASSERT(lu.dimensionOfKernel())\n  VERIFY_RAISES_ASSERT(lu.isInjective())\n  VERIFY_RAISES_ASSERT(lu.isSurjective())\n  VERIFY_RAISES_ASSERT(lu.isInvertible())\n  VERIFY_RAISES_ASSERT(lu.inverse())\n\n  PartialPivLU<MatrixType> plu;\n  VERIFY_RAISES_ASSERT(plu.matrixLU())\n  VERIFY_RAISES_ASSERT(plu.permutationP())\n  VERIFY_RAISES_ASSERT(plu.solve(tmp))\n  VERIFY_RAISES_ASSERT(plu.determinant())\n  VERIFY_RAISES_ASSERT(plu.inverse())\n}\n\nvoid test_lu()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( lu_non_invertible<Matrix3f>() );\n    CALL_SUBTEST_1( lu_invertible<Matrix3f>() );\n    CALL_SUBTEST_1( lu_verify_assert<Matrix3f>() );\n\n    CALL_SUBTEST_2( (lu_non_invertible<Matrix<double, 4, 6> >()) );\n    CALL_SUBTEST_2( (lu_verify_assert<Matrix<double, 4, 6> >()) );\n\n    CALL_SUBTEST_3( lu_non_invertible<MatrixXf>() );\n    CALL_SUBTEST_3( lu_invertible<MatrixXf>() );\n    CALL_SUBTEST_3( lu_verify_assert<MatrixXf>() );\n\n    CALL_SUBTEST_4( lu_non_invertible<MatrixXd>() );\n    CALL_SUBTEST_4( lu_invertible<MatrixXd>() );\n    CALL_SUBTEST_4( lu_partial_piv<MatrixXd>() );\n    CALL_SUBTEST_4( lu_verify_assert<MatrixXd>() );\n\n    CALL_SUBTEST_5( lu_non_invertible<MatrixXcf>() );\n    CALL_SUBTEST_5( lu_invertible<MatrixXcf>() );\n    CALL_SUBTEST_5( lu_verify_assert<MatrixXcf>() );\n\n    CALL_SUBTEST_6( lu_non_invertible<MatrixXcd>() );\n    CALL_SUBTEST_6( lu_invertible<MatrixXcd>() );\n    CALL_SUBTEST_6( lu_partial_piv<MatrixXcd>() );\n    CALL_SUBTEST_6( lu_verify_assert<MatrixXcd>() );\n\n    CALL_SUBTEST_7(( lu_non_invertible<Matrix<float,Dynamic,16> >() ));\n\n    // Test problem size constructors\n    CALL_SUBTEST_9( PartialPivLU<MatrixXf>(10) );\n    CALL_SUBTEST_9( FullPivLU<MatrixXf>(10, 20); );\n  }\n}\n", "meta": {"hexsha": "176a2f09081ad08bd34647e4d9046b315da644e0", "size": 9867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/3rdparty/Eigen/test/lu.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "gtsam/3rdparty/Eigen/test/lu.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "gtsam/3rdparty/Eigen/test/lu.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 718.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T18:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T08:10:53.000Z", "avg_line_length": 34.7429577465, "max_line_length": 108, "alphanum_fraction": 0.7150096281, "num_tokens": 2979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6710384777088927}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include \"../utils.hpp\"\n#include \"Operator.hpp\"\n\nnamespace yavque\n{\n\nclass DenseHermitianMatrix\n{\nprivate:\n\tconst Eigen::MatrixXcd ham_;\n\n\tmutable bool diagonalized_;\n\tmutable Eigen::VectorXd evals_;\n\tmutable Eigen::MatrixXcd evecs_;\n\n\tvoid diagonalize() const\n\t{\n\t\t// Add mutex (future)\n\t\tif(diagonalized_)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> es(ham_);\n\t\tevals_ = es.eigenvalues();\n\t\tevecs_ = es.eigenvectors();\n\t\tdiagonalized_ = true;\n\t}\n\npublic:\n\texplicit DenseHermitianMatrix(Eigen::MatrixXcd ham) : ham_{std::move(ham)}\n\t{\n\t\tassert(ham_.rows() == ham_.cols()); // check diagonal\n\t\tdiagonalized_ = false;\n\t}\n\n\t[[nodiscard]] uint32_t dim() const { return ham_.rows(); }\n\n\t[[nodiscard]] const Eigen::MatrixXcd& get_ham() const& { return ham_; }\n\n\t[[nodiscard]] Eigen::MatrixXcd get_ham() && { return ham_; }\n\n\t[[nodiscard]] const Eigen::MatrixXcd& evecs() const&\n\t{\n\t\tif(!diagonalized_)\n\t\t{\n\t\t\tdiagonalize();\n\t\t}\n\t\treturn evecs_;\n\t}\n\n\t[[nodiscard]] Eigen::MatrixXcd evecs() &&\n\t{\n\t\tif(!diagonalized_)\n\t\t{\n\t\t\tdiagonalize();\n\t\t}\n\t\treturn evecs_;\n\t}\n\n\t[[nodiscard]] const Eigen::VectorXd& evals() const&\n\t{\n\t\tif(!diagonalized_)\n\t\t{\n\t\t\tdiagonalize();\n\t\t}\n\t\treturn evals_;\n\t}\n\n\t[[nodiscard]] Eigen::VectorXd evals() &&\n\t{\n\t\tif(!diagonalized_)\n\t\t{\n\t\t\tdiagonalize();\n\t\t}\n\t\treturn evals_;\n\t}\n\n\t[[nodiscard]] Eigen::MatrixXcd ham_exp(cx_double x) const\n\t{\n\t\tif(!diagonalized_)\n\t\t{\n\t\t\tdiagonalize();\n\t\t}\n\n\t\tEigen::VectorXcd v = exp(x * evals_.array());\n\t\treturn evecs_ * v.asDiagonal() * evecs_.adjoint();\n\t}\n};\n\n} // namespace yavque\n", "meta": {"hexsha": "9a6a4c695723fe6ce5b7213aaa43b21fb3712fc8", "size": 1628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Operators/DenseHermitianMatrix.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "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/yavque/Operators/DenseHermitianMatrix.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "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/yavque/Operators/DenseHermitianMatrix.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "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": 16.7835051546, "max_line_length": 75, "alphanum_fraction": 0.6566339066, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6709373427190374}}
{"text": "//  (C) Copyright John Maddock 2019.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Contains Quickbook snippets used by boost/libs/multiprecision/doc/multiprecision.qbk,\n// section Literal Types and constexpr Support.\n\n#include <iostream>\n#include <boost/config.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n//[constexpr_circle\n#include <boost/math/constants/constants.hpp> // For constant pi with full precision of type T.\n// using  boost::math::constants::pi;\n\ntemplate <class T>\ninline constexpr T circumference(T radius)\n{\n   return 2 * boost::math::constants::pi<T>() * radius;\n}\n\ntemplate <class T>\ninline constexpr T area(T radius)\n{\n   return boost::math::constants::pi<T>() * radius * radius;\n}\n//] [/constexpr_circle]\n\ntemplate <class T, unsigned Order>\nstruct const_polynomial\n{\n public:\n   T data[Order + 1];\n\n public:\n   constexpr const_polynomial(T val = 0) : data{val} {}\n   constexpr const_polynomial(const std::initializer_list<T>& init) : data{}\n   {\n      if (init.size() > Order + 1)\n         throw std::range_error(\"Too many initializers in list!\");\n      for (unsigned i = 0; i < init.size(); ++i)\n         data[i] = init.begin()[i];\n   }\n   constexpr T& operator[](std::size_t N)\n   {\n      return data[N];\n   }\n   constexpr const T& operator[](std::size_t N) const\n   {\n      return data[N];\n   }\n   template <class U>\n   constexpr T operator()(U val)const\n   {\n      T result = data[Order];\n      for (unsigned i = Order; i > 0; --i)\n      {\n         result *= val;\n         result += data[i - 1];\n      }\n      return result;\n   }\n   constexpr const_polynomial<T, Order - 1> derivative() const\n   {\n      const_polynomial<T, Order - 1> result;\n      for (unsigned i = 1; i <= Order; ++i)\n      {\n         result[i - 1] = (*this)[i] * i;\n      }\n      return result;\n   }\n   constexpr const_polynomial operator-()\n   {\n      const_polynomial t(*this);\n      for (unsigned i = 0; i <= Order; ++i)\n         t[i] = -t[i];\n      return t;\n   }\n   template <class U>\n   constexpr const_polynomial& operator*=(U val)\n   {\n      for (unsigned i = 0; i <= Order; ++i)\n         data[i] = data[i] * val;\n      return *this;\n   }\n   template <class U>\n   constexpr const_polynomial& operator/=(U val)\n   {\n      for (unsigned i = 0; i <= Order; ++i)\n         data[i] = data[i] / val;\n      return *this;\n   }\n   template <class U>\n   constexpr const_polynomial& operator+=(U val)\n   {\n      data[0] += val;\n      return *this;\n   }\n   template <class U>\n   constexpr const_polynomial& operator-=(U val)\n   {\n      data[0] -= val;\n      return *this;\n   }\n};\n\ntemplate <class T, unsigned Order1, unsigned Order2>\ninline constexpr const_polynomial<T, (Order1 > Order2 ? Order1 : Order2)> operator+(const const_polynomial<T, Order1>& a, const const_polynomial<T, Order2>& b)\n{\n   if\n      constexpr(Order1 > Order2)\n      {\n         const_polynomial<T, Order1> result(a);\n         for (unsigned i = 0; i <= Order2; ++i)\n            result[i] += b[i];\n         return result;\n      }\n   else\n   {\n      const_polynomial<T, Order2> result(b);\n      for (unsigned i = 0; i <= Order1; ++i)\n         result[i] += a[i];\n      return result;\n   }\n}\ntemplate <class T, unsigned Order1, unsigned Order2>\ninline constexpr const_polynomial<T, (Order1 > Order2 ? Order1 : Order2)> operator-(const const_polynomial<T, Order1>& a, const const_polynomial<T, Order2>& b)\n{\n   if\n      constexpr(Order1 > Order2)\n      {\n         const_polynomial<T, Order1> result(a);\n         for (unsigned i = 0; i <= Order2; ++i)\n            result[i] -= b[i];\n         return result;\n      }\n   else\n   {\n      const_polynomial<T, Order2> result(b);\n      for (unsigned i = 0; i <= Order1; ++i)\n         result[i] = a[i] - b[i];\n      return result;\n   }\n}\ntemplate <class T, unsigned Order1, unsigned Order2>\ninline constexpr const_polynomial<T, Order1 + Order2> operator*(const const_polynomial<T, Order1>& a, const const_polynomial<T, Order2>& b)\n{\n   const_polynomial<T, Order1 + Order2> result;\n   for (unsigned i = 0; i <= Order1; ++i)\n   {\n      for (unsigned j = 0; j <= Order2; ++j)\n      {\n         result[i + j] += a[i] * b[j];\n      }\n   }\n   return result;\n}\ntemplate <class T, unsigned Order, class U>\ninline constexpr const_polynomial<T, Order> operator*(const const_polynomial<T, Order>& a, const U& b)\n{\n   const_polynomial<T, Order> result(a);\n   for (unsigned i = 0; i <= Order; ++i)\n   {\n      result[i] *= b;\n   }\n   return result;\n}\ntemplate <class U, class T, unsigned Order>\ninline constexpr const_polynomial<T, Order> operator*(const U& b, const const_polynomial<T, Order>& a)\n{\n   const_polynomial<T, Order> result(a);\n   for (unsigned i = 0; i <= Order; ++i)\n   {\n      result[i] *= b;\n   }\n   return result;\n}\ntemplate <class T, unsigned Order, class U>\ninline constexpr const_polynomial<T, Order> operator/(const const_polynomial<T, Order>& a, const U& b)\n{\n   const_polynomial<T, Order> result;\n   for (unsigned i = 0; i <= Order; ++i)\n   {\n      result[i] /= b;\n   }\n   return result;\n}\n\n//[hermite_example\ntemplate <class T, unsigned Order>\nclass hermite_polynomial\n{\n   const_polynomial<T, Order> m_data;\n\n public:\n   constexpr hermite_polynomial() : m_data(hermite_polynomial<T, Order - 1>().data() * const_polynomial<T, 1>{0, 2} - hermite_polynomial<T, Order - 1>().data().derivative())\n   {\n   }\n   constexpr const const_polynomial<T, Order>& data() const\n   {\n      return m_data;\n   }\n   constexpr const T& operator[](std::size_t N)const\n   {\n      return m_data[N];\n   }\n   template <class U>\n   constexpr T operator()(U val)const\n   {\n      return m_data(val);\n   }\n};\n//] [/hermite_example]\n\n//[hermite_example2\ntemplate <class T>\nclass hermite_polynomial<T, 0>\n{\n   const_polynomial<T, 0> m_data;\n\n public:\n   constexpr hermite_polynomial() : m_data{1} {}\n   constexpr const const_polynomial<T, 0>& data() const\n   {\n      return m_data;\n   }\n   constexpr const T& operator[](std::size_t N) const\n   {\n      return m_data[N];\n   }\n   template <class U>\n   constexpr T operator()(U val)\n   {\n      return m_data(val);\n   }\n};\n\ntemplate <class T>\nclass hermite_polynomial<T, 1>\n{\n   const_polynomial<T, 1> m_data;\n\n public:\n   constexpr hermite_polynomial() : m_data{0, 2} {}\n   constexpr const const_polynomial<T, 1>& data() const\n   {\n      return m_data;\n   }\n   constexpr const T& operator[](std::size_t N) const\n   {\n      return m_data[N];\n   }\n   template <class U>\n   constexpr T operator()(U val)\n   {\n      return m_data(val);\n   }\n};\n//] [/hermite_example2]\n\n\nvoid test_double()\n{\n   constexpr double radius = 2.25;\n   constexpr double c      = circumference(radius);\n   constexpr double a      = area(radius);\n\n   std::cout << \"Circumference = \" << c << std::endl;\n   std::cout << \"Area = \" << a << std::endl;\n\n   constexpr const_polynomial<double, 2> pa = {3, 4};\n   constexpr const_polynomial<double, 2> pb = {5, 6};\n   static_assert(pa[0] == 3);\n   static_assert(pa[1] == 4);\n   constexpr auto pc = pa * 2;\n   static_assert(pc[0] == 6);\n   static_assert(pc[1] == 8);\n   constexpr auto pd = 3 * pa;\n   static_assert(pd[0] == 3 * 3);\n   static_assert(pd[1] == 4 * 3);\n   constexpr auto pe = pa + pb;\n   static_assert(pe[0] == 3 + 5);\n   static_assert(pe[1] == 4 + 6);\n   constexpr auto pf = pa - pb;\n   static_assert(pf[0] == 3 - 5);\n   static_assert(pf[1] == 4 - 6);\n   constexpr auto pg = pa * pb;\n   static_assert(pg[0] == 15);\n   static_assert(pg[1] == 38);\n   static_assert(pg[2] == 24);\n\n   #if defined(__clang__) && (__clang_major__ < 6)\n   #else\n   constexpr hermite_polynomial<double, 2> h1;\n   static_assert(h1[0] == -2);\n   static_assert(h1[1] == 0);\n   static_assert(h1[2] == 4);\n\n   constexpr hermite_polynomial<double, 3> h3;\n   static_assert(h3[0] == 0);\n   static_assert(h3[1] == -12);\n   static_assert(h3[2] == 0);\n   static_assert(h3[3] == 8);\n\n   constexpr hermite_polynomial<double, 9> h9;\n   static_assert(h9[0] == 0);\n   static_assert(h9[1] == 30240);\n   static_assert(h9[2] == 0);\n   static_assert(h9[3] == -80640);\n   static_assert(h9[4] == 0);\n   static_assert(h9[5] == 48384);\n   static_assert(h9[6] == 0);\n   static_assert(h9[7] == -9216);\n   static_assert(h9[8] == 0);\n   static_assert(h9[9] == 512);\n\n   static_assert(h9(0.5) == 6481);\n   #endif\n}\n\nvoid test_float128()\n{\n#ifdef BOOST_HAS_FLOAT128\n//[constexpr_circle_usage\n\n   using boost::multiprecision::float128;\n\n   constexpr float128 radius = 2.25;\n   constexpr float128 c      = circumference(radius);\n   constexpr float128 a      = area(radius);\n\n   std::cout << \"Circumference = \" << c << std::endl;\n   std::cout << \"Area = \" << a << std::endl;\n\n //]   [/constexpr_circle_usage]\n\n\n   constexpr hermite_polynomial<float128, 2> h1;\n   static_assert(h1[0] == -2);\n   static_assert(h1[1] == 0);\n   static_assert(h1[2] == 4);\n\n   constexpr hermite_polynomial<float128, 3> h3;\n   static_assert(h3[0] == 0);\n   static_assert(h3[1] == -12);\n   static_assert(h3[2] == 0);\n   static_assert(h3[3] == 8);\n\n   //[hermite_example3\n   constexpr hermite_polynomial<float128, 9> h9;\n   //\n   // Verify that the polynomial's coefficients match the known values:\n   //\n   static_assert(h9[0] == 0);\n   static_assert(h9[1] == 30240);\n   static_assert(h9[2] == 0);\n   static_assert(h9[3] == -80640);\n   static_assert(h9[4] == 0);\n   static_assert(h9[5] == 48384);\n   static_assert(h9[6] == 0);\n   static_assert(h9[7] == -9216);\n   static_assert(h9[8] == 0);\n   static_assert(h9[9] == 512);\n   //\n   // Define an abscissa value to evaluate at:\n   constexpr float128 abscissa(0.5);\n   //\n   // Evaluate H_9(0.5) using all constexpr arithmetic, and check that it has the expected result:\n   static_assert(h9(abscissa) == 6481);\n   //]\n#endif\n}\n\nint main()\n{\n   test_double();\n   test_float128();\n   std::cout << \"Done!\" << std::endl;\n}\n", "meta": {"hexsha": "ff2244e140058bda7f89187ae274774c11076719", "size": 9922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/multiprecision/example/constexpr_float_arithmetic_examples.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/constexpr_float_arithmetic_examples.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": "Libs/boost_1_76_0/libs/multiprecision/example/constexpr_float_arithmetic_examples.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "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": 25.8385416667, "max_line_length": 173, "alphanum_fraction": 0.6120741786, "num_tokens": 2953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.793105951184112, "lm_q1q2_score": 0.6709219937101193}}
{"text": "#ifndef SPHEP_GENERATOR_HH\n#define SPHEP_GENERATOR_HH\n\n#include <Eigen/Dense>\n\nnamespace sphep\n{\n  // compute force from b to a\n  template <class V>\n  V computeForce(const V& a, const V& b)\n  {\n    // compute direction of force a-b\n    auto diff = a - b;\n    // scale force by norm(diff)^3\n    typename V::Scalar diffsq = diff.squaredNorm();\n    return diff / (diffsq * std::sqrt(diffsq));\n  }\n\n  // update the veloctiy in an explicit euler fashion\n  template <class V>\n  void updateVelocity(const std::vector<V>& points, typename V::Scalar dt, std::vector<V>& velocity)\n  {\n    assert(points.size() == velocity.size());\n\n    for (std::size_t i = 0; i < points.size(); ++i) {\n      for (std::size_t j = i + 1; j < points.size(); ++j) {\n        // compute force from j to i\n        V diff = computeForce(points[i], points[j]);\n        // update velocity of i and j with dt*diff (using action = reaction)\n        velocity[i] += dt * diff;\n        velocity[j] -= dt * diff;\n      }\n    }\n  }\n\n  // redistribute the given points on the unit sphere, such that they are\n  // more evenly distributed\n  template <class V>\n  void optimizePointsOnUnitSphere(std::vector<V>& points, unsigned int iterations,\n                                  typename V::Scalar dist, typename V::Scalar dt)\n  {\n    const std::size_t N = points.size();\n    std::vector<V> velocity(points.size(), V::Zero());\n    for (unsigned int iter = 0; iter < iterations; ++iter) {\n      // update velocity (explicit euler)\n      updateVelocity(points, dt, velocity);\n      // update points (explicit euler)\n      typename V::Scalar globalDist = 0.0;\n      for (std::size_t i = 0; i < N; ++i) {\n        V oldPoint(points[i]);\n        // update point\n        points[i] += dt * velocity[i];\n        // fetch p_i back onto sphere\n        points[i] /= points[i].norm();\n        // compute distance between old and newpoint\n        globalDist += (oldPoint - points[i]).norm();\n      }\n      // stop iteration if global update is less than threshold\n      if (globalDist < dist) {\n        break;\n      }\n    }\n  }\n\n  // non-specialized struct for generating random points on the unit sphere\n  template <class Vector>\n  struct PointOnUnitSphereGenerator;\n\n  // three dimensional spcialization of the random points on unit sphere\n  // generator. Uses sphere coordinates.\n  template <class T>\n  struct PointOnUnitSphereGenerator<Eigen::Matrix<T, 3, 1> >\n  {\n    typedef Eigen::Matrix<T, 3, 1> Vector;\n\n    Vector operator()() const\n    {\n      // generate random sphere coordinates between [0,2*PI]\n      T theta = 2.0 * M_PI * static_cast<T>(std::rand()) / RAND_MAX;\n      T phi = 2.0 * M_PI * static_cast<T>(std::rand()) / RAND_MAX;\n      // transform sphere coordinates to cartesian\n      Vector p;\n      p << std::sin(theta) * std::cos(phi), std::sin(theta) * std::sin(phi), std::cos(theta);\n      return p;\n    }\n  };\n\n  // perform the operation axpy on a vector\n  template <class Vector>\n  struct ScaleAndTranslateFunctor\n  {\n    typedef typename Vector::Scalar Scalar;\n\n    ScaleAndTranslateFunctor(const Scalar& factor_ = Scalar(1.0),\n                             const Vector& offset_ = Vector::Zero())\n        : factor(factor_)\n        , offset(offset_)\n    {\n    }\n\n    void operator()(Vector& vector) const { vector = vector * factor + offset; }\n\n    Scalar factor;\n    Vector offset;\n  };\n\n  // generator more or less evenly distributed points on a sphere\n  template <class Vector>\n  void generatePoints(unsigned int N, std::vector<Vector>& points,\n                      const Vector& center = Vector::Zero(), typename Vector::Scalar radius = 1.0,\n                      unsigned int iterations = 500, typename Vector::Scalar dist = 1e-3,\n                      typename Vector::Scalar dt = 0.1)\n  {\n    typedef typename Vector::Scalar Scalar;\n    // construct vector\n    std::vector<Vector> newPoints;\n    newPoints.reserve(N);\n\n    // generate N points on unit sphere\n    std::generate_n(std::back_inserter(newPoints), N, PointOnUnitSphereGenerator<Vector>());\n    // optimize these points on unit sphere\n    optimizePointsOnUnitSphere(newPoints, iterations, dist, dt);\n\n    // map from unit sphere to radius-sphere at center\n    std::for_each(newPoints.begin(), newPoints.end(),\n                  ScaleAndTranslateFunctor<Vector>(radius, center));\n\n    // copy the new vectors into the output\n    std::copy(newPoints.begin(), newPoints.end(), std::back_inserter(points));\n  }\n}\n\n#endif // SPHEP_GENERATOR_HH\n", "meta": {"hexsha": "495d897cd1d4d0de3751dc742f042b8b469f154e", "size": 4471, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/include/sphep/generator.hh", "max_stars_repo_name": "anuessing/sphep", "max_stars_repo_head_hexsha": "1942eb36f48181fbef32c3292bbde6d332b59703", "max_stars_repo_licenses": ["MIT"], "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/sphep/generator.hh", "max_issues_repo_name": "anuessing/sphep", "max_issues_repo_head_hexsha": "1942eb36f48181fbef32c3292bbde6d332b59703", "max_issues_repo_licenses": ["MIT"], "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/sphep/generator.hh", "max_forks_repo_name": "anuessing/sphep", "max_forks_repo_head_hexsha": "1942eb36f48181fbef32c3292bbde6d332b59703", "max_forks_repo_licenses": ["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.3656716418, "max_line_length": 100, "alphanum_fraction": 0.6264817714, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6708695281580073}}
{"text": "\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <cassert>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <algorithm>\n\n#include \"aux/eigen2hdf.hpp\"\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/h2n_1d.hpp\"\n#include \"spectral/hermite_to_nodal.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n\n//#include <deal.II/base/exceptions.h>\n\nusing namespace std;\nusing namespace boltzmann;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n  typedef Eigen::VectorXd vec_t;\n\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n\n  string fname = \"spectral_basis.desc\";\n  cout << \"reading `\" << fname << \"` from disk.\\n\";\n  SpectralBasisFactoryKS::create(polar_basis, fname);\n\n  int K = spectral::get_max_k(polar_basis) + 1;\n  int N = polar_basis.n_dofs();\n\n  // create basis files\n  typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, K, 2);\n  cout << \"Hermite basis size: \" << hermite_basis.n_dofs() << endl;\n  cout << \"Polar basis size: \" << polar_basis.n_dofs() << endl;\n\n  // polar 2 hermite\n  Polar2Hermite<polar_basis_t, hermite_basis_t> P2H(polar_basis, hermite_basis);\n\n  typedef Eigen::MatrixXd mat_t;\n  // hermite to nodal\n  Hermite2Nodal<hermite_basis_t> h2n(\n      hermite_basis, K, [K](mat_t& m1, mat_t& m2) { H2N_1d<>::create(m1, m2, K); });\n\n  // debug\n  auto& M = h2n.get_h2n();\n  cout << \"M := H2N-matrix\\n\";\n  cout << \"M.T * M\\n\";\n  Eigen::MatrixXd O = M.transpose() * M;\n\n  double MtM_diff = (O - Eigen::MatrixXd::Identity(O.rows(), O.cols())).cwiseAbs().sum();\n  if (MtM_diff > 1e-13 * O.rows() * O.cols()) {\n    cout << \"diff: \" << MtM_diff << \"\\n\";\n    O = (O.array().cwiseAbs() > 1e-15).select(O, Eigen::ArrayXXd::Zero(O.rows(), O.cols()));\n    cout << O << endl;\n  }\n\n  cout << \"---------- Test: P->H->N->H->P  ----------\"\n       << \"\\n\";\n  fname = \"coefficients.h5\";\n  vec_t cp(N);  // polar coefficients\n  if (!boost::filesystem::exists(fname)) {\n    cp.setOnes();\n  } else {\n    hid_t h5_init = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n    eigen2hdf::load(h5_init, \"coeffs\", cp);\n    H5Fclose(h5_init);\n  }\n\n  assert(polar_basis.n_dofs() == cp.size());\n\n  // Transform Polar to Hermite basis\n  vec_t ch = cp;\n  P2H.to_hermite(ch, cp);\n\n  // Transform Hermite to Nodal basis\n  Eigen::MatrixXd cn;\n  h2n.to_nodal(cn, ch);\n  // Transform Nodal to Hermite basis\n  h2n.to_hermite(ch.data(), cn);\n  // Tranform Hermite to Polar basis\n  vec_t cp2(N);\n  P2H.to_polar(cp2, ch);\n\n  /* hid_t h5f = H5Fcreate(\"out.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); */\n  /* eigen2hdf::save(h5f, \"coeffs_nodal\", cn); */\n  /* eigen2hdf::save(h5f, \"coeffs_hermite\", ch); */\n  /* eigen2hdf::save(h5f, \"coeffs\", cp2); */\n  /* H5Fclose(h5f); */\n\n  vec_t diff = (cp2 - cp).rowwise().squaredNorm();\n  if (diff.sum() > 1e-10) {\n    cout << \"diff\\n\";\n    cout << diff << endl;\n  } else {\n    cout << \"sum(diff) \" << diff.sum() << endl;\n  }\n\n  // int i,j;\n  // cout << \"max diff: \" << diff.maxCoeff(&i, &j) << \" at \" << i << \", \" << j << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "26190ac245db8d4c9c36f3ccd0bc1cccfc50aa07", "size": 3339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/H2N/main.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/H2N/main.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/H2N/main.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2894736842, "max_line_length": 92, "alphanum_fraction": 0.6504941599, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636752, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6708695150147901}}
{"text": "// This is C++ code for discretizing AR(1) process by using Rouwenhorst method (1995)\n// written on 2017/10/17\n// z' = rho*z+e e~N(0,(sig_e)^2)\n//\n// INPUTS (through Terminal)\n// N:     Number of grids\n// rho:   Coeffecient of AR(1) process z'=mew+rho*z+e, e~N(0,sigmasq)\n// sig_e: Std of innovation, e, in AR(1) process\n//\n// OUTPUT\n// vZ:    grids\n// mPI:   transition prob. matrix\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <random>\n#include <armadillo>  // YOU SHOULD INSTALL \"armadillo\" BEFORE USING THIS FILE\n\n\n//////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////\n//                          MAIN PART\n//////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////\n\nint main(int argc, char* argv[])\n{\n  ///////////////////////////////////////////////////////////\n  // 1. Basic Parameters\n  ///////////////////////////////////////////////////////////\n\n  // Ex. Standard quarterly calibration for pruductivity\n  // process of the US economy\n\n  int     N = 5;          // Number of grids, N\n  double  rho = 0.95;     // AR(1) coefficient\n  double  sig_e = 0.007;  // std of innovation\n\n  ///////////////////////////////////////////////////////////\n  // 2. Generating grids && Parameterization\n  ///////////////////////////////////////////////////////////\n\n  double  sig_z = sqrt(pow(sig_e,2)/(1-pow(rho,2)));  // std of AR(1) process r.v.\n  double  z_max = sig_z*sqrt(N-1);                    // Max grid\n  double  z_min = -z_max;                             // Min grid\n  double  p = (1+rho)/2, q = p;                       // prob. parameters\n\n  arma::vec vZ = arma::linspace<arma::vec>(z_min,z_max,N); // Grid vector 1*N\n\n  ////////////////////////////////////////////////////////////\n  // 3. Transition matrix\n  ////////////////////////////////////////////////////////////\n\n  arma::mat mPI_old = {{p,1-p},{1-q,q}}; // Initial PI\n\n  // for recursive computation\n  arma::mat mPI_new(3,3);\n  arma::mat mPI_new1(3,3);\n  arma::mat mPI_new2(3,3);\n  arma::mat mPI_new3(3,3);\n  arma::mat mPI_new4(3,3);\n\n  for (int i=3;i<N+1; i++)\n  {\n\n    mPI_new.zeros(i,i);\n    mPI_new1.zeros(i,i);\n    mPI_new2.zeros(i,i);\n    mPI_new3.zeros(i,i);\n    mPI_new4.zeros(i,i);\n\n    mPI_new1.submat(0,0,i-2,i-2) = mPI_old;\n    mPI_new2.submat(0,1,i-2,i-1) = mPI_old;\n    mPI_new3.submat(1,0,i-1,i-2) = mPI_old;\n    mPI_new4.submat(1,1,i-1,i-1) = mPI_old;\n\n    mPI_new = p*mPI_new1 + (1-p)*mPI_new2 + (1-q)*mPI_new3 + q*mPI_new4;\n    mPI_new.submat(1,0,i-2,i-1) = 0.5 * mPI_new.submat(1,0,i-2,i-1); // divide by 2\n\n    mPI_old.resize(i,i);\n    mPI_old = mPI_new;\n\n  }\n\n  ////////////////////////////////////////////////////////////\n  // 4. Display result with 4 decimals\n  ////////////////////////////////////////////////////////////\n\n  std::cout << \"Grids are\\n\";\n  for (int i=0; i<N; i++)\n  {\n    std::cout << std::fixed << std::setprecision(4) << vZ(i) << \" \";\n  }\n\n  std::cout << \"\\n \\nTransition Prob Matrix is \\n\";\n  for (int i = 0; i < N; i++)\n  {\n    for (int j = 0; j < N; j++)\n    {\n      if (j == N-1)\n      {\n        std::cout << std::fixed << std::setprecision(4) << mPI_new(i,j) << '\\n';\n      }\n      else\n      {\n        std::cout << std::fixed << std::setprecision(4) << mPI_new(i,j) << ' ';\n      }\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "5087670788d6c4af21d5b11aa02c8b002a35d18c", "size": 3380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rouwenhorst.cpp", "max_stars_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_stars_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rouwenhorst.cpp", "max_issues_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_issues_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rouwenhorst.cpp", "max_forks_repo_name": "Akihisa-Kato/discretizing_stochastic_process", "max_forks_repo_head_hexsha": "5166cf882b45af41047bdb2111bb5ef2d63ed760", "max_forks_repo_licenses": ["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.9115044248, "max_line_length": 85, "alphanum_fraction": 0.4340236686, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6708695059054003}}
{"text": "#include <iostream>\n#include <string>\n#include <armadillo>\n#include <time.h>\n#include \"ga.h\"\n#include \"simpleNN.h\"\n\n\nusing namespace std;\nusing namespace arma;\n\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nvec sigmoid(vec inp){\n    return 1/(1 + exp(-inp));\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nvec myTanh(vec inp){\n    return tanh(inp);\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nrowvec sigmoidR(rowvec inp){\n    return 1/(1 + exp(-inp));\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nrowvec myTanhR(rowvec inp){\n    return tanh(inp);\n}\n//------------------------------------------------------------------------------------------------------------------------\nmat simpleNNmat(mat X, vec inp, mat inpWeights , cube weights, mat outWeights ,vec inpBiases, mat biases, vec outBiases){\n\n    vec buffVec;\n    buffVec = sigmoid(inpWeights*inp + inpBiases);\n\n    int largeI = 0;\n\n    mat Y(X.n_rows, outBiases.n_elem);\n\n\n// Adding Data from values from x to each type of weights and biases.\n    for(int i = 0; i < X.n_rows; i++){\n\n        for(int dummyX = 0; dummyX < inpWeights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < inpWeights.n_cols; dummyY++){\n                inpWeights.at(dummyX,dummyY) = X.at(i,largeI); \n                largeI++;\n            }\n        }\n\n        for(int dummyX = 0; dummyX < weights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < weights.n_cols; dummyY++){\n                for(int dummyZ = 0; dummyZ < weights.n_slices; dummyZ++){\n                    weights.at(dummyX,dummyY,dummyZ) = X.at(i,largeI); \n                    largeI++;\n                }\n            }\n        }\n\n        for(int dummyX = 0; dummyX < outWeights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < outWeights.n_cols; dummyY++){\n                outWeights.at(dummyX,dummyY) = X.at(i,largeI); \n                largeI++;\n            }\n        }\n\n\n        for(int dummyX = 0; dummyX < inpBiases.n_rows; dummyX++){\n            inpBiases.at(dummyX) = X.at(i,largeI); \n            largeI++;\n        }\n\n\n        for(int dummyX = 0; dummyX < biases.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < biases.n_cols; dummyY++){\n                biases.at(dummyX,dummyY) = X.at(i,largeI); \n                largeI++;\n            }\n        }\n\n        for(int dummyX = 0; dummyX < outBiases.n_rows; dummyX++){\n            outBiases.at(dummyX) = X.at(i,largeI); \n            largeI++;\n        }\n\n// Feed Forward into hidden.\n        buffVec = myTanh(inpWeights*inp + inpBiases);\n// Feed Forward each hidden Layer.\n        for(int l = 0; l < weights.n_slices; l++){\n            buffVec = myTanh(weights.slice(l)*buffVec + biases.col(l));\n          }\n// Feed Forward each hidden Layer.\n          Y.row(i) = sigmoidR((outWeights*buffVec).t() + outBiases.t());\n   largeI = 0;\n   }\n\n      return Y;\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nvec simpleNNvec(vec x, vec inp, mat inpWeights , cube weights, mat outWeights ,vec inpBiases, mat biases, vec outBiases){ \n\n    vec buffVec;\n    buffVec = sigmoid(inpWeights*inp + inpBiases);\n\n    int largeI = 0;\n\n    vec y(outBiases.n_elem);\n\n// Adding Data from values from x to each type of weights and biases.\n        for(int dummyX = 0; dummyX < inpWeights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < inpWeights.n_cols; dummyY++){\n                inpWeights.at(dummyX,dummyY) = x.at(largeI); \n                largeI++;\n            }\n        }\n\n\n        for(int dummyX = 0; dummyX < weights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < weights.n_cols; dummyY++){\n                for(int dummyZ = 0; dummyZ < weights.n_slices; dummyZ++){\n\n                    weights.at(dummyX,dummyY,dummyZ) = x.at(largeI); \n                    largeI++;\n                }\n            }\n        }\n\n\n        for(int dummyX = 0; dummyX < outWeights.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < outWeights.n_cols; dummyY++){\n                outWeights.at(dummyX,dummyY) = x.at(largeI); \n                largeI++;\n            }\n        }\n\n\n        for(int dummyX = 0; dummyX < inpBiases.n_rows; dummyX++){\n            inpBiases.at(dummyX) = x.at(largeI); \n            largeI++;\n        }\n\n\n        for(int dummyX = 0; dummyX < biases.n_rows; dummyX++){\n            for(int dummyY = 0; dummyY < biases.n_cols; dummyY++){\n                biases.at(dummyX,dummyY) = x.at(largeI); \n                largeI++;\n            }\n        }\n\n        for(int dummyX = 0; dummyX < outBiases.n_rows; dummyX++){\n            outBiases.at(dummyX) = x.at(largeI); \n            largeI++;\n        }\n\n// Feed Forward into hidden.\n        buffVec = myTanh(inpWeights*inp + inpBiases);\n// Feed Forward each hidden Layer.\n        for(int l = 0; l < weights.n_slices; l++){\n            buffVec = myTanh(weights.slice(l)*buffVec + biases.col(l));\n          }\n// Feed Forward  final Layer.\n          y = sigmoid((outWeights*buffVec)  + outBiases);\n      return y;\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6d7e0f9fdedf87c572659203d752274e2abc08d8", "size": 6340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simpleNN.cpp", "max_stars_repo_name": "Aki78/PongAI", "max_stars_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_stars_repo_licenses": ["MIT"], "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/simpleNN.cpp", "max_issues_repo_name": "Aki78/PongAI", "max_issues_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_issues_repo_licenses": ["MIT"], "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/simpleNN.cpp", "max_forks_repo_name": "Aki78/PongAI", "max_forks_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T09:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T09:44:29.000Z", "avg_line_length": 34.4565217391, "max_line_length": 122, "alphanum_fraction": 0.3895899054, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9504109770159683, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6707858378698163}}
{"text": "/*\n * Copyright 2017 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n */\n\n/*\n * File:   CoordinateTransformTest.cpp\n * Author: glm,jordan\n *\n */\n\n#include \"catch.hpp\"\n#include \"../src/math/CoordinateTransform.hpp\"\n#include <Eigen/Dense>\n#include \"../src/Position.hpp\"\n#include <math.h>\n\n#define POSITION_PRECISION 0.00000001\n\n/**Test if the coordinate transform works*/\nTEST_CASE(\"Coordinate Transform Test\") {\n\n    // prime meridian, equator, on ellipsoid\n    Position primeMeridianEquator(0, 0, 0, 0);\n\n    Eigen::Vector3d testPositionECEF;\n    CoordinateTransform::getPositionECEF(testPositionECEF,primeMeridianEquator);\n\n    Eigen::Vector3d expectedPositionECEF;\n    expectedPositionECEF << 6378137.0 , 0, 0;\n\n    REQUIRE( testPositionECEF.isApprox(expectedPositionECEF, POSITION_PRECISION) );\n\n    // North Pole on ellipsoid\n    Position northPole(0, 90, 0, 0);\n    Eigen::Vector3d northPoleECEF;\n    CoordinateTransform::getPositionECEF(northPoleECEF,northPole);\n\n    Eigen::Vector3d expectedNorthPoleECEF;\n    expectedNorthPoleECEF << 0, 0, 6356752.3142; // WGS 84 polar semi-minor axis\n\n    double northPolePrecision = 0.00000001;\n    REQUIRE( northPoleECEF.isApprox(expectedNorthPoleECEF, northPolePrecision) );\n\n    \n\n}\n\n/**test if the conversion between ECEF and longitude latitude height works*/\nTEST_CASE(\"Conversions between ECEF and Longitude Latitude Height\") {\n    Position testPosition(0, 48, -68, 10);\n\n    Eigen::Vector3d testPositionECEF;\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    Position expectedPosition(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, 60, 79, -100);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, -60, -79, 100);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, -70, 48, 90);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, 70, 60, 80);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, 0, 0, 0);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, -80, -40, -50);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n    \n    testPosition = Position(0, 87, -43, -59);\n\n    CoordinateTransform::getPositionECEF(testPositionECEF,testPosition);\n\n    expectedPosition = Position(0,0,0,0);\n    CoordinateTransform::convertECEFToLongitudeLatitudeElevation(testPositionECEF, expectedPosition);\n\n    std::cout << \"expectedPosition:\" << std::endl;\n    std::cout << expectedPosition << std::endl;\n\n    REQUIRE(abs((roundf(expectedPosition.getLatitude()*100)/100)-testPosition.getLatitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getLongitude()*100)/100)-testPosition.getLongitude())<1e-10);\n    REQUIRE(abs((roundf(expectedPosition.getEllipsoidalHeight()*100)/100)-testPosition.getEllipsoidalHeight())<1e-10);\n}\n\n/**Test if the conversion between spherical to cartesian works*/\nTEST_CASE(\"Conversion between spherical to cartesian\"){\n    Eigen::Vector3d v;\n\n    CoordinateTransform::spherical2cartesian(v,45,45,1);\n\n    REQUIRE(abs(v(0) - 0.5) < 0.000000001);\n    REQUIRE(abs(v(1) - 0.5) < 0.000000001);\n    REQUIRE(abs(v(2) - 0.707107) < 0.000001);\n}\n\n/**Test if the conversion between sonar to cartesian works*/\nTEST_CASE(\"Conversion between sonar to cartesian\"){\n    Eigen::Vector3d v;\n    CoordinateTransform::sonar2cartesian(v,90,0,1);\n    REQUIRE(std::abs(v(0)-1)<1e-10);\n    REQUIRE(std::abs(v(1)-0)<1e-10);\n    REQUIRE(std::abs(v(2)-0)<1e-10);\n    CoordinateTransform::sonar2cartesian(v,0,90,1);\n    REQUIRE(std::abs(v(0)-0)<1e-10);\n    REQUIRE(std::abs(v(1)-1)<1e-10);\n    REQUIRE(std::abs(v(2)-0)<1e-10);\n    CoordinateTransform::sonar2cartesian(v,0,0,1);\n    REQUIRE(std::abs(v(0)-0)<1e-10);\n    REQUIRE(std::abs(v(1)-0)<1e-10);\n    REQUIRE(std::abs(v(2)-1)<1e-10);\n}\n\n/**Test if the conversion between NED to ECEF position works*/\nTEST_CASE(\"Conversion between NED to ECEF position\")\n{\n    Position nedPos(0,0,0,0);\n    Eigen::Matrix3d mECEF;\n    CoordinateTransform::ned2ecef(mECEF,nedPos);\n    Eigen::Matrix3d matrixSearch;\n    matrixSearch << 0,0,-1,\n                    0,1,0,\n                    1,0,0;\n    REQUIRE(mECEF == matrixSearch);\n    \n    nedPos = Position(0,16,19,0);\n    CoordinateTransform::ned2ecef(mECEF,nedPos);\n    matrixSearch << -0.260620240054051,-0.325568154457157,-0.908890789521783,\n                    -0.0897387452327910,0.945518575599317,-0.312956196296995,\n                    0.961261695938319,0,-0.275637355816999;\n    REQUIRE(abs(mECEF(0,0)-matrixSearch(0,0))< 1e-10);\n    REQUIRE(abs(mECEF(0,1)-matrixSearch(0,1))< 1e-10);\n    REQUIRE(abs(mECEF(0,2)-matrixSearch(0,2))< 1e-10);\n    REQUIRE(abs(mECEF(1,0)-matrixSearch(1,0))< 1e-10);\n    REQUIRE(abs(mECEF(1,1)-matrixSearch(1,1))< 1e-10);\n    REQUIRE(abs(mECEF(1,2)-matrixSearch(1,2))< 1e-10);\n    REQUIRE(abs(mECEF(2,0)-matrixSearch(2,0))< 1e-10);\n    REQUIRE(abs(mECEF(2,1)-matrixSearch(2,1))< 1e-10);\n    REQUIRE(abs(mECEF(2,2)-matrixSearch(2,2))< 1e-10);\n}\n\n/**Test if the conversion between Terrestial to Geodetic works*/\nTEST_CASE(\"Conversion between Terrestial to Geodetic\")\n{\n    Position pos(0,0,0,0);\n    Eigen::Matrix3d mGeo;\n    CoordinateTransform::getTerrestialToLocalGeodeticReferenceFrameMatrix(mGeo,pos);\n    Eigen::Matrix3d matrixSearch;\n    matrixSearch << 0,0,1,\n                    0,1,0,\n                    -1,0,0;\n    REQUIRE(mGeo == matrixSearch);\n    \n    pos = Position(0,45,56,0);\n    CoordinateTransform::getTerrestialToLocalGeodeticReferenceFrameMatrix(mGeo,pos);\n    matrixSearch << -0.395409094035560,-0.586218089412104,0.707106781186548,\n                    -0.829037572555042,0.559192903470747,0,\n                    -0.395409094035560,-0.586218089412104,-0.707106781186548;\n    REQUIRE(abs(mGeo(0,0)-matrixSearch(0,0))< 1e-10);\n    REQUIRE(abs(mGeo(0,1)-matrixSearch(0,1))< 1e-10);\n    REQUIRE(abs(mGeo(0,2)-matrixSearch(0,2))< 1e-10);\n    REQUIRE(abs(mGeo(1,0)-matrixSearch(1,0))< 1e-10);\n    REQUIRE(abs(mGeo(1,1)-matrixSearch(1,1))< 1e-10);\n    REQUIRE(abs(mGeo(1,2)-matrixSearch(1,2))< 1e-10);\n    REQUIRE(abs(mGeo(2,0)-matrixSearch(2,0))< 1e-10);\n    REQUIRE(abs(mGeo(2,1)-matrixSearch(2,1))< 1e-10);\n    REQUIRE(abs(mGeo(2,2)-matrixSearch(2,2))< 1e-10);\n}\n\n/**Test if CoordinateTransform get a valid DCM*/\nTEST_CASE(\"getDCM Test\") {\n\n    Eigen::Vector3d testVector = Eigen::Vector3d::Ones();\n\n    Attitude attitudeZero(0, 0, 0, 0);\n    Eigen::Matrix3d dcmAttitudeZero;\n    CoordinateTransform::getDCM(dcmAttitudeZero,attitudeZero);\n    REQUIRE(dcmAttitudeZero.isIdentity());\n\n    // roll 180 degrees\n    Attitude attitudeRoll(0, 180, 0, 0);\n    Eigen::Matrix3d dcmFromAttitudeRollTest;\n    CoordinateTransform::getDCM(dcmFromAttitudeRollTest,attitudeRoll);\n    Eigen::Vector3d testRollVector = dcmFromAttitudeRollTest * testVector;\n\n    double testRollPrecision = 0.000000001;\n    REQUIRE(abs(testRollVector(0) - 1.0) < testRollPrecision);\n    REQUIRE(abs(testRollVector(1) - -1.0) < testRollPrecision);\n    REQUIRE(abs(testRollVector(2) - -1.0) < testRollPrecision);\n\n    // pitch 180 degrees\n    Attitude attitudePitch(0, 0, 180, 0);\n    Eigen::Matrix3d dcmFromAttitudePitchTest;\n    CoordinateTransform::getDCM(dcmFromAttitudePitchTest,attitudePitch);\n    Eigen::Vector3d testPitchVector = dcmFromAttitudePitchTest * testVector;\n\n    double testPitchPrecision = 0.000000001;\n    REQUIRE(abs(testPitchVector(0) - -1.0) < testPitchPrecision);\n    REQUIRE(abs(testPitchVector(1) - 1.0) < testPitchPrecision);\n    REQUIRE(abs(testPitchVector(2) - -1.0) < testPitchPrecision);\n\n    // heading 180 degrees\n    Attitude attitudeHeading(0, 0, 0, 180);\n    Eigen::Matrix3d dcmFromAttitudeHeadingTest;\n    CoordinateTransform::getDCM(dcmFromAttitudeHeadingTest,attitudeHeading);\n    Eigen::Vector3d testHeadingVector = dcmFromAttitudeHeadingTest * testVector;\n\n    double testHeadingPrecision = 0.000000001;\n    REQUIRE(abs(testHeadingVector(0) - -1.0) < testHeadingPrecision);\n    REQUIRE(abs(testHeadingVector(1) - -1.0) < testHeadingPrecision);\n    REQUIRE(abs(testHeadingVector(2) - 1.0) < testHeadingPrecision);\n\n    // random attitude\n    double roll = 24.357;\n    double pitch = 36.54;\n    double heading = 157.43;\n    Attitude attitudeRandom(0,roll, pitch, heading);\n    Eigen::Matrix3d dcmFromAttitudeRandomTest;\n    CoordinateTransform::getDCM(dcmFromAttitudeRandomTest,attitudeRandom);\n\n    Eigen::Matrix3d dcmFromEulerAngles;\n    dcmFromEulerAngles = Eigen::AngleAxisd(heading*D2R, Eigen::Vector3d::UnitZ())\n      * Eigen::AngleAxisd(pitch*D2R, Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(roll*D2R, Eigen::Vector3d::UnitX());\n\n    double randomPrecision = 0.000000001;\n    Eigen::Matrix3d dcmDifferences = dcmFromAttitudeRandomTest - dcmFromEulerAngles;\n    dcmDifferences = dcmDifferences.cwiseAbs();\n    REQUIRE(dcmDifferences.maxCoeff() < randomPrecision);\n};\n\nTEST_CASE(\"Test getPositionInNavigationFrame function\")\n{\n    Eigen::Vector3d posNav;\n    Position pos(0,0,0,0);\n    Eigen::Matrix3d dcm;\n    dcm << 0,0,0,\n           0,0,0,\n           0,0,0;\n    Eigen::Vector3d origin(0,0,0);\n    CoordinateTransform::getPositionInNavigationFrame(posNav,pos,dcm,origin);\n    REQUIRE(posNav(0) == 0);\n    REQUIRE(posNav(1) == 0);\n    REQUIRE(posNav(2) == 0);\n    \n    pos = Position(0,180,180,0);\n    dcm << 1,0,0,\n           0,1,0,\n           0,0,1;\n    origin(0) = 0;\n    origin(1) = 0;\n    origin(2) = 0;\n    CoordinateTransform::getPositionInNavigationFrame(posNav,pos,dcm,origin);\n    Eigen::Vector3d vectorSearch(6378137,-0.0000000008,0.0000000008);\n    REQUIRE(abs(posNav(0) - vectorSearch(0))< 1e-10);\n    REQUIRE(abs(posNav(1) - vectorSearch(1))< 1e-10);\n    REQUIRE(abs(posNav(2) - vectorSearch(2))< 1e-10);\n}\n", "meta": {"hexsha": "3d0bcff271d2c70bf6137fa7711b7f49aee054d7", "size": 13863, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/CoordinateTransformTest.hpp", "max_stars_repo_name": "EmileGagne/MBES-lib", "max_stars_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CoordinateTransformTest.hpp", "max_issues_repo_name": "EmileGagne/MBES-lib", "max_issues_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_issues_repo_licenses": ["MIT"], "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/CoordinateTransformTest.hpp", "max_forks_repo_name": "EmileGagne/MBES-lib", "max_forks_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1364985163, "max_line_length": 119, "alphanum_fraction": 0.7106686864, "num_tokens": 4070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6707453785349121}}
{"text": "// system includes ------------------------------------------------------------\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/MPRealSupport>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <iomanip>\n#include <iostream>\n//#include <quadmath.h>\n\n// own includes ---------------------------------------------------------------\n#include \"base/numbers.hpp\"\n#include \"maxwell_quadrature.hpp\"\n#include \"spectral/mpfr/import_std_math.hpp\"\n\nnamespace mp = boost::multiprecision;  // Reduce the typing a bit later...\n\nusing namespace mpfr;\n\ntypedef mp::mpfr_float_backend<100000> mfloat_t;\ntypedef mp::number<mfloat_t> mpfr_float_t;\n\nusing namespace std;\n\nconst mpfr_float_t PI = boost::math::constants::pi<mpfr_float_t>();\nconst mpfr_float_t rPI = boost::math::constants::root_pi<mpfr_float_t>();\n\ntemplate <typename T>\nclass Beta\n{\n public:\n  Beta(int p = 1)\n      : p_(p)\n      , beta_n(1)\n  {\n    beta_n[0] = 0;\n    navail = 0;\n  }\n\n  template <typename A>\n  const T& get(unsigned int n, A& alpha);\n\n private:\n  int p_;\n  std::vector<T> beta_n;\n  unsigned int navail;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename T>\ntemplate <typename A>\nconst T& Beta<T>::get(unsigned int n, A& alpha)\n{\n  if (n < beta_n.size())\n    return beta_n[n];\n  else {\n    // make sure all previous n's exist\n    for (unsigned int i = navail + 1; i < n; ++i) {\n      this->get(i, alpha);\n    }\n    // compute\n    T am = alpha.get(n - 1, *this);\n    T an = alpha.get(n, *this);\n    T bm = this->get(n - 1, alpha);\n    T denom = 2 + 4 * am * (am + an) + 4 * bm;\n    T nom = n * (n + p_);\n    T res = nom / denom;\n    beta_n.push_back(res);\n    navail++;\n    assert(navail == n);\n    assert(beta_n[n] == res);\n    return beta_n[n];\n  }\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename T>\nclass Alpha\n{\n public:\n  Alpha(int p = 1)\n      : p_(p)\n      , alpha_n(2)\n  {\n    mpfr_float_t one(1);\n    mpfr_float_t two(2);\n    mpfr_float_t three(3);\n    mpfr_float_t four(4);\n    mpfr_float_t eight(8);\n\n    if (p == 0) {\n      alpha_n[0] = one / rPI;\n      alpha_n[1] = two / rPI / (PI - two);\n    } else if (p == 1) {\n      alpha_n[0] = rPI / two;\n      alpha_n[1] = rPI * (PI - two) / two / (four - PI);\n    } else if (p == 2) {\n      alpha_n[0] = two / rPI;\n      alpha_n[1] = four * (four - PI) / rPI / (three * PI - eight);\n    } else {\n      throw std::runtime_error(\"invalid p\");\n    }\n\n    navail = 1;\n  }\n  template <typename B>\n  const T& get(unsigned int n, B& beta);\n\n private:\n  int p_;\n  std::vector<T> alpha_n;\n  unsigned int navail;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename T>\ntemplate <typename B>\nconst T& Alpha<T>::get(unsigned int n, B& beta)\n{\n  if (n < alpha_n.size())\n    return alpha_n[n];\n  else {\n    // make sure all previous n's exist\n    for (unsigned int i = navail + 1; i < n; ++i) {\n      this->get(i, beta);\n    }\n    // use recursion formula (15)\n    // compute\n    T sum = 0;\n    T am = this->get(n - 1, beta);\n    T am2 = am * am;\n    for (unsigned int k = 0; k < n; ++k) {\n      sum += this->get(k, beta);\n    }\n    sum /= (2 * n - 1 + p_ - 2 * am2 - 2 * beta.get(n - 1, *this));\n    sum -= am;\n    alpha_n.push_back(sum);\n    navail++;\n    assert(navail == n);\n    assert(alpha_n[n] == sum);\n    return alpha_n[n];\n  }\n}\n\nvoid MaxwellQuadrature::init(int ndigits)\n{\n  // recurrence relation using mpfr_float_t\n  typedef Alpha<mpfr_float_t> alpha_t;\n  typedef Beta<mpfr_float_t> beta_t;\n\n  alpha_t alpha(p);\n  beta_t beta(p);\n\n  // eigen with mpreal\n  mpreal::set_default_prec(ndigits);\n  typedef mpreal mfloat_t;\n  //  typedef double mfloat_t;\n  typedef Eigen::Matrix<mfloat_t, Eigen::Dynamic, Eigen::Dynamic> MatrixXmp;\n  MatrixXmp A(N, N);\n  A.fill(0);\n  for (int i = 0; i < N; ++i) {\n    A(i, i) = mfloat_t(alpha.get(i, beta).backend().data()).setPrecision(ndigits);\n    const auto sqrt_beta1 = ::math::sqrt(beta.get(i + 1, alpha));\n    const auto sqrt_beta0 = ::math::sqrt(beta.get(i, alpha));\n\n    if (i + 1 < N) A(i, i + 1) = mfloat_t(sqrt_beta1.backend().data()).setPrecision(ndigits);\n    if (i > 0) A(i, i - 1) = mfloat_t(sqrt_beta0.backend().data()).setPrecision(ndigits);\n  }\n\n  Eigen::SelfAdjointEigenSolver<MatrixXmp> eigensolver;\n  eigensolver.compute(A, Eigen::ComputeEigenvectors);\n\n  // compute weights\n  const auto V = eigensolver.eigenvectors();\n  const auto w = eigensolver.eigenvalues();\n\n  if (V.rows() == 0) {\n    cerr << \"abort\";\n    exit(-1);\n  }\n\n  const double pi = boltzmann::numbers::PI;\n  std::array<double, 3> mp = {std::sqrt(pi) / 2, 0.5, std::sqrt(pi) / 4};\n\n  std::vector<double> weights(N);\n  for (int i = 0; i < N; ++i) {\n    // eigenvectors are normalized by eigen\n    auto v = V(0, i);\n    weights[i] = mp[p] * (v * v).toDouble();\n  }\n\n  std::vector<double> points(N);\n  for (int i = 0; i < N; ++i) {\n    points[i] = w(i).toDouble();\n  }\n\n  std::vector<std::pair<double, double> > pairs(N);\n  for (int i = 0; i < N; ++i) {\n    pairs[i] = std::make_pair(points[i], weights[i]);\n  }\n\n  std::sort(pairs.begin(), pairs.end());\n\n  for (int i = 0; i < N; ++i) {\n    pts_[i] = pairs[i].first;\n    wts_[i] = pairs[i].second;\n  }\n}\n", "meta": {"hexsha": "0ff2e0500d0c56a420a864b5654b9fff74f1cede", "size": 5334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectral/quadrature/maxwell_quadrature.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "spectral/quadrature/maxwell_quadrature.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "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": "spectral/quadrature/maxwell_quadrature.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 25.4, "max_line_length": 93, "alphanum_fraction": 0.5562429696, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6707453749330357}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <sophus/se3.hpp>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches);\n\n// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\nPoint2d pixel2cam(const Point2d &p, const Mat &K);\n\n// BA by g2o\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\nvoid bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose\n);\n\n// BA by gauss-newton\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose\n);\n\nint main(int argc, char **argv) {\n  if (argc != 5) {\n    cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2\" << endl;\n    return 1;\n  }\n  //-- \u8bfb\u53d6\u56fe\u50cf\n  Mat img_1 = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(argv[2], CV_LOAD_IMAGE_COLOR);\n  assert(img_1.data && img_2.data && \"Can not load images!\");\n\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n  cout << \"\u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl;\n\n  // \u5efa\u7acb3D\u70b9\n  Mat d1 = imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n  vector<Point3f> pts_3d;\n  vector<Point2f> pts_2d;\n  for (DMatch m:matches) {\n    ushort d = d1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    if (d == 0)   // bad depth\n      continue;\n    float dd = d / 5000.0;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n    pts_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n    pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n  }\n\n  cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  Mat r, t;\n  solvePnP(pts_3d, pts_2d, K, Mat(), r, t, false); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n  Mat R;\n  cv::Rodrigues(r, R); // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n  cout << \"R=\" << endl << R << endl;\n  cout << \"t=\" << endl << t << endl;\n\n  VecVector3d pts_3d_eigen;\n  VecVector2d pts_2d_eigen;\n  for (size_t i = 0; i < pts_3d.size(); ++i) {\n    pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n    pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n  }\n\n  cout << \"calling bundle adjustment by gauss newton\" << endl;\n  Sophus::SE3d pose_gn;\n  t1 = chrono::steady_clock::now();\n  bundleAdjustmentGaussNewton(pts_3d_eigen, pts_2d_eigen, K, pose_gn);\n  t2 = chrono::steady_clock::now();\n  time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n  cout << \"calling bundle adjustment by g2o\" << endl;\n  Sophus::SE3d pose_g2o;\n  t1 = chrono::steady_clock::now();\n  bundleAdjustmentG2O(pts_3d_eigen, pts_2d_eigen, K, pose_g2o);\n  t2 = chrono::steady_clock::now();\n  time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp by g2o cost time: \" << time_used.count() << \" seconds.\" << endl;\n  return 0;\n}\n\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,\n                          std::vector<KeyPoint> &keypoints_1,\n                          std::vector<KeyPoint> &keypoints_2,\n                          std::vector<DMatch> &matches) {\n  //-- \u521d\u59cb\u5316\n  Mat descriptors_1, descriptors_2;\n  // used in OpenCV3\n  Ptr<FeatureDetector> detector = ORB::create();\n  Ptr<DescriptorExtractor> descriptor = ORB::create();\n  // use this if you are in OpenCV2\n  // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n  // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n  Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n  //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n  vector<DMatch> match;\n  // BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n  double min_dist = 10000, max_dist = 0;\n\n  //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n    if (dist < min_dist) min_dist = dist;\n    if (dist > max_dist) max_dist = dist;\n  }\n\n  printf(\"-- Max dist : %f \\n\", max_dist);\n  printf(\"-- Min dist : %f \\n\", min_dist);\n\n  //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose) {\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  const int iterations = 10;\n  double cost = 0, lastCost = 0;\n  double fx = K.at<double>(0, 0);\n  double fy = K.at<double>(1, 1);\n  double cx = K.at<double>(0, 2);\n  double cy = K.at<double>(1, 2);\n\n  for (int iter = 0; iter < iterations; iter++) {\n    Eigen::Matrix<double, 6, 6> H = Eigen::Matrix<double, 6, 6>::Zero();\n    Vector6d b = Vector6d::Zero();\n\n    cost = 0;\n    // compute cost\n    for (int i = 0; i < points_3d.size(); i++) {\n      Eigen::Vector3d pc = pose * points_3d[i];\n      double inv_z = 1.0 / pc[2];\n      double inv_z2 = inv_z * inv_z;\n      Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx, fy * pc[1] / pc[2] + cy);\n\n      Eigen::Vector2d e = points_2d[i] - proj;\n\n      cost += e.squaredNorm();\n      Eigen::Matrix<double, 2, 6> J;\n      J << -fx * inv_z,\n        0,\n        fx * pc[0] * inv_z2,\n        fx * pc[0] * pc[1] * inv_z2,\n        -fx - fx * pc[0] * pc[0] * inv_z2,\n        fx * pc[1] * inv_z,\n        0,\n        -fy * inv_z,\n        fy * pc[1] * inv_z2,\n        fy + fy * pc[1] * pc[1] * inv_z2,\n        -fy * pc[0] * pc[1] * inv_z2,\n        -fy * pc[0] * inv_z;\n\n      H += J.transpose() * J;\n      b += -J.transpose() * e;\n    }\n\n    Vector6d dx;\n    dx = H.ldlt().solve(b);\n\n    if (isnan(dx[0])) {\n      cout << \"result is nan!\" << endl;\n      break;\n    }\n\n    if (iter > 0 && cost >= lastCost) {\n      // cost increase, update is not good\n      cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n      break;\n    }\n\n    // update your estimation\n    pose = Sophus::SE3d::exp(dx) * pose;\n    lastCost = cost;\n\n    cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << endl;\n    if (dx.norm() < 1e-6) {\n      // converge\n      break;\n    }\n  }\n\n  cout << \"pose by g-n: \\n\" << pose.matrix() << endl;\n}\n\n/// vertex and edges used in g2o ba\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  virtual void setToOriginImpl() override {\n    _estimate = Sophus::SE3d();\n  }\n\n  /// left multiplication on SE3\n  virtual void oplusImpl(const double *update) override {\n    Eigen::Matrix<double, 6, 1> update_eigen;\n    update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n    _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n};\n\nclass EdgeProjection : public g2o::BaseUnaryEdge<2, Eigen::Vector2d, VertexPose> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  EdgeProjection(const Eigen::Vector3d &pos, const Eigen::Matrix3d &K) : _pos3d(pos), _K(K) {}\n\n  virtual void computeError() override {\n    const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n    Sophus::SE3d T = v->estimate();\n    Eigen::Vector3d pos_pixel = _K * (T * _pos3d);\n    pos_pixel /= pos_pixel[2];\n    _error = _measurement - pos_pixel.head<2>();\n  }\n\n  virtual void linearizeOplus() override {\n    const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n    Sophus::SE3d T = v->estimate();\n    Eigen::Vector3d pos_cam = T * _pos3d;\n    double fx = _K(0, 0);\n    double fy = _K(1, 1);\n    double cx = _K(0, 2);\n    double cy = _K(1, 2);\n    double X = pos_cam[0];\n    double Y = pos_cam[1];\n    double Z = pos_cam[2];\n    double Z2 = Z * Z;\n    _jacobianOplusXi\n      << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n      0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n\nprivate:\n  Eigen::Vector3d _pos3d;\n  Eigen::Matrix3d _K;\n};\n\nvoid bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose) {\n\n  // \u6784\u5efa\u56fe\u4f18\u5316\uff0c\u5148\u8bbe\u5b9ag2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // pose is 6, landmark is 3\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // \u7ebf\u6027\u6c42\u89e3\u5668\u7c7b\u578b\n  // \u68af\u5ea6\u4e0b\u964d\u65b9\u6cd5\uff0c\u53ef\u4ee5\u4eceGN, LM, DogLeg \u4e2d\u9009\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n  optimizer.setAlgorithm(solver);   // \u8bbe\u7f6e\u6c42\u89e3\u5668\n  optimizer.setVerbose(true);       // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n\n  // vertex\n  VertexPose *vertex_pose = new VertexPose(); // camera vertex_pose\n  vertex_pose->setId(0);\n  vertex_pose->setEstimate(Sophus::SE3d());\n  optimizer.addVertex(vertex_pose);\n\n  // K\n  Eigen::Matrix3d K_eigen;\n  K_eigen <<\n          K.at<double>(0, 0), K.at<double>(0, 1), K.at<double>(0, 2),\n    K.at<double>(1, 0), K.at<double>(1, 1), K.at<double>(1, 2),\n    K.at<double>(2, 0), K.at<double>(2, 1), K.at<double>(2, 2);\n\n  // edges\n  int index = 1;\n  for (size_t i = 0; i < points_2d.size(); ++i) {\n    auto p2d = points_2d[i];\n    auto p3d = points_3d[i];\n    EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n    edge->setId(index);\n    edge->setVertex(0, vertex_pose);\n    edge->setMeasurement(p2d);\n    edge->setInformation(Eigen::Matrix2d::Identity());\n    optimizer.addEdge(edge);\n    index++;\n  }\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  optimizer.setVerbose(true);\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n  cout << \"pose estimated by g2o =\\n\" << vertex_pose->estimate().matrix() << endl;\n  pose = vertex_pose->estimate();\n}\n", "meta": {"hexsha": "1041ab5201c6d7b63b21acb3544caacfdbe8773b", "size": 11822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_stars_repo_name": "SJTU-ZYH/slambook2", "max_stars_repo_head_hexsha": "e1c022569bc4b4b8dcd038037c1d6363e6178953", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2812.0, "max_stars_repo_stars_event_min_datetime": "2018-08-19T07:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:11:04.000Z", "max_issues_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_issues_repo_name": "SJTU-ZYH/slambook2", "max_issues_repo_head_hexsha": "e1c022569bc4b4b8dcd038037c1d6363e6178953", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 219.0, "max_issues_repo_issues_event_min_datetime": "2018-08-28T08:35:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:29:43.000Z", "max_forks_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_forks_repo_name": "SJTU-ZYH/slambook2", "max_forks_repo_head_hexsha": "e1c022569bc4b4b8dcd038037c1d6363e6178953", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1301.0, "max_forks_repo_forks_event_min_datetime": "2018-08-28T01:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:03:01.000Z", "avg_line_length": 32.8388888889, "max_line_length": 108, "alphanum_fraction": 0.6401624091, "num_tokens": 4101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.6706716805370826}}
{"text": "#include <cassert>\n#include <cmath>\n#include <numeric> // accumulate\n#include <ostream>\n#include <utility>\n\n#include <boost/variant/static_visitor.hpp>\n\n#include \"Geometry.h\"\n\nusing namespace std;\n\nnamespace geometry {\n\nScalar size(Vector const &vec) { return std::hypot(vec.x, vec.y); }\n\n// Dot product\nScalar dot(Vector const &v1, Vector const &v2) {\n  return v1.x * v2.x + v1.y * v2.y;\n}\n\nScalar cos(Vector const &a, Vector const &b) {\n  return dot(a, b) / (size(a) * size(b));\n}\n\nVector projection(Vector const &v, Vector const &s) {\n  return ((v * s) / (s * s)) * s;\n}\n\nScalar projection(Point const &p, Point const &A, Point const &B) {\n  // http://stackoverflow.com/a/15187473/6209703\n  Vector const direction = B - A;\n  Scalar const t = ((p.x - A.x) * (B.x - A.x) + (p.y - A.y) * (B.y - A.y)) /\n                   (direction.x * direction.x + direction.y * direction.y);\n  // t=[(Cx-Ax)(Bx-Ax)+(Cy-Ay)(By-Ay)]/[(Bx-Ax)^2+(By-Ay)^2]\n  return t;\n}\n\nVector unit(Vector const &v) { return v / size(v); }\n\nScalar distance(Point const &p1, Point const &p2) {\n  auto d = p2 - p1;\n  return Scalar(std::hypot(d.x, d.y));\n}\n\nstd::ostream &operator<<(std::ostream &o, Point const &point) {\n  o << \"[\" << point.x << \",\" << point.y << \"]\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, Vector const &point) {\n  o << \"(\" << point.x << \",\" << point.y << \")\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, CircleShape const &shape) {\n  o << \"{ radius: \" << shape.radius << \" }\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, Circle const &c) {\n  o << \"{ circ at \" << c.center << \", r: \" << c.radius << \" }\";\n  return o;\n}\n\nPolygonalShape &operator+=(PolygonalShape &shape, Vector const &vec) {\n  for (auto &v : shape)\n    v += vec;\n  return shape;\n}\n\nPolygonalShape &operator*=(PolygonalShape &shape, Scalar scale) {\n  for (auto &v : shape)\n    v *= scale;\n  return shape;\n}\n\nPolygonalShape &operator-=(PolygonalShape &shape, Vector const &vec) {\n  for (auto &v : shape)\n    v -= vec;\n  return shape;\n}\n\nstd::ostream &operator<<(std::ostream &o, PolygonalShape const &shape) {\n  o << \"[\";\n  for (auto const &vec : shape)\n    o << \" \" << vec;\n  o << \" ]\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, Polygon const &p) {\n  o << \"[\";\n  for (auto const &pt : p)\n    o << \" \" << pt;\n  o << \" ]\";\n  return o;\n}\n\nstd::ostream &operator<<(std::ostream &o, RectangularArea const &area) {\n  o << \"{ area from \" << area.topLeft() << \" to \" << area.bottomRight() << \" }\";\n  return o;\n}\n\nbool in_triangle(Point const &p, Point const &p1, Point const &p2,\n                 Point const &p3) {\n  auto alpha = ((p2.y - p3.y) * (p.x - p3.x) + (p3.x - p2.x) * (p.y - p3.y)) /\n               ((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y));\n  auto beta = ((p3.y - p1.y) * (p.x - p3.x) + (p1.x - p3.x) * (p.y - p3.y)) /\n              ((p2.y - p3.y) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y));\n  auto gamma = 1.0f - alpha - beta;\n\n  return alpha >= 0 && beta >= 0 && gamma >= 0;\n}\n\nVector perpendicularDistance(Point const &p, Point const &A, Point const &B) {\n  Scalar const t = projection(p, A, B);\n  Point const projectedCenter = A + t * (B - A);\n  return p - projectedCenter;\n}\n\nbool onLeftOf(Point const &point, Point const &A, Point const &B) {\n  return ((A.x - point.x) * (B.y - point.y) -\n          (A.y - point.y) * (B.y - point.x)) > 0;\n}\n\n// http://stackoverflow.com/a/21096006/6209703\nbool in_polygon(Point const &point, Polygon const &polygon_old) {\n  Polygon polygon = polygon_old;\n\n  assert(polygon.size() >= 3);\n\n  while (polygon.size() > 3) {\n    // TODO detect automatically polygons rotation/order of verteces\n    Polygon newPolygon;\n    if (onLeftOf(point, polygon[0], polygon[polygon.size() / 2])) {\n      for (size_t i = 0; i <= polygon.size() / 2; i++)\n        newPolygon.push_back(polygon[i]);\n    } else {\n      for (size_t i = polygon.size() / 2; i < polygon.size(); i++)\n        newPolygon.push_back(polygon[i]);\n      newPolygon.push_back(polygon[0]);\n    }\n\n    assert(newPolygon.size() < polygon.size());\n    using std::swap;\n    swap(newPolygon, polygon);\n  }\n\n  return in_triangle(point, polygon[0], polygon[1], polygon[2]);\n}\n\nbool in_polygon(Circle const &circle, Polygon const &polygon) {\n  for (Point const &p : polygon) {\n    Vector const direction = unit(p - circle.center);\n    Point const outer = circle.center + circle.radius * direction;\n    if (!in_polygon(outer, polygon))\n      return false;\n  }\n  return true;\n}\n\nbool in_polygon(Polygon const &polygon1, Polygon const &polygon2) {\n  for (Point const &p : polygon1) {\n    if (!in_polygon(p, polygon2))\n      return false;\n  }\n  return true;\n}\n\nbool in_circle(Point const &point, Circle const &circle) {\n  auto vec = point - circle.center;\n  return std::hypot(vec.x, vec.y) <= circle.radius;\n}\n\nbool in_circle(Circle const & /*circle1*/, Circle const & /*circle2*/) {\n  return false;\n}\n\nbool in_circle(Polygon const &polygon, Circle const &circle) {\n  for (Point const &p : polygon) {\n    if (!in_circle(p, circle))\n      return false;\n  }\n  return true;\n}\n\nbool in(Point const &point, RectangularArea const &area) {\n  if (point.x <= area.topLeft().x)\n    return false;\n  if (point.x >= area.bottomRight().x)\n    return false;\n  if (point.y <= area.topLeft().y)\n    return false;\n  if (point.y >= area.bottomRight().y)\n    return false;\n  return true;\n}\n\nbool in(Circle const &circle, RectangularArea const &area) {\n  return in(circle.center, CircleShape{circle.radius}, area);\n}\n\nbool in(Point const &point, CircleShape const &shape,\n        RectangularArea const &area) {\n  if (point.x - shape.radius <= area.topLeft().x)\n    return false;\n  if (point.x + shape.radius >= area.bottomRight().x)\n    return false;\n  if (point.y - shape.radius <= area.topLeft().y)\n    return false;\n  if (point.y + shape.radius >= area.bottomRight().y)\n    return false;\n  return true;\n}\n\nbool in(Polygon const &polygon, RectangularArea const &area) {\n  // TODO use accumulate with ranges\n  for (auto const &p : polygon) {\n    if (!in(p, area))\n      return false;\n  }\n\n  return true;\n}\n\nnamespace {\n\ntemplate <typename Object1>\nclass InVisitor1 : public boost::static_visitor<bool> {\n  Object1 const &object1;\n\npublic:\n  explicit InVisitor1(Object1 const &object1) : object1(object1) {}\n\n  bool operator()(Polygon const &object2) {\n    return in_polygon(object1, object2);\n  }\n\n  bool operator()(Circle const &object2) { return in_circle(object1, object2); }\n};\n\nclass InVisitor2 : public boost::static_visitor<bool> {\n  Object2D const &object2;\n\npublic:\n  explicit InVisitor2(Object2D const &object2) : object2(object2) {}\n\n  bool operator()(Polygon const &object1) {\n    InVisitor1<Polygon> visitor{object1};\n    return boost::apply_visitor(visitor, object2);\n  }\n\n  bool operator()(Circle const &object1) {\n    InVisitor1<Circle> visitor{object1};\n    return boost::apply_visitor(visitor, object2);\n  }\n};\n\n} // anonymous namespace\n\nbool in(Object2D const &object1, Object2D const &object2) {\n  InVisitor2 visitor{object2};\n  return boost::apply_visitor(visitor, object1);\n}\n\nbool in(Object2D const &object, RectangularArea const &area) {\n  class Visitor : public boost::static_visitor<bool> {\n  private:\n    RectangularArea const &area;\n\n  public:\n    Visitor(RectangularArea const &area) : area(area) {}\n\n    bool operator()(Polygon const &polygon) { return in(polygon, area); }\n\n    bool operator()(Circle const &circle) { return in(circle, area); }\n  };\n\n  Visitor visitor{area};\n  return boost::apply_visitor(visitor, object);\n}\n\nScalar deg2rad(Scalar degrees) { return degrees * 3.141592653589793 / 180.0; }\n\nVector rotate(Vector const &vec, Angle angle) {\n  auto const dangle = deg2rad(angle);\n  auto const cs = Scalar(std::cos(dangle));\n  auto const sn = Scalar(std::sin(dangle));\n\n  return vec.x * Vector{cs, sn} + vec.y * Vector{Scalar(-sn), cs};\n}\n\nPoint rotate_around(Point const &center, Point const &point, Angle angle) {\n  return center + rotate(point - center, angle);\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "3c937361de0a097e70c263b0a54acfbe6cad92a2", "size": 8031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/common/Geometry.cpp", "max_stars_repo_name": "h0nzZik/toogashada", "max_stars_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_stars_repo_licenses": ["MIT"], "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/common/Geometry.cpp", "max_issues_repo_name": "h0nzZik/toogashada", "max_issues_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-06-10T11:02:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-10T11:02:58.000Z", "max_forks_repo_path": "source/common/Geometry.cpp", "max_forks_repo_name": "h0nzZik/toogashada", "max_forks_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_forks_repo_licenses": ["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.8595317726, "max_line_length": 80, "alphanum_fraction": 0.6271946208, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6706531211177874}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of square lattice Ising model\n\n#pragma once\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <standards/simpson.hpp>\n#include <lattice/graph.hpp>\n#include \"common.hpp\"\n\nnamespace ising {\nnamespace free_energy {\nnamespace square {\n\nnamespace {\n\ntemplate<typename T, typename FVAR>\nstruct functor {\n  typedef T real_t;\n  typedef FVAR fvar_t;\n  functor(real_t Jx, real_t Jy, fvar_t beta) {\n    using std::cosh; using std::sinh;\n    c_ = 1 / (2 * boost::math::constants::pi<real_t>());\n    chab_ = cosh(2 * beta * Jx) * cosh(2 * beta * Jy);\n    k_ = 1 / (sinh(2 * beta * Jx) * sinh(2 * beta * Jy));\n  }\n  fvar_t operator()(real_t t) const {\n    using std::cos; using std::log; using std::sqrt;\n    return c_ * log(chab_ + sqrt(1 + k_ * k_ - 2 * k_ * cos(2 * t)) / k_);\n  }\n  real_t c_;\n  fvar_t chab_, k_;\n};\n\ntemplate<typename T, std::size_t Order>\nstruct functor<T, boost::math::differentiation::detail::fvar<T, Order>> {\n  typedef T real_t;\n  typedef boost::math::differentiation::detail::fvar<real_t, Order> fvar_t;\n  functor(real_t Jx, real_t Jy, fvar_t beta) {\n    using std::cosh; using std::sinh;\n    c_ = 1 / (2 * boost::math::constants::pi<real_t>());\n    chab_ = cosh(2 * beta * Jx) * cosh(2 * beta * Jy);\n    k_ = 1 / (sinh(2 * beta * Jx) * sinh(2 * beta * Jy));\n  }\n  fvar_t operator()(real_t t) const {\n    using std::abs; using std::cos; using std::log; using std::sqrt;\n    auto r = sqrt(1 + k_ * k_ - 2 * k_ * cos(2 * t)) / k_;\n    if (abs(r.derivative(1)) > std::numeric_limits<real_t>::max()) {\n      auto x = boost::math::differentiation::make_fvar<real_t, 2>(real_t(0));\n      r = fvar_t(r.derivative(0)) + std::numeric_limits<real_t>::max() * x * x;\n    }\n    return c_ * log(chab_ + r);\n  }\n  real_t c_;\n  fvar_t chab_, k_;\n};\n\ntemplate<typename T, typename FVAR>\nfunctor<T, FVAR> func(T Jx, T Jy, FVAR beta) { return functor<T, FVAR>(Jx, Jy, beta); }\n\n}\n\ntemplate<typename T, typename U>\ninline U infinite(T Jx, T Jy, U beta) {\n  const unsigned long max_n = 1 << 16;\n  typedef T real_t;\n  if (Jx <= 0 || Jy <= 0)\n    throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n  if (beta <= 0)\n    throw(std::invalid_argument(\"beta should be positive\"));\n  real_t pi = boost::math::constants::pi<real_t>();\n  boost::math::quadrature::tanh_sinh<real_t> integrator;\n  auto logZ = log(real_t(2)) / 2 + 2 * integrator.integrate(func(Jx, Jy, beta), 0, pi / 2);\n  return - logZ / beta;\n}\n\ntemplate<typename I, typename T, typename U>\ninline U finite(I Lx, I Ly, T Jx, T Jy, U beta) {\n  typedef I int_t;\n  typedef T real_t;\n  typedef U value_t;\n  if (Lx <= 0 || Ly <= 0)\n    throw(std::invalid_argument(\"Lx and Ly should be positive\"));\n  if (Jx <= 0 || Jy <= 0)\n    throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n  real_t pi = boost::math::constants::pi<real_t>();\n  auto a = beta * Jx;\n  auto b = beta * Jy;\n  value_t lp0(0), lp1(0), lp2(0), lp3(0);\n  auto gamma0 = log((1 + cosh(2*a)) / sinh(2*a)) - 2*b;\n  for (int_t k = 0; k < 2 * Ly; ++k) {\n    auto cosh_g = (cosh(2*a) * cosh(2*b) - cos(pi * k / Ly) * sinh(2*b)) / sinh(2*a);\n    auto gamma = (k == 0) ? abs(gamma0) : (log(cosh_g + sqrt(cosh_g * cosh_g - 1)));\n    if ((k & 1) == 1) {\n      lp0 += (Lx * gamma/2) + log(1 + exp(-(Lx * gamma)));\n      lp1 += (Lx * gamma/2) + log(1 - exp(-(Lx * gamma)));\n    } else {\n      lp2 += (Lx * gamma/2) + log(1 + exp(-(Lx * gamma)));\n      lp3 += (Lx * gamma/2) + log(1 - exp(-(Lx * gamma)));\n    }\n  }\n  auto logZ = -log(real_t(2)) / (Lx * Ly) + a + real_t(1)/2 * log(1 - exp(-4*a));\n  if (gamma0 > 0) {\n    logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) - exp(lp3-lp0))) / (Lx * Ly);\n  } else if (gamma0 < 0) {\n    logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) + exp(lp3-lp0))) / (Lx * Ly);\n  } else {\n    logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0))) / (Lx * Ly);\n  }\n  return - logZ / beta;\n}\n\ntemplate<typename T, typename I>\ninline T finite_tc(I Lx, I Ly) {\n  typedef I int_t;\n  typedef T real_t;\n  if (Lx <= 0 || Ly <= 0)\n    throw(std::invalid_argument(\"Lx and Ly should be positive\"));\n  real_t pi = boost::math::constants::pi<real_t>();\n  real_t beta = log(sqrt(real_t(2)) + 1)/2;\n  real_t lp0(0), lp1(0);\n  for (int_t k = 1; k < 2 * Ly; k += 2) {\n    real_t c = (2 - cos(pi * k / Ly));\n    real_t cosh_g = c;\n    real_t gamma_abs = log(cosh_g + sqrt(cosh_g * cosh_g - 1));\n    lp0 += (Lx * gamma_abs/2) + log(1 + exp(-(Lx * gamma_abs)));\n    lp1 += (Lx * gamma_abs/2) + log(1 - exp(-(Lx * gamma_abs)));\n  }\n  real_t logZ = -log(real_t(2)) / (Lx * Ly) + beta + real_t(1)/2 * log(1 - exp(-4*beta))\n    + (lp0 + 2 * lp1) / (Lx * Ly)\n    + (lp0 + log(1 + 2 * exp(lp1-lp0))) / (Lx * Ly);\n  return - logZ / beta;\n}\n\ntemplate<typename I, typename T, typename U, typename W>\ninline boost::math::differentiation::promote<U, W> finite_count(I Lx, I Ly, T Jx, T Jy, U beta, W h) {\n  typedef I int_t;\n  typedef T real_t;\n  typedef boost::math::differentiation::promote<U, W> value_t;\n  if (Lx <= 0 || Ly <= 0)\n    throw(std::invalid_argument(\"Lx and Ly should be positive\"));\n  if (Jx <= 0 || Jy <= 0)\n    throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n\n  auto basis = lattice::basis::simple(2);\n  auto unitcell = lattice::unitcell(2);\n  unitcell.add_site(lattice::coordinate(0, 0), 0);\n  unitcell.add_bond(0, 0, lattice::offset(1, 0), 0);\n  unitcell.add_bond(0, 0, lattice::offset(0, 1), 1);\n  auto graph = lattice::graph(basis, unitcell, lattice::extent(Lx, Ly));\n  if (graph.num_sites() >= 32) throw(std::invalid_argument(\"too large system size\"));\n  \n  std::vector<real_t> J(2);\n  J[0] = Jx;\n  J[1] = Jy;\n  real_t gs_energy = -(Jx + Jy) * (Lx * Ly);\n  int_t num_states = 1 << graph.num_sites();\n  value_t Z(0);\n  for (int_t c = 0; c < num_states; ++c) {\n    real_t energy = 0;\n    for (int_t b = 0; b < graph.num_bonds(); ++b) {\n      real_t ci = real_t(2) * ((c >> graph.source(b)) & 1) - 1;\n      real_t cj = real_t(2) * ((c >> graph.target(b)) & 1) - 1;\n      energy -= J[graph.bond_type(b)] * ci * cj;\n    }\n    real_t mag = 0;\n    for (int_t s = 0; s < graph.num_sites(); ++s) {\n      mag += real_t(2) * ((c >> s) & 1) - 1;\n    }\n    Z += exp((gs_energy - energy - h * mag) * beta);\n  }\n  return (-log(Z)/beta + gs_energy) / (Lx * Ly);\n}\n\n} // end namespace square\n} // end namespace free_energy\n} // end namespace ising\n", "meta": {"hexsha": "e5362ae52a79a3336d7271c53ae84d67c110dc2a", "size": 7103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square.hpp", "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.hpp", "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.hpp", "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": 36.0558375635, "max_line_length": 102, "alphanum_fraction": 0.6021399409, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7520125626441471, "lm_q1q2_score": 0.6706531139988829}}
{"text": "#include <vector>\n#include <armadillo>\n#include \"ConvectionDiffusionEulerImplicit.h\"\n\nusing namespace std;\n\nvoid ConvectionDiffusionEulerImplicit::initialize() {\n\t// Initial time conditions\n\tcurrent_time = 0.0; // time 0 = option expiration - more pos = farther in the past\n\tcurrent_t_index = 0;\n\n\t// Proccessing step\n\tsolution.resize(T);\n    for (unsigned long t = 0; t < T; t++) { solution[t].resize(N,0.0); }\n\tx_values.resize(N,0.0);\n\t\n\t// Initialize the solution set at all x values\n\tdouble x;\n\tfor (unsigned long n = 0; n < N; n++) {\n\t\tx = static_cast<double>(n) * h;\n\t\tsolution[0][n] = pde->initial_condition(x);\n\t\tx_values[n] = x;\n\t}\n}\n\n\n// Compute PDE's boundary conditions\nvoid ConvectionDiffusionEulerImplicit::calculate_boundary() {\n\t// double time = current_time - k;\n\tsolution[current_t_index][0] = pde->left_boundary(current_time, x_values, solution[current_t_index-1],k,h);\n\tsolution[current_t_index][N-1] = pde->right_boundary(current_time, x_values, solution[current_t_index-1],k,h);\n}\n\n// Apply FEM to solve system of PDEs with given initial and boundary conditions\nvoid ConvectionDiffusionEulerImplicit::calculate_inner_mesh() {\n\tdouble right, center, left, source, x, prev_time = current_time - k;\n\tdouble sigma = k / (h * h);\n\tdouble lambda = k / h;\n\n\t// INIT TRANSITION MATRIX\n\tarma::mat A = arma::zeros<arma::mat>(N-2,N-2);\n\tfor (unsigned long n = 1; n < N-1; n++) {\n\t\tx = x_values[n];\n\n\t\tA(n-1,n-1) = 1.0 \n\t\t+ (2.0 * sigma * pde->diffusion_param(current_time,x)) \n\t\t- (k * pde->solution_param(current_time,x));\n\n\t\tif (n < N-2) { \n\t\t\tA(n-1,n) =  - (sigma * pde->diffusion_param(current_time,x)) \n            - (0.5 * lambda * pde->convection_param(current_time,x));\n\t\t} \n        if (n > 1) {\n\t\t\tA(n-1,n-2) = - (sigma * pde->diffusion_param(current_time,x)) \n\t\t\t+ (0.5 * lambda * pde->convection_param(current_time,x));\n\t\t}\n\t}\n\n\t// INIT BOUNDARY VECTOR\n\tarma::vec b = arma::zeros<arma::vec>(N-2);\n\n\tleft = - (sigma * pde->diffusion_param(current_time,x_values[0])) + (0.5 * lambda * pde->convection_param(current_time,x_values[0]));\n    b(0) = left * pde->left_boundary(current_time, x_values,solution[current_t_index-1],k,h);\n\n\tright = - (sigma * pde->diffusion_param(current_time,x_values[N-1])) - (0.5 * lambda * pde->convection_param(current_time,x_values[N-1]));\n    b(N-3) = right * pde->right_boundary(current_time, x_values,solution[current_t_index-1],k,h);\n\n\t// INIT SOURCE VECTOR\n\tarma::vec S = arma::zeros<arma::vec>(N-2);\n\tfor (unsigned long n = 1; n < N-1; n++) {\n\t\tS(n-1) = k * pde->source_param(current_time,x_values[n]);\n\t}\n\n\t// LAST SOLUTION\n\tarma::vec u = arma::zeros<arma::vec>(N-2);\n\tfor (unsigned long n = 1; n < N-1; n++) {\n        u(n-1) = solution[current_t_index-1][n];\n\t}\n\n\t// SOLVE \n    arma::vec sol = arma::solve(A, u + b + S);\n\n\t// STORE\n\tfor (unsigned long n = 1; n < N-1; n++) {\n\t\tsolution[current_t_index][n] = sol(n-1);\n\t}\n}\n\n// Define the solve function for a single PDE\nvoid ConvectionDiffusionEulerImplicit::solve() {\n\twhile (current_time < t_bound) {\n\t\tcurrent_time += k;\n\t\tcurrent_t_index++;\n\t\tcalculate_boundary();\n\t\tcalculate_inner_mesh();\n\t}\n}\n", "meta": {"hexsha": "45a522b5ac68950ee19a2dcf37a2d2a6fa91221f", "size": 3108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OptionX/ConvectionDiffusionEulerImplicit.cpp", "max_stars_repo_name": "ENGN2912B-2018/FEM-A", "max_stars_repo_head_hexsha": "35dc7133e3fff49c3d0c090dfad44746eb7f9964", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OptionX/ConvectionDiffusionEulerImplicit.cpp", "max_issues_repo_name": "ENGN2912B-2018/FEM-A", "max_issues_repo_head_hexsha": "35dc7133e3fff49c3d0c090dfad44746eb7f9964", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OptionX/ConvectionDiffusionEulerImplicit.cpp", "max_forks_repo_name": "ENGN2912B-2018/FEM-A", "max_forks_repo_head_hexsha": "35dc7133e3fff49c3d0c090dfad44746eb7f9964", "max_forks_repo_licenses": ["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.7142857143, "max_line_length": 139, "alphanum_fraction": 0.6615186615, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6706531103059133}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2016.\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\n// Example program showing a bare metal real-time performance measurement\n// of a shift-and-add variation of sqrt(negatable), 32-bit.\n\n#include <cstdint>\n#include <limits>\n\n#include <mcal_benchmark.h>\n#include <mcal_cpu.h>\n#include <mcal_irq.h>\n\n#define BOOST_FIXED_POINT_DISABLE_IOSTREAM\n#define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION\n\n#include <boost/fixed_point/fixed_point.hpp>\n\ntypedef mcal::benchmark::benchmark_port_type port_type;\n\ntypedef boost::fixed_point::negatable<7, -24> fixed_point_type;\n\nextern const fixed_point_type x;\nextern       fixed_point_type y;\n\nnamespace shift\n{\n  fixed_point_type sqrt(const fixed_point_type& x);\n\n  // Computes the fixed-point square root using a shift-and-add algorithm.\n  // Adapted from sqrt found here: http://codepad.org/CqvPx5u0\n  // And this has beem modified from Ken Turkowski's algorithm.\n  // Despite the somewhat confusing description of the result in the white paper,\n  // the algorithm builds a M.F fixed-point square root.\n  // @see http://www.realitypixels.com/turk/computergraphics/FixedSqrt.pdf\n  fixed_point_type sqrt(const fixed_point_type& x)\n  {\n    typedef fixed_point_type::unsigned_small_type local_unsigned_small_type;\n    typedef fixed_point_type::nothing             local_nothing;\n\n    constexpr std::uint_fast8_t total_bits      = static_cast<std::uint_fast8_t>(fixed_point_type::all_bits);\n    constexpr std::uint_fast8_t fractional_bits = static_cast<std::uint_fast8_t>(fixed_point_type::radix_split);\n\n    local_unsigned_small_type root  = static_cast<local_unsigned_small_type>(0U);                  // Clear the root.\n    local_unsigned_small_type remHi = static_cast<local_unsigned_small_type>(0U);                  // Clear the high part of the partial remainder.\n    local_unsigned_small_type remLo = static_cast<local_unsigned_small_type>(x.crepresentation()); // Get the argument into the low part of the partial remainder.\n\n    for(std::uint_fast8_t count = (total_bits >> 1) + (fractional_bits >> 1); count > 0U; --count)\n    {\n      // Get 2 bits of the argument.\n      remHi = (remHi << 2) | (remLo >> (total_bits - 2));\n      remLo <<= 2;\n\n      // Get ready for the next bit in the root.\n      root <<= 1;\n\n      // Test the radical.\n      const local_unsigned_small_type testDiv = (root << 1) + 1;\n\n      if(remHi >= testDiv)\n      {\n        remHi = remHi - testDiv;\n\n        ++root;\n      }\n    }\n\n    return fixed_point_type(local_nothing(), root);\n  }\n\n} // namespace shift\n\nnamespace app\n{\n  namespace benchmark\n  {\n    void task_init();\n    void task_func();\n  }\n}\n\nvoid app::benchmark::task_init()\n{\n  port_type::set_direction_output();\n}\n\nvoid app::benchmark::task_func()\n{\n  mcal::irq::disable_all();\n  port_type::set_pin_high();\n\n  // Use either one of the following two lines (but not both)\n  // to benchmark variations of square root algorithms.\n\n  y = shift::sqrt(x);\n  //y = boost::fixed_point::sqrt(x);\n\n  port_type::set_pin_low();\n\n  mcal::irq::enable_all();\n}\n\nconst fixed_point_type x(fixed_point_type(6U) /  10U);\n      fixed_point_type y;\n", "meta": {"hexsha": "f6384917fa117c8d38ee8065eb158018c00a82d3", "size": 3339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_bare_metal_benchmark_32bit_sqrt_variation.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_benchmark_32bit_sqrt_variation.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_benchmark_32bit_sqrt_variation.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": 30.3545454545, "max_line_length": 162, "alphanum_fraction": 0.6915244085, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6706019789069454}}
{"text": "#define BOOST_TEST_MODULE \"test_vector_matrix\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include \"../LinearAlgebra.hpp\"\nusing Vector3d = ax::Vector<double, 3>;\nusing Vector4d = ax::Vector<double, 4>;\nusing Matrix3  = ax::Matrix3d;\nusing Matrix4  = ax::Matrix4d;\n\n#include \"test_Defs.hpp\"\nusing ax::test::tolerance;\nusing ax::test::seed;\n\n#include <random>\n\nBOOST_AUTO_TEST_CASE(vector3d_matrix3x3_multiplication)\n{\n    const Vector3d vec1(1e0, 2e0, 3e0);\n    const Matrix3  mat1(1e0);\n    const Vector3d vec2 = mat1 * vec1;\n\n    BOOST_CHECK_EQUAL(vec2[0], vec1[0]);\n    BOOST_CHECK_EQUAL(vec2[1], vec1[1]);\n    BOOST_CHECK_EQUAL(vec2[2], vec1[2]);\n\n    const Matrix3  mat2(2e0);\n    const Vector3d vec3 = mat2 * vec1;\n\n    BOOST_CHECK_EQUAL(vec3[0], 2e0 * vec1[0]);\n    BOOST_CHECK_EQUAL(vec3[1], 2e0 * vec1[1]);\n    BOOST_CHECK_EQUAL(vec3[2], 2e0 * vec1[2]);\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    Matrix3  mat3;\n    std::array<std::array<double, 3>, 3> random1;\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            random1[i][j] = randreal(mt);\n\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            mat3(i, j) = random1[i][j];\n\n    const Vector3d ones(1e0, 1e0, 1e0);\n    const Vector3d vec4 = mat3 * ones;\n    for(std::size_t i = 0; i < 3; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 3; ++j)\n            value += random1[i][j];\n        BOOST_CHECK_EQUAL(vec4[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(matrix3x3_vector3d_multiplication)\n{\n    const Vector3d vec1(1e0, 2e0, 3e0);\n    const Matrix3  mat1(1e0);\n    const Vector3d vec2 = vec1 * mat1;\n\n    BOOST_CHECK_EQUAL(vec2[0], vec1[0]);\n    BOOST_CHECK_EQUAL(vec2[1], vec1[1]);\n    BOOST_CHECK_EQUAL(vec2[2], vec1[2]);\n\n    const Matrix3  mat2(2e0);\n    const Vector3d vec3 = vec1 * mat2;\n\n    BOOST_CHECK_EQUAL(vec3[0], 2e0 * vec1[0]);\n    BOOST_CHECK_EQUAL(vec3[1], 2e0 * vec1[1]);\n    BOOST_CHECK_EQUAL(vec3[2], 2e0 * vec1[2]);\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    Matrix3  mat3;\n    std::array<std::array<double, 3>, 3> random1;\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            random1[i][j] = randreal(mt);\n\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            mat3(i, j) = random1[i][j];\n\n    const Vector3d ones(1e0, 1e0, 1e0);\n    const Vector3d vec4 = ones * mat3;\n    for(std::size_t i = 0; i < 3; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 3; ++j)\n            value += random1[j][i];\n        BOOST_CHECK_EQUAL(vec4[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector4d_matrix4x4_multiplication)\n{\n    const Vector4d vec1(2e0);\n    const Matrix4  mat1(1e0);\n    const Vector4d vec2 = mat1 * vec1;\n\n    for(std::size_t i = 0; i<4; ++i)\n        BOOST_CHECK_EQUAL(vec2[i], vec1[i]);\n\n    const Matrix4 mat2(2e0);\n    const Vector4d vec3 = mat2 * vec1;\n\n    for(std::size_t i = 0; i<4; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 2e0 * vec1[i]);\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    Matrix4  mat3;\n    std::array<std::array<double, 4>, 4> random1;\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            random1[i][j] = randreal(mt);\n\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            mat3(i, j) = random1[i][j];\n\n    const Vector4d ones(1e0);\n    const Vector4d vec4 = mat3 * ones;\n    for(std::size_t i = 0; i < 4; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 4; ++j)\n            value += random1[i][j];\n        BOOST_CHECK_EQUAL(vec4[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(matrix4x4_vector4d_multiplication)\n{\n    const Vector4d vec1(1e0);\n    const Matrix4  mat1(1e0);\n    const Vector4d vec2 = vec1 * mat1;\n\n    for(std::size_t i=0; i<4; ++i)\n        BOOST_CHECK_EQUAL(vec2[i], vec1[i]);\n\n    const Matrix4  mat2(2e0);\n    const Vector4d vec3 = vec1 * mat2;\n\n    for(std::size_t i=0; i<4; ++i)\n        BOOST_CHECK_EQUAL(vec3[i], 2e0 * vec1[i]);\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    Matrix4 mat3;\n    std::array<std::array<double, 4>, 4> random1;\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            random1.at(i).at(j) = randreal(mt);\n\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            mat3(i, j) = random1.at(i).at(j);\n\n    const Vector4d ones(1e0);\n    const Vector4d vec4 = ones * mat3;\n    for(std::size_t i = 0; i < 4; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 4; ++j)\n            value += random1[j][i];\n        BOOST_CHECK_EQUAL(vec4[i], value);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(matrix4x3_vector3d_multiplication)\n{\n    const Vector3d        vec1(1e0, 1e0, 1e0);\n    ax::Matrix<double, 4, 3>  mat1;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, 3>, 4> random1;\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            random1[i][j] = randreal(mt);\n\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            mat1(i, j) = random1[i][j];\n\n    const Vector4d   vec2 = mat1 * vec1;\n    for(std::size_t i = 0; i < 4; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 3; ++j)\n            value += random1[i][j];\n        BOOST_CHECK_EQUAL(vec2[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(matrix3x4_vector4d_multiplication)\n{\n    const Vector4d vec1(1e0);\n    for(std::size_t i=0; i<4;++i)\n        assert(vec1[i] == 1e0);\n    ax::Matrix<double, 3, 4>    mat1;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, 4>, 3> random1;\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            random1.at(i).at(j) = randreal(mt);\n\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            mat1(i, j) = random1.at(i).at(j);\n\n    const Vector3d vec2 = mat1 * vec1;\n    for(std::size_t i = 0; i < 3; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 4; ++j)\n            value += random1[i][j];\n        BOOST_CHECK_EQUAL(vec2[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector4d_matrix4x3_multiplication)\n{\n    const Vector4d vec1(1e0);\n    for(std::size_t i = 0; i<4; ++i)\n        assert(vec1[i] == 1e0);\n\n    ax::Matrix<double, 4, 3>    mat1;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, 3>, 4> random1;\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            random1[i][j] = randreal(mt);\n\n    for(std::size_t i = 0; i < 4; ++i)\n        for(std::size_t j = 0; j < 3; ++j)\n            mat1(i, j) = random1[i][j];\n\n    const Vector3d vec2 = vec1 * mat1;\n    for(std::size_t i = 0; i < 3; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 4; ++j)\n            value += random1[j][i];\n        BOOST_CHECK_EQUAL(vec2[i], value);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vector3d_matrix3x4_multiplication)\n{\n    const Vector3d vec1(1e0, 1e0, 1e0);\n    for(std::size_t i = 0; i<3; ++i)\n        assert(vec1[i] == 1e0);\n\n    ax::Matrix<double, 3, 4> mat1;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, 4>, 3> random1;\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            random1.at(i).at(j) = randreal(mt);\n\n    for(std::size_t i = 0; i < 3; ++i)\n        for(std::size_t j = 0; j < 4; ++j)\n            mat1(i, j) = random1.at(i).at(j);\n\n    const Vector4d vec2 = vec1 * mat1;\n    for(std::size_t i = 0; i < 4; ++i)\n    {\n        double value = 0e0;\n        for(std::size_t j = 0; j < 3; ++j)\n            value += random1[j][i];\n        BOOST_CHECK_EQUAL(vec2[i], value);\n    }\n}\n", "meta": {"hexsha": "91a1ad307b72694b332bd3988f9835791c0befaf", "size": 8326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_vector_matrix.cpp", "max_stars_repo_name": "ToruNiina/AX", "max_stars_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T13:56:31.000Z", "max_issues_repo_path": "test/test_vector_matrix.cpp", "max_issues_repo_name": "ToruNiina/AX", "max_issues_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_vector_matrix.cpp", "max_forks_repo_name": "ToruNiina/AX", "max_forks_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_forks_repo_licenses": ["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.9395973154, "max_line_length": 62, "alphanum_fraction": 0.5607734807, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6706019768375125}}
{"text": "#ifndef HYPSYS1D_MODEL_HPP\n#define HYPSYS1D_MODEL_HPP\n\n#include <cmath>\n#include <memory>\n\n#include <Eigen/Dense>\n#include <ancse/config.hpp>\n\n/// Interface for implementing different models,\n/// eg. Euler equations, Shallow-water equations\n///\n/// Add more functions to this interface if needed.\nclass Model {\n  public:\n    virtual ~Model() = default;\n\n    virtual Eigen::VectorXd flux(const Eigen::VectorXd &u) const = 0;\n    virtual Eigen::VectorXd eigenvalues(const Eigen::VectorXd &u) const = 0;\n    virtual Eigen::MatrixXd eigenvectors(const Eigen::VectorXd &u) const = 0;\n    virtual double max_eigenvalue(const Eigen::VectorXd &u) const = 0;\n\n    virtual Eigen::VectorXd cons_to_prim(const Eigen::VectorXd &u) const = 0;\n    virtual Eigen::VectorXd prim_to_cons(const Eigen::VectorXd &u) const = 0;\n\n    virtual int get_nvars() const = 0;\n    virtual std::string get_name() const = 0;\n};\n\nclass Burgers : public Model {\n  public:\n\n    Eigen::VectorXd flux(const Eigen::VectorXd &u) const override\n    {\n        Eigen::VectorXd f(n_vars);\n        f(0) = 0.5*u(0)*u(0);\n\n        return f;\n    }\n\n    Eigen::VectorXd eigenvalues(const Eigen::VectorXd &u) const override\n    {\n        Eigen::VectorXd eigvals(n_vars);\n        eigvals(0) = u(0);\n\n        return eigvals;\n    }\n\n    Eigen::MatrixXd eigenvectors(const Eigen::VectorXd &) const override\n    {\n        Eigen::MatrixXd eigvecs(n_vars, n_vars);\n        eigvecs (0,0) = 1;\n\n        return eigvecs;\n    }\n\n    double max_eigenvalue(const Eigen::VectorXd &u) const override {\n        return (eigenvalues(u).cwiseAbs()).maxCoeff();\n    }\n\n    Eigen::VectorXd cons_to_prim(const Eigen::VectorXd &u) const override {\n        return u;\n    }\n\n    Eigen::VectorXd prim_to_cons(const Eigen::VectorXd &u) const override {\n        return u;\n    }\n\n    int get_nvars() const override\n    {\n        return n_vars;\n    }\n\n    std::string get_name() const override\n    {\n        return \"burgers\";\n    }\n\n  private:\n    int n_vars = 1;\n};\n\n/// Euler equations\nclass Euler : public Model {\n  public:\n    \n    Eigen::VectorXd flux(const Eigen::VectorXd &u) const override;\n    \n    Eigen::VectorXd eigenvalues(const Eigen::VectorXd &u) const override;\n\n    Eigen::MatrixXd eigenvectors(const Eigen::VectorXd &u) const override;\n    \n    double max_eigenvalue(const Eigen::VectorXd &u) const override;\n\n    Eigen::VectorXd cons_to_prim(const Eigen::VectorXd &u_cons) const override;\n\n    Eigen::VectorXd prim_to_cons(const Eigen::VectorXd &u_prim) const override;\n    \n\n    void set_gamma(double gamma_)\n    {\n        gamma = gamma_;\n    }\n\n    double get_gamma() const\n    {\n        return gamma;\n    }\n\n    int get_nvars() const override\n    {\n        return n_vars;\n    }\n\n    std::string get_name() const override\n    {\n        return \"euler\";\n    }\n\n  private:\n    int n_vars = 3;\n    double gamma = 5./3.;\n};\n\n\nstd::shared_ptr<Model> make_model (const nlohmann::json &config);\n\n#endif // HYPSYS1D_MODEL_HPP\n", "meta": {"hexsha": "bebea960ada3fe1cb61086e361f7e866c714acea", "size": 2958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_handout/hyp_sys_1d/include/ancse/model.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": "series2_handout/hyp_sys_1d/include/ancse/model.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": "series2_handout/hyp_sys_1d/include/ancse/model.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": 22.9302325581, "max_line_length": 79, "alphanum_fraction": 0.646382691, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6705982979879272}}
{"text": "/*\n * 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 */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <random>\n#include <array>\n#include <boost/core/demangle.hpp>\n#include <boost/math/interpolators/bilinear_uniform.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::interpolators::bilinear_uniform;\n\ntemplate<class Real>\nvoid test_four_values()\n{\n    Real x0 = 0;\n    Real y0 = 0;\n    Real dx = 1;\n    Real dy = 1;\n    Real value = 1.5;\n    std::vector<Real> v(2*2, value);\n    auto v_copy = v;\n    auto ub = bilinear_uniform<decltype(v)>(std::move(v_copy), 2, 2, dx, dy, x0, y0);\n    for (Real x = x0; x <= x0 + dx; x += dx/8) {\n        for (Real y = y0; y <= y0 + dx; y += dy/8) {\n            CHECK_ULP_CLOSE(value, ub(x, y), 1);\n        }\n    }\n\n    // Now we test the unit square:\n    std::random_device rd;\n    std::uniform_real_distribution<Real> dis(1,2);\n\n    int i = 0;\n    while (i++ < 300) {\n        v[0] = dis(rd);\n        v[1] = dis(rd);\n        v[2] = dis(rd);\n        v[3] = dis(rd);\n\n        // See https://en.wikipedia.org/wiki/Bilinear_interpolation, section: Unit square\n        auto f = [&v](Real x, Real y) {\n            return v[0]*(1-x)*(1-y) + v[1]*x*(1-y) + v[2]*(1-x)*y + v[3]*x*y;\n        };\n\n        v_copy = v;\n        ub = bilinear_uniform<decltype(v_copy)>(std::move(v_copy), 2, 2, dx, dy, x0, y0);\n        for (Real x = x0; x <= x0 + dx; x += dx/16) {\n            for (Real y = y0; y <= y0 + dx; y += dy/16) {\n                CHECK_ULP_CLOSE(f(x,y), ub(x, y), 3);\n            }\n        }\n    }\n}\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::random_device rd;\n    std::uniform_real_distribution<Real> dis(1,2);\n    std::array<Real, 4> a{dis(rd), dis(rd), dis(rd), dis(rd)};\n    auto f = [&a](Real x, Real y) {\n        return a[0] + a[1]*x + a[2]*y + a[3]*x*y;\n    };\n\n    for (int rows = 2; rows < 20; ++rows) {\n        for (int cols = 2; cols < 20; ++cols) {\n            Real dx = dis(rd);\n            Real dy = dis(rd);\n            Real x0 = dis(rd);\n            Real y0 = dis(rd);\n            std::vector<Real> v(rows*cols, std::numeric_limits<Real>::quiet_NaN());\n            for (int i = 0; i < cols; ++i) {\n                for (int j = 0; j < rows; ++j) {\n                    v[j*cols + i] = f(x0 + i*dx, y0 + j*dy);\n                }\n            }\n            auto ub = bilinear_uniform<decltype(v)>(std::move(v), rows, cols, dx, dy, x0, y0);\n\n           for (Real x = x0; x < x0 + (cols-1)*dx; x += dx/8) {\n                for (Real y = y0; y < y0 + (rows-1)*dy; y += dy/8) {\n                    if (!CHECK_ULP_CLOSE(f(x,y), ub(x, y), 13)) {\n                        std::cerr << \" f(\" << x << \", \" << y << \") = \" << f(x,y) << \"\\n\";\n                        std::cerr << \"ub(\" << x << \", \" << y << \") = \" << ub(x,y) << \"\\n\";\n                    }\n                }\n            }\n        }\n    }\n}\n\n\n\nint main()\n{\n    test_four_values<float>();\n    test_four_values<double>();\n    test_four_values<long double>();\n    test_linear<double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "fb1d3d502e4044395aad671fb55493be6ee05ce6", "size": 3312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bilinear_uniform_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/bilinear_uniform_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/bilinear_uniform_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 30.1090909091, "max_line_length": 94, "alphanum_fraction": 0.4978864734, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.670590441073762}}
{"text": "#ifndef HELPERS_H\n#define HELPERS_H\n\n#include <Eigen/Core>\n\nusing Eigen::VectorXd;\n\n//\n// Helper functions to fit and evaluate polynomials.\n//\n\n// Evaluate a polynomial.\ndouble polyeval(const 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\nVectorXd polyfit(const VectorXd &xvals, const VectorXd &yvals, int order) {\n  assert(xvals.size() == yvals.size());\n  assert(order >= 1 && order <= xvals.size() - 1);\n\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\n  return result;\n}\n\n#endif  // HELPERS_H\n", "meta": {"hexsha": "a20812dbaa3d264397b0894d68b7839a08faa6bb", "size": 994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mpc_to_line/include/helpers.hpp", "max_stars_repo_name": "Horki/CarND-MPC-Quizzes", "max_stars_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mpc_to_line/include/helpers.hpp", "max_issues_repo_name": "Horki/CarND-MPC-Quizzes", "max_issues_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpc_to_line/include/helpers.hpp", "max_forks_repo_name": "Horki/CarND-MPC-Quizzes", "max_forks_repo_head_hexsha": "236dc2f99a0f641efcbe8eac9cf4aa7e8db06a69", "max_forks_repo_licenses": ["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.1489361702, "max_line_length": 87, "alphanum_fraction": 0.6036217304, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.670585018061566}}
{"text": "#define BOOST_TEST_MODULE GraphLaplacian\n#include <boost/test/unit_test.hpp>\n\n#include <utility>\n#include <vector>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <graph_laplacian.hpp>\n\n\n// An matrix equality check copied from: http://lists.boost.org/Archives/boost/2005/11/96235.php\ntemplate<class E>\nbool equal(boost::numeric::ublas::matrix<E> lhs, boost::numeric::ublas::matrix<E> rhs)\n{\n  if (&lhs == &rhs) { return true; }\n  if (lhs.size1() != rhs.size1()) { return false; }\n  if (lhs.size2() != rhs.size2()) { return false; }\n  typename boost::numeric::ublas::matrix<E>::iterator1 l(lhs.begin1());\n  typename boost::numeric::ublas::matrix<E>::iterator1 r(rhs.begin1());\n  while (l != lhs.end1()) {\n    if (*l != *r) { return false; }\n    ++l;\n    ++r;\n  }\n  return true;\n}\n\nusing Graph = boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS>;\nusing Matrix = boost::numeric::ublas::matrix<int>;\n\nBOOST_AUTO_TEST_SUITE(TestGraphLaplacian)\n\n// An empty graph produces an empty matrix\nBOOST_AUTO_TEST_CASE(EmptyGraphTest)\n{\n  Graph g;\n\n  BOOST_CHECK(equal(graph_laplacian(g), Matrix(0, 0)));\n}\n\n// A graph with n vertices and no edges produces an (n x n)-zero matrix\nBOOST_AUTO_TEST_CASE(NoEdgesTest)\n{\n  Graph g(5);\n\n  BOOST_CHECK(equal(graph_laplacian(g), Matrix(5, 5, 0)));\n}\n\n// A graph with two vertices and an edge connecting them produces the following Laplacian matrix:\n//  1 -1\n// -1  1\nBOOST_AUTO_TEST_CASE(TwoVerticesOneEdgeGraphTest)\n{\n  using Edge = std::pair<int, int>;\n  std::vector<Edge> edges { Edge(0, 1) };\n  Graph g(edges.begin(), edges.end(), 2);\n\n  Matrix expected_mat(2, 2);\n  expected_mat <<=  1, -1,\n                   -1,  1;\n\n  BOOST_CHECK(equal(graph_laplacian(g), expected_mat));\n}\n\n// A free tree on 3 vertices (vertex 1 is the center vertex) produces following Laplacian matrix:\n//  1 -1  0\n// -1  2 -1\n//  0 -1  1\nBOOST_AUTO_TEST_CASE(ThreeVerticesFreeTreeTest)\n{\n  using Edge = std::pair<int, int>;\n  std::vector<Edge> edges { Edge(0, 1), Edge(1, 2) };\n  Graph g(edges.begin(), edges.end(), 3);\n\n  Matrix expected_mat(3, 3);\n  expected_mat <<=  1, -1,  0,\n                   -1,  2, -1,\n                    0, -1,  1;\n\n  BOOST_CHECK(equal(graph_laplacian(g), expected_mat));\n}\n\n// A free tree on 4 vertices (vertices 1, 2 are the middle vertices) produces following\n// Laplacian matrix:\n//  1 -1  0  0\n// -1  2 -1  0\n//  0 -1  2 -1\n//  0  0 -1  1\nBOOST_AUTO_TEST_CASE(FourVerticesFreeTreeTest)\n{\n  using Edge = std::pair<int, int>;\n  std::vector<Edge> edges { Edge(0, 1), Edge(1, 2), Edge(2, 3) };\n  Graph g(edges.begin(), edges.end(), 4);\n\n  Matrix expected_mat(4, 4);\n  expected_mat <<=  1, -1,  0,  0,\n                   -1,  2, -1,  0,\n                    0, -1,  2, -1,\n                    0,  0, -1,  1;\n\n  BOOST_CHECK(equal(graph_laplacian(g), expected_mat));\n}\n\n// A graph forming a square with 4 vertices produces follwoing Laplacian matrix:\n//  2 -1  0 -1\n// -1  2 -1  0\n//  0 -1  2 -1\n// -1  0 -1  2\nBOOST_AUTO_TEST_CASE(SquareTest)\n{\n  using Edge = std::pair<int, int>;\n  std::vector<Edge> edges { Edge(0, 1), Edge(1, 2), Edge(2, 3), Edge(3, 0) };\n  Graph g(edges.begin(), edges.end(), 4);\n\n  Matrix expected_mat(4, 4);\n  expected_mat <<=  2, -1,  0, -1,\n                   -1,  2, -1,  0,\n                    0, -1,  2, -1,\n                   -1,  0, -1,  2;\n\n  BOOST_CHECK(equal(graph_laplacian(g), expected_mat));\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // TestGraphLaplacian\n", "meta": {"hexsha": "6f77db60df7d8cbba26cc1e233a1f7fa879680d9", "size": 3604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_graph_laplacian.cpp", "max_stars_repo_name": "BerndSchwarzenbacher/Graph-Laplace", "max_stars_repo_head_hexsha": "ac1a64dd1fce26a2b2e3c9aa51fafabfe15c4983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-09T07:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-09T07:47:44.000Z", "max_issues_repo_path": "tests/test_graph_laplacian.cpp", "max_issues_repo_name": "BerndSchwarzenbacher/Graph-Laplace", "max_issues_repo_head_hexsha": "ac1a64dd1fce26a2b2e3c9aa51fafabfe15c4983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_graph_laplacian.cpp", "max_forks_repo_name": "BerndSchwarzenbacher/Graph-Laplace", "max_forks_repo_head_hexsha": "ac1a64dd1fce26a2b2e3c9aa51fafabfe15c4983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-02-02T23:16:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-23T05:50:50.000Z", "avg_line_length": 27.5114503817, "max_line_length": 97, "alphanum_fraction": 0.6270810211, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6705316119982723}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n  MatrixXd m(2,2);\n  m(0,0) = 3;\n  m(1,0) = 2.5;\n  m(0,1) = -1;\n  m(1,1) = m(1,0) + m(0,1);\n  std::cout << \"Here is the matrix m:\\n\" << 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\" << v << std::endl;\n\n}\n", "meta": {"hexsha": "6d982b6e1ae9bf4315ee80e2fccf488ce2758938", "size": 344, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/tut_matrix_coefficient_accessors.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/tut_matrix_coefficient_accessors.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/tut_matrix_coefficient_accessors.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": 17.2, "max_line_length": 59, "alphanum_fraction": 0.5029069767, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6703442142876903}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\n\nint main(){\n  const int nrows = 20;\n  const int ncols = 10;\n\n  MatrixXd grid(nrows, ncols);\n  grid = MatrixXd::Zero(nrows, ncols);\n\n  std::cout << grid << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "bb5604c5fffe50019bcf379b39fed1e5d62afa83", "size": 251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "Kabegami/tetris", "max_stars_repo_head_hexsha": "af16579f2038766f4f054d315e16ac1f12a2cb2b", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "Kabegami/tetris", "max_issues_repo_head_hexsha": "af16579f2038766f4f054d315e16ac1f12a2cb2b", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "Kabegami/tetris", "max_forks_repo_head_hexsha": "af16579f2038766f4f054d315e16ac1f12a2cb2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7647058824, "max_line_length": 38, "alphanum_fraction": 0.6414342629, "num_tokens": 72, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6703442017334512}}
{"text": "#include <sm/kinematics/quaternion_algebra.hpp>\n#include <sm/kinematics/rotations.hpp>\n#include <sm/assert_macros.hpp>\n#include <Eigen/Geometry>\n#include <limits>\n#include <cmath>\n\nnamespace sm { namespace kinematics {\n        template <typename Scalar_ = double>\n        inline bool isLessThenEpsilons4thRoot(Scalar_ x){\n          static const Scalar_ epsilon4thRoot = pow(std::numeric_limits<Scalar_>::epsilon(), 1.0/4.0);\n          return x < epsilon4thRoot;\n        }\n\n        // quaternion rotation.\n        Eigen::Vector4d r2quat(Eigen::Matrix3d const & R){\n      \n            const double & c1 = R(0,0);\n            const double & c2 = R(1,0);\n            const double & c3 = R(2,0);\n            const double & c4 = R(0,1);\n            const double & c5 = R(1,1);\n            const double & c6 = R(2,1);\n            const double & c7 = R(0,2);\n            const double & c8 = R(1,2);\n            const double & c9 = R(2,2);\n\n            Eigen::Vector4d dc(fabs(1.0+c1-c5-c9),\n                               fabs(1.0-c1+c5-c9),\n                               fabs(1.0-c1-c5+c9),\n                               fabs(1.0+c1+c5+c9));\n\n            unsigned maxq = 0;\n            double maxqval = dc(0);\n\n            for(unsigned i = 1; i < 4; i++) {\n                if(dc(i) > maxqval) {\n                    maxq = i;\n                    maxqval = dc(i);\n                }\n            }\n\n            double c;\n            Eigen::Vector4d q;\n            if(maxq == 0){\n                q(0)=0.5*sqrt(dc(0));\n                c = 0.25/q(0);\n                q(1)=c*(c4+c2);\n                q(2)=c*(c7+c3);\n                q(3)=c*(c8-c6);\n            } else if(maxq == 1){\n                q(1)=0.5*sqrt(dc(1));\n                c = 0.25/q(1);\n                q(0)=c*(c4+c2);\n                q(2)=c*(c6+c8);\n                q(3)=c*(c3-c7);\n            } else if(maxq == 2){\n                q(2)=0.5*sqrt(dc(2));\n                c = 0.25/q(2);\n                q(0)=c*(c3+c7);\n                q(1)=c*(c6+c8);\n                q(3)=c*(c4-c2);\n            } else {\n                q(3)=0.5*sqrt(dc(3));\n                c = 0.25/q(3);\n                q(0)=c*(c8-c6);\n                q(1)=c*(c3-c7);\n                q(2)=c*(c4-c2);\n            }\n\n            if(q(3) < 0)\n                q = -q;\n\n            return q;\n        }\n\n        Eigen::Matrix3d quat2r(Eigen::Vector4d const & q){\n    \n            SM_ASSERT_NEAR_DBG(std::runtime_error,q.norm(),1.f,1e-4, \"The quaternion must be a unit vector to represent a rotation\");\n            //double n = q(3);\n            //Eigen::Vector3d e = makeV3(q(0),q(1),q(2));\n            //R = (n^2 - e'*e) * eye(3) + 2 * e * e' + 2 * n * crossMx(e);\n            //Eigen::Matrix3d R = (n*n - e.dot(e))*Eigen::Matrix3d::Identity() + 2 * e * e.transpose() + 2 * n * crossMx(e);\n    \n            Eigen::Matrix3d R;\n\n            // [ q0^2 - q1^2 - q2^2 + q3^2,           2*q0*q1 + 2*q2*q3,           2*q0*q2 - 2*q1*q3]\n            // [         2*q0*q1 - 2*q2*q3, - q0^2 + q1^2 - q2^2 + q3^2,           2*q0*q3 + 2*q1*q2]\n            // [         2*q0*q2 + 2*q1*q3,           2*q1*q2 - 2*q0*q3, - q0^2 - q1^2 + q2^2 + q3^2]\n            R(0,0) = q[0]*q[0]-q[1]*q[1]-q[2]*q[2]+q[3]*q[3];\n            R(0,1) = q[0]*q[1]*2.0+q[2]*q[3]*2.0;\n            R(0,2) = q[0]*q[2]*2.0-q[1]*q[3]*2.0;\n            R(1,0) = q[0]*q[1]*2.0-q[2]*q[3]*2.0;\n            R(1,1) = -q[0]*q[0]+q[1]*q[1]-q[2]*q[2]+q[3]*q[3];\n            R(1,2) = q[0]*q[3]*2.0+q[1]*q[2]*2.0;\n            R(2,0) = q[0]*q[2]*2.0+q[1]*q[3]*2.0;\n            R(2,1) = q[0]*q[3]*(-2.0)+q[1]*q[2]*2.0;\n            R(2,2) = -q[0]*q[0]-q[1]*q[1]+q[2]*q[2]+q[3]*q[3];\n\n            return R;\n        }\n\n\n        Eigen::Matrix4d quatPlus(Eigen::Vector4d const & q)\n        {\n            // [  q3,  q2, -q1, q0]\n            // [ -q2,  q3,  q0, q1]\n            // [  q1, -q0,  q3, q2]\n            // [ -q0, -q1, -q2, q3]\n            Eigen::Matrix4d Q;\n            Q(0,0) =  q[3]; Q(0,1) =  q[2]; Q(0,2) = -q[1]; Q(0,3) =  q[0];\n            Q(1,0) = -q[2]; Q(1,1) =  q[3]; Q(1,2) =  q[0]; Q(1,3) =  q[1];\n            Q(2,0) =  q[1]; Q(2,1) = -q[0]; Q(2,2) =  q[3]; Q(2,3) =  q[2];\n            Q(3,0) = -q[0]; Q(3,1) = -q[1]; Q(3,2) = -q[2]; Q(3,3) =  q[3];\n\n            return Q;\n        }\n\n        Eigen::Matrix4d quatOPlus(Eigen::Vector4d const & q)\n        {\n            // [  q3, -q2,  q1, q0]\n            // [  q2,  q3, -q0, q1]\n            // [ -q1,  q0,  q3, q2]\n            // [ -q0, -q1, -q2, q3]\n\n            Eigen::Matrix4d Q;\n            Q(0,0) =  q[3]; Q(0,1) = -q[2]; Q(0,2) =  q[1]; Q(0,3) =  q[0];\n            Q(1,0) =  q[2]; Q(1,1) =  q[3]; Q(1,2) = -q[0]; Q(1,3) =  q[1];\n            Q(2,0) = -q[1]; Q(2,1) =  q[0]; Q(2,2) =  q[3]; Q(2,3) =  q[2];\n            Q(3,0) = -q[0]; Q(3,1) = -q[1]; Q(3,2) = -q[2]; Q(3,3) =  q[3];\n\n            return Q;\n\n        }\n\n        Eigen::Vector4d qplus(Eigen::Vector4d const & q, Eigen::Vector4d const & p)\n        {\n            Eigen::Vector4d qplus_p;\n            // p0*q3 + p1*q2 - p2*q1 + p3*q0\n            qplus_p[0] = p[0]*q[3] + p[1]*q[2] - p[2]*q[1] + p[3]*q[0];\n            // p2*q0 - p0*q2 + p1*q3 + p3*q1\n            qplus_p[1] = p[2]*q[0] - p[0]*q[2] + p[1]*q[3] + p[3]*q[1];\n            // p0*q1 - p1*q0 + p2*q3 + p3*q2\n            qplus_p[2] = p[0]*q[1] - p[1]*q[0] + p[2]*q[3] + p[3]*q[2];\n            // p3*q3 - p1*q1 - p2*q2 - p0*q0\n            qplus_p[3] = p[3]*q[3] - p[1]*q[1] - p[2]*q[2] - p[0]*q[0];\n\n            return qplus_p;\n        }\n\n        Eigen::Vector4d qoplus(Eigen::Vector4d const & q, Eigen::Vector4d const & p)\n        {\n            Eigen::Vector4d qoplus_p;\n            // p0*q3 - p1*q2 + p2*q1 + p3*q0\n            qoplus_p[0] = p[0]*q[3] - p[1]*q[2] + p[2]*q[1] + p[3]*q[0];\n            // p0*q2 - p2*q0 + p1*q3 + p3*q1\n            qoplus_p[1] = p[0]*q[2] - p[2]*q[0] + p[1]*q[3] + p[3]*q[1];\n            // p1*q0 - p0*q1 + p2*q3 + p3*q2\n            qoplus_p[2] = p[1]*q[0] - p[0]*q[1] + p[2]*q[3] + p[3]*q[2];\n            // p3*q3 - p1*q1 - p2*q2 - p0*q0\n            qoplus_p[3] = p[3]*q[3] - p[1]*q[1] - p[2]*q[2] - p[0]*q[0];\n\n            return qoplus_p;\n        }\n\n        Eigen::Vector4d quatInv(Eigen::Vector4d const & q)\n        {\n            Eigen::Vector4d qret = q;\n            invertQuat(qret);\n            return qret;\n        }\n\n        void invertQuat(Eigen::Vector4d & q)\n        {\n            q.head<3>() = -q.head<3>();\n        }\n\n\n        Eigen::Vector3d qeps(Eigen::Vector4d const & q)\n        {\n            return q.head<3>();\n        }\n\n        Eigen::Vector3f qeps(Eigen::Vector4f const & q)\n        {\n            return q.head<3>();\n        }\n\n        double qeta(Eigen::Vector4d const & q)\n        {\n            return q[3];\n        }\n\n        float qeta(Eigen::Vector4f const & q)\n        {\n            return q[3];\n        }\n\n\n        Eigen::Vector4d axisAngle2quat(Eigen::Vector3d const & a)\n        {\n            // Method of implementing this function that is accurate to numerical precision from\n            // Grassia, F. S. (1998). Practical parameterization of rotations using the exponential map. journal of graphics, gpu, and game tools, 3(3):29\u201348.\n      \n            double theta = a.norm();\n\n            // na is 1/theta sin(theta/2)\n            double na;\n            if(isLessThenEpsilons4thRoot(theta))\n            {\n                static const double one_over_48 = 1.0/48.0;\n                na = 0.5 + (theta * theta) * one_over_48;\n            }\n            else\n            {\n                na = sin(theta*0.5) / theta; \n            }\n            Eigen::Vector3d axis = a*na;\n            double ct = cos(theta*0.5);\n            return Eigen::Vector4d(axis[0],axis[1],axis[2],ct);\n        }\n\n        /**\n         * calculate arcsin(x)/x\n         * @param x\n         * @return\n         */\n        template <typename Scalar_>\n        inline Scalar_ arcSinXOverX(Scalar_ x) {\n          if(isLessThenEpsilons4thRoot(fabs(x))){\n            return Scalar_(1.0) + x * x * Scalar_(1/6);\n          }\n          return asin(x) / x;\n        }\n\n        template <typename Scalar_>\n        Eigen::Matrix<Scalar_, 3, 1> quat2AxisAngle(Eigen::Matrix<Scalar_, 4, 1> const & q)\n        {\n          SM_ASSERT_LT_DBG(std::runtime_error, fabs(q.norm() - 1), 8 * std::numeric_limits<Scalar_>::epsilon(), \"This function is inteded for unit quternions only.\");\n          const Eigen::Matrix<Scalar_, 3, 1> a = qeps(q);\n          const Scalar_ na = a.norm(), eta = qeta(q);\n          Scalar_ scale;\n          if(fabs(eta) < na){ // use eta because it is more precise than na to calculate the scale. No singularities here.\n            scale = acos(eta) / na;\n          } else {\n            /*\n             * In this case more precision is in na than in eta so lets use na only to calculate the scale:\n             *\n             * assume first eta > 0 and 1 > na > 0.\n             *               u = asin (na) / na  (this implies u in [1, pi/2], because na i in [0, 1]\n             *    sin (u * na) = na\n             *  sin^2 (u * na) = na^2\n             *  cos^2 (u * na) = 1 - na^2\n             *                              (1 = ||q|| = eta^2 + na^2)\n             *    cos^2 (u * na) = eta^2\n             *                              (eta > 0,  u * na = asin(na) in [0, pi/2] => cos(u * na) >= 0 )\n             *      cos (u * na) = eta\n             *                              (u * na in [ 0, pi/2] )\n             *                 u = acos (eta) / na\n             *\n             * So the for eta > 0 it is acos(eta) / na == asin(na) / na.\n             * From some geometric considerations (mirror the setting at the hyper plane q==0) it follows for eta < 0 that (pi - asin(na)) / na = acos(eta) / na.\n             */\n            if(eta > 0){\n              // For asin(na)/ na the singularity na == 0 can be removed. We can ask (e.g. Wolfram alpha) for its series expansion at na = 0. And that is done in the following function.\n              scale = arcSinXOverX(na);\n            }else{\n              // (pi - asin(na))/ na has a pole at na == 0. So we cannot remove this singularity.\n              // It is just the cut locus of the unit quaternion manifold at identity and thus the axis angle description becomes necessarily unstable there.\n              scale = (M_PI - asin(na)) / na;\n            }\n          }\n          return a * (Scalar_(2) * scale);\n        }\n        template Eigen::Matrix<double, 3, 1> quat2AxisAngle(Eigen::Matrix<double, 4, 1> const & q);\n        template Eigen::Matrix<float, 3, 1> quat2AxisAngle(Eigen::Matrix<float, 4, 1> const & q);\n\n        Eigen::Matrix<double,4,3> quatJacobian(Eigen::Vector4d const & p)\n        {\n            Eigen::Matrix<double,4,3> J;\n            // [  p3, -p2,  p1]\n            // [  p2,  p3, -p0]\n            // [ -p1,  p0,  p3]\n            // [ -p0, -p1, -p2]\n    \n            J(0,0) =  p[3];\n            J(0,1) = -p[2];\n            J(0,2) =  p[1];\n            J(1,0) =  p[2];\n            J(1,1) =  p[3];\n            J(1,2) = -p[0];\n            J(2,0) = -p[1];\n            J(2,1) =  p[0];\n            J(2,2) =  p[3];\n            J(3,0) = -p[0];\n            J(3,1) = -p[1];\n            J(3,2) = -p[2];\n\n            return J*0.5;\n        }\n\n        Eigen::Vector4d updateQuat(Eigen::Vector4d const & q, Eigen::Vector3d const & dq)\n        {\n            // the following code is an optimized version of:\n            // Eigen::Vector4d dq4 = axisAngle2quat(dq);\n            // Eigen::Vector4d retq = quatPlus(dq4)*q;\n            // return retq;\n\n            Eigen::Vector4d dq3 = axisAngle2quat(dq);\n            double ca = dq3[3];\n            Eigen::Vector4d retq;\n            retq[0] = q[0]*ca+dq3[0]*q[3]-dq3[1]*q[2]+dq3[2]*q[1];\n            retq[1] = q[1]*ca+dq3[0]*q[2]+dq3[1]*q[3]-dq3[2]*q[0];\n            retq[2] = q[2]*ca-dq3[0]*q[1]+dq3[1]*q[0]+dq3[2]*q[3];\n            retq[3] = q[3]*ca-dq3[0]*q[0]-dq3[1]*q[1]-dq3[2]*q[2];\n\n            return retq;\n        }\n\n        Eigen::Vector3d quatRotate(Eigen::Vector4d const & q_a_b, Eigen::Vector3d const & v_b)\n        {\n            return v_b + 2.0 * q_a_b.head<3>().cross(q_a_b.head<3>().cross(v_b) - q_a_b[3] * v_b);\n        }\n\n        Eigen::Vector4d quatRandom()\n        {\n            Eigen::Vector4d q_a_b;\n            q_a_b.setRandom();\n            q_a_b.array() -= 0.5;\n            q_a_b /= q_a_b.norm();\n            return q_a_b;\n        }\n\n        Eigen::Vector4d quatIdentity()\n        {\n            return Eigen::Vector4d(0,0,0,1);\n        }\n\n        Eigen::Matrix<double,3,4> quatS(Eigen::Vector4d q)\n        {\n            //   [  q3,  q2, -q1, -q0]\n            // 2 [ -q2,  q3,  q0, -q1]\n            //   [  q1, -q0,  q3, -q2]\n            q *= 2.0;\n      \n            Eigen::Matrix<double,3,4> S;\n            S <<\n                q[3],  q[2], -q[1], -q[0],\n                -q[2],  q[3],  q[0], -q[1],\n                q[1], -q[0],  q[3], -q[2];\n\n            return S;\n        }\n\n        Eigen::Matrix<double,4,3> quatInvS(Eigen::Vector4d q)\n        {\n            q *= 0.5;\n\n            // 1 [  q3, -q2,  q1]\n            // - [  q2,  q3, -q0]\n            // 2 [ -q1,  q0,  q3]\n            //   [ -q0, -q1, -q2]\n\n\n            Eigen::Matrix<double,4,3> invS;\n            invS <<\n                q[3], -q[2],  q[1],\n                q[2],  q[3], -q[0],\n                -q[1],  q[0],  q[3],\n                -q[0], -q[1], -q[2];\n            return invS;\n        }\n\n        Eigen::Vector4d qslerp(const Eigen::Vector4d & q0, const Eigen::Vector4d & q1, double t)\n        {\n          if(t <= 0.0)\n            {\n                return q0;\n            }\n            else if(t >= 1.0)\n            {\n                return q1;\n            }\n            else\n            {\n              if( (q0-q1).squaredNorm() > (q0 + q1).squaredNorm() ) {\n                // The quaternions are far away from eachother on the sphere.\n                // Flip one around so that this works out.\n                return qplus(q0, qexp(t * qlog( qplus(quatInv(q0),-q1))));\n              } else {\n                return qplus(q0, qexp(t * qlog( qplus(quatInv(q0),q1))));\n              }\n                \n            }\n        }\n        \n\n        /// \\brief do linear interpolation between p0 and p1 for times t = [0.0,1.0]\n        Eigen::VectorXd lerp(const Eigen::VectorXd & p0, const Eigen::VectorXd & p1, double t)\n        {\n            SM_ASSERT_EQ(std::runtime_error, p0.size(), p1.size(), \"The vectors must be the same size\");\n            if(t <= 0.0)\n            {\n                return p0;\n            }\n            else if(t >= 1.0)\n            {\n                return p1;\n            }\n            else\n            {\n                return (1-t) * p0  +  t * p1;\n            }\n        }\n\n        Eigen::Matrix<double,3,4> quatLogJacobian(const Eigen::Vector4d& p)\n        {\n          //      [qx]\n          //      [qy]                -2*x\n          // p =  [qz],    g(x) = ----------------\n          //      [qw]               sqrt(1-qw\u00b2)\n          //\n          //\n          //      [2*acos(qw)      0            0            g(qx)]\n          // J =  [0            2*acos(qw)      0            g(qy)]\n          //      [0            0            2*acos(qw)      g(qz)]\n\n\n          Eigen::Matrix<double, 3,4> J;\n          J.setZero();\n\n          double n = qeps(p).norm();\n\n\n          double de = n*n*n;//pow(n, 3);\n          double u12 = p(1)*p(1) + p(2)*p(2);//pow(p(1), 2) + pow(p(2), 2);\n          double u02 = p(0)*p(0) + p(2)*p(2);//pow(p(0), 2) + pow(p(2), 2);\n          double u01 = p(0)*p(0) + p(1)*p(1);//pow(p(0), 2) + pow(p(1), 2);\n          double a = acos(p(3));\n          double uw = sqrt(-(p(3)*p(3) - 1)*n*n);\n\n          J(0,0) = 2*a*u12 / de;\n          J(0,1) = -2*a*p(1)*p(0) / de;\n          J(0,2) = -2*a*p(2)*p(0) / de;\n          J(0,3) = -2*p(0) / uw;\n          J(1,0) = -2*a*p(0)*p(1) / de;\n          J(1,1) = 2*a*u02 / de;\n          J(1,2) = -2*a*p(1)*p(2) / de;\n          J(1,3) = -2*p(1) / uw;\n          J(2,0) = -2*a*p(0)*p(2) / de;\n          J(2,1) = -2*a*p(1)*p(2) / de;\n          J(2,2) = 2*a*u01 / de;\n          J(2,3) = -2*p(2) / uw;\n\n          return J;\n        }\n\n        template <typename Scalar_>\n        inline const typename Eigen::Matrix<Scalar_, 4, 3> & quatV(){\n          static const Eigen::Matrix<Scalar_, 4, 3> V = 0.5 * Eigen::Matrix<Scalar_, 4, 3>::Identity();\n          return V;\n        }\n        template const Eigen::Matrix<double, 4, 3> & quatV();\n        template const Eigen::Matrix<float, 4, 3> & quatV();\n\n\n        template <typename Scalar_>\n        Eigen::Matrix<Scalar_, 3, 3> expDiffMat(const Eigen::Matrix<Scalar_, 3, 1> & vec){\n          Scalar_ phi = vec.norm();\n\n          if(phi == 0){\n            return Eigen::Matrix<Scalar_, 3, 3>::Identity();\n          }\n\n          Eigen::Matrix<Scalar_, 3, 3> vecCross = crossMx(vec);\n\n          Scalar_ phiAbs = fabs(phi);\n          Scalar_ phiSquare = phi * phi;\n\n          Scalar_ a;\n          Scalar_ b;\n          if(!isLessThenEpsilons4thRoot(phiAbs)){\n            Scalar_ siPhiHalf = sin(phi / 2);\n            a = (2 * siPhiHalf * siPhiHalf / phiSquare);\n            b = ((1 - sin(phi) / phi)/phiSquare);\n          }\n          else{\n            a = (1.0/2) * (1 - (1.0 / (24 / 2)) * phiSquare);\n            b = (1.0/6) * (1 - (1.0 / (120 / 6)) * phiSquare);\n          }\n\n          return Eigen::Matrix<Scalar_, 3, 3>::Identity() - a * vecCross + b * vecCross * vecCross;\n        }\n        template Eigen::Matrix<double, 3, 3> expDiffMat<double>(const Eigen::Matrix<double, 3, 1>  &);\n        template Eigen::Matrix<float, 3, 3> expDiffMat<float>(const Eigen::Matrix<float, 3, 1>  &);\n\n        template <typename Scalar_>\n        Eigen::Matrix<Scalar_ , 4, 3> quatExpJacobian(const Eigen::Matrix<Scalar_ , 3, 1>& vec){\n          return quatOPlus(axisAngle2quat(vec.template cast<double>())).template cast<Scalar_>() * quatV<Scalar_>() * expDiffMat(vec);\n        }\n        template Eigen::Matrix<double, 4,3> quatExpJacobian(const Eigen::Matrix<double, 3, 1>& vec);\n        template Eigen::Matrix<float, 4,3> quatExpJacobian(const Eigen::Matrix<float, 3, 1>& vec);\n\n        template <typename Scalar_>\n        Eigen::Matrix<Scalar_, 3, 3> logDiffMat(const Eigen::Matrix<Scalar_, 3, 1>  & vec){\n          Scalar_ phi = vec.norm();\n          if(phi == 0){\n            return Eigen::Matrix<Scalar_, 3, 3>::Identity();\n          }\n\n          Scalar_ phiAbs = fabs(phi);\n          Eigen::Matrix<Scalar_, 3, 3> vecCross = crossMx(vec);\n\n          Scalar_ a;\n          if(!isLessThenEpsilons4thRoot(phiAbs)){\n            Scalar_ phiHalf = 0.5 * phi;\n            a = ((1 - phiHalf / tan(phiHalf))/phi/phi);\n          }\n          else{\n            a = 1.0 / 12 * (1 + 1.0 / 60 * phi * phi);\n          }\n          return Eigen::Matrix<Scalar_, 3, 3>::Identity() + 0.5 * vecCross + a * vecCross * vecCross;\n        }\n        template Eigen::Matrix<double, 3, 3> logDiffMat<double>(const Eigen::Matrix<double, 3, 1>  &);\n        template Eigen::Matrix<float, 3, 3> logDiffMat<float>(const Eigen::Matrix<float, 3, 1>  &);\n\n        template <typename Scalar_>\n        Eigen::Matrix<Scalar_ , 3, 4> quatLogJacobian2(const Eigen::Matrix<Scalar_ , 4, 1>& p){\n          return logDiffMat(quat2AxisAngle<>(p)) * (quatV<Scalar_>().transpose() * Scalar_(4.0)) * quatOPlus(quatInv(p.template cast<double>())).template cast<Scalar_>();\n        }\n        \n        template Eigen::Matrix<double, 3, 4> quatLogJacobian2(const Eigen::Matrix<double, 4, 1>&);\n        template Eigen::Matrix<float, 3, 4> quatLogJacobian2(const Eigen::Matrix<float, 4, 1>& );\n    }} // namespace sm::kinematics\n\n", "meta": {"hexsha": "d195914f3c2c38b52bfd813d43e7d720a642b2fe", "size": 19566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 36.5037313433, "max_line_length": 185, "alphanum_fraction": 0.4239497087, "num_tokens": 6769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658464, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6702786001925382}}
{"text": "//----------------------------------*-C++-*----------------------------------//\n/**\n *  @file   SphericalHarmonics.cc\n *  @author Jeremy Roberts\n *  @date   Jun 30, 2011\n *  @brief  SphericalHarmonics member definitions\n */\n//---------------------------------------------------------------------------//\n\n#include \"SphericalHarmonics.hh\"\n#include \"utilities/Constants.hh\"\n#include \"utilities/DBC.hh\"\n#include \"utilities/GenException.hh\"\n#include \"utilities/SoftEquivalence.hh\"\n#include <cmath>\n#ifdef DETRAN_ENABLE_BOOST\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#endif\n\nnamespace detran_angle\n{\n\n// Calculate the spherical harmonic of degree l, order m\n// given  cos(polar) and azimuthal angle\ndouble SphericalHarmonics::Y_lm(const int    l,\n                                const int    m,\n                                const double xi,\n                                const double varphi )\n{\n    Require (xi >= -1.0);\n    Require (xi <= 1.0);\n    Require (varphi >= 0.0);\n    Require (varphi <= detran_utilities::two_pi);\n\n    double sintheta = std::sqrt(1.0 - xi*xi);\n    double mu  = sintheta*std::cos(varphi);\n    double eta = sintheta*std::sin(varphi);\n    return get_Y_lm(l, m, mu, eta, xi);\n\n}\n\n// Calculate the spherical harmonic of degree l, order m\n// given the triplet of directional cosines\ndouble SphericalHarmonics::Y_lm(const int    l,\n                                const int    m,\n                                const double mu,\n                                const double eta,\n                                const double xi )\n{\n    return get_Y_lm(l, m, mu, eta, xi);\n}\n\n// Calculate the Legendre polynomial of degree l\n// given the polar angle cosine\ndouble SphericalHarmonics::Y_lm(const int    l,\n                                const double xi )\n{\n    return get_Y_lm(l, 0, 0, 0, xi);\n}\n\ndouble SphericalHarmonics::get_Y_lm(const int    l,\n                                    const int    m,\n                                    const double mu,\n                                    const double eta,\n                                    const double xi )\n{\n  using std::fabs;\n  Require(l >= 0);\n  Require(m <= l);\n  Require(m >= -l);\n  Require(mu >= -1.0);\n  Require(mu <= 1.0);\n  Require(eta >= -1.0);\n  Require(eta <= 1.0);\n  Require(xi >= -1.0);\n  Require(xi <= 1.0);\n  double unity = mu * mu + eta * eta + xi * xi;\n  if (!detran_utilities::soft_equiv(1.0, unity, 1.0e-5))\n  {\n    Require( detran_utilities::soft_equiv( fabs(mu), 0.0 ) &&\n             detran_utilities::soft_equiv( fabs(eta), 0.0 ) );\n  }\n\n  if ( l == 0 )\n    return 1.0;\n  else if ( l == 1 )\n  {\n    if ( m == -1 )\n      return eta;\n    else if ( m == 0 )\n      return xi;\n    else if ( m == 1 )\n      return mu;\n  }\n  else if ( l == 2 )\n  {\n    if ( m == -2 )\n      return 1.732050807568877*mu*eta;\n    else if ( m == -1 )\n      return 1.732050807568877*xi*eta;\n    else if ( m == 0 )\n      return 1.5*xi*xi-0.5;\n    else if ( m == 1 )\n      return 1.732050807568877*xi*mu;\n    else if ( m == 2 )\n      return 0.8660254037844385*(mu*mu-eta*eta);\n  }\n  else if ( l == 3 )\n  {\n    if ( m == -3 )\n      return 0.7905694150420948*eta*(3*mu*mu-eta*eta);\n    else if ( m == -2 )\n      return 3.872983346207417*xi*mu*eta;\n    else if ( m == -1 )\n      return 0.6123724356957945*eta*(5.0*xi*xi-1.0);\n    else if ( m == 0 )\n      return 2.5*xi*xi*xi - 1.5*xi;\n    else if ( m == 1 )\n      return 0.6123724356957945*mu*(5.0*xi*xi-1.0);\n    else if ( m == 2 )\n      return 1.936491673103708*xi*(mu*mu-eta*eta);\n    else if ( m == 3 )\n      return 0.7905694150420948*mu*(mu*mu-3.0*eta*eta);\n  }\n  else\n  {\n#ifdef DETRAN_ENABLE_BOOST\n    double phi   = std::acos(mu / std::sqrt(1.0 - xi*xi));\n    double theta = std::acos(xi);\n    // Normalization so that phi_00 = phi, phi_1m = current components, etc.\n    // This leads to a match with definitions given by Hebert.\n    double del = (m == 0) ? 1.0 : 2.0;\n    double norm = std::pow(-1.0, m) *\n                  std::sqrt(del * detran_utilities::four_pi / (2.*l + 1.));\n    if (m >= 0)\n      return norm * boost::math::spherical_harmonic_r(l, m, theta, phi);\n    else\n      return norm * boost::math::spherical_harmonic_i(l,-m, theta, phi);\n#else\n    // Degree not implemented.\n    THROW(\"Maximum Legendre order is 3. For higher orders, enable Boost.\");\n\treturn 0;\n#endif\n  }\n  return 0;\n}\n\n} // end namespace detran_angle\n\n//---------------------------------------------------------------------------//\n//              end of SphericalHarmonics.cc\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "2183e7063d5ad1cdc10f0690174d668301a5cf1e", "size": 4641, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/angle/SphericalHarmonics.cc", "max_stars_repo_name": "RLReed/libdetran", "max_stars_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T16:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T13:40:16.000Z", "max_issues_repo_path": "src/angle/SphericalHarmonics.cc", "max_issues_repo_name": "RLReed/libdetran", "max_issues_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T21:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T00:56:44.000Z", "max_forks_repo_path": "src/angle/SphericalHarmonics.cc", "max_forks_repo_name": "RLReed/libdetran", "max_forks_repo_head_hexsha": "77637c788823e0a14aae7e40e476a291f6f3184b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-03-07T16:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:14:23.000Z", "avg_line_length": 30.1363636364, "max_line_length": 79, "alphanum_fraction": 0.5175608705, "num_tokens": 1330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6702785974861026}}
{"text": "// Copyright (C) 2021 Christian Brommer, Control of Networked Systems, University of Klagenfurt, Austria.\n//\n// All rights reserved.\n//\n// This software is licensed under the terms of the BSD-2-Clause-License with\n// no commercial use allowed, the full terms of which are made available\n// in the LICENSE file. No license in patents is granted.\n//\n// You can contact the author at <christian.brommer@ieee.org>\n\n#include <mars/general_functions/utils.h>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n\nnamespace mars\n{\nUtils::Utils() = default;\n\nEigen::MatrixXd Utils::EnforceMatrixSymmetry(const Eigen::Ref<const Eigen::MatrixXd>& mat_in)\n{\n  Eigen::MatrixXd mat_out = (mat_in + mat_in.transpose()) / 2;\n  return mat_out;\n}\n\nEigen::Matrix3d Utils::Skew(const Eigen::Vector3d& v)\n{\n  Eigen::Matrix3d res;\n  res << 0, -v(2), v(1), v(2), 0, -v(0), -v(1), v(0), 0;\n  return res;\n}\n\nEigen::Matrix4d Utils::MatExp(const Eigen::Matrix4d& A, const int& order)\n{\n  Eigen::Matrix4d matexp(Eigen::Matrix4d::Identity());  // initial condition with k=0\n\n  int div = 1;\n  Eigen::Matrix4d a_loop = A;\n\n  for (int k = 1; k <= order; k++)\n  {\n    div = div * k;  // factorial(k)\n    matexp = matexp + a_loop / div;\n    a_loop = a_loop * A;  // adding one exponent each iteration\n  }\n\n  return matexp;\n}\n\nEigen::Matrix4d Utils::OmegaMat(const Eigen::Vector3d& v)\n{\n  Eigen::Matrix4d res;\n  res.setZero();\n\n  res.block(0, 1, 1, 3) = -v.transpose();\n  res.block(1, 0, 3, 1) = v;\n  res.block(1, 1, 3, 3) = -Skew(v);\n\n  return res;\n}\n\nEigen::Quaterniond Utils::QuatFromSmallAngle(const Eigen::Vector3d& d_theta_vec)\n{\n  const double d_theta_vec_norm = d_theta_vec.norm();\n  const double d_theta_squared = d_theta_vec_norm * d_theta_vec_norm;\n\n  if (d_theta_squared / 4.0 < 1.0)\n  {\n    return Eigen::Quaterniond(sqrt(1 - d_theta_squared / 4.0), d_theta_vec[0] * 0.5, d_theta_vec[1] * 0.5,\n                              d_theta_vec[2] * 0.5);\n  }\n  else\n  {\n    // In this case the error angle vector is not small at all.\n    std::cout << \"Warning: The error angle vector is not small\" << std::endl;\n\n    double w = 1.0 / sqrt(1 + d_theta_squared / 4.0);\n    double f = w * 0.5;\n    return Eigen::Quaterniond(w, d_theta_vec[0] * f, d_theta_vec[1] * f, d_theta_vec[2] * f);\n  }\n}\n\nEigen::Quaterniond Utils::ApplySmallAngleQuatCorr(const Eigen::Quaterniond& q_prior, const Eigen::Vector3d& correction)\n{\n  return (q_prior * QuatFromSmallAngle(correction)).normalized();\n}\n\nbool Utils::CheckCov(const Eigen::MatrixXd& cov_mat, const std::string& description, const bool& /*check_cond*/)\n{\n  bool result = true;\n  std::string info(\"[\" + description + \"]\" + \": \");\n\n  bool is_symmetric = Eigen::MatrixXd::Zero(cov_mat.rows(), cov_mat.cols()).isApprox(cov_mat - cov_mat.transpose());\n  if (!is_symmetric)\n  {\n    std::cout << \"Warning: \" << info << \"The covariance matrix is not symmetric\" << std::endl;\n    result = false;\n  }\n\n  double det = cov_mat.determinant();\n  if (det <= 0)\n  {\n    std::cout << \"Warning: \" << info << \"The determinant of the covariance matrix is not positive (\" << det << \")\"\n              << std::endl;\n    result = false;\n  }\n\n  double min_eigenvalue = Eigen::EigenSolver<Eigen::MatrixXd>(cov_mat).eigenvalues().real().minCoeff();\n  if (min_eigenvalue < 0)\n  {\n    std::cout << \"Warning: \" << info << \"The covariance matrix is not positive semidefinite min: \" << min_eigenvalue\n              << std::endl;\n    result = false;\n  }\n\n  return result;\n}\n}\n", "meta": {"hexsha": "1149fc7f9dc14655a65eb5c40c13cd0fc5e98f5a", "size": 3484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/mars/source/utils.cpp", "max_stars_repo_name": "eallak/mars_lib", "max_stars_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "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": "source/mars/source/utils.cpp", "max_issues_repo_name": "eallak/mars_lib", "max_issues_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "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": "source/mars/source/utils.cpp", "max_forks_repo_name": "eallak/mars_lib", "max_forks_repo_head_hexsha": "9657fb669c48be39471e7504c3648319126c020b", "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.0333333333, "max_line_length": 119, "alphanum_fraction": 0.653272101, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6701881826736271}}
{"text": "/**\n * ODE solver - JMU REU 2021\n *\n * @author Mike Lam\n */\n\n// standard headers\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <functional>\nusing namespace std;\n\n// Boost ODEint headers (individual files compile faster than the catch-all)\n#include <boost/numeric/odeint.hpp>\n//#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n//#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\nusing namespace boost::numeric::odeint;\n\n// floating-point precision control (control via compiler parameter -Dreal_t)\n//typedef double real_t;      // 64 bits\n//typedef float real_t;       // 32 bits\n\n// solver state\ntypedef std::vector<real_t> state_t;\n\n// parameters (most read from command line)\nreal_t a, b, c, x0;\ndouble t0 = 0.0;\ndouble tn, dt;\nconst int N = 10;\nreal_t ac[N+1];\n\n// output stream\nofstream out;\n\n// ODE system\nvoid ode(const state_t &x, state_t &dxdt, const real_t /*t*/)\n{\n    dxdt[0] = a*pow(x[0],2.0) + b*x[0] + c;\n}\n\n// power series solution at x\nvoid calc_coefficients(real_t x)\n{\n    ac[0] = x;\n    ac[1] = a * ac[0]*ac[0] + b * ac[0] + c;\n\n    for (int i = 2; i <= N; i++) {\n        ac[i] = 0.0;\n        for (int k = 0; k < i; k++) {\n            ac[i] += ac[k] * ac[i-1-k];\n        }\n        ac[i] = (a * ac[i] + b * ac[i-1]) / i;\n    }\n}\n\n// power series solution using Horner's method\nreal_t psm(const real_t t)\n{\n    real_t x = t * ac[N];\n    for (int j = N-1; j > 0; j--) {\n        x = t * (x + ac[j]);\n    }\n    x += ac[0];\n    return x;\n}\n\n// x \\left( t \\right) =1/2\\,{\\frac {1}{a} \\left( \\tan \\left( 1/2\\,t\\sqrt\n// {4\\,ac-{b}^{2}}+\\arctan \\left( {\\frac {2\\,{\\it x0}\\,a+b}{\\sqrt {4\\,ac-\n// {b}^{2}}}} \\right)  \\right) \\sqrt {4\\,ac-{b}^{2}}-b \\right) }\n//\n// @author Kevin Rojas\nreal_t solution(real_t a,real_t b, real_t c, real_t x0, real_t t)\n{\n    /* Inputs x:\n     * a,b,c: Parameters of the ODE\n     * x0   : Initial condition\n     * x    : Point to evaluate the exact solution on\n     * Output:\n     * x(t) where x solves x' = ax+bx+c, x(0) = x0\n     */\n\n    real_t disc = b*b-4.0*a*c;\n    //cout << \"discriminant: \" << disc << endl;\n    real_t val = 0.0;\n\n    if (disc > 0.0) {\n       real_t x1 = (-b+sqrt(disc))/(2.0*a);\n       real_t x2 = (-b-sqrt(disc))/(2.0*a);\n       real_t A = abs((x0-x2)/(x0-x1))*exp((x2-x1)*a*t);\n       real_t val1 = (A*x1-x2)/(A-1);\n\n       real_t B = -A;\n       real_t val2 = (B*x1-x2)/(B-1);\n\n       if((val1 >x2 && val1> x1) || (val1<x2 && val1<x1)){\n           val = val1;\n       }\n       else{\n           val = val2;\n       }\n       val = val2;\n       // TODO: deal with the absolute value?\n\n    } else if (disc < 0.0) {\n       real_t A = b/(2.0*sqrt(a));\n       real_t D = -disc/(4.0*a*a);\n       real_t c0 = atan((x0+A)/sqrt(D));\n       val = sqrt(D)*tan(a*sqrt(D)*t+c0)-A;\n\n    } else {\n       real_t x1 = -b/(2.0*a);\n       real_t c0 = -1.0/(x0-x1);\n       val = (x1-1.0/(a*t+c0));\n    }\n    return val;\n}\n\n// debug output helper\nvoid observe(const state_t &x, const real_t t)\n{\n    real_t sol = solution(a, b, c, x0, t);\n    real_t psm_sol = psm(0);\n\n    // re-center power series\n    calc_coefficients(psm(dt));\n\n    // write output\n    out << setw(8) << t;\n    out << setw(16) << sol;\n    out << setw(16) << x[0] << setw(16) << fabs(sol-x[0]);\n    out << setw(16) << psm_sol << setw(16) << fabs(sol-psm_sol);\n    out << endl;\n}\n\nint main(int argc, const char* argv[])\n{\n    // check parameters\n    if (argc != 7) {\n        cout << \"Usage: \" << argv[0] << \" <a> <b> <c> <x0> <tn> <dt>\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    // parse parameters\n    a  = stod(argv[1], NULL);\n    b  = stod(argv[2], NULL);\n    c  = stod(argv[3], NULL);\n    x0 = stod(argv[4], NULL);\n    tn = stod(argv[5], NULL);\n    dt = stod(argv[6], NULL);\n    // TODO: add stepper and t0?\n\n    // initialize state\n    state_t x(1);\n    x[0] = x0;\n\n    // precalculate coefficients\n    calc_coefficients(x0);\n\n    // show floating-point width\n    //cout << \"sizeof(real_t)=\" << sizeof(real_t) << endl;\n\n    // stepper\n    runge_kutta4<state_t> stp;\n\n    // integrate w/ debug output\n    out.open(\"out.dat\");\n    /*size_t steps =*/ integrate_const(stp, ode, x, t0, tn, dt, observe);\n    out.close();\n\n    // show final output\n    //cout << \"steps=\" << steps << \" x=\" << x[0] << endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5487c82e959983bc81f06ffaa5cd501a3e9d3b12", "size": 4362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solve_p2.cpp", "max_stars_repo_name": "delaneygmacd/jmu-reu-ode", "max_stars_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T17:12:01.000Z", "max_issues_repo_path": "solve_p2.cpp", "max_issues_repo_name": "delaneygmacd/jmu-reu-ode", "max_issues_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solve_p2.cpp", "max_forks_repo_name": "delaneygmacd/jmu-reu-ode", "max_forks_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T15:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T15:51:05.000Z", "avg_line_length": 24.0994475138, "max_line_length": 78, "alphanum_fraction": 0.5371389271, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.6701781494939243}}
{"text": "/**\n * @file model_predictive_controller.cpp\n * @brief Finite-horizon Model Predictive Controller.\n * \n */\n\n#include <mpc.hpp>\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace controller;\n\nMPC::MPC(const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, const double S) :\n    Q(Q), R(R), saturation(S), converged(false)\n{\n    P_new.setZero();\n    Ad.setZero(Q.rows(), Q.cols());\n    I.setIdentity(Q.rows(), Q.cols());\n    cmd_vel.setZero(1, R.rows()); // [translation rate, rotation rate].\n}\n\nEigen::MatrixXd MPC::computeDiscrete(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E, unsigned int numIteration, double tolarance, double dt)\n{\n    // A Cost-to-go matrix P evolving backwards in time from Q is defined as,\n    P = Q;\n\n    // Discretization.\n    Ad = (I + A * dt * 0.5) * (I - A * dt * 0.5).inverse();\n    Bd = B * dt;\n\n    // Iterating over a finite-horizon Algebraic Riccati Equation to a steady-state solution; that is, P_new - P ~= 0 + tolarance.\n    for(unsigned int i = 0; i < numIteration; i++)\n    {\n        P_new = Ad.transpose() * P * Ad - (Ad.transpose() * P * Bd) * (R + Bd.transpose() * P * Bd).inverse() * (Bd.transpose() * P * Ad) + Q;\n\n        // Check system convergence.\n        difference = fabs((P_new - P).maxCoeff());\n        if(difference < tolarance)\n        {\n            // std::cout << \"Solution found at i = \" << i << std::endl;\n\n            converged = true;\n            break;\n        }\n\n        // Update Riccati solution.\n        P = P_new;\n    }\n\n    // Get cmd_vel.\n    if(converged)\n    {\n        K = (R + Bd.transpose() * P * Bd).inverse() * Bd.transpose() * P * Ad;\n        controlUpdate = K * E;\n\n        // Compute magnitude of velocity vector.\n        cmd_vel << \n            sqrt(pow(controlUpdate(0, 0), 2.0) + pow(controlUpdate(0, 1), 2.0) + pow(controlUpdate(0, 2), 2.0)),\n            sqrt(pow(controlUpdate(1, 0), 2.0) + pow(controlUpdate(1, 1), 2.0) + pow(controlUpdate(1, 2), 2.0));\n        \n        // Saturate output signal.\n        if(cmd_vel(0, 0) > saturation) cmd_vel(0, 0) = saturation;\n        if(cmd_vel(0, 0) < -saturation) cmd_vel(0, 0) = -saturation;\n        if(cmd_vel(0, 1) > saturation) cmd_vel(0, 1) = saturation;\n        if(cmd_vel(0, 1) < -saturation) cmd_vel(0, 1) = -saturation;\n\n        return cmd_vel;\n    }\n    else\n    {\n        std::cout << \"MPC controller did not converge. Resetting cmd_vel... \u6c92\u6709\u89e3\u6c7a\u65b9\u6848\" << std::endl;\n        cmd_vel.setZero();\n\n        return cmd_vel;\n    }\n\n    converged = false;\n}", "meta": {"hexsha": "d5b9aa4b0b2c5b807e5f7fbb293f720ec89943aa", "size": 2517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control_system/src/model_predictive_controller.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/control_system/src/model_predictive_controller.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/control_system/src/model_predictive_controller.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": 32.2692307692, "max_line_length": 170, "alphanum_fraction": 0.5740961462, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6700727443058808}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2019.\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\n// chapter10_08-001_pi_millions_with_boost.cpp\n\n// This program can be used to compute millions of digits of pi.\n// In fact, it has been used to compute more than one billion\n// decimal digits of pi. Boost.Multiprecision is combined with\n// GMP (or MPIR) in order to carry out the calculation of pi.\n\n// This program requires inclusion of Boost.Multiprecision\n// and linking with GMP (or MPIR on certain targets).\n\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <cstdint>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <regex>\n#include <sstream>\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\nnamespace pi { namespace millions { namespace detail {\n\n// *****************************************************************************\n// Function    : template<typename float_type>\n//               const float_type& calculate_pi_template(const bool print_progress)\n//\n// Description : Compute pi using a quadratically convergent Gauss AGM,\n//               in the Schoenhage variant. For a description of the algorithm,\n//               see Algorithm 16.148, Chapter 16, page 236 in the book\n//               J. Arndt and C. Haenel, \"Pi Unleashed\",\n//               (Springer Verlag, Heidelberg, 2001).\n//\n//               The parameter print_progress_to_cout (= true),\n//               will print calculation progress to std::cout.\n//\n//               Book reference for \"Pi Unleashed\":\n//               https://www.springer.com/de/book/9783642567353\n//\n// *****************************************************************************\ntemplate<typename float_type>\nconst float_type& pi(const bool print_progress = false)\n{\n  static bool is_init;\n\n  static float_type val_pi;\n\n  if(!is_init)\n  {\n    is_init = true;\n\n    const std::regex rx(\"^[^e]+[e0+-]+([0-9]+)$\");\n\n    std::match_results<std::string::const_iterator> mr;\n\n    std::stringstream ss;\n    ss.setf(std::ios::scientific);\n    ss.precision(static_cast<std::streamsize>(4));\n\n    float_type a (1.0F);\n    float_type bB(0.5F);\n    float_type s (0.5F);\n    float_type t (0.375F);\n\n    // This loop is designed for computing a maximum of a few billion\n    // decimal digits of pi. The number of digits roughly doubles\n    // with each iteration of the loop. After 20 iterations,\n    // the precision is about 2.8 million decimal digits.\n    // After 29 iterations, the precision is more than one\n    // billion decimal digits.\n\n    for(std::uint_least16_t k = UINT8_C(1); k < UINT8_C(64); ++k)\n    {\n      using std::sqrt;\n\n      a      += sqrt(bB);\n      a      /= 2U;\n      val_pi  = a;\n      val_pi *= val_pi;\n      bB      = (val_pi - t);\n      bB     *= 2U;\n\n      const float_type iterate_term((bB - val_pi) * (UINT64_C(1) << k));\n\n      s += iterate_term;\n\n      // Extract the base-10 order of magnitude\n      // to estimate the base-10 digits in this\n      // iteration.\n\n      // Here, we produce a short printout\n      // of the iteration term that is subsequently\n      // parsed with a regular expression\n      // for extracting the base-10 order.\n\n      // Note: We are only extracting a few digits from iterate_term.\n      // So piping it to a stringstream is not exorbitantly costly here.\n      ss << iterate_term;\n\n      const std::string str_iterate_term(ss.str());\n\n      const bool is_match =\n        std::regex_match(str_iterate_term, mr, rx);\n\n      const std::uint64_t digits10_iterate =\n        (is_match ? (std::max)(boost::lexical_cast<std::uint64_t>(mr[1U]), std::uint64_t(0U))\n                  : UINT64_C(0));\n\n      if(print_progress)\n      {\n        std::cout << \"Base-10 digits of iteration \"\n                  << std::right\n                  << std::setw(3)\n                  << k\n                  << \": \"\n                  << std::right\n                  << std::setw(12)\n                  << digits10_iterate\n                  << '\\n';\n      }\n\n      // Test the approximate base-10 digits\n      // of this iteration term.\n\n      // If we have attained at least half or more\n      // of the total desired digits with this\n      // iteration, the calculation is finished\n      // because the change from the next iteration will be\n      // insignificantly small.\n      BOOST_CONSTEXPR_OR_CONST std::uint64_t digits10_iterate_goal =\n        static_cast<std::uint64_t>((static_cast<std::uint64_t>(std::numeric_limits<float_type>::digits10) + 1LL) / 2LL) + 16LL;\n\n      if(digits10_iterate > digits10_iterate_goal)\n      {\n        break;\n      }\n\n      t  = val_pi;\n      t += bB;\n      t /= 4U;\n\n      ss.str(std::string());\n    }\n\n    if(print_progress)\n    {\n      std::cout << \"Iteration loop done, compute inverse\" << '\\n';\n    }\n\n    val_pi += bB;\n    val_pi /= s;\n\n    if(print_progress)\n    {\n      std::cout << \"The pi calculation is done.\" << '\\n';\n    }\n  }\n\n  return val_pi;\n}\n\ntemplate<typename float_type>\nstd::ostream& report_pi_timing(std::ostream& os, const float elapsed)\n{\n  return os << \"=================================================\" << '\\n'\n            << \"Computed \"\n            << static_cast<std::uint64_t>(std::numeric_limits<float_type>::digits10 - 1)\n            << \" digits of pi.\\n\"\n            << \"Total computation time : \"\n            << std::fixed\n            << std::setprecision(2)\n            << elapsed\n            << \" seconds\"\n            << '\\n'\n            << \"=================================================\"\n            << '\\n';\n}\n\n} } } // namespace pi::millions::detail\n\nnamespace pi { namespace millions {\n\ntemplate<typename float_type>\nvoid print_pi(std::ostream& os)\n{\n  // Calculate the value of pi. When doing so, print the calculation\n  // messages to the console. Use the clock function to obtain the\n  // total time of the pi calculation.\n\n  using local_time_point_type =\n    std::chrono::high_resolution_clock::time_point;\n\n  const local_time_point_type start = std::chrono::high_resolution_clock::now();\n  detail::pi<float_type>(true);\n  const local_time_point_type stop  = std::chrono::high_resolution_clock::now();\n\n  // Evaluate the time that was required for the pi calculation.\n  const float elapsed =\n      static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count())\n    / static_cast<float>(1000.0F);\n\n  // Report the time of the pi calculation to the console.\n  static_cast<void>(detail::report_pi_timing<float_type>(std::cout, elapsed));\n\n  // Report the time of the pi calculation to the output stream.\n  static_cast<void>(detail::report_pi_timing<float_type>(os, elapsed));\n\n  // Report that we are writing the output file.\n  std::cout << \"Writing the output file.\" << '\\n';\n\n  // Pipe the value of pi into a stringstream object.\n  std::stringstream ss;\n\n  // Pipe the value of pi into a stringstream object with full precision.\n  ss << std::fixed\n     << std::setprecision(std::streamsize(std::numeric_limits<float_type>::digits10) - 1)\n     << detail::pi<float_type>();\n\n  // Extract the string value of pi.\n  const std::string str_pi(ss.str());\n\n  // Print pi using the following paramater-tunable format.\n\n  // pi = 3.1415926535 8979323846 2643383279 5028841971 6939937510 : 50\n  //        5820974944 5923078164 0628620899 8628034825 3421170679 : 100\n  //        8214808651 3282306647 0938446095 5058223172 5359408128 : 150\n  //        4811174502 8410270193 8521105559 6446229489 5493038196 : 200\n  //        ...\n\n  BOOST_CONSTEXPR_OR_CONST char* char_set_separator   = \" \";\n  BOOST_CONSTEXPR_OR_CONST char* char_group_separator = \"\\n\";\n\n  BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_set   = 10U;\n  BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_line  = digits_per_set * 5U;\n  BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_group = digits_per_line * 10U;\n\n  // The digits after the decimal point are grouped\n  // in sets of digits_per_set with digits_per_line\n  // digits per line. The running-digit count is reported\n  // at the end of each line.\n  \n  // The char_set_separator character string is inserted\n  // between sets of digits. Between groups of lines,\n  // we insert a char_group_separator character string\n  // (which likely might be selected as a newline).\n\n  // For a simple verification of 1,000,000 digits,\n  // for example, go to Wolfram Alpha and ask:\n  //   1000000th digit of Pi.\n  // This prints out 50 digits of pi in the neighborhood\n  // of a million digits, with the millionth digit in bold.\n\n  std::string::size_type pos;\n\n  if(   ((pos = str_pi.find(char('3'), 0U)) != std::string::npos)\n     && ((pos = str_pi.find(char('.'), 1U)) != std::string::npos)\n     && ((pos = str_pi.find(char('1'), 1U)) != std::string::npos))\n  {\n    ;\n  }\n  else\n  {\n    pos = 0U;\n  }\n\n  os << \"pi = \" << str_pi.substr(0U, pos);\n\n  const std::size_t digit_offset = pos;\n\n  // Extract the digits after the decimal point in a loop.\n  // Insert spaces, newlines and a running-digit count\n  // in order to create a format for comfortable reading.\n\n  bool all_output_streaming_is_finished = false;\n\n  while(all_output_streaming_is_finished == false)\n  {\n    // Print a set of digits (i.e. having 10 digits per set).\n    const std::string str_pi_substring(str_pi.substr(pos, digits_per_set));\n\n    os << str_pi_substring << char_set_separator;\n\n    pos += (std::min)(std::string::size_type(digits_per_set),\n                      str_pi_substring.length());\n\n    const std::size_t number_of_digits(pos - digit_offset);\n\n    // Check if all output streaming is finished.\n    all_output_streaming_is_finished = (pos >= str_pi.length());\n\n    if(all_output_streaming_is_finished)\n    {\n      // Write the final digit count.\n      // Break from the printing loop.\n      // Flush the output stream with std::endl.\n\n      os << \": \" << number_of_digits << std::endl;\n    }\n    else\n    {\n      const bool this_line_is_finished =\n        (std::size_t(number_of_digits % digits_per_line) == std::size_t(0U));\n\n      if(this_line_is_finished)\n      {\n        // Print the running-digit count and start a new line.\n        os << \": \" << number_of_digits << std::endl;\n\n        const bool this_group_of_lines_is_finished =\n          (std::size_t(number_of_digits % digits_per_group) == std::size_t(0U));\n\n        if(this_group_of_lines_is_finished)\n        {\n          // Insert a character (which might be a blank line)\n          // after a group of lines.\n          os << char_group_separator;\n        }\n\n        // Insert spaces at the start of the new line.\n        os << \"       \";\n      }\n    }\n  }\n}\n\n} } // namespace pi::millions\n\nint main()\n{\n  using float_type =\n    boost::multiprecision::number<boost::multiprecision::gmp_float<1000001UL>,\n                                  boost::multiprecision::et_off>;\n\n  std::ofstream out(\"pi.out\");\n\n  if(out.is_open())\n  {\n    pi::millions::print_pi<float_type>(out);\n\n    out.close();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "e164c449ccabc1d98d145075fc87fccec5e4e804", "size": 11139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_stars_repo_name": "gianricardo/real-time-cpp", "max_stars_repo_head_hexsha": "9fa7d8dfced7a2ff3f8d1d1d4aeff24a76a2dbec", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T08:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-19T08:10:23.000Z", "max_issues_repo_path": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_issues_repo_name": "dustex/real-time-cpp", "max_issues_repo_head_hexsha": "dedab60eefc6c5db94d53f1e1a890cfba8ae3f76", "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": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_forks_repo_name": "dustex/real-time-cpp", "max_forks_repo_head_hexsha": "dedab60eefc6c5db94d53f1e1a890cfba8ae3f76", "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.2893258427, "max_line_length": 127, "alphanum_fraction": 0.6161235299, "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6699788722212857}}
{"text": "#pragma once\n\n#include \"EM.hpp\"\n#include <Eigen/Dense>\n#include <cmath>\n\ntemplate<class Float, class C>\nrequires ContainerOf<C, Eigen::Matrix<Float, C::value_type::RowsAtCompileTime, 1> >\nEigen::Matrix<Float, C::value_type::RowsAtCompileTime, 1> weightedSum(\n    const std::vector<Float>& a,\n    const C& x)\n{\n    typedef Eigen::Matrix<Float, C::value_type::RowsAtCompileTime, 1> Vec;\n    assert( a.size() == x.size() );\n    int n = x.begin()->size();\n    return std::transform_reduce(a.begin(), a.end(), x.begin(), \n                                 (Vec)Vec::Zero(n));\n}\n\n\ntemplate<class Float, int N>\nclass IndependentGaussian\n        : public ProbabilityDistribution<Eigen::Matrix<Float, N, 1>, Float > {\nprivate:\n    typedef Eigen::Matrix<Float, N, 1> Vec;\npublic:\n    size_t n;\n    Vec deviation;\n    Vec mean;\n    \n    IndependentGaussian(size_t _n = N) : \n        n{_n}\n    {\n        assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n        init();\n    }\n    \n    IndependentGaussian(const Vec& _deviation, const Vec& _mean) : \n        n{(size_t)_deviation.size()},\n        deviation{_deviation},\n        mean{_mean}\n    {\n        assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n    }\n    \n    Float operator()(const Vec& x) const{\n        assert((size_t)x.size() == n);\n        Float p = 1.0;\n        Float s = 0.0;\n        for(size_t j=0; j<n; j++){\n            p *= one_two_pi/deviation(j);\n            s += - (x[j]-mean[j])*(x[j]-mean[j])/2.0/deviation[j]/deviation[j];\n        }\n        return p*exp(s);\n    }\n    \n    template <Container C>\n    requires ContainerOf<C, Vec>\n    void likelihoodEstimate(const std::vector<Float>& a, \n                            const C& x)\n    {\n        Float sumA = std::reduce(a.begin(), a.end());\n        if(sumA == 0.0){\n            return;\n        }\n        mean = weightedSum(a, x)/sumA;\n        \n        Vec s2 = std::transform_reduce(\n            a.begin(), a.end(), x.begin(),\n            (Vec)Vec::Zero(n),\n            std::plus<>(),\n            [&](Float ai, const Vec& xi) -> Vec {\n                return ai*(xi-mean).unaryExpr([&](auto xi_m){ return xi_m*xi_m; });\n            });\n\n        deviation = (s2/sumA).cwiseSqrt();\n    } \nprivate:\n    static constexpr Float one_two_pi = 1.0/sqrt(2*M_PI);\n    void init(){\n        mean = Vec::Zero(n);\n        deviation = Vec::Constant(n, 1.0);\n    }\n};\n\n\ntemplate<class Float, int N>\nclass Gaussian\n        : public ProbabilityDistribution<Eigen::Matrix<Float, N, 1>, Float > {\nprivate:\n    typedef Eigen::Matrix<Float, N, 1> Vec;\n    typedef Eigen::Matrix<Float, N, N> Mat;\n    size_t n;\npublic:\n    Vec mean;\n    class : public Mat{\n    public:\n        Float constantFactor{ calculateConstantFactor() };\n        void operator=(const Mat& _invCovariance){\n            assert(_invCovariance.rows() == _invCovariance.cols() && \"The inverse covariance matrix must be square\");\n            Mat::operator=(_invCovariance);\n            constantFactor = calculateConstantFactor();\n        }\n    private:\n        Float calculateConstantFactor(){\n            return pow(one_two_pi, this->rows())*sqrt(this->determinant());\n        }\n    } invCovariance;\n\n    Gaussian(size_t _n=N) : \n        n{_n},\n        mean{ Vec::Zero(n) },\n        invCovariance{ Vec::Constant(n, 1.0).asDiagonal() }\n    {\n        assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n    }\n    \n    Gaussian(const Mat& _invCovariance, const Vec& _mean) : \n        n{(size_t)_mean.size()},\n        mean{_mean},\n        invCovariance{_invCovariance}\n    {\n        assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n    }\n    \n    Float operator()(const Vec& x) const{\n        assert((size_t)x.size() == n);\n        return invCovariance.constantFactor * exp(-0.5*(x-mean).dot(invCovariance*(x-mean)));\n    }\n    \n    template <Container C>\n    requires ContainerOf<C, Vec>\n    void likelihoodEstimate(const std::vector<Float>& a, \n                            const C& x)\n    {\n        Float sumA = std::reduce(a.begin(), a.end());\n        if(sumA == 0.0){\n            return;\n        }\n        mean = weightedSum(a, x)/sumA;\n        \n        Mat Cov = std::transform_reduce(\n            a.begin(), a.end(), x.begin(),\n            (Mat)Mat::Zero(n, n),\n            std::plus<>(),\n            [&](Float ai, const Vec& xi) -> Mat {\n                return ai*(xi-mean)*(xi-mean).transpose();\n            });\n        //FIXME: what if there is no inverse?\n        invCovariance = (Cov/sumA).inverse();\n    } \nprivate:\n    static constexpr Float one_two_pi = 1.0/sqrt(2*M_PI);\n};\n\n\n", "meta": {"hexsha": "0924da04064dd3dd9f199b80cc680144ac35a666", "size": 4613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Gaussian.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/Gaussian.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/Gaussian.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": 29.3821656051, "max_line_length": 117, "alphanum_fraction": 0.5438976805, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6699392825844332}}
{"text": "\n#pragma once\n\n/// @file\n\n#include <type_traits>\n\n#include <boost/math/special_functions/relative_difference.hpp>\n\n/// neon namespace\nnamespace neon\n{\n/// Perform a floating point comparison using boost for large numbers and an absolute error for smaller ones\n\n/// \\tparam Floating point type\n/// \\param x Value 1\n/// \\param y Value 2\n/// \\param absolute_tolerance\n/// \\param relative_tolerance\ntemplate <class T>\nauto is_approx(T const x,\n               T const y,\n               T const absolute_tolerance = 0.0,\n               T const relative_tolerance = 1e-10) noexcept\n    -> std::enable_if_t<std::is_floating_point<T>::value, bool>\n{\n    // References:\n    // https://www.boost.org/doc/libs/1_67_0/libs/math/doc/html/math_toolkit/float_comparison.html\n    // https://www.python.org/dev/peps/pep-0485/\n    return boost::math::relative_difference(x, y) <= relative_tolerance\n           || std::abs(x - y) <= absolute_tolerance;\n}\n}\n", "meta": {"hexsha": "2b444677abcbd75583562245987ea19665fd9c22", "size": 937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/numeric/float_compare.hpp", "max_stars_repo_name": "dbeurle/neon", "max_stars_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "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/numeric/float_compare.hpp", "max_issues_repo_name": "dbeurle/neon", "max_issues_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "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/numeric/float_compare.hpp", "max_forks_repo_name": "dbeurle/neon", "max_forks_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "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": 27.5588235294, "max_line_length": 108, "alphanum_fraction": 0.6808964781, "num_tokens": 229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6699392801381657}}
{"text": "#include \"iostream\"\n#include <cmath>\n#include <string>\n#include \"CoupledPde.hpp\"\n#include \"gnuplot_i.hpp\"\n#include <omp.h>\n// #include <boost/test/unit_test.hpp>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ndouble model_prob_1_rhs(double x){return 2.0;}\ndouble model_prob_2_rhs(double x){return 34.0*sin(x);}\ndouble model_prob_3_rhs(double x, double y){return exp(-(x*x+y*y));}\ndouble uj0(double x){return 1*sin(x)+1;}\n\n\n\nint main(int argc, char* argv[]) {\n    // int nthreads, tid;\n    // #pragma omp parallel\n    // {\n    //     /* Obtain thread number */\n    //     tid = omp_get_thread_num();\n    //     printf(\"Hello World from thread = %d\\n\", tid);\n\n    //     /* Only master thread does this */\n    //     if (tid == 0) {\n    //         nthreads = omp_get_num_threads();\n    //         printf(\"Number of threads = %d\\n\", nthreads);\n    //     }\n    // }\n    \n    \n\n    SecondOrderOde ode_mp1(500, -5.0, 0.0, model_prob_1_rhs, 0.0, 15.0);\n    SecondOrderOde ode_mp2(5, -5.0, 0.0, model_prob_1_rhs, 0.0, 15.0);\n    BoundaryConditions bc_mp1;\n    BoundaryConditions bc_mp2;\n    bc_mp1.SetX0DirichletBc1D(0.15);\n    bc_mp1.SetXNNeumannBc1D(0);\n    bc_mp2.SetX0NeumannBc1D(1.0);\n    bc_mp2.SetXNNeumannBc1D(0);\n    // bc_mp1.SetX0NeumannBc1D(0);\n    // bc_mp1.SetXNDirichletBc1D(0);\n    // bc_mp1.SetXNNeumannBc1D(0);\n    // bc_mp1.SetXNRobinBc1D(0);\n    BvpPde oxygen(&ode_mp1, &bc_mp1,0.001, 1.0, 10.0, 128, uj0);\n    BvpPde organic_mater_1(&ode_mp2, &bc_mp2,0.001, 1.0, 10.0, 128, uj0);\n    // BvpOde oxygen(&ode_mp1, &bc_mp1, 10);\n    oxygen.SetFilename(\"oxygen_results.dat\");\n    organic_mater_1.SetFilename(\"om1_results.dat\");\n    // oxygen.Solve();\n    CoupledPde cpde(&oxygen, &organic_mater_1);\n    cpde.SolveSystem();\n\n\n    Gnuplot g1, g2;\n    g1.set_style(\"lines\").plot_xy(oxygen.mpGrid->xGrid,oxygen.solution,\"differentiation\");\n    g2.set_style(\"lines\").plot_xy(organic_mater_1.mpGrid->xGrid,organic_mater_1.solution,\"differentiation\");\n    // g1.set_style(\"lines\").plot_equation(\"0.5*x*(1-x)\",\"exact solution\");\n\n    // Gnuplot g2;\n    // SecondOrderOde ode_mp2(10.0, 5.0, 0.0, uj0, 0.0, 20.0);\n    // BoundaryConditions bc_mp2;\n    // bc_mp2.SetX0NeumannBc1D(10.0);\n    // bc_mp2.SetXNDirichletBc1D(0.0);\n    // BvpOde organic_mater_1(&ode_mp2, &bc_mp2, 64);\n    // organic_mater_1.SetFilename(\"model_problem_results2.dat\");\n    // organic_mater_1.Solve();\n    // g2.set_style(\"points\").plot_xy(organic_mater_1.mpGrid->xGrid,organic_mater_1.solution);\n    // g2.set_style(\"lines\").plot_equation(\"(4*exp(x) + exp(-4*x) ) / (4*exp(pi)+exp(-4*pi))-5*sin(x)-3*cos(x)\",\"exact solution\");\n\n    return 0;\n}", "meta": {"hexsha": "cbb6977216cd0d9a6ff9eafa684189475a9d049c", "size": 2619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "biogeochemistry/reaction_network", "max_stars_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_stars_repo_licenses": ["MIT", "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": "src/main.cpp", "max_issues_repo_name": "biogeochemistry/reaction_network", "max_issues_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_issues_repo_licenses": ["MIT", "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/main.cpp", "max_forks_repo_name": "biogeochemistry/reaction_network", "max_forks_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.012987013, "max_line_length": 130, "alphanum_fraction": 0.649102711, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.66993927786221}}
{"text": "/**\n * @file    pose_estimation_3d2d.cpp\n * @version v1.0.0\n * @date    Oct,27 2017\n * @author  jacob.lin\n */\n\n#include <iostream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector<cv::KeyPoint>&, std::vector<cv::KeyPoint>&, std::vector<cv::DMatch>&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\n/*  */\nvoid bundleAdjustment( const std::vector<cv::Point3f>, const std::vector<cv::Point2f>, const cv::Mat&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n    if (argc != 5) {\n        cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2.\" << endl;\n        return 1;\n    }\n    \n    //-- 1st, read photo\n    cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n    \n    if (img_1.empty() || img_2.empty()) {\n        cout << \"img1 or img2 is no find.\" << endl;\n        return 1;\n    }\n    \n    //-- 2nd, find the two photo feature matches points\n    std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n    std::vector<cv::DMatch> matches;\n    find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n    cout << \"feature matches points total is \" << matches.size() << endl;\n    \n    //-- 3rd, create 3 dimensions point correspondences\n    cv::Mat d1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);      // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    std::vector<cv::Point3f> pts_3d;\n    std::vector<cv::Point2f> pts_2d;\n    for (cv::DMatch m:matches) {\n        ushort d = d1.ptr<unsigned short>(int (keypoints_1[m.queryIdx].pt.y))[int (keypoints_1[m.queryIdx].pt.x)];\n        \n        if (d == 0) {   /* bad depth */\n            continue;\n        }\n        float dd = d/5000.0;\n        cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n        pts_3d.push_back(cv::Point3d (p1.x*dd, p1.y*dd, dd));\n        pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n    }\n    cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n    \n    //-- 4th, use PnP or bundle adjustment compute camera pose.\n    cv::Mat r, t;\n    cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false);    // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    cv::Mat R;\n    cv::Rodrigues(r, R);    // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n    \n    cout << \"R = \" << endl << R << endl;\n    cout << \"t = \" << endl << t << endl;\n    \n    cout << \"calling bundle adjustment\" << endl;\n    \n    bundleAdjustment(pts_3d, pts_2d, K, R, t);\n    \n    return 0;\n}\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector<cv::KeyPoint>& keypoints_1, std::vector<cv::KeyPoint>& keypoints_2, std::vector<cv::DMatch>& matches)\n{\n    //-- Initialize\n    cv::Mat descriptors_1, descriptors_2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    \n    //-- 1st: detect Oriented FAST KeyPoint \n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    \n    //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    \n    //-- 3rd: \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    std::vector<cv::DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    \n    //-- 4th: \u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist = 10000, max_dist = 0;\n    \n    /* \u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb */\n    for (int i = 0; i < descriptors_1.rows; i++) {\n        double dist = match[i].distance;\n        if (dist < min_dist) {\n            min_dist = dist;\n        }\n        if (dist > max_dist) {\n            max_dist = dist;\n        }\n    }\n    \n    printf(\"-- Max distance : %f \\r\\n\", max_dist);\n    printf(\"-- Min distance : %f \\r\\n\", min_dist);\n    \n    // \u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for (int i = 0; i < descriptors_2.rows; i ++) {\n        if (match[i].distance <= max(2*min_dist, 30.0)) {\n            matches.push_back(match[i]);\n        }\n    }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n    return cv::Point2d\n        (\n            (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n            (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n        );\n}\n\nvoid bundleAdjustment(\n    const std::vector<cv::Point3f> points_3d, \n    const std::vector<cv::Point2f> points_2d,\n    const cv::Mat& K,\n    cv::Mat& R,\n    cv::Mat& t )\n{\n    // Initialize g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> Block;   // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linear_solver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block((std::unique_ptr<Block::LinearSolverType>)(linear_solver));\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg((std::unique_ptr<Block>)solver_ptr);\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    \n    // vertex \n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();    // camera pose\n    Eigen::Matrix3d R_mat;\n    R_mat << \\\n        R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2), \\\n        R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2), \\\n        R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2);\n    pose->setId(0);\n    pose->setEstimate(\n        g2o::SE3Quat(\n            R_mat, \n            Eigen::Vector3d(t.at<double>(0, 0), t.at<double>(1, 0), t.at<double>(2, 0))\n        )\n    );\n    optimizer.addVertex(pose);\n    \n    int index = 1;\n    for (const cv::Point3f p:points_3d) {\n        g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n        point->setId(index ++);\n        point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));\n        point->setMarginalized(true);   // g2o \u4e2d\u5fc5\u987b\u8bbe\u7f6e marg \n        optimizer.addVertex(point);\n    }\n    \n    // parameter : camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters(\n        K.at<double>(0, 0), Eigen::Vector2d(K.at<double>(0, 2), K.at<double>(1, 2)), 0\n    );\n    camera->setId(0);\n    optimizer.addParameter(camera);\n    \n    // edges\n    index = 1;\n    for (const cv::Point2f p:points_2d) {\n        g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setId(index);\n        edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ*>(optimizer.vertex(index)));\n        edge->setVertex(1, pose);\n        edge->setMeasurement(Eigen::Vector2d(p.x, p.y));\n        edge->setParameterId(0, 0);\n        edge->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(edge);\n        index++;\n    }\n    \n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(100);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n    \n    cout << endl << \"after optimization: \" << endl;\n    cout << \"T = \" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1a9c5f33e7d7c106015c744f3b26ff1f3666f0b8", "size": 8107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d.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_estimation_3d2d/src/pose_estimation_3d2d.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_estimation_3d2d/src/pose_estimation_3d2d.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": 34.4978723404, "max_line_length": 183, "alphanum_fraction": 0.6205748119, "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6699392776918984}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#ifndef quantext_nadaraya_watson_regression_hpp\n#define quantext_nadaraya_watson_regression_hpp\n\n#include <ql/math/comparison.hpp>\n\n#include <boost/make_shared.hpp>\n\n/*! \\file qle/math/nadarayawatson.hpp\n    \\brief Nadaraya-Watson regression\n    \\ingroup math\n*/\n\nnamespace QuantExt {\nusing QuantLib::Real;\nusing QuantLib::Size;\nnamespace detail {\n\n//! Regression impl\n/*! \\ingroup math\n */\nclass RegressionImpl {\npublic:\n    virtual ~RegressionImpl() {}\n    virtual void update() = 0;\n    virtual Real value(Real x) const = 0;\n    virtual Real standardDeviation(Real x) const = 0;\n};\n\n//! Nadaraya Watson impl\n/*! \\ingroup math\n */\ntemplate <class I1, class I2, class Kernel> class NadarayaWatsonImpl : public RegressionImpl {\npublic:\n    /*! \\pre the \\f$ x \\f$ values must be sorted.\n        \\pre kernel needs a Real operator()(Real x) implementation\n    */\n    NadarayaWatsonImpl(const I1& xBegin, const I1& xEnd, const I2& yBegin, const Kernel& kernel)\n        : xBegin_(xBegin), xEnd_(xEnd), yBegin_(yBegin), kernel_(kernel) {}\n\n    void update() {}\n\n    Real value(Real x) const {\n\n        Real tmp1 = 0.0, tmp2 = 0.0;\n\n        for (Size i = 0; i < static_cast<Size>(xEnd_ - xBegin_); ++i) {\n            Real tmp = kernel_(x - xBegin_[i]);\n            tmp1 += yBegin_[i] * tmp;\n            tmp2 += tmp;\n        }\n\n        return QuantLib::close_enough(tmp2, 0.0) ? 0.0 : tmp1 / tmp2;\n    }\n\n    Real standardDeviation(Real x) const {\n\n        Real tmp1 = 0.0, tmp1b = 0.0, tmp2 = 0.0;\n\n        for (Size i = 0; i < static_cast<Size>(xEnd_ - xBegin_); ++i) {\n            Real tmp = kernel_(x - xBegin_[i]);\n            tmp1 += yBegin_[i] * tmp;\n            tmp1b += yBegin_[i] * yBegin_[i] * tmp;\n            tmp2 += tmp;\n        }\n\n        return QuantLib::close_enough(tmp2, 0.0) ? 0.0 : std::sqrt(tmp1b / tmp2 - (tmp1 * tmp1) / (tmp2 * tmp2));\n    }\n\nprivate:\n    I1 xBegin_, xEnd_;\n    I2 yBegin_;\n    Kernel kernel_;\n};\n} // namespace detail\n\n//! Nadaraya Watson regression\n/*! This implements the estimator\n\n    \\f[\n    m(x) = \\frac{\\sum_i y_i K(x-x_i)}{\\sum_i K(x-x_i)}\n    \\f]\n\n    \\ingroup math\n*/\nclass NadarayaWatson {\npublic:\n    /*! \\pre the \\f$ x \\f$ values must be sorted.\n        \\pre kernel needs a Real operator()(Real x) implementation\n    */\n    template <class I1, class I2, class Kernel>\n    NadarayaWatson(const I1& xBegin, const I1& xEnd, const I2& yBegin, const Kernel& kernel) {\n        impl_ = boost::make_shared<detail::NadarayaWatsonImpl<I1, I2, Kernel> >(xBegin, xEnd, yBegin, kernel);\n    }\n\n    Real operator()(Real x) const { return impl_->value(x); }\n\n    Real standardDeviation(Real x) const { return impl_->standardDeviation(x); }\n\nprivate:\n    boost::shared_ptr<detail::RegressionImpl> impl_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "c90798dafec54b961758a49700ae0fa2ec3672a0", "size": 3521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 28.3951612903, "max_line_length": 113, "alphanum_fraction": 0.6580516899, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6699392754159426}}
{"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// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\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#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/type_traits.hpp>\r\n\r\n#include <boost/geometry/arithmetic/determinant.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n#include <boost/geometry/strategies/side.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n/*!\r\n\\brief Check at which side of a segment a point lies:\r\n    left of segment (> 0), right of segment (< 0), on segment (0)\r\n\\ingroup strategies\r\n\\tparam CalculationType \\tparam_calculation\r\n */\r\ntemplate <typename CalculationType = void>\r\nclass side_by_triangle\r\n{\r\npublic :\r\n\r\n    // Template member function, because it is not always trivial\r\n    // or convenient to explicitly mention the typenames in the\r\n    // strategy-struct itself.\r\n\r\n    // Types can be all three different. Therefore it is\r\n    // not implemented (anymore) as \"segment\"\r\n\r\n    template <typename P1, typename P2, typename P>\r\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\r\n    {\r\n        typedef typename boost::mpl::if_c\r\n            <\r\n                boost::is_void<CalculationType>::type::value,\r\n                typename select_most_precise\r\n                    <\r\n                        typename select_most_precise\r\n                            <\r\n                                typename coordinate_type<P1>::type,\r\n                                typename coordinate_type<P2>::type\r\n                            >::type,\r\n                        typename coordinate_type<P>::type\r\n                    >::type,\r\n                CalculationType\r\n            >::type coordinate_type;\r\n\r\n        coordinate_type const x = get<0>(p);\r\n        coordinate_type const y = get<1>(p);\r\n\r\n        coordinate_type const sx1 = get<0>(p1);\r\n        coordinate_type const sy1 = get<1>(p1);\r\n        coordinate_type const sx2 = get<0>(p2);\r\n        coordinate_type const sy2 = get<1>(p2);\r\n\r\n        // Promote float->double, small int->int\r\n        typedef typename select_most_precise\r\n            <\r\n                coordinate_type,\r\n                double\r\n            >::type promoted_type;\r\n\r\n        promoted_type const dx = sx2 - sx1;\r\n        promoted_type const dy = sy2 - sy1;\r\n        promoted_type const dpx = x - sx1;\r\n        promoted_type const dpy = y - sy1;\r\n\r\n        promoted_type const s \r\n            = geometry::detail::determinant<promoted_type>\r\n                (\r\n                    dx, dy, \r\n                    dpx, dpy\r\n                );\r\n\r\n        promoted_type const zero = promoted_type();\r\n        return math::equals(s, zero) ? 0 \r\n            : s > zero ? 1 \r\n            : -1;\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate <typename CalculationType>\r\nstruct default_strategy<cartesian_tag, CalculationType>\r\n{\r\n    typedef side_by_triangle<CalculationType> type;\r\n};\r\n\r\n}\r\n#endif\r\n\r\n}} // namespace strategy::side\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n", "meta": {"hexsha": "103e199502e3064f52d87fbe7a24a465227a992a", "size": 3788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "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": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "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": 31.0491803279, "max_line_length": 80, "alphanum_fraction": 0.6158922914, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6698829262385328}}
{"text": "#include <glm/models/links/logit.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\nlogit_link::logit_link()\n    : glm_link::glm_link( \"logit\" )\n{\n}\n\nvec\nlogit_link::init_beta(const mat &X, const vec &y) const\n{\n    vec mu = (y + 0.5) / 2.0;\n    vec eta = log( mu / ( 1.0 - mu ) );\n    \n    return pinv( X ) * eta;\n}\n\nvec\nlogit_link::mu(const arma::vec &eta) const\n{\n    return 1.0 / ( 1.0 + exp( -eta ) );\n}\n\nvec\nlogit_link::eta(const arma::vec &mu) const\n{\n    return log( mu / ( 1 -mu ) );\n}\n\nvec\nlogit_link::mu_eta(const arma::vec &mu) const\n{\n    return 1.0 / ( mu % ( 1.0 - mu ) );\n}\n", "meta": {"hexsha": "255966e95be79c49e3f8423043e95331728b751b", "size": 590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/logit.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/models/links/logit.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/models/links/logit.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 15.5263157895, "max_line_length": 55, "alphanum_fraction": 0.5762711864, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6698407682292086}}
{"text": "/*\n *  Copyright (c) 2015-, Filippo Basso <bassofil@gmail.com>\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *     1. Redistributions of source code must retain the above copyright\n *        notice, this list of conditions and the following disclaimer.\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 *     3. Neither the name of the copyright holder(s) nor the\n *        names of its contributors may be used to endorse or promote products\n *        derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <Eigen/SVD>\n#include <calibration_algorithms/plane_to_plane_calibration.h>\n\nnamespace unipd\n{\nnamespace calib\n{\n\nTransform3\nPlaneToPlaneCalibration::estimateTransform (const std::vector<std::pair<Plane3, Plane3>> & plane_pair_vector)\n{\n  const Size1 SIZE = plane_pair_vector.size();\n  assert(SIZE >= 10);\n\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 3> normals_1(SIZE, 3);\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 3> normals_2(SIZE, 3);\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> distances_1(SIZE);\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> distances_2(SIZE);\n\n  for (int i = 0; i < SIZE; ++i)\n  {\n    const Plane3 & plane_1 = plane_pair_vector[i].first;\n    const Plane3 & plane_2 = plane_pair_vector[i].second;\n\n    if (plane_1.offset() > 0)\n    {\n      normals_1.row(i) = -plane_1.normal();\n      distances_1(i) = plane_1.offset();\n    }\n    else\n    {\n      normals_1.row(i) = plane_1.normal();\n      distances_1(i) = -plane_1.offset();\n    }\n\n    if (plane_2.offset() > 0)\n    {\n      normals_2.row(i) = -plane_2.normal();\n      distances_2(i) = plane_2.offset();\n    }\n    else\n    {\n      normals_2.row(i) = plane_2.normal();\n      distances_2(i) = -plane_2.offset();\n    }\n  }\n\n  Transform3 transform;\n\n  Eigen::Matrix<Scalar, 3, 3> USV = normals_2.transpose() * normals_1;\n  Eigen::JacobiSVD<Eigen::Matrix<Scalar, 3, 3> > svd;\n  svd.compute(USV, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  transform.linear() = svd.matrixV() * svd.matrixU().transpose();\n\n//  transform.translation() = (normals_1.transpose() * normals_1).inverse() * normals_1.transpose() * (distances_1 - distances_2);\n\n  // Use QR decomposition\n  Eigen::ColPivHouseholderQR<Eigen::Matrix<Scalar, Eigen::Dynamic, 3> > qr(normals_1.rows(), 3);\n  qr.compute(normals_1);\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 3> R = qr.matrixR().template triangularView<Eigen::Upper>();\n  transform.translation() = (qr.colsPermutation() * R.transpose() * R * qr.colsPermutation().transpose()).inverse() * normals_1.transpose() * (distances_1 - distances_2);\n\n  return transform;\n}\n\n} // namespace calib\n} // namespace unipd\n", "meta": {"hexsha": "f4f3d020b8ccaa471a16d5f8a8adb34f58666b34", "size": 3719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_stars_repo_name": "pionex/calibration_toolkit", "max_stars_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T04:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:08:55.000Z", "max_issues_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_issues_repo_name": "pionex/calibration_toolkit", "max_issues_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T07:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-06T21:55:47.000Z", "max_forks_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_forks_repo_name": "pionex/calibration_toolkit", "max_forks_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-15T00:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T21:16:09.000Z", "avg_line_length": 38.7395833333, "max_line_length": 170, "alphanum_fraction": 0.7015326701, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6698407618695567}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <vector>\n\n//CRS\nvoid compressedSparseRow()\n{\n/*\n    0 1 2 3 4 5 6 7 8\n   \u250c                 \u2510\n 0 |0 0 0 0 0 0 0 3 0|\n 1 |0 0 8 0 0 1 0 0 0|\n 2 |0 0 0 0 0 0 0 0 0|\n 3 |4 0 0 0 0 0 0 0 0|\n 4 |0 0 0 0 0 0 0 0 0|\n 5 |0 0 2 0 0 0 0 0 0|\n 6 |0 0 0 6 0 0 0 0 0|\n 7 |0 9 0 0 5 0 0 0 0|\n   \u2514                 \u2518\n*/\n\n\n    int rows=8;\n    int cols=9;\n    Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> dense_mat;\n    dense_mat.resize(rows,cols);\n\n\n    dense_mat<<0, 0, 0, 0, 0, 0, 0, 3, 0,\n                0, 0, 8, 0, 0, 1, 0, 0, 0,\n                0, 0, 0, 0, 0, 0, 0, 0, 0,\n                4, 0, 0, 0, 0, 0, 0, 0, 0,\n                0, 0, 0, 0, 0, 0, 0, 0, 0,\n                0, 0, 2, 0, 0, 0, 0, 0, 0,\n                0, 0, 0, 6, 0, 0, 0, 0, 0,\n                0, 9, 0, 0, 5, 0, 0, 0, 0;\n\n    //specify a tolerance:\n    //sparse_mat = dense_mat.sparseView(epsilon,reference);\n    Eigen::SparseMatrix<double,Eigen::RowMajor> sparse_mat = dense_mat.sparseView();\n\n    std::cout<<\"sparse matrix number of cols:\"<<sparse_mat.cols()   <<std::endl;\n    std::cout<<\"sparse matrix numner of rows:\"<<sparse_mat.rows()   <<std::endl;\n\n    std::cout<<\"sparse matrix values:\"<<std::endl;\n    auto valuePtr=sparse_mat.valuePtr();\n    for(int i=0;i <sparse_mat.nonZeros();i++)\n    {\n        std::cout<<*(valuePtr++)  <<\", \";\n    }\n    std::cout<< \"\\n\";\n\n\n    std::cout<<\"COL_INDEX array size:\"<<sparse_mat.innerSize()  <<std::endl;\n    std::cout<<\"COL_INDEX array :\" <<std::endl;\n    auto colIndexPtr=sparse_mat.innerIndexPtr();\n\n    for(int i=0;i <sparse_mat.innerSize();i++)\n    {\n        std::cout<<*(colIndexPtr++)  <<\", \";\n    }\n    std::cout<< \"\\n\";\n\n    std::cout<<\"ROW_INDEX array size:\"<<sparse_mat.outerSize()   <<std::endl;\n    std::cout<<\"ROW_INDEX array:\" <<std::endl;\n    auto rowIndexPtr=sparse_mat.outerIndexPtr();\n    for(int i=0;i <sparse_mat.outerSize();i++)\n    {\n        std::cout<<*(rowIndexPtr++)  <<\", \";\n    }\n    std::cout<< \"\\n \";\n\n    std::cout<<\"*********sparse matrix*********\\n\"<<sparse_mat  <<std::endl;\n\n    std::cout<<\"*********dense matrix*********\\n\"<<dense_mat  <<std::endl;\n\n\n\n\n\n\n}\n\nint main1()\n{\n    compressedSparseRow();\n}\n\n\n\ntypedef Eigen::SparseMatrix<double> SpMat; // declares a column-major sparse matrix type of double\ntypedef Eigen::Triplet<double> T;//structure to hold a non zero as a triplet (i,j,value).\n\nvoid buildProblem(std::vector<T>& coefficients, Eigen::VectorXd& b, int n){}\nvoid saveAsBitmap(const Eigen::VectorXd& x, int n, const char* filename){}\n//https://eigen.tuxfamily.org/dox/classEigen_1_1Triplet.html\nint main(int argc, char** argv)\n{\n  if(argc!=2) {\n    std::cerr << \"Error: expected one and only one argument.\\n\";\n    return -1;\n  }\n\n  int n = 300;  // size of the image\n  int m = n*n;  // number of unknows (=number of pixels)\n\n  // Assembly:\n  std::vector<T> coefficients;            // list of non-zeros coefficients\n  Eigen::VectorXd b(m);                   // the right hand side-vector resulting from the constraints\n  buildProblem(coefficients, b, n);\n\n  SpMat A(m,m);\n  A.setFromTriplets(coefficients.begin(), coefficients.end());\n\n  // Solving:\n  Eigen::SimplicialCholesky<SpMat> chol(A);  // performs a Cholesky factorization of A\n  Eigen::VectorXd x = chol.solve(b);         // use the factorization to solve for the given right hand side\n\n  // Export the result to a file:\n  saveAsBitmap(x, n, argv[1]);\n\n  return 0;\n}\n", "meta": {"hexsha": "2f371b33707ba4fb24ac7afcf6f09363e60f9fd9", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_matrices.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/sparse_matrices.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/sparse_matrices.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.784, "max_line_length": 108, "alphanum_fraction": 0.5715519724, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.669838274753459}}
{"text": "// Unit test for the makeGrid function in fvm_1d_functions.cpp\n// This function calculates a cell-centered grid\n// COMPLETE. This function works as intended. 2021/11/18\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n    \n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the makeGrid function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set the input parameters to the makeGrid function\n    // The goal is to make a cell centered grid such that the according nodal grid\n    // has a left value of -1.5, a right boundary of 0.5, and a dx of 0.5.\n    // This would give 4 cells within the domain with an additional 2 ghost cells on either side\n    int totalNCells = 8;\n    int numGhost = 2;\n    double xLeft = -1.5;\n    double dx = 0.5;\n\n    // Set the exact values for the 1D grid\n    ArrayXd x_Exact(8);\n    x_Exact << -2.25, -1.75, -1.25, -.75, -.25, .25, .75, 1.25;\n\n    // Calculate the values based on the function\n    ArrayXd x = makeGrid(totalNCells, numGhost, xLeft, dx);\n\n    // Set the acceptable tolerance. (Somewhat arbitrarily chosen)\n    double TOL = dx*1e-14;\n\n    // Determine if the two arrays are equal\n    Array<bool, Dynamic, 1> boolArray = isEqualArray1D(x, x_Exact, TOL);\n\n    // Print results\n    if (boolArray.minCoeff() == 1) {\n        cout << \"Test of makeGrid is a success.\" << endl;\n    }\n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of makeGrid is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }\n\n    cout << endl << endl;\n}", "meta": {"hexsha": "620f365748687a75a5e375ec6ef8752e6fc1643c", "size": 1745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_makeGrid.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/unitTests/test_makeGrid.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/unitTests/test_makeGrid.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.9245283019, "max_line_length": 96, "alphanum_fraction": 0.5793696275, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.6698382679237602}}
{"text": "//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <iostream>\n#include <benchmark/benchmark.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\n#include <gmpxx.h>\n\ntemplate <class Integer>\ninline Integer factorial(unsigned n)\n{\n   Integer result = 1;\n   for (unsigned k = 1; k <= n; ++k)\n      result *= k;\n   return result;\n}\n\ntemplate <class Rational, class Integer = typename Rational::value_type>\ninline Rational binomial(unsigned n, unsigned k)\n{\n   return Rational(factorial<Integer>(n), factorial<Integer>(k) * factorial<Integer>(n - k));\n}\n\ninline mpz_class pow(mpz_class i, unsigned p)\n{\n   mpz_class result;\n   mpz_pow_ui(result.get_mpz_t(), i.get_mpz_t(), p);\n   return result;\n}\n\ntemplate <class Rational, class Integer = typename Rational::value_type>\nRational Bernoulli(unsigned m)\n{\n   Rational result = 0;\n\n   for (unsigned k = 0; k <= m; ++k)\n   {\n      Rational inner = 0;\n      for (unsigned v = 0; v <= k; ++v)\n      {\n         Rational term = binomial<Rational, Integer>(k, v) * Rational(pow(Integer(v), m), k + 1);\n         if (v & 1)\n            term = -term;\n         inner += term;\n      }\n      result += inner;\n   }\n   return result;\n}\n\ntemplate <class Rational, class Integer = typename Rational::value_type>\nstatic void BM_bernoulli(benchmark::State& state)\n{\n   int m = state.range(0);\n   for (auto _ : state)\n   {\n      benchmark::DoNotOptimize(Bernoulli<Rational, Integer>(m));\n   }\n}\n\n\nBENCHMARK_TEMPLATE(BM_bernoulli, boost::multiprecision::cpp_rational)->DenseRange(50, 200, 4);\nBENCHMARK_TEMPLATE(BM_bernoulli, boost::multiprecision::mpq_rational)->DenseRange(50, 200, 4);\nBENCHMARK_TEMPLATE(BM_bernoulli, boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::gmp_int> >)->DenseRange(50, 200, 4);\nBENCHMARK_TEMPLATE(BM_bernoulli, mpq_class, mpz_class)->DenseRange(50, 200, 4);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "d00618e8ca3c1423ca0f6ffb243bfeb59eb79077", "size": 2054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_bernoulli_bench.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-27T21:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T21:15:52.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_bernoulli_bench.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "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": "lib/boost_1.78.0/libs/multiprecision/performance/rational_bernoulli_bench.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:34.000Z", "avg_line_length": 28.9295774648, "max_line_length": 162, "alphanum_fraction": 0.6903602726, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6698372042676227}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. 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_\n\n//[safe_prime\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <iostream>\n#include <iomanip>\n\nint main()\n{\n   using namespace boost::random;\n   using namespace boost::multiprecision;\n\n   typedef cpp_int int_type;\n   mt11213b base_gen(clock());\n   independent_bits_engine<mt11213b, 256, int_type> gen(base_gen);\n   //\n   // We must use a different generator for the tests and number generation, otherwise\n   // we get false positives.\n   //\n   mt19937 gen2(clock());\n\n   for(unsigned i = 0; i < 100000; ++i)\n   {\n      int_type n = gen();\n      if(miller_rabin_test(n, 25, gen2))\n      {\n         // Value n is probably prime, see if (n-1)/2 is also prime:\n         std::cout << \"We have a probable prime with value: \" << std::hex << std::showbase << n << std::endl;\n         if(miller_rabin_test((n-1)/2, 25, gen2))\n         {\n            std::cout << \"We have a safe prime with value: \" << std::hex << std::showbase << n << std::endl;\n            return 0;\n         }\n      }\n   }\n   std::cout << \"Ooops, no safe primes were found - probably a bad choice of seed values!\" << std::endl;\n   return 0;\n}\n\n//]\n", "meta": {"hexsha": "4421f8d7b9f3030e950f2d5eba254bf4da2242c9", "size": 1408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 30.6086956522, "max_line_length": 109, "alphanum_fraction": 0.6008522727, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6698371989599294}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::algorithm::log_shift.hpp                      //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. 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_STATISTICS_SURVIVAL_DATA_ALGORITHM_DETAIL_LOG_SHIFT_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_ALGORITHM_DETAIL_LOG_SHIFT_HPP_ER_2009\n#include <boost/math/special_functions/log1p.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace data{\nnamespace detail{\n            \n    template<typename T>\n    T log_shift(\n        const T& x,\n        const T& t\n    ){\n        return log(x+t);\n    }\n            \n    template<typename T>\n    T logit_shift(\n        const T& p,\n        const T& t\n    ){\n        // log(p/(1-p)) = log(p)-log(1-p)\n    \n        return log_shift(p,t) - boost::math::log1p(t - p);\n    }\n            \n            \n}// detail\n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "ffdd9e9ccfee4879f01cdd5f2a95ce56e5f07be2", "size": 1298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/algorithm/detail/log_shift.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "survival_data copy/boost/statistics/survival/data/algorithm/detail/log_shift.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "survival_data copy/boost/statistics/survival/data/algorithm/detail/log_shift.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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.1860465116, "max_line_length": 79, "alphanum_fraction": 0.4899845917, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6698054704532975}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Framework/TestingFramework.hpp\"\n\n#include <boost/math/tools/roots.hpp>\n#include <cmath>\n#include <cstddef>\n#include <utility>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"ErrorHandling/Error.hpp\"\n#include \"ErrorHandling/Exceptions.hpp\"\n#include \"Framework/TestHelpers.hpp\"\n#include \"NumericalAlgorithms/RootFinding/NewtonRaphson.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeString.hpp\"\n\nnamespace {\nstd::pair<double, double> func_and_deriv_free(double x) noexcept {\n  return std::make_pair(2. - square(x), -2. * x);\n}\nstruct FuncAndDeriv {\n  std::pair<double, double> operator()(double x) const noexcept {\n    return std::make_pair(2. - square(x), -2. * x);\n  }\n};\n\nvoid test_simple() noexcept {\n  /// [double_newton_raphson_root_find]\n  const size_t digits = 8;\n  const double correct = sqrt(2.);\n  const double guess = 1.5;\n  const double lower = 1.;\n  const double upper = 2.;\n  const auto func_and_deriv_lambda = [](double x) noexcept {\n    return std::make_pair(2. - square(x), -2. * x);\n  };\n  const auto root_from_lambda = RootFinder::newton_raphson(\n      func_and_deriv_lambda, guess, lower, upper, digits);\n  /// [double_newton_raphson_root_find]\n  const auto root_from_free = RootFinder::newton_raphson(\n      func_and_deriv_free, guess, lower, upper, digits);\n  const FuncAndDeriv func_and_deriv_functor{};\n  const auto root_from_functor = RootFinder::newton_raphson(\n      func_and_deriv_functor, guess, lower, upper, digits);\n  CHECK(std::abs(root_from_lambda - correct) < 1.0 / std::pow(10, digits));\n  CHECK(root_from_free == root_from_lambda);\n  CHECK(root_from_free == root_from_functor);\n}\n\nvoid test_bounds() noexcept {\n  const size_t digits = 8;\n  const double guess = 1.5;\n  double upper = 2.;\n  double lower = sqrt(2.);\n  const auto func_and_deriv_lambda = [](double x) noexcept {\n    return std::make_pair(2. - square(x), -2. * x);\n  };\n\n  auto root = RootFinder::newton_raphson(func_and_deriv_lambda, guess, lower,\n                                         upper, digits);\n  const double correct = sqrt(2.);\n\n  CHECK(std::abs(root - correct) < 1.0 / std::pow(10, digits));\n\n  lower = 0.;\n  upper = sqrt(2.);\n\n  root = RootFinder::newton_raphson(func_and_deriv_lambda, guess, lower, upper,\n                                    digits);\n  CHECK(std::abs(root - correct) < 1.0 / std::pow(10, digits));\n}\n\nvoid test_datavector() noexcept {\n  /// [datavector_newton_raphson_root_find]\n  const size_t digits = 8;\n  const DataVector guess{1.6, 1.9, -1.6, -1.9};\n  const DataVector lower{sqrt(2.), sqrt(2.), -2., -3.};\n  const DataVector upper{2., 3., -sqrt(2.), -sqrt(2.)};\n  const DataVector constant{2., 4., 2., 4.};\n\n  const auto func_and_deriv_lambda = [&constant](const double x,\n                                                 const size_t i) noexcept {\n    return std::make_pair(constant[i] - square(x), -2. * x);\n  };\n\n  const auto root = RootFinder::newton_raphson(func_and_deriv_lambda, guess,\n                                               lower, upper, digits);\n  /// [datavector_newton_raphson_root_find]\n\n  const DataVector correct{sqrt(2.), 2., -sqrt(2.), -2.};\n\n  for (size_t i = 0; i < guess.size(); i++) {\n    CHECK(std::abs(root[i] - correct[i]) < 1.0 / std::pow(10, digits));\n  }\n}\n\nvoid test_convergence_error_double() noexcept {\n  const size_t max_iterations = 2;\n  const size_t digits = 8;\n  const double guess = 1.5;\n  const double lower = 1.;\n  const double upper = 2.;\n  boost::uintmax_t max_iters = max_iterations;\n\n  const auto func_and_deriv = [](double x) noexcept {\n    return std::make_pair(2. - square(x), -2. * x);\n  };\n\n  // Exception message is expected to print the \"best\" result, so here\n  // we obtain that result directly with boost, as RootFinder::newton_raphson\n  // would throw an exception.\n  // clang-tidy: internal boost warning, can't fix it.\n  const auto best_result =\n      boost::math::tools::newton_raphson_iterate(  // NOLINT\n          func_and_deriv, guess, lower, upper,\n          std::round(std::log2(std::pow(10, digits))), max_iters);\n  test_throw_exception(\n      [&func_and_deriv, &guess, &lower, &upper, &max_iters]() {\n        RootFinder::newton_raphson(func_and_deriv, guess, lower, upper, digits,\n                                   max_iters);\n      },\n      convergence_error(MakeString{}\n                        << \"newton_raphson reached max iterations of \"\n                        << max_iterations\n                        << \" without converging. Best result is: \"\n                        << best_result << \" with residual \"\n                        << func_and_deriv(best_result).first));\n}\n\nvoid test_convergence_error_datavector() noexcept {\n  const size_t max_iterations = 2;\n  const size_t digits = 8;\n  const auto digits_binary = std::round(std::log2(std::pow(10, digits)));\n  const DataVector lower{sqrt(2.), sqrt(2.), -2., -3.};\n  const DataVector upper{2., 3., -sqrt(2.), -sqrt(2.)};\n  const DataVector constant{2., 4., 2., 4.};\n\n  const auto func_and_deriv = [&constant](const double x,\n                                          const size_t i) noexcept {\n    return std::make_pair(constant[i] - square(x), -2. * x);\n  };\n\n  // We test with different guesses, the difference being the location of the\n  // element in the DataVector expected to throw the exception.\n  const std::array<DataVector, 4> guess{{{1.6, 1.9, -1.6, -1.9},\n                                         {sqrt(2.), 1.9, -1.6, -1.9},\n                                         {sqrt(2.), 2.0, -1.6, -1.9},\n                                         {sqrt(2.), 2.0, -sqrt(2.), -1.9}}};\n  for (size_t i = 0; i < guess.size(); ++i) {\n    const DataVector& current_guess = gsl::at(guess, i);\n    // Exception message is expected to print the \"best\" result, so here\n    // we obtain that result directly with boost, as RootFinder::newton_raphson\n    // would throw an exception.\n    DataVector best_result_vector{lower.size()};\n    for (size_t s = 0; s < best_result_vector.size(); ++s) {\n      boost::uintmax_t max_iters = max_iterations;\n      // clang-tidy: internal boost warning, can't fix it.\n      best_result_vector[s] =\n          boost::math::tools::newton_raphson_iterate(  // NOLINT\n              [&func_and_deriv, s ](double x) noexcept {\n                return func_and_deriv(x, s);\n              },\n              current_guess[s], lower[s], upper[s], digits_binary, max_iters);\n    }\n    for (size_t s = 0; s < best_result_vector.size(); ++s) {\n      boost::uintmax_t max_iters = max_iterations;\n      test_throw_exception(\n          [&func_and_deriv, &current_guess, &lower, &upper, &max_iters]() {\n            RootFinder::newton_raphson(func_and_deriv, current_guess, lower,\n                                       upper, digits, max_iters);\n          },\n          convergence_error(MakeString{}\n                            << \"newton_raphson reached max iterations of \"\n                            << max_iterations\n                            << \" without converging. Best result is: \"\n                            << best_result_vector[i] << \" with residual \"\n                            << func_and_deriv(best_result_vector[i], i).first));\n    }\n  }\n}\n\nSPECTRE_TEST_CASE(\"Unit.Numerical.RootFinding.NewtonRaphson\",\n                  \"[NumericalAlgorithms][RootFinding][Unit]\") {\n  test_simple();\n  test_bounds();\n  test_datavector();\n  test_convergence_error_double();\n  test_convergence_error_datavector();\n}\n\n// [[OutputRegex, The desired accuracy of 100 base-10 digits must be smaller]]\n[[noreturn]] SPECTRE_TEST_CASE(\n    \"Unit.Numerical.RootFinding.NewtonRaphson.Digits.Double\",\n    \"[NumericalAlgorithms][RootFinding][Unit]\") {\n  ASSERTION_TEST();\n#ifdef SPECTRE_DEBUG\n  const size_t digits = 100;\n  const double guess = 1.5;\n  double lower = 1.;\n  double upper = 2.;\n  const auto func_and_deriv_lambda = [](double x) {\n    return std::make_pair(2. - square(x), -2. * x);\n  };\n\n  RootFinder::newton_raphson(func_and_deriv_lambda, guess, lower, upper,\n                             digits);\n  ERROR(\"Failed to trigger ASSERT in an assertion test\");\n#endif\n}\n\n// [[OutputRegex, The desired accuracy of 100 base-10 digits must be smaller]]\n[[noreturn]] SPECTRE_TEST_CASE(\n    \"Unit.Numerical.RootFinding.NewtonRaphson.Digits.DataVector\",\n    \"[NumericalAlgorithms][RootFinding][Unit]\") {\n  ASSERTION_TEST();\n#ifdef SPECTRE_DEBUG\n  const size_t digits = 100;\n  const DataVector guess{1.6, 1.9, -1.6, -1.9};\n  const DataVector lower{sqrt(2.), sqrt(2.), -2., -3.};\n  const DataVector upper{2., 3., -sqrt(2.), -sqrt(2.)};\n  const DataVector constant{2., 4., 2., 4.};\n\n  const auto func_and_deriv_lambda = [&constant](const double x,\n                                                 const size_t i) noexcept {\n    return std::make_pair(constant[i] - square(x), -2. * x);\n  };\n\n  const auto root = RootFinder::newton_raphson(func_and_deriv_lambda, guess,\n                                               lower, upper, digits);\n  ERROR(\"Failed to trigger ASSERT in an assertion test\");\n#endif\n}\n}  // namespace\n", "meta": {"hexsha": "fdd57ab271b9ea909e821671b5fe853e3e234113", "size": 9119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Unit/NumericalAlgorithms/RootFinding/Test_NewtonRaphson.cpp", "max_stars_repo_name": "keefemitman/spectre", "max_stars_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Unit/NumericalAlgorithms/RootFinding/Test_NewtonRaphson.cpp", "max_issues_repo_name": "keefemitman/spectre", "max_issues_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Unit/NumericalAlgorithms/RootFinding/Test_NewtonRaphson.cpp", "max_forks_repo_name": "keefemitman/spectre", "max_forks_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_forks_repo_licenses": ["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.4767932489, "max_line_length": 80, "alphanum_fraction": 0.6211207369, "num_tokens": 2389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.669805460242388}}
{"text": "#ifndef MIXMAT_HPP\n#define MIXMAT_HPP\n\n#include <vector>\n#include <cstddef>\n#include <iostream>\n#include <wignerSymbols.h>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <cassert>\n#include <exception>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nenum mixMatType\n{\n    TT,\n    EE,\n};\n\ntemplate<typename _realScalarType>\nclass MixingMatrix\n{\npublic:\n    /**\n     * \\typedef _realScalarType realScalarType\n     * \\brief real floating point type\n     */\n    typedef _realScalarType realScalarType;\n\n    /**\n     * \\typedef typename Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> mixingMatrixType\n     * \\brief mixing matrix type\n     */\n    typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,Eigen::Dynamic> mixingMatrixType;\n\n\n    /**\n     * \\typedef typename mixingMatrixType::Index indexType\n     * \\brief integral type\n     */\n    typedef typename mixingMatrixType::Index indexType;\n\n\n    /**\n     * \\typedef Eigen::LLT<mixingMatrixType> LLTType;\n     * \\brief Cholesky decompostion type\n     */\n    typedef Eigen::LLT<mixingMatrixType> LLTType;\n\n    typedef Eigen::Matrix<realScalarType,Eigen::Dynamic,1> powSpecType;\n\n\n    MixingMatrix(powSpecType const & W,mixMatType const mt)\n    :mW(W)\n    {\n        const indexType lMax = W.rows()-1;\n        const indexType matDim(lMax+1);\n        mM = mixingMatrixType::Zero(matDim,matDim);\n        mLMax = lMax;\n        mMT = mt;\n        std::cout<<\"lMax = \"<<lMax<<std::endl;\n    }\n\n    void computeMixingMatrixWithRecursion()\n    {\n        if(mMT == TT)\n        {\n            std::cout<<\"Computing TT mixing matrix\"<<std::endl;\n\n            const indexType matDim(mLMax+1);\n            mM = mixingMatrixType::Zero(matDim,matDim);\n\n            for(indexType l1=0;l1<=mLMax;++l1)\n            {\n                for(indexType l2=0;l2<=mLMax;++l2)\n                {\n                    std::vector<double> wig3j =\n                        WignerSymbols::wigner3j((double)l1,(double)l2,\n                            (double)0,(double)0,(double)0);\n\n                    indexType l3Min = std::max(std::abs(l1-l2),indexType(0));\n                    indexType l3max = std::min( l3Min + indexType(wig3j.size()-1),mLMax ) ;\n\n                    for(indexType l3=l3Min;l3<=l3max;++l3)\n                    {\n                        if( selectWig3j( l3,l1,l2,indexType(0),indexType(0),indexType(0) )  )\n                        {\n                            mM(l1,l2) += realScalarType(2*l3+1)*mW(l3)*wig3j[l3 - l3Min]*wig3j[l3 - l3Min];\n                        }\n                    }\n\n                    mM(l1,l2) *= realScalarType(2*l2+1)/(4*M_PI);\n                }\n            }\n        }\n        else if(mMT == EE)\n        {\n            std::cout<<\"Computing EE mixing matrix\"<<std::endl;\n\n            const indexType matDim(mLMax+1);\n            mM = mixingMatrixType::Zero(matDim,matDim);\n\n            for(indexType l1=0;l1<=mLMax;++l1)\n            {\n                for(indexType l2=0;l2<=mLMax;++l2)\n                {\n                    std::vector<double> wig3j =\n                        WignerSymbols::wigner3j((double)l1,(double)l2,\n                            (double)0,(double)2,(double)-2);\n\n                    indexType l3Min = std::max(std::abs(l1-l2),indexType(0));\n                    indexType l3max = std::min( l3Min + indexType(wig3j.size()-1),mLMax ) ;\n\n                    for(indexType l3=l3Min;l3<=l3max;++l3)\n                    {\n                        if( selectWig3j( l3,l1,l2,indexType(0),indexType(2),indexType(-2) ) && (l1+l2+l3)%2 == 0 )\n                        {\n                            mM(l1,l2) += realScalarType(2*l3+1)*realScalarType(2)*mW(l3)*wig3j[l3 - l3Min]*wig3j[l3 - l3Min];\n                        }\n                    }\n\n                    mM(l1,l2) *= realScalarType(2*l2+1)/(8*M_PI);\n                }\n            }\n\n        }\n\n    }\n\n    bool selectWig3j(indexType const l1,indexType const l2,indexType const l3,\n        indexType const m1,indexType const m2,indexType const m3)\n    {\n        bool select(true);\n\n        select = (\n            std::abs(m1+m2+m3) == indexType(0)\n            && l3 >= std::abs(l1-l2)\n            && l3 <= l1+l2\n            && std::abs(m1) <= l1\n            && std::abs(m2) <= l2\n            && std::abs(m3) <= l3\n        );\n\n        return ( select );\n    }\n\n    void save(std::string const fileName)\n    {\n        writeMatrixToFile(fileName,mM,10,\",\");\n    }\n\n\n    void applyMixingMatrix(powSpecType & C)\n    {\n        C = mM*C;\n    }\n\n    void applyMixingMatrixInv(powSpecType & C)\n    {\n        LLTType lltOfM;\n        lltOfM.compute(mM);\n        assert(lltOfM.info() == Eigen::Success);\n        C = lltOfM.solve(C);\n    }\n\nprivate:\n\n    void writeMatrixToFile(std::string const & fileName,\n        mixingMatrixType const& mat,unsigned int precision,\n        std::string const& separation)\n    {\n        std::ofstream outFile;\n        outFile.open(fileName.c_str(),std::ios::trunc);\n\n        if(outFile.is_open())\n        {\n            outFile<<std::scientific;\n            for(indexType i=0;i<mat.rows();++i)\n            {\n                for(indexType j=0;j<mat.cols()-1;++j)\n                {\n                    outFile<<std::setprecision(precision)<<mat(i,j)<<separation;\n                }\n                outFile<<mat(i,(mat.cols()-1) )<<std::endl;\n            }\n            outFile.close();\n        }\n        else\n        {\n            std::string msg = std::string(\"Error in opening the file \") +\n                fileName;\n            throw std::runtime_error(msg);\n        }\n    }\n\n    powSpecType mW;\n    mixingMatrixType mM;\n    indexType mLMax;\n    mixMatType mMT;\n\n};\n\n#endif //MIXMAT_HPP\n", "meta": {"hexsha": "aa3245bbf999e51eeb906aefb7a10999076ffb20", "size": 5659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mixmat.hpp", "max_stars_repo_name": "tbs1980/mixmat", "max_stars_repo_head_hexsha": "1ae09a8cdf1333a08a2a6ccbf79cef3c1f8f362a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mixmat.hpp", "max_issues_repo_name": "tbs1980/mixmat", "max_issues_repo_head_hexsha": "1ae09a8cdf1333a08a2a6ccbf79cef3c1f8f362a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mixmat.hpp", "max_forks_repo_name": "tbs1980/mixmat", "max_forks_repo_head_hexsha": "1ae09a8cdf1333a08a2a6ccbf79cef3c1f8f362a", "max_forks_repo_licenses": ["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.3381642512, "max_line_length": 125, "alphanum_fraction": 0.5119279025, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.669805453132694}}
{"text": "/**\n * @file k_means_clustering.hpp\n * @brief\n * @author Piotr Smulewicz, Piotr Wygocki\n * @version 1.0\n * @date 2014-06-25\n */\n#ifndef PAAL_K_MEANS_CLUSTERING_HPP\n#define PAAL_K_MEANS_CLUSTERING_HPP\n\n#include \"paal/clustering/k_means_clustering_engine.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/range/algorithm_ext/iota.hpp>\n#include <boost/range/empty.hpp>\n\n#include <vector>\n\nnamespace paal {\n\n/**\n * @brief  return centroid that minimize within-cluster sum of squares\n */\ntemplate <typename Cluster, typename OutputIterator>\nvoid centroid_minimalize_w_c_s_s(Cluster && cluster, OutputIterator out) {\n    assert(!boost::empty(cluster));\n    using point_t = range_to_elem_t<Cluster>;\n    using coordinate_t = range_to_elem_t<point_t>;\n\n    auto dim = boost::size(*std::begin(cluster));\n    for(auto idx : irange(dim)) {\n        coordinate_t res{};\n        for (auto && point : cluster) {\n            res += std::begin(point)[idx];\n        }\n        *out = res / boost::size(cluster);\n        ++out;\n   }\n}\n\n/**\n * @brief centroid minimize within cluster sum of squares\n * @param clusters\n * @param out\n * @tparam Clusters\n * @tparam OutputIterator\n */\ntemplate <typename Clusters, typename OutputIterator>\nvoid centroids_minimalize_w_c_s_s(Clusters && clusters, OutputIterator out) {\n    assert(!boost::empty(clusters));\n    assert(!boost::empty(*std::begin(clusters)));\n\n    using cluster_t = range_to_elem_t<Clusters>;\n    using point_t = range_to_elem_t<cluster_t>;\n    using coordinate_t = range_to_elem_t<point_t>;\n\n    auto size = boost::size(*std::begin(*begin(clusters)));\n    for (auto && cluster : clusters) {\n        std::vector<coordinate_t> point(size);\n        centroid_minimalize_w_c_s_s(cluster, point.begin());\n        *out = point;\n        ++out;\n    }\n}\n\n/**\n * @brief this is solve k_means_clustering problem\n * and return vector of cluster\n * example:\n *  \\snippet k_means_clustering_example.cpp K Means Clustering Example\n *\n * complete example is k_means_clustering_example.cpp\n * @param points\n * @param centers\n * @param result pairs of point and id of cluster\n * (number form 0,1,2 ...,number_of_cluster-1)\n * @param visitor\n * @tparam Points\n * @tparam OutputIterator\n * @tparam CoordinateType\n * @tparam Visitor\n */\ntemplate <typename Points, class Centers, class OutputIterator,\n          class Visitor = k_means_visitor>\nauto k_means(Points &&points, Centers &&centers, OutputIterator result,\n             Visitor visitor = Visitor{}) {\n    using point_t = range_to_elem_t<Points>;\n    using center_t = range_to_elem_t<Centers>;\n\n    center_t center{ *std::begin(centers) };\n\n    return k_means(\n        points, centers,\n        [&](std::vector<point_t> const & points)->center_t const & {\n            centroid_minimalize_w_c_s_s(points, std::begin(center));\n            return center;\n        },\n        [&](point_t const &point) { return closest_to(point, centers); },\n        result, utils::equal_to{}, visitor);\n}\n\n} //!paal\n\n#endif /* PAAL_K_MEANS_CLUSTERING_HPP */\n", "meta": {"hexsha": "c471a468c3c84a3e2ba65efa6ed6ced815717b58", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/clustering/k_means_clustering.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "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/paal/clustering/k_means_clustering.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "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/paal/clustering/k_means_clustering.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 28.7142857143, "max_line_length": 77, "alphanum_fraction": 0.6815920398, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6698054117853922}}
{"text": "\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/bindings/ublas/banded.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/bandwidth.hpp>\n#include <boost/numeric/bindings/lapack/computational/gbtrf.hpp>\n#include <boost/numeric/bindings/lapack/computational/gbtrs.hpp>\n#include <vector>\n#include <stdexcept>\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\n// solves the equation Ax = B, and puts the solution in B\n// A is mutated by this routine\ntemplate <typename MatrA, typename MatrB>\nvoid InPlaceSolve(MatrA& a, MatrB& b)\n{\n  // if the matrix has kl lower and ku upper diagonals, then we should have\n  // allocated kl lower and kl+ku upper diagonals\n  fortran_int_t const kl = bindings::bandwidth_lower(a);\n  fortran_int_t const ku = bindings::bandwidth_upper(a) - kl;\n  std::vector<fortran_int_t> piv(a.size1());\n  int ret = lapack::gbtrf(/*kl, ku, */a, piv);\n  if(ret < 0)\n  {\n    //CStdString err;\n    //err.Format(\"banded::Solve: argument %d in DGBTRF had an illegal value\", -ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: argument %d in DGBTRF had an illegal value\");\n  }\n  if(ret > 0)\n  {\n    //CStdString err;\n    //err.Format(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\", ret, ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\");\n  }\n\n  ret = lapack::gbtrs(/*kl, ku, */a, piv, b);\n  if(ret < 0)\n  {\n    //CStdString err;\n    //err.Format(\"banded::Solve: argument %d in DGBTRS had an illegal value\", -ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: argument %d in DGBTRS had an illegal value\");\n  }\n}\n\ntemplate<typename T>\nvoid do_typename()\n{\n  using namespace boost::numeric::ublas;\n  // if the matrix has kl lower and ku upper diagonals, then we should\n  // allocate kl lower and kl+ku upper diagonals\n  size_t sz = 1000, kl = 1, ku = 1;\n  ublas::banded_matrix<T> a(sz, sz, kl, kl+ku);\n  ublas::vector<T> b(sz);\n  // fill values in a and b\n  for(size_t i = 0; i < sz; ++i)\n  {\n    a(i,i) = i;\n    b(i) = i;\n  }\n  for(size_t i = 1; i < sz; ++i)\n  {\n    a(i,i-1) = i;\n    a(i-1,i) = 1;\n  }\n  InPlaceSolve(a, b);\n}\n\nint main()\n{\n  do_typename<float>();\n  do_typename<double>();\n  do_typename<std::complex<float> >();\n  do_typename<std::complex<double> >();\n  return 0;\n}\n", "meta": {"hexsha": "6d6d81539a091d0daf54aa98ea4c8e69019cefce", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 30.5487804878, "max_line_length": 94, "alphanum_fraction": 0.6686626747, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6697998385653774}}
{"text": "// test_integrate.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestIntegrate)\n    \n    double test_integrate_function_1(double x) {\n        return 5*pow(x, 3) + 2*cos(x);\n    }\n\n    double test_integrate_function_2(double x) {\n        return (cos(x) / (1.0 + exp(1.0 / x)));\n    }\n\n    BOOST_AUTO_TEST_CASE(test_integrate_simpson)\n    {\n        const double eps = 1e-9;\n        double *I = NULL;\n        double a, b;\n        double expected_result;\n\n        // Testing \\int_{0}^{1}\\left(\\5x^3 + 2cos(x)\\right) dx\n        a = 0.0;\n        b = 1.0;\n        expected_result = 2.93294196961579301330500464;\n        I = Numerary::integrate(test_integrate_function_1, a, b, \"simpson\", eps);\n        BOOST_CHECK(fabs(I[0] - expected_result) <= I[1]);\n\n\n        // Testing \\int_{-1}^{1} \\left( \\frac{\\cos x}{1 +e^{\\frac{1}{x}}} \\right)\n        a = -1.0;\n        b = 1.0;\n        expected_result = 0.8414709848078965066525023;\n        I = Numerary::integrate(test_integrate_function_2, a, b, \"simpson\", eps);\n        BOOST_CHECK(fabs(I[0] - expected_result) <= I[1]);\n\n        delete[] I;\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "6c9aed94d77cbda73c1c6d5c9647c3d9976ca0cf", "size": 1216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_integrate.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_integrate.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_integrate.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 25.3333333333, "max_line_length": 81, "alphanum_fraction": 0.5830592105, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6697950907652533}}
{"text": "#include <iostream>\n#include <complex>\n#include <cmath>\n#include <Eigen/Dense>\n#include \"mex.h\"\n\nconst std::complex<double> i1(0.0, 1.0);\n\nEigen::Matrix3cd T;\n\n\nvoid update_T(double a, double p)\n{\n    T(0,0) = pow(cos(a/2),2);\n    T(0,1) = pow(sin(a/2),2)*(cos(2*p)+1.0*i1*sin(2*p));\n    T(0,2) = sin(a)*(sin(p)-1.0*i1*cos(p));\n    T(1,0) = std::conj(T(0,1));\n    T(1,1) = T(0,0);\n    T(1,2) = std::conj(T(0,2));\n    T(2,0) = -0.5*sin(a)*(sin(p)+1.0*i1*cos(p));\n    T(2,1) = std::conj(T(2,0));\n    T(2,2) = cos(a);\n}\n\nvoid EPG_GRE(double *signal_real, double *signal_imag, double *path_real, double *path_imag, double *N, double *FA, double *RF, double *TR, double *T1, double *T2, double *M0)\n{\n    int n = (int) N[0];\n\n    //max order of EPG simulation\n    int KMAX = n;\n    if(n>25){KMAX = 25;}\n\n    ///// MEMORY ALLOCATION\t\n    // relaxation operators\n    double E1 = exp(-TR[0]/T1[0]);\n    double E2 = exp(-TR[0]/T2[0]);\n\n    // signal vectors\n    Eigen::VectorXcd F_plus(KMAX);\n    F_plus.setZero();\n\n    Eigen::VectorXcd F_minus(KMAX);\n    F_minus.setZero();\n\n    Eigen::VectorXcd Z(KMAX);\n    Z.setZero();\n\n    Eigen::Vector3cd aux_states(0, 0, 0);\n\n\n    /////SIGNAL SIMULATION\n    Z(0) = M0[0];\n    \n    // transition matrix\n    update_T(FA[0], RF[0]);\n\n    //apply first pulse\n    aux_states(0) = F_plus(0);\n    aux_states(1) = F_minus(0);\n    aux_states(2) = Z(0);\n    aux_states = T * aux_states;\n    F_plus(0) = aux_states(0);\n    F_minus(0) = aux_states(1);\n    Z(0) = aux_states(2);\n\n    //save F_minus_zero >> this is the measured signal\n    signal_real[0] = F_minus(0).real();\n    signal_imag[0] = F_minus(0).imag();\n\n    //simulate rest of the sequence\n    for (int j=1; j<n; j++){\n\n\t    //apply E\n    \tfor (int k=0; k<(std::min(j,KMAX)); k++)\n    \t{\n    \t\tF_plus(k) = F_plus(k) * E2;\n    \t\tF_minus(k) = F_minus(k) * E2;\n    \t\tZ(k) = Z(k) * E1; \n    \t}\n    \tZ(0) += (1.0 - E1)*M0[0];\n\n    \t//apply S\n    \tfor (int k=(std::min(KMAX-1,j)); k>0; k--){ F_plus(k) = F_plus(k-1); }\n    \tF_plus(0) = std::conj(F_minus(1));\n    \tfor (int k=0; k<(std::min(KMAX-1,j)); k++){ F_minus(k) = F_minus(k+1); }\n    \tF_minus(std::min(KMAX-1,j)) = 0.0 + 0.0*i1;\n\t\n    \t//apply T\n        update_T(FA[j], RF[j]);\n    \tfor (int k=0; k<(std::min(KMAX,j+1)); k++) \n    \t{\n    \t\taux_states(0) = F_plus(k);\n    \t\taux_states(1) = F_minus(k);\n    \t\taux_states(2) = Z(k);\n    \t\taux_states = T * aux_states;\n    \n    \t\tF_plus(k) = aux_states(0);\n    \t\tF_minus(k) = aux_states(1);\n    \t\tZ(k) = aux_states(2);\n    \t}\n\n            \n    \t//save F_minus_zero\n    \tsignal_real[j] = F_minus(0).real();\n        signal_imag[j] = F_minus(0).imag();\n\n        //save last states \n        if(j==(n-1))\n        {\n            for (int k=0; k<KMAX; k++)\n            {\n                path_real[3*k] = F_plus(k).real();\n                path_real[3*k+1] = F_minus(k).real();\n                path_real[3*k+2] = Z(k).real();\n                path_imag[3*k] = F_plus(k).imag();\n                path_imag[3*k+1] = F_minus(k).imag();\n                path_imag[3*k+2] = Z(k).imag();\n            }\n        }\n    }\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int rhs, const mxArray *prhs[])\n{\n    /* Declare arrays necessary to compute signals */ \n    double *N;\n    double *FA; \n    double *RF; \n    double *TR; \n    double *T1;\n    double *T2;\n    double *M0;\n\n    double *signal_real;\n    double *signal_imag;\n    double *path_real;\n    double *path_imag;\n\n    /* Check for proper number of arguments */\n    \n    /* Create pointers to the inputs */\n    N = mxGetPr(prhs[0]);\n    FA = mxGetPr(prhs[1]); \n    RF = mxGetPr(prhs[2]); \n    TR = mxGetPr(prhs[3]);\n    T1 = mxGetPr(prhs[4]); \n    T2 = mxGetPr(prhs[5]);\n    M0 = mxGetPr(prhs[6]);\n\n    /* Create pointers to the outputs */\n    plhs[0] = mxCreateDoubleMatrix((mwSize)*N, 1, mxCOMPLEX);\n    plhs[1] = mxCreateDoubleMatrix(3, 25, mxCOMPLEX);\n    \n    // Check this link to see how to return complex arrays:\n    // http://matlab.izmiran.ru/help/techdoc/matlab_external/ch04cre9.html\n    signal_real = mxGetPr(plhs[0]);\n    signal_imag = mxGetPi(plhs[0]);\n    path_real = mxGetPr(plhs[1]);\n    path_imag = mxGetPi(plhs[1]);\n        \n    /* Call the computational routine */\n    EPG_GRE(signal_real, signal_imag, path_real, path_imag, N, FA, RF, TR, T1, T2, M0);\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "f9ca5377c26a9da655476e36d457cd43da1da795", "size": 4291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library/cppEPG_GRE_MEP.cpp", "max_stars_repo_name": "mriphysics/qMRI_efficiency", "max_stars_repo_head_hexsha": "f311785041939e0e278e4c9c4ae7dbe54d31f9d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T16:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-19T01:59:23.000Z", "max_issues_repo_path": "library/cppEPG_GRE_MEP.cpp", "max_issues_repo_name": "mriphysics/qMRI_efficiency", "max_issues_repo_head_hexsha": "f311785041939e0e278e4c9c4ae7dbe54d31f9d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/cppEPG_GRE_MEP.cpp", "max_forks_repo_name": "mriphysics/qMRI_efficiency", "max_forks_repo_head_hexsha": "f311785041939e0e278e4c9c4ae7dbe54d31f9d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-17T04:47:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T04:47:33.000Z", "avg_line_length": 25.2411764706, "max_line_length": 175, "alphanum_fraction": 0.5376369145, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6697297866120272}}
{"text": "// main.cpp -- example use of CppGPs for Gaussian process regression\n\n//\n// Eigen macros for using externel routines (may need to be moved to header file)\n// ( see https://eigen.tuxfamily.org/dox/TopicUsingBlasLapack.html ) \n//#define EIGEN_USE_BLAS            // Must also link to BLAS library\n//#define EIGEN_USE_LAPACKE_STRICT  // Must also link to LAPACKE library\n//#define EIGEN_USE_MKL_ALL         // Must also link to Intel MKL library\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <vector>\n#include <string>\n#include <memory>\n#include <random>\n#include <chrono>\n#include <fstream>\n#include <boost/range/irange.hpp>\n#include \"GPs.h\"\n\n#include <limits>\n\n// Specify the target function for Gaussian process regression\ndouble targetFunc(Eigen::MatrixXd X)\n{\n\n  if ( X.size() == 1 )\n    {\n      // Define the target function to be an oscillatory, non-periodic function\n      double oscillation = 30.0;\n      double xshifted = 0.5*(X(0) + 1.0);\n      return std::sin(oscillation*(xshifted-0.1))*(0.5-(xshifted-0.1))*15.0;\n    }\n  else\n    {\n      // Define the target function to be the Marr wavelet (a.k.a \"Mexican Hat\" wavelet)\n      // ( see https://en.wikipedia.org/wiki/Mexican_hat_wavelet )\n      double sigma = 0.25;\n      double pi = std::atan(1)*4;\n      double radialTerm = std::pow(X.squaredNorm()/sigma,2);\n      return 2.0 / (std::sqrt(pi*sigma) * std::pow(pi,1.0/4.0)) * (1.0 - radialTerm) * std::exp(-radialTerm);\n    }\n}\n\n\n// Example use of CppGPs code for Gaussian process regression\nint main(int argc, char const *argv[])\n{\n\n  // Retrieve aliases from GP namescope\n  using Matrix = Eigen::MatrixXd;\n  using Vector = Eigen::VectorXd;\n\n  // Convenience using-declarations\n  using std::cout;\n  using std::endl;\n  using GP::GaussianProcess;\n  using GP::linspace;\n  using GP::sampleNormal;\n  using GP::sampleUnif;\n  using GP::RBF;\n  \n  // Used for timing code with chrono\n  using GP::high_resolution_clock;\n  using GP::time;\n  using GP::getTime;\n  \n  // Set random seed based on system clock\n  std::srand(static_cast<unsigned int>(high_resolution_clock::now().time_since_epoch().count()));\n\n  // Fix random seed for debugging and testing\n  //std::srand(static_cast<unsigned int>(0));\n\n\n  //\n  //   [ Define Training Data ]\n  //\n\n  // Specify the input dimensions\n  //int inputDim = 1;\n  int inputDim = 2;\n  \n  // Specify observation data count\n  int obsCount;\n    if ( inputDim == 1 )\n      obsCount = 250;\n    else\n      obsCount = 1000;\n  \n  // Specify observation noise level\n  auto noiseLevel = 1.0;\n\n  // Define random noise to add to target observations\n  auto noise = sampleNormal(obsCount) * noiseLevel;\n\n  // Define observations by sampling random uniform distribution\n  Matrix X = sampleUnif(-1.0, 1.0, obsCount, inputDim);\n  Matrix y;  y.resize(obsCount, 1);\n  \n  // Define target observations 'y' by applying 'targetFunc'\n  // to the input observations 'X' and adding a noise vector\n  for ( auto i : boost::irange(0,obsCount) )\n    y(i) = targetFunc(X.row(i)) + noise(i);\n\n\n  \n  //\n  //   [ Construct Gaussian Process Model ]\n  //\n\n  // Initialize Gaussian process model\n  GaussianProcess model;\n  \n  // Specify training observations for GP model\n  model.setObs(X,y);\n\n  // Fix noise level [ noise level is fit to the training data by default ]\n  //model.setNoise(0.33);\n  \n  // Initialize a RBF covariance kernel and assign it to the model\n  RBF kernel;\n  model.setKernel(kernel);\n\n  // Specify hyperparameter bounds  [ including noise bounds (index 0) ]\n  // Vector lbs(2); lbs << 0.0001 , 0.01;\n  // Vector ubs(2); ubs << 5.0    , 100.0;\n  // model.setBounds(lbs, ubs);\n\n  // Specify hyperparameter bounds  [ excluding noise bounds ]\n  Vector lbs(1);  lbs <<  0.01;\n  Vector ubs(1);  ubs <<  100.0;\n  model.setBounds(lbs, ubs);\n  \n\n  // Fit covariance kernel hyperparameters to the training data\n  time start = high_resolution_clock::now();\n  model.fitModel();  \n  time end = high_resolution_clock::now();\n  auto computationTime = getTime(start, end);\n\n  // Display computation time required for fitting the GP model\n  cout << \"\\nComputation Time: \";\n  cout << computationTime << \" s\" << endl;\n\n  // Retrieve the tuned/optimized kernel hyperparameters\n  auto optParams = model.getParams();\n  cout << \"\\nOptimized Hyperparameters:\" << endl << optParams.transpose() << \"  \";\n  auto noiseL = model.getNoise();\n  cout << \"(Noise = \" << noiseL << \")\\n\" << endl;\n\n  // Display the negative log marginal likelihood (NLML) of the optimized model\n  cout << \"NLML:  \" << std::fixed << std::setprecision(4) << model.computeNLML() << endl << endl;\n\n\n  //double eps = std::numeric_limits<double>::min();\n  //cout << \"Epsilon: \" << eps << endl;\n  \n  //\n  //   [ Posterior Predictions and Samples ]\n  //\n\n  // Define test mesh for GP model predictions\n  int predCount;\n  if ( inputDim == 1 )\n    predCount = 100;\n  else\n    predCount = 1000;\n  //int predRes = static_cast<int>(std::sqrt(predCount));\n  int predRes = static_cast<int>(std::pow(predCount,1.0/inputDim));\n  //auto testMesh = linspace(0.0, 1.0, predCount);\n  auto testMesh = linspace(-1.0, 1.0, predRes, inputDim);\n  model.setPred(testMesh);\n\n  // Reset predCount to account for rounding\n  predCount = std::pow(predRes,inputDim);\n\n  // Compute predicted means and variances for the test points\n  model.predict();\n  Matrix pmean = model.getPredMean();\n  Matrix pvar = model.getPredVar();\n  Matrix pstd = pvar.array().sqrt().matrix();\n\n  // Get sample paths from the posterior distribution of the model\n  int sampleCount;\n  Matrix samples;\n  if ( inputDim == 1 )\n    {\n      sampleCount = 25;\n      samples = model.getSamples(sampleCount);\n    }\n\n  \n  //\n  //   [ Save Results for Plotting ]\n  //\n  \n  // Save true and predicted means/variances to file\n  std::string outputFile = \"predictions.csv\";\n  //Matrix trueSoln = testMesh.unaryExpr(std::ptr_fun(targetFunc));\n\n  Matrix trueSoln(predCount,1);\n  for ( auto i : boost::irange(0,predCount) )\n    trueSoln(i,0) = targetFunc(testMesh.row(i));\n\n  std::ofstream fout;\n  fout.open(outputFile);\n  for ( auto i : boost::irange(0,predCount) )\n    {\n      for ( auto j : boost::irange(0,inputDim) )\n        fout << testMesh(i,j) << \",\";\n      \n      fout << trueSoln(i) << \",\" << pmean(i) << \",\" << pstd(i) << \"\\n\";\n    }\n  fout.close();\n\n  // Save observations to file\n  std::string outputObsFile = \"observations.csv\";\n  fout.open(outputObsFile);\n  for ( auto i : boost::irange(0,obsCount) )\n    {\n      for ( auto j : boost::irange(0,inputDim) )\n        fout << X(i,j) << \",\";\n      \n      fout << y(i) << \"\\n\";\n    }\n  fout.close();\n\n\n  if ( inputDim == 1 )\n    {\n      // Save samples to file\n      std::string outputSampleFile = \"samples.csv\";\n      fout.open(outputSampleFile);\n      for ( auto j : boost::irange(0,sampleCount) )\n        {\n          for ( auto i : boost::irange(0,predCount) )\n            fout << samples(i,j) << ((i<predCount-1) ? \",\" : \"\\n\");\n        }\n      fout.close();\n    }\n\n  \n  return 0;\n  \n}\n", "meta": {"hexsha": "9ef84cbf3f1a51f636e86f9bca53afc18b1c9254", "size": 6964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/TEST_CODE/Modified_L_BFGS/main.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/TEST_CODE/Modified_L_BFGS/main.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/TEST_CODE/Modified_L_BFGS/main.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 28.3089430894, "max_line_length": 109, "alphanum_fraction": 0.6430212522, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.6697188161577584}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\nvoid setZeroMean(mat& A)\n\n{\n    int n_rows;\n    int D;\n    n_rows=A.n_rows;\n    cout<<\"number row:\"<<n_rows<<endl;\n    D=A.n_cols;\n    cout<<\"number col:\"<<D<<endl;\n    mat Mean=mean(A); // should be 1 row D coln;\n    cout<<\"Mean =\"<<Mean<<endl;\n// subtract the mean - use score_out as temporary matrix\n    A =A-repmat(mean(A), n_rows, 1);\n    return ;\n}\nint main(int argc, char** argv)\n{\n    mat A = randu<mat>(4,5); //random matrix 4 rows 5 cols\n    setZeroMean(A);\n    mat Mean=mean(A);\n    cout<<\" centered data new Mean =\"<<Mean<<endl;\n\n    mat B = randu<mat>(4,5);\n\n//    cout << A*B.t() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "95d45a9c3bb8c81ddf509f8fc6974c5b35c34d3b", "size": 705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armadilloexample.cpp", "max_stars_repo_name": "lyase/barnes-hut-sne", "max_stars_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armadilloexample.cpp", "max_issues_repo_name": "lyase/barnes-hut-sne", "max_issues_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armadilloexample.cpp", "max_forks_repo_name": "lyase/barnes-hut-sne", "max_forks_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7352941176, "max_line_length": 58, "alphanum_fraction": 0.5957446809, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129513, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6695991332098471}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::scalar::gaussian.hpp                                              //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. 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_STATISTICS_DETAIL_KERNEL_KERNELS_SCALAR_GAUSSIAN_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_KERNEL_KERNELS_SCALAR_GAUSSIAN_HPP_ER_2009\n#include <cmath>\n#include <boost/statistics/detail/kernel/kernels/scalar/crtp.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace kernel{\nnamespace scalar{\n\ntemplate<typename T>\nstruct gaussian_kernel : scalar::crtp<gaussian_kernel<T>,T >{ \n    typedef gaussian_kernel<T> this_type;\n    typedef scalar::crtp<this_type,T> crtp_;\n    public:\n    typedef typename crtp_::result_type result_type;\n    \n    gaussian_kernel();\n    gaussian_kernel(const result_type& bandwidth);\n    \n    static result_type core_profile(const result_type& x);\n    static result_type core_nc;\n};\n\ntemplate<typename T> gaussian_kernel<T>::gaussian_kernel():crtp_(){}\ntemplate<typename T> gaussian_kernel<T>::gaussian_kernel(\n    const result_type& bandwidth\n)\n:crtp_(bandwidth){}\n    \ntemplate<typename T>\ntypename gaussian_kernel<T>::result_type\ngaussian_kernel<T>::core_profile(const result_type& x){\n    static result_type two = static_cast<T>(2);\n    return exp(- x * x / two);\n}\n    \ntemplate<typename T>\ntypename gaussian_kernel<T>::result_type\ngaussian_kernel<T>::core_nc = math::constants::root_two_pi<T>();\n\n}// scalar\n}// kernel\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "e964ddd269b539fe1c8f1a9d85fdda22ccaefc60", "size": 1934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "kernel/boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "kernel/boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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.9298245614, "max_line_length": 80, "alphanum_fraction": 0.6282316443, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.669599132163265}}
{"text": "//\n// diff.cpp\n//\n// Copyright (c) 2021 Izadori\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#include <Eigen/Eigen>\n\ntemplate <typename Derived>\nconst Eigen::MatrixXd Diff(const Eigen::MatrixBase<Derived> & m, const unsigned int n = 1)\n{\n    Eigen::MatrixXd mr = m;\n\n    for(unsigned int i = 0; i < n; i++)\n    {\n        mr = (mr.topRows(mr.rows() - 1) - mr.bottomRows(mr.rows() - 1)).eval();\n    }\n\n    return mr;\n}\n\ntemplate <typename Derived>\nconst Eigen::SparseMatrix<double> Diff(const Eigen::SparseMatrixBase<Derived> & m, const unsigned int n = 1)\n{\n    Eigen::SparseMatrix<double> mr = m;\n\n    for(unsigned int i = 0; i < n; i++)\n    {\n        mr = (mr.topRows(mr.rows() - 1) - mr.bottomRows(mr.rows() - 1)).eval();\n    }\n\n    return mr;\n}\n", "meta": {"hexsha": "8d0d77fc47a7cd6dcaf019814154dc72d2139044", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "diff.cpp", "max_stars_repo_name": "Izadori/cpp_eigen", "max_stars_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-25T08:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T08:30:07.000Z", "max_issues_repo_path": "diff.cpp", "max_issues_repo_name": "Izadori/cpp_eigen", "max_issues_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diff.cpp", "max_forks_repo_name": "Izadori/cpp_eigen", "max_forks_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_forks_repo_licenses": ["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.9459459459, "max_line_length": 108, "alphanum_fraction": 0.6145320197, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6695591639092547}}
{"text": "/**************************************\n * Class Name: PRNG, PrimeGen\n * Function: \u4f2a\u968f\u673a\u6570\u4e0e\u4f2a\u968f\u673a\u7d20\u6570\u6bd4\u7279\u751f\u6210\u5668\n * Introduction: PrimeGen \u7ee7\u627f\u4e8e PRNG \u7c7b\n * ***********************************/\n\n#include \"Random.h\"\n#include \"TDES.h\"\n#include <iostream>\n#include <ctime>\n#include <cstring>\n#include <NTL/ZZ.h>\n \nusing namespace std;\nusing namespace NTL;\n\ntypedef unsigned long long size_ul;\n\n/*---------------------------------\n * Class: PRNG\n *-------------------------------*/\n\n// \u6784\u9020\u51fd\u6570\uff0c\u8fdb\u884c\u521d\u59cb\u5316\u64cd\u4f5c\nPRNG::PRNG(int n) {\n    m = n;\n    x = new bitset<64>[m];\n    s = \"\";\n}\n\n// \u6790\u6784\u51fd\u6570\uff0c\u91ca\u653e\u5185\u5b58\u7a7a\u95f4\nPRNG::~PRNG() {\n    delete [] x;\n}\n\n// \u901a\u8fc7\u5916\u754c\u4fee\u6539 m \u7684\u6570\u503c\nvoid PRNG::SetM(int n) {\n    m = n;\n    delete [] x;\n    x = new bitset<64>[m];\n}\n\n// \u4f2a\u968f\u673a\u6570\u6bd4\u7279\u751f\u6210\u51fd\u6570\nZZ PRNG::GenerateRandom() {\n    // \u83b7\u53d6\u672c\u5730\u65f6\u95f4\u65e5\u671f\n    time_t now = time(0);\n    bitset<64> Date(now);\n\n    // \u4ea7\u751f 64 \u6bd4\u7279\u968f\u673a\u79cd\u5b50 s\n    size_ul ss = size_ul(random()) << 32 + random();\n    bitset<64> s(ss);\n\n    TDES td;\n    td.plain = Date;\n    bitset<64> Im = td.TDESEncrypt();\n    for (int i = 0; i < m; i++) {\n        td.plain = Im ^ s;\n        x[i] = td.TDESEncrypt();\n        td.plain = x[i] ^ Im;\n        s = td.TDESEncrypt();\n    }\n\n    // \u751f\u6210\u5b57\u7b26\u4e32\u7c7b\u578b\u4fdd\u5b58\n    bitsToString();\n    ZZ res = bitsToNumber();\n    return res;\n}\n\n// \u5c06\u6bd4\u7279\u6570\u8f6c\u5316\u4e3a ZZ \u578b\u6570\u5b57\nZZ PRNG::bitsToNumber() {\n    ZZ res(0);\n    for (int i = 0; i < m; i++) {\n        string str = x[i].to_string();\n        for (int j = 0; j < 64; j++) {\n            res = res * 2;\n            if (str[j] == '1') {\n                res = res + 1;\n            }\n        }\n    }\n    return res;\n}\n\n// \u6bd4\u7279\u4f4d\u8f6c\u4e3a\u5b57\u7b26\u4e32\u7c7b\u578b\uff0801\u5b57\u7b26\u4e32\uff09\nvoid PRNG::bitsToString() {\n    s = \"\";\n    for (int i = 0; i < m; i++) {\n        s += x[i].to_string();\n    }\n}\n\n// \u4ee5\u5341\u516d\u8fdb\u5236\u6253\u5370\u6bd4\u7279\u6570\u503c\nvoid PRNG::PrintInDER() {\n    cout << \"modulus:\";\n    string pairstr = \"\";\n    for (size_t i = 0; i < s.length(); i += 4) {\n        int index = 0;\n        \n        for (size_t j = i; j < i + 4; j++) {\n            index = index << 1;\n            if (s[j] == '1') {\n                index += 1;\n            }\n        }\n        pairstr += DERTable[index];\n        if (pairstr.length() == 2) {\n            cout << pairstr;\n            if (i + 4 < s.length()) {\n                cout << \":\";\n            }\n            pairstr = \"\";\n        }\n        if (i % 120 == 0) {\n            cout << endl << '\\t';\n        }\n    }\n    cout << endl;\n}\n\n\n/*---------------------------------\n * Class: PrimeGen\n *-------------------------------*/\n\nPrimeGen::PrimeGen(int n) : PRNG(n) {\n    cout << \"Create a pseudorandom number generator.\\n\";\n}\n\n// \u751f\u6210\u968f\u673a\u7d20\u6570\uff0c\u4f7f\u7528 NTL \u4e2d\u5e93\u51fd\u6570\u68c0\u9a8c\n// \u7d20\u6027\u68c0\u6d4b\u7b97\u6cd5\u4e3a Miller-Rabin \u68c0\u6d4b\nZZ PrimeGen::GeneratePrime() {\n    ZZ res(0);\n    // \u6b64\u5904\u8fdb\u884c srandom\uff0c\u4e3a\u4ea7\u751f 64 \u6bd4\u7279\u968f\u673a\u79cd\u5b50\n    srandom((unsigned)time(NULL));\n    do {\n        res = GenerateRandom();\n    } while(!ProbPrime(res, m * 32));\n\n    return res;\n}", "meta": {"hexsha": "c2c59e3de767f1acef373193b01c88b784d71a01", "size": 2776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Random.cpp", "max_stars_repo_name": "yuanyangwangTJ/RSA", "max_stars_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Random.cpp", "max_issues_repo_name": "yuanyangwangTJ/RSA", "max_issues_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random.cpp", "max_forks_repo_name": "yuanyangwangTJ/RSA", "max_forks_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_forks_repo_licenses": ["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.9712230216, "max_line_length": 56, "alphanum_fraction": 0.4398414986, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6695591581885}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <shz/math/matrix.hpp>\n \n\nBOOST_AUTO_TEST_CASE(matrixConstructors)\n{\n\t\n\tauto m = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\t\n\tBOOST_CHECK(true == m.is_identity());\n\tBOOST_CHECK(true == n.is_identity());\n\t\n\tBOOST_CHECK(1.f == m.data[0]);\n\tBOOST_CHECK(0.f == m.data[1]);\n\tBOOST_CHECK(0.f == m.data[2]);\n\tBOOST_CHECK(1.f == m.data[3]);\n}\n\nBOOST_AUTO_TEST_CASE(matrixSizeConstructors)\n{\n\tauto m = shz::math::matrix<shz::math::f64, 20, 30>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 20, 30>::identity();\n\n\n\tBOOST_CHECK(true == m.is_identity());\n\tBOOST_CHECK(true == n.is_identity());\n\n\tBOOST_CHECK(20*30 == m.size);\n\tBOOST_CHECK(20 == m.mindimension);\n\tBOOST_CHECK(20 == m.columns);\n\tBOOST_CHECK(30 == m.rows);\n}\n\nBOOST_AUTO_TEST_CASE(matrixAdds)\n{\n\tauto m = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\n\tauto j = m+n;\n\tBOOST_CHECK(true != j.is_identity());\n\tBOOST_CHECK(2*2 == j.size);\n\tBOOST_CHECK(2.f == j.data[0]);\n\tBOOST_CHECK(0.f == j.data[1]);\n\tBOOST_CHECK(0.f == j.data[2]);\n\tBOOST_CHECK(2.f == j.data[3]);\n\n\tm += n;\n\tBOOST_CHECK(2.f == m.data[0]);\n\tBOOST_CHECK(0.f == m.data[1]);\n\tBOOST_CHECK(0.f == m.data[2]);\n\tBOOST_CHECK(2.f == m.data[3]);\n\n\tn += 2.f;\n\tBOOST_CHECK(3.f == n.data[0]);\n\tBOOST_CHECK(2.f == n.data[1]);\n\tBOOST_CHECK(2.f == n.data[2]);\n\tBOOST_CHECK(3.f == n.data[3]);\n}\n\nBOOST_AUTO_TEST_CASE(matrixSubs)\n{\n\tauto m = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\n\tauto j = m-n;\n\tBOOST_CHECK(true != j.is_identity());\n\tBOOST_CHECK(2*2 == j.size);\n\tBOOST_CHECK(0.f == j.data[0]);\n\tBOOST_CHECK(0.f == j.data[1]);\n\tBOOST_CHECK(0.f == j.data[2]);\n\tBOOST_CHECK(0.f == j.data[3]);\n\n\tm -= n;\n\tBOOST_CHECK(0.f == m.data[0]);\n\tBOOST_CHECK(0.f == m.data[1]);\n\tBOOST_CHECK(0.f == m.data[2]);\n\tBOOST_CHECK(0.f == m.data[3]);\n\n\tn -= 2.f;\n\tBOOST_CHECK(-1.f == n.data[0]);\n\tBOOST_CHECK(-2.f == n.data[1]);\n\tBOOST_CHECK(-2.f == n.data[2]);\n\tBOOST_CHECK(-1.f == n.data[3]);\n}\n\n\nBOOST_AUTO_TEST_CASE(matrixMuls)\n{\n\tauto m = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 2, 2>::identity();\n\n\tauto j = m*n;\n\tBOOST_CHECK(true == j.is_identity());\n\tBOOST_CHECK(2*2 == j.size);\n\tBOOST_CHECK(1.f == j.data[0]);\n\tBOOST_CHECK(0.f == j.data[1]);\n\tBOOST_CHECK(0.f == j.data[2]);\n\tBOOST_CHECK(1.f == j.data[3]);\n\n\tauto v = shz::math::vector<shz::math::f64, 2>();\n\tv.data[0] = 2.f;\n\tv.data[1] = 2.f;\n\tauto b = m*v;\n\tBOOST_CHECK(2.f == b.data[0]);\n\tBOOST_CHECK(2.f == b.data[1]);\n\n\tm = n*2;\n\tBOOST_CHECK(true != m.is_identity());\n\tb = m*v;\n\tBOOST_CHECK(4.f == b.data[0]);\n\tBOOST_CHECK(4.f == b.data[1]);\n\n\tm *= n;\n\tBOOST_CHECK(true != m.is_identity());\n\tBOOST_CHECK(2.f == m.data[0]);\n\tBOOST_CHECK(0.f == m.data[1]);\n\tBOOST_CHECK(0.f == m.data[2]);\n\tBOOST_CHECK(2.f == m.data[3]);\n\n\tm *= 2;\n\tBOOST_CHECK(true != m.is_identity());\n\tBOOST_CHECK(4.f == m.data[0]);\n\tBOOST_CHECK(0.f == m.data[1]);\n\tBOOST_CHECK(0.f == m.data[2]);\n\tBOOST_CHECK(4.f == m.data[3]);\n\n}\n\n\n\n\n/*\nBOOST_AUTO_TEST_CASE(matrixPerformance)\n{\n\tauto m = shz::math::matrix<shz::math::f64, 200, 200>::identity();\n\tauto n = shz::math::matrix<shz::math::f64, 200, 200>::identity();\n\n\tfor(size_t i=0; i<10000; i++)\n\t\tauto r = m*n;\n}*/\n", "meta": {"hexsha": "e77cd66df49b75943c931309dc7c36ee24faf35b", "size": 3409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Math/matrix_tests.cpp", "max_stars_repo_name": "TraxNet/ShadingZenCpp", "max_stars_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-30T15:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:47:18.000Z", "max_issues_repo_path": "tests/Math/matrix_tests.cpp", "max_issues_repo_name": "TraxNet/ShadingZenCpp", "max_issues_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Math/matrix_tests.cpp", "max_forks_repo_name": "TraxNet/ShadingZenCpp", "max_forks_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_forks_repo_licenses": ["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.0070422535, "max_line_length": 66, "alphanum_fraction": 0.6127896744, "num_tokens": 1149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7520125737597971, "lm_q1q2_score": 0.6695124523895141}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nint main() {\n  Eigen::Matrix2d mat;\n  mat << 1, 2,\n      3, 4;\n  cout << \"Here is mat.sum():       \" << mat.sum() << endl;\n  cout << \"Here is mat.prod():      \" << mat.prod() << endl;\n  cout << \"Here is mat.mean():      \" << mat.mean() << endl;\n  cout << \"Here is mat.minCoeff():  \" << mat.minCoeff() << endl;\n  cout << \"Here is mat.maxCoeff():  \" << mat.maxCoeff() << endl;\n  cout << \"Here is mat.trace():     \" << mat.trace() << endl;\n}\n", "meta": {"hexsha": "c04f3fc37aaf53e8f1d6ad089ba6d1f2a011bdc3", "size": 504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/tut_arithmetic_redux_basic.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_redux_basic.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_redux_basic.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": 31.5, "max_line_length": 64, "alphanum_fraction": 0.5218253968, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6695124474414146}}
{"text": "/****************************************\n * Creator : L\u00e9o Gaspard                *\n * Mail    : leo.gaspard@outlook.fr     *\n * Git     : https://github.com/NehZio  *\n *                                      *\n * Date    : 26/08/2019                 *\n *                                      *\n * File    : main.cpp                   *\n ****************************************/\n\n\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <Eigen/Dense>\n#include <eigen3/unsupported/Eigen/MatrixFunctions>\n\nint main()\n{\n\tint norb(3);\n\tint nvec(3);\n\n\n\tEigen::MatrixXcd c(nvec,nvec);\n\tEigen::MatrixXcd d(norb,nvec);\n\tEigen::MatrixXcd p(nvec,nvec);\n\tEigen::MatrixXcd s(nvec,nvec);\n\tEigen::MatrixXcd invSqrtS(nvec,nvec);\n\tEigen::MatrixXcd pON(nvec,nvec);\n\tEigen::MatrixXcd heff(nvec,nvec);\n\tEigen::MatrixXd e(nvec,nvec);\n\n\n\tEigen::FullPivLU<Eigen::MatrixXcd> lu;\n\tEigen::ComplexEigenSolver<Eigen::MatrixXcd> eig;\n\n\tstd::cout << std::fixed << std::setprecision(6);\n\tstd::cout << std::endl << \"This program will perform Heff calculations using the method described in : \\n Chem. Rev. 2014, 114, 1, 429-492\" << std::endl;\n\n\n//*************************************************\n/*\n * Manual initialization of c\n */\n\n\tc(0,1) = {-0.4867551E+00,0.0000E-10};\n\tc(0,0) = {-0.2653160E+00,0.0000E-10};\n\tc(0,2) = { 0.7520712E+00,0.0000E-10};\n\n\tc(1,1) = { 0.6126111E+00,0.0000E-10};\n\tc(1,0) = {-0.7456646E+00,0.0000E-10};\n\tc(1,2) = { 0.1330535E+00,0.0000E-10};\n\n\tc(2,1) = {-0.5748099E+00,0.0000E-10};\n\tc(2,0) = {-0.5748095E+00,0.0000E-10};\n\tc(2,2) = {-0.5748079E+00,0.0000E-10};\n\n/*\n * Manual initializaion of e\n */\n\te(0,0) =-715.10E+00;\n\te(1,1) =-231.20E+00;\n\te(2,2) =   0.00E+00;\n//*************************************************\n\n\n\t\t\n\n\tstd::cout << std::endl << \"c Matrix : \" << std::endl << c << std::endl;\n\tstd::cout << std::endl << \"e Matrix :  \" <<  std::endl << e << std::endl << std::endl; \n\n\n\t/***********************\n\t * Calculation of the  *\n\t * projection operator *\n\t ***********************/\n\n\tstd::cout << std::endl << \"Projection matrix P = |I>*<I| :  \" << std::endl;\n        d = Eigen::MatrixXcd::Identity(norb,nvec);\n\tstd::cout << std::endl << d << std::endl;\n\n\t/**********************\n\t * Calculation of the *\n\t * projected vectors  *\n\t **********************/\n\n\tstd::cout << std::endl << \"Projected vectors into the model space :\" << std::endl;\n\tp = c*d;\n\tstd::cout << std::endl << p << std::endl;\n\n\t/***********************\n\t * Calculation of the  *\n\t * overlap matrix      *\n\t ***********************/\n\n\tstd::cout << std::endl << \"Overlap Matrix S = c*c^T: \" << std::endl;\n\ts = p*p.transpose();\n\tstd::cout << std::endl << s << std::endl;\n\n\t/***********************\n\t * Calculation of the  *\n\t * S^(-1/2) matrix     *\n\t ***********************/\n\n\n\tlu.compute(s.sqrt());\n\n\tif(lu.isInvertible())\n\t{\n\t\tinvSqrtS =  lu.inverse();\n\t}\n\telse\n\t{\n\t\tstd::cout << std::endl << \"Error : The square root of the overlap matrix is not invertible\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::cout << std::endl << \"S^(-1/2) Matrix : \" << std::endl;\n\n\tstd::cout << std::endl << invSqrtS << std::endl;\n\n\t/***********************\n\t * Calculation of the  *\n\t * otrhonormalized     *\n\t * projected vectors   *\n\t ***********************/\n\n\tpON =  invSqrtS*p;\n\tstd::cout << std::endl << \"Orthonormalized projected vectors : \" << std::endl;\n\tstd::cout << std::endl << pON << std::endl;\n\n\t/***********************\n\t * Calculation of the  *\n\t * effective           *\n\t * Hamiltonian         *\n\t ***********************/\n\n\theff = pON.transpose()*e*pON.conjugate();\n\n\tstd::cout << std::endl << \"Effective Hamiltonian |S,Ms> basis : \" << std::endl;\n\tstd::cout << std::endl << heff << std::endl;\n\n\t/***********************\n\t * Diagonalization of  *\n\t * the effective       *\n\t * Hamiltonian         *\n\t ***********************/\n\n\teig.compute(heff);\n\n\tstd::cout << std::endl << \"Eigenvalues of the effective Hamiltonian :\" << std::endl;\n\tstd::cout << std::endl << eig.eigenvalues() << std::endl;\n\n\tstd::cout << std::endl << \"Eigenvectors of the effective Hamiltonian :\" << std::endl;\n\tstd::cout << std::endl << eig.eigenvectors() << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "baf9ce6160669b73fa0120cfacc01232a9aa1acf", "size": 4129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "NehZio/Heff", "max_stars_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_stars_repo_licenses": ["MIT"], "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": "NehZio/Heff", "max_issues_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_issues_repo_licenses": ["MIT"], "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": "NehZio/Heff", "max_forks_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_forks_repo_licenses": ["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.1329113924, "max_line_length": 154, "alphanum_fraction": 0.4945507387, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6694771914979003}}
{"text": "#include <chrono>\n#include <iostream>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <cmath>\n\nusing Eigen::Vector3d;\nusing std::runtime_error;\n\nnamespace lambert {\n    struct LambertResults {\n        Vector3d v0;\n        Vector3d v;\n    };\n\n    double c2(double psi) {\n        double res;\n        auto eps = 1.0;\n        if (psi > eps) {\n            res = (1 - cos(sqrt(psi))) / psi;\n        } else if (psi < -eps) {\n            res = (cosh(sqrt(-psi)) - 1) / (-psi);\n        } else {\n            res = 1.0 / 2.0;\n            auto delta = (-psi) / tgamma(2 + 2 + 1);\n            auto k = 1;\n            while (res + delta != res) {\n                res += delta;\n                k += 1;\n                delta = pow(-psi, k) / tgamma(2*k + 2 + 1);\n            }\n        }\n        return res;\n    }\n\n    double c3(double psi) {\n        double res;\n        auto eps = 1.0;\n        if (psi > eps) {\n            res = (sqrt(psi) - sin(sqrt(psi))) / (psi * sqrt(psi));\n        } else if (psi < -eps) {\n            res = (sinh(sqrt(-psi)) - sqrt(-psi)) / (-psi * sqrt(-psi));\n        } else {\n            res = 1.0 / 6.0;\n            auto delta = (-psi) / tgamma(2 + 3 + 1);\n            int k = 1;\n            while (res + delta != res) {\n                res += delta;\n                k += 1;\n                delta = pow(-psi, k) / tgamma(2*k + 3 + 1);\n            }\n        }\n        return res;\n    }\n\n    LambertResults lambert(double k, Vector3d r0, Vector3d r, double tof,\n            bool shortway=true, int numiter=35, double rtol=1e-8) {\n        int t_m;\n        if (shortway) {\n            t_m = 1;\n        } else {\n            t_m = -1;\n        }\n        auto norm_r0 = r0.norm();\n        auto norm_r = r.norm();\n        auto cos_dnu = r0.dot(r) / (norm_r * norm_r0);\n\n        auto A = t_m * sqrt(norm_r * norm_r0 * (1 + cos_dnu));\n\n        if (A == 0.0) {\n            throw runtime_error(\"Cannot compute orbit, phase angle is 180 degrees\");\n        }\n\n        auto psi = 0.0;\n        auto psi_low = -4*M_PI;\n        auto psi_up = 4*M_PI;\n\n        auto count = 0;\n        double y;\n        while (count < numiter) {\n            y = norm_r0 + norm_r + A * (psi * c3(psi) - 1) / sqrt(c2(psi));\n            if (A > 0.0 & y < 0.0) {\n                while (y < 0.0) {\n                    psi_low = psi;\n                    psi = (0.8 * (1.0 / c3(psi)) *\n                            (1.0 - (norm_r0 + norm_r) * sqrt(c2(psi)) / A));\n                    y = norm_r0 + norm_r + A * (psi * c3(psi) - 1) / sqrt(c2(psi));\n                }\n            }\n            auto xi = sqrt(y / c2(psi));\n            auto tof_new = (pow(xi, 3) * c3(psi) + A * sqrt(y)) / sqrt(k);\n\n            if (fabs((tof_new - tof) / tof) < rtol) {\n                break;\n            } else {\n                count += 1;\n                if (tof_new <= tof) {\n                    psi_low = psi;\n                } else {\n                    psi_up = psi;\n                }\n                psi = (psi_up + psi_low) / 2;\n            }\n        }\n        if (count > numiter) {\n            throw runtime_error(\"Maximum number of iterations reached\");\n        }\n        auto f = 1 - y / norm_r0;\n        auto g = A * sqrt(y / k);\n        auto gdot = 1 - y / norm_r;\n        auto v0 = (r - f * r0) / g;\n        auto v = (gdot * r - r0) / g;\n        LambertResults results = {v, v0};\n        return results;\n    }\n\n    void benchmark(int times) {\n        auto mu = 3.986004418e5;\n        Vector3d r0(5000.0, 10000.0, 2100.0);\n        Vector3d r(-14600.0, 2500.0, 7000.0);\n        auto tof = 3600.0;\n\n        auto best = std::numeric_limits<double>::infinity();\n        auto worst = -std::numeric_limits<double>::infinity();\n        double all = 0;\n        for (auto i=0; i < times; i++) {\n            auto begin = std::chrono::high_resolution_clock::now();\n\n            lambert(mu, r0, r, tof);\n\n            auto end = std::chrono::high_resolution_clock::now();\n            auto current = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count()/1e9;\n            all += current;\n            if (current < best) {\n                best = current;\n            }\n            if (current > worst) {\n                worst = current;\n            }\n        }\n        std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "c12ab7a9d981cbf430b4c1d9a17b0c9927c5f217", "size": 4327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/lambert.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/lambert.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/lambert.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 30.0486111111, "max_line_length": 103, "alphanum_fraction": 0.4201525306, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6694771796573123}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n\nusing namespace Eigen;\nusing namespace std;\nMatrixXf computeLinkPos(MatrixXf L, MatrixXf P, Matrix3f R, MatrixXf s, MatrixXf pb);\nMatrixXf computeActuation(MatrixXf L, float lc);\n\nMatrixXf computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n// float* computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n  // void computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n  // - \u30b9\u30e9\u30a4\u30c0\u30fc\u9593\u8ddd\u96e2D[mm]        : 56+(12/2)*2=68mm\n  // - \u30ed\u30c3\u30c9\u9577\u3055lc[mm]                  : 262+(8/2)*2=268mm\n  // - \u30b9\u30e9\u30a4\u30c0\u30fc\u8a2d\u7f6e\u534a\u5f84rb[mm]    : sqrt(269.7^2-200.5^2)=180.38248\n  // - \u30c6\u30fc\u30d6\u30eb\u534a\u5f84re[mm]               :90mm\n  // - \u30c6\u30fc\u30d6\u30eb\u521d\u671f\u9ad8\u3055Pz[mm]       :438.17mm\n  // float re = 90;\n  // float Pz = 438.17;\n  // float D = 68;\n  // float lc = 268;\n  // float rb = 180.38;\n\n  float th = asin(D/(2*rb)); //% theta1: angle (linear actuator)\n  float th2 = asin(D/(2*re)); //% theta2: angle (end effector)\n\n  MatrixXf pb(6,3);\n  pb << \n    rb*cos(th),rb*sin(th),0,\n    rb*cos(-th),rb*sin(-th),0,\n    rb*cos(2*M_PI/3+th),rb*sin(2*M_PI/3+th),0,\n    rb*cos(2*M_PI/3-th),rb*sin(2*M_PI/3-th),0,\n    rb*cos(4*M_PI/3+th),rb*sin(4*M_PI/3+th),0,\n    rb*cos(4*M_PI/3-th),rb*sin(4*M_PI/3-th),0;\n\n  MatrixXf s_local(6,3);\n  s_local << \n    re*cos(th2),re*sin(th2),0,\n    re*cos(-th2),re*sin(-th2),0,\n    re*cos(2*M_PI/3+th2),re*sin(2*M_PI/3+th2),0,\n    re*cos(2*M_PI/3-th2),re*sin(2*M_PI/3-th2),0,\n    re*cos(4*M_PI/3+th2),re*sin(4*M_PI/3+th2),0,\n    re*cos(4*M_PI/3-th2),re*sin(4*M_PI/3-th2),0;\n\n  MatrixXf sliders(6,3);\n  sliders <<\n    rb*cos(th),rb*sin(th),Pz,\n    rb*cos(-th),rb*sin(-th),Pz,\n    rb*cos(2*M_PI/3+th),rb*sin(2*M_PI/3+th),Pz,\n    rb*cos(2*M_PI/3-th),rb*sin(2*M_PI/3-th),Pz,\n    rb*cos(4*M_PI/3+th),rb*sin(4*M_PI/3+th),Pz,\n    rb*cos(4*M_PI/3-th),rb*sin(4*M_PI/3-th),Pz;\n\n  // float phi = M_PI/24; //% rotation around X axis\n  // float theta = M_PI/12; //% rotation around Y axis\n  // float psi = M_PI/16; //% rotation around Z axis\n\n  Matrix3f R;\n  R << \n    cos(phi)*cos(theta),cos(phi)*sin(theta)*sin(psi)-sin(phi)*cos(psi),cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi),\n    sin(phi)*cos(theta),sin(phi)*sin(theta)*sin(psi)+cos(phi)*cos(psi),sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi),\n    -sin(theta),cos(theta)*sin(psi),cos(theta)*cos(psi);\n\n  Vector3f a;\n  a << 0,0,1;\n\n  MatrixXf s(6,3);\n  s = s_local*R;//6x3 x 3x3 => 6x3\n\n  MatrixXf P(1,3);\n  P << xd,yd,zd; //% Position Vector of the end effector\n  // P << 50,50,height; //% Position Vector of the end effector\n\n  // cout << \"*** re: \" << endl << s << endl;\n  // cout << \"*** rb: \" << endl << rb << endl;\n  // cout << \"*** pb:  \" << endl << pb << endl;\n  // cout << \"*** R:  \" << endl<< R << endl;\n\n  MatrixXf L(6,3);\n  L << computeLinkPos(L, P, R, s, pb); \n  // cout << \"*** L:  \" << endl << L << endl;\n\n  MatrixXf C(1,6);\n  C << computeActuation(L,lc);\n  cout << \"*** C:  \" << endl << C << endl;\n\n  return C;\n  // float* arrayf = C.data();\n}  \n\n// %% compute position vector of rod end of end effector\nMatrixXf computeLinkPos(MatrixXf L, MatrixXf P, Matrix3f R, MatrixXf s, MatrixXf pb){\n  // L = P + R*s - pb;\n  for(int i=0;i<6;i++){\n    L.block(i,0,1,3) << P + (s.block(i,0,1,3))*R - pb.block(i,0,1,3);\n  }\n  return L;\n}\n\nMatrixXf computeActuation(MatrixXf L, float lc){\n  MatrixXf C(1,6); \n  for (int i=0;i<6;i++){\n    float lxi = L(i,0);\n    float lyi = L(i,1);\n    float lzi = L(i,2);\n    C.block(0,i,1,1) << lzi - sqrt(lc*lc-lxi*lxi-lyi*lyi);\n  }\n  return C;\n}\n\n\nextern \"C\" {\n  void solveInverseMechanism(float* arrayf, float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi){\n    MatrixXf C(1,6);\n    C << computeSliderControl(re,rb,lc,D,Pz,xd,yd,zd,phi,theta,psi);\n    memcpy(arrayf,C.data(),C.size()*sizeof(float));\n  }\n}\n", "meta": {"hexsha": "7db077a830ece347110d1e70effc54720ff5cc33", "size": 4008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_stars_repo_name": "shohei/6axes-nanokontrol", "max_stars_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_issues_repo_name": "shohei/6axes-nanokontrol", "max_issues_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-04T02:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T02:48:17.000Z", "max_forks_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_forks_repo_name": "shohei/6axes-nanokontrol", "max_forks_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_forks_repo_licenses": ["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": 150, "alphanum_fraction": 0.5953093812, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6693181596065171}}
{"text": "#ifndef CANNON_MATH_MULTIVARIATE_NORMAL_H\n#define CANNON_MATH_MULTIVARIATE_NORMAL_H \n\n/*!\n * \\file cannon/math/multivariate_normal.hpp\n * \\brief File containing MultivariateNormal class definition.\n */\n\n#include <random>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace math {\n\n    /*!\n     * \\brief Class representing a multivariate normal distribution of\n     * arbitrary dimensionality.\n     */\n    class MultivariateNormal {\n      public:\n        MultivariateNormal() = delete;\n\n        /*!\n         * \\brief Constructor taking a covariance matrix. The distribution is\n         * assumed to be centered at zero.\n         */\n        MultivariateNormal(const Ref<const MatrixXd>& covar) :\n          MultivariateNormal(VectorXd::Zero(covar.rows()), covar) {}\n\n        /*!\n         * \\brief Constructor taking a mean and covariance matrix.\n         */\n        MultivariateNormal(const Ref<const VectorXd> &mean, const Ref<const MatrixXd> &covar)\n            : mean_(mean),\n              transform_(MatrixXd::Zero(mean.size(), mean.size())) {\n          SelfAdjointEigenSolver<MatrixXd> eigen_solver(covar);\n          transform_ = eigen_solver.eigenvectors() *\n            eigen_solver.eigenvalues().cwiseSqrt().asDiagonal();\n        }\n\n        /*!\n         * \\brief Sample a point from this distribution.\n         *\n         * \\returns A sample from the multivariate normal distribution\n         * represented by this object.\n         */\n        VectorXd sample() const {\n          return mean_ + (transform_ * VectorXd::NullaryExpr(mean_.size(),\n                [&](){return dist(gen);}));\n        }\n\n        /*!\n         * \\brief Set the seed for all normal distributions.\n         *\n         * \\param seed The new seed to use.\n         */ \n        static void set_seed(int seed);\n\n        static std::random_device rd; //!< Physical random number generator.\n        static std::mt19937 gen; //!< Pseudo-random number generator.\n        static std::normal_distribution<double> dist; //!< 1D normal distribution for sampling\n\n      private:\n        VectorXd mean_; //!< Mean of this normal distribution\n        MatrixXd transform_; //!< Transform used to compute multivariate samples\n\n    };\n\n  }\n}\n\n#endif /* ifndef CANNON_MATH_MULTIVARIATE_NORMAL_H */\n", "meta": {"hexsha": "35993cb83d8252c6fedb5ecc512e7c1acd310ea0", "size": 2285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/multivariate_normal.hpp", "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": "cannon/math/multivariate_normal.hpp", "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": "cannon/math/multivariate_normal.hpp", "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": 30.0657894737, "max_line_length": 94, "alphanum_fraction": 0.6249452954, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6692449369358631}}
{"text": "#include <Eigen/Dense>\n\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nint main() {\n  Vector3d x = Vector3d::Zero();\n  Vector3d y = Vector3d::Zero();\n\n  x[1] = 1.0;\n  x[2] = 2.0;\n\n  y[0] = 1.0;\n  y[1] = 2.0;\n  y[2] = 3.0;\n\n  log_info(x.array() > 0.0);\n  log_info((x.array() <= y.array()).all());\n  log_info(x.array().max(1));\n\n  Matrix3d A;\n  A << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n\n  Vector3d a = Vector3d::Zero();\n  for (unsigned int i = 0; i < 3; i++) {\n    a[i] = *(A.row(1).data() + i);\n  }\n  log_info(a);\n\n}\n", "meta": {"hexsha": "9cd0c339b0154f15a6145b2f23174ae59c66602f", "size": 564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/test_eigen.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/test_eigen.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/test_eigen.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": 15.6666666667, "max_line_length": 43, "alphanum_fraction": 0.5177304965, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6692449255361569}}
{"text": "#pragma once\n#include \"neumann_boundary.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n//----------------AssembleNeumannBegin----------------\n//! Adds the contribution of the boundary to the stiffness matrix.\n//!\n//! @note This should only be called for the *boundary* edges\n//!\n//! @param[in] edges a list of boundary edges\n//! @param[in] vertices a list of vertices\n//! @param[in] gamma the boundary parameter gamma\nSparseMatrix assembleBoundaryMatrix(\n    const Eigen::MatrixXd &vertices,\n    const Eigen::MatrixXi &edges,\n    double                 gamma) {\n\tSparseMatrix         B(vertices.rows(), vertices.rows());\n\tstd::vector<Triplet> triplets;\n\tconst int            numberOfElements = edges.rows();\n\n\t// (write your solution here)\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto indexSet = edges.row(i);\n\n\t\tconst auto &a = vertices.row(indexSet(0));\n\t\tconst auto &b = vertices.row(indexSet(1));\n\n\t\tEigen::Matrix2d boundaryMatrix;\n\t\tcomputeBoundaryMatrix(boundaryMatrix, a, b, gamma);\n\n\t\tfor (int n = 0; n < 2; ++n) {\n\t\t\tfor (int m = 0; m < 2; ++m) {\n\t\t\t\ttriplets.emplace_back(indexSet(n), indexSet(m), boundaryMatrix(n, m));\n\t\t\t}\n\t\t}\n\t}\n\n\tB.setFromTriplets(triplets.begin(), triplets.end());\n\treturn B;\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "d0323e749288c925d7c9b8a95ba330dce8e7a4a8", "size": 1293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/neumann_boundary_assemble.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series4/2d-rad-cooling/neumann_boundary_assemble.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series4/2d-rad-cooling/neumann_boundary_assemble.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.0697674419, "max_line_length": 74, "alphanum_fraction": 0.6372776489, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6692449199097028}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__INTERNAL__SO3_HPP_\n#define SMOOTH__INTERNAL__SO3_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief SO(3) Lie group represented as S^3\n *\n * Memory layout\n * -------------\n * Group:    qx qy qz qw  (same as Eigen quaternion)\n * Tangent:  \u03a9x \u03a9y \u03a9z\n *\n * Lie group Matrix form\n * ---------------------\n * 3x3 rotation matrix\n *\n * Lie algebra Matrix form\n * -----------------------\n * [  0 -\u03a9z  \u03a9y ]\n * [  \u03a9z  0 -\u03a9x ]\n * [ -\u03a9y \u03a9x   0 ]\n *\n * Constraints\n * -----------\n * Group:   qx * qx + qy * qy + qz * qz + qw * qw = 1\n * Tangent: -pi < \u03a9x, \u03a9y, \u03a9z <= pi\n */\ntemplate<typename _Scalar>\nclass SO3Impl\n{\npublic:\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index RepSize = 4;\n  static constexpr Eigen::Index Dim     = 3;\n  static constexpr Eigen::Index Dof     = 3;\n  static constexpr bool IsCommutative   = false;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out) { g_out << Scalar(0), Scalar(0), Scalar(0), Scalar(1); }\n\n  static void setRandom(GRefOut g_out)\n  {\n    g_out = Eigen::Quaternion<Scalar>::UnitRandom().coeffs();\n    if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    Eigen::Map<const Eigen::Quaternion<Scalar>> q(g_in.data());\n    m_out = q.toRotationMatrix();\n  }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    Eigen::Map<const Eigen::Quaternion<Scalar>> q1(g_in1.data());\n    Eigen::Map<const Eigen::Quaternion<Scalar>> q2(g_in2.data());\n    g_out = (q1 * q2).coeffs();\n    if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    Eigen::Map<const Eigen::Quaternion<Scalar>> q(g_in.data());\n    g_out = q.inverse().coeffs();\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    using std::atan2, std::sqrt;\n    const Scalar xyz2 = g_in[0] * g_in[0] + g_in[1] * g_in[1] + g_in[2] * g_in[2];\n\n    const auto phi = [&]() -> Scalar {\n      if (xyz2 < Scalar(eps2)) {\n        // https://www.wolframalpha.com/input/?i=series+atan%28y%2Fx%29+%2F+y+at+y%3D0\n        return Scalar(2) / g_in[3] - Scalar(2) * xyz2 / (Scalar(3) * g_in[3] * g_in[3] * g_in[3]);\n      } else {\n        const Scalar xyz = sqrt(xyz2);\n        return Scalar(2) * atan2(xyz, g_in[3]) / xyz;\n      }\n    }();\n\n    a_out << g_in[0], g_in[1], g_in[2];\n    a_out *= phi;\n  }\n\n  static void Ad(GRefIn g_in, TMapRefOut A_out)\n  {\n    Eigen::Map<const Eigen::Quaternion<Scalar>> q(g_in.data());\n    A_out = q.toRotationMatrix();\n  }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    using std::sqrt, std::cos, std::sin;\n\n    const Scalar th2 = a_in.squaredNorm();\n\n    const auto [A, B] = [&]() -> std::array<Scalar, 2> {\n      if (th2 < Scalar(eps2)) {\n        return {\n          // https://www.wolframalpha.com/input/?i=series+sin%28x%2F2%29%2Fx+at+x%3D0\n          Scalar(1) / Scalar(2) - th2 / Scalar(48),\n          // https://www.wolframalpha.com/input/?i=series+cos%28x%2F2%29+at+x%3D0\n          Scalar(1) - th2 / Scalar(8),\n        };\n      } else {\n        const Scalar th = sqrt(th2);\n        return {\n          sin(th / Scalar(2)) / th,\n          cos(th / Scalar(2)),\n        };\n      }\n    }();\n\n    g_out << A * a_in.x(), A * a_in.y(), A * a_in.z(), B;\n    if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out << Scalar(0), -a_in(2), a_in(1), a_in(2), Scalar(0), -a_in(0), -a_in(1), a_in(0),\n      Scalar(0);\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    a_out << (A_in(2, 1) - A_in(1, 2)) / Scalar(2), (A_in(0, 2) - A_in(2, 0)) / Scalar(2),\n      (A_in(1, 0) - A_in(0, 1)) / Scalar(2);\n  }\n\n  static void ad(TRefIn a_in, TMapRefOut A_out) { hat(a_in, A_out); }\n\n  static void dr_exp(TRefIn a_in, TMapRefOut A_out)\n  {\n    using std::sqrt, std::sin, std::cos;\n    const Scalar th2 = a_in.squaredNorm();\n\n    const auto [A, B] = [&]() -> std::array<Scalar, 2> {\n      if (th2 < Scalar(eps2)) {\n        return {\n          // https://www.wolframalpha.com/input/?i=series+%281-cos+x%29+%2F+x%5E2+at+x%3D0\n          Scalar(1) / Scalar(2) - th2 / Scalar(24),\n          // https://www.wolframalpha.com/input/?i=series+%28x+-+sin%28x%29%29+%2F+x%5E3+at+x%3D0\n          Scalar(1) / Scalar(6) - th2 / Scalar(120),\n        };\n      } else {\n        const Scalar th = sqrt(th2);\n        return {\n          (Scalar(1) - cos(th)) / th2,\n          (th - sin(th)) / (th2 * th),\n        };\n      }\n    }();\n\n    using TangentMap = Eigen::Matrix<Scalar, Dof, Dof>;\n    TangentMap ad_a;\n    ad(a_in, ad_a);\n    A_out.noalias() = TangentMap::Identity() - A * ad_a + B * ad_a * ad_a;\n  }\n\n  static void dr_expinv(TRefIn a_in, TMapRefOut A_out)\n  {\n    using std::sqrt, std::sin, std::cos;\n    const Scalar th2 = a_in.squaredNorm();\n\n    const auto A = [&]() -> Scalar {\n      if (th2 < Scalar(eps2)) {\n        // https://www.wolframalpha.com/input/?i=series+1%2Fx%5E2-%281%2Bcos+x%29%2F%282*x*sin+x%29+at+x%3D0\n        return Scalar(1) / Scalar(12) + th2 / Scalar(720);\n      } else {\n        const Scalar th = sqrt(th2);\n        return Scalar(1) / th2 - (Scalar(1) + cos(th)) / (Scalar(2) * th * sin(th));\n      }\n    }();\n\n    using TangentMap = Eigen::Matrix<Scalar, Dof, Dof>;\n    TangentMap ad_a;\n    ad(a_in, ad_a);\n    A_out.noalias() = TangentMap::Identity() + ad_a / Scalar(2) + A * ad_a * ad_a;\n  }\n\n  static void d2r_exp(TRefIn a_in, THessRefOut H_out)\n  {\n    const auto [A, B, dA_over_th, dB_over_th] = [&]() -> std::array<Scalar, 4> {\n      using std::sqrt;\n\n      const Scalar th2 = a_in.squaredNorm();\n      const Scalar th  = sqrt(th2);\n\n      if (th2 < Scalar(eps2)) {\n        return {\n          Scalar(0.5) - th2 / 24,\n          Scalar(1. / 6) - th2 / 120,\n          -Scalar(1) / 48,\n          -Scalar(1) / 60,\n        };\n      } else {\n        const Scalar sTh = sin(th);\n        const Scalar cTh = cos(th);\n        const Scalar th3 = th2 * th;\n        const Scalar th4 = th2 * th2;\n        const Scalar th5 = th3 * th2;\n        return {\n          (Scalar(1) - cTh) / th2,\n          (th - sTh) / th3,\n          sTh / th3 + 2 * cTh / th4 - 2 / th4,\n          -cTh / th4 - 2 / th4 + 3 * sTh / th5,\n        };\n      }\n    }();\n\n    // -A * d(ad) + B * d(ad^2)\n    // clang-format off\n    H_out <<\n      0., -2 * B * a_in.y(), -2 * B * a_in.z(), B * a_in.y(), B * a_in.x(), -A, B * a_in.z(), A, B * a_in.x(),\n      B * a_in.y(), B * a_in.x(), A, -2 * B * a_in.x(), 0., -2 * B * a_in.z(), -A, B * a_in.z(), B * a_in.y(),\n      B * a_in.z(), -A, B * a_in.x(), A, B * a_in.z(), B * a_in.y(), -2 * B * a_in.x(), -2 * B * a_in.y(), 0.;\n    // clang-format on\n\n    // add -dA * ad + dB * ad^2\n    Eigen::Matrix3<Scalar> ad_a;\n    ad(a_in, ad_a);\n    const Eigen::Matrix3<Scalar> ad_a2 = ad_a * ad_a;\n\n    for (auto i = 0u; i < 3; ++i) {\n      const Scalar dA_dxi = dA_over_th * a_in(i);\n      const Scalar dB_dxi = dB_over_th * a_in(i);\n      for (auto j = 0u; j < 3; ++j) {\n        H_out.col(i + 3 * j) -= dA_dxi * ad_a.row(j).transpose();\n        H_out.col(i + 3 * j) += dB_dxi * ad_a2.row(j).transpose();\n      }\n    }\n  }\n\n  static void d2r_expinv(TRefIn a_in, THessRefOut H_out)\n  {\n    const auto [A, dA_over_th] = [&]() -> std::array<Scalar, 2> {\n      using std::sqrt;\n\n      const Scalar th2 = a_in.squaredNorm();\n      const Scalar th  = sqrt(th2);\n      if (th2 < Scalar(eps2)) {\n        return {\n          Scalar(1) / Scalar(12) + th2 / Scalar(720),\n          Scalar(1) / Scalar(360),\n        };\n      } else {\n        const Scalar th3 = th2 * th;\n        const Scalar th4 = th2 * th2;\n        const Scalar sTh = sin(th);\n        const Scalar cTh = cos(th);\n        return {\n          Scalar(1) / th2 - (Scalar(1) + cTh) / (Scalar(2) * th * sTh),\n          1 / (2 * th2) + cTh * cTh / (2 * th2 * sTh * sTh) + cTh / (2 * th2 * sTh * sTh)\n            + cTh / (2 * th3 * sTh) + 1 / (2 * th3 * sTh) - 2 / th4,\n        };\n      }\n    }();\n\n    // A * d(ad^2)\n    // clang-format off\n    H_out <<\n      0, -2 * A * a_in.y(), -2 * A * a_in.z(), A * a_in.y(), A * a_in.x(), 0.5, A * a_in.z(), -0.5, A * a_in.x(),\n      A * a_in.y(), A * a_in.x(), -0.5, -2 * A * a_in.x(), 0, -2 * A * a_in.z(), 0.5, A * a_in.z(), A * a_in.y(),\n      A * a_in.z(), 0.5, A * a_in.x(), -0.5, A * a_in.z(), A * a_in.y(), -2 * A * a_in.x(), -2 * A * a_in.y(), 0;\n    // clang-format on\n\n    // add dA * ad^2\n    Eigen::Matrix3<Scalar> ad_a;\n    ad(a_in, ad_a);\n    const Eigen::Matrix3<Scalar> ad_a2 = ad_a * ad_a;\n    for (auto i = 0u; i < 3; ++i) {\n      const Scalar dA_dxi = dA_over_th * a_in(i);\n      for (auto j = 0u; j < 3; ++j) { H_out.col(i + 3 * j) += dA_dxi * ad_a2.row(j).transpose(); }\n    }\n  }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERNAL__SO3_HPP_\n", "meta": {"hexsha": "dbe2a1702fdb504c2e6c390ccf94abc1fc5545fb", "size": 10007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/so3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "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/smooth/internal/so3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "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/smooth/internal/so3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["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.8694267516, "max_line_length": 113, "alphanum_fraction": 0.5516138703, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6692449167711142}}
{"text": "// inverse_chi_squared_distribution_example.cpp\n\n// Copyright Paul A. Bristow 2010.\n// Copyright Thomas Mang 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 1 of using inverse chi squared distribution\n#include <boost/math/distributions/inverse_chi_squared.hpp>\nusing boost::math::inverse_chi_squared_distribution;  // inverse_chi_squared_distribution.\nusing boost::math::inverse_chi_squared; //typedef for nverse_chi_squared_distribution double.\n\n#include <iostream>\nusing std::cout;    using std::endl;\n#include <iomanip>\nusing std::setprecision;\nusing std::setw;\n#include <cmath>\nusing std::sqrt;\n\ntemplate <class RealType>\nRealType naive_pdf1(RealType df, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Inverse-chi-square_distribution\n  // definition 1 using tgamma for simplicity as a check.\n   using namespace std; // For ADL of std functions.\n   using boost::math::tgamma;\n   RealType df2 = df / 2;\n   RealType result = (pow(2., -df2) * pow(x, (-df2 -1)) * exp(-1/(2 * x) ) )\n      / tgamma(df2);  //\n   return result;\n}\n\ntemplate <class RealType>\nRealType naive_pdf2(RealType df, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Inverse-chi-square_distribution\n  // Definition 2, using tgamma for simplicity as a check.\n  // Not scaled, so assumes scale = 1 and only uses nu aka df.\n   using namespace std; // For ADL of std functions.\n   using boost::math::tgamma;\n   RealType df2 = df / 2;\n   RealType result = (pow(df2, df2) * pow(x, (-df2 -1)) * exp(-df/(2*x) ) )\n     / tgamma(df2);\n   return result;\n}\n\ntemplate <class RealType>\nRealType naive_pdf3(RealType df, RealType scale, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Scaled-inverse-chi-square_distribution\n  // *Scaled* version, definition 3, df aka nu, scale aka sigma^2\n  // using tgamma for simplicity as a check.\n   using namespace std; // For ADL of std functions.\n   using boost::math::tgamma;\n   RealType df2 = df / 2;\n   RealType result = (pow(scale * df2, df2) * exp(-df2 * scale/x) )\n     / (tgamma(df2) * pow(x, 1+df2));\n   return result;\n}\n\ntemplate <class RealType>\nRealType naive_pdf4(RealType df, RealType scale, RealType x)\n{ // Formula from http://mathworld.wolfram.com/InverseChi-SquaredDistribution.html\n  // Weisstein, Eric W. \"Inverse Chi-Squared Distribution.\" From MathWorld--A Wolfram Web Resource.\n  // *Scaled* version, definition 3, df aka nu, scale aka sigma^2\n  // using tgamma for simplicity as a check.\n   using namespace std; // For ADL of std functions.\n   using boost::math::tgamma;\n   RealType nu = df; // Wolfram uses greek symbols nu,\n   RealType xi = scale; // and xi.\n   RealType result =\n     pow(2, -nu/2) *  exp(- (nu * xi)/(2 * x)) * pow(x, -1-nu/2) * pow((nu * xi), nu/2)\n     / tgamma(nu/2);\n   return result;\n}\n\nint main()\n{\n\n  cout << \"Example (basic) using Inverse chi squared distribution. \" << endl;\n\n  // TODO find a more practical/useful example.  Suggestions welcome?\n\n#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n  int max_digits10 = 2 + (boost::math::policies::digits<double, boost::math::policies::policy<> >() * 30103UL) / 100000UL;\n  cout << \"BOOST_NO_CXX11_NUMERIC_LIMITS is defined\" << endl;\n#else\n  int max_digits10 = std::numeric_limits<double>::max_digits10;\n#endif\n  cout << \"Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = \"\n    << max_digits10 << endl;\n  cout.precision(max_digits10); //\n\n  inverse_chi_squared ichsqdef; // All defaults  - not very useful!\n  cout << \"default df = \" << ichsqdef.degrees_of_freedom()\n    << \", default scale = \" <<  ichsqdef.scale() << endl; //  default df = 1, default scale = 0.5\n\n   inverse_chi_squared ichsqdef4(4); // Unscaled version, default scale = 1 / degrees_of_freedom\n   cout << \"default df = \" << ichsqdef4.degrees_of_freedom()\n    << \", default scale = \" <<  ichsqdef4.scale() << endl; //  default df = 4, default scale = 2\n\n   inverse_chi_squared ichsqdef32(3, 2); // Scaled version, both degrees_of_freedom and scale specified.\n   cout << \"default df = \" << ichsqdef32.degrees_of_freedom()\n    << \", default scale = \" <<  ichsqdef32.scale() << endl; // default df = 3, default scale = 2\n\n  {\n    cout.precision(3);\n    double nu = 5.;\n    //double scale1 = 1./ nu; // 1st definition sigma^2 = 1/df;\n    //double scale2 = 1.; // 2nd definition sigma^2 = 1\n    inverse_chi_squared ichsq(nu, 1/nu); // Not scaled\n    inverse_chi_squared sichsq(nu, 1/nu); // scaled\n\n    cout << \"nu = \" << ichsq.degrees_of_freedom() << \", scale = \" << ichsq.scale() << endl;\n\n    int width = 8;\n\n    cout << \"     x        pdf      pdf1   pdf2  pdf(scaled)    pdf       pdf      cdf     cdf\" << endl;\n    for (double x = 0.0; x < 1.; x += 0.1)\n    {\n      cout\n        << setw(width) << x\n        << ' ' << setw(width) << pdf(ichsq, x) // unscaled\n        << ' ' << setw(width) << naive_pdf1(nu,  x) // Wiki def 1 unscaled matches graph\n        << ' ' << setw(width) << naive_pdf2(nu,  x) // scale = 1 - 2nd definition.\n        << ' ' << setw(width) << naive_pdf3(nu, 1/nu, x) // scaled\n        << ' ' << setw(width) << naive_pdf4(nu, 1/nu, x) // scaled\n        << ' ' << setw(width) << pdf(sichsq, x)  // scaled\n        << ' ' << setw(width) << cdf(sichsq, x)  // scaled\n        << ' ' << setw(width) << cdf(ichsq, x)  // unscaled\n       << endl;\n    }\n  }\n\n  cout.precision(max_digits10);\n\n  inverse_chi_squared ichisq(2., 0.5);\n  cout << \"pdf(ichisq, 1.) = \" << pdf(ichisq, 1.) << endl;\n  cout << \"cdf(ichisq, 1.) = \" << cdf(ichisq, 1.) << endl;\n\n  return 0;\n}  // int main()\n\n/*\n\nOutput is:\n Example (basic) using Inverse chi squared distribution.\n  Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = 17\n  default df = 1, default scale = 1\n  default df = 4, default scale = 0.25\n  default df = 3, default scale = 2\n  nu = 5, scale = 0.2\n       x        pdf      pdf1   pdf2  pdf(scaled)    pdf       pdf      cdf     cdf\n         0        0    -1.#J    -1.#J    -1.#J    -1.#J        0        0        0\n       0.1     2.83     2.83 3.26e-007     2.83     2.83     2.83   0.0752   0.0752\n       0.2     3.05     3.05  0.00774     3.05     3.05     3.05    0.416    0.416\n       0.3      1.7      1.7    0.121      1.7      1.7      1.7    0.649    0.649\n       0.4    0.941    0.941    0.355    0.941    0.941    0.941    0.776    0.776\n       0.5    0.553    0.553    0.567    0.553    0.553    0.553    0.849    0.849\n       0.6    0.345    0.345    0.689    0.345    0.345    0.345    0.893    0.893\n       0.7    0.227    0.227    0.728    0.227    0.227    0.227    0.921    0.921\n       0.8    0.155    0.155    0.713    0.155    0.155    0.155     0.94     0.94\n       0.9     0.11     0.11    0.668     0.11     0.11     0.11    0.953    0.953\n         1   0.0807   0.0807     0.61   0.0807   0.0807   0.0807    0.963    0.963\n  pdf(ichisq, 1.) = 0.30326532985631671\n  cdf(ichisq, 1.) = 0.60653065971263365\n\n\n*/\n", "meta": {"hexsha": "0fb6a6de08c6a9ec6d7aab1458488b528c12de9a", "size": 7092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 41.4736842105, "max_line_length": 122, "alphanum_fraction": 0.6122391427, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6692159101920716}}
{"text": "#include \"core/BezierCurve.h\"\n\n#include \"core/Util.h\"\n#include <boost/math/quadrature/trapezoidal.hpp>\n\nBezierCurve::BezierCurve(const vector_t& control0, const vector_t& control1, const vector_t& control2, const vector_t& control3)\n    : _control0(control0), _control1(control1), _control2(control2), _control3(control3) {\n\n}\n\nvector_t BezierCurve::Position(float t) const {\n  if (t <= 0) {\n    return _control0;\n  } else if (t >= 1) {\n    return _control3;\n  } else {\n    return (1 - t) * (1 - t) * (1 - t) * _control0 +\n      3 * (1 - t) * (1 - t) * t * _control1 +\n      3 * (1 - t) * t * t * _control2 +\n      t * t * t * _control3;\n  }\n}\n\nvector_t BezierCurve::Heading(float t) const {\n  if (t <= 0) {\n    return (_control1 - _control0).normalized();\n  } else if (t >= 1) {\n    return (_control3 - _control2).normalized();\n  } else {\n    return (3 * (1 - t) * (1 - t) * (_control1 - _control0) +\n      6 * (1 - t) * t * (_control2 - _control1) +\n      3 * t * t * (_control3 - _control2)).normalized();\n  }\n}\n\nfloat BezierCurve::Length(float start, float end) const {\n  if (start >= end) {\n    return 0;\n  } else {\n    return boost::math::quadrature::trapezoidal(\n        [this](float t) {\n          vector_t grad = -3 * (1 - t) * (1 - t) * _control0 +\n              3 * (1 - t) * (1 - 3 * t) * _control1 +\n              3 * t * (2 - 3 * t) * _control2 +\n              3 * t * t * _control3;\n          return grad.norm();\n        },\n        std::max(start, 0.0f), std::min(end, 1.0f), 1e-12f);\n  }\n}\n", "meta": {"hexsha": "70d1539acd1b2eac8044f07212060ce559690bcb", "size": 1506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/core/BezierCurve.cpp", "max_stars_repo_name": "modanesh/magic", "max_stars_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T22:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T03:29:03.000Z", "max_issues_repo_path": "cpp/src/core/BezierCurve.cpp", "max_issues_repo_name": "modanesh/magic", "max_issues_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-17T01:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T04:58:54.000Z", "max_forks_repo_path": "cpp/src/core/BezierCurve.cpp", "max_forks_repo_name": "modanesh/magic", "max_forks_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T07:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:40:29.000Z", "avg_line_length": 29.5294117647, "max_line_length": 128, "alphanum_fraction": 0.5484727756, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6691666698212935}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[length_with_strategy\n//`The following example shows the length measured over a sphere, expressed in kilometers. To do that the radius of the sphere must be specified in the constructor of the strategy.\n\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n\nint main()\n{\n    using namespace boost::geometry;\n    typedef model::point<float, 2, cs::spherical_equatorial<degree> > P;\n    model::linestring<P> line;\n    line.push_back(P(2, 41));\n    line.push_back(P(2, 48));\n    line.push_back(P(5, 52));\n    double const mean_radius = 6371.0; /*< [@http://en.wikipedia.org/wiki/Earth_radius Wiki]  >*/\n    std::cout << \"length is \"\n        << length(line, strategy::distance::haversine<P>(mean_radius) )\n        << \" kilometers \" << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[length_with_strategy_output\n/*`\nOutput:\n[pre\nlength is 1272.03 kilometers\n]\n*/\n//]\n", "meta": {"hexsha": "99c15fb19632549eca690e876822e5f69cd21ed6", "size": 1239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/doc/src/examples/algorithms/length_with_strategy.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/geometry/doc/src/examples/algorithms/length_with_strategy.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/geometry/doc/src/examples/algorithms/length_with_strategy.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": 28.1590909091, "max_line_length": 180, "alphanum_fraction": 0.7005649718, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6691666676935929}}
{"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\u00c3\u00a4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/timer.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\n\ntemplate <typename Matrix>\ntypename mtl::Collection<Matrix>::value_type\ninline determinant(const Matrix& A, double eps= 0)\n{\n    mtl::dense_vector<std::size_t> P(num_rows(A)); \n    mtl::dense2D<typename mtl::Collection<Matrix>::value_type>   LU(A);  // A is copied in a dense matrix because lu overwrites its argument\n    lu(LU, P, eps);\n    return product(diagonal(LU));\n}\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    laplacian_setup(A, 3, 4);\n    // boost::timer t;\n    cout << \"\\n\" << name << \", determinant is \" << determinant(A) << \"\\n\";\n    // cout << \"It took \" << t.elapsed() << \"s\\n\";\n}\n\n\nint main(int, char**) \n{\n    using namespace mtl;\n    dense2D<double>                                      dr;\n    dense2D<complex<double> >                            dz;\n    dense2D<double, mat::parameters<col_major> >      dc;\n    compressed2D<double>                                 cr;\n\n    test(dr, \"Row-major dense\");\n    test(dz, \"Row-major dense with complex numbers\");\n    test(dc, \"Column-major dense\");\n    test(cr, \"Row-major compressed\");\n    \n    return 0;\n}\n", "meta": {"hexsha": "add798cb8b8ebb94e1cf5ddb47f3389072beb496", "size": 1652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/determinant_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/experimental/determinant_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/experimental/determinant_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": 30.5925925926, "max_line_length": 140, "alphanum_fraction": 0.6210653753, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6691666669451105}}
{"text": "#include <Eigen/Core>\n\n#include <vector>\n#include <memory>\n\n#include \"SDOT/Polygon.h\"\n\nusing namespace sdot;\n\nvoid MakePolygonConvex(){\n\n  // First, construct a non-convex polygon\n  /*\n      v4     v2\n      | \\   /|\n      |  \\ / |\n      |  v3  |\n      |      |\n      v0-----v1\n */\n  Eigen::Matrix2Xd pts(2,5);\n  pts << 0, 1, 1, 0.5, 0,\n         0, 0, 1, 0.5, 1;\n\n  Polygon poly(pts);\n\n  // Test the IsConvex() function.\n  std::cout << \"Is non-convex base polygon being detected? \";\n  if(poly.IsConvex()){\n    std::cout << \" NO!\"<< std::endl;\n  }else{\n    std::cout << \" YES!\" << std::endl;\n  }\n\n\n  // Test the ability to construct a convex partition\n  std::vector<std::shared_ptr<Polygon>> polys = poly.ConvexPartition();\n\n  std::cout << \"Convex Polygons:\" << std::endl;\n  for(int i=0; i<polys.size(); ++i){\n    std::cout << \"  Poly\"<< i+1 << \" IsConvex()? \" << polys.at(i)->IsConvex() << std::endl;\n  }\n}\n\n\nint main(){\n\n  MakePolygonConvex();\n  return 0;\n}\n", "meta": {"hexsha": "7bf9aefb135393e05bc280cce82772364dccc362", "size": 958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Convexify.cpp", "max_stars_repo_name": "mparno/sdot2d", "max_stars_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/Convexify.cpp", "max_issues_repo_name": "mparno/sdot2d", "max_issues_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Convexify.cpp", "max_forks_repo_name": "mparno/sdot2d", "max_forks_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7843137255, "max_line_length": 91, "alphanum_fraction": 0.5438413361, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6691666563066074}}
{"text": "/* MonteCarlo.hpp\r\n-Description:\r\n\t*Declare and define MonteCarlo template class that calculates the price of a financial option using the Euler-Maruyama scheme.\r\n-State Objects:\r\n\t*variate_generator rng: Boost implemented normal random number generator for Monte Carlo path generation.\r\n-Class Methods:\r\n\t// Constructors/Destructors:\r\n\t*MonteCarlo(double t, double s, double k, double b, double r, double sigma, unsigned long NSIM, unsigned long NT, bool isCall): Overloaded Constructor.\r\n\t*MonteCarlo(const MonteCarlo&): Copy constructor.\r\n\t*~MonteCarlo(): Destructor.\r\n\t// Accessors:\r\n\t*unsigned long NSIM() const: Return the number of trials to be run in Monte Carlo.\r\n\t*unsigned long NT() const: Return number of sub-intervals in time to be used in generating each path.\r\n\t// Mutators:\r\n\t*void NSIM(unsigned long): Set number of trials.\r\n\t*void NT(unsigned long): Set number of time sub-intervals.\r\n\t// Misc. Methods:\r\n\t*double Price() const: Calculate price of associated option using Monte Carlo method with Euler-Maruyama scheme.\r\n*/\r\n\r\n#include <boost/random/variate_generator.hpp>\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <ctime>\r\n#include <cmath>\r\n#include <string>\r\n#include <vector>\r\n#include \"MonteCarlo.hpp\"\r\n#include \"MonteCarloExcept.hpp\"\r\n#include \"Option.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\tMonteCarlo::MonteCarlo(double t, double s, double k, double b, double r, double sigma, bool isCall, unsigned long NSIM_in, unsigned long NT_in) : /* Overloaded Constructor. Set all parameters. */\r\n\t\tOption(t, s, k, b, r, sigma, isCall), nT(NT_in), nSIM(NSIM_in)\t\r\n\t{\r\n\t\tmainRNG = new boost::variate_generator<boost::mt19937, boost::normal_distribution<double> >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::MonteCarlo(const MonteCarlo &in) : Option(in), nT(in.nT), nSIM(in.nSIM) /* Copy Constructor. */\r\n\t{\r\n\t\t\tmainRNG = new boost::variate_generator<boost::mt19937, boost::normal_distribution<double> >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::MonteCarlo(const Option &in, unsigned long NSIM, unsigned long NT): \t\t\t\t\t\t\t/* Copy Constructor 2, with NT and NSIM setting*/\r\n\t\tOption(in), nSIM(NSIM), nT(NT)\r\n\t{\r\n\t\tmainRNG = new boost::variate_generator<boost::mt19937, boost::normal_distribution<double> >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::~MonteCarlo()\t\t\t\t\t\t\t\t\t\t\t\t\t/* Destructor. */\r\n\t{\r\n\t\tdelete mainRNG;\r\n\t}\r\n\t////////////////////////////\r\n\t// Accessors:\r\n\t////////////////////////////\r\n\tunsigned long MonteCarlo::NSIM() const\t\t\t\t\t\t\t/* Return number of simulations run in the Monte Carlo. */\r\n\t{\r\n\t\treturn nSIM;\r\n\t}\r\n\tunsigned long MonteCarlo::NT() const\t\t\t\t\t\t\t\t/* Return number of time intervals run in the Monte Carlo path generation. */\r\n\t{\r\n\t\treturn nT;\r\n\t}\r\n\t////////////////////////////\r\n\t// Mutators:\r\n\t////////////////////////////\r\n\tvoid MonteCarlo::NSIM(unsigned long NSIM_in)\t\t\t\t\t\t/* Set the number of simulations to run in the Monte Carlo. */\r\n\t{\r\n\t\tnSIM = NSIM_in;\r\n\t}\r\n\tvoid MonteCarlo::NT(unsigned long NT_in)\t\t\t\t\t\t\t/* Set the number of time intervals to run in the Monte Carlo path generation. */\r\n\t{\r\n\t\tnT = NT_in;\r\n\t}\r\n\t////////////////////////////\r\n\t// Misc. Methods:\r\n\t////////////////////////////\r\n\tdouble MonteCarlo::Price() const\t\t/* Get price of option using Monte Carlo method with Euler-Maruyama pdf. */\r\n\t{\r\n\t\t// NSIM is number of paths to generate, 1/NT is the time divisor (discretizes \"t\" into number of subintervals).\r\n\t\t// As NSIM AND NT approach infinity, GeneratePrice approaches the exact price given by the Black-Scholes equation or the American Perpetual Option pricing method. \r\n\t\tdouble S, output = 0, payoff = 0;\r\n\t\tfor (unsigned long currTrial = 0; currTrial < nSIM; currTrial++)\r\n\t\t{\r\n\t\t\t// Reset the path:\r\n\t\t\tS = Param(\"s\");\r\n\t\t\t// Generate path using Euler-Maruyama partial differentiation scheme:\r\n\t\t\tfor (double currTimeInterval = 0; currTimeInterval < Param(\"t\"); currTimeInterval += 1.0 / (double) nT)\r\n\t\t\t{\r\n\t\t\t\tS += (Param(\"r\") * S * (((double) 1.0 / (double) nT))) + (Param(\"sigma\") * S * std::sqrt((double) 1.0 / (double) nT) * (*mainRNG)());\r\n\t\t\t}\r\n\t\t\t// Calculate payoff of option at expiry depending on type:\r\n\t\t\tif (Option::Type())\r\n\t\t\t{\r\n\t\t\t\tpayoff = std::max(S - Param(\"k\"), 0.0);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tpayoff = std::max(Param(\"k\") - S, 0.0);\r\n\t\t\t}\r\n\t\t\t// Discount the payoff back to present and accumulate:\r\n\t\t\toutput += payoff / (double) nSIM;\r\n\t\t}\r\n\t\t// Return the average discounted payoff:\r\n\t\treturn output * exp(-Param(\"r\") * Param(\"t\"));\r\n\t}\r\n\t////////////////////////////\r\n\t// Overloaded Operators:\r\n\t////////////////////////////\r\n\tMonteCarlo& MonteCarlo::operator=(const MonteCarlo &in)\t\t\t\t\t\t\t\t\t/* 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": "4e41b6972b1eaf262275b852c7ef9180f9f2d844", "size": 4986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Options/Files/MonteCarlo.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/MonteCarlo.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/MonteCarlo.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": 41.2066115702, "max_line_length": 197, "alphanum_fraction": 0.6385880465, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6691666541789066}}
{"text": "// EigenConsoleApplication1.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n\r\n//#include \"stdafx.h\"\r\n#include <ctime>\r\n#include <Eigen/Dense>\r\n#include <iostream>\r\n#include <complex>      // std::complex\r\n\r\n//using Eigen::MatrixXd;\r\n//using Eigen::Matrix3cd;\r\n\r\nvoid rf_pulse_matrix(Eigen::Matrix3cd *rfpulse, double alpha, double phi)\r\n{\r\n\tconst double PI = 3.1415926535897932384626433832795;\r\n\r\n\tdouble alpha_half = alpha / 2.0;\r\n\tdouble c_a_h = cos(alpha_half);\r\n\tdouble c_a_h2 = c_a_h * c_a_h;\r\n\tdouble s_a_h = sin(alpha_half);\r\n\tdouble s_a_h2 = s_a_h * s_a_h;\r\n\tdouble c_a = cos(alpha);\r\n\tdouble s_a = sin(alpha);\r\n\r\n\tstd::complex<double> i_phi = std::complex<double>(0.0, phi);\r\n\tstd::complex<double> i_half = std::complex<double>(0.0, 0.5);\r\n\r\n\t(*rfpulse)(0, 0) = c_a_h2;\r\n\t(*rfpulse)(0, 1) = exp(i_phi*2.0)*s_a_h2;\r\n\t(*rfpulse)(0, 2) = -1.0*std::complex<double>(0.0, 1.0)*exp(i_phi)*s_a;\r\n\r\n\t(*rfpulse)(1, 0) = exp(-2.0 * i_phi)*s_a_h2;\r\n\t(*rfpulse)(1, 1) = c_a_h2;\r\n\t(*rfpulse)(1, 2) = std::complex<double>(0.0, 1.0) * exp(-1.0*i_phi)*s_a;\r\n\r\n\t(*rfpulse)(2, 0) = -1.0*i_half*exp(-1.0*i_phi)*s_a;\r\n\t(*rfpulse)(2, 1) = 1.0*i_half*exp(1.0*i_phi)*s_a;\r\n\t(*rfpulse)(2, 2) = c_a;\r\n\r\n\t//std::cout << *rfpulse << std::endl;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nvoid epg_grad(Eigen::MatrixXcd *FpFmZ, int num_cols)\r\n{\r\n\r\n\tfor (int i = 0; i < num_cols - 1; i++)\r\n\t{\r\n\t\t//std::cout << i << \"\\t\" << num_cols - 1 - i << \"\\t\" << num_cols - 1 - i - 1 << \"\\t\" << (*FpFmZ)(0,i) << std::endl;\r\n\t\t(*FpFmZ)(0, num_cols - 1 - i) = (*FpFmZ)(0, num_cols - 1 - i - 1);\r\n\t}\r\n\r\n\r\n\t(*FpFmZ)(0, 0) = std::complex<double>(0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < num_cols - 1; i++)\r\n\t\t(*FpFmZ)(1, i) = (*FpFmZ)(1, i + 1);\r\n\r\n\t(*FpFmZ)(1, num_cols - 1) = std::complex<double>(0.0, 0.0);\r\n\r\n\t(*FpFmZ)(0, 0) = conj((*FpFmZ)(1, 0));\r\n}\r\n\r\n\r\nvoid  cpmg_epg(double *signal, int Nechos, double rf_180, double T1, double T2, double Techo)\r\n{\r\n\tconst double PI = 3.1415926535897932384626433832795;\r\n\tint    num_cols = 2 * Nechos;\r\n\r\n\tEigen::MatrixXcd FpFmZ(3, 34);\r\n\tEigen::Matrix3cd rfpulse90y = Eigen::Matrix3cd::Zero();\r\n\tEigen::Matrix3cd rfpulse180x = Eigen::Matrix3cd::Zero();\r\n\tEigen::Matrix3d ee = Eigen::Matrix3d::Zero();\r\n\t//Eigen::MatrixXd signal(1, 17);\r\n\r\n\r\n\r\n\r\n\tFpFmZ = FpFmZ.Zero(3, 34);\r\n\r\n\r\n\r\n\t// ****************************************\r\n\t// Initialize diagonal of relaxation matrix\r\n\t// ****************************************\r\n\r\n\tee(0, 0) = exp(-Techo / 2.0 / T2);\r\n\tee(1, 1) = exp(-Techo / 2.0 / T2);\r\n\tee(2, 2) = exp(-Techo / 2.0 / T1);\r\n\r\n\r\n\t// ********************************\r\n\t// Set Z magnetization to 1.0 +0.0j\r\n\t// ********************************\r\n\r\n\tFpFmZ(0, 0) = 0.0;\r\n\tFpFmZ(1, 0) = 0.0;\r\n\tFpFmZ(2, 0) = 1.0;\r\n\r\n\t// *********************************\r\n\t// Create 90(y) rotation matrix\r\n\t// *********************************\r\n\r\n\trf_pulse_matrix(&rfpulse90y, PI / 2.0, PI / 2.0);\r\n\r\n\t// *********************************\r\n\t// Create 180(x) rotation matrix\r\n\t// *********************************\r\n\r\n\trf_pulse_matrix(&rfpulse180x, rf_180*PI / 180.0, 0.0);\r\n\r\n\t// *********************************\r\n\t// Apply 90 degree pulse\r\n\t// *********************************\r\n\r\n\tFpFmZ = rfpulse90y * FpFmZ;\r\n\r\n\t// ****************************************\r\n\t// Apply 180 pulses of CPMG sequence\r\n\t// ****************************************\r\n\r\n\tfor (int i = 0; i < Nechos; i++)\r\n\t{\r\n\r\n\t\tFpFmZ = ee * FpFmZ;\r\n\t\tFpFmZ(2, 0) = FpFmZ(2, 0) + 1.0 - ee(2, 2);\r\n\t\tepg_grad(&FpFmZ, 34);\r\n\r\n\t\tFpFmZ = rfpulse180x * FpFmZ;\r\n\r\n\t\tFpFmZ = ee * FpFmZ;\r\n\t\tFpFmZ(2, 0) = FpFmZ(2, 0) + 1.0 - ee(2, 2);\r\n\t\tepg_grad(&FpFmZ, 34);\r\n\r\n\t\tsignal[i] = real(FpFmZ(0, 0));\r\n\t}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n//int main()\r\n//{\r\n//\tconst double PI = 3.1415926535897932384626433832795;\r\n//\tstd::clock_t    start;\r\n//\r\n//\tdouble T1 = 3000.0;\r\n//\tdouble T2 = 50.0;\r\n//\tdouble Techo = 10.0;\r\n//\tint    Nechos = 17;\r\n//\tint    num_cols = 2 * Nechos;\r\n//\r\n//\tEigen::MatrixXcd FpFmZ(3, num_cols);\r\n//\tEigen::Matrix3cd rfpulse90y = Eigen::Matrix3cd::Zero();\r\n//\tEigen::Matrix3cd rfpulse180x = Eigen::Matrix3cd::Zero();\r\n//\tEigen::Matrix3d ee = Eigen::Matrix3d::Zero();\r\n//\r\n//\tdouble *signal = new  double [Nechos] { 0.0 };\r\n//\r\n//\tstart = std::clock();\r\n//\r\n//\tfor (int j = 0; j < 10000; j++)\r\n//\t\tcpmg_epg(signal, Nechos, PI, T1, T2, Techo);\r\n//\r\n//\tstd::cout << \"Time: \" << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << \" ms\" << std::endl;\r\n//\r\n//\tfor (int i = 0; i<Nechos; i++)\r\n//\t\tstd::cout << signal[i] << std::endl;\r\n//\r\n//\r\n//\r\n//}\r\n", "meta": {"hexsha": "75a0d3899c9204d5ef53b06dc6137f2c7dbb5bd9", "size": 4485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated/epg_cpmg_eigen.cpp", "max_stars_repo_name": "EricHughesABC/EPG", "max_stars_repo_head_hexsha": "d5aaf80d20667a5d56db3ab0842d76bd2bf92ea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T01:42:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-13T12:23:56.000Z", "max_issues_repo_path": "deprecated/epg_cpmg_eigen.cpp", "max_issues_repo_name": "EricHughesABC/EPG", "max_issues_repo_head_hexsha": "d5aaf80d20667a5d56db3ab0842d76bd2bf92ea9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deprecated/epg_cpmg_eigen.cpp", "max_forks_repo_name": "EricHughesABC/EPG", "max_forks_repo_head_hexsha": "d5aaf80d20667a5d56db3ab0842d76bd2bf92ea9", "max_forks_repo_licenses": ["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.6428571429, "max_line_length": 118, "alphanum_fraction": 0.5090301003, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558355999, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6690836532987291}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  Matrix3f m = Matrix3f::Random();\n  m = (m + Matrix3f::Constant(1.2)) * 50;\n  cout << \"m =\" << endl << m << endl;\n  Vector3f v(1,2,3);\n  \n  cout << \"m * v =\" << endl << m * v << endl;\n}\n", "meta": {"hexsha": "edf3268cde0336ba805765aa7b72cda651fc0d7a", "size": 289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_stars_repo_name": "LEEZHEHUI/QT-SoftRender", "max_stars_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_issues_repo_name": "LEEZHEHUI/QT-SoftRender", "max_issues_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "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": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_forks_repo_name": "LEEZHEHUI/QT-SoftRender", "max_forks_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 18.0625, "max_line_length": 45, "alphanum_fraction": 0.5605536332, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6690836493471927}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2011\n//\n//============================================================================\n\n#include \"Math.hpp\"\n#include \"../../Array.hpp\"\n#include \"../../MatVec.hpp\"\n#include \"../../Ray3.hpp\"\n#include \"../../Triangle3.hpp\"\n#include <Eigen/SVD>\n\nnamespace Browse3D {\n\nMatrix3\northonormalBasisMatrix(Vector3 const & u, Vector3 const & v, Vector3 const & w)\n{\n  Vector3 w2 = w.normalized();\n  Vector3 u2 = v.cross(w2).normalized();\n  Vector3 v2 = w2.cross(u2);\n\n  Matrix3 ret; ret << u2, v2, w2;\n  return ret;\n}\n\nMatrix3\northonormalBasisMatrix(Matrix3 const & m)\n{\n  return orthonormalBasisMatrix(m.col(0), m.col(1), m.col(2));\n}\n\nReal\nestimateScalingFactor(Matrix3 const & m)\n{\n  return (m.col(0).norm() + m.col(1).norm() + m.col(2).norm()) / 3.0f;\n}\n\nVector3\nreflectPoint(Vector3 const & p, Plane3 const & mirror_plane)\n{\n  // Assume Plane3::normal() is unit\n  return p - 2 * (p - mirror_plane.getPoint()).dot(mirror_plane.getNormal()) * mirror_plane.getNormal();\n}\n\nVector3\nreflectVector(Vector3 const & v, Plane3 const & mirror_plane)\n{\n  // Assume Plane3::normal() is unit\n  return v - 2 * v.dot(mirror_plane.getNormal()) * mirror_plane.getNormal();\n}\n\nbool\nlineIntersectsTriangle(Line3 const & line, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real * time)\n{\n  // The code is taken from the ray-triangle intersection test in Dave Eberly's Wild Magic library, v5.3, released under the\n  // Boost license: http://www.boost.org/LICENSE_1_0.txt .\n\n  static Real const EPS = 1e-30f;\n\n  Vector3 diff = line.getPoint() - v0;\n  Vector3 normal = edge01.cross(edge02);\n\n  // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = line direction, E1 = edge01, E2 = edge02, N = Cross(E1,E2)) by\n  //   |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))\n  //   |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))\n  //   |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)\n\n  Real DdN = line.getDirection().dot(normal);\n  int sign;\n  if (DdN > EPS)\n    sign = 1;\n  else if (DdN < -EPS)\n  {\n    sign = -1;\n    DdN = -DdN;\n  }\n  else\n  {\n    // Line and triangle are parallel, call it a \"no intersection\" even if the line does intersect\n    return false;\n  }\n\n  Real DdQxE2 = sign * line.getDirection().dot(diff.cross(edge02));\n  if (DdQxE2 >= 0)\n  {\n    Real DdE1xQ = sign * line.getDirection().dot(edge01.cross(diff));\n    if (DdE1xQ >= 0)\n    {\n      if (DdQxE2 + DdE1xQ <= DdN)\n      {\n        // Line intersects triangle\n        Real QdN = -sign * diff.dot(normal);\n        if (time) *time = QdN / DdN;\n        return true;\n      }\n      // else: b1 + b2 > 1, no intersection\n    }\n    // else: b2 < 0, no intersection\n  }\n  // else: b1 < 0, no intersection\n\n  return false;\n}\n\n#define CLOSEST_PT_SEGMENT_SEGMENT(VecType) \\\nReal \\\nclosestPtSegmentSegment(VecType const & p1, VecType const & q1, VecType const & p2, VecType const & q2, Real & s, Real & t, \\\n                        VecType & c1, VecType & c2) \\\n{ \\\n  static Real const EPSILON = 1e-20f; \\\n \\\n  VecType d1 = q1 - p1; /* Direction vector of segment S1 */ \\\n  VecType d2 = q2 - p2; /* Direction vector of segment S2 */ \\\n  VecType r = p1 - p2; \\\n  Real a = d1.squaredNorm(); /* Squared length of segment S1, always nonnegative */ \\\n  Real e = d2.squaredNorm(); /* Squared length of segment S2, always nonnegative */ \\\n  Real f = d2.dot(r); \\\n \\\n  /* Check if either or both segments degenerate into points */ \\\n  if (a <= EPSILON && e <= EPSILON) \\\n  { \\\n    /* Both segments degenerate into points */ \\\n    s = t = 0; \\\n    c1 = p1; \\\n    c2 = p2; \\\n    return (c1 - c2).dot(c1 - c2); \\\n  } \\\n  if (a <= EPSILON) \\\n  { \\\n    /* First segment degenerates into a point */ \\\n    s = 0; \\\n    t = f / e; /* s = 0 => t = (b*s + f) / e = f / e */ \\\n    t = Math::clamp(t, (Real)0, (Real)1); \\\n  } \\\n  else \\\n  { \\\n    Real c = d1.dot(r); \\\n    if (e <= EPSILON) \\\n    { \\\n        /* Second segment degenerates into a point */ \\\n        t = 0; \\\n        s = Math::clamp(-c / a, (Real)0, (Real)1); /* t = 0 => s = (b*t - c) / a = -c / a */ \\\n    } \\\n    else \\\n    { \\\n      /* The general nondegenerate case starts here */ \\\n      Real b = d1.dot(d2); \\\n      Real denom = a * e - b * b; /* Always nonnegative */ \\\n \\\n      /* If segments not parallel, compute closest point on L1 to L2, and */ \\\n      /* clamp to segment S1. Else pick arbitrary s (here 0) */ \\\n      if (denom != 0) \\\n        s = Math::clamp((b * f - c * e) / denom, (Real)0, (Real)1); \\\n      else \\\n        s = 0; \\\n \\\n      /* Compute point on L2 closest to S1(s) using */ \\\n      /* t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e */ \\\n      t = (b * s + f) / e; \\\n \\\n      /* If t in [0,1] done. Else clamp t, recompute s for the new value */ \\\n      /* of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a */ \\\n      /* and clamp s to [0, 1] */ \\\n      if (t < 0) \\\n      { \\\n        t = 0; \\\n        s = Math::clamp(-c / a, (Real)0, (Real)1); \\\n      } \\\n      else if (t > 1) \\\n      { \\\n        t = 1; \\\n        s = Math::clamp((b - c) / a, (Real)0, (Real)1); \\\n      } \\\n    } \\\n  } \\\n \\\n  c1 = p1 + s * d1; \\\n  c2 = p2 + t * d2; \\\n  return (c1 - c2).squaredNorm(); \\\n}\n\nCLOSEST_PT_SEGMENT_SEGMENT(Vector2)\nCLOSEST_PT_SEGMENT_SEGMENT(Vector3)\n\n#define CLOSEST_PT_SEGMENT_LINE(VecType) \\\nReal \\\nclosestPtSegmentLine(VecType const & p1, VecType const & q1, VecType const & p2, VecType const & q2, Real & s, Real & t, \\\n                     VecType & c1, VecType & c2) \\\n{ \\\n  static Real const EPSILON = 1e-20f; \\\n \\\n  VecType d1 = q1 - p1; /* Direction vector of segment S1 */ \\\n  VecType d2 = q2 - p2; /* Direction vector of line L2 */ \\\n  VecType r = p1 - p2; \\\n  Real a = d1.squaredNorm(); /* Squared length of segment S1, always nonnegative */ \\\n  Real e = d2.squaredNorm(); /* Squared length of segment supporting L2, always nonnegative and assumed to be non-zero */ \\\n  Real f = d2.dot(r); \\\n \\\n  if (a <= EPSILON) \\\n  { \\\n    /* Segment degenerates into a point */ \\\n    s = 0; \\\n    t = f / e; /* s = 0 => t = (b*s + f) / e = f / e */ \\\n  } \\\n  else \\\n  { \\\n    /* The general nondegenerate case starts here */ \\\n    Real c = d1.dot(r); \\\n    Real b = d1.dot(d2); \\\n    Real denom = a * e - b * b; /* Always nonnegative */ \\\n\\\n    /* If segments not parallel, compute closest point on L1 to L2, and */ \\\n    /* clamp to segment S1. Else pick arbitrary s (here 0) */ \\\n    if (denom != 0) \\\n      s = Math::clamp((b * f - c * e) / denom, (Real)0, (Real)1); \\\n    else \\\n      s = 0; \\\n\\\n    /* Compute point on L2 closest to S1(s) using */ \\\n    /* t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e */ \\\n    t = (b * s + f) / e; \\\n  } \\\n \\\n  c1 = p1 + s * d1; \\\n  c2 = p2 + t * d2; \\\n  return (c1 - c2).squaredNorm(); \\\n}\n\nCLOSEST_PT_SEGMENT_LINE(Vector2)\nCLOSEST_PT_SEGMENT_LINE(Vector3)\n\nReal\nclosestPtLineTriangle(Line3 const & line, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real & s,\n                      Vector3 & c1, Vector3 & c2)\n{\n  if (lineIntersectsTriangle(line, v0, edge01, edge02, &s))\n  {\n    c1 = c2 = line.getPoint() + s * line.getDirection();\n    return 0;\n  }\n\n  // Either (1) the line is not parallel to the triangle and the point of\n  // intersection of the line and the plane of the triangle is outside the\n  // triangle or (2) the line and triangle are parallel.  Regardless, the\n  // closest point on the triangle is on an edge of the triangle.  Compare\n  // the line to all three edges of the triangle.\n  Real min_sqdist = -1;\n  Vector3 v[3] = { v0, v0 + edge01, v0 + edge02 };\n  Vector3 tmp_c1, tmp_c2;\n  float tmp_s, t;\n  for (int i0 = 2, i1 = 0; i1 < 3; i0 = i1++)\n  {\n    Real sqdist = closestPtSegmentLine(v[i0], v[i1], line.getPoint(), line.getPoint() + line.getDirection(),\n                                       t, tmp_s, tmp_c2, tmp_c1);\n    if (min_sqdist < 0 || sqdist < min_sqdist)\n    {\n      min_sqdist = sqdist;\n      s = tmp_s;\n      c1 = tmp_c1;\n      c2 = tmp_c2;\n    }\n  }\n\n  return min_sqdist;\n}\n\nReal\nclosestPtRayTriangle(Ray3 const & ray, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real & s,\n                     Vector3 & c1, Vector3 & c2)\n{\n  Real sqdist = closestPtLineTriangle(Line3::fromPointAndDirection(ray.getOrigin(), ray.getDirection()), v0, edge01, edge02,\n                                      s, c1, c2);\n  if (s >= 0)\n    return sqdist;\n\n  // Not the most efficient way but the most convenient\n  LocalTriangle3 tri(v0, v0 + edge01, v0 + edge02);\n  s = 0;\n  c1 = ray.getOrigin();\n  c2 = tri.closestPoint(c1);\n\n  return (c1 - c2).squaredNorm();\n}\n\nRigidTransform3\nclosestRigidTransform(std::vector<CoordinateFrame3> const & src, std::vector<CoordinateFrame3> const & dst)\n{\n  alwaysAssertM(src.size() == dst.size(), \"Source and destination sets must have same number of frames\");\n\n  if (src.empty())\n    return RigidTransform3::identity();\n  else if (src.size() == 1)\n    return RigidTransform3(dst[0]) * RigidTransform3(src[0].inverse());\n  else if (src.size() == 2)\n  {\n    // First map line segment to line segment...\n    Vector3 src_mean = 0.5f * (src[0].getTranslation() + src[1].getTranslation());\n    Vector3 dst_mean = 0.5f * (dst[0].getTranslation() + dst[1].getTranslation());\n\n    static Real const MIN_SQLEN = 1.0e-8f;\n\n    Vector3 src_axis = src[1].getTranslation() - src[0].getTranslation();\n    Vector3 dst_axis = dst[1].getTranslation() - dst[0].getTranslation();\n\n    if (src_axis.squaredNorm() > MIN_SQLEN && dst_axis.squaredNorm() > MIN_SQLEN)\n    {\n      Matrix3 rot = Math::rotationArc(src_axis, dst_axis);\n\n      // Now rotate around the mapped segment to align the z axes of the frames...\n      Vector3 src_dir = rot * (src[0].getRotation().col(2) + src[1].getRotation().col(2));\n      Vector3 dst_dir = dst[0].getRotation().col(2) + dst[1].getRotation().col(2);\n\n      // Transform src_dir and dst_dir to be perpendicular to dst_axis\n      dst_axis = dst_axis.normalized();\n      src_dir = src_dir - src_dir.dot(dst_axis) * dst_axis;\n      dst_dir = dst_dir - dst_dir.dot(dst_axis) * dst_axis;\n\n      if (src_dir.squaredNorm() > MIN_SQLEN && dst_dir.squaredNorm() > MIN_SQLEN)\n      {\n        src_dir = src_dir.normalized();\n        dst_dir = dst_dir.normalized();\n\n        Vector3 src_perp = dst_axis.cross(src_dir);\n        Vector3 dst_perp = dst_axis.cross(dst_dir);\n\n        Matrix3 src_basis; src_basis << src_dir, src_perp, dst_axis;\n        Matrix3 dst_basis; dst_basis << dst_dir, dst_perp, dst_axis;\n        Matrix3 extra_rot = dst_basis * src_basis.transpose();  // inverse == tranpose for rotation matrices\n\n        rot = extra_rot * rot;\n      }\n\n      CoordinateFrame3 cf(RigidTransform3::_fromAffine(AffineTransform3(rot, dst_mean - rot * src_mean)));\n      // THEA_CONSOLE.nospace() << \"R = \" << toString(cf.getRotation()) << \", T = \" << toString(cf.getTranslation());\n\n      return RigidTransform3(cf);\n    }\n    else\n      return RigidTransform3::translation(dst_mean - src_mean);\n  }\n\n  // ICP algorithm of Arun et al. 1987.\n\n  size_t num_frames = src.size();\n  Vector3 src_mean = Vector3::Zero(), dst_mean = Vector3::Zero();\n  for (size_t i = 0; i < num_frames; ++i)\n  {\n    CoordinateFrame3 const & src_frame = src[i];\n    CoordinateFrame3 const & dst_frame = dst[i];\n\n    // THEA_CONSOLE.nospace() << \"src[\" << i << \"] = R: \" << toString(src_frame.getRotation()) << \", T: \"\n    //                    << toString(src_frame.getTranslation());\n    // THEA_CONSOLE.nospace() << \"dst[\" << i << \"] = R: \" << toString(dst_frame.getRotation()) << \", T: \"\n    //                    << toString(dst_frame.getTranslation());\n\n    src_mean += src_frame.getTranslation();\n    dst_mean += dst_frame.getTranslation();\n  }\n\n  src_mean /= num_frames;\n  dst_mean /= num_frames;\n\n  Matrix3 corr = Matrix3::Zero();\n  Vector3 src_pt, dst_pt;\n  for (size_t i = 0; i < num_frames; ++i)\n  {\n    CoordinateFrame3 const & src_frame = src[i];\n    CoordinateFrame3 const & dst_frame = dst[i];\n\n    src_pt = src_frame.getTranslation() - src_mean;\n    dst_pt = dst_frame.getTranslation() - dst_mean;\n\n    for (int r = 0; r < 3; ++r)\n      for (int c = 0; c < 3; ++c)\n        corr(r, c) += src_pt[r] * dst_pt[c];\n  }\n\n  Eigen::JacobiSVD<Matrix3> svd(corr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Matrix3 U_T = svd.matrixU().transpose();\n  Matrix3 V = svd.matrixV();\n  Matrix3 rotation = V * U_T;\n\n  if (rotation.determinant() < 0)\n  {\n    // FIXME: One of the columns (which?) of V should be negated. See Eggert et al. '97, \"Estimating 3D rigid transformations: a\n    // comparison of four major algorithms\".\n    //\n    // For now, we'll do the dumb but safe thing and test each option for the minimum error.\n\n    THEA_WARNING << \"Estimated rigid transform involves reflection, fixing by negating a column of V\";\n\n    Real min_sqerr = -1;\n    for (int i = 0; i < 3; ++i)\n    {\n      // Swap i'th column of V\n      Matrix3 V_i = V;\n      V_i(0, i) = -V_i(0, i);\n      V_i(1, i) = -V_i(1, i);\n      V_i(2, i) = -V_i(2, i);\n\n      Matrix3 candidate_rot = V_i * U_T;\n      Real sqerr = 0;\n      for (size_t j = 0; j < num_frames; ++j)\n      {\n        CoordinateFrame3 const & src_frame = src[j];\n        CoordinateFrame3 const & dst_frame = dst[j];\n\n        src_pt = src_frame.getTranslation() - src_mean;\n        dst_pt = dst_frame.getTranslation() - dst_mean;\n        sqerr += (candidate_rot * src_pt - dst_pt).squaredNorm();\n      }\n\n      if (min_sqerr < 0 || sqerr < min_sqerr)\n      {\n        rotation = candidate_rot;\n        min_sqerr = sqerr;\n      }\n    }\n  }\n\n  Vector3 translation = dst_mean - rotation * src_mean;\n\n  CoordinateFrame3 cf(RigidTransform3::_fromAffine(AffineTransform3(rotation, translation)));\n  // THEA_CONSOLE.nospace() << \"R = \" << toString(rotation) << \", T = \" << toString(translation);\n\n  return RigidTransform3(cf);\n}\n\nint\nbvhDepth(intx num_elems, int max_elems_in_leaf)\n{\n  alwaysAssertM(num_elems >= 0, \"Can't compute BVH depth for negative number of elements\");\n  alwaysAssertM(max_elems_in_leaf > 0, \"Can't compute BVH depth for non-positive number of elements at leaf\");\n\n  int max_depth = (num_elems > 0 ? (int)std::ceil(Math::fastLog2(num_elems / (double)max_elems_in_leaf)) : 0);\n  return max_depth;\n}\n\nvoid\ngetBarycentricCoordinates2(Real qx, Real qy, Real x0, Real y0, Real x1, Real y1, Real x2, Real y2,\n                           Real & bc0, Real & bc1, Real & bc2)\n{\n  Real a = y1 - y2;\n  Real b = x0 - x2;\n  Real c = y2 - y0;\n  Real d = x2 - x1;\n\n  Real det = a * b - c * d;\n  if (std::abs(det) < 1.0e-30f)\n    bc0 = bc1 = bc2 = 1.0f / 3;\n  else\n  {\n    Real qx_rel_3 = qx - x2;\n    Real qy_rel_3 = qy - y2;\n\n    bc0 = (a * qx_rel_3 + d * qy_rel_3) / det;\n    bc1 = (c * qx_rel_3 + b * qy_rel_3) / det;\n    bc2 = 1 - bc0 - bc1;\n  }\n}\n\nvoid\ngetBarycentricCoordinates2(Vector2 const & q, Vector2 const & v0, Vector2 const & v1, Vector2 const & v2,\n                           Real & bc0, Real & bc1, Real & bc2)\n{\n  getBarycentricCoordinates2(q.x(), q.y(), v0.x(), v0.y(), v1.x(), v1.y(), v2.x(), v2.y(), bc0, bc1, bc2);\n}\n\nvoid\ngetBarycentricCoordinates3(Vector3 const & q, Vector3 const & v0, Vector3 const & v1, Vector3 const & v2,\n                           Real & bc0, Real & bc1, Real & bc2)\n{\n  switch (Math::maxAbsAxis((v1 - v0).cross(v2 - v0)))\n  {\n    case 0:           getBarycentricCoordinates2(q.tail<2>(), v0.tail<2>(), v1.tail<2>(), v2.tail<2>(), bc0, bc1, bc2); break;\n    case 1:           getBarycentricCoordinates2(Vector2( q[0],  q[2]),\n                                                 Vector2(v0[0], v0[2]),\n                                                 Vector2(v1[0], v1[2]),\n                                                 Vector2(v2[0], v2[2]), bc0, bc1, bc2); break;\n    default /* 2 */:  getBarycentricCoordinates2(q.head<2>(), v0.head<2>(), v1.head<2>(), v2.head<2>(), bc0, bc1, bc2);\n  }\n}\n\nVector3\ntriRandomPoint(Vector3 const & v0, Vector3 const & v1, Vector3 const & v2)\n{\n  return triRandomPointFromEdges(v0, v1 - v0, v2 - v0);\n}\n\nVector3\ntriRandomPointFromEdges(Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02)\n{\n  // From G3D::Triangle\n\n  // Choose a random point in the parallelogram\n\n  float s = Random::common().uniform01();\n  float t = Random::common().uniform01();\n\n  if (t > 1.0f - s)\n  {\n    // Outside the triangle; reflect about the diagonal of the parallelogram\n    t = 1.0f - t;\n    s = 1.0f - s;\n  }\n\n  return s * edge01 + t * edge02 + v0;\n}\n\nVector3\nquadRandomPoint(Vector3 const & v0, Vector3 const & v1, Vector3 const & v2, Vector3 const & v3)\n{\n  Vector3 edge01 = v1 - v0;\n  Vector3 edge03 = v3 - v0;\n  Vector3 edge21 = v1 - v2;\n  Vector3 edge23 = v3 - v2;\n\n  Real tri0_double_area = edge01.cross(edge03).norm();\n  Real tri1_double_area = edge21.cross(edge23).norm();\n\n  float tri = Random::common().uniform(0, tri0_double_area + tri1_double_area);\n  if (tri <= tri0_double_area)\n    return triRandomPointFromEdges(v0, edge01, edge03);\n  else\n    return triRandomPointFromEdges(v2, edge21, edge23);\n}\n\nReal\nraySphereIntersectionTime(Ray3 const & ray, Vector3 const & center, Real radius)\n{\n  Vector3 pmc = ray.getOrigin() - center;\n\n  double s[3];\n  s[2] = ray.getDirection().squaredNorm();\n  s[1] = 2 * pmc.dot(ray.getDirection());\n  s[0] = pmc.squaredNorm() - radius * radius;\n\n  double roots[2];\n  int num_roots = Math::solveQuadratic(s[0], s[1], s[2], roots);\n\n  double min_root = -1;\n  for (int i = 0; i < num_roots; ++i)\n    if (roots[i] >= 0 && (min_root < 0 || roots[i] < min_root))\n      min_root = roots[i];\n\n#if 0\n  if (min_root >= 0)\n    THEA_CONSOLE << \"min_root =\" << min_root;\n#endif\n\n  return (Real)min_root;\n}\n\nReal\nrayTorusIntersectionTime(Ray3 const & ray, Real torus_radius, Real torus_width)\n{\n  double r2pw2 = torus_radius * torus_radius + torus_width * torus_width;\n  double r2mw2 = r2pw2 - 2 * torus_width * torus_width;\n\n  Vector3 p2 = ray.getOrigin().cwiseProduct(ray.getOrigin());\n  Vector3 pu = ray.getOrigin().cwiseProduct(ray.getDirection());\n  Vector3 u2 = ray.getDirection().cwiseProduct(ray.getDirection());\n\n  double s[5];\n  s[4] = u2[0] * (u2[0] + 2 * u2[1]) + u2[1] * (u2[1] + 2 * u2[2]) + u2[2] * (u2[2] + 2 * u2[0]);\n  s[3] = 4 * (pu[0] + pu[1] + pu[2]) * (u2[0] + u2[1] + u2[2]);\n  s[2] = 2 * (r2mw2 * u2[2] - r2pw2 * (u2[0] + u2[1]))\n       + 8 * (pu[0] * pu[1] + pu[1] * pu[2] + pu[2] * pu[0])\n       + 6 * (pu[0] * pu[0] + pu[1] * pu[1] + pu[2] * pu[2])\n       + 2 * (p2[0] * (u2[1] + u2[2]) + p2[1] * (u2[2] + u2[0]) + p2[2] * (u2[0] + u2[1]));\n  s[1] = 4 * (r2mw2 * pu[2] - r2pw2 * (pu[0] + pu[1]) + (p2[0] + p2[1] + p2[2]) * (pu[0] + pu[1] + pu[2]));\n  s[0] = 2 * (r2mw2 * p2[2] - r2pw2 * (p2[0] + p2[1]) + p2[0] * p2[1] + p2[1] * p2[2] + p2[2] * p2[0])\n       + p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2] + r2mw2 * r2mw2;\n\n  double roots[4];\n  int num_roots = Math::solveQuartic(s[0], s[1], s[2], s[3], s[4], roots);\n\n  double min_root = -1;\n  for (int i = 0; i < num_roots; ++i)\n    if (roots[i] >= 0 && (min_root < 0 || roots[i] < min_root))\n      min_root = roots[i];\n\n#if 0\n  if (min_root >= 0)\n    THEA_CONSOLE << \"min_root =\" << min_root;\n#endif\n\n  return (Real)min_root;\n}\n\n} // namespace Browse3D\n", "meta": {"hexsha": "a7f9e77989399457beae9a2e313d3f0326b2cfb3", "size": 19503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 32.4509151414, "max_line_length": 128, "alphanum_fraction": 0.583397426, "num_tokens": 6433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6690530293862523}}
{"text": "#include \"matmult_impl.h\"\n\n#include <Eigen/Dense>\n\nusing Eigen::Index;\nusing Eigen::MatrixXd;\nusing grpc::StatusCode;\n\nStatus MatrixProductAPIImpl::Multiply(ServerContext* context,\n                                      const MultiplyRequest* request,\n                                      MultiplyResponse* response) {\n  const auto& mplier = request->multiplier();\n  const int mplier_columns_size = mplier.columns_size();\n  const int mplier_rows_size = mplier.columns(0).coefficients_size();\n  const auto& mplicand = request->multiplicand();\n  const int mplicand_columns_size = mplicand.columns_size();\n  const int mplicand_rows_size = mplicand.columns(0).coefficients_size();\n\n  if (mplier_columns_size != mplicand_rows_size) {  // very shallow validation\n    return Status(StatusCode::OUT_OF_RANGE, \"1-factor cols != 2-factor rows\");\n  }\n\n  MatrixXd mplier_eigen(mplier_rows_size, mplier_columns_size);\n  for (int i = 0; i != mplier_columns_size; ++i) {\n    for (int j = 0; j != mplier_rows_size; ++j) {\n      mplier_eigen(j, i) = mplier.columns(i).coefficients(j);\n    }\n  }\n  MatrixXd mplicand_eigen(mplicand_rows_size, mplicand_columns_size);\n  for (int i = 0; i != mplicand_columns_size; ++i) {\n    for (int j = 0; j != mplicand_rows_size; ++j) {\n      mplicand_eigen(j, i) = mplicand.columns(i).coefficients(j);\n    }\n  }\n\n  MatrixXd result_eigen = mplier_eigen * mplicand_eigen;\n\n  auto response_result = response->mutable_result();\n  for (Index ic = 0, ec = result_eigen.cols(); ec != ic; ++ic) {\n    auto response_result_column = response_result->add_columns();\n    for (Index ir = 0, er = result_eigen.rows(); er != ir; ++ir) {\n      response_result_column->add_coefficients(result_eigen(ir, ic));\n    }\n  }\n\n  return Status::OK;\n}\n", "meta": {"hexsha": "8eb679a82b4c4ca095cfe8d72b57f7163eef9327", "size": 1743, "ext": "cc", "lang": "C++", "max_stars_repo_path": "server/src/matmult_impl.cc", "max_stars_repo_name": "amwolff/2-lg-mats-bench", "max_stars_repo_head_hexsha": "cb3cdfd84d93d98fe12cb03a271632014cd662ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "server/src/matmult_impl.cc", "max_issues_repo_name": "amwolff/2-lg-mats-bench", "max_issues_repo_head_hexsha": "cb3cdfd84d93d98fe12cb03a271632014cd662ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T16:58:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T11:43:55.000Z", "max_forks_repo_path": "server/src/matmult_impl.cc", "max_forks_repo_name": "amwolff/2-lg-mats-bench", "max_forks_repo_head_hexsha": "cb3cdfd84d93d98fe12cb03a271632014cd662ec", "max_forks_repo_licenses": ["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.3125, "max_line_length": 78, "alphanum_fraction": 0.6764199656, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6690530218978864}}
{"text": "/**\n * Discrete time LQR controller implementation\n * @author: Haoguang Yang\n * @date: 09-27-2021\n * \n * Copyright (c) 2021-2022, Haoguang Yang\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    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 from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef _DLQR_H_\n#define _DLQR_H_\n\n#include <utility>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/LU>\n#include <eigen3/Eigen/Eigenvalues>\n//#include <armadillo>\n\nnamespace control\n{\n  /// @class dLQR\n  /// @brief A discrete time LQR controller class. The LQR controller minimizes the Hinf control cost,\n  /// as defined by: J = \\sum_t[(Xd(t)-X(t))'Q(Xd(t)-X(t)) + u(t)'Ru(t) + 2*(Xd(t)-X(t))'Nu(t)].\n  class dLQR\n  {\n  public:\n    /// @brief Constructor\n    /// @param[in] K is the LQR gain matrix for u=K(Xd-X), which drives X to Xd.\n    dLQR(const Eigen::MatrixXd& K);\n\n    /// @brief Constructor using system x[n+1]=Ax[n]+Bu[n]\n    /// @param[in] A specifies the discrete-time state space equation.\n    /// @param[in] B specifies the discrete-time state space equation.\n    /// @param[in] Q specifies the state space error penalty.\n    /// @param[in] R specifies the control effort penalty.\n    /// @param[in] N specifies the error-effort cross penalty.\n    /// @param[in] dt specifies the control interval.\n    dLQR(const Eigen::MatrixXd& A,\n         const Eigen::MatrixXd& B,\n         const Eigen::MatrixXd& Q,\n         const Eigen::MatrixXd& R,\n         const Eigen::MatrixXd& N);\n\n    dLQR(){};\n\n    ~dLQR(){ initialized = false; };\n\n    /// @brief Calculate the ARE solution given A, B, Q, R, N matrices. This algorithm is based\n    /// on the work of https://github.com/TakaHoribe/Riccati_Solver/ and W. F. Arnold and A. J. Laub, \n    /// \"Generalized eigenproblem algorithms and software for algebraic Riccati equations,\" in \n    /// Proceedings of the IEEE, vol. 72, no. 12, pp. 1746-1754, Dec. 1984, doi: 10.1109/PROC.1984.13083.\n    /// The DARE solver is based on: https://github.com/arunabh1904/LQR-ROS/blob/master/lqr_obsavoid/src/are_solver.cpp\n    /// The WIP DARE solver with N term used is based on: https://github.com/scipy/scipy/blob/v1.7.1/scipy/linalg/_solvers.py#L529-L734\n    Eigen::MatrixXd care(const Eigen::MatrixXd& A,\n                          const Eigen::MatrixXd& B,\n                          const Eigen::MatrixXd& Q,\n                          const Eigen::MatrixXd& R,\n                          const Eigen::MatrixXd& N);\n\n    Eigen::MatrixXd dare(const Eigen::MatrixXd& A,\n                          const Eigen::MatrixXd& B,\n                          const Eigen::MatrixXd& Q,\n                          const Eigen::MatrixXd& R,\n                          const Eigen::MatrixXd& N);\n\n    /// @brief Input the current states and desired states, output the control values\n    /// @param X is the most recently state space\n    /// @param Xd is the most recently desired state space\n    /// @return the control value from the LQR algorithm\n    const Eigen::VectorXd& calculateControl(const Eigen::VectorXd& X, const Eigen::VectorXd& Xd);\n    \n    void balance_matrix(const Eigen::MatrixXd &A, Eigen::MatrixXd &Aprime, Eigen::VectorXd &D);\n\n    /// @brief Get the current LQR gain.\n    /// @return The current K matrix.\n    inline const Eigen::MatrixXd& getK() const { return K_; };\n\n    /// @brief Get the current value of the control error\n    inline const Eigen::VectorXd& CurrentError() const { return e_; };\n\n    /// @brief Get the current control value (calculated based on most recent errors)\n    /// @return the current control value\n    inline const Eigen::VectorXd& CurrentControl() const { return u_; };\n    inline bool isInitialized() const { return initialized; };\n    \n  private:\n    /// @brief is initialized\n    bool initialized = false;\n\n    /// @brief LQR gain.\n    Eigen::MatrixXd K_;\n\n    /// @brief Current state space error used in LQR control algorithm\n    Eigen::VectorXd e_;\n\n    /// @brief Current control value\n    Eigen::VectorXd u_;\n\n  }; // End class dLQR\n\n} // End namespace control\n\n#endif", "meta": {"hexsha": "4d2038ac278ee1a47f50bd91f3b2a70cd33084ea", "size": 5448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/LQR.hpp", "max_stars_repo_name": "HaoguangYang/lqgController", "max_stars_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "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/LQR.hpp", "max_issues_repo_name": "HaoguangYang/lqgController", "max_issues_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "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/LQR.hpp", "max_forks_repo_name": "HaoguangYang/lqgController", "max_forks_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "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": 42.5625, "max_line_length": 135, "alphanum_fraction": 0.6749265786, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6690458544585989}}
{"text": "#ifndef INTEGRALS_HPP_\n#define INTEGRALS_HPP_\n/**\n * @file integrals.hpp\n * @author Adam Lamson\n * @brief Probility Density Function integrals for KMC algorithm. Used to create\n * lookup tables\n * @version 0.1\n * @date 2019-04-15\n *\n * @copyright Copyright (c) 2019\n *\n */\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n/*! \\brief Integrate exponential factor with the form of\n * e^{-M * (\\sqrt{ s^2 + lm^2}-ell0 -1)^2}\n * from sbound0 to sbound1  with respect to the variable s.\n *\n * \\param lm Physically, this is the perpendicular distance above rod\n * \\param sbound lowerr limit of integral\n * \\param sbound Upper limit of integral\n * \\param M exponential constant factor. Physically, this is the product of\n (1-load_sensitivity)*spring_const/(k_B * Temperature)\n * \\param ell0 Shift of the integrands mean. Physically, protein rest length\n * \\return result The value of the integration\n\n */\ninline double integral(double lm, double sbound0, double sbound1, double M,\n                       double ell0) {\n    if (sbound0 >= sbound1) {\n        return 0;\n    }\n    auto integrand = [&](double s) {\n        // lambda capture variabls ell0 and M\n        const double exponent = sqrt(s * s + lm * lm) - ell0 - 1;\n        return exp(-M * exponent * exponent);\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, sbound0, sbound1, 10, 1e-6, &error);\n    return result;\n}\n\n#endif /* INTEGRALS_HPP_ */\n", "meta": {"hexsha": "c2e1695d2e32149961f57a424b25a2fda8e6ae3f", "size": 1570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KMC/integrals.hpp", "max_stars_repo_name": "jeffmm/KMC", "max_stars_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KMC/integrals.hpp", "max_issues_repo_name": "jeffmm/KMC", "max_issues_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMC/integrals.hpp", "max_forks_repo_name": "jeffmm/KMC", "max_forks_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_forks_repo_licenses": ["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.1923076923, "max_line_length": 80, "alphanum_fraction": 0.6700636943, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6689148123345399}}
{"text": "#include <math.h>\r\n#include <cmath>\r\n//#include <RcppEigen.h>\r\n#include <RcppArmadillo.h>\r\n//#include <iostream>\r\n//#include <vector>\r\n//#include <Eigen/Core>\r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::depends(RcppEigen)]]\r\n\r\ntypedef Eigen::Triplet<float> T; //tripleta para rellenar matrices sparse\r\ntypedef Eigen::MappedSparseMatrix<float> MSpMat; //alias para matriz sparse\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorXd; //alias para vector sparse\r\nusing namespace Rcpp;\r\n//using namespace RcppArmadillo;\r\n\r\n// [[Rcpp::export]]\r\nfloat KernelGauss (arma::cube x, arma::cube y, int dimension, double sigJ, double sigd, float distancia)\r\n{\r\n  //Calculo individual del kernel entre dos observaciones\r\n  // input: x observaciones\r\n  //        y observaciones\r\n  // dimension: numero de canales\r\n  //sigJ: sd de la imagen\r\n  //sigd: sd de la posicion\r\n  //distancia: distancia L_2 entre los dos pixeles\r\n  float kernel_value = 0;\r\n  float siJ = (float)sigJ;\r\n  float sid = (float)sigd;\r\n  for (int i = 0; i < dimension; i++ )\r\n  {\r\n    kernel_value +=(float)pow( (float)(x[i] - y[i]),2);\r\n  }\r\n  kernel_value = exp(-(kernel_value/(2*pow(siJ,2)) ) - distancia/(2*pow(sid, 2)));\r\n  return( kernel_value );\r\n}\r\n\r\n\r\n  \r\n// [[Rcpp::export]]\r\nEigen::SparseMatrix<float> Kernel_RGB ( arma::cube  M, int h, int w, double distancia, double sigJ, double sigd, int dimension)\r\n{\r\n  // Funcion para calcular  la matriz de similaridades de todos los puntos de una imagen \r\n  //  input: w: altura en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n  //         h: ancho en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n  //         distancia: limite de la vecindad del pixel a considerar\r\n  //         M: imagen de 'dimension' dimensiones (numero de canales)\r\n  //         sigJ: sigma para kernel gaussiano, de la imagen\r\n  //         sigd: sigma para kernell gaussiano, de las distancias\r\n  //         dimension: numero de canales\r\n  //output: W, similaridad calculada \r\n  int i, j, k, l = 0 ;\r\n  float vecindad = distancia;\r\n  float d2 = 0.;\r\n  float calculo = 0.;\r\n  std::vector<T> tripletList; //inicializamos tripleta\r\n  tripletList.reserve((int)floor(h*h*w*w*.1));\r\n  \r\n  //comienza calculo de matriz de similaridades\r\n  for(i=0; i < h; i++)\r\n  {\r\n    for(j=0; j< w; j++ )\r\n    {\r\n      for(k=0; k<h; k++)\r\n      {\r\n        for(l=0; l<w; l++)\r\n        {\r\n          d2 = (float)(pow(i-k,2)+pow(j-l,2));\r\n          if(d2 <= vecindad)\r\n          {\r\n            calculo = KernelGauss( M.tube(j,i), M.tube(l, k), dimension, sigJ, sigd,  vecindad);\r\n            tripletList.push_back(T((j)*h+i, (l)*h+k, calculo ));\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n  //termina calculo de matriz de similaridades\r\n  Eigen::SparseMatrix<float>  W(h*w, h*w); //construccion de matriz de similaridades\r\n  W.setFromTriplets(tripletList.begin(), tripletList.end());\r\n  return(W);\r\n}\r\n\r\n\r\n\r\n// [[Rcpp::export]]\r\nEigen::SparseMatrix<float> Kernel_float ( NumericMatrix M, int h, int w, double distancia, double sigJ, double sigd)\r\n{\r\n  // Funcion para calcular  la matriz de similaridades de todos los puntos de una imagen \r\n  //  input: w: altura en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n  //         h: ancho en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n  //         distancia: limite de la vecindad del pixel a considerar\r\n  //         M: imagen de 2 dimensiones (EN ESCALA DE GRISES)\r\n  //         sigJ: sigma para kernel gaussiano, de la imagen\r\n  //         sigd: sigma para kernell gaussiano, de las distancias\r\n  //output: W, similaridad calculada, sparse \r\n  int i, j, k, l = 0 ;\r\n  float vecindad = (float)distancia;\r\n  float d2 = 0.;\r\n  float calculo = 0.;\r\n  std::vector<T> tripletList; //inicializamos tripleta\r\n  tripletList.reserve((int)(h*h*w*w*.1));\r\n  //comienza calculo de matriz de similaridades\r\n  for(i=0; i < h; i++)\r\n  {\r\n    for(j=0; j< w; j++ )\r\n    {\r\n      for(k=0; k<h; k++)\r\n      {\r\n        for(l=0; l<w; l++)\r\n        {\r\n          d2 = (float)(pow(i-k,2)+pow(j-l,2));\r\n          if(d2 <= vecindad)\r\n          {\r\n            calculo = (float) (exp(-pow(M(j,i)-M(l,k),2)/(2*pow(sigJ,2))-d2/(2*pow(sigd,2))));\r\n            tripletList.push_back(T((j)*h+i, (l)*h+k, calculo ));\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n  //termina calculo de matriz de similaridades\r\n  Eigen::SparseMatrix<float>  W(h*w, h*w); //construccion de matriz de similaridades\r\n  W.setFromTriplets(tripletList.begin(), tripletList.end());\r\n  return(W);\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "c41a26c351a2406e965ad04af49b6e7e6c9d215c", "size": 4536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_stars_repo_name": "fou-foo/MCE", "max_stars_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_issues_repo_name": "fou-foo/MCE", "max_issues_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_forks_repo_name": "fou-foo/MCE", "max_forks_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_forks_repo_licenses": ["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.8923076923, "max_line_length": 128, "alphanum_fraction": 0.6071428571, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6688461863835468}}
{"text": "#include \"iris/geometry.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <iostream>\n#include \"iris_cdd.h\"\n\nnamespace iris {\n\nint factorial(int n) {\n  return n == 0 ? 1 : factorial(n - 1) * n;\n}\n\ndouble nSphereVolume(int dim, double radius) {\n  double v;\n  int k = std::floor(dim / 2);\n  if (dim % 2 == 0) {\n    v = std::pow(M_PI, k) / static_cast<double>(factorial(k));\n  } else {\n    v = (2.0 * factorial(k) * std::pow(4 * M_PI, k)) / static_cast<double>(factorial(2 * k + 1));\n  }\n  return v * std::pow(radius, dim);\n}\n\nEllipsoid::Ellipsoid(int dim) :\n  C_(Eigen::MatrixXd(dim, dim)),\n  d_(Eigen::VectorXd(dim)) {}\nEllipsoid::Ellipsoid(Eigen::MatrixXd C, Eigen::VectorXd d):\n  C_(C),\n  d_(d) {}\nconst Eigen::MatrixXd& Ellipsoid::getC() const {\n  return C_;\n}\nconst Eigen::VectorXd& Ellipsoid::getD() const {\n  return d_;\n}\nvoid Ellipsoid::setC(const Eigen::MatrixXd &C) {\n  C_ = C;\n}\nvoid Ellipsoid::setCEntry(Eigen::DenseIndex row, \n                          Eigen::DenseIndex col, double value) {\n  C_(row, col) = value;\n}\nvoid Ellipsoid::setD(const Eigen::VectorXd &d) {\n  d_ = d;\n}\nvoid Ellipsoid::setDEntry(Eigen::DenseIndex index, double value) {\n  d_(index) = value;\n}\nint Ellipsoid::getDimension() const {\n  return C_.cols();\n}\ndouble Ellipsoid::getVolume() const {\n  return C_.determinant() * nSphereVolume(this->getDimension(), 1.0);\n}\nEllipsoid Ellipsoid::fromNSphere(Eigen::VectorXd &center, double radius) {\n  const int dim = center.size();\n  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim, dim);\n  C.diagonal().setConstant(radius);\n  Ellipsoid ellipsoid(C, center);\n  return ellipsoid;\n}\n\nPolyhedron::Polyhedron(int dim):\n  A_(0, dim),\n  b_(0, 1),\n  dd_representation_dirty_(true) {}\nPolyhedron::Polyhedron(Eigen::MatrixXd A, Eigen::VectorXd b):\n    A_(A),\n    b_(b),\n    dd_representation_dirty_(true) {}\nvoid Polyhedron::setA(const Eigen::MatrixXd &A) {\n  A_ = A;\n  dd_representation_dirty_ = true;\n}\nconst Eigen::MatrixXd& Polyhedron::getA() const {\n  return A_;\n}\nvoid Polyhedron::setB(const Eigen::VectorXd &b) {\n  b_ = b;\n  dd_representation_dirty_ = true;\n}\nconst Eigen::VectorXd& Polyhedron::getB() const {\n  return b_;\n}\nint Polyhedron::getDimension() const {\n  return A_.cols();\n}\nint Polyhedron::getNumberOfConstraints() const {\n  return A_.rows();\n}\nvoid Polyhedron::appendConstraints(const Polyhedron &other) {\n  A_.conservativeResize(A_.rows() + other.getA().rows(), A_.cols());\n  A_.bottomRows(other.getA().rows()) = other.getA();\n  b_.conservativeResize(b_.rows() + other.getB().rows());\n  b_.tail(other.getB().rows()) = other.getB();\n  dd_representation_dirty_ = true;\n}\nvoid Polyhedron::updateDDRepresentation() {\n  generator_points_.clear();\n  generator_rays_.clear();\n  getGenerators(A_, b_, generator_points_, generator_rays_);\n  dd_representation_dirty_ = false;\n}\nstd::vector<Eigen::VectorXd> Polyhedron::generatorPoints() {\n  if (dd_representation_dirty_) {\n    updateDDRepresentation();\n  }\n  return generator_points_;\n}\nstd::vector<Eigen::VectorXd> Polyhedron::generatorRays() {\n  if (dd_representation_dirty_) {\n    updateDDRepresentation();\n  }\n  return generator_rays_;\n}\nbool Polyhedron::contains(Eigen::VectorXd point, double tolerance) {\n  return (A_ * point - b_).maxCoeff() <= tolerance;\n}\n\n}", "meta": {"hexsha": "6190849ec95ad832207ec3879332de6364beca37", "size": 3246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cxx/geometry.cpp", "max_stars_repo_name": "tardani95/iris-distro", "max_stars_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T15:32:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:03:08.000Z", "max_issues_repo_path": "src/cxx/geometry.cpp", "max_issues_repo_name": "tardani95/iris-distro", "max_issues_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T16:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:47:52.000Z", "max_forks_repo_path": "src/cxx/geometry.cpp", "max_forks_repo_name": "tardani95/iris-distro", "max_forks_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 61.0, "max_forks_repo_forks_event_min_datetime": "2015-03-20T18:49:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:35:38.000Z", "avg_line_length": 27.05, "max_line_length": 97, "alphanum_fraction": 0.6823783118, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6688326171154351}}
{"text": "/**\n * Kalman Filter \n * Skeleton code for teaching \n * A3M33MKR\n * Czech Technical University \n * Faculty of Electrical Engineering\n * Intelligent and Mobile Robotics group\n *\n * Authors: Zden\u011bk Kasl, Karel Ko\u0161nar kosnar@labe.felk.cvut.cz\n *\n * this code is inspired by tutorial on Kalman Filter by Greg Czerniak \n *\n * Licence: MIT (see LICENSE file)\n **/\n\n#include<cmath>\n#include<cassert>\n#include<cstdlib>\n#include<fstream>\n#include<iostream>\n#include <Eigen/Dense>\n\n#include \"gui/gui.h\"\n#include \"systemSimulator/system.h\"\nusing namespace imr;\nusing namespace gui;\nusing namespace Eigen;\n\nPoint KalmanFilter(Point measuredPosition);\n\n//    float v0 = 149;\n//    float alpha = (float) (M_PI / 4 - 0.007);\n    float v0 = 150;\n    float alpha = (float) (M_PI / 4);\n    float dt = 0.1;\n    float g = (float) (9.8 * dt);\n\n    Matrix4f A,R,Sigma;\n    Matrix<float,4,1> B;\n    Matrix2f Q;\n    Matrix<float,2,4> C;\n    Vector4f X;\n\n\n\nvoid help(char** argv)\n{\n    std::cout << \"\\nUsage of the program \" << argv[0]+2 << std::endl\n         << \"Parameter [-h or -H] displays this message.\" <<std::endl\n\t << \" Parameter [-n or -N] number of simulation steps.\"\n         << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n    A <<    1,0,dt,0,\n            0,1,0,dt,\n            0,0,1,0,\n            0,0,0,1;\n    B <<    0,\n            0,\n            0,\n            -1;\n    C <<    1,0,0,0,\n            0,1,0,0;\n    X <<   0,\n            0,\n            cos(alpha) * v0,\n            sin(alpha) * v0;\n    R <<    3,0,0,0,\n            0,3,0,0,\n            0,0,3,0,\n            0,0,0,3;\n    Q <<    50,0,\n            0,50;\n    Sigma << 1,0,0,0,\n            0,1,0,0,\n            0,0,1,0,\n            0,0,0,1;\n\n    int nSteps = 1000;\n    char *dataFile;\n\n    // Parse all console parameters\n    for (int i=0; i<argc; i++) {\n        if (argv[i][0]=='-') {\n            switch(argv[i][1]) {\n                //> HELP\n                case 'H' : case 'h' :\n                    help(argv);\n                    break;\n\t\tcase 'N': case 'n':\n                    assert(i+1 < argc);\n                    assert(atoi(argv[i+1])>1);\n                    nSteps = atoi(argv[i+1]);\n\t\t    break;\n                default :\n                    std::cout << \"Parameter \\033[1;31m\" << argv[i] << \"\\033[0m is not valid!\\n\"\n                        << \"Use parameter -h or -H for help.\" << std::endl;\n                    break;\n            }\n        }\n    }\n    // All parameters parsed\n\n    Gui gui;\n    System system;\n    \n    //> comment line below in order to let the program\n    //> continue right away\n//    gui.startInteractor();\n\n    Point measurement;\n    Point truth;\n    Point kfPosition;\n\n    for(int i=1; i<nSteps; i++) {\n       system.makeStep();\n       truth = system.getTruthPosition();\n       measurement = system.getMeasurement();\n       kfPosition = KalmanFilter(measurement);\n       gui.setPoints(truth, measurement, kfPosition);\n\n       //> comment line below in order to let the program\n       //> continue right away\n       if (i%40 == 0) gui.startInteractor();\n    \n    }\n    gui.startInteractor();\n\n    return EXIT_SUCCESS;\n}\n\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n//                               implement Kalman Filter here\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\nPoint  KalmanFilter(const Point measuredPosition)\n{\n    Point ret;\n    Vector2f Z;\n    Z <<    measuredPosition.x,\n            measuredPosition.y;\n    Matrix<float,4,1> input = g * B;\n    Vector4f X_ = A * X + input;\n    Matrix4f Sigma_ = A * Sigma * A.transpose() + R;\n    Matrix<float,4,2> K =  Sigma_ * C.transpose() * (C * Sigma_ * C.transpose() + Q).inverse();\n    X = X_ + 1*K * (Z - C * X_);\n\n    ret.x = X(0);\n    ret.y = X(1);\n    return ret;\n}\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n\n", "meta": {"hexsha": "a47052ebe3148cf2bc65510dc45f30ef3ae9c2e2", "size": 3974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kf_main.cpp", "max_stars_repo_name": "kralma/mkr_kf", "max_stars_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kf_main.cpp", "max_issues_repo_name": "kralma/mkr_kf", "max_issues_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kf_main.cpp", "max_forks_repo_name": "kralma/mkr_kf", "max_forks_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_forks_repo_licenses": ["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.5308641975, "max_line_length": 95, "alphanum_fraction": 0.4632611978, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6688326121796766}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of square lattice Ising model\n\n#pragma once\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <standards/simpson.hpp>\n\nnamespace ising {\nnamespace free_energy {\nnamespace square {\n\nnamespace {\n\ntemplate<typename T, typename FVAR>\nstruct functor {\n  functor(T Jx, T Jy, FVAR beta) {\n    using std::cosh; using std::sinh;\n    c_ = 1 / (2 * boost::math::constants::pi<T>());\n    chab_ = cosh(2 * beta * Jx) * cosh(2 * beta * Jy);\n    k_ = 1.0 / (sinh(2 * beta * Jx) * sinh(2 * beta * Jy));\n  }\n  FVAR operator()(T t) const {\n    using std::cos; using std::log; using std::sqrt;\n    return c_ * log(chab_ + sqrt(1 + k_ * k_ - 2 * k_ * cos(2 * t)) / k_);\n  }\n  T c_;\n  FVAR chab_, k_;\n};\n\ntemplate<typename T, typename FVAR>\nfunctor<T, FVAR> func(T Jx, T Jy, FVAR beta) { return functor<T, FVAR>(Jx, Jy, beta); }\n  \n}\n\ntemplate<typename T>\ninline std::tuple<T, T, T> infinite(T Jx, T Jy, T beta) {\n  typedef T real_t;\n  using std::log;\n  if (Jx <= 0 || Jy <= 0) throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n  if (beta <= 0) throw(std::invalid_argument(\"beta should be positive\"));\n  const real_t pi = boost::math::constants::pi<real_t>();\n  auto beta_fvar = boost::math::differentiation::make_fvar<real_t, 2>(beta);\n  auto logZ = log(real_t(2)) / 2 + standards::simpson_1d(func(Jx, Jy, beta_fvar), real_t(0), pi, 8);\n  real_t d2 = logZ.derivative(2);\n  for (unsigned long n = 16; n < 1024; n *= 2) {\n    logZ = log(real_t(2)) / 2 + standards::simpson_1d(func(Jx, Jy, beta_fvar), real_t(0), pi, n);\n    if (beta * beta * abs((logZ.derivative(2) - d2) / logZ.derivative(0)) <\n        2 * std::numeric_limits<real_t>::epsilon()) break;\n    d2 = logZ.derivative(2);\n  }\n  real_t free_energy = - logZ.derivative(0) / beta;\n  real_t energy = - logZ.derivative(1);\n  real_t specific_heat = beta * beta * logZ.derivative(2);\n  return std::make_tuple(free_energy, energy, specific_heat);\n}\n\ntemplate<typename I, typename T>\ninline std::tuple<T, T, T> finite(I Lx, I Ly, T Jx, T Jy, T beta) {\n  typedef T real_t;\n  using std::exp; using std::log;\n  if (Lx <= 0 || Ly <= 0) throw(std::invalid_argument(\"Lx and Ly should be positive\"));\n  if (Jx <= 0 || Jy <= 0) throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n  if (beta <= 0) throw(std::invalid_argument(\"beta should be positive\"));\n  const real_t pi = boost::math::constants::pi<real_t>();\n  auto beta_fvar = boost::math::differentiation::make_fvar<real_t, 2>(beta);\n  auto a = beta_fvar * Jx;\n  auto b = beta_fvar * Jy;\n  decltype(beta_fvar) lp0(0), lp1(0), lp2(0), lp3(0);\n  for (std::size_t k = 0; k < 2 * Lx; ++k) {\n    auto cosh_g = (cosh(2*a) * cosh(2*b) - cos(pi * k / Lx) * sinh(2*b)) / sinh(2*a);\n    auto gamma_abs = log(cosh_g + sqrt(cosh_g * cosh_g - 1));\n    if ((k & 1) == 1) {\n      lp0 += (Ly * gamma_abs/2) + log(1 + exp(-(Ly*gamma_abs)));\n      lp1 += (Ly * gamma_abs/2) + log(1 - exp(-(Ly*gamma_abs)));\n    } else {\n      lp2 += (Ly * gamma_abs/2) + log(1 + exp(-(Ly*gamma_abs)));\n      lp3 += (Ly * gamma_abs/2) + log(1 - exp(-(Ly*gamma_abs)));\n    }\n  }\n  auto logZ = -log(real_t(2)) / (Lx * Ly) + a + real_t(1)/2 * log(1 - exp(-4*a));\n  if (sinh(2*a) * sinh(2*b) < real_t(1)) {\n    logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) - exp(lp3-lp0))) / (Lx * Ly);\n  } else {\n    logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) + exp(lp3-lp0))) / (Lx * Ly);\n  }\n  real_t free_energy = - logZ.derivative(0) / beta;\n  real_t energy = - logZ.derivative(1);\n  real_t specific_heat = beta * beta * logZ.derivative(2);\n  return std::make_tuple(free_energy, energy, specific_heat);\n}\n\n} // end namespace square\n} // end namespace free_energy\n} // end namespace ising\n", "meta": {"hexsha": "03710c13e206a33640875d107286bd30b424b9b2", "size": 4417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square_count.hpp", "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_count.hpp", "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_count.hpp", "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": 38.7456140351, "max_line_length": 100, "alphanum_fraction": 0.6359520036, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6688326029420584}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n////////////////////////////////////////////////////////////////////////////////\n/// @file\n/// Solution of the Euler Problem #3\n/// (<a href=\"https://projecteuler.net/problem=3\" target=_blank>link</a>).\n////////////////////////////////////////////////////////////////////////////////\n\n#include <stapl/utility/do_once.hpp>\n#include <stapl/array.hpp>\n#include <stapl/algorithm.hpp>\n#include <boost/lexical_cast.hpp>\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Returns truncated integer square root of given number.\n/// @tparam IntType Integral type of the number.\n////////////////////////////////////////////////////////////////////////////////\ntemplate <typename IntType>\ninline IntType sqrt_int(IntType n)\n{\n  return static_cast<IntType>( std::sqrt(n) );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Functor that returns the larger of @p n and @p x/n that is both a\n///        factor of @p x and a prime number (0 if neither satisfies these\n///        conditions).\n/// @tparam IntType Integral type of the dividend @p x.\n////////////////////////////////////////////////////////////////////////////////\ntemplate <typename IntType>\nstruct largest_prime_factors_filter\n{\n  static_assert(std::is_integral<IntType>::value, \"Integer required.\");\n\n  typedef IntType result_type;\n\n  largest_prime_factors_filter(IntType x)\n    : m_x(x)\n  { }\n\n  IntType operator()(IntType n)\n  {\n    if ((m_x % n) != 0)   // n is not a factor of x\n      return 0;\n\n    if (is_prime(m_x/n))  // x/n (which is larger than n) is prime\n      return m_x/n;\n\n    return is_prime(n) ? n : 0;\n  }\n\n  void define_type(stapl::typer& t)\n  {\n    t.member(m_x);\n  }\n\nprivate:\n  IntType m_x;\n\n  static bool is_prime(IntType n)\n  {\n    IntType sqrt_n = sqrt_int(n);\n\n    for (IntType i = 2; i <= sqrt_n; ++i)\n    {\n      if ((n % i) == 0)\n        return false;\n    }\n\n    return true;\n  }\n};\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n  using value_t = std::size_t;\n\n  if (argc < 2)\n  {\n    stapl::do_once( [] {\n      std::cout << \"Run as: mpirun -n <ncpu> pe_3b <number>\" << std::endl;\n    });\n    return EXIT_FAILURE;\n  }\n\n  stapl::counter<stapl::default_timer> exec_timer;\n  exec_timer.start();\n\n  // Read the dividend from command line.\n  value_t num = boost::lexical_cast<value_t> (argv[1]);\n\n  // Create a generator of consecutive values from 2 to sqrt(num).\n  auto c_vw = stapl::counting_view(sqrt_int(num)-1, 2);\n\n  // Apply the filter that effectively replaces each generated number by zero\n  // if it is not prime factor of <num> and accumulate a maximum of these\n  // numbers.\n  value_t max_prime_factor = stapl::map_reduce(\n      largest_prime_factors_filter<value_t>(num),\n      stapl::max<value_t>(),\n      c_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": "b80efa289045a68d168dd39d151affd9c8f8fecc", "size": 3462, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_3b.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_3b.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_3b.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": 28.1463414634, "max_line_length": 80, "alphanum_fraction": 0.5589254766, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6687687987885138}}
{"text": "/**\n * @file\n * @brief NPDE homework ProjectionOntoGradients code\n * @author ?, Philippe Peter\n * @date December 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../projectionontogradients.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/fe/fe.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <memory>\n\nnamespace ProjectionOntoGradients::test {\n\nTEST(ProjectionOntoGradients, ElementMatrixProvider) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // implemented element matrix provider\n  ElementMatrixProvider my_elem_mat_provider{};\n\n  // For comparison\n  lf::uscalfe::LinearFELaplaceElementMatrix lfe_elem_mat_provider{};\n\n  // loop over cells and compute element matrices\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    Eigen::Matrix3d my_mat{my_elem_mat_provider.Eval(*cell)};\n    lf::uscalfe::LinearFELaplaceElementMatrix::ElemMat lfe_mat{\n        lfe_elem_mat_provider.Eval(*cell)};\n\n    // compare element matrices:\n    EXPECT_NEAR((lfe_mat.block<3, 3>(0, 0) - my_mat).norm(), 0.0, 1E-3);\n  }\n}\n\nTEST(ProjectionOntoGradients, GradProjRhsProvider_1) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functions f and v for which the linear form is evaluated\n  auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(1.0, 2.0); };\n  auto v = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n  auto v_mf = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  // set up finite elements\n  std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // construct element vector provider\n  GradProjRhsProvider my_vec_provider(f);\n\n  // assemble vector\n  Eigen::VectorXd phi(fe_space->LocGlobMap().NumDofs());\n  phi.setZero();\n  lf::assemble::AssembleVectorLocally(0, fe_space->LocGlobMap(),\n                                      my_vec_provider, phi);\n\n  // project v onto the fe space\n  auto v_vec = lf::fe::NodalProjection<double>(*fe_space, v_mf);\n\n  // evaluate linear form on projected function:\n  auto product = (v_vec.transpose() * phi).eval();\n  EXPECT_NEAR(product(0, 0), 36, 1E-5);\n}\n\nTEST(ProjectionOntoGradients, GradProjRhsProvider_2) {\n  // Building triangular test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n\n  // initialize functions f and v for which the linear form is evaluated\n  auto f = [](Eigen::Vector2d x) { return Eigen::Vector2d(x(1), x(0)); };\n  auto v = [](Eigen::Vector2d x) { return 2 * x(0) + x(1); };\n  auto v_mf = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  // set up finite elements\n  std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>> fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // construct element vector provider\n  GradProjRhsProvider my_vec_provider(f);\n\n  // assemble vector\n  Eigen::VectorXd phi(fe_space->LocGlobMap().NumDofs());\n  phi.setZero();\n  lf::assemble::AssembleVectorLocally(0, fe_space->LocGlobMap(),\n                                      my_vec_provider, phi);\n\n  // project v onto the fe space\n  auto v_vec = lf::fe::NodalProjection<double>(*fe_space, v_mf);\n\n  // evaluate linear form on projected function:\n  auto product = (v_vec.transpose() * phi).eval();\n  EXPECT_NEAR(product(0, 0), 40.5, 1E-5);\n}\n\n/* SAM_LISTING_BEGIN_1 */\nTEST(ProjectionOntoGradients, div_free_test) {\n  //====================\n  // Your code goes here\n  //====================\n}\n/* SAM_LISTING_END_1 */\n\nTEST(ProjectionOntoGradients, exact_sol_test) {\n  // I. Construct the test mesh\n  //====================\n  // Your code goes here\n  //====================\n\n  // II. Construct a linear finite element space on the test mesh\n  //====================\n  // Your code goes here\n  //====================\n\n  // III. Define a function which computes the index of the triangle in which\n  // the coorindates of a given point are\n  //====================\n  // Your code goes here\n  //====================\n\n  // IV. Define the function f\n  //====================\n  // Your code goes here\n  //====================\n\n  // V. Define the tent function associated with the central node\n  //====================\n  // Your code goes here\n  //====================\n\n  // VI.Determine the coefficient vector of the tent function in\n  // the FE space (perform a Nodal projection)\n  //====================\n  // Your code goes here\n  //====================\n\n  // VII. Test your implementation\n  //====================\n  // Your code goes here\n  //====================\n}\n\n}  // namespace ProjectionOntoGradients::test\n", "meta": {"hexsha": "4f011dd43e37f973b76ba13f35407f798169d307", "size": 4827, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ProjectionOntoGradients/templates/test/projectionontogradients_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ProjectionOntoGradients/templates/test/projectionontogradients_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ProjectionOntoGradients/templates/test/projectionontogradients_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.3441558442, "max_line_length": 77, "alphanum_fraction": 0.6449140253, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6687431342261849}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n#include <CGAL/Timer.h>\n#include <vector>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <boost/iterator/counting_iterator.hpp>\n\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\n\ntypedef Kernel::Point_3 Point_3;\ntypedef std::size_t Point;\n\n//definition of the property map and get\n//function as friend function to have access to\n//private member\nclass My_point_property_map{\n  const std::vector<Point_3>& points;\npublic:\n  typedef Point_3 value_type;\n  typedef const value_type& reference;\n  typedef Point key_type;\n  typedef boost::lvalue_property_map_tag category;  \n\n  My_point_property_map(const std::vector<Point_3>& pts):points(pts){}\n\n  friend reference get(const My_point_property_map& ppmap,key_type i) \n  {return ppmap.points[i];}\n};\ntypedef CGAL::Search_traits_3<Kernel> Traits_base;\ntypedef CGAL::Search_traits_adapter<Point,My_point_property_map,Traits_base> Traits;\n\ntypedef CGAL::Orthogonal_k_neighbor_search<Traits> K_neighbor_search;\ntypedef K_neighbor_search::Tree       Tree;\ntypedef Tree::Splitter              Splitter; \ntypedef K_neighbor_search::Distance Distance;\n\n\nint main() {\n  const unsigned int N = 50;\n  CGAL::Timer timer;\n  timer.start();\n\n  std::vector<Point_3> points, queries;\n  Point_3 p;\n\n  std::ifstream point_stream(\"points.xyz\");\n  while(point_stream >> p){\n    points.push_back(p);\n\n  }\n\n  My_point_property_map ppmap(points);\n  Distance tr_dist(ppmap);\n\n  std::ifstream query_stream(\"queries.xyz\");\n  while(query_stream >> p ){\n    queries.push_back(p);\n\n  }\n  timer.stop();\n  std::cerr << \"reading points took \" << timer.time() << \" sec.\" << std::endl;\n\n\n  timer.reset();\n  timer.start();\n  Tree tree( boost::counting_iterator<std::size_t>(0),\n             boost::counting_iterator<std::size_t>(points.size()),\n             Splitter(),\n             Traits(ppmap));\n  tree.build();\n  timer.stop();\n  std::cerr << \"tree construction took \" << timer.time() << \" sec.\" << std::endl;\n\n\n  // Initialize the search structure, and search all N points\n  \n  double d = 0;\n  timer.reset();\n  timer.start();\n  for(int i = 0; i < queries.size(); i++){\n    K_neighbor_search search(tree, queries[i], 50, 0, true, tr_dist);\n\n    // report the N nearest neighbors and their distance\n    // This should sort all N points by increasing distance from origin\n    for(K_neighbor_search::iterator it = search.begin(); it != search.end(); ++it){\n      //std::cout << it->first << std::endl;\n      d += get(ppmap,it->first).x();\n    }\n  }\n  timer.stop();\n  std::cerr << d << std::endl;\n  std::cerr << queries.size() << \" queries in \" << timer.time() << \" sec.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "fef44a9cd917326250ff1d96aed12365df1268aa", "size": 2781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Spatial_searching/benchmark/Spatial_searching/nearest_neighbor_searching_inplace_50.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Spatial_searching/benchmark/Spatial_searching/nearest_neighbor_searching_inplace_50.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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": "graphics/cgal/Spatial_searching/benchmark/Spatial_searching/nearest_neighbor_searching_inplace_50.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "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.5346534653, "max_line_length": 88, "alphanum_fraction": 0.6882416397, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6687281062470561}}
{"text": "#pragma once\n#ifndef __NVCC__\n#include <armadillo>\n#include <algorithm>\n#endif\n\n#ifdef __NVCC__\n#define GPU __device__\n#else\n#define GPU\n#endif\n\nstruct Squared_Error {\n  template<typename U>\n  GPU static inline U error(U target, U result) {\n    return 1/2.0f * (target - result) * (target - result);\n  }\n  template<typename U, typename J>\n  #ifdef __NVCC__\n  __device__ static inline U error_dir(U target, J result) {\n    return (target - result);\n  }\n  #else\n  static inline auto error_dir(U target, J result) -> decltype(target-result) {\n    return (target - result);\n  }\n  #endif\n};\n\n//Activation\n#ifndef __NVCC__\nusing arma::exp;\n#endif\nstruct Logistic {\n  template<typename U>\n  GPU static inline U activation(U k) {\n    return 1 / (1 + exp(-k));\n  }\n\n  template<typename U>\n  #ifdef __NVCC__\n  __device__ static inline U activation_dir(U k) {\n    return k * (1.0f - k);\n  }\n  #else\n  static inline U activation_dir(U k) {\n    return k % (1.0f - k);\n  }\n  #endif\n};\n\nstruct Linear {\n  template<typename U>\n  GPU static inline U activation(U k) {\n    return k;\n  }\n\n  #ifdef __NVCC__\n  template<typename U>\n  GPU static inline U activation_dir(U k) {\n    return 1;\n  }\n  #else\n  template<typename U>\n  static inline U activation_dir(U k) {\n    return k.ones();\n  }\n  #endif\n\n};\n\n#undef GPU\n\n", "meta": {"hexsha": "f5fa317c8fb4bde4be74d829be272c5be460a224", "size": 1295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/functions.hpp", "max_stars_repo_name": "lukemetz/Neural-Net-Experiments", "max_stars_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-24T17:17:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T09:46:37.000Z", "max_issues_repo_path": "src/functions.hpp", "max_issues_repo_name": "lukemetz/Neural-Net-Experiments", "max_issues_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-04-09T00:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-09T00:41:28.000Z", "max_forks_repo_path": "src/functions.hpp", "max_forks_repo_name": "lukemetz/Neural-Net-Experiments", "max_forks_repo_head_hexsha": "c50e93ec2f0e4acac2db7815174af71cf191420f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-03-29T15:24:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T07:45:41.000Z", "avg_line_length": 17.5, "max_line_length": 79, "alphanum_fraction": 0.6586872587, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6687280970523474}}
{"text": "#include \"resection.h\"\n\n#include <Eigen/SVD>\n#include <iostream>\n#include \"sfm_utils.h\"\n#include \"defines.h\"\n\nnamespace {\n\n    matrix34d canonicalizeP(const matrix34d &P)\n    {\n        matrix3d RR = P.get_minor<3, 3>(0, 0);\n        vector3d tt;\n        tt[0] = P(0, 3);\n        tt[1] = P(1, 3);\n        tt[2] = P(2, 3);\n\n        if (cv::determinant(RR) < 0) {\n            RR *= -1;\n            tt *= -1;\n        }\n\n        double sc = 0;\n        for (int i = 0; i < 9; i++) {\n            sc += RR.val[i] * RR.val[i];\n        }\n        sc = std::sqrt(3 / sc);\n\n        Eigen::MatrixXd RRe;\n        copy(RR, RRe);\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(RRe, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        RRe = svd.matrixU() * svd.matrixV().transpose();\n        copy(RRe, RR);\n\n        tt *= sc;\n\n        matrix34d result;\n        for (int i = 0; i < 9; ++i) {\n            result(i / 3, i % 3) = RR(i / 3, i % 3);\n        }\n        result(0, 3) = tt(0);\n        result(1, 3) = tt(1);\n        result(2, 3) = tt(2);\n\n        return result;\n    }\n\n    // (\u0441\u043c. Hartley & Zisserman p.178)\n    cv::Matx34d estimateCameraMatrixDLT(const cv::Vec3d *Xs, const cv::Vec3d *xs, int count)\n    {\n        using mat = Eigen::MatrixXd;\n        using vec = Eigen::VectorXd;\n\n        mat A(2 * count, 12);\n\n        for (int i = 0; i < count; ++i) {\n\n            double x = xs[i][0];\n            double y = xs[i][1];\n            double w = xs[i][2];\n\n            double X = Xs[i][0];\n            double Y = Xs[i][1];\n            double Z = Xs[i][2];\n            double W = 1.0;\n\n            A.row(i * 2 + 0) << 0, 0, 0, 0, -w*X, -w*Y, -w*Z, -w*W, y*X, y*Y, y*Z, y*W;\n            A.row(i * 2 + 1) << w*X, w*Y, w*Z, w*W, 0, 0, 0, 0, -x*X, -x*Y, -x*Z, -x*W;\n        }\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::VectorXd null_space = svd.matrixV().col(11);\n\n        matrix34d result;\n        for (int i = 0; i < 12; ++i) {\n            result(i / 4, i % 4) = null_space(i);\n        }\n\n        return canonicalizeP(result);\n    }\n\n\n    cv::Matx34d estimateCameraMatrixRANSAC(const phg::Calibration &calib, const std::vector<cv::Vec3d> &X, const std::vector<cv::Vec2d> &x, bool verbose)\n    {\n        if (X.size() != x.size()) {\n            throw std::runtime_error(\"estimateCameraMatrixRANSAC: X.size() != x.size()\");\n        }\n\n        const int n_points = X.size();\n\n        // https://en.wikipedia.org/wiki/Random_sample_consensus#Parameters\n        // \u0431\u0443\u0434\u0435\u0442 \u043e\u0442\u043b\u0438\u0447\u0430\u0442\u044c\u0441\u044f \u043e\u0442 \u0441\u043b\u0443\u0447\u0430\u044f \u0441 \u0433\u043e\u043c\u043e\u0433\u0440\u0430\u0444\u0438\u0435\u0439\n        const int n_trials = 10000;\n\n        const double threshold_px = 3;\n\n        const int n_samples = 6;\n        uint64_t seed = 1;\n\n        int best_support = 0;\n        cv::Matx34d best_P;\n\n        std::vector<int> sample;\n        for (int i_trial = 0; i_trial < n_trials; ++i_trial) {\n            phg::randomSample(sample, n_points, n_samples, &seed);\n\n            cv::Vec3d ms0[n_samples];\n            cv::Vec3d ms1[n_samples];\n            for (int i = 0; i < n_samples; ++i) {\n                ms0[i] = X[sample[i]];\n                ms1[i] = calib.unproject(x[sample[i]]);\n            }\n\n            cv::Matx34d P = estimateCameraMatrixDLT(ms0, ms1, n_samples);\n\n            int support = 0;\n            for (int i = 0; i < n_points; ++i) {\n                cv::Vec3d pt = calib.project(P * cv::Vec4d(X[i][0], X[i][1], X[i][2], 1.0));\n                if (pt[2] == 0) {\n                    continue;\n                }\n                cv::Vec2d px = {pt[0] / pt[2], pt[1] / pt[2]};\n                if (cv::norm(px - x[i]) < threshold_px) {\n                    ++support;\n                }\n            }\n\n            if (support > best_support) {\n                best_support = support;\n                best_P = P;\n\n                if (verbose) std::cout << \"estimateCameraMatrixRANSAC : support: \" << best_support << \"/\" << n_points << std::endl;\n\n                if (best_support == n_points) {\n                    break;\n                }\n            }\n        }\n\n        if (verbose) std::cout << \"estimateCameraMatrixRANSAC : best support: \" << best_support << \"/\" << n_points << std::endl;\n\n        if (best_support == 0) {\n            throw std::runtime_error(\"estimateCameraMatrixRANSAC : failed to estimate camera matrix\");\n        }\n\n        return best_P;\n    }\n\n\n}\n\ncv::Matx34d phg::findCameraMatrix(const Calibration &calib, const std::vector <cv::Vec3d> &X, const std::vector <cv::Vec2d> &x, bool verbose) {\n    return estimateCameraMatrixRANSAC(calib, X, x, verbose);\n}\n", "meta": {"hexsha": "a0374c5ac6c973e27d7c15e1e99ac17fae93f57a", "size": 4538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/resection.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/resection.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/resection.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2774193548, "max_line_length": 153, "alphanum_fraction": 0.4832525342, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6687280887816516}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include \"serializer.hpp\"\n\nnamespace tomoto\n{\n\tnamespace math\n\t{\n\t\ttemplate<typename _Ty = float>\n\t\tstruct MultiNormalDistribution\n\t\t{\n\t\t\tstatic constexpr _Ty log2pi = (_Ty)1.83787706641;\n\t\t\tEigen::Matrix<_Ty, -1, 1> mean;\n\t\t\tEigen::Matrix<_Ty, -1, -1> cov, l;\n\t\t\t_Ty logDet = 0;\n\n\t\t\tMultiNormalDistribution(size_t k = 0) :\n\t\t\t\tmean{ Eigen::Matrix<_Ty, -1, 1>::Zero(k) },\n\t\t\t\tcov{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) },\n\t\t\t\tl{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) }\n\t\t\t{\n\t\t\t}\n\n\t\t\t_Ty getLL(const Eigen::Matrix<_Ty, -1, 1>& x) const\n\t\t\t{\n\t\t\t\t_Ty ll = -((x - mean).transpose() * cov.inverse() * (x - mean))[0] / 2;\n\t\t\t\tll -= log2pi * mean.size() / 2 + logDet;\n\t\t\t\treturn ll;\n\t\t\t}\n\n\t\t\tconst Eigen::Matrix<_Ty, -1, -1>& getCovL() const\n\t\t\t{\n\t\t\t\treturn l;\n\t\t\t}\n\n\t\t\ttemplate<typename _List>\n\t\t\tstatic MultiNormalDistribution<_Ty> estimate(_List list, size_t len)\n\t\t\t{\n\t\t\t\tMultiNormalDistribution<_Ty> newDist;\n\t\t\t\tif (len)\n\t\t\t\t{\n\t\t\t\t\tnewDist.mean = list(0);\n\t\t\t\t\tfor (size_t i = 1; i < len; ++i) newDist.mean += list(i);\n\t\t\t\t\tnewDist.mean /= len;\n\t\t\t\t\tnewDist.cov = Eigen::Matrix<_Ty, -1, -1>::Identity(newDist.mean.size(), newDist.mean.size());\n\t\t\t\t\tfor (size_t i = 0; i < len; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tEigen::Matrix<_Ty, -1, 1> o = list(i) - newDist.mean;\n\t\t\t\t\t\tnewDist.cov += o * o.transpose();\n\t\t\t\t\t}\n\t\t\t\t\tif (len > 1) newDist.cov /= len - 1;\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd l = newDist.cov.template cast<double>().llt().matrixL();\n\t\t\t\tnewDist.l = l.template cast<float>();\n\t\t\t\tnewDist.logDet = l.diagonal().array().log().sum();\n\t\t\t\treturn newDist;\n\t\t\t}\n\n\t\t\tDEFINE_SERIALIZER_CALLBACK(onRead, mean, cov);\n\t\tprivate:\n\t\t\tvoid onRead() \n\t\t\t{\n\t\t\t\tl = cov.llt().matrixL();\n\t\t\t\tlogDet = l.diagonal().array().log().sum();\n\t\t\t}\n\t\t};\n\n\t}\n}", "meta": {"hexsha": "8e0d96c7c4bd88039fbd5c12734115c4a2a6e40d", "size": 1790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_stars_repo_name": "bab2min/tomotopy", "max_stars_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 393.0, "max_stars_repo_stars_event_min_datetime": "2019-05-11T16:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:54:28.000Z", "max_issues_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_issues_repo_name": "bab2min/tomotopy", "max_issues_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:58:01.000Z", "max_forks_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_forks_repo_name": "bab2min/tomotopy", "max_forks_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2019-06-05T09:04:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:04:20.000Z", "avg_line_length": 25.5714285714, "max_line_length": 98, "alphanum_fraction": 0.5832402235, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6687235625052518}}
{"text": "#ifndef POLYTOPE_H\n#define POLYTOPE_H\n\n#include <cassert>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\n\nnamespace integrator_chains {\n\n\n/** Basic half-space representation of polytopes.\n\n   \\ingroup integrator_chains */\nclass Polytope {\n  public:\n    Polytope( Eigen::MatrixXd incoming_H, Eigen::VectorXd incoming_K );\n    Polytope( const Polytope &other );\n\n    /** Check that defining matrices have consistent dimensions.\n\n       The \"defining matrices\" are those involved in the inequality providing\n       the half-space representation, i.e., H and K in {x | Hx <= K}.\n       N.B., this check does not occur during instantiation of Polytope. */\n    bool is_consistent() const;\n\n    /** Is X contained in this polytope?\n\n       The polytope is a closed set. No numerical tolerance is used. */\n    bool is_in( Eigen::VectorXd X ) const;\n\n    /** Intersect two polytopes that are defined in the same dimension space. */\n    Polytope operator&( const Polytope &P2 );\n\n    // Factory functions\n    /** Create random Polytope in R^n using Eigen::MatrixXd::Random().\n\n       \\param n dimension of the containing space.\n\n       Random matrices as provided by Eigen::MatrixXd::Random() are used to\n       instantiate Polytope in half-space representation. The matrices have\n       \\c n+1 rows, corresponding to \\c n+1 inequalities.\n    */\n    static Polytope * randomH( int n );\n\n    /** Construct Polytope that is an axis-aligned rectangle.\n\n       \\param bounds an array of the form\n       \\code\n       [x1_min, x1_max, x2_min, x2_max, ..., xn_min, xn_max],\n       \\endcode\n       which defines a polytope in terms of intervals along each axis in R^n.\n       The interval along the first axis is [x1_min, x1_max], the interval along\n       the second axis is [x2_min, x2_max], etc. Thus the length of the given\n       array is 2n.\n\n       E.g., a unit square in R^2 can be created using\n       \\code\n           Eigen::Vector4d bounds;\n           bounds << 0, 1,\n                     0, 1;\n           Polytope *square = Polytope::box( bounds );\n       \\endcode\n    */\n    static Polytope * box( const Eigen::VectorXd &bounds );\n\n    /** Output this polytope in JSON to given stream. */\n    friend std::ostream & operator<<( std::ostream &out, const Polytope &P );\n\n    /** Output this polytope in JSON excluding opening { and closing }.\n\n       This method facilitates inheritance from Polytope without crowding the\n       JSON representations of other classes. */\n    void dumpJSONcore( std::ostream &out ) const;\n\n  private:\n    // { x \\in R^n | Hx \\leq K }\n    Eigen::MatrixXd H;\n    Eigen::VectorXd K;\n};\n\nstd::ostream & operator<<( std::ostream &out, const Polytope &P )\n{\n    out << \"{ \";\n    P.dumpJSONcore( out );\n    out << \" }\";\n    return out;\n}\n\nvoid Polytope::dumpJSONcore( std::ostream &out ) const\n{\n    int i, j;\n    out << \"\\\"H\\\": [\";\n    for (i = 0; i < H.rows(); i++) {\n        if (i > 0) {\n            out << \", \";\n        }\n        out << \"[\";\n        for (j = 0; j < H.cols(); j++) {\n            if (j > 0)\n                out << \", \";\n            out << H(i,j);\n        }\n        out << \"]\";\n    }\n    out << \"], \\\"K\\\": [\";\n    for (i = 0; i < K.rows(); i++) {\n        if (i > 0) {\n            out << \", \";\n        }\n        out << K(i);\n    }\n    out << \"]\";\n}\n\nPolytope * Polytope::randomH( int n )\n{\n    return new Polytope( Eigen::MatrixXd::Random( n+1, n ),\n                         Eigen::VectorXd::Random( n+1 ) );\n}\n\nPolytope * Polytope::box( const Eigen::VectorXd &bounds )\n{\n    assert( bounds.size() % 2 == 0 );\n\n    int n = bounds.size()/2;\n    Eigen::MatrixXd H = Eigen::MatrixXd::Zero( 2*n, n );\n    Eigen::VectorXd K( 2*n );\n    for (int i = 0; i < n; i++) {\n        H(2*i, i) = -1;\n        K(2*i) = -bounds(2*i);\n        H(2*i+1, i) = 1;\n        K(2*i+1) = bounds(2*i+1);\n    }\n    return new Polytope( H, K );\n}\n\nbool Polytope::is_consistent() const\n{\n    if (H.rows() == K.size()) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nbool Polytope::is_in( Eigen::VectorXd X ) const\n{\n    assert( H.cols() == X.size() );\n\n    if ((H*X-K).maxCoeff() <= 0) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nPolytope Polytope::operator&( const Polytope &P2 )\n{\n    assert( this->H.cols() == P2.H.cols() );\n\n    Eigen::MatrixXd H( this->H.rows() + P2.H.rows(), this->H.cols() );\n    Eigen::VectorXd K( this->H.rows() + P2.H.rows(), 1 );\n\n    H.topRows( this->H.rows() ) = this->H;\n    K.topRows( this->H.rows() ) = this->K;\n    H.bottomRows( P2.H.rows() ) = P2.H;\n    K.bottomRows( P2.H.rows() ) = P2.K;\n\n    return Polytope( H, K );\n}\n\nPolytope::Polytope( Eigen::MatrixXd incoming_H, Eigen::VectorXd incoming_K )\n    : H(incoming_H), K(incoming_K)\n{ }\n\nPolytope::Polytope( const Polytope &other )\n    : H(other.H), K(other.K)\n{ }\n\n\n/** Extension of Polytope to have label (string).\n\n   This class provides a basis for labeling trajectories. E.g., the labeling of\n   the state can be a set of strings corresponding to the labels of polytopes\n   containing the state.\n\n   \\ingroup integrator_chains */\nclass LabeledPolytope : public Polytope {\npublic:\n    std::string label;\n\n    LabeledPolytope( const Polytope &other );\n\n    /** Polytope::box() but including a label. */\n    static LabeledPolytope * box( const Eigen::VectorXd &bounds, std::string label=\"\" );\n\n    /** Output this labeled polytope in JSON to given stream. */\n    friend std::ostream & operator<<( std::ostream &out, const LabeledPolytope &P );\n};\n\nLabeledPolytope::LabeledPolytope( const Polytope &other )\n    : label(\"\"), Polytope( other )\n{ }\n\nLabeledPolytope * LabeledPolytope::box( const Eigen::VectorXd &bounds, std::string label )\n{\n    Polytope *P = Polytope::box( bounds );\n    LabeledPolytope *Q = new LabeledPolytope( *P );\n    delete P;\n    Q->label = label;\n    return Q;\n}\n\nstd::ostream & operator<<( std::ostream &out, const LabeledPolytope &P )\n{\n    out << \"{ \\\"label\\\": \\\"\" << P.label << \"\\\", \";\n    P.dumpJSONcore( out );\n    out << \" }\";\n    return out;\n}\n\n\n} // namespace integrator_chains\n\n\n#endif  // ifndef POLYTOPE_H\n", "meta": {"hexsha": "c94b10d56f13ff1ab1e3ede4cbd36148363b5523", "size": 6090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_stars_repo_name": "fmrchallenge/fmrbenchmark", "max_stars_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-05-28T22:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T00:21:12.000Z", "max_issues_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_issues_repo_name": "fmrchallenge/fmrbenchmark", "max_issues_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2016-02-07T20:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T23:42:06.000Z", "max_forks_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_forks_repo_name": "fmrchallenge/fmrbenchmark", "max_forks_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-12-28T20:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-08T23:30:44.000Z", "avg_line_length": 26.4782608696, "max_line_length": 90, "alphanum_fraction": 0.5866995074, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6687235552796125}}
{"text": "#pragma once\n\n#include \"layer.hpp\"\n#include <Eigen/Dense>\n\nnamespace\n{\n\tusing namespace nn;\n\n\tuint32_t conv_size(uint32_t input, uint32_t kernel_width, uint32_t padding, uint32_t stride)\n\t{\n\t\treturn (input - kernel_width + 2 * padding) / stride + 1;\n\t}\n\n\tlayer::MatrixType conv_helper(const layer::MatrixType& input,\n\t\tconst layer::MatrixType& kernel,\n\t\tuint32_t start_row, uint32_t start_col,\n\t\tuint32_t end_row, uint32_t end_col,\n\t\tuint32_t stride,\n\t\tbool normalize)\n\t{\n\t\tlayer::MatrixType output = layer::MatrixType::Zero(end_row - start_row, end_col - start_col);\n\t\tconst auto KSizeX = kernel.rows();\n\t\tconst auto KSizeY = kernel.cols();\n\n\t\tfor (auto row = start_row; row < end_row; row += stride)\n\t\t\tfor (auto col = start_col; col < end_col; col += stride)\n\t\t\t\toutput(row - start_row, col - start_col) = input.block(row - KSizeX / 2, col - KSizeY / 2, KSizeX, KSizeY).cwiseProduct(kernel).sum();\n\n\t\tif (normalize)\n\t\t\treturn output / kernel.sum();\n\t\telse\n\t\t\treturn output;\n\t}\n\n\tlayer::MatrixType zero_pad(const layer::MatrixType& input, uint32_t size)\n\t{\n\t\tlayer::MatrixType result = layer::MatrixType::Zero(input.rows() + 2 * size, input.cols() + 2 * size);\n\t\tresult.block(size, size, input.rows(), input.cols()) = input;\n\t\treturn result;\n\t}\n}\n\nnamespace nn\n{\n\tlayer::MatrixType conv(const layer::MatrixType& input, const layer::MatrixType& kernel, uint32_t stride, bool zeroPad = false, bool normalize = false)\n\t{\n\t\tconst auto kernel_half_width = kernel.cols() / 2;\n\t\tconst auto kernel_half_height = kernel.rows() / 2;\n\t\tif (!zeroPad)\n\t\t{\n\t\t\tconst auto result_width = conv_size(input.cols(), kernel.cols(), 0, stride);\n\t\t\tconst auto result_height = conv_size(input.rows(), kernel.rows(), 0, stride);\n\t\t\tconst auto conv_start_col = (input.cols() - result_width) / 2;\n\t\t\tconst auto conv_start_row = (input.rows() - result_height) / 2;\n\t\t\tconst auto conv_end_col = conv_start_col + result_width;\n\t\t\tconst auto conv_end_row = conv_start_row + result_height;\n\t\t\treturn conv_helper(input, kernel, conv_start_row, conv_start_col, conv_end_row, conv_end_col, stride, normalize);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn conv_helper(zero_pad(input, kernel_half_width), \n\t\t\t\tkernel, kernel_half_width, kernel_half_height, \n\t\t\t\tkernel_half_width + input.cols(),\n\t\t\t\tkernel_half_height + input.rows(),\n\t\t\t\tstride,\n\t\t\t\tnormalize);\n\t\t}\n\t}\n\n}", "meta": {"hexsha": "30d14d0e94d0fb60ffc4510347f8bce9decd5cb7", "size": 2317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/convolution.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/convolution.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/convolution.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": 32.6338028169, "max_line_length": 151, "alphanum_fraction": 0.7078118256, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6687235529650186}}
{"text": "#include \"vio/eigen_utils.h\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace vio {\n\nEigen::Vector3d rotro2eu(Eigen::Matrix3d R) {\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\nEigen::Matrix3d roteu2ro(Eigen::Vector3d eul) {\n  double cr = cos(eul[0]);\n  double sr = sin(eul[0]);  // roll\n  double cp = cos(eul[1]);\n  double sp = sin(eul[1]);  // pitch\n  double ch = cos(eul[2]);\n  double sh = sin(eul[2]);  // 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  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  Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n  // ColPivHouseholderQR<MatrixXd> qr(A); //don't use column pivoting because in\n  // that case Q*R-A!=0\n  Eigen::MatrixXd nullQ = qr.householderQ();\n\n  int rows = A.rows(), cols = A.cols();\n  assert(rows >\n         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, Eigen::MatrixXd *Q2,\n                                 Eigen::MatrixXd *Q1) {\n  int rows = A.rows(), cols = A.cols();\n  assert(rows > cols);  // \"Rows should be greater than columns in computing\n                        // left nullspace\"\n  Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n  // don't use column pivoting because in that case Q*R-A!=0\n  Eigen::MatrixXd Q = qr.householderQ();\n\n  Q2->resize(rows, rows - cols);\n  *Q2 = Q.block(0, cols, rows, rows - cols);\n\n  Q1->resize(rows, cols);\n  *Q1 = Q.block(0, 0, rows, cols);\n}\n\nEigen::Matrix<double, Eigen::Dynamic, 1> superdiagonal(\n    const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> &M) {\n  const int numElements = std::min(M.rows(), M.cols()) - 1;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> r(numElements, 1);\n  for (int jack = 0; jack < numElements; ++jack) r[jack] = M(jack, jack + 1);\n  return r;\n}\n\nEigen::Matrix<double, Eigen::Dynamic, 1> subdiagonal(\n    const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> &M) {\n  const int numElements = std::min(M.rows(), M.cols()) - 1;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> r(numElements, 1);\n  for (int jack = 0; jack < numElements; ++jack) r[jack] = M(jack + 1, jack);\n  return r;\n}\n\nvoid reparameterize_AIDP(const Eigen::Matrix3d &Ri, const Eigen::Matrix3d &Rj,\n                         const Eigen::Vector3d &abrhoi,\n                         const Eigen::Vector3d &pi, const Eigen::Vector3d &pj,\n                         Eigen::Vector3d &abrhoj,\n                         Eigen::Matrix<double, 3, 9> *jacobian) {\n  Eigen::Matrix<double, 4, 4> Tci2cj = Eigen::Matrix<double, 4, 4>::Identity();\n  Tci2cj.topLeftCorner<3, 3>() = Rj.transpose() * Ri;\n  Tci2cj.block<3, 1>(0, 3).noalias() = Rj.transpose() * (pi - pj);\n  Eigen::Matrix<double, 4, 1> homogi;\n  homogi << abrhoi.head<2>(), 1, abrhoi[2];\n  double rhoj_drhoi = 1 / (Tci2cj.row(2) * homogi);  //\\rho_j divided by \\rho_i\n  abrhoj.head<2>() = rhoj_drhoi * Tci2cj.topLeftCorner<2, 4>() * homogi;\n  abrhoj[2] = abrhoi[2] * rhoj_drhoi;\n  if (jacobian) {\n    Eigen::Matrix3d lhs;\n    lhs.setIdentity();\n    lhs.col(2) = -abrhoj;\n    //{\\alpha, \\beta, \\rho}_i\n    Eigen::Matrix<double, 3, 3> subrhs;\n    subrhs << Tci2cj.topLeftCorner<3, 2>(), Tci2cj.block<3, 1>(0, 3);\n    jacobian->topLeftCorner<3, 3>() = rhoj_drhoi * lhs * subrhs;\n    (*jacobian)(2, 2) =\n        rhoj_drhoi * rhoj_drhoi * Tci2cj.block<1, 3>(2, 0) * homogi.head<3>();\n    //{pi, pj}\n    Eigen::Matrix<double, 3, 6> rhs;\n    rhs.topLeftCorner<3, 3>() = abrhoi[2] * Rj.transpose(),\n                         rhs.block<3, 3>(0, 3) = -rhs.topLeftCorner<3, 3>();\n    jacobian->block<3, 6>(0, 3) = rhoj_drhoi * lhs * rhs;\n  }\n}\n\nvoid reparameterizeNumericalJacobian(const Eigen::Matrix3d &Ri,\n                                     const Eigen::Matrix3d &Rj,\n                                     const Eigen::Vector3d &abrhoi,\n                                     const Eigen::Vector3d &pi,\n                                     const Eigen::Vector3d &pj,\n                                     Eigen::Vector3d &abrhoj,\n                                     Eigen::Matrix<double, 3, 9> &jacobian) {\n  // numerical differentation\n  Eigen::Vector3d abrhojp;\n  reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj);\n  double h = 1e-8;\n  for (int jack = 0; jack < 3; ++jack) {\n    Eigen::Vector3d abrhoip = abrhoi;\n    abrhoip[jack] = abrhoi[jack] + h;\n    reparameterize_AIDP(Ri, Rj, abrhoip, pi, pj, abrhojp);\n    Eigen::Vector3d subJacobian = (abrhojp - abrhoj) / h;\n    jacobian.col(jack) = subJacobian;\n  }\n\n  for (int jack = 0; jack < 3; ++jack) {\n    Eigen::Vector3d pip = pi;\n    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;\n    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\n\nEigen::Vector3d unskew3d(const Eigen::Matrix3d &Omega) {\n  return 0.5 * Eigen::Vector3d(Omega(2, 1) - Omega(1, 2),\n                               Omega(0, 2) - Omega(2, 0),\n                               Omega(1, 0) - Omega(0, 1));\n}\n\n// https://github.com/ethz-asl/maplab_lightweight_filtering/blob/28417454164b08d5483754f0c0d250b84f2ce951/include/lightweight_filtering/Update.hpp\ndouble getConditionNumberOfMatrix(const Eigen::MatrixXd &matrix) {\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(matrix);\n  return svd.singularValues()(0) /\n         svd.singularValues()(svd.singularValues().size() - 1);\n}\n}  // namespace vio\n", "meta": {"hexsha": "ca391984d77a364939cf5ba3902efa9a0437530f", "size": 6445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_utils.cpp", "max_stars_repo_name": "stellarpower/vio_common", "max_stars_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T07:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:39:39.000Z", "max_issues_repo_path": "src/eigen_utils.cpp", "max_issues_repo_name": "stellarpower/vio_common", "max_issues_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-08-10T04:01:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-18T08:21:17.000Z", "max_forks_repo_path": "src/eigen_utils.cpp", "max_forks_repo_name": "stellarpower/vio_common", "max_forks_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-08-03T02:23:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-22T02:17:46.000Z", "avg_line_length": 36.8285714286, "max_line_length": 146, "alphanum_fraction": 0.5851047324, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6686988797681043}}
{"text": "#include \"engine/math/hcMatrix.h\"\n#include \"engine/hcImageFITS.h\"\n//#include \"engine/math/coordTransform.h\"\n\n#include \"src/pfss.h\"\n\n//#include \"extern/soil/SOIL.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <fstream>\n\n#include <boost/regex.hpp>\n#include \"boost/lexical_cast.hpp\"\n#include <fstream>\n\nusing namespace std;\nusing namespace boost;\n\n/*! returns the magnetic field vector at given position (spherical coordinates) for a dipole\n *  at the origin oriented along the positive z-axis. Return value given in spherical coordinates.\n *  mathematics found at http://www.physicsinsights.org/dipole_field_1.html\n */\nVec3D getDipoleField(Vec3D pos, hcFloat dipole, bool debug)\n{\n\thcFloat r\t\t= pos[0] / r_sol;\n\thcFloat theta\t= pos[1];\n\thcFloat stheta\t= sin(theta);\n\thcFloat ctheta\t= cos(theta);\n\thcFloat fac\t\t= dipole / (r * r * r);\n\thcFloat Br\t\t= fac * 2 * ctheta;\n\thcFloat Bt\t\t= fac * stheta;\n\n\tVec3D retval((hcFloat)Br, (hcFloat)Bt, (hcFloat)0.0f);\n\n\tif(debug)\n\t\tprintf(\"r: %E, t: %E, fac: %E, Br: %E, Bt: %E\\n\", r, theta, fac, Br, Bt);\n\n\treturn retval;\n}\n\n/*! mathematics found in \"The Model Magnetic Configuration of the Extended Corona\nin the Solar Wind Formation Region - Igor Veselovsky and Olga Panasenco\"\n */\nVec3D getDipoleCurrentField(Vec3D pos, hcFloat dipole, bool debug)\n{\n\thcFloat r\t\t= pos[0] / r_sol;\n\thcFloat theta\t= pos[1];\n\thcFloat stheta\t= sin(theta);\n\thcFloat ctheta\t= cos(theta);\n\thcFloat fac\t\t= dipole / (r * r * r);\n\n\thcFloat mu0\t\t= 4*PI*1E-7;\n\thcFloat mu\t\t= mu0 * dipole;\n\thcFloat r0\t\t= 2.5;\n\thcFloat B0\t\t= -1E-8;\n\thcFloat Ba\t\t= (B0*r0*r0) * (B0*r0*r0) * (B0*r0*r0) / (4 * mu * mu);\n\thcFloat a\t\t= 2 * mu / (B0*r0*r0);\n\thcFloat rho\t\t= r / a;\n\n\thcFloat Br\t\t= Ba / (rho * rho) * (ctheta / rho + (theta - PI/2.0 < 0 ? -1.0 : 1.0));\n\thcFloat Bt\t\t= 1 / (2 * rho * rho * rho) * Ba * stheta;\n\n\tif(debug)\n\t{\n\t\tprintf(\"r: %E, t: %E, Ba: %E, a: %E, rho: %E, Br: %E, Bt: %E\\n\", r, theta, Ba, a, rho, Br, Bt);\n\t\t//printf(\"(B0*r0*r0): %E, ^3: %E, denom: %E, ba: %E\\n\", (B0*r0*r0), (B0*r0*r0) * (B0*r0*r0) * (B0*r0*r0), (4 * dipole * dipole), Ba);\n\t}\n\n\tVec3D retval((hcFloat)Br, (hcFloat)Bt, (hcFloat)0.0f);\n\n\treturn retval;\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC(const char *filename, bool WSOfile, hcFloat r_ss)\n{\n\tinitNULL();\n\timportCoefficients(filename, WSOfile, r_ss);\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC()\n{\n    initNULL();\n}\n\nPFSSsolution_SHC::~PFSSsolution_SHC()\n{\n    clear();\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC(const PFSSsolution_SHC &other)\n{\n\tprintf(\"PFSS_magfield: cpy constructor not implemented!\\n\");\n\tinitNULL();\n}\n\nPFSSsolution_SHC &PFSSsolution_SHC::operator=(const PFSSsolution_SHC &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tprintf(\"PFSSsolution_SHC: assignment operator not implemented!\\n\");\n\n\treturn *this;\n}\n\nvoid PFSSsolution_SHC::initNULL()\n{\n\tg \t\t\t\t\t= NULL;\n\th \t\t\t\t\t= NULL;\n\tassLegPoly \t\t\t= NULL;\n\tcoeffOrder \t\t\t= 0;\n}\n\nvoid PFSSsolution_SHC::clear()\n{\n\tif(g!=NULL)\n\t{\n\t\tfor(uint i=0;i<coeffOrder;++i)\n\t\t{\n\t\t\tdelete [] g[i];\n\t\t\tdelete [] h[i];\n\t\t\tdelete [] assLegPoly[i];\n\t\t}\n\t\tdelete [] g;\n\t\tdelete [] h;\n\t\tdelete [] assLegPoly;\n\t}\n\n\tinitNULL();\n}\n\n/*! computes spherical harmonic coefficients from synoptic magnetogram\n *\n * \t@param \torder\t\t\tmaximum order of coefficients to be computed\n * \t@param\tr_ss\t\t\theliocentric position of source surface (in m)\n * \t@param\tphotMagfield\tdata structure containing synoptic photospheric (LOS) magnetic field strength\n */\nvoid PFSSsolution_SHC::determineCoefficientsFromPhotMagfield(uint order, hcFloat r_ss, SynPhotMagfield &photMagfield)\n{\n    init(order, r_ss);\n\n    uint width \t\t\t= photMagfield.width;\n    uint height \t\t= photMagfield.height;\n    hcFloat\tmaxSinLat\t= photMagfield.synInfo.maxSinLat;\n    hcFloat minSinLat\t= -photMagfield.synInfo.maxSinLat;\n    hcFloat numerator \t= 1.0 / (width * height);\n\n    for(uint l=0;l<=coeffOrder;++l)\n        for(uint m=0;m<=l;++m)\n        {\n            g[l][m] = 0.0;\n            h[l][m] = 0.0;\n            for(uint y=0;y<height;++y)\n            {\n            \thcFloat dSinTheta \t= (maxSinLat - minSinLat) / (height-1);\n                hcFloat theta\t\t= PI / 2.0 - asin(maxSinLat - (height - 1 - y) * dSinTheta);\n                hcFloat legPolyEval = assLegPoly[l][m].operator ()(cos(theta));\n                hcFloat cosecans\t= 1.0 / sin(theta);\n\n                for(uint x=0;x<width;++x)\n                {\n                    hcFloat phi\t\t= m * (x+1.0/2.0) * 2.0 * PI / width;\n\t\t\t\t\thcFloat D_xy \t= photMagfield(x,y) * cosecans;\n\t\t\t\t\thcFloat gm\t\t= D_xy * cos(phi) * legPolyEval;\n\t\t\t\t\thcFloat hm\t\t= D_xy * sin(phi) * legPolyEval;\n                    g[l][m] \t\t+= gm;\n                    h[l][m] \t\t+= hm;\n                }\n            }\n\n            /*//according to Altschuler & Newkirk for source surf at inf\n            g[l][m] *= (2.0*l + 1) / (l + 1) * numerator;\n            h[l][m] *= (2.0*l + 1) / (l + 1) * numerator;\n\n            /*/\n\n            // according to Xudong Sun:\n            g[l][m] *= (2.0*l + 1) * numerator;\n            h[l][m] *= (2.0*l + 1) * numerator;//*/\n        }\n}\n\nbool PFSSsolution_SHC::importCoefficients(const char *filename, bool WSOfile, hcFloat r_ss)\n{\n    FILE* coeffFile;\n    char str[1000];\n    char tempstr[100];\n    uint k,z,order;\n    int highestOrder = 0;\n\n\tif (!doesFileExist(filename))\n\t{\n\t\tprintf(\"ERROR! PFSSsolution_SHC::load input file '%s' does not exist\\n\", filename);\n\t\tinit(0, 2.5*r_sol);\n\t\treturn false;\n\t}\n\n    coeffFile = fopen(filename, \"r\");\n\n    uint i = 0;\n    while(strcmp(fgets(str, 1000, coeffFile), \"\\n\"))\n    {\n        while(str[i++] != ' ');\n        strncpy(tempstr, str, --i);\n        tempstr[i] = '\\0';\n        if (atoi(tempstr) > highestOrder)\n            highestOrder = atoi(tempstr);\n    }\n\n    init((uint)highestOrder, r_ss);\n\n    fseek(coeffFile,0, SEEK_SET);\n    uint j=0;\n    while (fgets(str, 1000, coeffFile) != NULL)\n    {\n        if(j==0)        // load g's\n        {\n            if(str[0] == '\\n')\n                ++j;\n            else\n            {\n                i = 0;\n\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-z] = '\\0';\n                    g[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n                ++order;\n            }\n        }\n        else            // load h's\n        {\n            if(str[0] == '\\n')\n                break;\n            else\n            {\n                i = 0;\n\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-1-z] = '\\0';\n                    h[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n\n                ++order;\n            }\n        }\n\n    }\n    fclose(coeffFile);\n\n    if(WSOfile)\t\t\t\t// WSO files employ microTesla as units\n    {\n    \tfor(uint l=0; l<=coeffOrder; ++l)\n    \t\tfor(uint m=0; m<=l; ++m)\n    \t\t{\n    \t\t\tg[l][m] /= 100;\n    \t\t\th[l][m] /= 100;\n    \t\t}\n    }\n\n    return true;\n}\n\nvoid PFSSsolution_SHC::exportCoefficients(const char *filename)\n{\n    char tempstr[10000];\n    char tmp[100];\n\n    FILE *outfile = fopen(filename, \"w\");\n    for(uint l=0;l<=coeffOrder;++l)\n    {\n        tempstr[0] = '\\0';\n        sprintf(tempstr, \"%u \", l);\n        for(uint m=0;m<=l;++m)\n        {\n            tmp[0] = '\\0';\n            sprintf(tmp, \"%f \", g[l][m]);\n            strcat(tempstr, tmp);\n        }\n        if(l==0)\n            strcat(tempstr, \"\\t\\t g's\");\n        strcat(tempstr, \"\\n\");\n        fprintf(outfile, \"%s\", tempstr);\n    }\n    fprintf(outfile, \"\\n\");\n    for(uint l=0;l<=coeffOrder;++l)\n    {\n        tempstr[0] = '\\0';\n        sprintf(tempstr, \"%u \", l);\n        for(uint m=0;m<=l;++m)\n        {\n            tmp[0] = '\\0';\n            sprintf(tmp, \"%f \", h[l][m]);\n            strcat(tempstr, tmp);\n        }\n        if(l==0)\n            strcat(tempstr, \"\\t\\t h's\");\n        strcat(tempstr, \"\\n\");\n        fprintf(outfile, \"%s\", tempstr);\n    }\n    fclose(outfile);\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//---   PFSSsolution_SHC_sun\n//---------------------------------------------------------------------------------------------------------------\n\nPFSSsolution_SHC_sun::PFSSsolution_SHC_sun()\n{\n\tinitNULL();\n}\n\nPFSSsolution_SHC_sun::PFSSsolution_SHC_sun(const PFSSsolution_SHC_sun &other)\n{\n\tinitNULL();\n\toperator =(other);\n}\n\nPFSSsolution_SHC_sun::~PFSSsolution_SHC_sun()\n{\n\tclear();\n}\n\nPFSSsolution_SHC_sun &PFSSsolution_SHC_sun::operator=(const PFSSsolution_SHC_sun &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tinit(other.coeffOrder, other.sourceSurfaceFactor*r_sol);\n\n\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\tfor(uint m=0; m<=l; ++m)\n\t\t{\n\t\t\tg[l][m]\t= other.g[l][m];\n\t\t\th[l][m]\t= other.h[l][m];\n\t\t}\n\n\treturn *this;\n}\n\nPFSSsolution_SHC_sun PFSSsolution_SHC_sun::operator-(const PFSSsolution_SHC_sun &other)\n{\n\tPFSSsolution_SHC_sun retval;\n\n\tif(this->coeffOrder != other.coeffOrder || this->sourceSurfaceFactor != other.sourceSurfaceFactor)\n\t{\n\t\tprintf(\"PFSS_magfield::operator- order does not match (%u != %u) or r_ss is different.\\n\", this->coeffOrder, other.coeffOrder);\n\t\tretval.init(0, 2.5*r_sol);\n\t}\n\telse\n\t{\n\t\tretval.init(this->coeffOrder, this->sourceSurfaceFactor);\n\t\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\t\tfor(uint m=0; m<=l; ++m)\n\t\t\t{\n\t\t\t\thcFloat g1 \t\t= fabs(this->g[l][m] - other.g[l][m]) / fabs(this->g[l][m]);\n\t\t\t\thcFloat g2 \t\t= fabs(this->g[l][m] - other.g[l][m]) / fabs(other.g[l][m]);\n\t\t\t\thcFloat h1 \t\t= fabs(this->h[l][m] - other.h[l][m]) / fabs(this->h[l][m]);\n\t\t\t\thcFloat h2 \t\t= fabs(this->h[l][m] - other.h[l][m]) / fabs(other.h[l][m]);\n\n\t\t\t\tretval.g[l][m] \t= this->g[l][m]==0 ? 0.0 : g1 < g2 ? g1 : g2;\n\t\t\t\tretval.h[l][m] \t= this->h[l][m]==0 ? 0.0 : h1 < h2 ? h1 : h2;\n\t\t\t}\n\t}\n\n\treturn retval;\n\n}\n\nvoid PFSSsolution_SHC_sun::init(uint order, hcFloat r_ss)\n{\n\tclear();\n\tcoeffOrder \t= order;\n\tsourceSurfaceFactor = r_ss/r_sol;\n\tg \t\t\t= new hcFloat*[coeffOrder + 1];\n\th \t\t\t= new hcFloat*[coeffOrder + 1];\n\tassLegPoly \t= new AssocLegendrePoly_sun*[coeffOrder + 1];\n\n\tfor(uint i=0;i<=coeffOrder;++i)\n\t{\n\t\tg[i] \t\t\t= new hcFloat[i+1];\n\t\th[i] \t\t\t= new hcFloat[i+1];\n\t\tassLegPoly[i] \t= new AssocLegendrePoly_sun[i+1];\n\n\t\tfor(uint j=0;j<=i;++j)\n\t\t{\n\t\t\tAssocLegendrePoly_sun temp(i, j);\n\t\t\tassLegPoly[i][j] = temp;\n\t\t}\n\t}\n}\n\nvoid PFSSsolution_SHC_sun::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n\thcFloat r_ss \t\t= sourceSurfaceFactor * r_sol;     // source surface\n\thcFloat retval_r \t= 0.0;\n\thcFloat retval_t \t= 0.0;\n\thcFloat retval_p \t= 0.0;\n\n\tfor(uint l=0;l<=coeffOrder;++l)\n\t\tfor(uint m=0;m<=l;++m)\n\t\t{   // equation 16 from Notes on PFSS Extrapolation, Xudong Sun\n\t\t\tretval_r += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t  * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t  * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t  * (l+1+l*pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\n\t\t\t// equation 17\n\t\t\tretval_t += -assLegPoly[l][m].getDeriv(theta)\n\t\t\t\t\t  * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t  * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t  * (1 - pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\n\t\t\t// equation 18\n\t\t\tretval_p += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t  * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n\t\t\t\t\t  * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t  * (1 - pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\t\t}\n\n\tresult(0) = retval_r;\n\tresult(1) = retval_t;\n\tresult(2) = retval_p;\n}\n\n\n//---------------------------------------------------------------------------------------------------------------\n//---   PFSSsolution_SHC_hoek\n//---------------------------------------------------------------------------------------------------------------\n\nPFSSsolution_SHC_hoek::PFSSsolution_SHC_hoek()\n{\n\tinitNULL();\n}\n\nPFSSsolution_SHC_hoek::PFSSsolution_SHC_hoek(const PFSSsolution_SHC_hoek &other)\n{\n\tinitNULL();\n\toperator =(other);\n}\n\nPFSSsolution_SHC_hoek::~PFSSsolution_SHC_hoek()\n{\n\tclear();\n}\n\nPFSSsolution_SHC_hoek &PFSSsolution_SHC_hoek::operator=(const PFSSsolution_SHC_hoek &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tprintf(\"PFSSsolution_SHC: assignment operator not implemented!\\n\");\n\n\treturn *this;\n}\n\nPFSSsolution_SHC_hoek PFSSsolution_SHC_hoek::operator-(const PFSSsolution_SHC_hoek &other)\n{\n\tPFSSsolution_SHC_hoek retval;\n\n\tif(this->coeffOrder != other.coeffOrder)\n\t{\n\t\tprintf(\"PFSS_magfield::operator- order does not match (%u != %u)\\n\", this->coeffOrder, other.coeffOrder);\n\t\tretval.init(0, 2.5*r_sol);\n\t}\n\telse\n\t{\n\t\tretval.init(this->coeffOrder, this->sourceSurfaceFactor);\n\t\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\t\tfor(uint m=0; m<=l; ++m)\n\t\t\t{\n\t\t\t\tretval.g[l][m] = this->g[l][m]==0 ? 0.0 : (this->g[l][m] - other.g[l][m]) / this->g[l][m];\n\t\t\t\tretval.h[l][m] = this->h[l][m]==0 ? 0.0 : (this->h[l][m] - other.h[l][m]) / this->h[l][m];\n\t\t\t}\n\t}\n\n\treturn retval;\n\n}\n\nvoid PFSSsolution_SHC_hoek::init(uint order, hcFloat r_ss)\n{\n\tclear();\n\tcoeffOrder \t= order;\n\tsourceSurfaceFactor = r_ss / r_sol;\n\tg \t\t\t= new hcFloat*[coeffOrder + 1];\n\th \t\t\t= new hcFloat*[coeffOrder + 1];\n\tassLegPoly \t= new AssocLegendrePoly_sun*[coeffOrder + 1];\n\n\tfor(uint i=0;i<=coeffOrder;++i)\n\t{\n\t\tg[i] \t\t\t= new hcFloat[i+1];\n\t\th[i] \t\t\t= new hcFloat[i+1];\n\t\tassLegPoly[i] \t= new AssocLegendrePoly_sun[i+1];\n\n\t\tfor(uint j=0;j<=i;++j)\n\t\t{\n\t\t\tAssocLegendrePoly_sun temp(i, j);\n\t\t\tassLegPoly[i][j] = temp;\n\t\t}\n\t}\n}\n\nvoid PFSSsolution_SHC_hoek::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n\thcFloat r_ss \t\t= sourceSurfaceFactor * r_sol;     // source surface\n\thcFloat retval_r \t= 0.0;\n\thcFloat retval_t \t= 0.0;\n\thcFloat retval_p \t= 0.0;\n\n\tfor(uint l=0;l<=coeffOrder;++l)\n\t\tfor(uint m=0;m<=l;++m)\n\t\t{\n\t\t\thcFloat c\t= -pow(r_sol / r_ss, (hcFloat)(l+2));\n\n\t\t\tretval_r += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t  * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t  * ((l+1) * pow(r_sol / r, (hcFloat)(l+2)) - c * l * pow(r / r_ss, (hcFloat)((int)l-1)));\n\n\t\t\tretval_t += -assLegPoly[l][m].getDeriv(theta)\n\t\t\t\t\t  * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t  * (pow(r_sol / r, (hcFloat)(l+2)) + c * pow(r / r_ss, (hcFloat)((int)l-1)));\n\n\t\t\tretval_p += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t  * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n\t\t\t\t\t  * (pow(r_sol / r, (hcFloat)(l+2)) + c * pow(r / r_ss, (hcFloat)((int)l-1))) * m / sin(theta);\n\t\t}\n\n\tresult(0) = retval_r;\n\tresult(1) = retval_t;\n\tresult(2) = retval_p;\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//---   CSSS\n//---------------------------------------------------------------------------------------------------------------\n\n\n\nCSSS_magfield::CSSS_magfield(const char *filename)\n{\n\tinitNULL();\n    if(!load(filename))\n    \tprintf(\"ERROR! CSSS_magfield constructor could not load file '%s'\\n\", filename);\n}\n\nCSSS_magfield::CSSS_magfield()\n{\n\tinitNULL();\n    printf(\"ERROR! CSSS_magfield std constructor not implemented!\\n\");\n}\n\nCSSS_magfield::CSSS_magfield(const CSSS_magfield &other)\n{\n\tinitNULL();\n\tprintf(\"ERROR! CSSS_magfield cpy constructor not implemented!\\n\");\n}\n\nCSSS_magfield::~CSSS_magfield()\n{\n    clear();\n}\n\nvoid CSSS_magfield::initNULL()\n{\n\tg \t\t\t\t\t= NULL;\n\th \t\t\t\t\t= NULL;\n\tassLegPoly \t\t\t= NULL;\n\tsourceSurfaceFactor = 2.5;\n\torder \t\t\t= 0;\n}\n\nvoid CSSS_magfield::clear()\n{\n\tif(g != NULL)\n\t{\n\t\tfor(uint i=0;i<=order;++i)\n\t\t{\n\t\t\tdelete [] g[i];\n\t\t\tdelete [] h[i];\n\t\t\tdelete [] assLegPoly[i];\n\t\t}\n\t\tdelete [] g;\n\t\tdelete [] h;\n\t\tdelete assLegPoly;\n\t}\n\n\tinitNULL();\n}\n\n\nvoid CSSS_magfield::init(uint order)\n{\n\tclear();\n\n    this->order\t= order;\n    g \t\t\t= new double*[order + 1];\n    h \t\t\t= new double*[order + 1];\n    assLegPoly \t= new AssocLegendrePoly_sun*[order + 1];\n\n    for(uint l=0;l<=order;++l)\n    {\n        g[l] \t\t\t= new double[l+1];\n        h[l] \t\t\t= new double[l+1];\n        assLegPoly[l] \t= new AssocLegendrePoly_sun[l+1];\n        for(uint m=0;m<=l;++m)\n        {\n            AssocLegendrePoly_sun temp(l, m);\n            assLegPoly[l][m] \t= temp;\n            g[l][m]\t\t\t\t= 0.0;\n            h[l][m]\t\t\t\t= 0.0;\n        }\n    }\n}\n\nvoid CSSS_magfield::exportCoefficients(const char *filename)\n{\n    char tempstr[10000];\n    char tmp[100];\n    FILE *outfile = fopen(filename, \"w\");\n    for(uint l=0;l<=order;++l)\n    {\n        tempstr[0] = '\\0';\n        sprintf(tempstr, \"%u \", l);\n        for(uint m=0;m<=l;++m)\n        {\n            tmp[0] = '\\0';\n            sprintf(tmp, \"%f \", g[l][m]);\n            strcat(tempstr, tmp);\n        }\n        if(l==0)\n            strcat(tempstr, \"\\t\\t g's\");\n        strcat(tempstr, \"\\n\");\n        fprintf(outfile, \"%s\", tempstr);\n    }\n    fprintf(outfile, \"\\n\");\n    for(uint l=0;l<=order;++l)\n    {\n        tempstr[0] = '\\0';\n        sprintf(tempstr, \"%u \", l);\n        for(uint m=0;m<=l;++m)\n        {\n            tmp[0] = '\\0';\n            sprintf(tmp, \"%f \", h[l][m]);\n            strcat(tempstr, tmp);\n        }\n        if(l==0)\n            strcat(tempstr, \"\\t\\t h's\");\n        strcat(tempstr, \"\\n\");\n        fprintf(outfile, \"%s\", tempstr);\n    }\n    fclose(outfile);\n}\n\n/*\nvoid CSSS_magfield::determineCoefficientsFromFITSsineLat(uint order, const char *FITS_filename,\n\t\tdouble maxSinLat, double minSinLat, bool accountForMissingFlux)\n{\n\n    uint x, y, l, m;\n    initArrays(order);\n    hcImageFITS fitsIMG(FITS_filename);\n    uint width \t= fitsIMG.width;\n    uint height = fitsIMG.height;\n\n    double dTheta = PI / (2 * height);\n    double dSinTheta = (maxSinLat - minSinLat) / (height-1);\n    double dPhi = 2*PI/(width);\n\n    // compute missing-flux-term\n    double delta = 0.0;\n    double tempB;\n    double theta;\n    double cosecans;\n    double numerator = 0.0;\n\n    for(y=0;y<height;++y)\n    {\n        tempB = 0.0;\n        // this is for equally spaced theta\n        //theta = (2.0*(height - 1 - y) + 1 ) * dTheta;\n        // this is for equally spaced sin(latitude) -- theta = 180\u00b0 - (lat + 90\u00b0)\n        theta = PI / 2 - asin(maxSinLat - (height - 1- y) * dSinTheta);\n\n        cosecans = 1.0 / sin(theta);\n        numerator += cosecans;\n\n\n        for(x=0;x<width;++x)\n            if(!isnan(fitsIMG(x,y)) && !(fitsIMG(x,y) == -32768.0))\n            {\n                tempB += fitsIMG(x,y);\n            }\n        delta += tempB * cosecans;\n    }\n\n    delta /= (numerator * width);\n    if(accountForMissingFlux == false)\n        delta = 0;\n\n    // now compute the coefficients\n    numerator = 1.0 / (width * height);\n    double legPolyEval;\n    double phi;\n    double D_xy;\n\n    for(l=0;l<=coeffOrder;++l)\n        for(m=0;m<=l;++m)\n        {\n            g[l][m] = 0.0;\n            h[l][m] = 0.0;\n            for(y=0;y<height;++y)\n            {\n                // this is for equally spaced theta\n                //theta = (2*(height - 1 - y) + 1 ) * dTheta;\n                //this is for equally spaced sin(latitude)\n                theta \t\t= PI / 2 - asin(maxSinLat - (height - 1- y) * dSinTheta);\n\n                legPolyEval = assLegPoly[l][m].operator ()(cos(theta));\n                cosecans \t= 1 / sin(theta);\n\n                for(x=0;x<width;++x)\n                {\n                    phi = m * x * dPhi;\n                    if(!isnan(fitsIMG(x,y)) && !(fitsIMG(x,y) == -32768.0))\n                        D_xy = fitsIMG(x,y) - delta;\n                    else\n                        D_xy = -delta;\n                    g[l][m] += D_xy * cos(phi) * cosecans * legPolyEval;\n                    h[l][m] += D_xy * sin(phi) * cosecans * legPolyEval;\n                }\n            }\n\n            //according to Altschuler & Newkirk for source surf at inf\n            //g[l][m] *= (2.0*l + 1) / (l + 1) * numerator;\n            //h[l][m] *= (2.0*l + 1) / (l + 1) * numerator;\n\n            //according to Xudong Sun:\n            g[l][m] *= (2.0*l + 1) * numerator * 100;\n            h[l][m] *= (2.0*l + 1) * numerator * 100;\n        }\n}//*/\n\nbool CSSS_magfield::load(const char *filename)\n{\n\tif(!doesFileExist(filename))\n\t\treturn false;\n\n\tchar line[1000];\n\tifstream file(filename);\n\n\tuint order = 0;\n\n\twhile (!file.eof())\n\t{\n\t\tfile.getline(line, 1000);\n\n\t\tif((line[0] == '#') || line[0] == '\\n')\n\t\t\tcontinue;\n\n\t\tregex re(\".*([0-9]{3}).*\", regex::icase);\n\t\tcmatch what;\n\t\tregex_search(line, what, re);\n\n\t\tif(what[0].matched)\n\t\t{\n\t\t\torder = boost::lexical_cast<int>(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tre.assign(\".*([0-9]{2}).*\", regex::icase);\n\t\tregex_search(line, what, re);\n\n\t\tif(what[0].matched)\n\t\t{\n\t\t\torder = boost::lexical_cast<int>(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tre.assign(\".*([0-9]{1}).*\", regex::icase);\n\t\tregex_search(line, what, re);\n\n\t\tif(what[0].matched)\n\t\t{\n\t\t\torder = boost::lexical_cast<int>(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"ERROR! loadCSSScoeff: Order of solution could not be found!\\n\");\n\t\treturn false;\n\t}\n\n\tinit(order);\n\n\tchar lstr[1000], mstr[1000], gstr[1000], hstr[1000];\n\n\twhile(file >> lstr >> mstr >> gstr >> hstr)\n\t{\n\t\tuint l \t\t= atoi(lstr);\n\t\tuint m \t\t= atoi(mstr);\n\t\tdouble gval = atof(gstr);\n\t\tdouble hval\t= atof(hstr);\n\n\t\tif((l>order) || (m>l))\n\t\t{\n\t\t\tprintf(\"Error! loadCSSScoeff: l: %u, m: %u\\n\", l, m);\n\t\t\treturn false;\n\t\t}\n\n\t\tg[l][m]\t= gval;\n\t\th[l][m]\t= hval;\n\t}\n\treturn true;\n}\n\nvoid CSSS_magfield::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n    double r_ss \t\t= sourceSurfaceFactor * r_sol;     // source surface\n    double retval_r \t= 0.0;\n    double retval_t \t= 0.0;\n    double retval_phi \t= 0.0;\n\n    for(uint l=0;l<=order;++l)\n        for(uint m=0;m<=l;++m)\n        {   // equation 16 from Notes on PFSS Extrapolation, Xudong Sun\n            retval_r += assLegPoly[l][m](cos(theta))\n                    \t* ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n                    \t* pow(r_sol / r, (double)(l+2))\n                    \t* (l+1+l*pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));\n\n            // equation 17 (there has to be theta instead of cos(theta) below!)\n            retval_t += -assLegPoly[l][m].getDeriv(theta)\n                    \t* ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n                    \t* pow(r_sol / r, (double)(l+2))\n                    \t* (1 - pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));\n\n            // equation 18\n            retval_phi += assLegPoly[l][m](cos(theta))\n                    \t  * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n                    \t  * pow(r_sol / r, (double)(l+2))\n                    \t  * (1 - pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));//*/\n\n        }\n    result(0) = retval_r;\n    result(1) = retval_t;\n    result(2) = retval_phi;\n}\n\nvoid CSSS_magfield::dump()\n{\n\tprintf(\"CSSS harmonic coefficients (up to order %u):\\n----------------------------------------------------------\\n\", order);\n\tfor(uint l=1; l<=order; ++l)\n\t\tfor(uint m=0; m<=l; ++m)\n\t\t\tprintf(\"l:\\t%u, m:\\t%u, g_lm:\\t%E, h_lm:\\t%E\\n\", m, l, g[l][m], h[l][m]);\n\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//---   PFSS_visualization\n//---------------------------------------------------------------------------------------------------------------\n\n#ifdef GUI\n\nPFSS_visualization::PFSS_visualization(){\n\n\tdrawScale\t\t\t= 0.0;\n\tupperOrder \t\t\t= 0;\n\tlowerOrder\t\t\t= 0;\n\tupperSS\t\t\t\t= 0;\n\tlowerSS\t\t\t\t= 0;\n\ttextScreenID\t\t= 0;\n\tssAnimScreenID\t\t= 0;\n\tcontourProjScreenID\t= 0;\n\taccumulatedTimediff = 0;\n\tanimPointer\t\t\t= 0;\n\tanimationPlaying\t= false;\n\tfps\t\t\t\t\t= 0;\n\tnumFrames\t\t\t= 0;\n\tmagLines\t\t\t= NULL;\n}\n\nPFSS_visualization::PFSS_visualization(char *filename) : hcScene3D(){\n\n    initFromCoeffFile(filename);\n}\n\nPFSS_visualization::~PFSS_visualization()\n{\n    clear();\n}\n\nvoid PFSS_visualization::clear()\n{\n    if(magLines != NULL)\n    {\n        delete [] magLines;\n        magLines = NULL;\n    }\n}\n\nvoid PFSS_visualization::init()\n{\n    clear();\n    hcScene3D::init();\n    magLines \t\t\t\t= NULL;\n    accumulatedTimediff \t= 0.0;\n    drawScale \t\t\t\t= 1 / (1.5 * r_sol);\n    double ssSize \t\t\t= magfield.sourceSurfaceFactor * r_sol * drawScale;\n    double sunSize\t\t\t = r_sol * drawScale;\n    sun.appendFragment(*(new hcDSphere3D(origin3D, 1.0)));\n    sources.appendFragment(*(new hcDSphere3D(origin3D, 1.0)));\n    sources.TFmodel.loadIdentity();\n    sources.TFmodel.scaleHom(ssSize);\n    sun.TFmodel.loadIdentity();\n    sun.TFmodel.scaleHom(sunSize);\n    animationPlaying = false;\n}\n\nvoid PFSS_visualization::initFromSynopticFITSsineLat(uint order, const char *filename, double maxSinLat, double minSinLat)\n{\n    init();\n    SynPhotMagfield synPhot;\n    synPhot.load(filename);\n    magfield.determineCoefficientsFromPhotMagfield(order, 2.5*r_sol, synPhot);\n\n    sun.texContainer.rmTexture();\n    sun.texContainer.addFITSTexFromFile(filename);\n\n    sources.texContainer.rmTexture();\n    sources.texContainer.addMonoTexture(char2RGBA8(255,255,255,50));\n\n    initScene();\n\n}\n\nvoid PFSS_visualization::initFromSynopticWSO(uint order, const char *filename)\n{\n    std::ifstream in(filename);\n\n    char instrings[31][1000];\n    in.getline(instrings[0], 1000);\n    in.getline(instrings[0], 1000);\n\n    uint ntheta \t\t= 30;\n    uint nphi \t\t\t= 73;\n    //hcFloat *imageData \t= new hcFloat[ntheta * nphi];\n    hcImageFITS img(nphi, ntheta);\n\n    uint i;\n    uint j=0;\n    while(in >> instrings[0] >> instrings[1] >> instrings[2] >> instrings[3] >> instrings[4] >> instrings[5] >> instrings[6] >> instrings[7] >> instrings[8] >> instrings[9] >> instrings[10] >> instrings[11] >> instrings[12] >> instrings[13] >> instrings[14] >> instrings[15] >> instrings[16] >> instrings[17] >> instrings[18] >> instrings[19] >> instrings[20] >> instrings[21] >> instrings[22] >> instrings[23] >> instrings[24] >> instrings[25] >> instrings[26] >> instrings[27] >> instrings[28] >> instrings[29] >> instrings[30])\n    {\n        if(strncmp(instrings[0], \"CTxxxxxxxx\", 2))\n        {\n            printf(\"ERROR! PFSS_visualization::initFromSynopticWSO: Data alignment mismatch! Check the WSO-file!\\n\");\n            printf(\"j: %u, instrings[0]: %s\\n\", j, instrings[0]);\n            exit(1);\n        }\n\n        for(i=0;i<ntheta;++i)\n        {\n            img(nphi - j - 1, ntheta - i - 1) = atof(instrings[i+1]);\n        }\n        j++;\n    }\n    char outfilename[1000];\n    outfilename[0] = '\\0';\n    strcat(outfilename, filename);\n    strcat(outfilename, \".FITS\\0\");\n\n    img.save(outfilename);\n    //delete [] imageData;\n    initFromSynopticFITSsineLat(order, outfilename, 14.5/15, -14.5/15);\n}\n\nvoid PFSS_visualization::initFromCoeffFile(const char *filename)\n{\n    init();\n    magfield.importCoefficients(filename, true, 2.5*r_sol);\n\n    sun.texContainer.rmTexture();\n    sun.texContainer.addTexFromFile(\"../textures/spicules_sst_big.jpg\");\n\n    sources.texContainer.rmTexture();\n    sources.texContainer.addMonoTexture(char2RGBA8(255,255,255,50));\n\n    initScene();\n}\n\n//*/\n\n/*! \\brief compares two coefficient files\n *\n *  treats the second file as an deviation from the first and prints the\n *  relative errors for each coefficient in outfile\n */\nvoid PFSS_visualization::compareCoeffFiles(const char *infile1, const char *infile2, const char *outfile)\n{\n    FILE *coeffFile1, *coeffFile2, *compFile;\n    char str[1000];\n    char tempstr[100];\n    uint i,j,k,z,order;\n    int highestOrder1 \t= 0;\n    int highestOrder2 \t= 0;\n    tempstr[0] \t\t\t= '\\0';\n    str[0] \t\t\t\t= '\\0';\n\n    coeffFile1 = fopen(infile1, \"r\");\n    if(!coeffFile1)\n    {\n        printf(\"ERROR! PFSSsolution_SHC_sun::compareCoeffFiles: File %s does not exist!\\n\", infile1);\n        return;\n    }\n    i=0;\n    while(strcmp(fgets(str, 1000, coeffFile1), \"\\n\"))\n    {\n        while(str[i++] != ' ');\n        strncpy(tempstr, str, --i);\n        tempstr[i] = '\\0';\n        if (atoi(tempstr) > highestOrder1)\n            highestOrder1 = atoi(tempstr);\n    }\n\n    coeffFile2 = fopen(infile2, \"r\");\n    if(!coeffFile2)\n    {\n        printf(\"ERROR! PFSSsolution_SHC_sun::compareCoeffFiles: File %s does not exist!\\n\", infile1);\n        return;\n    }\n    i=0;\n    while(strcmp(fgets(str, 1000, coeffFile2), \"\\n\"))\n    {\n        while(str[i++] != ' ');\n        strncpy(tempstr, str, --i);\n        tempstr[i] = '\\0';\n        if (atoi(tempstr) > highestOrder2)\n            highestOrder2 = atoi(tempstr);\n    }\n\n    if(highestOrder1 != highestOrder2)\n    {\n        printf(\"ERROR! PFSSsolution_SHC_sun::compareCoeffFiles: Coefficient order does not match! (%i != %i)\\n\", highestOrder1, highestOrder2);\n        return;\n    }\n\n    fseek(coeffFile1,0, SEEK_SET);\n    fseek(coeffFile2,0, SEEK_SET);\n\n    double **g1 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n    double **h1 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n    double **g2 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n    double **h2 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n    for(i=0;i<=highestOrder1;++i)\n    {\n        g1[i] = (double*) malloc(sizeof(double) * (i+1));\n        h1[i] = (double*) malloc(sizeof(double) * (i+1));\n        g2[i] = (double*) malloc(sizeof(double) * (i+1));\n        h2[i] = (double*) malloc(sizeof(double) * (i+1));\n    }\n\n    j=0;\n    while (fgets(str, 1000, coeffFile1) != NULL)\n    {\n        if(j==0)        // load g's\n        {\n            if(str[0] == '\\n')\n                ++j;\n            else\n            {\n                i = 0;\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-1-z] = '\\0';\n                    g1[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n                ++order;\n            }\n        }\n        else            // load h's\n        {\n            if(str[0] == '\\n')\n                break;\n            else\n            {\n                i = 0;\n\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-1-z] = '\\0';\n                    h1[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n                ++order;\n            }\n        }\n    }\n\n    j=0;\n    while (fgets(str, 1000, coeffFile2) != NULL)\n    {\n        if(j==0)        // load g's\n        {\n            if(str[0] == '\\n')\n                ++j;\n            else\n            {\n                i = 0;\n\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-1-z] = '\\0';\n                    g2[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n                ++order;\n            }\n        }\n        else            // load h's\n        {\n            if(str[0] == '\\n')\n                break;\n            else\n            {\n                i = 0;\n\n                tempstr[0] = '\\0';\n                while(str[i++] != ' ');\n                z = i;\n                strncpy(tempstr, str, i-1);\n                tempstr[i-1] = '\\0';\n                order=(uint)atoi(tempstr);\n                k=0;\n\n                while(k<=order)\n                {\n                    while(str[i] == ' ' || str[i] == '\\t')\n                        ++i;\n                    z=i;\n                    while(str[i] != ' ' && str[i++] != '\\n');\n                    strncpy(tempstr, str+z, i-1);\n                    tempstr[i-1-z] = '\\0';\n                    h2[order][k++] = strtof(tempstr, NULL);\n                    tempstr[0] = '\\0';\n                    z=i;\n                }\n                ++order;\n            }\n        }\n    }\n\n    fclose(coeffFile1);\n    fclose(coeffFile2);\n    compFile = fopen(outfile, \"w\");\n\n    double error;\n    double gAccum = 0.0;\n    double hAccum = 0.0;\n    for(i=0;i<=highestOrder1;++i)\n    {\n        fprintf(compFile, \"%i \", i);\n        for(j=0;j<=i;++j)\n        {\n            error = fabs((g2[i][j]-g1[i][j])/g1[i][j]);\n            fprintf(compFile, \"%f\\t\", error);\n            if(!isnan((long double)error))\n                gAccum += error;\n        }\n        fprintf(compFile, \"\\n\");\n    }\n\n    fprintf(compFile, \"\\n\");\n    for(i=0;i<=highestOrder1;++i)\n    {\n        fprintf(compFile, \"%i \", i);\n        for(j=0;j<=i;++j)\n        {\n            error = fabs((h2[i][j]-h1[i][j])/h1[i][j]);\n            fprintf(compFile, \"%f\\t\", error);\n            if(!isnan((long double)error))\n                hAccum += error;\n        }\n        fprintf(compFile, \"\\n\");\n    }\n\n    fprintf(compFile, \"\\nAccumulated error in g: %f\\nAccumulated error in h: %f\\n\", gAccum, hAccum);\n    fclose(compFile);\n\n    for(i=0;i<=highestOrder1;++i)\n    {\n        free(g1[i]);\n        free(h1[i]);\n        free(g2[i]);\n        free(h2[i]);\n    }\n    free(g1);\n    free(h1);\n    free(g2);\n    free(h2);\n}\n\nvoid PFSS_visualization::initScene()\n{\n#define maxNumPointsPerMagLine 1000\n\n    uint numTheta \t= 10;\n    uint numPhi \t= 20;\n\n    uint i,j,k;\n    Vec3D temp;\n    Vec3D pos;\n    Vec3D temp_mag;\n    Vec3D *posData;\n    Vec3D gridPos;\n    double theta, phi;\n\n    appendObject(sun);\n\n    magLines = new hcDObject3D[1];\n    magLines[0].init();\n    magLines[0].texContainer.init(3);\n    magLines[0].texContainer.addMonoTexture(char2RGBA8(255, 0, 0, 255)); //downward maglines\n    magLines[0].texContainer.addMonoTexture(char2RGBA8(0, 255, 0, 255)); //upward maglines\n    magLines[0].texContainer.addMonoTexture(char2RGBA8(255, 255, 255, 30)); //source surface\n\n    hcDLineStrip3D lineStrip;\n\n    for(j=0;j<=numTheta;++j)\n        for(k=0;k<numPhi;++k)\n        {\n            if((j==0 || j==numTheta) && k > 0) \t\t\t// compute poles only for k=0\n                break;\n            bool upwards;\n            theta \t\t\t\t= j * PI / numTheta;\t// TODO please review this\n            phi \t\t\t\t= k * 2 * PI / numPhi;\t// TODO please review this\n            gridPos.content[0] \t= r_sol;\n            gridPos.content[1] \t= theta;\n            gridPos.content[2] \t= phi;\n\n            posData \t\t\t= new Vec3D[maxNumPointsPerMagLine];\n\n            for(i=0;i<maxNumPointsPerMagLine;++i)\n            {\n                if(i==0)\n                {\n                    magfield.eval(gridPos, temp_mag);\n\n                    if(temp_mag.content[0] < 0)\n                        upwards = false;\n                    else\n                        upwards = true;\n\n                    pos = gridPos.convCoordSpher2Cart();\n\n                    pos.scale(drawScale);\n                    temp = temp_mag;\n                    //temp_mag.convertSphericalToCartesian(temp);\n                    temp_mag = temp_mag.convVecSpher2Cart(gridPos.convCoordSpher2Cart());\n                }\n                else\n                {\n                    if((pos.length() / drawScale < r_sol - 1E7) || (pos.length() / drawScale > magfield.sourceSurfaceFactor * r_sol))\n                    {\n                        lineStrip.init(i, posData);\n                        lineStrip.drawOptions.computeLighting = false;\n\n                        uint num = magLines[0].appendFragment(lineStrip);\n                        if(!upwards)\n                            magLines[0][num].texturePointer = 0;\n                        else\n                            magLines[0][num].texturePointer = 1;\n                        break;\n                    }\n\n                    temp = pos;\n                    temp.scale(1/drawScale);\n                    temp = temp.convCoordCart2Spher();\n                    magfield.eval(temp, temp_mag);\n                }\n\n                if(!upwards)\n                {\n                    //temp.loadZeroes();\n                    //temp.minus(temp_mag);\n                    temp = -temp_mag;\n                    temp_mag = temp;\n                }\n\n                posData[i] = pos;\n                temp_mag.scale(0.01 / temp_mag.length());\n                //pos.plus(temp_mag);\n                pos\t+= temp_mag;\n            }\n            delete [] posData;\n        }\n    appendObject(magLines[0]);\n    appendObject(sources);\n}\n\nint PFSS_visualization::loadAnimation(const char *path)\n{\n    uint i, j;\n    numFrames \t= 1;\n    lowerSS \t= 0;\n    upperSS \t= 0;\n    lowerOrder \t= 0;\n    upperOrder \t= 0;\n\n    char cfgFilename[1000];\n    char inputFilename[1000];\n    cfgFilename[0] = '\\0';\n    sprintf(cfgFilename, \"%s%s\", path, \"config.cfg\");\n    std::ifstream config(cfgFilename);\n\n    char option[1000], argument[1000];\n    option[0] = '\\0';\n    argument[0] = '\\0';\n\n    while(config >> option >> argument)\n    {\n        if (!strcmp(option, \"numFrames\"))\n            numFrames = atof(argument);\n        if (!strcmp(option, \"lowerSS\"))\n            lowerSS = atof(argument);\n        if (!strcmp(option, \"upperSS\"))\n            upperSS = atof(argument);\n        if (!strcmp(option, \"fps\"))\n            fps = atof(argument);\n        if (!strcmp(option, \"lowerOrder\"))\n            lowerOrder = (uint)atoi(argument);\n        if (!strcmp(option, \"upperOrder\"))\n            upperOrder = (uint)atoi(argument);\n    }\n\n    clear();\n    hcScene3D::init();\n    //appendElement(sun);\n    magLines = new hcDObject3D[numFrames];\n\n    for(i=0;i<numFrames;++i)\n    {\n        inputFilename[0] = '\\0';\n        sprintf(inputFilename, \"%smaglines%u.obj\", path, i);\n\n        magLines[i].loadMesh(inputFilename);\n        magLines[i].visible = false;\n        appendObject(magLines[i]);\n\n    }\n\n    overlay.init();\n    Vec2D ssMagScreenPos(0.38, 0.8);\n    ssAnimScreenID = overlay.createAnimationScreen(ssMagScreenPos, 1.2, 0.3, numFrames);\n    for(i=0;i<numFrames;++i)\n    {\n        inputFilename[0] = '\\0';\n        sprintf(inputFilename, \"%sssmagfield%u.fits.contour.BMP\", path, i);\n        overlay[ssAnimScreenID].texContainer.addTexFromFile(inputFilename);\n    }\n\n    Fonthandler ftHandler;\n    char fileNam[1000] = \"../data/Roboto-Regular.ttf\";\n    ftHandler.init(fileNam, 20);\n\n    uint reqWidth, reqHeight;\n    float reqRelWidth, reqRelHeight;\n    //uint *textlayer;\n\n\n    float relHeight = 0.1;\n    float relWidth = 0.5;\n    uint pixelHeight = relHeight * heightPixelScale;\n    uint pixelWidth = relWidth * widthPixelScale;\n\n    Vec2D textScreenPos(-0.65, 0.9);\n    textScreenID = overlay.createAnimationScreen(textScreenPos, relWidth, relHeight, numFrames);\n\n    //textlayer = (uint*)malloc(sizeof(uint) * pixelHeight * pixelWidth);\n    char text[100];\n\n    hcImageRGBA textlayer(pixelWidth, pixelHeight);\n\n    for(i=0;i<numFrames;++i)\n    {\n        text[0] = '\\0';\n        if(upperSS == 0)    // animation is concerned with order of spherical functions\n            sprintf(text, \"order: %u\", lowerOrder+i);\n        else\n            sprintf(text, \"R = %f\", lowerSS + i * (float)(upperSS-lowerSS) / numFrames);\n\n\n        j = 0;\n        while(text[j++] != '\\0');\n        --j;\n\n        ftHandler.getImgDim(text, 0, 0, reqWidth, reqHeight);\n        reqRelHeight = reqHeight / heightPixelScale;\n        reqRelWidth = reqWidth / heightPixelScale;\n        if(reqRelHeight > relHeight)\n            printf(\"ERROR: PFSS_visualization::loadAnimation(const char *path): Resolution of window too low for text rendering\\n(height = %E, required: %E)!\\n\", relHeight, reqRelHeight);\n        if(reqRelWidth > relWidth)\n            printf(\"ERROR: PFSS_visualization::loadAnimation(const char *path): Resolution of window too low for text rendering\\n(width = %e, required: %E)!\\n\", relWidth, reqRelWidth);\n\n        ftHandler.printTextToImage(text, char2RGBA8(255, 255, 255, 255), 0, 0, pixelWidth, pixelHeight, textlayer);\n        overlay[textScreenID].texContainer.addTexture2D(textlayer, false);\n\n    }//*/\n    //free(textlayer);\n\n    Vec2D contourPosProj(0.38, 0.5);\n    contourProjScreenID = overlay.createAnimationScreen(contourPosProj, 1.2, 0.3, numFrames);\n    for(i=0;i<numFrames;++i)\n    {\n        inputFilename[0] = '\\0';\n        sprintf(inputFilename, \"%smagfield25%u.fits.contour.BMP\", path, i);\n        overlay[contourProjScreenID].texContainer.addTexFromFile(inputFilename);\n    }\n\n    return 1;\n}\n\n#define outputwidth 800\n#define outputheight 200\n\nvoid PFSS_visualization::exportRadialMagfieldAtHeight(float r, const char *filename)\n{\n\thcFloat dPhi \t\t= 2 * PI / outputwidth;\n    hcFloat dTheta \t\t= PI / (outputheight-1);\n    //hcFloat *imageData \t= new hcFloat[outputwidth * outputheight];\n\n    hcImageFITS img(outputwidth, outputheight);\n\n    Vec3D pos, mag;\n    pos.content[0] = r;\n\n    for(uint x=0;x<outputwidth;++x)\n        for(uint y=0;y<outputheight;++y)\n        {\n            pos.content[1] = PI - dTheta * y;\t// TODO review this\n            pos.content[2] = dPhi * x;\t\t\t// TODO review this\n            magfield.eval(pos, mag);\n            //imageData[y * outputwidth + x] = mag[0];\n            img(x, y) = mag[0];\n        }\n\n    img.save(filename);\n\n    //delete [] imageData;\n}\n\nvoid PFSS_visualization::exportRadialProjectedMagfieldAtHeight(float r, const char *filename)\n{\n    uint x,y;\n    hcFloat dPhi \t\t= 2 * PI / outputwidth;\n    hcFloat dTheta \t\t= PI / (outputheight-1);\n    //hcFloat *imageData \t= new hcFloat[outputwidth * outputheight];\n    hcImageFITS img(outputwidth, outputheight);\n\n    Vec3D pos, mag;\n    pos.content[0] = magfield.sourceSurfaceFactor * r_sol;\n    hcFloat distance = r - pos[0];\n\n    for(x=0;x<outputwidth;++x)\n        for(y=0;y<outputheight;++y)\n        {\n            pos.content[1] = PI - dTheta * y;\t// TODO review this\n            pos.content[2] = dPhi * x;\t\t\t// TODO review this\n            magfield.eval(pos, mag);\n            img(x,y) = mag[0] * pow(pos[0]/r, 2);\n        }\n\n    img.save(filename);\n\n    //delete [] imageData;\n}\n\nvoid PFSS_visualization::draw(GLuint programID)\n{\n    hcScene3D::draw(programID);\n    overlay.draw();\n}\n#endif\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ecea1ea54969dc0805e1111b4bad9fe4eb58e610", "size": 43885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pfss.cpp", "max_stars_repo_name": "kurtsansom/pfss", "max_stars_repo_head_hexsha": "03622296ccf4f87f62c6c87c0a6fc287b6ece77a", "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/pfss.cpp", "max_issues_repo_name": "kurtsansom/pfss", "max_issues_repo_head_hexsha": "03622296ccf4f87f62c6c87c0a6fc287b6ece77a", "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/pfss.cpp", "max_forks_repo_name": "kurtsansom/pfss", "max_forks_repo_head_hexsha": "03622296ccf4f87f62c6c87c0a6fc287b6ece77a", "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": 27.7929069031, "max_line_length": 530, "alphanum_fraction": 0.5105389085, "num_tokens": 13095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6686988796273795}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, falling_factorial) {\n  using stan::math::falling_factorial;\n  \n  EXPECT_FLOAT_EQ(24, falling_factorial(4.0,3));\n  EXPECT_FLOAT_EQ(120, falling_factorial(5.0,4));\n  EXPECT_FLOAT_EQ(144.8261, falling_factorial(6.1,3.1));\n  EXPECT_THROW(falling_factorial(-1, 4), std::domain_error);\n}\n\nTEST(MathFunctions, falling_factorial_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::falling_factorial(4.0, nan));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::falling_factorial(nan, 4.0));\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::falling_factorial(nan, nan));\n}\n", "meta": {"hexsha": "1f3aa8c18edbaec42adfd9d20c29ba65263eb6c6", "size": 828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/falling_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/falling_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/falling_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8461538462, "max_line_length": 60, "alphanum_fraction": 0.7053140097, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6686491489299248}}
{"text": "#ifndef TODA_ACTION_VARIABLES_GK_HPP\n#define TODA_ACTION_VARIABLES_GK_HPP\n\n#include <cmath>\n#include <vector>\n#include <clstatphys/physics/toda_discriminant.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\nusing namespace boost::math::quadrature;\n\nvoid TodaActionVariablesGK(std::vector<double> & action_variables, \n                         integrable::TodaDiscriminant const & discriminant, \n                         int max_depth=5,double relative_error=1e-5){\n\n  int matrix_size = discriminant.matrix_size();\n  std::vector<double> roots(2*matrix_size);\n  discriminant.total_roots(roots);\n\n  auto func = [&discriminant](double x){ \n    if(discriminant(x) > 2) return std::acosh(0.5*discriminant(x));\n    else if(discriminant(x) < -2) return std::acosh(-0.5*discriminant(x));\n    else return 0.0;\n  };\n\n  for(int i = 0; i < matrix_size - 1; ++i){\n    double error;\n    if(roots[2*i+1] - roots[2*i+2] == 0)\n      action_variables[i] = 0.0;\n    else\n      action_variables[i] = 2.0 / M_PI \n                          * gauss_kronrod<double, 15>::integrate(\n                                                               func, \n                                                               roots[2*i+1], \n                                                               roots[2*i+2], \n                                                               max_depth, \n                                                               relative_error, \n                                                               &error\n                                                               );\n  }\n}\n\n#endif\n", "meta": {"hexsha": "4b47f27b8a6566585d5b8108fb1665a778a5d5a8", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 37.0697674419, "max_line_length": 79, "alphanum_fraction": 0.4755332497, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6686310625350081}}
{"text": "/*\nsource file to apply LinearModels header file\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <limits>\n#include \"LinearModels.hpp\"\nusing namespace std;\nusing namespace arma;\n\n// 1. Linear Regression\n//\tconstructors and destructors\nLinearRegression::LinearRegression() : fit_intercept(true) {};\nLinearRegression::LinearRegression(const LinearRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta) {};\nLinearRegression::LinearRegression(bool fit_intercept1) : fit_intercept(fit_intercept1) {};\nLinearRegression::~LinearRegression() {};\n\n//\tassignment operation\nLinearRegression& LinearRegression::operator=(const LinearRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void LinearRegression::fit(mat X, const mat& y) {\n\t//\tadd an addtional column if fit intercept\n\tif (fit_intercept == true) X = join_rows(ones(X.n_rows), X);\n\t//\tipseduo inverse part of the equation\n\tmat ipseudo_inverse = (X.t() * X).i() * X.t();\n\n\ttheta = ipseudo_inverse * y;\t\t//\tsave results\n\treturn;\n}\n\n// return predicted values with trained model\nconst mat LinearRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\t\n\tmat y_pred = _X * theta;\n\treturn y_pred;\n}\n\n\n//\t2. Ridge Regression\nRidgeRegression::RidgeRegression() : fit_intercept(true), lambda(1.0) {};\nRidgeRegression::RidgeRegression(const RidgeRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta), lambda(source.lambda) {};\nRidgeRegression::RidgeRegression(double lambda1, bool fit_intercept1) : fit_intercept(fit_intercept1), lambda(lambda1) {};\nRidgeRegression::~RidgeRegression() {};\n\n//\tassignment operation\nRidgeRegression& RidgeRegression::operator=(const RidgeRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\tlambda = source.lambda;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void RidgeRegression::fit(mat X, const mat& y) {\n\t//\tadd an addtional column if fit intercept\n\tif (fit_intercept == true) X = join_rows(ones(X.n_rows), X);\n\n\t//\tmatrix for alpha\n\n\tmat A = lambda * eye(X.n_cols, X.n_cols);\n\t//\tipseduo inverse part of the equation\n\tmat ipseudo_inverse = (X.t() * X + A).i() * X.t();\n\n\ttheta = ipseudo_inverse * y;\t\t//\tsave results\n\treturn;\n}\n\n// return predicted values with trained model\nconst mat RidgeRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\tmat y_pred = _X * theta;\n\n\treturn y_pred;\n}\n\n\n// 3. Logistic Regression\n//\tconstructors and destructors\nLogisticRegression::LogisticRegression() : fit_intercept(true), lambda(0.0), penalty(\"l2\") {};\nLogisticRegression::LogisticRegression(const LogisticRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta), lambda(source.lambda), penalty(source.penalty) {};\nLogisticRegression::LogisticRegression(double lambda1, bool fit_intercept1, string penalty1) : fit_intercept(fit_intercept1), penalty(penalty1), lambda(lambda1) {};\nLogisticRegression::~LogisticRegression() {};\n\n//\tassignment operation\nLogisticRegression& LogisticRegression::operator=(const LogisticRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\tlambda = source.lambda;\n\t\tpenalty = source.penalty;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void LogisticRegression::fit(mat _X, const mat& y, double lr, double tol, long max_iter) {\n\t//\twhether to fit an intercept\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\t//\tprevious loss value to store loss\n\tdouble loss, l_prev = 999999.0;\n\ttheta = vec(_X.n_cols, fill::randn);\n\n\t//\tset loss and y_pred\n\t//double loss;\n\tmat y_pred;\n\n\tfor (long i = 0; i < max_iter; i++) {\n\t\ty_pred = sigmoid(_X * theta);\n\t\tloss = _NLL(_X, y, y_pred);\n\t\t//\tstop if change is less than tol\n\t\tif (l_prev - loss < tol) return;\n\t\tl_prev = loss;\n\t\ttheta = theta - lr * _NLL_grad(_X, y, y_pred);\n\t}\n}\n\n// supplemental function to calculate negative log likelihood under current model\ndouble LogisticRegression::_NLL(const mat& X, const mat& y, const mat& y_pred) {\n\t//\tfor X with M rows (number of examples), and N cols (number of features)\n\tauto M = X.n_rows, N = X.n_cols;\n\tint order; // type of penalty depending on value of penalty\n\tif (penalty == \"l2\") order = 2;\n\telse order = 1;\n\n\tdouble norm_theta = arma::norm(theta, order);\n\n\tdouble nll, penalty_val;\n\tnll = sum(-arma::log(y_pred.elem(find(y == 1)))) - sum(log(1 - y_pred.elem(find(y == 0))));\n\n\tif (order == 2) penalty_val = (lambda / 2) * pow(norm_theta, 2);\n\telse penalty_val = lambda * norm_theta;\n\n\treturn (nll + penalty_val) / double(M);\n}\n\n\n// supplemental function to calculate Gradient of the penalized negative log likelihood wrt theta\nvec LogisticRegression::_NLL_grad(const mat& X, const mat& y, const mat& y_pred) {\n\t//\tfor X with N rows (number of examples), and M cols (number of features)\n\tauto M = X.n_rows, N = X.n_cols;\n\n\t// calculate delta penalty\n\tvec d_penalty;\n\tif (penalty == \"l2\") d_penalty = lambda * theta;\n\telse d_penalty = lambda * sign(theta);\n\n\treturn (((y - y_pred).t() * X).t() + d_penalty) / -double(M);\n}\n\n// return predicted values with trained model\nconst mat LogisticRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\tmat y_pred = _X * theta;\n\n\treturn round(sigmoid(y_pred));\n}\n\n//  supplemental functions\n\n//The logistic sigmoid function\nmat sigmoid(const mat& X) {\n\treturn 1 / (1 + exp(-X));\n};", "meta": {"hexsha": "7d6878e08ccd6d269c329159859ccffcc21c5f45", "size": 6123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.cpp", "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.cpp", "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.cpp", "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": 32.057591623, "max_line_length": 183, "alphanum_fraction": 0.7146823453, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6685952157110956}}
{"text": "#include <Eigen/Sparse>\n#include <Eigen/SPQRSupport>\n#include <Eigen/OrderingMethods>\n#include <Eigen/SparseQR>\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n// declares a column-major sparse matrix type of double\ntypedef Eigen::SparseMatrix<float> SparseMatrix;\ntypedef Eigen::Triplet<float> Triplet;\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMajorMatrixXf;\n\nconst float GRID_DX = 0.1;\nconst float GRID_DY = 1;\nconst float MIN_X = 0;\nconst float MAX_X = 359.9999;\nconst float MIN_Y = 30;\nconst float MAX_Y = 150;\n\ntemplate <typename T>\nT clamp(const T& v, const T& min_v, const T& max_v)\n{\n    return v < min_v ? min_v : (v > max_v ? max_v : v);\n}\n\nvoid saveAsBitmap(const Eigen::VectorXf& x, size_t rows, size_t cols, const char* fname)\n{\n    std::ofstream ofs(fname);\n    ofs << \"P2\\n\" << cols << \" \" << rows << \"\\n255\\n\";\n    for(size_t rr = 0; rr < rows; rr++) {\n        for(size_t cc = 0; cc < cols; cc++) {\n            ofs << clamp<int>((int)x[rr * cols + cc], 0, 255) << \" \";\n        }\n        ofs << \"\\n\";\n    }\n}\n\ninline\nint wrap(int v, int min_v, int max_v)\n{\n    int width = max_v - min_v + 1;\n    while(v < min_v) v += width;\n    while(v > max_v) v -= width;\n    return v;\n}\n\ninline\nfloat sqr(float x)\n{\n    return x*x;\n}\n\ninline\nfloat cube(float x)\n{\n    return x*x*x;\n}\n\ninline\nfloat bspline(float x)\n{\n    if(x < -2) {\n        return 0;\n    } else if(x < -1) {\n        return (cube(x+2)/6.0);\n    } else if(x < 0) {\n        return (-3*cube(x+2-1)+3*sqr(x+2-1)+3*(x+2-1)+1)/6;\n    } else if(x < 1) {\n        return ((3*cube(x+2-2) - 6*sqr(x+2-2) + 4)/6);\n    } else if(x < 2) {\n        return cube(1 - (x + 2 - 3))/6.0;\n    } else {\n        return 0;\n    }\n}\n\n\nfloat kernel(float x, float width=4)\n{\n    // bspline width is 4\n    width /= 4;\n    return bspline(x / width ) / width;\n}\n\ninline\nsize_t grid_index(size_t width, size_t height, size_t grid_x, size_t grid_y)\n{\n    return grid_y * width + grid_x;\n}\n\n\nstruct BSpline\n{\n    float grid_dx = GRID_DX;\n    float grid_dy = GRID_DY;\n    float grid_min_x = MIN_Y;\n    float grid_max_x = MAX_X;\n    float grid_min_y = MIN_Y;\n    float grid_max_y = MAX_Y;\n\n    size_t x_knots = (grid_max_x - grid_min_x) / grid_dx;\n    size_t y_knots = (grid_max_y - grid_min_y) / grid_dy;\n    size_t n_knots = x_knots * y_knots;\n\n    SparseMatrix getWeights(const Eigen::MatrixXf& points) const\n    {\n        assert(points.cols() >= 2);\n        std::vector<Triplet> coeffs;\n        coeffs.reserve(points.size()*5);\n\n        for(size_t pp = 0; pp < points.rows(); pp++) {\n            const auto& pt = points.row(pp);\n            float c_xbin = x_knots * (pt.x() - grid_min_x)/(grid_max_x - grid_min_x);\n            float c_ybin = y_knots * (pt.y() - grid_min_y)/(grid_max_y - grid_min_y);\n\n            // add weights to adjacent knots\n            for(int ii = -2; ii <= 2; ii++) {\n                for(int jj = -2; jj <= 2; jj++) {\n                    int raw_xbin = (int)c_xbin + ii;\n                    int wrapped_xbin = wrap(raw_xbin, 0, x_knots - 1);\n\n                    int ybin = (int)c_ybin + jj;\n                    if(ybin < 0 || ybin >= y_knots)\n                        continue;\n\n                    float w = kernel(c_xbin - raw_xbin)*kernel(c_ybin - ybin);\n                    size_t grid_ind = grid_index(x_knots, y_knots, wrapped_xbin, ybin);\n                    coeffs.push_back(Triplet(pp, grid_ind, w));\n                }\n            }\n        }\n\n        size_t num_points = points.rows();\n        SparseMatrix Bmat(num_points, n_knots);\n        Bmat.setFromTriplets(coeffs.begin(), coeffs.end());\n        return Bmat;\n    }\n\n};\n\nEigen::VectorXf solve(const BSpline& spl, const Eigen::MatrixXf& points)\n{\n    std::cerr << \"Filling Weights\" << std::endl;\n    auto Bmat = spl.getWeights(points);\n    Bmat.makeCompressed();\n    std::cerr << \"Done\" << std::endl;\n\n    //Eigen::SparseQR<SparseMatrix, Eigen::NaturalOrdering<int>> qr;\n    std::cerr << \"QR\" << std::endl;\n    Eigen::SparseQR<SparseMatrix, Eigen::COLAMDOrdering<int>> qr(Bmat);\n    std::cerr << \"Done\" << std::endl;\n    //Eigen::SPQR<SparseMatrix> qr;\n    //qr.compute(Bmat);\n    //Eigen::SparseLU<SparseMatrix> qr(Bmat);\n    std::cerr << \"Solving: \"<< std::endl;\n    Eigen::VectorXf sol = qr.solve(points.col(2));\n    std::cerr << \"Done\" << std::endl;\n    return sol;\n};\n\nEigen::VectorXf interpolate(const BSpline& spl,\n        const Eigen::VectorXf& knot_values, const Eigen::MatrixXf& points)\n{\n    auto bmat = spl.getWeights(points);\n    return bmat * knot_values;\n}\n\nvoid drawPoints(const BSpline& spl, const Eigen::MatrixXf& points, const char* fname)\n{\n    size_t x_bins = spl.x_knots;\n    size_t y_bins = spl.y_knots;\n    Eigen::VectorXf raster(x_bins * y_bins);\n    raster.fill(0);\n    for(size_t rr = 0; rr < points.rows(); rr++) {\n        float x = points(rr, 0);\n        float y = points(rr, 1);\n        float c_xbin = x_bins * (x - spl.grid_min_x) / (spl.grid_max_x - spl.grid_min_x);\n        float c_ybin = y_bins * (y - spl.grid_min_y) / (spl.grid_max_y - spl.grid_min_y);\n        raster[(int)c_xbin + (int)c_ybin * x_bins] = 255;\n    }\n    saveAsBitmap(raster, y_bins, x_bins, fname);\n}\n\nint main(int argc, char** argv)\n{\n    size_t num_points = 30;\n    Eigen::MatrixXf points = Eigen::MatrixXf::Random(num_points, 3); // x, y, value\n    for(size_t rr = 0; rr < points.rows(); rr++) {\n        points(rr, 0) = MIN_X + std::abs(points(rr, 0)) * (MAX_X - MIN_X);\n        points(rr, 1) = MIN_Y + std::abs(points(rr, 1)) * (MAX_Y - MIN_Y);\n        points(rr, 2) = 1;\n    }\n\n    BSpline spl;\n    drawPoints(spl, points, \"orig.pgm\");\n\n    // Matrix maps from knots to known points\n    // v = Bx\n    //\n    // x is the value of the knots, B is the weights of values at each knot s.t.\n    // the values reflect the positions of the input points and v is the value\n    // at the input points\n    Eigen::VectorXf knots = solve(spl, points);\n\n    // Use the known knots to solve for the actual values at each knot location\n    Eigen::MatrixXf grid_points(spl.x_knots*spl.y_knots, 2);\n    for(size_t yy = 0; yy < spl.y_knots; yy++) {\n        for(size_t xx = 0; xx < spl.x_knots; xx++) {\n            grid_points(yy * spl.x_knots + xx, 0) = spl.grid_min_x + xx * spl.grid_dx;\n            grid_points(yy * spl.x_knots + xx, 1) = spl.grid_min_y + yy * spl.grid_dy;\n        }\n    }\n\n    Eigen::VectorXf interpolated = interpolate(spl, knots, grid_points);\n    //Eigen::VectorXf interpolated = interpolate(spl, knots, points);\n\n    saveAsBitmap(255*interpolated, spl.y_knots, spl.x_knots, \"smoothed.pgm\");\n    return 0;\n}\n", "meta": {"hexsha": "2d64cc737f02d7478a6217ee3d71166f87225630", "size": 6620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bspline_fit.cpp", "max_stars_repo_name": "micahcc/ctest", "max_stars_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bspline_fit.cpp", "max_issues_repo_name": "micahcc/ctest", "max_issues_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bspline_fit.cpp", "max_forks_repo_name": "micahcc/ctest", "max_forks_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_forks_repo_licenses": ["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.6860986547, "max_line_length": 95, "alphanum_fraction": 0.5904833837, "num_tokens": 2022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6685952118572367}}
{"text": "#include <math.h>\n#include \"inertiatest.hpp\"\n#include <frames_io.hpp>\n#include <rotationalinertia.hpp>\n#include <rigidbodyinertia.hpp>\n#include <articulatedbodyinertia.hpp>\n\n#include <Eigen/Core>\nCPPUNIT_TEST_SUITE_REGISTRATION( InertiaTest );\n\nusing namespace KDL;\nusing namespace Eigen;\n\nvoid InertiaTest::setUp()\n{\n}\n\nvoid InertiaTest::tearDown()\n{\n}\n\nvoid InertiaTest::TestRotationalInertia() {\n    //Check if construction works fine\n    RotationalInertia I0=RotationalInertia::Zero();\n    CPPUNIT_ASSERT(Map<Matrix3d>(I0.data).isZero());\n    RotationalInertia I1;\n    CPPUNIT_ASSERT(Map<Matrix3d>(I1.data).isZero());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I0.data).isApprox(Map<Matrix3d>(I1.data)));\n    RotationalInertia I2(1,2,3,4,5,6);\n    \n    //Check if copying works fine\n    RotationalInertia I3=I2;\n    CPPUNIT_ASSERT(Map<Matrix3d>(I3.data).isApprox(Map<Matrix3d>(I2.data)));\n    I2.data[0]=0.0;\n    CPPUNIT_ASSERT(!Map<Matrix3d>(I3.data).isApprox(Map<Matrix3d>(I2.data)));\n\n    //Check if addition and multiplication works fine\n    Map<Matrix3d>(I0.data).setRandom();\n    I1=-2*I0;\n    CPPUNIT_ASSERT(!Map<Matrix3d>(I1.data).isZero());\n    I1=I1+I0+I0;\n    CPPUNIT_ASSERT(Map<Matrix3d>(I1.data).isZero());\n\n    //Check if matrix is symmetric\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.data).isApprox(Map<Matrix3d>(I2.data).transpose()));\n\n    //Check if angular momentum is correctly calculated:\n    Vector omega;\n    random(omega);\n    Vector momentum=I2*omega;\n    \n    CPPUNIT_ASSERT(Map<Vector3d>(momentum.data).isApprox(Map<Matrix3d>(I2.data)*Map<Vector3d>(omega.data)));\n\n}\n\nvoid InertiaTest::TestRigidBodyInertia() {\n    RigidBodyInertia I1(0.0);\n    double mass;\n    Vector c;\n    RotationalInertia Ic;\n    random(mass);\n    random(c);\n    Matrix3d Ic_eig = Matrix3d::Random();\n    //make it symmetric:\n    Map<Matrix3d>(Ic.data)=Ic_eig+Ic_eig.transpose();\n    RigidBodyInertia I2(mass,c,Ic);\n    //Check if construction works fine\n    CPPUNIT_ASSERT_EQUAL(I2.getMass(),mass);\n    CPPUNIT_ASSERT(!Map<Matrix3d>(I2.getRotationalInertia().data).isZero());\n    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),c);\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(Ic.data)-mass*(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity()))));\n    \n    RigidBodyInertia I3=I2;\n    //check if copying works fine\n    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I3.getMass());\n    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I3.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I3.getRotationalInertia().data)));\n    //Check if multiplication and addition works fine\n    RigidBodyInertia I4=-2*I2 +I3+I3;\n    CPPUNIT_ASSERT_EQUAL(I4.getMass(),0.0);\n    CPPUNIT_ASSERT_EQUAL(I4.getCOG(),Vector::Zero());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I4.getRotationalInertia().data).isZero());\n    \n    //Check if transformations work fine\n    //Check only rotation transformation\n    //back and forward\n    Rotation R;\n    random(R);\n    I3 = R*I2;\n    I4 = R.Inverse()*I3;\n    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());\n    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));\n    //rotation and total with p=0\n    Frame T(R);\n    I4 = T*I2;\n    CPPUNIT_ASSERT_EQUAL(I3.getMass(),I4.getMass());\n    CPPUNIT_ASSERT_EQUAL(I3.getCOG(),I4.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I3.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));\n    \n    //Check only transformation\n    Vector p;\n    random(p);\n    I3 = I2.RefPoint(p);\n    I4 = I3.RefPoint(-p);\n    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());\n    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));\n    T=Frame(-p);\n    I4 = T*I2;\n    CPPUNIT_ASSERT_EQUAL(I3.getMass(),I4.getMass());\n    CPPUNIT_ASSERT_EQUAL(I3.getCOG(),I4.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I3.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));\n    \n    random(T);\n    I3=T*I2;\n    I4=T.Inverse()*I3;\n    \n    Twist a;\n    random(a);\n    Wrench f=I2*a;\n    CPPUNIT_ASSERT_EQUAL(T*f,(T*I2)*(T*a));\n    \n    random(T);\n    I3 = T*I2;\n    I4 = T.Inverse()*I3;\n    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());\n    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());\n    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));\n\n}\nvoid InertiaTest::TestArticulatedBodyInertia() {\n    double mass;\n    Vector c;\n    RotationalInertia Ic;\n    random(mass);\n    random(c);\n    Matrix3d::Map(Ic.data).triangularView<Lower>()= Matrix3d::Random().triangularView<Lower>();\n    RigidBodyInertia RBI2(mass,c,Ic);\n    ArticulatedBodyInertia I2(RBI2);\n    ArticulatedBodyInertia I1(mass,c,Ic);\n    //Check if construction works fine\n    CPPUNIT_ASSERT_EQUAL(I2.M,I1.M);\n    CPPUNIT_ASSERT_EQUAL(I2.H,I1.H);\n    CPPUNIT_ASSERT_EQUAL(I2.I,I1.I);\n    I1 = ArticulatedBodyInertia(I2);\n    CPPUNIT_ASSERT_EQUAL(I2.M,I1.M);\n    CPPUNIT_ASSERT_EQUAL(I2.H,I1.H);\n    CPPUNIT_ASSERT_EQUAL(I2.I,I1.I);\n\n    CPPUNIT_ASSERT_EQUAL(I2.M,(Matrix3d::Identity()*mass).eval());\n    CPPUNIT_ASSERT(!I2.I.isZero());\n    //CPPUNIT_ASSERT(I2.I.isApprox(Map<Matrix3d>(Ic.data)-mass*(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity()))));\n    //CPPUNIT_ASSERT(I2.H.isApprox(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity())));\n    ArticulatedBodyInertia I3=I2;\n    //check if copying works fine\n    CPPUNIT_ASSERT_EQUAL(I2.M,I3.M);\n    CPPUNIT_ASSERT_EQUAL(I2.H,I3.H);\n    CPPUNIT_ASSERT_EQUAL(I2.I,I3.I);\n    //Check if multiplication and addition works fine\n    ArticulatedBodyInertia I4=-2*I2 +I3+I3;\n    CPPUNIT_ASSERT_EQUAL(I4.M,Matrix3d::Zero().eval());\n    CPPUNIT_ASSERT_EQUAL(I4.H,Matrix3d::Zero().eval());\n    CPPUNIT_ASSERT_EQUAL(I4.I,Matrix3d::Zero().eval());\n    \n    //Check if transformations work fine\n    //Check only rotation transformation\n    //back and forward\n    Rotation R;\n    random(R);\n    I3 = R*I2;\n    Map<Matrix3d> E(R.data);\n    Matrix3d tmp = E.transpose()*I2.M*E;\n    CPPUNIT_ASSERT(I3.M.isApprox(tmp));\n    tmp = E.transpose()*I2.H*E;\n    CPPUNIT_ASSERT_EQUAL(I3.H,tmp);\n    tmp = E.transpose()*I2.I*E;\n    CPPUNIT_ASSERT(I3.I.isApprox(tmp));\n\n    I4 = R.Inverse()*I3;\n    CPPUNIT_ASSERT(I2.M.isApprox(I4.M));\n    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));\n    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));\n    //rotation and total with p=0\n    Frame T(R);\n    I4 = T*I2;\n    CPPUNIT_ASSERT_EQUAL(I3.M,I4.M);\n    CPPUNIT_ASSERT_EQUAL(I3.H,I4.H);\n    CPPUNIT_ASSERT_EQUAL(I3.I,I4.I);\n\n    //Check only transformation\n    Vector p;\n    random(p);\n    I3 = I2.RefPoint(p);\n    I4 = I3.RefPoint(-p);\n    CPPUNIT_ASSERT_EQUAL(I2.M,I4.M);\n    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));\n    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));\n    T=Frame(-p);\n    I4 = T*I2;\n    CPPUNIT_ASSERT_EQUAL(I3.M,I4.M);\n    CPPUNIT_ASSERT_EQUAL(I3.H,I4.H);\n    CPPUNIT_ASSERT_EQUAL(I3.I,I4.I);\n\n    \n    random(T);\n    I3=T*I2;\n    I4=T.Inverse()*I3;\n    \n    Twist a;\n    random(a);\n    Wrench f=I2*a;\n    CPPUNIT_ASSERT_EQUAL(T*f,(T*I2)*(T*a));\n    \n    random(T);\n    I3 = T*I2;\n    I4 = T.Inverse()*I3;\n    CPPUNIT_ASSERT(I2.M.isApprox(I4.M));\n    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));\n    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));\n}\n", "meta": {"hexsha": "bff2ddb4e231765f588ab6993fd040b81a048292", "size": 7649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/orocos_kinematics_dynamics/orocos_kdl/tests/inertiatest.cpp", "max_stars_repo_name": "numberen/apollo-platform", "max_stars_repo_head_hexsha": "8f359c8d00dd4a98f56ec2276c5663cb6c100e47", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 742.0, "max_stars_repo_stars_event_min_datetime": "2017-07-05T02:49:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:55:43.000Z", "max_issues_repo_path": "ros/orocos_kinematics_dynamics/orocos_kdl/tests/inertiatest.cpp", "max_issues_repo_name": "numberen/apollo-platform", "max_issues_repo_head_hexsha": "8f359c8d00dd4a98f56ec2276c5663cb6c100e47", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 73.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T12:50:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T08:07:07.000Z", "max_forks_repo_path": "ros/orocos_kinematics_dynamics/orocos_kdl/tests/inertiatest.cpp", "max_forks_repo_name": "numberen/apollo-platform", "max_forks_repo_head_hexsha": "8f359c8d00dd4a98f56ec2276c5663cb6c100e47", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 425.0, "max_forks_repo_forks_event_min_datetime": "2017-07-04T22:03:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T06:59:06.000Z", "avg_line_length": 34.454954955, "max_line_length": 234, "alphanum_fraction": 0.6811347889, "num_tokens": 2327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6685952118572365}}
{"text": "#include \"Algorithms/ExpertIo/Level1.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <string>\n#include <vector>\n\nusing Algorithms::ExpertIo::EasyNonConstructibleChange::\n  non_constructible_change_sort;\nusing Algorithms::ExpertIo::NthFibonacci::get_nth_fibonacci_recursive;\nusing Algorithms::ExpertIo::is_valid_subsequence;\nusing Algorithms::ExpertIo::sorted_squared_array_algorithmic;\nusing Algorithms::ExpertIo::sorted_squared_array_two_indices;\nusing Algorithms::ExpertIo::sorted_squared_array_with_selection_sort;\nusing Algorithms::ExpertIo::tournament_winner;\nusing Algorithms::ExpertIo::two_number_sum_brute;\nusing Algorithms::ExpertIo::two_number_sum_with_map;\n\nusing std::string;\nusing std::vector;\n\nBOOST_AUTO_TEST_SUITE(Algorithms)\nBOOST_AUTO_TEST_SUITE(ExpertIo)\n\nBOOST_AUTO_TEST_SUITE(TwoNumberSum)\n\nconst vector<int> example_array {3, 5, -4, 8, 11, 1, -1, 6};\nconst int example_target_sum {10};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ExampleFindingAnyTwoArraySumBruteForce)\n{\n  const vector<int> brute_solution {\n    two_number_sum_brute(example_array, example_target_sum)};\n\n  BOOST_TEST(brute_solution[0] == 11);\n  BOOST_TEST(brute_solution[1] == -1);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ExampleFindingAnyTwoArraySumWithMap)\n{\n  const vector<int> map_solution {\n    two_number_sum_with_map(example_array, example_target_sum)};\n\n  BOOST_TEST(map_solution[0] == 11);\n  BOOST_TEST(map_solution[1] == -1);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // TwoNumberSum\n\nBOOST_AUTO_TEST_SUITE(ValidateSubsequence)\n\nconst vector<int> sample_array {5, 1, 22, 25, 6, -1, 8, 10};\nconst vector<int> sample_sequence {1, 6, -1, 10};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ExampleWithTwoPointers)\n{\n  BOOST_TEST(is_valid_subsequence(sample_array, sample_sequence));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // ValidateSubsequence\n\nBOOST_AUTO_TEST_SUITE(SortedSquaredArray)\n\nconst vector<int> sample_array {1, 2, 3, 4, 5, 6, 8, 9};\n\nconst vector<int> test_case_array_8 {-2, -1};\n\nconst vector<int> test_case_array_9 {-5, -4, -3, -2, -1};\n\nconst vector<int> test_case_array_11 {-10, -5, 0, 5, 10};\n\nconst vector<int> test_case_array_12 {-7, -3, 1, 9, 22, 30};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SortedSquaredArrayWithAlgorithmImplementation)\n{\n  const auto x = sorted_squared_array_algorithmic(sample_array);\n\n  auto iter_x = x.begin();\n\n  for (const auto& a : sample_array)\n  {\n    BOOST_TEST((a * a == *iter_x));\n\n    ++iter_x;\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareOfNegativeValuesGetsSorted)\n{\n  {\n    const auto x = sorted_squared_array_algorithmic(test_case_array_8);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 4);\n  }\n\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareOfNegativeValuesGetsSortedWithSelectionSort)\n{\n  {\n    const auto x = sorted_squared_array_with_selection_sort(test_case_array_9);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 4);\n    BOOST_TEST(x.at(2) == 9);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareOfPositiveValuesGetsSortedWithTwoIndices)\n{\n  {\n    const auto x = sorted_squared_array_two_indices(sample_array);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 4);\n    BOOST_TEST(x.at(2) == 9);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareOfNegativeValuesGetsSortedWithTwoIndices)\n{\n  {\n    const auto x = sorted_squared_array_two_indices(test_case_array_8);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 4);\n  }\n  {\n    const auto x = sorted_squared_array_two_indices(test_case_array_9);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 4);\n    BOOST_TEST(x.at(2) == 9);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(SquareOValuesGetsSortedWithTwoIndices)\n{\n  {\n    const auto x = sorted_squared_array_two_indices(test_case_array_11);\n\n    BOOST_TEST(x.at(0) == 0);\n    BOOST_TEST(x.at(1) == 25);\n    BOOST_TEST(x.at(2) == 25);\n  }\n  {\n    const auto x = sorted_squared_array_two_indices(test_case_array_12);\n\n    BOOST_TEST(x.at(0) == 1);\n    BOOST_TEST(x.at(1) == 9);\n    BOOST_TEST(x.at(2) == 49);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // SortedSquaredArray\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TournamentWinnerWithUnorderedMapWorks)\n{\n  const vector<vector<string>> competitions {\n    {\"HTML\", \"C#\"},\n    {\"C#\", \"Python\"},\n    {\"Python\", \"HTML\"}};\n\n  const vector<int> competition_results {0, 0, 1};\n\n  const string winner {tournament_winner(competitions, competition_results)};\n\n  BOOST_TEST(winner == \"Python\");\n}\n\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(TournamentWinnerWithUnorderedMapWorksForOtherTestCases)\n{\n  // Test case 9\n  {\n    const vector<vector<string>> competitions {\n      {\"HTML\", \"Java\"},\n      {\"Java\", \"Python\"},\n      {\"Python\", \"HTML\"},\n      {\"C#\", \"Python\"},\n      {\"Java\", \"C#\"},\n      {\"C#\", \"HTML\"},\n      {\"SQL\", \"C#\"},\n      {\"HTML\", \"SQL\"},\n      {\"SQL\", \"Python\"},\n      {\"SQL\", \"Java\"}};\n\n    const vector<int> competition_results {0, 0, 0, 0, 0, 0, 1, 0, 1, 1};\n\n    const string winner {tournament_winner(competitions, competition_results)};\n\n    BOOST_TEST(winner == \"SQL\");\n  }\n\n  // Test case 10\n  {\n    const vector<vector<string>> competitions {\n      {\"A\", \"B\"}};\n\n    const vector<int> competition_results {0};\n\n    const string winner {tournament_winner(competitions, competition_results)};\n\n    BOOST_TEST(winner == \"B\");\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(NonConstructibleChangeSortPassesSampleCases)\n{\n  {\n    const vector<int> given_coins {1, 2, 5};\n    const int expected {4};\n\n    const int result {non_constructible_change_sort(given_coins)};\n\n    BOOST_TEST(result == 6);\n  }\n\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(NonConstructibleChangePassesSampleCases)\n{\n  {\n    const vector<int> given_coins {1, 2, 5};\n    const int expected {4};\n\n\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE(NthFibonacci)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(FibonacciRecursiveComputesCorrectly)\n{\n  BOOST_TEST(get_nth_fibonacci_recursive(1) == 0);\n  BOOST_TEST(get_nth_fibonacci_recursive(2) == 1);\n  BOOST_TEST(get_nth_fibonacci_recursive(16) == 610);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // NthFibonacci\n\nBOOST_AUTO_TEST_SUITE_END() // ExpertIo\nBOOST_AUTO_TEST_SUITE_END() // Algorithms", "meta": {"hexsha": "a475f994f934a4e9d7befb781b5e0e8a6c249d00", "size": 8134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Algorithms/ExpertIo/Level1_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Algorithms/ExpertIo/Level1_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Algorithms/ExpertIo/Level1_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9044117647, "max_line_length": 80, "alphanum_fraction": 0.5161052373, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6685771859742717}}
{"text": "#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Eigen>\n#include <math.h>\n\nint main(int argc, char **argv)\n{\n\n    {\n        Eigen::Matrix3d m = Eigen::Matrix3d::Identity(); //\u751f\u6210\u5355\u4f4d\u77e9\u9635\n        std::cout << \"m^T:\" << std::endl\n                  << m.transpose() << std::endl; // transpose() \u8f6c\u7f6e\u540e\u8f93\u51fa\n\n        Eigen::Vector3d v1(3, 0, 0);\n        Eigen::Vector3d v2(0, 4, 0);\n        Eigen::Vector3d v3(0, 0, 5);\n        std::cout << \"v1^T:\" << std::endl\n                  << v1 << std::endl\n                  << \"v2^T:\" << std::endl\n                  << v2.transpose() << std::endl\n                  << \"v3^T:\" << std::endl\n                  << v3.transpose() << std::endl;\n\n        // m.block<1, 3>(0, 0)\n        // \u5206\u5757\u6bcf\u5757\u5927\u5c0f<1\u884c\uff0c3\u5217>\n        // \u53d6\u51fa\uff08\u7b2c0\u884c\uff0c\u7b2c0\u5217\uff09\u4e2a\u5757\n        m.block<1, 3>(0, 0) = v1.transpose();\n        m.block<1, 3>(1, 0) = v2.transpose();\n        m.block<1, 3>(2, 0) = v3.transpose();\n\n        std::cout << \"m:\" << std::endl\n                  << m << std::endl;\n\n        Eigen::Vector3d VecAll1;\n        VecAll1.fill(1); //\u5411\u91cf\u5404\u4e2a\u503c\u5168\u90e8\u586b\u5145\u4e3a1\n        std::cout << \"VecAll1^T:\" << std::endl\n                  << VecAll1.transpose() << std::endl;\n\n        Eigen::Vector3d normal = m.inverse() * VecAll1;\n        double NormalLen = normal.norm(); //\u5411\u91cf\u7684\u6a21\n        normal = normal / NormalLen;      //v1 v2 v3 \u6784\u6210\u5e73\u9762\u7684\u5355\u4f4d\u6cd5\u5411\u91cf\n        double d_plane_o = 1 / NormalLen; //\u5e73\u9762\u5230\u539f\u70b9\u7684\u8ddd\u79bb\n\n        std::cout << \"normal^T:\" << std::endl\n                  << normal.transpose() << std::endl;\n        std::cout << d_plane_o << std::endl;\n    }\n    return 0;\n}", "meta": {"hexsha": "2853914feb4a01a7cbfc2a25cd832b7aee344e81", "size": 1546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Examples/eigen/useeigen.cc", "max_stars_repo_name": "2hanhan/LearnCpp", "max_stars_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T08:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:51:21.000Z", "max_issues_repo_path": "Examples/eigen/useeigen.cc", "max_issues_repo_name": "2hanhan/LearnCpp", "max_issues_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "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": "Examples/eigen/useeigen.cc", "max_forks_repo_name": "2hanhan/LearnCpp", "max_forks_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "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.5510204082, "max_line_length": 69, "alphanum_fraction": 0.4676584735, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.668553416156272}}
{"text": "//!\n//! Contains the interface for the Gaussian distribution.\n//!\n//! \\file distrib/gaussian.hpp\n//! \\author Lachlan McCalman\n//! \\date February 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace obsidian\n{\n  namespace distrib\n  {\n    //! Compute the log Gaussian distribution PDF with a diagonal covariance matrix.\n    //!\n    //! \\param x The vector to evaluate the distribution at.\n    //! \\param mu The mean vector containing the means of each dimension.\n    //! \\param sigma The diagonal of the covariance matrix.\n    //!\n    double logGaussian(const Eigen::VectorXd& x, const Eigen::VectorXd& mu, const Eigen::VectorXd& sigma)\n    {\n      double coeff = -std::log(std::pow(2.0 * M_PI, x.size() * 0.5) * sigma.prod());\n      return coeff - 0.5 * (x - mu).cwiseQuotient(sigma).squaredNorm();\n    }\n  }\n}\n", "meta": {"hexsha": "05790b954c57e558d31b60ba0dd4ee64d4729311", "size": 925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distrib/gaussian.hpp", "max_stars_repo_name": "divad-nhok/obsidian_fork", "max_stars_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/distrib/gaussian.hpp", "max_issues_repo_name": "divad-nhok/obsidian_fork", "max_issues_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:46:58.000Z", "max_forks_repo_path": "src/distrib/gaussian.hpp", "max_forks_repo_name": "divad-nhok/obsidian_fork", "max_forks_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 28.0303030303, "max_line_length": 105, "alphanum_fraction": 0.6648648649, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6684742626069811}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 Fran\u00e7ois du Vignaud\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n\n#ifndef quantlib_tap_correlations_hpp\n#define quantlib_tap_correlations_hpp\n\n#include <ql/types.hpp>\n#include <ql/utilities/disposable.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/math/optimization/costfunction.hpp>\n#include <boost/function.hpp>\n#include <vector>\n\nnamespace QuantLib {\n\n    //! Returns the Triangular Angles Parametrized correlation matrix\n    /*! The matrix \\f$ m \\f$ is filled with values corresponding to angles\n        given in the \\f$ angles \\f$ vector. See equation (24) in\n        \"Parameterizing correlations: a geometric interpretation\"\n        by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio\n\n        \\test\n        - the correctness of the results is tested by reproducing\n          known good data.\n        - the correctness of the results is tested by checking\n          returned values against numerical calculations.\n    */\n    Disposable<Matrix>\n    triangularAnglesParametrization(const Array& angles,\n                                    Size matrixSize,\n                                    Size rank);\n\n    Disposable<Matrix>\n    lmmTriangularAnglesParametrization(const Array& angles,\n                                       Size matrixSize,\n                                       Size rank);\n\n    // the same function using the angles parameterized by the following\n    // transformation \\f[ \\teta_i = \\frac{\\Pi}{2} - arctan(x_i)\\f]\n    Disposable<Matrix>\n    triangularAnglesParametrizationUnconstrained(const Array& x,\n                                                 Size matrixSize,\n                                                 Size rank);\n\n    Disposable<Matrix>\n    lmmTriangularAnglesParametrizationUnconstrained(const Array& x,\n                                                    Size matrixSize,\n                                                    Size rank);\n\n\n    //! Returns the rank reduced Triangular Angles Parametrized correlation matrix\n    /*! The matrix \\f$ m \\f$ is filled with values corresponding to angles\n        corresponding  to the 3D spherical spiral paramterized by\n        \\f$ alpha \\f$, \\f$ t0 \\f$, \\f$ epsilon \\f$ values. See equation (32) in\n        \"Parameterizing correlations: a geometric interpretation\"\n        by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio\n\n        \\test\n        - the correctness of the results is tested by reproducing\n          known good data.\n        - the correctness of the results is tested by checking\n          returned values against numerical calculations.\n    */\n    Disposable<Matrix>\n    triangularAnglesParametrizationRankThree(Real alpha,\n                                             Real t0,\n                                             Real epsilon,\n                                             Size nbRows);\n\n    // the same function with parameters packed in an Array\n    Disposable<Matrix>\n    triangularAnglesParametrizationRankThreeVectorial(const Array& paramters,\n                                                      Size nbRows);\n\n    // Cost function associated with Frobenius norm.\n    // <http://en.wikipedia.org/wiki/Matrix_norm>\n    class FrobeniusCostFunction : public CostFunction{\n      public:\n        FrobeniusCostFunction(\n            const Matrix& target,\n            const boost::function<Disposable<Matrix>(const Array&,\n                                                     Size,\n                                                     Size)>& f,\n                                                     Size matrixSize,\n                                                     Size rank)\n        : target_(target), f_(f), matrixSize_(matrixSize), rank_(rank) {}\n        Real value (const Array &x) const;\n        Disposable<Array> values (const Array &x) const;\n      private:\n        Matrix target_;\n        boost::function<Disposable<Matrix>(const Array&, Size, Size)> f_;\n        Size matrixSize_;\n        Size rank_;\n    };\n}\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 Fran\u00e7ois du Vignaud\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <cmath>\n\nnamespace QuantLib {\n\n    inline Disposable<Matrix> triangularAnglesParametrization(const Array& angles,\n                                                       Size matrixSize,\n                                                       Size rank) {\n\n        // what if rank == 1?\n        QL_REQUIRE((rank-1) * (2*matrixSize - rank) == 2*angles.size(),\n                    \"rank-1) * (matrixSize - rank/2) == angles.size()\");\n        Matrix m(matrixSize, matrixSize);\n\n        // first row filling\n        m[0][0] = 1.0;\n        for (Size j=1; j<matrixSize; ++j)\n            m[0][j] = 0.0;\n\n        // next ones...\n        Size k = 0; //angles index\n        for (Size i=1; i<m.rows(); ++i) {\n            Real sinProduct = 1.0;\n            Size bound = std::min(i,rank-1);\n            for (Size j=0; j<bound; ++j) {\n                m[i][j] = std::cos(angles[k]);\n                m[i][j] *= sinProduct;\n                sinProduct *= std::sin(angles[k]);\n                ++k;\n            }\n            m[i][bound] = sinProduct;\n            for (Size j=bound+1; j<m.rows(); ++j)\n                m[i][j] = 0;\n        }\n        return m;\n    }\n\n    inline Disposable<Matrix> lmmTriangularAnglesParametrization(const Array& angles,\n                                                          Size matrixSize,\n                                                          Size) {\n        Matrix m(matrixSize, matrixSize);\n        for (Size i=0; i<m.rows(); ++i) {\n            Real cosPhi, sinPhi;\n            if (i>0) {\n                cosPhi = std::cos(angles[i-1]);\n                sinPhi = std::sin(angles[i-1]);\n            } else {\n                cosPhi = 1.0;\n                sinPhi = 0.0;\n            }\n\n            for (Size j=0; j<i; ++j)\n                m[i][j] = sinPhi * m[i-1][j];\n\n            m[i][i] = cosPhi;\n\n            for (Size j=i+1; j<m.rows(); ++j)\n                m[i][j] = 0.0;\n        }\n        return m;\n    }\n\n    inline Disposable<Matrix> triangularAnglesParametrizationUnconstrained(\n                                                            const Array& x,\n                                                            Size matrixSize,\n                                                            Size rank) {\n        Array angles(x.size());\n        //we convert the unconstrained parameters in angles\n        for (Size i = 0; i < x.size(); ++i)\n            angles[i] = M_PI*.5 - std::atan(x[i]);\n        return triangularAnglesParametrization(angles, matrixSize, rank);\n    }\n\n    inline Disposable<Matrix> lmmTriangularAnglesParametrizationUnconstrained(\n                                                            const Array& x,\n                                                            Size matrixSize,\n                                                            Size rank) {\n        Array angles(x.size());\n        //we convert the unconstrained parameters in angles\n        for (Size i = 0; i < x.size(); ++i)\n            angles[i] = M_PI*.5 - std::atan(x[i]);\n        return lmmTriangularAnglesParametrization(angles, matrixSize, rank);\n    }\n\n    inline Disposable<Matrix> triangularAnglesParametrizationRankThree(\n                                            Real alpha, Real t0,\n                                            Real epsilon, Size matrixSize) {\n        Matrix m(matrixSize, 3);\n        for (Size i=0; i<m.rows(); ++i) {\n            Real t = t0 * (1 - std::exp(epsilon*Real(i)));\n            Real phi = std::atan(alpha * t);\n            m[i][0] = std::cos(t)*std::cos(phi);\n            m[i][1] = std::sin(t)*std::cos(phi);\n            m[i][2] = -std::sin(phi);\n        }\n        return m;\n    }\n\n    inline Disposable<Matrix> triangularAnglesParametrizationRankThreeVectorial(\n                                                    const Array& parameters,\n                                                    Size nbRows) {\n        QL_REQUIRE(parameters.size() == 3,\n                   \"the parameter array must contain exactly 3 values\" );\n        return triangularAnglesParametrizationRankThree(parameters[0],\n                                                        parameters[1],\n                                                        parameters[2],\n                                                        nbRows);\n\n    }\n\n  inline Real FrobeniusCostFunction::value(const Array& x) const {\n        Array temp = values(x);\n        return DotProduct(temp, temp);\n    }\n\n  inline Disposable<Array> FrobeniusCostFunction::values(const Array& x) const {\n        Array result((target_.rows()*(target_.columns()-1))/2);\n        Matrix pseudoRoot = f_(x, matrixSize_, rank_);\n        Matrix differences = pseudoRoot * transpose(pseudoRoot) - target_;\n        Size k = 0;\n        // then we store the elementwise differences in a vector.\n        for (Size i=0; i<target_.rows(); ++i) {\n            for (Size j=0; j<i; ++j){\n                result[k] = differences[i][j];\n                ++k;\n            }\n        }\n        return result;\n    }\n}\n\n\n#endif\n", "meta": {"hexsha": "76424e19f926ebc7bdaaa2fdf58796b2a9f273d5", "size": 10487, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/matrixutilities/tapcorrelations.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/matrixutilities/tapcorrelations.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/matrixutilities/tapcorrelations.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 39.5735849057, "max_line_length": 85, "alphanum_fraction": 0.5306570039, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6684742308374823}}
{"text": "/* Main routine to run an implicit 3-node Lobatto finite-difference method\n   for solution of a second-order, scalar-valued BVP:\n\n      u'' = p(t)*u' + q(t)*u + r(t),  a<t<b,\n      u(a) = ua,  u(b) = ub\n\n   where the problem has stiffness that may be adjusted using\n   the real-valued parameter lambda<0 [read from the command line]\n\n   D.R. Reynolds\n   Math 6321 @ SMU\n   Fall 2020  */\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <armadillo>\n#include \"bvp.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n// utility routine to map from physical/component space to linear algebra index space\n//    interval:  physical interval index [1 <= interval <= N]\n//    location:  location in interval [0=left, 1=midpoint, 2=right]\n//    component: solution component at this location [0=u, 1=u']\nint idx(int interval, int location, int component) {\n  return ( 4*(interval-1) + 2*location + component );\n}\n\n\n// main routine\nint main(int argc, char **argv) {\n\n  // get lambda from the command line, otherwise set to -10\n  double lambda;\n  if (argc > 1)\n    lambda = atof(argv[1]);\n  if (lambda >= 0.0)\n    lambda = -10.0;\n\n  // define BVP object\n  BVP bvp(lambda);\n\n  // test 'idx' function by outputting mapping for small N\n  cout << \"Test output from 'idx' function for N = 5, M = 22:\";\n  for (int interval=1; interval<=5; interval++) {\n    cout << \"\\n  interval \" << interval << \", (loc,comp,idx):\";\n    for (int location=0; location<=2; location++) {\n      for (int component=0; component<=1; component++) {\n        cout << \"  (\" << location << \", \" << component << \", \"\n             << idx(interval,location,component) << \")\";\n      }\n    }\n  }\n\n  // loop over spatial resolutions for tests\n  vector<int> N = {100, 1000, 10000};\n  for (int i=0; i<N.size(); i++) {\n\n    // output problem information\n    cout << \"\\nImplicit Lobatto-3 FD method for BVP with lambda = \"\n         << lambda << \":\" << \",  N = \" << N[i] << endl;\n\n    // compute/store analytical solution\n    vec t = zeros(N[i]+1);\n    t(0) = 0.0;\n    t(N[i]) = 1.0;\n    for (int j=1; j<=N[i]-1; j++)\n      t(j) = 0.5*(1.0-cos((2*j-1)*M_PI/(2*(N[i]-1))));\n    vec utrue(N[i]+1);\n    for (int j=0; j<=N[i]; j++)\n      utrue(j) = bvp.utrue(t(j));\n\n    // set integer for overall linear algebra problem size\n    int M = 4*N[i]+2;\n\n    // create matrix and right-hand side vectors\n#ifdef USE_SPARSE\n    sp_mat A(M,M);\n#else\n    mat A(M,M);\n    A.fill(0.0);\n#endif\n    vec b(M);\n    b.fill(0.0);\n\n    // set up linear system:\n    //    recall 'idx' usage: idx(interval,location,component)\n    //      interval:  physical interval index [1 <= interval <= N]\n    //      location:  location in interval [0=left, 1=midpoint, 2=right]\n    //      component: solution component at this location [0=u, 1=u']\n    A(0,idx(1,0,0)) = 1.0;\n    b(0) = bvp.ua;\n    A(1,idx(N[i],2,0)) = 1.0;\n    b(1) = bvp.ub;\n    int irow = 2;\n    for (int j=1; j<=N[i]; j++) {\n\n      // setup interval-specific information\n      double tl = t(j-1);\n      double tr = t(j);\n      double th = 0.5*(tl+tr);\n      double h = tr-tl;\n\n      // setup first equation for this interval:\n      //    -24*y_{j-1,0} - 5*h*y_{j-1,1} + 24*y_{j-1/2,0} - 8*h*y_{j-1/2,1} + h*y_{j,1} = 0\n      A(irow,idx(j,0,0)) = -24.0;\n      A(irow,idx(j,0,1)) = -5.0*h;\n      A(irow,idx(j,1,0)) = 24.0;\n      A(irow,idx(j,1,1)) = -8.0*h;\n      A(irow,idx(j,2,1)) = h;\n      b(irow) = 0.0;\n      irow++;\n\n      // setup second equation for this interval:\n      //    -5*h*q_{j-1}*y_{j-1,0} - (24+5*h*p_{j-1})*y_{j-1,1} - 8*h*q_{j-1/2}*y_{j-1/2,0}\n      //      + (24-8*h*p_{j-1/2})*y_{j-1/2,1} + h*q_{j}*y_{j,0} + h*p_{j}*y_{j,1} = h*(5*r_{j-1}+8*r_{j-1/2}-r_{j})\n      A(irow,idx(j,0,0)) = -5.0*h*bvp.q(tl);\n      A(irow,idx(j,0,1)) = -(24.0 + 5.0*h*bvp.p(tl));\n      A(irow,idx(j,1,0)) = -8.0*h*bvp.q(th);\n      A(irow,idx(j,1,1)) = (24.0-8.0*h*bvp.p(th));\n      A(irow,idx(j,2,0)) = h*bvp.q(tr);\n      A(irow,idx(j,2,1)) = h*bvp.p(tr);\n      b(irow) = h*(5.0*bvp.r(tl) + 8.0*bvp.r(th) - bvp.r(tr));\n      irow++;\n\n      // setup third equation for this interval:\n      //    -6*y_{j-1,0} - h*y_{j-1,1} - 4*h*y_{j-1/2,1} + 6*y_{j,0} - h*y_{j,1} = 0\n      A(irow,idx(j,0,0)) = -6.0;\n      A(irow,idx(j,0,1)) = -h;\n      A(irow,idx(j,1,1)) = -4.0*h;\n      A(irow,idx(j,2,0)) = 6.0;\n      A(irow,idx(j,2,1)) = -h;\n      b(irow) = 0.0;\n      irow++;\n\n      // setup fourth equation for this interval:\n      //    -h*q_{j-1}*y_{j-1,0} - (6+h*p_{j-1})*y_{j-1,1} - 4*h*q_{j-1/2}*y_{j-1/2,0} - 4*h*p_{j-1/2}*y_{j-1/2,1}\n      //       - h*q_j*y_{j,0} + (6-h*p_j)*y_{j,1} = h*(r_{j-1} + 4*r_{j-1/2} + r_{j})\n      A(irow,idx(j,0,0)) = -h*bvp.q(tl);\n      A(irow,idx(j,0,1)) = -(6.0 + h*bvp.p(tl));\n      A(irow,idx(j,1,0)) = -4.0*h*bvp.q(th);\n      A(irow,idx(j,1,1)) = -4.0*h*bvp.p(th);\n      A(irow,idx(j,2,0)) = -h*bvp.q(tr);\n      A(irow,idx(j,2,1)) = (6.0-h*bvp.p(tr));\n      b(irow) = h*(bvp.r(tl) + 4.0*bvp.r(th) + bvp.r(tr));\n      irow++;\n\n    }\n\n    // solve linear system for BVP solution\n#ifdef USE_SPARSE\n    vec y = arma::spsolve(A,b);\n#else\n    vec y = arma::solve(A,b);\n#endif\n\n    // output maximum error\n    vec u(N[i]+1);\n    for (int j=0; j<=N[i]; j++)\n      u(j) = y(idx(j+1,0,0));\n    vec uerr = abs(u-utrue);\n    cout << \"  Maximum BVP solution error = \" << std::setprecision(4)\n       << uerr.max() << \"\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "370fa08c7321bf29ad5dffce4c29e79db5010a43", "size": 5358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bvp/lobatto_driver.cpp", "max_stars_repo_name": "drreynolds/Math6321-codes", "max_stars_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "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": "bvp/lobatto_driver.cpp", "max_issues_repo_name": "drreynolds/Math6321-codes", "max_issues_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "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": "bvp/lobatto_driver.cpp", "max_forks_repo_name": "drreynolds/Math6321-codes", "max_forks_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T18:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T18:04:07.000Z", "avg_line_length": 31.5176470588, "max_line_length": 116, "alphanum_fraction": 0.5242627846, "num_tokens": 2057, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.668357799840817}}
{"text": "/* \n// Copyright 2018 University of Liege\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// Authors:\n// - Adrien Crovato\n*/\n\n//// Bilinear interpolation\n// Interpolate linearly a quantity defined at 4 points to another point\n//\n// Inputs:\n// - x0, x1, x2, x3: x-coordinates of interpolation points\n// - y0, y1, y2, y3: y-coordinates of interpolation points\n// - z0, z1, z2, z3: z-coordinates of interpolation points\n// - s0, s1, s2, s3: quantity to interpolate at interpolation point\n// - x, y, z: coordinates of interpolated point\n//\n// Output:\n// - i: interpolated quantity\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"interp.h\"\n\n#define TOL 1e-2 // geometric tolerance on z (measure how far target point is w.r.t. interpolation plane)\n\nusing namespace std;\nusing namespace Eigen;\n\ndouble interp(double x0, double y0, double z0, double x1, double y1, double z1,\n              double x2, double y2, double z2, double x3, double y3, double z3,\n              double s0, double s1, double s2, double s3,\n              double x, double y, double z) {\n\n    //// Initialization\n    Vector3d l, p, n; // unit vector\n    Vector3d cg; // CG of planed formed by interpolation points\n    Vector2d A, B, C, D, X; // (rotated) interpolation and interpolated points\n    Vector2d E, F, G, H; // temporary vector\n    double zd, avg; // distance between interpolated point and interpolation plane & plane diagonal\n    double k2, k1, k0, Delta; // coefficients of k2*x^2 + k1*x + k0 and discriminant\n    double u, v ;// inverse bilinear interpolation parameters\n    double i0, i1, i ;// interpolated quantities\n\n    //// Move change of coordinates out of file to improve CPU runtime\n    //// Change of axes\n    // Plane center\n    cg(0) = 0.25*(x0 + x1 + x2 + x3);\n    cg(1) = 0.25*(y0 + y1 + y2 + y3);\n    cg(2) = 0.25*(z0 + z1 + z2 + z3);\n    // Unit vectors\n    l(0) = 0.5*(0.5*(x0+x3)-0.5*(x1+x2));\n    l(1) = 0.5*(0.5*(y0+y3)-0.5*(y1+y2));\n    l(2) = 0.5*(0.5*(z0+z3)-0.5*(z1+z2));\n    n(0) = (y2-y0)*(z1-z3) - (z2-z0)*(y1-y3);\n    n(1) = (z2-z0)*(x1-x3) - (x2-x0)*(z1-z3);\n    n(2) = (x2-x0)*(y1-y3) - (y2-y0)*(x1-x3);\n    p = n.cross(l);\n    l = l / l.norm(); // normalize\n    p = p / p.norm(); // normalize\n    n = n / n.norm(); // normalize\n    // Translation & Rotation\n    A(0) = l(0)*(cg(0)-x0) + l(1)*(cg(1)-y0) + l(2)*(cg(2)-z0);\n    A(1) = p(0)*(cg(0)-x0) + p(1)*(cg(1)-y0) + p(2)*(cg(2)-z0);\n    B(0) = l(0)*(cg(0)-x1) + l(1)*(cg(1)-y1) + l(2)*(cg(2)-z1);\n    B(1) = p(0)*(cg(0)-x1) + p(1)*(cg(1)-y1) + p(2)*(cg(2)-z1);\n    C(0) = l(0)*(cg(0)-x2) + l(1)*(cg(1)-y2) + l(2)*(cg(2)-z2);\n    C(1) = p(0)*(cg(0)-x2) + p(1)*(cg(1)-y2) + p(2)*(cg(2)-z2);\n    D(0) = l(0)*(cg(0)-x3) + l(1)*(cg(1)-y3) + l(2)*(cg(2)-z3);\n    D(1) = p(0)*(cg(0)-x3) + p(1)*(cg(1)-y3) + p(2)*(cg(2)-z3);\n    X(0) = l(0)*(cg(0)-x) + l(1)*(cg(1)-y) + l(2)*(cg(2)-z);\n    X(1) = p(0)*(cg(0)-x) + p(1)*(cg(1)-y) + p(2)*(cg(2)-z);\n    // Error measure\n    avg = sqrt((x2-x0)*(x2-x0) + (y2-y0)*(y2-y0) + (z2-z0)*(z2-z0));\n    zd = n(0)*(x-cg(0)) + n(1)*(y-cg(1)) + n(2)*(z-cg(2));\n    #ifdef VERBOSE\n    if (abs(zd/avg) > TOL) {\n        cout << endl << \"Interpolated point is far from interpolation plane; bilinear interpolation might be inaccurate!\" << endl;\n        cout << \"Distance versus interpolation plane diagonal: \" << zd << \" / \" << avg << \" > \" << TOL << endl;\n        cout << \"This might be caused by a coarse panelling of the body surface.\" << endl;\n    }\n    #endif\n\n    //// Interpolation\n    // Intermediate vectors\n    E = B-A;\n    F = D-A;\n    G = (A-B) + (C-D);\n    H = X-A;\n    // Coefficients\n    k2 = G(0)*F(1) - G(1)*F(0); //\n    k1 = E(0)*F(1) - E(1)*F(0) + H(0)*G(1) - H(1)*G(0);\n    k0 = H(0)*E(1) - H(1)*E(0);\n    // Solve quadratic equation\n    if (k2 == 0) {\n        v = -k0/k1;\n    }\n    else {\n        Delta = k1*k1 - 4*k2*k0;\n        if (Delta < 0) {\n            cout << endl << \"Discriminant of inverse bilinear interpolation is negative. Cannot interpolate!\" << endl;\n            exit(EXIT_FAILURE);\n        }\n        else if (Delta == 0) {\n            v = (-k1) / (2.0*k2);\n        }\n        else {\n            Delta = sqrt(Delta);\n            v = (-k1 - Delta) / (2.0*k2);\n        }\n    }\n    u = (H(0) - F(0)*v) / (E(0) + G(0)*v);\n    // Interpolation along l\n    i0 = (1-u)*s0 + u*s1;\n    i1 = (1-u)*s3 + u*s2;\n    // Interpolation along p\n    i = (1-v)*i0 + v*i1;\n    return i;\n}", "meta": {"hexsha": "9cf8d2b50badeed80f445f7753d09aeacbfec91e", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interp.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/interp.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "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/interp.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4732824427, "max_line_length": 130, "alphanum_fraction": 0.5483805256, "num_tokens": 1825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6683577838223973}}
{"text": "#include \"setup.h\"\n\n#include <NTL/ZZXFactoring.h>\n\n#include \"util.h\"\n\nnamespace {\n    using namespace NTL;\n}\n\nnamespace gnfs {\n    ZZ check_f_irred(const ZZX& f, const ZZ& m) {\n        ZZ c;\n        vec_pair_ZZX_long factors;\n\n        factor(c, factors, f);\n\n        // just evaluate at first factor\n        // if irreducible, this spits out f(m)\n        return eval(factors[0].a, m);\n    }\n}\n", "meta": {"hexsha": "6a0ddb3cc76b00531549b802f5efd4b9bde25e7a", "size": 393, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/setup.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/setup.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/setup.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": 17.0869565217, "max_line_length": 49, "alphanum_fraction": 0.5928753181, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6683577739432657}}
{"text": "/*\n * test_EMA.cpp\n *\n *  Created on: 2013-4-10\n *      Author: fasiondog\n */\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <fstream>\n#include <hikyuu/StockManager.h>\n#include <hikyuu/indicator/crt/EMA.h>\n#include <hikyuu/indicator/crt/KDATA.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n#include <hikyuu/indicator/crt/MA.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_EMA test_indicator_EMA\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_EMA ) {\n    PriceList d;\n    for (int i = 0; i < 30; ++i) {\n        d.push_back(i);\n    }\n\n    /** @arg n = 1 */\n    Indicator data = PRICELIST(d);\n    Indicator ema = EMA(data, 1);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(ema[10] == 10.0);\n    BOOST_CHECK(ema[29] == 29.0);\n\n    /** @arg n = 2 */\n    ema = EMA(data, 2);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(std::fabs(ema[1] - 0.66667) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[2] - 1.55556) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[3] - 2.51852) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[4] - 3.50617) < 0.0001);\n\n    /** @arg n = 10 */\n    ema = EMA(data, 10);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(std::fabs(ema[1] - 0.18182) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[2] - 0.51240) < 0.0001);\n\n#if 0 //\u7531\u4e8e\u4fee\u6539\u4e86SMA\u8ba1\u7b97\u8fc7\u7a0b\uff0cMA\u7684\u629b\u5f03\u6570\u91cf\u4e3a\u96f6\uff0c\u4e0b\u9762\u7684\u6d4b\u8bd5\u7528\u4f8b\u5931\u6548\n    /** @arg \u5f85\u8ba1\u7b97\u7684\u6570\u636e\u5b58\u5728\u975e\u96f6\u7684discard */\n    Indicator ma = MA(data, 2);\n    ema = EMA(ma, 2);\n    BOOST_CHECK(ma.discard() == 1);\n    BOOST_CHECK(ema.discard() == 1);\n    BOOST_CHECK(ma[0] == Null<price_t>());\n    BOOST_CHECK(ma[1] == 0.5);\n    BOOST_CHECK(ma[2] == 1.5);\n    BOOST_CHECK(ema[0] == Null<price_t>());\n    BOOST_CHECK(ema[1] == 0.5);\n    BOOST_CHECK(std::fabs(ema[2] - 1.16667) < 0.0001 );\n#endif\n\n    /** @arg operator() */\n    Indicator ma = MA(data, 2);\n    Indicator expect = EMA(ma, 2);\n    ema = EMA(2);\n    Indicator result = ema(ma);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result[i] == expect[i]);\n    }\n}\n\n\n//-----------------------------------------------------------------------------\n// test export\n//-----------------------------------------------------------------------------\n#if HKU_SUPPORT_SERIALIZATION\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_EMA_export ) {\n    StockManager& sm = StockManager::instance();\n    string filename(sm.tmpdir());\n    filename += \"/EMA.xml\";\n\n    Stock stock = sm.getStock(\"sh000001\");\n    KData kdata = stock.getKData(KQuery(-20));\n    Indicator ma1 = EMA(CLOSE(kdata), 10);\n    {\n        std::ofstream ofs(filename);\n        boost::archive::xml_oarchive oa(ofs);\n        oa << BOOST_SERIALIZATION_NVP(ma1);\n    }\n\n    Indicator ma2;\n    {\n        std::ifstream ifs(filename);\n        boost::archive::xml_iarchive ia(ifs);\n        ia >> BOOST_SERIALIZATION_NVP(ma2);\n    }\n\n    BOOST_CHECK(ma1.size() == ma2.size());\n    BOOST_CHECK(ma1.discard() == ma2.discard());\n    BOOST_CHECK(ma1.getResultNumber() == ma2.getResultNumber());\n    for (size_t i = 0; i < ma1.size(); ++i) {\n        BOOST_CHECK_CLOSE(ma1[i], ma2[i], 0.00001);\n    }\n}\n#endif /* #if HKU_SUPPORT_SERIALIZATION */\n\n/** @} */\n\n", "meta": {"hexsha": "8d5dd3bfdb395981c8774545e3b757ca3fb9aab9", "size": 3496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_stars_repo_name": "archya/hikyuu", "max_stars_repo_head_hexsha": "2305a977a78bab832bf8fcb4d66482dfef442c9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-12T23:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-12T23:48:13.000Z", "max_issues_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_issues_repo_name": "allen9mu/hikyuu", "max_issues_repo_head_hexsha": "bed68183029e5a653e3e0ad53510036605e1d610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T03:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-16T03:23:15.000Z", "max_forks_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_forks_repo_name": "archya/hikyuu", "max_forks_repo_head_hexsha": "2305a977a78bab832bf8fcb4d66482dfef442c9d", "max_forks_repo_licenses": ["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.5275590551, "max_line_length": 79, "alphanum_fraction": 0.5735125858, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6683254618864256}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <boost/core/demangle.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/math/quadrature/wavelet_transforms.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::constants::pi;\nusing boost::math::constants::root_two;\nusing boost::math::quadrature::daubechies_wavelet_transform;\nusing boost::math::quadrature::trapezoidal;\n\ntemplate<typename Real, int p>\nvoid test_wavelet_transform()\n{\n    std::cout << \"Testing wavelet transform of \" << p << \" vanishing moment Daubechies wavelet on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    auto psi = boost::math::daubechies_wavelet<Real, p>();\n\n    auto abs_psi = [&psi](Real x) {\n        return abs(psi(x));\n    };\n    auto [a, b] = psi.support();\n    auto psil1 = trapezoidal(abs_psi, a, b);\n    Real psi_sup_norm = 0;\n    for (double x = a; x < b; x += 0.0001)\n    {\n        Real y = psi(x);\n        if (std::abs(y) > psi_sup_norm)\n        {\n            psi_sup_norm = std::abs(y);\n        }\n    }\n    std::cout << \"psi sup norm = \" << psi_sup_norm << \"\\n\";\n    // An even function:\n    auto f = [](Real x) {\n        return std::exp(-abs(x));\n    };\n    Real fmax = 1;\n    Real fl2 = 1;\n    Real fl1 = 2;\n    std::cout << \"||f||_1 = \" << fl1 << \"\\n\";\n    std::cout << \"||f||_2 = \" << fl2 << \"\\n\";\n\n    auto Wf = daubechies_wavelet_transform(f, psi);\n    for (double s = 0; s < 10; s += 0.01)\n    {\n        Real w1 = Wf(s, 0.0);\n        Real w2 = Wf(-s, 0.0);\n        // Since f is an even function, we get w1 = w2:\n        CHECK_ULP_CLOSE(w1, w2, 12);\n    }\n\n    // The wavelet transform with respect to Daubechies wavelets \n    for (double s = -10; s < 10; s += 0.1)\n    {\n        for (double t = -10; t < 10; t+= 0.1)\n        {\n            Real w = Wf(s, t);\n            // Integral inequality:\n            Real r1 = sqrt(abs(s))*fmax*psil1;\n            if(abs(w) > r1)\n            {\n                std::cerr << \" Integral inequality | int fg| <= ||f||_infty ||psi||_1 is violated.\\n\";\n            }\n            if (s != 0)\n            {\n                Real r2 = fl1*psi_sup_norm/sqrt(abs(s));\n                if(abs(w) > r2)\n                {\n                    std::cerr << \" Integral inequality | int fg| <= ||f||_1 ||psi||_infty/sqrt(|s|) is violated.\\n\";\n                    std::cerr << \" Violation: \" << abs(w) << \" !<= \" << r2 << \"\\n\";\n                }\n                Real r3 = fmax*psil1/sqrt(abs(s));\n                if(abs(w) > r3)\n                {\n                    std::cerr << \" Integral inequality | int fg| <= ||f||_infty ||psi||_1/sqrt(|s|) is violated.\\n\";\n                    std::cerr << \" Computed = \" << abs(w) << \", expected \" << r3 << \"\\n\";\n                }\n            }\n            if (abs(w) > fl2)\n            {\n                std::cerr << \"  Integral inequality |f psi_s,t| <= ||f||_2 ||psi||2 violated.\\n\";\n            }\n            Real r4 = sqrt(abs(s))*fl1*psi_sup_norm;\n            if (abs(w) > r4)\n            {\n                std::cerr << \"  Integral inequality |W[f](s,t)| <= sqrt(|s|)||f||_1 ||psi||_infty is violated.\\n\";\n            }\n            Real r5 = sqrt(abs(s))*fmax*psil1;\n            if (abs(w) > r5)\n            {\n                std::cerr << \"  Integral inequality |W[f](s,t)| <= sqrt(|s|)||f||_infty ||psi||_1 is violated.\\n\";\n            }\n\n        }\n    }\n}\n\nint main()\n{\n    boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i) {\n        test_wavelet_transform<double, i+3>();\n    });\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "25ed881dcf46355190e58d829c532b0fcb6c7215", "size": 4075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/wavelet_transform_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/wavelet_transform_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:54:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:25:14.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/wavelet_transform_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 32.6, "max_line_length": 159, "alphanum_fraction": 0.5185276074, "num_tokens": 1195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.668273746744391}}
{"text": "#pragma once\n\n#include <type_traits>\n\ntemplate <int N, int K>\nconstexpr auto Stirling2nd()\n{\n    if constexpr (K >= N || K <= 1)\n    {\n        return std::integral_constant<int, 1> {};\n    }\n    else\n    {\n        return std::integral_constant<int,\n            Stirling2nd<N - 1, K - 1>() + K * Stirling2nd<N - 1, K>()> {};\n    }\n}\n\n// Set Partition\n//\n// A set partition of the set [n] = {1,2,3,...,n} is a collection B0,\n// B1, ... Bj of disjoint subsets of [n] whose union is [n]. Each Bj\n// is called a block. Below we show the partitions of [4]. The periods\n// separtate the individual sets so that, for example, 1.23.4 is the\n// partition {{1},{2,3},{4}}.\n//   1 block:  1234\n//   2 blocks: 123.4   124.3   134.2   1.234   12.34   13.24   14.23\n//   3 blocks: 1.2.34  1.24.3  14.2.3  13.2.4  12.3.4\n//   4 blocks: 1.2.3.4\n//\n// Each partition above has its blocks listed in increasing order of\n// smallest element; thus block 0 contains element 1, block1 contains\n// the smallest element not in block 0, and so on. A Restricted Growth\n// string (or RG string) is a sring a[1..n] where a[i] is the block in\n// whcih element i occurs. Restricted Growth strings are often called\n// restricted growth functions. Here are the RG strings corresponding\n// to the partitions shown above.\n//\n//   1 block:  0000\n//   2 blocks: 0001, 0010, 0100, 0111, 0011, 0101, 0110\n//   3 blocks: 0122, 0121, 0112, 0120, 0102,\n//\n// ...more\n//\n// Reference:\n// Frank Ruskey. Simple combinatorial Gray codes constructed by\n// reversing sublists. Lecture Notes in Computer Science, #762,\n// 201-208. Also downloadable from\n// http://webhome.cs.uvic.ca/~ruskey/Publications/SimpleGray/SimpleGray.html\n//\n#include <boost/coroutine2/all.hpp>\n#include <cassert>\n#include <cctype>\n#include <cstdio>\n#include <functional>\n#include <utility>\n\nclass set_partition_\n{\n    using ret_t = std::tuple<int, int>;\n    using Fun = std::function<void(ret_t)>;\n\n  private:\n    // int b[100 + 1]; /* maximum value of n */\n    // int cnt{};\n    Fun yield;\n\n  public:\n    /**\n     * @brief Construct object\n     *\n     * @param[in] yield_\n     */\n    explicit set_partition_(Fun yield_)\n        : yield(std::move(yield_))\n    {\n    }\n\n    /**\n     * @brief\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void run(int n, int k)\n    {\n        if (k % 2 == 0)\n        {\n            this->_GEN0_even(n, k);\n        }\n        else\n        {\n            this->_GEN0_odd(n, k);\n        }\n    }\n\n  private:\n    /**\n     * @brief Move\n     *\n     * @param[in] x\n     * @param[in] y\n     */\n    void _Move(int x, int y)\n    {\n        yield(std::tuple {x, y});\n    }\n\n    /**\n     * @brief S(n,k,0) even k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _GEN0_even(int n, int k);\n\n    /**\n     * @brief S'(n,k,0) even k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _NEG0_even(int n, int k);\n\n    /**\n     * @brief S(n,k,1) even k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _GEN1_even(int n, int k);\n\n    /**\n     * @brief S'(n,k,1) even k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _NEG1_even(int n, int k);\n\n    /**\n     * @brief S(n,k,0) odd k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _GEN0_odd(int n, int k);\n\n    /**\n     * @brief S'(n,k,0) odd k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _NEG0_odd(int n, int k);\n\n    /**\n     * @brief S(n,k,1) odd k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _GEN1_odd(int n, int k);\n\n    /**\n     * @brief S'(n,k,1) odd k\n     *\n     * @param[in] n\n     * @param[in] k\n     */\n    void _NEG1_odd(int n, int k);\n};\n\nusing ret_t = std::tuple<int, int>;\nusing coro_t = boost::coroutines2::coroutine<ret_t>;\n\nextern coro_t::pull_type set_partition(int n, int k);\n", "meta": {"hexsha": "2bd34b927e9b4d0a2fb5c651bc7f2b5fc500bfba", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/ckpttncpp/set_partition.hpp", "max_stars_repo_name": "luk036/ckpttncpp", "max_stars_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "max_stars_repo_licenses": ["MIT"], "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/ckpttncpp/set_partition.hpp", "max_issues_repo_name": "luk036/ckpttncpp", "max_issues_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "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/ckpttncpp/set_partition.hpp", "max_forks_repo_name": "luk036/ckpttncpp", "max_forks_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-17T02:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T02:40:02.000Z", "avg_line_length": 21.3707865169, "max_line_length": 76, "alphanum_fraction": 0.5381177708, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.66821651787747}}
{"text": "/*\n * stuart_landau.cpp\n *\n * This example demonstrates how one can use odeint can be used with state types consisting of complex variables.\n *\n * Copyright 2009-2012 Karsten Ahnert and Mario Mulansky.\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\n#include <iostream>\n#include <complex>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ stuart_landau_system_function\ntypedef complex< double > state_type;\n\nstruct stuart_landau\n{\n    double m_eta;\n    double m_alpha;\n\n    stuart_landau( double eta = 1.0 , double alpha = 1.0 )\n    : m_eta( eta ) , m_alpha( alpha ) { }\n\n    void operator()( const state_type &x , state_type &dxdt , double t ) const\n    {\n        const complex< double > I( 0.0 , 1.0 );\n        dxdt = ( 1.0 + m_eta * I ) * x - ( 1.0 + m_alpha * I ) * norm( x ) * x;\n    }\n};\n//]\n\n\n/*\n//[ stuart_landau_system_function_alternative\ndouble eta = 1.0;\ndouble alpha = 1.0;\n\nvoid stuart_landau( const state_type &x , state_type &dxdt , double t )\n{\n    const complex< double > I( 0.0 , 1.0 );\n    dxdt[0] = ( 1.0 + m_eta * I ) * x[0] - ( 1.0 + m_alpha * I ) * norm( x[0] ) * x[0];\n}\n//]\n*/\n\n\nstruct streaming_observer\n{\n    std::ostream& m_out;\n\n    streaming_observer( std::ostream &out ) : m_out( out ) { }\n\n    template< class State >\n    void operator()( const State &x , double t ) const\n    {\n        m_out << t;\n        m_out << \"\\t\" << x.real() << \"\\t\" << x.imag() ;\n        m_out << \"\\n\";\n    }\n};\n\n\n\n\nint main( int argc , char **argv )\n{\n    //[ stuart_landau_integration\n    state_type x = complex< double >( 1.0 , 0.0 );\n\n    const double dt = 0.1;\n\n    typedef runge_kutta4< state_type , double , state_type , double , \n                          vector_space_algebra > stepper_type;\n\n    integrate_const( stepper_type() , stuart_landau( 2.0 , 1.0 ) , x , 0.0 , 10.0 , dt , streaming_observer( cout ) );\n    //]\n\n    return 0;\n}\n", "meta": {"hexsha": "10891b59686ca61c306cb93559e61a70ed161462", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.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/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.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/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.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": 23.2727272727, "max_line_length": 118, "alphanum_fraction": 0.611328125, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6682165150827575}}
{"text": "#include <cstdlib>\n#include <cstdio>\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nint main()\n{\n    size_t L = 100;\n\n    boost::random::random_device rd;\n    boost::random::mt19937_64 rng(rd);\n    boost::random::uniform_int_distribution<int64_t> dist0L(0,L);\n\n    printf(\"Maximum value of distribution: %ld\\n\\n\", dist0L.max());\n    for(size_t i = 0; i < 10; i++)\n    {\n        printf(\"%ld\\n\",dist0L(rng));\n    }\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "22da272a8ed6e788eb9ebc07fa513eb4700adbed", "size": 537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CPP/uintdis.cpp", "max_stars_repo_name": "CaryRock/Phys642_Final_Project", "max_stars_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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": "testing/CPP/uintdis.cpp", "max_issues_repo_name": "CaryRock/Phys642_Final_Project", "max_issues_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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": "testing/CPP/uintdis.cpp", "max_forks_repo_name": "CaryRock/Phys642_Final_Project", "max_forks_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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": 21.48, "max_line_length": 67, "alphanum_fraction": 0.6666666667, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6682165150827574}}
{"text": "\n#include <alglib/graph/directed_graph.h>\n#include <alglib/graph/bellman_ford.h>\n\nusing namespace std;\nusing namespace alglib::graph;\n\n\nint main() {\n\n    // vertex_type = int; edge_attribute_type = int = weight\n    directed_graph<int, int> G;\n\n    for(int i = 0; i < 10; i++)\n        G.add_vertex(i);\n\n    G.add_edge(1, 3, 4);\n    G.add_edge(3, 5, 6);\n    G.add_edge(1, 5, 7);\n\n    vertex_property<directed_graph<int, int>, int> D = bellman_ford(G, 1);\n   \n    cout << D;\n\n}\n", "meta": {"hexsha": "c73ee068977e4ecd914db34c5473068c6c02f8f9", "size": 475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/bellman_ford.cpp", "max_stars_repo_name": "divkakwani/alglib", "max_stars_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T13:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T12:30:03.000Z", "max_issues_repo_path": "test/graph/bellman_ford.cpp", "max_issues_repo_name": "divkakwani/alglib", "max_issues_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/graph/bellman_ford.cpp", "max_forks_repo_name": "divkakwani/alglib", "max_forks_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T14:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:30:28.000Z", "avg_line_length": 18.2692307692, "max_line_length": 74, "alphanum_fraction": 0.6189473684, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6682165071843615}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLbeta, Fvar) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n\n  fvar<double> x(0.5, 1.0);\n  fvar<double> y(1.2, 2.0);\n\n  double w = 1.3;\n\n  fvar<double> a = lbeta(x, y);\n  EXPECT_FLOAT_EQ(lbeta(0.5, 1.2), a.val_);\n  EXPECT_FLOAT_EQ(\n      digamma(0.5) + 2.0 * digamma(1.2) - (1.0 + 2.0) * digamma(0.5 + 1.2),\n      a.d_);\n\n  fvar<double> b = lbeta(x, w);\n  EXPECT_FLOAT_EQ(lbeta(0.5, 1.3), b.val_);\n  EXPECT_FLOAT_EQ(1.0 * digamma(0.5) - 1.0 * digamma(0.5 + 1.3), b.d_);\n\n  fvar<double> c = lbeta(w, x);\n  EXPECT_FLOAT_EQ(lbeta(1.3, 0.5), c.val_);\n  EXPECT_FLOAT_EQ(1.0 * digamma(0.5) - 1.0 * digamma(1.3 + 0.5), c.d_);\n}\n\nTEST(AgradFwdLbeta, FvarFvarDouble) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::lbeta;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = lbeta(x, y);\n\n  EXPECT_FLOAT_EQ(lbeta(3.0, 6.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(digamma(3.0) - digamma(9.0), a.val_.d_);\n  EXPECT_FLOAT_EQ(digamma(6.0) - digamma(9.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(-0.11751202, a.d_.d_);\n}\n\nstruct lbeta_fun {\n  template <typename T0, typename T1>\n  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(\n      const T0 arg1, const T1 arg2) const {\n    return lbeta(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdLbeta, nan_0) {\n  lbeta_fun lbeta_;\n  test_nan_fwd(lbeta_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "5d4014ab0d0f8a66679567cc076ab43730697a06", "size": 1640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/lbeta_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/lbeta_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/lbeta_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.625, "max_line_length": 76, "alphanum_fraction": 0.6353658537, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6682165050583915}}
{"text": "#include <boost/python.hpp>\n#include <numpy/arrayobject.h>\n#include <complex>\n\n\nPyObject* IFT_mat2tau(PyObject *f_mat_in, const int &Nmax, const double &beta, const double &asymp_coefs1, const double &asymp_coefs2)\n{\n    PyArrayObject *f_mat = (PyArrayObject *) f_mat_in;\n    import_array1(NULL);\n    uint nfreq = f_mat->dimensions[0];\n    npy_intp Nm = (npy_intp)Nmax;\n    PyArrayObject *f_tau = (PyArrayObject *)PyArray_SimpleNew(1, &Nm, NPY_DOUBLE);\n    Py_INCREF(f_tau);\n    double *buf = (double *)PyArray_DATA(f_tau);\n    std::complex<double> *f_matsubara = (std::complex<double> *)PyArray_DATA(f_mat);\n    double C[2] = {asymp_coefs1, asymp_coefs2};\n\n    for (int i = 0; i < Nmax; i++) {\n        double tau=double(i)*beta/double(Nmax - 1);\n        buf[i] = -C[0]/2. + C[1]/4.*(-beta+2*tau);\n        for (uint k = 0; k < nfreq; ++k) {\n            double wt((2*k+1)*double(i)*M_PI/double(Nmax - 1));\n            std::complex<double> iomegan(0,(2*k+1)*M_PI/beta);\n            std::complex<double> f_matsubara_nomodel = f_matsubara[k] - C[0]/iomegan - C[1]/(iomegan*iomegan);\n            buf[i] += 2./beta*(cos(wt)*f_matsubara_nomodel.real() + sin(wt)*f_matsubara_nomodel.imag());\n        }\n    }\n    return PyArray_Return(f_tau);\n}\n\nPyObject* FT_tau2mat(PyObject *f_tau_py_in, const double &beta, const int &Nmax)\n{\n    PyArrayObject *f_tau_py = (PyArrayObject *) f_tau_py_in;\n    import_array1(NULL);\n    double *f_tau = (double *)PyArray_DATA(f_tau_py);\n    int nfreq = f_tau_py->dimensions[0] - 1;\n    PyArrayObject *f_mat;\n    npy_intp Nm = (npy_intp)Nmax;\n    f_mat = (PyArrayObject *)PyArray_SimpleNew(1, &Nm, NPY_CDOUBLE);\n    Py_INCREF(f_mat);\n    std::complex<double> *f_matsubara = (std::complex<double> *)PyArray_DATA(f_mat);\n    \n    // trapezoidal rule for integration\n    for (int n = 0; n < Nmax; n++) {\n        double wn = (2*n + 1)*M_PI/beta;\n        f_matsubara[n] = 0;\n        for (int p = 1; p < nfreq; p++) {\n            double tau = beta/double(nfreq)*p;\n            f_matsubara[n] += f_tau[p]*(cos(wn*tau) + std::complex<double>(0,1)*sin(wn*tau));\n        }\n        f_matsubara[n] = beta/2./double(nfreq)*(f_tau[0] - f_tau[nfreq]) + beta/double(nfreq)*f_matsubara[n];\n    }   \n    return PyArray_Return(f_mat);\n}\n\n", "meta": {"hexsha": "85d9801ef786a2476544d95c7dabe22337a3eeb9", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppext/fourier.cpp", "max_stars_repo_name": "hungdt/scf_dmft", "max_stars_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T17:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:55:13.000Z", "max_issues_repo_path": "cppext/fourier.cpp", "max_issues_repo_name": "hungdt/scf_dmft", "max_issues_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppext/fourier.cpp", "max_forks_repo_name": "hungdt/scf_dmft", "max_forks_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_forks_repo_licenses": ["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.0178571429, "max_line_length": 134, "alphanum_fraction": 0.6224899598, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.668216499468966}}
{"text": "#include <complex>\n#include <iostream>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <mkl.h>\n#include <mkl_dfti.h>\n#include <mkl_vsl.h>\n#include \"numeric_utils.h\"\n\nnamespace numeric_utils {\nEigen::MatrixXd corr_to_cov(const Eigen::MatrixXd& corr,\n                            const Eigen::VectorXd& std_dev) {\n  Eigen::MatrixXd cov_matrix = Eigen::MatrixXd::Zero(corr.rows(), corr.cols());\n\n  for (unsigned int i = 0; i < cov_matrix.rows(); ++i) {\n    for (unsigned int j = 0; j < cov_matrix.cols(); ++j) {\n      cov_matrix(i, j) = corr(i, j) * std_dev(i) * std_dev(j);\n    }\n  }\n\n  return cov_matrix;\n}\n  \nbool convolve_1d(const std::vector<double>& input_x,\n                 const std::vector<double>& input_y,\n                 std::vector<double>& response) {\n  bool status = true;\n  response.resize(input_x.size() + input_y.size() - 1);\n\n  // Create convolution status and task pointer\n  int conv_status;\n  VSLConvTaskPtr conv_task;\n  // Construct convolution task, with solution mode set to direct\n  conv_status =\n      vsldConvNewTask1D(&conv_task, VSL_CONV_MODE_DIRECT, input_x.size(),\n                        input_y.size(), response.size());\n\n  // Check if convolution construction was successful\n  if (conv_status != VSL_STATUS_OK) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::convolve_1d: Error in convolution \"\n        \"construction\\n\");\n    status = false;\n  }\n\n  // Set convolution to start at first element in input_y\n  vslConvSetStart(conv_task, 0);\n\n  // Execute convolution\n  conv_status = vsldConvExec1D(conv_task, input_x.data(), 1, input_y.data(), 1,\n                               response.data(), 1);\n\n  // Check if convolution exectution was successful\n  if (conv_status != VSL_STATUS_OK) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::convolve_1d: Error in convolution \"\n        \"execution\\n\");\n    status = false;\n  }\n\n  // Delete convolution task\n  vslConvDeleteTask(&conv_task);\n\n  return status;\n}\n\nbool inverse_fft(std::vector<std::complex<double>> input_vector,\n                 std::vector<double>& output_vector) {\n  output_vector.resize(input_vector.size());\n\n  // Create task descriptor and MKL status\n  DFTI_DESCRIPTOR_HANDLE fft_descriptor;\n  MKL_LONG fft_status;\n\n  // Allocate the descriptor data structure and initializes it with default\n  // configuration values\n  fft_status = DftiCreateDescriptor(&fft_descriptor, DFTI_DOUBLE, DFTI_REAL, 1,\n                                input_vector.size());\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in descriptor creation\\n\");\n    return false;\n  }\n  \n  // Set configuration value to not do inplace transformation\n  fft_status = DftiSetValue(fft_descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in setting configuration\\n\");\n    return false;\n  }\n\n  // Set the backward scale factor to be 1 divided by the size of the input vector\n  // to make the backward tranform the inverse of the forward transform\n  fft_status = DftiSetValue(fft_descriptor, DFTI_BACKWARD_SCALE,\n                            static_cast<double>(1.0 / input_vector.size()));\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in setting backward \"\n        \"scale factor\\n\");\n    return false;\n  }  \n\n  // Perform all initialization for the actual FFT computation\n  fft_status = DftiCommitDescriptor(fft_descriptor);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in committing descriptor\\n\");\n    return false;\n  }\n  \n  // Compute the backward FFT\n  fft_status = DftiComputeBackward(fft_descriptor, input_vector.data(),\n                                   output_vector.data());\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in computing backward FFT\\n\");\n    return false;\n  }\n  \n  // Free the memory allocated for descriptor\n  fft_status = DftiFreeDescriptor(&fft_descriptor);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::inverse_fft: Error in freeing FFT descriptor\\n\");\n    return false;\n  }  \n\n  return true;\n}\n\nbool inverse_fft(const Eigen::VectorXcd& input_vector,\n                 Eigen::VectorXd& output_vector) {\n  // Convert input Eigen vector to std vector\n  std::vector<std::complex<double>> input_vals(input_vector.size());\n  std::vector<double> outputs(input_vals.size());\n  Eigen::VectorXcd::Map(&input_vals[0], input_vector.size()) = input_vector;\n \n  try {\n    inverse_fft(input_vals, outputs);\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In numeric_utils::inverse_fft (With Eigen Vectors):\"\n              << e.what() << std::endl;\n  }\n\n  // Convert output from std vector to Eigen vector\n  output_vector = Eigen::Map<Eigen::VectorXd>(outputs.data(), outputs.size());\n\n  return true;\n}\n\nbool inverse_fft(const Eigen::VectorXcd& input_vector,\n                 std::vector<double>& output_vector) {\n  // Convert input Eigen vector to std vector\n  std::vector<std::complex<double>> input_vals(input_vector.size());\n  Eigen::VectorXcd::Map(&input_vals[0], input_vector.size()) = input_vector;\n  output_vector.resize(input_vector.size());  \n \n  try {\n    inverse_fft(input_vals, output_vector);\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In numeric_utils::inverse_fft (With Eigen Vectors):\"\n              << e.what() << std::endl;\n  }\n\n  return true;  \n}\n\nbool fft(std::vector<double> input_vector,\n         std::vector<std::complex<double>>& output_vector) {\n  // Convert input vector to complex values\n  std::vector<std::complex<double>> input_complex(input_vector.size());\n  std::copy(input_vector.begin(), input_vector.end(), input_complex.begin());\n  \n  output_vector.resize(input_vector.size());\n\n  // Create task descriptor and MKL status\n  DFTI_DESCRIPTOR_HANDLE fft_descriptor;\n  MKL_LONG fft_status;\n\n  // Allocate the descriptor data structure and initializes it with default\n  // configuration values\n  fft_status = DftiCreateDescriptor(&fft_descriptor, DFTI_DOUBLE, DFTI_COMPLEX,\n                                    1, input_complex.size());\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::fft: Error in descriptor creation\\n\");\n    return false;\n  }\n  \n  // Set configuration value to not do inplace transformation\n  fft_status = DftiSetValue(fft_descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::fft: Error in setting configuration\\n\");\n    return false;\n  }\n\n  // Perform all initialization for the actual FFT computation\n  fft_status = DftiCommitDescriptor(fft_descriptor);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::fft: Error in committing descriptor\\n\");\n    return false;\n  }\n  \n  // Compute the backward FFT\n  fft_status = DftiComputeForward(fft_descriptor, input_complex.data(),\n                                  output_vector.data());\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::fft: Error in computing FFT\\n\");\n    return false;\n  }\n  \n  // Free the memory allocated for descriptor\n  fft_status = DftiFreeDescriptor(&fft_descriptor);\n  if (fft_status != DFTI_NO_ERROR) {\n    throw std::runtime_error(\n        \"\\nERROR: in numeric_utils::fft: Error in freeing FFT descriptor\\n\");\n    return false;\n  }  \n\n  return true;\n}\n\nbool fft(const Eigen::VectorXd& input_vector, Eigen::VectorXcd& output_vector) {\n  // Convert input Eigen vector to std vector\n  std::vector<double> input_vals(input_vector.size());\n  std::vector<std::complex<double>> outputs(input_vals.size());\n  Eigen::VectorXd::Map(&input_vals[0], input_vector.size()) = input_vector;\n \n  try {\n    fft(input_vals, outputs);\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In numeric_utils::fft (With Eigen Vectors):\"\n              << e.what() << std::endl;\n  }\n\n  // Convert output from std vector to Eigen vector\n  output_vector = Eigen::Map<Eigen::VectorXcd>(outputs.data(), outputs.size());\n\n  return true;\n}\n\nbool fft(const Eigen::VectorXd& input_vector,\n                 std::vector<std::complex<double>>& output_vector) {\n  // Convert input Eigen vector to std vector\n  std::vector<double> input_vals(input_vector.size());\n  Eigen::VectorXd::Map(&input_vals[0], input_vector.size()) = input_vector;\n  output_vector.resize(input_vector.size());  \n \n  try {\n    fft(input_vals, output_vector);\n  } catch (const std::exception& e) {\n    std::cerr << \"\\nERROR: In numeric_utils::fft (With Eigen Vector and STL vector):\"\n              << e.what() << std::endl;\n  }\n\n  return true;  \n}  \n  \ndouble trapazoid_rule(const std::vector<double>& input_vector, double spacing) {\n  double result = (input_vector[0] + input_vector[input_vector.size() - 1]) / 2.0;\n\n  for (unsigned int i = 1; i < input_vector.size() - 1; ++i) {\n    result = result + input_vector[i];\n  }\n\n  return result * spacing;\n}\n\ndouble trapazoid_rule(const Eigen::VectorXd& input_vector, double spacing) {\n  double result = (input_vector[0] + input_vector[input_vector.size() - 1]) / 2.0;\n\n  for (unsigned int i = 1; i < input_vector.size() - 1; ++i) {\n    result = result + input_vector[i];\n  }\n\n  return result * spacing;\n}\n\nEigen::VectorXd polyfit_intercept(const Eigen::VectorXd& points,\n                                       const Eigen::VectorXd& data,\n\t\t\t\t       double intercept,\n                                       unsigned int degree) {\n\n  Eigen::MatrixXd coefficients =\n      Eigen::MatrixXd::Zero(points.size(), degree - 1);\n  \n  for (unsigned int i = 0; i < degree - 1; ++i) {\n    coefficients.col(i) = points.array().pow(degree - i);\n  }\n\n  // Solve system\n  Eigen::VectorXd solution = coefficients.fullPivHouseholderQr().solve(\n      (data.array() - intercept).matrix());\n\n  // Set y-intercept to zero\n  Eigen::VectorXd poly_fit(solution.size() + 2);\n\n  for (unsigned int i = 0; i < solution.size(); ++i) {\n    poly_fit(i) = solution(i);\n  }  \n  poly_fit(poly_fit.size() - 1) = intercept;\n  poly_fit(poly_fit.size() - 2) = 0.0;\n\n  return poly_fit;\n}\n\nEigen::VectorXd polynomial_derivative(const Eigen::VectorXd& coefficients) {\n  Eigen::VectorXd derivative(coefficients.size() - 1);\n\n  for (unsigned int i = 0; i < derivative.size(); ++i) {\n    derivative(i) = coefficients(i) * (coefficients.size() - 1 - i);\n  }\n\n  return derivative;\n}\n\nstd::vector<double> derivative(const std::vector<double>& coefficients,\n                               double constant_factor, bool add_zero) {\n\n  if (add_zero) {\n    std::vector<double> derivative(coefficients.size());\n    derivative[0] = coefficients[0] * constant_factor;\n\n    for (unsigned int i = 1; i < derivative.size(); ++i) {\n      derivative[i] = (coefficients[i] - coefficients[i - 1]) * constant_factor;\n    }\n\n    return derivative;\n  } else {\n    std::vector<double> derivative(coefficients.size() - 1);\n\n    for (unsigned int i = 0; i < derivative.size(); ++i) {\n      derivative[i] = (coefficients[i + 1] - coefficients[i]) * constant_factor;\n    }\n\n    return derivative;\n  }\n}\n\nEigen::VectorXd evaluate_polynomial(const Eigen::VectorXd& coefficients,\n                                    const Eigen::VectorXd& points) {\n  Eigen::VectorXd evaluations = Eigen::VectorXd::Zero(points.size());\n\n  for (unsigned int i = 0; i < evaluations.size(); ++i) {\n    for (unsigned int j = 0; j < coefficients.size(); ++j) {\n      evaluations(i) +=\n          coefficients(j) * std::pow(points(i), coefficients.size() - 1 - j);\n    }\n  }\n\n  return evaluations;\n}\n\nEigen::VectorXd evaluate_polynomial(const Eigen::VectorXd& coefficients,\n                                    const std::vector<double>& points) {\n  Eigen::VectorXd evaluations = Eigen::VectorXd::Zero(points.size());\n\n  for (unsigned int i = 0; i < evaluations.size(); ++i) {\n    for (unsigned int j = 0; j < coefficients.size(); ++j) {\n      evaluations(i) +=\n          coefficients(j) * std::pow(points[i], coefficients.size() - 1 - j);\n    }\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> evaluate_polynomial(const std::vector<double>& coefficients,\n                                        const std::vector<double>& points) {\n  std::vector<double> evaluations(points.size(), 0.0);\n\n  for (unsigned int i = 0; i < evaluations.size(); ++i) {\n    for (unsigned int j = 0; j < coefficients.size(); ++j) {\n      evaluations[i] +=\n          coefficients[j] * std::pow(points[i], coefficients.size() - 1 - j);\n    }\n  }\n\n  return evaluations;\n}  \n}  // namespace numeric_utils\n", "meta": {"hexsha": "9cd9e43418772d7be4f6c204e83bd039420fecd5", "size": 12876, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/numeric_utils.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/numeric_utils.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/numeric_utils.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 33.3575129534, "max_line_length": 85, "alphanum_fraction": 0.6546287667, "num_tokens": 3138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6681975076411579}}
{"text": "\n\n#include <iostream>\n#include <NTL/ZZ_pX.h>\n#include <NTL/matrix.h>\n#include <NTL/ZZ_pXFactoring.h>\n#include <NTL/ZZ_pE.h>\n#include <NTL/ZZ_pEX.h>\n#include <NTL/ZZX.h>\n\n#include \"BaseChange.h\"\n#include \"MultipointEval.h\"\n#include \"Util.h\"\n#include \"HasseLift.h\"\n#include \"HasseLiftExt.h\"\n#include \"MultiComposeMod.h\"\n#include \"FrobComp.h\"\n#include \"SSFactoring.h\"\n\n\n\nusing namespace std;\n\n//void testBaseChange(long degree) {\n//    cout << \"degree: \" << degree << \"\\n\";\n//\n//    ZZ_pX f, g, h;\n//\n//    random(f, degree - 1);\n//    random(h, degree - 1);\n//    \n//    // build a square-free modulus\n//    random(g, degree);\n//    SetCoeff(g, degree, 1);\n//    diff(h, g);\n//    GCD(h, g, h);\n//    div(g, g, h);\n//    ZZ_pXModulus modulus;\n//    build(modulus, g);\n//    \n//    CompMod(g, h, f, modulus);\n//    BaseChange baseChane;\n//    baseChane.changeBasis(f, f, g, modulus);\n//\n//    if (f == h)\n//        cout << \"ok\\n\";\n//    else\n//        cout << \"oops\\n\";\n//\n//    f.kill();\n//    g.kill();\n//    h.kill();\n//    modulus.f.kill();\n//}\n//\n\nvoid testCompose() {\n    long k = 1;\n    long n = 2000;\n    ZZ_pX f;\n    random(f, n);\n    SetCoeff(f, n, 1);\n    ZZ_pXModulus F;\n    build(F, f);\n\n    Vec<ZZ_pX> result;\n    Vec<ZZ_pX> result1;\n    Vec<ZZ_pX> gVec;\n    result.SetLength(k);\n    result1.SetLength(k);\n    gVec.SetLength(k);\n\n    for (long i = 0; i < k; i++)\n        random(gVec[i], n);\n\n    ZZ_pX h;\n    random(h, n);\n\n    MultiComposeMod multiComposeMod;\n\n    Util util;\n    long start = util.getTimeMillis();\n    multiComposeMod.compose(result, gVec, h, F);\n    cout << util.getTimeMillis() - start << endl;\n\n    start = util.getTimeMillis();\n    for (long i = 0; i < k; i++) {\n        CompMod(result1[i], gVec[i], h, F);\n    }\n    cout << util.getTimeMillis() - start << endl;\n\n    for (long i = 0; i < k; i++) {\n        if (result[i] != result1[i]) {\n            cout << \"Failed\" << endl;\n            break;\n        }\n    }\n}\n//\n//\n//void testMultipointEval() {\n//    long numPoints = 100;\n//    \n//    long degree = 20;\n//    ZZ_pX f;\n//    random(f, degree);\n//    SetCoeff(f, degree, 1);\n//    \n//    ZZ_pE::init(f);\n//    \n//    Vec<ZZ_pE> points;\n//    Vec<ZZ_pE> results;\n//    points.SetLength(numPoints);\n//    results.SetLength(numPoints);\n//    \n//    for (long i = 0; i < numPoints; i++)\n//        random(points[i]);\n//    \n//    ZZ_pEX g;\n//    random(g, numPoints);\n//    SetCoeff(g, numPoints + 1, 1);\n//    \n//    Util util;\n//    long start = util.getTimeMillis();\n//    MultipointEval multiPointEval;\n//    multiPointEval.eval(results, g, points);\n//    cout << (util.getTimeMillis() - start) << endl;\n//    \n//    start = util.getTimeMillis();\n//    ZZ_pE temp;\n//    for (long i = 0; i < numPoints; i++) {\n//        eval(temp, g, points[i]);\n//        if (temp != results[i]) {\n//            cout << \"not equal\" << endl;\n//            break;\n//        }\n//    }\n//    cout << (util.getTimeMillis() - start) << endl;\n//}\n//\n\nvoid testFrob() {\n    ZZ_pX f;\n    long d = 100;\n    random(f, d);\n    SetCoeff(f, d, 1);\n    ZZ_pXModulus F;\n    build(F, f);\n\n    long m = 20;\n\n    Vec<ZZ_pX> frobs;\n    frobs.SetLength(m);\n    ZZ_pX xq;\n    SetX(xq);\n    PowerMod(xq, xq, ZZ_p::modulus(), F);\n\n    FrobComp frobComp;\n    frobComp.computeFrobePowers(frobs, m, xq, F);\n\n    Vec<ZZ_pX> frobs1;\n    frobs1.SetLength(m);\n    frobs1[0] = xq;\n    for (long i = 1; i < m; i++) {\n        PowerMod(frobs1[i], frobs1[i - 1], ZZ_p::modulus(), F);\n    }\n\n    if (frobs == frobs1)\n        cout << \"OK\" << endl;\n    else\n        cout << \"Failed\" << endl;\n}\n\nvoid testHasseLift() {\n    ZZ_pX f, g, delta, lift1, lift2;\n\n    long degree = 10000;\n\n    // build a square-free modulus\n    Util util;\n    util.randomMonic(f, degree);\n    diff(g, f);\n    GCD(g, g, f);\n    div(f, f, g);\n    ZZ_pXModulus F;\n    build(F, f);\n    degree = deg(F);\n\n    random(g, degree);\n    random(delta, degree);\n\n    HasseLiftExt hasseLiftExt(g, delta, F);\n    long start = util.getTimeMillis();\n//    hasseLiftExt.computeNaive(lift1, degree / 2);\n//    cout << util.getTimeMillis() - start << endl;\n//\n//    start = util.getTimeMillis();\n    hasseLiftExt.compute(lift2, degree / 2, 1);\n    cout << util.getTimeMillis() - start << endl;\n\n    if (lift1 == lift2)\n        cout << \"OK\" << endl;\n    else\n        cout << \"Failed\" << endl;\n}\n\nvoid testFactoring() {\n    Util util;\n    \n    long n = 10;\n    ZZ_pX f;\n    util.randomMonic(f, n);\n    cout << \"p: \" << ZZ_p::modulus() << endl;\n    cout << \"f: \" << f << endl;\n    \n    Vec<pair_ZZ_pX_long> factors1;\n    Vec<pair_ZZ_pX_long> factors2;\n    \n    SSFactoring sSfactoring;\n//    long start = util.getTimeMillis();\n    sSfactoring.factor(factors1, f);\n    cout << factors1 << endl;\n//    cout << util.getTimeMillis() - start << endl;\n//    \n//    start = util.getTimeMillis();\n//    CanZass(factors2, f, 1);\n//    cout << util.getTimeMillis() - start << endl;\n//\n//    ZZ_pX g;\n//    mul(g, factors1);\n//    if (f == g)\n//        cout << \"OK\" << endl;\n//    else\n//        cout << \"Failed\" << endl;\n}\n\nint main(int argc, char** argv) {\n\n    ZZ p;\n    NextPrime(p, to_ZZ(7));\n    ZZ_p::init(p);\n    \n    testFactoring();\n    \n    return 0;\n}\n\n", "meta": {"hexsha": "260fd13dfe0b9fc65ffaff6ca425edf0d0538c6d", "size": 5188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ss_drinfeld_impl/test.cpp", "max_stars_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_stars_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-05-31T17:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T03:04:49.000Z", "max_issues_repo_path": "ss_drinfeld_impl/test.cpp", "max_issues_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_issues_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ss_drinfeld_impl/test.cpp", "max_forks_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_forks_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_forks_repo_licenses": ["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.9193548387, "max_line_length": 63, "alphanum_fraction": 0.5291056284, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6681975024168333}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2015, University of Toronto\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the University of Toronto 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/* Author: Jonathan Gammell*/\n\n// This file's header\n#include \"ompl/util/GeometricEquations.h\"\n\n// For pre C++ 11 gamma function\n#include <boost/math/special_functions/gamma.hpp>\n\n// OMPL exceptions\n#include \"ompl/util/Exception.h\"\n\ndouble ompl::nBallMeasure(unsigned int N, double r)\n{\n    return std::pow(std::sqrt(boost::math::constants::pi<double>()) * r, static_cast<double>(N)) / boost::math::tgamma(static_cast<double>(N)/2.0 + 1.0);\n}\n\ndouble ompl::unitNBallMeasure(unsigned int N)\n{\n    // This is the radius version with r removed (as it is 1) for efficiency\n    return std::pow(std::sqrt(boost::math::constants::pi<double>()), static_cast<double>(N)) / boost::math::tgamma(static_cast<double>(N)/2.0 + 1.0);\n}\n\ndouble ompl::prolateHyperspheroidMeasure(unsigned int N, double dFoci, double dTransverse)\n{\n    // Sanity check input\n    if (dTransverse < dFoci)\n    {\n        throw Exception(\"Transverse diameter cannot be less than the minimum transverse diameter.\");\n    }\n\n    // Variable\n    // The conjugate diameter:\n    double conjugateDiameter;\n    // The Lebesgue measure return value\n    double lmeas;\n\n    // Calculate the conjugate diameter:\n    conjugateDiameter = std::sqrt(dTransverse * dTransverse - dFoci * dFoci);\n\n    // Calculate the volume\n    // First multiply together the radii, noting that the first radius is the transverse diameter/2.0, and the other N-1 are the conjugate diameter/2.0\n    lmeas = dTransverse/2.0;\n    for (unsigned int i = 1u; i < N; ++i)\n    {\n        lmeas = lmeas * conjugateDiameter/2.0;\n    }\n\n    // Then multiply by the volume of the unit n-ball.\n    lmeas = lmeas * unitNBallMeasure(N);\n\n    // Finally return:\n    return lmeas;\n}\n", "meta": {"hexsha": "fc8244071e2bfc8713d6d256db045822864a3d0a", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/util/src/GeometricEquations.cpp", "max_stars_repo_name": "ivaROS/ivaOmplCore", "max_stars_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "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/ompl/util/src/GeometricEquations.cpp", "max_issues_repo_name": "ivaROS/ivaOmplCore", "max_issues_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "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/ompl/util/src/GeometricEquations.cpp", "max_forks_repo_name": "ivaROS/ivaOmplCore", "max_forks_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T14:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:46:59.000Z", "avg_line_length": 39.4659090909, "max_line_length": 153, "alphanum_fraction": 0.6945004319, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6681975024168333}}
{"text": "#define EIGEN_USE_MKL_ALL\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"../misc.hpp\"\n\n#include \"models/transformers/principal_components_analysis.hpp\"\n#include \"models/transformers/zero_components_analysis.hpp\"\n\nvoid pca_examples() {\n\tEigen::MatrixXd X(2, 6);\n\n\tX.row(0) << -1, -2, -3, 1, 2, 3;\n\tX.row(1) << -1, -1, -2, 1, 1, 2;\n\n\tmlt::models::transformers::PrincipalComponentsAnalysis pca;\n\tpca.fit(X);\n\n\tstd::cout << \"PCA: \" << std::endl;\n\tstd::cout << pca.explained_variance_ratio() << std::endl << std::endl;\n\tstd::cout << \"X2\" << std::endl << X << std::endl;\n\tstd::cout << \"PCA(X2)\" << std::endl << pca.transform(X) << std::endl;\n\tstd::cout << \"PCA-1(PCA(X2))\" << std::endl << pca.inverse_transform(pca.transform(X)) << std::endl;\n\tstd::cout << \"PCA(X2[:,1])\" << std::endl << pca.transform(X.leftCols(1)) << std::endl;\n\tstd::cout << \"PCA-1(PCA(X2[:,1]))\" << std::endl << pca.inverse_transform(pca.transform(X.leftCols(1))) << std::endl << std::endl;\n\n\tmlt::models::transformers::ZeroComponentsAnalysis zca;\n\tzca.fit(X);\n\n\tstd::cout << \"ZCA: \" << std::endl;\n\tstd::cout << zca.explained_variance_ratio() << std::endl << std::endl;\n\tstd::cout << \"X2\" << std::endl << X << std::endl;\n\tstd::cout << \"ZCA(X2)\" << std::endl << zca.transform(X) << std::endl;\n\tstd::cout << \"ZCA-1(ZCA(X2))\" << std::endl << zca.inverse_transform(zca.transform(X)) << std::endl;\n\tstd::cout << \"ZCA(X2[:,1])\" << std::endl << zca.transform(X.leftCols(1)) << std::endl;\n\tstd::cout << \"ZCA-1(ZCA(X2[:,1]))\" << std::endl << zca.inverse_transform(zca.transform(X.leftCols(1))) << std::endl << std::endl;\n}", "meta": {"hexsha": "8d708e2e960a7c8358beae24ef41b7d3fb508279", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/principal_components_analysis.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/principal_components_analysis.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/principal_components_analysis.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": 40.6666666667, "max_line_length": 130, "alphanum_fraction": 0.6191677175, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6680442671049004}}
{"text": "//\n// Created by Alex Beccaro on 18/12/17.\n//\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"problem80.hpp\"\n#include <iostream>\n\nusing boost::multiprecision::cpp_dec_float_100;\nusing std::string;\n\nnamespace problems {\n    uint32_t problem80::solve(uint32_t ub) {\n        uint32_t sum = 0;\n        for (uint32_t i = 2; i <= ub; i++) {\n            cpp_dec_float_100 n(i);\n            n = sqrt(n);\n            if (n == (uint32_t) n)\n                continue;\n\n            string s = n.str().substr(0, 101); // 100 digits and '.'\n            s.erase(s.find('.'), 1);\n\n            for (const auto& c : s)\n                sum += c - '0';\n        }\n        return sum;\n    }\n}", "meta": {"hexsha": "8fda92679abf65f446ee3d400fd7ebfb0b2509ea", "size": 683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problems/51-100/80/problem80.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "src/problems/51-100/80/problem80.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "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/problems/51-100/80/problem80.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["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.5517241379, "max_line_length": 68, "alphanum_fraction": 0.5197657394, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6680442556475207}}
{"text": "#pragma once\n#include <math.h>\n#include <stdlib.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <chrono>\n\n/*!\n   \\brief Enforce orthogonality conditions on the given rotation matrix such that det(R) == 1 and R.tranpose() * R = I\n   \\param R The input rotation matrix either 2x2 or 3x3, will be overwritten with a slightly modified matrix to\n   satisfy orthogonality conditions.\n*/\nvoid enforce_orthogonality(Eigen::MatrixXd &R);\n\n/*!\n   \\brief Retrieve the rigid transformation that transforms points in p1 into points in p2.\n   The output transform type (float or double) and size SE(2) vs. SE(3) depends on the size of the input points p1, p2.\n   \\param p1 A dim x N vector of points in either 2D (dim = 2) or 3D (dim = 3)\n   \\param p2 A dim x N vector of points in either 2D (dim = 2) or 3D (dim = 3)\n   \\param Tf [out] This matrix will be overwritten as the output transform\n   \\pre p1 and p2 are the same size. p1 and p2 are the matched feature point locations between two point clouds\n   \\post orthogonality is enforced on the rotation matrix.\n*/\nvoid get_rigid_transform(Eigen::MatrixXd p1, Eigen::MatrixXd p2, Eigen::MatrixXd &Tf);\n\n/*!\n   \\brief Returns a random subset of indices, where 0 <= indices[i] <= max_index. indices are non-repeating.\n*/\nstd::vector<int> random_subset(int max_index, int subset_size);\n\n/*!\n   \\brief Returns the output of the cross operator.\n   For 3 x 1 input, cross(x) * y is equivalent to cross_product(x, y)\n   For 6 x 1 input, x = [rho, phi]^T. out = [cross(phi), rho; 0 0 0 1]\n   \\param x Input vector which can be 3 x 1 or 6 x 1.\n   \\return If the input if 3 x 1, the output is 3 x 3, if the input is 6 x 1, the output is 4 x 4.\n*/\nEigen::MatrixXd cross(Eigen::VectorXd x);\n\n/*!\n   \\brief Returns the output of the circledot operator. cross(epsilon) * p == circledot(p) * epsilon,\n   where epsilon is 6x1 and p is 4 x 1 homogeneous.\n   p = [rhobar, eta]^T  circledot(p) = [eta * identity(3), -cross(rhobar); 0 0 0 0 0 0]\n   \\param x Input is a 4 x 1 homogeneous 3D vector.\n   \\return returns the 4 x 6 output of circledot(x)\n*/\nEigen::MatrixXd circledot(Eigen::VectorXd x);\n\n/*!\n   \\brief This function converts from a lie vector to a 4 x 4 SE(3) transform.\n   // Lie Vector xi = [rho, phi]^T (6 x 1) --> SE(3) T = [C, R; 0 0 0 1] (4 x 4)\n   \\param x Input vector is 6 x 1\n   \\return Output is 4 x SE(3) transform\n*/\nEigen::Matrix4d se3ToSE3(Eigen::MatrixXd xi);\n\n/*!\n   \\brief This function converts from an SE(3) transform into a lie vector\n   // SE(3) T = [C, R; 0 0 0 1] (4 x 4) --> Lie Vector xi = [rho, phi]^T (6 x 1)\n   \\param T Input is a 4x4 SE(3) transform\n   \\return Output is 6x1 lie vector\n*/\nEigen::VectorXd SE3tose3(Eigen::MatrixXd T);\n\n/*!\n   \\brief Converts a vector of x-y-z euler parameters to a rotation matrix.\n   \\param eul 3x1 vector of euler rotation parameters (x,y,z) == (roll, pitch, yaw)\n   \\return Output is a 3x3 rotation matrix, equivalent to the given euler parameters.\n*/\nEigen::MatrixXd eulerToRot(Eigen::VectorXd eul);\n\n/*!\n   \\brief Ensures that theta is within [0, 2 * pi)\n*/\ndouble wrapto2pi(double theta);\n\n//* Ransac\n/**\n* \\brief This class estimates a single rigid transform between two point clouds using RANSAC and singular value decomp\n*/\nclass Ransac {\npublic:\n    // p1, p2 need to be either (x, y) x N or (x, y, z) x N (must be in homogeneous coordinates)\n    Ransac(Eigen::MatrixXd p1_, Eigen::MatrixXd p2_, double tolerance_, double inlier_ratio_,\n        int iterations_) : p1(p1_), p2(p2_), tolerance(tolerance_),\n        inlier_ratio(inlier_ratio_), iterations(iterations_) {\n        int dim = p1.rows();\n        assert(p1.cols() == p2.cols() && p1.rows() == p2.rows() && (dim == 2 || dim == 3));\n        T_best = Eigen::MatrixXd::Identity(dim + 1, dim + 1);\n    }\n    void setTolerance(double tolerance_) {tolerance = tolerance_;}\n    void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n    void setMaxIterations(int iterations_) {iterations = iterations_;}\n    void getTransform(Eigen::MatrixXd &Tf) {Tf = T_best;}\n\n    /*!\n       \\brief Computes the transform that best aligns the two pointclouds such at T * p1 = p2\n    */\n    double computeModel();\n\n    /*!\n       \\brief Retrieves the set of point pairs which are inliers given the current transform Tf.\n    */\n    void getInliers(Eigen::MatrixXd Tf, std::vector<int> &inliers);\n\nprivate:\n    Eigen::MatrixXd p1, p2;\n    double tolerance = 0.05;\n    double inlier_ratio = 0.9;\n    int iterations = 40;\n    Eigen::MatrixXd T_best;\n};\n\n//* MotionDistortedRansac\n/**\n* \\brief This class estimates the linear velocity and angular velocity of the sensor in the body-frame.\n*\n* Assuming constant velocity, the motion vector can be used to estimate the transform between any two pairs of points\n* if the delta_t between those points is known.\n*\n* A single transform between the two pointclouds can also be retrieved.\n*\n* All operations are done in SE(3) even if the input is 2D. The output motion and transforms are in 3D.\n*/\nclass MotionDistortedRansac {\npublic:\n    MotionDistortedRansac(Eigen::MatrixXd p1, Eigen::MatrixXd p2, std::vector<int64_t> t1, std::vector<int64_t> t2,\n        double tolerance_, double inlier_ratio_, int iterations_) : tolerance(tolerance_),\n        inlier_ratio(inlier_ratio_), iterations(iterations_) {\n        const int dim = p1.rows();\n        assert(p1.cols() == p2.cols() && p1.rows() == p2.rows() && p1.cols() >= p1.rows() && (dim == 2 || dim == 3));\n        p1bar = Eigen::MatrixXd::Zero(4, p1.cols());\n        p2bar = Eigen::MatrixXd::Zero(4, p2.cols());\n        p1bar.block(3, 0, 1, p1.cols()) = Eigen::MatrixXd::Ones(1, p1.cols());\n        p2bar.block(3, 0, 1, p2.cols()) = Eigen::MatrixXd::Ones(1, p2.cols());\n        if (dim == 2) {\n            p1bar.block(0, 0, 2, p1.cols()) = p1;\n            p2bar.block(0, 0, 2, p2.cols()) = p2;\n        } else if (dim == 3) {\n            p1bar.block(0, 0, 3, p1.cols()) = p1;\n            p2bar.block(0, 0, 3, p2.cols()) = p2;\n        }\n        R_pol << pow(0.25, 2), 0, 0, 0, 0, pow(0.0157, 2), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n        delta_ts = std::vector<double>(p1.cols(), 0.0);\n        for (uint i = 0; i < p1bar.cols(); ++i) {\n            int64_t delta_t = t2[i] - t1[i];\n            delta_ts[i] = double(delta_t) / 1000000.0;\n            if (delta_ts[i] > max_delta_t) {\n                max_delta_t = delta_ts[i];\n            }\n            if (delta_ts[i] < min_delta_t) {\n                min_delta_t = delta_ts[i];\n            }\n        }\n        double delta_diff = (max_delta_t - min_delta_t) / (num_transforms - 1);\n        for (int i = 0; i < num_transforms; ++i) {\n            delta_vec.push_back(min_delta_t + i * delta_diff);\n        }\n    }\n    void setTolerance(double tolerance_) {tolerance = tolerance_;}\n    void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n    void setMaxIterations(int iterations_) {iterations = iterations_;}\n    void setMaxGNIterations(int iterations_) {max_gn_iterations = iterations_;}\n    void setConvergenceThreshold(double eps) {epsilon_converge = eps;}\n    void correctForDoppler(bool doppler_) {doppler = doppler_;}\n    void getTransform(double delta_t, Eigen::MatrixXd &Tf);\n    void getMotion(Eigen::VectorXd &w) {w = w_best;}\n    void setDopplerParameter(double beta_) {beta = beta_;}\n\n    /*!\n       \\brief Computes the ego-motion vector that best aligns the two pointclouds\n    */\n    double computeModel();\n\n    /*!\n       \\brief Retrieves the set of point pairs which are inliers given the current motion estimate.\n    */\n    void getInliers(Eigen::VectorXd wbar, std::vector<int> &inliers);\n\nprivate:\n    Eigen::MatrixXd p1bar, p2bar;\n    std::vector<double> delta_ts;\n    double tolerance = 0.05;\n    double inlier_ratio = 0.9;\n    int iterations = 40;\n    int max_gn_iterations = 10;\n    double epsilon_converge = 0.0001;\n    double error_converge = 0.01;\n    int dim = 2;\n    double beta = -0.049;  // beta = (f_t / (df / dt))\n    double r_observable_sq = 0.0625;\n    bool doppler = false;\n    int num_transforms = 21;\n    double max_delta_t = 0.0;\n    double min_delta_t = 0.5;\n    std::vector<double> delta_vec;\n    Eigen::VectorXd w_best = Eigen::VectorXd::Zero(6);\n    Eigen::Matrix4d R_pol = Eigen::Matrix4d::Identity();\n    Eigen::MatrixXd get_jacobian(Eigen::Vector4d gbar);\n    Eigen::MatrixXd get_inv_jacobian(Eigen::Vector4d gbar);\n    Eigen::VectorXd to_cylindrical(Eigen::VectorXd gbar);\n    Eigen::VectorXd from_cylindrical(Eigen::VectorXd ybar);\n\n    /*!\n       \\brief Given two sets of point pairs (p1small, p2small), this function computes the motion of the sensor\n       (linear and angular velocity) in the body frame using nonlinear least squares.\n       \\pre It's very important that the delt_t_local is accurate. Note that each azimuth in the radar scan is time\n       stamped, this should be used to get the more accurate time differences.\n    */\n    void get_motion_parameters(std::vector<int> subset, Eigen::VectorXd &wbar);\n\n    /*!\n       \\brief This function also computes the motion of the sensor, but it uses the linear least squares version of\n       MDRANSAC. This is a lot less accurate, but it computes the motion vector in a single step.\n    */\n    void get_motion_parameters2(Eigen::MatrixXd& p1small, Eigen::MatrixXd& p2small, std::vector<double> delta_t_local,\n        Eigen::VectorXd &wbar);\n\n    /*!\n       \\brief Retrieve the number of inliers corresponding to body motion vector wbar. (6 x 1)\n    */\n    int getNumInliers(Eigen::VectorXd wbar);\n\n    /*!\n       \\brief Given a body motion vector wbar (6 x 1), adjust the position of point p to account\n       for the Doppler distortion which may be present in the data.\n    */\n    void dopplerCorrection(Eigen::VectorXd wbar, Eigen::VectorXd &p);\n};\n\n/*!\n   \\brief Retrieve a 4x4 homogeneous transformation matrix T_enu_sensor for this ground truth vector.\n   \\param gt [GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z]\n*/\nEigen::Matrix4d getTransformFromGT(std::vector<double> gt);\n\n/*!\n   \\brief This function removes motion distortion from a cloud of points.\n   \\param pc The input point cloud should be 4 x N, as in homogeneous coordinates (x, y, z, 1) (z = 0 for 2D data)\n   \\param times Timestamps associated with each point, in seconds.\n   \\param T_enu_sensor A global transformation from the nominal sensor position to the ENU frame,\n        used to transform the velocity vector from the ENU frame to the sensor frame.\n   \\param gt [GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z]\n   \\param t_ref 0 (radar) --> use first time as reference, -1 (lidar) --> use last time as reference.\n*/\nvoid removeMotionDistortion(Eigen::MatrixXd &pc, std::vector<float> &times, Eigen::Matrix4d T_enu_sensor,\n    std::vector<double> gt, int t_ref);\n\n// Return the inverse of a 4x4 homogeneous transformation matrix\nEigen::Matrix4d get_inverse_tf(Eigen::Matrix4d T);\n", "meta": {"hexsha": "5e6a3fb4ffbcda6f387f1074deaa9c39e4d66860", "size": 10964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/association.hpp", "max_stars_repo_name": "carlschiller/yeti_radar_odometry", "max_stars_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T01:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:34:48.000Z", "max_issues_repo_path": "include/association.hpp", "max_issues_repo_name": "carlschiller/yeti_radar_odometry", "max_issues_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-27T08:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T01:36:55.000Z", "max_forks_repo_path": "include/association.hpp", "max_forks_repo_name": "carlschiller/yeti_radar_odometry", "max_forks_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T08:48:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:32:52.000Z", "avg_line_length": 43.1653543307, "max_line_length": 119, "alphanum_fraction": 0.6700109449, "num_tokens": 3179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6680442470316679}}
{"text": "#include \"scan_matching_skeleton/transform.h\"\n#include <cmath>\n#include \"ros/ros.h\"\n#include <Eigen/Geometry>\n#include <complex>\n\nusing namespace std;\n\n\nvoid transformPoints(const vector<Point>& points, Transform& t, vector<Point>& transformed_points) {\n  transformed_points.clear();\n  for (int i = 0; i < points.size(); i++) {\n    transformed_points.push_back(t.apply(points[i]));\n    //printf(\"%f %transformed_points.back().r, transformed_points.back().theta);\n  }\n}\n\n// returns the largest real root to ax^3 + bx^2 + cx + d = 0\ncomplex<float> get_cubic_root(float a, float b, float c, float d) {\n  //std::cout<< \"a= \" << a<< \";  b= \" << b<< \";  c= \" << c<< \";  d= \" << d<<\";\"<<std::endl;\n  // Reduce to depressed cubic\n  float p = c/a - b*b/(3*a*a);\n  float q = 2*b*b*b/(27*a*a*a) + d/a - b*c/(3*a*a);\n\n  // std::cout<<\"p = \"<<p<<\";\"<<std::endl;\n  // std::cout<<\"q = \"<<q<<\";\"<<std::endl;\n\n  complex<float> xi(-.5, sqrt(3)/2);\n\n  complex<float> inside = sqrt(q*q/4 + p*p*p/27);\n\n  complex<float> root;\n\n  for (float k = 0; k < 3; ++k) {\n    // get root for 3 possible values of k\n    root = -b/(3*a) + pow(xi, k) * pow(-q/2.f + inside, 1.f/3.f) + pow(xi, 2.f*k) * pow(-q/2.f - inside, 1.f/3.f);\n    //std::cout<<\"RootTemp: \"<< root<<std::endl;\n    if (root.imag() != 0) { return root; }\n  }\n\n  return root;\n}\n\n// returns the largest real root to ax^4 + bx^3 + cx^2 + dx + e = 0\nfloat greatest_real_root(float a, float b, float c, float d, float e) {\n  // Written with inspiration from: https://en.wikipedia.org/wiki/Quartic_function#General_formula_for_roots\n  //std::cout<< \"a= \" << a<< \";  b= \" << b<< \";  c= \" << c<< \";  d= \" << d<< \";  e= \" << e<<\";\"<<std::endl;\n\n  // Reduce to depressed Quadratic\n  float p = (8*a*c-3*b*b)/(8*a*a);\n  float q = (b*b*b-4*a*b*c+8*a*a*d)/(8*a*a*a);\n  float r = (-3*b*b*b*b+256*a*a*a*e-64*a*a*b*d+16*a*b*b*c)/(256*a*a*a*a);\n\n  // std::cout<<\"p = \"<<p<<\";\"<<std::endl;\n  // std::cout<<\"q = \"<<q<<\";\"<<std::endl;\n  // std::cout<<\"r = \"<<r<<\";\"<<std::endl;\n\n  // Ferrari's Solution for Quartics: 8m^3 + 8pm^2 + (2p^2-8r)m - q^2 = 0\n  complex<float> m = get_cubic_root(8, 8*p, 2*p*p-8*r, -q*q);\n\n  complex<float> root1 = -b/(4*a) + ( sqrt(2.f*m) + sqrt(-(2*p + 2.f*m + sqrt(2.f)*q/sqrt(m))))/2.f;\n  complex<float> root2 = -b/(4*a) + ( sqrt(2.f*m) - sqrt(-(2*p + 2.f*m + sqrt(2.f)*q/sqrt(m))))/2.f;\n  complex<float> root3 = -b/(4*a) + (-sqrt(2.f*m) + sqrt(-(2*p + 2.f*m - sqrt(2.f)*q/sqrt(m))))/2.f;\n  complex<float> root4 = -b/(4*a) + (-sqrt(2.f*m) - sqrt(-(2*p + 2.f*m - sqrt(2.f)*q/sqrt(m))))/2.f;\n\n  vector<complex<float>> roots { root1, root2, root3, root4 };\n\n  float max_real_root = 0.f;\n\n  for (complex<float> root: roots) {\n    if(root.imag()==0){\n    max_real_root = max(max_real_root, root.real());\n  }\n  //std::cout<<\"Max real root:\" << max_real_root<<std::endl;\n\n  return max_real_root;\n}}\n\nvoid updateTransform(vector<Correspondence>& corresponds, Transform& curr_trans) {\n  // Written with inspiration from: https://github.com/AndreaCensi/gpc/blob/master/c/gpc.c\n  // You can use the helper functions which are defined above for finding roots and transforming points as and when needed.\n  // use helper functions and structs in transform.h and correspond.h\n  // input : corresponds : a struct vector of Correspondene struct object defined in correspond.\n  // input : curr_trans : A Transform object refernece\n  // output : update the curr_trans object. Being a call by reference function, Any changes you make to curr_trans will be reflected in the calling function in the scan_match.cpp program/\n\n// You can change the number of iterations here. More the number of iterations, slower will be the convergence but more accurate will be the results. You need to find the right balance.\nint number_iter = 1;\n\nfor(int i = 0; i<number_iter; i++){\n\n  //fill in the values of the matrics\n  Eigen::MatrixXf M_i(2, 4);\n  Eigen::Matrix2f C_i;\n  Eigen::Vector2f pi_i;\n\n  // Fill in the values for the matrices\n  Eigen::Matrix4f M, W;\n  Eigen::MatrixXf g(4, 1);\n  M << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n  W << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n  g << 0, 0, 0, 0;\n\n\n  // Define sub-matrices A, B, D from M\n  Eigen::Matrix2f A, B, D;\n\n  //define S and S_A matrices from the matrices A B and D\n  Eigen::Matrix2f S;\n  Eigen::Matrix2f S_A;\n\n  //find the coefficients of the quadratic function of lambda\n  float pow_2; float pow_1; float pow_0;\n\n  // find the value of lambda by solving the equation formed. You can use the greatest real root function\n  float lambda;\n\n  //find the value of x which is the vector for translation and rotation\n  Eigen::Vector4f x;\n\n  // Convert from x to new transform\n\n  float theta = atan2(x(3), x(2));\n  curr_trans= Transform(x(0), x(1), theta);\n}\n}\n", "meta": {"hexsha": "280b84e1766418a5e86b5e614d80e3b2db4ecb84", "size": 4743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "f1tenth_labs-master/lab5/code/src/transform.cpp", "max_stars_repo_name": "Yuze-HE/F1_tenth", "max_stars_repo_head_hexsha": "a388c72cd5c236140c290f47ce26d3eec22c14b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "f1tenth_labs-master/lab5/code/src/transform.cpp", "max_issues_repo_name": "Yuze-HE/F1_tenth", "max_issues_repo_head_hexsha": "a388c72cd5c236140c290f47ce26d3eec22c14b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "f1tenth_labs-master/lab5/code/src/transform.cpp", "max_forks_repo_name": "Yuze-HE/F1_tenth", "max_forks_repo_head_hexsha": "a388c72cd5c236140c290f47ce26d3eec22c14b9", "max_forks_repo_licenses": ["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.3464566929, "max_line_length": 187, "alphanum_fraction": 0.6156441071, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361276, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6680442470316679}}
{"text": "/**\n * @file discontinuousgalerkin1d.cc\n * @brief NPDE homework \"DiscontinuousGalerkin1D\" code\n * @author Oliver Rietmann\n * @date 22.05.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"discontinuousgalerkin1d.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace DiscontinuousGalerkin1D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<double> compBmat(int Ml, int Mr, double h) {\n  const int N = 2 * (Ml + Mr + 1);\n  Eigen::SparseMatrix<double> A(N, N);\n  // Tell Eigen that the matrix is diagonal, which allows efficient\n  // initialization\n  A.reserve(Eigen::VectorXi::Ones(N));\n  for (int i = 0; i < N; i += 2) {\n    A.insert(i, i) = h;\n    A.insert(i + 1, i + 1) = h * h * h / 12.0;\n  }\n  return A;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble Feo(double v, double w) {\n  double result;\n  auto f = [](double u) { return u * (1.0 - u); };\n  auto I = [](double s) {\n    double y = 0.25 - s * (1.0 - s);\n    return s < 0.5 ? y : -y;\n  };\n  result = 0.5 * (f(v) + f(w)) - 0.5 * (I(v) - I(w));\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nSolution solveTrafficFlow() {\n  int Ml = 40;\n  int Mr = 40;\n  int N_half = Mr + Ml + 1;\n  int N = 2 * N_half;\n\n  double h = 0.05;\n  double tau = h / 3;\n  double T = 1.0;\n  unsigned int m = (unsigned int)(T / tau);\n\n  // Spatial mesh\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N_half, -2.0, 2.0);\n  // Initial condition according to \\prbeqref{eq:u0}. Note that we just\n  // initialize the cell averages; a more refined implementation would also\n  // sample the local first moments of $u_0$.\n  Eigen::VectorXd mu0 = Eigen::VectorXd::Zero(N);\n  auto u0 = [](double x) { return 0.0 <= x && x <= 1.0 ? 1.0 : 0.0; };\n  for (int i = 0; i < N_half; ++i) {\n    mu0(2 * i) = u0(x(i));\n  }\n  // Flux function\n  auto f = [](double u) { return u * (1.0 - u); };\n  // Perform fully discrete evolution\n  Eigen::VectorXd mu = dgcl(mu0, f, Feo, T, Ml, Mr, h, m);\n  // Retrieve cell averages\n  Eigen::VectorXd u(N_half);\n  for (int i = 0; i < N_half; ++i) {\n    u(i) = mu(2 * i);\n  }\n\n  return Solution(std::move(x), std::move(u));\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace DiscontinuousGalerkin1D\n", "meta": {"hexsha": "6a1ea3b5f687bb62cb5002e0917761d475df248b", "size": 2187, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.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": 27.0, "max_line_length": 75, "alphanum_fraction": 0.6049382716, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6680386958458949}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n\nTEST(AgradRev, gamma_p_var_var) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_p(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(a, b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(-0.389837, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5, 1.0), g[1]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n}\nTEST(AgradRev, gamma_p_double_var) {\n  double a = 0.5;\n  AVAR b = 1.0;\n  AVAR f = gamma_p(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(b);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p_derivative(0.5, 1.0), g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n}\nTEST(AgradRev, gamma_p_var_double) {\n  AVAR a = 0.5;\n  double b = 1.0;\n  AVAR f = gamma_p(a, b);\n  EXPECT_FLOAT_EQ(boost::math::gamma_p(0.5, 1.0), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC g;\n  f.grad(x, g);\n  EXPECT_FLOAT_EQ(-0.389837, g[0]);\n\n  a = -0.5;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n\n  b = -1.0;\n  EXPECT_THROW(gamma_p(a, b), std::domain_error);\n}\n\nstruct gamma_p_fun {\n  template <typename T0, typename T1>\n  inline typename stan::return_type<T0, T1>::type operator()(\n      const T0& arg1, const T1& arg2) const {\n    return gamma_p(arg1, arg2);\n  }\n};\n\nTEST(AgradRev, gamma_p_nan) {\n  gamma_p_fun gamma_p_;\n  test_nan(gamma_p_, 0.5, 1.0, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 0.5;\n  AVAR b = 1.0;\n  test::check_varis_on_stack(stan::math::gamma_p(a, b));\n  test::check_varis_on_stack(stan::math::gamma_p(a, 1.0));\n  test::check_varis_on_stack(stan::math::gamma_p(0.5, b));\n}\n", "meta": {"hexsha": "4fb891d7eb2edb8a58854b57cc0f22bf48c7c0f1", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_stars_repo_name": "danluu/math", "max_stars_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_issues_repo_name": "danluu/math", "max_issues_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/rev/scal/fun/gamma_p_test.cpp", "max_forks_repo_name": "danluu/math", "max_forks_repo_head_hexsha": "a293807aadc0f0d57fa56fec70251ac70f1bd8c4", "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.7625, "max_line_length": 67, "alphanum_fraction": 0.650681474, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.8080672043084051, "lm_q1q2_score": 0.6680386951035008}}
{"text": "\n#include \"mesh_param.h\"\n\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <igl/grad.h>\n#include <igl/slice.h>\n#include <igl/cat.h>\n#include <igl/doublearea.h>\n#include <igl/harmonic.h>\n#include <igl/lscm.h>\n#include <igl/boundary_loop.h>\n#include <igl/map_vertices_to_circle.h>\n#include <set>\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd interpolate_field\n(\n    const MatrixXd& V,          // Vertices of the mesh\n    const MatrixXi& F,          // Faces\n    const MatrixXi& TT,         // Adjacency triangle-triangle\n    const VectorXi& b,          // Constrained faces id\n    const MatrixXd& bc          // Cosntrained faces representative vector\n) \n{\n    // Lots of the codes below are based on the codes in tutorial_nrosy.cpp\n    // However, there are a lot of modifications\n\n    // Starter code, same as template\n    assert(b.size() > 0); // One constraint is necessary to make the solution unique\n    Matrix<double,Eigen::Dynamic,3> T1(F.rows(),3), T2(F.rows(),3);\n    // Compute the local reference systems for each face\n    for (unsigned i=0;i<F.rows();++i)\n    {\n        Vector3d e1 =  V.row(F(i, 1)) - V.row(F(i, 0));\n        Vector3d e2 =  V.row(F(i, 2)) - V.row(F(i, 0));\n        T1.row(i) = e1.normalized();\n        T2.row(i) = T1.row(i).cross(T1.row(i).cross(e2)).normalized();\n    }\n\n    // Build the sparse matrix, with an energy term for each edge\n    std::vector< Triplet<std::complex<double> > > t;\n    // The b vector is all zeroes so we do not need it here\n    // std::vector< Triplet<std::complex<double> > > tb;\n\n    // Handle the free part of matrix A; same as template\n    unsigned count = 0;\n    for (unsigned f=0;f<F.rows();++f)\n    {\n        for (unsigned ei=0;ei<F.cols();++ei)\n        {\n            // Look up the opposite face\n            int g = TT(f,ei);\n            // If it is a boundary edge, it does not contribute to the energy\n            if (g == -1) continue;\n            // Avoid to count every edge twice\n            if (f > g) continue;\n            // Compute the complex representation of the common edge\n            Vector3d e  = (V.row(F(f,(ei+1)%3)) - V.row(F(f,ei)));\n            Vector2d vef = Vector2d(e.dot(T1.row(f)),e.dot(T2.row(f))).normalized();\n            std::complex<double> ef(vef(0),vef(1));\n            Vector2d veg = Vector2d(e.dot(T1.row(g)),e.dot(T2.row(g))).normalized();\n            std::complex<double> eg(veg(0),veg(1));\n            // Add the term conj(f)^n*ui - conj(g)^n*uj to the energy matrix\n            t.push_back(Triplet<std::complex<double> >(count,f,    std::conj(ef)));\n            t.push_back(Triplet<std::complex<double> >(count,g,-1.*std::conj(eg)));\n            ++count;\n        }\n    }\n\n    // Since tb is not used, comment out the codes related to tb\n    // double lambda = 10e6;\n    double lambda = 0;\n    for (unsigned r=0; r<b.size(); ++r)\n    {\n        int f = b(r);\n        // Vector3d v = bc.row(r);\n        // std::complex<double> c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n        t.push_back(Triplet<std::complex<double> >(count,f, sqrt(lambda)));\n        // tb.push_back(Triplet<std::complex<double> >(count,0, c * std::complex<double>(sqrt(lambda),0)));\n        ++count;\n    }\n\n    const unsigned fr = F.rows();\n    const unsigned bs = b.size();\n\n    // Solve the linear system\n    // Here the solving is based on the equation\n    // Aff * u = - Afc * xc\n    // (#f is the number of total faces)\n    // (#b is number of constrained faces)\n    // (so #f-#b is the number of free faces)\n    // Where Aff is (#f-#b)*(#f-#b) matrix\n    //       u is our answer, (#f-#b)*#1 vector\n    //       Afc is (#f-#b)*#b matrix \n    //       xc is #b*#1 vector\n    // Therefore, the right part is (#f-#b)*#1 vector\n    // We need A to be a matrix of #count*#f\n    // So that Q=A.adjoint()*A is #f*#f\n    // Aff is the (#f-#b)*(#f-#b) part of Q\n    // Afc is the (#f-#b)*#b part of Q\n    typedef SparseMatrix<std::complex<double>> SparseMatrixXcd;\n    // SparseMatrixXcd A(count,F.rows());\n    SparseMatrixXcd A(count,fr); // #count*#f\n    A.setFromTriplets(t.begin(), t.end());\n    VectorXcd xc(bs,1); // #b*#1\n    for (unsigned r=0; r<b.size(); ++r) {\n        int f = b(r);\n        Vector3d v = bc.row(r);\n        std::complex<double> c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n        xc(r) = c;\n    }\n\n    #ifdef DEBUG_3\n    for (unsigned r=0; r<b.size(); ++r) {\n        int f = b(r);\n        cout << \"representation for vector on face \" << f << \": \";\n        cout << bc.row(r) << \", \" << xc(r) << \", \";\n        cout << T1.row(f) * xc(r).real() + T2.row(f) * xc(r).imag() << endl;\n    }\n    #endif\n\n    SparseMatrixXcd Q = A.adjoint()*A; // #f*#f\n\n    // Get a set of constrained faces\n    set<int> constrained_set;\n    for (unsigned r=0; r<b.size(); ++r) {\n        int f = b(r);\n        constrained_set.insert(f);\n    }\n\n    // Get the vector representing free faces\n    VectorXi vf(fr-bs);\n    unsigned findex = 0;\n    for (unsigned f=0;f<F.rows();++f) {\n        if (constrained_set.find(f) == constrained_set.end()) {\n            vf(findex) = f;\n            findex++;\n        }\n    }\n\n    #ifdef DEBUG_5\n    cout << \"constrained faces: \" << endl;\n    cout << b << endl;\n    cout << xc << endl;\n    cout << \"--------------\" << endl;\n    cout << \"free faces: \" << endl;\n    cout << vf << endl;\n    #endif\n\n    // Construct Aff\n    SparseMatrixXcd Aff(fr-bs, fr-bs); // (#f-#b)*(#f-#b)\n    igl::slice(Q, vf, vf, Aff); \n\n    // Construct Afc\n    SparseMatrixXcd Afc(fr-bs, bs); // (#f-#b)*#b\n    igl::slice(Q, vf, b, Afc);\n\n    MatrixXcd mb = (Afc * xc) * -1; // (#f-#b)*#1\n    // SparseMatrixXcd b(count,1);\n    // b.setFromTriplets(tb.begin(), tb.end());\n    SimplicialLDLT< SparseMatrixXcd > solver;\n    solver.compute(Aff);\n    // solver.compute(A.adjoint()*A);\n    assert(solver.info()==Success);\n    MatrixXcd u = solver.solve(mb);\n    // MatrixXcd u = solver.solve(A.adjoint()*MatrixXcd(b));\n    assert(solver.info()==Success);\n\n    // Finally, rearrange u and store values in ua\n    VectorXcd ua(fr);\n    for (unsigned ui = 0; ui < u.size(); ui++) {\n        ua(vf(ui)) = u(ui);\n    }\n    for (unsigned r=0; r<b.size(); ++r) {\n        ua(b(r)) = xc(r);\n    }\n\n    #ifdef DEBUG_3\n    cout << \"final insertion locations and values: \";\n    for (int i = 0; i < bs; i++) {\n        cout << b(i) << \",\" << xc(i) << \" \";\n    }\n    cout << endl;\n    #endif\n\n    // Debugging informations\n    #ifdef DEBUG_2\n    cout << \"--------------\" << endl;\n    cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n    cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n    cout << \"TT: \" << TT.rows() << \" * \" << TT.cols() << endl;\n    cout << \"b: \" << b.rows() << \" * \" << b.cols() << endl;\n    cout << \"vf: \" << vf.rows() << \" * \" << vf.cols() << endl;\n    cout << \"bc: \" << bc.rows() << \" * \" << bc.cols() << endl;\n    cout << \"T1: \" << T1.rows() << \" * \" << T1.cols() << endl;\n    cout << \"T2: \" << T2.rows() << \" * \" << T2.cols() << endl;\n    cout << \"t: \" << t.size() << endl;\n    cout << \"count = \" << count << endl;\n    cout << \"A: \" << A.rows() << \" * \" << A.cols() << endl;\n    cout << \"Q: \" << Q.rows() << \" * \" << Q.cols() << endl;\n    cout << \"xc: \" << xc.rows() << \" * \" << xc.cols() << endl;\n    cout << \"Aff: \" << Aff.rows() << \" * \" << Aff.cols() << endl;\n    cout << \"Afc: \" << Afc.rows() << \" * \" << Afc.cols() << endl;\n    cout << \"mb: \" << mb.rows() << \" * \" << mb.cols() << endl;\n    cout << \"u: \" << u.rows() << \" * \" << u.cols() << endl;\n    cout << \"ua: \" << ua.rows() << \" * \" << ua.cols() << endl;\n    cout << \"--------------\" << endl;\n    cout << \"Q nonzeros: \" << Q.nonZeros() << endl;\n    cout << \"Aff nonzeros: \" << Aff.nonZeros() << endl;\n    cout << \"Afc nonzeros: \" << Afc.nonZeros() << endl;\n    cout << \"--------------\" << endl;\n    #endif\n\n    // Convert the interpolated polyvector into Euclidean vectors\n    MatrixXd R(F.rows(),3);\n    for (int f=0; f<ua.size(); ++f) {\n        R.row(f) = T1.row(f) * ua(f).real() + T2.row(f) * ua(f).imag();\n    }\n\n    #ifdef DEBUG_3\n    cout << \"final insertion locations and coordinates: \";\n    for (int i = 0; i < bs; i++) {\n        cout << b(i) << \",\" << R.row(b(i)) << \" \";\n    }\n    cout << endl;\n    #endif\n\n    #ifdef DEBUG_3\n    cout << \"original locations and coordinates: \";\n    for (int i = 0; i < bs; i++) {\n        cout << b(i) << \",\" << bc.row(i) << \" \";\n    }\n    cout << endl;\n    #endif\n    \n    return R;\n}\n\nMatrixXd get_scalar_field\n(\n    const MatrixXd& V,             // Vertices of the mesh\n    const MatrixXi& F,             // Faces\n    const MatrixXd& R,             // Vector field\n    const SparseMatrix<double>& G  // Gradient operator \n) \n{\n    // Construct matrix A (areas)\n    VectorXd A1(F.rows());\n    igl::doublearea(V,F,A1);\n    SparseMatrix<double> A(F.rows()*3, F.rows()*3); // #3f*#3f\n    for (unsigned f = 0; f < F.rows(); ++f) {\n        A.insert(f,f) = A1(f);\n        A.insert(f+F.rows(),f+F.rows()) = A1(f);\n        A.insert(f+F.rows()*2,f+F.rows()*2) = A1(f);\n    }\n\n    // Construct matrix u (from R)\n    VectorXd u(F.rows()*3); // #3f*#1\n    for (unsigned f = 0; f < F.rows(); ++f) {\n        u(f) = R(f,0);\n        u(f+F.rows()) = R(f,1);\n        u(f+2*F.rows()) = R(f,2);\n    }\n\n    // Construct K\n    SparseMatrix<double> K = G.transpose() * A * G; // #v*#v\n    // Construct b\n    VectorXd b = G.transpose() * A * u; // #v*#1\n\n    // Row/col removal\n    SparseMatrix<double> Kff = K.bottomRightCorner(K.rows()-1, K.cols()-1);\n    // SparseMatrix<double> Kfc = K.bottomLeftCorner(K.rows()-1, 1);\n    // VectorXd sc(1);\n    // sc << 0;\n    // VectorXd bt = b.bottomRows(b.rows()-1) - Kfc * sc;\n    VectorXd bt = b.bottomRows(b.rows()-1);\n\n    #ifdef DEBUG_7\n    cout << \"--------------\" << endl;\n    cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n    cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n    cout << \"R: \" << R.rows() << \" * \" << R.cols() << endl;\n    cout << \"G: \" << G.rows() << \" * \" << G.cols() << endl;\n    cout << \"A: \" << A.rows() << \" * \" << A.cols() << endl;\n    cout << \"u: \" << u.rows() << \" * \" << u.cols() << endl;\n    cout << \"K: \" << K.rows() << \" * \" << K.cols() << endl;\n    cout << \"b: \" << b.rows() << \" * \" << b.cols() << endl;\n    cout << \"--------------\" << endl;\n    cout << \"G nonzeros: \" << G.nonZeros() << endl;\n    cout << \"A nonzeros: \" << A.nonZeros() << endl;\n    cout << \"K nonzeros: \" << K.nonZeros() << endl;\n    #endif\n\n    // Solve the system\n    SimplicialLDLT<SparseMatrix<double>> solver;\n    // solver.compute(K);\n    // assert(solver.info() == Success);\n    // MatrixXd s = solver.solve(b);\n    // assert(solver.info() == Success);\n    solver.compute(Kff);\n    assert(solver.info() == Success);\n    MatrixXd sf = solver.solve(bt);\n    assert(solver.info() == Success);\n    VectorXd s(K.rows());\n    s(0) = 0;\n    for (unsigned i = 1; i < K.rows(); i++) {\n        s(i) = sf(i-1);\n    }\n\n    // Debugging informations\n    #ifdef DEBUG_7\n    cout << \"s: \" << s.rows() << \" * \" << s.cols() << endl;\n    cout << \"--------------\" << endl;\n    #endif\n\n    return s;\n}\n\nMatrixXd harmonic_param\n(\n    const MatrixXd& V,             // Vertices of the mesh\n    const MatrixXi& F              // Faces\n) \n{\n    // Find the open boundary\n    VectorXi bnd;\n    igl::boundary_loop(F, bnd);\n    // Map the boundary to a circle\n    MatrixXd bnd_uv;\n    igl::map_vertices_to_circle(V, bnd, bnd_uv);\n    // Harmonic parameterizations\n    MatrixXd V_uv;\n    igl::harmonic(V,F,bnd,bnd_uv,1,V_uv);\n    V_uv *= 8;\n\n    #ifdef DEBUG_9\n    cout << \"--------------\" << endl;\n    cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n    cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n    cout << \"bnd: \" << bnd.rows() << \" * \" << bnd.cols() << endl;\n    cout << \"bnd_uv: \" << bnd_uv.rows() << \" * \" << bnd_uv.cols() << endl;\n    cout << \"V_uv: \" << V_uv.rows() << \" * \" << V_uv.cols() << endl;\n    cout << \"--------------\" << endl;\n    #endif\n\n    return V_uv;\n}\n\nMatrixXd lscm_param\n(\n    const MatrixXd& V,             // Vertices of the mesh\n    const MatrixXi& F              // Faces\n) \n{\n    // Fix two points on the boundary\n    VectorXi bnd, b(2,1);\n    igl::boundary_loop(F,bnd);\n    b(0) = bnd(0);\n    b(1) = bnd(round(bnd.size()/2));\n    MatrixXd bc(2,2);\n    bc << 0,0,1,0;\n    // LSCM parametrizations\n    MatrixXd V_uv;\n    igl::lscm(V,F,b,bc,V_uv);\n    V_uv *= 8;\n\n    #ifdef DEBUG_9\n    cout << \"--------------\" << endl;\n    cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n    cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n    cout << \"bnd: \" << bnd.rows() << \" * \" << bnd.cols() << endl;\n    cout << \"V_uv: \" << V_uv.rows() << \" * \" << V_uv.cols() << endl;\n    cout << \"--------------\" << endl;\n    #endif\n\n    return V_uv;\n}\n\n", "meta": {"hexsha": "d6805a95732b038c4d8c81c5ab7e6cf058fea2a4", "size": 12807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab4/src/mesh_param.cpp", "max_stars_repo_name": "bambrow/geometric-modeling", "max_stars_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T05:20:52.000Z", "max_issues_repo_path": "lab4/src/mesh_param.cpp", "max_issues_repo_name": "bambrow/geometric-modeling", "max_issues_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab4/src/mesh_param.cpp", "max_forks_repo_name": "bambrow/geometric-modeling", "max_forks_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_forks_repo_licenses": ["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.2649350649, "max_line_length": 107, "alphanum_fraction": 0.4991020536, "num_tokens": 4040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.667980507969872}}
{"text": "#define BOOST_TEST_MODULE SRF\n#include <boost/test/included/unit_test.hpp>\n\n#include <limits>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n#include \"triumf/superconductivity/bcs.hpp\"\n#include \"triumf/superconductivity/pippard.hpp\"\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pippard_g, T, test_types) {\n  BOOST_TEST(triumf::superconductivity::pippard::g<T>(0.0) ==\n             static_cast<T>(1.0));\n\n  T large_value = 1e10;\n  BOOST_TEST(triumf::superconductivity::pippard::g<T>(large_value) ==\n                 static_cast<T>(0.0),\n             boost::test_tools::tolerance(0.01));\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pippard_J_0, T, test_types) {\n  T T_c = 10.0;\n  T Delta = triumf::superconductivity::bcs::gap_meV<T>(T_c);\n  T n = 4.0;\n\n  BOOST_TEST(triumf::superconductivity::pippard::J_0<T>(\n                 0.0 * T_c, T_c, Delta, n) == static_cast<T>(1.0));\n\n  BOOST_TEST(std::isnan(\n      triumf::superconductivity::pippard::J_0<T>(1.0 * T_c, T_c, Delta, n)));\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(pippard_coherence_length, T, test_types) {\n  T T_c = 10.0;\n  T Delta = triumf::superconductivity::bcs::gap_meV<T>(T_c);\n  T n = 4.0;\n  T xi_0 = 100.0;\n  T ell = 1.0;\n\n  //\n  T effective_xi = 1.0 / ((1.0 / xi_0) + (1.0 / ell));\n  BOOST_TEST(triumf::superconductivity::pippard::coherence_length<T>(\n                 0.0 * T_c, T_c, Delta, n, xi_0, ell) == effective_xi);\n\n  //\n  BOOST_TEST(std::isnan(triumf::superconductivity::pippard::coherence_length<T>(\n      1.0 * T_c, T_c, Delta, n, xi_0, ell)));\n\n  //\n  ell = std::numeric_limits<T>::infinity();\n  effective_xi = 1.0 / ((1.0 / xi_0) + (1.0 / ell));\n  BOOST_TEST(triumf::superconductivity::pippard::coherence_length<T>(\n                 0.0 * T_c, T_c, Delta, n, xi_0, ell) == effective_xi);\n}\n\n", "meta": {"hexsha": "c65ac1dc7835d863319cfa623cf17324be27070b", "size": 1778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/superconductivity_pippard.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/superconductivity_pippard.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/superconductivity_pippard.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.6333333333, "max_line_length": 80, "alphanum_fraction": 0.6456692913, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.667951067408036}}
{"text": "/*\n *  Copyright (c) 2015-, Filippo Basso <bassofil@gmail.com>\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *     1. Redistributions of source code must retain the above copyright\n *        notice, this list of conditions and the following disclaimer.\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 *     3. Neither the name of the copyright holder(s) nor the\n *        names of its contributors may be used to endorse or promote products\n *        derived from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n#define UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n\n#include <calibration_algorithms/plane_fit.h>\n#include <Eigen/Eigenvalues>\n\nnamespace unipd\n{\nnamespace calib\n{\n\ntemplate <typename ScalarT_>\n  Plane3_<ScalarT_>\n  plane_fit (const Cloud3_<ScalarT_> & points)\n  {\n    assert(points.elements() > 1);\n\n    Point3_<ScalarT_> centroid = Point3_<ScalarT_>::Zero();\n    typename Cloud3_<ScalarT_>::Container diff(3, points.elements());\n    Size1 count = 0;\n    for (Size1 i = 0; i < points.elements(); ++i)\n    {\n      if (points[i].allFinite())\n      {\n        centroid += points[i];\n        diff.col(count++) = points[i];\n      }\n    }\n    centroid /= count;\n    diff.conservativeResize(3, count);\n    diff.colwise() -= centroid;\n\n    Eigen::Matrix<ScalarT_, 3, 3> covariance_matrix = diff * diff.transpose() / ScalarT_(count - 1);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<ScalarT_, 3, 3> > solver(covariance_matrix, Eigen::ComputeEigenvectors);\n\n    Point3_<ScalarT_> eigen_vector = solver.eigenvectors().col(0);\n    return Plane3_<ScalarT_>(eigen_vector, -eigen_vector.dot(centroid));\n  }\n\n} // namespace calib\n} // namespace unipd\n#endif // UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n", "meta": {"hexsha": "0b5ef2333e2833531d012bcc1b3b1d01f9814a3b", "size": 2944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_stars_repo_name": "pionex/calibration_toolkit", "max_stars_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T04:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:08:55.000Z", "max_issues_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_issues_repo_name": "pionex/calibration_toolkit", "max_issues_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T07:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-06T21:55:47.000Z", "max_forks_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_forks_repo_name": "pionex/calibration_toolkit", "max_forks_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-15T00:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T21:16:09.000Z", "avg_line_length": 41.4647887324, "max_line_length": 120, "alphanum_fraction": 0.7309782609, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6679510620543554}}
{"text": "#include \"tetelem.hpp\"\r\n#include <Eigen/LU>\r\n\r\n#define ZERO_DET_EPS 1e-14\r\n\r\n\r\nTetElem::TetElem(std::string& log_buf)\r\n    : log_buf_(log_buf)\r\n{}\r\n\r\nbool TetElem::Init(const uint i_elem,\r\n                   const Mat &node_mat,\r\n                   const real e_modulus,\r\n                   const real nu)\r\n{\r\n    node_mat_ = node_mat;\r\n    e_modulus_ = e_modulus;\r\n    nu_ = nu;\r\n\r\n    A_ = Mat::Zero(4, 4);\r\n    A_ << Vec::Ones(4, 1), node_mat_.block(0, 0, 4, 3);\r\n    V6_ = A_.determinant();\r\n\r\n    if (abs(V6_) == 0.0)\r\n    {\r\n        log_buf_ = \"Zero determinant for the \" + std::to_string(i_elem) + \"th element.\";\r\n        return false;\r\n    }\r\n\r\n    const Mat tmp = V6_ * A_.inverse().transpose();\r\n    a_ = tmp.col(0);\r\n    b_ = tmp.col(1);\r\n    c_ = tmp.col(2);\r\n    d_ = tmp.col(3);\r\n\r\n    D_ = Mat::Zero(6, 6);\r\n    D_(0, 0) = D_(1, 1) = D_(2, 2) = e_modulus*(1.0 - nu) / ((1.0 + nu) * (1.0 - 2*nu));\r\n    D_(0, 1) = D_(0, 2) = D_(1, 2) =\r\n    D_(1, 0) = D_(2, 0) = D_(2, 1) = e_modulus*nu / ((1.0 + nu) * (1.0 - 2*nu));\r\n    D_(3, 3) = D_(4, 4) = D_(5, 5) = e_modulus / (2.0 + 2.0*nu);\r\n\r\n    return true;\r\n}\r\n\r\nMat TetElem::BuildStifMat() const\r\n{\r\n    Mat B = Mat::Zero(6, 3*4);\r\n    BuildShapeFuncDerMat(B);\r\n\r\n    return (V6_/6.) * B.transpose() * D_ * B;\r\n}\r\n\r\nvoid TetElem::BuildShapeFuncDerMat(Mat& B) const\r\n{\r\n    for(int i = 0; i < 4; ++i)\r\n    {\r\n        B(0, 0 + 3*i) = b_[i];\r\n        B(1, 1 + 3*i) = c_[i];\r\n        B(2, 2 + 3*i) = d_[i];\r\n        B(3, 0 + 3*i) = c_[i];\r\n        B(3, 1 + 3*i) = b_[i];\r\n        B(4, 1 + 3*i) = d_[i];\r\n        B(4, 2 + 3*i) = c_[i];\r\n        B(5, 0 + 3*i) = d_[i];\r\n        B(5, 2 + 3*i) = b_[i];\r\n    }\r\n\r\n    B /= V6_;\r\n}\r\n\r\nvoid TetElem::BuildShapeFuncDerRow(Vec& row, const int idx) const\r\n{\r\n    switch(idx)\r\n    {\r\n    case 0: for(int i=0;i<4;++i) row(0 + 3*i) = b_[i]; break;\r\n    case 1: for(int i=0;i<4;++i) row(1 + 3*i) = c_[i]; break;\r\n    case 2: for(int i=0;i<4;++i) row(2 + 3*i) = d_[i]; break;\r\n    case 3: for(int i=0;i<4;++i){row(0 + 3*i) = c_[i]; row(1 + 3*i) = b_[i];} break;\r\n    case 4: for(int i=0;i<4;++i){row(1 + 3*i) = d_[i]; row(2 + 3*i) = c_[i];} break;\r\n    case 5: for(int i=0;i<4;++i){row(0 + 3*i) = d_[i]; row(2 + 3*i) = b_[i];} break;\r\n    default: return;\r\n    }\r\n\r\n    row /= V6_;\r\n}\r\n\r\nMat TetElem::BuildIsoMatHookeTensor(const real e_modulus,\r\n                                    const real nu)\r\n{\r\n    Mat m = Mat::Zero(6, 6);\r\n    m(0, 0) = m(1, 1) = m(2, 2) = 1 - nu;\r\n    m(3, 3) = m(4, 4) = m(5, 5) = 0.5 - nu;\r\n    m(0, 1)=m(1, 0) = m(0, 2)=m(2, 0) = m(1, 2)=m(1, 2) = nu;\r\n\r\n    return e_modulus / ((1 + nu)*(1 - 2*nu)) * m;\r\n}\r\n", "meta": {"hexsha": "89d2461f7912e7af45286676722548747eec5016", "size": 2632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solv_plug/tetelem.cpp", "max_stars_repo_name": "master-clown/ofeata", "max_stars_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T13:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T13:51:42.000Z", "max_issues_repo_path": "src/solv_plug/tetelem.cpp", "max_issues_repo_name": "master-clown/ofeata", "max_issues_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_issues_repo_licenses": ["MIT"], "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/solv_plug/tetelem.cpp", "max_forks_repo_name": "master-clown/ofeata", "max_forks_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T13:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T13:51:35.000Z", "avg_line_length": 27.1340206186, "max_line_length": 89, "alphanum_fraction": 0.4494680851, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6679510570976502}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"admmSolver.hpp\"\n\nint main(int argc, char **argv)\n{\n    Eigen::VectorXf mu = Eigen::VectorXf(4);\n    const float regularization = 0.1f;\n    const float volatility_target = 0.05; // 5% max vol\n\n    // Vector of asset expected returns\n    mu << 0.1, 0.3, -0.5, 0.6;\n\n    Eigen::MatrixXf Sigma(4,4);\n    // Sample covariance matrix (positive-definite)\n    Sigma << 4.2,   0.3,    0.1,    1.25,\n             0.3,   5.95,   0.56,   1.56,\n             0.1,   0.56,   4.45,   0.25,\n             1.25,  1.56,   0.25,   4.56;\n\n    Eigen::VectorXf x0 = Eigen::VectorXf::Zero(4);\n\n    // Regularized markowitz optimization\n\n    proxopp::ptfVolConstrainedL2 optim(mu, Sigma, x0, volatility_target, regularization);\n    optim.setVerbose(1);\n\n    Eigen::VectorXf ptf = optim.solve();\n    std::cout << \"Solution: \\n\";\n    std::cout << ptf << std::endl;\n    std::cout << \"(ex-ante) Volatility :\" << ptf.dot(Sigma*ptf) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "b29a2b29316f23ee4a3f273a6ce904c93bcbfe3c", "size": 984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regularizedPortfolio.cpp", "max_stars_repo_name": "jopago/proxopp", "max_stars_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T21:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T21:20:15.000Z", "max_issues_repo_path": "regularizedPortfolio.cpp", "max_issues_repo_name": "Meloignon/proxopp", "max_issues_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regularizedPortfolio.cpp", "max_forks_repo_name": "Meloignon/proxopp", "max_forks_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T21:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T21:04:38.000Z", "avg_line_length": 28.9411764706, "max_line_length": 89, "alphanum_fraction": 0.5823170732, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6679510517439697}}
{"text": "\n#include \"slamdunk/include/transformation_estimation.h\"\n#include \"slamdunk/include/pretty_printer.h\"\n\n#include <iostream>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <Eigen/SVD>\n#include <Eigen/LU> // required for determinant computation\n\n#include <android/log.h>\n\n#define  LOG_TAG4\t\"slamdunk_app\"\n#define  LOGI4(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG4, __VA_ARGS__)\n\nvoid SLAM_DUNK_API slamdunk::estimateTransformationSVD(const std::vector<Eigen::Vector3f>& reference,\n                                                const std::vector<Eigen::Vector3f>& query,\n                                                const std::vector< std::pair<unsigned, unsigned> >& ref_query_ids,\n                                                Eigen::Isometry3d& queryToRef)\n{\n  const unsigned no_of_matches = ref_query_ids.size();\n  Eigen::Vector3f mean_ref(0,0,0), mean_qry(0,0,0);\n  for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n  {\n    mean_ref += reference[ ref_query_ids[rqidx].first ];\n    mean_qry += query[ ref_query_ids[rqidx].second ];\n  }\n  mean_ref /= (float)no_of_matches;\n  mean_qry /= (float)no_of_matches;\n\n  Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n  for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n  {\n    H.noalias() += (query[ ref_query_ids[rqidx].second ] - mean_qry).cast<double>() *\n                   (reference[ ref_query_ids[rqidx].first ] - mean_ref).cast<double>().transpose();\n  }\n  // SVD\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d V = svd.matrixV();\n  Eigen::Matrix3d R = V * svd.matrixU().transpose();\n  if(R.determinant() < 0.0)\n  {\n    V.col(2) = V.col(2)*-1.0;\n    R.noalias() = V * svd.matrixU().transpose();\n  }\n\n  queryToRef.setIdentity();\n  queryToRef.rotate(R);\n  queryToRef.translation() = (mean_ref.cast<double>() - R*mean_qry.cast<double>());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\nbool slamdunk::RANSAC::findInliers(const std::vector<Eigen::Vector3f>& reference,\n                                const std::vector<Eigen::Vector3f>& query,\n                                const std::vector< std::pair<unsigned, unsigned> >& ref_query_ids)\n{\n  if(ref_query_ids.size() < 3)\n  {\n    if(m_verbose)\n      std::cout << SLAM_DUNK_WARNING_STR(\"Less than 3 matches provided\") << std::endl;\n    m_inlier_indices.clear();\n    return false;\n  }\n\n  const unsigned no_of_matches = ref_query_ids.size();\n  if(m_deterministic)\n    m_rnd_eng.seed(42u);\n  boost::variate_generator< boost::mt19937&, boost::uniform_int<unsigned> > rnd_gen(m_rnd_eng, boost::uniform_int<unsigned>(0, no_of_matches-1));\n  unsigned current_max_iterations = m_max_iterations;\n\n  unsigned a, b, c;\n  Eigen::Matrix3d ref_mtx, qry_mtx;\n  Eigen::Isometry3d current_transformation = Eigen::Isometry3d::Identity();\n  unsigned best_score = 0;\n\n  const double no_of_matches_inverse = 1.0/(double)no_of_matches;\n  const double lognum = std::log(1-m_probability);\n\n  /*std::stringstream sst;\n  sst << \"RANSAC MATCHES NUMBER: \" << no_of_matches;\n  LOGI4(sst.str().data());*/\n\n  unsigned it = 0;\n  int k = 0;\n  for(; it < current_max_iterations; ++it)\n  {\n    a = rnd_gen();\n    do b = rnd_gen(); while(a == b);\n    do c = rnd_gen(); while(c == b || c == a);\n\n    /*std::stringstream ss;\n    ss << \"RANSAC IDS: (\" << a << \", \" << b << \", \" << c << \")\";\n    LOGI4(ss.str().data());*/\n\n    ref_mtx.row(0) = reference[ ref_query_ids[a].first ].cast<double>();\n    ref_mtx.row(1) = reference[ ref_query_ids[b].first ].cast<double>();\n    ref_mtx.row(2) = reference[ ref_query_ids[c].first ].cast<double>();\n    qry_mtx.col(0) = query[ ref_query_ids[a].second ].cast<double>();\n    qry_mtx.col(1) = query[ ref_query_ids[b].second ].cast<double>();\n    qry_mtx.col(2) = query[ ref_query_ids[c].second ].cast<double>();\n\n    /*Eigen::Vector3d ref1 = reference[ ref_query_ids[a].first ].cast<double>();\n    Eigen::Vector3d ref2 = reference[ ref_query_ids[b].first ].cast<double>();\n    Eigen::Vector3d ref3 = reference[ ref_query_ids[c].first ].cast<double>();\n    Eigen::Vector3d query1 = query[ ref_query_ids[a].second ].cast<double>();\n    Eigen::Vector3d query2 = query[ ref_query_ids[b].second ].cast<double>();\n    Eigen::Vector3d query3 = query[ ref_query_ids[c].second ].cast<double>();\n\n    std::stringstream ssx1;\n    ssx1 << \"REF1: (\" << ref1.x() << \", \" << ref1.y() << \", \" << ref1.z() << \")\";\n    LOGI4(ssx1.str().data());\n    std::stringstream ssx2;\n    ssx2 << \"REF2: (\" << ref2.x() << \", \" << ref2.y() << \", \" << ref2.z() << \")\";\n    LOGI4(ssx2.str().data());\n    std::stringstream ssx3;\n    ssx3 << \"REF3: (\" << ref3.x() << \", \" << ref3.y() << \", \" << ref3.z() << \")\";\n    LOGI4(ssx3.str().data());\n    std::stringstream ssx4;\n    ssx4 << \"QUERY1: (\" << query1.x() << \", \" << query1.y() << \", \" << query1.z() << \")\";\n    LOGI4(ssx4.str().data());\n    std::stringstream ssx5;\n    ssx5 << \"QUERY2: (\" << query2.x() << \", \" << query2.y() << \", \" << query2.z() << \")\";\n    LOGI4(ssx5.str().data());\n    std::stringstream ssx6;\n    ssx6 << \"QUERY3: (\" << query3.x() << \", \" << query3.y() << \", \" << query3.z() << \")\";\n    LOGI4(ssx6.str().data());*/\n\n    // compute centroids\n    const Eigen::Vector3d cRef = (ref_mtx.row(0)+ref_mtx.row(1)+ref_mtx.row(2))*(0.33333333333333333333);\n    const Eigen::Vector3d cQry = (qry_mtx.col(0)+qry_mtx.col(1)+qry_mtx.col(2))*(0.33333333333333333333);\n\n    ref_mtx.row(0) -= cRef;\n    ref_mtx.row(1) -= cRef;\n    ref_mtx.row(2) -= cRef;\n    qry_mtx.col(0) -= cQry;\n    qry_mtx.col(1) -= cQry;\n    qry_mtx.col(2) -= cQry;\n    const Eigen::Matrix3d H = qry_mtx*ref_mtx;\n\n    // SVD\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix3d V = svd.matrixV();\n    Eigen::Matrix3d R = V * svd.matrixU().transpose();\n    if(R.determinant() < 0.0)\n    {\n      V.col(2) = V.col(2)*-1.0;\n      R.noalias() = V * svd.matrixU().transpose();\n    }\n    current_transformation = Eigen::Isometry3d(R);\n    current_transformation.translation() = cRef-R*cQry;\n\n    // voting\n    unsigned current_score = 0;\n    for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n      if((current_transformation * query[ ref_query_ids[rqidx].second ].cast<double>()\n            - reference[ ref_query_ids[rqidx].first ].cast<double>()).squaredNorm() <= m_squared_threshold)\n        ++current_score;  // TODO: weight the actual distance\n\n    // update\n    if(current_score > best_score)\n    {\n      best_score = current_score;\n      m_query2ref = current_transformation;\n\n      if(best_score == no_of_matches)\n        current_max_iterations = 0;\n      else\n        current_max_iterations = std::min((double)m_max_iterations, std::ceil(lognum / std::log(1.0 - std::pow((double)best_score * no_of_matches_inverse, 3.0))));\n    }\n  }\n\n  if(m_verbose)\n    std::cout << SLAM_DUNK_INFO_STR(\"No of iterations: \" << it) << std::endl;\n\n  if(best_score < 4)\n  {\n    if(m_verbose)\n      std::cout << SLAM_DUNK_WARNING_STR(\"Empty inlier set\") << std::endl;\n    m_inlier_indices.clear();\n    return false;\n  }\n\n  // store indices\n  m_inlier_indices.clear();\n  m_inlier_indices.reserve(best_score);\n  for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n    if((m_query2ref * query[ ref_query_ids[rqidx].second ].cast<double>()\n          - reference[ ref_query_ids[rqidx].first ].cast<double>()).squaredNorm() <= m_squared_threshold)\n      m_inlier_indices.push_back(rqidx);\n\n  return true;\n}\n", "meta": {"hexsha": "681ddaba15fe5240d010740e2a6ed18d443d4184", "size": 7534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 39.0362694301, "max_line_length": 163, "alphanum_fraction": 0.6140164587, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6678577999460437}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// math::function::versatile_equal.hpp                                       //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. 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_STATISTICS_DETAIL_MATH_FUNCTION_VERSATILE_EQUAL_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_MATH_FUNCTION_VERSATILE_EQUAL_HPP_ER_2009\n#include <cmath>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/math/tools/precision.hpp>\n\nnamespace boost{\nnamespace statistics{ \nnamespace detail{\nnamespace math{\nnamespace function{\n\n    template<typename T>\n    typename boost::enable_if<boost::is_float<T>,bool>::type\n    versatile_equal(const T& t1,const T& t2)\n    {\n        static const T eps = boost::math::tools::epsilon<T>();\n        return std::fabs(t1-t2)<eps;\n    } // warning: consider relative difference\n\n    template<typename T>\n    typename boost::enable_if<boost::is_integral<T>,bool>::type\n    versatile_equal(const T& t1,const T& t2){\n        return (t1 == t2);\n    }\n\n\n}// function\n}// math\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "f033dcbaa77315fefd5936cbb9ca9032ebec87cf", "size": 1509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/math/boost/statistics/detail/math/function/versatile_equal.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/math/boost/statistics/detail/math/function/versatile_equal.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/math/boost/statistics/detail/math/function/versatile_equal.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": 35.0930232558, "max_line_length": 79, "alphanum_fraction": 0.5732273028, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6678577891010599}}
{"text": "/*\n * Copyright (c) 2016-2017, the mcl_3dl authors\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * 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 *     * Neither the name of the copyright holder nor the names of its \n *       contributors may be used to endorse or promote products derived from \n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <cstddef>\n#include <cmath>\n#include <Eigen/Geometry>\n\n#include <gtest/gtest.h>\n\n#include <mcl_3dl/nd.h>\n\nTEST(NormalLiklihood, Normality)\n{\n  for (double sigma = 1.0; sigma <= 3.0; sigma += 1.0)\n  {\n    // Check distribution\n    mcl_3dl::NormalLikelihood<double> nl(sigma);\n    const double likelihood0 = 1.0 / sqrtf(M_PI * 2.0 * sigma * sigma);\n    ASSERT_NEAR(nl(0.0), likelihood0, 1e-6);\n    ASSERT_NEAR(nl(sigma), likelihood0 * 0.60653066, 1e-6);\n    ASSERT_NEAR(nl(-sigma), likelihood0 * 0.60653066, 1e-6);\n    ASSERT_NEAR(nl(3.0 * sigma), likelihood0 * 0.011108997, 1e-6);\n    ASSERT_NEAR(nl(-3.0 * sigma), likelihood0 * 0.011108997, 1e-6);\n\n    // Check integrated value\n    double sum(0.0);\n    const double step = 0.1;\n    for (double i = -100.0; i < 100.0; i += step)\n    {\n      sum += nl(i) * step;\n    }\n    ASSERT_NEAR(sum, 1.0, 1e-6);\n  }\n}\n\nTEST(NormalLiklihood, NormalityNd)\n{\n  for (double sigma = 1.0; sigma <= 3.0; sigma += 1.0)\n  {\n    // Check distribution\n    using NormalLikelihood2d = mcl_3dl::NormalLikelihoodNd<double, 2>;\n    NormalLikelihood2d::Matrix cov;\n    cov << sigma, 0,\n        0, sigma * 2;\n    NormalLikelihood2d nl(cov);\n\n    const double likelihood0 = 1.0 / (M_PI * 2.0 * sqrt(cov.determinant()));\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(0.0, 0.0)), likelihood0, 1e-6);\n\n    const double e1a =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(sigma, 0.0).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(sigma, 0.0));\n    const double e1b =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(0.0, sigma).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(0.0, sigma));\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(sigma, 0.0)), likelihood0 * e1a, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(-sigma, 0.0)), likelihood0 * e1a, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(0.0, sigma)), likelihood0 * e1b, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(0.0, -sigma)), likelihood0 * e1b, 1e-6);\n\n    const double e2a =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(3.0 * sigma, 0.0).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(3.0 * sigma, 0.0));\n    const double e2b =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(0.0, 3.0 * sigma).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(0.0, 3.0 * sigma));\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(3.0 * sigma, 0.0)), likelihood0 * e2a, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(-3.0 * sigma, 0.0)), likelihood0 * e2a, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(0.0, 3.0 * sigma)), likelihood0 * e2b, 1e-6);\n    ASSERT_NEAR(\n        nl(NormalLikelihood2d::Vector(0.0, -3.0 * sigma)), likelihood0 * e2b, 1e-6);\n\n    // Check integrated value\n    double sum(0.0);\n    const double step = 0.1;\n    const double step_sq = step * step;\n    for (double i = -100.0; i < 100.0; i += step)\n    {\n      for (double j = -100.0; j < 100.0; j += step)\n      {\n        sum += nl(NormalLikelihood2d::Vector(i, j)) * step_sq;\n      }\n    }\n    ASSERT_NEAR(sum, 1.0, 1e-6);\n  }\n  for (double sigma = 1.0; sigma <= 3.0; sigma += 1.0)\n  {\n    // Check distribution\n    using NormalLikelihood2d = mcl_3dl::NormalLikelihoodNd<double, 2>;\n    NormalLikelihood2d::Matrix cov;\n    cov << sigma, 0,\n        0, sigma;\n    NormalLikelihood2d nl(cov);\n\n    const double likelihood0 = 1.0 / (M_PI * 2.0 * sqrt(cov.determinant()));\n    const double e1 =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(sigma, 0.0).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(sigma, 0.0));\n    const double e2 =\n        exp(-0.5 *\n            NormalLikelihood2d::Vector(3.0 * sigma, 0.0).transpose() *\n            cov.inverse() *\n            NormalLikelihood2d::Vector(3.0 * sigma, 0.0));\n    for (double r = 0; r < M_PI * 2; r += M_PI / 6)\n    {\n      const auto v1 =\n          Eigen::Rotation2D<double>(r) *\n          NormalLikelihood2d::Vector(sigma, 0.0);\n      ASSERT_NEAR(nl(v1), likelihood0 * e1, 1e-6);\n      const auto v2 =\n          Eigen::Rotation2D<double>(r) *\n          NormalLikelihood2d::Vector(3.0 * sigma, 0.0);\n      ASSERT_NEAR(nl(v2), likelihood0 * e2, 1e-6);\n    }\n  }\n}\n\nint main(int argc, char** argv)\n{\n  testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "3dacc76918e5320e148ddea66a9f8e01cf34ed8f", "size": 6103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/test_nd.cpp", "max_stars_repo_name": "doctorwk007/mcl_3dl", "max_stars_repo_head_hexsha": "6eda33369a52d09c4f3927e36fd26f8f64fd2ece", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-01T12:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:49:20.000Z", "max_issues_repo_path": "test/src/test_nd.cpp", "max_issues_repo_name": "ZHI-ANG/learning_mcl_3dl", "max_issues_repo_head_hexsha": "56d7252ebc94e1607bf3c2dc1104f608ca198589", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T06:36:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-23T06:36:32.000Z", "max_forks_repo_path": "test/src/test_nd.cpp", "max_forks_repo_name": "ZHI-ANG/learning_mcl_3dl", "max_forks_repo_head_hexsha": "56d7252ebc94e1607bf3c2dc1104f608ca198589", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-09T03:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T03:35:51.000Z", "avg_line_length": 36.3273809524, "max_line_length": 84, "alphanum_fraction": 0.6293626086, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6678175788046181}}
{"text": "// functions to calculate X^2 (Pearson's cumulative test statistic)\n// and significance (1 - P(X^2/2, k/2)) for k categories. \n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/format.hpp>\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include \"ChiSquared.hxx\"\n\ndouble ChiSquared::pearsonCTS(const std::vector<int> & S, \n\t\t  const std::vector<int> & X)\n{\n  // The inputs S[i] and X[i] are in the form of \"number of samples in\n  // category [i] for the \"standard\" case (the histogram that fits\n  // the null hypothesis) and the sample to be tested. \n  \n  // first make the p[i] (normative probability of an occurance in\n  // bucket [i].\n  int num_Ssamps = 0;\n  int N = 0;   \n  for(int i = 0; i < S.size(); i++) {\n    num_Ssamps += S[i];\n    N += X[i];     \n  }\n\n  std::vector<double> p; \n  double rtsamps = 1.0 / ((double) num_Ssamps); \n  for(int i = 0; i < S.size(); i++) {\n    double v = (double) S[i]; \n    p.push_back(v * rtsamps);\n  }\n\n  // check\n  double sum_c = 0.0; \n  for(double pi: p) {\n    sum_c += pi; \n  }\n  std::cerr << \"sum_c = \" << sum_c << \" (1-sum_c) = \" << (1.0 - sum_c) << std::endl; \n\n  double X2 = -1.0 * ((double) N);\n  \n  for(int i = 0; i < S.size(); i++) {\n    double m = N * p[i]; \n    double xi = ((double) X[i]); \n    \n    X2 += (xi * xi / m); \n  }\n\n  return X2; \n}\n\ndouble ChiSquared::test(const std::vector<int> & S, const std::vector<int> X)\n{\n  int k = S.size(); \n  \n  return 1.0 - boost::math::gamma_p(((double) k) * 0.5, pearsonCTS(S, X) * 0.5);\n}\n\n\n", "meta": {"hexsha": "0b4ca778de25f4fae412d77a36b3f2aeb3f4ba6c", "size": 1510, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/ChiSquared.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/ChiSquared.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/ChiSquared.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": 24.3548387097, "max_line_length": 85, "alphanum_fraction": 0.5728476821, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6675785555060704}}
{"text": "#ifndef SPLINE_SPLINE_HPP\n#define SPLINE_SPLINE_HPP\n\n#include <Eigen/Dense>\n#include <utility>\n#include <vector>\n#include <iostream>\n\nclass QuadraticSplineSegment {\npublic:\n\n    void setCtrlPointsAbscissa(double x_1, double x_2) {\n        x1 = x_1;\n        x2 = x_2;\n    }\n\n    void setCtrlPointsOrdinate(double y_1, double y_2) {\n        y1 = y_1;\n        y2 = y_2;\n    }\n\n    void setTangent(double tangent) {\n        t1 = tangent;\n    }\n\n    bool computeParams() {\n        Eigen::Matrix3d A;\n        Eigen::Vector3d Y, X;\n\n        A << pow(x1, 2), x1, 1,\n                pow(x2, 2), x2, 1,\n                2 * x1, 1, 0;\n\n        Y << y1, y2, t1;\n\n        X = A.colPivHouseholderQr().solve(Y);\n\n        a2 = X[0];\n        a1 = X[1];\n        a0 = X[2];\n        std::cout << a2 << \" \" << a1 << \" \" << a0 << std::endl;\n    }\n\n    void getParams(double &a_2, double &a_1, double &a_0) const {\n        a_2 = a2;\n        a_1 = a1;\n        a_0 = a0;\n    }\n\n    double getTangent() const {\n        return t1;\n    }\n\n    double arcLength(double gamma) {\n        computeParams();\n        double yi = y1, yi1, xi = x1, xi1, len, ti;\n        while (norm(xi - x2, yi - y2) > gamma * 3) {\n            ti = evalDerivative(xi);\n            yi = evalFunction(xi);\n            xi1 = xi + gamma / norm(1, ti);\n            yi1 = evalFunction(xi1);\n            len += norm(xi1 - xi, yi1 - yi);\n            std::cout << ((norm(xi - x2, yi - y2) - gamma) / gamma - 1.0) * 100 << \" \" << xi << std::endl;\n            xi = xi1;\n        }\n        return len;\n    }\n\n    double evalFunction(double x) const {\n        return a2 * pow(x, 2) + a1 * x + a0;\n    }\n\n    double evalDerivative(double x) const {\n        return a2 * x + a1;\n    }\n\nprotected:\n\n    static inline double norm(double x, double y) {\n        return sqrt(pow(x, 2) + pow(y, 2));\n    }\n\n    double t1, x1, x2, y1, y2;\n    double a2, a1, a0;\n};\n\nclass QuadraticSplineCurve {\npublic:\n\n    explicit QuadraticSplineCurve(std::vector<std::vector<double>> coordinates, double tangent) : coord(\n            std::move(coordinates)), t(tangent) {}\n\n    void compute() {\n        QuadraticSplineSegment segment{};\n        double x1, y1, x2, y2;\n\n        for (int i = 0; i < coord.size() - 1; ++i) {\n            auto pts1 = coord[i];\n            auto pts2 = coord[i + 1];\n            x1 = pts1[0];\n            y1 = pts1[1];\n            x2 = pts2[0];\n            y2 = pts2[1];\n\n            segment.setCtrlPointsAbscissa(x1, x2);\n            segment.setCtrlPointsOrdinate(y1, y2);\n\n            if (i == 0) {\n                segment.setTangent(t);\n            } else {\n                segment.setTangent(curve[curve.size() - 1].evalDerivative(x2));\n            }\n\n            segment.computeParams();\n\n            curve.push_back(segment);\n        }\n    }\n\n    double evalFunction(double x) {\n        double x1, x2;\n\n        for (int i = 0; i < coord.size() - 1; ++i) {\n\n            auto pts1 = coord[i];\n            auto pts2 = coord[i + 1];\n\n            x1 = pts1[0];\n            x2 = pts2[0];\n\n            if (x1 < x2) {\n                if ((x >= x1) and (x <= x2)) {\n                    return curve[i].evalFunction(x);\n                }\n            } else {\n                if ((x <= x1) and (x >= x2)) {\n                    return curve[i].evalFunction(x);\n                }\n            }\n        }\n    }\n\n    double length(double gamma) {\n        cLength = 0;\n        for (auto segment : curve) {\n            cLength += segment.arcLength(gamma/1000.0);\n        }\n    }\n\nprotected:\n    std::vector<std::vector<double>> coord;\n    std::vector<QuadraticSplineSegment> curve;\n    double t, cLength{};\n};\n\n#endif //SPLINE_SPLINE_HPP\n", "meta": {"hexsha": "7268666312ba8918aa46584c9445fcdfaa1a13ed", "size": 3662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Spline.hpp", "max_stars_repo_name": "dcmde/spline", "max_stars_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_stars_repo_licenses": ["MIT"], "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/Spline.hpp", "max_issues_repo_name": "dcmde/spline", "max_issues_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_issues_repo_licenses": ["MIT"], "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/Spline.hpp", "max_forks_repo_name": "dcmde/spline", "max_forks_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_forks_repo_licenses": ["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.3248407643, "max_line_length": 106, "alphanum_fraction": 0.4751501912, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6675785522880643}}
{"text": "/**\n * This file is part of https://github.com/adrelino/interpolation-methods\n *\n * Copyright (c) 2018 Adrian Haarbach <mail@adrian-haarbach.de>\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n#ifndef INTERPOL_RANDOM_HPP\n#define INTERPOL_RANDOM_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace interpol {\n\nnamespace random {\n    double numberUniform();\n    double numberNormal();\n\n    Eigen::Vector3d vectorUniform(double scale=1.0);\n    Eigen::Vector3d vectorNormal(double sigma=1.0);\n\n    enum class QuaternionSampling {Hypersphere, AngleAxis, Shoemake, NormalDistribution};\n    Eigen::Quaterniond quaternionUniform(QuaternionSampling method=QuaternionSampling::Hypersphere);\n} // ns random\n\n} // ns interpol\n\n#endif // INTERPOL_RANDOM_HPP\n", "meta": {"hexsha": "a0cc2028dcc4acbb7c2a96226fdc24d47ea3eb0c", "size": 843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libinterpol/include/interpol/utils/random.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/utils/random.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/utils/random.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": 27.1935483871, "max_line_length": 100, "alphanum_fraction": 0.7580071174, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6675523064295434}}
{"text": "// g2o sphere\n// based on https://github.com/RainerKuemmerle/g2o/blob/master/g2o/examples/sphere/create_sphere.cpp\n// reference 1 :  https://malcolmmielle.wordpress.com/2016/06/20/g2o-optimization/\n// reference 2 : http://fzheng.me/2016/03/15/g2o-demo/\n// Created by Seung-Chan Kim on 12/29/16.\n\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n\n#include \"g2o/types/slam3d/vertex_se3.h\"\n#include \"g2o/types/slam3d/edge_se3.h\"\n#include \"g2o/stuff/sampler.h\"\n#include \"g2o/stuff/command_args.h\"\n#include \"g2o/core/factory.h\"\n\n\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/optimization_algorithm_gauss_newton.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\n\n\nusing namespace std;\nusing namespace g2o;\n\nint main(int argc, char** argv)\n{\n    // command line parsing\n    int nodesPerLevel;\n    int numLaps;\n    bool randomSeed;\n    double radius;\n    std::vector<double> noiseTranslation;\n    std::vector<double> noiseRotation;\n    string outFilename;\n    CommandArgs arg;\n    arg.param(\"o\", outFilename, \"-\", \"output filename\");\n    arg.param(\"nodesPerLevel\", nodesPerLevel, 50, \"how many nodes per lap on the sphere\");\n    arg.param(\"laps\", numLaps, 50, \"how many times the robot travels around the sphere\");\n    arg.param(\"radius\", radius, 100., \"radius of the sphere\");\n    arg.param(\"noiseTranslation\", noiseTranslation, std::vector<double>(), \"set the noise level for the translation, separated by semicolons without spaces e.g: \\\"0.1;0.1;0.1\\\"\");\n    arg.param(\"noiseRotation\", noiseRotation, std::vector<double>(), \"set the noise level for the rotation, separated by semicolons without spaces e.g: \\\"0.001;0.001;0.001\\\"\");\n    arg.param(\"randomSeed\", randomSeed, false, \"use a randomized seed for generating the sphere\");\n    arg.parseArgs(argc, argv);\n\n    if (noiseTranslation.size() == 0)\n    {\n        cerr << \"using default noise for the translation\" << endl;\n        noiseTranslation.push_back(0.01);\n        noiseTranslation.push_back(0.01);\n        noiseTranslation.push_back(0.01);\n    }\n    cerr << \"Noise for the translation:\";\n    for (size_t i = 0; i < noiseTranslation.size(); ++i)\n        cerr << \" \" << noiseTranslation[i];\n    cerr << endl;\n    if (noiseRotation.size() == 0)\n    {\n        cerr << \"using default noise for the rotation\" << endl;\n        noiseRotation.push_back(0.005);\n        noiseRotation.push_back(0.005);\n        noiseRotation.push_back(0.005);\n    }\n    cerr << \"Noise for the rotation:\";\n    for (size_t i = 0; i < noiseRotation.size(); ++i)\n        cerr << \" \" << noiseRotation[i];\n    cerr << endl;\n\n    Eigen::Matrix3d transNoise = Eigen::Matrix3d::Zero();\n    /*\n     0 0 0\n     0 0 0\n     0 0 0\n     */\n\n    for (int i = 0; i < 3; ++i)\n    transNoise(i, i) = std::pow(noiseTranslation[i], 2);\n\n\n    Eigen::Matrix3d rotNoise = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < 3; ++i)\n        rotNoise(i, i) = std::pow(noiseRotation[i], 2);\n    cout << \"transNoise =\" <<endl;\n    cout << transNoise << endl;\n\n    cout << \"rotNoise =\" <<endl;\n    cout << rotNoise << endl;\n\n    Eigen::Matrix<double, 6, 6> information = Eigen::Matrix<double, 6, 6>::Zero();\n    information.block<3,3>(0,0) = transNoise.inverse();\n    information.block<3,3>(3,3) = rotNoise.inverse();\n\n    // information matrix represents how reliable this measurement is. Therefore, the more precisely the measurement is made or the more you trust in this measurement, the larger values in the information matrix you can set. (see http://fzheng.me/2016/03/15/g2o-demo/ )\n    cout << \"information =\" <<endl;\n    cout << information << endl;\n\n    cout << \"numLaps (how many times the robot travels around the sphere) = \" << numLaps << endl;\n    cout << \"nodesPerLevel (how many nodes per lap on the sphere) = \" << nodesPerLevel << endl;\n\n    vector<VertexSE3*> vertices;\n    vector<EdgeSE3*> odometryEdges;\n    vector<EdgeSE3*> edges;\n    \n    // create the optimizer to load the data and carry out the optimization\n    SparseOptimizer optimizer;\n    \n    int id = 0;\n    FILE *fp = fopen(\"out_t.txt\", \"w+\");\n    for (int f = 0; f < numLaps; ++f)\n    {\n        for (int n = 0; n < nodesPerLevel; ++n)\n        {\n            VertexSE3* v = new VertexSE3;\n            v->setId(id++);\n            \n            if(id==1)\n            v->setFixed( true );\n\n            Eigen::AngleAxisd rotz(-M_PI + 2*n*M_PI / nodesPerLevel, Eigen::Vector3d::UnitZ());\n            Eigen::AngleAxisd roty(-0.5*M_PI + id*M_PI / (numLaps * nodesPerLevel), Eigen::Vector3d::UnitY());\n            Eigen::Matrix3d rot = (rotz * roty).toRotationMatrix();\n\n            Eigen::Isometry3d t;\n            t = rot;\n            t.translation() = t.linear() * Eigen::Vector3d(radius, 0, 0);\n            //cout << t.translation().transpose() <<endl;;\n            v->setEstimate(t);\n            vertices.push_back(v);\n\n            optimizer.addVertex(v);\n            //row-wise\n            fprintf(fp, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",\n                        t(0,0), t(0,1),t(0,2), t(0,3),\n                        t(1,0), t(1,1),t(1,2), t(1,3),\n                        t(2,0), t(2,1),t(2,2), t(2,3),\n                        t(3,0), t(3,1),t(3,2), t(3,3) );\n        }\n    }\n    fclose(fp);\n\n    // generate odometry edges\n    for (size_t i = 1; i < vertices.size(); ++i) {\n        VertexSE3* prev = vertices[i-1];\n        VertexSE3* cur  = vertices[i];\n        Eigen::Isometry3d t = prev->estimate().inverse() * cur->estimate();\n        EdgeSE3* e = new EdgeSE3;\n        e->setVertex(0, prev);\n        e->setVertex(1, cur);\n        e->setMeasurement(t);\n        e->setInformation(information);\n        odometryEdges.push_back(e);\n        edges.push_back(e);\n        optimizer.addEdge(e);\n    }\n\n    // generate loop closure edges\n    fp = fopen(\"out_loopclosure_from+to.txt\", \"w+\");\n    for (int f = 1; f < numLaps; ++f) {\n        for (int nn = 0; nn < nodesPerLevel; ++nn) {\n            VertexSE3* from = vertices[(f-1)*nodesPerLevel + nn];\n            //row-wise\n            Eigen::Isometry3d tf = from->estimate();\n\n            for (int n = -1; n <= 1; ++n) // set three vertices\n            {\n                if (f == numLaps-1 && n == 1)\n                    continue;\n            //  VertexSE3* from = vertices[(f-1)*nodesPerLevel + nn];\n                VertexSE3* to   = vertices[f*nodesPerLevel + nn + n]; // one-level\uc704\uc5d0\uc11c 3\uac1c\uc758 vertices\uc640 \uc5f0\uacb0\n                Eigen::Isometry3d t = from->estimate().inverse() * to->estimate();\n                EdgeSE3* e = new EdgeSE3;\n                e->setVertex(0, from);\n                e->setVertex(1, to);\n                e->setMeasurement(t);\n                e->setInformation(information);\n                edges.push_back(e);\n                optimizer.addEdge(e); // what happens if commented out?\n                \n                Eigen::Isometry3d tt = to->estimate();\n                fprintf(fp, \"%f\\t%f\\t%f\\t%f\\t\\t\",   tf(0,3),tf(1,3),tf(2,3),tf(3,3) );\n                fprintf(fp, \"%f\\t%f\\t%f\\t%f\\n\",     tt(0,3),tt(1,3),tt(2,3),tt(3,3) );\n            }\n            //fprintf(fp, \"\\n\");\n        }\n    }\n    fclose(fp);\n\n    GaussianSampler<Eigen::Vector3d, Eigen::Matrix3d> transSampler;\n    transSampler.setDistribution(transNoise);\n    GaussianSampler<Eigen::Vector3d, Eigen::Matrix3d> rotSampler;\n    rotSampler.setDistribution(rotNoise);\n\n#if 0\n    if (randomSeed)\n    {\n        std::random_device r;\n        std::seed_seq seedSeq{r(), r(), r(), r(), r()};\n        vector<int> seeds(2);\n        seedSeq.generate(seeds.begin(), seeds.end());\n        cerr << \"using seeds:\";\n        for (size_t i = 0; i < seeds.size(); ++i)\n            cerr << \" \" << seeds[i];\n        cerr << endl;\n        transSampler.seed(seeds[0]); // error ?\n        rotSampler.seed(seeds[1]);\n    }\n#endif\n\n    // noise for all the edges\n    for (size_t i = 0; i < edges.size(); ++i)\n    {\n        EdgeSE3* e = edges[i];\n        Eigen::Quaterniond gtQuat = (Eigen::Quaterniond)e->measurement().linear();\n        Eigen::Vector3d gtTrans = e->measurement().translation();\n\n        Eigen::Vector3d quatXYZ = rotSampler.generateSample();\n        double qw = 1.0 - quatXYZ.norm();\n        if (qw < 0)\n        {\n            qw = 0.;\n            cerr << \"x\";\n        }\n        Eigen::Quaterniond rot(qw, quatXYZ.x(), quatXYZ.y(), quatXYZ.z());\n        rot.normalize();\n        Eigen::Vector3d trans = transSampler.generateSample();\n        rot = gtQuat * rot;\n        trans = gtTrans + trans;\n\n        Eigen::Isometry3d noisyMeasurement = (Eigen::Isometry3d) rot;\n        noisyMeasurement.translation() = trans;\n        e->setMeasurement(noisyMeasurement);\n    }\n\n\n    // concatenate all the odometry constraints to compute the initial state\n    // An hyper graph is a graph where an edge can connect one or more nodes.\n    for (size_t i =0; i < odometryEdges.size(); ++i)\n    {\n        EdgeSE3* e = edges[i];\n        VertexSE3* from = static_cast<VertexSE3*>(e->vertex(0));\n        VertexSE3* to = static_cast<VertexSE3*>(e->vertex(1));\n        HyperGraph::VertexSet aux;\n        aux.insert(from);\n        e->initialEstimate(aux, to);\n    }\n\n    // write output\n    ofstream fileOutputStream;\n    if (outFilename != \"-\")\n    {\n        //cerr << \"Writing into \" << outFilename << endl;\n        //fileOutputStream.open(outFilename.c_str());\n    }\n    else\n    {\n        //cerr << \"writing to stdout\" << endl;\n        outFilename = \"out_vertex+edge.g2o\";\n\n    }\n    cerr << \"Writing into \" << outFilename << endl;\n    fileOutputStream.open(outFilename.c_str());\n\n    string vertexTag = Factory::instance()->tag(vertices[0]);\n    string edgeTag = Factory::instance()->tag(edges[0]);\n    cout << \"vertexTag = \"<< vertexTag << endl;\n    cout << \"edgeTag = \"<< edgeTag << endl;\n    \n    ostream& fout = outFilename != \"-\" ? fileOutputStream : cout;\n    for (size_t i = 0; i < vertices.size(); ++i)\n    {\n        VertexSE3* v = vertices[i];\n        fout << vertexTag << \" \" << v->id() << \" \";\n        v->write(fout);\n        fout << endl;\n    }\n\n\n    for (size_t i = 0; i < edges.size(); ++i)\n    {\n        EdgeSE3* e = edges[i];\n        VertexSE3* from = static_cast<VertexSE3*>(e->vertex(0));\n        VertexSE3* to = static_cast<VertexSE3*>(e->vertex(1));\n        fout << edgeTag << \" \" << from->id() << \" \" << to->id() << \" \";\n        e->write(fout);\n        fout << endl;\n    }\n\n    // write output\n    fp = fopen(\"out_vertices_before.txt\", \"w\");\n    for(int i=0; i<vertices.size(); i++)\n    {\n     \n        Eigen::Isometry3d t = vertices[i]->estimate();\n        //cout<<\"vertex pose(before)=\"<<endl<<t.matrix()<<endl;\n        \n        fprintf(fp, \"%f\\t%f\\t%f\\t%f\\n\",   t(0,3),t(1,3),t(2,3),t(3,3) );\n        \n    }\n    fclose(fp);\n    \n    \n    // create the linear solver\n    BlockSolverX::LinearSolverType * linearSolver = new LinearSolverCSparse<BlockSolverX::PoseMatrixType>();\n    \n    // create the block solver on top of the linear solver\n    BlockSolverX* blockSolver = new BlockSolverX(linearSolver);\n\n    \n    // create the algorithm to carry out the optimization\n    //OptimizationAlgorithmGaussNewton* optimizationAlgorithm = new OptimizationAlgorithmGaussNewton(blockSolver);\n    OptimizationAlgorithmLevenberg* optimizationAlgorithm = new OptimizationAlgorithmLevenberg(blockSolver);\n\n    \n    optimizer.setVerbose(true);\n    optimizer.setAlgorithm(optimizationAlgorithm);\n    \n    int maxIterations = 10;\n    \n    \n    optimizer.initializeOptimization();\n    optimizer.optimize(maxIterations);\n\n    // Visulizing only points (w/o pose)\n    fp = fopen(\"out_vertices_after.txt\", \"w\");\n    for(size_t i=0; i<vertices.size(); i++)\n    //for(int i=0; i<2; i++)\n    {\n        g2o::VertexSE3* v = dynamic_cast<g2o::VertexSE3*>( optimizer.vertex(i) );\n        Eigen::Isometry3d t = v->estimate();\n        //cout<<\"vertex pose(after)=\"<<endl<<t.matrix()<<endl;\n        \n        fprintf(fp, \"%f\\t%f\\t%f\\t%f\\n\",   t(0,3),t(1,3),t(2,3),t(3,3) );\n        \n    }\n    fclose(fp);\n    \n    cout << \"Done!!! \" << endl;\n    return 0;\n}\n", "meta": {"hexsha": "bf897757a7b387daa290ad1f35688de6fd7fe512", "size": 12140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Optimization/g2o/g2otest-sphere/main.cpp", "max_stars_repo_name": "faipaz/Algorithms", "max_stars_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-08-19T14:00:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T09:11:48.000Z", "max_issues_repo_path": "Optimization/g2o/g2otest-sphere/main.cpp", "max_issues_repo_name": "faipaz/Algorithms", "max_issues_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T19:20:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T19:20:47.000Z", "max_forks_repo_path": "Optimization/g2o/g2otest-sphere/main.cpp", "max_forks_repo_name": "faipaz/Algorithms", "max_forks_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T15:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-09T10:55:36.000Z", "avg_line_length": 34.9855907781, "max_line_length": 269, "alphanum_fraction": 0.5755354201, "num_tokens": 3379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6674896577511494}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <utility>\n\n#include <Eigen/Dense>\n\nnamespace orient {\n\n// \\brief Calculate rotation matrix from quaternion\n//        Quaternion is expressed as a 4D-vector [w,a,b,c] such that\n//        q = w + a*i + b*j + c*k\n// \\param q Source quaternion\n// \\return Rotation matrix\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, 3, 3> rotationMatrixFromQuaternion(Eigen::Matrix<Scalar, 4, 1> const& q);\n\n// \\brief Calculate rotation matrix and partial derivatives from quaternion\n//        See above for more detail\n// \\param q Source quaternion\n// \\return A pair containg first the rotation matrix then secondly the Jacobian matrix \ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar, 3, 3>, Eigen::Matrix<Scalar, 9, 4>> rotationMatrixFromQuaternionWD(Eigen::Matrix<Scalar, 4, 1> const& q);\n\n// \\brief Calculate angle axis derivatives from quaternion\n//        See above for more detail\n// \\param q Source quaternion\n// \\return Angle axis\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, 3, 1> angleAxisFromQuaternion(Eigen::Matrix<Scalar, 4, 1> const& q);\n\n// \\brief Calculate angle axis and partial derivatives from quaternion\n//        See above for more detail\n// \\param q Source quaternion\n// \\return A pair containg first the angle axis secondly the Jacobian matrix \ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar, 3, 1>, Eigen::Matrix<Scalar, 3, 4>> angleAxisFromQuaternionWD(Eigen::Matrix<Scalar, 4, 1> const& q);\n\n}\n\n#include <orient/impl/from_quaternion.hpp>\n", "meta": {"hexsha": "65bac322ee6910fb4432736db2b1c01d0d5a4699", "size": 1713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/from_quaternion.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/from_quaternion.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/from_quaternion.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": 37.2391304348, "max_line_length": 137, "alphanum_fraction": 0.7238762405, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6674630774115037}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <boost/math/constants/constants.hpp>\n#include \"ear/common_types.hpp\"\n#include \"ear/metadata.hpp\"\n\nnamespace ear {\n\n  template <typename T>\n  inline T radians(T d) {\n    return d * static_cast<T>(boost::math::constants::pi<double>() / 180.0);\n  }\n\n  template <typename T>\n  inline T degrees(T r) {\n    return r * static_cast<T>(180.0 / boost::math::constants::pi<double>());\n  }\n\n  /** @brief Assuming y is clockwise from x, increment y by 360 until it's not\n   * less than x.\n   *\n   * @param x Start angle in degrees.\n   * @param y End angle in degrees.\n   *\n   * @returns y shifted such that it represents the same angle but is greater\n   *  than x.\n   */\n  inline double relativeAngle(double x, double y) {\n    while (y - 360.0 >= x) {\n      y -= 360.0;\n    }\n    while (y < x) {\n      y += 360.0;\n    }\n    return y;\n  }\n\n  /** @brief Assuming end is clockwise from start, is the angle x inside\n   * [start,end] within some tolerance?\n   *\n   * @param x Angle to test, in degrees\n   * @param start Start angle of range, in degrees\n   * @param end End angle of range, in degrees\n   * @param tol Tolerance in degrees to check within\n   */\n  bool insideAngleRange(double x, double start, double end, double tol = 0.0);\n\n  /** @brief Order the vertices of a convex, approximately planar polygon.\n   *\n   * @param vertices Vertices to order (n, 3)\n   *\n   * @returns Indices to put the vertices into the right order.\n   */\n  Eigen::VectorXi ngonVertexOrder(Eigen::MatrixXd vertices);\n\n  double azimuth(Eigen::Vector3d position);\n  double elevation(Eigen::Vector3d position);\n  double distance(Eigen::Vector3d position);\n\n  Eigen::Vector3d cart(double azimuth, double elevation, double distance);\n\n  inline Eigen::RowVector3d cartT(double azimuth, double elevation,\n                                  double distance) {\n    return cart(azimuth, elevation, distance).transpose();\n  }\n\n  PolarPosition toPolarPosition(CartesianPosition position);\n  CartesianPosition toCartesianPosition(PolarPosition position);\n  Eigen::Vector3d toNormalisedVector3d(PolarPosition position);\n\n  Eigen::Vector3d toCartesianVector3d(PolarPosition position);\n  Eigen::Vector3d toCartesianVector3d(CartesianPosition position);\n  Eigen::Vector3d toCartesianVector3d(SpeakerPosition position);\n  Eigen::Vector3d toCartesianVector3d(PolarSpeakerPosition position);\n  Eigen::Vector3d toCartesianVector3d(CartesianSpeakerPosition position);\n\n  Eigen::MatrixXd toPositionsMatrix(\n      const std::vector<PolarPosition>& positions);\n\n  /** @brief Calc local coordinate system\n   *\n   * @param azimuth: ADM format azimuth\n   * @param elevation: ADM format elevation\n   *\n   * @return Vectors pointing along x, y and z, rotated so that +y points at\n   * cart(az, el, 1).\n   */\n  inline Eigen::Matrix3d localCoordinateSystem(double azimuth,\n                                               double elevation) {\n    Eigen::Matrix3d ret;\n    ret << cartT(azimuth - 90.0, 0.0, 1.0),  //\n        cartT(azimuth, elevation, 1.0),  //\n        cartT(azimuth, elevation + 90.0, 1.0);\n    return ret;\n  }\n\n}  // namespace ear\n", "meta": {"hexsha": "17a1a5bb28a8def4c4277ae10b504b65d0ad8a4d", "size": 3122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/geom.hpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/common/geom.hpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/common/geom.hpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 31.8571428571, "max_line_length": 78, "alphanum_fraction": 0.6768097373, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6674630750403252}}
{"text": "/** @file 38.cpp Problem 38: Pandigital multiples\n *\n * Take the number 192 and multiply it by each of 1, 2, and 3:\n *\n *      192 x 1 = 192\n *      192 x 2 = 384\n *      192 x 3 = 576\n *\n * By concatenating each product we get the 1 to 9 pandigital, 192384576. We\n * will call 192384576 the concatenated product of 192 and (1,2,3)\n *\n * The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4,\n * and 5, giving the pandigital, 918273645, which is the concatenated product\n * of 9 and (1,2,3,4,5).\n *\n * What is the largest 1 to 9 pandigital 9-digit number that can be formed as\n * the concatenated product of an integer with (1,2, ... , n) where n > 1?\n */\n\n// At most eight values of n, 2 through 9, are worth considering; n < 2 is\n// explicitly prohibited by the problem description, and n > 9 will produce a\n// number that exceeds the specified (9-digit) length.\n//\n// Similarly, we can limit the values of the multiplicand `m` to those that\n// produce 9-digit concatenated products.\n\n#include \"int_util.hpp\"                         // pandigital\n\n/// @cond\n#include <boost/iterator/counting_iterator.hpp> // counting_iterator\n#include <boost/multiprecision/cpp_int.hpp>     // cpp_int\n\n#include <algorithm>                            // all_of\n#include <iostream>                             // cout\n#include <vector>\n/// @endcond\n\nusing boost::make_counting_iterator;\nusing boost::multiprecision::cpp_int;\nusing int_util::length;\nusing int_util::pandigital;\n\ncpp_int cat_prod(cpp_int const& m, std::vector<int> const& v)\n{\n    std::string s;\n    for (auto const& x : v)\n        s += cpp_int(m * x).str();\n    return cpp_int(s);\n}\n\nint main()\n{\n    cpp_int r = 0;\n    for (int n = 2; n <= 9; ++n) {\n        std::vector<int> v(\n                make_counting_iterator(1),\n                make_counting_iterator(n + 1));\n        cpp_int m = 1;\n        auto p = cat_prod(m, v);\n        while (p.str().size() < 9) {  // Skip products that are too short.\n            ++m;\n            p = cat_prod(m, v);\n        }\n        while (p.str().size() == 9) {\n            if (p > r && pandigital(p))\n                r = p;\n            p = cat_prod(++m, v);\n        }\n    }\n    std::cout << r << std::endl;\n}\n", "meta": {"hexsha": "74cdaff659cb84271a6a1487af6ce826887eea8c", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/38.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/38.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/38.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": 30.7916666667, "max_line_length": 77, "alphanum_fraction": 0.5886332882, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.667463068002375}}
{"text": "#ifndef GAUSSIAN_H\n#define GAUSSIAN_H\n\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nclass Gaussian\n{\n    public:\n        Gaussian(){mean=0;sd=1;};\n        Gaussian(double m, double s);\n        Gaussian(VectorXd& data);\n        double log_likelihood(double test);\n        double likelihood(double test);\n        double getMean();\n        void setMean( double n);\n        double getSd();\n        void setSd( double n);\n    private:\n        double mean,sd;\n};\n\n\n\n#endif \n", "meta": {"hexsha": "e260d4eb2cb0ec00ec3cae9257d1743c45f27b2c", "size": 510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/likelihood/gaussian.hpp", "max_stars_repo_name": "fjorquerauribe/multitarget-tracking", "max_stars_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T20:49:10.000Z", "max_issues_repo_path": "src/likelihood/gaussian.hpp", "max_issues_repo_name": "fjorquerauribe/multitarget-tracking", "max_issues_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "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/likelihood/gaussian.hpp", "max_forks_repo_name": "fjorquerauribe/multitarget-tracking", "max_forks_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-01T07:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T05:21:04.000Z", "avg_line_length": 17.5862068966, "max_line_length": 43, "alphanum_fraction": 0.6098039216, "num_tokens": 118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.66746306792679}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass DCT\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using MatrixXd = Eigen::MatrixXd;\n\n  DCT(index maxInputSize, index maxOutputSize)\n  {\n    mTableStorage = MatrixXd::Zero(maxOutputSize, maxInputSize);\n  }\n\n  void init(index inputSize, index outputSize)\n  {\n    using namespace std;\n    assert(inputSize >= outputSize);\n    mInputSize = inputSize;\n    mOutputSize = outputSize;\n    mTable = mTableStorage.block(0, 0, mOutputSize, mInputSize);\n    mTable.setZero();\n    for (index i = 0; i < mOutputSize; i++)\n    {\n      double  scale = i == 0 ? 1.0 / sqrt(inputSize) : sqrt(2.0 / inputSize);\n      ArrayXd freqs = ((pi / inputSize) * i) *\n                      ArrayXd::LinSpaced(inputSize, 0.5, inputSize - 0.5);\n      mTable.row(i) = freqs.cos() * scale;\n    }\n  }\n\n  void processFrame(const RealVector in, RealVectorView out)\n  {\n    assert(in.size() == mInputSize);\n    ArrayXd frame = _impl::asEigen<Eigen::Array>(in);\n    ArrayXd result = (mTable * frame.matrix()).array();\n    out <<= _impl::asFluid(result);\n  }\n\n  void processFrame(Eigen::Ref<const ArrayXd> input, Eigen::Ref<ArrayXd> output)\n  {\n    output = (mTable * input.matrix()).array();\n  }\n  index    mInputSize{40};\n  index    mOutputSize{13};\n  MatrixXd mTable;\n  MatrixXd mTableStorage;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "aad0e21c10f98eb522fb039e8f510e324e527d78", "size": 1991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/DCT.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/DCT.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/DCT.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": 28.0422535211, "max_line_length": 80, "alphanum_fraction": 0.6825715721, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6674533008559915}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n\n#include <sophus/se3.hpp>\n#include <sophus/so3.hpp>\nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n/************************************************\n * \u672c\u7a0b\u5e8f\u6f14\u793a\u5982\u4f55\u7528g2o solver\u8fdb\u884c\u4f4d\u59ff\u56fe\u4f18\u5316\n * sphere.g2o\u662f\u4eba\u5de5\u751f\u6210\u7684\u4e00\u4e2aPose graph\uff0c\u6211\u4eec\u6765\u4f18\u5316\u5b83\u3002\n * \u5c3d\u7ba1\u53ef\u4ee5\u76f4\u63a5\u901a\u8fc7load\u51fd\u6570\u8bfb\u53d6\u6574\u4e2a\u56fe\uff0c\u4f46\u6211\u4eec\u8fd8\u662f\u81ea\u5df1\u6765\u5b9e\u73b0\u8bfb\u53d6\u4ee3\u7801\uff0c\u4ee5\u671f\u83b7\u5f97\u66f4\u6df1\u523b\u7684\u7406\u89e3\n * \u672c\u8282\u4f7f\u7528\u674e\u4ee3\u6570\u8868\u8fbe\u4f4d\u59ff\u56fe\uff0c\u8282\u70b9\u548c\u8fb9\u7684\u65b9\u5f0f\u4e3a\u81ea\u5b9a\u4e49\n * **********************************************/\n\ntypedef Eigen::Matrix<double,6,6> Matrix6d;\n\n// \u7ed9\u5b9a\u8bef\u5dee\u6c42J_R^{-1}\u7684\u8fd1\u4f3c\nMatrix6d JRInv( SE3 e )\n{\n    Matrix6d J;\n    J.block(0,0,3,3) = SO3::hat(e.so3().log());\n    J.block(0,3,3,3) = SO3::hat(e.translation());\n    J.block(3,0,3,3) = Eigen::Matrix3d::Zero(3,3);\n    J.block(3,3,3,3) = SO3::hat(e.so3().log());\n    J = J*0.5 + Matrix6d::Identity();\n    return J;\n}\n// \u674e\u4ee3\u6570\u9876\u70b9\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\nclass VertexSE3LieAlgebra: public g2o::BaseVertex<6, SE3>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    bool read ( istream& is )\n    {\n        double data[7];\n        for ( int i=0; i<7; i++ )\n            is>>data[i];\n        setEstimate ( SE3 (\n                Eigen::Quaterniond ( data[6],data[3], data[4], data[5] ),\n                Eigen::Vector3d ( data[0], data[1], data[2] )\n        ));\n    }\n\n    bool write ( ostream& os ) const\n    {\n        os<<id()<<\" \";\n        Eigen::Quaterniond q = _estimate.unit_quaternion();\n        os<<_estimate.translation().transpose()<<\" \";\n        os<<q.coeffs()[0]<<\" \"<<q.coeffs()[1]<<\" \"<<q.coeffs()[2]<<\" \"<<q.coeffs()[3]<<endl;\n        return true;\n    }\n    \n    virtual void setToOriginImpl()\n    {\n        _estimate = Sophus::SE3();\n    }\n    // \u5de6\u4e58\u66f4\u65b0\n    virtual void oplusImpl ( const double* update )\n    {\n        Sophus::SE3 up (\n            Sophus::SO3 ( update[3], update[4], update[5] ),\n            Eigen::Vector3d ( update[0], update[1], update[2] )\n        );\n        _estimate = up*_estimate;\n    }\n};\n\n// \u4e24\u4e2a\u674e\u4ee3\u6570\u8282\u70b9\u4e4b\u8fb9\nclass EdgeSE3LieAlgebra: public g2o::BaseBinaryEdge<6, SE3, VertexSE3LieAlgebra, VertexSE3LieAlgebra>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    bool read ( istream& is )\n    {\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        setMeasurement (\n            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            {\n                is >> information() ( i,j );\n                if ( i!=j )\n                    information() ( j,i ) =information() ( i,j );\n            }\n        return true;\n    }\n    bool write ( ostream& os ) const\n    {\n        VertexSE3LieAlgebra* v1 = static_cast<VertexSE3LieAlgebra*> (_vertices[0]);\n        VertexSE3LieAlgebra* v2 = static_cast<VertexSE3LieAlgebra*> (_vertices[1]);\n        os<<v1->id()<<\" \"<<v2->id()<<\" \";\n        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        // information matrix \n        for ( int i=0; i<information().rows(); i++ )\n            for ( int j=i; j<information().cols(); j++ )\n            {\n                os << information() ( i,j ) << \" \";\n            }\n        os<<endl;\n        return true;\n    }\n\n    // \u8bef\u5dee\u8ba1\u7b97\u4e0e\u4e66\u4e2d\u63a8\u5bfc\u4e00\u81f4\n    virtual void computeError()\n    {\n        Sophus::SE3 v1 = (static_cast<VertexSE3LieAlgebra*> (_vertices[0]))->estimate();\n        Sophus::SE3 v2 = (static_cast<VertexSE3LieAlgebra*> (_vertices[1]))->estimate();\n        _error = (_measurement.inverse()*v1.inverse()*v2).log();\n    }\n    \n    // \u96c5\u53ef\u6bd4\u8ba1\u7b97\n    virtual void linearizeOplus()\n    {\n        Sophus::SE3 v1 = (static_cast<VertexSE3LieAlgebra*> (_vertices[0]))->estimate();\n        Sophus::SE3 v2 = (static_cast<VertexSE3LieAlgebra*> (_vertices[1]))->estimate();\n        Matrix6d J = JRInv(SE3::exp(_error));\n        // \u5c1d\u8bd5\u628aJ\u8fd1\u4f3c\u4e3aI\uff1f\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    {\n        cout<<\"Usage: pose_graph_g2o_SE3_lie sphere.g2o\"<<endl;\n        return 1;\n    }\n    ifstream fin ( argv[1] );\n    if ( !fin )\n    {\n        cout<<\"file \"<<argv[1]<<\" does not exist.\"<<endl;\n        return 1;\n    }\n\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,6>> Block;  // BlockSolver\u4e3a6x6\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCholmod<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block ( linearSolver );     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    // \u8bd5\u8bd5G-N\u6216Dogleg\uff1f\n    // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton ( solver_ptr );\n    \n    g2o::SparseOptimizer optimizer;     // \u56fe\u6a21\u578b\n    optimizer.setAlgorithm ( solver );  // \u8bbe\u7f6e\u6c42\u89e3\u5668\n\n    int vertexCnt = 0, edgeCnt = 0; // \u9876\u70b9\u548c\u8fb9\u7684\u6570\u91cf\n    \n    vector<VertexSE3LieAlgebra*> vectices;\n    vector<EdgeSE3LieAlgebra*> edges;\n    while ( !fin.eof() )\n    {\n        string name;\n        fin>>name;\n        if ( name == \"VERTEX_SE3:QUAT\" )\n        {\n            // \u9876\u70b9\n            VertexSE3LieAlgebra* v = new VertexSE3LieAlgebra();\n            int index = 0;\n            fin>>index;\n            v->setId( index );\n            v->read(fin);\n            optimizer.addVertex(v);\n            vertexCnt++;\n            vectices.push_back(v);\n            if ( index==0 )\n                v->setFixed(true);\n        }\n        else if ( name==\"EDGE_SE3:QUAT\" )\n        {\n            // SE3-SE3 \u8fb9\n            EdgeSE3LieAlgebra* e = new EdgeSE3LieAlgebra();\n            int idx1, idx2;     // \u5173\u8054\u7684\u4e24\u4e2a\u9876\u70b9\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<<\"prepare optimizing ...\"<<endl;\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    cout<<\"calling optimizing ...\"<<endl;\n    optimizer.optimize(30);\n\n    cout<<\"saving optimization results ...\"<<endl;\n    // \u56e0\u4e3a\u7528\u4e86\u81ea\u5b9a\u4e49\u9876\u70b9\u4e14\u6ca1\u6709\u5411g2o\u6ce8\u518c\uff0c\u8fd9\u91cc\u4fdd\u5b58\u81ea\u5df1\u6765\u5b9e\u73b0\n    // \u4f2a\u88c5\u6210 SE3 \u9876\u70b9\u548c\u8fb9\uff0c\u8ba9 g2o_viewer \u53ef\u4ee5\u8ba4\u51fa\n    ofstream fout(\"result_lie.g2o\");\n    for ( VertexSE3LieAlgebra* v:vectices )\n    {\n        fout<<\"VERTEX_SE3:QUAT \";\n        v->write(fout);\n    }\n    for ( EdgeSE3LieAlgebra* e:edges )\n    {\n        fout<<\"EDGE_SE3:QUAT \";\n        e->write(fout);\n    }\n    fout.close();\n    return 0;\n}\n", "meta": {"hexsha": "80ee9fe6eda018a598db59c2e38657a8d99c6690", "size": 7368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_stars_repo_name": "seanleecn/learn_SLAM14", "max_stars_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_issues_repo_name": "seanleecn/learn_SLAM14", "max_issues_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_forks_repo_name": "seanleecn/learn_SLAM14", "max_forks_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_forks_repo_licenses": ["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.6223175966, "max_line_length": 112, "alphanum_fraction": 0.5571389794, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6674532887833668}}
{"text": "//  (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_Z_TEST_HPP\n#define BOOST_MATH_STATISTICS_Z_TEST_HPP\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n#include <iterator>\n#include <type_traits>\n#include <utility>\n#include <cmath>\n\nnamespace boost { namespace math { namespace statistics { namespace detail {\n\ntemplate<typename ReturnType, typename T>\nReturnType one_sample_z_test_impl(T sample_mean, T sample_variance, T sample_size, T assumed_mean)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using std::sqrt;\n    using no_promote_policy = boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false>>;\n\n    Real test_statistic = (sample_mean - assumed_mean) / (sample_variance / sqrt(sample_size));\n    auto z = boost::math::normal_distribution<Real, no_promote_policy>(sample_size - 1);\n    Real pvalue;\n    if(test_statistic > 0)\n    {\n        pvalue = 2*boost::math::cdf<Real>(z, -test_statistic);\n    }\n    else\n    {\n        pvalue = 2*boost::math::cdf<Real>(z, test_statistic);\n    }\n\n    return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType one_sample_z_test_impl(ForwardIterator begin, ForwardIterator end, typename std::iterator_traits<ForwardIterator>::value_type assumed_mean) \n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    std::pair<Real, Real> temp = mean_and_sample_variance(begin, end);\n    Real mu = std::get<0>(temp);\n    Real s_sq = std::get<1>(temp);\n    return one_sample_z_test_impl<ReturnType>(mu, s_sq, Real(std::distance(begin, end)), Real(assumed_mean));\n}\n\ntemplate<typename ReturnType, typename T>\nReturnType two_sample_z_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 std::sqrt;\n    using no_promote_policy = boost::math::policies::policy<boost::math::policies::promote_float<false>, boost::math::policies::promote_double<false>>;\n\n    Real test_statistic = (mean_1 - mean_2) / sqrt(variance_1/size_1 + variance_2/size_2);\n    auto z = boost::math::normal_distribution<Real, no_promote_policy>(size_1 + size_2 - 1);\n    Real pvalue;\n    if(test_statistic > 0)\n    {\n        pvalue = 2*boost::math::cdf<Real>(z, -test_statistic);\n    }\n    else\n    {\n        pvalue = 2*boost::math::cdf<Real>(z, test_statistic);\n    }\n\n    return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType two_sample_z_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\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\n    return two_sample_z_test_impl<ReturnType>(mean_1, variance_1, Real(n1), mean_2, variance_2, Real(n2));\n}\n\n} // detail\n\ntemplate<typename Real, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(Real sample_mean, Real sample_variance, Real sample_size, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_z_test_impl<std::pair<double, double>>(sample_mean, sample_variance, sample_size, assumed_mean);\n}\n\ntemplate<typename Real, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(Real sample_mean, Real sample_variance, Real sample_size, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_z_test_impl<std::pair<Real, Real>>(sample_mean, sample_variance, sample_size, assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_z_test_impl<std::pair<double, double>>(begin, end, assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_z_test_impl<std::pair<Real, Real>>(begin, end, assumed_mean);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type,\n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(Container const & v, Real assumed_mean) -> std::pair<double, double>\n{\n    return detail::one_sample_z_test_impl<std::pair<double, double>>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type,\n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto one_sample_z_test(Container const & v, Real assumed_mean) -> std::pair<Real, Real>\n{\n    return detail::one_sample_z_test_impl<std::pair<Real, Real>>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_z_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<double, double>\n{\n    return detail::two_sample_z_test_impl<std::pair<double, double>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_z_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair<Real, Real>\n{\n    return detail::two_sample_z_test_impl<std::pair<Real, Real>>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_z_test(Container const & u, Container const & v) -> std::pair<double, double>\n{\n    return detail::two_sample_z_test_impl<std::pair<double, double>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>\ninline auto two_sample_z_test(Container const & u, Container const & v) -> std::pair<Real, Real>\n{\n    return detail::two_sample_z_test_impl<std::pair<Real, Real>>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\n}}} // boost::math::statistics\n\n#endif // BOOST_MATH_STATISTICS_Z_TEST_HPP\n", "meta": {"hexsha": "a8ef838e40bf1d04a9a39ac4c83e7e51c753d547", "size": 7597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/z_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/z_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/z_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.8950617284, "max_line_length": 154, "alphanum_fraction": 0.7422666842, "num_tokens": 1930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6673745122571033}}
{"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):       Mathieu Carri\u00e8re\n *\n *    Copyright (C) 2018  INRIA\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"kernel\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>  // float comparison\n#include <limits>\n#include <string>\n#include <vector>\n#include <algorithm>  // std::max\n#include <gudhi/Persistence_heat_maps.h>\n#include <gudhi/common_persistence_representations.h>\n#include <gudhi/Sliced_Wasserstein.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/reader_utils.h>\n\nusing constant_scaling_function = Gudhi::Persistence_representations::constant_scaling_function;\nusing SW = Gudhi::Persistence_representations::Sliced_Wasserstein;\nusing PWG = Gudhi::Persistence_representations::Persistence_heat_maps<constant_scaling_function>;\nusing Persistence_diagram = std::vector<std::pair<double,double> >;\n\nstd::function<double(std::pair<double, double>, std::pair<double, double>)> Gaussian_function(double sigma){\n  return [=](std::pair<double, double> p, std::pair<double, double> q){\n    return (1/std::sqrt(2*Gudhi::Persistence_representations::pi)*sigma) * std::exp(  -( (p.first-q.first)*(p.first-q.first) + (p.second-q.second)*(p.second-q.second) )/(2*sigma)  );\n  };\n}\n\nBOOST_AUTO_TEST_CASE(check_PWG) {\n  Persistence_diagram v1, v2; v1.emplace_back(0,1); v2.emplace_back(0,2);\n  PWG pwg1(v1, Gaussian_function(1.0));\n  PWG pwg2(v2, Gaussian_function(1.0));\n  BOOST_CHECK(std::abs(pwg1.compute_scalar_product(pwg2) - std::exp(-0.5)/(std::sqrt(2*Gudhi::Persistence_representations::pi))) <= 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(check_SW) {\n  Persistence_diagram v1, v2; v1.emplace_back(0,1); v2.emplace_back(0,2);\n  SW sw1(v1, 1.0, 100); SW swex1(v1, 1.0, -1);\n  SW sw2(v2, 1.0, 100); SW swex2(v2, 1.0, -1);\n  BOOST_CHECK(std::abs(sw1.compute_scalar_product(sw2) - swex1.compute_scalar_product(swex2)) <= 1e-1);\n}\n", "meta": {"hexsha": "63089538e6b9b428b9e2df8b5c95eefce86b1264", "size": 2128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistence_representations/test/kernels.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Persistence_representations/test/kernels.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Persistence_representations/test/kernels.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 42.56, "max_line_length": 182, "alphanum_fraction": 0.7283834586, "num_tokens": 637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6673745027697743}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, log1m) {\n  EXPECT_FLOAT_EQ(stan::math::log1p(-0.1),stan::math::log1m(0.1));\n}\n\nTEST(MathFunctions, log1mOverflow) {\n    EXPECT_EQ(-std::numeric_limits<double>::infinity(),\n              stan::math::log1m(1.0));\n    EXPECT_EQ(-std::numeric_limits<double>::infinity(),\n              stan::math::log1m(1));\n\n}\n\nTEST(MathFunctions, log1m_exception) {\n  EXPECT_THROW(stan::math::log1m(10.0), std::domain_error);\n}\n\n\nTEST(MathFunctions, log1m_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log1m(nan));\n}\n", "meta": {"hexsha": "44969fb788dae0607bd867d6bdf3bd107c3e54e3", "size": 722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log1m_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7407407407, "max_line_length": 66, "alphanum_fraction": 0.6731301939, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6673744930206305}}
{"text": "\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace ilqr\n{\n\n// Helper class to store the terms of the quadratic value function.\nclass QuadraticValue \n{\npublic:\n    // Inititalizes the Value function terms V_, G_, W_ to zeros.\n    QuadraticValue(const int state_dim);\n\n    Eigen::MatrixXd& V() { return V_; }\n    Eigen::MatrixXd& G() { return G_; }\n    double& W() { return W_; }\n\n    const Eigen::MatrixXd& V() const { return V_; }\n    const Eigen::MatrixXd& G() const { return G_; }\n    const double& W() const { return W_; }\n\nprivate:\n    // Quadratic term [dim(x)] x [dim(x)]\n    Eigen::MatrixXd V_;\n    // Linear term [1] x [dim(x)]\n    Eigen::MatrixXd G_;\n    // Constant term [1] x [1]\n    double W_;\n};\n\n// Dynamics Function Prototype. Takes state, control and returns the next state.\nusing DynamicsFunc = std::function<Eigen::VectorXd(const Eigen::VectorXd&,const Eigen::VectorXd&)>; \n\n// Cost Function Prototype. Takes state, control and returns a real-valued cost.\nusing CostFunc = std::function<double(const Eigen::VectorXd&,const Eigen::VectorXd&)>; \n\n// Linearized dynamics parameters in terms of the state [x].\nstruct Dynamics\n{\n    // Linear dynamics matrix. [dim(x)] x [dim(x)]\n    // (extension is last row is [\\vec{0}, 1])\n    Eigen::MatrixXd A;\n\n    // Controls matrix. [dim(x)] x [dim(u)]\n    // (extension is last row is [\\vec{0}])\n    Eigen::MatrixXd B;\n};\n\n// Quadratic cost parameters in terms of the state x and control u.\nstruct Cost \n{\n    // Quadratic state-cost matrix. [dim(x)] x [dim(x)]\n    Eigen::MatrixXd Q;\n\n    // Cost cross-term matrix. [dim(x)] x [dim(u)]\n    Eigen::MatrixXd P;\n\n    // Quadratic control-cost matrix. [dim(u)] x [dim(u)]\n    Eigen::MatrixXd R;\n\n    // Linear control-cost  matrix. [dim(u)] x [1]\n    Eigen::VectorXd g_u;\n\n    // Linear control-cost matrix. [dim(x)] x [1]\n    Eigen::VectorXd g_x;\n\n    // Constant offset term\n    double c;\n};\n\n\nilqr::Dynamics linearize_dynamics(const DynamicsFunc &dynamics_func, \n                        const Eigen::VectorXd &x, \n                        const Eigen::VectorXd &u);\n\nilqr::Cost quadraticize_cost(const CostFunc &cost_func, \n                        const Eigen::VectorXd &x, \n                        const Eigen::VectorXd &u);\n\n} // namespace ilqr\n\n", "meta": {"hexsha": "279055be4794c64372b5b1d9786c410ac7f02ccf", "size": 2251, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 26.7976190476, "max_line_length": 100, "alphanum_fraction": 0.6268325189, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6673437821496067}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Deliberately contains some unicode characters:\n// \n// boost-no-inspect\n//\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/centered_continued_fraction.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n\nusing boost::math::constants::root_two;\nusing boost::math::constants::phi;\nusing boost::math::constants::pi;\nusing boost::math::constants::e;\nusing boost::math::constants::zeta_three;\nusing boost::math::tools::centered_continued_fraction;\nusing boost::multiprecision::mpfr_float;\n\nint main()\n{\n    using Real = mpfr_float;\n    int p = 10000;\n    mpfr_float::default_precision(p);\n    auto phi_cfrac = centered_continued_fraction(phi<Real>());\n    std::cout << \"\u03c6 \u2248 \" << phi_cfrac << \"\\n\";\n    std::cout << \"Khinchin mean: \" << std::setprecision(10) << phi_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n    auto pi_cfrac = centered_continued_fraction(pi<Real>());\n    std::cout << \"\u03c0 \u2248 \" << pi_cfrac << \"\\n\";\n    std::cout << \"Khinchin mean: \" << std::setprecision(10) << pi_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n    auto rt_cfrac = centered_continued_fraction(root_two<Real>());\n    std::cout << \"\u221a2 \u2248 \" << rt_cfrac << \"\\n\";\n    std::cout << \"Khinchin mean: \" << std::setprecision(10) <<  rt_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n    auto e_cfrac = centered_continued_fraction(e<Real>());\n    std::cout << \"e \u2248 \" << e_cfrac << \"\\n\";\n    std::cout << \"Khinchin mean: \" << std::setprecision(10) <<  e_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n    auto z_cfrac = centered_continued_fraction(zeta_three<Real>());\n    std::cout << \"\u03b6(3) \u2248 \" << z_cfrac << \"\\n\";\n    std::cout << \"Khinchin mean: \" << std::setprecision(10) <<  z_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n\n    // http://jeremiebourdon.free.fr/data/Khintchine.pdf\n    std::cout << \"The expected Khinchin mean for a random centered continued fraction is 5.45451724454\\n\";\n}\n", "meta": {"hexsha": "6d357d2b913531339b6d2c137d858e86535e3c29", "size": 2132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/centered_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/centered_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/centered_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": 41.0, "max_line_length": 111, "alphanum_fraction": 0.6735459662, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6673437771408034}}
{"text": "/**\n * @file finitevolumesineconslaw_main.cc\n * @brief NPDE homework \"FiniteVolumeSineConsLaw\" code\n * @author Oliver Rietmann\n * @date 25.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <fstream>\n#include <iostream>\n\n#include \"finitevolumesineconslaw.h\"\n\nusing namespace FiniteVolumeSineConsLaw;\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  /* SAM_LISTING_BEGIN_1 */\n  unsigned int N = 600;\n  unsigned int M = 200;\n  double h = 12.0 / N;\n  Eigen::VectorXd x =\n      Eigen::VectorXd::LinSpaced(N, -6.0 + 0.5 * h, 6.0 - 0.5 * h);\n\n  std::ofstream file;\n\n  // without reaction term\n  Eigen::VectorXd ufinal = solveSineConsLaw(&sineClawRhs, N, M);\n#if SOLUTION\n  file.open(\"ufinal.csv\");\n  file << x.transpose().format(CSVFormat) << std::endl;\n  file << ufinal.transpose().format(CSVFormat) << std::endl;\n  file.close();\n\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/ufinal.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n              \"/ufinal.csv \" CURRENT_BINARY_DIR \"/ufinal.eps\");\n#else\n  //====================\n  // Your code goes here\n  // Use std::ofstream to write the solution to\n  // the file \"ufinal.csv\". To plot this\n  // file you may uncomment the following line:\n  // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n  // \"/ufinal.csv \" CURRENT_BINARY_DIR \"/ufinal.eps\");\n  //====================\n#endif\n  /* SAM_LISTING_END_1 */\n\n  // with reaction term: -c * u(x, t), where c = 1.0\n  double c = 1.0;\n  auto bind_c = [c](const Eigen::VectorXd &mu) {\n    return sineClawReactionRhs(mu, c);\n  };\n  Eigen::VectorXd ufinal_reaction = solveSineConsLaw(bind_c, N, M);\n#if SOLUTION\n  file.open(\"ufinal_reaction.csv\");\n  file << x.transpose().format(CSVFormat) << std::endl;\n  file << ufinal_reaction.transpose().format(CSVFormat) << std::endl;\n  file.close();\n\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/ufinal_reaction.csv\"\n            << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n              \"/ufinal_reaction.csv \" CURRENT_BINARY_DIR\n              \"/ufinal_reaction.eps\");\n#else\n  //====================\n  // Your code goes here\n  // Use std::ofstream to write the solution to\n  // the file \"ufinal_reaction.csv\". To plot this\n  // file you may uncomment the following line:\n  // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n  // \"/ufinal_reaction.csv \" CURRENT_BINARY_DIR \"/ufinal_reaction.eps\");\n  //====================\n#endif\n\n  // Finding the optimal timestep (no reaction term)\n  unsigned int M_small = findTimesteps();\n  std::cout\n      << \"The smallest number of timesteps keeping the solution in [0, 2] is \"\n      << M_small << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "0f3be7fac6aba699b3abf462e6027cffcf53b8a7", "size": 2868, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_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/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_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/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_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": 32.2247191011, "max_line_length": 78, "alphanum_fraction": 0.6440027894, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6672363465427404}}
{"text": "#ifndef QUAD_TANH_SINH_RULE_HPP\n#define QUAD_TANH_SINH_RULE_HPP\n\n#include <tuple>\n\n#include <Eigen/Core>\n\n#include <mxpfit/math/constants.hpp>\n\nnamespace quad\n{\n\n//==============================================================================\n// Double exponential formula for numerical integration\n//==============================================================================\n\n///\n/// ### DESinhTanhRule\n///\n/// \\brief Double exponential quadrature for finite interval [-1, 1]\n/// \\tparam T the scalar type for quadrature nodes and weights\n///\n/// This class computes nodes and weights of the sinh-tanh quadrature rule which\n/// can efficiently compute the integral over the finite interval. ///\n///\n/// \\f[\n///   I = \\int_{-1}^{1}f(x) dx \\approx \\sum_{k=N_{-}}^{N_{+}} w_{k} f(x_k)\n/// \\f]\n///\n/// This sinh-tanh rule is obtained by applying the change of variable in the\n/// form\n///\n/// \\f[\n///   x = \\phi(t)\n///     = \\tanh\\left(\\frac{\\pi}{2}\\sinh(t)\\right) ,\\quad t \\in (-\\infty,\\infty).\n/// \\f]\n///\n/// and discretizing the integral over \\f$ t \\f$ by the trapezoidal rule of the\n/// step width \\f$h\\f$. The integration nodes and weighs are given as\n///\n/// \\f[\n///   x_k = \\tanh\\left(\\frac{\\pi}{2}\\sinh(kh)\\right), \\\\\n///   w_k =\n///   \\frac{\\frac{1}{2}h\\pi\\cosh(kh)}{\\cosh^\\left(\\frac{1}{2}\\pi\\sinh(kh)\\right)}.\n/// \\f]\n///\ntemplate <typename T>\nclass DESinhTanhRule\n{\npublic:\n    constexpr static const T alpha = math::constant<T>::pi / 2;\n\n    using Scalar    = T;\n    using ArrayType = Eigen::Array<T, Eigen::Dynamic, 1>;\n    using Index     = Eigen::Index;\n\nprivate:\n    ArrayType m_node;            // nodes\n    ArrayType m_weight;          // weights\n    ArrayType m_dist_from_lower; // distance of nodes from lower bound\n    ArrayType m_dist_from_upper; // distance of nodes from upper bound\n    ArrayType m_adj_diff;        // adjacent difference of nodes\npublic:\n    /// Default constructor\n    DESinhTanhRule() = default;\n    /// Copy constructor\n    DESinhTanhRule(const DESinhTanhRule&) = default;\n    /// Move constructor\n    DESinhTanhRule(DESinhTanhRule&&) = default;\n    /// Destructor\n    ~DESinhTanhRule() = default;\n\n    /// Copy assignment operator\n    DESinhTanhRule& operator=(const DESinhTanhRule&) = default;\n    /// Move assignment operator\n    DESinhTanhRule& operator=(DESinhTanhRule&&) = default;\n\n    ///\n    /// Construst `n`-points quadrature rule\n    ///\n    /// \\param[in] n  number of integration points\n    /// \\param[in] tiny A threshold value that the integration weights can be\n    ///    negligibly small. If the integrand is a regular function at\n    ///    boundaries,\n    ///\n    /// \\pre `n > 2` is required\n    ///\n    explicit DESinhTanhRule(Index n, T tiny)\n    {\n        compute(n, tiny);\n    }\n\n    ///\n    /// \\return number of integration points.\n    ///\n    Index size() const\n    {\n        return m_node.size();\n    }\n    ///\n    /// \\return const reference to the vector of integration points.\n    ///\n    const ArrayType& x() const\n    {\n        return m_node;\n    }\n\n    ///\n    /// Get a node\n    ///\n    /// \\param[in] i  index of integration point. `i < size()` required.\n    /// \\return `i`-th integration point.\n    ///\n    Scalar x(Index i) const\n    {\n        assert(i < size());\n        return m_node[i];\n    }\n    ///\n    /// \\return const reference to the vector of integration weights.\n    ///\n    const ArrayType& w() const\n    {\n        return m_weight;\n    }\n\n    ///\n    /// Get a weight\n    ///\n    /// \\parma[in] i  index of integration point. `i < size()` required.\n    /// \\return `i`-th integration weight.\n    ///\n    Scalar w(Index i) const\n    {\n        assert(i < size());\n        return m_weight[i];\n    }\n    ///\n    /// Get the distance of node from lower bound, \\f$ x + 1, \\f$ where \\f$ x\n    /// \\in [-1,1].\\f$\n    ///\n    Scalar distanceFromLower(Index i) const\n    {\n        assert(i < size());\n        return m_dist_from_lower[i];\n    }\n    ///\n    /// Get the distance of node from upper bound, \\f$ 1 - x, \\f $where \\f$ x\n    /// \\in [-1,1].\\f$\n    ///\n    Scalar distanceFromUpper(Index i) const\n    {\n        assert(i < size());\n        return m_dist_from_upper[i];\n    }\n    ///\n    /// Get the adjacent difference of nodes.\n    ///\n    /// \\param[in] i index of nodes\n    ///\n    /// \\return `x(0)` for `i=0`, `x(i)-x(i-1)` for `i=1,2,...,size()-1.`\n    ///\n    Scalar adjacentDifference(Index i) const\n    {\n        assert(i < size());\n        return m_adj_diff[i];\n    }\n\n    ///\n    /// Compute nodes and weights of the \\c n point Gauss-Legendre\n    /// quadrature rule. Nodes are located in the interval [-1,1].\n    ///\n    /// \\param[in] n  number of integration points\n    /// \\param[in] tiny A threshold value that the integration weights can be\n    ///    negligibly small. If the integrand is a regular function at\n    ///    boundaries,\n    ///\n    /// \\pre `n > 2` is required\n    ///\n    void compute(Index n, T tiny)\n    {\n        using Eigen::numext::log;\n        assert(T() < tiny && tiny < T(1));\n\n        resize(n);\n\n        const auto t_bound =\n            log(log(T(2) / (alpha * tiny) * log(T(2) / tiny)) / alpha);\n        const auto h     = T(2) * t_bound / (n - 1);\n        const auto w_pre = h * alpha;\n\n        const auto sh_half = std::sinh(h / T(2));\n        const auto ch_half = std::cosh(h / T(2));\n\n        T di_pre;\n\n        {\n            const auto u0        = alpha * std::sinh(-t_bound);\n            const auto d0        = std::cosh(u0);\n            m_node[0]            = std::tanh(u0);\n            m_weight[0]          = w_pre * std::cosh(-t_bound) / (d0 * d0);\n            m_dist_from_lower[0] = std::exp(u0) / d0;\n            m_dist_from_upper[0] = std::exp(-u0) / d0;\n            m_adj_diff[0]        = m_node[0];\n\n            di_pre = d0;\n        }\n\n        for (Index i = 1; i < n; ++i)\n        {\n            const auto ti = -t_bound + T(i) * h;\n            const auto si = alpha * std::sinh(ti);\n            const auto ci = alpha * std::cosh(ti);\n            const auto di = std::cosh(si);\n\n            m_node[i]            = std::tanh(si);\n            m_weight[i]          = w_pre * std::cosh(ti) / (di * di);\n            m_dist_from_lower[i] = std::exp(si) / di;\n            m_dist_from_upper[i] = std::exp(-si) / di;\n            // alpha * (sinh(t[i]) - sinh(t[i-1]))\n            const auto ui_diff = T(2) * sh_half * (ci * ch_half - si * sh_half);\n            m_adj_diff[i]      = std::sinh(ui_diff) / (di * di_pre);\n            di_pre             = di;\n        }\n\n        return;\n    }\n\n    ///\n    /// Inverse of variable transformation\n    ///\n    /// \\return \\f$ t = \\phi^{-1}(x) \\f$\n    ///\n    static T inverse(T x)\n    {\n        return std::asinh(std::atanh(x) / alpha);\n    }\n\nprivate:\n    void resize(Index n)\n    {\n        m_node.resize(n);\n        m_weight.resize(n);\n        m_dist_from_lower.resize(n);\n        m_dist_from_upper.resize(n);\n        m_adj_diff.resize(n);\n    }\n};\n\n} // namespace: quad\n\n#endif /* QUAD_TANH_SINH_RULE_HPP */\n", "meta": {"hexsha": "d50f6164dcf8e797b9f733a3fcf3e04de10e5564", "size": 7000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["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.6679841897, "max_line_length": 82, "alphanum_fraction": 0.5298571429, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6671890198345725}}
{"text": "/*\n * oper_matrix.cpp\n *\n *  Created on: 2017. 6. 6.\n *      Author: cho\n */\n\n#include <random>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/// number of data\nconst unsigned int N = 30;\nconst int order = 3; // 3 means second order polynomial\n\n// return polynomial value\n// ex, return y = a0 + a1*x + a2*x^2\ndouble polyval( const ublas::vector<double>& a, const double x ) {\n\tublas::vector<double> tmp(a);\n\n\tfor ( unsigned i = 1; i < a.size(); ++i ) {\n\t\tfor ( unsigned j = i; j < a.size(); ++j )\n\t\t\ttmp(j) *= x;\n\t}\n\n\treturn ublas::sum( tmp );\n}\n\nint main() {\n\trandom_device rd;     // seed, rd()\n\tmt19937_64 gen(rd());    // random number generator\n\n\tublas::vector<double> t (N); // time vector, sec\n\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = (i+1);\n\t//cout << \"t(\"<<N<<\") = \" << t << endl;\n\n\t//uniform_int_distribution<int> dis_y( -10, 10 );\n\tnormal_distribution<float> dis_y( 0, 10 );\n\tublas::vector<double> y (N); // measured value\n\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\t//cout << \"y(\"<<N<<\") = \" << y << endl;\n\n\tublas::matrix<double> X(N, order);                 // X = Vandermonde matrix\n\tublas::column(X, 0) = ublas::vector<double>(N, 1); // 0 column = t^0, all one\n\tublas::column(X, 1) = t;                           // 1 column = t^1, t itself\n\tfor ( unsigned j = 2; j<order; ++ j ) {\n\t\tublas::column(X, j) = element_prod(t, ublas::column(X, j-1));\n\t}\n\n\tublas::matrix<double> M = prod( trans(X), X );\n\n\tcout << endl;\n\tublas::permutation_matrix<double> pm(M.size1());\n\tublas::matrix<double> LU( M );                          // LU <- M\n\tbool singular = ublas::lu_factorize( LU, pm);           // LU <- LU\n\tif ( singular ) {\n\t\tcout << \"ERROR!!! \" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t// continuous value y\n\tcout << \"y, lowpass, polyval t\" << endl;\n\tfor ( unsigned i = 0; i < 200; ++i ) {\n\t\t// generate y\n\t\tfor (unsigned i = 1; i < y.size(); ++i) y(i-1) = y(i); // left shift\n\t\ty(y.size()-1) += dis_y(gen);                           // append 1 element\n\n\t\t// backup y\n\t\tdouble bakup_y = y(y.size()-1);\n\t\tif ( i == 100 ) y(y.size()-1) = 0;\n\n\t\t// y\n\t\tcout << y(N-1);\n\t\tstatic double lpv = y(N-1);\n\n\t\t// low-pass filter, alpha = 0.5\n\t\tlpv = lpv/2 + y(N-1)/2;\n\t\tcout << \",\" << lpv;\n\n\t\t// polyval t\n\t\tublas::vector<double> tmp_y( y );\n\t\tublas::vector<double> a( prod( trans(X), tmp_y ) );\n\t\tublas::lu_substitute( LU, pm, a );\n\t\tcout << \",\" << polyval(a, t(N-1));\n\n\t\t// restore\n\t\ty(y.size()-1) = bakup_y;\n\n\t\tcout << endl;\n\t}\n}\n", "meta": {"hexsha": "086bc1ffc5b55c2154e2e54baef4091f96c5f1d0", "size": 2726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_ublas/smoothing.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/smoothing.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/smoothing.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": 27.5353535354, "max_line_length": 79, "alphanum_fraction": 0.5623624358, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6671890027989895}}
{"text": "/*\n * Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)\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\n#include <ros/ros.h>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n#include <cob_twist_controller/inverse_jacobian_calculations/inverse_jacobian_calculation.h>\n\n/**\n * Calculates the pseudoinverse of the Jacobian by using SVD technique.\n * This allows to get information about singular values and evaluate them.\n */\nEigen::MatrixXd PInvBySVD::calculate(const Eigen::MatrixXd& jacobian) const\n{\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double eps_truncation = DIV0_SAFE;  // prevent division by 0.0\n    Eigen::VectorXd singularValues = svd.singularValues();\n    Eigen::VectorXd singularValuesInv = Eigen::VectorXd::Zero(singularValues.rows());\n\n    // small change to ref: here quadratic damping due to Control of Redundant Robot Manipulators : R.V. Patel, 2005, Springer [Page 13-14]\n    for (uint32_t i = 0; i < singularValues.rows(); ++i)\n    {\n        double denominator = singularValues(i) * singularValues(i);\n        // singularValuesInv(i) = (denominator < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n        singularValuesInv(i) = (singularValues(i) < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n    }\n    Eigen::MatrixXd result = svd.matrixV() * singularValuesInv.asDiagonal() * svd.matrixU().transpose();\n\n    return result;\n}\n\n/**\n * Calculates the pseudoinverse of the Jacobian by using SVD technique.\n * This allows to get information about singular values and evaluate them.\n */\nEigen::MatrixXd PInvBySVD::calculate(const TwistControllerParams& params,\n                                     boost::shared_ptr<DampingBase> db,\n                                     const Eigen::MatrixXd& jacobian) const\n{\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    double eps_truncation = params.eps_truncation;\n    Eigen::VectorXd singularValues = svd.singularValues();\n    Eigen::VectorXd singularValuesInv = Eigen::VectorXd::Zero(singularValues.rows());\n    Eigen::MatrixXd lambda = db->getDampingFactor(singularValues, jacobian);\n\n    if (params.numerical_filtering)\n    {\n        // Formula 20 Singularity-robust Task-priority Redundandancy Resolution\n        // Sum part\n        for (uint32_t i = 0; i < singularValues.rows()-1; ++i)\n        {\n            // pow(beta, 2) << pow(lambda, 2)\n            singularValuesInv(i) = singularValues(i) / (pow(singularValues(i), 2) + pow(params.beta, 2));\n        }\n        // Formula 20 - additional part - numerical filtering for least singular value m\n        uint32_t m = singularValues.rows()-1;\n        singularValuesInv(m) = singularValues(m) / (pow(singularValues(m), 2) + pow(params.beta, 2) + lambda(m, m));\n    }\n    else\n    {\n        // small change to ref: here quadratic damping due to Control of Redundant Robot Manipulators : R.V. Patel, 2005, Springer [Page 13-14]\n        for (uint32_t i = 0; i < singularValues.rows(); ++i)\n        {\n            double denominator = (singularValues(i) * singularValues(i) + lambda(i, i) );\n            // singularValuesInv(i) = (denominator < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n            singularValuesInv(i) = (singularValues(i) < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n        }\n\n        //// Formula from Advanced Robotics : Redundancy and Optimization : Nakamura, Yoshihiko, 1991, Addison-Wesley Pub. Co [Page 258-260]\n        // for(uint32_t i = 0; i < singularValues.rows(); ++i)\n        // {\n        //       // damping is disabled due to damping factor lower than a const. limit\n        //       singularValues(i) = (singularValues(i) < eps_truncation) ? 0.0 : 1.0 / singularValues(i);\n        // }\n    }\n\n    Eigen::MatrixXd result = svd.matrixV() * singularValuesInv.asDiagonal() * svd.matrixU().transpose();\n\n    return result;\n}\n\n/**\n * Calculates the pseudoinverse by means of left/right pseudo inverse respectively.\n */\nEigen::MatrixXd PInvDirect::calculate(const Eigen::MatrixXd& jacobian) const\n{\n    Eigen::MatrixXd result;\n    Eigen::MatrixXd jac_t = jacobian.transpose();\n    uint32_t rows = jacobian.rows();\n    uint32_t cols = jacobian.cols();\n\n    if (cols >= rows)\n    {\n        result = jac_t * (jacobian * jac_t).inverse();\n    }\n    else\n    {\n        result = (jac_t * jacobian).inverse() * jac_t;\n    }\n\n    return result;\n}\n\n/**\n * Calculates the pseudoinverse by means of left/right pseudo inverse respectively.\n */\nEigen::MatrixXd PInvDirect::calculate(const TwistControllerParams& params,\n                                      boost::shared_ptr<DampingBase> db,\n                                      const Eigen::MatrixXd& jacobian) const\n{\n    Eigen::MatrixXd result;\n    Eigen::MatrixXd jac_t = jacobian.transpose();\n    uint32_t rows = jacobian.rows();\n    uint32_t cols = jacobian.cols();\n    if (params.damping_method == LEAST_SINGULAR_VALUE)\n    {\n        ROS_ERROR(\"PInvDirect does not support SVD. Use PInvBySVD class instead!\");\n    }\n\n    Eigen::MatrixXd lambda = db->getDampingFactor(Eigen::VectorXd::Zero(1, 1), jacobian);\n    if (cols >= rows)\n    {\n        Eigen::MatrixXd ident = Eigen::MatrixXd::Identity(rows, rows);\n        Eigen::MatrixXd temp = jacobian * jac_t + lambda * ident;\n        result = jac_t * temp.inverse();\n    }\n    else\n    {\n        Eigen::MatrixXd ident = Eigen::MatrixXd::Identity(cols, cols);\n        Eigen::MatrixXd temp = jac_t * jacobian + lambda * ident;\n        result = temp.inverse() * jac_t;\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "656c4027b0af49684bd5d95f7345f2d8eabf9097", "size": 6130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_stars_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_stars_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_stars_repo_licenses": ["MIT"], "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/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_issues_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_issues_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_issues_repo_licenses": ["MIT"], "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/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_forks_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_forks_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T17:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:31:42.000Z", "avg_line_length": 40.5960264901, "max_line_length": 143, "alphanum_fraction": 0.6610114192, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6671889956252622}}
{"text": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <Eigen/Eigen>\n\nint binomial(int n, int k) {\n//    if (c < 0)\n//        std::cout << \"c: \" << c << std::endl;\n//    if (n < 0)\n//        std::cout << \"n: \" << n << std::endl;\n    if (k > n)\n        return 0;\n    if (k == 0 || k == n)\n        return 1;\n    return binomial(n-1, k-1) + binomial(n-1, k);\n}\n\nint factorial(int n) {\n    assert(n >= 0);\n    return (n == 1 || n == 0) ? 1 : factorial(n-1) * n;\n}\n\ndouble k_pfac(double pfac, int n, int l, int m, double alpha,\n         double beta, double gamma) {\n    if (pfac == 0.0)\n        return 0;\n    double sum_term = 0.0;\n    //std::cout << \"n,l,m: \" << n << \",\" << l << \",\" << m << std::endl;\n    //std::cout << \"alpha: \" << alpha << \" beta: \" << beta << \" gamma: \" << gamma << std::endl;\n    for (std::size_t a = 0; a != (n+2); ++a) {\n        for (std::size_t b = 0; b != (l+2); ++b) {\n            for (std::size_t c = 0; c != (m+2); ++c) {\n                double sum_term_part = binomial(l + 1 - b + a, a) *\n                            binomial(m + 1 - c + b, b) * binomial(n + 1 - a + c, c)\n                            / (pow((alpha + beta)*2, l - b + a + 2)\n                               * pow((alpha + gamma)*2, n - a + c + 2)\n                               * pow((beta + gamma)*2, m - c + b + 2));\n                //std::cout << \"a,b,c: \" << a << \",\" << b << \",\" << c << \" sum term contrib: \" << sum_term_part << std::endl;\n                sum_term += sum_term_part;\n            }\n        }\n    }\n\n    return pfac * 16.0 * M_PI * M_PI * factorial(n+1) * factorial(l+1) * factorial(m+1) * sum_term;\n}\n\ndouble k(int n, int l, int m, double alpha,\n        double beta, double gamma) {\n    \n    double sum_term = 0.0;\n    for (std::size_t a = 0; a != n+2; ++a) {\n        for (std::size_t b = 0; b != l+2; ++b) {\n            for (std::size_t c = 0; c != m+2; ++c) {\n                sum_term += binomial(l + 1 - b + a, a) * \n                    binomial(m + 1 - c + b, b) * binomial(n + 1 - a + c, c) \n                    / (pow((alpha + beta)*2, l - b + a + 2)\n                    * pow((alpha + gamma)*2, n - a + c + 2)\n                    * pow((beta + gamma)*2, m - c + b + 2));\n            }\n        }\n    }\n\n    return 16.0 * M_PI * M_PI * factorial(n+1) * factorial(l+1) * factorial(m+1) * sum_term;\n}\n\ndouble s(int ni, int li, int mi, int nj,\n        int lj, int mj, double alpha, double beta, double gamma) {\n    //std::cout << \"ni: \" << ni << \" nj: \" << nj << \" li: \" << li << \" lj: \" << lj << \" mi: \" <<\n    //mi << \" mj: \" << mj << std::endl;\n    //std::cout << \"alpha: \" << alpha << \" beta: \" << beta << \" gamma: \" << gamma << std::endl;\n    return k_pfac(1, ni + nj, li + lj, mi + mj, alpha, beta, gamma);\n}\n\ndouble v_ne(int ni, int li, int mi, int nj,\n        int lj, int mj, double alpha, double beta, double gamma,\n        int z) {\n    return -z * (k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n        + k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma));\n}\n\ndouble v_ee(int ni, int li, int mi, int nj,\n        int lj, int mj, double alpha, double beta, double gamma) {\n    return k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma);\n}\n\ndouble t_e(int ni, int li, int mi, int nj,\n           int lj, int mj, double alpha, double beta, double gamma) {\n    return -((alpha*2.0) * (alpha*2.0) + (beta*2.0) * (beta*2.0) + 2.0 * (gamma*2.0) * (gamma*2.0)) * s(ni, li, mi, nj, lj, mj, alpha, beta, gamma) / 8.0\n        + (nj * (alpha*2.0) / 2.0) * k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n        + (lj * (beta*2.0) / 2.0) * k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n        + (mj * (gamma*2.0)) * k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n//        - (nj * (nj - 1) / 2) * k(ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n        - k_pfac((nj * (nj - 1) / 2.0), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n//        - (lj * (lj - 1) / 2) * k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n        - k_pfac((lj * (lj - 1) / 2.0), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n//\n        - k_pfac((mj * (mj - 1)), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n        + ((alpha*2.0) / 2.0) * k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n        + ((beta*2.0) / 2.0) * k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n        + ((gamma*2.0)) * k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n//        - (nj) * k(ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n        - k_pfac((nj), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n//        - (lj) * k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n        - k_pfac((lj), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n//        - (2 * mj) * k(ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n        - k_pfac((2.0 * mj), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n        - ((alpha*2.0) * (gamma*2.0) / 8.0) * (k(ni + nj - 1, li + lj, mi + mj + 1, alpha, beta, gamma)\n            + k(ni + nj + 1, li + lj, mi + mj - 1, alpha, beta, gamma)\n            - k(ni + nj - 1, li + lj + 2, mi + mj - 1, alpha, beta, gamma))\n        - ((beta*2.0) * (gamma*2.0) / 8.0) * (k(ni + nj, li + lj - 1, mi + mj + 1, alpha, beta, gamma)\n            + k(ni + nj, li + lj + 1, mi + mj - 1, alpha, beta, gamma)\n            - k(ni + nj + 2, li + lj - 1, mi + mj - 1, alpha, beta, gamma))\n//        + (nj * gamma / 4) * (k(ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma))\n        + (k_pfac((nj * (gamma*2.0) / 4.0), ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma)\n            + k_pfac((nj * (gamma*2.0) / 4.0), ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n            - k_pfac((nj * (gamma*2.0) / 4.0), ni + nj - 2, li + lj + 2, mi + mj - 1, alpha, beta, gamma))\n//        + (mj * alpha / 4) * (k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n        + (k_pfac((mj * (alpha*2.0) / 4.0), ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n            + k_pfac((mj * (alpha*2.0) / 4.0), ni + nj + 1, li + lj, mi + mj - 2, alpha, beta, gamma)\n            - k_pfac((mj * (alpha*2.0) / 4.0), ni + nj - 1, li + lj + 2, mi + mj - 2, alpha, beta, gamma))\n//        - (nj * mj / 2) * (k(ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma)\n        - (k_pfac((nj * mj / 2.0), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n            + k_pfac((nj * mj / 2.0), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n            - k_pfac((nj * mj / 2.0), ni + nj - 2, li + lj + 2, mi + mj - 2, alpha, beta, gamma))\n//        + (lj * gamma / 4) * (k(ni + nj, li + lj - 2, mi + mj + 1, alpha, beta, gamma)\n        + (k_pfac((lj * (gamma*2.0) / 4.0), ni + nj, li + lj - 2, mi + mj + 1, alpha, beta, gamma)\n            + k_pfac((lj * (gamma*2.0) / 4.0), ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n            - k_pfac((lj * (gamma*2.0) / 4.0), ni + nj + 2, li + lj - 2, mi + mj - 1, alpha, beta, gamma))\n//        + (mj * beta / 4) * (k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n        + (k_pfac((mj * (beta*2.0) / 4.0), ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n            + k_pfac((mj * (beta*2.0) / 4.0), ni + nj, li + lj + 1, mi + mj - 2, alpha, beta, gamma)\n            - k_pfac((mj * (beta*2.0) / 4.0), ni + nj + 2, li + lj - 1, mi + mj - 2, alpha, beta, gamma))\n//        - (lj * mj / 2) * (k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n        - (k_pfac((lj * mj / 2.0), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n            + k_pfac((lj * mj / 2.0), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n            - k_pfac((lj * mj / 2.0), ni + nj + 2, li + lj - 2, mi + mj - 2, alpha, beta, gamma));\n}\n\nEigen::MatrixXd s_matrix_builder(std::vector<std::pair<std::vector<int>, std::vector<double> > > basis) {\n    Eigen::MatrixXd result;\n    result.setZero(basis.size(), basis.size());\n    for (std::size_t i = 0; i != basis.size(); ++i) {\n        for (std::size_t j = 0; j != basis.size(); ++j) {\n            //std::vector<int> q_nos_i, q_nos_j;\n            //std::vector<double> exp_i, exp_j;\n            //auto [q_nos_i, exp_i] = basis[i];\n            //auto [q_nos_j, exp_j] = basis[j];\n            std::vector<int> q_nos_i = basis[i].first;\n            std::vector<double> exp_i = basis[i].second;\n            std::vector<int> q_nos_j = basis[j].first;\n            //std::cout << \"S(\" << i << \",\" << j << \") = s(\" << q_nos_i[0] << \",\" <<  q_nos_i[1] << \",\" << q_nos_i[2] << \",\" << q_nos_j[0] << \",\" <<  q_nos_j[1] << \",\" << q_nos_j[2] << \",\" << exp_i[0] << \",\" << exp_i[1] << \",\" << exp_i[2] << std::endl;\n            result(i,j) = s(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2]);\n        }\n    }\n    return result;\n}\n\nEigen::MatrixXd h_matrix_builder(std::vector<std::pair<std::vector<int>, std::vector<double> > > basis, int z) {\n    Eigen::MatrixXd result;\n    result.setZero(basis.size(), basis.size());\n    for (std::size_t i = 0; i != basis.size(); ++i) {\n        for (std::size_t j = 0; j != basis.size(); ++j) {\n            //std::vector<int> q_nos_i, q_nos_j;\n            //std::vector<double> exp_i, exp_j;\n            //auto [q_nos_i, exp_i] = basis[i];\n            //auto [q_nos_j, exp_j] = basis[j];\n            std::vector<int> q_nos_i = basis[i].first;\n            std::vector<double> exp_i = basis[i].second;\n            std::vector<int> q_nos_j = basis[j].first;\n            result(i,j) = (v_ne(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2], z)\n                + v_ee(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2])\n                + t_e(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2]));\n//            if (result(i,j) == nan(0)) {\n//                result(i,j) = 0;\n//            }\n        }\n    }\n    return result;\n}\n\n//template<typename T,typename U>\n//std::pair<T, U>\nstd::pair<Eigen::MatrixXd, Eigen::MatrixXd> hylleraas(std::vector<std::pair<std::vector<int>, std::vector<double> > > basis, int z) {\n    auto H = h_matrix_builder(basis, z);\n    auto S = s_matrix_builder(basis);\n\n    Eigen::GeneralizedEigenSolver<Eigen::MatrixXd> ges;\n    ges.compute(H,S);\n\n    Eigen::MatrixXd evecs = ges.eigenvectors().real();\n    Eigen::MatrixXd evals = ges.eigenvalues().real();\n\n    return std::pair(evecs, evals);\n}\n\nstd::vector<std::pair<std::vector<int>, std::vector<double> > > generate_basis(std::size_t N, double alpha, double gamma) {\n    std::vector<std::pair<std::vector<int>, std::vector<double> > > result;\n    for (int n = 0; n != N; ++n) {\n        for (int l = 0; l != (N-n); ++l) {\n            for (int m = 0; m != (N-n-l); ++m) {\n                if ((n + l + m) <= N)\n                    result.push_back(std::pair<std::vector<int>, std::vector<double>>{std::vector<int>{n,l,m}, std::vector<double>{alpha, alpha, gamma}});\n            }\n        }\n    }\n    return result;\n}\n\ntemplate<typename T,typename U>\nstd::pair<T, U> hylleraas_generic(int N, int z, double alpha, double gamma) {\n    auto basis = generate_basis(N, alpha, gamma);\n    auto [evecs, evals] = hylleraas(basis, z); //<Eigen::MatrixXd, Eigen::MatrixXd>\n    return std::pair(evecs, evals);\n}\n\nint main() {\n    std::vector<std::pair<std::vector<int>, std::vector<double> > > basis =\n            {std::pair(std::vector<int>{0,0,0}, std::vector<double>{1.6875, 1.6875, 0.0})};\n    Eigen::MatrixXd S = s_matrix_builder(basis);\n    std::cout << \"S with single basis fn: \\n\" << S << std::endl;\n\n    Eigen::MatrixXd H = h_matrix_builder(basis, 2);\n    std::cout << \"H with single basis fn: \\n\" << H << std::endl;\n\n//    double k_test = k(0, 0, 0, 0.5, 0.5, 0.5);\n//    std::cout << \"k(-1,-1,-1,0.5,0.5,0.5): \" << k_test << std::endl;\n\n//    double k_test_pfac = k_pfac(1,0, 0, 0, 1, 1, 1);\n//    std::cout << \"k(1,0,0,0,1,1,1): \" << k_test_pfac << std::endl;\n//    double k_test_pfac2 = k_pfac(1,0, 0, 0, 1.6875, 1.6875, 0);\n//    std::cout << \"k(1,0,0,0,1.6875,1.6875,0): \" << k_test_pfac2 << std::endl;\n\n//    int binom_test = binomial(2,1);\n//    std::cout << \"binom test C(2,1)\\n\" << binom_test;\n\n    std::vector<std::pair<std::vector<int>, std::vector<double> > > func3_basis =\n            {std::pair(std::vector<int>{0,0,0}, std::vector<double>{1.8, 1.8, 0.0}), std::pair(std::vector{1,1,0}, std::vector{1.8, 1.8, 0.0}), std::pair(std::vector{0,0,1}, std::vector{1.8, 1.8, 0.0})};\n    Eigen::MatrixXd S_3func = s_matrix_builder(func3_basis);\n    std::cout << \"S_3func: \\n\" << S_3func << std::endl;\n\n    Eigen::MatrixXd H_3func = h_matrix_builder(func3_basis, 2);\n    std::cout << \"H_3func: \\n\" << H_3func << std::endl;\n\n    auto [evecs_3func, evals_3func] = hylleraas(func3_basis, 2);\n    std::cout << \"3basis evecs: \\n\" << evecs_3func << \"\\n\\n3basis evals: \\n\" << evals_3func << std::endl;\n\n    //hylleraas generic\n    auto [evecs_gen_func, evals_gen_func] = hylleraas_generic<Eigen::MatrixXd, Eigen::MatrixXd>(3, 2, 1.8, 0.0);\n    std::cout << \"gen basis evecs: \\n\" << evecs_gen_func << \"\\n\\ngen basis evals: \\n\" << evals_gen_func << std::endl;\n\n//    std::vector<double> evals; //(15);\n//    for (size_t i = 1; i != 16; ++i) {\n//        auto [evecs_gen_func, evals_gen_func] = hylleraas_generic<Eigen::MatrixXd, Eigen::MatrixXd>(i, 2, 1.8, 0.0);\n//\n//        evals.push_back(evals_gen_func.minCoeff());\n//        std::cout << \"Completed \" << i << \"th computation: \" << evals_gen_func.minCoeff() << \"\\n\";\n//    }\n//\n//    for (std::size_t i = 1; i != 16; ++i) {\n//        std::cout << \"He energy computed with i=\" << i << \": \" << evals[i] << \"\\n\";\n//    }\n\n    auto [evecs_7_func, evals_7_func] = hylleraas_generic<Eigen::MatrixXd, Eigen::MatrixXd>(8, 2, 1.8, 0.0);\n    std::cout << \"7-basis evecs: \\n\" << evecs_7_func << \"\\n\\n7-basis evals: \\n\" << evals_7_func << std::endl;\n\n    auto [evecs_8_func, evals_8_func] = hylleraas_generic<Eigen::MatrixXd, Eigen::MatrixXd>(8, 2, 1.8, 0.0);\n    std::cout << \"8-basis evecs: \\n\" << evecs_8_func << \"\\n\\n8-basis evals: \\n\" << evals_8_func << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "cd4773ecadc443c2267a62a6ffdfaff9a12fd6df", "size": 14059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hylleraas.cpp", "max_stars_repo_name": "powellsr/hylleraas", "max_stars_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hylleraas.cpp", "max_issues_repo_name": "powellsr/hylleraas", "max_issues_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hylleraas.cpp", "max_forks_repo_name": "powellsr/hylleraas", "max_forks_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_forks_repo_licenses": ["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.8782287823, "max_line_length": 252, "alphanum_fraction": 0.4932783271, "num_tokens": 5336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6671493622642348}}
{"text": "/******************************************************************************\n * Copyright (C) 2014 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n#include \"aslam/calibration/car/geo/geodetic.h\"\n\n#include <Eigen/Core>\n\n#include <cmath>\n\n#include <sm/kinematics/quaternion_algebra.hpp>\n\nusing namespace sm::kinematics;\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Methods                                                                    */\n/******************************************************************************/\n\n    sm::kinematics::Transformation ecef2enu(double x, double y, double z, double\n        latitude, double longitude) {\n      return enu2ecef(x, y, z, latitude, longitude).inverse();\n    }\n\n    sm::kinematics::Transformation enu2ecef(double x, double y, double z, double\n        latitude, double longitude) {\n\n      const double slat = std::sin(latitude);\n      const double clat = std::cos(latitude);\n      const double slong = std::sin(longitude);\n      const double clong = std::cos(longitude);\n\n      Eigen::Matrix3d enu_R_ecef;\n      enu_R_ecef << -slong, clong, 0,\n        -slat * clong, -slat * slong, clat,\n        clat * clong, clat * slong, slat;\n\n      return Transformation(\n        r2quat(enu_R_ecef.transpose()), Eigen::Vector3d(x, y, z));\n    }\n\n    sm::kinematics::Transformation ecef2ned(double x, double y, double z, double\n        latitude, double longitude) {\n      return ned2ecef(x, y, z, latitude, longitude).inverse();\n    }\n\n    sm::kinematics::Transformation ned2ecef(double x, double y, double z, double\n        latitude, double longitude) {\n\n      const double slat = std::sin(latitude);\n      const double clat = std::cos(latitude);\n      const double slong = std::sin(longitude);\n      const double clong = std::cos(longitude);\n\n      Eigen::Matrix3d ned_R_ecef;\n      ned_R_ecef << -slat * clong, -slat * slong, clat,\n        -slong, clong, 0,\n        -clat * clong, -clat * slong, -slat;\n\n      return Transformation(\n        r2quat(ned_R_ecef.transpose()), Eigen::Vector3d(x, y, z));\n    }\n\n    void wgs84ToEcef(double latitude, double longitude, double altitude,\n        double& x, double& y, double& z) {\n      const double slat = std::sin(latitude);\n      const double clat = std::cos(latitude);\n      const double slong = std::sin(longitude);\n      const double clong = std::cos(longitude);\n      const double a = 6378137;\n      const double e2 = 0.006694380004260827;\n      const double R = a / std::sqrt(1 - e2 * slat * slat);\n      x = (R + altitude) * clat * clong;\n      y = (R + altitude) * clat * slong;\n      z = (R * (1 - e2) + altitude) * slat;\n    }\n\n  }\n}\n", "meta": {"hexsha": "00eb481640cc574cb301fa4dae256f38c0c676fe", "size": 2887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 34.7831325301, "max_line_length": 80, "alphanum_fraction": 0.5226879113, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6671384184655587}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef PLANARQUAD_DYNAMICS_HPP_\n#define PLANARQUAD_DYNAMICS_HPP_\n\n#include <Eigen/Dense>\n\n// template here over some type\ntemplate<typename T1, typename T2>\nauto planarquad_dynamics(const Eigen::MatrixBase<T1> & x, const Eigen::MatrixBase<T2> & u)\n{\n  // Define nx, nu\n  constexpr auto nx = T1::RowsAtCompileTime;\n  constexpr auto nu = T2::RowsAtCompileTime;\n\n  // Initialize Parameters\n  constexpr double I = 0.2;\n  constexpr double m = 0.5;\n  constexpr double r = 0.25;\n  constexpr double gr = 9.81;\n\n  using T = typename decltype(x * u.transpose())::EvalReturnType::Scalar;\n\n  // xDot = f(x) + g(x)*u\n  Eigen::Matrix<T, nx, 1> xDot;\n  Eigen::Matrix<typename T1::Scalar, nx, 1> f;\n\n  Eigen::Matrix<typename T1::Scalar, nx, nu> g;\n  Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g1(g.data());\n  Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g2(g.data() + nx);\n\n  // Define States\n  // const auto & X = x[0];\n  // const auto & Y = x[1];\n  const auto & theta = x[2];\n\n  // Dynamics\n  f[0] = x[3];\n  f[1] = x[4];\n  f[2] = x[5];\n  f[3] = 0.;\n  f[4] = -gr;\n  f[5] = 0.;\n\n\n  g1[0] = 0;                g2[0] = 0;\n  g1[1] = 0;                g2[1] = 0;\n  g1[2] = 0;                g2[2] = 0;\n  g1[3] = -sin(theta) / m;  g2[3] = -sin(theta) / m;\n  g1[4] = cos(theta) / m;   g2[4] = cos(theta) / m;\n  g1[5] = r / I;            g2[5] = -r / I;\n\n  xDot = f + g * u;\n\n  return xDot;\n}\n\n#endif  // PLANARQUAD_DYNAMICS_HPP_\n", "meta": {"hexsha": "1b947f6648f6e12ec0b5bd00dd7414f103d77c8f", "size": 1533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/planarquad_dynamics.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "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/planarquad_dynamics.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "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/planarquad_dynamics.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["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.131147541, "max_line_length": 90, "alphanum_fraction": 0.5851272016, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6671331617624823}}
{"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#include <stapl/array.hpp>\n#include <stapl/algorithm.hpp>\n#include <stapl/utility/do_once.hpp>\n#include <boost/lexical_cast.hpp>\n\ntypedef unsigned long long ulong_type;\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Determines whether a number is fibonacci or not.\n///        If the fibonacci number is even, false is returned.\n///        Otherwise the number is not fibonacci number and even, thus true is\n///        returned.\n////////////////////////////////////////////////////////////////////////////////\nstruct not_even_fib\n{\n  template <typename T>\n  bool operator()(T i)\n  {\n    // Statements used to determine if a number is Fibonacci or not is\n    //   (5*(N^2))-4 OR (5*(N^2))+4\n    //   If the result of either statement is a perfect square number,\n    //   Then N is a fibonacci number.\n    ulong_type fib_check_1 = 5 * (static_cast<ulong_type>(\n      pow(static_cast<long double>(i), 2.0))) - 4;\n\n    ulong_type fib_check_2 = 5 * (static_cast<ulong_type>(\n      pow(static_cast<long double>(i), 2.0))) + 4;\n\n    // Square root taken to determine if the number is a perfect square.\n    ulong_type root_1 = static_cast<ulong_type>(\n      sqrt(static_cast<long double>(fib_check_1)));\n\n    ulong_type root_2 = static_cast<ulong_type>(\n      sqrt(static_cast<long double>(fib_check_2)));\n\n    // Checks if the number is even and verifies as a perfect square\n    //   number.\n    if ((root_1 * root_1 == fib_check_1 ||\n         root_2 * root_2 == fib_check_2) && (i%2 == 0))\n      return false;\n\n    return true;\n  }\n\n};\n\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n  ulong_type num = boost::lexical_cast<ulong_type> (argv[1]);\n\n  // Creates array container of unsigned integers that will be used for storage.\n  stapl::array<ulong_type> fibonacci(num);\n\n  // Creates view over container.\n  stapl::array_view<stapl::array<ulong_type>> view(fibonacci);\n\n  // Fills the container with values from 1 to n.\n  stapl::iota(view,1);\n\n  // For numbers in the container that return true to the not_even_fib\n  //   functor, they are set to 0.\n  stapl::replace_if(view, not_even_fib(), 0);\n\n  // Adds the total of all elements in container.\n  ulong_type ans = stapl::accumulate(view, 0);\n\n  // Prints the total sum.\n  stapl::do_once ([&] {\n    std::cout << \"The total is: \" << ans << std::endl;\n  });\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "56a19519f909e7a3db3dd928de4f23c4fd7f38c3", "size": 2747, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_2a.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_2a.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_2a.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": 31.9418604651, "max_line_length": 80, "alphanum_fraction": 0.6417910448, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.667133154044081}}
{"text": "#include <iomanip>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n \nusing big_float = boost::multiprecision::cpp_dec_float_100;\n \nbig_float f(unsigned int n) {\n    big_float pi(boost::math::constants::pi<big_float>());\n    return exp(sqrt(big_float(n)) * pi);\n}\n \nint main() {\n    std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n        << std::setprecision(80) << f(163) << '\\n';\n    std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n    std::cout << std::setprecision(30);\n    for (unsigned int n : {19, 43, 67, 163}) {\n        auto x = f(n);\n        auto c = ceil(x);\n        auto pc = 100.0 * (x/c);\n        std::cout << \"f(\" << n << \") = \" << x << \" = \"\n            << pc << \"% of \" << c << '\\n';\n    }\n    return 0;\n}", "meta": {"hexsha": "3e34d5667673350e82e0292124fc5ceb84e92b18", "size": 829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_stars_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_stars_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2020-10-01T10:06:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:57:18.000Z", "max_issues_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_issues_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_issues_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2020-09-27T04:55:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T18:49:06.000Z", "max_forks_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_forks_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_forks_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 327.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T17:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T06:04:39.000Z", "avg_line_length": 31.8846153846, "max_line_length": 79, "alphanum_fraction": 0.5609167672, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6670994777640955}}
{"text": "#include \"UtilEOL.h\"\n\n#include \"external\\ArcSim\\geometry.hpp\"\n\n#include <iostream>\n\n#include <Eigen\\SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd deform_grad(const Face *f)\n{\n\tMatrixXd Dx(3, 2);\n\tDx(0, 0) = f->v[1]->node->x[0] - f->v[0]->node->x[0];\n\tDx(0, 1) = f->v[2]->node->x[0] - f->v[0]->node->x[0];\n\tDx(1, 0) = f->v[1]->node->x[1] - f->v[0]->node->x[1];\n\tDx(1, 1) = f->v[2]->node->x[1] - f->v[0]->node->x[1];\n\tDx(2, 0) = f->v[1]->node->x[2] - f->v[0]->node->x[2];\n\tDx(2, 1) = f->v[2]->node->x[2] - f->v[0]->node->x[2];\n\tMatrix2d DX;\n\tDX(0, 0) = f->v[1]->u[0] - f->v[0]->u[0];\n\tDX(0, 1) = f->v[2]->u[0] - f->v[0]->u[0];\n\tDX(1, 0) = f->v[1]->u[1] - f->v[0]->u[1];\n\tDX(1, 1) = f->v[2]->u[1] - f->v[0]->u[1];\n\treturn Dx * DX.inverse();\n}\n\nMatrixXd deform_grad_v(const Vert* v)\n{\n\tdouble tot_ang = 0.0;\n\tMatrix3d Q = Matrix3d::Zero();\n\tMatrix2d P = Matrix2d::Zero();\n\n\tfor (int f = 0; f < v->adjf.size(); f++) {\n\t\tFace* face = v->adjf[f];\n\n\t\tMatrixXd F = deform_grad(face);\n\t\tJacobiSVD<MatrixXd> svd(F, ComputeFullU | ComputeFullV);\n\n\t\tMatrixXd V3(2, 3);\n\t\tV3 << svd.matrixV(), Vector2d::Zero();\n\n\t\tMatrixXd Qx = svd.matrixU() * V3.transpose();\n\t\tMatrix3d Qxrot;\n\t\tQxrot << Qx.col(0), Qx.col(1), Qx.block<3,1>(0,0).cross(Qx.block<3,1>(0,1));\n\n\t\tMatrix2d S2;\n\t\tS2 << svd.singularValues(), svd.singularValues();\n\n\t\tMatrix2d Px = svd.matrixV() * S2 * svd.matrixV().transpose();\n\n\t\tQ += incedent_angle(v, face) * Qxrot.log();\n\t\t\n\t\tP += incedent_angle(v, face) * Px;\n\t\t\n\t\ttot_ang += incedent_angle(v, face);\n\t}\n\t\n\tQ /= tot_ang;\n\tQ = Q.exp();\n\n\tP /= tot_ang;\n\n\treturn Q.block<3, 2>(0, 0) * P;\n}", "meta": {"hexsha": "d9ed1f35d9fd6918ae1f5d06cdff3a2138032de1", "size": 1648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UtilEOL.cpp", "max_stars_repo_name": "sueda/eol-cloth", "max_stars_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T04:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T03:46:30.000Z", "max_issues_repo_path": "src/UtilEOL.cpp", "max_issues_repo_name": "sueda/eol-cloth", "max_issues_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-19T09:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T15:03:18.000Z", "max_forks_repo_path": "src/UtilEOL.cpp", "max_forks_repo_name": "sueda/eol-cloth", "max_forks_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T03:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:41:50.000Z", "avg_line_length": 24.5970149254, "max_line_length": 78, "alphanum_fraction": 0.5594660194, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6670442825688918}}
{"text": "#include <glm/models/links/log.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\nlog_link::log_link()\n    : glm_link::glm_link( \"log\" )\n{\n}\n\nvec\nlog_link::init_beta(const mat &X, const vec &y) const\n{\n    vec mu = (y + 0.5) / 2.0;\n    vec eta = log( mu );\n    \n    return pinv( X ) * eta;\n}\n\nvec\nlog_link::mu(const arma::vec &eta) const\n{\n    return exp( eta );\n}\n\nvec\nlog_link::eta(const arma::vec &mu) const\n{\n    return log( mu );\n}\n\nvec\nlog_link::mu_eta(const arma::vec &mu) const\n{\n    return 1.0 / mu;\n}\n", "meta": {"hexsha": "3086e6ce0cbb5a3fcdca7e5eede3c20a8ad4c2a4", "size": 511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/log.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/models/links/log.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/models/links/log.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 13.4473684211, "max_line_length": 53, "alphanum_fraction": 0.6046966732, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6670442737410338}}
{"text": "\n#include <OGRE/OgreVector3.h>\n#include <OGRE/OgreSceneNode.h>\n#include <OGRE/OgreSceneManager.h>\n\n#include <ros/console.h>\n#include <rviz/ogre_helpers/axes.h>\n#include <rviz/ogre_helpers/shape.h>\n\n#include <Eigen/Dense>\n\n#include \"covariance_visual.h\"\n\ntemplate<typename Derived>\ninline bool isfinite(const Eigen::MatrixBase<Derived>& x)\n{\n  return ( (x - x).array() == (x - x).array()).all();\n}\n\n\ntemplate<typename Derived>\ninline bool isnan(const Eigen::MatrixBase<Derived>& x)\n{\n  return !((x.array() == x.array())).all();\n}\n\nstd::pair<Eigen::Matrix3d, Eigen::Vector3d> computeEigenValuesAndVectors(const geometry_msgs::PoseWithCovariance& msg,  unsigned offset)\n{\n  Eigen::Matrix3d covariance   = Eigen::Matrix3d::Zero();\n  Eigen::Vector3d eigenValues  = Eigen::Vector3d::Identity();\n  Eigen::Matrix3d eigenVectors = Eigen::Matrix3d::Zero();\n\n  for (size_t i = 0; i < 3; ++i)\n  {\n    for (size_t j = 0; j < 3; ++j)\n    {\n      covariance (i, j) = msg.covariance[(i + offset) * 6 + j + offset];\n    }\n  }\n\n  // Compute eigen values and eigen vectors.\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(covariance);\n\n  if (eigensolver.info() == Eigen::Success)\n  {\n    eigenValues  = eigensolver.eigenvalues();\n    eigenVectors = eigensolver.eigenvectors();\n  }\n  else\n  {\n    ROS_WARN_THROTTLE(1, \"Failed to compute eigen vectors/values. Is the covariance matrix correct?\");\n  }\n\n  return std::make_pair(eigenVectors, eigenValues);\n}\n\nOgre::Quaternion computeRotation(const geometry_msgs::PoseWithCovariance& msg, std::pair<Eigen::Matrix3d, Eigen::Vector3d>& pair)\n{\n  Ogre::Matrix3 rotation;\n\n  for (size_t i = 0; i < 3; ++i)\n  {\n    for (size_t j = 0; j < 3; ++j)\n    {\n      rotation[i][j] = pair.first(i, j);\n    }\n  }\n\n  return Ogre::Quaternion(rotation);\n}\n\nnamespace rviz_plugin_covariance\n{\n\nCovarianceVisual::CovarianceVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node)\n  : frame_node_(parent_node->createChildSceneNode())\n  , scene_manager_(scene_manager)\n  , scale_(1.0)\n{\n  axes_.reset(new rviz::Axes(scene_manager_, frame_node_));\n\n  position_node_    = axes_->getSceneNode()->createChildSceneNode();\n  orientation_node_ = axes_->getSceneNode()->createChildSceneNode();\n\n  position_shape_.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_, position_node_));\n  orientation_shape_.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_, orientation_node_));\n\n  axes_->getSceneNode()->setVisible(show_axis_);\n  position_node_->setVisible(show_position_);\n  orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nCovarianceVisual::~CovarianceVisual()\n{\n  scene_manager_->destroySceneNode(orientation_node_);\n  scene_manager_->destroySceneNode(position_node_);\n  scene_manager_->destroySceneNode(frame_node_);\n}\n\nvoid CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovariance& msg)\n{\n  // Construct pose position and orientation.\n  const geometry_msgs::Point& p = msg.pose.position;\n  Ogre::Vector3 position(p.x, p.y, p.z);\n  Ogre::Quaternion orientation(msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z);\n\n  // Set position and orientation for axes scene node.\n  if (!position.isNaN())\n  {\n    axes_->setPosition(position);\n  }\n  else\n  {\n    ROS_WARN_STREAM_THROTTLE(1, \"Position contains NaN: \" << position);\n  }\n\n  if (!orientation.isNaN())\n  {\n    axes_->setOrientation(orientation);\n  }\n  else\n  {\n    ROS_WARN_STREAM_THROTTLE(1, \"Orientation contains NaN: \" << orientation);\n  }\n\n  if (use_6dof_)\n  {\n    // Check for NaN in covariance\n    for (size_t i = 0; i < 3; ++i)\n    {\n      if (isnan(msg.covariance[i]))\n      {\n        ROS_WARN_THROTTLE(1, \"Covariance contains NaN\");\n        return;\n      }\n    }\n\n    // Compute eigen values and vectors for both shapes.\n    std::pair<Eigen::Matrix3d, Eigen::Vector3d> positionEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 0));\n    std::pair<Eigen::Matrix3d, Eigen::Vector3d> orientationEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 3));\n\n    Ogre::Quaternion positionQuaternion(computeRotation(msg, positionEigenVectorsAndValues));\n    Ogre::Quaternion orientationQuaternion(computeRotation(msg, orientationEigenVectorsAndValues));\n\n    position_node_->setOrientation(positionQuaternion);\n    orientation_node_->setOrientation(orientationQuaternion);\n\n    // Compute scaling.\n    Ogre::Vector3 positionScaling(\n        std::sqrt(positionEigenVectorsAndValues.second[0]),\n        std::sqrt(positionEigenVectorsAndValues.second[1]),\n        std::sqrt(positionEigenVectorsAndValues.second[2]));\n    positionScaling *= scale_;\n\n    Ogre::Vector3 orientationScaling(\n        std::sqrt(orientationEigenVectorsAndValues.second[0]),\n        std::sqrt(orientationEigenVectorsAndValues.second[1]),\n        std::sqrt(orientationEigenVectorsAndValues.second[2]));\n    orientationScaling *= scale_;\n\n    // Set the scaling.\n    if (!positionScaling.isNaN())\n    {\n      position_node_->setScale(positionScaling);\n    }\n    else\n    {\n      ROS_WARN_STREAM_THROTTLE(1, \"PositionScaling contains NaN: \" << positionScaling);\n    }\n\n    if (!orientationScaling.isNaN())\n    {\n      orientation_node_->setScale(orientationScaling);\n    }\n    else\n    {\n      ROS_WARN_STREAM_THROTTLE(1, \"OrientationScaling contains NaN: \" << orientationScaling);\n    }\n\n    // Debugging.\n    ROS_DEBUG_STREAM_THROTTLE(1,\n       \"Position:\\n\"\n       << position << \"\\n\"\n       << \"Positional part 3x3 eigen values:\\n\"\n       << positionEigenVectorsAndValues.second << \"\\n\"\n       << \"Positional part 3x3 eigen vectors:\\n\"\n       << positionEigenVectorsAndValues.first << \"\\n\"\n       << \"Sphere orientation:\\n\"\n       << positionQuaternion << \"\\n\"\n       << positionQuaternion.getYaw() << \"\\n\"\n       << \"Sphere scaling:\\n\"\n       << positionScaling << \"\\n\"\n       << \"Rotational part 3x3 eigen values:\\n\"\n       << orientationEigenVectorsAndValues.second << \"\\n\"\n       << \"Rotational part 3x3 eigen vectors:\\n\"\n       << orientationEigenVectorsAndValues.first << \"\\n\"\n       << \"Cone orientation:\\n\"\n       << orientationQuaternion << \"\\n\"\n       << orientationQuaternion.getRoll() << \" \"\n       << orientationQuaternion.getPitch() << \" \"\n       << orientationQuaternion.getYaw() << \"\\n\"\n       << \"Cone scaling:\\n\"\n       << orientationScaling);\n  }\n  else // 3DOF\n  {\n    // Take (x, y, th) part from the covariance matrix:\n    //   x y z R P Y\n    // x * *       x\n    // y * *       x\n    // z\n    // R\n    // P\n    // Y x x       *\n    //\n    // Actually, we only take the elements marked with '*', although we could\n    // also take a 3x3 matrix with the '*' and 'x' elements.\n    Eigen::Matrix2d cov_xy; cov_xy << msg.covariance[0], msg.covariance[1],\n                                      msg.covariance[6], msg.covariance[7];\n    const double cov_yaw = msg.covariance[35];\n\n    // Check for NaN in covariance\n    if (isnan(cov_xy) || isnan(cov_yaw))\n    {\n      ROS_WARN_STREAM_THROTTLE(1, \"Covariance contains NaN: \" <<\n          \"C_xy = \" << cov_xy << \", C_yaw = \" << cov_yaw);\n      return;\n    }\n\n    // Compute eigen values and vectors for xy\n    Eigen::Vector2d eigen_values  = Eigen::Vector2d::Identity();\n    Eigen::Matrix2d eigen_vectors = Eigen::Matrix2d::Zero();\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigensolver(cov_xy);\n    if (eigensolver.info() == Eigen::Success)\n    {\n      eigen_values  = eigensolver.eigenvalues();\n      eigen_vectors = eigensolver.eigenvectors();\n    }\n    else\n    {\n      ROS_WARN_THROTTLE(1, \"Failed to compute eigen values/vectors. Is the covariance matrix correct?\");\n    }\n\n    // Compute ellipsoid angle, and axes\n    const double yaw = atan2(eigen_vectors(1, 0), eigen_vectors(0, 0));\n    const double axis_major = sqrt(eigen_values[0]);\n    const double axis_minor = sqrt(eigen_values[1]);\n    const double axis_yaw   = sqrt(cov_yaw);\n\n    // Compute the ellipsoid orientation\n    Ogre::Quaternion positionQuaternion;\n    Ogre::Matrix3 R;\n    R.FromEulerAnglesXYZ(Ogre::Radian(0.0), Ogre::Radian(0.0), Ogre::Radian(yaw));\n    positionQuaternion.FromRotationMatrix(R);\n\n    // Set the orientation\n    position_node_->setOrientation(positionQuaternion);\n\n    // Compute the ellipsoid scale\n    Ogre::Vector3 positionScaling(\n        std::isnormal(axis_major) ? axis_major : 0.001,\n        std::isnormal(axis_minor) ? axis_minor : 0.001,\n        std::isnormal(axis_yaw  ) ? axis_yaw   : 0.001);\n    positionScaling *= scale_;\n\n    // Set the scaling\n    if (!positionScaling.isNaN())\n    {\n      position_node_->setScale(positionScaling);\n    }\n    else\n    {\n      ROS_WARN_STREAM_THROTTLE(1, \"PositionScaling contains NaN: \" << positionScaling);\n    }\n\n    // Debugging\n    ROS_DEBUG_STREAM_THROTTLE(1,\n       \"Position:\\n\"\n       << position << \"\\n\"\n       << \"C_xy:\\n\"\n       << cov_xy << \"\\n\"\n       << \"C_yaw:\\n\"\n       << cov_yaw << \"\\n\"\n       << \"axis (major, minor, yaw): (\" << axis_major << \", \" << axis_minor << \", \" << axis_yaw << \")\\n\"\n       << \"yaw: \" << yaw << \"\\n\"\n       << \"Positional part 2x2 eigen values:\\n\"\n       << eigen_values << \"\\n\"\n       << \"Positional part 2x2 eigen vectors:\\n\"\n       << eigen_vectors << \"\\n\"\n       << \"Sphere orientation:\\n\"\n       << positionQuaternion << \"\\n\"\n       << positionQuaternion.getRoll() << \" \"\n       << positionQuaternion.getPitch() << \" \"\n       << positionQuaternion.getYaw() << \"\\n\"\n       << \"Sphere scaling:\\n\"\n       << positionScaling);\n  }\n}\n\nvoid CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg)\n{\n  setMessage(msg->pose);\n}\n\nvoid CovarianceVisual::setMessage(const nav_msgs::OdometryConstPtr& msg)\n{\n  setMessage(msg->pose);\n}\n\nvoid CovarianceVisual::setFramePosition(const Ogre::Vector3& position)\n{\n  frame_node_->setPosition(position);\n}\n\nvoid CovarianceVisual::setFrameOrientation(const Ogre::Quaternion& orientation)\n{\n  frame_node_->setOrientation(orientation);\n}\n\nvoid CovarianceVisual::setColor(float r, float g, float b, float a)\n{\n  position_shape_->setColor(r, g, b, a);\n  orientation_shape_->setColor(r, g, b, a);\n}\n\nvoid CovarianceVisual::setScale(float scale)\n{\n  scale_ = scale;\n}\n\nvoid CovarianceVisual::setShowAxis(bool show_axis)\n{\n  show_axis_ = show_axis;\n\n  axes_->getSceneNode()->setVisible(show_axis);\n  position_node_->setVisible(show_position_);\n  orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nvoid CovarianceVisual::setShowPosition(bool show_position)\n{\n  show_position_ = show_position;\n\n  position_node_->setVisible(show_position_);\n}\n\nvoid CovarianceVisual::setShowOrientation(bool show_orientation)\n{\n  show_orientation_ = show_orientation;\n\n  orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nvoid CovarianceVisual::setUse6DOF(bool use_6dof)\n{\n  use_6dof_ = use_6dof;\n\n  orientation_node_->setVisible(use_6dof && show_orientation_);\n}\n\n} // end namespace rviz_plugin_covariance\n", "meta": {"hexsha": "cbf4a7bdf84a32066f1511c8267fd617c20417ca", "size": 10888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_stars_repo_name": "hect1995/Robotics_intro", "max_stars_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T14:52:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:59:00.000Z", "max_issues_repo_path": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_issues_repo_name": "hect1995/Robotics_intro", "max_issues_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "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": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_forks_repo_name": "hect1995/Robotics_intro", "max_forks_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-09-29T10:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T12:38:37.000Z", "avg_line_length": 29.9944903581, "max_line_length": 136, "alphanum_fraction": 0.6708302719, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6670341478957673}}
{"text": "/*\n * distributions_boost.cpp\n *\n *  Created on: 7 Sep 2018\n *      Author: admin\n */\n#include <Eigen/Eigen>\n#include <math.h>\n#include \"distributions_boost.hpp\"\n#include <boost/random/gamma_distribution.hpp>\n#include \"boost/random.hpp\"\n#include \"boost/generator_iterator.hpp\"\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_01.hpp>\n\nDistributions_boost::Distributions_boost(unsigned int pseed):seed(pseed){\n    rng=boost::mt19937(pseed);\n}\nDistributions_boost::~Distributions_boost(){\n}\n\ndouble Distributions_boost::rgamma(double shape, double scale){\n    boost::random::gamma_distribution<double> myGamma(shape, scale);\n    boost::random::variate_generator<boost::mt19937&, boost::random::gamma_distribution<> > rand_gamma(rng, myGamma);\n    return rand_gamma();\n}\n\ndouble Distributions_boost::unif_rng(){\n    boost::random::uniform_real_distribution<double> myU(0,1);\n    boost::random::variate_generator<boost::mt19937&, boost::random::uniform_real_distribution<> > real_variate_generator(rng, myU);\n    return real_variate_generator();\n\n}\n\nEigen::VectorXd Distributions_boost::dirichlet_rng(Eigen::VectorXd alpha) {\n    int len;\n    len=alpha.size();\n    Eigen::VectorXd result(len);\n    for(int i=0;i<len;i++)\n        result[i]=rgamma(alpha[i],(double)1.0);\n    result/=result.sum();\n    return result;\n}\n\ndouble Distributions_boost::inv_gamma_rng(double shape,double scale){\n    return ((double)1.0 / rgamma(shape, 1.0/scale));\n}\ndouble Distributions_boost::gamma_rng(double shape,double scale){\n    return rgamma(shape, scale);\n}\ndouble Distributions_boost::inv_gamma_rate_rng(double shape,double rate){\n    return (double)1.0 / gamma_rate_rng(shape, rate);\n}\ndouble Distributions_boost::gamma_rate_rng(double shape,double rate){\n    return rgamma(shape,(double)1.0/rate);\n}\n\ndouble Distributions_boost::inv_scaled_chisq_rng(double dof,double scale){\n    return inv_gamma_rng((double)0.5*dof, (double)0.5*dof*scale);\n}\ndouble Distributions_boost::norm_rng(double mean,double sigma2){\n    boost::normal_distribution<double> nd(mean, std::sqrt((double)sigma2));\n    boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);\n    return var_nor();\n}\n\ninline double runif(unsigned int seed){\n    boost::mt19937 rng(seed);\n    static boost::uniform_01<boost::mt19937> zeroone(rng);\n    return zeroone();\n}\n\ndouble Distributions_boost::component_probs(double b2,Eigen::VectorXd pi){\n    double sum;\n    double p;\n    p=runif(seed);\n    sum= pi[0]*exp((-0.5*b2)/(5e-2))/sqrt(5e-2)+pi[1]*exp((-0.5*b2));\n    if(p<=(pi[0]*exp((-0.5*b2)/(5e-2))/sqrt(5e-2))/sum)\n        return 5e-2;\n    else\n        return 1;\n}\n\n\n\n\n", "meta": {"hexsha": "d9f375519b42b97f3deff1c69ba36bb618f3efe9", "size": 2676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distributions_boost.cpp", "max_stars_repo_name": "ctggroup/BayesMap", "max_stars_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-06T14:43:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:05:05.000Z", "max_issues_repo_path": "src/distributions_boost.cpp", "max_issues_repo_name": "ctggroup/BayesMap", "max_issues_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-01T17:22:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T04:43:18.000Z", "max_forks_repo_path": "src/distributions_boost.cpp", "max_forks_repo_name": "ctggroup/BayesRRcmd", "max_forks_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-03T10:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T10:01:55.000Z", "avg_line_length": 30.7586206897, "max_line_length": 132, "alphanum_fraction": 0.7189835575, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6669930661470107}}
{"text": "#pragma once\n\n#include <iomanip>\n#include <vector>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n\n#include \"Bounds.hh\"\n#include \"../Math/math.hh\"\n#include \"../util/assert.hh\"\n#include \"../util/Maybe.hh\"\n\n#include \"LineSegment/linesegment.hh\"\n\nnamespace bold\n{\n  /**\n   * Line, specified using radius/distance-from-origin parameters (normal form.)\n   *\n   * Equations defining the line are:\n   *\n   *   r = x*sin(theta) + y*cos(theta)\n   *\n   *   x = (r - y*cos(theta))/sin(theta)\n   *   y = (r - x*sin(theta))/cos(theta)\n   */\n  class Line\n  {\n  // TODO rename to NormalLine2d?\n  public:\n    Line(double const radius, double const theta, const ushort votes = 0)\n    : d_radius(radius),\n      d_theta(theta)\n    {\n      ASSERT(theta >= 0);\n      ASSERT(theta <= M_PI);\n      ASSERT(!std::isnan(theta) && !std::isnan(radius) && !std::isinf(theta) && !std::isinf(radius));\n    };\n\n    double radius() const { return d_radius; }\n    double theta() const { return d_theta; }\n    double thetaDegrees() const { return Math::radToDeg(d_theta); }\n\n    double gradient() const { return tanh(d_theta); }\n    double yIntersection() const { return d_radius / cos(d_theta); }\n\n    void draw(cv::Mat& mat, cv::Scalar const& color) const\n    {\n      Maybe<LineSegment<int,2>> line(intersectWith(Bounds2i(Eigen::Vector2i::Zero(), Eigen::Vector2i(mat.cols, mat.rows))));\n\n      if (line.hasValue())\n      {\n        Eigen::Vector2i const& p1 = line->p1();\n        Eigen::Vector2i const& p2 = line->p2();\n        cv::line(mat, cv::Point(p1.x(), p1.y()), cv::Point(p2.x(), p2.y()), color);\n      }\n    }\n\n    template<typename T>\n    Maybe<LineSegment<T,2>> intersectWith(Bounds<T,2> bounds) const\n    {\n      ASSERT(d_theta >= 0 && d_theta <= M_PI);\n\n      double tsin = sin(d_theta);\n      double tcos = cos(d_theta);\n\n      int minX = bounds.min().x();\n      int minY = bounds.min().y();\n      int maxX = bounds.max().x();\n      int maxY = bounds.max().y();\n\n      // r = x*sin(theta) + y*cos(theta)\n      // x = (r - y*cos(theta))/sin(theta)\n      // y = (r - x*sin(theta))/cos(theta)\n\n      double xWhenYMin = (d_radius-minY*tcos)/tsin;\n      double yWhenXMin = (d_radius-minX*tsin)/tcos;\n\n      double xWhenYMax = (d_radius-maxY*tcos)/tsin;\n      double yWhenXMax = (d_radius-maxX*tsin)/tcos;\n\n      std::vector<Eigen::Matrix<T,2,1>> edgeContactPoints;\n\n      if (xWhenYMin >= minX && xWhenYMin <= maxX)\n        edgeContactPoints.emplace_back(xWhenYMin, minY);\n\n      if (xWhenYMax >= minX && xWhenYMax <= maxX)\n        edgeContactPoints.emplace_back(xWhenYMax, maxY);\n\n      if (yWhenXMin >= minY && yWhenXMin <= maxY)\n        edgeContactPoints.emplace_back(minX, yWhenXMin);\n\n      if (yWhenXMax >= minY && yWhenXMax <= maxY)\n        edgeContactPoints.emplace_back(maxX, yWhenXMax);\n\n      if (edgeContactPoints.size() == 0)\n        return Maybe<LineSegment<T,2>>::empty();\n\n      ASSERT(edgeContactPoints.size() == 2);\n\n      if (edgeContactPoints.size() != 2)\n        return Maybe<LineSegment<T,2>>::empty();\n\n      return Maybe<LineSegment<T,2>>(LineSegment<T,2>(edgeContactPoints[0], edgeContactPoints[1]));\n    }\n\n    bool operator==(Line const& other) const\n    {\n      const double epsilon = 0.0000001;\n      return fabs(d_radius - other.d_radius) < epsilon\n          && fabs(d_theta - other.d_theta) < epsilon;\n    }\n\n    template<typename T>\n    static Line fromSegment(LineSegment2<T> const& segment)\n    {\n      double theta = atan2(segment.p2().y() - segment.p1().y(),\n                           segment.p1().x() - segment.p2().x());\n      \n      double radius = segment.p1().x() * std::sin(theta) +\n        segment.p1().y() * std::cos(theta);\n\n      while (theta < 0)\n      {\n        theta += M_PI;\n        radius = -radius;\n      }\n\n      while (theta > M_PI)\n      {\n        theta -= M_PI;\n        radius = -radius;\n      }\n\n      return Line(radius, theta);\n    }\n\n    friend std::ostream& operator<<(std::ostream& stream, Line const& line)\n    {\n      return stream << std::setprecision(13) << \"Line (radius=\" << line.radius() << \" theta=\" << line.theta() << \")\";\n    }\n\n  private:\n    double d_radius;\n    double d_theta;\n  };\n}\n", "meta": {"hexsha": "1b9b6f7befe4a78f84618a9371aad184ba85ea8e", "size": 4161, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/Line.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/Line.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/Line.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.74, "max_line_length": 124, "alphanum_fraction": 0.5866378274, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6669053055324907}}
{"text": "/* Boost libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.cpp\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013 Pascal Germroth\r\n Copyright 2013 Mario Mulansky\r\n\r\n Parallelized Lorenz ensembles using nested omp algebra\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include <omp.h>\r\n#include <vector>\r\n#include <iostream>\r\n#include <iterator>\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/numeric/odeint/external/openmp/openmp.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include \"point_type.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntypedef point<double, 3> point_type;\r\ntypedef vector< point_type > state_type;\r\n\r\nconst double sigma = 10.0;\r\nconst double b = 8.0 / 3.0;\r\n\r\n\r\nstruct sys_func {\r\n    const vector<double> &R;\r\n    sys_func( vector<double> &R ) : R(R) {}\r\n\r\n    void operator()( const state_type &x , state_type &dxdt , double t ) const {\r\n#       pragma omp parallel for\r\n        for(size_t i = 0 ; i < x.size() ; i++) {\r\n            dxdt[i][0] = -sigma * (x[i][0] - x[i][1]);\r\n            dxdt[i][1] = R[i] * x[i][0] - x[i][1] - x[i][0] * x[i][2];\r\n            dxdt[i][2] = -b * x[i][2] + x[i][0] * x[i][1];\r\n        }\r\n    }\r\n};\r\n\r\n\r\nint main(int argc, char **argv) {\r\n    size_t n = 1024;\r\n    if(argc > 1) n = boost::lexical_cast<size_t>(argv[1]);\r\n\r\n    vector<double> R(n);\r\n    const double Rmin = 0.1, Rmax = 50.0;\r\n#   pragma omp parallel for\r\n    for(size_t i = 0 ; i < n ; i++)\r\n        R[i] = Rmin + (Rmax - Rmin) / (n - 1) * i;\r\n\r\n    state_type state( n , point_type(10, 10, 10) );\r\n\r\n    typedef runge_kutta4< state_type, double , state_type , double ,\r\n                          openmp_nested_algebra<vector_space_algebra> > stepper;\r\n\r\n    const double t_max = 10.0, dt = 0.01;\r\n\r\n    integrate_const(\r\n        stepper(),\r\n        sys_func(R),\r\n        state,\r\n        0.0, t_max, dt\r\n    );\r\n\r\n    std::copy( state.begin(), state.end(), ostream_iterator<point_type>(cout, \"\\n\") );\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "578e71a5dad922bf9ebd6ed2707a5df3fa81cc3a", "size": 2099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.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/numeric/odeint/examples/openmp/lorenz_ensemble_nested.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/numeric/odeint/examples/openmp/lorenz_ensemble_nested.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": 27.6184210526, "max_line_length": 87, "alphanum_fraction": 0.595521677, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6667915064612215}}
{"text": "#pragma once\n\n#include <armadillo>\n#include <vector>\n#include <tuple>\n\n#define MAX_ITERS 100\n\nstruct KMedNode\n{\n\tKMedNode(size_t n, size_t k) : N(n), K(k), \n\t\t\t\t\t\tmedoids(K,arma::fill::zeros),\n\t\t\t\t\t\tmultiplicity(K,arma::fill::zeros),\n\t\t\t\t\t\tassignments(N,arma::fill::zeros) { }\n\tsize_t N;\n\tsize_t K;\n\tarma::uvec medoids;\n\tarma::uvec multiplicity;\n\tarma::uvec assignments;\n};\n\n\nvoid \nassign_to_medoids(const arma::mat& dists, KMedNode& kmn)\n{\n\tarma::mat sub_dists = dists.rows(kmn.medoids);\n\tkmn.multiplicity.zeros();\n\tfor(size_t i = 0; i < kmn.N; ++i)\n\t{\n\t\tarma::uvec idx = arma::find(kmn.medoids==i,1);\n\t\tif(idx.n_elem == 1)\n\t\t{\n\t\t\tsize_t loc = idx[0];\n\t\t\tkmn.multiplicity[loc]++;\n\t\t\tkmn.assignments[i] = kmn.medoids[loc];\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tsize_t min_idx = sub_dists.col(i).index_min();\n\t\tkmn.assignments[i] = kmn.medoids[min_idx];\n\t\tkmn.multiplicity[min_idx]++;\n\t}\n}\n\nvoid\nupdate_medoids(const arma::mat& dists, KMedNode& kmn)\n{\n\tarma::uvec set;\n\tfor(size_t k = 0; k < kmn.K; ++k)\n\t{\n\t\tset = arma::find(kmn.assignments == kmn.medoids[k]);\n\t\tarma::mat sub_dist = dists(set,set);\n\t\tarma::vec row_sums = arma::sum(sub_dist,1);\n\t\tsize_t min_idx = row_sums.index_min();\n\t\tif(kmn.medoids[k] != set[min_idx])\n\t\t\tprintf(\"Swapping %llu for %llu\\n\",set[min_idx],kmn.medoids[k]);\n\t\tkmn.medoids[k] = set[min_idx];\n\t}\n}\n\narma::uvec\nkmpp_init(const arma::mat& dists, size_t k, const arma::uvec& seeds)\n{\n\tarma::uvec medoids(k);\n\tsize_t start;\n\tprintf(\"Initializing random center\\n\");\n\tif(seeds.n_elem > k)\n\t\tthrow std::runtime_error(\"kmeans++ called with seed count greater than k\");\n\tif(seeds.n_elem > 0)\n\t{\n\t\tfor(size_t i = 0; i < seeds.n_elem; ++i)\n\t\t\tmedoids(i) = seeds(i);\n\t\tstart = seeds.n_elem;\n\t} else {\n\t\t// randomly initialize one value\n\t\tauto init = arma::randi<arma::uvec>(1,arma::distr_param(0,dists.n_rows-1));\n\t\tmedoids(0)=init(0);\n\t\tstart = 1;\n\t}\n\tfor(size_t i = start; i < k; ++i)\n\t{\n\t\t// Dsq(x) = min_i D(x,medoid_i)^2\n\t\t// so minimize across columns to find the min value of D(x,medoids_i)\n\t\tarma::uvec assigned = medoids(arma::span(0,i-1));\n\t\tarma::vec Dsq = arma::square(arma::min(dists.cols(assigned),1));\n\n\t\tarma::vec cdf = arma::cumsum(Dsq/arma::accu(Dsq));\n\t\tarma::vec r = arma::randu<arma::vec>(1);\n\t\tarma::uvec loc = arma::find(cdf > r[0],1,\"first\");\n\t\tif(loc.is_empty())\n\t\t{\n\t\t\tmedoids[i] = dists.n_rows-1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmedoids[i] = loc[0];\n\t\t}\n\t}\n\n\treturn medoids;\n}\n// uses Voronoi iteration\nKMedNode\nselect_kmedoids(const arma::mat& dists, size_t k, const arma::uvec& seeds = arma::uvec() )\n{\n\tint N = dists.n_rows;\n\tKMedNode kmn(N, k);\n\t\n\tkmn.medoids = arma::sort(kmpp_init(dists,k,seeds));\n\tarma::uvec old_medoids = kmn.medoids;\n\tarma::uvec diff, sindex;\n\n\tbool converged = false;\n\tfor(size_t i = 0; i < MAX_ITERS && !converged; ++i)\n\t{\n\t\tprintf(\"Iteration %lu\\n\",i);\n\t\tassign_to_medoids(dists,kmn);\n\t\tupdate_medoids(dists,kmn);\n\t\tkmn.medoids = arma::sort(kmn.medoids);\n\n\t\tdiff = arma::find(old_medoids != kmn.medoids);\n\t\tif(diff.is_empty())\n\t\t\tconverged = true;\n\t\telse\n\t\t\told_medoids = kmn.medoids;\n\t}\n\n\tassign_to_medoids(dists,kmn);\n\treturn kmn;\n}\n\nstd::tuple<pyarr_u,pyarr_u>\nkmedoids(pyarr_d dists, size_t k, pyarr_u seeds = pyarr_u(0,nullptr))\n{\n\tarma::arma_rng::set_seed_random();\n\tarma::mat d = py_to_mat(dists);\n\tarma::uvec seed_medoid = py_to_uvec(seeds);\n\tseed_medoid.print(\"Seed Medoids\");\n\tKMedNode kmn = select_kmedoids(d,k, seed_medoid);\n\treturn std::make_tuple(uvec_to_py(kmn.medoids),uvec_to_py(kmn.multiplicity));\n}\n", "meta": {"hexsha": "cdeac377ef68784f3d8bf1967a8b935a761be55d", "size": 3463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/KMedoids.hpp", "max_stars_repo_name": "awlong/DiffusionMap", "max_stars_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T10:32:04.000Z", "max_issues_repo_path": "src/KMedoids.hpp", "max_issues_repo_name": "awlong/DiffusionMap", "max_issues_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_issues_repo_licenses": ["MIT"], "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/KMedoids.hpp", "max_forks_repo_name": "awlong/DiffusionMap", "max_forks_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-08-11T17:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T04:20:00.000Z", "avg_line_length": 24.3873239437, "max_line_length": 90, "alphanum_fraction": 0.6621426509, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6667430446589162}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <kv/vleq.hpp>\n\nnamespace ub = boost::numeric::ublas;\ntypedef kv::interval<double> itv;\n\nint main()\n{\n\tub::matrix<itv> a(2, 2);\n\tub::matrix<itv> b(2, 1);\n\tub::matrix<itv> x(2, 1);\n\n\ta(0, 0) = 1.; a(0, 1) = 2.;\n\ta(1, 0) = 3.; a(1, 1) = 4.;\n\n\tb(0, 0) = 5.; b(1, 0) = 6.;\n\n\tkv::vleq(a, b, x);\n\n\tstd::cout.precision(20);\n\tstd::cout << x << \"\\n\";\n\tstd::cout << prod(a, x) << \"\\n\";\n}\n", "meta": {"hexsha": "49e5bcf198b493bb46da1a0a63e74ef5b4718918", "size": 529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-vleq.cc", "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": "test/test-vleq.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "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": "test/test-vleq.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "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": 18.8928571429, "max_line_length": 41, "alphanum_fraction": 0.572778828, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6666215387517037}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\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// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <cstdlib>\n#include <iostream>\n\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/system.hpp>\n#include <boost/compute/algorithm/copy_n.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/utility/source.hpp>\n\nnamespace compute = boost::compute;\n\n// return a random float between lo and hi\nfloat rand_float(float lo, float hi)\n{\n    float x = (float) std::rand() / (float) RAND_MAX;\n\n    return (1.0f - x) * lo + x * hi;\n}\n\n// this example demostrates a black-scholes option pricing kernel.\nint main()\n{\n    // number of options\n    const int N = 4000000;\n\n    // black-scholes parameters\n    const float risk_free_rate = 0.02f;\n    const float volatility = 0.30f;\n\n    // get default device and setup context\n    compute::device gpu = compute::system::default_device();\n    compute::context context(gpu);\n    compute::command_queue queue(context, gpu);\n    std::cout << \"device: \" << gpu.name() << std::endl;\n\n    // initialize option data on host\n    std::vector<float> stock_price_data(N);\n    std::vector<float> option_strike_data(N);\n    std::vector<float> option_years_data(N);\n\n    std::srand(5347);\n    for(int i = 0; i < N; i++){\n        stock_price_data[i] = rand_float(5.0f, 30.0f);\n        option_strike_data[i] = rand_float(1.0f, 100.0f);\n        option_years_data[i] = rand_float(0.25f, 10.0f);\n    }\n\n    // create memory buffers on the device\n    compute::vector<float> call_result(N, context);\n    compute::vector<float> put_result(N, context);\n    compute::vector<float> stock_price(N, context);\n    compute::vector<float> option_strike(N, context);\n    compute::vector<float> option_years(N, context);\n\n    // copy initial values to the device\n    compute::copy_n(stock_price_data.begin(), N, stock_price.begin(), queue);\n    compute::copy_n(option_strike_data.begin(), N, option_strike.begin(), queue);\n    compute::copy_n(option_years_data.begin(), N, option_years.begin(), queue);\n\n    // source code for black-scholes program\n    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n        // approximation of the cumulative normal distribution function\n        static float cnd(float d)\n        {\n            const float A1 =  0.319381530f;\n            const float A2 = -0.356563782f;\n            const float A3 =  1.781477937f;\n            const float A4 = -1.821255978f;\n            const float A5 =  1.330274429f;\n            const float RSQRT2PI = 0.39894228040143267793994605993438f;\n\n            float K = 1.0f / (1.0f + 0.2316419f * fabs(d));\n            float cnd =\n                RSQRT2PI * exp(-0.5f * d * d) *\n                (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))));\n\n            if(d > 0){\n                cnd = 1.0f - cnd;\n            }\n\n            return cnd;\n        }\n\n        // black-scholes option pricing kernel\n        __kernel void black_scholes(__global float *call_result,\n                                    __global float *put_result,\n                                    __global const float *stock_price,\n                                    __global const float *option_strike,\n                                    __global const float *option_years,\n                                    float risk_free_rate,\n                                    float volatility)\n        {\n            const uint opt = get_global_id(0);\n\n            float S = stock_price[opt];\n            float X = option_strike[opt];\n            float T = option_years[opt];\n            float R = risk_free_rate;\n            float V = volatility;\n\n            float sqrtT = sqrt(T);\n            float d1 = (log(S / X) + (R + 0.5f * V * V) * T) / (V * sqrtT);\n            float d2 = d1 - V * sqrtT;\n            float CNDD1 = cnd(d1);\n            float CNDD2 = cnd(d2);\n\n            float expRT = exp(-R * T);\n            call_result[opt] = S * CNDD1 - X * expRT * CNDD2;\n            put_result[opt] = X * expRT * (1.0f - CNDD2) - S * (1.0f - CNDD1);\n        }\n    );\n\n    // build black-scholes program\n    compute::program program = compute::program::create_with_source(source, context);\n    program.build();\n\n    // setup black-scholes kernel\n    compute::kernel kernel(program, \"black_scholes\");\n    kernel.set_arg(0, call_result);\n    kernel.set_arg(1, put_result);\n    kernel.set_arg(2, stock_price);\n    kernel.set_arg(3, option_strike);\n    kernel.set_arg(4, option_years);\n    kernel.set_arg(5, risk_free_rate);\n    kernel.set_arg(6, volatility);\n\n    // execute black-scholes kernel\n    queue.enqueue_1d_range_kernel(kernel, 0, N, 0);\n\n    // print out the first option's put and call prices\n    float call0, put0;\n    compute::copy_n(put_result.begin(), 1, &put0, queue);\n    compute::copy_n(call_result.begin(), 1, &call0, queue);\n\n    std::cout << \"option 0 call price: \" << call0 << std::endl;\n    std::cout << \"option 0 put price: \" << put0 << std::endl;\n\n    // due to the differences in the random-number generators between linux and\n    // mac os x, we will get different \"expected\" results for this example\n#ifdef __APPLE__\n    double expected_call0 = 0.000249461;\n    double expected_put0 = 26.2798;\n#else\n    double expected_call0 = 0.0999f;\n    double expected_put0 = 43.0524f;\n#endif\n\n    // check option prices\n    if(std::abs(call0 - expected_call0) > 1e-4 || std::abs(put0 - expected_put0) > 1e-4){\n        std::cerr << \"error: option prices are wrong\" << std::endl;\n        return -1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "b4b046956b2e9cc96a0d2932e27d544f657fa192", "size": 5860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/black_scholes.cpp", "max_stars_repo_name": "skozilla/compute", "max_stars_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "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/black_scholes.cpp", "max_issues_repo_name": "skozilla/compute", "max_issues_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "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/black_scholes.cpp", "max_forks_repo_name": "skozilla/compute", "max_forks_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "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": 35.3012048193, "max_line_length": 89, "alphanum_fraction": 0.5872013652, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6665490631223572}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include <pangolin/pangolin.h>\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::NumericDiffCostFunction;\nusing ceres::CENTRAL;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\nusing Eigen::Isometry3d;\nusing Eigen::Vector3d;\nusing Eigen::Quaterniond;\nusing Eigen::Matrix3d;\nusing Eigen::cos;\nusing Eigen::sin;\nusing std::vector;\n\nconst double DT = 1.0 / 18;\n// const Eigen::Vector3d GRAVITY{0, 0, 0};\nconst Eigen::Vector3d GRAVITY{0, 0, -9.8};\n\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>);\nvoid DrawTrajectoryComparison(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>,\n                              vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>);\n\nstruct State {\n  Eigen::Vector3d pos = Eigen::Vector3d::Random(); // position \n  Eigen::Vector3d vel = Eigen::Vector3d::Random(); // velocity\n  Eigen::Vector3d aaxis = Eigen::Vector3d::Random(); // Lie Algebra (Angle axis)\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 PoseError {\n  PoseError(const Eigen::Vector3d& pos_measured,\n            const Eigen::Matrix3d& R_measured)\n    : pos_measured_(pos_measured), R_measured_(R_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_hat_ptr,\n                  const T* const aaxis_hat_ptr,\n                  T* residuals_ptr) const {   \n    Eigen::Matrix<T, 6, 1> residuals;\n    \n    Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n    Eigen::Matrix<T, 3, 1> pos_delta;\n    residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast<T>();\n\n    Eigen::Matrix<T, 3, 1> axis_hat(aaxis_hat_ptr);\n    Eigen::AngleAxisd aaxis_m(R_measured_);\n\n    T angle_hat = -axis_hat.norm();\n    axis_hat.normalize();\n    T sin_half_hat = sin(angle_hat / T(2.0));\n    T cos_half_hat = cos(angle_hat / T(2.0));\n\n    T angle_m = T(aaxis_m.angle());\n    Eigen::Matrix<T, 3, 1> axis_m = aaxis_m.axis().template cast<T>();\n    T sin_half_m = sin(angle_m / T(2.0));\n    T cos_half_m = cos(angle_m / T(2.0));\n\n    T cos_half_delta = cos_half_hat * cos_half_m - sin_half_hat * sin_half_m * axis_hat.dot(axis_m);\n    Eigen::Matrix<T, 3, 1> axis_delta = sin_half_hat * cos_half_m * axis_hat + \n                                        cos_half_hat * sin_half_m * axis_m + \n                                        sin_half_hat * sin_half_m * axis_hat.cross(axis_m);\n\n    residuals.template block<3, 1>(3, 0) = axis_delta;\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::Matrix3d& R_measured) {\n    return new AutoDiffCostFunction<PoseError, 6, 3, 3>(\n      new PoseError(pos_measured, R_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d pos_measured_;\n  const Eigen::Matrix3d R_measured_;\n};\n\nstruct PredictionError{\n  PredictionError(const Eigen::Vector3d& acc_measured,\n                  const Eigen::Vector3d& omega_measured)\n    : acc_measured_(acc_measured), omega_measured_(omega_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_b_ptr,\n                  const T* const vel_b_ptr,\n                  const T* const aaxis_b_ptr,\n                  const T* const pos_e_ptr,\n                  const T* const vel_e_ptr,\n                  const T* const aaxis_e_ptr,\n                  const T* const bias_ptr,\n                  T* residuals_ptr) const {\n    Eigen::Matrix<T, 9, 1> residuals;\n\n    // rot error\n    Eigen::Matrix<T, 3, 1> axis_b(aaxis_b_ptr);\n    Eigen::Matrix<T, 3, 1> axis_e(aaxis_e_ptr);\n    Eigen::Matrix<T, 3, 1> axis_d = omega_measured_.template cast<T>() * DT;\n\n    int choice = 1;\n    if (choice == 0) {\n      // Eigen::AngleAxis<T> aaxis_b(axis_b.norm(), axis_b.normalized());\n      // Eigen::AngleAxis<T> aaxis_e(axis_e.norm(), axis_e.normalized());\n      // Eigen::AngleAxis<T> aaxis_d(axis_d.norm(), axis_d.normalized());\n\n      // Eigen::AngleAxis<T> aaxis_delta(aaxis_d.inverse() * aaxis_b.inverse() * aaxis_e);\n      // residuals.template block<3, 1>(6, 0) = aaxis_delta.angle() * aaxis_delta.axis();\n    } else if (choice == 1) {\n    }\n    // Reference: https://math.stackexchange.com/questions/382760/composition-of-two-axis-angle-rotations\n    T angle_b = -axis_b.norm();\n    axis_b.normalize();\n    T sin_half_b = sin(angle_b / T(2));\n    T cos_half_b = cos(angle_b / T(2));\n\n    T angle_e = axis_e.norm();\n    axis_e.normalize();\n    T sin_half_e = sin(angle_e / T(2));\n    T cos_half_e = cos(angle_e / T(2));\n\n    T cos_half_be = cos_half_b * cos_half_e - sin_half_b * sin_half_e * axis_b.dot(axis_e);\n    Eigen::Matrix<T, 3, 1> axis_be = sin_half_b * cos_half_e * axis_b + cos_half_b * sin_half_e * axis_e + sin_half_b * sin_half_e * axis_b.cross(axis_e);\n    T sin_half_be = axis_be.norm();\n    axis_be.normalize();\n\n    T angle_d = -axis_d.norm();\n    axis_d.normalize();\n    T sin_half_d = sin(angle_d / T(2));\n    T cos_half_d = cos(angle_d / T(2));\n\n    T cos_half_delta = cos_half_d * cos_half_be - sin_half_d * sin_half_be * axis_d.dot(axis_be);\n    Eigen::Matrix<T, 3, 1> axis_delta = sin_half_d * cos_half_be * axis_d + cos_half_d * sin_half_be * axis_be + sin_half_d * sin_half_be * axis_d.cross(axis_be);\n\n    residuals.template block<3, 1>(6, 0) = axis_delta;\n  \n    angle_b = -angle_b;\n    T sin_b = sin(angle_b);\n    T cos_b = cos(angle_b);\n    Eigen::Matrix<T, 3, 3> axis_b_cross = Eigen::Matrix<T, 3, 3>::Zero();\n    axis_b_cross(0, 1) = -axis_b[2]; \n    axis_b_cross(1, 0) = axis_b[2]; \n    axis_b_cross(0, 2) = axis_b[1]; \n    axis_b_cross(2, 0) = -axis_b[1]; \n    axis_b_cross(1, 2) = -axis_b[0]; \n    axis_b_cross(2, 1) = axis_b[0]; \n    \n    Eigen::Matrix<T, 3, 3> rot_b = cos_b * Eigen::Matrix<T, 3, 3>::Identity() +\n                                   (T(1.0) - cos_b) * axis_b * axis_b.transpose() + \n                                   sin_b * axis_b_cross;\n    // vel error\n    const Eigen::Matrix<T, 3, 1> bias(bias_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_b(vel_b_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_e(vel_e_ptr);\n    residuals.template block<3, 1>(3, 0) = vel_b + (rot_b * (acc_measured_.template cast<T>() - bias) - GRAVITY) * DT - vel_e;\n\n    // pos error\n    const Eigen::Matrix<T, 3, 1> pos_b(pos_b_ptr);\n    const Eigen::Matrix<T, 3, 1> pos_e(pos_e_ptr);\n    residuals.template block<3, 1>(0, 0) = pos_b + vel_b * DT - pos_e;\n\n    for (int i = 0; i < 9; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& acc_measured,\n                              const Eigen::Vector3d& omega_measured) {\n    return new AutoDiffCostFunction<PredictionError, 9, 3, 3, 3, 3, 3, 3, 3>(\n      new PredictionError(acc_measured, omega_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d acc_measured_;\n  const Eigen::Vector3d omega_measured_;\n};\n\nstd::vector<Measurement, Eigen::aligned_allocator<Measurement>> readSensorData(std::string path) {\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> ret;\n\n  std::ifstream csvFile;\n  csvFile.open(path);\n\n  std::string line;\n  while(std::getline(csvFile, line)) {\n    std::vector<double> row;\n    std::cout << \"line:\" << line << std::endl;\n    std::istringstream s(line);\n    std::string field;\n    while (std::getline(s, field,',')) {\n      // std::cout << \"field: \" << field << std::endl;\n      row.push_back(std::stod(field));\n    }  \n    Eigen::Matrix3d Rwr;\n    Eigen::Quaterniond qwr;\n    Eigen::Vector3d twr;\n    Eigen::Vector3d acc;\n    Eigen::Vector3d omega; \n    Rwr << row[0], row[1], row[2],\n          row[4], row[5], row[6],\n          row[8], row[9], row[10];\n    qwr = Rwr;\n    twr << row[3], row[7], row[11];\n    acc << row[16], row[17], row[18];\n    omega << row[19], row[20], row[21];\n    std::cout << \"Rwr: \" << Rwr << std::endl;\n    std::cout << \"qwr: \" << qwr.w() << \" \" << qwr.vec() << std::endl; \n    std::cout << \"twr: \" << twr << std::endl;\n    std::cout << \"acc: \" << acc << std::endl;\n    std::cout << \"omega: \" << omega << std::endl;\n    \n    ret.push_back(Measurement(Rwr, qwr, twr, acc, omega));\n  }\n\n  return ret;\n}\n\ndouble abs_pos_error(const std::vector<State, Eigen::aligned_allocator<State>>& states,\n                     const std::vector<State, Eigen::aligned_allocator<State>>& gt_states) {\n  double err = 0.0;\n  std::cout << \"abs_pos_err by step: \";\n  for (int i = 0; i < states.size(); i++) {\n    double step_err = (states[i].pos - gt_states[i].pos).norm();\n    err += step_err;\n    std::cout << step_err << \" \";\n  }\n  std::cout << std::endl;\n  return err;\n}\n\nint main(int argc, char** argv) {\n  if(argc < 2) {\n    std::cout << \"missing arg for the csv file\" << std::endl;\n  }\n\n  std::string path = argv[1];\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> data = readSensorData(path);    \n  \n  int cnt = data.size();\n  // int cnt = 3;\n\n  // Eigen::Vector3d bias = Eigen::Vector3d::Random();\n  Eigen::Vector3d bias;\n  bias << 0, 0, 0;\n  std::vector<State, Eigen::aligned_allocator<State>> states(cnt);\n  std::vector<State, Eigen::aligned_allocator<State>> gt_states(cnt);\n  std::cout << \"states size: \" << states.size() << std::endl;\n\n  for (int i = 0; i < gt_states.size(); i++) {\n    gt_states[i].pos = data[i].twr;\n    gt_states[i].vel = Eigen::Vector3d::Zero();\n    Eigen::AngleAxisd temp(data[i].Rwr);\n    gt_states[i].aaxis = temp.angle() * temp.axis();\n  }\n\n  Problem problem;\n  \n  ceres::LossFunction* loss_function = nullptr;\n\n  for (int i = 0; i < cnt; i++) {\n    ceres::CostFunction* pos_cost_function = PoseError::Create(data[i].twr, data[i].Rwr);\n    problem.AddResidualBlock(pos_cost_function,\n                             loss_function,\n                             states[i].pos.data(),\n                             states[i].aaxis.data());\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].aaxis.data(),\n                               states[i].pos.data(),\n                               states[i].vel.data(),\n                               states[i].aaxis.data(),\n                               bias.data());\n    }\n  } \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  vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses;\n  vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> gt_poses;\n  for (int i = 0; i < cnt; i++) {\n    Eigen::AngleAxisd temp(states[i].aaxis.norm(), states[i].aaxis.normalized());\n    Isometry3d Twr(temp.matrix());\n    Twr.pretranslate(states[i].pos / 20); // manually divided by 20 to zoom out\n    poses.push_back(Twr);\n  }\n  for (int i = 0; i < cnt; i++) {\n    Eigen::AngleAxisd temp(gt_states[i].aaxis.norm(), gt_states[i].aaxis.normalized());\n    Isometry3d Twr(temp.matrix());\n    Twr.pretranslate(gt_states[i].pos / 20); // manually divided by 20 to zoom out\n    gt_poses.push_back(Twr);\n  }\n\n  double err = abs_pos_error(states, gt_states); \n  std::cout << \"absolute position error: \" << err << std::endl;\n  DrawTrajectoryComparison(poses, gt_poses);\n  return 0;\n}\n\nvoid DrawTrajectoryComparison(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses,\n                              vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> gt_poses) {\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(1.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = gt_poses[i].translation();\n      Vector3d Xw = gt_poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = gt_poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = gt_poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      glColor3f(0.0, 1.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = gt_poses[i], p2 = gt_poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}\n\n/*******************************************************************************************/\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses) {\n  // create pangolin window and plot the trajectory\n  pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n  glEnable(GL_DEPTH_TEST);\n  glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // \u753b\u6bcf\u4e2a\u4f4d\u59ff\u7684\u4e09\u4e2a\u5750\u6807\u8f74\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // \u753b\u51fa\u8fde\u7ebf\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(0.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}", "meta": {"hexsha": "10346858bcb6ca78cd73b49f6f253eaf6a982ba6", "size": 17392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/solverLieNum.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/solverLieNum.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/solverLieNum.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": 36.2333333333, "max_line_length": 162, "alphanum_fraction": 0.6001034959, "num_tokens": 5555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6665490508236882}}
{"text": "#include <mona/utility.hpp>\n#include <mona/line.hpp>\n#include <mona/targets/window.hpp>\n#include <mona/axes.hpp>\n#include <mona/axes3.hpp>\n#include <mona/colors.hpp>\n#include <mona/grid.hpp>\n#include <mona/surface_mesh.hpp>\n#include <mona/camera_steady_control.hpp>\n\n#include <armadillo>\n\n\nauto fit(const arma::fvec& x, const arma::fvec& y) -> arma::fvec\n{\n    auto xx = x - arma::mean(x);\n    auto yy = y - arma::mean(y);\n    float b = arma::sum(xx % yy) / arma::sum(xx % xx);\n    float a = arma::mean(y) - b * arma::mean(x);\n    return a + b * x;\n}\n\n\nauto random(arma::fvec x, float mean, float std)\n{\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<> dis(mean, std);\n\n    for(auto& e: x)\n    {\n        e += dis(gen);\n    }\n\n    return x;\n}\n\n\nauto get_dots()\n{\n    arma::fvec x = mona::linspace(-4, 4, 30);\n    arma::fvec y = random(x, 0, 0.9);\n    return mona::dots(x, y, mona::colors::tomato);\n}\n\nauto get_line()\n{\n    auto f = [](double x)\n    {\n        return std::sin(x);\n    };\n\n    arma::fvec x = mona::linspace(-4, 4, 50);\n    arma::fvec y = x;\n    y.transform(f);\n\n    return mona::line(x, y, mona::colors::midnight_blue);\n}\n\n\nauto f1(double x, double y)\n{\n    return (7 * x * y) / std::exp(x*x + y*y);\n};\n\nauto f2(double x, double y)\n{\n    return std::pow(x, 4) + std::pow(y, 4) - std::pow(x + y, 2);\n};\n\ntemplate <typename F>\nauto get_surface(F f)\n{\n    arma::fvec line = mona::linspace(-2, 2, 50);\n    auto [x, y] = mona::meshgrid(line, line);\n    auto z = mona::apply(f, x, y);\n\n    auto mesh = mona::surface_mesh(x, y, z);\n\n    return mesh;\n}\n\nint main()\n{\n    auto win  = mona::targets::window();\n    auto view = mona::grid(2, 2);\n    auto cam  = mona::camera();\n    auto axes_dots = mona::axes();\n    auto axes_line = mona::axes();\n    auto axes_surf1 = mona::axes3({-4, 4}, {-4, 4}, {-4, 4}, 5);\n    axes_surf1.set_camera_control(win.get_camera_control());\n\n    auto axes_surf2 = mona::axes3({-4, 4}, {-4, 4}, {-4, 4}, 5);\n    axes_surf2.set_camera_control(mona::camera_steady_control(0.2f, 0.f));\n\n    auto dots = get_dots();\n    auto line = get_line();\n    auto surf1 = get_surface(f1);\n    auto surf2 = get_surface(f2);\n\n    while (win.active())\n    {\n        axes_dots.submit(dots);\n        axes_line.submit(line);\n        axes_surf1.submit(surf1);\n        axes_surf2.submit(surf2);\n\n        view(0, 0).submit(axes_dots);\n        view(0, 1).submit(axes_surf1);\n        view(1, 0).submit(axes_surf2);\n        view(1, 1).submit(axes_line);\n\n        win.submit(view);\n        win.draw();\n    }\n}", "meta": {"hexsha": "c6398d902fdb59704ecb6aa3fd1fc2451daf70bc", "size": 2551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/grid_view/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/grid_view/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/grid_view/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9913793103, "max_line_length": 74, "alphanum_fraction": 0.5770286162, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6665329806982901}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 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\r\n// fixed_point_detail_constants.hpp implements templates\r\n// for computing fixed-point representations of the\r\n// mathematical constants sqrt(2), pi, log(2) and e.\r\n\r\n#ifndef FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n  #define FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n\r\n  #include <cmath>\r\n  #include <limits>\r\n\r\n  #include <boost/config.hpp>\r\n\r\n  namespace boost { namespace fixed_point { namespace detail {\r\n\r\n  template<typename NumericType>\r\n  NumericType calculate_root_two()\r\n  {\r\n    // Provide a very rough initial guess of 4/3, which is about\r\n    // 5 percent off of the actual value. Use small integers here\r\n    // because the underlying NumericType might have limited range.\r\n    NumericType a(NumericType(4U) / 3U);\r\n\r\n    // Estimate the zero'th term of the iteration with [1 / (2 * result)],\r\n    // giving [1 / (2 * (4/3))] = 3/8.\r\n    using std::ldexp;\r\n    NumericType vi(ldexp(NumericType(3U), -3));\r\n\r\n    // Compute the square root of x using coupled Newton iteration.\r\n    // We begin with an estimate of 1 binary digit of precision and\r\n    // double the number of binary digits of precision with each iteration.\r\n\r\n    for(std::uint_fast16_t i = UINT16_C(1); i <= std::uint_fast16_t(std::numeric_limits<NumericType>::digits); i *= UINT16_C(2))\r\n    {\r\n      // Perform the next iteration of vi.\r\n      vi += vi * (-((a * vi) * 2U) + NumericType(1U));\r\n\r\n      // Perform the next iteration of the result.\r\n      a += (vi * (-((a) * (a)) + NumericType(2U)));\r\n    }\r\n\r\n    return a;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType calculate_pi()\r\n  {\r\n    using std::fabs;\r\n    using std::ldexp;\r\n    using std::sqrt;\r\n\r\n    // Use a quadratically converging Gauss-AGM method to compute pi.\r\n\r\n    NumericType val_pi;\r\n\r\n    NumericType a (1U);\r\n    NumericType bB(ldexp(NumericType(1U), -1));\r\n    NumericType s (bB);\r\n    NumericType t (ldexp(NumericType(3U), -3));\r\n\r\n    // This loop is designed for computing a maximum of a few million\r\n    // decimal digits of pi. The number of digits roughly doubles\r\n    // with each iteration of the loop. After 20 iterations,\r\n    // the precision is about 2.8 million decimal digits.\r\n    // We are, however, not using that many digits in this\r\n    // application --- rarely more than a few thousand at most.\r\n\r\n    const NumericType tolerance = ldexp(NumericType(1U), -int((long(std::numeric_limits<NumericType>::digits) * 3L) / 4L));\r\n\r\n    for(std::uint_least8_t k = UINT8_C(1); k < UINT8_C(32); ++k)\r\n    {\r\n      // Perform the iteration steps of the Gauss AGM.\r\n\r\n      a      += sqrt(bB);\r\n      a      /= 2U;\r\n      val_pi  = (a * a);\r\n      bB      = (val_pi - t) * 2U;\r\n\r\n      const NumericType iterate_term((bB - val_pi) * (UINT32_C(1) << k));\r\n\r\n      s += iterate_term;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (k > UINT8_C(4));\r\n\r\n      if((minimum_number_of_iterations_is_complete) && (fabs(iterate_term) <= tolerance))\r\n      {\r\n        break;\r\n      }\r\n\r\n      t = (val_pi + bB) / 4U;\r\n    }\r\n\r\n    val_pi += bB;\r\n    val_pi /= s;\r\n\r\n    return val_pi;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType calculate_ln_two()\r\n  {\r\n    using std::fabs;\r\n    using std::ldexp;\r\n    using std::sqrt;\r\n\r\n    // Use a quadratically converging Gauss-AGM method for computing log(2).\r\n\r\n    // Choose m > (N * 1.661), where N is the number of decimal digits requested.\r\n    BOOST_CONSTEXPR_OR_CONST int m((long(std::numeric_limits<NumericType>::digits10) * 17L) / 10L);\r\n\r\n    // Set a0 = 1.\r\n    // Set b0 = 4 / (2^m) = 1 / 2^(m - 2).\r\n    NumericType ak(1);\r\n\r\n    NumericType bk(ldexp(NumericType(1), -(m - 2)));\r\n\r\n    const NumericType tolerance = ldexp(NumericType(1U), -int((long(std::numeric_limits<NumericType>::digits) * 3L) / 4L));\r\n\r\n    for(std::uint_least8_t k = UINT8_C(0); k < UINT8_C(32); ++k)\r\n    {\r\n      const NumericType a(ak);\r\n\r\n      ak += bk;\r\n      ak /= 2U;\r\n\r\n      bk = sqrt(bk * a);\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (k > UINT8_C(4));\r\n\r\n      if((minimum_number_of_iterations_is_complete) && (fabs(ak - bk) <= tolerance))\r\n      {\r\n        break;\r\n      }\r\n    }\r\n\r\n    // The iteration is now finished. Compute ln2 = pi / [AGM(1, 4 / 2^m) * 2m].\r\n    // Note that the result of the AGM iteration is [ak = bk = AGM(...)].\r\n    const NumericType val_ln_two = calculate_pi<NumericType>() / (ak * (2U * m));\r\n\r\n    return val_ln_two;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType calculate_e()\r\n  {\r\n    using std::fabs;\r\n\r\n    NumericType term(1U);\r\n    NumericType sum (2U);\r\n\r\n    BOOST_CONSTEXPR_OR_CONST std::uint32_t maximum_number_of_iterations = UINT32_C(10000);\r\n\r\n    // Perform the Taylor series expansion of Euler's constant, e = exp(1).\r\n    for(std::uint32_t n = UINT32_C(2); n < maximum_number_of_iterations; ++n)\r\n    {\r\n      term /= n;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (n > UINT32_C(4));\r\n\r\n      if(   (minimum_number_of_iterations_is_complete)\r\n         && (fabs(term) <= std::numeric_limits<NumericType>::epsilon()))\r\n      {\r\n        break;\r\n      }\r\n\r\n      sum += term;\r\n    }\r\n\r\n    return sum;\r\n  }\r\n  } } } // namespace boost::fixed_point::detail\r\n\r\n#endif // FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n", "meta": {"hexsha": "673359d2e296e8a902a82051385cfb86a4bdebfb", "size": 5549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "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": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "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": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "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": 30.8277777778, "max_line_length": 129, "alphanum_fraction": 0.6136240764, "num_tokens": 1492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.666532977263737}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n#include <base/init.hpp>\n#include \"fft/shift.hpp\"\n\nusing namespace std;\n\ntypedef Eigen::ArrayXXd array_t;\n\ntypedef Eigen::ArrayXd array1_t;\n\nvoid test_rowwise()\n{\n  int n = 6;\n  array1_t x = array1_t::LinSpaced(n, -n / 2, n / 2 - (n + 1) % 2);\n  //  cout << x << \"\\n\";\n  array_t X(n, 10);\n  X.colwise() = x;\n  // --------------------------------------------------\n  // test rowwise shift\n  array1_t y = array1_t::LinSpaced(n, -n / 2, n / 2 - (n + 1) % 2);\n\n  array_t Y(10, n);\n  Y.rowwise() = y.transpose();\n\n  cout << \"---------- Y ----------\"\n       << \"\\n\";\n  cout << Y << \"\\n\";\n\n  cout << \"---------- ifftshift(Y) ----------\"\n       << \"\\n\";\n  array_t iY = array_t::Zero(Y.rows(), Y.cols());\n  ifftshift(iY, Y, 1);\n  cout << iY << \"\\n\\n\";\n\n  cout << \"---------- fftshift(ifftshift(Y))  ----------\"\n       << \"\\n\";\n  array_t Y2 = array_t::Zero(Y.rows(), Y.cols());\n  fftshift(Y2, iY, 1);\n  cout << Y2 << \"\\n\\n\";\n}\n\nvoid test_colwise()\n{\n  int n = 6;\n  array1_t x = array1_t::LinSpaced(n, -n / 2, n / 2 - (n + 1) % 2);\n  cout << x << \"\\n\";\n  array_t X(n, 10);\n  X.colwise() = x;\n  // --------------------------------------------------\n  // test colwise shift\n  cout << \"---------- X ----------\"\n       << \"\\n\";\n  cout << X << \"\\n\";\n\n  cout << \"---------- ifftshift(X) ----------\"\n       << \"\\n\";\n  array_t iX = array_t::Zero(X.rows(), X.cols());\n  ifftshift(iX, X, 0);\n  cout << iX << \"\\n\\n\";\n\n  cout << \"---------- fftshift(ifftshift(X))  ----------\"\n       << \"\\n\";\n  array_t X2 = array_t::Zero(X.rows(), X.cols());\n  fftshift(X2, iX, 0);\n  cout << X2 << \"\\n\\n\";\n}\n\nvoid test2d()\n{\n  // test shift in both directions\n  int nx = 6;\n  int ny = 4;\n\n  array_t XX(ny, nx);\n  XX.setZero();\n  int posx_max = nx / 2;\n  int posy_max = ny / 2;\n\n  XX.block(0, 0, posy_max, posx_max) = array_t::Ones(posy_max, posx_max);\n  XX.block(posy_max, 0, ny - posy_max, nx) = 2 * array_t::Ones(ny - posy_max, nx);\n  XX.block(0, posx_max, posy_max, nx - posx_max) = 3 * array_t::Ones(posy_max, nx - posx_max);\n  XX.block(posy_max, posx_max, ny - posy_max, nx - posx_max) =\n      4 * array_t::Ones(ny - posy_max, nx - posx_max);\n\n  cout << \"---------- XX ----------\"\n       << \"\\n\";\n  cout << XX << endl;\n\n  cout << \"---------- fftshift(XX) ----------\"\n       << \"\\n\";\n  array_t YY(ny, nx);\n  YY.setZero();\n  fftshift(YY, XX);\n  cout << YY << \"\\n\";\n\n  cout << \"---------- ifftshift(fftshift(XX)) ----------\"\n       << \"\\n\";\n  array_t XX2(ny, nx);\n  XX2.setZero();\n  ifftshift(XX2, YY);\n  cout << XX2 << \"\\n\";\n}\n\nvoid test2d_v2()\n{\n  // test shift in both directions\n  int nx = 6;\n  int ny = 4;\n\n  array_t XX(ny, nx);\n  array_t YY(ny, nx);\n  XX.setZero();\n  YY.setZero();\n  int posx_max = nx / 2;\n  int posy_max = ny / 2;\n\n  XX = Eigen::ArrayXd::LinSpaced(nx, -posx_max, posx_max - 1).transpose().replicate(ny, 1);\n  YY = Eigen::ArrayXd::LinSpaced(ny, -posy_max, posy_max - 1).replicate(1, nx);\n\n  cout << \"---------- ifftshift(fftshift(XX)) ----------\"\n       << \"\\n\";\n  array_t XXt(ny, nx);\n  XXt.setZero();\n  fftshift(XXt, XX);\n  array_t XX2(ny, nx);\n  ifftshift(XX2, XXt);\n  {\n    double diff = (XX2 - XX).abs().sum();\n    cout << \"diff= \" << diff << endl;\n  }\n\n  cout << \"---------- ifftshift(fftshift(YY)) ----------\"\n       << \"\\n\";\n  array_t YYt(ny, nx);\n  YYt.setZero();\n  fftshift(YYt, YY);\n  array_t YY2(ny, nx);\n  ifftshift(YY2, YYt);\n  {\n    double diff = (YY2 - YY).abs().sum();\n    cout << \"diff= \" << diff << endl;\n  }\n}\n\nint main(int argc, char *argv[])\n{\n  SOURCE_INFO();\n\n  cout << \"---------- test rowwise ----------\"\n       << \"\\n\";\n  test_rowwise();\n\n  cout << \"---------- test colwise ----------\"\n       << \"\\n\";\n  test_colwise();\n\n  cout << \"---------- test 2d ----------\"\n       << \"\\n\";\n  test2d_v2();\n\n  return 0;\n}\n", "meta": {"hexsha": "4e3efa5145951759c942990ee8df0834abb9b674", "size": 3766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_fftshift.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_fftshift.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_fftshift.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 22.8242424242, "max_line_length": 94, "alphanum_fraction": 0.4758364312, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6665132571537417}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix2i m = Matrix2i::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is the transpose of m:\" << endl << m.transpose() << endl;\ncout << \"Here is the coefficient (1,0) in the transpose of m:\" << endl\n     << m.transpose()(1,0) << endl;\ncout << \"Let us overwrite this coefficient with the value 0.\" << endl;\nm.transpose()(1,0) = 0;\ncout << \"Now the matrix m is:\" << endl << m << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "fa8e5145b7a2b725d937cd973af0c0521fd5a9b0", "size": 634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_transpose.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_transpose.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_transpose.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 24.3846153846, "max_line_length": 71, "alphanum_fraction": 0.6451104101, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.6664644915807434}}
{"text": "/*=============================================================================\n\nMPHYG0022CW1: CW1, 2019: Linear Regression.\n\nCopyright (c) University College London (UCL). All rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.\n\nSee LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"mphyNormalEquationSolverStrategy.h\"\n#include \"vectorPairTypes.h\"\n#include <memory>\n#include <iostream>\n#include <math.h>\n#include <Eigen/StdVector>\n#include <Eigen/Dense>\n#include <map>\n\n\nnamespace mphy {\n\npairdd normSolver::FitData(vecPairdd data){\n\t/* \n\tFinds optimal theta using the Normal Equation. \n\ttheta_best = inv(X^T . X) . X^T . y, where:\n\n\tdata:\t\ta vector of pairs (x, y)\n\tX:\t\t\ta 2xnumData matrix of (1, x0; 1, x1; 1, x2...)\n\t */\n\t\n\tEigen::Matrix<double, Eigen::Dynamic, 2> xdata; \n\tEigen::VectorXd ydata, theta_best; \n\n\txdata = copyXtoEigen(data);\n\tydata = copyYtoEigen(data);\n\t\n\ttheta_best = ((xdata.transpose()*xdata).inverse())*xdata.transpose()*ydata;\n\t\n\n\treturn pairdd(theta_best(0), theta_best(1));\n}\n\n} // end namespace mphy", "meta": {"hexsha": "c8bfaada1f11a7a8c7779a30c63e4d31c551b2bd", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_stars_repo_name": "DylanScotney/MPHY0022CW1", "max_stars_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "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": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_issues_repo_name": "DylanScotney/MPHY0022CW1", "max_issues_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_forks_repo_name": "DylanScotney/MPHY0022CW1", "max_forks_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "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.5833333333, "max_line_length": 79, "alphanum_fraction": 0.6294788274, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6664165339883676}}
{"text": "// Eigen lib tutorial -- Array class and coefficient-wise operations\n// Source:\n// http://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(void)\n{\n    // Accessing values inside an Array\n    ArrayXXf m(2,2);\n\n    // assign some value coefficient by coefficient\n    m(0,0) = 1.0; m(0,1) = 2.0;\n    m(1,0) = 3.0; m(1,1) = m(0,1) + m(1,0);\n\n    // print values to standard output\n    std::cout << m << '\\n' << std::endl;\n\n    // using the comma-initializer is also allowed\n    m << 1.0, 3.0,\n         5.0, 7.0;\n    std::cout << m  << std::endl;\n\n    // Array addition and subtraction\n    ArrayXXf a(3,3);\n    ArrayXXf b(3,3);\n    a << 1,2,3,\n         4,5,6,\n         7,8,9;\n    b << 1,2,3,\n         1,2,3,\n         1,2,3;\n\n    // Adding two arrays\n    std::cout << \"a + b = \" << '\\n' << a + b << std::endl;\n\n    // Subtracting a scalar from an array\n    std::cout << \"a - 2 = \" << '\\n' << a -2 << std::endl;\n\n\n    // Array multiplication\n    ArrayXXf c(2,2);\n    ArrayXXf d(2,2);\n    c << 1,2,\n         3,4;\n    d << 5,6,\n         7,8;\n    std::cout << \"c * d = \" << '\\n' << c * d << std::endl;\n\n    // Converting b/w array and matrix expressions\n    MatrixXf u(2,2);\n    MatrixXf v(2,2);\n    MatrixXf result(2,2);\n\n    u << 1,2,\n         3,4;\n    v << 5,6,\n         7,8;\n\n    result = u * v;\n    std::cout << \"-- Matrix u * v: --\\n\" << result << '\\n' << std::endl;\n\n    result = u.array() * v.array();\n    std::cout << \"-- Array u * v: --\\n\" << result << '\\n' << std::endl;\n\n    result = u.cwiseProduct(v);\n    std::cout << \"-- With cwiseProduct: --\\n\" << result << '\\n' << std::endl;\n\n    result = u.array() + 4;\n    std::cout << \"-- Array u + 4: --\\n\" << result << '\\n' << std::endl;\n\n    result = (u.array() + 4).matrix() * u;\n    std::cout << \"-- Combination 1: --\" << std::endl << result << std::endl << std::endl;\n    result = (u.array() * v.array()).matrix() * u;\n    std::cout << \"-- Combination 2: --\" << std::endl << result << std::endl << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "3047aa69acd8b2a4fe50edb57ed716f435a28f17", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex5.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "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/Eigen_practice/eigen_ex5.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "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_practice/eigen_ex5.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 25.4197530864, "max_line_length": 89, "alphanum_fraction": 0.4934434191, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6664032147357991}}
{"text": "#ifdef SPARSE\n#include \"fast_mass_springs_precomputation_sparse.h\"\n#include \"fast_mass_springs_step_sparse.h\"\n#else\n#include \"fast_mass_springs_precomputation_dense.h\"\n#include \"fast_mass_springs_step_dense.h\"\n#endif\n#include \"read_json.h\"\n#include <igl/get_seconds.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Sparse>\n\n\nint main(int argc, char * argv[])\n{\n  Eigen::MatrixXd V,VT;\n  Eigen::MatrixXi F,FT,E;\n  double k;\n  Eigen::VectorXd m;\n  Eigen::VectorXi b;\n  Eigen::MatrixXd bc;\n  Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> R,G,B;\n  if(!read_json(argv[1],V,F,E,k,m,b,bc,VT,FT,R,G,B))\n  {\n    std::cerr<<\"Error: Failed to load \"<<argv[1]<<std::endl;\n    return EXIT_FAILURE;\n  }\n\n  const double delta_t = 1.0/30.0;\n  Eigen::VectorXd r;\n#ifdef SPARSE\n  Eigen::SparseMatrix<double> M,A,C;\n  Eigen::SimplicialLLT <Eigen::SparseMatrix<double > > prefactorization;\n  if(!fast_mass_springs_precomputation_sparse(\n    V,E,k,m,b,delta_t,r,M,A,C,prefactorization))\n  {\n    std::cerr<<\"precomputation failed.\"<<std::endl;\n  }\n#else\n  Eigen::MatrixXd M,A,C;\n  Eigen::LLT<Eigen::MatrixXd> prefactorization;\n  if(!fast_mass_springs_precomputation_dense(\n    V,E,k,m,b,delta_t,r,M,A,C,prefactorization))\n  {\n    std::cerr<<\"precomputation failed.\"<<std::endl;\n  }\n#endif\n\n  // Point colors\n  Eigen::MatrixXd CM = Eigen::MatrixXd::Zero(V.rows(),V.cols());\n  const Eigen::RowVector3d silver(0.8,0.8,0.8);\n  for(int i = 0;i<b.rows();i++) { CM.row(b(i)) = silver; }\n\n  int graph_id,mesh_id;\n  igl::opengl::glfw::Viewer viewer;\n  std::cout<<R\"(\n  [space]  (turn off animation and) step forward one time step\n  A,a  toggle animation \n  L,l  show/hide edges (springs) and verties (point masses)\n  R,r  reset to rest configuration\n  W,w  toggle horizontal wind\n)\";\n\n  // Initial conditions\n  const Eigen::MatrixXd U0 = V;\n  const Eigen::MatrixXd Udot0 = Eigen::MatrixXd::Zero(V.rows(),V.cols());\n\n  Eigen::MatrixXd U = U0;\n  Eigen::MatrixXd Uprev = U0 - delta_t*Udot0;\n\n  const auto update = [&]()\n  {\n    viewer.data_list[mesh_id].set_vertices(U);\n    viewer.data_list[mesh_id].compute_normals();\n    viewer.data_list[graph_id].set_points(U,CM);\n    viewer.data_list[graph_id].set_edges(U,E,Eigen::RowVector3d(0,0,0));\n  };\n  bool first = true;\n  bool wind = false;\n  const double bbd = (V.colwise().maxCoeff()-V.colwise().minCoeff()).norm();\n  const auto step = [&]()\n  {\n    Eigen::MatrixXd fext = Eigen::MatrixXd::Zero(V.rows(),V.cols());\n    // gravity\n    fext.col(1).setConstant(-9.8);\n    if(wind)\n    {\n      for(int i = 0;i<V.rows();i++)\n      {\n        const double x = U(i,0)/bbd;\n        const double phi = x+igl::get_seconds();\n        fext(i,0) = 3.0+3.0*0.5*(1.0+cos(5.*phi));\n        fext(i,2) = 2.0*0.5*(sin(phi));\n        fext(i,1) += 1.0*(1.0+cos(0.3+phi));\n      }\n    }\n    const Eigen::MatrixXd U_stash = U;\n#ifdef SPARSE\n    fast_mass_springs_step_sparse(\n        V,E,k,b,delta_t,fext,\n        r,M,A,C,prefactorization,\n        Uprev,U_stash,\n        U);\n#else\n    fast_mass_springs_step_dense(\n        V,E,k,b,delta_t,fext,\n        r,M,A,C,prefactorization,\n        Uprev,U_stash,\n        U);\n#endif\n    Uprev = U_stash;\n    update();\n  };\n  viewer.callback_pre_draw = [&](igl::opengl::glfw::Viewer &)->bool\n  {\n    if(viewer.core().is_animating)\n    {\n      if(!first)\n      {\n        step();\n      }\n      first = false;\n    }\n    return false;\n  };\n\n  viewer.callback_key_pressed = [&](\n    igl::opengl::glfw::Viewer & v,\n    unsigned char key,\n    int /*modifier*/\n    )->bool\n  {\n    switch(key)\n    {\n      default:\n        return false;\n      case ' ':\n        viewer.core().is_animating = false;\n        step();\n        return true;\n      case 'L':\n      case 'l':\n        viewer.data_list[0].is_visible ^= 1;\n        return true;\n      case 'W':\n      case 'w':\n        wind ^= 1;\n        return true;\n      case 'R':\n      case 'r':\n        first = true;\n        U = U0;\n        Uprev = U0 - delta_t*Udot0;\n        update();\n        return true;\n    }\n  };\n\n  graph_id = viewer.selected_data_index;\n  viewer.data_list[graph_id].set_points(V,CM);\n  viewer.data_list[graph_id].set_edges(V,E,Eigen::RowVector3d(0,0,0));\n  viewer.append_mesh();\n  mesh_id = viewer.selected_data_index;\n\n  viewer.data_list[mesh_id].set_mesh(V,F);\n  viewer.data_list[mesh_id].set_face_based(true);\n  if(R.size() > 0 && VT.rows()>0 && FT.rows() >0)\n  {\n    viewer.data_list[mesh_id].set_uv(VT,FT);\n    viewer.data_list[mesh_id].set_texture(R,G,B);\n    viewer.data_list[mesh_id].set_colors(Eigen::RowVector3d(1,1,1));\n    viewer.data_list[mesh_id].show_texture = true;\n    viewer.data_list[mesh_id].set_face_based(false);\n  }\n  viewer.data_list[mesh_id].show_lines = false;\n  viewer.core().is_animating = false;\n\n  viewer.launch_init(true,false);\n  viewer.data().meshgl.init();\n  // Ooof. All this to turn on double-sided lighting...\n  igl::opengl::destroy_shader_program(viewer.data().meshgl.shader_mesh);\n  {\n    std::string mesh_vertex_shader_string =\nR\"(#version 150\n  uniform mat4 view;\n  uniform mat4 proj;\n  uniform mat4 normal_matrix;\n  in vec3 position;\n  in vec3 normal;\n  out vec3 position_eye;\n  out vec3 normal_eye;\n  in vec4 Ka;\n  in vec4 Kd;\n  in vec4 Ks;\n  in vec2 texcoord;\n  out vec2 texcoordi;\n  out vec4 Kai;\n  out vec4 Kdi;\n  out vec4 Ksi;\n\n  void main()\n  {\n    position_eye = vec3 (view * vec4 (position, 1.0));\n    normal_eye = vec3 (normal_matrix * vec4 (normal, 0.0));\n    normal_eye = normalize(normal_eye);\n    gl_Position = proj * vec4 (position_eye, 1.0); //proj * view * vec4(position, 1.0);\"\n    Kai = Ka;\n    Kdi = Kd;\n    Ksi = Ks;\n    texcoordi = texcoord;\n  }\n)\";\n\n    std::string mesh_fragment_shader_string =\nR\"(#version 150\n  uniform mat4 view;\n  uniform mat4 proj;\n  uniform vec4 fixed_color;\n  in vec3 position_eye;\n  in vec3 normal_eye;\n  uniform vec3 light_position_eye;\n  vec3 Ls = vec3 (1, 1, 1);\n  vec3 Ld = vec3 (1, 1, 1);\n  vec3 La = vec3 (1, 1, 1);\n  in vec4 Ksi;\n  in vec4 Kdi;\n  in vec4 Kai;\n  in vec2 texcoordi;\n  uniform sampler2D tex;\n  uniform float specular_exponent;\n  uniform float lighting_factor;\n  uniform float texture_factor;\n  out vec4 outColor;\n  void main()\n  {\n    vec3 Ia = La * vec3(Kai);    // ambient intensity\n\n    vec3 vector_to_light_eye = light_position_eye - position_eye;\n    vec3 direction_to_light_eye = normalize (vector_to_light_eye);\n    float dot_prod = dot (direction_to_light_eye, normalize(normal_eye));\n    float clamped_dot_prod = abs(dot_prod);\n    vec3 Id = Ld * vec3(Kdi) * clamped_dot_prod;    // Diffuse intensity\n\n    vec3 reflection_eye = reflect (-direction_to_light_eye, normalize(normal_eye));\n    vec3 surface_to_viewer_eye = normalize (-position_eye);\n    float dot_prod_specular = dot (reflection_eye, surface_to_viewer_eye);\n    dot_prod_specular = float(abs(dot_prod)==dot_prod) * max (dot_prod_specular, 0.0);\n    float specular_factor = pow (dot_prod_specular, specular_exponent);\n    vec3 Kfi = 0.5*vec3(Ksi);\n    vec3 Lf = Ls;\n    float fresnel_exponent = 2*specular_exponent;\n    float fresnel_factor = 0;\n    {\n      float NE = max( 0., dot( normalize(normal_eye), surface_to_viewer_eye));\n      fresnel_factor = pow (max(sqrt(1. - NE*NE),0.0), fresnel_exponent);\n    }\n    vec3 Is = Ls * vec3(Ksi) * specular_factor;    // specular intensity\n    vec3 If = Lf * vec3(Kfi) * fresnel_factor;     // fresnel intensity\n    vec4 color = vec4(lighting_factor * (If + Is + Id) + Ia + (1.0-lighting_factor) * vec3(Kdi),(Kai.a+Ksi.a+Kdi.a)/3);\n    outColor = mix(vec4(1,1,1,1), texture(tex, texcoordi), texture_factor) * color;\n    if (fixed_color != vec4(0.0)) outColor = fixed_color;\n  }\n)\";\n\n    igl::opengl::create_shader_program(\n      mesh_vertex_shader_string,\n      mesh_fragment_shader_string,\n      {},\n      viewer.data().meshgl.shader_mesh);\n  }\n  viewer.launch_rendering(true);\n  viewer.launch_shut();\n}\n", "meta": {"hexsha": "67cb7bf82d8019ca898182153285cb4e8c059ed6", "size": 7834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ericpko/computer-graphics-mass-spring-systems", "max_stars_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_stars_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-mass-spring-systems", "max_issues_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_issues_repo_licenses": ["MIT"], "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": "ericpko/computer-graphics-mass-spring-systems", "max_forks_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_forks_repo_licenses": ["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.5912408759, "max_line_length": 119, "alphanum_fraction": 0.6467960174, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6664031993521593}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    testGaussianISAM.cpp\n * @brief   Unit tests for GaussianISAM\n * @author  Michael Kaess\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/GaussianBayesTree.h>\n#include <gtsam/linear/GaussianBayesNet.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/GaussianDensity.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/geometry/Rot2.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign/std/list.hpp> // for operator +=\nusing namespace boost::assign;\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace example;\n\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\n// Some numbers that should be consistent among all smoother tests\n\nstatic double sigmax1 = 0.786153, /*sigmax2 = 1.0/1.47292,*/ sigmax3 = 0.671512, sigmax4 =\n    0.669534 /*, sigmax5 = sigmax3, sigmax6 = sigmax2*/, sigmax7 = sigmax1;\n\nstatic const double tol = 1e-4;\n\n/* ************************************************************************* *\n Bayes tree for smoother with \"natural\" ordering:\nC1 x6 x7\nC2   x5 : x6\nC3     x4 : x5\nC4       x3 : x4\nC5         x2 : x3\nC6           x1 : x2\n**************************************************************************** */\nTEST( GaussianBayesTree, linear_smoother_shortcuts )\n{\n  // Create smoother with 7 nodes\n  GaussianFactorGraph smoother = createSmoother(7);\n\n  GaussianBayesTree bayesTree = *smoother.eliminateMultifrontal();\n\n  // Create the Bayes tree\n  LONGS_EQUAL(6, (long)bayesTree.size());\n\n  // Check the conditional P(Root|Root)\n  GaussianBayesNet empty;\n  GaussianBayesTree::sharedClique R = bayesTree.roots().front();\n  GaussianBayesNet actual1 = R->shortcut(R);\n  EXPECT(assert_equal(empty,actual1,tol));\n\n  // Check the conditional P(C2|Root)\n  GaussianBayesTree::sharedClique C2 = bayesTree[X(5)];\n  GaussianBayesNet actual2 = C2->shortcut(R);\n  EXPECT(assert_equal(empty,actual2,tol));\n\n  // Check the conditional P(C3|Root)\n  double sigma3 = 0.61808;\n  Matrix A56 = (Matrix(2,2) << -0.382022,0.,0.,-0.382022).finished();\n  GaussianBayesNet expected3;\n  expected3 += GaussianConditional(X(5), Z_2x1, I_2x2/sigma3, X(6), A56/sigma3);\n  GaussianBayesTree::sharedClique C3 = bayesTree[X(4)];\n  GaussianBayesNet actual3 = C3->shortcut(R);\n  EXPECT(assert_equal(expected3,actual3,tol));\n\n  // Check the conditional P(C4|Root)\n  double sigma4 = 0.661968;\n  Matrix A46 = (Matrix(2,2) << -0.146067,0.,0.,-0.146067).finished();\n  GaussianBayesNet expected4;\n  expected4 += GaussianConditional(X(4), Z_2x1, I_2x2/sigma4, X(6), A46/sigma4);\n  GaussianBayesTree::sharedClique C4 = bayesTree[X(3)];\n  GaussianBayesNet actual4 = C4->shortcut(R);\n  EXPECT(assert_equal(expected4,actual4,tol));\n}\n\n/* ************************************************************************* *\n Bayes tree for smoother with \"nested dissection\" ordering:\n\n   Node[x1] P(x1 | x2)\n   Node[x3] P(x3 | x2 x4)\n   Node[x5] P(x5 | x4 x6)\n   Node[x7] P(x7 | x6)\n   Node[x2] P(x2 | x4)\n   Node[x6] P(x6 | x4)\n   Node[x4] P(x4)\n\n becomes\n\n   C1     x5 x6 x4\n   C2      x3 x2 : x4\n   C3        x1 : x2\n   C4      x7 : x6\n\n************************************************************************* */\nTEST( GaussianBayesTree, balanced_smoother_marginals )\n{\n  // Create smoother with 7 nodes\n  GaussianFactorGraph smoother = createSmoother(7);\n\n  // Create the Bayes tree\n  Ordering ordering;\n  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n  GaussianBayesTree bayesTree = *smoother.eliminateMultifrontal(ordering);\n\n  VectorValues actualSolution = bayesTree.optimize();\n  VectorValues expectedSolution = VectorValues::Zero(actualSolution);\n  EXPECT(assert_equal(expectedSolution,actualSolution,tol));\n\n  LONGS_EQUAL(4, (long)bayesTree.size());\n\n  double tol=1e-5;\n\n  // Check marginal on x1\n  JacobianFactor expected1 = GaussianDensity::FromMeanAndStddev(X(1), Z_2x1, sigmax1);\n  JacobianFactor actual1 = *bayesTree.marginalFactor(X(1));\n  Matrix expectedCovarianceX1 = I_2x2 * (sigmax1 * sigmax1);\n  Matrix actualCovarianceX1;\n  GaussianFactor::shared_ptr m = bayesTree.marginalFactor(X(1), EliminateCholesky);\n  actualCovarianceX1 = bayesTree.marginalFactor(X(1), EliminateCholesky)->information().inverse();\n  EXPECT(assert_equal(expectedCovarianceX1, actualCovarianceX1, tol));\n  EXPECT(assert_equal(expected1,actual1,tol));\n\n  // Check marginal on x2\n  double sigx2 = 0.68712938; // FIXME: this should be corrected analytically\n  JacobianFactor expected2 = GaussianDensity::FromMeanAndStddev(X(2), Z_2x1, sigx2);\n  JacobianFactor actual2 = *bayesTree.marginalFactor(X(2));\n  EXPECT(assert_equal(expected2,actual2,tol));\n\n  // Check marginal on x3\n  JacobianFactor expected3 = GaussianDensity::FromMeanAndStddev(X(3), Z_2x1, sigmax3);\n  JacobianFactor actual3 = *bayesTree.marginalFactor(X(3));\n  EXPECT(assert_equal(expected3,actual3,tol));\n\n  // Check marginal on x4\n  JacobianFactor expected4 = GaussianDensity::FromMeanAndStddev(X(4), Z_2x1, sigmax4);\n  JacobianFactor actual4 = *bayesTree.marginalFactor(X(4));\n  EXPECT(assert_equal(expected4,actual4,tol));\n\n  // Check marginal on x7 (should be equal to x1)\n  JacobianFactor expected7 = GaussianDensity::FromMeanAndStddev(X(7), Z_2x1, sigmax7);\n  JacobianFactor actual7 = *bayesTree.marginalFactor(X(7));\n  EXPECT(assert_equal(expected7,actual7,tol));\n}\n\n/* ************************************************************************* */\nTEST( GaussianBayesTree, balanced_smoother_shortcuts )\n{\n  // Create smoother with 7 nodes\n  GaussianFactorGraph smoother = createSmoother(7);\n\n  // Create the Bayes tree\n  Ordering ordering;\n  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n  GaussianBayesTree bayesTree = *smoother.eliminateMultifrontal(ordering);\n\n  // Check the conditional P(Root|Root)\n  GaussianBayesNet empty;\n  GaussianBayesTree::sharedClique R = bayesTree.roots().front();\n  GaussianBayesNet actual1 = R->shortcut(R);\n  EXPECT(assert_equal(empty,actual1,tol));\n\n  // Check the conditional P(C2|Root)\n  GaussianBayesTree::sharedClique C2 = bayesTree[X(3)];\n  GaussianBayesNet actual2 = C2->shortcut(R);\n  EXPECT(assert_equal(empty,actual2,tol));\n\n  // Check the conditional P(C3|Root), which should be equal to P(x2|x4)\n  /** TODO: Note for multifrontal conditional:\n   * p_x2_x4 is now an element conditional of the multifrontal conditional bayesTree[ordering[X(2)]]->conditional()\n   * We don't know yet how to take it out.\n   */\n//  GaussianConditional::shared_ptr p_x2_x4 = bayesTree[ordering[X(2)]]->conditional();\n//  p_x2_x4->print(\"Conditional p_x2_x4: \");\n//  GaussianBayesNet expected3(p_x2_x4);\n//  GaussianISAM::sharedClique C3 = isamTree[ordering[X(1)]];\n//  GaussianBayesNet actual3 = GaussianISAM::shortcut(C3,R);\n//  EXPECT(assert_equal(expected3,actual3,tol));\n}\n\n///* ************************************************************************* */\n//TEST( BayesTree, balanced_smoother_clique_marginals )\n//{\n//  // Create smoother with 7 nodes\n//  Ordering ordering;\n//  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n//  GaussianFactorGraph smoother = createSmoother(7, ordering).first;\n//\n//  // Create the Bayes tree\n//  GaussianBayesNet chordalBayesNet = *GaussianSequentialSolver(smoother).eliminate();\n//  GaussianISAM bayesTree(chordalBayesNet);\n//\n//  // Check the clique marginal P(C3)\n//  double sigmax2_alt = 1/1.45533; // THIS NEEDS TO BE CHECKED!\n//  GaussianBayesNet expected = simpleGaussian(ordering[X(2)],Z_2x1,sigmax2_alt);\n//  push_front(expected,ordering[X(1)], Z_2x1, eye(2)*sqrt(2), ordering[X(2)], -eye(2)*sqrt(2)/2, ones(2));\n//  GaussianISAM::sharedClique R = bayesTree.root(), C3 = bayesTree[ordering[X(1)]];\n//  GaussianFactorGraph marginal = C3->marginal(R);\n//  GaussianVariableIndex varIndex(marginal);\n//  Permutation toFront(Permutation::PullToFront(C3->keys(), varIndex.size()));\n//  Permutation toFrontInverse(*toFront.inverse());\n//  varIndex.permute(toFront);\n//  for(const GaussianFactor::shared_ptr& factor: marginal) {\n//    factor->permuteWithInverse(toFrontInverse); }\n//  GaussianBayesNet actual = *inference::EliminateUntil(marginal, C3->keys().size(), varIndex);\n//  actual.permuteWithInverse(toFront);\n//  EXPECT(assert_equal(expected,actual,tol));\n//}\n\n/* ************************************************************************* */\nTEST( GaussianBayesTree, balanced_smoother_joint )\n{\n  // Create smoother with 7 nodes\n  Ordering ordering;\n  ordering += X(1),X(3),X(5),X(7),X(2),X(6),X(4);\n  GaussianFactorGraph smoother = createSmoother(7);\n\n  // Create the Bayes tree, expected to look like:\n  //   x5 x6 x4\n  //     x3 x2 : x4\n  //       x1 : x2\n  //     x7 : x6\n  GaussianBayesTree bayesTree = *smoother.eliminateMultifrontal(ordering);\n\n  // Conditional density elements reused by both tests\n  const Matrix I = I_2x2, A = -0.00429185*I;\n\n  // Check the joint density P(x1,x7) factored as P(x1|x7)P(x7)\n  GaussianBayesNet expected1 = list_of\n    // Why does the sign get flipped on the prior?\n    (GaussianConditional(X(1), Z_2x1, I/sigmax7, X(7), A/sigmax7))\n    (GaussianConditional(X(7), Z_2x1, -1*I/sigmax7));\n  GaussianBayesNet actual1 = *bayesTree.jointBayesNet(X(1),X(7));\n  EXPECT(assert_equal(expected1, actual1, tol));\n\n  //  // Check the joint density P(x7,x1) factored as P(x7|x1)P(x1)\n  //  GaussianBayesNet expected2;\n  //  GaussianConditional::shared_ptr\n  //      parent2(new GaussianConditional(X(1), Z_2x1, -1*I/sigmax1, ones(2)));\n  //    expected2.push_front(parent2);\n  //  push_front(expected2,X(7), Z_2x1, I/sigmax1, X(1), A/sigmax1, sigma);\n  //  GaussianBayesNet actual2 = *bayesTree.jointBayesNet(X(7),X(1));\n  //  EXPECT(assert_equal(expected2,actual2,tol));\n\n  // Check the joint density P(x1,x4), i.e. with a root variable\n  double sig14 = 0.784465;\n  Matrix A14 = -0.0769231*I;\n  GaussianBayesNet expected3 = list_of\n    (GaussianConditional(X(1), Z_2x1, I/sig14, X(4), A14/sig14))\n    (GaussianConditional(X(4), Z_2x1, I/sigmax4));\n  GaussianBayesNet actual3 = *bayesTree.jointBayesNet(X(1),X(4));\n  EXPECT(assert_equal(expected3,actual3,tol));\n\n  //  // Check the joint density P(x4,x1), i.e. with a root variable, factored the other way\n  //  GaussianBayesNet expected4;\n  //  GaussianConditional::shared_ptr\n  //      parent4(new GaussianConditional(X(1), Z_2x1, -1.0*I/sigmax1, ones(2)));\n  //    expected4.push_front(parent4);\n  //  double sig41 = 0.668096;\n  //  Matrix A41 = -0.055794*I;\n  //  push_front(expected4,X(4), Z_2x1, I/sig41, X(1), A41/sig41, sigma);\n  //  GaussianBayesNet actual4 = *bayesTree.jointBayesNet(X(4),X(1));\n  //  EXPECT(assert_equal(expected4,actual4,tol));\n}\n\n/* ************************************************************************* */\nTEST(GaussianBayesTree, shortcut_overlapping_separator)\n{\n  // Test computing shortcuts when the separator overlaps.  This previously\n  // would have highlighted a problem where information was duplicated.\n\n  // Create factor graph:\n  // f(1,2,5)\n  // f(3,4,5)\n  // f(5,6)\n  // f(6,7)\n  GaussianFactorGraph fg;\n  noiseModel::Diagonal::shared_ptr model = noiseModel::Unit::Create(1);\n  fg.add(1, (Matrix(1, 1) <<  1.0).finished(), 3, (Matrix(1, 1) <<  2.0).finished(), 5, (Matrix(1, 1) <<  3.0).finished(), (Vector(1) << 4.0).finished(), model);\n  fg.add(1, (Matrix(1, 1) <<  5.0).finished(), (Vector(1) << 6.0).finished(), model);\n  fg.add(2, (Matrix(1, 1) <<  7.0).finished(), 4, (Matrix(1, 1) <<  8.0).finished(), 5, (Matrix(1, 1) <<  9.0).finished(), (Vector(1) << 10.0).finished(), model);\n  fg.add(2, (Matrix(1, 1) <<  11.0).finished(), (Vector(1) << 12.0).finished(), model);\n  fg.add(5, (Matrix(1, 1) <<  13.0).finished(), 6, (Matrix(1, 1) <<  14.0).finished(), (Vector(1) << 15.0).finished(), model);\n  fg.add(6, (Matrix(1, 1) <<  17.0).finished(), 7, (Matrix(1, 1) <<  18.0).finished(), (Vector(1) << 19.0).finished(), model);\n  fg.add(7, (Matrix(1, 1) <<  20.0).finished(), (Vector(1) << 21.0).finished(), model);\n\n  // Eliminate into BayesTree\n  // c(6,7)\n  // c(5|6)\n  //   c(1,2|5)\n  //   c(3,4|5)\n  Ordering ordering(fg.keys());\n  GaussianBayesTree bt = *fg.eliminateMultifrontal(ordering); // eliminate in increasing key order, fg.keys() is sorted.\n\n  GaussianFactorGraph joint = *bt.joint(1,2, EliminateQR);\n\n  Matrix expectedJointJ = (Matrix(2,3) <<\n    5, 0, 6,\n    0, -11, -12\n    ).finished();\n  Matrix actualJointJ = joint.augmentedJacobian();\n\n  EXPECT(assert_equal(expectedJointJ, actualJointJ));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr);}\n/* ************************************************************************* */\n", "meta": {"hexsha": "8b2aa3ae7f9c681f5e7cf25c766219a96b4c31de", "size": 13068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testGaussianBayesTreeB.cpp", "max_stars_repo_name": "alexhagiopol/GTSAM", "max_stars_repo_head_hexsha": "c397fac199d0202c7abb1cd8e6005731658f56e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2018-04-23T02:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T14:41:03.000Z", "max_issues_repo_path": "trunk/tests/testGaussianBayesTreeB.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-02T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T03:04:04.000Z", "max_forks_repo_path": "trunk/tests/testGaussianBayesTreeB.cpp", "max_forks_repo_name": "shaolinbit/PPP-BayesTree", "max_forks_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T05:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:51:18.000Z", "avg_line_length": 39.8414634146, "max_line_length": 162, "alphanum_fraction": 0.6437098255, "num_tokens": 4037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6664031902896174}}
{"text": "//(XTX)-1XTY\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <string>\n#include <vector>\n#include <core/engine.hpp>\n#include \"io/input/hdfs_line_inputformat.hpp\"\n#include \"boost/tokenizer.hpp\"\ntypedef std::vector<double> fvec;\ntypedef std::vector<std::vector<double>> matrix;\n\n\n\nclass PIObject {\n   public:\n    typedef int KeyT;\n    int key;\n\n    explicit PIObject(KeyT key) { this->key = key; }\n\n    const int& id() const { return key; }\n};\n\nstd::string vec_to_str(fvec v) {\n    std::string str(\"\");\n    for (auto& x : v) {\n        str += std::to_string(x);\n        str += \" \";\n    }\n    return str;\n}\n\n\nfvec& operator+= (fvec& va, const fvec& vb) {\n\n    int n = va.size();\n    for (int i=0; i < n; i++) va[i] += vb[i];\n    return va;\n}\nmatrix& operator+= (matrix& ma, const matrix& mb) {\n\n    int m = ma.size();\n    int n = ma[0].size();\n    for (int i=0; i < m; i++)\n      for (int j=0; j< n; j++)\n        ma[i][j] += mb[i][j];\n    return ma;\n}\n\n\n\nnamespace ublas = boost::numeric::ublas;\n/* Matrix inversion routine.\n   Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool InvertMatrix (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {\n\n typedef ublas::permutation_matrix<std::size_t> pmatrix;\n // create a working copy of the input\n ublas::matrix<T> A(input);\n // create a permutation matrix for the LU-factorization\n pmatrix pm(A.size1());\n // perform LU-factorization\n int res = lu_factorize(A,pm);\n       if( res != 0 ) return false;\n // create identity matrix of \"inverse\"\n inverse.assign(ublas::identity_matrix<T>(A.size1()));\n // backsubstitute to get the inverse\n lu_substitute(A, pm, inverse);\n return true;\n}\n\n\nbool MatrixInversion(const matrix& input, matrix& output){\n  int n=input.size();\n  ublas::matrix<double> input2 (n,n);\n  ublas::matrix<double> output2 (n,n);\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      input2(i,j)=input[i][j];\n    }\n  }\n\n  InvertMatrix(input2,output2);\n\n\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      output[i][j]=output2(i,j);\n    }\n  }\n}\n\nvoid MatrixVectormultiplication(const matrix& A,const fvec& B,fvec& output){\n  int m=A.size();\n  int n=A[0].size();\n  for(int i=0;i<m;i++){\n    for(int j=0;j<n;j++){\n      output[i]+=A[i][j]*B[j];\n    }\n  }\n\n\n}\n\n\nvoid linear_regression() {\n  husky::io::HDFSLineInputFormat infmt;\n  infmt.set_input(husky::Context::get_param(\"input\"));\n  husky::ObjList<PIObject> pi_list;\n  std::vector<fvec> X;\n  std::vector<double> y;\n\n  auto parse_wc = [&](boost::string_ref& chunk) {\n      if (chunk.size() == 0)\n          return;\n      fvec here;\n      boost::char_separator<char> sep(\" \\t\");\n      boost::tokenizer<boost::char_separator<char>> tok(chunk, sep);\n\n      for (auto& w : tok) {\n          here.push_back(std::stod(w));\n      }\n      y.push_back(here.back());\n      here.pop_back();\n      // The intercept term\n      here.push_back(1.0);\n      X.push_back(here);\n\n  };\n\n  husky::load(infmt, parse_wc);\n\n  std::cout << \"helloworld\" << std::endl;\n\n\n  auto& ch1 =husky::ChannelFactory::create_push_combined_channel<matrix, husky::SumCombiner<matrix>>(pi_list, pi_list);\n  auto& ch2 =husky::ChannelFactory::create_push_combined_channel<fvec, husky::SumCombiner<fvec>>(pi_list, pi_list);\n  std::cout << \"helloworld\" << std::endl;\n  int dimension=0;\n  if (X.size()>0)\n    dimension=X[0].size();\n  std::cout << \"dimension: \"<<dimension<<\" numberofexamples\"<<X.size() << std::endl;\n  matrix A(dimension, fvec(dimension));\n  for(int i=0;i<X.size();i++){\n    fvec now=X[i];\n    for(int a=0;a<dimension;a++){\n      for(int b=0;b<dimension;b++){\n        A[a][b]+=now[a]*now[b];\n      }\n    }\n\n  }\n  std::cout << \"helloworld2\" << std::endl;\n  if(dimension!=0)\n    ch1.push(A,0);\n  std::cout << \"helloworld3\" << std::endl;\n  fvec B(dimension);\n  for(int i=0;i<X.size();i++){\n    fvec now=X[i];\n    for(int a=0;a<dimension;a++){\n        B[a]+=now[a]*y[i];\n    }\n  }\n  if(dimension!=0)\n    ch2.push(B,0);\n\n\n  ch1.flush();\n  ch2.flush();\n  list_execute(pi_list, [&ch1,&ch2](PIObject& obj) {\n      matrix XTX = ch1.get(obj);\n\n      fvec XTy=ch2.get(obj);\n\n      int dimension=XTX.size();\n      matrix IA(dimension,fvec(dimension));\n      MatrixInversion(XTX,IA);\n      fvec output(dimension,0.0);\n      MatrixVectormultiplication(IA,XTy,output);\n      husky::base::log_msg(vec_to_str(output));\n  });\n\n\n\n\n\n\n}\n\nint main(int argc, char** argv) {\n    std::vector<std::string> args;\n    args.push_back(\"hdfs_namenode\");\n    args.push_back(\"hdfs_namenode_port\");\n    args.push_back(\"input\");\n\n    if (husky::init_with_args(argc, argv, args)) {\n        husky::run_job(linear_regression);\n        return 0;\n    }\n    return 1;\n}\n", "meta": {"hexsha": "8f4e5eada018b43ba4af807d4a75f0fc1d482276", "size": 4868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/linear_regression_closed_form.cpp", "max_stars_repo_name": "Christina-hshi/Boosting-with-Husky", "max_stars_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T02:10:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-23T02:10:10.000Z", "max_issues_repo_path": "examples/linear_regression_closed_form.cpp", "max_issues_repo_name": "Christina-hshi/Boosting-with-Husky", "max_issues_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "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": "examples/linear_regression_closed_form.cpp", "max_forks_repo_name": "Christina-hshi/Boosting-with-Husky", "max_forks_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "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.5169082126, "max_line_length": 119, "alphanum_fraction": 0.6138044371, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632936392131, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6663980738627275}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\ntemplate <class Matrix>\nvoid kron(const Matrix & A, const Matrix & B, Matrix & C)\n{\t\n\t/*int n=A.cols();\n\tint m=A.rows();*/\n\tC= Matrix(A.rows()*B.rows(),A.cols()*B.cols());\n\tfor (int i=0;i<A.rows();++i){\n\t\tfor (int j=0;j<A.cols();++j){\n\t\t\tC.block(i*B.rows(),j*B.cols(),B.rows(),B.cols())=A(i,j)*B;\n\t\t}\n\t}\n\t// TODO\n}\n", "meta": {"hexsha": "52f3c962b92200d2de501c3e644403e3b89b0309", "size": 377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS2/kron.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/PS2/kron.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/PS2/kron.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": 20.9444444444, "max_line_length": 61, "alphanum_fraction": 0.5676392573, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6662124815509355}}
{"text": "//####### Test module for Quantum Synchrotron tables ###########################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/quantum_sync/tables\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <vector>\n#include <algorithm>\n#include <array>\n\n#include \"quantum_sync_engine_tables.hpp\"\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-3;\nconst double double_small = 1e-20;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-2;\nconst float float_small = 1e-10;\n\n\nusing namespace picsar::multi_physics::phys::quantum_sync;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\ntemplate <typename T>\nT constexpr small()\n{\n    if(std::is_same<T,float>::value)\n        return float_small;\n    else\n        return double_small;\n}\n\nconst double chi_min = 0.001;\nconst double chi_max = 1000;\nconst int how_many = 500;\nconst int how_many_frac = 500;\nconst double frac_min = 1e-12;\n\ntemplate <typename RealType, typename VectorType>\nauto get_table()\n{\n    const auto params =\n        dndt_lookup_table_params<RealType>{\n            static_cast<RealType>(chi_min),\n            static_cast<RealType>(chi_max), how_many};\n\n    return dndt_lookup_table<RealType, VectorType>{params};\n}\n\ntemplate <typename RealType, typename VectorType>\nauto get_em_table()\n{\n    const auto params =\n        photon_emission_lookup_table_params<RealType>{\n            static_cast<RealType>(chi_min),\n            static_cast<RealType>(chi_max),\n            static_cast<RealType>(frac_min),\n            how_many, how_many_frac};\n\n    return photon_emission_lookup_table<RealType, VectorType>{params};\n}\n\n\n\n// ------------- Tests --------------\n\ntemplate <typename RealType, typename VectorType>\nvoid check_dndt_table()\n{\n    auto table = get_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table.is_init(),false);\n\n    VectorType coords = table.get_all_coordinates();\n\n    BOOST_CHECK_EQUAL(coords.size(),how_many);\n\n    const RealType log_chi_min = log(chi_min);\n    const RealType log_chi_max = log(chi_max);\n\n     for (int i = 0 ; i < static_cast<int>(coords.size()); ++i){\n         auto res = coords[i];\n         auto expected = static_cast<RealType>(\n             exp(log_chi_min + i*(log_chi_max-log_chi_min)/(how_many-1)));\n         BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>());\n     }\n\n    auto vals = VectorType{coords};\n\n    const RealType alpha = 3.0;\n\n    std::transform(coords.begin(), coords.end(), vals.begin(),\n        [=](RealType x){return alpha*x;});\n\n    bool result = table.set_all_vals(vals);\n    BOOST_CHECK_EQUAL(result,true);\n    BOOST_CHECK_EQUAL(table.is_init(),true);\n\n    auto table_2 = get_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table_2 == table, false);\n    BOOST_CHECK_EQUAL(table == table, true);\n    BOOST_CHECK_EQUAL(table_2 == table_2, true);\n\n    const RealType xo0 = chi_min*0.1;\n    const RealType xo1 = chi_max*10;\n    const RealType x0 = chi_min;\n    const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min;\n    const RealType x2 = chi_max;\n\n    const RealType ye_ext_o0 = alpha*chi_min;\n    const RealType ye_ext_o1 = alpha*chi_max;\n    const RealType ye0 = alpha*x0;\n    const RealType ye1 = alpha*x1;\n    const RealType ye2 = alpha*x2;\n\n    const auto xxs = std::array<RealType, 5>\n        {xo0, x0, x1, x2, xo1};\n\n    const auto exp_ext = std::array<RealType, 5>\n        {ye_ext_o0, ye0, ye1, ye2, ye_ext_o1};\n\n    const auto is_out = std::array<bool, 5>\n        {true, false, false, false, true};\n\n    for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){\n        const RealType res = table.interp(xxs[i]);\n        bool flag_out = false;\n        const RealType res2 = table.interp(xxs[i], &flag_out);\n        BOOST_CHECK_EQUAL(flag_out, is_out[i]);\n        BOOST_CHECK_EQUAL(res, res2);\n\n        const RealType expect = exp_ext[i];\n\n        if(i != 0)\n            BOOST_CHECK_SMALL((res-expect)/expect, tolerance<RealType>());\n        else\n            BOOST_CHECK_SMALL((res-expect), tolerance<RealType>());\n    }\n\n    const auto table_view = table.get_view();\n\n    for(int i = 0 ; i < static_cast<int>(xxs.size()) ; ++i){\n        BOOST_CHECK_EQUAL(table_view.interp(xxs[i]), table.interp(xxs[i]));\n    }\n}\n\n// ***Test Quantum Synchrotron dndt table\nBOOST_AUTO_TEST_CASE( picsar_breit_wheeler_dndt_table)\n{\n    check_dndt_table<double, std::vector<double>>();\n    check_dndt_table<float, std::vector<float>>();\n}\n\n\ntemplate <typename RealType, typename VectorType>\nvoid check_dndt_table_serialization()\n{\n    const auto params =\n        dndt_lookup_table_params<RealType>{\n            static_cast<RealType>(0.1),\n            static_cast<RealType>(10.0), 3};\n\n    auto table = dndt_lookup_table<\n        RealType, VectorType>{params, {1.,2.,3.}};\n\n    auto raw_data = table.serialize();\n    auto new_table = dndt_lookup_table<\n        RealType, VectorType>{raw_data};\n\n    BOOST_CHECK_EQUAL(new_table.is_init(), true);\n    BOOST_CHECK_EQUAL(new_table == table, true);\n}\n\n// ***Test Quantum Synchrotron dndt table serialization\nBOOST_AUTO_TEST_CASE( picsar_quantum_sync_dndt_table_serialization)\n{\n    check_dndt_table_serialization<float, std::vector<float>>();\n}\n\ntemplate <typename RealType, typename VectorType>\nvoid check_photon_emission_table()\n{\n    auto table = get_em_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table.is_init(),false);\n\n    auto coords = table.get_all_coordinates();\n\n    BOOST_CHECK_EQUAL(coords.size(),how_many*how_many_frac);\n\n    const RealType log_chi_min = log(chi_min);\n    const RealType log_chi_max = log(chi_max);\n    const RealType log_frac_min = log(frac_min);\n\n     for (int i = 0 ; i < how_many*how_many_frac; ++i){\n         auto res_1 = coords[i][0];\n         auto res_2 = coords[i][1];\n         const auto ii = i/how_many_frac;\n         const auto jj = i%how_many_frac;\n         auto expected_1 = static_cast<RealType>(\n             exp(log_chi_min +ii*(log_chi_max-log_chi_min)/(how_many-1)));\n        auto expected_2 = static_cast<RealType>(\n             expected_1*exp(log_frac_min +jj*(0.0-log_frac_min)/(how_many_frac-1)));\n\n         BOOST_CHECK_SMALL((res_1-expected_1)/expected_1, tolerance<RealType>());\n         if(expected_2 != static_cast<RealType>(0.0))\n            BOOST_CHECK_SMALL((res_2-expected_2)/expected_2, tolerance<RealType>());\n        else\n            BOOST_CHECK_SMALL((res_2-expected_2), tolerance<RealType>());\n     }\n\n    auto vals = VectorType(coords.size());\n\n    auto functor = [=](std::array<RealType,2> x){\n        return static_cast<RealType>(1.0*pow(x[1]/x[0], 4.0 + log10(x[0])));};\n\n    auto inverse_functor = [=](std::array<RealType,2> x){\n            return static_cast<RealType>(1.0*pow((1-x[1]), 1.0/(4.0 + log10(x[0]))));};\n\n    std::transform(coords.begin(), coords.end(), vals.begin(),functor);\n\n    bool result = table.set_all_vals(vals);\n    BOOST_CHECK_EQUAL(result,true);\n    BOOST_CHECK_EQUAL(table.is_init(),true);\n\n\n    auto table_2 = get_em_table<RealType, VectorType>();\n    BOOST_CHECK_EQUAL(table_2 == table, false);\n    BOOST_CHECK_EQUAL(table == table, true);\n    BOOST_CHECK_EQUAL(table_2 == table_2, true);\n\n\n    const RealType xo0 = chi_min*0.1;\n    const RealType xo1 = chi_max*10;\n    const RealType x0 = chi_min;\n    const RealType x1 = (chi_max+chi_min)*0.5642 + chi_min;\n    const RealType x2 = chi_max;\n\n    const auto xxs = std::array<RealType, 5>\n        {xo0, x0, x1, x2, xo1};\n    const auto rrs = std::array<RealType, 11>\n            {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99};\n\n    for (const auto xx : xxs){\n        for (const auto rr : rrs){\n            auto res = table.interp(xx, rr);\n            auto rxx = xx;\n            if(rxx < chi_min) rxx = chi_min;\n            if(rxx > chi_max) rxx = chi_max;\n            auto expected = inverse_functor(std::array<RealType,2>{rxx, rr})*xx;\n            if(expected < small<RealType>())\n                BOOST_CHECK_SMALL((res-expected)/expected, tolerance<RealType>());\n            else\n                BOOST_CHECK_SMALL((res-expected), tolerance<RealType>());\n\n        }\n    }\n\n    const auto table_view = table.get_view();\n\n    for(auto xx : xxs){\n        for (auto r : rrs)\n            BOOST_CHECK_EQUAL(table_view.interp(xx,r ), table.interp(xx, r));\n    }\n}\n\n// ***Test Quantum Synchrotron photon emission table\nBOOST_AUTO_TEST_CASE( picsar_quantum_sync_photon_emission_table)\n{\n    check_photon_emission_table<double, std::vector<double>>();\n    check_photon_emission_table<float, std::vector<float>>();\n}\n\n\ntemplate <typename RealType, typename VectorType>\nvoid check_photon_emission_table_serialization()\n{\n    const auto params =\n        photon_emission_lookup_table_params<RealType>{\n            static_cast<RealType>(0.1),static_cast<RealType>(10.0),\n            static_cast<RealType>(1e-5), 3, 3};\n\n    auto table = photon_emission_lookup_table<\n        RealType, VectorType>{params, {1.,2.,3.,4.,5.,6.,7.,8.,9.}};\n\n    auto raw_data = table.serialize();\n    auto new_table =\n        photon_emission_lookup_table<RealType, VectorType>{raw_data};\n\n    BOOST_CHECK_EQUAL(new_table.is_init(), true);\n    BOOST_CHECK_EQUAL(new_table == table, true);\n}\n\n\n// ***Test Quantum Synchrotron photon emission table serialization\nBOOST_AUTO_TEST_CASE( picsar_quantum_sync_photon_emission_table_serialization)\n{\n    check_photon_emission_table_serialization<double, std::vector<double>>();\n    check_photon_emission_table_serialization<float, std::vector<float>>();\n}\n", "meta": {"hexsha": "d3a6e75005b64685aad14dfc2ede34675f11e47a", "size": 9738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp", "max_stars_repo_name": "LDAmorim/picsar", "max_stars_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp", "max_issues_repo_name": "LDAmorim/picsar", "max_issues_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_picsar_quantum_sync_tables.cpp", "max_forks_repo_name": "LDAmorim/picsar", "max_forks_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2115384615, "max_line_length": 87, "alphanum_fraction": 0.6649209283, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.666212479161344}}
{"text": "//\n//  common.cpp\n//  kcalg\n//\n//  Created by knightc on 2019/7/12.\n//  Copyright \u00a9 2019 knightc. All rights reserved.\n//\n\n#include <stdio.h>\n\n#include \"opentsb/math.h\"\n#include <NTL/GF2X.h>\n#include <NTL/ZZX.h>\n\nusing namespace NTL;\nusing namespace std;\n\n void lcm(ZZ& k, const ZZ& x, const ZZ& y) {\n    ZZ gcd;\n    mul(k, x, y);\n    GCD(gcd, x, y);\n    k /= gcd;\n}\n\n//\u4e00\u6b21\u6027\u8fd0\u7b97\u6c42 \u5411\u91cf\u7684 lcm/gcd\nvec_ZZ lcm_gcd_vec(const vec_ZZ& v,int typemode){\n    \n    vec_ZZ vec_out;\n    long m,n,j,i;\n    ZZ temp;\n    i=0;\n    j=0;\n\n     n= v.length();\n    m= ceil(n/2.0);//\u5411\u4e0a\u53d6\u6574\uff0c\u5fc5\u987b\u662f\u975e\u6574\u6570\uff0c\u5373 2---\u300b2.0\n      vec_out.SetLength(m);\n    switch (typemode) {\n        case 1:\n            for (i=0; i < n-1; i+=2) {\n                \n                lcm(temp,v[i],v[i+1]);\n                // cout << temp<< endl;\n                vec_out[j] = temp;\n                //cout << vec_out << endl;\n                j++;\n                // cout << j << endl;\n            }\n            // cout << i << endl;\n            if (n % 2 == 1 ) {\n                lcm( vec_out[j],v[i],ZZ(1));\n            }\n            break;\n         case 2:\n            for (i=0; i < n-1; i+=2) {\n                GCD(temp,v[i],v[i+1]);\n                // cout << temp<< endl;\n                vec_out[j] = temp;\n                //cout << vec_out << endl;\n                j++;\n                // cout << j << endl;\n            }\n            // cout << i << endl;\n            if (n % 2 == 1 ) {\n                GCD( vec_out[j],v[i],v[i-1]);\n            }\n            break;\n    }\n    return vec_out;\n}\n\n//\u6c42 n \u4e2a\u6570\u7684\u6700\u5927\u516c\u7ea6\u6570/\u6700\u5c0f\u516c\u500d\u6570\nvec_ZZ lcm_gcd_vec(const vec_ZZ& v,int typemode,long endleng){\n    \n    vec_ZZ vec_out;\n    \n    vec_out= lcm_gcd_vec(v, typemode);\n    endleng=vec_out.length();\n    \n    while (endleng != 1) {\n       vec_out= lcm_gcd_vec(vec_out, typemode);\n         endleng=vec_out.length();\n    }\n    \n    return vec_out;\n}\n\n\n\n//array can use \"for\" to assignment\uff0cbut vector can't\u3002if must\uff0ccan use vector.push_back\nvoid array_to_vec(const ZZ arr[],vec_ZZ &v,long len) {\n   // long n= v.length();\n    \n    v.SetLength(len);\n    for (int i=0; i<=len-1; i++) {\n        v[i]=arr[i];\n    }\n    //cout<<v<<endl;\n}\n\nvoid array_to_vec(const int arr[],vec_ZZ &v,long len) {\n   // long n= v.length();\n    \n    for (int i=0; i<=len-1; i++) {\n        v[i]=to_ZZ(arr[i]);\n        \n    }\n    // cout<<v<<endl;\n}\n\nvoid array2_to_mat(const vector< vector<ZZ> > arr,mat_ZZ &v){\n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=arr[i][j];\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<int> > arr,mat_ZZ &v){\n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=to_ZZ(arr[i][j]);\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<int> > arr,mat_GF2 &v){\n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=to_GF2(arr[i][j]);\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<ZZ> > arr,mat_GF2 &v){\n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=to_GF2(arr[i][j]);\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<GF2> > arr,mat_GF2 &v){\n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=arr[i][j];\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<int> > arr,mat_GF2E &v){\n    \n    \n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n//    const GF2X P(INIT_MONO,8);\n//    GF2E::init(P);\n    GF2X P;\n    SetCoeff(P, 8, 1);\n    SetCoeff(P, 4, 1);\n    SetCoeff(P, 3, 1);\n    SetCoeff(P, 1, 1);\n    SetCoeff(P, 0, 1);\n    GF2E::init(P);\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=to_GF2E(arr[i][j]);\n        }\n    }\n    \n}\n\nvoid array2_to_mat(const vector< vector<int> > arr,mat_ZZ_p &v){\n  \n    v.SetDims(arr.size(),arr[0].size());\n    \n    long m= v.NumRows();\n    long n= v.NumCols();\n    \n    ZZ_p::init(ZZ(256));\n    \n    for (int i=0;i<=m-1;i++){\n        for (int j=0; j<=n-1; j++) {\n            v[i][j]=to_ZZ_p(long(arr[i][j]));\n        }\n    }\n    \n}\n\n\n//void inv_array2_to_mat(const mat_GF2E &v, vector< vector<int> > &arr) //gf2e --> int  ?????\n\n\n//to_ZZX(vec);\u53ef\u4ee5\u628a\u4e00\u4e2a\u4e00\u7ef4\u6570\u7ec4/\u5411\u91cf \u8f6c\u4e3a\u591a\u9879\u5f0f\uff08\u7cfb\u6570\u66f4\u6362\uff09\nvoid kc_lagrange(vec_vec_ZZ_p &pointMat,vec_zz_p &coeffVec) {\n    \n}\n", "meta": {"hexsha": "6a28a08fd3a03d7d8af77d99b4736dc0ec2e2861", "size": 4569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/math/common.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/math/common.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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": "kcalg/math/common.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "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.8630136986, "max_line_length": 93, "alphanum_fraction": 0.4602757715, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6661838915755645}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"stiffness_matrix.hpp\"\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the stiffness matrix\n//! for the linear system.\n//!\n//!\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\nSparseMatrix assembleStiffnessMatrix(\n    const Eigen::MatrixXd &vertices,\n    const Eigen::MatrixXi &triangles) {\n\tSparseMatrix         A(vertices.rows(), vertices.rows());\n\tstd::vector<Triplet> triplets;\n\tconst int            numberOfElements = triangles.rows();\n\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 stiffnessMatrix;\n\t\tcomputeStiffnessMatrix(stiffnessMatrix, 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\tauto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));\n\t\t\t\ttriplets.push_back(triplet);\n\t\t\t}\n\t\t}\n\t}\n\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\n\treturn A;\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "b669e9083ef1db80162d517e2e5ace008c88d8bd", "size": 1213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/stiffness_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/stiffness_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/stiffness_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": 26.9555555556, "max_line_length": 76, "alphanum_fraction": 0.6380873866, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6661679515551763}}
{"text": "/**\n * @file   gweyl.hpp\n * @author ALIKAWA Hidehisa <alleyhide@gmail.com>\n * @date   2018/04/30\n * \n * @brief  public header file of gweyl\n * \n * Released under the MIT license\n */\n#pragma once\n\n#include <boost/rational.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//\n// our namespace \"gweyl\"\n//\nnamespace gweyl{\n\n//\n// rational numbers\n//\nusing rational=boost::rational<int>;\n\n//\n// matrix of rational numbers\n//\nusing matrix=boost::numeric::ublas::matrix<rational>;\n\n//\n// number vector\n// this is vector of mathematics (primitive linear algera)\n//\nusing NumberVector=boost::numeric::ublas::vector<rational>;\n\n//\n// we define equality of matirx and number vector\n// because boost does not define the equality\n//\nbool equal(const matrix &X, const matrix &Y);\nbool equal(const NumberVector &v, const NumberVector &w);\n\n//\n// gweyl treats simple Lie algebra types\n// in Cartan's classification\n//\nenum class Type{\n    invalid,A,B,C,D,E,F,G,\n};\n\n//\n// Coordinate system\n// There are at least two coordinates on root spaces.\n// One is simple roots, and the other is fundamental weights.\n//\nenum class Coordinate {\n    simple, fundamental,\n};\n\n//\n// trace the message\n// @param[in] msg message\n// \n//\nvoid trace(std::string& msg);\n\n///\n/// The definition of Cartan Matrix is equivalent to\n/// the definition of the root space, according to structure theory of Lie algebra,\n/// that is, Cartan matrix is the source of \"gweyl\"\n///\nmatrix CartanMatrix(Type X, unsigned n);\nmatrix InverseCartanMatrix(Type X, unsigned n);\n\nclass VectorRootSpace;\n\n//\n// class Cartan\n//  other names are RootSpace, DynkinDiagram, ..\n// fundamental class of gweyl\n//\nclass Cartan\n{\npublic:\n    explicit Cartan(Type X, unsigned n);\n    Cartan();\n    Cartan(const Cartan &rhs);\n    virtual ~Cartan();\n    Cartan& operator=(const Cartan& rhs);\n\n    //\n    // @return Cartan matrix\n    //\n    matrix CartanMatrix();\n    \n    //\n    // @return invers of Cartan matrix\n    //\n    matrix InverseCartanMatrix();\n\n    //\n    // @return the 'i'-th simple root\n    //\n    VectorRootSpace SimpleRoot(unsigned i);\n\n    //\n    // @return the 'i'-th fundamental weight\n    //\n    VectorRootSpace FundamentalWeight(unsigned i);\n\n    //\n    // @return highest root <not implemented>\n    //\n    VectorRootSpace HighestRoot();\n\n    //\n    // @return zero vector\n    //\n    VectorRootSpace Zero();\n    \n    //\n    // @return half sum of positive roots\n    //\n    VectorRootSpace Rho();\n\n    //\n    // @return positive roots\n    //\n    std::vector<VectorRootSpace> PositiveRoots();\n\n    //\n    // @return roots <not implemented>\n    //\n    std::vector<VectorRootSpace> Roots();\n\n    // getters\n    Type type();\n    Type type() const;\n    unsigned rank();\n    unsigned rank() const;\n\n    // operators\n    bool operator==(const Cartan& rhs);\n    bool operator!=(const Cartan& rhs);\n\n    \nprivate:\n    struct Impl;\n    std::unique_ptr<Impl> pImpl;\n};\n\n//\n// In gweyl, the class RootSpace, DynkinDiagram and the class Cartan are same\n//\nusing RootSpace = Cartan;\nusing DynkinDiagram = Cartan;\n\n//\n// Vector in root space\n//\nclass VectorRootSpace \n{\npublic:\n    // constructors\n    explicit VectorRootSpace(Type X, NumberVector& v, Coordinate c);\n    VectorRootSpace();\n    virtual ~VectorRootSpace();\n    VectorRootSpace(const VectorRootSpace& rhs);\n    VectorRootSpace& operator=(const VectorRootSpace& rhs);\n\n    // for debug\n    void printf();\n\n    // getters\n    NumberVector simpleCoefficients();\n    NumberVector simpleCoefficients() const;\n    NumberVector fundamentalCoefficients();\n    NumberVector fundamentalCoefficients() const;\n    Type type();\n    Type type() const;\n    unsigned rank();\n    unsigned rank() const;\n\n    // eqaulity\n    bool isInSameSpace(const VectorRootSpace& rhs);\n    bool operator==(const VectorRootSpace& rhs);\n    bool operator!=(const VectorRootSpace& rhs);\n\n    // operators\n    VectorRootSpace& operator+=(const VectorRootSpace& rhs);\n    VectorRootSpace& operator-=(const VectorRootSpace& rhs);\n    VectorRootSpace& operator*=(rational r);\n\n    // dominant integral\n    bool dominant();\n    bool integral();\n    bool isDominantIntegral();\nprivate:\n    struct Impl;\n    std::unique_ptr<Impl> pImpl;\n};\n\n//\n// operators of the class VectorRootSpace\n//\nrational InnerProduct(VectorRootSpace& v, VectorRootSpace& w);\nVectorRootSpace operator+(const VectorRootSpace& v1, const VectorRootSpace& v2);\nVectorRootSpace operator-(const VectorRootSpace& v1, const VectorRootSpace& v2);\nVectorRootSpace operator*(const VectorRootSpace& v1, const rational r);\nVectorRootSpace operator*(const rational r, const VectorRootSpace& v1);\n\n//\n// class IrreducibleRepresentation\n// \nclass IrreducibleRepresentation{\npublic:\n    //constructors\n    IrreducibleRepresentation();\n    explicit IrreducibleRepresentation(VectorRootSpace& highestweight);\n    virtual ~IrreducibleRepresentation();\n    IrreducibleRepresentation(const IrreducibleRepresentation& rhs);\n    IrreducibleRepresentation& operator=(const IrreducibleRepresentation& rhs);\n\n    //getters\n    Type type();\n    Type type() const;\n    unsigned rank();\n    unsigned rank() const;\n    VectorRootSpace highestweight();\n    VectorRootSpace highestweight() const;\n\n    //operators\n    bool operator==(const IrreducibleRepresentation& rhs);\n    bool operator!=(const IrreducibleRepresentation& rhs);\n\n    int dimension();\n    \nprivate:\n    struct Impl;\n    std::unique_ptr<Impl> pImpl;\n};\n\n\n}\n", "meta": {"hexsha": "669cb7824966fe1b33cc7d2ddd119b64251f6e7f", "size": 5502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gweyl.hpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gweyl.hpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gweyl.hpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2753036437, "max_line_length": 83, "alphanum_fraction": 0.6862958924, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6661679445174472}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::gamma::log_unnormalized_pdf         //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\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_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_GAMMA_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <cmath>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost{\nnamespace math{\n\ntemplate <class T, class P>\ninline T log_unnormalized_pdf(\n    const boost::math::gamma_distribution<T, P>& dist,\n    const T& x\n)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function\n    = \"log_unnormalized_pdf(const gamma_distribution<%1%>&, %1%)\";\n\n   T shape = dist.shape();\n   T scale = dist.scale();\n\n   T result;\n   if(false == boost::math::detail::check_gamma(\n        function, scale, shape, &result, P()))\n      return result;\n   if(false == boost::math::detail::check_gamma_x(function, x, &result, P()))\n      return result;\n\n   if(x == 0)\n   {\n      // TODO just a guess based on definition of math::pdf\n      // cast is needed by MSVC\n      return log(static_cast<T>(0));\n   }\n   static T one_ = static_cast<T>(1);\n   result = (shape - one_) * log(x) - x / scale;\n   return result;\n} // log_unnormalized_pdf\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "721586b7a4f2dbad4aa51d8ca8947d49b787af1e", "size": 1840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/log_unnormalized_pdf.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/log_unnormalized_pdf.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/gamma/log_unnormalized_pdf.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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.0740740741, "max_line_length": 91, "alphanum_fraction": 0.5777173913, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6661679371193134}}
{"text": "// g++ -O3 -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX\n\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef VECTYPE\n#define VECTYPE VectorXLd\n#endif\n\n#ifndef VECSIZE\n#define VECSIZE 1000000\n#endif\n\n#ifndef REPEAT\n#define REPEAT 1000\n#endif\n\nint main(int argc, char *argv[])\n{\n\tVECTYPE I = VECTYPE::Ones(VECSIZE);\n\tVECTYPE m(VECSIZE,1);\n\tfor(int i = 0; i < VECSIZE; i++)\n\t{\n\t\tm[i] = 0.1 * i/VECSIZE;\n\t}\n\tfor(int a = 0; a < REPEAT; a++)\n\t{\n\t\tm = VECTYPE::Ones(VECSIZE) + 0.00005 * (m.cwise().square() + m/4);\n\t}\n\tcout << m[0] << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "6a487b409d310da2eb33e542b77421203a8d8748", "size": 585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/bench/benchmarkXcwise.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/bench/benchmarkXcwise.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/bench/benchmarkXcwise.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": 16.7142857143, "max_line_length": 69, "alphanum_fraction": 0.6427350427, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6661580167451427}}
{"text": "#include <Eigen/Eigenvalues>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <common_robotics_utilities/math.hpp>\n#include <common_robotics_utilities/utility.hpp>\n\nnamespace common_robotics_utilities\n{\nnamespace math\n{\nbool Equal3d(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n  if ((v1.x() == v2.x()) && (v1.y() == v2.y()) && (v1.z() == v2.z()))\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\n\nbool Equal4d(const Eigen::Vector4d& v1, const Eigen::Vector4d& v2)\n{\n  if ((v1(0) == v2(0)) && (v1(1) == v2(1))\n      && (v1(2) == v2(2)) && (v1(3) == v2(3)))\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nbool CloseEnough(const double p1, const double p2, const double threshold)\n{\n  const double real_threshold = std::abs(threshold);\n  const double abs_delta = std::abs(p2 - p1);\n  if (abs_delta <= real_threshold)\n  {\n    return true;\n  }\n  else\n  {\n    return false;\n  }\n}\n\nbool CloseEnough(const Eigen::Vector3d& v1,\n                 const Eigen::Vector3d& v2,\n                 const double threshold)\n{\n  const double real_threshold = std::abs(threshold);\n  if (std::abs(v1.x() - v2.x()) > real_threshold)\n  {\n    return false;\n  }\n  if (std::abs(v1.y() - v2.y()) > real_threshold)\n  {\n    return false;\n  }\n  if (std::abs(v1.z() - v2.z()) > real_threshold)\n  {\n    return false;\n  }\n  return true;\n}\n\nEigen::Vector3d RotateVector(const Eigen::Quaterniond& quat,\n                             const Eigen::Vector3d& vec)\n{\n  const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n  const Eigen::Quaterniond res = quat * (temp * quat.inverse());\n  return Eigen::Vector3d(res.x(), res.y(), res.z());\n}\n\nEigen::Vector3d RotateVectorReverse(const Eigen::Quaterniond& quat,\n                                    const Eigen::Vector3d& vec)\n{\n  const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n  const Eigen::Quaterniond res = quat.inverse() * (temp * quat);\n  return Eigen::Vector3d(res.x(), res.y(), res.z());\n}\n\ndouble EnforceContinuousRevoluteBounds(const double value)\n{\n  if ((value <= -M_PI) || (value > M_PI))\n  {\n    const double remainder = std::fmod(value, 2.0 * M_PI);\n    if (remainder <= -M_PI)\n    {\n      return (remainder + (2.0 * M_PI));\n    }\n    else if (remainder > M_PI)\n    {\n      return (remainder - (2.0 * M_PI));\n    }\n    else\n    {\n      return remainder;\n    }\n  }\n  else\n  {\n    return value;\n  }\n}\n\nEigen::VectorXd SafeNormal(const Eigen::VectorXd& vec)\n{\n  if (vec.size() > 0)\n  {\n    const double norm = vec.norm();\n    if (norm > std::numeric_limits<double>::epsilon())\n    {\n      return vec / norm;\n    }\n    else\n    {\n      return Eigen::VectorXd::Zero(vec.size());\n    }\n  }\n  else\n  {\n    return Eigen::VectorXd::Zero(vec.size());\n  }\n}\n\ndouble SquaredNorm(const std::vector<double>& vec)\n{\n  double squared_norm = 0.0;\n  for (size_t idx = 0; idx < vec.size(); idx++)\n  {\n    const double element = vec[idx];\n    squared_norm += (element * element);\n  }\n  return squared_norm;\n}\n\ndouble Norm(const std::vector<double>& vec)\n{\n  return std::sqrt(SquaredNorm(vec));\n}\n\nstd::vector<double> Abs(const std::vector<double>& vec)\n{\n  std::vector<double> absed(vec.size(), 0.0);\n  for (size_t idx = 0; idx < absed.size(); idx++)\n  {\n    absed[idx] = std::abs(vec[idx]);\n  }\n  return absed;\n}\n\nstd::vector<double> Multiply(const std::vector<double>& vec,\n                             const double scalar)\n{\n  std::vector<double> multiplied(vec.size(), 0.0);\n  for (size_t idx = 0; idx < multiplied.size(); idx++)\n  {\n    const double element = vec[idx];\n    multiplied[idx] = element * scalar;\n  }\n  return multiplied;\n}\n\nstd::vector<double> Multiply(const std::vector<double>& vec1,\n                             const std::vector<double>& vec2)\n{\n  if (vec1.size() == vec2.size())\n  {\n    std::vector<double> multiplied(vec1.size(), 0.0);\n    for (size_t idx = 0; idx < multiplied.size(); idx++)\n    {\n      const double element1 = vec1[idx];\n      const double element2 = vec2[idx];\n      multiplied[idx] = element1 * element2;\n    }\n    return multiplied;\n  }\n  else\n  {\n    throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n  }\n}\n\nstd::vector<double> Divide(const std::vector<double>& vec, const double scalar)\n{\n  const double inv_scalar = 1.0 / scalar;\n  return Multiply(vec, inv_scalar);\n}\n\nstd::vector<double> Divide(const std::vector<double>& vec1,\n                           const std::vector<double>& vec2)\n{\n  if (vec1.size() == vec2.size())\n  {\n    std::vector<double> divided(vec1.size(), 0.0);\n    for (size_t idx = 0; idx < divided.size(); idx++)\n    {\n      const double element1 = vec1[idx];\n      const double element2 = vec2[idx];\n      divided[idx] = element1 / element2;\n    }\n    return divided;\n  }\n  else\n  {\n    throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n  }\n}\n\nstd::vector<double> Add(const std::vector<double>& vec, const double scalar)\n{\n  std::vector<double> added(vec.size(), 0.0);\n  for (size_t idx = 0; idx < added.size(); idx++)\n  {\n    added[idx] = vec[idx] + scalar;\n  }\n  return added;\n}\n\nstd::vector<double> Add(const std::vector<double>& vec1,\n                        const std::vector<double>& vec2)\n{\n  if (vec1.size() == vec2.size())\n  {\n    std::vector<double> added(vec1.size(), 0.0);\n    for (size_t idx = 0; idx < added.size(); idx++)\n    {\n      const double element1 = vec1[idx];\n      const double element2 = vec2[idx];\n      added[idx] = element1 + element2;\n    }\n    return added;\n  }\n  else\n  {\n    throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n  }\n}\n\nstd::vector<double> Sub(const std::vector<double>& vec, const double scalar)\n{\n  std::vector<double> subed(vec.size(), 0.0);\n  for (size_t idx = 0; idx < subed.size(); idx++)\n  {\n    subed[idx] = vec[idx] - scalar;\n  }\n  return subed;\n}\n\nstd::vector<double> Sub(const std::vector<double>& vec1,\n                        const std::vector<double>& vec2)\n{\n  if (vec1.size() == vec2.size())\n  {\n    std::vector<double> subed(vec1.size(), 0.0);\n    for (size_t idx = 0; idx < subed.size(); idx++)\n    {\n      const double element1 = vec1[idx];\n      const double element2 = vec2[idx];\n      subed[idx] = element1 - element2;\n    }\n    return subed;\n  }\n  else\n  {\n    throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n  }\n}\n\ndouble Sum(const std::vector<double>& vec)\n{\n  double sum = 0.0;\n  for (size_t idx = 0; idx < vec.size(); idx++)\n  {\n    const double element = vec[idx];\n    sum += element;\n  }\n  return sum;\n}\n\nEigen::Matrix3d Skew(const Eigen::Vector3d& vector)\n{\n  Eigen::Matrix3d skewed;\n  skewed << 0.0, -vector.z(), vector.y(),\n        vector.z(), 0.0, -vector.x(),\n        -vector.y(), vector.x(), 0.0;\n  return skewed;\n}\n\nEigen::Vector3d Unskew(const Eigen::Matrix3d& matrix)\n{\n  const Eigen::Matrix3d matrix_symetric = (matrix - matrix.transpose()) / 2.0;\n  const Eigen::Vector3d unskewed(matrix_symetric(2, 1),\n                                 matrix_symetric(0, 2),\n                                 matrix_symetric(1, 0));\n  return unskewed;\n}\n\nEigen::Matrix4d TwistHat(const Eigen::Matrix<double, 6, 1>& twist)\n{\n  const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n  const Eigen::Matrix3d hatted_rot_velocity = Skew(twist.segment<3>(3));\n  Eigen::Matrix4d hatted_twist = Eigen::Matrix4d::Zero();\n  hatted_twist.block<3, 3>(0, 0) = hatted_rot_velocity;\n  hatted_twist.block<3, 1>(0, 3) = trans_velocity;\n  return hatted_twist;\n}\n\nEigen::Matrix<double, 6, 1> TwistUnhat(const Eigen::Matrix4d& hatted_twist)\n{\n   const Eigen::Vector3d trans_velocity = hatted_twist.block<3, 1>(0, 3);\n   const Eigen::Vector3d rot_velocity = Unskew(hatted_twist.block<3, 3>(0, 0));\n   Eigen::Matrix<double, 6, 1> twist;\n   twist.segment<3>(0) = trans_velocity;\n   twist.segment<3>(3) = rot_velocity;\n   return twist;\n}\n\nEigen::Matrix<double, 6, 6> AdjointFromTransform(\n    const Eigen::Isometry3d& transform)\n{\n  const Eigen::Matrix3d rotation = transform.matrix().block<3, 3>(0, 0);\n  const Eigen::Vector3d translation = transform.matrix().block<3, 1>(0, 3);\n  const Eigen::Matrix3d translation_hat = Skew(translation);\n  // Assemble the adjoint matrix\n  Eigen::Matrix<double, 6, 6> adjoint;\n  adjoint.block<3, 3>(0, 0) = rotation;\n  adjoint.block<3, 3>(0, 3) = translation_hat * rotation;\n  adjoint.block<3, 3>(3, 0) = Eigen::Matrix3d::Zero();\n  adjoint.block<3, 3>(3, 3) = rotation;\n  return adjoint;\n}\n\nEigen::Matrix<double, 6, 1> TransformTwist(\n    const Eigen::Isometry3d& transform,\n    const Eigen::Matrix<double, 6, 1>& initial_twist)\n{\n  return (Eigen::Matrix<double, 6, 1>)(AdjointFromTransform(transform)\n                                       * initial_twist);\n}\n\nEigen::Matrix<double, 6, 1> TwistBetweenTransforms(\n    const Eigen::Isometry3d& start,\n    const Eigen::Isometry3d& end)\n{\n  const Eigen::Isometry3d t_diff = start.inverse() * end;\n  return TwistUnhat(t_diff.matrix().log());\n}\n\nEigen::Matrix3d ExpMatrixExact(const Eigen::Matrix3d& hatted_rot_velocity,\n                               const double delta_t)\n{\n  if (std::abs(Unskew(hatted_rot_velocity).norm() - 1.0) < 1e-10)\n  {\n    const Eigen::Matrix3d exp_matrix = Eigen::Matrix3d::Identity()\n      + (hatted_rot_velocity * sin(delta_t))\n      + (hatted_rot_velocity * hatted_rot_velocity * (1.0 - cos(delta_t)));\n    return exp_matrix;\n  }\n  else\n  {\n    throw std::invalid_argument(\"Invalid hatted_rot_velocity: \"\n                                \"std::abs(Unskew(hatted_rot_velocity).norm()\"\n                                \" - 1.0) >= 1e-10\");\n  }\n}\n\nEigen::Isometry3d ExpTwist(const Eigen::Matrix<double, 6, 1>& twist,\n                           const double delta_t)\n{\n  const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n  const Eigen::Vector3d rot_velocity = twist.segment<3>(3);\n  const double trans_velocity_norm = trans_velocity.norm();\n  const double rot_velocity_norm = rot_velocity.norm();\n  Eigen::Matrix4d raw_transform = Eigen::Matrix4d::Identity();\n  if (rot_velocity_norm >= 1e-100)\n  {\n    const double scaled_delta_t = delta_t * rot_velocity_norm;\n    const Eigen::Vector3d scaled_trans_velocity\n        = trans_velocity / rot_velocity_norm;\n    const Eigen::Vector3d scaled_rot_velocity\n        = rot_velocity / rot_velocity_norm;\n    const Eigen::Matrix3d rotation_displacement\n        = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n    const Eigen::Vector3d translation_displacement\n        = ((Eigen::Matrix3d::Identity() - rotation_displacement)\n           * scaled_rot_velocity.cross(scaled_trans_velocity))\n          + (scaled_rot_velocity * scaled_rot_velocity.transpose()\n             * scaled_trans_velocity * scaled_delta_t);\n    raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n    raw_transform.block<3, 1>(0, 3) = translation_displacement;\n  }\n  else\n  {\n    if ((trans_velocity_norm >= 1e-100) || (rot_velocity_norm == 0.0))\n    {\n      raw_transform.block<3, 1>(0, 3) = trans_velocity * delta_t;\n    }\n    else\n    {\n      std::cerr << \"YOU MAY ENCOUNTER NUMERICAL INSTABILITY IN EXPTWIST(...)\"\n                   \" WITH TRANS & ROT VELOCITY NORM < 1e-100 ***\" << std::endl;\n      const double scaled_delta_t = delta_t * rot_velocity_norm;\n      const Eigen::Vector3d scaled_trans_velocity\n          = trans_velocity / rot_velocity_norm;\n      const Eigen::Vector3d scaled_rot_velocity\n          = rot_velocity / rot_velocity_norm;\n      const Eigen::Matrix3d rotation_displacement\n          = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n      const Eigen::Vector3d translation_displacement\n          = ((Eigen::Matrix3d::Identity() - rotation_displacement)\n             * scaled_rot_velocity.cross(scaled_trans_velocity))\n            + (scaled_rot_velocity * scaled_rot_velocity.transpose()\n               * scaled_trans_velocity * scaled_delta_t);\n      raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n      raw_transform.block<3, 1>(0, 3) = translation_displacement;\n    }\n  }\n  Eigen::Isometry3d transform;\n  transform = raw_transform;\n  return transform;\n}\n\ndouble Interpolate(const double p1, const double p2, const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  // This is the numerically stable version,\n  // rather than  (p1 + (p2 - p1) * real_ratio)\n  return ((p1 * (1.0 - real_ratio)) + (p2 * real_ratio));\n}\n\ndouble InterpolateContinuousRevolute(const double p1,\n                                     const double p2,\n                                     const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Safety check args\n  const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n  const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n  // Interpolate\n  double interpolated = 0.0;\n  double diff = real_p2 - real_p1;\n  if (std::abs(diff) <= M_PI)\n  {\n    interpolated = real_p1 + diff * real_ratio;\n  }\n  else\n  {\n    if (diff > 0.0)\n    {\n      diff = 2.0 * M_PI - diff;\n    }\n    else\n    {\n      diff = -2.0 * M_PI - diff;\n    }\n    interpolated = real_p1 - diff * real_ratio;\n    // Input states are within bounds, so the following check is sufficient\n    if (interpolated > M_PI)\n    {\n      interpolated -= 2.0 * M_PI;\n    }\n    else\n    {\n      if (interpolated < -M_PI)\n      {\n        interpolated += 2.0 * M_PI;\n      }\n    }\n  }\n  return interpolated;\n}\n\nstd::vector<double> Interpolate(const std::vector<double>& v1,\n                                const std::vector<double>& v2,\n                                const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Safety check inputs\n  const size_t len = v1.size();\n  if (len != v2.size())\n  {\n    throw std::invalid_argument(\"Vectors v1 and v2 must be the same size\");\n  }\n  // Interpolate\n  // This is the numerically stable version,\n  // rather than  (p1 + (p2 - p1) * real_ratio)\n  std::vector<double> interped(len, 0);\n  for (size_t idx = 0; idx < len; idx++)\n  {\n    interped[idx] = ((v1[idx] * (1.0 - real_ratio)) + (v2[idx] * real_ratio));\n  }\n  return interped;\n}\n\nEigen::Quaterniond Interpolate(const Eigen::Quaterniond& q1,\n                               const Eigen::Quaterniond& q2,\n                               const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  return q1.slerp(real_ratio, q2);\n}\n\nEigen::VectorXd InterpolateXd(const Eigen::VectorXd& v1,\n                              const Eigen::VectorXd& v2,\n                              const double ratio)\n{\n  // Safety check sizes\n  if (v1.size() != v2.size())\n  {\n    throw std::invalid_argument(\"Vectors v1 and v2 must be the same size\");\n  }\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  // This is the numerically stable version,\n  // rather than  (p1 + (p2 - p1) * real_ratio)\n  return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Vector3d Interpolate3d(const Eigen::Vector3d& v1,\n                              const Eigen::Vector3d& v2,\n                              const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  // This is the numerically stable version,\n  // rather than  (p1 + (p2 - p1) * real_ratio)\n  return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Vector4d Interpolate4d(const Eigen::Vector4d& v1,\n                              const Eigen::Vector4d& v2,\n                              const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  // This is the numerically stable version,\n  // rather than  (p1 + (p2 - p1) * real_ratio)\n  return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Isometry3d Interpolate(const Eigen::Isometry3d& t1,\n                              const Eigen::Isometry3d& t2,\n                              const double ratio)\n{\n  // Safety check ratio\n  const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n  // Interpolate\n  const Eigen::Vector3d v1 = t1.translation();\n  const Eigen::Quaterniond q1(t1.rotation());\n  const Eigen::Vector3d v2 = t2.translation();\n  const Eigen::Quaterniond q2(t2.rotation());\n  const Eigen::Vector3d vint = Interpolate3d(v1, v2, real_ratio);\n  const Eigen::Quaterniond qint = Interpolate(q1, q2, real_ratio);\n  const Eigen::Isometry3d tint = ((Eigen::Translation3d)vint) * qint;\n  return tint;\n}\n\ndouble SquaredDistance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n{\n  const double xd = v2.x() - v1.x();\n  const double yd = v2.y() - v1.y();\n  return ((xd * xd) + (yd * yd));\n}\n\ndouble Distance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n{\n  return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble SquaredDistance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n  const double xd = v2.x() - v1.x();\n  const double yd = v2.y() - v1.y();\n  const double zd = v2.z() - v1.z();\n  return ((xd * xd) + (yd * yd) + (zd * zd));\n}\n\ndouble Distance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n  return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble SquaredDistance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n{\n  if (v1.size() == v2.size())\n  {\n    return (v2 - v1).squaredNorm();\n  }\n  else\n  {\n    throw std::invalid_argument(\"v1.size() != v2.size()\");\n  }\n}\n\ndouble Distance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n{\n  return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble Distance(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2)\n{\n  const double dq = std::abs((q1.w() * q2.w())\n                             + (q1.x() * q2.x())\n                             + (q1.y() * q2.y())\n                             + (q1.z() * q2.z()));\n  if (dq < (1.0 - std::numeric_limits<double>::epsilon()))\n  {\n    return std::acos(2.0 * (dq * dq) - 1.0);\n  }\n  else\n  {\n    return 0.0;\n  }\n}\n\ndouble Distance(const Eigen::Isometry3d& t1,\n                const Eigen::Isometry3d& t2,\n                const double alpha)\n{\n  const double real_alpha = utility::ClampValue(alpha, 0.0, 1.0);\n  const Eigen::Vector3d v1 = t1.translation();\n  const Eigen::Quaterniond q1(t1.rotation());\n  const Eigen::Vector3d v2 = t2.translation();\n  const Eigen::Quaterniond q2(t2.rotation());\n  const double vdist = Distance(v1, v2) * (1.0 - real_alpha);\n  const double qdist = Distance(q1, q2) * (real_alpha);\n  return vdist + qdist;\n}\n\ndouble SquaredDistance(const std::vector<double>& p1,\n                       const std::vector<double>& p2)\n{\n  if (p1.size() == p2.size())\n  {\n    double distance = 0.0;\n    for (size_t idx = 0; idx < p1.size(); idx++)\n    {\n      distance += (p2[idx] - p1[idx]) * (p2[idx] - p1[idx]);\n    }\n    return distance;\n  }\n  else\n  {\n    throw std::invalid_argument(\"p1.size() != p2.size()\");\n  }\n}\n\ndouble Distance(const std::vector<double>& p1, const std::vector<double>& p2)\n{\n  if (p1.size() == p2.size())\n  {\n    return std::sqrt(SquaredDistance(p1, p2));\n  }\n  else\n  {\n    throw std::invalid_argument(\"p1.size() != p2.size()\");\n  }\n}\n\ndouble ContinuousRevoluteSignedDistance(const double p1, const double p2)\n{\n  // Safety check args\n  const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n  const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n  const double raw_distance = real_p2 - real_p1;\n  if ((raw_distance <= -M_PI) || (raw_distance > M_PI))\n  {\n    if (raw_distance <= -M_PI)\n    {\n      return (-(2.0 * M_PI) - raw_distance);\n    }\n    else if (raw_distance > M_PI)\n    {\n      return ((2.0 * M_PI) - raw_distance);\n    }\n    else\n    {\n      return raw_distance;\n    }\n  }\n  else\n  {\n    return raw_distance;\n  }\n}\n\ndouble ContinuousRevoluteDistance(const double p1, const double p2)\n{\n  return std::abs(ContinuousRevoluteSignedDistance(p1, p2));\n}\n\ndouble AddContinuousRevoluteValues(const double start, const double change)\n{\n  return EnforceContinuousRevoluteBounds(start + change);\n}\n\ndouble GetContinuousRevoluteRange(const double start, const double end)\n{\n  const double raw_range = ContinuousRevoluteSignedDistance(start, end);\n  if (raw_range >= 0.0)\n  {\n    return raw_range;\n  }\n  else\n  {\n    return (2.0 * M_PI) + raw_range;\n  }\n}\n\nbool CheckInContinuousRevoluteRange(const double start,\n                                    const double range,\n                                    const double val)\n{\n  const double real_val = EnforceContinuousRevoluteBounds(val);\n  const double real_start = EnforceContinuousRevoluteBounds(start);\n  const double delta = ContinuousRevoluteSignedDistance(real_start, real_val);\n  if (delta >= 0.0)\n  {\n    if (delta <= range)\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n  else\n  {\n    const double real_delta = (2.0 * M_PI) + delta;\n    if (real_delta <= range)\n    {\n      return true;\n    }\n    else\n    {\n      return false;\n    }\n  }\n}\n\nbool CheckInContinuousRevoluteBounds(const double start,\n                                     const double end,\n                                     const double val)\n{\n  const double range = GetContinuousRevoluteRange(start, end);\n  return CheckInContinuousRevoluteRange(start, range, val);\n}\n\ndouble AverageStdVectorDouble(const std::vector<double>& values,\n                              const std::vector<double>& weights)\n{\n  // Get the weights\n  if (values.empty())\n  {\n    throw std::invalid_argument(\"Provided vector is empty\");\n  }\n  if ((weights.size() != values.size()) && (weights.size() != 0))\n  {\n    throw std::invalid_argument(\"Provided weights must be empty\"\n                                \" or same size to provided vector\");\n  }\n  const bool use_weights = (weights.size() != 0);\n  // Find the first element with non-zero weight\n  size_t starting_idx = 0;\n  while (starting_idx < weights.size()\n         && std::abs(weights[starting_idx]) == 0.0)\n  {\n    starting_idx++;\n  }\n  // If all weights are zero, result is undefined\n  if (starting_idx >= values.size())\n  {\n    throw std::invalid_argument(\"Provided weights are all zero\");\n  }\n  // Start the recursive definition with the base case\n  double average = values[starting_idx];\n  const double starting_weight = use_weights ? std::abs(weights[starting_idx])\n                                             : 1.0;\n  double weights_running_sum = starting_weight;\n  // Do the weighted averaging on the rest of the vectors\n  for (size_t idx = starting_idx + 1; idx < values.size(); idx++)\n  {\n    const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n    weights_running_sum += weight;\n    const double effective_weight = weight / weights_running_sum;\n    const double prev_average = average;\n    const double current = values[idx];\n    average = prev_average + (effective_weight * (current - prev_average));\n  }\n  return average;\n}\n\ndouble ComputeStdDevStdVectorDouble(const std::vector<double>& values,\n                                    const double mean)\n{\n  if (values.empty())\n  {\n    throw std::invalid_argument(\"Provided vector is empty\");\n  }\n  else if (values.size() == 1)\n  {\n    return 0.0;\n  }\n  else\n  {\n    const double inv_n_minus_1 = 1.0 / (double)(values.size() - 1);\n    double stddev_sum = 0.0;\n    for (size_t idx = 0; idx < values.size(); idx++)\n    {\n      const double delta = values[idx] - mean;\n      stddev_sum += (delta * delta);\n    }\n    return std::sqrt(stddev_sum * inv_n_minus_1);\n  }\n}\n\ndouble ComputeStdDevStdVectorDouble(const std::vector<double>& values)\n{\n  const double mean = AverageStdVectorDouble(values);\n  return ComputeStdDevStdVectorDouble(values, mean);\n}\n\ndouble AverageContinuousRevolute(const std::vector<double>& angles,\n                                 const std::vector<double>& weights)\n{\n  return AverageStdVectorDouble(angles, weights);\n}\n\nEigen::Vector3d AverageEigenVector3d(const VectorVector3d& vectors,\n                                     const std::vector<double>& weights)\n{\n  return AverageEigenVector(vectors, weights);\n}\n\nEigen::VectorXd AverageEigenVectorXd(\n    const std::vector<Eigen::VectorXd>& vectors,\n    const std::vector<double>& weights)\n{\n  return AverageEigenVector(vectors, weights);\n}\n\n// Implementation of method described in (http://stackoverflow.com/a/27410865)\n// See paper at (http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf) for more\nEigen::Quaterniond AverageEigenQuaterniond(const VectorQuaterniond& quaternions,\n                                           const std::vector<double>& weights)\n{\n  // Get the weights\n  const bool use_weights = weights.size() == quaternions.size() ? true : false;\n  if (quaternions.empty())\n  {\n    throw std::invalid_argument(\"Provided vector is empty\");\n  }\n  if ((weights.size() != quaternions.size()) && (weights.size() != 0))\n  {\n    throw std::invalid_argument(\"Provided weights must be empty\"\n                                \" or same size to provided vector\");\n  }\n  // Shortcut the process if there is only 1 quaternion\n  if (quaternions.size() == 1)\n  {\n    if (weights.size() > 0)\n    {\n      if (std::abs(weights[0]) == 0.0)\n      {\n        throw std::invalid_argument(\"Single quaternion with zero weight\");\n      }\n    }\n    return quaternions[0];\n  }\n  // Build the averaging matrix\n  Eigen::MatrixXd q_matrix(4, quaternions.size());\n  for (size_t idx = 0; idx < quaternions.size(); idx++)\n  {\n    const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n    const Eigen::Quaterniond& q = quaternions[idx];\n    q_matrix.col((ssize_t)idx) << weight * q.w(),\n                                  weight * q.x(),\n                                  weight * q.y(),\n                                  weight * q.z();\n  }\n  // Make the matrix square\n  const Eigen::Matrix<double, 4, 4> qqtranspose_matrix\n      = q_matrix * q_matrix.transpose();\n  // Compute the eigenvectors and eigenvalues of the qqtranspose matrix\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>\n      solver(qqtranspose_matrix);\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvalueType\n      eigen_values = solver.eigenvalues();\n  const Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>>::EigenvectorsType\n      eigen_vectors = solver.eigenvectors();\n  // Extract the eigenvector corresponding to the largest eigenvalue\n  double max_eigenvalue = -std::numeric_limits<double>::infinity();\n  int64_t max_eigenvector_index = -1;\n  for (size_t idx = 0; idx < 4; idx++)\n  {\n    const double current_eigenvalue = eigen_values((long)idx).real();\n    if (current_eigenvalue > max_eigenvalue)\n    {\n      max_eigenvalue = current_eigenvalue;\n      max_eigenvector_index = (int64_t)idx;\n    }\n  }\n  if (max_eigenvector_index < 0)\n  {\n    throw std::runtime_error(\"Failed to find max eigenvector\");\n  }\n  // Note that these are already normalized!\n  const Eigen::Vector4cd best_eigenvector\n      = eigen_vectors.col((long)max_eigenvector_index);\n  // Convert back into a quaternion\n  const Eigen::Quaterniond average_q(best_eigenvector(0).real(),\n                                     best_eigenvector(1).real(),\n                                     best_eigenvector(2).real(),\n                                     best_eigenvector(3).real());\n  return average_q;\n}\n\nEigen::Isometry3d AverageEigenIsometry3d(const VectorIsometry3d& transforms,\n                                         const std::vector<double>& weights)\n{\n  if (transforms.empty())\n  {\n    throw std::invalid_argument(\"Provided vector is empty\");\n  }\n  if ((weights.size() != transforms.size()) && (weights.size() != 0))\n  {\n    throw std::invalid_argument(\"Provided weights must be empty\"\n                                \" or same size to provided vector\");\n  }\n  // Shortcut the process if there is only 1 transform\n  if (transforms.size() == 1)\n  {\n    if (weights.size() > 0)\n    {\n      if (std::abs(weights[0]) == 0.0)\n      {\n        throw std::invalid_argument(\"Single transform with zero weight\");\n      }\n    }\n    return transforms[0];\n  }\n  // Extract components\n  VectorVector3d translations(transforms.size());\n  VectorQuaterniond rotations(transforms.size());\n  for (size_t idx = 0; idx < transforms.size(); idx++)\n  {\n    translations[idx] = transforms[idx].translation();\n    rotations[idx] = Eigen::Quaterniond(transforms[idx].rotation());\n  }\n  // Average\n  const Eigen::Vector3d average_translation\n      = AverageEigenVector(translations, weights);\n  const Eigen::Quaterniond average_rotation\n      = AverageEigenQuaterniond(rotations, weights);\n  // Make the average transform\n  const Eigen::Isometry3d average_transform\n      = (Eigen::Translation3d)average_translation * average_rotation;\n  return average_transform;\n}\n\ndouble WeightedDotProduct(const Eigen::VectorXd& vec1,\n                          const Eigen::VectorXd& vec2,\n                          const Eigen::VectorXd& weights)\n{\n  return vec1.cwiseProduct(weights).dot(vec2);\n}\n\ndouble WeightedSquaredNorm(const Eigen::VectorXd& vec,\n                           const Eigen::VectorXd weights)\n{\n  return WeightedDotProduct(vec, vec, weights);\n}\n\ndouble WeightedNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd& weights)\n{\n  return std::sqrt(WeightedSquaredNorm(vec, weights));\n}\n\ndouble WeightedCosineAngleBetweenVectors(const Eigen::VectorXd& vec1,\n                                         const Eigen::VectorXd& vec2,\n                                         const Eigen::VectorXd& weights)\n{\n  const double vec1_norm = WeightedNorm(vec1, weights);\n  const double vec2_norm = WeightedNorm(vec2, weights);\n  if (vec1_norm > 0 && vec2_norm > 0)\n  {\n    const double result\n        = WeightedDotProduct(vec1, vec2, weights) / (vec1_norm * vec2_norm);\n    return std::max(-1.0, std::min(result, 1.0));;\n  }\n  else\n  {\n    throw std::invalid_argument(\"One or more input vectors has zero norm\");\n  }\n}\n\ndouble WeightedAngleBetweenVectors(const Eigen::VectorXd& vec1,\n                                   const Eigen::VectorXd& vec2,\n                                   const Eigen::VectorXd& weights)\n{\n  return std::acos(WeightedCosineAngleBetweenVectors(vec1, vec2, weights));\n}\n}  // namespace math\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "ef709c034f7d5bad41fd27b43e2dec133fc65c46", "size": 30106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common_robotics_utilities/math.cpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common_robotics_utilities/math.cpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common_robotics_utilities/math.cpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5156862745, "max_line_length": 80, "alphanum_fraction": 0.6195110609, "num_tokens": 8144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6660756329316053}}
{"text": "#define BOOST_TEST_MODULE \"Testing Euclidean Functions\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Euclidean.hpp\"\n\nusing namespace genex;\n#define TOLERANCE 1e-9\n\nBOOST_AUTO_TEST_CASE( eucdist, *boost::unit_test::tolerance(TOLERANCE) )\n{\n   Euclidean d;\n\n   TimeSeries ts_1 {NULL, 0, 0, 2};\n   TimeSeries ts_2 {NULL, 0, 0, 2};\n\n   data_t a = d.dist(100.0, 110.0);\n\n   data_t first = d.init();\n   data_t second = d.reduce(first, first, 4.0, 0.0);\n   data_t third = d.reduce(second, second, 7.0, 10.0);\n   data_t c = d.norm(third, ts_1, ts_2);\n\n   d.clean(third);\n\n   BOOST_TEST( a == 100 );\n   BOOST_TEST( c == sqrt(25.0 / 2) );\n}\n", "meta": {"hexsha": "a1bf749d5b3d5e00c17f3d76bf436d19caa415ae", "size": 643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/EuclideanTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/EuclideanTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/EuclideanTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 22.1724137931, "max_line_length": 72, "alphanum_fraction": 0.6594090202, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6660756170979445}}
{"text": "#include \"slick/scene/triangulation.h\"\n#include <iostream>\n#include <Eigen/Core>\n\n#include \"slick/math/se3.h\"\n\nint test_triangulate() {\n  std::cout << \"generting 3D points...\" << std::endl;\n  std::vector<Eigen::Matrix<slick::SlickScalar, 3, 1>> v3_points(100);\n  for (size_t i = 0; i < v3_points.size(); ++i) {\n    v3_points[i].setRandom();\n    v3_points[i] *= 20.0; // scale up to value range to [-100,100]\n    if (v3_points[i][2] < 0)\n      v3_points[i][2] = -v3_points[i][2];\n    v3_points[i][2] = 17.0; // all 3D points are on the same plane\n  }\n  // generates a  3degree rotation around axis-y & 1unit translate along axis-a\n  slick::SE3 pose1;\n  Eigen::Matrix<slick::SlickScalar, 3, 1> v3(0, 3.0 * M_PI / 180.0, 0);\n  slick::SO3Group<slick::SlickScalar> so3_r(v3);\n  slick::SE3Group<slick::SlickScalar> pose2(\n      so3_r, Eigen::Matrix<slick::SlickScalar, 3, 1>(-1.0, 0.0, 0.0));\n\n  std::vector<slick::SlickScalar> norms;\n  for (int i = 0; i < v3_points.size(); ++i) {\n    Eigen::Matrix<slick::SlickScalar, 2, 1> v2_p1 = slick::project(pose1 * v3_points[i]);\n    Eigen::Matrix<slick::SlickScalar, 2, 1> v2_p2 = slick::project(pose2 * v3_points[i]);\n    std::pair<Eigen::Matrix<slick::SlickScalar, 3, 1>, slick::SlickScalar> res =\n        slick::triangulate(v2_p1, v2_p2, pose1, pose2);\n\n    std::cout << \"norm(real-estimate):\" << (v3_points[i] - res.first).norm()\n              << std::endl;\n    norms.push_back((v3_points[i] - res.first).norm());\n  }\n\n  slick::SlickScalar sum_norm(0.0);\n  for (std::vector<slick::SlickScalar>::iterator j = norms.begin();\n       j != norms.end(); ++j)\n    sum_norm += *j;\n  std::cout << \"sum_norm:\"\n            << \"mean_norm:\" << sum_norm / norms.size() << std::endl;\n  if (sum_norm / norms.size() > 1.e-9)\n    return -1;\n  return 1;\n}\n\nint main(int argc, char **argv) {\n  bool ok = true, final_ok = true;\n  ok = test_triangulate();\n  std::cout << \"test_triangulate():\" << ok << std::endl;\n  final_ok &= ok;\n\n  return (final_ok) ? 0 : -1;\n}\n", "meta": {"hexsha": "1dabdfc5dbdc27547357db1dadad9c10be106a97", "size": 1983, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/test_scene_triangulation.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/test_scene_triangulation.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "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": "slick/test/test_scene_triangulation.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "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.0545454545, "max_line_length": 89, "alphanum_fraction": 0.6157337368, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6660653399501508}}
{"text": "/*\n * test_EMA.cpp\n *\n *  Created on: 2013-4-10\n *      Author: fasiondog\n */\n\n#ifdef TEST_ALL_IN_ONE\n    #include <boost/test/unit_test.hpp>\n#else\n    #define BOOST_TEST_MODULE test_hikyuu_indicator_suite\n    #include <boost/test/unit_test.hpp>\n#endif\n\n#include <hikyuu/indicator/crt/EMA.h>\n#include <hikyuu/indicator/crt/PRICELIST.h>\n#include <hikyuu/indicator/crt/MA.h>\n\nusing namespace hku;\n\n/**\n * @defgroup test_indicator_EMA test_indicator_EMA\n * @ingroup test_hikyuu_indicator_suite\n * @{\n */\n\n/** @par \u68c0\u6d4b\u70b9 */\nBOOST_AUTO_TEST_CASE( test_EMA ) {\n    PriceList d;\n    for (int i = 0; i < 30; ++i) {\n        d.push_back(i);\n    }\n\n    /** @arg n = 1 */\n    Indicator data = PRICELIST(d);\n    Indicator ema = EMA(data, 1);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(ema[10] == 10.0);\n    BOOST_CHECK(ema[29] == 29.0);\n\n    /** @arg n = 2 */\n    ema = EMA(data, 2);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(std::fabs(ema[1] - 0.66667) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[2] - 1.55556) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[3] - 2.51852) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[4] - 3.50617) < 0.0001);\n\n    /** @arg n = 10 */\n    ema = EMA(data, 10);\n    BOOST_CHECK(ema.discard() == 0);\n    BOOST_CHECK(ema.size() == 30);\n    BOOST_CHECK(ema[0] == 0.0);\n    BOOST_CHECK(std::fabs(ema[1] - 0.18182) < 0.0001);\n    BOOST_CHECK(std::fabs(ema[2] - 0.51240) < 0.0001);\n\n#if 0 //\u7531\u4e8e\u4fee\u6539\u4e86SMA\u8ba1\u7b97\u8fc7\u7a0b\uff0cMA\u7684\u629b\u5f03\u6570\u91cf\u4e3a\u96f6\uff0c\u4e0b\u9762\u7684\u6d4b\u8bd5\u7528\u4f8b\u5931\u6548\n    /** @arg \u5f85\u8ba1\u7b97\u7684\u6570\u636e\u5b58\u5728\u975e\u96f6\u7684discard */\n    Indicator ma = MA(data, 2);\n    ema = EMA(ma, 2);\n    BOOST_CHECK(ma.discard() == 1);\n    BOOST_CHECK(ema.discard() == 1);\n    BOOST_CHECK(ma[0] == Null<price_t>());\n    BOOST_CHECK(ma[1] == 0.5);\n    BOOST_CHECK(ma[2] == 1.5);\n    BOOST_CHECK(ema[0] == Null<price_t>());\n    BOOST_CHECK(ema[1] == 0.5);\n    BOOST_CHECK(std::fabs(ema[2] - 1.16667) < 0.0001 );\n#endif\n\n    /** @arg operator() */\n    Indicator ma = MA(data, 2);\n    Indicator expect = EMA(ma, 2);\n    ema = EMA(2);\n    Indicator result = ema(ma);\n    BOOST_CHECK(result.size() == expect.size());\n    for (size_t i = 0; i < expect.size(); ++i) {\n        BOOST_CHECK(result[i] == expect[i]);\n    }\n}\n\n/** @} */\n\n", "meta": {"hexsha": "0005878abd3e55744e1d5c191ee3aab30bf435b5", "size": 2289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_stars_repo_name": "waruqi/hikyuu", "max_stars_repo_head_hexsha": "5d252eafff3e4e9ab41af4e2c492b38ff764214d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-08T12:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-08T12:24:35.000Z", "max_issues_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_issues_repo_name": "heiye007/hikyuu", "max_issues_repo_head_hexsha": "5bf64446a549202574f493953546115396a91d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hikyuu_cpp/unit_test/libs/hikyuu/indicator/test_EMA.cpp", "max_forks_repo_name": "heiye007/hikyuu", "max_forks_repo_head_hexsha": "5bf64446a549202574f493953546115396a91d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-31T16:45:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-31T16:45:23.000Z", "avg_line_length": 26.0113636364, "max_line_length": 57, "alphanum_fraction": 0.5871559633, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6660458833062661}}
{"text": "#include \"simulate.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include <armadillo>\n#include <boost/math/distributions/normal.hpp>\n\nusing namespace std;\n\n// constants\nconst double ALPHA = 0.05;\n\nint main(int argc, char *argv[]) {\n  clock_t startTime = clock();\n  ios::sync_with_stdio(false); cin.tie(NULL);\n  // parse arguments\n  int ITERATIONS = stoi(argv[1]); // simulation runs\n  int N = stoi(argv[2]);          // 1/2 sample size\n  double POWER = stod(argv[3]);    // power\n\n  // calculate variance used for generators\n  double variance = calculateVariance(N, ALPHA, POWER);\n  double standardDeviation = sqrt(variance);\n  \n  // set up generators\n  random_device randomDevice;\n  mt19937_64 rng; \n  rng.seed(randomDevice());\n  normal_distribution<double> normalMean0(0, standardDeviation);  \n  normal_distribution<double> normalMean1(1, standardDeviation);  \n\n  // store and print results\n  vector<tuple<double, double, int, int, double, double>> results(ITERATIONS); // initial p-value, \"cheated\" beta, set size, subset size, balance p-value, \"cheated\" p-value\n  cout << setprecision(12) << fixed;\n  cout << \"2N\\tpower\\tp.value\\tbeta\\tset.size\\tsubset.size\\tbalance.p.value\\tfake.p.value\" << endl;\n  // randomly assign treatment\n  vector<int> X(2*N); \n  for (int i = 0; i < N; ++i) X[i] = 1;  \n  shuffle(X.begin() , X.end(), rng);  \n  arma::mat Z(2*N, 2*N, arma::fill::zeros); // pre allocate Z matrix\n  for (int i = 0; i < ITERATIONS; ++i) {\n    // generate response\n    arma::Col<double> Y(2*N);\n    for (int j = 0; j < 2*N; ++j) {\n      Y(j) = X[j] == 0 ? normalMean0(rng) : normalMean1(rng);\n    }            \n    results[i] = simulate(Y, X, standardDeviation, true, Z, rng);\n    cout << 2*N << '\\t' << POWER << '\\t' \n         << get<0>(results[i]) << '\\t' \n         << get<1>(results[i]) << '\\t' \n         << get<2>(results[i]) << '\\t' \n         << get<3>(results[i]) << '\\t'\n         << get<4>(results[i]) << '\\t'\n         << get<5>(results[i]) << endl;\n  }\n\n  double duration = (clock() - startTime) / (double) CLOCKS_PER_SEC;\n  cerr << \"Time taken (seconds): \" << duration << endl;\n  return 0;\n}\n", "meta": {"hexsha": "c67398c435da291cdbb88578dbac4b7814a5de4d", "size": 2233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "powerSimulation.cpp", "max_stars_repo_name": "ppham27/cheating-linear-models-simulations", "max_stars_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "powerSimulation.cpp", "max_issues_repo_name": "ppham27/cheating-linear-models-simulations", "max_issues_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "powerSimulation.cpp", "max_forks_repo_name": "ppham27/cheating-linear-models-simulations", "max_forks_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_forks_repo_licenses": ["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.3623188406, "max_line_length": 172, "alphanum_fraction": 0.6157635468, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6660458745721101}}
{"text": "\n// requires LAPACK v. 3.0\n\n#include <cstddef>\n#include <iostream>\n#include <algorithm> \n#include <boost/numeric/bindings/lapack/driver/gesdd.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::vector<real_t> v_t;\n\nint main() {\n\n  cout << endl; \n\n  size_t m = 3, n = 4;   \n  size_t minmn = m < n ? m : n; \n  m_t a (m, n);  \n  a(0,0) = 2.;  a(0,1) = 2.;  a(0,2) = 2.;   a(0,3) = 2.;\n  a(1,0) = 1.7; a(1,1) = 0.1; a(1,2) = -1.7; a(1,3) = -0.1;\n  a(2,0) = 0.6; a(2,1) = 1.8; a(2,2) = -0.6; a(2,3) = -1.8;\n\n  m_t a2 (a); // for parts 2 & 3\n\n  print_m (a, \"A\"); \n  cout << endl; \n\n  v_t s (minmn); \n  m_t u (m, minmn);\n  m_t vt (minmn, n);\n\n//  lapack::gesdd (a, s, u, vt);\n  lapack::gesdd ('S', a, s, u, vt);\n\n  print_v (s, \"s\"); \n  cout << endl; \n  print_m (u, \"U\"); \n  cout << endl; \n  print_m (vt, \"V^T\"); \n  cout << endl << endl;\n\n  // part 2\n  \n  // singular values and singular vectors satisfy  A v_i == s_i u_i\n  for (int i = 0; i < minmn; ++i) {\n    cout << \"A v_\" << i << \" == s_\" << i << \" u_\" << i << endl; \n    v_t avi = ublas::prod (a2, ublas::row (vt, i));  \n    print_v (avi);\n    v_t siui = s[i] * ublas::column (u, i);\n    print_v (siui);\n    cout << endl; \n  }\n  cout << endl; \n  \n  // singular values and singular vectors satisfy  A^T u_i == s_i v_i\n  for (int i = 0; i < minmn; ++i) {\n    cout << \"A^T u_\" << i << \" == s_\" << i << \" v_\" << i << endl; \n    v_t atui = ublas::prod (trans (a2), ublas::column (u, i));  \n    print_v (atui);\n    v_t sivi = s[i] * ublas::row (vt, i);\n    print_v (sivi);\n    cout << endl; \n  }\n  cout << endl; \n  \n  // part 3 \n  \n//  lapack::gesdd (a2, s);\n  lapack::gesdd ('N', a2, s, u, vt);\n  \n  print_v (s, \"singular values only\"); \n  cout << endl; \n}\n\n", "meta": {"hexsha": "3a02a1d8b1a11c45c2c2b0425dcf8281b44b3490", "size": 2119, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 24.0795454545, "max_line_length": 69, "alphanum_fraction": 0.5474280321, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6660230567460257}}
{"text": "#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_cloud.h>\n#include <pcl/common/transforms.h>                 \n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/console/parse.h>\n#include <pcl/point_types.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/ModelCoefficients.h>\n#include <vector>\n\n#include <time.h>\n\n\n\n#define PI 3.1415926\n\nclass Point\n{\n    public:\n    double x;\n    double y;\n    double z;\n    Point(double v[]):x(v[0]),y(v[1]),z(v[2]){}\n};\n\n//\u6c42\u6cd5\u5411\u91cf\ndouble* get_normal(Point p1, Point p2, Point p3)\n{   \n    double* norm_vec;\n    norm_vec = new double[3];\n    double a = ( (p2.y-p1.y)*(p3.z-p1.z)-(p2.z-p1.z)*(p3.y-p1.y));\n \n    double b = ( (p2.z-p1.z)*(p3.x-p1.x)-(p2.x-p1.x)*(p3.z-p1.z));\n \n    double c = ( (p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x));\n\n    \n\n    double norm = std::sqrt(a*a+b*b+c*c);\n    \n    norm_vec[0] = a/norm;\n    norm_vec[1] = b/norm;\n    norm_vec[2] = c/norm;\n    // double v[3] = {a/norm, b/norm, c/norm};\n\n    return norm_vec;\n}\n\n//\u6c42\u65cb\u8f6c\u77e9\u96354*4\n\ndouble get_theta_from_2_vec(double*v1,double*v2)\n{\n    double costheta = (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) / (0.000001+std::sqrt((v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2])*(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])));\n    return std::acos(costheta);\n}\n\nEigen::Matrix4d get_mat(Eigen::VectorXd coed)\n{\n    double z[3] = {0,0,1};\n    // double a[3] = {-0.0554246, 0.0372348, 0.997768};\n    // double a[3] = {-0.0842539, 0.882628, 0.462459};\n    double a[3] = {coed[0], coed[1], coed[2]};\n\n    std::cout<<\"normal vector: \"<<coed[0]<<\", \"<<coed[1]<<\", \"<<coed[2]<<std::endl;\n    // double za = z[0]*a[0] + z[1]*a[1] + z[2]*a[2];\n\n    double o[3] = {0,0,0};\n    Point p1(z);\n    Point p2(a);\n    Point p3(o);\n    double* axis_line = get_normal(p1, p2, p3);\n    std::cout<<axis_line[1] << std::endl;\n    \n\n    // double a_xOy[3] = {a[0], a[1],0};\n    // double x_vec[3] = {1,0,0};\n    // double thetaxOz= get_theta_from_2_vec(a_xOy,x_vec);\n    // //Eigen::Quaterniond q_rotate_to_xOz (std::cos(thetaxOz/2),std::sin(thetaxOz/2),0,0);\n    // Eigen::Quaterniond q_rotate_to_xOz (std::cos(thetaxOz/2),0,0,std::sin(thetaxOz/2));\n\n\n    // double a_xOy_to_z[3] = {a[0],0, a[2]};\n    // double z_vec[3] = {0,0,1};\n    // double theta_toz = 1.0*get_theta_from_2_vec(a_xOy_to_z, z_vec);\n    // Eigen::Quaterniond q_rotate_to_z(std::cos(theta_toz/2),0,std::sin(theta_toz/2),0);\n    \n    // double a_z0y_to_x[3] = {0, a[1], a[2]};\n    // double y_vec[3] = {0,1,0};\n    // double theta_yox = get_theta_from_2_vec(a_z0y_to_x,y_vec);\n    // Eigen::Quaterniond q_rotate_to_x(std::cos(theta_yox/2),std::sin(theta_yox/2),0,0);\n    \n\n    //\u56db\u5143\u6570{cos(r/2), nx*sin(r/2), ny*sin(r/2), nz*sin(r/2)}\n    //Eigen::Quaterniond q = q_rotate_to_xOz*q_rotate_to_z;\n    //Eigen::Quaterniond q = q_rotate_to_xOz*q_rotate_to_z*q_rotate_to_x;\n\n    double theta_all = -1.0*get_theta_from_2_vec(a, z);\n    Eigen::Quaterniond q(std::cos(theta_all/2),axis_line[0]*std::sin(theta_all/2),axis_line[1]*std::sin(theta_all/2),axis_line[2]*std::sin(theta_all/2));\n    // Eigen::Quaterniond q(std::cos(theta_all/2),-0.557652*std::sin(theta_all/2),-0.830075*std::sin(theta_all/2),0);\n\n    // Eigen::Quaterniond q = q_rotate_to_xOz;\n    Eigen::Matrix3d mat3 = q.toRotationMatrix();\n    Eigen::Matrix4d mat4 = Eigen::Matrix4d::Identity();\n    mat4.block(0,0,3,3) = mat3;\n    mat4(2, 3) = coed[3];\n\n    std::cout << mat3 << std::endl;\n\n    return mat4;\n}\n\nvoid\nshowHelp ()\n{\n  std::cout << std::endl;\n  std::cout << \"Usage: ./rotate_pcd input.pcd [Options]\"<< std::endl;\n  std::cout << \"Options:\" << std::endl;\n  std::cout << \"     -h:                        Show this help.\" << std::endl;\n  std::cout << \"     -v:                        Show pcl viewer.\" << std::endl;\n  std::cout << \"     -o  output.pcd:            Save inlier points to pcd file.\" << std::endl;\n  std::cout << \"     -t  threshold:             Distance threshold (default 0.1)\" << std::endl;\n  std::cout << \"     -cs coord_scale:           Coordinate Scale of pcl viewer (default 100.0)\" << std::endl;\n}\n\n\nint main (int argc, char** argv)\n{\n\n    std::clock_t t1 = std::clock();\n    //creates a PointCloud<PointXYZ> boost shared pointer and initializes it.\n    pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud (new pcl::PointCloud<pcl::PointXYZ> ());\n    \n    if (pcl::console::find_switch (argc, argv, \"-h\"))\n    {\n        showHelp ();\n        exit (0);\n    }\n    std::string input_path;\n    if (argc < 2)\n    {\n        showHelp ();\n        exit (0);\n    }\n    else\n    {\n        input_path = argv[1];\n        if (pcl::io::loadPCDFile<pcl::PointXYZ> (input_path, *source_cloud) == -1) //* load the file\n        {\n            std::cerr << \"Input path: \" << input_path << std::endl;\n            PCL_ERROR (\"Couldn't read file model, please try again. \\n\");\n            showHelp();\n            return (-1);\n        }\n    }\n    \n    std::size_t sz = source_cloud->points.size();\n    std::cout<<\"Points size: \"<<sz<<std::endl;\n    \n\n    pcl::SampleConsensusModelPlane<pcl::PointXYZ>::Ptr\n    model_p (new pcl::SampleConsensusModelPlane<pcl::PointXYZ> (source_cloud));\n    Eigen::VectorXf coef = Eigen::VectorXf::Zero(4 , 1);\n    pcl::RandomSampleConsensus<pcl::PointXYZ> ransac (model_p);\n\n    double threshold;\n    if (pcl::console::parse_argument (argc, argv, \"-t\", threshold) != -1)\n    {\n      std::cout<<\"Distance threshold: \"<<threshold<<std::endl;\n    }\n    else\n    {\n      threshold = 0.1;\n      std::cout<<\"Distance threshold: 0.1\"<<std::endl;\n    }\n\n    ransac.setDistanceThreshold (threshold);\n    ransac.computeModel();\n    // ransac.getInliers(inliers);\n    ransac.getModelCoefficients(coef);\n    \n    Eigen::VectorXd coed = coef.cast<double>();\n    \n    std::clock_t t2 = std::clock();\n\n\n    Eigen::Matrix4d transform_1_d = get_mat(coed);\n\n    \n    // std::cout << transform_1_d << std::endl;\n\n\n    // Executing the transformation\n    pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZ> ());\n    /*\n    void pcl::transformPointCloud(const pcl::PointCloud< PointT > & cloud_in, \n                                    pcl::PointCloud< PointT > &  cloud_out,  \n                                    const Eigen::Matrix4f &  transform  ) \n    */\n    // Apply an affine transform defined by an Eigen Transform.\n\n    Eigen::Matrix4f transform_1_f = transform_1_d.cast<float>(); \n\n    pcl::transformPointCloud (*source_cloud, *transformed_cloud, transform_1_f);\n    \n\n    std::clock_t t3 = std::clock();\n    // pcl::io::savePCDFileASCII(\"model_1_transform.pcd\", *transformed_cloud);\n    std::string output_path;\n    if (pcl::console::parse_argument (argc, argv, \"-o\", output_path) != -1)\n    {\n        std::cout << \"Rotated model will saved at: \"<<output_path<<std::endl;\n        \n    }\n    else\n    {\n        output_path = \"transform.pcd\";\n        std::cout << \"Rotated model will saved at: transform.pcd\" <<std::endl;\n    }\n    if (pcl::io::savePCDFileASCII(output_path, *transformed_cloud) == -1) //* load the file\n    {\n        PCL_ERROR (\"Couldn't save file model, please try again. \\n\");\n        return (-1);\n    }\n\n\n    std::clock_t t4 = std::clock();\n\n    std::cout <<\"Full cost: \"<<(double)(t4-t1)/CLOCKS_PER_SEC<<std::endl;\n\n    std::cout <<\"RANSaC cost: \"<<(double)(t2-t1)/CLOCKS_PER_SEC<<std::endl;\n    std::cout <<\"Transform cost: \"<<(double)(t3-t1)/CLOCKS_PER_SEC<<std::endl;\n    // Visualization\n    if (pcl::console::find_switch (argc, argv, \"-v\"))\n    {\n        printf(  \"\\nPoint cloud colors :  white  = original point cloud\\n\"\n        \"                        red  = transformed point cloud\\n\");\n        pcl::visualization::PCLVisualizer viewer (\"Matrix transformation example\");\n\n        // Define R,G,B colors for the point cloud\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source_cloud_color_handler (source_cloud, 255, 255, 255);\n        //We add the point cloud to the viewer and pass the color handler\n        viewer.addPointCloud (source_cloud, source_cloud_color_handler, \"original_cloud\");\n\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> transformed_cloud_color_handler (transformed_cloud, 230, 20, 20); // Red\n        viewer.addPointCloud (transformed_cloud, transformed_cloud_color_handler, \"transformed_cloud\");\n\n        double coord_scale;\n        if (pcl::console::parse_argument (argc, argv, \"-cs\", coord_scale) != -1)\n        {\n            std::cout<<\"Display coordinate scale: \"<<coord_scale<<std::endl;\n        }\n        else\n        {\n            coord_scale = 100.0;\n            std::cout<<\"Display coordinate scale: 100.0\"<<std::endl;\n        }\n        viewer.addCoordinateSystem (coord_scale, 0);  //Adds 3D axes describing a coordinate system to screen at 0,0,0. \n        viewer.setBackgroundColor(0.05, 0.05, 0.05, 0); // Setting background to a dark grey\n        viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, \"original_cloud\");\n        viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, \"transformed_cloud\");\n\n        \n        \n\n        viewer.setPosition(800, 400); // Setting visualiser window position\n\n        while (!viewer.wasStopped ()) { // Display the visualiser until 'q' key is pressed\n        viewer.spinOnce ();\n        }\n    }\n\n    \n  return 0;\n}\n", "meta": {"hexsha": "83af43d88ea19c5459f39d7311c4918ba4d3a1ab", "size": 9428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated/algorithms/sfm/sfm_plane_detection/rotate_pcd.cpp", "max_stars_repo_name": "mfkiwl/GAAS", "max_stars_repo_head_hexsha": "29ab17d3e8a4ba18edef3a57c36d8db6329fac73", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "algorithms/sfm/sfm_plane_detection/rotate_pcd.cpp", "max_issues_repo_name": "Wayne-xixi/GAAS", "max_issues_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "algorithms/sfm/sfm_plane_detection/rotate_pcd.cpp", "max_forks_repo_name": "Wayne-xixi/GAAS", "max_forks_repo_head_hexsha": "308ff4267ccc6fcad77eef07e21fa006cc2cdd5f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 33.6714285714, "max_line_length": 160, "alphanum_fraction": 0.6033092915, "num_tokens": 2910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6660060180310685}}
{"text": "#include <igl/boundary_facets.h>\r\n#include <igl/cotmatrix.h>\r\n#include <igl/invert_diag.h>\r\n#include <igl/jet.h>\r\n#include <igl/massmatrix.h>\r\n#include <igl/min_quad_with_fixed.h>\r\n#include <igl/readOFF.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n#include <Eigen/Sparse>\r\n#include <iostream>\r\n#include \"tutorial_shared_path.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  MatrixXd V;\r\n  MatrixXi F;\r\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/cheburashka.off\",V,F);\r\n\r\n  // Two fixed points\r\n  VectorXi b(2,1);\r\n  // Left hand, left foot\r\n  b<<4331,5957;\r\n  VectorXd bc(2,1);\r\n  bc<<1,-1;\r\n\r\n  // Construct Laplacian and mass matrix\r\n  SparseMatrix<double> L,M,Minv,Q;\r\n  igl::cotmatrix(V,F,L);\r\n  igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);\r\n  igl::invert_diag(M,Minv);\r\n  // Bi-Laplacian\r\n  Q = L * (Minv * L);\r\n  // Zero linear term\r\n  VectorXd B = VectorXd::Zero(V.rows(),1);\r\n\r\n  VectorXd Z,Z_const;\r\n  {\r\n    // Alternative, short hand\r\n    igl::min_quad_with_fixed_data<double> mqwf;\r\n    // Empty constraints\r\n    VectorXd Beq;\r\n    SparseMatrix<double> Aeq;\r\n    igl::min_quad_with_fixed_precompute(Q,b,Aeq,true,mqwf);\r\n    igl::min_quad_with_fixed_solve(mqwf,B,bc,Beq,Z);\r\n  }\r\n\r\n  {\r\n    igl::min_quad_with_fixed_data<double> mqwf;\r\n    // Constraint forcing difference of two points to be 0\r\n    SparseMatrix<double> Aeq(1,V.rows());\r\n    // Right hand, right foot\r\n    Aeq.insert(0,6074) = 1;\r\n    Aeq.insert(0,6523) = -1;\r\n    Aeq.makeCompressed();\r\n    VectorXd Beq(1,1);\r\n    Beq(0) = 0;\r\n    igl::min_quad_with_fixed_precompute(Q,b,Aeq,true,mqwf);\r\n    igl::min_quad_with_fixed_solve(mqwf,B,bc,Beq,Z_const);\r\n  }\r\n\r\n\r\n  // Pseudo-color based on solution\r\n  struct Data{\r\n    MatrixXd C,C_const;\r\n  } data;\r\n  // Use same color axes\r\n  const double min_z = std::min(Z.minCoeff(),Z_const.minCoeff());\r\n  const double max_z = std::max(Z.maxCoeff(),Z_const.maxCoeff());\r\n  igl::jet(      Z,min_z,max_z,data.C);\r\n  igl::jet(Z_const,min_z,max_z,data.C_const);\r\n\r\n  // Plot the mesh with pseudocolors\r\n  igl::opengl::glfw::Viewer viewer;\r\n  viewer.data().set_mesh(V, F);\r\n  viewer.data().show_lines = false;\r\n  viewer.data().set_colors(data.C);\r\n\r\n  viewer.callback_key_down = \r\n    [](igl::opengl::glfw::Viewer& viewer,unsigned char key,int mod)->bool\r\n    {\r\n      if(key == ' ')\r\n      {\r\n        Data & data = *static_cast<Data*>(viewer.callback_key_down_data);\r\n        static bool toggle = true;\r\n        viewer.data().set_colors(toggle?data.C_const:data.C);\r\n        toggle = !toggle;\r\n        return true;\r\n      }else\r\n      {\r\n        return false;\r\n      }\r\n    };\r\n  viewer.callback_key_down_data = &data;\r\n  cout<<\r\n    \"Press [space] to toggle between unconstrained and constrained.\"<<endl;\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "8b1489d8c1e0e93118124cc6fec0b9779ce6844c", "size": 2787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf-net/lib/submodules/libigl/tutorial/304_LinearEqualityConstraints/main.cpp", "max_stars_repo_name": "hardikk13/nglod", "max_stars_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/tutorial/304_LinearEqualityConstraints/main.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/tutorial/304_LinearEqualityConstraints/main.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 27.87, "max_line_length": 76, "alphanum_fraction": 0.638320775, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181876, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.666005994184328}}
{"text": "#include <complex>\n#include <limits>\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <rsvd/GramSchmidt.hpp>\n\nusing Eigen::Index;\nusing Rsvd::Internal::modifiedGramSchmidt;\n\ntemplate <typename T> struct GramSchmidt : public ::testing::Test {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  using RealType = typename Eigen::NumTraits<T>::Real;\n\n  const unsigned int prngSeed = 777;\n\n  const RealType macheps = std::numeric_limits<RealType>::epsilon();\n};\n\nusing NumericalTypes = ::testing::Types<float, double, std::complex<float>, std::complex<double>>;\n\nTYPED_TEST_CASE(GramSchmidt, NumericalTypes, );\n\n/// \\brief MGS function asserts that the number of columns is less or equal than the number of\n/// columns. Otherwise, the columns are linearly dependent.\nTYPED_TEST(GramSchmidt, MoreColumnsThanRows) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType a = MatrixType::Zero(4, 6);\n  ASSERT_DEATH(modifiedGramSchmidt(a),\n               \"Assertion `\\\\w+\\\\.cols\\\\(\\\\) <= \\\\w+\\\\.rows\\\\(\\\\)' failed\");\n}\n\n/// \\brief Test deflation on linearly dependent columns. All linearly-dependent columns must be\n/// filled with zeros.\nTYPED_TEST(GramSchmidt, LinearlyDependentColumnsEasy) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType testee = MatrixType::Ones(10, 7);\n  modifiedGramSchmidt(testee);\n\n  MatrixType reference = MatrixType::Zero(10, 7);\n  reference.col(0).setOnes();\n  reference.col(0) /= sqrt(10);\n\n  ASSERT_TRUE(testee.isApprox(reference));\n}\n\n/// \\brief Test the deflation case when (new) independent directions come after linearly dependent\n/// ones.\nTYPED_TEST(GramSchmidt, LinearlyDependentColumnsOrder) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  MatrixType testee(5, 5);\n  testee << 1, 1, 1, 1, 1, // 1\n      0, 1, 1, 1, 1,       // 2\n      0, 0, 0, 1, 1,       // 3\n      0, 0, 0, 0, 1,       // 4\n      0, 0, 0, 0, 0;       // 5\n  modifiedGramSchmidt(testee);\n\n  MatrixType reference(5, 5);\n  reference << 1, 0, 0, 0, 0, // 1\n      0, 1, 0, 0, 0,          // 2\n      0, 0, 0, 1, 0,          // 3\n      0, 0, 0, 0, 1,          // 4\n      0, 0, 0, 0, 0;          // 5\n\n  ASSERT_TRUE(testee.isApprox(reference));\n}\n\n/// \\brief Test the deflation case when the columns are numerically linearly dependent.\nTYPED_TEST(GramSchmidt, LinearlyDependentColumnsNumericalRankLoss) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  const auto e = 10 * TestFixture::macheps;\n\n  MatrixType testee(5, 5);\n  testee << 1, 1, 1, 1, 1, // 1\n      0, 1, 1, 1, 1,       // 2\n      0, 0, e, 1, 1,       // 3\n      0, 0, 0, 0, 1,       // 4\n      0, 0, 0, 0, 0;       // 5\n  modifiedGramSchmidt(testee);\n\n  MatrixType reference(5, 5);\n  reference << 1, 0, 0, 0, 0, // 1\n      0, 1, 0, 0, 0,          // 2\n      0, 0, 0, 1, 0,          // 3\n      0, 0, 0, 0, 1,          // 4\n      0, 0, 0, 0, 0;          // 5\n\n  ASSERT_TRUE(testee.isApprox(reference));\n}\n\n/// \\brief A matrix which is already orthonormal must remain the same.\nTYPED_TEST(GramSchmidt, AlreadyOrthogonalIdentity) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  const MatrixType reference = MatrixType::Identity(10, 4);\n  MatrixType testee = MatrixType::Identity(10, 4);\n\n  modifiedGramSchmidt(testee);\n\n  ASSERT_TRUE(testee.isApprox(reference));\n}\n\n/// \\brief A matrix which is already orthonormal must remain the same, larger matrix without\n/// structure.\nTYPED_TEST(GramSchmidt, AlreadyOrthogonalRandom) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n\n  const Index numRows = 50;\n  const Index numCols = 25;\n\n  auto source = MatrixType::Random(numRows, numCols);\n  Eigen::ColPivHouseholderQR<MatrixType> qr(source);\n  const auto reference = qr.householderQ() * MatrixType::Identity(numRows, numCols);\n\n  auto testee = reference;\n  modifiedGramSchmidt(testee);\n\n  ASSERT_TRUE(testee.isApprox(reference));\n}\n\n/// \\brief Test if the matrix columns have unit norm after orthonormalization.\nTYPED_TEST(GramSchmidt, CorrectNormalization) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n\n  const Index numRows = 50;\n  const Index numCols = 25;\n\n  MatrixType testee = MatrixType::Random(numRows, numCols);\n  modifiedGramSchmidt(testee);\n\n  for (Index i = 0; i < numCols; ++i) {\n    ASSERT_NEAR(testee.col(i).norm(), 1, 2 * TestFixture::macheps);\n  }\n}\n\n/// \\brief Test if the matrix columns are mutually orthogonal after orthonormalization.\nTYPED_TEST(GramSchmidt, CorrectOrthogonality) {\n  using MatrixType = typename TestFixture::MatrixType;\n\n  std::srand(TestFixture::prngSeed);\n\n  const Index numRows = 50;\n  const Index numCols = 25;\n\n  MatrixType testee = MatrixType::Random(numRows, numCols);\n  modifiedGramSchmidt(testee);\n\n  for (Index i = 0; i < numCols; ++i) {\n    for (Index j = 0; j < i; ++j) {\n      const auto res = std::abs(testee.col(i).dot(testee.col(j)));\n      ASSERT_NEAR(res, 0, 2 * TestFixture::macheps);\n    }\n  }\n}\n", "meta": {"hexsha": "34b1eb375cfccc6b5ff014a7fc6c56b09671d94e", "size": 4998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/GramSchmidt.cpp", "max_stars_repo_name": "valerii-filev-picsart/rsvd", "max_stars_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T09:12:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T15:40:04.000Z", "max_issues_repo_path": "test/GramSchmidt.cpp", "max_issues_repo_name": "valerii-filev-picsart/rsvd", "max_issues_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/GramSchmidt.cpp", "max_forks_repo_name": "valerii-filev-picsart/rsvd", "max_forks_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T18:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T18:45:56.000Z", "avg_line_length": 30.2909090909, "max_line_length": 98, "alphanum_fraction": 0.6662665066, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6659980080977859}}
{"text": "\ufeff//******************************************************************************\r\n//  project:\t\tWeather-based simulation framework (WBSF)\r\n//\tProgrammer:     R\u00e9mi Saint-Amant\r\n// \r\n//  It under the terms of the GNU General Public License as published by\r\n//     the Free Software Foundation\r\n//  It is provided \"as is\" without express or implied warranty.\r\n//\r\n// Class:\tCStatistic, CStatisticEx, CStatisticXW, CStatisticXY, CStatisticXYEx, CStatisticXYW\r\n//\t\t\t\r\n//****************************************************************************\r\n// 02/12/2015   R\u00e9mi Saint-Amant  Add weathed statistic and quartile\r\n// 22/12/2014   R\u00e9mi Saint-Amant  Add RANGE as statistic type\r\n// 24/05/2013\tR\u00e9mi Saint-Amant  Add standart deviation over population (N) \r\n// 20/02/2009\tR\u00e9mi Saint-Amant  Add classification class\r\n// 04/03/2004\tR\u00e9mi Saint-Amant  Remove the old GetVaporPressureDeficit\r\n// 20/11/2003\tR\u00e9mi Saint-Amant  Initiale Version\r\n//****************************************************************************\r\n\r\n#include \"stdafx.h\"\r\n#include <math.h>\r\n#include <float.h>\r\n#include <algorithm>\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\n\r\n#include \"Basic/Statistic.h\"\r\n#include \"Basic/UtilMath.h\"\r\n#include \"WeatherBasedSimulationString.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t \r\n\t//this static variable is share by CStatistic and CStatisticXY\r\n\tdouble STAT_VMISS = -9999999.0;\r\n\r\n\r\n\tconst char* CStatistic::NAME[NB_STATXY_TYPE_EX] =\r\n\t{ \r\n\t\t\"Lowest\", \"Mean\", \"Sum\", \"Sum\u00b2\", \"StandardDeviation (N-1)\", \"StandardDeviation (N)\", \"StandardError\", \"CoeficientOfVariation\", \"Variance\", \"Highest\", \"TotalSumOfSquares\", \"QuadraticMean\", \"Range\", \"NbValue\",\r\n\t\t\"MeanAbsoluteDeviation\", \"Skewness\", \"Kurtosis\", \"Median\", \"Mode\", \"Lo\", \"Q\u00b9\", \"Q\u00b3\", \"Hi\", \"IQR\",\r\n\t\t\"MeanX\", \"MeanY\", \"Intercept\", \"Slope\", \"Covariance\", \"Correlation\", \"Bias\", \"MeanAbsolutError\", \"RootMeanSquareError\", \"ResidualSumOfSquare\", \"CoeficientOfDetermination\", \"CoeficientOfCorrelation\", \"R\u00b2\",\r\n\t\t\"TheilSenIntercept\", \"TheilSenSlope\", \"Likelihood\"\r\n\t\t//, \"LogLikelihood2\"\r\n\t};\r\n\r\n\t\r\n\r\n\tStringVector CStatistic::TITLE;\r\n\tconst char* CStatistic::GetTitle(size_t s)\r\n\t{\r\n\t\tassert(s < NB_STATXY_TYPE_EX);\r\n\t\tif (TITLE.empty())\r\n\t\t\tTITLE.LoadString(IDS_STR_STATISTIC, \"|;\");\r\n\r\n\t\tassert(TITLE.size() == NB_STATXY_TYPE_EX);\r\n\r\n\t\treturn TITLE[s].c_str();\r\n\t}\r\n\r\n\tvoid CStatistic::ReloadString()\r\n\t{\r\n\t\tTITLE.clear();\r\n\t}\r\n\r\n\tCStatistic::CStatistic()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatistic::Reset()\r\n\t{\r\n\t\tm_nbValues = 0;\r\n\r\n\t\tm_lowest = DBL_MAX;\r\n\t\tm_sum = 0;\r\n\t\tm_sum\u00b2 = 0;\r\n\t\tm_hightest = -DBL_MAX;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator=(const CStatistic& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tm_nbValues = in.m_nbValues;\r\n\r\n\t\t\tm_lowest = in.m_lowest;\r\n\t\t\tm_sum = in.m_sum;\r\n\t\t\tm_sum\u00b2 = in.m_sum\u00b2;\r\n\t\t\tm_hightest = in.m_hightest;\r\n\t\t}\r\n\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator+=(double value)\r\n\t{\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\tm_nbValues++;\r\n\r\n\t\tif (value < m_lowest)\r\n\t\t\tm_lowest = value;\r\n\r\n\t\tm_sum += value;\r\n\t\tm_sum\u00b2 += Square(value);\r\n\t\tif (value > m_hightest)\r\n\t\t\tm_hightest = value;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator+=(const CStatistic& statistic)\r\n\t{\r\n\t\tm_nbValues += statistic.m_nbValues;\r\n\r\n\t\tif (statistic.m_lowest < m_lowest)\r\n\t\t\tm_lowest = statistic.m_lowest;\r\n\r\n\t\tm_sum += statistic.m_sum;\r\n\t\tm_sum\u00b2 += statistic.m_sum\u00b2;\r\n\t\tif (statistic.m_hightest > m_hightest)\r\n\t\t\tm_hightest = statistic.m_hightest;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatistic::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(type >= 0 && type < NB_STAT_TYPE);\r\n\t\tconst CStatistic& me = *this;\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tsize_t nbVal = m_nbValues == 1 ? m_nbValues : m_nbValues - 1;\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST: value = m_lowest; break;\r\n\t\t\tcase SUM:value = m_sum; break;\r\n\t\t\tcase SUM\u00b2:value = m_sum\u00b2; break;\r\n\t\t\tcase MEAN:value = m_sum / m_nbValues; break;\r\n\t\t\tcase STD_DEV:value = sqrt(std::max(0.0, (m_sum\u00b2 - Square(m_sum) / m_nbValues)) / (nbVal)); break;\r\n\t\t\tcase STD_DEV_OVER_POP:value = sqrt(std::max(0.0, (m_sum\u00b2 - Square(m_sum) / m_nbValues)) / (m_nbValues)); break;\r\n\t\t\tcase STD_ERR:value = (me[STD_DEV] / sqrt((double)m_nbValues)); break;\r\n\t\t\tcase TSS: value = std::max(0.0, m_sum\u00b2 - Square(m_sum) / m_nbValues); break;\r\n\t\t\tcase COEF_VAR:\r\n\t\t\t\tif (!(m_sum\u00b2 > 0 && m_sum == 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = m_sum != 0 ? me[STD_DEV] / me[MEAN] : 0;//est-ce que doit accepter les valeur n\u00e9gative???\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\tcase VARIANCE:value = std::max(0.0, (m_sum\u00b2 - Square(m_sum) / m_nbValues) / (nbVal)); break;\r\n\t\t\tcase HIGHEST:value = m_hightest; break;\r\n\t\t\tcase QUADRATIC_MEAN:  value = sqrt(m_sum\u00b2 / m_nbValues); break;\r\n\t\t\tcase RANGE: value = m_hightest - m_lowest; break;\r\n\t\t\tcase NB_VALUE:value = (double)m_nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);//not supported by this statistic class\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\tdouble CStatistic::GetVMiss(){ return STAT_VMISS; }\r\n\tvoid CStatistic::SetVMiss(double vmiss){ STAT_VMISS = vmiss; }\r\n\r\n\tbool CStatistic::operator==(const CStatistic& in)const\r\n\t{\r\n\t\tbool bEqual = true;\r\n\t\tif (m_nbValues != in.m_nbValues)bEqual = false;\r\n\t\tif (fabs(m_lowest - in.m_lowest) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_sum - in.m_sum) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_sum\u00b2 - in.m_sum\u00b2) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_hightest - in.m_hightest) > EPSILON_DATA)bEqual = false;\r\n\r\n\t\treturn bEqual;\r\n\t}\r\n\t//*************************************************************\r\n\t//CStatisticEx : keep in memory all elements for MAD computation\r\n\r\n\tCStatisticEx::CStatisticEx()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatisticEx::Reset()\r\n\t{\r\n\t\tCStatistic::Reset();\r\n\t\tm_values.clear();\r\n\t\tm_sorted.clear();\r\n\t}\r\n\r\n\tCStatisticEx& CStatisticEx::operator=(const CStatisticEx& in)\r\n\t{\r\n\t\tCStatistic::operator=(in);\r\n\t\tm_values = in.m_values;\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticEx&  CStatisticEx::operator+=(double value)\r\n\t{\r\n\t\tCStatistic::operator+=(value);\r\n\t\tm_values.push_back(value);\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticEx&  CStatisticEx::operator+=(const CStatisticEx& statistic)\r\n\t{\r\n\t\tCStatistic::operator+=(statistic);\r\n\t\tm_values.insert(m_values.end(), statistic.m_values.begin(), statistic.m_values.end());\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid CStatisticEx::sort()const\r\n\t{\r\n\t\tif (m_sorted.empty())\r\n\t\t{\r\n\t\t\tCStatisticEx& me = const_cast<CStatisticEx&>(*this);\r\n\t\t\tme.m_sorted = m_values;\r\n\t\t\tstd::sort(me.m_sorted.begin(), me.m_sorted.end());\r\n\t\t}\r\n\r\n\t\tASSERT(m_sorted.size() == m_values.size());\r\n\t}\r\n\r\n\tdouble CStatisticEx::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_values.size() == m_nbValues);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STAT_TYPE_EX);\r\n\t\tconst CStatisticEx& me = *this;\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tif (type == MAD)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += fabs(m_values[i] - mean);\r\n\r\n\t\t\t\tvalue /= m_values.size();\r\n\t\t\t}\r\n\t\t\telse if (type == SKEWNESS)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += pow(m_values[i] - mean, 3);\r\n\r\n\t\t\t\tdouble SD = CStatistic::operator[](STD_DEV);\r\n\t\t\t\tdouble tmp = ((m_values.size() - 1)*pow(SD, 3));\r\n\r\n\t\t\t\tif (tmp != 0)\r\n\t\t\t\t\tvalue /= tmp;\r\n\t\t\t}\r\n\t\t\telse if (type == KURTOSIS)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += pow(m_values[i] - mean, 4);\r\n\r\n\t\t\t\tdouble SD = CStatistic::operator[](STD_DEV);\r\n\t\t\t\tdouble tmp = ((m_values.size() - 1)*pow(SD, 4));\r\n\r\n\t\t\t\tif (tmp != 0)\r\n\t\t\t\t\tvalue /= tmp;\r\n\t\t\t}\r\n\t\t\telse if (type == MEDIAN || type == Q\u00b2)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tsize_t N1 = (m_sorted.size() + 1) / 2 - 1;\r\n\t\t\t\tsize_t N2 = m_sorted.size() / 2 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\t\t\t\t\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == MODE )\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tint maxOcc = 0;\r\n\t\t\t\tint occ = 0;\r\n\t\t\t\tdouble lastVal = -DBL_MAX;\r\n\t\t\t\tfor (size_t i = 0; i < m_sorted.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (fabs(m_sorted[i] - lastVal) < 0.000001)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tocc++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tocc = 1;\r\n\t\t\t\t\t\tlastVal = m_sorted[i];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (occ > maxOcc)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmaxOcc = occ;\r\n\t\t\t\t\t\tvalue = lastVal;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (type == Q\u1d38)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\t\t\t\t\r\n\t\t\t\tdouble Q1 = me[Q\u00b9];\r\n\t\t\t\tdouble IQR = me[INTER_Q];\r\n\t\t\t\tvalue = max(Q1 - 1.5*IQR, m_sorted.front());\r\n\t\t\t}\r\n\t\t\telse if (type == Q\u00b9)\r\n\t\t\t{\r\n\t\t\t\tsize_t N1 = (m_sorted.size() + 1) / 4 - 1;\r\n\t\t\t\tsize_t N2 = m_sorted.size() / 4 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\r\n\t\t\t\tsort();\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == Q\u00b3)\r\n\t\t\t{\r\n\t\t\t\tsize_t N1 = 3 * (m_sorted.size() + 1) / 4 - 1;\r\n\t\t\t\tsize_t N2 = 3 * m_sorted.size() / 4 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\r\n\t\t\t\tsort();\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == Q\u1d34)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tdouble Q3 = me[Q\u00b3];\r\n\t\t\t\tdouble IQR = me[INTER_Q];\r\n\t\t\t\tvalue = min(Q3 + 1.5*IQR, m_sorted.back());\r\n\t\t\t}\r\n\t\t\telse if (type == INTER_Q)\r\n\t\t\t{\r\n\t\t\t\tvalue = me[Q\u00b3] - me[Q\u00b9];\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvalue = CStatistic::operator[](type);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\tdouble CStatisticEx::percentil(double p)const\r\n\t{\r\n\t\tASSERT(p >= 0 && p <= 100);\r\n\t\tsort();//create sorted array\r\n\t\t\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (!m_sorted.empty())\r\n\t\t{\r\n\t\t\tsize_t n = max(size_t(1), size_t(ceil(p / 100 * m_sorted.size()))) - size_t(1);\r\n\t\t\tvalue = m_sorted[n];\r\n\t\t}\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\t//*************************************************************\r\n\t//Weighted CStatistic\r\n\tCStatisticXW::CStatisticXW()\r\n\t{\r\n\t\tm_wx = 0;\r\n\t\tm_wx\u00b2 = 0;\r\n\t}\r\n\r\n\r\n\tvoid CStatisticXW::Reset()\r\n\t{\r\n\t\tm_x.clear();\r\n\t\tm_w.clear();\r\n\t\tm_wx = 0;\r\n\t\tm_wx\u00b2 = 0;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::operator=(const CStatisticXW& in)\r\n\t{\r\n\t\tm_x = in.m_x;\r\n\t\tm_w = in.m_w;\r\n\t\tm_wx = in.m_wx;\r\n\t\tm_wx\u00b2 = in.m_wx\u00b2;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::Add(double x, double w)\r\n\t{\r\n\t\tm_x.insert(x);\r\n\t\tm_w.insert(w);\r\n\t\tm_wx += w*x;\r\n\t\tm_wx\u00b2 += w*x*x;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::operator+=(const CStatisticXW& statistic)\r\n\t{\r\n\t\tm_x += statistic.m_x;\r\n\t\tm_w += statistic.m_w;\r\n\t\tm_wx += statistic.m_wx;\r\n\t\tm_wx\u00b2 += statistic.m_wx\u00b2;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXW::operator[](size_t type)const\r\n\t{\r\n\t\tASSERT(m_x[NB_VALUE] == m_w[NB_VALUE]);\r\n\t\tASSERT(type >= 0 && type < NB_STAT_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXW& me = *this;\r\n\t\tdouble nbValues = m_x[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST:\tvalue = m_x[LOWEST]; break;\r\n\t\t\tcase SUM:\t\tvalue = m_wx; break;\r\n\t\t\tcase SUM\u00b2:\t\tvalue = m_wx\u00b2; break;\r\n\t\t\tcase MEAN:\t\tvalue = m_wx / m_w[SUM]; break;\r\n\t\t\t\t//from https://stat.ethz.ch/pipermail/r-help/2008-July/168762.html\r\n\t\t\tcase STD_DEV:\r\n\t\t\tcase STD_DEV_OVER_POP:\r\n\t\t\t{\r\n\t\t\t\tif ((Square(m_w[SUM]) - m_w[SUM\u00b2]) != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble mean = me[MEAN];\r\n\t\t\t\t\tdouble sum = 0;\r\n\t\t\t\t\tfor (size_t i = 0; i < m_x().size(); i++)\r\n\t\t\t\t\t\tsum += m_w(i) * Square(m_x(i) - mean);\r\n\r\n\t\t\t\t\tvalue = m_w[SUM] / (Square(m_w[SUM]) - m_w[SUM\u00b2]) *sum;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STD_ERR:value = (me[STD_DEV] / sqrt(m_w[SUM])); break;\r\n\t\t\tcase TSS: value = std::max(0.0, m_wx\u00b2 * m_w[SUM] - Square(m_wx)); break;\r\n\t\t\tcase COEF_VAR:\r\n\t\t\t\tif (!(m_wx\u00b2>0 && m_wx == 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = m_wx > 0 ? me[STD_DEV] / me[MEAN] : 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\tcase VARIANCE: value = ((Square(m_w[SUM]) - m_w[SUM\u00b2]) != 0) ? (m_wx\u00b2 * m_w[SUM] - Square(m_wx)) / (Square(m_w[SUM]) - m_w[SUM\u00b2]) : VMISS; break;\r\n\t\t\tcase HIGHEST: value = m_x[HIGHEST]; break;\r\n\t\t\tcase QUADRATIC_MEAN:  value = sqrt(m_wx\u00b2 / m_w[SUM]); break;\r\n\t\t\tcase RANGE: value = m_x[RANGE]; break;\r\n\t\t\tcase NB_VALUE: value = nbValues; break;\r\n\t\t\tdefault: ASSERT(false);//not supported by this class\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\t//*************************************************************\r\n\t//CStatisticXY: statistic of 2 variables\r\n\r\n\tCStatisticXY::CStatisticXY()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tCStatisticXY& CStatisticXY::operator=(const CStatisticXY& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tm_x = in.m_x;\r\n\t\t\tm_y = in.m_y;\r\n\t\t\tm_lowest = in.m_lowest;\r\n\t\t\tm_xy = in.m_xy;\r\n\t\t\tm_e = in.m_e;\r\n\t\t\tm_rs = in.m_rs;\r\n\t\t\tm_ae = in.m_ae;\r\n\t\t\tm_hightest = in.m_hightest;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid CStatisticXY::Reset()\r\n\t{\r\n\t\tm_x.clear();\r\n\t\tm_y.clear();\r\n\r\n\t\tm_lowest = DBL_MAX;\r\n\t\tm_xy = 0;\r\n\t\tm_e = 0;\r\n\t\tm_rs = 0;\r\n\t\tm_ae = 0;\r\n\t\tm_hightest = -DBL_MAX;\r\n\t}\r\n\r\n\t//x = pred, y = obs\r\n\tCStatisticXY& CStatisticXY::Add(double x, double y)\r\n\t{\r\n\t\tm_x += x;\r\n\t\tm_y += y;\r\n\r\n\t\tdouble e = (x - y);\r\n\t\tif (e < m_lowest)\r\n\t\t\tm_lowest = e;\r\n\r\n\t\tm_xy += x*y;\r\n\t\tm_e += (x - y);\r\n\t\tm_rs += Square(x - y);\r\n\t\tm_ae += abs(x - y);\r\n\r\n\t\tif (e > m_hightest)\r\n\t\t\tm_hightest = e;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXY& CStatisticXY::operator+=(const CStatisticXY& in)\r\n\t{\r\n\t\tm_x += in.m_x;\r\n\t\tm_y += in.m_y;\r\n\r\n\t\tif (in.m_lowest < m_lowest)\r\n\t\t\tm_lowest = in.m_lowest;\r\n\r\n\t\tm_xy += in.m_xy;\r\n\t\tm_e += in.m_e;\r\n\t\tm_rs += in.m_rs;\r\n\t\tm_ae += in.m_ae;\r\n\r\n\t\tif (in.m_hightest > m_hightest)\r\n\t\t\tm_hightest = in.m_hightest;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXY::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_x[NB_VALUE] == m_y[NB_VALUE]);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STATXY_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXY& me = *this;\r\n\t\tdouble nbValues = m_x[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tdouble nbVal = (nbValues == 1) ? nbValues : nbValues - 1;\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST:\tvalue = m_lowest; break;\r\n\t\t\tcase MEAN:\t\tvalue = m_e / nbValues; break;//mean of error (bias) (m_y[MEAN] + m_x[MEAN]) / 2; break;\r\n\t\t\tcase MEAN_X:\tvalue = m_x[MEAN]; break;\r\n\t\t\tcase MEAN_Y:\tvalue = m_y[MEAN]; break;\r\n\t\t\tcase TSS:\t\tvalue = m_y[TSS]; break;\r\n\t\t\tcase INTERCEPT: value = m_y[MEAN] - m_x[MEAN] * me[SLOPE]; break;\r\n\t\t\tcase SLOPE:\r\n\t\t\t\tif (m_x[TSS] != 0)\r\n\t\t\t\t\tvalue = (m_xy - (m_x[SUM] * m_y[SUM] / nbValues)) / m_x[TSS];\r\n\t\t\t\tbreak;\r\n\t\t\tcase COVARIANCE: value = ((m_xy - m_x[SUM] * m_y[MEAN] - m_y[SUM] * m_x[MEAN] + nbValues*m_x[MEAN] * m_y[MEAN])) / nbVal; break;\r\n\t\t\tcase CORRELATION:\r\n\t\t\t{\r\n\t\t\t\tdouble stdDev = (m_x[STD_DEV] * m_y[STD_DEV]);\r\n\t\t\t\tif (stdDev != 0)\r\n\t\t\t\t\tvalue = me[COVARIANCE] / stdDev;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase BIAS:\t\tvalue = m_e / nbValues; break;\r\n\t\t\tcase MAE:\t\tvalue = m_ae / nbValues; break;\r\n\t\t\tcase RMSE:\t\tvalue = sqrt(m_rs / nbValues); break;\r\n\t\t\tcase RSS:\t\tvalue = m_rs; break;\r\n\t\t\tcase COEF_D:\tvalue = me[TSS] > 0 ? (1 - me[RSS] / me[TSS]) : STAT_VMISS; break;\r\n\t\t\tcase COEF_C:\r\n\t\t\t{\r\n\t\t\t\tdouble d = sqrt(nbValues*m_x[SUM\u00b2] - Square(m_x[SUM]))*sqrt(nbValues*m_y[SUM\u00b2] - Square(m_y[SUM]));\r\n\t\t\t\tif (d != 0)\r\n\t\t\t\t\tvalue = (nbValues*m_xy - m_x[SUM] * m_y[SUM]) / d;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STAT_R\u00b2:\r\n\t\t\t{\r\n\t\t\t\tdouble c = me[COEF_C];\r\n\t\t\t\tif (c > STAT_VMISS)\r\n\t\t\t\t\tvalue = Square(c);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase HIGHEST:\tvalue = m_hightest; break;\r\n\t\t\tcase RANGE:\t\tvalue = m_hightest - m_lowest; break;\r\n\t\t\tcase NB_VALUE:\tvalue = nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\tdouble CStatisticXY::GetVMiss(){ return STAT_VMISS; }\r\n\tvoid CStatisticXY::SetVMiss(double vmiss){ STAT_VMISS = vmiss; }\r\n\r\n\t//*****************************************************************\r\n\t//CStatisticXYEx: statistic of 2 variables, keeps all values in memory\r\n\tCStatisticXYEx::CStatisticXYEx()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatisticXYEx::Reset()\r\n\t{\r\n\t\tCStatisticXY::Reset();\r\n\t\tm_xValues.clear();\r\n\t\tm_yValues.clear();\r\n\t}\r\n\r\n\tCStatisticXYEx& CStatisticXYEx::operator=(const CStatisticXYEx& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCStatisticXY::operator=(in);\r\n\t\t\tm_xValues = m_xValues;\r\n\t\t\tm_yValues = m_yValues;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXYEx::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_xValues.size() == m_yValues.size());\r\n\t\t_ASSERTE(m_xValues.size() == GetX()[NB_VALUE]);\r\n\t\t_ASSERTE(m_yValues.size() == GetY()[NB_VALUE]);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STATXY_TYPE_EX);\r\n\r\n\t\tconst CStatisticXYEx& me = *this;\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_xValues.size() > 0)\r\n\t\t{\r\n\t\t\tif (type == INTERCEPT_THEIL_SEN)\r\n\t\t\t{\r\n\t\t\t\tvalue = m_yValues[MEDIAN] - m_xValues[MEDIAN] * me[SLOPE_THEIL_SEN];\r\n\t\t\t}\r\n\t\t\telse if (type == SLOPE_THEIL_SEN)\r\n\t\t\t{\r\n\t\t\t\tCStatisticEx stat;\r\n\t\t\t\tASSERT(m_xValues.size() == m_yValues.size());\r\n\t\t\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t j = i + 1; j < m_xValues.size(); j++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble deltaX = (m_xValues[i] - m_xValues[j]);\r\n\t\t\t\t\t\tdouble deltaY = (m_yValues[i] - m_yValues[j]);\r\n\t\t\t\t\t\tif (deltaX != 0)\r\n\t\t\t\t\t\t\tstat += deltaY / deltaX;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvalue = stat[MEDIAN];\r\n\t\t\t}\r\n\t\t\t//else if (type == LOG_LIKELIHOOD1)\r\n\t\t\t//{\r\n\t\t\t//\t//double xSum = m_x[SUM];\r\n\t\t\t//\tdouble ySum = m_y[SUM];\r\n\t\t\t//\tif (ySum > 0)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tdouble LL = 0;\r\n\t\t\t//\t\t//likelihood with classical sigma hat\r\n\t\t\t//\t\tdouble sigma = sqrt(me[RSS] / (m_xValues.size() - 1))*(m_xValues.size()) / (m_xValues.size() - 1);\r\n\t\t\t//\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tdouble m = m_xValues[i];\r\n\t\t\t//\t\t\tboost::math::normal_distribution<> N(m, sigma);\r\n\r\n\t\t\t//\t\t\tdouble x = m_yValues[i];\r\n\t\t\t//\t\t\tdouble p = boost::math::pdf(N, x);\r\n\t\t\t//\t\t\tASSERT(p > 0);\r\n\t\t\t//\t\t\tLL += log(p);\r\n\t\t\t//\t\t}\r\n\r\n\t\t\t//\t\tvalue = LL;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t\telse if (type == LIKELIHOOD)\r\n\t\t\t{\r\n\t\t\t\tdouble xSum = m_x[SUM];\r\n\t\t\t\tdouble ySum = m_y[SUM];\r\n\t\t\t\tif (ySum > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble LL = LogFactorial(xSum);\r\n\t\t\t\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble p = pow(m_yValues[i] / ySum, m_xValues[i]);\r\n\t\t\t\t\t\tLL += log(p);\r\n\t\t\t\t\t\tLL -= LogFactorial(m_xValues[i]);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvalue = LL;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvalue = CStatisticXY::operator[](type);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value) && _finite(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\t//x = pred, y = obs\r\n\tCStatisticXYEx& CStatisticXYEx::Add(double x, double y)\r\n\t{\r\n\t\tm_CS.Enter();\r\n\t\tCStatisticXY::Add(x, y);\r\n\r\n\t\tm_xValues.push_back(x);\r\n\t\tm_yValues.push_back(y);\r\n\t\tm_CS.Leave();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYEx& CStatisticXYEx::operator+=(const CStatisticXYEx& statistic)\r\n\t{\r\n\t\tCStatisticXY::operator+=(statistic);\r\n\t\tm_xValues.insert(m_xValues.end(), statistic.m_xValues.begin(), statistic.m_xValues.end());\r\n\t\tm_yValues.insert(m_yValues.end(), statistic.m_yValues.begin(), statistic.m_yValues.end());\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t//cook distance\r\n\tstd::vector<double> CStatisticXYEx::GetCookDistance()const\r\n\t{\r\n\t\tASSERT(m_xValues.size() == m_yValues.size());\r\n\r\n\t\tstd::vector<double> cookD(x().size());\r\n\r\n\t\tvector<array<double, 2>> X(x().size());\r\n\t\tfor (size_t i = 0; i < x().size(); i++)\r\n\t\t{\r\n\t\t\tX[i][0] = 1;\r\n\t\t\tX[i][1] = x(i);\r\n\t\t}\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\tdouble d = (m_x[NB_VALUE] * m_x[SUM\u00b2]) - Square(m_x[SUM]);\r\n\t\tarray<array<double, 2>, 2> s =\r\n\t\t{ \r\n\t\t\t{{m_x[SUM\u00b2] / d,-m_x[SUM] / d},\r\n\t\t\t{-m_x[SUM] / d, m_x[NB_VALUE] / d}}\r\n\t\t};\r\n\r\n\t\tvector<vector<double>> P(X.size());\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tP[i].resize(X.size());\r\n\t\t\tfor (size_t j = 0; j < X.size(); j++)\r\n\t\t\t{\r\n\t\t\t\tP[i][j] = (s[0][0] * X[i][0] + s[1][0] * X[i][1])*X[j][0] + (s[0][1] * X[i][0] + s[1][1] * X[i][1])*X[j][1];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tarray<double, 2> b = { 0 };\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tb[0] += (s[0][0] * X[i][0] + s[1][0] * X[i][1])*y(i);\r\n\t\t\tb[1] += (s[0][1] * X[i][0] + s[1][1] * X[i][1])*y(i);\r\n\t\t}\r\n\r\n\t\tdouble RSS=0;\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t\tRSS += Square(y(i) - (b[0] * X[i][0] + b[1] * X[i][1]));\r\n\t\t\r\n\t\tsize_t k = 2;\r\n\t\tdouble s2 = RSS / (X.size() - k);                  //three predictors(including intercept(100 - k = 98))\r\n\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tdouble res\u00b2 = Square(y(i) - (b[0] * X[i][0] + b[1] * X[i][1]));\r\n\t\t\tcookD[i] = (res\u00b2 / (k*s2))*(P[i][i] / Square(1.0 - P[i][i]));\r\n\t\t}\r\n\r\n\t\treturn cookD;\r\n\r\n\t}\r\n\r\n\t//*************************************************************\r\n\t//Weighted CStatisticXY\r\n\tCStatisticXYW::CStatisticXYW()\r\n\t{\r\n\t\tm_wxy = 0;\r\n\t\tm_we = 0;\r\n\t\tm_wrs = 0;\r\n\t\tm_wae = 0;\r\n\t}\r\n\r\n\r\n\tvoid CStatisticXYW::Reset()\r\n\t{\r\n\t\tm_xw.clear();\r\n\t\tm_yw.clear();\r\n\t\tm_wxy = 0;\r\n\t\tm_we = 0;\r\n\t\tm_wrs = 0;\r\n\t\tm_wae = 0;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::operator=(const CStatisticXYW& in)\r\n\t{\r\n\t\tm_xw = in.m_xw;\r\n\t\tm_yw = in.m_yw;\r\n\t\tm_wxy = in.m_wxy;\r\n\t\tm_we = in.m_we;\r\n\t\tm_wrs = in.m_wrs;\r\n\t\tm_wae = in.m_wae;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::Add(double x, double y, double w)\r\n\t{\r\n\t\tm_xw.insert(x, w);\r\n\t\tm_yw.insert(y, w);\r\n\t\tdouble e = x - y;\r\n\t\tm_wxy += w*x*y;\r\n\t\tm_we += w*e;\r\n\t\tm_wrs += w*e*e;\r\n\t\tm_wae += w*fabs(e);\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::operator+=(const CStatisticXYW& in)\r\n\t{\r\n\t\tm_xw += in.m_xw;\r\n\t\tm_yw += in.m_yw;\r\n\t\tm_wxy += in.m_wxy;\r\n\t\tm_we += in.m_we;\r\n\t\tm_wrs += in.m_wrs;\r\n\t\tm_wae += in.m_wae;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXYW::operator[](size_t type)const\r\n\t{\r\n\t\tASSERT(m_xw[NB_VALUE] == m_yw[NB_VALUE]);\r\n\t\tASSERT(type >= 0 && type < NB_STATXY_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXYW& me = *this;\r\n\t\tdouble nbValues = m_xw[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST: /*value = m_e[LOWEST];*/ break;\r\n\t\t\tcase MEAN: value = m_we / m_xw.W(SUM); break;\r\n\t\t\tcase MEAN_X: value = m_xw[MEAN]; break;\r\n\t\t\tcase MEAN_Y:value = m_yw[MEAN]; break;\r\n\t\t\tcase TSS: value = m_yw[TSS]; break;\r\n\t\t\tcase INTERCEPT: value = m_yw[MEAN] - m_xw[MEAN] * me[SLOPE]; break;\r\n\t\t\tcase SLOPE:\r\n\t\t\t\tif (m_xw[TSS] != 0)\r\n\t\t\t\t\tvalue = (m_wxy - (m_xw[SUM] * m_yw[SUM] / m_xw.W(SUM))) / m_xw[TSS];\r\n\t\t\t\tbreak;\r\n\t\t\tcase COVARIANCE: value = ((m_wxy - m_xw[SUM] * m_yw[MEAN] - m_yw[SUM] * m_xw[MEAN] + m_xw.W(SUM)*m_xw[MEAN] * m_yw[MEAN])) / m_xw.W(SUM); break;\r\n\t\t\tcase CORRELATION:\r\n\t\t\t{\r\n\t\t\t\tdouble stdDev = (m_xw[STD_DEV] * m_yw[STD_DEV]);\r\n\t\t\t\tif (stdDev != 0)\r\n\t\t\t\t\tvalue = me[COVARIANCE] / stdDev;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tcase BIAS: value = m_we / m_xw.W(SUM); break;\r\n\t\t\tcase MAE: value = m_wae / m_xw.W(SUM); break;\r\n\t\t\tcase RMSE: value = sqrt(m_wrs / m_xw.W(SUM)); break;//ici il ya une erreur dans le calcul... a faire\r\n\t\t\tcase RSS: value = m_wrs / m_xw.W(SUM); break;\r\n\t\t\tcase COEF_D: value = me[TSS] > 0 ? (1 - me[RSS] / me[TSS]) : STAT_VMISS; break;\r\n\t\t\tcase COEF_C:\r\n\t\t\t{\r\n\t\t\t\tdouble d = sqrt(max(0.0, m_xw.W(SUM)*m_xw[SUM\u00b2] - Square(m_xw[SUM])))*sqrt(max(0.0, m_xw.W(SUM) * m_yw[SUM\u00b2] - Square(m_yw[SUM])));\r\n\t\t\t\tif (d != 0)\r\n\t\t\t\t\tvalue = (m_xw.W(SUM)*m_wxy - m_xw[SUM] * m_yw[SUM]) / d;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STAT_R\u00b2:\r\n\t\t\t{\r\n\t\t\t\tdouble c = me[COEF_C];\r\n\t\t\t\tif (c > STAT_VMISS)\r\n\t\t\t\t\tvalue = Square(c);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase HIGHEST: value = STAT_VMISS; break;\r\n\t\t\tcase RANGE: value = STAT_VMISS; break;\r\n\t\t\tcase NB_VALUE: value = nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//************************************************************\r\n\r\n\tCClassify::CClassify()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CClassify::Reset()\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_values.clear();\r\n\t}\r\n\r\n\r\n\tvoid CClassify::Add(double x, double y)\r\n\t{\r\n\t\tm_values.push_back(CXY<double, double>(x, y));\r\n\t}\r\n\r\n\tvoid CClassify::ClassifyManual(vector<double> classLimit)\r\n\t{\r\n\t\t_ASSERTE(classLimit.size() >= 2);\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(classLimit.size() - 1);\r\n\r\n\t\tif (m_values.size() > 0)\r\n\t\t{\r\n\t\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\t\tdouble first = m_values.begin()->m_x;\r\n\t\t\tdouble last = m_values.rbegin()->m_x;\r\n\t\t\tif (classLimit[0] == -1)\r\n\t\t\t\tclassLimit[0] = first;\r\n\r\n\t\t\tif (classLimit[classLimit.size() - 1] == -1)\r\n\t\t\t\tclassLimit[classLimit.size() - 1] = last;\r\n\r\n\t\t\tint j = 0;\r\n\t\t\tfor (int i = 0; i<int(classLimit.size() - 1); i++)\r\n\t\t\t{\r\n\t\t\t\twhile (j < (int)m_values.size() &&\r\n\t\t\t\t\tm_values[j].m_x >= classLimit[i] &&\r\n\t\t\t\t\tm_values[j].m_x < classLimit[i + 1])\r\n\t\t\t\t{\r\n\t\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t\t\tj++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CClassify::ClassifyEqualInterval(short nbClass)\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(nbClass);\r\n\r\n\t\tif (m_values.size() > 0)\r\n\t\t{\r\n\t\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\t\tdouble first = m_values.begin()->m_x;\r\n\t\t\tdouble last = m_values.rbegin()->m_x;\r\n\t\t\tdouble classSize = (double)(last - first) / nbClass;\r\n\t\t\tint j = 0;\r\n\t\t\tfor (int i = 0; i < nbClass; i++)\r\n\t\t\t{\r\n\t\t\t\tdouble limit = first + (i + 1)*classSize;\r\n\r\n\t\t\t\twhile (j < (int)m_values.size() &&\r\n\t\t\t\t\tm_values[j].m_x <= limit)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t\t\tj++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid CClassify::ClassifyNaturalBreak(short nbClass)\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(nbClass);\r\n\r\n\r\n\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\tdouble classSize = (double)m_values.size() / nbClass;\r\n\t\tfor (int i = 0; i < nbClass; i++)\r\n\t\t{\r\n\t\t\tint f = int(i*classSize);\r\n\t\t\tint l = int((i + 1)*classSize);\r\n\t\t\t_ASSERTE(f >= 0 && f <= (int)m_values.size());\r\n\t\t\t_ASSERTE(l >= 0 && l <= (int)m_values.size());\r\n\r\n\t\t\tfor (int j = f; j < l; j++)\r\n\t\t\t{\r\n\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}//namespace WBSF", "meta": {"hexsha": "643f4a208e572f9cba45dd413e2674055a85066a", "size": 25709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Basic/Statistic.cpp", "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/Basic/Statistic.cpp", "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/Basic/Statistic.cpp", "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": 24.3687203791, "max_line_length": 210, "alphanum_fraction": 0.5572756622, "num_tokens": 8620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6658812671571228}}
{"text": "//  (C) Copyright Nick Thompson, 2018\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MODULE numerical_differentiation_test\n\n#include <cmath>\n#include <limits>\n#include <iostream>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/tools/numerical_differentiation.hpp>\n\nusing std::abs;\nusing std::pow;\nusing boost::math::tools::finite_difference_derivative;\nusing boost::math::tools::complex_step_derivative;\nusing boost::math::cyl_bessel_j;\nusing boost::math::cyl_bessel_j_prime;\nusing boost::math::constants::half;\nusing boost::multiprecision::cpp_dec_float_100;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::multiprecision::cpp_bin_float_quad;\n\n\ntemplate<class Real, size_t order>\nvoid test_order(size_t points_to_test)\n{\n    std::cout << \"Testing order \" <<  order  << \" derivative error estimate on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << std::fixed << std::scientific;\n    auto f = [](Real t) { return cyl_bessel_j<Real>(1, t); };\n    Real min = -100000.0;\n    Real max = -min;\n    Real x = min;\n    Real max_error = 0;\n    Real max_relative_error_in_error = 0;\n    size_t j = 0;\n    size_t failures = 0;\n    while (j < points_to_test)\n    {\n        x = min + (Real) 2*j*max/ (Real) points_to_test;\n        Real error_estimate;\n        Real computed = finite_difference_derivative<decltype(f), Real, order>(f, x, &error_estimate);\n        Real expected = (Real) cyl_bessel_j_prime<Real>(1, x);\n        Real error = abs(computed - expected);\n        // The error estimate is provided under the assumption that the function is evaluated to 1 ULP.\n        // Presumably no one will be too offended by this estimate being off by a factor of 2 or so.\n        if (error > 2*error_estimate)\n        {\n            ++failures;\n            Real relative_error_in_error = abs(error - error_estimate)/ error;\n            if (relative_error_in_error > max_relative_error_in_error)\n            {\n                max_relative_error_in_error = relative_error_in_error;\n            }\n            if (relative_error_in_error > 2)\n            {\n                throw std::logic_error(\"Relative error in error is too high!\");\n            }\n        }\n        if (error > max_error)\n        {\n            max_error = error;\n        }\n        ++j;\n    }\n    //std::cout << \"Maximum error :\" << max_error << \"\\n\";\n    //std::cout <<  \"Error estimate failed \" << failures << \" times out of \" << points_to_test << \"\\n\";\n    //std::cout << \"Failure rate: \" << (double) failures / (double) points_to_test << \"\\n\";\n    //std::cout << \"Maximum error in estimated error = \" << max_relative_error_in_error << \"\\n\";\n    //Real convergence_rate = (Real) order/ (Real) (order + 1);\n    //std::cout << \"eps^(order/order+1) = \" << pow(std::numeric_limits<Real>::epsilon(), convergence_rate) << \"\\n\\n\\n\";\n\n    bool max_error_good = max_error < 2*sqrt(std::numeric_limits<Real>::epsilon());\n    BOOST_TEST(max_error_good);\n\n    bool error_estimate_good = max_relative_error_in_error < (Real) 2;\n    BOOST_TEST(error_estimate_good);\n\n    double failure_rate = (double) failures / (double) points_to_test;\n    BOOST_CHECK_SMALL(failure_rate, 0.05);\n}\n\ntemplate<class Real>\nvoid test_bessel()\n{\n    std::cout << \"Testing numerical derivatives of Bessel's function on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n\n    Real eps = std::numeric_limits<Real>::epsilon();\n    Real x = static_cast<Real>(25.1);\n    auto f = [](Real t) { return cyl_bessel_j(12, t); };\n\n    Real computed = finite_difference_derivative<decltype(f), Real, 1>(f, x);\n    Real expected = cyl_bessel_j_prime(12, x);\n    Real error_estimate = 4*abs(f(x))*sqrt(eps);\n    //std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << \"cyl_bessel_j_prime: \" << expected << std::endl;\n    //std::cout << \"First order fd    : \" << computed << std::endl;\n    //std::cout << \"Error             : \" << abs(computed - expected) << std::endl;\n    //std::cout << \"a prior error est : \" << error_estimate << std::endl;\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, computed, 10*error_estimate);\n\n    computed = finite_difference_derivative<decltype(f), Real, 2>(f, x);\n    expected = cyl_bessel_j_prime(12, x);\n    error_estimate = abs(f(x))*pow(eps, boost::math::constants::two_thirds<Real>());\n    //std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << \"cyl_bessel_j_prime: \" << expected << std::endl;\n    //std::cout << \"Second order fd   : \" << computed << std::endl;\n    //std::cout << \"Error             : \" << abs(computed - expected) << std::endl;\n    //std::cout << \"a prior error est : \" << error_estimate << std::endl;\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, computed, 50*error_estimate);\n\n    computed = finite_difference_derivative<decltype(f), Real, 4>(f, x);\n    expected = cyl_bessel_j_prime(12, x);\n    error_estimate = abs(f(x))*pow(eps, (Real) 4 / (Real) 5);\n    //std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << \"cyl_bessel_j_prime: \" << expected << std::endl;\n    //std::cout << \"Fourth order fd   : \" << computed << std::endl;\n    //std::cout << \"Error             : \" << abs(computed - expected) << std::endl;\n    //std::cout << \"a prior error est : \" << error_estimate << std::endl;\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, computed, 25*error_estimate);\n\n\n    computed = finite_difference_derivative<decltype(f), Real, 6>(f, x);\n    expected = cyl_bessel_j_prime(12, x);\n    error_estimate = abs(f(x))*pow(eps, (Real)  6/ (Real) 7);\n    //std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << \"cyl_bessel_j_prime: \" << expected << std::endl;\n    //std::cout << \"Sixth order fd    : \" << computed << std::endl;\n    //std::cout << \"Error             : \" << abs(computed - expected) << std::endl;\n    //std::cout << \"a prior error est : \" << error_estimate << std::endl;\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, computed, 100*error_estimate);\n\n    computed = finite_difference_derivative<decltype(f), Real, 8>(f, x);\n    expected = cyl_bessel_j_prime(12, x);\n    error_estimate = abs(f(x))*pow(eps, (Real)  8/ (Real) 9);\n    //std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    //std::cout << \"cyl_bessel_j_prime: \" << expected << std::endl;\n    //std::cout << \"Eighth order fd   : \" << computed << std::endl;\n    //std::cout << \"Error             : \" << abs(computed - expected) << std::endl;\n    //std::cout << \"a prior error est : \" << error_estimate << std::endl;\n\n    BOOST_CHECK_CLOSE_FRACTION(expected, computed, 25*error_estimate);\n}\n\n// Example of a function which is subject to catastrophic cancellation using finite-differences, but is almost perfectly stable using complex step:\ntemplate<class RealOrComplex>\nRealOrComplex moler_example(RealOrComplex x)\n{\n    using std::sin;\n    using std::cos;\n    using std::exp;\n\n    RealOrComplex cosx = cos(x);\n    RealOrComplex sinx = sin(x);\n    return exp(x)/(cosx*cosx*cosx + sinx*sinx*sinx);\n}\n\ntemplate<class RealOrComplex>\nRealOrComplex moler_example_derivative(RealOrComplex x)\n{\n    using std::sin;\n    using std::cos;\n    using std::exp;\n\n    RealOrComplex expx = exp(x);\n    RealOrComplex cosx = cos(x);\n    RealOrComplex sinx = sin(x);\n    RealOrComplex coscubed_sincubed = cosx*cosx*cosx + sinx*sinx*sinx;\n    return (expx/coscubed_sincubed)*(1 - 3*(sinx*sinx*cosx - sinx*cosx*cosx)/ (coscubed_sincubed));\n}\n\n\ntemplate<class Real>\nvoid test_complex_step()\n{\n    using std::abs;\n    using std::complex;\n    using std::isfinite;\n    using std::isnormal;\n    std::cout << \"Testing numerical derivatives of Bessel's function on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n    Real x = -100;\n    while ( x < 100 )\n    {\n        if (!isfinite(moler_example(x)))\n        {\n            x += 1;\n            continue;\n        }\n        Real expected = moler_example_derivative<Real>(x);\n        Real computed = complex_step_derivative(moler_example<complex<Real>>, x);\n        if (!isfinite(expected))\n        {\n            x += 1;\n            continue;\n        }\n        if (abs(expected) <= std::numeric_limits<Real>::epsilon())\n        {\n            bool issmall = computed < std::numeric_limits<Real>::epsilon();\n            BOOST_TEST(issmall);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(expected, computed, 200*std::numeric_limits<Real>::epsilon());\n        }\n        x += 1;\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(numerical_differentiation_test)\n{\n    test_complex_step<float>();\n    test_complex_step<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_complex_step<long double>();\n#endif\n    test_bessel<float>();\n    test_bessel<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_bessel<long double>();\n#endif\n    test_bessel<cpp_bin_float_50>();\n\n    size_t points_to_test = 1000;\n    test_order<float, 1>(points_to_test);\n    test_order<double, 1>(points_to_test);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_order<long double, 1>(points_to_test);\n#endif\n    test_order<cpp_bin_float_50, 1>(points_to_test);\n\n    test_order<float, 2>(points_to_test);\n    test_order<double, 2>(points_to_test);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_order<long double, 2>(points_to_test);\n#endif\n    test_order<cpp_bin_float_50, 2>(points_to_test);\n\n    test_order<float, 4>(points_to_test);\n    test_order<double, 4>(points_to_test);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_order<long double, 4>(points_to_test);\n#endif\n\n    test_order<float, 6>(points_to_test);\n    test_order<double, 6>(points_to_test);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_order<long double, 6>(points_to_test);\n#endif\n\n    test_order<float, 8>(points_to_test);\n    test_order<double, 8>(points_to_test);\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_order<long double, 8>(points_to_test);\n#endif\n}\n", "meta": {"hexsha": "047dd28750db8d0e6519e95833606b0b32c78fdf", "size": 10751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/test/test_numerical_differentiation.cpp", "max_stars_repo_name": "pdu/boost", "max_stars_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2018-02-01T20:53:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T18:41:05.000Z", "max_issues_repo_path": "math/test/test_numerical_differentiation.cpp", "max_issues_repo_name": "pdu/boost", "max_issues_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "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": "math/test/test_numerical_differentiation.cpp", "max_forks_repo_name": "pdu/boost", "max_forks_repo_head_hexsha": "d6da5587d43699be1a73f6f959f4b4fcaed021fc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T05:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T14:56:56.000Z", "avg_line_length": 39.380952381, "max_line_length": 147, "alphanum_fraction": 0.6610547856, "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.6658812582104239}}
{"text": "// Implementing the class that is defined in the header file: ChooserOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n\r\n#include \"ChooserOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\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 ChooserOption::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 ChooserOption::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\r\ndouble ChooserOption::ChooserPrice() const\r\n{\r\n\treturn ::ChooserPrice(S, K, T, t, r, sig, b);\r\n}\r\n\r\n\r\n// Initialising all the default values\r\nvoid ChooserOption::init()\t\t\t\t\t\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 105;\r\n\tS = 100;\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\tT = 1;\t\t\t\t\r\n\tt = 0.5;\t\t\t//\ttime that has passed since t = 0\r\n\r\n}\r\n\r\n\r\nvoid ChooserOption::copy(const ChooserOption& option)\r\n{\r\n\tr = option.r;\r\n\tt = option.t;\r\n\tT = option.T;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\tS = option.S;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nChooserOption::ChooserOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nChooserOption::ChooserOption(const ChooserOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nChooserOption::ChooserOption(const double& S1, const double& K1, const double& T1, const double& t1, const double& r1,\r\n\tconst double& sig1, const double& b1) : Option(), S(S1), K(K1), T(T1), t(t1), r(r1), sig(sig1), b(b1) {}\r\n\r\n//\tDestructor\r\nChooserOption::~ChooserOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nChooserOption& ChooserOption::operator = (const ChooserOption& 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// Member function that calculate the option price\r\ndouble ChooserOption::Price() const\r\n{\r\n\treturn ChooserPrice();\r\n}\r\n\r\n\r\n// Global functions\r\ndouble ChooserPrice(const double S, const double K, const double T, const double t, const double r, const double sig, const double b)\r\n{\r\n\r\n\tdouble y1 = (log(S / K) + (b * T) + (sig * sig * 0.5 * t)) / (sig * sqrt(t));\r\n\tdouble y2 = y1 - (sig * sqrt(t));\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\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\tdouble w = (S * exp((b - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2)) - (S * exp((b - r) * T) * cdf(standard_normal, -y1)) + (K * exp(-r * T) * cdf(standard_normal, -y2));\r\n\treturn w;\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "cc49aa2cb7bd5843464cd7405cc29082eed08963", "size": 2785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ChooserOption.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": "ChooserOption.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": "ChooserOption.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": 22.8278688525, "max_line_length": 211, "alphanum_fraction": 0.6301615799, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6658707067810831}}
{"text": "#ifndef RBF_HPP \n#define RBF_HPP\n\n#pragma once\n\n#include <vector>\n#include <glimac/Cube.hpp>\n#include <math.h>\n#include <algorithm>\n#include <numeric>\n#include <Eigen/Dense>\n\nnamespace glimac{\n\nenum class FunctionType\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        BiharmonicSpline, // f(r) = r\n        Multiquadric,     // f(r) = sqrt(1 + (epsiolon * r^2))\n    };\n\n class ControlPoint\n{\npublic:\n    glm::vec3 m_position;\n    float m_value;\n};\n\n\n    float getRBF(FunctionType type, const glm::vec3 vecA, const glm::vec3 vecB, const float epsilon);\n    Eigen::VectorXf caclulRBF(std::vector <ControlPoint> &list_controls, FunctionType type,  const float epsilon);\n    void applyRBF(std::vector <Cube> &list_cubes,  std::vector <ControlPoint> &list_controls, FunctionType type);\n\n}\n\n\n\n#endif ", "meta": {"hexsha": "8648e7123be435500cfe76e3dc042479355e8a62", "size": 929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/glimac/include/glimac/Rbf.hpp", "max_stars_repo_name": "elisacia/World-Imaker", "max_stars_repo_head_hexsha": "c168521c168336a4be7835a2adeee9cc7a672681", "max_stars_repo_licenses": ["MIT"], "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/glimac/include/glimac/Rbf.hpp", "max_issues_repo_name": "elisacia/World-Imaker", "max_issues_repo_head_hexsha": "c168521c168336a4be7835a2adeee9cc7a672681", "max_issues_repo_licenses": ["MIT"], "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/glimac/include/glimac/Rbf.hpp", "max_forks_repo_name": "elisacia/World-Imaker", "max_forks_repo_head_hexsha": "c168521c168336a4be7835a2adeee9cc7a672681", "max_forks_repo_licenses": ["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.225, "max_line_length": 114, "alphanum_fraction": 0.638320775, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211323, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6658005839295749}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Example of 1-dimensional RBF interpolation.\n */\n#include <Eigen/Core>\n#include <pybind11/eigen.h>\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/kernel_interpolator.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nauto main() -> int {\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::kernel_interpolator;\n    using num_collect::interp::kernel::rbf_kernel;\n\n    using kernel_type =\n        rbf_kernel<euclidean_distance<double>, gaussian_rbf<double>>;\n\n    const auto vars = std::vector<double>{0.0, 0.1, 0.5, 0.4, 1.2, 1.0};\n    const auto data = Eigen::VectorXd{{0.0, 0.2, 0.5, 0.7, 1.0, 2.0}};\n\n    auto interpolator = kernel_interpolator<kernel_type>();\n    interpolator.compute(vars, data);\n\n    constexpr num_collect::index_type num_samples = 201;\n    const Eigen::VectorXd sample_vars =\n        Eigen::VectorXd::LinSpaced(num_samples, -0.1, 1.3);\n    Eigen::VectorXd sample_data = Eigen::VectorXd::Zero(num_samples);\n    Eigen::VectorXd sample_upper = Eigen::VectorXd::Zero(num_samples);\n    Eigen::VectorXd sample_lower = Eigen::VectorXd::Zero(num_samples);\n    for (num_collect::index_type i = 0; i < num_samples; ++i) {\n        const auto [mean, var] =\n            interpolator.evaluate_mean_and_variance_on(sample_vars(i));\n        const auto err = 3.0 * std::sqrt(var);\n        sample_data(i) = mean;\n        sample_upper(i) = mean + err;\n        sample_lower(i) = mean - err;\n    }\n\n    pybind11::scoped_interpreter interpreter;\n    auto go = pybind11::module::import(\"plotly.graph_objects\");\n    auto fig = go.attr(\"Figure\")();\n\n    // upper and lower limits\n    fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n        pybind11::arg(\"y\") = sample_lower, pybind11::arg(\"mode\") = \"lines\",\n        pybind11::arg(\"name\") = \"Lower bound (3 sigma)\"));\n    fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n        pybind11::arg(\"y\") = sample_upper, pybind11::arg(\"mode\") = \"lines\",\n        pybind11::arg(\"name\") = \"Uppper bound (3 sigma)\",\n        pybind11::arg(\"fill\") = \"tonexty\"));\n\n    // interpolated line\n    fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n        pybind11::arg(\"y\") = sample_data, pybind11::arg(\"mode\") = \"lines\",\n        pybind11::arg(\"name\") = \"Interpolation\"));\n\n    // inputs\n    fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = vars,\n        pybind11::arg(\"y\") = data, pybind11::arg(\"mode\") = \"markers\",\n        pybind11::arg(\"name\") = \"Input data\"));\n\n    fig.attr(\"update_layout\")(pybind11::arg(\"title\") = \"RBF Interpolation\",\n        pybind11::arg(\"xaxis_title\") = \"x\", pybind11::arg(\"yaxis_title\") = \"y\");\n\n    fig.attr(\"write_html\")(\"interp_rbf_1dim.html\");\n    fig.attr(\"write_image\")(\"interp_rbf_1dim.png\");\n}\n", "meta": {"hexsha": "1b6019784a04d3959c012e28078ed0f53cd5edcc", "size": 3676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8444444444, "max_line_length": 80, "alphanum_fraction": 0.6700217628, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6657790275429911}}
{"text": "#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <cmath>\n#include <random>\n#include <limits>\n\n#include \"GRANSAC.hpp\"\n#include \"least_squares_model.hpp\"\n\n#include <vector>\n#include <Eigen/QR>\n\nusing namespace std;\n\n\nint main(int argc, char *argv[])\n{\n    if (argc != 1 && argc != 3)\n    {\n        std::cout << \"[ USAGE ]: \" << argv[0] << \" [<Image Size> = 1000] [<nPoints> = 500]\" << std::endl;\n        return -1;\n    }\n\n    int side = 400;\n    int n_points = 50;\n    if (argc == 3)\n    {\n        side = std::atoi(argv[1]);\n        n_points = std::atoi(argv[2]);\n    }\n\n    cv::Mat img_canvas(side, side, CV_8UC3);\n    img_canvas.setTo(255);\n\n    // Randomly generate points in a 2D plane roughly aligned in a line for testing\n    std::random_device seed_device;\n    std::mt19937 RNG = std::mt19937(seed_device());\n\n    std::uniform_int_distribution<int> uni_dist(0, side - 1); // [Incl, Incl]\n    int perturb = 40;\n    std::normal_distribution<float> perturb_dist(0, perturb);\n\n    std::vector<std::shared_ptr<GRANSAC::AbstractParameter>> cand_points;\n    while (n_points > 0){\n        int diag = uni_dist(RNG);\n        float x = diag + perturb_dist(RNG);\n        // y = 2100-20x+0.05*x*x\n        float y;\n        if (n_points > 5 )\n            y = 2100 - 20 * x + 0.05 * x * x + perturb_dist(RNG);\n        else\n            y = uni_dist(RNG);\n\n        if (x<=side && x > 0 && y<=side && y > 0){\n            cv::Point pt(floor(x), floor(y));\n            cv::circle(img_canvas, pt, floor(side / 100) + 2, cv::Scalar(0, 0, 0), 2, cv::LINE_AA);\n\n            std::shared_ptr<GRANSAC::AbstractParameter> cand_pt = std::make_shared<GRANSAC::Point2D>(pt.x, pt.y);\n            cand_points.push_back(cand_pt);\n\n            n_points -= 1;\n        }\n    }\n\n    //set grid\n    std::map<string, float> additional_params = {{\"img_width\", float(side)}, {\"img_height\", float(side)}, {\"grid_num_x\", float(side/10)}, {\"grid_num_y\", float(side/10)}};\n\n    //draw grid\n    cv::Mat img_overlay;\n    float alpha = 0.3;\n    img_canvas.copyTo(img_overlay);\n    for (int i=0; i < side/10; i++){\n        cv::Point pt_1(i*10, 0);\n        cv::Point pt_2(i*10, side);\n        cv::line(img_overlay, pt_1, pt_2, cv::Scalar(0, 100, 0), 1, cv::LINE_AA, 0);\n        cv::Point pt_3(0, i*10);\n        cv::Point pt_4(side, i*10);\n        cv::line(img_overlay, pt_3, pt_4, cv::Scalar(0, 100, 0), 1, cv::LINE_AA, 0);\n    }\n    cv::addWeighted(img_overlay, alpha, img_canvas, 1 - alpha, 0, img_canvas);\n    \n    // estimate parameters with RANSAC\n    int param_num = 4; // 3rd order\n    additional_params[\"sample_number\"]=10; // sample number for over-deterministic least squares\n    GRANSAC::RANSAC<GRANSAC::LinearLeastSquaresModel<4>, 4> estimator;\n    estimator.initialize(1, 100, additional_params); // Threshold, iterations, the threshold is p-1 distance on grid, 1 means 1 grid cell distance\n\n    float time_average = 0;\n    for (int i=0; i<100; i++){\n        int start = cv::getTickCount();\n        estimator.estimate(cand_points);\n        int end = cv::getTickCount();\n        float time_of_trial = float(end - start) / float(cv::getTickFrequency()) * 1000.0; // [ms]\n        time_average += time_of_trial;\n    }\n    std::cout << \"RANSAC took, average time in 100 trials: \" << time_average/100 << \" ms.\" << std::endl;\n\n    // draw definition points from best model\n    auto best_inliers = estimator.getBestInliers();\n    if (best_inliers.size() > 0)\n    {\n        for (auto &inlier : best_inliers)\n        {\n            auto RPt = std::dynamic_pointer_cast<GRANSAC::Point2D>(inlier);\n            cv::Point pt(floor(RPt->m_point2D[0]), floor(RPt->m_point2D[1]));\n            cv::circle(img_canvas, pt, floor(side / 100), cv::Scalar(0, 255, 0), -1, cv::LINE_AA);\n        }\n    }\n\n    // draw curve from best model\n    auto best_line = estimator.getBestModel();\n    if (best_line)\n    {\n        cout << \"coefficients are : \" << endl;\n        for (auto each : best_line->getModelCoefficients()){\n            cout << each << \", \";\n        }\n        cout << endl;\n\n        std::vector<float> x_values, y_values, coeff;\n        for (int i=0; i<best_line->getModelDefParams().size(); i++){\n            auto best_line_pt = std::dynamic_pointer_cast<GRANSAC::Point2D>(best_line->getModelDefParams()[i]);\n            x_values.push_back(best_line_pt->m_point2D[0]); //x\n            y_values.push_back(best_line_pt->m_point2D[1]); //x\n            cv::Point pt(floor(best_line_pt->m_point2D[0]), floor(best_line_pt->m_point2D[1]));\n            cv::circle(img_canvas, pt, floor(side / 100), cv::Scalar(0, 0, 255), -1, cv::LINE_AA);\n        }\n\n        // draw polynomial line\n        float start_point_x = 0;\n        float end_point_x = side;\n        vector<cv::Point2f> curve_points;\n        //Define the curve through equation. In this example, a simple parabola\n        for (float x = start_point_x; x <= end_point_x; x+=1){\n            float y = 0;\n            for (int j = 0; j < best_line->getModelCoefficients().size(); j++){\n                y += best_line->getModelCoefficients()[j]*std::pow(x, float(j));\n            } \n\n            cv::Point2f new_point = cv::Point2f(x, y);                  //resized to better visualize\n            curve_points.push_back(new_point);                       //add point to vector/list\n        }\n        for (int i = 0; i < curve_points.size() - 1; i++){\n            cv::line(img_canvas, curve_points[i], curve_points[i + 1], cv::Scalar(0,255,0), 2, CV_AA);\n        }\n    }\n\n    while (true)\n    {\n        cv::imshow(\"RANSAC Example\", img_canvas);\n        char Key = cv::waitKey(1);\n        if (Key == 27)\n            return 0;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "00705a28a36e2b123359052603cdd044c440a827", "size": 5653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/lls_fitting_example.cpp", "max_stars_repo_name": "masszhou/GRANSAC", "max_stars_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_stars_repo_licenses": ["MIT"], "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/lls_fitting_example.cpp", "max_issues_repo_name": "masszhou/GRANSAC", "max_issues_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_issues_repo_licenses": ["MIT"], "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/lls_fitting_example.cpp", "max_forks_repo_name": "masszhou/GRANSAC", "max_forks_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_forks_repo_licenses": ["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.0063694268, "max_line_length": 170, "alphanum_fraction": 0.5770387405, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6657764309370606}}
{"text": "#define BOOST_TEST_MODULE Logic test\n#include <boost/test/unit_test.hpp>\n\n#include \"Variable.h\"\n\nusing namespace omnn::math;\n\nBOOST_AUTO_TEST_CASE(ifz_tests)\n{\n    // two different bits\n    // if a=0 then b=1 else b=0\n    // if a=1 then b=0 else b=1\n    Variable a,b;\n    auto e = a.Equals(1).Ifz(b.Equals(0), b.Equals(1));\n    {\n        auto ee = e;\n        ee.Eval(a, 0);\n        ee.Eval(b, 1);\n        ee.optimize();\n        BOOST_TEST(ee==0);\n    }\n    {\n        auto ee = e;\n        ee.Eval(a, 1);\n        ee.Eval(b, 0);\n        ee.optimize();\n        BOOST_TEST(ee==0);\n    }\n// TODO :   {\n//        auto ee = e;\n//        ee.Eval(a,1); // b == 0\n//        ee.optimize();\n//        auto solutions = ee(b);\n//        BOOST_TEST(solutions.size()==1);\n//        BOOST_TEST(*solutions.begin()==0);\n//    }\n// TODO :\n//    {\n//        auto ee = e;\n//        ee.Eval(a, 0); // b == 1\n//        ee.optimize();\n//        auto solutions = ee(b);\n//        BOOST_TEST(solutions.size()==1);\n//        BOOST_TEST(*solutions.begin()==1);\n//    }\n}\n", "meta": {"hexsha": "fc508f3b9f5d29fc9154ac78b746bbe5d13c4536", "size": 1041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/logic.cpp", "max_stars_repo_name": "leannejdong/openmind", "max_stars_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T06:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T06:47:44.000Z", "max_issues_repo_path": "omnn/math/test/logic.cpp", "max_issues_repo_name": "leannejdong/openmind", "max_issues_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "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": "omnn/math/test/logic.cpp", "max_forks_repo_name": "leannejdong/openmind", "max_forks_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "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.1489361702, "max_line_length": 55, "alphanum_fraction": 0.4812680115, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6657578532909558}}
{"text": "#include <iostream>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\n\nusing namespace boost::numeric::odeint;\n\nconst double b = 0.1;\nconst double g = 0.05;\n\ntypedef boost::array< double , 3 > state_type;\n\nvoid sir( const state_type &x , state_type &dxdt , double t )\n{\n    dxdt[0] = -b * x[0] * x[1];\n    dxdt[1] = b * x[0] * x[1] - g * x[1];\n    dxdt[2] = g * x[1];\n}\n\nvoid write_sir(const state_type &x , const double t )\n{\n    std::cout << t << ' ' << x[0] << ' ' << x[1] << ' ' << x[2] << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n    state_type x = { 0.99 , 0.01 , 0.0 }; // initial conditions\n    integrate( sir , x , 0.0 , 200.0 , 0.1 , write_sir );\n}\n", "meta": {"hexsha": "7cea7d9d50a790cdc6968ca9bd6ce21a5f29c04d", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/simple_deterministic_models/sir/sir.cpp", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "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/simple_deterministic_models/sir/sir.cpp", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "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/simple_deterministic_models/sir/sir.cpp", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 22.6666666667, "max_line_length": 77, "alphanum_fraction": 0.5632352941, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6657578471843814}}
{"text": "\n\n// Spline fit with unknown parameter positions.\n\n\n#include <iostream>\n\n#include \"main.h\"\n#include <unsupported/Eigen/LevenbergMarquardt>\n#include <unsupported/Eigen/SparseExtra>\n\n#include <Eigen/Eigen>\n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n// This disables some useless Warnings on MSVC.\n// It is intended to be done for this test only.\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n\n#define NUM_SAMPLE_POINTS 100\n\nstruct SplineParameter {\n  int segment;\n  double t;\n};\n\ntemplate <typename _Scalar>\nstruct SplineFitting : LevenbergMarquardtFunctor<_Scalar>\n{\n  typedef LevenbergMarquardtFunctor<Scalar> Base;\n\n  typedef int Index;\n  typedef Matrix<Scalar, Dynamic, 1> InputType;\n  typedef Matrix<Scalar, Dynamic, 1> ValueType;\n  typedef Matrix<Scalar, Dynamic, 1> StepType;\n\n  typedef SparseMatrix<Scalar, ColMajor, Index> JacobianType;\n\n  typedef SparseQR<SparseMatrix<Scalar>, COLAMDOrdering<int> > BlockSolver;\n  typedef ColPivHouseholderQR<Matrix<Scalar, Dynamic, Dynamic> > DenseSolver;\n  typedef BlockDiagonalSparseQR<JacobianType, DenseSolver> LeftSuperBlockSolver;\n  typedef BlockSparseQR<JacobianType, LeftSuperBlockSolver, DenseSolver> QRSolver;\n\n  const Eigen::Matrix<double, 3, Eigen::Dynamic> SplinePoints;\n\n  static const int nParamsModel = 5;\n\n  SplineFitting(Eigen::Matrix<double, 3, Eigen::Dynamic>& points) :\n    Base(nParamsModel + points.cols(), points.cols() * 2),\n    SplinePoints(points)\n  {\n  }\n\n  // Functor functions\n  int operator()(const InputType& uv, ValueType& fvec) {\n    int npoints = SplinePoints.cols();\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    for (int i = 0; i < npoints; 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) = SplinePoints(0, i) - x;\n      fvec(2 * i + 1) = SplinePoints(1, i) - y;\n    }\n\n    return 0;\n  }\n\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 = SplinePoints.cols();\n    auto params = uv.tail(nParamsModel);\n    double a = params[0];\n    double b = params[1];\n    double r = params[4];\n    for (int i = 0; i<npoints; i++) {\n      double t = uv(i);\n      fjac.coeffRef(2 * i, npoints + 0) = -cos(t)*cos(r);\n      fjac.coeffRef(2 * i, npoints + 1) = +sin(t)*sin(r);\n      fjac.coeffRef(2 * i, npoints + 2) = -1;\n      fjac.coeffRef(2 * i, npoints + 4) = +a*cos(t)*sin(r) + b*sin(t)*cos(r);\n      fjac.coeffRef(2 * i, i) = +a*cos(r)*sin(t) + b*sin(r)*cos(t);\n\n      fjac.coeffRef(2 * i + 1, npoints + 0) = -cos(t)*sin(r);\n      fjac.coeffRef(2 * i + 1, npoints + 1) = -sin(t)*cos(r);\n      fjac.coeffRef(2 * i + 1, npoints + 3) = -1;\n      fjac.coeffRef(2 * i + 1, npoints + 4) = -a*cos(t)*cos(r) + b*sin(t)*sin(r);\n      fjac.coeffRef(2 * i + 1, i) = +a*sin(r)*sin(t) - b*cos(r)*cos(t);\n    }\n\n    fjac.makeCompressed();\n    return 0;\n  }\n\n\n  void initQRSolver(QRSolver &qr) {\n    // set block size\n    qr.getLeftSolver().setSparseBlockParams(2, 1);\n    qr.setBlockParams(SplinePoints.cols());\n  }\n\n  void increment_in_place(InputType* x, StepType const& p)\n  {\n    *x += p;\n  }\n\n  double estimateNorm(InputType const& x, StepType const& diag)\n  {\n    return x.cwiseProduct(diag).stableNorm();\n  }\n};\n\n\nvoid testSplineFitting() {\n\n  // Spline 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  Eigen::Matrix<double, 3, Eigen::Dynamic> SplinePoints;\n  SplinePoints.resize(3, nDataPoints);\n  double incr = 1.3*EIGEN_PI / double(nDataPoints);\n  for (int i = 0; i<nDataPoints; i++) {\n    double t = double(i)*incr;\n    SplinePoints(0, i) = x0 + a*cos(t)*cos(r) - b*sin(t)*sin(r);\n    SplinePoints(1, i) = y0 + a*cos(t)*sin(r) + b*sin(t)*cos(r);\n    SplinePoints(2, i) = 1;\n  }\n\n  // INITIAL PARAMS\n  SplineFitting<double>::InputType lm_params;\n  auto& params = lm_params;\n  params.resize(SplineFitting<double>::nParamsModel + nDataPoints);\n  double minX, minY, maxX, maxY;\n  minX = maxX = SplinePoints(0, 0);\n  minY = maxY = SplinePoints(1, 0);\n  for (int i = 0; i<SplinePoints.cols(); i++) {\n    minX = (std::min)(minX, SplinePoints(0, i));\n    maxX = (std::max)(maxX, SplinePoints(0, i));\n    minY = (std::min)(minY, SplinePoints(1, i));\n    maxY = (std::max)(maxY, SplinePoints(1, i));\n  }\n  params(SplinePoints.cols()) = 0.5*(maxX - minX);\n  params(SplinePoints.cols() + 1) = 0.5*(maxY - minY);\n  params(SplinePoints.cols() + 2) = 0.5*(maxX + minX);\n  params(SplinePoints.cols() + 3) = 0.5*(maxY + minY);\n  params(SplinePoints.cols() + 4) = 0;\n  for (int i = 0; i<SplinePoints.cols(); i++) {\n    params(i) = double(i)*incr;\n  }\n\n  std::cout << \"INITIALIZATION\" << \" \";\n  std::cout << \"a=\" << params(SplinePoints.cols()) << \"\\t\";\n  std::cout << \"b=\" << params(SplinePoints.cols() + 1) << \"\\t\";\n  std::cout << \"x0=\" << params(SplinePoints.cols() + 2) << \"\\t\";\n  std::cout << \"y0=\" << params(SplinePoints.cols() + 3) << \"\\t\";\n  std::cout << \"r=\" << params(SplinePoints.cols() + 4)*180. / EIGEN_PI << \"\\t\";\n  std::cout << std::endl << std::endl;\n\n  SplineFitting<double> functor(SplinePoints);\n  Eigen::LevenbergMarquardt< SplineFitting<double> > lm(functor);\n  Eigen::LevenbergMarquardtSpace::Status info;\n\n  info = lm.minimizeInit(lm_params);\n  if (info == Eigen::LevenbergMarquardtSpace::ImproperInputParameters) {\n    std::cerr << \"Improper Input Parameters\" << std::endl;\n    return;\n  }\n\n  do {\n    info = lm.minimizeOneStep(lm_params);\n  } while (info == Eigen::LevenbergMarquardtSpace::Running);\n\n  std::cout << \"END\" << \" \";\n  std::cout << \"a=\" << params(SplinePoints.cols()) << \"\\t\";\n  std::cout << \"b=\" << params(SplinePoints.cols() + 1) << \"\\t\";\n  std::cout << \"x0=\" << params(SplinePoints.cols() + 2) << \"\\t\";\n  std::cout << \"y0=\" << params(SplinePoints.cols() + 3) << \"\\t\";\n  std::cout << \"r=\" << params(SplinePoints.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(SplinePoints.cols() + 1)) > fabs(params(SplinePoints.cols()))) {\n    std::swap(params(SplinePoints.cols()), params(SplinePoints.cols() + 1));\n    params(SplinePoints.cols() + 4) -= 0.5*EIGEN_PI;\n  }\n  // a and b should be positive\n  if (params(SplinePoints.cols())<0) {\n    params(SplinePoints.cols()) *= -1.;\n    params(SplinePoints.cols() + 1) *= -1.;\n    params(SplinePoints.cols() + 4) += EIGEN_PI;\n  }\n  // fix rotation angle range\n  while (params(SplinePoints.cols() + 4) < 0) params(SplinePoints.cols() + 4) += 2.*EIGEN_PI;\n  while (params(SplinePoints.cols() + 4) > EIGEN_PI) params(SplinePoints.cols() + 4) -= EIGEN_PI;\n\n\n  eigen_assert(fabs(a - params(SplinePoints.cols())) < 0.00001);\n  eigen_assert(fabs(b - params(SplinePoints.cols() + 1)) < 0.00001);\n  eigen_assert(fabs(x0 - params(SplinePoints.cols() + 2)) < 0.00001);\n  eigen_assert(fabs(y0 - params(SplinePoints.cols() + 3)) < 0.00001);\n  eigen_assert(fabs(r - params(SplinePoints.cols() + 4)) < 0.00001);\n\n\n\n}\n\n\nvoid test_spline_fitting()\n{\n  CALL_SUBTEST(testSplineFitting());\n}\n", "meta": {"hexsha": "ce3c8931feb1bd2e1c5986d8291e65ae7ea6a27e", "size": 7621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pr/unsupported/test/spline_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/spline_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/spline_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": 32.429787234, "max_line_length": 97, "alphanum_fraction": 0.6206534576, "num_tokens": 2534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6655066021229994}}
{"text": "/**\n * @file cd_tools.cc\n * @brief Utility Functions for the Convection-Diffusion Problem\n * @author Philippe Peter\n * @date July 2021\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"cd_tools.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <memory>\n\nnamespace ConvectionDiffusion {\n\ndouble Diameter(const lf::mesh::Entity& entity) {\n  const lf::geometry::Geometry* geo_p = entity.Geometry();\n  Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n\n  switch (entity.RefEl()) {\n    case lf::base::RefEl::kTria(): {\n      // Diameter of a triangle corresponds to the longest edge\n      Eigen::Vector2d e0 = corners.col(1) - corners.col(0);\n      Eigen::Vector2d e1 = corners.col(2) - corners.col(1);\n      Eigen::Vector2d e2 = corners.col(0) - corners.col(1);\n      return std::max(e0.norm(), std::max(e1.norm(), e2.norm()));\n    }\n    case lf::base::RefEl::kQuad(): {\n      // Diameter of a (convex) quadrilateral corresponds to the longer diagonal\n      Eigen::Vector2d d0 = corners.col(2) - corners.col(0);\n      Eigen::Vector2d d1 = corners.col(3) - corners.col(1);\n      return std::max(d0.norm(), d1.norm());\n    }\n    default: {\n      LF_ASSERT_MSG(false,\n                    \"Diameter not available for \" << entity.RefEl().ToString());\n    }\n  }\n}  // namespace ConvectionDiffusion\n\ndouble MeshWidth(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  double h = 0.0;\n  for (const lf::mesh::Entity* entity_p : mesh_p->Entities(0)) {\n    h = std::max(h, Diameter(*entity_p));\n  }\n  return h;\n}\n\n}  // namespace ConvectionDiffusion\n", "meta": {"hexsha": "e05aaabab64e26998ee85ebf44a65be36a79ea56", "size": 1642, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/ConvectionDiffusion/cd_tools.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": "lecturecodes/ConvectionDiffusion/cd_tools.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": "lecturecodes/ConvectionDiffusion/cd_tools.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": 29.8545454545, "max_line_length": 80, "alphanum_fraction": 0.6485992692, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6654896118528629}}
{"text": "/**\n * @file    Types.hpp\n *\n * @author  btran\n *\n */\n\n#pragma once\n\n#include <memory>\n#include <string>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace perception\n{\nclass CameraInfo\n{\n public:\n    using Ptr = std::shared_ptr<CameraInfo>;\n\n    explicit CameraInfo(const std::string cameraInfoPath);\n    ~CameraInfo();\n\n    const Eigen::Matrix3d& K() const;\n\n private:\n    Eigen::Matrix3d m_K;\n};\n\nusing TransformInfo = Eigen::Matrix<double, 6, 1>;  // x, y, z, r, p, y\n}  // namespace perception\n", "meta": {"hexsha": "38ed84aeec7c1b15de97ee07f12e93a3ce8dfaa1", "size": 505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sensors_calib/Types.hpp", "max_stars_repo_name": "xmba15/automatic_lidar_camera_calibration", "max_stars_repo_head_hexsha": "a3bcf26e4cb0c38a5f7bb62c9e4e86a4c38c7b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-11-10T01:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:02:41.000Z", "max_issues_repo_path": "include/sensors_calib/Types.hpp", "max_issues_repo_name": "xmba15/automatic_lidar_camera_calibration", "max_issues_repo_head_hexsha": "a3bcf26e4cb0c38a5f7bb62c9e4e86a4c38c7b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T02:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-09T06:52:17.000Z", "max_forks_repo_path": "include/sensors_calib/Types.hpp", "max_forks_repo_name": "xmba15/automatic_lidar_camera_calibration", "max_forks_repo_head_hexsha": "a3bcf26e4cb0c38a5f7bb62c9e4e86a4c38c7b42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-11-01T16:37:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T16:56:13.000Z", "avg_line_length": 14.8529411765, "max_line_length": 71, "alphanum_fraction": 0.6495049505, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6654267326226719}}
{"text": "#ifndef CANNON_ML_RLS_H\n#define CANNON_ML_RLS_H \n\n/*!\n * \\file cannon/ml/rls.hpp\n * \\brief File containing RLSFilter class definition.\n */\n\n#include <utility>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Class representing a Recursive Least Squares Filter supporting\n     * intercept estimation and forgetting. See\n     * http://cannontwo.com/assets/rls_notes.pdf.\n     */\n    class RLSFilter {\n      public:\n\n        RLSFilter() = delete;\n\n        /*!\n         * \\brief Constructor taking input dimension, output dimension, inverse\n         * covariance matrix initialization alpha, and forgetting factor.\n         */\n        RLSFilter(unsigned int in_dim, unsigned int out_dim,\n                  double alpha = 1.0e6, double forgetting = 1.0)\n            : in_dim_(in_dim), out_dim_(out_dim), param_dim_(in_dim),\n              alpha_(alpha), forgetting_(forgetting),\n              intercept_(VectorXd::Zero(out_dim_)),\n              theta_(MatrixXd::Zero(param_dim_, out_dim_)),\n              corrected_theta_(MatrixXd::Zero(param_dim_, out_dim_)),\n              feat_mean_(RowVectorXd::Zero(param_dim_)),\n              output_mean_(RowVectorXd::Zero(out_dim_)),\n              covar_(MatrixXd::Identity(param_dim_, param_dim_) * alpha_),\n              pred_error_covar_(MatrixXd::Zero(out_dim_, out_dim_)) {}\n\n        /*!\n         * \\brief Get number of data points contributing to this filter.\n         *\n         * \\returns Number of data points used to fit this filter.\n         */\n        unsigned int get_num_data() const;\n\n        /*!\n         * \\brief Process a single datum and update this filter.\n         *\n         * \\param in_vec Input features of the datum to process.\n         * \\param output Output features of the datum to process.\n         */\n        void process_datum(const VectorXd& in_vec, const VectorXd& output);\n\n        /*!\n         * \\brief Get the identified linear parameters and offset vector fit by\n         * this filter.\n         *\n         * \\returns A pair containing the linear parameters and offset vector.\n         */ \n        std::pair<MatrixXd, VectorXd> get_identified_mats() const;\n        \n        /*!\n         * \\brief Get prediction error covariance matrix for this filter.\n         *\n         * \\returns Prediction error covariance matrix.\n         */\n        MatrixXd get_pred_error_covar() const;\n\n        /*!\n         * \\brief Predict the value of the linear approximation fit by this\n         * filter for the input point.\n         *\n         * \\param in_vec Input features of point to predict for.\n         *\n         * \\returns Prediction fit by this filter.\n         */\n        VectorXd predict(const VectorXd& in_vec) const;\n\n        /*!\n         * \\brief Set the parameters of this RLS filter. Input and output mean\n         * are recovered from the intercept.\n         *\n         * \\param theta Parameter matrix to set.\n         * \\param intercept Intercept to set.\n         * \\param in_mean Input mean. \n         */\n        void set_params(const Ref<const MatrixXd> &theta,\n                        const Ref<const VectorXd> &intercept,\n                        const Ref<const VectorXd> &in_mean);\n\n        /*!\n         * \\brief Reset this filter.\n         */\n        void reset();\n\n      private:\n\n        /*!\n         * \\brief Make internal feature vector for the input features.\n         *\n         * \\param in_vec Input features to transform into internal feature space.\n         *\n         * \\returns Internal features.\n         */\n        RowVectorXd make_feature_vec_(const VectorXd& in_vec) const;\n        \n        /*!\n         * \\brief Make U matrix for inverse covariance matrix update.\n         *\n         * \\param feat Internal feature vector for update.\n         *\n         * \\returns U matrix.\n         */\n        MatrixX2d make_u_(const RowVectorXd& feat) const;\n\n        /*!\n         * \\brief Make V matrix for inverse covariance matrix update.\n         *\n         * \\param feat Internal feature vector for update.\n         *\n         * \\returns V matrix.\n         */\n        Matrix2Xd make_v_(const RowVectorXd& feat) const;\n\n        /*!\n         * \\brief Make C matrix for inverse covariance matrix update.\n         *\n         * \\returns C matrix.\n         */\n        Matrix2d make_c_() const;\n\n        /*!\n         * \\brief Update inverse covariance matrix for this filter.\n         *\n         * \\param u U matrix\n         * \\param c C matrix\n         * \\param v V matrix\n         */\n        void update_covar_(const MatrixX2d& u, const Matrix2d& c, \n            const Matrix2Xd& v);\n\n        /*!\n         * \\brief Update linear approximation stored by this filter.\n         *\n         * \\param c_t C matrix transpose.\n         * \\param feat Internal feature vector for new datum.\n         * \\param output Output for new datum.\n         */\n        void update_theta_(const MatrixXd& c_t, const RowVectorXd& feat, \n            const VectorXd& output);\n        \n        /*!\n         * \\brief Update output mean for this filter.\n         *\n         * \\param output Observed output.\n         */\n        void update_output_mean_(const VectorXd& output);\n\n        /*!\n         * \\brief Update internal feature mean for this filter.\n         *\n         * \\param feat Observed internal features.\n         */\n        void update_feat_mean_(const RowVectorXd& feat);\n\n        /*!\n         * \\brief Update prediction error covariance matrix in light of an\n         * observed datum.\n         *\n         * \\param in_vec Input feature vector.\n         * \\param output Observed output.\n         */\n        void update_pred_error_covar_(const VectorXd& in_vec, const VectorXd& output);\n\n        // Parameters\n        unsigned int in_dim_; //!< Dimension of input to this filter.\n        unsigned int out_dim_; //!< Dimension of output for this filter.\n        unsigned int param_dim_; //!< Number of linear parameters of this filter.\n        double alpha_; //!< Inverse covariance matrix initialization parameter.\n        double forgetting_; //!< Forgetting factor.\n        double t_ = 0.0; //!< Number of observed data points.\n\n        // Matrices\n        VectorXd intercept_; //!< Intercept vector of filter\n        MatrixXd theta_; //!< Linear parameters of filter\n        MatrixXd corrected_theta_; //!< Linear parameters corrected for intercept\n        RowVectorXd feat_mean_; //!< Mean of internal features for this filter\n        RowVectorXd output_mean_; //!< Mean of observed outputs for this filter\n        MatrixXd covar_; //!< Internal inverse covariance matrix.\n        MatrixXd pred_error_covar_; //!< Prediction error covariance matrix for this filter.\n\n    };\n\n  } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_RLS_H */\n", "meta": {"hexsha": "83fd3766e22b144fc6950a5732f0982f69ba6d08", "size": 6780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/rls.hpp", "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": "cannon/ml/rls.hpp", "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": "cannon/ml/rls.hpp", "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": 33.3990147783, "max_line_length": 92, "alphanum_fraction": 0.589380531, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6654150025965393}}
{"text": "/* Basic example showing the usage of QuantLibAdjoint\n*/\n\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/instruments/makevanillaswap.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n\n#include <boost/make_shared.hpp>\n\n#include <iostream>\n\nusing namespace QuantLib;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::ios;\n\nint main(int, char* []) {\n\t\n\tDate referenceDate(3, Aug, 2016);\n\tSettings::instance().evaluationDate() = referenceDate;\n\tActual365Fixed dayCounter;\n\t\n\t// Example 1\n\t\n\t// These will be the X (independent) and Y (dependent) vectors\n\tvector<Rate> zeroRate(1, 0.02);\n\tvector<Rate> swapNpv(1, 0.0);\n\n\t// Start taping with zeroRate as independent variable and set up flat zero curve\n\tcl::Independent(zeroRate);\n\tRelinkableHandle<YieldTermStructure> flatCurve(boost::make_shared<FlatForward>(referenceDate, zeroRate[0], dayCounter));\n\tflatCurve->enableExtrapolation();\n\n\t// Create and price swap\n\tPeriod swapTenor(5, Years);\n\tboost::shared_ptr<IborIndex> iborIndex = boost::make_shared<Euribor6M>(flatCurve);\n\tRate fixedRate = 0.03;\n\tPeriod forwardStart(0, Days);\n\tboost::shared_ptr<VanillaSwap> swap = MakeVanillaSwap(swapTenor, iborIndex, fixedRate, forwardStart) .withNominal(100);\n\tswapNpv[0] = swap->NPV();\n\n\t// Stop taping and transfer operation sequence to function f (ultimately an AD function object)\n\tcl::tape_function<double> f(zeroRate, swapNpv);\n\n\t// Calculate d(swapNpv) / d(zero) with forward and reverse mode\n\tvector<double> dZ(1, 1.0);\n\tdouble forwardDeriv = f.Forward(1, dZ)[0];\n\tdouble reverseDeriv = f.Reverse(1, dZ)[0];\n\n\t// Calculate analytically the derivative\n\tReal derivative = 0.0;\n\tconst Leg& fixedLeg = swap->fixedLeg();\n\tfor (const auto& cf : fixedLeg) {\n\t\tReal amount = cf->amount();\n\t\tTime time = dayCounter.yearFraction(referenceDate, cf->date());\n\t\tDiscountFactor discount = flatCurve->discount(time);\n\t\tderivative += amount * time * discount;\n\t}\n\tTime timeToStart = dayCounter.yearFraction(referenceDate, swap->startDate());\n\tTime timeToEnd = dayCounter.yearFraction(referenceDate, swap->maturityDate());\n\tderivative += 100*(timeToEnd * flatCurve->discount(timeToEnd) - timeToStart * flatCurve->discount(timeToStart));\n\n\t//Compare bumped value to Taylor approximation\n\tReal basis_point = 0.01; \n\tReal approx_sensitivity = derivative * basis_point;\n\t//new bumped yield curve\n\t//when yield curve changes, swap recalculates \n\tflatCurve.linkTo(boost::make_shared<FlatForward>(referenceDate, zeroRate[0] + basis_point, dayCounter));\n\tReal bumped_npv = swap->NPV();\n\n\n\t// Output the results\n\tcout.precision(9);\n\tcout.setf(ios::fixed, ios::floatfield);\n\tcout << \"Forward derivative:  \" << forwardDeriv << endl;\n\tcout << \"Reverse derivative:  \" << reverseDeriv << endl;\n\tcout << \"Analytic derivative: \" << derivative << endl;\n\t//approx should be close to bumped\n\tcout << \"Approx_Sensitivity: \" << approx_sensitivity << endl;\n\tcout << \"Bumped Sensitivity: \" << bumped_npv - swapNpv[0] << endl;\n\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "137dab6140dad9a985d295afbc49790f876e5d78", "size": 2973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/BasicExample/basicexample.cpp", "max_stars_repo_name": "kedonaghey/QuantLibAdjoint", "max_stars_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T13:31:35.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T13:31:35.000Z", "max_issues_repo_path": "Examples/BasicExample/basicexample.cpp", "max_issues_repo_name": "kedonaghey/QuantLibAdjoint", "max_issues_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "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/BasicExample/basicexample.cpp", "max_forks_repo_name": "kedonaghey/QuantLibAdjoint", "max_forks_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "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.1724137931, "max_line_length": 121, "alphanum_fraction": 0.7346115035, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6652529777238508}}
{"text": "/**\n * @ file pointEvaluation.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author Christian Mitsch, Liaowang Huang (refactoring)\n * @ date 22/03/2019, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"pointevaluationrhs.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <utility>\n\n#include \"pointevaluationrhs_norms.h\"\n\nnamespace PointEvaluationRhs {\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::Vector2d GlobalInverseTria(Eigen::Matrix<double, 2, 3> mycorners,\n                                  Eigen::Vector2d x) {\n  Eigen::Vector2d x_hat;\n\n#if SOLUTION\n  // The unique affine mapping of the unit triangle to a general triangle\n  // is given by the formula $\\cob{\\Bx = \\VA_K*\\wh{\\Bx} + \\Bs}$,\n  // Use the vertex coordinates to calculate matrix A and translation vector s\n  Eigen::Matrix2d A(2, 2);\n  A.col(0) = mycorners.col(1) - mycorners.col(0);\n  A.col(1) = mycorners.col(2) - mycorners.col(0);\n  // The inverse mapping: $\\cob{\\wh{\\Bx} = \\VA_K^{-1} * (\\Bx - \\Ba_0)}$\n  x_hat = A.partialPivLu().solve(x - mycorners.col(0));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return x_hat;\n}\n/* SAM_LISTING_END_5 */\n\n/** @brief Numerically stable solution of a quadratic equation in R\n * @param a,b,c coefficients of quadratic polynomias ax^2+bx+c\n * @return both zeros, NaN if complex\n */\n/* SAM_LISTING_BEGIN_4 */\nstd::pair<double, double> solveQuadraticEquation(double a, double b, double c) {\n  // Implement the cases which are solvable and return their solutions\n#if SOLUTION\n  if (a != 0.) {\n    b /= a;\n    c /= a;\n    const double D = b * b - 4 * c;  // discriminant\n    if (D >= 0) {                    // real solutions\n      const double rtD = std::sqrt(D);\n      // Real solutions, cancellation-free formulas !\n      if (b < 0) {\n        const double root = 0.5 * (-b + rtD);\n        return {root, c / root};\n      } else {  // b >= 0\n        const double root = 0.5 * (-b - rtD);\n        return {root, c / root};\n      }\n    }\n  } else {\n    if (b != 0.0) {\n      return {-c / b, -c / b};\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  // Return NAN if there are no (real) roots\n  return {NAN, NAN};\n}\n\n/* SAM_LISTING_END_4 */\n\n/** @brief Computes the area of a triangle\n * @param a,b,c vertex coordinate vectors\n */\ninline double triaArea(const Eigen::Vector2d a, const Eigen::Vector2d b,\n                       const Eigen::Vector2d c) {\n  double result = 0;\n#if SOLUTION\n  result = 0.5 * std::abs((b[0] - a[0]) * (c[1] - a[1]) -\n                          (b[1] - a[1]) * (c[0] - a[0]));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return result;\n}\n\nEigen::Vector2d GlobalInverseQuad(Eigen::Matrix<double, 2, 4> vert,\n                                  Eigen::Vector2d x) {\n  constexpr double kEPS = 1.0E-8;\n  Eigen::Vector2d x_hat;\n\n  // Implement and use the functions triaArea and solveQuadraticEquation\n#if SOLUTION\n  /* SAM_LISTING_BEGIN_1 */\n  // I: Find sub-triangle with largest area and use its\n  // middle vertex as new \"vertex 0\".\n  unsigned int vt_zero_idx{0};\n  double max_area{0.0};\n  for (int l = 0; l < 4; ++l) {\n    const double sub_tria_area =\n        triaArea(vert.col(l), vert.col((l + 1) % 4), vert.col((l + 2) % 4));\n    if (sub_tria_area > max_area) {\n      vt_zero_idx = (l + 1) % 4;\n      max_area = sub_tria_area;\n    }\n  }\n  // vt_zero_idx stores the index of the vertex that will now\n  // be regarded as \"pivotal vertex 0\"\n\n  /* SAM_LISTING_END_1 */\n\n  const Eigen::Vector2d corner0 = vert.col(vt_zero_idx);\n  const Eigen::Vector2d corner1 = vert.col((vt_zero_idx + 1) % 4);\n  const Eigen::Vector2d corner2 = vert.col((vt_zero_idx + 2) % 4);\n  const Eigen::Vector2d corner3 = vert.col((vt_zero_idx + 3) % 4);\n\n  /* SAM_LISTING_BEGIN_2 */\n  // Use corners to calculate matrix A, the translation t\n  // and the coefficient vector d\n  Eigen::Matrix2d A(2, 2);\n  A.col(0) = corner1 - corner0;\n  A.col(1) = corner3 - corner0;\n  Eigen::Vector2d t = corner0;\n  Eigen::Vector2d d = corner2 + corner0 - corner1 - corner3;\n\n  // Calculate the coefficients in the non-linear system of equations\n  Eigen::Vector2d y = A.partialPivLu().solve(x - t);\n  Eigen::Vector2d q = A.partialPivLu().solve(d);\n  Eigen::Vector2d q_orth(q(1), -q(0));\n\n  // Treat exceptional cases\n  // If q vanishes\n  const double ref_size = y.norm();\n  if (q.norm() < kEPS * ref_size) {\n    x_hat = y;\n  } else if (std::abs(q(0)) < kEPS * ref_size) {\n    x_hat(0) = y(0);\n    x_hat(1) = y(1) / (1 + q(1) * x_hat(0));\n  } else if (std::abs(q(1)) < kEPS * ref_size) {\n    x_hat(1) = y(1);\n    x_hat(0) = y(0) / (1 + q(0) * x_hat(1));\n  } else {\n    // Generic case; solve quadratic equation\n    double a = q(0);\n    double b = 1 + y.dot(q_orth);\n    double c = -y(1);\n\n    auto [x_op1, x_op2] = solveQuadraticEquation(a, b, c);\n    // No solution\n    if (std::isnan(x_op1) || std::isnan(x_op2)) {\n      x_hat(0) = NAN;\n      x_hat(1) = NAN;\n    } else {\n      // There is a solution\n      // Find root in the unit interval -> x_op1\n      if ((x_op1 < 0.) || (x_op1 > 1.)) {\n        if ((x_op2 >= 0.) && (x_op2 <= 1.)) {\n          x_op1 = x_op2;\n        }\n      }\n      x_hat(1) = x_op1;\n      x_hat(0) = (y.dot(q_orth) + q(0) * x_hat(1)) / q(1);\n    }\n  }\n  /* SAM_LISTING_END_2 */\n  /* SAM_LISTING_BEGIN_3 */\n  // Reverse initial permutation\n  switch (vt_zero_idx) {\n    case 1: {\n      x_hat = ((Eigen::Matrix2d() << 0., -1., 1., 0.)).finished() * x_hat +\n              Eigen::Vector2d(1.0, 0.0);\n      break;\n    }\n    case 2: {\n      x_hat = -x_hat + Eigen::Vector2d(1.0, 1.0);\n      break;\n    }\n    case 3: {\n      x_hat = ((Eigen::Matrix2d() << 0., 1., -1., 0.)).finished() * x_hat +\n              Eigen::Vector2d(0.0, 1.0);\n      break;\n    }\n  }\n    /* SAM_LISTING_END_3 */\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return x_hat;\n}\n\nstd::pair<double, double> normsSolutionPointLoadDirichletBVP(\n    const lf::assemble::DofHandler &dofh, Eigen::Vector2d source_point,\n    Eigen::VectorXd &sol_vec) {\n  std::pair<double, double> result(0, 0);\n  const unsigned int N_dofs = dofh.NumDofs();\n  sol_vec.resize(N_dofs);\n  sol_vec.setZero();\n#if SOLUTION\n  /* SAM_LISTING_BEGIN_7 */\n  // Assemble matrix A\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n  lf::uscalfe::LinearFELaplaceElementMatrix loc_mat_laplace{};\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, loc_mat_laplace, A);\n  // Build rhs vector using dedicated ENTITY_VECTOR_PROVIDER\n  Eigen::VectorXd rhs(N_dofs);\n  rhs.setZero();\n  PointEvaluationRhs::DeltaLocalVectorAssembler myvec_pro(source_point);\n  lf::assemble::AssembleVectorLocally(0, dofh, myvec_pro, rhs);\n\n  // Enforce Dirichlet boundary conditions\n  const double boundary_val = 0;  // zero Dirichlet boundary conditions\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(dofh.Mesh(), 2)};\n  auto my_selector = [&dofh, &bd_flags, &boundary_val](unsigned int dof_idx) {\n    if (bd_flags(dofh.Entity(dof_idx))) {\n      return (std::pair<bool, double>(true, boundary_val));\n    } else {\n      // interior node: the value we return here does not matter\n      return (std::pair<bool, double>(false, 42.0));\n    }\n  };\n  lf::assemble::FixFlaggedSolutionComponents<double>(my_selector, A, rhs);\n\n  // Solve linear system of equations A*x = rhs\n  const Eigen::SparseMatrix<double> A_crs(A.makeSparse());\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_crs);\n  if (solver.info() == Eigen::Success) {\n    sol_vec = solver.solve(rhs);\n  } else {\n    LF_ASSERT_MSG(false, \"Eigen Factorization failed\");\n  }\n  /* SAM_LISTING_END_7 */\n  // return the norms of the solution vector\n  result = std::pair<double, double>(\n      PointEvaluationRhs::computeL2normLinearFE(dofh, sol_vec),\n      PointEvaluationRhs::computeH1seminormLinearFE(dofh, sol_vec));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return result;\n}\n\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd DeltaLocalVectorAssembler::Eval(const lf::mesh::Entity &cell) {\n  Eigen::VectorXd result;\n  // get the coordinates of the corners of this cell\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  auto vertices = lf::geometry::Corners(*geo_ptr);\n#if SOLUTION\n  Eigen::Vector2d x_hat;\n  // the margin we allow when we determine wether a point is inside an\n  // element\n  const double margin = 1e-10;\n  if (lf::base::RefEl::kTria() == cell.RefEl()) {\n    x_hat = PointEvaluationRhs::GlobalInverseTria(vertices, x_0);\n    result.resize(3);\n    result.setZero();\n    if (x_hat(0) <= 1 + margin && x_hat(0) >= 0 - margin &&\n        x_hat(1) <= 1 + margin && x_hat(1) >= 0 - margin &&\n        x_hat(1) + x_hat(0) <= 1 + margin) {\n      already_found = true;\n      // Barycentric coordinates on reference triangle\n      result[0] = 1.0 - x_hat(0) - x_hat(1);\n      result[1] = x_hat(0);\n      result[2] = x_hat(1);\n    }\n  } else if (lf::base::RefEl::kQuad() == cell.RefEl()) {\n    x_hat = PointEvaluationRhs::GlobalInverseQuad(vertices, x_0);\n    result.resize(4);\n    result.setZero();\n    if (x_hat(0) <= 1 + margin && x_hat(0) >= 0 - margin &&\n        x_hat(1) <= 1 + margin && x_hat(1) >= 0 - margin) {\n      already_found = true;\n      // Local shape functions on unit square\n      result[0] = (1.0 - x_hat(0)) * (1.0 - x_hat(1));\n      result[1] = x_hat(0) * (1.0 - x_hat(1));\n      result[2] = x_hat(0) * x_hat(1);\n      result[3] = (1.0 - x_hat(0)) * x_hat(1);\n    }\n  } else {\n    LF_ASSERT_MSG(\n        false, \"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/* SAM_LISTING_END_6 */\n\n}  // namespace PointEvaluationRhs\n", "meta": {"hexsha": "827acf8bc7fab3855882ef870424a6acb0ed3d7b", "size": 10065, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.6509433962, "max_line_length": 80, "alphanum_fraction": 0.6021857923, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6652405470731572}}
{"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\n#ifndef _SCL_SECURE_NO_WARNINGS\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"OptionData.hpp\" \n#include \"StandardDeviation_StandardError.hpp\"\n#include \"UtilitiesDJD/RNG/NormalGenerator.hpp\"\n#include \"UtilitiesDJD/Geometry/Range.cpp\"\n#include <boost/tuple/tuple.hpp> // include tuple class\n#include <boost/tuple/tuple_io.hpp> // include I/O for tuple\n#include <vector>\n#include <cmath>\n#include <iostream>\n\ntemplate <class T> void print(const std::vector<T>& myList)\n{  // A generic print function for vectors\n\t\n\tstd::cout << std::endl << \"Size of vector is \" << l.size() << \"\\n[\";\n\n\t// We must use a const iterator here, otherwise we get a compiler error.\n\tstd::vector<T>::const_iterator i;\n\tfor (i = myList.begin(); i != myList.end(); ++i)\n\t{\n\t\t\tstd::cout << *i << \",\";\n\n\t}\n\n\tstd::cout << \"]\\n\";\n}\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\t\n\t\treturn (data->r)*X; // r - D\n\t}\n\n\t\n\tdouble diffusion(double t, double X)\n\t{ // Diffusion term\n\t\n\t\tdouble betaCEV = 1.0;\n\t\treturn data->sig * pow(X, betaCEV);\n\t\t\n\t}\n\n\tdouble diffusionDerivative(double t, double X)\n\t{ // Diffusion term, needed for the Milstein method\n\t\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\\n\";\n\n\t/*==========================MODIFIED================================*/\n\tvector<double> price_vec; // create a vector to store prices for each simulation\n\t/*================================================================*/\n\n\t// Batch 1 data\n\tOptionData myOption;\n\tmyOption.K = 65.0;\n\tmyOption.T = 0.25;\n\tmyOption.r = 0.08;\n\tmyOption.sig = 0.3;\n\tmyOption.type = -1;\t// Put -1, Call +1\n\tdouble S_0 = 60.0;\n\n\t//// Batch 2 data\n\t//OptionData myOption;\n\t//myOption.K = 100.0;\n\t//myOption.T = 1.0;\n\t//myOption.r = 0.0;\n\t//myOption.sig = 0.2;\n\t//myOption.type = -1;\t// Put -1, Call +1\n\t//double S_0 = 100.0;\n\n\t//// Batch 4 data\n\t//OptionData myOption;\n\t//myOption.K = 100.0;\n\t//myOption.T = 30.0;\n\t//myOption.r = 0.08;\n\t//myOption.sig = 0.30;\n\t//myOption.type = 1;\t// Put -1, Call +1\n\t//double S_0 = 100.0;\n\n\tlong N = 100;\n\tstd::cout << \"Number of subintervals in time: \";\n\tstd::cin >> N;\n\n\t// Create the basic SDE (Context class)\n\tRange<double> range (0.0, myOption.T);\n\tdouble VOld = S_0;\n\tdouble VNew;\n\n\tstd::vector<double> x = range.mesh(N);\n\t\n\n\t// V2 mediator stuff\n\tlong NSim = 50000;\n\tstd::cout << \"Number of simulations: \";\n\tstd::cin >> NSim;\n\n\tdouble k = myOption.T / double (N);\n\tdouble sqrk = sqrt(k);\n\n\t// Normal random number\n\tdouble dW;\n\tdouble price = 0.0;\t// Option price\n\n\t// NormalGenerator is a base class\n\tNormalGenerator* myNormal = new BoostNormal();\n\n\tusing namespace SDEDefinition;\n\tSDEDefinition::data = &myOption;\n\n\tstd::vector<double> res;\n\tint coun = 0; // Number of times S hits origin\n\n\t// A.\n\tfor (long i = 1; i <= NSim; ++i)\n\t{ // Calculate a path at each iteration\n\t\t\t\n\t\tif ((i/10000) * 10000 == i)\n\t\t{// Give status after each 10000th iteration\n\n\t\t\t\tstd::cout << i << std::endl;\n\t\t}\n\n\t\tVOld = S_0;\n\t\tfor (unsigned long index = 1; index < x.size(); ++index)\n\t\t{\n\n\t\t\t// Create a random number\n\t\t\tdW = myNormal->getNormal();\n\t\t\t\t\n\t\t\t// The FDM (in this case explicit Euler)\n\t\t\tVNew = VOld  + (k * drift(x[index-1], VOld))\n\t\t\t\t\t\t+ (sqrk * diffusion(x[index-1], VOld) * dW);\n\n\t\t\tVOld = VNew;\n\n\t\t\t// Spurious values\n\t\t\tif (VNew <= 0.0) coun++;\n\t\t}\n\t\t\t\n\t\tdouble tmp = myOption.myPayOffFunction(VNew);\n\t\t/*==========================MODIFIED================================*/\n\t\tprice_vec.push_back(tmp); // add each simulation price to the price vector\n\t    /*================================================================*/\n\t\tprice += (tmp)/double(NSim);\n\t}\n\t\n\t// D. Finally, discounting the average price\n\tprice *= exp(-myOption.r * myOption.T);\n\n\t// Cleanup; V2 use scoped pointer\n\tdelete myNormal;\n\n\tstd::cout << \"Price, after discounting: \" << price << \", \" << std::endl;\n\tstd::cout << \"Number of times origin is hit: \" << coun << endl;\n\n\t/*==========================MODIFIED================================*/\n\t// show the standard deviation and standard error \n\tboost::tuple<double, double> SD_SE = get_SD_SE(price_vec, myOption.r, myOption.T);\n\n\tcout << \"SD = \" << get<0>(SD_SE) << \", SE = \" << get<1>(SD_SE) << endl;\n\t/*================================================================*/\n\tsystem(\"Pause\");\n\n\treturn 0;\n}", "meta": {"hexsha": "12435a4c5a6c9d8c120c32ca22ccb86211133e41", "size": 4821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_stars_repo_name": "bondxue/Option-Pricing-Model", "max_stars_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_issues_repo_name": "bondxue/Option-Pricing-Model", "max_issues_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_forks_repo_name": "bondxue/Option-Pricing-Model", "max_forks_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7230769231, "max_line_length": 83, "alphanum_fraction": 0.5907488073, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.665240537120972}}
{"text": "#include <geometrycentral/surface/direction_fields.h>\n\n#include \"geometrycentral/numerical/linear_solvers.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\nnamespace surface {\n\nnamespace {\n\nSparseMatrix<std::complex<double>> computeVertexConnectionLaplacian(IntrinsicGeometryInterface& geometry, int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireVertexIndices();\n  geometry.requireEdgeCotanWeights();\n  geometry.requireTransportVectorsAlongHalfedge();\n\n  int numInvalid = 0;\n\n  std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n  for (Halfedge he : mesh.halfedges()) {\n\n    size_t iTail = geometry.vertexIndices[he.vertex()];\n    size_t iTip = geometry.vertexIndices[he.next().vertex()];\n\n    // Levi-Civita connection between vertices\n    Vector2 rot = geometry.transportVectorsAlongHalfedge[he.twin()].pow(nSym);\n    double weight = geometry.edgeCotanWeights[he.edge()];\n    if (!rot.isFinite() || !isfinite(weight)) {\n#ifndef GC_NLINALG_DEBUG\n      //std::cout << \"computeVertexConnectionLaplacian: Oopsie at \" << iTip << \" x \" << iTail << std::endl;\n#endif\n      weight = 0;\n      rot = Vector2::zero();\n      numInvalid++;\n    }\n\n    triplets.emplace_back(iTail, iTail, weight);\n    triplets.emplace_back(iTail, iTip, -weight * rot);\n  }\n  if (numInvalid > 0) {\n    std::cout << \"computeVertexConnectionLaplacian: \" << numInvalid << \" invalid entried.\" << std::endl;\n  }\n\n  // assemble matrix from triplets\n  Eigen::SparseMatrix<std::complex<double>> vertexConnectionLaplacian(mesh.nVertices(), mesh.nVertices());\n  vertexConnectionLaplacian.setFromTriplets(triplets.begin(), triplets.end());\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<std::complex<double>> eye(mesh.nVertices(), mesh.nVertices());\n  eye.setIdentity();\n  vertexConnectionLaplacian += 1e-9 * eye;\n\n  return vertexConnectionLaplacian;\n}\n\nSparseMatrix<std::complex<double>> computeFaceConnectionLaplacian(IntrinsicGeometryInterface& geometry, int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireFaceIndices();\n  geometry.requireTransportVectorsAcrossHalfedge();\n\n  std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n  for (Face f : mesh.faces()) {\n    size_t i = geometry.faceIndices[f];\n\n    std::complex<double> weightDiagSum = 0;\n    for (Halfedge he : f.adjacentHalfedges()) {\n      if (he.twin().isInterior()) {\n\n        Face neighFace = he.twin().face();\n        size_t j = geometry.faceIndices[neighFace];\n\n        // Levi-Civita connection between the faces\n        Vector2 rot = geometry.transportVectorsAcrossHalfedge[he.twin()].pow(nSym);\n\n        double weight = 1;\n        triplets.emplace_back(i, j, -weight * rot);\n\n        weightDiagSum += weight;\n      }\n    }\n\n    triplets.emplace_back(i, i, weightDiagSum + 1e-9); // Shift to avoid singularity\n  }\n  // assemble matrix from triplets\n  Eigen::SparseMatrix<std::complex<double>> faceConnectionLaplacian(mesh.nFaces(), mesh.nFaces());\n  faceConnectionLaplacian.setFromTriplets(triplets.begin(), triplets.end());\n\n  return faceConnectionLaplacian;\n}\n\n} // namespace\n\nVertexData<Vector2> computeSmoothestVertexDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireVertexIndices();\n  geometry.requireVertexGalerkinMassMatrix();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.vertexGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n  // Find the smallest eigenvector\n  Vector<std::complex<double>> solution = smallestEigenvectorSquare(energyMatrix, massMatrix);\n\n  // Copy the result to a VertexData vector\n  VertexData<Vector2> toReturn(mesh);\n  for (Vertex v : mesh.vertices()) {\n    toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n    toReturn[v] = unit(toReturn[v]);\n  }\n\n  return toReturn;\n}\n\nFaceData<Vector2> computeSmoothestFaceDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireFaceIndices();\n  geometry.requireFaceGalerkinMassMatrix();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.faceGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n  // Find the smallest eigenvector\n  Vector<std::complex<double>> solution = smallestEigenvectorSquare(energyMatrix, massMatrix);\n\n  // Copy the result to a FaceData vector\n  FaceData<Vector2> toReturn(mesh);\n  for (Face f : mesh.faces()) {\n    toReturn[f] = Vector2::fromComplex(solution(geometry.faceIndices[f]));\n    toReturn[f] = unit(toReturn[f]);\n  }\n\n  return toReturn;\n}\n\nVertexData<Vector2> computeSmoothestBoundaryAlignedVertexDirectionField(IntrinsicGeometryInterface& geometry,\n                                                                        int nSym) {\n  SurfaceMesh& mesh = geometry.mesh;\n\n  if (!mesh.hasBoundary()) {\n    throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n  }\n\n  geometry.requireVertexGalerkinMassMatrix();\n  geometry.requireHalfedgeVectorsInVertex();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.vertexGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n  // Compute the boundary values\n  VertexData<std::complex<double>> boundaryValues(mesh);\n  for (Vertex v : mesh.vertices()) {\n    if (v.isBoundary()) {\n\n      // Find incoming and outgoing boundary vectors as tangent\n      Halfedge heBoundaryA = v.halfedge();\n      Halfedge heBoundaryB = heBoundaryA.twin().next();\n\n      Vector2 vecA = geometry.halfedgeVectorsInVertex[heBoundaryA];\n      Vector2 vecB = geometry.halfedgeVectorsInVertex[heBoundaryB];\n\n      Vector2 tangentV = unit(-vecA + vecB);\n      Vector2 normalV = tangentV.rotate90();\n\n      boundaryValues[v] = normalV.pow(nSym);\n    } else {\n      boundaryValues[v] = 0;\n    }\n  }\n\n  // Assemble right-hand side from these boundary values\n  Vector<std::complex<double>> b(mesh.nVertices());\n  b.setZero();\n\n  for (Vertex v : mesh.vertices()) {\n    if (!v.isBoundary()) {\n\n      for (Halfedge he : v.incomingHalfedges()) {\n        Face neighFace = he.twin().face();\n        if (he.vertex().isBoundary()) {\n\n          size_t i = geometry.vertexIndices[v];\n          size_t j = geometry.vertexIndices[he.vertex()];\n\n          // move boundary terms to the right-hand side and remove the corresponding matrix entries\n          std::complex<double> Aij = energyMatrix.coeff(i, j);\n          energyMatrix.coeffRef(i, j) = 0;\n          std::complex<double> bVal = boundaryValues[he.vertex()];\n          b(i) += -Aij * bVal;\n        }\n      }\n    }\n  }\n\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n  Eigen::VectorXcd RHS = massMatrix * b;\n  Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n  // Copy the result to a VertexData vector for both the boundary and interior\n  VertexData<Vector2> toReturn(mesh);\n  for (Vertex v : mesh.vertices()) {\n    if (v.isBoundary()) {\n      toReturn[v] = Vector2::fromComplex(boundaryValues[v]);\n    } else {\n      toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n      toReturn[v] = unit(toReturn[v]);\n    }\n  }\n\n  return toReturn;\n}\n\nFaceData<Vector2> computeSmoothestBoundaryAlignedFaceDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  if (!mesh.hasBoundary()) {\n    throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n  }\n\n  geometry.requireFaceGalerkinMassMatrix();\n  geometry.requireHalfedgeVectorsInFace();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.faceGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n  // Compute boundary values\n  FaceData<bool> isInterior(mesh);\n  FaceData<std::complex<double>> boundaryValues(mesh);\n  for (Face f : mesh.faces()) {\n    bool isBoundary = false;\n    for (Edge e : f.adjacentEdges()) {\n      isBoundary |= e.isBoundary();\n    }\n    isInterior[f] = !isBoundary;\n\n    if (isInterior[f]) {\n      boundaryValues[f] = 0;\n    } else {\n      Vector2 bC = Vector2::zero();\n      for (Halfedge he : f.adjacentHalfedges()) {\n        if (he.edge().isBoundary()) {\n          bC -= geometry.halfedgeVectorsInFace[he].rotate90(); // negate the vector to point outwards\n        }\n      }\n      bC = unit(bC);\n      boundaryValues[f] = bC.pow(nSym);\n    }\n  }\n\n  // Assemble right-hand side from these boundary values\n  Vector<std::complex<double>> b(mesh.nFaces());\n  b.setZero();\n\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n\n      for (Halfedge he : f.adjacentHalfedges()) {\n        Face neighFace = he.twin().face();\n        if (!isInterior[neighFace]) {\n\n          size_t i = geometry.faceIndices[f];\n          size_t j = geometry.faceIndices[neighFace];\n\n          // move boundary terms to the right-hand side and remove the corresponding matrix entries\n          std::complex<double> Aij = energyMatrix.coeff(i, j);\n          energyMatrix.coeffRef(i, j) = 0;\n          std::complex<double> bVal = boundaryValues[neighFace];\n          b(i) += -Aij * bVal;\n        }\n      }\n    }\n  }\n\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n  Eigen::VectorXcd RHS = massMatrix * b;\n  Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n  // Copy the result to a FaceData object\n  FaceData<Vector2> field(mesh);\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n      field[f] = Vector2::fromComplex(solution(geometry.faceIndices[f]));\n      field[f] = unit(field[f]);\n    } else {\n      field[f] = Vector2::fromComplex(boundaryValues[f]);\n    }\n  }\n\n  return field;\n}\n\nVertexData<Vector2> computeCurvatureAlignedVertexDirectionField(ExtrinsicGeometryInterface& geometry, int nSym) {\n\n\n  SurfaceMesh& mesh = geometry.mesh;\n  size_t N = mesh.nVertices();\n\n  geometry.requireVertexIndices();\n  geometry.requireVertexGalerkinMassMatrix();\n  geometry.requireVertexPrincipalCurvatureDirections();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.vertexGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n  Vector<std::complex<double>> dirVec(N);\n  if (nSym == 2) {\n    for (Vertex v : mesh.vertices()) {\n      dirVec[geometry.vertexIndices[v]] = geometry.vertexPrincipalCurvatureDirections[v];\n    }\n  } else if (nSym == 4) {\n    for (Vertex v : mesh.vertices()) {\n      dirVec[geometry.vertexIndices[v]] =\n          std::pow(std::complex<double>(geometry.vertexPrincipalCurvatureDirections[v]), 2);\n    }\n  } else {\n    throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or 4\");\n  }\n\n  // Normalize the alignment field\n  double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n  dirVec /= scale;\n\n  // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n  double lambdaT = 0;\n\n  Eigen::VectorXcd RHS = massMatrix * dirVec;\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n  Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n  // Copy the result to a VertexData vector\n  VertexData<Vector2> toReturn(mesh);\n  for (Vertex v : mesh.vertices()) {\n    toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n    toReturn[v] = unit(toReturn[v]);\n  }\n\n  return toReturn;\n}\n\nFaceData<Vector2> computeCurvatureAlignedFaceDirectionField(EmbeddedGeometryInterface& geometry, int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n  const unsigned int N = mesh.nFaces();\n\n  geometry.requireFaceIndices();\n  geometry.requireFaceGalerkinMassMatrix();\n  geometry.requireFacePrincipalCurvatureDirections();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.faceGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n  Eigen::VectorXcd dirVec(N);\n  if (nSym == 2) {\n    for (Face f : mesh.faces()) {\n      dirVec[geometry.faceIndices[f]] = geometry.facePrincipalCurvatureDirections[f];\n    }\n  } else if (nSym == 4) {\n    for (Face f : mesh.faces()) {\n      dirVec[geometry.faceIndices[f]] = std::pow(std::complex<double>(geometry.facePrincipalCurvatureDirections[f]), 2);\n    }\n  } else {\n    throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or 4\");\n  }\n\n  // Normalize the alignment field\n  double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n  dirVec /= scale;\n\n  double lambdaT = 0.0; // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n\n  Eigen::VectorXcd RHS = massMatrix * dirVec;\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n  Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n  // Copy the result to a FaceData object\n  FaceData<Vector2> field(mesh);\n  for (Face f : mesh.faces()) {\n    field[f] = Vector2::fromComplex(solution[geometry.faceIndices[f]]);\n    field[f] = unit(field[f]);\n  }\n\n  return field;\n}\n\n\nFaceData<int> computeFaceIndex(IntrinsicGeometryInterface& geometry, const VertexData<Vector2>& directionField,\n                               int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireTransportVectorsAlongHalfedge();\n  geometry.requireFaceGaussianCurvatures();\n\n  // Store the result here\n  FaceData<int> indices(mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (Face f : mesh.faces()) {\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = geometry.faceGaussianCurvatures[f] * nSym;\n\n    for (Halfedge he : f.adjacentHalfedges()) {\n      if (he.twin().isInterior()) {\n        // Compute the rotation along the halfedge implied by the field\n        Vector2 x0 = directionField[he.vertex()];\n        Vector2 x1 = directionField[he.twin().vertex()];\n        Vector2 rot = geometry.transportVectorsAlongHalfedge[he].pow(nSym);\n\n        // Find the difference in angle\n        double theta0 = (rot * x0).arg();\n        double theta1 = x1.arg();\n        double deltaTheta = regularizeAngle(theta1 - theta0 + PI) - PI; // regularize to [-PI,PI]\n\n        totalRot += deltaTheta; // accumulate\n      }\n    }\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[f] = index;\n  }\n\n  return indices;\n}\n\n\nVertexData<int> computeVertexIndex(IntrinsicGeometryInterface& geometry, const FaceData<Vector2>& directionField,\n                                   int nSym) {\n\n  SurfaceMesh& mesh = geometry.mesh;\n\n  geometry.requireTransportVectorsAcrossHalfedge();\n  geometry.requireVertexGaussianCurvatures();\n\n  // Store the result here\n  VertexData<int> indices(mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (Vertex v : mesh.vertices()) {\n\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = geometry.vertexGaussianCurvatures[v] * nSym;\n\n    if (!v.isBoundary()) {\n      for (Halfedge he : v.incomingHalfedges()) {\n        // Compute the rotation along the halfedge implied by the field\n        Vector2 x0 = directionField[he.face()];\n        Vector2 x1 = directionField[he.twin().face()];\n        Vector2 rot = geometry.transportVectorsAcrossHalfedge[he].pow(nSym);\n\n        double deltaTheta = regularizeAngle(x1.arg() - (rot * x0).arg() + PI) - PI; // regularize to [-PI,PI]\n\n        totalRot += deltaTheta;\n      }\n    }\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[v] = index;\n  }\n\n  return indices;\n}\n/*\nVertexData<Vector2> computeSmoothestBoundaryAlignedVertexDirectionField(IntrinsicGeometryInterface& geometry,\n                                                                        int nSym) {\n  SurfaceMesh& mesh = geometry.mesh;\n\n\n  if (!mesh.hasBoundary()) {\n    throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n  }\n\n  geometry.requireVertexGalerkinMassMatrix();\n  geometry.requireVertexConnectionLaplacian();\n  geometry.requireHalfedgeVectorsInVertex();\n\n  // Mass matrix\n  SparseMatrix<std::complex<double>> massMatrix = geometry.vertexGalerkinMassMatrix.cast<std::complex<double>>();\n\n  // Energy matrix\n  SparseMatrix<std::complex<double>> energyMatrix = geometry.vertexConnectionLaplacian;\n\n  // Compute the boundary values\n  VertexData<std::complex<double>> boundaryValues(mesh);\n  VertexData<char> isBoundary(mesh, false);\n  for (Vertex v : mesh.vertices()) {\n    if (v.isBoundary()) {\n      isBoundary[v] = true;\n\n      // Find incoming and outgoing boundary vectors as tangent\n      Halfedge heBoundaryA = v.halfedge();\n      Halfedge heBoundaryB = heBoundaryA.twin().next();\n\n      Vector2 vecA = geometry.halfedgeVectorsInVertex[heBoundaryA];\n      Vector2 vecB = geometry.halfedgeVectorsInVertex[heBoundaryB];\n\n      Vector2 tangentV = unit(-vecA + vecB);\n      Vector2 normalV = tangentV.rotate90();\n\n      boundaryValues[v] = normalV.pow(nSym);\n    } else {\n      boundaryValues[v] = 0;\n    }\n  }\n  Vector<std::complex<double>> b = boundaryValues.toVector();\n  Vector<char> isBoundaryVec = isBoundary.toVector();\n\n  // Block decompose problem\n\n\n  // Compute the actual solution\n  std::cout << \"Solving linear problem...\" << std::endl;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    geometry.requirePrincipalDirections();\n\n    Eigen::VectorXcd dirVec(nInterior);\n    for (Vertex v : mesh.vertices()) {\n      if (v.isBoundary()) {\n        continue;\n      }\n\n      Vector2 directionVal = geometry.principalDirections[v];\n      if (nSym == 4) {\n        directionVal = std::pow(directionVal, 2);\n      }\n\n      // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n      // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals and\n      // the magnitude of the desired field.  Be careful when interpreting this as opposed to the usual direction field\n      // optimization.\n      dirVec[geometry.interiorVertexIndices[v]] = directionVal / std::abs(directionVal);\n    }\n\n    double t = 0.01; // this is something of a magical constant, see \"Globally\n                     // Optimal Direction Fields\", eqn 9\n\n    Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    solution = solveSquare(LHS, RHS);\n  }\n  // Otherwise find the general closest solution\n  else {\n    std::cout << \"Solving smoothest field dirichlet problem...\" << std::endl;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    Eigen::VectorXcd RHS = massMatrix * b;\n    solution = solveSquare(LHS, RHS);\n  }\n\n  // Copy the result to a VertexData vector for both the boudary and interior\n  VertexData<Vector2> toReturn(*mesh);\n  for (Vertex v : mesh.vertices()) {\n    if (v.isBoundary()) {\n      toReturn[v] = boundaryValues[v];\n    } else {\n      toReturn[v] = unit(solution[geometry.interiorVertexIndices[v]]);\n    }\n  }\n\n  return toReturn;\n}\n\n// Helpers for computing face-based direction fields\nnamespace {\n\nFaceData<Vector2> computeSmoothestFaceDirectionField_noBoundary(IntrinsicGeometryInterface& geometry, int nSym = 1,\n                                                                bool alignCurvature = false) {\n\n\n  SurfaceMesh* mesh = geometry->getMesh();\n  unsigned int N = mesh.nFaces();\n\n  GeometryCache<Euclidean>& geometry = geometry->cache;\n  geometry.requireFaceTransportCoefs();\n  geometry.requireFaceNormals();\n  geometry.requireFaceAreas();\n  geometry.requireDihedralAngles();\n  geometry.requireFaceIndices();\n\n  // === Allocate matrices\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(N, N);\n  energyMatrix.reserve(Eigen::VectorXi::Constant(N, 4));\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(N, N);\n  massMatrix.reserve(Eigen::VectorXi::Constant(N, 1));\n\n\n  // === Build matrices\n\n  // Build the mass matrix\n  for (Face f : mesh.faces()) {\n    size_t i = geometry.faceIndices[f];\n    massMatrix.insert(i, i) = geometry.faceAreas[f];\n  }\n\n  // Build the energy matrix\n  for (Face f : mesh.faces()) {\n    size_t i = geometry.faceIndices[f];\n\n    std::complex<double> weightISum = 0;\n    for (Halfedge he : f.adjacentHalfedges()) {\n\n      if (!he.twin().isInterior()) {\n        continue;\n      }\n\n      Face neighFace = he.twin().face();\n      unsigned int j = geometry.faceIndices[neighFace];\n\n      // LC connection between the faces\n      Vector2 rBar = std::pow(geometry.faceTransportCoefs[he.twin()], nSym);\n\n      double weight = 1; // FIXME TODO figure out weights\n      energyMatrix.insert(i, j) = -weight * rBar;\n      weightISum += weight;\n    }\n\n    energyMatrix.insert(i, i) = weightISum;\n  }\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<Vector2> eye(N, N);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    Eigen::VectorXcd dirVec(N);\n    for (Face f : mesh.faces()) {\n\n      // Compute something like the principal directions\n      double weightSum = 0;\n      Vector2 sum = 0;\n\n      for (Halfedge he : f.adjacentHalfedges()) {\n\n        double dihedralAngle = std::abs(geometry.dihedralAngles[he.edge()]);\n        double weight = norm(geometry->vector(he));\n        weightSum += weight;\n        double angleCoord = angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), geometry.faceNormals[f]);\n        Vector2 coord = std::exp(angleCoord * IM_I *\n                                 (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n        sum += coord * weight * dihedralAngle;\n      }\n\n      sum /= weightSum;\n\n      dirVec[geometry.faceIndices[f]] = sum;\n    }\n\n    // Normalize the alignment field\n    double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n    dirVec /= scale;\n\n    double lambdaT = 0.0; // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n\n    // Eigen::VectorXcd RHS = massMatrix * dirVec;\n    Eigen::VectorXcd RHS = dirVec;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n    solution = solveSquare(LHS, RHS);\n\n  }\n  // Otherwise find the smallest eigenvector\n  else {\n    std::cout << \"Solving smoothest field eigenvalue problem...\" << std::endl;\n    solution = smallestEigenvectorPositiveDefinite(energyMatrix, massMatrix);\n  }\n\n\n  // Copy the result to a FaceData object\n  FaceData<Vector2> field(*mesh);\n  for (Face f : mesh.faces()) {\n    field[f] = solution[geometry.faceIndices[f]] / std::abs(solution[geometry.faceIndices[f]]);\n  }\n\n  return field;\n}\n\nFaceData<Vector2> computeSmoothestFaceDirectionField_boundary(IntrinsicGeometryInterface& geometry, int nSym = 1,\n                                                              bool alignCurvature = false) {\n\n  SurfaceMesh* mesh = geometry->getMesh();\n\n  GeometryCache<Euclidean>& geometry = geometry->cache;\n  geometry.requireFaceTransportCoefs();\n  geometry.requireFaceNormals();\n  geometry.requireFaceAreas();\n  geometry.requireDihedralAngles();\n\n\n  // Index interior faces\n  size_t nInteriorFace = 0;\n  FaceData<size_t> interiorFaceInd(*mesh, -77);\n  FaceData<char> isInterior(*mesh);\n  for (Face f : mesh.faces()) {\n    bool isBoundary = false;\n    for (Edge e : f.adjacentEdges()) {\n      isBoundary |= e.isBoundary();\n    }\n    isInterior[f] = !isBoundary;\n    if (!isBoundary) {\n      interiorFaceInd[f] = nInteriorFace++;\n    }\n  }\n\n  // Compute boundary values\n  FaceData<Vector2> boundaryValues(*mesh);\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n      boundaryValues[f] = 0;\n    } else {\n      Vector3 bVec = Vector3::zero();\n      for (Halfedge he : f.adjacentHalfedges()) {\n        if (he.edge().isBoundary()) {\n          bVec += geometry->vector(he).rotate_around(geometry.faceNormals[f], -PI / 2.0);\n        }\n      }\n      Vector2 bC(dot(geometry.faceBases[f][0], bVec), dot(geometry.faceBases[f][1], bVec));\n      bC = unit(bC);\n      boundaryValues[f] = std::pow(bC, nSym);\n    }\n  }\n\n\n  // === Allocate matrices\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(nInteriorFace, nInteriorFace);\n  energyMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 4));\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(nInteriorFace, nInteriorFace);\n  massMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 1));\n\n  // RHS\n  Eigen::VectorXcd b(nInteriorFace);\n\n  // === Build matrices\n\n  // Build the mass matrix\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n      size_t i = interiorFaceInd[f];\n      massMatrix.insert(i, i) = geometry.faceAreas[f];\n    }\n  }\n\n  // Build the energy matrix\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n      size_t i = interiorFaceInd[f];\n\n      std::complex<double> weightISum = 0;\n      for (Halfedge he : f.adjacentHalfedges()) {\n\n        Face neighFace = he.twin().face();\n        double weight = 1; // FIXME TODO figure out weights\n        Vector2 rBar = std::pow(geometry.faceTransportCoefs[he.twin()], nSym);\n\n        if (isInterior[neighFace]) {\n          size_t j = interiorFaceInd[neighFace];\n          energyMatrix.insert(i, j) = -weight * rBar;\n        } else {\n          std::complex<double> bVal = boundaryValues[neighFace];\n          b(i) += weight * rBar * bVal;\n        }\n\n        weightISum += weight;\n      }\n\n      energyMatrix.insert(i, i) = weightISum;\n    }\n  }\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<Vector2> eye(nInteriorFace, nInteriorFace);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    Eigen::VectorXcd dirVec(nInteriorFace);\n    for (Face f : mesh.faces()) {\n      if (isInterior[f]) {\n\n        // Compute something like the principal directions\n        double weightSum = 0;\n        Vector2 sum = 0;\n\n        for (Halfedge he : f.adjacentHalfedges()) {\n\n          double dihedralAngle = std::abs(geometry.dihedralAngles[he.edge()]);\n          double weight = norm(geometry->vector(he));\n          weightSum += weight;\n          double angleCoord =\n              angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), geometry.faceNormals[f]);\n          Vector2 coord = std::exp(angleCoord * IM_I *\n                                   (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n          sum += coord * weight * dihedralAngle;\n        }\n\n        sum /= weightSum;\n\n        // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n        // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals\n        // and the magnitude of the desired field.  Be careful when interpreting this as opposed to the usual direction\n        // field optimization.\n        dirVec[interiorFaceInd[f]] = unit(sum);\n      }\n    }\n\n\n    double t = 0.1; // this is something of a magical constant, see \"Globally\n                    // Optimal Direction Fields\", eqn 9\n                    // NOTE: This value is different from the one used for vertex fields; seems to work better?\n\n    std::cout << \"Solving smoothest field dirichlet problem with curvature term...\" << std::endl;\n    Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    solution = solveSquare(LHS, RHS);\n\n  }\n  // Otherwise find the general closest solution\n  else {\n    std::cout << \"Solving smoothest field dirichlet problem...\" << std::endl;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    Eigen::VectorXcd RHS = massMatrix * b;\n    solution = solveSquare(LHS, RHS);\n  }\n\n\n  // Copy the result to a FaceData object\n  FaceData<Vector2> field(*mesh);\n  for (Face f : mesh.faces()) {\n    if (isInterior[f]) {\n      field[f] = unit(solution[interiorFaceInd[f]]);\n    } else {\n      field[f] = unit(boundaryValues[f]);\n    }\n  }\n\n  return field;\n}\n\n} // namespace\n\nFaceData<Vector2> computeSmoothestFaceDirectionField(Geometry<Euclidean>* geometry, int nSym, bool alignCurvature) {\n\n  std::cout << \"Computing globally optimal direction field in faces\" << std::endl;\n\n  if (alignCurvature && !(nSym == 2 || nSym == 4)) {\n    throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or \"\n                           \"4\");\n  }\n\n  // Dispatch to either the boundary of no boundary variant depending on the mesh type\n  bool hasBoundary = false;\n  for (Vertex v : geometry->getMesh()->vertices()) {\n    hasBoundary |= v.isBoundary();\n  }\n\n\n  if (hasBoundary) {\n    std::cout << \"Mesh has boundary, computing dirichlet boundary condition solution\" << std::endl;\n    return computeSmoothestFaceDirectionField_boundary(geometry, nSym, alignCurvature);\n  } else {\n    std::cout << \"Mesh has no boundary, computing unit-norm solution\" << std::endl;\n    return computeSmoothestFaceDirectionField_noBoundary(geometry, nSym, alignCurvature);\n  }\n}\n\nFaceData<int> computeFaceIndex(IntrinsicGeometryInterface& geometry, const VertexData<Vector2>& directionField,\n                               int nSym) {\n\n  SurfaceMesh* mesh = geometry->getMesh();\n\n  GeometryCache<Euclidean>& geometry = geometry->cache;\n  geometry.requireFaceTransportCoefs();\n\n  // Store the result here\n  FaceData<int> indices(*mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (Face f : mesh.faces()) {\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = 0;\n\n    for (Halfedge he : f.adjacentHalfedges()) {\n      // Compute the rotation along the halfedge implied by the field\n      Vector2 x0 = directionField[he.vertex()];\n      Vector2 x1 = directionField[he.twin().vertex()];\n      Vector2 transport = std::pow(geometry.vertexTransportCoefs[he], nSym);\n\n      // Find the difference in angle\n      double theta0 = std::arg(transport * x0);\n      double theta1 = std::arg(x1);\n      double deltaTheta = regularizeAngle(theta1 - theta0 + PI) - PI; // regularize to [-PI,PI]\n\n      totalRot += deltaTheta; // accumulate\n    }\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[f] = index;\n  }\n\n  return indices;\n}\n\n\nVertexData<int> computeVertexIndex(IntrinsicGeometryInterface& geometry, const FaceData<Vector2>& directionField,\n                                   int nSym) {\n\n  SurfaceMesh* mesh = geometry->getMesh();\n  GeometryCache<Euclidean>& geometry = geometry->cache;\n  geometry.requireFaceTransportCoefs();\n\n  // Store the result here\n  VertexData<int> indices(*mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (Vertex v : mesh.vertices()) {\n\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = 0;\n\n    for (Halfedge he : v.incomingHalfedges()) {\n      // Compute the rotation along the halfedge implied by the field\n      Vector2 x0 = directionField[he.face()];\n      Vector2 x1 = directionField[he.twin().face()];\n      Vector2 transport = std::pow(geometry.faceTransportCoefs[he], nSym);\n\n      // Find the difference in angle\n      double theta0 = std::arg(transport * x0);\n      double theta1 = std::arg(x1);\n      double deltaTheta = std::arg(x1 / (transport * x0));\n\n      totalRot += deltaTheta;\n    }\n\n    double angleDefect = geometry->angleDefect(v);\n    totalRot += angleDefect * nSym;\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[v] = index;\n  }\n\n  return indices;\n}\n*/\n\n} // namespace surface\n} // namespace geometrycentral\n", "meta": {"hexsha": "4fb25f1faacb2d37ffdace8c016ea5b52462a0b3", "size": 33442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface/direction_fields.cpp", "max_stars_repo_name": "erkil1452/geometry-central", "max_stars_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_stars_repo_licenses": ["MIT"], "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/surface/direction_fields.cpp", "max_issues_repo_name": "erkil1452/geometry-central", "max_issues_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_issues_repo_licenses": ["MIT"], "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/direction_fields.cpp", "max_forks_repo_name": "erkil1452/geometry-central", "max_forks_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_forks_repo_licenses": ["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.8184494603, "max_line_length": 120, "alphanum_fraction": 0.6707134741, "num_tokens": 8255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6651953296107715}}
{"text": "// Copyright (c) 2000-2021, Heiko Bauke\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n//   * Redistributions of source code must retain the above copyright\n//     notice, this list of conditions and the following disclaimer.\n//\n//   * Redistributions in binary form must reproduce the above\n//     copyright notice, this list of conditions and the following\n//     disclaimer in the documentation and/or other materials provided\n//     with the distribution.\n//\n//   * Neither the name of the copyright holder nor the names of its\n//     contributors may be used to endorse or promote products derived\n//     from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n// OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <array>\n#include <vector>\n#include <tuple>\n#include <utility>\n#include <limits>\n#include <cmath>\n#include <ciso646>\n\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <trng/int_math.hpp>\n\n\nBOOST_AUTO_TEST_SUITE(test_suite_int_math)\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_integer_math)\n\nBOOST_AUTO_TEST_CASE(test_pow2) {\n  BOOST_TEST(trng::int_math::pow2(0) == 1, \"2^0 = 1\");\n  BOOST_TEST(trng::int_math::pow2(8) == 256, \"2^8 = 256\");\n  BOOST_TEST(trng::int_math::pow2(63ull) == 0x8000000000000000ull,\n             \"2^63 = 9223372036854775808\");\n}\n\nBOOST_AUTO_TEST_CASE(test_log2_floor) {\n  BOOST_TEST(trng::int_math::log2_floor(1) == 0, \"ld_floor 1 = 0\");\n  BOOST_TEST(trng::int_math::log2_floor(0x10000) == 16, \"ld_floor 65536 = 16\");\n  BOOST_TEST(trng::int_math::log2_floor(0x1ffff) == 16, \"ld_floor 131071 = 16\");\n}\n\nBOOST_AUTO_TEST_CASE(test_log2_ceil) {\n  BOOST_TEST(trng::int_math::log2_ceil(1) == 0, \"ld_ceil 1 = 0\");\n  BOOST_TEST(trng::int_math::log2_ceil(0x10000) == 16, \"ld_ceil 65536 = 16\");\n  BOOST_TEST(trng::int_math::log2_ceil(0x10001) == 17, \"ld_ceil 65537 = 17\");\n}\n\nBOOST_AUTO_TEST_CASE(test_ceil2) {\n  BOOST_TEST(trng::int_math::ceil2(1) == 1, \"ceil2 1 = 1\");\n  BOOST_TEST(trng::int_math::ceil2(0x10000) == 0x10000, \"ceil 65536 = 65536\");\n  BOOST_TEST(trng::int_math::ceil2(0x10001) == 0x20000, \"ceil 65537 = 131072\");\n}\n\nBOOST_AUTO_TEST_CASE(test_mask) {\n  BOOST_TEST(trng::int_math::mask(0x10000) == 0x1ffff, \"mask 65536 = 65536\");\n  BOOST_TEST(trng::int_math::mask(0x10001) == 0x1ffff, \"mask 65537 = 131071\");\n  BOOST_TEST(trng::int_math::mask(trng::int32_t(0x7fffffff)) == 0x7fffffff,\n             \"mask 2147483647 = 2147483647\");\n  BOOST_TEST(trng::int_math::mask(trng::uint32_t(0xffffffffu)) == 0xffffffffu,\n             \"mask 4294967295 = 4294967295\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_linear_algebra)\n\nBOOST_AUTO_TEST_CASE(test_matrix_vec_mult) {\n  const int n{3};\n  // clang-format off\n  const trng::int32_t A[n * n]{\n    1, 2, 3,\n    2, 4, 6,\n    3, 2, 5 };\n  // clang-format on\n  const trng::int32_t b[n]{2, 3, 4};\n  const trng::int32_t m{7};\n  trng::int32_t c[n];\n  const trng::int32_t c_exact[n]{6, 5, 4};\n  trng::int_math::matrix_vec_mult<n>(A, b, c, m);\n  bool ok{true};\n  for (int i{0}; i < n; ++i)\n    ok = ok and (c[i] == c_exact[i]);\n  BOOST_TEST(ok, \"modular matrix-vector multiplication\");\n}\n\nBOOST_AUTO_TEST_CASE(test_matrix_mult) {\n  const int n{3};\n  // clang-format off\n  const trng::int32_t A[n * n]{\n    1, 2, 3,\n    2, 4, 6,\n    3, 2, 5 };\n  const trng::int32_t B[n * n]{\n    2, 2, 3,\n    2, 3, 6,\n    3, 2, 4 };\n  const trng::int32_t C_exact[n * n] {\n    1, 0, 6,\n    2, 0, 5,\n    4, 1, 6 };\n  // clang-format on\n  const trng::int32_t m{7};\n  trng::int32_t C[n * n];\n  trng::int_math::matrix_mult<3>(A, B, C, m);\n  bool ok{true};\n  for (int i{0}; i < n * n; ++i)\n    ok = ok and (C[i] == C_exact[i]);\n  BOOST_TEST(ok, \"modular matrix-matrix multiplication\");\n}\n\nBOOST_AUTO_TEST_CASE(test_gauss) {\n  const int n{3};\n  // clang-format off\n  trng::int32_t A[n * n]{\n    1, 2, 3,\n    2, 1, 6,\n    3, 2, 5 };\n  // clang-format on\n  trng::int32_t b[n]{2, 4, 3};\n  const trng::int32_t m{7};\n  const trng::int32_t x_exact[n]{5, 0, 6};\n  trng::int_math::gauss<n>(A, b, m);\n  bool ok{true};\n  for (int i{0}; i < n; ++i)\n    ok = ok and (b[i] == x_exact[i]);\n  BOOST_TEST(ok, \"modular Gaussian elimination\");\n}\n\nBOOST_AUTO_TEST_CASE(test_gauss_singular_matrix) {\n  const int n{3};\n  // clang-format off\n  trng::int32_t A[n * n]{\n    1, 2, 3,\n    2, 4, 6,\n    3, 2, 5 };\n  const trng::int32_t A_orig[n * n]{\n    1, 2, 3,\n    2, 4, 6,\n    3, 2, 5 };\n  // clang-format on\n  trng::int32_t b[n]{2, 4, 3};\n  const trng::int32_t b_orig[n]{2, 4, 3};\n  const trng::int32_t m{7};\n  // solution is not unique because the matrix is singular, gaussian elimination picks one\n  // solution if one exists\n  trng::int_math::gauss<n>(A, b, m);\n  trng::int32_t c[n]{0, 0, 0};\n  trng::int_math::matrix_vec_mult<3>(A_orig, b, c, m);\n  bool ok{true};\n  for (int i{0}; i < n; ++i)\n    ok = ok and (c[i] == b_orig[i]);\n  BOOST_TEST(ok, \"modular Gaussian elimination\");\n}\n\nBOOST_AUTO_TEST_CASE(test_gauss_singular_matrix_no_solution) {\n  const int n{3};\n  // clang-format off\n  trng::int32_t A[n * n]{\n    1, 2, 3,\n    2, 4, 6,\n    3, 2, 5 };\n  // clang-format on\n  trng::int32_t b[n]{2, 1, 3};\n  const trng::int32_t m{7};\n  // solution does not exist because the matrix is singular and the choice of the right-hand\n  // side\n  BOOST_CHECK_THROW(trng::int_math::gauss<n>(A, b, m), std::exception);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(test_suite_modulo_inverse)\n\nBOOST_AUTO_TEST_CASE(test_modulo_inverse_prime_modulus) {\n  const long m{104729};  // must be prime\n  bool modulo_inverse_ok{true};\n  for (long a{1}; a < m and modulo_inverse_ok; ++a) {\n    int b{trng::int_math::modulo_inverse(a, m)};\n    modulo_inverse_ok = (static_cast<long long>(a) * static_cast<long long>(b)) % m == 1;\n  }\n  BOOST_TEST(modulo_inverse_ok, \"modulo inverse prime modulus\");\n  BOOST_CHECK_THROW(trng::int_math::modulo_inverse(0, m), std::exception);\n}\n\nBOOST_AUTO_TEST_CASE(test_modulo_inverse_power2_modulus) {\n  const long m{1024 * 1024};  // must be power of 2\n  bool modulo_inverse_ok{true};\n  for (long a{1}; a < m and modulo_inverse_ok; a += 2) {\n    int b{trng::int_math::modulo_inverse(a, m)};\n    modulo_inverse_ok = (static_cast<long long>(a) * static_cast<long long>(b)) % m == 1;\n  }\n  BOOST_TEST(modulo_inverse_ok, \"modulo inverse power-of-2 modulus\");\n  BOOST_CHECK_THROW(trng::int_math::modulo_inverse(100, m), std::exception);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//-----------------------------------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "569b9b5af3f20c9fe23e44b8b00138d877133e74", "size": 7680, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_int_math.cc", "max_stars_repo_name": "joseasoler/trng4", "max_stars_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T15:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:35:10.000Z", "max_issues_repo_path": "tests/test_int_math.cc", "max_issues_repo_name": "joseasoler/trng4", "max_issues_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-09-16T23:58:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T20:41:07.000Z", "max_forks_repo_path": "tests/test_int_math.cc", "max_forks_repo_name": "joseasoler/trng4", "max_forks_repo_head_hexsha": "589bdf263821706fd845843912d4241f9c89ba3e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-07-16T16:54:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T20:50:47.000Z", "avg_line_length": 33.3913043478, "max_line_length": 92, "alphanum_fraction": 0.6455729167, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6651953243056953}}
{"text": "// test natural ordering\n\n#include \"test_common_linear_systems.h\"\n\n#include <minisam/3rdparty/Catch2/catch.hpp>\n#include <minisam/utils/testAssertions.h>\n\n#include <minisam/linear/Ordering.h>\n#include <minisam/linear/AMDOrdering.h>\n\n#include <Eigen/LU> // rank\n#include <iostream>\n\nusing namespace minisam;\n\n\n// exmaple systems\ntest::ExampleLinearSystems data;\n\n// assert_equal for MatrixXi\nbool assert_equal_MatrixXi(const Eigen::MatrixXi& expected, const Eigen::MatrixXi& actual) {\n  // check dim\n  if (expected.rows() != actual.rows() || expected.cols() != actual.cols()) {\n    std::cout << \"Not equal:\" << std::endl \n        << \"expected dimension: (\" << expected.rows() << \", \" << expected.cols() << \")\" << std::endl \n        << \"actual dimension: (\" << actual.rows() << \", \" << actual.cols() << \")\" << std::endl;\n    return false;\n  }\n  // check values\n  for (int i = 0; i < expected.rows(); i++) {\n    for (int j = 0; j < expected.cols(); j++) {\n      if (expected(i,j) != actual(i,j)) {\n        std::cout << \"Not equal:\" << std::endl << \"expected: \" << expected \n            << std::endl << \"actual: \" << actual << std::endl;\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"OrderingBase\", \"[linear]\") {\n\n  Eigen::SparseMatrix<double> H, Hord_exp, Hord_act(2, 2), Hord_tmp;\n  Eigen::VectorXd Atbord_exp, Atbord_act, x_act;\n\n  // sys2: identity ordering \n  H = data.A2.transpose() * data.A2;\n  Hord_exp = data.A2.transpose() * data.A2;\n  Atbord_exp = data.A2.transpose() * data.b2;\n\n  Ordering ordering1(Ordering::PermMatrix((Eigen::VectorXi(2) << 0, 1).finished()));\n\n  ordering1.permuteSystemSelfAdjoint<Eigen::Lower>(H, Hord_act);\n  CHECK(assert_equal<Eigen::SparseMatrix<double>>(Hord_exp.triangularView<Eigen::Lower>(), Hord_act));\n\n  ordering1.permuteSystemSelfAdjoint<Eigen::Upper>(H, Hord_act);\n  CHECK(assert_equal<Eigen::SparseMatrix<double>>(Hord_exp.triangularView<Eigen::Upper>(), Hord_act));\n\n  ordering1.permuteSystemFull(H, Hord_act);\n  CHECK(assert_equal(Hord_exp, Hord_act));\n\n  ordering1.permuteRhs(data.A2.transpose() * data.b2, Atbord_act);\n  CHECK(assert_equal(Atbord_exp, Atbord_act));\n\n  ordering1.permuteBackSolution(Eigen::MatrixXd(Hord_act).inverse() * Atbord_act, x_act);\n  CHECK(assert_equal(data.x2_exp, x_act));\n\n  // sys2: reverse ordering \n  Hord_exp.setZero();\n  Hord_exp.insert(0,0) = 78.0100;\n  Hord_exp.insert(0,1) = -0.0400;\n  Hord_exp.insert(1,0) = -0.0400;\n  Hord_exp.insert(1,1) = 13.8500;\n  Hord_exp.makeCompressed();\n  Atbord_exp << -17.5500, 20.3900;\n\n  Ordering ordering2(Ordering::PermMatrix((Eigen::VectorXi(2) << 1, 0).finished()));\n\n  // FIXME: only dense assert equal works\n  ordering2.permuteSystemSelfAdjoint<Eigen::Lower>(H, Hord_act);\n  CHECK(assert_equal<Eigen::MatrixXd>(Hord_exp.triangularView<Eigen::Lower>(), Hord_act));\n\n  ordering2.permuteSystemSelfAdjoint<Eigen::Upper>(H, Hord_act);\n  CHECK(assert_equal<Eigen::MatrixXd>(Hord_exp.triangularView<Eigen::Upper>(), Hord_act));\n\n  ordering2.permuteSystemFull(H, Hord_act);\n  CHECK(assert_equal(Hord_exp, Hord_act));\n\n  ordering2.permuteRhs(data.A2.transpose() * data.b2, Atbord_act);\n  CHECK(assert_equal(Atbord_exp, Atbord_act));\n\n  ordering2.permuteBackSolution(Eigen::MatrixXd(Hord_act).inverse() * Atbord_act, x_act);\n  CHECK(assert_equal(data.x2_exp, x_act));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"AMDOrdering\", \"[linear]\") {\n\n  Eigen::SparseMatrix<double> H, Hord_exp, Hord_act;\n  Eigen::VectorXd Atbord_exp, Atbord_act, x_act;\n\n  // sys1: identity\n  H = data.A1.transpose() * data.A1;\n  Hord_act = Eigen::SparseMatrix<double>(H.rows(), H.cols());\n  Hord_exp = data.A1.transpose() * data.A1;\n  Atbord_exp = data.A1.transpose() * data.b1;\n\n  AMDOrdering ordering1(H);\n\n  ordering1.permuteSystemFull(H, Hord_act);\n  CHECK(assert_equal(Hord_exp, Hord_act));\n\n  ordering1.permuteRhs(data.A1.transpose() * data.b1, Atbord_act);\n  CHECK(assert_equal(Atbord_exp, Atbord_act));\n\n  ordering1.permuteBackSolution(Eigen::MatrixXd(Hord_act).inverse() * Atbord_act, x_act);\n  CHECK(assert_equal(data.x1_exp, x_act));\n\n  // sys1: well-cond\n  H = data.A2.transpose() * data.A2;\n  Hord_act = Eigen::SparseMatrix<double>(H.rows(), H.cols());\n  Hord_exp = data.A2.transpose() * data.A2;\n  Atbord_exp = data.A2.transpose() * data.b2;\n\n  AMDOrdering ordering2(H);\n\n  ordering2.permuteSystemFull(H, Hord_act);\n  CHECK(assert_equal(Hord_exp, Hord_act));\n\n  ordering2.permuteRhs(data.A2.transpose() * data.b2, Atbord_act);\n  CHECK(assert_equal(Atbord_exp, Atbord_act));\n\n  ordering2.permuteBackSolution(Eigen::MatrixXd(Hord_act).inverse() * Atbord_act, x_act);\n  CHECK(assert_equal(data.x2_exp, x_act));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"OrderingGivenOrdering\", \"[linear]\") {\n  // given indices\n  int Hsize = 10;\n  Eigen::MatrixXd H = Eigen::MatrixXd::Random(Hsize, Hsize);\n  // make H symmetric\n  H = 0.5 * (H + H.transpose()).eval();\n  Eigen::VectorXd x = Eigen::VectorXd::Random(Hsize);\n  Eigen::VectorXi indx(Hsize), indx_reverse(Hsize);\n  indx << 4, 7, 1, 3, 0, 9, 5, 8, 6, 2;\n  indx_reverse << 4, 2, 9, 3, 0, 6, 8, 1, 7, 5;\n\n  Eigen::MatrixXd H_perm_exp(Hsize, Hsize);\n  Eigen::SparseMatrix<double> H_perm_act;\n  Eigen::VectorXd x_perm_act, x_perm_exp(Hsize);\n  for (int i = 0; i < Hsize; i++)\n    for (int j = 0; j < Hsize; j++)\n      H_perm_exp(indx(i), indx(j)) = H(i, j);\n  for (int i = 0; i < Hsize; i++)\n    x_perm_exp(indx(i)) = x(i);\n  \n  // ordering\n  Ordering ordering(indx);\n  CHECK(assert_equal_MatrixXi(indx, ordering.indices()));\n  CHECK(assert_equal_MatrixXi(indx_reverse, ordering.reversedIndices()));\n\n  // matrix\n  ordering.permuteSystemFull(H.sparseView(), H_perm_act);\n  CHECK(assert_equal(H_perm_exp, Eigen::MatrixXd(H_perm_act)));\n\n  // vector\n  ordering.permuteRhs(x, x_perm_act);\n  CHECK(assert_equal(x_perm_exp, x_perm_act));\n  ordering.permuteBackSolution(x_perm_exp, x_perm_act);\n  CHECK(assert_equal(x, x_perm_act));\n\n  // reverse ordering\n  Ordering ordering_reversed(indx_reverse);\n  CHECK(assert_equal_MatrixXi(indx_reverse, ordering_reversed.indices()));\n  CHECK(assert_equal_MatrixXi(indx, ordering_reversed.reversedIndices()));\n\n  ordering_reversed.permuteSystemFull(H_perm_exp.sparseView(), H_perm_act);\n  CHECK(assert_equal(H, Eigen::MatrixXd(H_perm_act)));\n\n  ordering_reversed.permuteRhs(x_perm_exp, x_perm_act);\n  CHECK(assert_equal(x, x_perm_act));\n  ordering_reversed.permuteBackSolution(x, x_perm_act);\n  CHECK(assert_equal(x_perm_exp, x_perm_act));\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"OrderingNaturalOrdering\", \"[linear]\") {\n  // use random A to generate test, to test whether R'R - ordering.permute(A'A) = 0\n  const int A_row = 40, A_col = 20;\n  Eigen::MatrixXd A_dense;\n  int A_rank;\n  do {\n    A_dense = Eigen::MatrixXd::Random(A_row, A_col);\n    Eigen::FullPivLU<Eigen::MatrixXd> lu_decomp(A_dense);\n    A_rank = lu_decomp.rank();\n  } while (A_rank < A_col); // make sure full rank\n\n  Eigen::SparseMatrix<double> A, H;\n  A = A_dense.sparseView();\n  H = A.transpose() * A;\n  Eigen::VectorXd x = Eigen::VectorXd::Random(A_col);\n\n  NaturalOrdering ordering(H);\n\n  // indices\n  Eigen::VectorXi idx_exp(H.cols());\n  for (int i = 0; i < H.cols(); i++)\n    idx_exp[i] = i;\n\n  CHECK(ordering.indices() == idx_exp);\n  CHECK(ordering.reversedIndices() == idx_exp);\n\n  // perm system\n  Eigen::SparseMatrix<double> Hperm;\n  Eigen::VectorXd xperm;\n\n  ordering.permuteSystemFull(H, Hperm);\n  CHECK(assert_equal(H, Hperm));\n  ordering.permuteSystemSelfAdjoint<Eigen::Upper>(H, Hperm);\n  CHECK(assert_equal(H, Eigen::SparseMatrix<double>(Hperm.selfadjointView<Eigen::Upper>())));\n  ordering.permuteSystemSelfAdjoint<Eigen::Lower>(H, Hperm);\n  CHECK(assert_equal(H, Eigen::SparseMatrix<double>(Hperm.selfadjointView<Eigen::Lower>())));\n  ordering.permuteRhs(x, xperm);\n  CHECK(assert_equal(x, xperm));\n  ordering.permuteBackSolution(x, xperm);\n  CHECK(assert_equal(x, xperm));\n}\n\n", "meta": {"hexsha": "ab52db9f358e3e1ffafede1092e5b7368fc84a0b", "size": 8093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testOrdering.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "tests/testOrdering.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "tests/testOrdering.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": 34.8836206897, "max_line_length": 102, "alphanum_fraction": 0.6699616953, "num_tokens": 2327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.6651486718912765}}
{"text": "#pragma once\n#include <boost/circular_buffer.hpp>\n#include \"DenseMatrix.hpp\"\n#include \"Mapping.hpp\"\n\nnamespace NonlinearSolvers {\n\n\tstruct FixedPointData {\n\t\tOperator f; // residual operator\n\t\tOperator g; // iteration operator\n\t};\n\n\tinline void logFixedPoint(double r, Index i, Index max = 1) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tauto& w = std::setw(std::to_string(max).length());\n\t\tlogger.buf << \"|| f(x_\" << std::setfill('0') << w << i << \") || = \" << std::scientific << r;\n\t\tlogger.log();\n\t}\n\n\tinline std::vector<double> FixedPointMethod(\n\t\tFixedPointData const & fp,\n\t\tstd::vector<double> const & x_0,\n\t\tIndex n = 100, // max numb of iters\n\t\tdouble eps = 1e-7\n\t) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tlogger.log(\"start Fixed Point method\");\n\t\tauto x = x_0;\n\t\tauto r_norm = norm(fp.f(x));\n\t\tlogFixedPoint(r_norm, 0, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tIndex i;\n\t\tfor (i = 1; i <= n; ++i) {\n\t\t\tx = fp.g(x);\n\t\t\tr_norm = norm(fp.f(x));\n\t\t\tlogFixedPoint(r_norm, i, n);\n\t\t\tif (r_norm < eps) break;\n\t\t}\n\t\tlogger.log(\"stop Fixed Point method\");\n\t\tif (i > n) logger.wrn(\"Fixed Point Method exceeded max numb of iterations\");\n\t\treturn x;\n\t}\n\t\n\tinline std::vector<double> AndersonMixingMethod(\n\t\t\tFixedPointData const & fp,\n\t\t\tstd::vector<double> const & x_0,\n\t\t\tIndex m = 0,\n\t\t\tIndex n = 100, // max numb of iters\n\t\t\tdouble eps = 1e-7\n\t\t) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tif (m == 0) {\n\t\t\tlogger.log(\"m = 0 -> Fixed Point Method\");\n\t\t\treturn FixedPointMethod(fp, x_0, n, eps);\n\t\t}\n\t\tboost::circular_buffer<std::vector<double>> F(m), G(m + 1);\n\t\tlogger.log(\"start Fixed Point method\");\n\t\t// i = 0\n\t\tauto x = x_0;\n\t\tauto r = fp.f(x);\n\t\tauto r_norm = norm(r);\n\t\tlogFixedPoint(r_norm, 0, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tG.push_front(fp.g(x));\n\t\t// i = 1\n\t\tx = G[0];\n\t\tauto r_new = fp.f(x);\n\t\tr_norm = norm(r_new);\n\t\tlogFixedPoint(r_norm, 1, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tG.push_front(fp.g(x));\n\t\tF.push_front(r_new - r);\n\t\tr = r_new;\n\t\tlogger.log(\"stop Fixed Point method\");\n\t\t// i = 2, 3, . . .\n\t\tlogger.log(\"start Anderson Mixing method\");\n\t\tIndex i;\n\t\tfor (i = 2; i <= n; ++i) {\n\t\t\tm = F.size();\n\t\t\tDenseMatrix<double> A(m);\n\t\t\tstd::vector<double> b(m);\n\t\t\tfor (Index k = 0; k < m; ++k) {\n\t\t\t\tb[k] = F[k] * r;\n\t\t\t\tfor (Index j = 0; j < m; ++j)\n\t\t\t\t\tA(k, j) = F[k] * F[j];\n\t\t\t}\n\t\t\tauto beta = A.GaussElimination(b);\n\t\t\tdecltype(beta) alpha(m + 1);\n\t\t\talpha[0] = 1. - beta[0];\n\t\t\tfor (Index k = 1; k < m; ++k) alpha[k] = beta[k - 1] - beta[k];\n\t\t\talpha[m] = beta[m - 1];\n\t\t\tstd::fill(x.begin(), x.end(), 0.);\n\t\t\tfor (Index k = 0; k < m + 1; ++k) x += alpha[k] * G[k];\n\t\t\tr_new = fp.f(x);\n\t\t\tr_norm = norm(r_new);\n\t\t\tlogFixedPoint(r_norm, i, n);\n\t\t\tif (r_norm < eps) break;\n\t\t\tG.push_front(fp.g(x));\n\t\t\tF.push_front(r_new - r);\n\t\t\tr = r_new;\n\t\t}\n\t\tlogger.log(\"stop Anderson Mixing method\");\n\t\tif (i > n) logger.wrn(\"Anderson Mixing Method exceeded max numb of iterations\");\n\t\treturn x;\n\t}\n\n}", "meta": {"hexsha": "b52c2cb7673cf2a7b06b731168d3f0988f27fa51", "size": 3086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_stars_repo_name": "frfly/CATSPDEs", "max_stars_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T13:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T19:37:44.000Z", "max_issues_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_issues_repo_name": "frfly/Solving-elliptic-equation-using-FEM", "max_issues_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-06T17:37:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-06T17:37:04.000Z", "max_forks_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_forks_repo_name": "frfly/Solving-elliptic-equation-using-FEM", "max_forks_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T15:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T21:44:50.000Z", "avg_line_length": 26.6034482759, "max_line_length": 94, "alphanum_fraction": 0.588139987, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.665148660934465}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <ceres/ceres.h>\n#include <Eigen/Core>\n#include <fstream>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <opencv2/opencv.hpp>\n#include <pcl_conversions/pcl_conversions.h>\n#include <vector>\n#include <string>\n\n#include \"common.h\"\n#include \"result_verify.h\"\n\nusing namespace std;\n\ntypedef pcl::PointXYZRGB PointType;\nEigen::Matrix3d inner;\nstring lidar_path, photo_path, intrinsic_path, extrinsic_path;\nint error_threshold;\nvector<float> init;\n\nvoid getParameters();\n\nclass external_cali {\npublic:\n    external_cali(PnPData p) {\n        pd = p;\n    }\n\n    template <typename T>\n    bool operator()(const T *_q, const T *_t, T *residuals) const {\n        Eigen::Matrix<T, 3, 3> innerT = inner.cast<T>();\n        Eigen::Quaternion<T> q_incre{_q[ 3 ], _q[ 0 ], _q[ 1 ], _q[ 2 ]};\n        Eigen::Matrix<T, 3, 1> t_incre{_t[ 0 ], _t[ 1 ], _t[ 2 ]};\n\n        Eigen::Matrix<T, 3, 1> p_l(T(pd.x), T(pd.y), T(pd.z));\n        Eigen::Matrix<T, 3, 1> p_c = q_incre.toRotationMatrix() * p_l + t_incre;\n        Eigen::Matrix<T, 3, 1> p_2 = innerT * p_c;\n\n        residuals[0] = p_2[0]/p_2[2] - T(pd.u);\n        residuals[1] = p_2[1]/p_2[2] - T(pd.v);\n\n        return true;\n    }\n\n    static ceres::CostFunction *Create(PnPData p) {\n        return (new ceres::AutoDiffCostFunction<external_cali, 2, 4, 3>(new external_cali(p)));\n    }\n\n\nprivate:\n    PnPData pd;\n\n};\n\nvoid getParameters() {\n    cout << \"Get the parameters from the launch file\" << endl;\n\n    if (!ros::param::get(\"input_lidar_path\", lidar_path)) {\n        cout << \"Can not get the value of input_lidar_path\" << endl;\n        exit(1);\n    }\n    if (!ros::param::get(\"input_photo_path\", photo_path)) {\n        cout << \"Can not get the value of input_photo_path\" << endl;\n        exit(1);\n    }\n    if (!ros::param::get(\"intrinsic_path\", intrinsic_path)) {\n        cout << \"Can not get the value of intrinsic_path\" << endl;\n        exit(1);\n    }\n    if (!ros::param::get(\"extrinsic_path\", extrinsic_path)) {\n        cout << \"Can not get the value of extrinsic_path\" << endl;\n        exit(1);\n    }\n    if (!ros::param::get(\"error_threshold\", error_threshold)) {\n        cout << \"Can not get the value of error_threshold\" << endl;\n        exit(1);\n    }\n    init.resize(12);\n    if (!ros::param::get(\"init_value\", init)) {\n        cout << \"Can not get the value of init_value\" << endl;\n        exit(1);\n    }\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"getExt1\");\n    getParameters();\n\n    vector<PnPData> pData;\n    getData(lidar_path, photo_path, pData);\n\n    Eigen::Matrix4d extrin;\n    // set the intrinsic parameters\n    vector<float> intrinsic;\n    getIntrinsic(intrinsic_path, intrinsic);\n    inner << intrinsic[0], intrinsic[1], intrinsic[2],\n    intrinsic[3], intrinsic[4], intrinsic[5],\n    intrinsic[6], intrinsic[7], intrinsic[8];\n\n    // init the matrix of extrinsic, matrix of rotation and translation\n    // keep this init value, or it is possible to get a local optimal result\n    Eigen::Matrix3d R;  \n    R << init[0], init[1], init[2],\n         init[4], init[5], init[6],\n         init[8], init[9], init[10];\n    Eigen::Quaterniond q(R); \n    double ext[7];\n\n    ext[0] = q.x();\n    ext[1] = q.y();\n    ext[2] = q.z();\n    ext[3] = q.w();\n    ext[4] = init[3];  \n    ext[5] = init[7];  \n    ext[6] = init[11];  \n\n    Eigen::Map<Eigen::Quaterniond> m_q = Eigen::Map<Eigen::Quaterniond>(ext);\n    Eigen::Map<Eigen::Vector3d> m_t = Eigen::Map<Eigen::Vector3d>(ext + 4);\n\n    ceres::LocalParameterization * q_parameterization = new ceres::EigenQuaternionParameterization();\n    ceres::Problem problem;\n\n    problem.AddParameterBlock(ext, 4, q_parameterization);\n    problem.AddParameterBlock(ext + 4, 3);\n  \n    for(auto val : pData) {\n        ceres::CostFunction *cost_function;\n        cost_function = external_cali::Create(val);\n        problem.AddResidualBlock(cost_function, NULL, ext, ext + 4);\n    }\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    cout << summary.BriefReport() << endl;\n\n    Eigen::Matrix3d rot = m_q.toRotationMatrix();\n    writeExt(extrinsic_path, rot, m_t);\n    cout << rot << endl;\n    cout << m_t << endl;\n\n    cout << \"Use the extrinsic result to reproject the data\" << endl;\n    float error[2] = {0, 0};\n    getUVError(intrinsic_path, extrinsic_path, lidar_path, photo_path, error, error_threshold, 1, cv::Size(2464, 2056));    \n    \n    cout << \"u average error is: \" << error[0] << endl;\n    cout << \"v average error is: \" << error[1] << endl;\n    if (error[0] + error[1] < error_threshold) {\n        cout << endl << \"The reprojection error smaller than the threshold, extrinsic result seems ok\" << endl;\n    }\n    else {\n        cout << endl << \"The reprojection error bigger than the threshold, extrinsic result seems not ok\" << endl;\n    }\n\n    return 0;  \n}\n\n\n", "meta": {"hexsha": "7b258275bfeaa122ce088878594c6c64b0245dd0", "size": 5093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cam_lid_external1.cpp", "max_stars_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_stars_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_stars_repo_licenses": ["MIT"], "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/cam_lid_external1.cpp", "max_issues_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_issues_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_issues_repo_licenses": ["MIT"], "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/cam_lid_external1.cpp", "max_forks_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_forks_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_forks_repo_licenses": ["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.6807228916, "max_line_length": 124, "alphanum_fraction": 0.6214411938, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6650126210581654}}
{"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_ATAN2PI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2PI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atan2pi capabilities\n\n    atan2pi function : atan2 in pi multiples.\n\n    @par Semantic:\n\n    For every parameters of same floating type\n\n    @code\n    auto r = atan2pi(y, x);\n    @endcode\n\n    is similar  to:\n\n    @code\n    auto r =  atan2(y, x)/Pi;\n    @endcode\n\n    as it is quadrant aware.\n\n    For any real arguments @c x and @c y not both equal to zero, <tt>atan2pi(y, x)</tt>\n    is the angle in degrees between the positive x-axis of a plane and the point\n    given by the coordinates  <tt>(x, y)</tt>.\n\n    It is also the angle in \\f$[-1, 1[\\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    @see atand, atan2, atan2d, atan\n\n  **/\n  Value atan2pi(Value const& x, const Value &y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2pi.hpp>\n#include <boost/simd/function/simd/atan2pi.hpp>\n\n#endif\n", "meta": {"hexsha": "e611e8ae00a66398f939128a09ee21664df97d9a", "size": 1499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2pi.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/function/atan2pi.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/atan2pi.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 24.9833333333, "max_line_length": 100, "alphanum_fraction": 0.5917278185, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6649726586348138}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n//! Our function pointer, typedef'd to make it easier to use\ntypedef double (*FunctionPointer)(double, double);\n\n//----------------poissonBegin----------------\n//! Create the Poisson matrix for 2D finite difference.\n//! @param[out] A will be the Poisson matrix (as in the exercise)\n//! @param[in] N number of elements in the x-direction\nvoid createPoissonMatrix2D(SparseMatrix &A, int N) {\n\t// Fill the matrix A using setFromTriplets - method (see other exercise\n\t// for how to use it).\n\t// (write your solution here)\n}\n//----------------poissonEnd----------------\n\n//----------------RHSBegin----------------\n//! Create the Right hand side for the 2D finite difference\n//! @param[out] rhs will at the end contain the right hand side\n//! @param[in] f the right hand side function f\n//! @param[in] N the number of points in the x direction\n//! @param[in] dx the cell width\nvoid createRHS(Vector &rhs, FunctionPointer f, int N, double dx) {\n\trhs.resize(N * N);\n\t// fill up RHS\n\t// remember that the index (i,j) corresponds to i*N+j\n\t// (write your solution here)\n}\n//----------------RHSEnd----------------\n\n//----------------solveBegin----------------\n//! Solve the Poisson equation in 2D\n//! @param[out] u will contain the solution u\n//! @param[in] f the function pointer to f\n//! @param[in] N the number of points to use (in x direction)\nvoid poissonSolve(Vector &u, FunctionPointer f, int N) {\n\t// Solve Poisson 2D here\n\t// (write your solution here)\n}\n//----------------solveEnd----------------\n\ndouble F(double x, double y) {\n\treturn 8 * M_PI * M_PI * sin(2 * M_PI * x) * sin(2 * M_PI * y);\n}\n\nint main(int, char **) {\n\tVector u;\n\tpoissonSolve(u, F, 100);\n\twriteToFile(\"u_fd.txt\", u);\n}\n", "meta": {"hexsha": "ddfebdd517d1f0a6ca01dbe423244c4d3402d759", "size": 2061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_warmup/2d-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_warmup/2d-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_warmup/2d-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": 31.7076923077, "max_line_length": 72, "alphanum_fraction": 0.6399805919, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6649726541132698}}
{"text": "// Implements functions that fit planes to data.\n// File: planefit.h\n// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>\n\n// Includes\n#include <rc_utils/planefit.h>\n#include <Eigen/SVD>\n#include <numeric>\n#include <cmath>\n\n// Namespaces\nusing namespace rc_utils;\n\n//\n// Plane fitting\n//\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector4d& coeff)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d normal, mean;\n\tfitPlane(P, normal, mean);\n\n\t// Construct the coefficient vector (a,b,c,d) where the equation of the plane is ax + by + cz + d = 0\n\tcoeff << normal, -normal.dot(mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector4d& coeff, Eigen::Vector3d& mean)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d normal;\n\tfitPlane(P, normal, mean);\n\n\t// Construct the coefficient vector (a,b,c,d) where the equation of the plane is ax + by + cz + d = 0\n\tcoeff << normal, -normal.dot(mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector3d& normal)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d mean;\n\tfitPlane(P, normal, mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector3d& normal, Eigen::Vector3d& mean)\n{\n\t// Retrieve how many data points there are\n\tsize_t N = P.size();\n\n\t// Handle trivial cases\n\tif(N <= 0)\n\t{\n\t\tnormal << 0.0, 0.0, 1.0;\n\t\tmean.setZero();\n\t\treturn;\n\t}\n\telse if(N == 1)\n\t{\n\t\tnormal << 0.0, 0.0, 1.0;\n\t\tmean = P[0];\n\t\treturn;\n\t}\n\n\t// Calculate the mean of the data points (the plane of best fit always passes through the mean)\n\tmean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\n\t// Construct the matrix of zero mean data points\n\tEigen::MatrixXd A(3, N);\n\tfor(size_t i = 0; i < N; i++)\n\t\tA.col(i) = P[i] - mean;\n\n\t// Perform an SVD decomposition to determine the direction with the minimum variance\n\tunsigned int options = (N >= 3 ? Eigen::ComputeThinU : Eigen::ComputeFullU) | Eigen::ComputeThinV;\n\tnormal = A.jacobiSvd(options).matrixU().col(2).normalized();\n}\n\n// Calculate the fitting error of a plane to certain 3D data\ndouble PlaneFit::fitPlaneError(const Points3D& P, const Eigen::Vector4d& coeff)\n{\n\t// Calculate the normalised equation coefficients (to put the resulting error in units of normal distance to plane)\n\tEigen::Vector3d normal = coeff.head<3>();\n\tdouble norm = normal.norm();\n\tdouble scale = (norm > 0.0 ? norm : coeff.w());\n\tEigen::Vector3d abc = normal / scale;\n\tdouble d = coeff.w() / scale;\n\n\t// Calculate the average distance to the plane of the data points\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs(abc.dot(P[i]) + d)/N;\n\n\t// Return the calculated error\n\treturn err;\n}\n\n// Calculate the fitting error of a plane to certain 3D data\ndouble PlaneFit::fitPlaneError(const Points3D& P, const Eigen::Vector3d& normal, Eigen::Vector3d& point)\n{\n\t// Normalise the normal vector (to put the resulting error in units of normal distance to plane)\n\tEigen::Vector3d n = normal.normalized();\n\n\t// Calculate the average distance to the plane of the data points\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs(n.dot(P[i] - point))/N;\n\n\t// Return the calculated error\n\treturn err;\n}\n// EOF", "meta": {"hexsha": "d3367434e94832e0e574d86278a9b5afa056f8ba", "size": 3405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T04:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-10T12:59:36.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 28.8559322034, "max_line_length": 116, "alphanum_fraction": 0.6851688693, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6649469752776731}}
{"text": "#pragma once\n\n#include \"cppitertools/enumerate.hpp\"\n#include \"cppitertools/range.hpp\"\n\n#include <Eigen/Core>\n\n#include <functional>\n#include <vector>\n\n\ntemplate<class T>\nstruct KalmanSmoother\n{\n    using DataTable = std::vector<std::vector<T>>;\n\n    Eigen::VectorX<T> x;\n    Eigen::MatrixX<T> P;\n    Eigen::MatrixX<T> F;\n    Eigen::MatrixX<T> H;\n    Eigen::MatrixX<T> R;\n    Eigen::MatrixX<T> Q;\n\n    std::vector<Eigen::VectorX<T>> x_;\n    std::vector<Eigen::VectorX<T>> _x;\n    std::vector<Eigen::MatrixX<T>> P_;\n    std::vector<Eigen::MatrixX<T>> _P;\n\n    std::function<void(int, std::vector<T>)> function_beforeKFcorrect;\n    std::function<void(int, std::vector<T>)> function_afterKFcorrect;\n\n    KalmanSmoother(int dynamParams, int measureParams, int controlParams = 0);\n\n    DataTable forwardPass(DataTable & dataSeries);\n    DataTable backwardPass();\n\nprivate:\n\n    int m_dynamParams;\n    int m_measureParams;\n    int m_controlParams;\n\n    std::vector<std::vector<T>> zk;\n};\n\ntemplate<class T>\ninline KalmanSmoother<T>::KalmanSmoother(int dynamParams, int measureParams, int controlParams)\n{\n    m_dynamParams   = dynamParams;\n    m_measureParams = measureParams;\n    m_controlParams = controlParams;\n\n    x = Eigen::VectorX<T>(dynamParams);\n    P = Eigen::MatrixX<T>(dynamParams, dynamParams);\n    F = Eigen::MatrixX<T>(dynamParams, dynamParams);\n    H = Eigen::MatrixX<T>(measureParams, dynamParams);\n    R = Eigen::MatrixX<T>(measureParams, measureParams);\n    Q = Eigen::MatrixX<T>(dynamParams, dynamParams);\n}\n\ntemplate<class T>\ninline std::vector<std::vector<T>>\n  KalmanSmoother<T>::forwardPass(DataTable & dataSeries)\n{\n    for (auto & data : dataSeries) {\n        if (data.size() != m_measureParams)\n            throw std::length_error(\"One of the data point's dimension is inadequate.\");\n    }\n\n    x_.clear();\n    x_.resize(dataSeries.size() + 1, x);\n    _x.clear();\n    _x.resize(dataSeries.size() + 1, x);\n    P_.clear();\n    P_.resize(dataSeries.size() + 1, P);\n    _P.clear();\n    _P.resize(dataSeries.size() + 1, P);\n\n    for (auto && [idx, data] : iter::enumerate(dataSeries)) {\n        const int i = idx + 1;\n\n        Eigen::Map<Eigen::VectorX<T>> z(data.data(), m_measureParams);\n\n        // Kalman predict\n        _x[i] = F * x_[i - 1];\n        _P[i] = F * P_[i - 1] * F.transpose() + Q;\n\n        // Kalman correct\n        auto K = _P[i] * H.transpose() * (R + H * _P[i] * H.transpose()).inverse();\n        auto I = Eigen::MatrixX<T>::Identity(m_dynamParams, m_dynamParams);\n        x_[i]  = _x[i] + K * (z - H * _x[i]);\n        P_[i]  = (I - K * H) * _P[i];\n    }\n\n    DataTable result;\n    result.reserve(x_.size());\n    for (auto & x : x_) {\n        std::vector<T> temp;\n        for (auto value : x) {\n            temp.push_back(value);\n        }\n        result.push_back(temp);\n    }\n\n    return result;\n}\n\ntemplate<class T>\ninline std::vector<std::vector<T>>\n  KalmanSmoother<T>::backwardPass()\n{\n    const int n = x_.size();\n\n    std::vector<Eigen::VectorX<T>> xs;\n    xs.resize(n, x_[n - 1]);\n    std::vector<Eigen::MatrixX<T>> Ps;\n    Ps.resize(n, P_[n - 1]);\n\n    for (auto i : iter::range(n - 2, -1, -1)) {\n        // Ps[i] = F * P_[i] * F.transpose() + Q;\n\n        // auto K = P_[i] * F.transpose() * Ps[i].inverse();\n        // xs[i] += K * (x_[i + 1] - F * _x[i]);\n        // Ps[i] += K * (P_[i + 1] - P_[i]) * K.transpose();\n\n        auto C = P_[i] * F.transpose() * _P[i + 1].inverse();\n\n        xs[i] += x_[i] + C * (xs[i + 1] - _x[i + 1]);\n        Ps[i] += P_[i] + C * (Ps[i + 1] - _P[i + 1]) * C.transpose();\n    }\n\n    DataTable result;\n    result.reserve(xs.size());\n    for (auto & x : xs) {\n        std::vector<T> temp;\n        for (auto value : x) {\n            temp.push_back(value);\n        }\n        result.push_back(temp);\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "f055d1408238229fec48cb41841e42a4c33e05af", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/KalmanSmoother.hpp", "max_stars_repo_name": "attila-fenyvesi/TrafficMapper", "max_stars_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_stars_repo_licenses": ["MIT"], "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/KalmanSmoother.hpp", "max_issues_repo_name": "attila-fenyvesi/TrafficMapper", "max_issues_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_issues_repo_licenses": ["MIT"], "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/KalmanSmoother.hpp", "max_forks_repo_name": "attila-fenyvesi/TrafficMapper", "max_forks_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 95, "alphanum_fraction": 0.575446898, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6649269048413294}}
{"text": "/*=================================================================\n*\n* todo!!!!!!!!\n* compute \"voronoi\" area of each vertex\n* reference: Discrete Differential Geometry Operators for triangulated 2-manifolds_02\n* usage: \n\t\tva = vertex_area(verts, faces);\n* inputs:\n\t\tverts: 3*nverts\n\t\tfaces: 3*faces\n\t\tbVoronoi: use fast approximation or voronoi area\n*\n* output:\n*\t\tva: nverts*1\n*          \n*\n* JJCAO, 2013\n*\n*=================================================================*/\n\n#include <mex.h>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nvoid compute_vertex_area_fast(Eigen::MatrixXd& V, Eigen::MatrixXd& F, double* va)\n{\n\tint n1,n2,n3;\n\tEigen::Vector3d v1,v2,v3;\n\tEigen::Vector3d e1,e2;\n\tEigen::Vector3d tmpV;\n\tdouble tmp;\n\tdouble farea;\n\tfor( int i = 0; i < F.rows(); ++i)\n\t{\n\t\tn1 = F.coeff(i,0)-1; n2 = F.coeff(i,1)-1; n3 = F.coeff(i,2)-1;\n\t\tv1 = V.row(n1); v2 = V.row(n2); v3 = V.row(n3);\n\t\te1 = v2 - v1; e2 = v3 - v1;\n\n\t\ttmpV = e1.cross(e2);\n\t\tfarea = tmpV.norm()*0.5;\n\t\ttmp = farea / 3.0;\n\t\t\n\t\tva[n1] += tmp;\n\t\tva[n2] += tmp;\n\t\tva[n3] += tmp;\n\t}\n}\nvoid compute_vertex_voronoi_area(Eigen::MatrixXd& V, Eigen::MatrixXd& F, double* va)\n{\n\tmexErrMsgTxt(\"not implemented still !\");\n}\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])\n{\n\t///////////// Error Check\n\tif ( nrhs < 2) \n\t\tmexErrMsgTxt(\"Number of input should > 1!\");\n\n\t///////////// input & output arguments\t\n\t// input 0: verts: 3*nverts\n\tint nverts = mxGetM(prhs[0]);\n\tint col = mxGetN(prhs[0]);\n\tif(col != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be n*3\");\n\n\tdouble *verts = mxGetPr(prhs[0]);\n\n\t// input 1: faces: 3*nfaces\n\tint nfaces = mxGetM(prhs[1]);\n\tcol = mxGetN(prhs[1]);\n\tif(col != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be n*3\");\n\n\tdouble* faces = mxGetPr(prhs[1]);\n\n\t\n\tbool bVoronoi(false);\n\tif ( nrhs > 2) \n\t{\n\t\tdouble* tmp = mxGetPr(prhs[2]);\n\t\tif ( *tmp != 0)\n\t\t\tbVoronoi = true;\n\t}\n\n\t///////////////////////////////////////////////\n\t// output 0\n\tplhs[0] = mxCreateDoubleMatrix( nverts, 1, mxREAL);   \n\tdouble *va = mxGetPr(plhs[0]);\n\tfor ( int i = 0; i < nverts; ++i)\n\t{\n\t\tva[i] = 0;\n\t}\n\n\t///////////////////////////////////////////////\t\n\t// process\n\tEigen::MatrixXd V = Eigen::Map<Eigen::MatrixXd>(verts, nverts, 3);\n\tEigen::MatrixXd F = Eigen::Map<Eigen::MatrixXd>(faces, nfaces, 3);\n\n\tif ( bVoronoi)\n\t\tcompute_vertex_voronoi_area(V,F,va);\n\telse\n\t\tcompute_vertex_area_fast(V,F,va);\n}", "meta": {"hexsha": "0e1e16fcefe7f714d9a1588e97fb7b69541bf259", "size": 2450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/vertex_area.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/vertex_area.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/vertex_area.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": 23.786407767, "max_line_length": 85, "alphanum_fraction": 0.5648979592, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6649254305528799}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdCbrt, Fvar) {\n  using boost::math::cbrt;\n  using stan::math::fvar;\n  using std::isnan;\n\n  fvar<double> x(0.5, 1.0);\n  fvar<double> a = cbrt(x);\n\n  EXPECT_FLOAT_EQ(cbrt(0.5), a.val_);\n  EXPECT_FLOAT_EQ(1 / (3 * pow(0.5, 2.0 / 3.0)), a.d_);\n\n  fvar<double> b = 3 * cbrt(x) + x;\n  EXPECT_FLOAT_EQ(3 * cbrt(0.5) + 0.5, b.val_);\n  EXPECT_FLOAT_EQ(3 / (3 * pow(0.5, 2.0 / 3.0)) + 1, b.d_);\n\n  fvar<double> c = -cbrt(x) + 5;\n  EXPECT_FLOAT_EQ(-cbrt(0.5) + 5, c.val_);\n  EXPECT_FLOAT_EQ(-1 / (3 * pow(0.5, 2.0 / 3.0)), c.d_);\n\n  fvar<double> d = -3 * cbrt(x) + 5 * x;\n  EXPECT_FLOAT_EQ(-3 * cbrt(0.5) + 5 * 0.5, d.val_);\n  EXPECT_FLOAT_EQ(-3 / (3 * pow(0.5, 2.0 / 3.0)) + 5, d.d_);\n\n  fvar<double> e = -3 * cbrt(-x) + 5 * x;\n  EXPECT_FLOAT_EQ(-3 * cbrt(-0.5) + 5 * 0.5, e.val_);\n  EXPECT_FLOAT_EQ(3 / (3 * cbrt(-0.5) * cbrt(-0.5)) + 5, e.d_);\n\n  fvar<double> y(0.0, 1.0);\n  fvar<double> f = cbrt(y);\n  EXPECT_FLOAT_EQ(cbrt(0.0), f.val_);\n  isnan(f.d_);\n}\n\nTEST(AgradFwdCbrt, FvarFvarDouble) {\n  using boost::math::cbrt;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 1.5;\n  x.val_.d_ = 2.0;\n\n  fvar<fvar<double> > a = cbrt(x);\n\n  EXPECT_FLOAT_EQ(cbrt(1.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(2.0 / (3.0 * cbrt(1.5) * cbrt(1.5)), a.val_.d_);\n  EXPECT_FLOAT_EQ(0, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1.5;\n  y.d_.val_ = 2.0;\n\n  a = cbrt(y);\n  EXPECT_FLOAT_EQ(cbrt(1.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(0, a.val_.d_);\n  EXPECT_FLOAT_EQ(2.0 / (3.0 * cbrt(1.5) * cbrt(1.5)), a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n}\n\nstruct cbrt_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return cbrt(arg1);\n  }\n};\n\nTEST(AgradFwdCbrt, cbrt_NaN) {\n  cbrt_fun cbrt_;\n  test_nan_fwd(cbrt_, false);\n}\n", "meta": {"hexsha": "5588194b62ee85541ffe0818a5bb8039334ceab1", "size": 1950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/fwd/scal/fun/cbrt_test.cpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/fwd/scal/fun/cbrt_test.cpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/fwd/scal/fun/cbrt_test.cpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "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.6578947368, "max_line_length": 66, "alphanum_fraction": 0.6025641026, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6648674341415592}}
{"text": "/* Boost example/newton-raphson.cpp\n * Newton iteration for intervals\n *\n * Copyright 2003 Guillaume Melquiond\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#include <boost/numeric/interval.hpp>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <iostream>\n#include <iomanip>\n\ntemplate <class I> I f(const I& x)\n{ return x * (x - 1.) * (x - 2.) * (x - 3.) * (x - 4.); }\ntemplate <class I> I f_diff(const I& x)\n{ return (((5. * x - 40.) * x + 105.) * x - 100.) * x + 24.; }\n\nstatic const double max_width = 1e-10;\nstatic const double alpha = 0.75;\n\nusing namespace boost;\nusing namespace numeric;\nusing namespace interval_lib;\n\n// First method: no empty intervals\n\ntypedef interval<double> I1_aux;\ntypedef unprotect<I1_aux>::type I1;\n\nstd::vector<I1> newton_raphson(const I1& xs) {\n  std::vector<I1> l, res;\n  I1 vf, vd, x, x1, x2;\n  l.push_back(xs);\n  while (!l.empty()) {\n    x = l.back();\n    l.pop_back();\n    bool x2_used;\n    double xx = median(x);\n    vf = f<I1>(xx);\n    vd = f_diff<I1>(x);\n    if (zero_in(vf) && zero_in(vd)) {\n      x1 = I1::whole();\n      x2_used = false;\n    } else {\n      x1 = xx - division_part1(vf, vd, x2_used);\n      if (x2_used) x2 = xx - division_part2(vf, vd);\n    }\n    if (overlap(x1, x)) x1 = intersect(x, x1);\n    else if (x2_used) { x1 = x2; x2_used = false; }\n    else continue;\n    if (x2_used)\n      if (overlap(x2, x)) x2 = intersect(x, x2);\n      else x2_used = false;\n    if (x2_used && width(x2) > width(x1)) std::swap(x1, x2);\n    if (!zero_in(f(x1)))\n      if (x2_used) { x1 = x2; x2_used = false; }\n      else continue;\n    if (width(x1) < max_width) res.push_back(x1);\n    else if (width(x1) > alpha * width(x)) {\n      std::pair<I1, I1> p = bisect(x);\n      if (zero_in(f(p.first))) l.push_back(p.first);\n      x2 = p.second;\n      x2_used = true;\n    } else l.push_back(x1);\n    if (x2_used && zero_in(f(x2)))\n      if (width(x2) < max_width) res.push_back(x2);\n      else l.push_back(x2);\n  }\n  return res;\n}\n\n// Second method: with empty intervals\n\ntypedef change_checking<I1_aux, checking_no_nan<double> >::type I2_aux;\ntypedef unprotect<I2_aux>::type I2;\n\nstd::vector<I2> newton_raphson(const I2& xs) {\n  std::vector<I2> l, res;\n  I2 vf, vd, x, x1, x2;\n  l.push_back(xs);\n  while (!l.empty()) {\n    x = l.back();\n    l.pop_back();\n    double xx = median(x);\n    vf = f<I2>(xx);\n    vd = f_diff<I2>(x);\n    if (zero_in(vf) && zero_in(vd)) {\n      x1 = x;\n      x2 = I2::empty();\n    } else {\n      bool x2_used;\n      x1 = intersect(x, xx - division_part1(vf, vd, x2_used));\n      x2 = intersect(x, xx - division_part2(vf, vd, x2_used));\n    }\n    if (width(x2) > width(x1)) std::swap(x1, x2);\n    if (empty(x1) || !zero_in(f(x1)))\n      if (!empty(x2)) { x1 = x2; x2 = I2::empty(); }\n      else continue;\n    if (width(x1) < max_width) res.push_back(x1);\n    else if (width(x1) > alpha * width(x)) {\n      std::pair<I2, I2> p = bisect(x);\n      if (zero_in(f(p.first))) l.push_back(p.first);\n      x2 = p.second;\n    } else l.push_back(x1);\n    if (!empty(x2) && zero_in(f(x2)))\n      if (width(x2) < max_width) res.push_back(x2);\n      else l.push_back(x2);\n  }\n  return res;\n}\n\ntemplate<class T, class Policies>\nstd::ostream &operator<<(std::ostream &os,\n                         const boost::numeric::interval<T, Policies> &x) {\n  os << \"[\" << x.lower() << \", \" << x.upper() << \"]\";\n  return os;\n}\n\nint main() {\n  {\n    I1_aux::traits_type::rounding rnd;\n    std::vector<I1> res = newton_raphson(I1(-1, 5.1));\n    std::cout << \"Results: \" << std::endl << std::setprecision(12);\n    for(std::vector<I1>::const_iterator i = res.begin(); i != res.end(); ++i)\n      std::cout << \"  \" << *i << std::endl;\n    std::cout << std::endl;\n  }\n  {\n    I2_aux::traits_type::rounding rnd;\n    std::vector<I2> res = newton_raphson(I2(-1, 5.1));\n    std::cout << \"Results: \" << std::endl << std::setprecision(12);\n    for(std::vector<I2>::const_iterator i = res.begin(); i != res.end(); ++i)\n      std::cout << \"  \" << *i << std::endl;\n    std::cout << std::endl;\n  }\n}\n", "meta": {"hexsha": "c1f9759370d3a7ad44dcfe3ae1e1faaaf7b5307e", "size": 4150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/interval/examples/newton-raphson.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/numeric/interval/examples/newton-raphson.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/numeric/interval/examples/newton-raphson.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": 29.2253521127, "max_line_length": 77, "alphanum_fraction": 0.5761445783, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6648674144282994}}
{"text": "#include \"curve_fit.h\"\n#include <armadillo>\n\nusing arma::Col;\nusing arma::Mat;\n\nusing TD = double;\n\nint main(int argc, char *argv[])\n{\n\tconst int deg = 5;\n\tconst bool bounded = true;\n\n\t// Get input data\n\tMat<TD> data;\n\tdata.load(\"test_data.dat\", arma::raw_ascii);\n\n\tauto cur = CurveFit<TD>();\n\tauto bez = cur.bezier_fit(data, deg, bounded);\n\n\tbez.save(\"build/output/bezier_fit.dat\", arma::raw_ascii);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a027830afd4f2aec6ead72e68469b09bfe8e9c76", "size": 415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "SentionLimited/BezierCurveFit", "max_stars_repo_head_hexsha": "1308e355e97b470595959980649407bec83fb97a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "SentionLimited/BezierCurveFit", "max_issues_repo_head_hexsha": "1308e355e97b470595959980649407bec83fb97a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "SentionLimited/BezierCurveFit", "max_forks_repo_head_hexsha": "1308e355e97b470595959980649407bec83fb97a", "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": 16.6, "max_line_length": 58, "alphanum_fraction": 0.6746987952, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6648674096856895}}
{"text": "#include \"xpbd/tetrahedron_volume_constraint.h\"\n\n#include <Eigen/Dense>\n\nnamespace xpbd {\n\ntetrahedron_volume_constraint_t::tetrahedron_volume_constraint_t(\n    std::initializer_list<index_type> indices,\n    positions_type const& p,\n    scalar_type const alpha)\n    : base_type(indices, alpha), V0_{0.}\n{\n    assert(indices.size() == 4u);\n    V0_ = volume(p);\n}\n\ntetrahedron_volume_constraint_t::scalar_type\ntetrahedron_volume_constraint_t::volume(positions_type const& V) const\n{\n    Eigen::RowVector3d const p0 = V.row(indices()[0]);\n    Eigen::RowVector3d const p1 = V.row(indices()[1]);\n    Eigen::RowVector3d const p2 = V.row(indices()[2]);\n    Eigen::RowVector3d const p3 = V.row(indices()[3]);\n\n    auto const vol = (1. / 6.) * (p1 - p0).cross(p2 - p0).dot(p3 - p0);\n    return std::abs(vol);\n}\n\ntetrahedron_volume_constraint_t::scalar_type\ntetrahedron_volume_constraint_t::evaluate(positions_type const& p, masses_type const& m) const\n{\n    return volume(p) - V0_;\n}\n\nvoid tetrahedron_volume_constraint_t::project(\n    positions_type& p,\n    masses_type const& m,\n    scalar_type& lagrange,\n    scalar_type const dt) const\n{\n    auto const v0 = indices()[0];\n    auto const v1 = indices()[1];\n    auto const v2 = indices()[2];\n    auto const v3 = indices()[3];\n\n    auto const w0 = 1. / m(v0);\n    auto const w1 = 1. / m(v1);\n    auto const w2 = 1. / m(v2);\n    auto const w3 = 1. / m(v3);\n\n    Eigen::RowVector3d const p0 = p.row(v0);\n    Eigen::RowVector3d const p1 = p.row(v1);\n    Eigen::RowVector3d const p2 = p.row(v2);\n    Eigen::RowVector3d const p3 = p.row(v3);\n\n    auto const C = evaluate(p, m);\n\n    Eigen::RowVector3d const grad0 = (1. / 6.) * (p1 - p2).cross(p3 - p2);\n    Eigen::RowVector3d const grad1 = (1. / 6.) * (p2 - p0).cross(p3 - p0);\n    Eigen::RowVector3d const grad2 = (1. / 6.) * (p0 - p1).cross(p3 - p1);\n    Eigen::RowVector3d const grad3 = (1. / 6.) * (p1 - p0).cross(p2 - p0);\n\n    auto const weighted_sum_of_gradients = w0 * grad0.squaredNorm() + w1 * grad1.squaredNorm() +\n                                           w2 * grad2.squaredNorm() + w3 * grad3.squaredNorm();\n\n    if (weighted_sum_of_gradients < 1e-5)\n        return;\n\n    scalar_type const alpha_tilde = alpha_ / (dt * dt);\n    scalar_type const delta_lagrange =\n        -(C + alpha_tilde * lagrange) / (weighted_sum_of_gradients + alpha_tilde);\n\n    lagrange += delta_lagrange;\n    p.row(v0) += w0 * grad0 * delta_lagrange;\n    p.row(v1) += w1 * grad1 * delta_lagrange;\n    p.row(v2) += w2 * grad2 * delta_lagrange;\n    p.row(v3) += w3 * grad3 * delta_lagrange;\n}\n\n} // namespace xpbd", "meta": {"hexsha": "8a68eeb0b42b164a8c7ed992b321377ddfd20458", "size": 2587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xpbd/tetrahedron_volume_constraint.cpp", "max_stars_repo_name": "Q-Minh/position-based-dynamics", "max_stars_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T23:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:30:58.000Z", "max_issues_repo_path": "src/xpbd/tetrahedron_volume_constraint.cpp", "max_issues_repo_name": "Q-Minh/position-based-dynamics", "max_issues_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "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/xpbd/tetrahedron_volume_constraint.cpp", "max_forks_repo_name": "Q-Minh/position-based-dynamics", "max_forks_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "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": 32.3375, "max_line_length": 96, "alphanum_fraction": 0.6401236954, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.664865067543896}}
{"text": "#ifndef EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n#define EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n\n#include <cmath>\n#include <string>\n#include <vector>\n#include <boost/math/special_functions/bessel.hpp>\n#include <clstatphys/rootfinder/false_position_method.hpp>\n#include <clstatphys/rootfinder/newton_method.hpp>\n\n\nnamespace exactsolution{\n\nclass PartitionFunctionClassicalXYFullyConnected{\npublic :\n  static std::string name() { return \"Exact partition function, classical XY, Fully Connected\"; }\n  PartitionFunctionClassicalXYFullyConnected(double J,unsigned int num) : J_(J), num_(num) {}\n    \n  double operator()(double T){\n    double value = 0.0;\n    value = logZ(T);\n    value = std::exp(value);\n    return value;\n  }\n\n  double logZ(double T) {\n    double value = 0.0;\n    double M_temp = M(T);\n    value -= 0.5 * std::log(2.0 * M_PI * T) - 0.5 * J_ / T - 0.5 * M_temp * M_temp / T * J_  + F(M_temp / T * J_);\n    value *= num_;\n    return value;\n  }\n\n  double T(double U){\n    double T0 = 0.0;\n    double T1 = 0.75;\n    if(U >= 0.25 + 0.5 * J_){\n      return 2.0 * U - J_;\n    } else{\n      //False Position Method\n      optimization::FalsePositionMethod optimizer;\n      double J = J_;\n      auto diff_U = [&J,&U,this](double x) { return U - ( 0.5 * x + 0.5 * J * ( 1 - this->M(x) * this->M(x)));};\n      optimizer.find_zero(diff_U, T0, T1);\n      return optimizer.zero();\n    }\n  }\n\n  double M(double T) {\n    double M_tmp = 0.0;\n    if(T >= J_ * 0.5) return 0.0;\n    else if( T == 0.0) return 1.0;\n    else{\n      M_tmp = std::sqrt(1 - 2.0 * T / J_);\n      optimization::NewtonMethod optimizer;\n      double J = J_;\n      auto diff_M = [&J,&T,this](double x) { return x - this->dF(x * J / T);};\n      auto d_diff_M = [&J,&T,this](double x) { return 1 - J / T * this->ddF(x * J / T);};\n      optimizer.find_zero(diff_M, d_diff_M, M_tmp);\n      return optimizer.zero();\n    }\n  }\n\n  double F(double value){\n    return std::log(2.0 * M_PI * boost::math::cyl_bessel_i(0,value));\n  }\n\n  double dF(double value){\n    double value_output = 0.0;\n    value_output = boost::math::cyl_bessel_i(1.0,value) / boost::math::cyl_bessel_i(0.0,value);\n    return value_output;\n  }\n\n  double ddF(double value){\n    double value_output = 0.0;\n    value_output = 0.5 * ( boost::math::cyl_bessel_i(0.0,value) + boost::math::cyl_bessel_i(2.0,value) ) * boost::math::cyl_bessel_i(0.0,value); \n    value_output -=  boost::math::cyl_bessel_i(1.0,value) * boost::math::cyl_bessel_i(1.0,value);\n    value_output /= boost::math::cyl_bessel_i(0.0,value) * boost::math::cyl_bessel_i(0.0,value);\n    return value_output;\n  }\n\nprivate :\n  double J_;\n  unsigned int num_;\n  mutable double U_;\n  mutable double T_;\n}; //end harmonic_chain \n\n}\n#endif //EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n", "meta": {"hexsha": "cf815da719b705e9ae141f55ffc13df59e9c6926", "size": 2840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 31.2087912088, "max_line_length": 145, "alphanum_fraction": 0.6454225352, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6648650586546994}}
{"text": "#include <Eigen/Dense>\n#include \"util.hpp\"\n\nusing Eigen::MatrixXf;\n\nvector<vector<double> > inverse(vector<vector<double> > m) {\n  int dim = m.size();\n  MatrixXf m_(dim, dim);\n  for (int i=0; i<dim; i++)\n    for (int j=0; j<dim; j++)\n      m_(i, j) = m[i][j];\n  MatrixXf inv_ = m_.inverse();\n  vector<vector<double> > inv(dim, vector<double>(dim));\n  for (int i=0; i<dim; i++)\n    for (int j=0; j<dim; j++)\n      inv[i][j] = inv_(i, j);\n  return inv;\n}\n\nvector<vector<double> > pseudo_inv(vector<vector<double> > m) {\n  int dim = m.size();\n  MatrixXf m_(dim, dim);\n  for (int i=0; i<dim; i++)\n    for (int j=0; j<dim; j++)\n      m_(i, j) = m[i][j];\n  MatrixXf inv_ = m_.partialPivLu().solve(MatrixXf::Identity(dim, dim));\n  vector<vector<double> > inv(dim, vector<double>(dim));\n  for (int i=0; i<dim; i++)\n    for (int j=0; j<dim; j++)\n      inv[i][j] = inv_(i, j);\n  return inv;  \n}", "meta": {"hexsha": "86e21477450e8597a9730f22f229b82001cdbc65", "size": 884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NumOpt/src/util.cpp", "max_stars_repo_name": "Behrouz-Babaki/NumOpt", "max_stars_repo_head_hexsha": "cf74db7bf9f3a644bf6507f405923a84fe1b1566", "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": "NumOpt/src/util.cpp", "max_issues_repo_name": "Behrouz-Babaki/NumOpt", "max_issues_repo_head_hexsha": "cf74db7bf9f3a644bf6507f405923a84fe1b1566", "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": "NumOpt/src/util.cpp", "max_forks_repo_name": "Behrouz-Babaki/NumOpt", "max_forks_repo_head_hexsha": "cf74db7bf9f3a644bf6507f405923a84fe1b1566", "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.625, "max_line_length": 72, "alphanum_fraction": 0.5701357466, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069105, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6648650434084787}}
{"text": "#pragma once\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n// STL includes\n#include <vector>\n#include <random>\n#ifdef USE_THREADS\n#include <thread>\n#endif\n\n// Local include\n#include \"DirectionsSampling.hpp\"\n\n/* This header provide multiple ways to project spherical function to Spherical\n * Harmonics vectors.\n *\n *    + 'ProjectToSH' return the SH coefficient vector when the Functor to be\n *    projected is bandlimited to the max order of SH. Warning: do not use with\n *    highly varying functions! This projection will probably behave very\n *    badly. In such case, it is advised to use the 'ProjectToShMC' method.\n *\n *    + 'ProjectToShMC' return the SH coefficient vector by integrating <f\u00b7Ylm>\n *    using Monte Carlo integration. It is possible to choose the type of\n *    random or quasi- random sequence for the integration.\n *\n *    + 'TripleTensorProduct' return the premultiplied triple tensor product:\n *    the integral of <Ylm x Ylm x Ylm> multiplied by the SH coefficients 'clm'\n *    of 'f'.  The integral is computed using Monte Carlo, as 'ProjectToShMC'\n *    does.\n *\n * TODO: Template the direction sequence.\n */\n\n#define USE_FIBONACCI_SEQ\n//#define USE_BLUENOISE_SEQ\n\n/* From a set of `basis` vector directions, and a spherical function `Functor`,\n * generate the Spherical Harmonics projection of the `Functor`. This algorithm\n  * works as follows:\n *\n *  1. Evaluate the matrix Ylm(w_i) for each SH index and each direction\n *  2. Evaluate the vector of the functor [f(w_0), ..., f(w_n)]\n *  3. Return the product Ylm(w_i)^{-1} [f(w_0), ..., f(w_n)]\n *\n *  Requierement: `basis` must have the dimension of the output SH vector.\n *                `f` must be real valued. Higher dimension functor are not\n *                handled yet.\n */\ntemplate<class Functor, class Vector, class SH>\ninline Eigen::VectorXf ProjectToSH(const Functor& f,\n                                   const std::vector<Vector>& basis) {\n\n   // Get the number of elements to compute\n   const int dsize = basis.size();\n   const int order = sqrt(dsize)-1;\n\n   Eigen::MatrixXf Ylm(dsize, dsize);\n   Eigen::VectorXf flm(dsize);\n\n   for(unsigned int i=0; i<basis.size(); ++i) {\n\n      const Vector& w = basis[i];\n\n      auto ylm = SH::FastBasis(w, order);\n      Ylm.row(i) = ylm;\n\n      flm[i] = f(w);\n   }\n\n   return Ylm.inverse() * flm;\n}\n\n/* Project a spherical function `f` onto Spherical Harmonics coefficients up\n * to order `order` using Monte-Carlo integration.\n */\ntemplate<class Functor, class Vector, class SH>\ninline Eigen::VectorXf ProjectToShMC(const Functor& f, int order, int M=100000) {\n\n   std::mt19937 gen(0);\n   std::uniform_real_distribution<float> dist(0.0,1.0);\n\n   Eigen::VectorXf shCoeffs((order+1)*(order+1));\n#if   defined(USE_FIBONACCI_SEQ)\n   const std::vector<Vector> directions = SamplingFibonacci<Vector>(M);\n#elif defined(USE_BLUENOISE_SEQ)\n   const std::vector<Vector> directions = SamplingBlueNoise<Vector>(M);\n#else\n   const std::vector<Vector> directions = SamplingRandom<Vector>(M);\n#endif\n   for(auto& w : directions) {\n      // Evaluate the function and the basis vector\n      shCoeffs += f(w) * SH::FastBasis(w, order);\n   }\n   shCoeffs *= 4.0*M_PI / float(M);\n\n   return shCoeffs;\n}\n\n/* Compute the triple tensor product \\int Ylm * Ylm * Ylm\n *\n * ## Arguments:\n *\n *    + 'ylm' is the input spherical function SH coeffcients. They will be\n *      prefactored to the triple product tensor to build the matrix.\n *\n *    + 'truncated' allows to export either the truncated matrix (up to order\n *      'n', where 'n' is the order the input SH coeffs 'ylm') or the full matrix\n *      that is order '2n-1'.\n */\ntemplate<class SH, class Vector>\ninline Eigen::MatrixXf TripleTensorProduct(const Eigen::VectorXf& ylm,\n                                           bool truncated=true,\n                                           int nDirections=100000) {\n\n   // Compute the max order\n   const int vsize = ylm.size();\n   const int order = (truncated) ? sqrt(vsize)-1 : 2*sqrt(vsize)-2;\n   const int msize = (truncated) ? vsize         : SH::Terms(order);\n\n   Eigen::MatrixXf res = Eigen::MatrixXf::Zero(msize, msize);\n   Eigen::VectorXf clm(msize);\n\n   // Take a uniformly distributed point sequence and integrate the triple tensor\n   // for each SH band\n#if   defined(USE_FIBONACCI_SEQ)\n   const std::vector<Vector> directions = SamplingFibonacci<Vector>(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n   const std::vector<Vector> directions = SamplingBlueNoise<Vector>(nDirections);\n#else\n   const std::vector<Vector> directions = SamplingRandom<Vector>(nDirections);\n#endif\n   for(auto& w : directions) {\n      SH::FastBasis(w, order, clm);\n      res += clm.segment(0, vsize).dot(ylm) * clm * clm.transpose();\n   }\n\n   res *= 4.0f * M_PI / float(nDirections);\n   return res;\n}\n\n/* Compute the triple tensor product \\int Ylm * Ylm * Ylm for a bunch of\n * function projected on Spherical Harmonics. This method is specially\n * interesting to construct product of (R,G,B) component where each component\n * is stored in a separate vector.\n *\n * ## Arguments:\n *\n *    + 'ylm' is the input spherical function SH coeffcients. They will be\n *      prefactored to the triple product tensor to build the matrix.\n *\n *    + 'truncated' allows to export either the truncated matrix (up to order\n *      'n', where 'n' is the order the input SH coeffs 'ylm') or the full matrix\n *      that is order '2n-1'.\n */\ntemplate<class SH, class Vector>\ninline std::vector<Eigen::MatrixXf> TripleTensorProduct(\n                                       const std::vector<Eigen::VectorXf>& ylms,\n                                       bool truncated=true,\n                                       int nDirections=100000) {\n\n#ifdef USE_THREADS\n   struct TTPThread : public std::thread {\n\n      std::vector<Eigen::MatrixXf> res;\n\n      TTPThread(const std::vector<Vector>& dirs, unsigned int start, unsigned int end,\n                const std::vector<Eigen::VectorXf>& ylms, int order) :\n         std::thread(&TTPThread::run, this, dirs, start, end, ylms, order) {}\n\n      void run(const std::vector<Vector>& dirs, unsigned int start, unsigned int end,\n               const std::vector<Eigen::VectorXf>& ylms, int order) {\n         const int vsize = ylms[0].size();\n         const float fact = 4.0f * M_PI / float(dirs.size());\n\n         const int msize = SH::Terms(order);\n         Eigen::MatrixXf mat(msize, msize);\n         Eigen::VectorXf clm(msize);\n\n         res.reserve(3);\n         res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n         res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n         res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n\n         for(unsigned int k=start; k<end; ++k) {\n            // Get the vector\n            const Vector& w = dirs[k];\n\n            // Construct the matrix\n            SH::FastBasis(w, order, clm);\n            mat = clm * clm.transpose();\n\n            // For each SH vector apply the weight to the matrix and sum it\n            for(unsigned int i=0; i<ylms.size(); ++i) {\n               res[i] += fact * clm.segment(0, vsize).dot(ylms[i]) * mat;\n            }\n         }\n      }\n   };\n#endif\n\n   // Compute the max order\n   const int vsize = ylms[0].size();\n   const int order = (truncated) ? sqrt(vsize)-1 : 2*sqrt(vsize)-2;\n   const int msize = (truncated) ? vsize         : SH::Terms(order);\n\n   std::vector<Eigen::MatrixXf> res(ylms.size(), Eigen::MatrixXf::Zero(msize, msize));\n\n   // Take a uniformly distributed point sequence and integrate the triple tensor\n   // for each SH band\n#if   defined(USE_FIBONACCI_SEQ)\n   const std::vector<Vector> directions = SamplingFibonacci<Vector>(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n   const std::vector<Vector> directions = SamplingBlueNoise<Vector>(nDirections);\n#else\n   const std::vector<Vector> directions = SamplingRandom<Vector>(nDirections);\n#endif\n\n#ifdef USE_THREADS\n   std::vector<TTPThread*> threads;\n   const unsigned int nthreads = std::thread::hardware_concurrency();\n   for(unsigned int i=0; i<nthreads; ++i) {\n      const unsigned int block = nDirections / nthreads;\n      const unsigned int start = i * block;\n      const unsigned int end   = (i<nthreads-1) ? (i+1)*block : nDirections;\n      threads.push_back(new TTPThread(directions, start, end, ylms, order));\n   }\n\n   for(TTPThread* thread : threads) {\n      thread->join();\n\n      for(unsigned int i=0; i<3; ++i) {\n         res[i] += thread->res[i];\n      }\n   }\n#else\n   Eigen::VectorXf clm(msize);\n   const float fact = 4.0f * M_PI / float(nDirections);\n   for(auto& w : directions) {\n      // Construct the matrix\n      SH::FastBasis(w, order, clm);\n      const auto matrix = clm * clm.transpose();\n\n      // For each SH vector apply the weight to the matrix and sum it\n      for(unsigned int i=0; i<ylms.size(); ++i) {\n         res[i] += fact * clm.segment(0, vsize).dot(ylms[i]) * matrix ;\n      }\n   }\n#endif\n   return res;\n}\n\ntemplate<class SH, class Vector>\nEigen::MatrixXf TripleTensorProductCos(int  order,\n                                       int  nDirections=100000) {\n\n   // Compute the max order\n   const int msize = SH::Terms(order);\n\n   Eigen::MatrixXf res = Eigen::MatrixXf::Zero(msize, msize);\n\n   // Take a uniformly distributed point sequence and integrate the triple tensor\n   // for each SH band\n#if   defined(USE_FIBONACCI_SEQ)\n   const std::vector<Vector> directions = SamplingFibonacci<Vector>(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n   const std::vector<Vector> directions = SamplingBlueNoise<Vector>(nDirections);\n#else\n   const std::vector<Vector> directions = SamplingRandom<Vector>(nDirections);\n#endif\n   const float fact = 4.0f * M_PI / float(nDirections);\n   for(auto& w : directions) {\n      // Construct the matrix\n      const Eigen::VectorXf clm = SH::FastBasis(w, order);\n      const auto matrix = clm * clm.transpose();\n\n      // For each SH vector apply the weight to the matrix and sum it\n      if(w[2] > 0.0) {\n         res += fact * w[2] * matrix;\n      }\n   }\n   return res;\n}\n", "meta": {"hexsha": "782455f2c6216ebb83713978ff3b6e2caa6298d7", "size": 10037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SphericalHarmonics.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/SphericalHarmonics.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "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/SphericalHarmonics.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 35.0944055944, "max_line_length": 86, "alphanum_fraction": 0.6449138189, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6648086604839326}}
{"text": "#include <iostream>\nusing namespace std;\n\n#include <ctime>\n// Eigen \u6838\u5fc3\u90e8\u5206\n#include <Eigen/Core>\n// \u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\n#include <Eigen/Dense>\n// Eigenatrix Exponential\n#include <unsupported/Eigen/MatrixFunctions>\nusing namespace Eigen;\n\n// Declaration\nQuaterniond quat_mul(Quaterniond q1,Quaterniond q2);\n\nint main() {\n    // Initializae an euler_angle vector\n    // euler_angle: Roll-Pitch-Yaw\n    //              0 -> -pi/2 -> -pi/4\n    Eigen::Vector3d euler_angle(-M_PI/ 4.0, -M_PI/ 2.0, 0.0);\n    cout << \"euler = \" << euler_angle.transpose() << endl;\n\n    Eigen::Matrix3d R;\n    R = Eigen::AngleAxisd(euler_angle[0], Eigen::Vector3d::UnitZ()) *\n        Eigen::AngleAxisd(euler_angle[1], Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(euler_angle[2], Eigen::Vector3d::UnitX());\n    cout << \"rotation matrix =\\n\" << R << endl;\n\n    Eigen::Quaterniond q;\n    q = Eigen::AngleAxisd(euler_angle[0], Eigen::Vector3d::UnitZ()) *\n        Eigen::AngleAxisd(euler_angle[1], Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(euler_angle[2], Eigen::Vector3d::UnitX());\n    cout << \"quaternion = \" << q.coeffs().transpose() << endl;\n\n    // w\n    Eigen::Vector3d w(0.01,0.02,0.03);\n    cout << \"w = \" << w.transpose() << endl;\n    // w^\n    Eigen::Matrix3d w_hat;\n    w_hat << 0, -w(2), w(1),\n            w(2), 0, -w(0),\n            -w(1), w(0), 0;\n    cout << \"w^= \\n\" << w_hat << endl;\n\n    // R <- Rexp(w^)\n    R = R*w_hat.exp();\n    cout << \"new R = \\n\" << R << endl;\n\n    // q <- q x [1,w].T\n    Eigen::Quaterniond w_mul(1,w(0)/2, w(1)/2, w(2)/2);\n    q = quat_mul(q, w_mul);\n    cout << \"new q = \" << q.coeffs().transpose() << endl;\n    cout << \"new R from q = \\n\" << q.normalized().toRotationMatrix() << endl;\n\n    return 0;\n}\n\n\nQuaterniond quat_mul(Quaterniond q1,Quaterniond q2) {\n    double x =  q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y() + q1.w() * q2.x();\n    double y = -q1.x() * q2.z() + q1.y() * q2.w() + q1.z() * q2.x() + q1.w() * q2.y();\n    double z =  q1.x() * q2.y() - q1.y() * q2.x() + q1.z() * q2.w() + q1.w() * q2.z();\n    double w = -q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z() + q1.w() * q2.w();\n\n    return Quaterniond(w,x,y,z);\n}", "meta": {"hexsha": "b51a18ead139db89eecc252e9e738065ddc7d0b0", "size": 2173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Week1-cpp-eigen/main.cpp", "max_stars_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_stars_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week1-cpp-eigen/main.cpp", "max_issues_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_issues_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week1-cpp-eigen/main.cpp", "max_forks_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_forks_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_forks_repo_licenses": ["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.9242424242, "max_line_length": 86, "alphanum_fraction": 0.5439484584, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6648086581864212}}
{"text": "// error.cpp: numerical error analysis benchmark environment\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 and configure number systems\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 0\n#include <hprblas>\n// Boost arbitrary precision floats\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n// matrix generators\n#include <generators/matrix_generators.hpp>\n\ntemplate<typename Scalar, typename Vector>\nvoid GenerateNumericalAnalysisTestCase(const std::string& header, unsigned N, bool verbose = false) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\n\tstd::cout << \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" << header << std::endl;\n\n\t// calculate the numerical error caused by the linear algebra computation\n\tVector e(N), eprime(N), eabsolute(N), erelative(N), I(N);\n\te = Scalar(1);\n\tI = Scalar(1);\n\t// TODO: it is not clear that for posits this would be a fused matrix-vector operation\n\tmatvec(eprime, I, e);\n\tcout << \"reference vector : \" << e << '\\n';\n\tcout << \"error vector     : \" << eprime << '\\n';\n\t// absolute error\n\teabsolute = e - eprime;\n\tcout << \"absolute error vector : \" << eabsolute << '\\n';\n\tcout << \"L1 norm   \" << hex_format(l1_norm(eabsolute)) << \"  \" << l1_norm(eabsolute) << '\\n';\n\tcout << \"L2 norm   \" << hex_format(l2_norm(eabsolute)) << \"  \" << l2_norm(eabsolute) << '\\n';\n\tcout << \"Linf norm \" << hex_format(linf_norm(eabsolute)) << \"  \" << linf_norm(eabsolute) << '\\n';\n\n\t// relative error\n\tcout << \"relative error\\n\";\n\tScalar relative_error;\n\trelative_error = l1_norm(eabsolute) / l1_norm(e);\n\tcout << \"L1 norm   \" << hex_format(relative_error) << \"  \" << relative_error << '\\n';\n\trelative_error = l2_norm(eabsolute) / l2_norm(e);\n\tcout << \"L2 norm   \" << hex_format(relative_error) << \"  \" << relative_error << '\\n';\n\trelative_error = linf_norm(eabsolute) / linf_norm(e);\n\tcout << \"Linf norm \" << hex_format(relative_error) << \"  \" << relative_error << '\\n';\n\n\t// error volume\n\tcout << \"error bounding box volume\\n\";\n\tcout << \"Measured in Euclidean distance    : \" << error_volume(linf_norm(eabsolute), N, false) << '\\n';\n\tcout << \"Measured in ULPs                  : \" << error_volume(linf_norm(eabsolute), N, true) << \" ulps^\" << N << '\\n';\n\tScalar ulp = numeric_limits<Scalar>::epsilon();\n\tcout << \"L-infinitiy norm measured in ULPs : \" << linf_norm(eabsolute) / ulp << \" ulps\" << '\\n';\n\n\tcout << endl;\n}\n\n// Benchmark Suite runner for numerical error analysis measurements\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\tint nrOfFailedTestCases = 0;\n\n\t// we need to enumerate along the following dimensions\n\t// 1- number systems: the key here is that when we have posits, we use FDP\n\t// 2- algorithms: different computational approaches to solve a system of linear equations\n\t// 3- matrices. easy, difficult, empirical\n\n\t// The measurement will always be the error to this equation:\n\t//    Ax = b, with a b that delivers the solution x = ones()\n\n\t// There is another measure and that is driven by the characteristic polynomial of the matrix:\n\t// If we have very wildy differing eigenvalues, then there are b vectors that can lift up small\n\t// eigenvalues compared to large eigenvalues. Those are situations in which we want to make\n\t// certain we don't have cancellation: a big eigenvalue multiplied by a small scaling factor\n\t// and a small eigenvalue multiplied by a big scaling factor.\n\n\t// the benchmark runner is structured as follows:\n\t// foreach test system\n\t//     pick a test size N\n\t//     foreach number system\n\t//         generate the test matrix A(N,N)\n\t//         generate the test right hand side: b(N) = A * ones()\n\t//         foreach algorithm\n\t//             generate the inverse or decomposition\n\t//             solve the system of equations: Ax = b\n\t//             measure the difference between result x and ones()\n\tusing Scalar = sw::unum::posit<32, 2>;\n\tusing Vector = mtl::vec::dense_vector<Scalar>;\n\tusing Matrix = mtl::mat::dense2D<Scalar>;\n\n\tint N = 5;\n\tMatrix H(N, N);\n\tsw::hprblas::GenerateHilbertMatrix(H, false);\n\tMatrix Hinv = GaussJordanInversion(H);\n\tMatrix Href(N, N);\n\tGenerateHilbertMatrixInverse(Href);\n\tMatrix I(N, N);  // H * Hinv should yield the identity matrix\n\t// TODO: this is not clear that for posits this would be a fused matrix multiply\n\tmatmul(I, H, Hinv);\n\n\tGenerateNumericalAnalysisTestCase<Scalar, Vector>(\"testing\", 10, true);\n\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : 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": "feef637f234f5799b6b5e2bc0e2909f2cb19e30b", "size": 5498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/benchmark/error.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": "tools/benchmark/error.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": "tools/benchmark/error.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": 39.5539568345, "max_line_length": 120, "alphanum_fraction": 0.6818843216, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6647592487063634}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <sstream>\n#include <boost/scoped_ptr.hpp>\n\n#include \"wali/domains/matrix/Matrix.hpp\"\n\n#include \"fixtures-minplus-matrix.hpp\"\n#include \"matrix-equal.hpp\"\n\nusing namespace testing::minplus_matrix;\n\nnamespace wali {\nnamespace domains {\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$constructorAndMatrix, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    MinPlusIntMatrix m(f.mat);\n\n    EXPECT_EQ(m.matrix(), f.mat);\n}\n\n\n#define NUM_ELEMENTS(arr) ((sizeof arr)/(sizeof arr[0]))\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$equalAndIsZeroAndIsOne, battery)\n{\n    MatrixFixtures_3x3 f;\n    MinPlusIntMatrix mats[] = {\n        MinPlusIntMatrix(f.zero.mat),\n        MinPlusIntMatrix(f.id.mat),\n        MinPlusIntMatrix(f.r1.mat),\n        MinPlusIntMatrix(f.r2.mat),\n        MinPlusIntMatrix(f.ext_r1_r2.mat),\n        MinPlusIntMatrix(f.ext_r2_r1.mat),\n    };\n\n    for (size_t left=0; left<NUM_ELEMENTS(mats); ++left) {\n        for (size_t right=0; right<NUM_ELEMENTS(mats); ++right) {\n            EXPECT_EQ(left == right,\n                      mats[left].equal(&mats[right]));\n        }\n    }\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$zero_raw, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    ZeroBackingMatrix_3x3 z;\n\n    MinPlusIntMatrix m(f.mat);\n    MinPlusIntMatrix mz(z.mat);\n\n    boost::scoped_ptr<MinPlusIntMatrix> result(m.zero_raw());\n\n    EXPECT_EQ(z.mat, result->matrix());\n    EXPECT_TRUE(mz.equal(result.get()));\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$one_raw, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    IdBackingMatrix_3x3 z;\n\n    MinPlusIntMatrix m(f.mat);\n    MinPlusIntMatrix mid(z.mat);\n\n    boost::scoped_ptr<MinPlusIntMatrix> result(m.one_raw());\n\n    EXPECT_EQ(z.mat, result->matrix());\n    EXPECT_TRUE(mid.equal(result.get()));\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, twoRandomMatrices)\n{\n    RandomMatrix1_3x3 f1;\n    RandomMatrix2_3x3 f2;\n    ExtendR1R2_3x3 fr12;\n    ExtendR2R1_3x3 fr21;\n\n    MinPlusIntMatrix m1(f1.mat);\n    MinPlusIntMatrix m2(f2.mat);\n\n    boost::scoped_ptr<MinPlusIntMatrix> result12(m1.extend_raw(&m2));\n    boost::scoped_ptr<MinPlusIntMatrix> result21(m2.extend_raw(&m1));\n\n    EXPECT_EQ(fr12.mat, result12->matrix());\n    EXPECT_EQ(fr21.mat, result21->matrix());\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, extendAgainstZero)\n{\n    RandomMatrix1_3x3 f;\n    ZeroBackingMatrix_3x3 z;\n\n    MinPlusIntMatrix mf(f.mat);\n    MinPlusIntMatrix mz(z.mat);\n\n    boost::scoped_ptr<MinPlusIntMatrix>\n        result1Z(mf.extend_raw(&mz)),\n        resultZ1(mz.extend_raw(&mf)),\n        resultZZ(mz.extend_raw(&mz));\n\n    EXPECT_EQ(z.mat, result1Z->matrix());\n    EXPECT_EQ(z.mat, resultZ1->matrix());\n    EXPECT_EQ(z.mat, resultZZ->matrix());\n\n    EXPECT_TRUE(mz.equal(result1Z.get()));\n    EXPECT_TRUE(mz.equal(resultZ1.get()));\n    EXPECT_TRUE(mz.equal(resultZZ.get()));\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$extend_raw, extendAgainstOne)\n{\n    RandomMatrix1_3x3 fr1;\n    IdBackingMatrix_3x3 id;\n\n    MinPlusIntMatrix mr1(fr1.mat);\n    MinPlusIntMatrix mid(id.mat);\n\n    boost::scoped_ptr<MinPlusIntMatrix>\n        result_R1_Id(mr1.extend_raw(&mid)),\n        result_Id_R1(mid.extend_raw(&mr1)),\n        result_Id_Id(mid.extend_raw(&mid));\n\n    EXPECT_EQ(fr1.mat, result_R1_Id->matrix());\n    EXPECT_EQ(fr1.mat, result_Id_R1->matrix());\n    EXPECT_EQ(id.mat,  result_Id_Id->matrix());\n\n    EXPECT_TRUE(mr1.equal(result_R1_Id.get()));\n    EXPECT_TRUE(mr1.equal(result_Id_R1.get()));\n    EXPECT_TRUE(mid.equal(result_Id_Id.get()));\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix$$print, random)\n{\n    RandomMatrix1_3x3 f;\n    MinPlusIntMatrix m(f.mat);\n    std::stringstream ss;\n\n    m.print(ss);\n\n    EXPECT_EQ(\"Matrix: [3,3]\"\n              \"(([1],[infinity],[infinity]),\"\n              \"([12],[0],[1]),\"\n              \"([infinity],[infinity],[17]))\",\n              ss.str());\n}\n\n\nTEST(wali$domains$matrix$MinPlusIntMatrix, callWaliTestSemElemImpl)\n{\n    RandomMatrix1_3x3 f;\n    sem_elem_t m = new MinPlusIntMatrix(f.mat);\n    test_semelem_impl(m);\n}\n\n}\n}\n", "meta": {"hexsha": "5c36a7be805f1f4ea1926e3c18dfa04012c8b051", "size": 4066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-minplusmatrix.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-minplusmatrix.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-minplusmatrix.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 24.3473053892, "max_line_length": 78, "alphanum_fraction": 0.6773241515, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6647592307285781}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <list>\n\n/**\n* A Simple Kalman filter.\n*   A - System dynamics matrix\n*   C - Output matrix\n*   Q - Process noise covariance\n*   R - Measurement noise covariance\n*   P - Estimate error covariance\n* The input is a 3d position vector.\n* Outputs are a 3d position, 3d velocity, and 3d acceleration vectors.\n*/\n\nclass KalmanFilter_Position3D {\n\npublic:\n\t/**\n\t* Initialize the kalman filter.\n\t* dt - a filter time step.\n\t*/\n\tKalmanFilter_Position3D(const double dt);\n\n\t/** Update the estimated state based on measured values. */\n\tvoid Update(const Eigen::VectorXd& y);\n\n\t/** Returns the filter estimation. */\n\tinline Eigen::VectorXd GetEstimate() { return x_predicted; }\nprivate:\n\tstatic const int n, m;\t\t\t\t// The size of the filter output and input vectors.\n\tconst double dt;\t\t\t\t\t// The filter time step size.\n\n\tEigen::VectorXd x_predicted;\t\t// Last predicted value.\n\tEigen::MatrixXd P, A, H, R, Q, I;\t// Kalman filter matrices.\n};\n", "meta": {"hexsha": "b9257d9bfb2c4f795213da3bf67838a085aac82f", "size": 973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kalman/kalman-pos-3d.hpp", "max_stars_repo_name": "bitbloop/KalmanFilter", "max_stars_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T15:55:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:55:01.000Z", "max_issues_repo_path": "src/kalman/kalman-pos-3d.hpp", "max_issues_repo_name": "bitbloop/KalmanFilter", "max_issues_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_issues_repo_licenses": ["MIT"], "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/kalman/kalman-pos-3d.hpp", "max_forks_repo_name": "bitbloop/KalmanFilter", "max_forks_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T07:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:29:55.000Z", "avg_line_length": 25.6052631579, "max_line_length": 78, "alphanum_fraction": 0.7009249743, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.664605409457244}}
{"text": "#ifndef PRIMALITY_HPP\n#define PRIMALITY_HPP\n\n#include <algorithm>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/random.hpp>\n#include <cmath>\n#include <ctime>\n#include <iostream>\n#include <random>\n\n#include \"big_int_type.hpp\"\n#include \"mod_exponentiation.hpp\"\n\nclass Prime_generator {\nprivate:\n  big_int prime;\n  big_int odd;\n  boost::random::mt19937 mt19937_gen;\n\npublic:\n  Prime_generator() {}\n  Prime_generator(unsigned seed);\n\n  bool is_composite(big_int n, int a, big_int d, big_int s);\n\n  bool miller_rabin(big_int n);\n\n  /*\n   * Gera um n\u00famero primo aleat\u00f3rio no intervalo.\n   */\n  big_int random_prime(unsigned max_bits);\n\n  big_int random_odd(unsigned max_bits);\n};\n\n#endif", "meta": {"hexsha": "cba1ea39cc9f30dcc8741cd5082331ee88979def", "size": 738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/primality.hpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/primality.hpp", "max_issues_repo_name": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/primality.hpp", "max_forks_repo_name": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4210526316, "max_line_length": 60, "alphanum_fraction": 0.7479674797, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6645936304761173}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/list.hpp>\n\n#include <itmx/geometry/DualNumber.h>\nusing namespace itmx;\n\n//#################### TESTS ####################\n\ntypedef boost::mpl::list<double,float> TS;\n\nBOOST_AUTO_TEST_SUITE(test_DualNumber)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_conjugate, T, TS)\n{\n  DualNumber<T> dn(2,3);\n  BOOST_CHECK(DualNumber<T>::close(dn.conjugate(), DualNumber<T>(2,-3)));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_inverse, T, TS)\n{\n  DualNumber<T> dn(2,3);\n  DualNumber<T> dnInv = dn.inverse();\n  BOOST_CHECK(DualNumber<T>::close(dnInv, DualNumber<T>(0.5f,-0.75f)));\n  BOOST_CHECK(DualNumber<T>::close(dnInv.inverse(), dn));\n  BOOST_CHECK(DualNumber<T>::close(dn * dnInv, DualNumber<T>(1,0)));\n  BOOST_CHECK(DualNumber<T>::close(dnInv * dn, DualNumber<T>(1,0)));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_sqrt, T, TS)\n{\n  DualNumber<T> dn(2,3);\n  DualNumber<T> dnSqr = dn.sqrt();\n  BOOST_CHECK(DualNumber<T>::close(dnSqr, DualNumber<T>(1.41421f,1.06066f)));\n  BOOST_CHECK(DualNumber<T>::close(dnSqr * dnSqr, dn));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3e863aa35940313630cd248a26f6af25952cc833", "size": 1107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/itmx/test_DualNumber.cpp", "max_stars_repo_name": "GucciPrada/spaint", "max_stars_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T06:39:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-16T06:39:21.000Z", "max_issues_repo_path": "tests/unit/itmx/test_DualNumber.cpp", "max_issues_repo_name": "GucciPrada/spaint", "max_issues_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "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": "tests/unit/itmx/test_DualNumber.cpp", "max_forks_repo_name": "GucciPrada/spaint", "max_forks_repo_head_hexsha": "b09ff1ec0d9e123cf316f2737e1b70b5ecc0beea", "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.675, "max_line_length": 77, "alphanum_fraction": 0.6973803071, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6645936232723555}}
{"text": "\n#include <boost/numeric/ublas/vector.hpp>\n\nvoid toto(unsigned n) {\n  boost::numeric::ublas::vector<double> v(n);\n  for (unsigned i = 0; i < v.size (); i++) {\n    v (i) = i;\n  }\n}\n\n", "meta": {"hexsha": "2ee8445637d4ef54024c3bbfb19dc93823ec4269", "size": 181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pagai2/ex/boost_vector.cpp", "max_stars_repo_name": "trailofbits/screen", "max_stars_repo_head_hexsha": "311e5e4e1a8ee12844b404c5a4d39e27072cbb6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2016-10-24T22:12:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T03:36:21.000Z", "max_issues_repo_path": "ex/boost_vector.cpp", "max_issues_repo_name": "julienhenry/pagai", "max_issues_repo_head_hexsha": "d58578c460b755c7239987350202ff35bd9ec2aa", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-10-05T19:35:21.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-10T02:15:57.000Z", "max_forks_repo_path": "pagai2/ex/boost_vector.cpp", "max_forks_repo_name": "trailofbits/screen", "max_forks_repo_head_hexsha": "311e5e4e1a8ee12844b404c5a4d39e27072cbb6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T04:53:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T03:36:24.000Z", "avg_line_length": 16.4545454545, "max_line_length": 45, "alphanum_fraction": 0.5745856354, "num_tokens": 61, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6645936116004442}}
{"text": "#pragma once\n\n// Eigen includes\n#include <Eigen/Core>\n\n// STL includes\n#include <cassert>\n#include <vector>\n\n#define AXIAL_EPSILON 1.0E-6\n\n/* _Cosine Sum Integral_\n */\ninline Eigen::VectorXf CosSumIntegral(float x, float y, float c, int n) {\n\n\tconst float siny  = sin(y);\n\tconst float sinx  = sin(x);\n\tconst float cosy  = cos(y);\n\tconst float cosx  = cos(x);\n\tconst float cosy2 = cosy*cosy;\n\tconst float cosx2 = cosx*cosx;\n\n   static const Eigen::Vector2i i1 = {1, 1};\n   static const Eigen::Vector2i i2 = {2, 2};\n   Eigen::Vector2i i = {0, 1};\n   Eigen::Vector2f F = {y-x, siny-sinx};\n   Eigen::Vector2f S = {0.0f, 0.0f};\n\n   Eigen::VectorXf R = Eigen::VectorXf::Zero(n+2);\n\n   Eigen::Vector2f pow_c    = {1.0, c};\n   Eigen::Vector2f pow_cosx = {cosx, cosx2};\n   Eigen::Vector2f pow_cosy = {cosy, cosy2};\n\n   while(i[1] <= n) {\n      // S <= S + c^{i} F\n      S += pow_c.cwiseProduct(F);\n\n      // The resulting vector `R` is shifted of one to the right. This is due to\n      // the fact that order `n` moment requires only up to order `n-1` power of\n      // cosine integrals.\n      R.segment(i[1], 2) = S;\n\n      // T <= cos(y)^{i+1} sin(y) - cos(x)^{i+1} sin(x)\n      // F <= (T + i+1) F / (i+2)\n      auto T = pow_cosy*siny - pow_cosx*sinx;\n      F = (T + (i+i1).cast<float>().cwiseProduct(F)).cwiseQuotient((i+i2).cast<float>());\n\n      // Update temp variable\n      i        += i2;\n      pow_c    *= c*c;\n      pow_cosx *= cosx2;\n      pow_cosy *= cosy2;\n   }\n\n   return R;\n}\n\n/* _sign_\n *\n * Sign function template\n */\ntemplate <typename T>\ninline int sign(T val) {\n    return (T(0) <= val) - (val < T(0));\n}\n\n/* _clamp_\n *\n * Clamp function template to restrict a given function to be in between\n * boundaries.\n */\ntemplate <typename T>\ninline T clamp(T val, T a, T b) {\n    return std::max<T>(a, std::min<T>(b, val));\n}\n\n\n/* _Line Integral_\n */\ntemplate<class Vector>\ninline Eigen::VectorXf LineIntegral(const Vector& A, const Vector& B,\n                                    const Vector& w, int n) {\n#ifdef ZERO_ORTHOGONAL\n   auto wDotA = Vector::Dot(A, w);\n   auto wDotB = Vector::Dot(B, w);\n   // Zeroth moment and orthogonal directions 'w' to the while edge do not\n   // require this part since it will always return '0';\n   if(std::abs(wDotA) < AXIAL_EPSILON && std::abs(wDotB) < AXIAL_EPSILON) {\n      return Eigen::VectorXf::Zero(n+2);\n   }\n#endif\n\n   // Note: expanding the (I-ssT)B expression from Arvo's LineIntegral pseudo\n   // code to the projection of B on plane with A as normal.\n   const auto s = Vector::Normalize(A);\n   const auto t = Vector::Normalize(B - Vector::Dot(s, B)*s);\n\n   const auto a = Vector::Dot(w, s);\n   const auto b = Vector::Dot(w, t);\n   const auto c = sqrt(a*a + b*b);\n\n   // Compute the arc-length on which to compute the integral of the moment\n   // function and the shift 'p' that change the integral to the integral of\n   // a shifted cosine.\n   const auto r = Vector::Dot(s, B) / Vector::Dot(B,B);\n   const auto l = acos(clamp<float>(r, -1.0f, 1.0f));\n   const auto p = atan2(b, a);\n\n   return CosSumIntegral(-p, l-p, c, n);\n}\n\n/* _Boundary Integral_\n *\n * Compute the integral along P egdes of the up to order 'n' axial moment\n * around w. By using 'n' = 'w' you can compute the single axis moment. Double\n * axis moment with second axis begin the normal must use 'v' == 'n' ('n' being\n * the normal).\n */\ntemplate<class Polygon, class Vector>\ninline Eigen::VectorXf BoundaryIntegral(const Polygon& P, const Vector& w,\n                                        const Vector& v, int n) {\n   // Init to zero\n   Eigen::VectorXf b = Eigen::VectorXf::Zero(n+2);\n\n   for(auto& edge : P) {\n      // Compute the edge normal\n      const auto normal = Vector::Normalize(Vector::Cross(edge.A, edge.B));\n\n      // Add the egde integral to the total integral\n      const auto dotNV   = Vector::Dot(normal, v);\n      const auto lineInt = LineIntegral<Vector>(edge.A, edge.B, w, n);\n      b += dotNV * lineInt;\n   }\n\n   return b;\n}\n\n/* _Solid Angle_\n *\n * Compute the solid angle sustained by a `Polygon P`.\n */\ntemplate<class Polygon, class Vector>\ninline float SolidAngle(const Polygon& P) {\n   if(P.size() == 3) {\n      // Using the method of Oosterom and Strackee [1983]\n      const Vector& A = P[0].A;\n      const Vector& B = P[1].A;\n      const Vector& C = P[2].A;\n\n      const Vector bc = Vector::Cross(B,C);\n      const float num = std::abs(Vector::Dot(bc, A));\n      const float al = Vector::Length(A);\n      const float bl = Vector::Length(B);\n      const float cl = Vector::Length(C);\n      const float den = al*bl*cl\n                      + Vector::Dot(A, B)*cl\n                      + Vector::Dot(A, C)*bl\n                      + Vector::Dot(B, C)*al;\n\n      float phi = atan2(num, den);\n      if(phi < 0) {\n         phi += M_PI;\n      }\n      return 2.0f * phi;\n\n   } else {\n      // Using the algorithm for computing solid angle of polyhedral cones by\n      // Mazonka found in http://arxiv.org/pdf/1205.1396v2.pdf\n      std::complex<float> z(1, 0);\n      for(unsigned int k=0; k<P.size(); ++k) {\n         const Vector& A = P[(k > 0) ? k-1 : P.size()-1].A;\n         const Vector& B = P[k].A;\n         const Vector& C = P[k].B;\n\n         const float ak = Vector::Dot(A, C);\n         const float bk = Vector::Dot(A, B);\n         const float ck = Vector::Dot(B, C);\n         const float dk = Vector::Dot(A, Vector::Cross(B, C));\n         const std::complex<float> zk(bk*ck-ak, dk);\n         z *= zk;\n      }\n      const float arg = std::arg(z);\n      return arg;\n   }\n}\n\n/* _Check Polygon_\n *\n * Check if the Poylgon P is well oriented. For a triangle, the centroid of the\n * triangle `D` is computed as `A + B + C / 3` and compared to the normal of\n * the triangle using the orientation. The normal and the centroid must match\n * orientation for the normal of edges to be outwards.\n */\ntemplate<class Polygon, class Vector>\ninline bool CheckPolygon(const Polygon& P) {\n\n   // A closed Polygon cannot be smaller than 3 Edges.\n   if(P.size() < 3) {\n      return false;\n\n   // Special case for triangles.\n   } else if(P.size() == 3) {\n      // Check with respect to centroid\n      const auto D = (P[0].A + P[1].A + P[2].A) / 3.0f;\n      const auto N = Vector::Cross(P[1].A-P[0].A, P[2].A-P[0].A);\n      return Vector::Dot(D, N) <= 0.0f;\n\n   // General computation\n   } else {\n      // This is a heuristic to select a point on the bounding box of the\n      // polygon. The orientation test is then computed on this particular\n      // corner.\n      unsigned int K = 0;\n      const Vector* minX = &P[0].B;\n      for(unsigned int k=1; k<P.size(); ++k) {\n         const Vector* X = &P[k].B;\n         if(X->x < minX->x || (X->x <= minX->x && X->y < minX->y)) {\n            minX = X;\n            K    = k;\n         }\n      }\n\n      // Perform the test as defined on the Wikipedia page:\n      //   https://en.wikipedia.org/wiki/Curve_orientation\n      const int K2 = (K < P.size()-1) ? K+1 : 0;\n      const auto D = (P[K].A + P[K].B + P[K2].B) / 3.0f;\n      const auto N = Vector::Cross(P[K].B-P[K].A, P[K2].B-P[K].A);\n      const bool r = Vector::Dot(D, N) <= 0.0f;\n      return r;\n   }\n}\n\n/* _Axial Moments_\n *\n * input:\n *   + Polygon P: A set of egdes that can be enumerated using iterators.\n                  Each edge must enable to access two Vector A and B.\n *   + Vector  w: A 3D vector with elements accessible as x,y,z this\n                  vector defines the axis on which to compute moments.\n *   + int     n: The maximum moment order to be computed.\n *\n * output:\n *   + VectorX r: A vector containing all moments up to order 'n'\n */\ntemplate<class Polygon, class Vector>\ninline Eigen::VectorXf AxialMoment(const Polygon& P, const Vector& w, int n) {\n\n   // Check if the polygon is well oriented\n   const bool check = CheckPolygon<Polygon, Vector>(P);\n   if(!check) {\n      return Eigen::VectorXf::Zero(n+2);\n   }\n\n   // Arvo's boundary integral for single vector moment.\n   Eigen::VectorXf a = - BoundaryIntegral<Polygon, Vector>(P, w, w, n);\n\n   // Generate the 'b' vector which equals to the Polygon solid angle for\n   // even moments and zero for odd moments.\n   const int n2 = (n+2)/2;\n   auto b = Eigen::Map<Eigen::VectorXf, 0, Eigen::InnerStride<2>>(a.data(), n2);\n   b += Eigen::VectorXf::Constant(n2, SolidAngle<Polygon, Vector>(P));\n\n   // 'c' is the vector of linear elements, storing 'i+1' for index 'i'\n   auto c = Eigen::VectorXf::LinSpaced(n+2, 1, n+2);\n\n   return a.cwiseQuotient(c);\n}\n\n/* _Axial Moments_\n *\n * Compute the axial moments for given set of directions used for lobe sharing\n * the maximum cosine order to compute the integral is a function of the size\n * of the directions list.\n */\ntemplate<class Polygon, class Vector>\ninline Eigen::VectorXf AxialMoments(const Polygon& P,\n                                    const std::vector<Vector>& directions) {\n\n   const int dsize = directions.size();\n   const int order = (dsize-1) / 2 + 1;\n\n   Eigen::VectorXf result(dsize*order);\n\n   for(int i=0; i<dsize; ++i) {\n\n      // Get the vector associated to the current row\n      const Vector& w = directions[i];\n\n      // Evaluate all the Y_{l,m} for the current vector\n      const auto In = AxialMoment<Polygon, Vector>(P, w, order-1);\n\n      const int shift = i*order;\n      result.segment(shift, order) = In.segment(0, order);\n   }\n   return result;\n}\n", "meta": {"hexsha": "714d6b42179bbddb5a5550804b569853fb429dbe", "size": 9328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/AxialMoments.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/AxialMoments.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "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/AxialMoments.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 31.3020134228, "max_line_length": 89, "alphanum_fraction": 0.5966981132, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6645936021626073}}
{"text": "#include<iostream>\n#include<fstream>\n#include<vector>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/sparsity_pattern.h>\n\nusing namespace dealii;\n\n// Computing matrix A times vector b, and using the A[0] to store the result and return it.\nstd::vector<double> multiply(std::vector<std::vector<double>> A, std::vector<double> b)\n{\n  int m=A.size();\n  int n=b.size();\n  for (int i=0;i<m;i++)\n    {\n      double temp=0;\n      for(int j=0;j<n;j++)\n\t{\n\t  temp+=A[i][j]*b[j];\n\t}\n      A[0][i]=temp;\n      //std::cout<<temp;\n      //std::cout<<\"The result of \"<<i+1<<\"th iteration\\n\";\t\t\t\n      \n    }\n\n  return A[0];\n}\n\n// Computing u'*v;\ndouble multiply(std::vector<double> u, std::vector<double> v)\n{\n  if(u.size()!=v.size())\n    {\n      std::cout<<\"Multiply() ERROR: u'*v error! Please Check the size of u and v!\";\n    }\n  else\n    {\n      double sum=0;\n      for(int i=0;i<u.size();i++)\n\t{\n\t  sum+=u[i]*v[i];\n\t}\n      \n      return sum;\n    }\n}\n\n// Design for return transpose matrix of A;\nstd::vector<std::vector<double>> transpose(std::vector<std::vector<double>> A)\n{\n  int n=A.size();\n  int m=A[0].size();\n    if (n < m)\n      {\n        for (int i = 0; i < n; i++)\n\t  {\n            for (int j = 0; j < i; j++)\n\t      {\n                double temp = A[j][i];\n                A[j][i] = A[i][j];\n                A[i][j] = temp;\n\t      }\n\t  }\n        for (int i = n; i < m; i++)\n\t  {\n            std::vector<double> temp;\n            for (int j = 0; j < n; j++)\n\t      {\n                temp.push_back(A[j][i]);\n\t      }\n            A.push_back(temp);\n\t  }\n        for (int i = 0; i < n; i++)\n\t  {\n            for (int j = n; j < m; j++)\n\t      {\n                A[i].pop_back();\n\t      }\n\t  }\n      }\n    else if(m<n)\n      {\n        for (int i = 0; i < m; i++)\n\t  {\n            for (int j = 0; j < i; j++)\n\t      {\n                double temp = A[j][i];\n                A[j][i] = A[i][j];\n\t\tA[i][j] = temp;\n\t      }\n\t  }\n        for (int i = 0; i < m; i++)\n\t  {\n            for (int j = m; j < n; j++)\n\t      {\n                A[i].push_back(A[j][i]);\n\t      }\n\t  }\n\n        for (int i = m; i < n; i++)\n\t  {\n            A.pop_back();\n\t  }\n\n      }\n    else\n      {\n\tfor(int i=0;i<n;i++)\n\t  {\n\t    for(int j=0;j<i;j++)\n\t      {\n\t\tdouble temp=A[j][i];\n\t\tA[j][i]=A[i][j];\n\t\tA[i][j]=temp;\n\t      }\n\t  }\n      }\n\n    return A;\n\n}\n\n//This function computes the matrix A times matrix B, and its result will be stored in A.\n// It can be improved if reducing the use of the temp matrix to store the original values which\n// is used in computing.\nvoid multiply(std::vector<std::vector<double>> &A, std::vector<std::vector<double>> B)\n{\n    int n = A.size();\n    int m = B.size();\n    int col = B[0].size();\n    std::vector<double> temp(m);\n    std::vector<std::vector<double>> A0(n, temp);\n\n    if (col < n)\n      {\n        for (int i = 0; i < n; i++)\n\t  {\n            for (int j = 0; j < col; j++)\n\t      {\n                double tempValue = 0;\n                for (int t = 0; t < m; t++)\n\t\t  {\n                    tempValue += A[i][t] * B[t][j];\n\t\t  }\n                A0[i][j] = tempValue;\n\t      }\n            for (int j = col; j < m; j++)\n\t      {\n                A0[i].pop_back();\n\t      }\n\t  }\n\n        A = A0;\n      }\n    else\n      {\n        for (int i = 0; i <n; i++)\n\t  {\n            for (int j = 0; j < m; j++)\n\t      {\n                double tempValue = 0;\n                for (int t = 0; t < m; t++)\n\t\t  {\n                    tempValue += A[i][t] * B[t][j];\n\t\t  }\n                A0[i][j] = tempValue;\n\t      }\n            for (int j = m; j < col; j++)\n\t      {\n                double tempValue = 0;\n                for (int t = 0; t < m; t++)\n\t\t  {\n                    tempValue += A[i][t] * B[t][j];\n\t\t  }\n                A0[i].push_back(tempValue);\n\t      }\n\t  }\n        A = A0;\n      }\n}\n\n// this function will turn the matrix Q into the nxn identity matrix;\nvoid identitymatrix(std::vector<std::vector<double>> &Q, int n)\n{\n  Q.clear();\n  std::vector<double> temp(n,0);\n  for (int i=0;i<n;i++)\n    {\n      Q.push_back(temp);\n      Q[i][i]=1;\n    }\n}\n\n// This function computes the infi-norm of vector x;\ndouble infi_Norm(std::vector<double> x)\n{\n  double norm=0;\n  for (int i=0;i<x.size();i++)\n    {\n      if (norm<abs(x[i]))\n\t{\n\t  norm=abs(x[i]);\n\t}\n    }\n  return norm;\n}\n\n//////\n// Multiplication of SparseMatrix A and vector x0;\nstd::vector<double> multiply(const SparseMatrix<double> &A, std::vector<double> x0)\n{\n  std::vector<double> x(x0.size(),0);\n  //  std::cout<<\"Flag 1!!\\n\";\n  //std::cout<<A.n()<<\"\\n\";\n  \n  if (A.n()!=x0.size())\n    {\n      std::cout<<\"Function multiply() ERROR: The sizes of matrix and vector are not same! Please check it!\\n\";\n    }\n  else\n    {\n      // std::cout<<\"TEST POINT 2 \\n\";\n      for(int k=0;k<A.m();k++)\n\t{\n\t  //std::cout<<\"this is the \"<<k<<\"th iterations \\n\";\n\t  SparseMatrix<double>::const_iterator i=A.begin(k);\n\t  \n\t  while(i!=A.end(k))\n\t    {\n\t      x[k]+=i->value()*x0[i->column()];\n\t      ++i;\n\t    }\n\t}\n      return x;\n    }\n}\n\n\n//void Householder(std::vector<std::vector<double>> *A, std::vector<std::vector<double>> *P)\n//void Householder(std::vector<std::vector<double>> *A, std::vector<std::vector<double>> *P)\n\n// This function computes the householder process of the symmetric definite matrix, it return\n// two matrices. The tridiagonal matrix coordinating with A and the hermitian unitary matrix P.\nvoid Householder(std::vector<std::vector<double>> &A, std::vector<std::vector<double>> &P)\n{\n  int n=A.size();\n  std::vector<std::vector<double>> Pk;\n\n  for(int k=0;k<n-2;k++)\n    {\n      identitymatrix(Pk, n);\n      double q=0;\n      double alpha=0;\n      // Computing the value of q in the Householder function;\n      for(int i=k+1;i<n;i++)\n\t{\n\t  q+=A[i][k]*(A[i][k]);\n\t}\n\n      // Computing the value of alpha\n      if(A[k+1][k]==0)\n\t{\n\t  alpha=-sqrt(q);\n\t}\n      else\n\t{\n\t  alpha=-sqrt(q)*A[k+1][k]/abs(A[k+1][k]);\n\t  // std::cout<<\"the abs A[k+1][k] is \"<<A[k+1][k]<<std::endl;\n\t}\n      \n      double RSQ=alpha*alpha-alpha*A[k+1][k]; // RSQ = 2r^2;\n\n      //std::cout<<\"Check Point 2, This is RSQ:::\"<<RSQ<<\"\\n\";\n\t\n      std::vector<double> v(n-k,0), u(n-k,0), z(n-k,0);\n      v[0]=0;\n      v[1]=A[k+1][k]-alpha;\n\n      //std::cout<<\"Check Point 3::: \"<<v[1]<<\" \\n\";\n      // w=(1/sqrt(2*RSQ)*v=1/2r*v);\n      for(int j=2;j<v.size();j++)\n\t{\n\t  v[j]=A[k+j][k];\n\t}\n      \n      // std::cout<<\"CheckPPPPPoint555 \\n\";\n      \n      for(int j=0;j<n-k;j++)\n\t{\n\t  for(int i=1;i<n-k;i++)\n\t    {\n\t      u[j]+=A[k+j][k+i]*v[i];\n\t    }\n\t  u[j]/=RSQ;\n\t}\n\n      //std::cout<<\"Check POOOIONIOHIHO\\n\";\n      \n      double PROD=0;\n      for(int i=1;i<n-k;i++)\n\t{\n\t  PROD+=v[i]*u[i];\n\t}\n\n      //std::cout<<\"CheckPoint 4!!!!!!!!!\\n\";\n      \n      for(int j=0;j<n-k;j++)\n\t{\n\t  z[j]=u[j]-PROD/(2*RSQ)*v[j];\n\t}\n\n      for(int l=k+1;l<n-1;l++)\n\t{\n\t  for(int j=l+1;j<n;j++)\n\t    {\n\t      A[j][l]=A[j][l]-v[l-k]*z[j-k]-v[j-k]*z[l-k];\n\t      A[l][j]=A[j][l];\n\t    }\n\t  A[l][l]=A[l][l]-2*v[l-k]*z[l-k];\n\t}\n      \n      A[n-1][n-1]=A[n-1][n-1]-2*v[n-k-1]*z[n-k-1];\n\t\n      for(int j=k+2;j<n;j++)\n\t{\n\t  A[k][j]=0;\n\t  A[j][k]=0;\n\t}\n\n      A[k+1][k]=A[k+1][k]-v[1]*z[0];\n      A[k][k+1]=A[k+1][k];\n\n\n      for (int j=k+1;j<n;j++)\n\t{\n\t  std::vector<double> temp(j-k,0);\n\t  for(int i=k+1;i<=j;i++)\n\t    {\n\t      for(int t=k+1;t<n;t++)\n\t\t{\n\t\t  temp[i-k-1]+=v[i-k]*v[t-k]*Pk[t][j]/(2*RSQ);\n\t\t}\n\t    }\n      \n\t  //temp=multiply(W,Pj);// to get the jth column of the W*P;\n\t  for (int i=k+1;i<=j;i++)\n\t    {\n\t      Pk[i][j]-=2*temp[i-k-1];\n\t      Pk[j][i]=Pk[i][j];\n\t    }\n\t}\n      multiply(P,Pk);\n\n    }\n\n}\n\n\n///////\n// This function computes the QR factorization of the tridiagonal matrix A.\n// Input: tridiagonal matrix A, identity matrix Q\n// Output: uptriangle matrix A_, the orthonormal matrix Q; A=Q*A_;\n//\n// tips: Maybe I can improve the function by replace the matrix A by two vectors an bn-1;\n// an contains the diagonal entries of A; bn-1 contains the sub-diagonal entries of A;\n\nvoid QR(std::vector<std::vector<double>> &A, std::vector<std::vector<double>> &Q)\n{\n  int n=A.size();\n\n  // obtain the diagonal and subdiagonal entries of matrix A;\n  /*\n  std::vector<double>an(n),bn(n-1);\n  for (int i=0;i<A.size()-1;i++)\n    {\n      an[i]=A[i][i];\n      bn[i]=A[i+1][i];\n    }\n  an[n-1]=A[n-1][n-1];\n  */\n  \n  for (int i=0;i<A.size()-1;i++)\n    {\n      double theta=0;\n      double tempa1=A[i][i],tempa2=A[i+1][i+1],tempb=A[i+1][i],tempc=A[i][i+1];\n      theta=atan(A[i+1][i]/A[i][i]);\n      double c=cos(theta), s=sin(theta);\n\n      A[i][i]=c*tempa1+s*tempb;\n      A[i][i+1]=c*tempc+s*tempa2;\n      A[i+1][i+1]=-s*tempc+c*tempa2;\n      A[i+1][i]=-s*tempa1+c*tempb;\n      if (i<A.size()-2)\n\t{\n\t  A[i][i+2]=s*A[i+1][i+2];\n\t  A[i+1][i+2]=c*A[i+1][i+2];\n\t}\n\n\n      // update the orthogonal matrix Q by Q_k=Q_k-1*Q;\n      \n      for(int k=0;k<n;k++)\n\t{\n\t  double tmp1=Q[k][i],tmp2=Q[k][i+1];\n\t  Q[k][i]=Q[k][i]*c+Q[k][i+1]*s;\n\t  Q[k][i+1]=tmp1*(-s)+tmp2*c;\n\t}\n      \n    }\n\n}\n\n\n\n\n// This function computes the eigenvalue of the matrix A by QR methods, and it will also return the\n// matrix Q during the process;\nvoid QRSolver(std::vector<std::vector<double>> &A, std::vector<std::vector<double>> &Q, double tol=0.001)\n{\n  int n=A.size();\n  // using householder transform matrix A into the tridiagonal matrix\n  // store it in A and store the Householder unitary matrix in Q; A=QA_Q; \n  //Householder(A,Q);\n\n  // Qk as the initial matrix for every QR factorization, multiplying it together to get the\n  // final unitary matrix;\n  std::vector<std::vector<double>> Qk;\n  \n  // Get the subdiagonal entries of the matrix A and verify if its norm smaller than the tolerance;\n  // If it is small enough that means we diagonalize the matrix A and the diagonal entries are\n  // eigenvalues of A.\n  std::vector<double> b(n-1,1);\n  for(int i=0;i<n-1;i++)\n    {\n      b.push_back(A[i+1][i]);\n    }\n\n  int num=0;\n  while (infi_Norm(b)>tol&&num<1000)\n    {\n      num++;\n\n      b.clear();\n\n      Householder(A,Q);\n      \n      identitymatrix(Qk,n);\n\n      QR(A,Qk);\n     \n      // Compute the num-th iteration, get the Qk in this step;\n      multiply(Q,Qk);\n      // compute R*Q beacuse I store the R(computed above) into A, So I directly use multiply\n      // function to get A*Q into A=RQ.\n      multiply(A,Qk);\n\n      //update the entries of b, i.e. the subdiagonal entries of matrix A=RQ;\n        for(int i=0;i<n-1;i++)\n\t  {\n\t    b.push_back(A[i+1][i]);\n\t  }\n    }\n}\n\n\nclass MinTrace\n{\n public:\n  MinTrace();\n  MinTrace(SparseMatrix<double> A, SparseMatrix<double> M, int p=1);\n\n  // get the random initial matrix V which satisifies that: V'*M*V=I_p;\n  std::vector<std::vector<double>>rand_V(); \n\n  // compute the orthonormal vectors corresponding to M from the original vectors U={u_1,u_2,...,u_p};\n  std::vector<std::vector<double>> M_GS(std::vector<std::vector<double>> U);\n  \n  // Compute the solution vector of the equation of X_k[i] and PAP*d_i=PA*X_k[i];\n  std::vector<double>CG(std::vector<double> X_ki);\n  // get the p smallest eigenvalues of A correponding with M;\n  std::vector<double> min_trace(int max_iter, double eps);\n  \n  \n private:\n  SparseMatrix<double> A;\n  SparseMatrix<double> M;\n  int p; // The number of the eigenvalues to be solved;\n};\n\nMinTrace::MinTrace()\n{\n  int p=3;\n  SparsityPattern sparsity_pattern(10,10,{2,3,3,3,3,3,3,3,3,2});\n  SparsityPattern sp2(10,10,1);\n  //sparsity_pattern.add(1,2);\n  sparsity_pattern.add(0,1);\n  sparsity_pattern.add(9,8);\n  for (int i=1;i<9;i++)\n    {\n      sparsity_pattern.add(i,i+1);\n      sparsity_pattern.add(i,i-1);\n    }\n  \n  A.reinit(sparsity_pattern);\n  M.reinit(sp2);\n\n  for (int k=0;k<A.m();k++)\n    {\n      SparseMatrix<double>::iterator i=A.begin(k);\n      i->value()=2;\n      while(i!=A.end(k))\n\t{\n\t  i->value()+=1;\n\t  ++i;\n\t}\n    }\n\n  SparseMatrix<double>::iterator i=M.begin();\n  double num=0;\n  while(i!=M.end())\n    {\n      num=num+1;\n      i->value()=num;\n      ++i;\n    }\n}\n\n// ATTENTION!!! There is a difficulty that SparseMatrix can not be copied directly!\nMinTrace::MinTrace(SparseMatrix<double> A0, SparseMatrix<double> M0, int p0)\n{\n  \n};\n\nstd::vector<std::vector<double>> MinTrace::M_GS(std::vector<std::vector<double>> U)\n{\n  std::vector<std::vector<double>> V;\n  V=transpose(U);\n}\n\nstd::vector<std::vector<double>> MinTrace::rand_V()\n{\n  std::cout<<\"CheckPoint1\\n\";\n  std::vector<double> x(M.n(),0);\n  for (int i=0;i<x.size();i++)\n    {\n      std::cout<<x[i]<<\" \";\n    }\n  std::cout<<\"\\n\";\n  std::cout<<\"CheckPoint666 \\n\";\n  std::vector<std::vector<double>> V(p,x);\n  std::cout<<\"CheckPoint12314113\\n\";\n  \n  V[0][0]=1;\n  V[1][1]=sqrt(2.0)/2;\n  V[2][2]=sqrt(3.0)/3;\n  std::cout<<\"231wqrdasd24121321321321adsadq2q1312321sada\\n\";\n  return V;\n}\n\nstd::vector<double> MinTrace::min_trace(int max_iter=10, double eps=1e-03)\n{\n  std::cout<<M.n()<<\"   it is a test!\\n\";\n  \n  std::vector<double> x(p); // define the eigenvector;\n  std::vector<std::vector<double>> V; // V is an n x p matrix and stored as V[p][n];\n\n  V=rand_V();\n  std::cout<<\"wewqewqewqewqeqw\\n\";\n  //  for(int k=0;k<max_iter;k++)\n    for(int k=0;k<1;k++)\n    {\n      std::cout<<\"CheckPoint222\\n\";\n      std::vector<std::vector<double>> VMV(p,x),tmpVMV(p); // VMV is a p x p matrix;\n      std::cout<<\"AAAAAAAAAAAAAAAAAAAAAAAA\\n\";\n      for(int i=0;i<p;i++)\n\t{\n\t  tmpVMV[i]=multiply(M,V[i]);\n\t  std::cout<<\"CheckPoint111111111\\n\";\n\t}\n\n      std::cout<<\"CheckPoint2\\n\";\n      for(int i=0;i<p;i++)\n\t{\n\t  for(int j=0;j<p;j++)\n\t    {\n\t      double tmp=0;\n\t      for(int l=0;l<M.n();l++)\n\t\t{\n\t\t  tmp+=V[i][l]*tmpVMV[j][l];\n\t\t}\n\t      VMV[i][j]=tmp;\n\t    }\n\t}\n\n      for(int i=0;i<p;i++)\n\t{\n\t  for(int j=0;j<p;j++)\n\t    {\n\t      std::cout<<VMV[i][j]<<\" \";\n\t    }\n\t  std::cout<<\"\\n\";\n\t}\n    }\n  \n   return x;\n}\n\nint main()\n{\n  SparseMatrix<double> A, M;\n  // std::ofstream sparsematrix1 (\"original_matrix.1\");\n  //A.print(sparsematrix1);\n  std::vector<unsigned int> row_length(10,10);\n  unsigned int t=3;\n  SparsityPattern sparsity_pattern(10,10,{2,3,3,3,3,3,3,3,3,2});\n  SparsityPattern sp2(10,10,1);\n  //sparsity_pattern.add(1,2);\n  sparsity_pattern.add(0,1);\n  sparsity_pattern.add(9,8);\n  for (int i=1;i<9;i++)\n    {\n      sparsity_pattern.add(i,i+1);\n      sparsity_pattern.add(i,i-1);\n    }\n  \n  A.reinit(sparsity_pattern);\n  M.reinit(sp2);\n\n  // In this way, I can construct a SparseMatrix to be the test data for the algorithm.\n  for (int k=0;k<A.m();k++)\n    {\n      SparseMatrix<double>::iterator i=A.begin(k);\n      i->value()=2;\n      while(i!=A.end(k))\n\t{\n\t  i->value()+=1;\n\t  ++i;\n\t}\n    }\n\n  SparseMatrix<double>::iterator i=M.begin();\n  double num=0;\n  while(i!=M.end())\n    {\n      num=num+1;\n      i->value()=num;\n      ++i;\n    }\n  \n  std::ofstream out (\"sparsity_pattern.1\");\n  sparsity_pattern.print_gnuplot(out);\n\n  std::ofstream sparsematrix (\"sparse_matrix.1\");\n  A.print(sparsematrix);\n\n  std::ofstream sparsematrix2 (\"sparse_matrix.2\");\n  M.print(sparsematrix2); \n\n  std::vector<double> x(10,1);\n  x=multiply(M,x);\n  for(int i=0;i<x.size();i++)\n    {\n      std::cout<<x[i]<<\" \";\n    }\n // std::cout<<\"\\n\"<<1e-03<<\"\\n\";\n\n  MinTrace solve;\n  \n//  solve.min_trace();\n  //sparsity_pattern.print();\n  return 0;\n}\n", "meta": {"hexsha": "a45aeafa473070a75b3e33ff705617000d902025", "size": 15113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mintrace/c_min_trace/example2/test.cpp", "max_stars_repo_name": "CauchYLIU3551/EigenSolver", "max_stars_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mintrace/c_min_trace/example2/test.cpp", "max_issues_repo_name": "CauchYLIU3551/EigenSolver", "max_issues_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mintrace/c_min_trace/example2/test.cpp", "max_forks_repo_name": "CauchYLIU3551/EigenSolver", "max_forks_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_forks_repo_licenses": ["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.4228486647, "max_line_length": 110, "alphanum_fraction": 0.5236551313, "num_tokens": 5001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6645171266659218}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrixXd A = MatrixXd::Random(3,3);\nMatrixXd B = MatrixXd::Random(3,2);\ncout << \"Here is the invertible matrix A:\" << endl << A << endl;\ncout << \"Here is the matrix B:\" << endl << B << endl;\nMatrixXd X = A.lu().solve(B);\ncout << \"Here is the (unique) solution X to the equation AX=B:\" << endl << X << endl;\ncout << \"Relative error: \" << (A*X-B).norm() / B.norm() << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "432295eb8707f2be8d40ecbaa7489f1c5fa99a3f", "size": 905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_PartialPivLU_solve.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_PartialPivLU_solve.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_PartialPivLU_solve.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.1935483871, "max_line_length": 224, "alphanum_fraction": 0.6563535912, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.8104789132480439, "lm_q1q2_score": 0.6645062527369126}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include<opencv2/core/eigen.hpp>\n#include <chrono>\n#include <sophus/se3.hpp>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n// \u76f8\u673a\u5185\u53c2\nMat K = (Mat_<double>(3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches);\n\nvoid bundleAdjustmentGaussNewton(const VecVector3d &points_3d, const VecVector2d &points_2d,\n                                 const Mat &K, Sophus::SE3d &pose);\nvoid bundleAdjustmentG2O(const VecVector3d &points_3d, const VecVector2d &points_2d,\n                         const Mat &K, Sophus::SE3d &pose);\n\n\n// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\nPoint2d pixel2cam(const Point2d &p);\n\n\n\n\nint main(int argc, char **argv){\n\n  // \u8bfb\u53d6\u56fe\u50cf\n  Mat img_1 = imread(\"../1.png\", CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(\"../2.png\", CV_LOAD_IMAGE_COLOR);\n  assert(img_1.data && img_2.data);\n  cout << \"\u8bfb\u53d6\u56fe\u50cf \u5b8c\u6210\uff01\" << endl;\n\n\n  // \u7279\u5f81\u70b9\u5339\u914d\n  cout << \"\u5f00\u59cb\u7279\u5f81\u70b9\u5339\u914d ......\" << endl;\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n  cout << \"\u7279\u5f81\u70b9\u5339\u914d \u5b8c\u6210\uff01 \u4e00\u5171\u627e\u5230\u4e86\" << matches.size() << \"\u7ec4\u5339\u914d\u70b9\" << endl << endl;\n  // for (DMatch m:matches) {\n  //   cout << keypoints_1[m.queryIdx].pt.x << \" \" << keypoints_1[m.queryIdx].pt.y << endl;\n  // }\n\n\n\n  // \u8bfb\u53d6\u6df1\u5ea6\u56fe\uff0c\u5efa\u7acb3D\u70b9\n  Mat img_depth_1 = imread(\"../1_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n  Mat img_depth_2 = imread(\"../2_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n\n  vector<Point3d> points_3d;\n  vector<Point2d> points_2d;\n\n  for (DMatch m:matches){\n    // ushort d = img_depth_1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    ushort d = img_depth_1.at<unsigned short>((int)keypoints_1[m.queryIdx].pt.y, (int)keypoints_1[m.queryIdx].pt.x);\n    if (d==0) continue;\n    float dd = d / 5000.0;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt);\n    points_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n    points_2d.push_back(keypoints_2[m.trainIdx].pt);\n  }\n  cout << \"Total number of valid 3d-2d pairs: \" << points_3d.size() << endl;\n\n\n  cout << \"\u5f00\u59cbPnP\u6c42\u89e3 ......\" << endl;\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  Mat R, r, t;\n  solvePnP(points_3d, points_2d, K, Mat(), r, t, false);\n  cv::Rodrigues(r, R);\n  cout << \"R = \" << endl << R << endl;\n  cout << \"t = \" << t.t() << endl;\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n  cout << endl;\n\n\n  cout << \"\u5f00\u59cb\u624b\u5199G-N\u4f18\u5316 ......\" << endl;\n  VecVector3d points_3d_eig;\n  VecVector2d points_2d_eig;\n  for(size_t i=0; i<points_3d.size(); i++){\n    Point3d p_3d = points_3d[i];\n    Point2d p_2d = points_2d[i];\n    points_3d_eig.push_back(Vector3d(p_3d.x, p_3d.y, p_3d.z));\n    points_2d_eig.push_back(Vector2d(p_2d.x, p_2d.y));\n  }\n\n  Matrix3d R_eig;\n  Vector3d t_eig;\n  cv2eigen(R, R_eig);\n  cv2eigen(t, t_eig);\n  Sophus::SE3d pose_gn(R_eig, t_eig);\n  t1 = chrono::steady_clock::now();\n  bundleAdjustmentGaussNewton(points_3d_eig, points_2d_eig, K, pose_gn);\n  t2 = chrono::steady_clock::now();\n  time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"pose by g-n: \" << endl << pose_gn.matrix() << endl;\n  cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << endl << endl;\n\n\n  cout << \"\u5f00\u59cbG2O\u4f18\u5316 ......\" << endl;\n  Sophus::SE3d pose_g2o(R_eig, t_eig);\n  bundleAdjustmentG2O(points_3d_eig, points_2d_eig, K, pose_g2o);\n  cout << \"pose by g2o: \" << endl << pose_gn.matrix() << endl;\n\n\n  return 0;\n} \n\n\n\n\nvoid bundleAdjustmentGaussNewton(const VecVector3d &points_3d, const VecVector2d &points_2d,\n                                 const Mat &K, Sophus::SE3d &pose){\n\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  const int iterations = 10;\n  double cost = 0, lastCost = 0;\n  double fx = K.at<double>(0, 0);\n  double fy = K.at<double>(1, 1);\n  double cx = K.at<double>(0, 2);\n  double cy = K.at<double>(1, 2);\n\n  for (int iter=0; iter<iterations; iter++){\n    Matrix<double, 6, 6> H = Matrix<double, 6, 6>::Zero();\n    Vector6d b = Vector6d::Zero();\n    cost = 0;\n\n    for (int i=0; i<points_3d.size(); i++){\n      Vector3d pc = pose * points_3d[i];\n      double inv_z = 1.0 / pc[2];\n      double inv_z2 = inv_z * inv_z;\n      Vector2d proj (fx*pc[0]*inv_z + cx,\n                     fy*pc[1]*inv_z + cy);\n      Vector2d e = points_2d[i] - proj;\n\n      cost += e.squaredNorm();\n\n      Matrix<double, 2, 6> J;\n      J << -fx * inv_z,\n        0,\n        fx * pc[0] * inv_z2,\n        fx * pc[0] * pc[1] * inv_z2,\n        -fx - fx * pc[0] * pc[0] * inv_z2,\n        fx * pc[1] * inv_z,\n        0,\n        -fy * inv_z,\n        fy * pc[1] * inv_z2,\n        fy + fy * pc[1] * pc[1] * inv_z2,\n        -fy * pc[0] * pc[1] * inv_z2,\n        -fy * pc[0] * inv_z;\n\n      H += J.transpose() * J;\n      b +=  - J.transpose() * e;\n    }\n\n    Vector6d dx;\n    dx = H.ldlt().solve(b);\n\n    if (isnan(dx[0])){\n      cout << \"result is nan!\" << endl;\n    }\n\n    if (iter > 0 && cost > lastCost){\n      cout << \"the cost is larger than last cost!\";\n      break;\n    }\n\n    pose *= Sophus::SE3d::exp(dx);\n    lastCost = cost;\n\n    cout << \"iteration \" << iter << \" cost=\" << cost << endl;\n\n    if (dx.norm() < 1e-6){\n      cout << \"have converge.\" << endl;\n      break;\n    }\n  }\n}\n\n\n\n\n\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches){\n\n    Mat descriptors_1, descriptors_2;\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n\n    // --\u7b2c\u4e00\u6b65\uff1a\u68c0\u6d4bOriented Fast\u89d2\u70b9\u4f4d\u7f6e\n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    cout << \"--\u7b2c\u4e00\u6b65\u5b8c\u6210\uff1a\u68c0\u6d4bOriented Fast\u89d2\u70b9\u4f4d\u7f6e\" << endl;\n\n    // --\u7b2c\u4e8c\u6b65\uff1a\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97BRIEF\u63cf\u8ff0\u5b50\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    cout << \"--\u7b2c\u4e8c\u6b65\u5b8c\u6210\uff1a\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97BRIEF\u63cf\u8ff0\u5b50\" << endl;\n\n    // -- \u7b2c\u4e09\u6b65\uff1a\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528Hamming\u8ddd\u79bb\n    vector<DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    cout << \"--\u7b2c\u4e09\u6b65\u5b8c\u6210\uff1a\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528Hamming\u8ddd\u79bb\" << endl;\n\n    // --\u7b2c\u56db\u6b65\uff1a\u5339\u914d\u70b9\u5bf9 \u7b5b\u9009\n    auto min_max = minmax_element(match.begin(), match.end(),\n                [] (const DMatch &m1, const DMatch &m2) {return m1.distance < m2.distance;});\n    double min_dist = min_max.first->distance;\n    double max_dist = min_max.second->distance;\n\n    for (int i=0; i<descriptors_1.rows; i++){\n        if(match[i].distance <= max(2*min_dist, 30.0)){\n            matches.push_back(match[i]);\n        }\n    }\n    cout << \"--\u7b2c\u56db\u6b65\u5b8c\u6210\uff1a\u5339\u914d\u70b9\u5bf9 \u7b5b\u9009\" << endl;\n}\n\n\n\n\n\n\nPoint2d pixel2cam(const Point2d &p) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\n\n\n\n\n\n\n\n\n\n\n\nclass VertexPose: public g2o::BaseVertex<6, Sophus::SE3d>{\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::Matrix<double, 6, 1> update_eigen;\n    update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n    _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n};\n\n\nclass EdgeProjection: public g2o::BaseUnaryEdge<2, Vector2d, VertexPose>{\n  public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  EdgeProjection(const Vector3d &pos, const Matrix3d &K): _pos3d(pos), _K(K){}\n\n  virtual void computeError() override{\n    const VertexPose *v = static_cast<VertexPose *>(_vertices[0]);\n    Sophus::SE3d T = v->estimate();\n    Vector3d pos_pixel = _K * (T * _pos3d);\n    pos_pixel = pos_pixel / pos_pixel[2];\n    _error = _measurement - pos_pixel.head<2>();\n  }\n\n  virtual void linearizeOplus() override {\n    const VertexPose *v = static_cast<VertexPose *>(_vertices[0]);\n    Sophus::SE3d T = v->estimate();\n    Vector3d pos_cam = T * _pos3d;\n    double fx = _K(0, 0);\n    double fy = _K(1, 1);\n    double cx = _K(0, 2);\n    double cy = _K(1, 2);\n    double X = pos_cam[0];\n    double Y = pos_cam[1];\n    double Z = pos_cam[2];\n    double Z2 = Z * Z;\n    _jacobianOplusXi\n      << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n      0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n\n  private:\n  Eigen::Vector3d _pos3d;\n  Eigen::Matrix3d _K;\n};\n\n\nvoid bundleAdjustmentG2O(const VecVector3d &points_3d, const VecVector2d &points_2d,\n                         const Mat &K, Sophus::SE3d &pose){\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;\n  optimizer.setAlgorithm(solver);\n  optimizer.setVerbose(true);\n\n  VertexPose *vertex_pose = new VertexPose();\n  vertex_pose->setId(0);\n  vertex_pose->setEstimate(Sophus::SE3d());\n  optimizer.addVertex(vertex_pose);\n\n  Matrix3d K_eigen;\n  cv2eigen(K, K_eigen);\n\n  for(size_t i=0; i < points_3d.size(); i++){\n    auto p2d = points_2d[i];\n    auto p3d = points_3d[i];\n    EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n    edge->setId(i);\n    edge->setVertex(0, vertex_pose);\n    edge->setMeasurement(p2d);\n    edge->setInformation(Matrix2d::Identity());\n    optimizer.addEdge(edge);\n  }\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n  pose = vertex_pose->estimate();\n}", "meta": {"hexsha": "8468cf3b35643303b40a0a0b2682da16aba31628", "size": 11108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch7/pose_estimation_3d2d/pose_estimation_3d2d.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/ch7/pose_estimation_3d2d/pose_estimation_3d2d.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/ch7/pose_estimation_3d2d/pose_estimation_3d2d.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": 30.1029810298, "max_line_length": 120, "alphanum_fraction": 0.6380986676, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6644510443536438}}
{"text": "/*\n    EigenQP: Fast quadradic programming template library based on Eigen.\n \n    From https://github.com/jarredbarber/eigen-QP\n \n    MIT License\n\n    Copyright (c) 2017 Jarred Barber\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 _EIGEN_QP_H_\n#define _EIGEN_QP_H_\n\n#include <Eigen/Dense>\n\n/**\n * Solves quadradic programs with equality constraints\n *  using direct matrix factorization of the KKT system.\n */\n\n\nnamespace EigenQP\n{\n\n// Default tolerance levels specialized on types\ntemplate<typename t> t defTol();\ntemplate<>\n    inline double defTol<double>() { return 1E-9; }\ntemplate<>\n    inline float defTol<float>()   { return 1E-4f; }\n\n/*\n * Solver for equality constrained problems.\n *  The KKT conditions are linear here, so we just\n *  invert with an LDLT decomposition.\n */\ntemplate<typename Scalar, int NVars=-1, int NEq=-1>\nclass QPEqSolver\n{\nprivate:\n    const int n;\n    const int m;\n\n    static constexpr int NWork = \n           ((NVars == -1) || (NEq == -1)) ? -1 : (NVars+NEq);\n    Eigen::Matrix<Scalar,NWork,NWork> Z;\n    Eigen::Matrix<Scalar,NWork,1> C;\n\npublic:\n    QPEqSolver(int n_vars=NVars, int n_const=NEq) : n(n_vars),m(n_const),\n            Z(n+m,n+m), C(n+m,1)\n        {\n            Z.block(n,n,m,m).setZero();\n        }\n    void solve(Eigen::Matrix<Scalar,NVars,NVars> &Q, Eigen::Matrix<Scalar,NVars,1> &c, \n              Eigen::Matrix<Scalar,NEq,NVars> &A, Eigen::Matrix<Scalar,NEq,1> &b,\n              Eigen::Matrix<Scalar,NVars,1> &x)\n    {\n        Z.block(0,0,n,n) = Q;\n        Z.block(0,n,n,m) = A.adjoint();\n        Z.block(n,0,m,n) = A;\n\n        C.head(n) = -c;\n        C.tail(m) = b;\n\n        x = Z.ldlt().solve(C).head(n);\n    }\n};\n\n/*\n * Solver for inequality constrained problems\n *\n * This uses a predictor-corrector interior point method from\n * \"Interior-Point Algorithms for Quadratic Programming\" by Thomas Kruth\n *\n * Some small notation changes from Kruth => this code:\n *\n * G => Q\n * g => c\n * A => A.adjoint() (i.e., the constraint matrix is transposed)\n * lambda => z\n */\ntemplate<typename Scalar, int NVars=-1, int NIneq=-1>\nclass QPIneqSolver\n{\n    typedef Eigen::Matrix<Scalar,NVars,1> PVec;\n    typedef Eigen::Matrix<Scalar,NIneq,1> DVec; // Dual (i.e., Lagrange multiplier) vector\n    typedef Eigen::Matrix<Scalar,NVars,NVars> PMat;\nprivate:\n    // Problem size\n    const int n;\n    const int m;\n    \n    // Work buffers\n    DVec s;\n    DVec z;\n\n    PVec rd;\n    DVec rp;\n    DVec rs;\n\n    PVec dx;\n    DVec ds;\n    DVec dz;\n\n    PVec x;\n    \npublic:\n    // Parameters\n    Scalar tolerance;\n    int    max_iters;\n\n    QPIneqSolver(int n_vars=NVars, int n_const=NIneq) : n(n_vars),m(n_const), s(m), z(m), rd(n), rp(m), rs(m), dx(n), ds(m), dz(m)\n        {\n            tolerance = defTol<Scalar>();\n            max_iters = 250;\n            if (NVars == -1) {\n                x.resize(n_vars);\n            }\n            if (NIneq == -1) {\n                s.resize(n_const);\n                z.resize(n_const);\n            }\n        }\n\n    ~QPIneqSolver() {}\n\n    void solve(Eigen::Matrix<Scalar,NVars,NVars> &Q, Eigen::Matrix<Scalar,NVars,1> &c, \n              Eigen::Matrix<Scalar,NIneq,NVars> &A, Eigen::Matrix<Scalar,NIneq,1> &b,\n              Eigen::Matrix<Scalar,NVars,1> &x_out)\n    {\n        const Scalar eta(0.95);\n        const Scalar eps = tolerance;\n\n        // Initialization\n        s.setOnes();\n        z.setOnes();\n        x.setZero();\n\n        // Initial residuals. Uses fact that x=0 here.\n        rd = c - A.adjoint()*z;\n        rp = s + b;\n        rs = (s.array()*z.array());\n\n        const Scalar ms = Scalar(1.0)/(Scalar)m;\n        Scalar mu = (Scalar)n/((Scalar)m); // Initial mu based on knowing that s,z are ones.\n        Scalar alpha;\n\n        for (int iter=0; iter < max_iters; iter++)\n        {\n            // Precompute decompositions for this iteration\n            Eigen::LLT<PMat> Gbar = (Q + A.adjoint()*((z.array()/s.array()).matrix().asDiagonal())*A).llt();\n\n            for (int ii=0; ii < 2; ii++)\n            {   \n                // Prediction/correction step\n                {\n                    auto tmp = (rs.array() - z.array()*rp.array())/s.array();\n                    dx = -Gbar.solve(rd + A.adjoint()*tmp.matrix());\n                    ds = A*dx - rp;\n                    dz.array() = -(rs.array() + z.array()*ds.array())/s.array();\n                }\n\n                // Compute alph,mu \n                alpha = Scalar(1.0);\n                for (int jj=0; jj < m; jj++)\n                {\n                    Scalar a = -z(jj)/dz(jj);\n                    alpha    = (a < alpha) && (a > 0) ? a : alpha;\n                    a        = -s(jj)/ds(jj);\n                    alpha    = (a < alpha) && (a > 0) ? a : alpha;\n                }\n\n\n                if (ii)\n                    break; // Don't need to compute any more\n\n                // Centering    \n                Scalar mu_aff = (s + alpha*ds).dot(z + alpha*dz)*ms;\n                Scalar sigma = mu_aff / mu;\n                sigma *= sigma*sigma;\n\n                // Corrector residual\n                rs.array() += ds.array()*dz.array() - sigma*mu;\n            }\n\n            // Step\n            alpha *= eta; // rescale step size\n            x += alpha*dx;\n            s += alpha*ds;\n            z += alpha*dz;\n\n            // Update residuals\n            rd = Q*x + c - A*z;\n            rp = s + A.adjoint()*x - b;\n            rs = (s.array()*z.array());\n\n            mu = s.dot(z)*ms;\n\n            // Convergence test\n            if ( (mu < eps) && \n                 (rd.norm() < eps) && \n                 (rs.norm() < eps) )\n            {\n                break;\n            }\n        }\n        x_out = x;\n    }\n    public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n#if 0\n/**\n * General QPs with both equality and inequality constraints.\n *  This doesn't currently work.\n */\ntemplate<typename Scalar, int NVars=-1, int NEq=-1, int NIneq=-1>\nclass QPGenSolver\n{\n    // Static size for work matrix.\n    static constexpr int NWork = \n        ((NVars == -1) || (NEq == -1) || (NIneq==-1)) ? -1 : (NVars+NEq+2*NIneq);\n    typedef Eigen::Matrix<Scalar,NVars,1> PVec;\n    typedef Eigen::Matrix<Scalar,NIneq,1> DVec; // Dual (i.e., Lagrange multiplier) vector\n    typedef Eigen::Matrix<Scalar,NEq,1> EVec;   // Dual (i.e., Lagrange multiplier) vector for equality\n\n    typedef Eigen::Matrix<Scalar,NWork,NWork> WorkBuf;\nprivate:\n\n    // Problem size\n    const int n;\n    const int mi;\n    const int me;\n\n    // Work buffers\n    DVec s;\n    DVec z;\n    EVec y; \n\n    PVec rd;\n    DVec rp;\n    DVec rs;\n    EVec ry;\n\n    PVec dx;\n    DVec ds;\n    DVec dz;\n    EVec dy;\n\n    WorkBuf augSystem;\npublic:\n    QPGenSolver(int n_vars=NVars, int n_const_eq=NEq, int n_const_ineq=NIneq) \n        : n(n_vars),mi(n_const_ineq),me(n_const_eq), \n          s(mi), z(mi), y(me), rd(n), rp(mi), rs(mi), \n          ry(me), dx(n), ds(mi), dz(mi), dy(me),\n          augSystem(2*mi+me+n,2*mi+me+n)\n        {\n        }\n\n    ~QPGenSolver() {}\n\n    void solve(Eigen::Matrix<Scalar,NVars,NVars> &Q, Eigen::Matrix<Scalar,NVars,1> &c, \n              Eigen::Matrix<Scalar,NIneq,NVars> &A, Eigen::Matrix<Scalar,NIneq,1> &b,\n              Eigen::Matrix<Scalar,NEq,NVars> &E, Eigen::Matrix<Scalar,NEq,1> &f,\n              Eigen::Matrix<Scalar,NVars,1> &x)\n    {\n       \n    }\n};\n#endif\n\ntemplate<typename Scalar, int NVars, int NIneq>\nvoid quadprog(Eigen::Matrix<Scalar,NVars,NVars> &Q, Eigen::Matrix<Scalar,NVars,1> &c, \n              Eigen::Matrix<Scalar,NIneq,NVars> &A, Eigen::Matrix<Scalar,NIneq,1> &b,\n              Eigen::Matrix<Scalar,NVars,1> &x)\n{\n    QPIneqSolver<Scalar,NVars,NIneq> qp(c.size(),b.size());\n    qp.solve(Q,c,A,b,x);\n}\n\n} // End namespace\n#endif\n", "meta": {"hexsha": "2356f3749e8c48fadc0cd3b37945c542b4288a51", "size": 8736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen-qp.hpp", "max_stars_repo_name": "jarredbarber/eigen-QP", "max_stars_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T20:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:40:24.000Z", "max_issues_repo_path": "eigen-qp.hpp", "max_issues_repo_name": "jarredbarber/eigen-QP", "max_issues_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T05:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-13T01:47:12.000Z", "max_forks_repo_path": "eigen-qp.hpp", "max_forks_repo_name": "jarredbarber/eigen-QP", "max_forks_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T15:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T06:43:00.000Z", "avg_line_length": 28.9271523179, "max_line_length": 130, "alphanum_fraction": 0.5549450549, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6644510370217255}}
{"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):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n// workaround for the annoying boost message in boost 1.69\n#define BOOST_PENDING_INTEGER_LOG2_HPP\n#include <boost/integer/integer_log2.hpp>\n// end workaround\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"function\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <gudhi/Functions/Function_Sm_in_Rd.h>\n#include <gudhi/Functions/Function_affine_plane_in_Rd.h>\n#include <gudhi/Functions/Constant_function.h>\n#include <gudhi/Functions/Function_chair_in_R3.h>\n#include <gudhi/Functions/Function_torus_in_R3.h>\n#include <gudhi/Functions/Function_whitney_umbrella_in_R3.h>\n#include <gudhi/Functions/Function_lemniscate_revolution_in_R3.h>\n#include <gudhi/Functions/Function_iron_in_R3.h>\n#include <gudhi/Functions/Function_moment_curve_in_Rd.h>\n#include <gudhi/Functions/Embed_in_Rd.h>\n#include <gudhi/Functions/Translate.h>\n#include <gudhi/Functions/Linear_transformation.h>\n#include <gudhi/Functions/Negation.h>\n#include <gudhi/Functions/Cartesian_product.h>\n#include <gudhi/Functions/PL_approximation.h>\n\n#include <gudhi/Coxeter_triangulation.h>\n\n#include <string>\n\n#include <random>\n#include <cstdlib>\n\nusing namespace Gudhi::coxeter_triangulation;\n\ntemplate <class Function>\nvoid test_function(const Function& fun) {\n  Eigen::VectorXd seed = fun.seed();\n  Eigen::VectorXd res_seed = fun(fun.seed());\n  BOOST_CHECK(seed.size() == (long int)fun.amb_d());\n  BOOST_CHECK(res_seed.size() == (long int)fun.cod_d());\n  for (std::size_t i = 0; i < fun.cod_d(); i++) GUDHI_TEST_FLOAT_EQUALITY_CHECK(res_seed(i), 0., 1e-10);\n}\n\nBOOST_AUTO_TEST_CASE(function) {\n  {\n    // the sphere testing part\n    std::size_t m = 3, d = 5;\n    Eigen::VectorXd center(d);\n    center << 2, 1.5, -0.5, 4.5, -1;\n    double radius = 5;\n    typedef Function_Sm_in_Rd Function_sphere;\n    Function_sphere fun_sphere(radius, m, d, center);\n    test_function(fun_sphere);\n  }\n  {\n    // the affine plane testing part\n    std::size_t m = 0, d = 5;\n    Eigen::MatrixXd normal_matrix = Eigen::MatrixXd::Zero(d, d - m);\n    for (std::size_t i = 0; i < d - m; ++i) normal_matrix(i, i) = 1;\n    typedef Function_affine_plane_in_Rd Function_plane;\n    Function_plane fun_plane(normal_matrix);\n    test_function(fun_plane);\n  }\n  {\n    // the constant function testing part\n    std::size_t k = 2, d = 5;\n    auto x = Eigen::VectorXd::Constant(k, 1);\n    Constant_function fun_const(d, k, x);\n    Eigen::VectorXd res_zero = fun_const(Eigen::VectorXd::Zero(d));\n    for (std::size_t i = 0; i < k; ++i) GUDHI_TEST_FLOAT_EQUALITY_CHECK(res_zero(i), x(i), 1e-10);\n  }\n  {\n    // the chair function\n    Function_chair_in_R3 fun_chair;\n    test_function(fun_chair);\n  }\n  {\n    // the torus function\n    Function_torus_in_R3 fun_torus;\n    test_function(fun_torus);\n  }\n  {\n    // the whitney umbrella function\n    Function_whitney_umbrella_in_R3 fun_umbrella;\n    test_function(fun_umbrella);\n  }\n  {\n    // the lemniscate revolution function\n    Function_lemniscate_revolution_in_R3 fun_lemniscate;\n    test_function(fun_lemniscate);\n  }\n  {\n    // the iron function\n    Function_iron_in_R3 fun_iron;\n    test_function(fun_iron);\n  }\n  {\n    Function_moment_curve_in_Rd fun_moment_curve(3, 5);\n    test_function(fun_moment_curve);\n  }\n  {\n    // function embedding\n    Function_iron_in_R3 fun_iron;\n    auto fun_embed = make_embedding(fun_iron, 5);\n    test_function(fun_iron);\n\n    // function translation\n    Eigen::VectorXd off = Eigen::VectorXd::Random(5);\n    auto fun_trans = translate(fun_embed, off);\n    test_function(fun_trans);\n\n    // function linear transformation\n    Eigen::MatrixXd matrix = Eigen::MatrixXd::Random(5, 5);\n    BOOST_CHECK(matrix.determinant() != 0.);\n    auto fun_lin = make_linear_transformation(fun_trans, matrix);\n    test_function(fun_lin);\n\n    // function negative\n    auto fun_neg = negation(fun_lin);\n    test_function(fun_neg);\n\n    // function product\n    typedef Function_Sm_in_Rd Function_sphere;\n    Function_sphere fun_sphere(1, 1);\n    auto fun_prod = make_product_function(fun_sphere, fun_sphere, fun_sphere);\n    test_function(fun_prod);\n\n    // function PL approximation\n    Coxeter_triangulation<> cox_tr(6);\n    typedef Coxeter_triangulation<>::Vertex_handle Vertex_handle;\n    auto fun_pl = make_pl_approximation(fun_prod, cox_tr);\n    Vertex_handle v0 = Vertex_handle(cox_tr.dimension(), 0);\n    Eigen::VectorXd x0 = cox_tr.cartesian_coordinates(v0);\n    Eigen::VectorXd value0 = fun_prod(x0);\n    Eigen::VectorXd pl_value0 = fun_pl(x0);\n    for (std::size_t i = 0; i < fun_pl.cod_d(); i++) GUDHI_TEST_FLOAT_EQUALITY_CHECK(value0(i), pl_value0(i), 1e-10);\n    Vertex_handle v1 = v0;\n    v1[0] += 1;\n    Eigen::VectorXd x1 = cox_tr.cartesian_coordinates(v1);\n    Eigen::VectorXd value1 = fun_prod(x1);\n    Eigen::VectorXd pl_value1 = fun_pl(x1);\n    for (std::size_t i = 0; i < fun_pl.cod_d(); i++) GUDHI_TEST_FLOAT_EQUALITY_CHECK(value1(i), pl_value1(i), 1e-10);\n    Eigen::VectorXd pl_value_mid = fun_pl(0.5 * x0 + 0.5 * x1);\n    for (std::size_t i = 0; i < fun_pl.cod_d(); i++)\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(0.5 * value0(i) + 0.5 * value1(i), pl_value_mid(i), 1e-10);\n  }\n}\n", "meta": {"hexsha": "43dbcb75d9a8baf0ddf700e5839cd0af9edbb951", "size": 5496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/function_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/function_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "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/Coxeter_triangulation/test/function_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["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.5660377358, "max_line_length": 117, "alphanum_fraction": 0.71069869, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6644129288717936}}
{"text": "/* A namespace that extends Eigen to contain other necessary functions \n *\n * Author        : Jonathan EDEN\n * Created       : 2016\n * Description   : A namepsace that extends the Eigen library\n*/\n\n#pragma once\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\nusing namespace Eigen;\n// This is a namespace to add some necessary functions into.\nnamespace EigenExtension{\n  /**\n   * Skew symmetric matrix for cross product computation\n   * @param v 3d Vector\n   * @return skew symmetric matrix\n   */\n  Matrix3f SkewSymmetric(Vector3f v);\n  /**\n   * Skew symmetric matrix for cross product computation\n   * @param v 3d Vector\n   * @return skew symmetric matrix\n   */\n  Matrix3d SkewSymmetric2(Vector3d v);\n  // Get the spline coefficients.\n  Matrix<float,2,1> GetLinearSplineCoefficients(float q_r_i, float q_r_ip1, double t);\n  Matrix<float,4,1> GetCubicSplineCoefficients(float q_r_i, float q_d_r_i,\n                                          float q_r_ip1, float q_d_r_ip1, double t);\n  Matrix<float,6,1> GetQuinticSplineCoefficients(float q_r_i, float q_d_r_i, float q_dd_r_i,\n                                          float q_r_ip1, float q_d_r_ip1, float q_dd_r_ip1, double t);\n  // Interpolate the spline\n  void LinearSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix<float,2,1> a, double t);\n  void CubicSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix<float,4,1> a, double t);                                        \n  void QuinticSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix<float,6,1> a, double t);\n  // Compute the rotation matrix\n  Matrix3f ComputeRotationMatrix(AngleAxisf a);\n  // Compute the derivative of a rotation matrix\n  Matrix3f ComputeRotationMatrixDeriv(AngleAxisf a, AngleAxisf a_d);\n  // Compute the double derivative of a rotation matrix\n  Matrix3f ComputeRotationMatrixDoubleDeriv(AngleAxisf a, AngleAxisf a_d, AngleAxisf a_dd);\n  /**\n   *  Pseudo inverse matrix\n   * @param A\n   * @return Pseudo inverse matrix\n   */\n  MatrixXf Pinv(MatrixXf A);\n  /**\n   *  Pseudo inverse matrix\n   * @param A\n   * @return Pseudo inverse matrix\n   */\n  MatrixXd Pinv(MatrixXd A);\n\n  //MatrixXf LeftPseudoInverse(MatrixXf A);\n  //MatrixXf RightMatrixPseudoInverse(MatrixXf A);\n}", "meta": {"hexsha": "509191db6b39d389d4a1367098efe0019f06713b", "size": 2282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_stars_repo_name": "NexusReflex/VRpuppet", "max_stars_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T09:58:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-31T02:52:54.000Z", "max_issues_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_issues_repo_name": "NexusReflex/VRpuppet", "max_issues_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-12-02T14:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T12:10:06.000Z", "max_forks_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_forks_repo_name": "NexusReflex/VRpuppet", "max_forks_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-02T09:55:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T11:54:30.000Z", "avg_line_length": 38.0333333333, "max_line_length": 142, "alphanum_fraction": 0.6958808063, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6644129255775039}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <cmath>\n#include <Eigen/Dense>\n\nnamespace orient::detail {\n\ntemplate<typename Scalar>\nstd::pair<Scalar, Scalar> asinWD(Scalar x)\n{\n  return std::make_pair(std::asin(x), 1.0 / std::sqrt(1.0 - x*x));\n}\n\ntemplate<typename Scalar>\nstd::pair<Scalar, Scalar> acosWD(Scalar x)\n{\n  return std::make_pair(std::acos(x), -1.0 / std::sqrt(1.0 - x*x));\n}\n\n\ntemplate<typename Scalar>\nstd::tuple<Scalar, Scalar, Scalar> atan2WD(Scalar y, Scalar x)\n{\n  const auto norm = x*x + y*y;\n  const auto Jy = x / norm;\n  const auto Jx = - y / norm;\n  return std::make_tuple(std::atan2(y, x), Jy, Jx);\n}\n\ntemplate<typename Derived, typename Scalar=typename Eigen::DenseBase<Derived>::Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar, 9, 9>> transposeWD(Eigen::MatrixBase<Derived> const& M)\n{\n  Eigen::Matrix<Scalar, 9,9> J = Eigen::Matrix<Scalar, 9,9>::Identity();\n  J.col(1).swap(J.col(3));\n  J.col(2).swap(J.col(6));\n  J.col(5).swap(J.col(7));\n  return std::make_pair(M.transpose(), J);\n}\n\ntemplate<typename Derived, typename Scalar=typename Eigen::DenseBase<Derived>::Scalar>\nstd::pair<Scalar, Eigen::Matrix<Scalar, 1, 9>> traceWD(Eigen::MatrixBase<Derived> const& M)\n{\n  Eigen::Matrix<Scalar, 1, 9> J;\n  J << 1,0,0,0,1,0,0,0,1;\n  return std::make_pair(M.trace(), J);\n}\n\n}\n", "meta": {"hexsha": "7d5242578c7eacb272a76ad3eb5c20751a70d7de", "size": 1509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/detail/derivative_helpers.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/detail/derivative_helpers.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/detail/derivative_helpers.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": 27.9444444444, "max_line_length": 114, "alphanum_fraction": 0.6706428098, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6644129070323158}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file NaiveSO3Tests.cpp\n/// \\brief Unit tests for the naive implementation of the SO3 Lie Group math.\n/// \\details Unit tests for the various Lie Group functions will test both special cases,\n///          and randomly generated cases.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <iostream>\n#include <iomanip>\n#include <ios>\n\n#include <Eigen/Dense>\n#include <lgmath/CommonMath.hpp>\n#include <lgmath/so3/Operations.hpp>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// UNIT TESTS OF SO(3) MATH\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of SO(3) hat function\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, test3x3HatFunction) {\n\n  // Init\n  std::vector<Eigen::Matrix<double,3,1> > trueVecs;\n  std::vector<Eigen::Matrix<double,3,3> > trueMats;\n\n  // Add vectors to be tested - we choose a few\n  trueVecs.push_back(Eigen::Matrix<double,3,1>( 0.0,  0.0,  0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>( 1.0,  2.0,  3.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(-1.0, -2.0, -3.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>::Random());\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Setup truth matrices\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> mat;\n    mat <<               0.0,  -trueVecs.at(i)[2],   trueVecs.at(i)[1],\n           trueVecs.at(i)[2],                 0.0,  -trueVecs.at(i)[0],\n          -trueVecs.at(i)[1],   trueVecs.at(i)[0],                 0.0;\n    trueMats.push_back(mat);\n  }\n\n  // Test the function\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> testMat = lgmath::so3::hat(trueVecs.at(i));\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n\n  // Test identity,  hat(v)^T = -hat(v)\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> testMat = lgmath::so3::hat(trueVecs.at(i));\n    EXPECT_TRUE(lgmath::common::nearEqual(testMat.transpose(), -testMat, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test special cases of exponential functions: vec2rot and rot2vec\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, testVec2RotSpecialCase) {\n\n  // Init\n  std::vector<Eigen::Matrix<double,3,1> > trueVecs;\n  std::vector<Eigen::Matrix<double,3,3> > trueMats;\n  Eigen::Matrix<double,3,3> temp;\n\n  // Identity\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.0));\n  trueMats.push_back(Eigen::Matrix<double,3,3>::Identity());\n\n  // x-rot by PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(lgmath::constants::PI, 0.0, 0.0));\n  temp <<  1.0,  0.0,  0.0,\n           0.0, -1.0,  0.0,\n           0.0,  0.0, -1.0;\n  trueMats.push_back(temp);\n\n  // y-rot by PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, lgmath::constants::PI, 0.0));\n  temp << -1.0,  0.0,  0.0,\n           0.0,  1.0,  0.0,\n           0.0,  0.0, -1.0;\n  trueMats.push_back(temp);\n\n  // z-rot by PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, lgmath::constants::PI));\n  temp << -1.0,  0.0,  0.0,\n           0.0, -1.0,  0.0,\n           0.0,  0.0,  1.0;\n  trueMats.push_back(temp);\n\n  // x-rot by -PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(-lgmath::constants::PI, 0.0, 0.0));\n  temp <<  1.0,  0.0,  0.0,\n           0.0, -1.0,  0.0,\n           0.0,  0.0, -1.0;\n  trueMats.push_back(temp);\n\n  // y-rot by -PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, -lgmath::constants::PI, 0.0));\n  temp << -1.0,  0.0,  0.0,\n           0.0,  1.0,  0.0,\n           0.0,  0.0, -1.0;\n  trueMats.push_back(temp);\n\n  // z-rot by -PI\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, -lgmath::constants::PI));\n  temp << -1.0,  0.0,  0.0,\n           0.0, -1.0,  0.0,\n           0.0,  0.0,  1.0;\n  trueMats.push_back(temp);\n\n  // x-rot by PI/2\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.5*lgmath::constants::PI, 0.0, 0.0));\n  temp <<  1.0,  0.0,  0.0,\n           0.0,  0.0, -1.0,\n           0.0,  1.0,  0.0;\n  trueMats.push_back(temp);\n\n  // y-rot by PI/2\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.5*lgmath::constants::PI, 0.0));\n  temp <<  0.0,  0.0,  1.0,\n           0.0,  1.0,  0.0,\n          -1.0,  0.0,  0.0;\n  trueMats.push_back(temp);\n\n  // z-rot by PI/2\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.5*lgmath::constants::PI));\n  temp <<  0.0, -1.0,  0.0,\n           1.0,  0.0,  0.0,\n           0.0,  0.0,  1.0;\n  trueMats.push_back(temp);\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Test vec2rot\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> testMat = lgmath::so3::vec2rot(trueVecs.at(i));\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n\n  // Test rot2vec\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,1> testVec = lgmath::so3::rot2vec(trueMats.at(i));\n    std::cout << \"true: \" << trueVecs.at(i) << std::endl;\n    std::cout << \"func: \" << testVec << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqualAxisAngle(trueVecs.at(i), testVec, 1e-6));\n  }\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of exponential functions: vec2rot and rot2vec\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, CompareAnalyticalAndNumericVec2Rot) {\n\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double,3,1> > trueVecs;\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, lgmath::constants::PI));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(-lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, -lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, -lgmath::constants::PI));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.5*lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.5*lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.5*lgmath::constants::PI));\n  const unsigned numRand = 50;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double,3,1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc matrices\n  std::vector<Eigen::Matrix<double,3,3> > analyticRots;\n  for (unsigned i = 0; i < numTests; i++) {\n    analyticRots.push_back(lgmath::so3::vec2rot(trueVecs.at(i)));\n  }\n\n  // Compare analytical and numeric result\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> numericRot = lgmath::so3::vec2rot(trueVecs.at(i), 20);\n    std::cout << \"ana: \" << analyticRots.at(i) << std::endl;\n    std::cout << \"num: \" << numericRot << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(analyticRots.at(i), numericRot, 1e-6));\n  }\n\n  // Test identity, rot^T = rot^-1\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> lhs = analyticRots.at(i).transpose();\n    Eigen::Matrix<double,3,3> rhs = analyticRots.at(i).inverse();\n    std::cout << \"lhs: \" << lhs << std::endl;\n    std::cout << \"rhs: \" << rhs << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(lhs, rhs, 1e-6));\n  }\n\n  // Test rot2vec\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,1> testVec = lgmath::so3::rot2vec(analyticRots.at(i));\n    std::cout << \"true: \" << trueVecs.at(i) << std::endl;\n    std::cout << \"func: \" << testVec << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqualAxisAngle(trueVecs.at(i), testVec, 1e-6));\n  }\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of exponential jacobians: vec2jac and vec2jacinv\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, CompareAnalyticalJacobiansInversesAndNumericCounterparts) {\n\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double,3,1> > trueVecs;\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, lgmath::constants::PI));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(-lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, -lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, -lgmath::constants::PI));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.5*lgmath::constants::PI, 0.0, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.5*lgmath::constants::PI, 0.0));\n  trueVecs.push_back(Eigen::Matrix<double,3,1>(0.0, 0.0, 0.5*lgmath::constants::PI));\n  const unsigned numRand = 50;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double,3,1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc analytical matrices\n  std::vector<Eigen::Matrix<double,3,3> > analyticJacs;\n  std::vector<Eigen::Matrix<double,3,3> > analyticJacInvs;\n  for (unsigned i = 0; i < numTests; i++) {\n    analyticJacs.push_back(lgmath::so3::vec2jac(trueVecs.at(i)));\n    analyticJacInvs.push_back(lgmath::so3::vec2jacinv(trueVecs.at(i)));\n  }\n\n  // Compare inversed analytical and analytical inverse\n  for (unsigned i = 0; i < numTests; i++) {\n    std::cout << \"ana: \" << analyticJacs.at(i) << std::endl;\n    std::cout << \"num: \" << analyticJacInvs.at(i) << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(analyticJacs.at(i).inverse(), analyticJacInvs.at(i), 1e-6));\n  }\n\n  // Compare analytical and 'numerical' jacobian\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> numericJac = lgmath::so3::vec2jac(trueVecs.at(i), 20);\n    std::cout << \"ana: \" << analyticJacs.at(i) << std::endl;\n    std::cout << \"num: \" << numericJac << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(analyticJacs.at(i), numericJac, 1e-6));\n  }\n\n  // Compare analytical and 'numerical' jacobian inverses\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> numericJac = lgmath::so3::vec2jacinv(trueVecs.at(i), 20);\n    std::cout << \"ana: \" << analyticJacInvs.at(i) << std::endl;\n    std::cout << \"num: \" << numericJac << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(analyticJacInvs.at(i), numericJac, 1e-6));\n  }\n\n  // Test identity, rot(v) = eye(3) + hat(v)*jac(v), through the 'alternate' vec2rot method\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double,3,3> lhs = lgmath::so3::vec2rot(trueVecs.at(i));\n    Eigen::Matrix<double,3,3> rhs, jac;\n    // the following vec2rot call uses the identity: rot(v) = eye(3) + hat(v)*jac(v)\n    lgmath::so3::vec2rot(trueVecs.at(i), &rhs, &jac);\n    std::cout << \"lhs: \" << lhs << std::endl;\n    std::cout << \"rhs: \" << rhs << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(lhs, rhs, 1e-6));\n  }\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n", "meta": {"hexsha": "5e77cc503f4cf2b29c04a4744afdd5a22fc646fe", "size": 12076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/SO3Tests.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "tests/SO3Tests.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "tests/SO3Tests.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 40.5234899329, "max_line_length": 102, "alphanum_fraction": 0.562023849, "num_tokens": 4112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.664403990426585}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n#undef VERSION\n#define VERSION 3\n\nusing namespace std;\nusing namespace mtl;\n\ndense_vector<double> inline last_unit_vector(size_t n)\n{\n    dense_vector<double> v(n, 0.0);\n    v[n-1]= 1;\n    return v;\n}\n\ndense_vector<double> inline unit_vector(size_t k, size_t n)\n{\n    dense_vector<double> v(n, 0.0);\n    v[k]= 1;\n    return v;\n}\n\n#if VERSION == 1\n\ndense2D<double> inline inverse_upper(dense2D<double> const& A)\n{\n    const size_t N= num_rows(A);\n    assert(num_cols(A) == N); // Matrix must be square\n\n    dense2D<double> Inv(N, N);\n\n    for (size_t k= 0; k < N; ++k) {\n\tdense_vector<double> e_k(N);\n\tfor (size_t i= 0; i < N; ++i)\n\t    if (i == k) \n\t\te_k[i]= 1.0;\n\t    else\n\t\te_k[i]= 0.0;    \n\n\tdense_vector<double> res_k(N);\n\tres_k= upper_trisolve(A, e_k);\n\n\tfor (size_t i= 0; i < N; ++i)\n\t    Inv[i][k]= res_k[i];\n    }\n    return Inv;\n}\n\n#elif VERSION == 2\n\ndense2D<double> inverse_upper(dense2D<double> const& A)\n{\n    const size_t N= num_rows(A);\n    assert(num_cols(A) == N); // Matrix must be square\n\n    dense2D<double> Inv(N, N);\n\n    for (size_t k= 0; k < N; ++k) {\n\tdense_vector<double> e_k(N);\n\tfor (size_t i= 0; i < N; ++i)\n\t    e_k[i]= i == k ? 1.0 : 0.0;\n\n\tfor (size_t i= 0; i < N; ++i)\n\t    Inv[i][k]= upper_trisolve(A, e_k)[i];\n    }\n    return Inv;\n}\n\n#elif VERSION == 3\n\ndense2D<double> inverse_upper(dense2D<double> const& A)\n{\n    const size_t N= num_rows(A);\n    assert(num_cols(A) == N); // Matrix must be square\n\n    dense2D<double> Inv(N, N);\n    Inv= 0;\n\n    for (size_t k= 0; k < N; ++k) {\n\tirange r(0, k+1);\n\tInv[r][k]= upper_trisolve(A[r][r], unit_vector(k, k+1));\n    }\n    return Inv;\n}\n\n#endif\n\ndense2D<double> inline inverse_lower(dense2D<double> const& A)\n{\n    dense2D<double> T(trans(A));\n    return dense2D<double>(trans(inverse_upper(T)));\n}\n\ndense2D<double> inline inverse(dense2D<double> const& A)\n{\n    assert(num_cols(A) == num_rows(A)); // Matrix must be square\n\n    dense2D<double>          PLU(A);\n    dense_vector<size_t>   Pv(num_rows(A));\n\n    lu(PLU, Pv);\n    dense2D<double>  I(num_rows(A), num_cols(A));\n    I= 1;\n    dense2D<double>  PU(upper(PLU)), \n        PL(strict_lower(PLU) + I);\n\n    return dense2D<double>(inverse_upper(PU) * inverse_lower(PL) * permutation(Pv));\n}\n\n\n\nint main(int, char**)\n{\n    const unsigned size= 3;\n    typedef dense2D<double>      Matrix;\n    Matrix   A(size, size);\n    A=  4, 1, 2, \n\t1, 5, 3,\n\t2, 6, 9; \n\n    cout << \"A is:\\n\" << A;\n\n    Matrix LU(A);\n    mtl::dense_vector<size_t> Pv(size);\n    lu(LU, Pv);\n\n    Matrix P(permutation(Pv));\n    cout << \"Permutation vector is \" << Pv << \"\\nPermutation matrix is\\n\" << P;\n\n    cout << \"Permuted A is \\n\" << Matrix(P * A);\n    Matrix I(size, size); I= 1;\n    //Matrix I(mat::identity(size, size)), L(I + strict_lower(LU)), U(upper(LU));\n    Matrix L(I + strict_lower(LU)), U(upper(LU));\n\n    Matrix UI(inverse_upper(U));\n    cout << \"inverse(U) [permuted] is:\\n\" << UI << \"UI * U is:\\n\" << Matrix(UI * U);\n    assert(one_norm(Matrix(UI * U - I)) < 0.1);\n    \n    Matrix LI(inverse_lower(L));\n    cout << \"inverse(L) [permuted] is:\\n\" << LI << \"LI * L is:\\n\" << Matrix(LI * L);\n    assert(one_norm(Matrix(LI * L - I)) < 0.1);\n\n\n    Matrix AI(UI * LI * P);\n    cout << \"inverse(A) [UI * LI * P] is \\n\" << AI << \"A * AI is\\n\" << Matrix(AI * A);\n    assert(one_norm(Matrix(AI * A - I)) < 0.1);\n   \n    Matrix A_inverse(inverse(A));\n    cout << \"inverse(A) is \\n\" << A_inverse << \"A * AI is\\n\" << Matrix(A_inverse * A);\n    assert(one_norm(Matrix(A_inverse * A - I)) < 0.1);\n\n    Matrix A_e(inv(A));\n    cout << \"inv(A) is \\n\" << A_e << \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "094ad4c9bd7062a2b586c595382a2eb5435c9727", "size": 4095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/inverse_matrix.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/examples/inverse_matrix.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/examples/inverse_matrix.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": 24.0882352941, "max_line_length": 94, "alphanum_fraction": 0.5868131868, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6644039712782871}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char *argv[])\n{\n   // Initialize matrix for initializer list\n   auto A = mat{{1.0,2.0,3.0},{4.0, 5.0,6.0},{7.0, 8.0, 9.0}};\n   cout << A << endl;\n\n   // Zero filled matrix and direct element\n   // initialization \n   auto B = mat(3,3, fill::ones);\n   B(1,1) = 10;\n   cout << B << endl;\n\n   // Elementwise multiplication\n   auto C = A % B;\n\n\n   auto b = vec{6.0, 60.0, 24.0};\n\n   auto x = solve(C,b);\n\n   cout << x << endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "b81e6b217f7d457b377a6fce3edb389caff15c1b", "size": 543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example_01/armasample01.cpp", "max_stars_repo_name": "putanowr/ArmadilloDrill", "max_stars_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_stars_repo_licenses": ["MIT"], "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_01/armasample01.cpp", "max_issues_repo_name": "putanowr/ArmadilloDrill", "max_issues_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_issues_repo_licenses": ["MIT"], "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_01/armasample01.cpp", "max_forks_repo_name": "putanowr/ArmadilloDrill", "max_forks_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_forks_repo_licenses": ["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.5161290323, "max_line_length": 62, "alphanum_fraction": 0.5727440147, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6643213651763135}}
{"text": "#ifndef OCC_RAYCASTING_HPP_7K2XI8HT\n#define OCC_RAYCASTING_HPP_7K2XI8HT\n\n#include <Eigen/Core>\n\n#include <pcl_util/point_types.hpp>\n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/scrollgrid3.hpp\"\n#include \"scrollgrid/dense_array3.hpp\"\n\n#include <math.h> \n\nnamespace ca\n{\n\nstatic const int32_t CA_SG_COMPLETELY_FREE = 0;\nstatic const int32_t CA_SG_COMPLETELY_OCCUPIED = 255;  //250\nstatic const int32_t CA_SG_BELIEF_UPDATE_POS = 20; // when hit\nstatic const int32_t CA_SG_BELIEF_UPDATE_NEG = 10; // when pass-through  2\n\ntemplate<class TraceFunctor>\nvoid occupancy_trace(const Vec3Ix& start_pos,\n                     const Vec3Ix& end_pos,\n                     const TraceFunctor& fun) {\n  // beware: vec3ix are int64_t\n  int x = start_pos[0],\n      y = start_pos[1],\n      z = start_pos[2];\n  int dx = end_pos[0] - start_pos[0],\n      dy = end_pos[1] - start_pos[1],\n      dz = end_pos[2] - start_pos[2];\n  int sx, sy, sz;\n  //X\n  if ( dx>0 ) {\n    sx = 1;\n  } else if ( dx<0 ) {\n    sx = -1;\n    dx = -dx;\n  } else {\n    sx = 0;\n  }\n\n  //Y\n  if ( dy>0 ) {\n    sy = 1;\n  } else if ( dy<0 ) {\n    sy = -1;\n    dy = -dy;\n  } else {\n    sy = 0;\n  }\n\n  //Z\n  if ( dz>0 ) {\n    sz = 1;\n  } else if ( dz<0 ) {\n    sz = -1;\n    dz = -dz;\n  } else {\n    sz = 0;\n  }\n\n  int ax = 2*dx,\n      ay = 2*dy,\n      az = 2*dz;\n\n  if ( ( dy <= dx ) && ( dz <= dx ) ) {\n    for (int decy=ay-dx, decz=az-dx;\n         ;\n         x+=sx, decy+=ay, decz+=az) {\n      //SetP ( grid,x,y,z,end_pos, atMax, count);\n      fun(x,y,z,false);\n      //Bresenham step\n      if ( x==end_pos[0] ) break;\n      if ( decy>=0 ) {\n        decy-=ax;\n        y+=sy;\n      }\n      if ( decz>=0 ) {\n        decz-=ax;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dy,decz=az-dy;\n         ;\n         y+=sy,decx+=ax,decz+=az ) {\n      // SetP ( grid,x,y,z,end_pos, atMax, count);\n      fun(x,y,z,false);\n      //Bresenham step\n      if ( y==end_pos[1] ) break;\n      if ( decx>=0 ) {\n        decx-=ay;\n        x+=sx;\n      }\n      if ( decz>=0 ) {\n        decz-=ay;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dz,decy=ay-dz;\n         ;\n         z+=sz,decx+=ax,decy+=ay ) {\n      //SetP ( grid,x,y,z,end_pos, atMax, count);\n      fun(x,y,z,false);\n      //Bresenham step\n      if ( z==end_pos[2] ) break;\n      if ( decx>=0 ) {\n        decx-=az;\n        x+=sx;\n      } if ( decy>=0 ) {\n        decy-=az;\n        y+=sy;\n      }\n    }\n  }\n  fun(x,y,z,true);\n}\n\ntemplate<class TraceFunctor>\nvoid occupancy_trace_dist(const Vec3Ix& start_pos,\n                     const Vec3Ix& end_pos,\n                     const TraceFunctor& fun,\n\t\t     double distance) {  //TODO add distance\n  // beware: vec3ix are int64_t\n  int x = start_pos[0],\n      y = start_pos[1],\n      z = start_pos[2];\n  int dx = end_pos[0] - start_pos[0],\n      dy = end_pos[1] - start_pos[1],\n      dz = end_pos[2] - start_pos[2];\n  int sx, sy, sz;\n  //X\n  if ( dx>0 ) {\n    sx = 1;\n  } else if ( dx<0 ) {\n    sx = -1;\n    dx = -dx;\n  } else {\n    sx = 0;\n  }\n\n  //Y\n  if ( dy>0 ) {\n    sy = 1;\n  } else if ( dy<0 ) {\n    sy = -1;\n    dy = -dy;\n  } else {\n    sy = 0;\n  }\n\n  //Z\n  if ( dz>0 ) {\n    sz = 1;\n  } else if ( dz<0 ) {\n    sz = -1;\n    dz = -dz;\n  } else {\n    sz = 0;\n  }\n\n  int ax = 2*dx,\n      ay = 2*dy,\n      az = 2*dz;\n\n  if ( ( dy <= dx ) && ( dz <= dx ) ) {\n    for (int decy=ay-dx, decz=az-dx;\n         ;\n         x+=sx, decy+=ay, decz+=az) {\n      //SetP ( grid,x,y,z,end_pos, atMax, count);\n//       fun(x,y,z,false,distance);\n      distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n      fun(x,y,z,false,distance);\n      //Bresenham step\n      if ( x==end_pos[0] ) break;\n      if ( decy>=0 ) {\n        decy-=ax;\n        y+=sy;\n      }\n      if ( decz>=0 ) {\n        decz-=ax;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dy,decz=az-dy;\n         ;\n         y+=sy,decx+=ax,decz+=az ) {\n      // SetP ( grid,x,y,z,end_pos, atMax, count);\n//       fun(x,y,z,false,distance);\n      distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n      fun(x,y,z,false,distance);\n      //Bresenham step\n      if ( y==end_pos[1] ) break;\n      if ( decx>=0 ) {\n        decx-=ay;\n        x+=sx;\n      }\n      if ( decz>=0 ) {\n        decz-=ay;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dz,decy=ay-dz;\n         ;\n         z+=sz,decx+=ax,decy+=ay ) {\n      //SetP ( grid,x,y,z,end_pos, atMax, count);\n//       fun(x,y,z,false,distance);\n      distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n      fun(x,y,z,false,distance);\n      //Bresenham step\n      if ( z==end_pos[2] ) break;\n      if ( decx>=0 ) {\n        decx-=az;\n        x+=sx;\n      } if ( decy>=0 ) {\n        decy-=az;\n        y+=sy;\n      }\n    }\n  }\n//       fun(x,y,z,true,distance);\n      distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n      fun(x,y,z,true,distance);\n}\n/**\n * Update occupancy information along ray.\n */\ntemplate<class GridScalar>\nvoid occupancy_trace_simple(const Vec3Ix& start_pos, // in ijk\n                            const Vec3Ix& end_pos, // in ijk\n                            const ca::ScrollGrid3<GridScalar>& grid3,\n                            ca::DenseArray3<uint8_t>& array3)\n                            {\n  //int ray_ctr = 0;\n  // beware: vec3ix are int64_t\n  int x = start_pos[0],\n      y = start_pos[1],\n      z = start_pos[2];\n  int dx = end_pos[0] - start_pos[0],\n      dy = end_pos[1] - start_pos[1],\n      dz = end_pos[2] - start_pos[2];\n  int sx, sy, sz;\n  //X\n  if ( dx>0 ) {\n    sx = 1;\n  } else if ( dx<0 ) {\n    sx = -1;\n    dx = -dx;\n  } else {\n    sx = 0;\n  }\n\n  //Y\n  if ( dy>0 ) {\n    sy = 1;\n  } else if ( dy<0 ) {\n    sy = -1;\n    dy = -dy;\n  } else {\n    sy = 0;\n  }\n\n  //Z\n  if ( dz>0 ) {\n    sz = 1;\n  } else if ( dz<0 ) {\n    sz = -1;\n    dz = -dz;\n  } else {\n    sz = 0;\n  }\n\n  int ax = 2*dx,\n      ay = 2*dy,\n      az = 2*dz;\n\n  if ( ( dy <= dx ) && ( dz <= dx ) ) {\n    // this is tracing loop. we step through the ray in integer coordinates\n    // until we reach the end\n    for (int decy=ay-dx, decz=az-dx;\n         ;\n         x+=sx, decy+=ay, decz+=az) {\n\n      // here we are in the middle of tracing the\n      // ray. here we are passing through.\n      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n\n      // by definition here we are passing through\n      // TODO correct & efficent boundary check\n      int32_t new_value = static_cast<int32_t>(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n      array3[mem_ix] = static_cast<uint8_t>(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n      //Bresenham step\n      if ( x==end_pos[0] ) break;\n      if ( decy>=0 ) {\n        decy-=ax;\n        y+=sy;\n      }\n      if ( decz>=0 ) {\n        decz-=ax;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dy,decz=az-dy;\n         ;\n         y+=sy,decx+=ax,decz+=az ) {\n\n      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      int32_t new_value = static_cast<int32_t>(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n      array3[mem_ix] = static_cast<uint8_t>(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n      //Bresenham step\n      if ( y==end_pos[1] ) break;\n      if ( decx>=0 ) {\n        decx-=ay;\n        x+=sx;\n      }\n      if ( decz>=0 ) {\n        decz-=ay;\n        z+=sz;\n      }\n    }\n  } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n    //dy>=dx,dy\n    for (int decx=ax-dz,decy=ay-dz;\n         ;\n         z+=sz,decx+=ax,decy+=ay ) {\n\n      mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n      int32_t new_value = static_cast<int32_t>(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n      array3[mem_ix] = static_cast<uint8_t>(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n      //array3[mem_ix] = ray_ctr++;\n      //Bresenham step\n      if ( z==end_pos[2] ) break;\n      if ( decx>=0 ) {\n        decx-=az;\n        x+=sx;\n      } if ( decy>=0 ) {\n        decy-=az;\n        y+=sy;\n      }\n    }\n  }\n\n  // here we are at the end of the ray.\n  // here we update according to xyz\n\n  mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n  int32_t new_value = static_cast<int32_t>(array3[mem_ix])+CA_SG_BELIEF_UPDATE_POS;\n  array3[mem_ix] = static_cast<uint8_t>(std::min(CA_SG_COMPLETELY_OCCUPIED, new_value));\n\n}\n} /* ca\n */\n\n#endif /* end of include guard: OCC_RAYCASTING_HPP_7K2XI8HT */\n\n", "meta": {"hexsha": "a6657900b9fcfca175dca992d9eef3b2e30b47f7", "size": 8722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_stars_repo_name": "ganlumomo/semantic_3d_mapping", "max_stars_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T13:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:37:55.000Z", "max_issues_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_issues_repo_name": "ganlumomo/semantic_3d_mapping", "max_issues_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-28T09:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:46:00.000Z", "max_forks_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_forks_repo_name": "ganlumomo/semantic_3d_mapping", "max_forks_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T06:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:42.000Z", "avg_line_length": 23.572972973, "max_line_length": 123, "alphanum_fraction": 0.4926622334, "num_tokens": 3083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6642832373797828}}
{"text": "#define MIN(a,b) a < b ? a : b  \n#define MAX(a,b) a > b ? a : b  \n\n#include <mpi.h>\n#include <cassert>\n#include <vector>\n#include <random>\n#include <iostream>\n#include <boost/mpi/datatype.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\nusing namespace boost::numeric::ublas;\n\ntemplate <typename T>\nmatrix<T>* gen_matrix(size_t rows = 1024, size_t cols = 1024,int min = 0, int max = 3){\n  std::random_device seeder;\n  boost::random::mt19937 gen(seeder());\n  boost::random::uniform_int_distribution<> dist(min, max);\n\n  matrix<T>* m = new matrix<T> (rows, cols);\n  for (unsigned i = 0; i < m->size1 (); ++ i)\n    for (unsigned j = 0; j < m->size2 (); ++ j)\n        m->at_element(i, j) = dist(gen);;\n  return m;\n}\n\ntemplate <typename T>\nvoid vm_mul_row_wise(std::vector<T>* sub_vectors, matrix<T>* m, std::vector<T>* sub_out){\n  const int m_rows = m->size1();\n  const int m_cols = m->size2();\n  const int v_cols = m->size1();\n  const int v_rows = sub_vectors->size() / v_cols;\n\n  for(int i=0; i < v_rows; i++){\n    for(int j=0; j < m_cols; j++){\n      T temp = 0;\n      for(int k=0; k < m_rows; k++){\n        temp += sub_vectors->at(i * v_cols + k) * m->at_element(k, j);\n      }\n      sub_out->at(i*v_cols + j) = temp;\n    }\n  }\n}\n\ntemplate <typename T>\nbool check_equality(matrix<T>* m1, matrix<T>* m2){\n  for(int i=0; i < m1->size1(); i++){\n    for(int j=0; j < m1->size2(); j++){\n      if(m1->at_element(i,j) != m2->at_element(i,j)){\n      \treturn false;\n      }\n    }\n  }\n  return true;\n}\n\nvoid matrix_mul(const int rows=1024, const int cols=1024){\n\n  int world_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n  int world_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n  auto mpi_type = MPI_INT;\n  const int root = 0;\n\n  matrix<int>* m1 = NULL;\n  matrix<int>* m2 = NULL; \n  // matrix<int> m_origin_out; \n  if (world_rank == root) {\n    m1 = gen_matrix<int>(rows, cols);\n    m2 = gen_matrix<int>(cols, rows);\n    // m_origin_out = matrix<int>(prod(*m1, *m2));\n  }else{\n    m2 = new matrix<int>(rows, cols);\n    // m_origin_out = matrix<int>(rows, cols);\n  }\n  MPI_Bcast(m2->data().begin(), rows * cols, mpi_type, root, MPI_COMM_WORLD);\n  // MPI_Bcast(m_origin_out.data().begin(), rows * rows, mpi_type, root, MPI_COMM_WORLD);\n  \n  if( rows % world_size != 0){\n    MPI_Abort(MPI_COMM_WORLD, -1);\n  }\n  int recv_count =  rows / world_size * cols;\n  \n  std::vector<int>* sub_vectors = new std::vector<int>(recv_count);\n  assert(sub_vectors != NULL);\n\n  if(world_rank == root){\n    MPI_Scatter( m1->data().begin(), recv_count, mpi_type, sub_vectors->data(), recv_count, mpi_type, root, MPI_COMM_WORLD);\n  } else{\n    MPI_Scatter( NULL, recv_count, mpi_type, sub_vectors->data(), recv_count, mpi_type, root, MPI_COMM_WORLD);\n  }\n\n  // v_rows * cols ,  cols * rows,  v_rows * rows\n  std::vector<int>* sub_out = new std::vector<int>(recv_count);\n  matrix<int>* m_out = new matrix<int>(rows, rows);\n  assert(m_out != NULL);\n\n  vm_mul_row_wise<int>(sub_vectors, m2, sub_out);\n\n  MPI_Allgather(sub_out->data(), recv_count, mpi_type, m_out->data().begin(), recv_count, mpi_type, MPI_COMM_WORLD); \n\n  std::cout << *m_out << std::endl;\n  // auto is_same = check_equality(m_out, &m_origin_out);\n  // std::cout <<  \"Rank:\" << world_rank  << \",The two results are same:\" << is_same << std::endl; \n  // MPI_Barrier(MPI_COMM_WORLD);\n\n  delete sub_out;\n  delete m_out;\n  delete m2;\n  if (world_rank == root) {\n    delete m1;\n  }\n}\n\ntemplate <typename T>\nint get_max(vector<T>* v){\n  T max = v->at(0);\n  for(int i=0; i<v->size(); i++){\n    max = (max < v->at(i)) ? v->at(i) : max;\n  }\n  return max;\n}\n\n// (W\u2212F+2P)/S+1\n// here just implement max pooling\nvoid matrix_pool(const int rows=1024, const int cols=1024, const int k_h = 4, const int k_w = 4,\n\t\tconst int p_h = 0, const int p_w = 0, const int stride_h = 4, const int stride_w = 4){\n \n  int world_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n  int world_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n  auto mpi_type = MPI_INT;\n  const int root = 0;\n\n  matrix<int>* M = NULL;\n  if( world_rank == root){\n    M = gen_matrix<int>(rows, cols);\n  }else{\n    M = new matrix<int>(rows, cols);\n  }\n  MPI_Bcast(M->data().begin(), rows*cols, mpi_type, root, MPI_COMM_WORLD);\n\n  if( rows % k_h != 0 || cols % k_w != 0){\n    MPI_Abort(MPI_COMM_WORLD, -1);\n  }\n\n  const int new_rows = (rows - k_h + 2 * p_h) / stride_h + 1;\n  const int new_cols = (cols - k_w + 2 * p_w) / stride_w + 1;\n\n  matrix<int>* N = new matrix<int>(new_rows, new_cols);\n  int num_elements_per_proc = new_rows * new_cols / world_size;\n  std::vector<int>* sub_vec = new std::vector<int>(num_elements_per_proc);\n  MPI_Scatter(N->data().begin(), num_elements_per_proc, mpi_type, sub_vec->data(), num_elements_per_proc, mpi_type, root, MPI_COMM_WORLD);\n  \n  for(int i=0; i < num_elements_per_proc; i++){\n    int pool_index = i*world_size + world_rank;\n\n    int nr = pool_index / new_cols;\n    int nc = pool_index % new_cols;\n    \n    int hstart = nr * stride_h - p_h;\n    int wstart = nc * stride_w - p_w;\n    int hend = MIN(hstart + k_h, rows);\n    int wend = MIN(wstart + k_w, cols);\n    hstart = MAX(hstart, 0);\n    wstart = MAX(wstart, 0); \n\n    int temp_max = INT_MIN;\n    for(int h=hstart; h < hend; h++){\n      for(int w=wstart; w < wend; w++){\n        int index = h * cols + w;\n        int bottom_data = M->at_element(h, w);\n        if(bottom_data > temp_max ){\n          temp_max = bottom_data;\n        }\n      }\n    }\n    sub_vec->at(i) = temp_max;\n  }\n\n  MPI_Allgather(sub_vec->data(), num_elements_per_proc, mpi_type, N->data().begin(), num_elements_per_proc,mpi_type, MPI_COMM_WORLD);\n  std::cout<< *M << std::endl;\n  std::cout<< *N << std::endl;\n}\n\n// (W\u2212F+2P)/S+1\n// just implement naive conv\n// TODO: im2col  \nvoid matrix_conv(const int rows=1024, const int cols=1024, const int k_h = 4, const int k_w = 4,\n\t\tconst int p_h = 0, const int p_w = 0, const int stride_h = 4, const int stride_w = 4){\n \n  int world_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n  int world_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n  auto mpi_type = MPI_INT;\n  const int root = 0;\n\n  matrix<int>* M = NULL;\n  matrix<int>* K = NULL;\n  if( world_rank == root){\n    M = gen_matrix<int>(rows, cols);\n    K = gen_matrix<int>(k_h, k_w);\n  }else{\n    M = new matrix<int>(rows, cols);\n    K = new matrix<int>(k_h, k_w);\n  }\n  MPI_Bcast(M->data().begin(), rows*cols, mpi_type, root, MPI_COMM_WORLD);\n  MPI_Bcast(K->data().begin(), k_h * k_w, mpi_type, root, MPI_COMM_WORLD);\n\n  if( rows % k_h != 0 || cols % k_w != 0){\n    MPI_Abort(MPI_COMM_WORLD, -1);\n  }\n\n  const int new_rows = (rows - k_h + 2 * p_h) / stride_h + 1;\n  const int new_cols = (cols - k_w + 2 * p_w) / stride_w + 1;\n\n  matrix<int>* N = new matrix<int>(new_rows, new_cols);\n  int num_elements_per_proc = new_rows * new_cols / world_size;\n  std::vector<int>* sub_vec = new std::vector<int>(num_elements_per_proc);\n  MPI_Scatter(N->data().begin(), num_elements_per_proc, mpi_type, sub_vec->data(), num_elements_per_proc, mpi_type, root, MPI_COMM_WORLD);\n  \n  for(int i=0; i < num_elements_per_proc; i++){\n    int pool_index = i*world_size + world_rank;\n\n    int nr = pool_index / new_cols;\n    int nc = pool_index % new_cols;\n    \n    int hstart = nr * stride_h - p_h;\n    int wstart = nc * stride_w - p_w;\n    int hend = MIN(hstart + k_h, rows);\n    int wend = MIN(wstart + k_w, cols);\n    hstart = MAX(hstart, 0);\n    wstart = MAX(wstart, 0); \n\n    int temp_prod = 0;\n    for(int h=hstart; h < hend; h++){\n      for(int w=wstart; w < wend; w++){\n        int index = h * cols + w;\n        int bottom_data = M->at_element(h, w);\n        int weight = K->at_element(h-hstart, w-wstart);\n        temp_prod += bottom_data * weight;\n      }\n    }\n    sub_vec->at(i) = temp_prod;\n  }\n\n  MPI_Allgather(sub_vec->data(), num_elements_per_proc, mpi_type, N->data().begin(), num_elements_per_proc,mpi_type, MPI_COMM_WORLD);\n  std::cout<< *M << std::endl;\n  std::cout<< *K << std::endl;\n  std::cout<< *N << std::endl;\n\n}\n\nint main(int argc, char** argv) {\n\n  MPI_Init(NULL, NULL);\n\n  matrix_mul(1024, 1024);\n  matrix_pool(1024,1024);\n  matrix_conv(1024, 1024);\n\n  MPI_Finalize();\n}\n", "meta": {"hexsha": "22d57355b4d76779d846c4b6e415711a105f17a4", "size": 8287, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homework1/hw1_2.cc", "max_stars_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_stars_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homework1/hw1_2.cc", "max_issues_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_issues_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework1/hw1_2.cc", "max_forks_repo_name": "ONLY-VEDA/MPI_2019_SPRING", "max_forks_repo_head_hexsha": "b0a8bd58dfbc62613b54b99b8e85a74f77a2c468", "max_forks_repo_licenses": ["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.3553113553, "max_line_length": 138, "alphanum_fraction": 0.6297815856, "num_tokens": 2611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436395, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6642832316720472}}
{"text": "#include \"QuarticPolynomial.h\"\n\n#include <Eigen/LU>\n#include <cmath>\n\nusing namespace Eigen;\n\nQuarticPolynomial::QuarticPolynomial(double xs, double vxs, double axs,\n        double vxe, double axe, double t):\n        a0(xs), a1(vxs) {\n    a2 = axs / 2.0;\n    Matrix2d A;\n    Vector2d B;\n    A << 3 * pow(t, 2), 4 * pow(t, 3), 6 * t, 12 * pow(t, 2);\n    B << vxe - a1 - 2 * a2 * t, axe - 2 * a2;\n    Matrix2d A_inv = A.inverse();\n    Vector2d x = A_inv * B;\n    a3 = x[0];\n    a4 = x[1];\n}\n\ndouble QuarticPolynomial::calc_point(double t) {\n    return a0 + a1 * t + a2 * pow(t, 2) + a3 * pow(t, 3) + a4 * pow(t, 4);\n}\n\ndouble QuarticPolynomial::calc_first_derivative(double t) {\n    return a1 + 2 * a2 * t + 3 * a3 * pow(t, 2) + 4 * a4 * pow(t, 3);\n}\n\ndouble QuarticPolynomial::calc_second_derivative(double t) {\n    return 2 * a2 + 6 * a3 * t + 12 * a4 * pow(t, 2);\n}\n\ndouble QuarticPolynomial::calc_third_derivative(double t) {\n    return 6 * a3 + 24 * a4 * t;\n}", "meta": {"hexsha": "976bd930199abcb3ed99dafa29262ef588d94ee6", "size": 962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_stars_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_stars_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T16:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:56:27.000Z", "max_issues_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_issues_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_issues_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-05-16T11:57:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T07:54:17.000Z", "max_forks_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_forks_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_forks_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2020-04-28T06:02:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:13:23.000Z", "avg_line_length": 26.7222222222, "max_line_length": 74, "alphanum_fraction": 0.5831600832, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6642529046314467}}
{"text": "#include \"PoseEstimator.h\"\n#include \"PoseOptimizer.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <opencv2/core/eigen.hpp>\n\nnamespace MVSO\n{\n\tvoid solveICP(std::vector<cv::Point3f>& points3D_t0, std::vector<cv::Point3f>& points3D_t1, cv::Mat& R, cv::Mat& t)\n\t{\n\t\tcv::Point3f p1, p2;     // center of mass\n\t\tint N = points3D_t0.size();\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tp1 += points3D_t0[i];\n\t\t\tp2 += points3D_t1[i];\n\t\t}\n\t\tp1 = cv::Point3f(cv::Vec3f(p1) / N);\n\t\tp2 = cv::Point3f(cv::Vec3f(p2) / N);\n\t\tstd::vector<cv::Point3f>     q1(N), q2(N); // remove the center\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tq1[i] = points3D_t0[i] - p1;\n\t\t\tq2[i] = points3D_t1[i] - p2;\n\t\t}\n\n\t\t// compute q1*q2^T\n\t\tEigen::Matrix3d W = Eigen::Matrix3d::Zero();\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tW += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n\t\t}\n\n\t\t// SVD on W\n\t\tEigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tEigen::Matrix3d U = svd.matrixU();\n\t\tEigen::Matrix3d V = svd.matrixV();\n\n\t\tif (U.determinant() * V.determinant() < 0)\n\t\t{\n\t\t\tfor (int x = 0; x < 3; ++x)\n\t\t\t{\n\t\t\t\tU(x, 2) *= -1;\n\t\t\t}\n\t\t}\n\n\t\tEigen::Matrix3d R_ = U * (V.transpose());\n\t\tEigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n\n\t\tcv::eigen2cv(R_, R);\n\t\tcv::eigen2cv(t_, t);\n\t}\n\n\n\tvoid solveICPRansac(std::vector<cv::Point3f>& pts1, std::vector<cv::Point3f>& pts2,\n\t\tcv::Mat& R, cv::Mat& t,std::vector<int>& inliers,\n\t\tint iterationCount, float reprojectionError)\n\t{\n\t\tcv::Mat bestR = (cv::Mat_<double>(3, 3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);\n\t\tcv::Mat bestT = (cv::Mat_<double>(3, 1) << 0, 0, 0);\n\t\tstd::vector<int> bestInliers;\n\t\tcv::Mat ptsMat1(pts1);\n\t\tcv::Mat ptsMat2(pts2);\n\t\tfor (int it = 0; it < iterationCount; it++)\n\t\t{\n\t\t\tstd::vector<cv::Point3f> subset1;\n\t\t\tstd::vector<cv::Point3f> subset2;\n\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t{\n\t\t\t\tint id = rand() % pts1.size();\n\n\t\t\t\tsubset1.push_back(pts1[id]);\n\t\t\t\tsubset2.push_back(pts2[id]);\n\t\t\t}\n\n\t\t\tcv::Mat tmpR, tmpT;\n\t\t\tsolveICP(subset1, subset2, tmpR, tmpT);\n\n\t\t\tstd::vector<int> inliers;\n\t\t\tfor (int i = 0; i < pts1.size(); i++)\n\t\t\t{\n\t\t\t\tcv::Point3f& p1 = pts1[i];\n\t\t\t\tcv::Point3f& p2 = pts2[i];\n\t\t\t\tcv::Point3f ep2;\n\t\n\t\t\t\tep2.x = tmpR.at<double>(0, 0) * p1.x + tmpR.at<double>(0, 1) * p1.y + tmpR.at<double>(0, 2) * p1.z + tmpT.at<double>(0);\n\t\t\t\tep2.y = tmpR.at<double>(1, 0) * p1.x + tmpR.at<double>(1, 1) * p1.y + tmpR.at<double>(1, 2) * p1.z + tmpT.at<double>(1);\n\t\t\t\tep2.z = tmpR.at<double>(2, 0) * p1.x + tmpR.at<double>(2, 1) * p1.y + tmpR.at<double>(2, 2) * p1.z + tmpT.at<double>(2);\n\n\t\t\t\tfloat err = sqrt((p2.x - ep2.x)*(p2.x - ep2.x) + (p2.y - ep2.y)*(p2.y - ep2.y) + (p2.z - ep2.z));\n\t\t\t\tif (err < reprojectionError)\n\t\t\t\t{\n\t\t\t\t\tinliers.push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (inliers.size() > bestInliers.size())\n\t\t\t{\n\t\t\t\tbestInliers = inliers;\n\t\t\t\tbestR = tmpR;\n\t\t\t\tbestT = tmpT;\n\t\t\t}\n\n\t\t}\n\t\tR = bestR;\n\t\tt = bestT;\n\t\tinliers = bestInliers;\n\t}\n\n\n\tMVSO::PoseEstimator::PoseEstimator(CameraModel & camera): camera_(camera)\n\t{\n\t}\n\n\tcv::Mat PoseEstimator::estimatePose(std::vector<cv::Point2f>& pointsLeft_t0, std::vector<cv::Point2f>& pointsLeft_t1, std::vector<cv::Point3f>& points3D_t0)\n\t{\n\t\t// Calculate frame to frame transformation\n\t\tcv::Mat pose;\n\t\tcv::Mat rotation, translation;\n\n\t\t// -----------------------------------------------------------\n\t\t// Rotation(R) estimation using Nister's Five Points Algorithm\n\t\t// -----------------------------------------------------------\n\t\tdouble focal = camera_.fx_;\n\t\tcv::Point2d principle_point(camera_.cx_, camera_.cy_);\n\n\t\t//recovering the pose and the essential cv::matrix\n\t\tcv::Mat E, mask;\n\t\tcv::Mat translation_mono = cv::Mat::zeros(3, 1, CV_64F);\n\t\tE = cv::findEssentialMat(pointsLeft_t1, pointsLeft_t0, focal, principle_point, cv::RANSAC, 0.999, 1.0, mask);\n\t\tcv::recoverPose(E, pointsLeft_t1, pointsLeft_t0, rotation, translation_mono, focal, principle_point, mask);\n\t\t// std::cout << \"recoverPose rotation: \" << rotation << std::endl;\n\n\t\t// ------------------------------------------------\n\t\t// Translation (t) estimation by use solvePnPRansac\n\t\t// ------------------------------------------------\n\t\tcv::Mat distCoeffs = cv::Mat::zeros(4, 1, CV_64FC1);\n\t\tcv::Mat inliers;\n\t\tcv::Mat rvec = cv::Mat::zeros(3, 1, CV_64FC1);\n\n\t\tint iterationsCount = 100;        // number of Ransac iterations.\n\t\tfloat reprojectionError = 1.0;    // maximum allowed distance to consider it an inlier.\n\t\tfloat confidence = 0.98;          // RANSAC successful confidence.\n\t\tbool useExtrinsicGuess = false;\n\t\tint flags = cv::SOLVEPNP_EPNP;\n\n\t\t//cv::Rodrigues(rotation, rvec);\n\t\tcv::solvePnPRansac(points3D_t0, pointsLeft_t1, camera_.intrinsicMat_, distCoeffs, rvec, translation,\n\t\t\tuseExtrinsicGuess, iterationsCount, reprojectionError, confidence,\n\t\t\tinliers, flags);\n\n\n\t\tstd::vector<cv::Point3f> points3d;\n\t\tstd::vector<cv::Point2f> points2d;\n\t\tstd::vector<double> weights;\n\n\t\tfor (int i = 0; i < inliers.rows; i++)\n\t\t{\n\t\t\tint id = inliers.at<int>(i, 0);\n\n\t\t\tcv::Point3f p3d = points3D_t0[id];\n\t\t\tcv::Point2f p0 = pointsLeft_t0[id], p1 = pointsLeft_t1[id];\n\t\t\tpoints3d.push_back(p3d);\n\t\t\tpoints2d.push_back(p1);\n\n\t\t\tdouble w = sqrt((p0.x - p1.x)*(p0.x - p1.x) + (p0.y - p1.y)*(p0.y - p1.y));\n\t\t\t//w *= 1/(1+exp(abs(p3d.z - 5)));\n\t\t\tif (w > 7)\n\t\t\t\tw = 7;\n\t\t\telse if (w < 1.0)\n\t\t\t\tw = 1.0;\n\t\t\tweights.push_back(exp(-w));\n\t\t}\n\n\t\tPoseOptimizer optimizer(camera_);\n\t\t//cv::Rodrigues(rvec, rotation);\n\t\t//optimizer.optimizePose(points3d, points2d, rotation, translation);\n\t\toptimizer.optimizePose(points3d, points2d, weights,rotation, translation);\n\n\n\t\t//cv::Rodrigues(rvec, rotation);\n\t\trotation = rotation.t();\n\t\ttranslation = -translation;\n\t\t// std::cout << \"inliers size: \" << inliers.size() << std::endl;\n\t\tcv::hconcat(rotation, translation, pose);\n\t\treturn pose;\n\t}\n\n\tcv::Mat PoseEstimator::estimatePose(std::vector<cv::Point2f>& points_t0, std::vector<cv::Point2f>& points_t1, std::vector<cv::Point3f>& points3D_t0, std::vector<cv::Point3f>& points3D_t1)\n\t{\n\t\t\n\t\tcv::Mat R, t;\n\t\tstd::vector<int> inliers;\n\t\tsolveICPRansac(points3D_t0, points3D_t1, R, t, inliers, 100, 1.0);\n\n\t\tstd::vector<cv::Point3f> pts1, pts2;\n\t\tfor (int n : inliers)\n\t\t{\n\t\t\tpts1.push_back(points3D_t0[n]);\n\t\t\tpts2.push_back(points3D_t1[n]);\n\t\t}\n\n\n\t\tPoseOptimizer optimizer(camera_);\n\t\toptimizer.optimizePose(pts1, pts2, R, t);\n\t\tcv::Mat pose;\n\t\tcv::hconcat(R, t, pose);\n\t\treturn pose;\n\n\t}\n\n\tPoseEstimator::~PoseEstimator()\n\t{\n\t}\n\n}\n\n", "meta": {"hexsha": "3d783fc744fd6b6b2049cedc48047e8085de060c", "size": 6523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PoseEstimator.cpp", "max_stars_repo_name": "lambdald/visualOdometry", "max_stars_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_stars_repo_licenses": ["MIT"], "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/PoseEstimator.cpp", "max_issues_repo_name": "lambdald/visualOdometry", "max_issues_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_issues_repo_licenses": ["MIT"], "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/PoseEstimator.cpp", "max_forks_repo_name": "lambdald/visualOdometry", "max_forks_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_forks_repo_licenses": ["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.65, "max_line_length": 188, "alphanum_fraction": 0.6020236088, "num_tokens": 2382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6642311358396703}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3i m = Matrix3i::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is the upper-triangular matrix extracted from m:\" << endl\n     << Matrix3i(m.triangularView<Eigen::Upper>()) << endl;\ncout << \"Here is the strictly-upper-triangular matrix extracted from m:\" << endl\n     << Matrix3i(m.triangularView<Eigen::StrictlyUpper>()) << endl;\ncout << \"Here is the unit-lower-triangular matrix extracted from m:\" << endl\n     << Matrix3i(m.triangularView<Eigen::UnitLower>()) << endl;\n// FIXME need to implement output for triangularViews (Bug 885)\n\n  return 0;\n}\n", "meta": {"hexsha": "bf8736d240c874504d0206b8cf0ef33a58473b82", "size": 793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_triangularView.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_triangularView.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_MatrixBase_triangularView.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 29.3703703704, "max_line_length": 80, "alphanum_fraction": 0.6973518285, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.664213056426818}}
{"text": "#ifndef SPLINE_HPP\n#define SPLINE_HPP\n\n#include <array>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\nusing namespace std;\nusing namespace Eigen;\n\n/**\n * A 1D polynomial of type f(t) = a + b t + c t^2 + d t^3 + ... + z t^(order)\n * that is bounded to the range t in [0; 1].\n */\ntemplate<unsigned int Order>\nstruct UnitBoundedPolynomial1\n{\n    static_assert(Order % 2 == 1, \"Order must be odd\");\n    static_assert(Order > 0);\n\n    /**\n     * The number of derivates (including 0-th derivative) \n     * required to fit this polynomial to start and end point\n     */\n    static constexpr const int RequiredValues = (Order + 1) / 2;\n\n    double coeffs[Order+1];\n\n    /**\n     * Returns point at t on polynomial\n     * @param  t in [0;1]\n     * @return   double\n     */\n    double interpolate(double t) const;\n\n    /**\n     * Returns first derivative of polynomial at t\n     * @param  t in [0;1]\n     * @return   double\n     */\n    double derivative(double t) const;\n\n    /**\n     * Returns second derivative of polynomial at t\n     * @param  t in [0;1]\n     * @return   double\n     */\n    double derivative2(double t) const;\n\n    /**\n     * Fits the polynomial to go through start and end point\n     * with specified derivatives.\n     */\n    static UnitBoundedPolynomial1<Order> fit(const Matrix<double, RequiredValues, 1> a, const Matrix<double, RequiredValues, 1> b);\n};\n\n/**\n * A multi dimensional polynomial function. Aggregate of multiple independent 1-dimensional polynomials.\n */\ntemplate<unsigned int Order, unsigned int Dims>\nstruct UnitBoundedPolynomial\n{\n    static_assert(Order > 0);\n    static_assert(Dims > 0);\n\n    typedef Matrix<double, Dims, 1> VectorNd;\n    typedef UnitBoundedPolynomial1<Order> Poly1;\n\n    UnitBoundedPolynomial1<Order> _dims[Dims];\n    double length;\n\n    VectorNd interpolate(double t) const;\n    VectorNd derivative(double t) const;\n\n    /**\n     * Walks on the polynomial. Calls fn many times with points on the function.\n     * Resolution is specified using deltatau.\n     * @param deltatau  Resolution with which to walk \n     * @param fn        Callback function\n     * @param payload   Gets passed to callback\n     * @param a         Optional, start point, can be used for extrapolation\n     * @param b         Optional, end point, can be used for extrapolation\n     */\n    void walk(const double deltatau, void (*fn)(VectorNd, double, const UnitBoundedPolynomial<Order, Dims>&, void *), void *payload = nullptr, double a = 0.0, double b = 1.0) const;\n\n    /**\n     * Calculates a spline.\n     * @param  A Matrix of point a with A[:, 0] = point, A[:, 1] = 1st derivative, A[:, 2] = 2nd derivative\n     * @param  B Matrix of point b with B[:, 0] = point, B[:, 1] = 1st derivative, B[:, 2] = 2nd derivative\n     * @return   Spline\n     */\n    static UnitBoundedPolynomial<Order, Dims> fit(Matrix<double, Dims, Poly1::RequiredValues> A, \n                                                  Matrix<double, Dims, Poly1::RequiredValues> B);\n\nprivate:\n    void calculateLength();\n};\n\ntemplate<unsigned int Order, unsigned int Dims>\nclass SplineSolver;\n\n/**\n * A hermite spline. \n * Order and dimensionality can vary. \n * Currently only quintic and cubic splines are supported.\n */\ntemplate<unsigned int Order, unsigned int Dims>\nstruct HermiteSpline\n{\n    static_assert(Order > 0);\n    static_assert(Dims > 0);\n\n    using Solver = SplineSolver<Order, Dims>;\n\n    typedef Matrix<double, Dims, 1> VectorNd;\n    typedef Matrix<double, Dims, Dynamic> MatrixNXd;\n\n    typedef UnitBoundedPolynomial1<Order> Polynomial1;\n    typedef UnitBoundedPolynomial<Order, Dims> Polynomial;\n\n    vector<Polynomial> children;\n    double length;\n\n    HermiteSpline() : length(0)\n    {\n    }\n\n    VectorNd interpolate(double s);\n\n    void walk(const double deltatau, void (*fn)(VectorNd, HermiteSpline<Order, Dims>&, double, Polynomial&, void *), void *payload = nullptr);\n    void add(Polynomial sp);\n\n    /**\n     * Calculates the hermite spline.\n     * @param values    An array of required values (i.e. point, derivative, 2nd derivative, ..) x dimensions x number of points.\n     * @return HermiteSpline\n     */\n    static HermiteSpline<Order, Dims> fit(array<MatrixNXd, Polynomial1::RequiredValues> values);\n};\n\ntemplate<unsigned int Order, unsigned int Dims>\nclass BaseSplineSolver\n{\npublic:\n\n    typedef typename Eigen::Matrix<double, Dims, 1> VectorNd;\n    typedef typename Eigen::Matrix<double, Dims, Dynamic> MatrixNXd;\n    typedef typename MatrixNXd::RowXpr RowXpr;\n\n    typedef UnitBoundedPolynomial1<Order> Polynomial1;\n    typedef UnitBoundedPolynomial<Order, Dims> Polynomial;\n\n    typedef HermiteSpline<Order, Dims> Spline;\n\n    HermiteSpline<Order, Dims> solve(vector<VectorNd> points, \n                                     Matrix<double, Dims, Polynomial1::RequiredValues - 1> start, \n                                     Matrix<double, Dims, Polynomial1::RequiredValues - 1> end);\n\nprotected:\n\n    virtual bool find_params_1d(RowXpr params[Polynomial1::RequiredValues]) = 0;\n\n};\n\n/**\n * The spline solver class implements methods\n * to compute a spline given N+1 points\n * plus start and end point slopes.\n */\ntemplate<unsigned int Order, unsigned int Dims>\nclass SplineSolver : public BaseSplineSolver<Order, Dims>\n{};\n\n\n// Quintic solver\n\ntemplate<unsigned int Dims>\nclass SplineSolver<5, Dims> : public BaseSplineSolver<5, Dims>\n{\npublic:\n\n    using RowXpr = typename BaseSplineSolver<5, Dims>::RowXpr;\n\nprotected:\n\n    SparseMatrix<double> A;\n    SparseLU<SparseMatrix<double>,  COLAMDOrdering<int>> solver;\n\n    bool find_params_1d(RowXpr params[3]);\n    bool build_solver(const int N, const int M);\n\n};\n\n// Cubic solver\n\ntemplate<unsigned int Dims>\nclass SplineSolver<3, Dims> : public BaseSplineSolver<3, Dims>\n{\npublic:\n\n    using RowXpr = typename BaseSplineSolver<3, Dims>::RowXpr;\n\nprotected:\n\n    SparseMatrix<double> A;\n    SparseLU<SparseMatrix<double>,  COLAMDOrdering<int>> solver;\n\n    bool find_params_1d(RowXpr params[2]);\n    bool build_solver(const int N, const int M);\n\n};\n\ntemplate <unsigned int Dims>\nusing CubicHermiteSpline = HermiteSpline<3, Dims>;\n\ntemplate <unsigned int Dims>\nusing QuinticHermiteSpline = HermiteSpline<5, Dims>;\n\n#endif\n", "meta": {"hexsha": "1be3b7eb589623410bef002247a4fedc5fd1be8f", "size": 6247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_stars_repo_name": "janhuenermann/quintic-spline-solver", "max_stars_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T14:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T01:37:24.000Z", "max_issues_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_issues_repo_name": "janhuenermann/quintic-spline-solver", "max_issues_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_forks_repo_name": "janhuenermann/quintic-spline-solver", "max_forks_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_forks_repo_licenses": ["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.0134529148, "max_line_length": 181, "alphanum_fraction": 0.675204098, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.7122321964553656, "lm_q1q2_score": 0.6641232682616954}}
{"text": "#include \"ImplicitIntegrator.h\"\n#include \"Deformation.hpp\"\n#include \"ProtoConverter.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/SVD>\n#include <Eigen/IterativeLinearSolvers>\n#include <Mathematics/SymmetricEigensolver3x3.h>\n\n#include <iostream>\n#include <glm/gtc/constants.hpp>\n\nusing Eigen::MatrixXd;\n\nnamespace Deformation\n{\n    using FloatT = double;\n    using Mat3 = Eigen::Matrix<FloatT, 3, 3>;\n    using Mat3x4 = Eigen::Matrix<FloatT, 3, 4>;\n    using Mat9x12 = Eigen::Matrix<FloatT, 9, 12>;\n    using Mat9 = Eigen::Matrix<FloatT, 9, 9>;\n    using Mat12 = Eigen::Matrix<FloatT, 12, 12>;\n    using Vec3 = Eigen::Matrix<FloatT, 3, 1>;\n    using Vec9 = Eigen::Matrix<FloatT, 9, 1>;\n    using Vec12 = Eigen::Matrix<FloatT, 12, 1>;\n\n    Mat3 Calc_Ds(const Deformation::Tetrahedra& tet, const std::vector<Vertex>& vertices, bool restState)\n    {\n        Mat3 ds = Mat3::Zero();\n\n        for (int row = 0; row < 3; row++)\n        {\n            for (int col = 1; col < 4; col++)\n            {\n                if (restState)\n\t\t\t\t\tds(row, col - 1) = vertices[tet.mIndices[col]].mMaterialCoordinates[row] - vertices[tet.mIndices[0]].mMaterialCoordinates[row];\n                else\n                    ds(row, col - 1) = vertices[tet.mIndices[col]].mPosition[row] - vertices[tet.mIndices[0]].mPosition[row];\n            }\n        }\n\n        return ds;\n    }\n\n    Mat3 Calc_DmInv(const Deformation::Tetrahedra& tet, const std::vector<Vertex>& vertices)\n    {\n        auto mat = Calc_Ds(tet, vertices, true);\n        if (std::abs(mat.determinant()) < 1e-10f)\n            throw std::exception(\"Small\");\n        return mat.inverse();\n    }\n\n    Mat3 Calc_F(const Mat3& ds, const Mat3& dmInv)\n    {\n        return ds * dmInv;\n    }\n\n    Mat3 Calc_E(const Mat3& f)\n    {\n        return 0.5f * (f * f.transpose() - Mat3::Identity());\n    }\n\n    Mat3 Calc_dPsiDf(const Mat3& f, const Mat3& e)\n    {\n        FloatT youngsModulus = 8 * 10e8f;\n        FloatT poissonRatio = 0.45f;\n        FloatT lamba = youngsModulus * poissonRatio / ((1.0f + poissonRatio) * (1.0f - 2.0f * poissonRatio));\n        FloatT mu = youngsModulus / (2.0f + 2.0f * poissonRatio);\n        return mu * f * e + lamba * e.trace() * f;\n    }\n\n    Vec9 Reshape3x3(const Mat3& m)\n    {\n        Vec9 vec = Vec9::Zero();\n        vec(0, 0) = m(0, 0);\n        vec(1, 0) = m(1, 0);\n        vec(2, 0) = m(2, 0);\n\n        vec(3, 0) = m(0, 1);\n        vec(4, 0) = m(1, 1);\n        vec(5, 0) = m(2, 1);\n\n        vec(6, 0) = m(0, 2);\n        vec(7, 0) = m(1, 2);\n        vec(8, 0) = m(2, 2);\n\n        return vec;\n    }\n\n    Vec12 Reshape3x4(const Mat3x4& m)\n    {\n        Vec12 vec = Vec12::Zero();\n        vec(0, 0) = m(0, 0);\n        vec(1, 0) = m(1, 0);\n        vec(2, 0) = m(2, 0);\n\n        vec(3, 0) = m(0, 1);\n        vec(4, 0) = m(1, 1);\n        vec(5, 0) = m(2, 1);\n\n        vec(6, 0) = m(0, 2);\n        vec(7, 0) = m(1, 2);\n        vec(8, 0) = m(2, 2);\n\n        vec(9, 0) = m(0, 3);\n        vec(10, 0) = m(1, 3);\n        vec(11, 0) = m(2, 3);\n        return vec;\n    }\n\n    Mat9x12 Calc_dFdx(const Mat3& dmInv)\n    {\n        auto m = dmInv(0, 0);\n        auto n = dmInv(0, 1);\n        auto o = dmInv(0, 2);\n        auto p = dmInv(1, 0);\n        auto q = dmInv(1, 1);\n        auto r = dmInv(1, 2);\n        auto s = dmInv(2, 0);\n        auto t = dmInv(2, 1);\n        auto u = dmInv(2, 2);\n\n        auto t1 = -m - p - s;\n        auto t2 = -n - q - t;\n        auto t3 = -o - r - u;\n\n        Mat9x12 dFdx = Mat9x12::Zero();\n\n        dFdx(0, 0) = t1;\n        dFdx(0, 3) = m;\n        dFdx(0, 6) = p;\n        dFdx(0, 9) = s;\n        dFdx(1, 1) = t1;\n        dFdx(1, 4) = m;\n        dFdx(1, 7) = p;\n        dFdx(1, 10) = s;\n\n        dFdx(2, 2) = t1;\n        dFdx(2, 5) = m;\n        dFdx(2, 8) = p;\n        dFdx(2, 11) = s;\n        dFdx(3, 0) = t2;\n        dFdx(3, 3) = n;\n        dFdx(3, 6) = q;\n        dFdx(3, 9) = t;\n        dFdx(4, 1) = t2;\n        dFdx(4, 4) = n;\n\n        dFdx(4, 7) = q;\n        dFdx(4, 10) = t;\n        dFdx(5, 2) = t2;\n        dFdx(5, 5) = n;\n        dFdx(5, 8) = q;\n        dFdx(5, 11) = t;\n        dFdx(6, 0) = t3;\n        dFdx(6, 3) = o;\n        dFdx(6, 6) = r;\n        dFdx(6, 9) = u;\n        dFdx(7, 1) = t3;\n        dFdx(7, 4) = o;\n\n        dFdx(7, 7) = r;\n        dFdx(7, 10) = u;\n        dFdx(8, 2) = t3;\n        dFdx(8, 5) = o;\n        dFdx(8, 8) = r;\n        dFdx(8, 11) = u;\n\n        return dFdx;\n    }\n\n    Vec9 Calc_g_i(const Mat3& f)\n    {\n        Vec9 g_i = Vec9::Zero();\n        g_i(0, 0) = 2 * f(0, 0);\n        g_i(1, 0) = 2 * f(1, 0);\n        g_i(2, 0) = 2 * f(2, 0);\n\n        g_i(3, 0) = 2 * f(0, 1);\n        g_i(4, 0) = 2 * f(1, 1);\n        g_i(5, 0) = 2 * f(2, 1);\n\n        g_i(6, 0) = 2 * f(0, 2);\n        g_i(7, 0) = 2 * f(1, 2);\n        g_i(8, 0) = 2 * f(2, 2);\n        return g_i;\n    }\n\n    Mat3 Calc_dj_df(const Mat3& f)\n    {\n        Mat3 dj_df = Mat3::Zero();\n        dj_df.col(0) = f.col(1).cross(f.col(2));\n        dj_df.col(1) = f.col(2).cross(f.col(0));\n        dj_df.col(2) = f.col(0).cross(f.col(1));\n\n        //dj_df.block(0, 0, 3, 1) = f.col(1).cross(f.col(2));\n        //dj_df.block(0, 1, 3, 1) = f.col(2).cross(f.col(0));\n        //dj_df.block(0, 2, 3, 1) = f.col(0).cross(f.col(1));\n        return dj_df;\n    }\n\n    FloatT Calc_i_c(const Mat3& f)\n    {\n        auto frob = f.norm();\n        return frob * frob;\n    }\n\n    Mat9 Calc_h_i()\n    {\n        return 2 * Mat9::Identity();\n    }\n\n    Mat3 Calc_f_hat(const Vec3& f_i)\n    {\n        Mat3 f_hat = Mat3::Zero();\n        // col 0\n        f_hat(1, 0) = f_i(2);\n        f_hat(2, 0) = -f_i(1);\n        \n        // col 1\n        f_hat(0, 1) = -f_i(2);\n        f_hat(2, 1) = f_i(0);\n\n        // col 2\n        f_hat(0, 2) = f_i(1);\n        f_hat(1, 2) = -f_i(0);\n\n        return f_hat;\n    }\n\n    Mat9 Calc_h_j(const Mat3& f)\n    {\n        Mat9 h_j = Mat9::Zero();\n        auto f0_hat = Calc_f_hat(f.col(0));\n        auto f1_hat = Calc_f_hat(f.col(1));\n        auto f2_hat = Calc_f_hat(f.col(2));\n\n        // col 0\n        h_j.block(3, 0, 3, 3) = f2_hat;\n        h_j.block(6, 0, 3, 3) = -f1_hat;\n\n        // col 1\n        h_j.block(0, 3, 3, 3) = -f2_hat;\n        h_j.block(6, 3, 3, 3) = f0_hat;\n\n        // col 2\n        h_j.block(0, 6, 3, 3) = f1_hat;\n        h_j.block(3, 6, 3, 3) = -f0_hat;\n        \n        return h_j;\n    }\n\n    Mat9 Calc_D(const Mat3& f)\n    {\n        Mat9 d = Mat9::Zero();\n        const auto& f0 = f.col(0);\n        const auto& f1 = f.col(1);\n        const auto& f2 = f.col(2);\n\n        d.block(0, 0, 3, 3) = f0 * f0.transpose();\n        d.block(3, 0, 3, 3) = f0 * f1.transpose();\n        d.block(6, 0, 3, 3) = f0 * f2.transpose();\n\n        d.block(0, 3, 3, 3) = f1 * f0.transpose();\n        d.block(3, 3, 3, 3) = f1 * f1.transpose();\n        d.block(6, 3, 3, 3) = f1 * f2.transpose();\n\n        d.block(0, 6, 3, 3) = f2 * f0.transpose();\n        d.block(3, 6, 3, 3) = f2 * f1.transpose();\n        d.block(6, 6, 3, 3) = f2 * f2.transpose();\n\n        return d;\n    }\n\n    Mat9 KroneckerProduct(const Mat3& a, const Mat3& b)\n    {\n        Mat9 product = Mat9::Zero();\n        product.block(0, 0, 3, 3) = a(0, 0) * b;\n        product.block(3, 0, 3, 3) = a(1, 0) * b;\n        product.block(6, 0, 3, 3) = a(2, 0) * b;\n\n        product.block(0, 3, 3, 3) = a(0, 1) * b;\n        product.block(3, 3, 3, 3) = a(1, 1) * b;\n        product.block(6, 3, 3, 3) = a(2, 1) * b;\n\n        product.block(0, 6, 3, 3) = a(0, 2) * b;\n        product.block(3, 6, 3, 3) = a(1, 2) * b;\n        product.block(6, 6, 3, 3) = a(2, 2) * b;\n\n        return product;\n    }\n\n    Mat9 Calc_h_2(const Mat3& f, const Mat9& d)\n    {\n        return 4 * (KroneckerProduct(Mat3::Identity(), f * f.transpose()) + KroneckerProduct(f * f.transpose(), Mat3::Identity()) + d);\n    }\n\n    Mat9 Calc_vec_dPsi2_dF2(const Vec9& g_i, FloatT i_c, const Mat9& h_i, const Mat9& h_2, FloatT mu, FloatT lambda)\n    {\n        return lambda / 4.0f * (g_i * g_i.transpose()) + (-mu / 2.0f + lambda / 4.0f * (i_c - 3.0f)) * h_i + mu / 4.0f * h_2;\n    }\n\n    Mat12 Calc_dfdx(const Mat9x12& dFdx, const Mat9 & vec_dPsi2_dF2, FloatT restVol)\n    {\n        return -restVol * dFdx.transpose() * vec_dPsi2_dF2 * dFdx;\n    }\n\n    Mat3 Get_Q(int i, const std::array<FloatT, 3>& epsilon, const std::array<FloatT, 3>& sigma, const Mat3& u, const Mat3& v_transpose)\n    {\n        Mat3 d = Mat3::Zero();\n        d(0, 0) = sigma[0] * sigma[2] + sigma[1] * epsilon[i];\n        d(1, 1) = sigma[1] * sigma[2] + sigma[0] * epsilon[i];\n\t\td(2, 2) = epsilon[i] * epsilon[i] - sigma[2] * sigma[2];\n        return 1.0f / d.norm() * u * d * v_transpose;\n    }\n\n    Mat3 Get_Q(const Mat3 & U, const Mat3 & V, int i)\n    {\n        //Mat3 q = Mat3::Zero();\n\n        //if (i == 3)\n        //{\n        //    q(0, 1) = -1;\n        //    q(1, 0) = 1;\n        //}\n        //else if (i == 4)\n        //{\n        //    q(1, 2) = 1;\n        //    q(2, 1) = -1;\n        //}\n        //else if (i == 5)\n        //{\n        //    q(0, 2) = 1;\n        //    q(2, 0) = -1;\n        //}\n        //else if (i == 6)\n        //{\n        //    q(0, 1) = 1;\n        //    q(1, 0) = 1;\n        //}\n        //else if (i == 7)\n        //{\n        //    q(1, 2) = 1;\n        //    q(2, 1) = 1;\n        //}\n        //else if (i == 8)\n        //{\n        //    q(0, 2) = 1;\n        //    q(2, 0) = 1;\n        //}\n\n        //return 1 / sqrt(2.0f) * u * q * v_transpose;\n\n        static const FloatT scale = 1.0 / std::sqrt(2.0);\n        const Mat3 sV = scale * V;\n\n        using M3 = Eigen::Matrix<FloatT, 3, 3, Eigen::ColMajor>;\n\n        M3 A;\n        A << sV(0, 2) * U(0, 1), sV(1, 2)* U(0, 1), sV(2, 2)* U(0, 1),\n            sV(0, 2)* U(1, 1), sV(1, 2)* U(1, 1), sV(2, 2)* U(1, 1),\n            sV(0, 2)* U(2, 1), sV(1, 2)* U(2, 1), sV(2, 2)* U(2, 1);\n\n        M3 B;\n        B << sV(0, 1) * U(0, 2), sV(1, 1)* U(0, 2), sV(2, 1)* U(0, 2),\n            sV(0, 1)* U(1, 2), sV(1, 1)* U(1, 2), sV(2, 1)* U(1, 2),\n            sV(0, 1)* U(2, 2), sV(1, 1)* U(2, 2), sV(2, 1)* U(2, 2);\n\n        M3 C;\n        C << sV(0, 2) * U(0, 0), sV(1, 2)* U(0, 0), sV(2, 2)* U(0, 0),\n            sV(0, 2)* U(1, 0), sV(1, 2)* U(1, 0), sV(2, 2)* U(1, 0),\n            sV(0, 2)* U(2, 0), sV(1, 2)* U(2, 0), sV(2, 2)* U(2, 0);\n\n        M3 D;\n        D << sV(0, 0) * U(0, 2), sV(1, 0)* U(0, 2), sV(2, 0)* U(0, 2),\n            sV(0, 0)* U(1, 2), sV(1, 0)* U(1, 2), sV(2, 0)* U(1, 2),\n            sV(0, 0)* U(2, 2), sV(1, 0)* U(2, 2), sV(2, 0)* U(2, 2);\n\n        M3 E;\n        E << sV(0, 1) * U(0, 0), sV(1, 1)* U(0, 0), sV(2, 1)* U(0, 0),\n            sV(0, 1)* U(1, 0), sV(1, 1)* U(1, 0), sV(2, 1)* U(1, 0),\n            sV(0, 1)* U(2, 0), sV(1, 1)* U(2, 0), sV(2, 1)* U(2, 0);\n\n        M3 F;\n        F << sV(0, 0) * U(0, 1), sV(1, 0)* U(0, 1), sV(2, 0)* U(0, 1),\n            sV(0, 0)* U(1, 1), sV(1, 0)* U(1, 1), sV(2, 0)* U(1, 1),\n            sV(0, 0)* U(2, 1), sV(1, 0)* U(2, 1), sV(2, 0)* U(2, 1);\n\n        if (i == 3)\n            return B - A;\n        else if (i == 4)\n            return D - C;\n        else if (i == 5)\n            return F - E;\n        else if (i == 6)\n            return A + B;\n        else if (i == 7)\n            return C + D;\n        else if (i == 8)\n            return E + F;\n    }\n\n    FloatT Calc_Epsilon(int i, FloatT I2, FloatT I3)\n    {\n        return 2 * sqrtf(I2 / 3.0f) * cosf(1.0f / 3.0f * (acosf(3*I3/I2*sqrtf(3/I2)) + 2*glm::pi<FloatT>()*(i-1)));\n    }\n\n    void BuildTwistAndFlipEigenvectors(const Mat3& U, const Mat3& V, Mat9& Q)\n    {\n        static const FloatT scale = 1.0 / std::sqrt(2.0);\n        const Mat3 sV = scale * V;\n\n        using M3 = Eigen::Matrix<FloatT, 3, 3, Eigen::ColMajor>;\n\n        M3 A;\n        A << sV(0, 2) * U(0, 1), sV(1, 2)* U(0, 1), sV(2, 2)* U(0, 1),\n            sV(0, 2)* U(1, 1), sV(1, 2)* U(1, 1), sV(2, 2)* U(1, 1),\n            sV(0, 2)* U(2, 1), sV(1, 2)* U(2, 1), sV(2, 2)* U(2, 1);\n\n        M3 B;\n        B << sV(0, 1) * U(0, 2), sV(1, 1)* U(0, 2), sV(2, 1)* U(0, 2),\n            sV(0, 1)* U(1, 2), sV(1, 1)* U(1, 2), sV(2, 1)* U(1, 2),\n            sV(0, 1)* U(2, 2), sV(1, 1)* U(2, 2), sV(2, 1)* U(2, 2);\n\n        M3 C;\n        C << sV(0, 2) * U(0, 0), sV(1, 2)* U(0, 0), sV(2, 2)* U(0, 0),\n            sV(0, 2)* U(1, 0), sV(1, 2)* U(1, 0), sV(2, 2)* U(1, 0),\n            sV(0, 2)* U(2, 0), sV(1, 2)* U(2, 0), sV(2, 2)* U(2, 0);\n\n        M3 D;\n        D << sV(0, 0) * U(0, 2), sV(1, 0)* U(0, 2), sV(2, 0)* U(0, 2),\n            sV(0, 0)* U(1, 2), sV(1, 0)* U(1, 2), sV(2, 0)* U(1, 2),\n            sV(0, 0)* U(2, 2), sV(1, 0)* U(2, 2), sV(2, 0)* U(2, 2);\n\n        M3 E;\n        E << sV(0, 1) * U(0, 0), sV(1, 1)* U(0, 0), sV(2, 1)* U(0, 0),\n            sV(0, 1)* U(1, 0), sV(1, 1)* U(1, 0), sV(2, 1)* U(1, 0),\n            sV(0, 1)* U(2, 0), sV(1, 1)* U(2, 0), sV(2, 1)* U(2, 0);\n\n        M3 F;\n        F << sV(0, 0) * U(0, 1), sV(1, 0)* U(0, 1), sV(2, 0)* U(0, 1),\n            sV(0, 0)* U(1, 1), sV(1, 0)* U(1, 1), sV(2, 0)* U(1, 1),\n            sV(0, 0)* U(2, 1), sV(1, 0)* U(2, 1), sV(2, 0)* U(2, 1);\n\n        // Twist eigenvectors\n        //std::cout << \"eigenvectors before mapping\" << std::endl;\n        //std::cout << Q << std::endl;\n        //std::cout << \"B-A\" << std::endl;\n        //std::cout << B - A << std::endl;\n        Eigen::Map<M3>(Q.data()) = B - A;\n        //std::cout << \"eigenvectors after single mapping\" << std::endl;\n        //std::cout << Q << std::endl;\n        Eigen::Map<M3>(Q.data() + 9) = D - C;\n        Eigen::Map<M3>(Q.data() + 18) = F - E;\n\n        // Flip eigenvectors\n        Eigen::Map<M3>(Q.data() + 27) = A + B;\n        Eigen::Map<M3>(Q.data() + 36) = C + D;\n        Eigen::Map<M3>(Q.data() + 45) = E + F;\n    }\n\n    Mat9 CalcProjectedHessian(FloatT mu, FloatT lambda, const Mat3& F, const Mat3& U, const Mat3& V, const Vec3& S)\n    {\n        Vec9 eigenvalues;\n        Mat9 eigenvectors;\n\n        const FloatT J = F.determinant();\n\n        // Compute the twist and flip eigenvalues\n        {\n            // Twist eigenvalues\n            eigenvalues.segment<3>(0) = S;\n            // Flip eigenvalues\n            eigenvalues.segment<3>(3) = -S;\n            const FloatT evScale = lambda * (J - 1.0) - mu;\n            eigenvalues.segment<6>(0) *= evScale;\n            eigenvalues.segment<6>(0).array() += mu;\n        }\n\n        // Compute the twist and flip eigenvectors\n        BuildTwistAndFlipEigenvectors(U, V, eigenvectors);\n\n        // Compute the remaining three eigenvalues and eigenvectors\n        {\n            Mat3 A;\n            const FloatT s0s0 = S(0) * S(0);\n            const FloatT s1s1 = S(1) * S(1);\n            const FloatT s2s2 = S(2) * S(2);\n            A(0, 0) = mu + lambda * s1s1 * s2s2;\n            A(1, 1) = mu + lambda * s0s0 * s2s2;\n            A(2, 2) = mu + lambda * s0s0 * s1s1;\n            const FloatT evScale = lambda * (2.0 * J - 1.0) - mu;\n            A(0, 1) = evScale * S(2);\n            A(1, 0) = A(0, 1);\n            A(0, 2) = evScale * S(1);\n            A(2, 0) = A(0, 2);\n            A(1, 2) = evScale * S(0);\n            A(2, 1) = A(1, 2);\n\n            //std::cout << \"A\" << std::endl;\n            //std::cout << A << std::endl;\n\n            const Eigen::SelfAdjointEigenSolver<Mat3> Aeigs(A);\n            eigenvalues.segment<3>(6) = Aeigs.eigenvalues();\n\n   //         std::cout << \"u\" << std::endl;\n   //         std::cout << U << std::endl;\n\n   //         std::cout << \"v\" << std::endl;\n   //         std::cout << V << std::endl;\n\n   //         std::cout << \"A eigs\" << std::endl;\n   //         std::cout << Aeigs.eigenvalues() << std::endl;\n   //         std::cout << \"Unrotated eig vectors\" << std::endl;\n\t\t\t//std::cout << Aeigs.eigenvectors() << std::endl;\n\n   //         std::cout << \"Rotated eigen 0 matrix\" << std::endl;\n   //         std::cout << U * Aeigs.eigenvectors().col(0).asDiagonal() * V.transpose() << std::endl;\n\n   //         std::cout << \"eigenvectors before mapping\" << std::endl;\n   //         std::cout << eigenvectors << std::endl;\n            Eigen::Map<Mat3>(eigenvectors.data() + 54) = U * Aeigs.eigenvectors().col(0).asDiagonal() * V.transpose();\n            //std::cout << \"eigenvectors after single mapping\" << std::endl;\n            //std::cout << eigenvectors << std::endl;\n            Eigen::Map<Mat3>(eigenvectors.data() + 63) = U * Aeigs.eigenvectors().col(1).asDiagonal() * V.transpose();\n            Eigen::Map<Mat3>(eigenvectors.data() + 72) = U * Aeigs.eigenvectors().col(2).asDiagonal() * V.transpose();\n        }\n\n        // Clamp the eigenvalues\n        for (int i = 0; i < 9; i++)\n        {\n            //std::cout << \"lambda_\" << i << \" \" << eigenvalues(i) << std::endl;\n\n            if (eigenvalues(i) < 0.0)\n            {\n                eigenvalues(i) = 0.0;\n                //eigenvalues(i) = -eigenvalues(i);\n\n            }\n        }\n        //std::cout << \"eigenvalues\" << std::endl;\n        //std::cout << eigenvalues << std::endl;\n\n        //std::cout << \"eigenvectors\" << std::endl;\n        //std::cout << eigenvectors << std::endl;\n\n        return eigenvectors * eigenvalues.asDiagonal() * eigenvectors.transpose();\n    }\n\n    Mat3x4 CalcBm(const std::array<size_t, 4>& vertIndices, const std::vector<Vertex>& vertices)\n    {\n        std::vector<Vec3> vertices_converted;\n        glm::ivec4 tetIndices({ vertIndices[0], vertIndices[1], vertIndices[2], vertIndices[3] });\n\n        for (int i = 0; i < 4; i++)\n        {\n            const auto& pos = vertices[tetIndices[i]].mMaterialCoordinates;\n            vertices_converted.push_back(Vec3(pos.x, pos.y, pos.z));\n        }\n\n        // TODO: Eliminate this class, it is just used to get the area normal\n        class Triangle final\n        {\n        public:\n            Triangle(const Vec3& v0, const Vec3& v1, const Vec3& v2)\n                : _x0(v0)\n                , _x1(v1)\n                , _x2(v2)\n            {}\n\n            // TODO: Make this a constructor\n            static Triangle GenerateFace(const int faceNum, const glm::ivec4& tet, const std::vector<Vec3>& verts)\n            {\n                assert(faceNum >= 0); assert(faceNum < 4);\n                if (faceNum == 0)\n                {\n                    return Triangle(verts[static_cast<unsigned long>(tet[0])], verts[static_cast<unsigned long>(tet[1])], verts[static_cast<unsigned long>(tet[3])]);\n                }\n                else if (faceNum == 1)\n                {\n                    return Triangle(verts[static_cast<unsigned long>(tet[0])], verts[static_cast<unsigned long>(tet[2])], verts[static_cast<unsigned long>(tet[1])]);\n                }\n                else if (faceNum == 2)\n                {\n                    return Triangle(verts[static_cast<unsigned long>(tet[3])], verts[static_cast<unsigned long>(tet[2])], verts[static_cast<unsigned long>(tet[0])]);\n                }\n                else if (faceNum == 3)\n                {\n                    return Triangle(verts[static_cast<unsigned long>(tet[1])], verts[static_cast<unsigned long>(tet[2])], verts[static_cast<unsigned long>(tet[3])]);\n                }\n                else\n                {\n                    std::cerr << \"Error, impossible code path hit.\" << std::endl;\n                    std::exit(EXIT_FAILURE);\n                }\n            }\n\n            // TODO: Roll these into one computation\n            Vec3 normal() const\n            {\n                return ((_x1 - _x0).cross(_x2 - _x0)).normalized();\n            }\n            FloatT area() const\n            {\n                return 0.5 * ((_x1 - _x0).cross(_x2 - _x0)).norm();\n            }\n        private:\n            const Vec3& _x0;\n            const Vec3& _x1;\n            const Vec3& _x2;\n        };\n\n        Mat3x4 Bm;\n\t\tconst Triangle tri0 = Triangle::GenerateFace(0, tetIndices, vertices_converted);\n\t\tconst Triangle tri1 = Triangle::GenerateFace(1, tetIndices, vertices_converted);\n\t\tconst Triangle tri2 = Triangle::GenerateFace(2, tetIndices, vertices_converted);\n\t\tconst Triangle tri3 = Triangle::GenerateFace(3, tetIndices, vertices_converted);\n\n\t\t// Calculate the area vectors\n\t\t// v0 is incident on faces (0,1,2)\n\t\tBm.col(0) = tri0.normal() * tri0.area() + tri1.normal() * tri1.area() + tri2.normal() * tri2.area();\n\t\t// v1 is incident on faces (0,1,3)\n\t\tBm.col(1) = tri0.normal() * tri0.area() + tri1.normal() * tri1.area() + tri3.normal() * tri3.area();\n\t\t// v2 is incident on faces (1,2,3)\n\t\tBm.col(2) = tri1.normal() * tri1.area() + tri2.normal() * tri2.area() + tri3.normal() * tri3.area();\n\t\t// v3 is incident on faces (0,2,3)\n\t\tBm.col(3) = tri0.normal() * tri0.area() + tri2.normal() * tri2.area() + tri3.normal() * tri3.area();\n\t\tBm /= -3.0;\n\n        return Bm;\n    }\n\n    Eigen::VectorXf ComputePerturbedForce(const TetraGroup& group, const Eigen::VectorXf& deltaX)\n    {\n        size_t numVertices = group.mVertices.size();\n        Eigen::VectorXf globalForce = Eigen::VectorXf::Zero(3 * numVertices);\n\n        for (const auto& pair : group.mIdToTetrahedra)\n        {\n            const auto& tet = pair.second;\n\n            auto ds = Calc_Ds(tet, group.mVertices, false);\n            auto dmInv = Calc_DmInv(tet, group.mVertices);\n            auto f = Calc_F(ds, dmInv);\n\n            auto j = f.determinant();\n            auto dj_df = Calc_dj_df(f);\n            auto g_j = Reshape3x3(dj_df);\n            Mat3 dPsi_dF = group.mMu * f + (group.mLambda * (j - 1.0f) - group.mMu) * dj_df;\n\n            auto dF_dx = Calc_dFdx(dmInv);\n            auto dPsi_dx = dF_dx.transpose() * Reshape3x3(dPsi_dF);\n            Vec12 force = -tet.mRestVolume * dPsi_dx; // 12x1 atm\n\n            Eigen::JacobiSVD<Mat3, Eigen::NoQRPreconditioner> svd_f(f, Eigen::ComputeFullU | Eigen::ComputeFullV);\n            auto sigmas = svd_f.singularValues();\n            auto u = svd_f.matrixU();\n            auto v = svd_f.matrixV();\n\n            if (u.determinant() < 0.0)\n            {\n                u.col(0) *= -1.0;\n                sigmas(0) *= -1.0;\n            }\n            if (v.determinant() < 0.0)\n            {\n                v.col(0) *= -1.0;\n                sigmas(0) *= -1.0;\n            }\n\n            // Contribution to globalB\n            for (size_t i = 0; i < 4; i++)\n            {\n                auto vert_i = tet.mIndices[i];\n                globalForce(3 * vert_i + 0) += force(3 * i + 0);\n                globalForce(3 * vert_i + 1) += force(3 * i + 1);\n                globalForce(3 * vert_i + 2) += force(3 * i + 2);\n            }\n        }\n\n        return globalForce;\n    }\n\n    bool ImplicitUpdate(TetraGroup& group, float timestep, bool saveFrame, IronGames::SimulationFrame* frame, float deltaVThreshold)\n    {\n        size_t numVertices = group.mVertices.size();\n        Eigen::SparseMatrix<float> globalA(3* numVertices, 3* numVertices);\n        Eigen::VectorXf globalB = Eigen::VectorXf::Zero(3 * numVertices);\n\t\tEigen::VectorXf globalX = Eigen::VectorXf::Zero(3 * numVertices);\n        Vec12 nodeVelocities = Vec12::Zero();\n        Vec12 localB = Vec12::Zero();\n\n        Eigen::VectorXf globalForce = Eigen::VectorXf::Zero(3 * numVertices);\n        Eigen::VectorXf globalVelocities = Eigen::VectorXf::Zero(3 * numVertices);\n        Eigen::SparseMatrix<float> globalDfDx(3 * numVertices, 3 * numVertices);\n        Eigen::SparseMatrix<float> massMatrix(3 * numVertices, 3 * numVertices);\n\n        //std::cout << \"timestep \" << timestep << std::endl;\n\n        for (size_t i = 0; i < group.mVertices.size(); i++)\n        {\n            globalA.coeffRef(3 * i, 3 * i) = group.mVertices[i].mMass;\n            globalA.coeffRef(3 * i + 1, 3 * i + 1) = group.mVertices[i].mMass;\n\t\t\tglobalA.coeffRef(3 * i + 2, 3 * i + 2) = group.mVertices[i].mMass;\n        }\n\n        for (const auto& pair : group.mIdToTetrahedra)\n        {\n            const auto& tet = pair.second;\n\n            auto ds = Calc_Ds(tet, group.mVertices, false);\n            //std::cout << \"ds\" << std::endl;\n            //std::cout << ds << std::endl;\n            auto dmInv = Calc_DmInv(tet, group.mVertices);\n            //std::cout << \"dmInv\" << std::endl;\n            //std::cout << dmInv << std::endl;\n            auto f = Calc_F(ds, dmInv);\n            //std::cout << \"f\" << std::endl;\n            //std::cout << f << std::endl;\n\n            // Stable Neo-hookean potential\n\t\t\tauto j = f.determinant();\n\t\t\tauto dj_df = Calc_dj_df(f); // SEEMS OK\n            //std::cout << \"dj_df\" << std::endl;\n            //std::cout << dj_df << std::endl;\n\t\t\tauto g_j = Reshape3x3(dj_df);\n            //auto dPsi_dF = group.mMu * Reshape3x3(f) + group.mLambda * (j - 1.0f - group.mMu/group.mLambda) * g_j;\n            Mat3 dPsi_dF = group.mMu * f + (group.mLambda * (j - 1.0f) - group.mMu) * dj_df;\n            //auto elementForce = dPsi_dF * CalcBm(tet.mIndices, group.mVertices);\n\n\t\t\tauto dF_dx = Calc_dFdx(dmInv);\n            //std::cout << \"dfdx\" << std::endl;\n            //std::cout << dF_dx << std::endl;\n\t\t\tauto dPsi_dx = dF_dx.transpose() * Reshape3x3(dPsi_dF);\n\t\t\tVec12 force = -tet.mRestVolume * dPsi_dx; // 12x1 atm\n\n            //std::cout << \"Force\" << std::endl;\n            //std::cout << force << std::endl;\n            //force = -Reshape3x4(elementForce); // 12x1 atm\n\n\t\t\tauto h_j = Calc_h_j(f);\n            //std::cout << \"h_j\" << std::endl;\n            //std::cout << h_j << std::endl;\n            //std::cout << \"g_j * g_j^T\" << std::endl;\n            //std::cout << (g_j * g_j.transpose()) << std::endl;\n\t\t\t//Mat9 dPsi2_dF2 = group.mMu * Mat9::Identity() + group.mLambda * (j - 1.0f - group.mMu / group.mLambda) * h_j + group.mLambda * g_j * g_j.transpose();\n            \n            Eigen::JacobiSVD<Mat3, Eigen::NoQRPreconditioner> svd_f(f, Eigen::ComputeFullU | Eigen::ComputeFullV);\n            auto sigmas = svd_f.singularValues();\n            auto u = svd_f.matrixU();\n            auto v = svd_f.matrixV();\n\n            if (u.determinant() < 0.0)\n            {\n                u.col(0) *= -1.0;\n                sigmas(0) *= -1.0;\n            }\n            if (v.determinant() < 0.0)\n            {\n                v.col(0) *= -1.0;\n                sigmas(0) *= -1.0;\n            }\n\n            auto dPsi2_dF2 = CalcProjectedHessian(group.mMu, group.mLambda, f, u, v, sigmas);\n\n\t\t\tauto dfdx = Calc_dfdx(dF_dx, dPsi2_dF2, tet.mRestVolume);\n\n            //std::cout << \"dfdx\" << std::endl;\n            //std::cout << dfdx << std::endl;\n\n            // Contribution to globalA\n            // 12 x 12 matrix df/dx\n            // the force on one of the 4 vertices is a 3-vector\n            // the derivative of that with respect to the spatial coordinates of all four node spatial coordinates should give me a 3x12 matrix (?)\n            // then we have that for each of the nodes\n            // and we get a 12x12\n            // so a single element tells me how the force in coordinate (x,y,z) on node i changes with respect to the (x,y,z) position of node j, makes sense\n            // and a 3x3 block tells me how the force on node i changes with respect to the position of node j\n            // so it's probably easier to consider the global matrix as n x n where elements are 3x3 rather than 3n x 3n with scalar elements.\n            for (size_t i = 0; i < 4; i++)\n            {\n                auto vert_i = tet.mIndices[i];\n\n                for (size_t j = 0; j < 4; j++)\n                {\n                    auto vert_j = tet.mIndices[j];\n\n                    // we want to set a 3x3 block in globalA here from (3*vertId to 3*vertId + 2, 3*otherVertId to 3*otherVertId + 2)\n                    // and we should draw from (3*i to 3*i + 2, 3*j to 3*j + 2)\n                    for (size_t sub_i = 0; sub_i < 3; sub_i++)\n                    {\n                        for (size_t sub_j = 0; sub_j < 3; sub_j++)\n                        {\n                            globalA.coeffRef(3 * vert_i + sub_i, 3 * vert_j + sub_j) -= timestep * timestep * dfdx(3 * i + sub_i, 3 * j + sub_j);\n                            globalDfDx.coeffRef(3 * vert_i + sub_i, 3 * vert_j + sub_j) += dfdx(3 * i + sub_i, 3 * j + sub_j);\n                        }\n                    }\n                }\n            }\n            \n            for (size_t i = 0; i < 4; i++)\n            {\n                nodeVelocities(3 * i + 0) = group.mVertices[tet.mIndices[i]].mVelocity.x;\n                nodeVelocities(3 * i + 1) = group.mVertices[tet.mIndices[i]].mVelocity.y;\n                nodeVelocities(3 * i + 2) = group.mVertices[tet.mIndices[i]].mVelocity.z;\n            }\n\n            localB = timestep * force + timestep * timestep * dfdx * nodeVelocities;\n\n            if (isnan(localB.norm()))\n                throw std::exception(\"nan detected in local forces\");\n\n            // Contribution to globalB\n            for (size_t i = 0; i < 4; i++)\n            {\n                auto vert_i = tet.mIndices[i];\n                globalB(3 * vert_i + 0) += localB(3 * i + 0);\n                globalB(3 * vert_i + 1) += localB(3 * i + 1);\n                globalB(3 * vert_i + 2) += localB(3 * i + 2);\n\n                globalForce(3 * vert_i + 0) += force(3 * i + 0);\n                globalForce(3 * vert_i + 1) += force(3 * i + 1);\n                globalForce(3 * vert_i + 2) += force(3 * i + 2);\n            }\n        }\n\n        // Apply additional per-node forces\n        for (int i = 0; i < group.mVertices.size(); i++)\n        {\n            // Gravity\n            globalB(3 * i + 1) += -9.8 * timestep * group.mVertices[i].mMass;\n\n            // Collision forces\n            //globalB(3 * i + 0) += group.mVertices[i].mForce.x;\n            //globalB(3 * i + 1) += group.mVertices[i].mForce.y;\n            //globalB(3 * i + 2) += group.mVertices[i].mForce.z;\n        }\n\n        if (isnan(globalA.norm()))\n            throw std::exception(\"Nan detected.\");\n\n        if (isnan(globalB.norm()))\n            throw std::exception(\"Nan detected.\");\n\n        //{\n        //    auto denseGlobalA = globalA.toDense();\n\n        //    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> solver(denseGlobalA);\n        //    auto eigs = solver.eigenvalues();\n        //    auto minVal = 1000.0f;\n        //    for (int i = 0; i < eigs.size(); i++)\n        //        minVal = std::min(minVal, eigs[i]);\n\n        //    if (minVal < 0)\n        //    {\n        //        std::cout << \"Timestep : \" << timestep << std::endl;\n        //        std::cout << \"Negative eig\" << std::endl;\n        //    }\n        //}\n\n        //std::cout << \"globalA\" << std::endl;\n        //std::cout << globalA << std::endl;\n\n        //std::cout << \"globalB\" << std::endl;\n        //std::cout << globalB << std::endl;\n\n        // PCG Solver\n        {\n            Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower | Eigen::Upper> solver;\n            solver.compute(globalA);\n\n            globalX = solver.solve(globalB);\n            if (isnan(solver.error()))\n                throw std::exception(\"Solver failed.\");\n\n            //std::cout << \"globalX\" << std::endl;\n            //std::cout << globalX << std::endl;\n            //std::cout << \"globalX inf norm: \" << globalX.lpNorm<Eigen::Infinity>() << std::endl;\n            //if (globalX.lpNorm<Eigen::Infinity>() > deltaVThreshold)\n            //    return false;\n            // lets see, make the threshold value here 1\n\n            std::string solverInfo;\n            if (solver.info() == 0)\n                solverInfo = std::string(\"Success\");\n            else if (solver.info() == 1)\n                solverInfo = std::string(\"Numerical issue\");\n            else if (solver.info() == 2)\n                solverInfo = std::string(\"No convergence\");\n            else if (solver.info() == 3)\n                solverInfo = std::string(\"Invalid input\");\n\n            if (solver.info() != 0)\n\t\t\t\tstd::cout << \"Solver info : \" << solverInfo << std::endl;\n        }\n\n        // Check error against nonlinear equation\n        {\n            for (int i = 0; i < numVertices; i++)\n            {\n                globalVelocities(3 * i + 0) = group.mVertices[i].mVelocity[0];\n                globalVelocities(3 * i + 1) = group.mVertices[i].mVelocity[1];\n                globalVelocities(3 * i + 2) = group.mVertices[i].mVelocity[2];\n                massMatrix.coeffRef(3 * i, 3 * i) = 1.0/group.mVertices[i].mMass;\n                massMatrix.coeffRef(3 * i + 1, 3 * i + 1) = 1.0/group.mVertices[i].mMass;\n                massMatrix.coeffRef(3 * i + 2, 3 * i + 2) = 1.0/group.mVertices[i].mMass;\n            }\n\n            // dv = h M^-1 (f0 + df/dx * dx)\n            auto dx = timestep * (globalVelocities + globalX);\n            auto perturbedForce = ComputePerturbedForce(group, dx);\n            auto residual = timestep * massMatrix * perturbedForce - globalX;\n            // this isn't the nonlinear eq. unfortunately, we'd need to evaluate the force with new position\n            // to get that\n            std::cout << \"timestep: \" << timestep << std::endl;\n            std::cout << \"infinity error: \" << residual.lpNorm<Eigen::Infinity>() << std::endl;\n            std::cout << \"l2 error: \" << residual.norm() << std::endl;\n            if (residual.lpNorm<Eigen::Infinity>() > 10.0)\n            {\n                return false;\n            }\n        }\n\n        // SparseLU Solver\n        //{\n        //    Eigen::SparseLU<Eigen::SparseMatrix<float>, Eigen::COLAMDOrdering<int> >   solver;\n        //    solver.analyzePattern(globalA);\n        //    solver.factorize(globalA);\n        //    globalX = solver.solve(globalB);\n\n        //    if (isnan(globalX.norm()))\n        //        throw std::exception(\"Solver failed.\");\n        //}\n\n        // Integrate\n        for (int i = 0; i < group.mVertices.size(); i++)\n        {\n            auto& vertex = group.mVertices[i];\n            auto deltaV = glm::dvec3(globalX(3 * i + 0), globalX(3 * i + 1), globalX(3 * i + 2));\n\n            if (saveFrame)\n            {\n                auto& vert = *frame->mutable_vertices(i);\n                *vert.mutable_force() = ProtoConverter::Convert(deltaV);\n            }\n\n            vertex.mVelocity += deltaV;\n            vertex.mPosition += (double)timestep * vertex.mVelocity;\n        }\n\n        return true;\n\n        // things to try:\n        // - 'solveWithGuess' and providing the previous timestep's change in velocities as the guess?\n        // - other preconditioners, solvers\n        // - the doc's have globalX = solver.solve(globalB) twice, so maybe it tries for a specified number of\n        //   iterations each time and refines the solution.. ?\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "6cad84faa8a001db2c34d076ee7ea1acb8d78f21", "size": 34414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/ImplicitIntegrator.cpp", "max_stars_repo_name": "claytonkanderson/Fractus", "max_stars_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_stars_repo_licenses": ["MIT"], "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/ImplicitIntegrator.cpp", "max_issues_repo_name": "claytonkanderson/Fractus", "max_issues_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_issues_repo_licenses": ["MIT"], "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/ImplicitIntegrator.cpp", "max_forks_repo_name": "claytonkanderson/Fractus", "max_forks_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_forks_repo_licenses": ["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.7733887734, "max_line_length": 165, "alphanum_fraction": 0.4711164061, "num_tokens": 11921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.6641232598922512}}
{"text": "#include \"alpha.h\"\n\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <numeric>\n\n#include \"operationVector.h\" // ceci va chercher le fichier qui contient les operations sur les vecteurs\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nmatrix<double> Alpha(matrix<double> Obs, matrix<double> M, std::vector<double> pie) {\n\n// \tObs est la matrice des observations\n// \tM est la matrice de transition\n// \tpie est le vecteur de probabilite initiale\n\n\tconst int m = Obs.size2(); // Nombre detat, de cases\n\tconst int n = Obs.size1(); // Nombre dobservation, duree de la partie\n\n//\tmatrix Alpha = matrix(NbLigne= n, NbCol= m);  Initialisation de la matric Alpha de tailler n*m\n\tmatrix<double> matAlpha(n, m);\n\tauto alph = std::vector<double>(m, 0); // Declaration d'un vecteur de longueur m remplie de 0\n\n\tfor (int i = 0; i < m; ++i) {\n\t\talph[i] = pie[i] * Obs(0, i);\n\t}\n\n\tdouble log1surc = log(sum(alph)); // J'ai ajouter la fonction sum, qui fait la somme d'une matrice ou d'un vecteur\n\n// \talph = alph * (1 / std::accumulate(alph.begin(), alph.end(), 0));\n\talph = scalarMultiplication(alph, 1.0 / sum(alph));\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tmatAlpha(0, i) = log(alph[i]) + log1surc;\n\t}\n\n\tauto Alph = matrix<double>(1, m);\n\n\tfor (int i = 0 ; i < m ; ++i) {\n\t\tAlph(0, i) = alph[i];\n\t}\n\t\n\tfor (int i = 1; i < n ; ++i) { // J'ai changer la partie \"i < n, ++j\" pour \"i < n ; ++i\"\n\t\t\n\t\tAlph = prod(Alph, M); // prod est le produit matriciel\n\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tAlph(0, j) = Alph(0, j) * Obs(i, j);\n\t\t}\n\n\t\tlog1surc += log(sum(Alph));\n\t\tAlph /= sum(Alph);\n\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tmatAlpha(i, j) = log(Alph(0, j)) + log1surc;\n\t\t}\n\n\t}\n\t\n\treturn matAlpha;\n\n}\n", "meta": {"hexsha": "e68a60383be704e37df543d17697159845d30143", "size": 1707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha.cpp", "max_stars_repo_name": "Louis-Alexandre/Captain-Markov", "max_stars_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-29T09:47:49.000Z", "max_issues_repo_path": "src/alpha.cpp", "max_issues_repo_name": "Louis-Alexandre/Captain-Markov", "max_issues_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_issues_repo_licenses": ["MIT"], "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/alpha.cpp", "max_forks_repo_name": "Louis-Alexandre/Captain-Markov", "max_forks_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_forks_repo_licenses": ["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.671875, "max_line_length": 115, "alphanum_fraction": 0.618629174, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6641216228382633}}
{"text": "// The template and inlines for the -*- C++ -*- finite field classes.\n// Initially implemented by Wai-Shing Luk <luk036@gmail.com>\n//\n\n/** @file include/GF.hpp\n *  This is a C++ Library header.\n */\n\n#ifndef FUN_GF_HPP\n#define FUN_GF_HPP 1\n\n#include <boost/operators.hpp>\n#include <cassert>\n\nnamespace fun {\n/**\n * @defgroup GF Finite (Galois) Field\n * @ingroup arithmetic\n *\n * Classes and functions for (extended) finite field.\n * @{\n */\n\n// Forward declarations.\ntemplate <unsigned int _p> struct GF;\n\n/**\n *  finite (Galois) field.\n *\n *  @param  p  Prime number\n */\ntemplate <unsigned int _p = 3> struct GF : boost::field_operators<GF<_p>> {\n  /// Default constructor.\n  constexpr GF() noexcept : _m(0) {}\n\n  ///  Unspecified parameters default to 0.\n  explicit GF(unsigned int m) noexcept : _m(m) { assert(_m < _p); }\n\n  // Lets the compiler synthesize the copy constructor\n  // GF (const GF<_p>&);\n  /// Copy constructor\n  GF(const GF<_p> &s) noexcept : _m(s.value()) { assert(_m >= 0); }\n\n  /// Return internal element of finite field.\n  constexpr unsigned int value() const noexcept { return _m; }\n\n  // Lets the compiler synthesize the assignment operator\n  // GF<_p>& operator= (const GF<_p>&);\n  /// Assign this finite field to finite field @a s.\n  GF<_p> &operator=(const GF<_p> &s) {\n    _m = s.value();\n    return *this;\n  }\n\n  /// Add @a s to this finite field.\n  GF<_p> &operator+=(const GF<_p> &s) {\n    _m += s.value();\n    _m %= _p;\n    assert(_m < _p);\n    return *this;\n  }\n\n  /// Subtract @a s from this finite field.\n  GF<_p> &operator-=(const GF<_p> &s) {\n    _m += _p - s.value();\n    _m = _m % _p;\n    assert(_m < _p);\n    return *this;\n  }\n\n  /// Multiply @a s to this finite field.\n  GF<_p> &operator*=(const GF<_p> &s) {\n    _m *= s.value();\n    _m %= _p;\n    assert(_m < _p);\n    return *this;\n  }\n\nprivate:\n  unsigned int _m;\n};\n\n// Operators:\n///  Return new finite field @a r plus @a s.\ntemplate <unsigned int _p> inline GF<_p> operator+(GF<_p> r, const GF<_p> &s) {\n  return r += s;\n}\n\n///  Return new finite field @a r minus @a s.\ntemplate <unsigned int _p> inline GF<_p> operator-(GF<_p> r, const GF<_p> &s) {\n  return r -= s;\n}\n\n//@{\n///  Return new finite field @a r times @a a.\ntemplate <unsigned int _p> inline GF<_p> operator*(GF<_p> r, const GF<_p> &s) {\n  return r *= s;\n}\n//@}\n\n/// Return @a r.\ntemplate <unsigned int _p>\ninline constexpr GF<_p> operator+(const GF<_p> &r) noexcept {\n  return r;\n}\n\n/// Return negation of @a r\ntemplate <unsigned int _p> inline GF<_p> operator-(const GF<_p> &r) {\n  if (r.value() == 0)\n    return r;\n  return GF<_p>(_p - r.value());\n}\n\n/// Return true if @a r is equal to @a s.\ntemplate <unsigned int _p>\ninline constexpr bool operator==(const GF<_p> &r, const GF<_p> &s) noexcept {\n  return r.value() == s.value();\n}\n\n/// Return false if @a r is equal to @a s.\ntemplate <unsigned int _p>\ninline constexpr bool operator!=(const GF<_p> &r, const GF<_p> &s) noexcept {\n  return !(r == s);\n}\n\n///  Insertion operator for finite field values.\ntemplate <unsigned int _p, class _Stream>\n_Stream &operator<<(_Stream &os, const GF<_p> &r) {\n  os << '(' << r.value() << \" mod \" << _p << ')';\n  return os;\n}\n}\n\n#endif\n", "meta": {"hexsha": "6474c018ce0253d0c7860aae09c205ae5ca03d95", "size": 3185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/fun/GF.hpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "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/fun/GF.hpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "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/include/fun/GF.hpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["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.5925925926, "max_line_length": 79, "alphanum_fraction": 0.6163265306, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6641216066518806}}
{"text": "/** @file\n * @ingroup utils\n *\n * Utility mathematical functions that do not fit anywhere else.\n *\n * The type definitions are shorthands for declaring `Eigen::Vector`,\n * `Eigen::Matrix` and `Eigen::Quaternion` objects. At current we assume all\n * slam code development will be using double precision floating points.\n */\n\n#ifndef WAVE_UTILS_MATH_HPP\n#define WAVE_UTILS_MATH_HPP\n\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n\nnamespace wave {\n/** @addtogroup utils\n *  @{ */\n\n#ifndef EIGEN_TYPEDEF\n#define EIGEN_TYPEDEF\ntypedef Eigen::Matrix<double, 1, 1> Vec1;\ntypedef Eigen::Vector2d Vec2;\ntypedef Eigen::Vector3d Vec3;\ntypedef Eigen::Vector4d Vec4;\ntypedef Eigen::Matrix<double, 5, 1> Vec5;\ntypedef Eigen::Matrix<double, 6, 1> Vec6;\ntypedef Eigen::Matrix<double, 12, 1> Vec12;\ntypedef Eigen::VectorXd VecX;\n\ntypedef Eigen::Matrix2d Mat2;\ntypedef Eigen::Matrix3d Mat3;\ntypedef Eigen::Matrix4d Mat4;\ntypedef Eigen::Matrix<double, 5, 5> Mat5;\ntypedef Eigen::Matrix<double, 6, 6> Mat6;\ntypedef Eigen::Matrix<double, 12, 12> Mat12;\ntypedef Eigen::MatrixXd MatX;\n\ntypedef Eigen::Matrix<double, 3, 4> Mat34;\n\ntypedef Eigen::Matrix<float, 1, 1> Vec1f;\ntypedef Eigen::Vector2f Vec2f;\ntypedef Eigen::Vector3f Vec3f;\ntypedef Eigen::Vector4f Vec4f;\ntypedef Eigen::Matrix<float, 5, 1> Vec5f;\ntypedef Eigen::Matrix<float, 6, 1> Vec6f;\ntypedef Eigen::Matrix<float, 12, 1> Vec12f;\ntypedef Eigen::VectorXf VecXf;\n\ntypedef Eigen::Matrix2f Mat2f;\ntypedef Eigen::Matrix3f Mat3f;\ntypedef Eigen::Matrix4f Mat4f;\ntypedef Eigen::Matrix<float, 5, 5> Mat5f;\ntypedef Eigen::Matrix<float, 6, 6> Mat6f;\ntypedef Eigen::Matrix<float, 12, 12> Mat12f;\ntypedef Eigen::MatrixXf MatXf;\n\ntypedef Eigen::Matrix<float, 3, 4> Mat34f;\n\ntypedef Eigen::Affine3d Affine3;\n\ntypedef Eigen::Quaterniond Quaternion;\n#endif\n\n/**\n * Eigen vector comparator\n */\nstruct VecComparator {\n    bool operator()(const VecX &a, const VecX &b) const {\n        return std::lexicographical_compare(\n          a.data(), a.data() + a.size(), b.data(), b.data() + b.size());\n    }\n};\n\n/**\n * Eigen matrix comparator\n */\nstruct MatComparator {\n    bool operator()(const MatX &a, const MatX &b) const {\n        return std::lexicographical_compare(\n          a.data(), a.data() + a.size(), b.data(), b.data() + b.size());\n    }\n};\n\n/** Generates random integer with a upper bound `ub` and lower bound `lb` using\n * a uniform random distribution. */\nint randi(int ub, int lb);\n\n/** Generates random float with a upper bound `ub` and lower bound `lb` using a\n * uniform random distribution. */\ndouble randf(double ub, double lb);\n\n/** Compares two floating point numbers `f1` and `f2` with an error threshold\n * defined by `threshold`.\n * @return\n * - `0`: If `f1` == `f2` or the difference is less then `threshold`\n * - `1`: If `f1` > `f2`\n * - `-1`: If `f1` < `f2`\n */\nint fltcmp(double f1, double f2, double threshold = 0.0001);\n\n/** @return the median of `v`. */\ndouble median(std::vector<double> v);\n\n/** Converts degrees to radians. */\ndouble deg2rad(double d);\n\n/** Converts radians to degrees. */\ndouble rad2deg(double r);\n\n/** Reshapes a vector `x` to matrix `y` of size `rows` and `cols` */\nvoid vec2mat(std::vector<double> x, int rows, int cols, MatX &y);\n\n/** Reshapes a matrix to a vector*/\nvoid mat2vec(MatX A, std::vector<double> &x);\n\n/** Wraps `euler_angle` to 180 degrees **/\ndouble wrapTo180(double euler_angle);\n\n/** Wraps `euler_angle` to 360 degrees **/\ndouble wrapTo360(double euler_angle);\n\n/** Convert euler angle to rotation matrix **/\nint euler2rot(Vec3 euler, int euler_seq, Mat3 &R);\n\n/** Convert euler angle to quaternion **/\nint euler2quat(Vec3 euler, int euler_seq, Quaternion &q);\n\n/** Convert quaternion to euler angles **/\nint quat2euler(Quaternion q, int euler_seq, Vec3 &euler);\n\n/** Convert quaternion to rotation matrix **/\nint quat2rot(Quaternion q, Mat3 &R);\n\n/** ENU to NWU coordinate system **/\nvoid enu2nwu(const Vec3 &enu, Vec3 &nwu);\n\n/** NED to ENU coordinate system **/\nvoid ned2enu(const Vec3 &ned, Vec3 &enu);\n\n/** NED to NWU coordinate system **/\nvoid ned2nwu(const Quaternion &ned, Quaternion &enu);\n\n/** NWU to ENU coordinate system **/\nvoid nwu2enu(const Vec3 &nwu, Vec3 &enu);\n\n/** NWU to NED coordinate system **/\nvoid nwu2ned(const Quaternion &nwu, Quaternion &ned);\n\n/** NWU to EDN coordinate system **/\nvoid nwu2edn(const Vec3 &nwu, Vec3 &edn);\n\n/** @} group utils */\n}  // namespace wave\n\n#endif  // WAVE_UTILS_MATH_HPP\n", "meta": {"hexsha": "1ce58806ec9d28c6de443d33dbd0c845fbb55c11", "size": 4458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 27.5185185185, "max_line_length": 79, "alphanum_fraction": 0.6982951996, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.664121604764689}}
{"text": "\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n\nnamespace ublas = boost::numeric::ublas;\n/* Matrix inversion routine.\n   Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\n\nbool InvertMatrix (const ublas::matrix<double>& input, ublas::matrix<double>& inverse)\n{\n  using namespace boost::numeric::ublas;\n  typedef permutation_matrix<std::size_t> pmatrix;\n  // create a working copy of the input\n  matrix<double> A(input);\n  // create a permutation matrix for the LU-factorization\n  pmatrix pm(A.size1());\n  // perform LU-factorization\n  int res = lu_factorize(A,pm);\n  if( res != 0 ) return false;\n  // create identity matrix of \"inverse\"\n  inverse.assign(ublas::identity_matrix<double>(A.size1()));\n  // backsubstitute to get the inverse\n  lu_substitute(A, pm, inverse);\n  return true;\n}\n\n\nbool InvertMatrixGen(const ublas::matrix<double>& input, ublas::matrix<double>& inverse)\n{\n  const int n = input.size1();\n  gsl_matrix *A = gsl_matrix_alloc(n,n);\n  gsl_matrix *V = gsl_matrix_alloc(n,n);\n  gsl_vector *S = gsl_vector_alloc(n);\n  gsl_vector *work = gsl_vector_alloc(n);\n\n  for(int i = 0; i < n; ++i) {\n    for(int j = 0; j < n; ++j) {\n      gsl_matrix_set(A,i,j,input(i,j));\n      inverse(i,j) = 0.0;\n    }\n  }\n\n  gsl_linalg_SV_decomp(A,V,S,work);\n\n  const double smax = gsl_vector_get(S,0);\n  for(int k = 0; k < n; ++k) {\n    const double s = gsl_vector_get(S,k);\n    if(s/smax > 1.0e-8) {\n      for(int i = 0; i < n; ++i) {\n\tfor(int j = 0; j < n; ++j) {\n\t  inverse(i,j) += gsl_matrix_get(V,i,k) * gsl_matrix_get(A,j,k) / s;\n\t}\n      }\n    }\n  }\n\n  gsl_matrix_free(A);\n  gsl_matrix_free(V);\n  gsl_vector_free(S);\n  gsl_vector_free(work);\n  return true;\n}\n", "meta": {"hexsha": "9810d6ae1f4d11a5f7eead0f617c517e46c268cf", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/InvertMatrix.cpp", "max_stars_repo_name": "arkinjo/lgm_mc", "max_stars_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/InvertMatrix.cpp", "max_issues_repo_name": "arkinjo/lgm_mc", "max_issues_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": "src/InvertMatrix.cpp", "max_forks_repo_name": "arkinjo/lgm_mc", "max_forks_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "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": 27.7323943662, "max_line_length": 88, "alphanum_fraction": 0.6724225495, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6640606411609803}}
{"text": "#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <iostream>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>           Traits;\ntypedef Traits::FT                                                              NT;\ntypedef Traits::Point_2                                                         Point;\ntypedef Traits::Circle_2                                                        Circle;\ntypedef Traits::Euclidean_line_2                                                Line;\ntypedef Traits::Construct_intersection_2                                        Construct_intersection_2;\n\nint main(int /*argc*/, char** /*argv*/)\n{\n  NT F2(2);\n\n  Line ell1(NT(1),  sqrt(F2 - sqrt(F2)), NT(0));\n  Line ell2(NT(1), -sqrt(F2 + sqrt(F2)), NT(0));\n\n  // In the Poincar\u00e9 disk, all Euclidean lines pass through the origin\n  NT sx = NT(0);\n  NT sy = NT(0);\n  Point sol(sx, sy);\n\n  Point p = Construct_intersection_2()(ell1, ell2);\n  std::cout << \"line-line intersection: \" << p << \", solution is: \" << sol << std::endl;\n  assert(p == sol);\n  std::cout << \"The solution is exact!\" << std::endl;\n\n  Point pc1(NT(2)/NT(10), NT(5)/NT(10));\n  Point pc2(-NT(3)/NT(10), NT(15)/NT(100));\n  Point pc3(NT(20)/NT(29), NT(50)/NT(29));\n  Circle c1(pc1, pc2, pc3);\n  std::pair<Point, Point> ipt = Construct_intersection_2()(ell1, c1);\n  Point ip1 = ipt.first, ip2 = ipt.second;\n\n  NT sq(sqrt(NT(2)));\n  NT nsq( sqrt( NT(2) - sqrt(NT(2)) ) );\n  NT sol1x( nsq*(NT(2438)+NT(1451)*nsq-sqrt(NT(3933846)-NT(31801)*sq+NT(7075076)*nsq))/(-NT(4320)+NT(1440)*sq) );\n  NT sol1y( (-NT(2438)-NT(1451)*nsq+sqrt(NT(3933846)-NT(31801)*sq+NT(7075076)*nsq))/(-NT(4320)+NT(1440)*sq) );\n  Point solution1(sol1x, sol1y);\n\n  std::cout << \"Intersection of circle and line: \" << ip1 << \" and \" << ip2 << std::endl;\n  std::cout << \"Solution: \" << solution1 << std::endl;\n  assert(ip1 == solution1 || ip2 == solution1);\n  std::cout << \"The solution is exact!\" << std::endl;\n\n  Point pc4(NT(2)/NT(10), -NT(15)/NT(100));\n  Circle c2(pc1, pc4, pc3);\n\n  std::pair<Point, Point> cpt = Construct_intersection_2()(c1, c2);\n  ip1 = cpt.first;\n  ip2 = cpt.second;\n  std::cout << \"Intersection of circles: \" << ip1 << \" and \" << ip2 << std::endl;\n  assert(ip1 == pc1 || ip2 == pc1);\n  std::cout << \"The solution is exact!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "38648d8603ab3b464722c68c6018ad0191e4fc94", "size": 2571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.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": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.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": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.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.5538461538, "max_line_length": 113, "alphanum_fraction": 0.5877090626, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6640606231658388}}
{"text": "/*\n * DataSet.cpp\n *\n *  Created on: 2014/06/11\n *      Author: kryozahiro\n */\n\n#include \"DataSet.h\"\n\n#include <cfloat>\n#include <boost/lexical_cast.hpp>\n#include \"cpputil/GenericIo.h\"\nusing namespace std;\nusing namespace cpputil;\n\nstd::vector<double> DataSet::nguyen(int dimension, const std::vector<double>& input) {\n\tvector<double> output(1, 0);\n\tfor (int i = 1; i <= dimension; ++i) {\n\t\toutput[0] += pow(input[0], (double)i);\n\t}\n\treturn output;\n}\n\nstd::vector<double> DataSet::rosenbrock(const std::vector<double>& input) {\n\tvector<double> output(1, 0);\n\tfor (unsigned int i = 0; i < input.size() - 1; ++i) {\n\t\toutput[0] += 100.0 * pow(input[i + 1] - input[i] * input[i], 2.0) + pow(input[i] - 1.0, 2.0);\n\t}\n\treturn output;\n}\n\nstd::vector<double> DataSet::schwefel(const std::vector<double>& input) {\n\tvector<double> output(1, 418.9829 * input.size());\n\tfor (unsigned int i = 0; i < input.size(); ++i) {\n\t\toutput[0] -= input[i] * sin(sqrt(abs(input[i])));\n\t}\n\treturn output;\n}\n\nstd::vector<double> DataSet::sphere(const std::vector<double>& input) {\n\tvector<double> output(1, 0);\n\tfor (unsigned int i = 0; i < input.size(); ++i) {\n\t\toutput[0] += input[i] * input[i];\n\t}\n\treturn output;\n}\n\nstd::vector<double> DataSet::threeHumpCamel(const std::vector<double>& input) {\n\tvector<double> output(1, 0);\n\toutput[0] = 2.0*input[0]*input[0] - 1.05*pow(input[0], 4.0) + pow(input[0], 6.0)/6.0 + input[0]*input[1] + input[1]*input[1];\n\treturn output;\n}\n\nDataSet::DataSet() {\n}\n\nDataSet::DataSet(const ProgramType& programType) : programType(programType) {\n}\n\nDataSet::DataSet(const boost::property_tree::ptree& dataTree, mt19937_64& randomEngine) {\n\tstring name = dataTree.get<string>(\"Name\");\n\tint dimension = dataTree.get<int>(\"Dimension\");\n\tint size = dataTree.get<int>(\"Size\");\n\tif (name.find(\"Nguyen\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-1, 1, 0.001, 1), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, [=](const vector<double>& input) {\n\t\t\treturn nguyen(dimension, input);\n\t\t});\n\t} else if (name.find(\"Rosenbrock\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5, 10, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, rosenbrock);\n\t} else if(name.find(\"Schwefel\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-500, 500, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, schwefel);\n\t} else if (name.find(\"Sphere\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5.12, 5.12, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, sphere);\n\t} else if (name.find(\"ThreeHumpCamel\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5, 5, 0.001, 2), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, threeHumpCamel);\n\t} else {\n\t\tassert(false);\n\t}\n}\n\nconst ProgramType& DataSet::getProgramType() const {\n\treturn programType;\n}\n\nint DataSet::getSize() const {\n\treturn data.size();\n}\n\npair<vector<double>, vector<double>>& DataSet::operator[](int i) {\n\treturn data[i];\n}\n\nconst pair<vector<double>, vector<double>>& DataSet::operator[](int i) const {\n\treturn data[i];\n}\n\nvector<double>& DataSet::getInput(int i) {\n\treturn data[i].first;\n}\n\nvector<double>& DataSet::getOutput(int i) {\n\treturn data[i].second;\n}\n\nvoid DataSet::addData(const vector<double>& input, const vector<double>& output) {\n\tdata.push_back(make_pair(input, output));\n}\n\nstring DataSet::toString() const {\n\tstring ret = \"DataSet\\n\";\n\tfor (const pair<vector<double>, vector<double>>& point : data) {\n\t\tret += boost::lexical_cast<string>(point) + \"\\n\";\n\t}\n\treturn ret;\n}\n", "meta": {"hexsha": "14904c4ed0466610a8f672d47c8f0a42d72b01ed", "size": 3638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/problem/DataSet.cpp", "max_stars_repo_name": "kryozahiro/gamesolver", "max_stars_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "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": "gamesolver/problem/DataSet.cpp", "max_issues_repo_name": "kryozahiro/gamesolver", "max_issues_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "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": "gamesolver/problem/DataSet.cpp", "max_forks_repo_name": "kryozahiro/gamesolver", "max_forks_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-06T16:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T16:06:10.000Z", "avg_line_length": 30.0661157025, "max_line_length": 126, "alphanum_fraction": 0.6676745465, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.664017425112838}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\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_AVERAGE_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_AVERAGE_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n                  {\n\n /*!\n    @ingroup group-arithmetic\n    Function object implementing average capabilities\n\n    Computes the arithmetic mean of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = average(x, y);\n    @endcode\n\n    For floating point values the code is equivalent to:\n\n    @code\n    T r = (x+y)/T(2);\n    @endcode\n\n    for integer types  it returns a rounded value at a distance guaranteed\n    less or equal to 0.5 of the average floating value,  but can differ\n    of one unity from the truncation given by (x1+x2)/T(2).\n\n    @par Note:\n\n    This function does not overflow.\n\n    @see meanof\n\n  **/\n  const boost::dispatch::functor<tag::average_> average = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/average.hpp>\n#include <boost/simd/function/simd/average.hpp>\n\n#endif\n", "meta": {"hexsha": "c92e1091cfc740fe8b8b8651f27593e04d3ef76d", "size": 1434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/average.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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/simd/function/average.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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/average.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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.1578947368, "max_line_length": 100, "alphanum_fraction": 0.5948396095, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6640174240835128}}
{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <vector>\nusing namespace std;\n\n/**********************************************************\n\nThis is the program for the bifurcation diagram! :D\nThe flow is simple: For each r value between 1 and 4 (with\nresolution of dr), 100 values of the logistic map are saved\nin the solutions vector. The values are chosen far enough\naway from the origin to remove the effects of the initial\nbehavior. The values are paired with the r value they were\ncalculated at and then sent to the plotter.\n\n**********************************************************/\n\nconst int START = 900;\nconst int CUTOFF = 1000;\t// Cutoff value for finding attractors\nconst double dr = 0.001;\nconst double x0 = 0.5;\t\t// Initial value\n\nvoid plotStuff(vector<double> x, vector<double> y){\t// Pretty plotting shenanigans\n\tGnuplot gp;\n\n\tgp << \"set xrange [1:4]\\n\";\n\tgp << \"set yrange [0:1]\\n\";\n\tgp << \"set term wxt font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"End Behavior of the Logistic Function vs. Growth Rate (x_0 = 0.5)\\\"\\n\";\n\tgp << \"set xlabel \\\"r\\\"\\n\";\n\tgp << \"set ylabel \\\"x_n\\\"\\n\";\n\tgp << \"set output \\\"plot.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(x,y));\n}\n\nvector<double> getSolutions(double r){\n\tdouble x = x0;\t\t\t\t\t\t\t// Set up x_0\n\tvector<double> out;\t\t\t\t\t\t// All the solutions for this value of r\n\n\tfor(int i = 0; i < CUTOFF; i++){\t\t// Loop until the cutoff\n\t\tif(i >= START){out.push_back(x);}\t// Push the x value onto the vector of values, but only after a few (900) iterations to observe only the long-term behavior\n\t\tx = r*x*(1-x);\t\t\t\t\t\t// Perform the logistic map operation x_n+1 = r*x_n*(1-x_n)\n\t}\n\n\treturn out;\n}\n\nint main(){\n\tvector<double> rvals;\t\t\t\t\t// R values (there will be lots of repeats since each r value has 100 solutions)\n\tvector<double> solutions;\t\t\t\t// Solutions\n\n\tfor(double r = 1; r < 4; r += dr){\t\t// between r=1 and r=4\n\t\tvector<double> s = getSolutions(r);\t// Get the solutions for that value of r\n\n\t\tfor(int i = 0; i < s.size(); i++){\t// Go through all solutions\n\t\t\tsolutions.push_back(s[i]);\t\t// Add them to the main list\n\t\t\trvals.push_back(r);\t\t\t\t// Along with the value of r they were recorded at\n\t\t}\n\t}\n\n\tcout << \"Done with calculation!\\n\";\t\t// This is for debug\n\n\tplotStuff(rvals,solutions);\t\t\t\t// Plot it!\n}", "meta": {"hexsha": "c56229b95a41a891b6af3a0bcd75cd42e1618a7d", "size": 2376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Logistic Map/FullPlot.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/FullPlot.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/FullPlot.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": 36.0, "max_line_length": 159, "alphanum_fraction": 0.6372053872, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6639932484222074}}
{"text": "/*\n * Main.cpp\n *\n *  Created on: Nov 10, 2015\n *      Author: doncole\n */\n\n#include <stdio.h>\n#include <iostream>\n#include <Eigen>\n#include <Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nArrayXXf InitMatrix(ArrayXXf matrix);\nArrayXf InitVector(ArrayXf vector);\nArrayXXf AddRowToMatrix(ArrayXf rowA, ArrayXXf matrixU, int i);\nArrayXf AddNumBToVectorB(float numB,ArrayXf vectorB, int j);\n\n\nint main(void){\n\n\tint squareNum = 7;\t//square matrix 7x7 and vector = 7\n\n\tArrayXXf matrixA(squareNum,squareNum);\n\tArrayXXf matrixU(squareNum,squareNum);\n\tArrayXf vectorB(squareNum);\n\tArrayXf rowA(squareNum), rowB(squareNum), solutionX(squareNum);\n\tfloat numA, numB;\n\t//Init the Matrix and Vector\n\tmatrixA = InitMatrix(matrixA);\n\tvectorB = InitVector(vectorB);\n\tmatrixU = matrixA;\n\n\tcout << \"Matrix A \" << endl << matrixA << endl;\n\tcout << \"Vector B \" << endl << vectorB << endl;\n\t//Solve by G.E.\n\t//iterate squareNum-1 times\n\tfor (int i = 0; i < squareNum -1; i++)\n\t{\n\t\trowA = matrixU.row(i);\t//Get the row\n\t\tnumA = rowA[i];\t//Get the Rows first number\n\t\trowA = rowA/numA; \t//divide the row by the number\n\t\tnumB = vectorB[i]/numA;\t//divide the Vector by the number\n\t\t//numB = vectorB[i];\t//copy the number for the rest of the vector\n\n\t\tfor (int j = i+1; j< squareNum; j++)\n\t\t{\n\t\t\trowB = rowA;\t//get the beginning Row again\n//\t\t\tcout << \"Matrix U\" << endl << matrixU << endl;\t//print the Matrix out\n\t\t\t//Multiply the Row by the Next row's first Integer\n\t\t\t//get the next rows first integer\n//\t\t\tcout << \"The next Rows integer\" << matrixU.row(j)[i] << endl;\n\t\t\trowB = rowB * (-1.0) * matrixU.row(j)[i];\n\t\t\tnumB = (numB * (-1.0) * matrixU.row(j)[i]);\n//\t\t\tcout << \"The num B \" << endl << numB << endl;\n//\t\t\tcout << \"The row multiplied By\" << endl << rowB << endl;\n\t\t\t//Add the row to the next Rows\n\t\t\tmatrixU = AddRowToMatrix(rowB, matrixU, j);\t\t//add the row to the rest of the matrix\n\t\t\tvectorB = AddNumBToVectorB(numB, vectorB, j);\t//add the number to the rest of the vector\n\t\t}\n\t}\n\tsolutionX[squareNum-1] = vectorB[squareNum-1]/matrixU.row(squareNum-1)[squareNum-1];\n//\tcout << \"Solution X\" << endl << solutionX << endl;\n\n\tfor (int i = squareNum-2; i>-1; i--)\n\t{\n\t\tfloat sum = 0;\n//\t\tcout << \"VectorB\" << endl << vectorB[i] << endl;\n//\t\tmatrixU.row(i)/matrixU.row(i)[i];\n//\t\tvectorB[i] = vectorB[i]/matrixU.row(i)[i];\n//\t\tcout << \"Matrix U\" << endl << matrixU << endl;\n//\t\tcout << \"Vector B\" << endl << vectorB << endl;\n\n\t\tfor (int j = 6; j > i; j--)\n\t\t{\n\t\t\tsum = sum + matrixU.row(i)[j] * solutionX[i+1];\n\t\t\t//cout << \"sum\" << endl << sum << endl;\n\t\t}\n\t\tsolutionX[i] = (vectorB[i] - sum)/matrixU.row(i)[i];\n//\t\tcout << \"Solution X\" << endl << solutionX << endl;\n\t}\n\t//Print the outputs\n\tcout << \"Matrix U \" << endl << matrixU << endl;\n\tcout << \"Vector B \" << endl << vectorB << endl;\n\tcout << \"The Solution Matrix \" << endl << solutionX << endl;\n\n\treturn 0;\n}\n\nArrayXf AddNumBToVectorB(float numB, ArrayXf vectorB, int row)\n{\n\t//vectorB[0] = 100.0;\n\twhile (row < 7)\n\t{\n\t\tvectorB[row] = vectorB[row] + numB;\n\t\trow++;\n\t}\n\t//print the Vector\n\t//cout << \"VectorB\" << endl << vectorB << endl;\n\treturn vectorB;\n}\n\nArrayXXf AddRowToMatrix(ArrayXf rowA, ArrayXXf matrixU, int row)\n{\n\t//we need to construct the matrices\n\t//By first adding the row to the rest of the matrix\n//\tArrayXXf tempArray(7, 7);\n//\ttempArray = matrixU.array();\n\twhile (row < 7)\n\t{\n\t\t//add to the rest of the rows\n\t\tmatrixU.row(row) += rowA;\n\t\trow++;\n\t}\n\t//print the array\n\t//cout << \"MatrixU\" << endl << matrixU << endl;\n\treturn matrixU;\n}\n\n//Initialize the Given 7x7 Matrix\nArrayXXf InitMatrix(ArrayXXf matrix)\n{\n\tint i= 0, j = 0;\n\t//First Row\n\tmatrix(i, j++) = .1897;\n\tmatrix(i, j++) = .3784;\n\tmatrix(i, j++) = .6449;\n\tmatrix(i, j++) = .7271;\n\tmatrix(i, j++) = .4449;\n\tmatrix(i, j++) = .1730;\n\tmatrix(i, j++) = .0118;\n\tj = 0;\n\ti++;\n\t//Second Row\n\tmatrix(i, j++) = .1934;\n\tmatrix(i, j++) = .8600;\n\tmatrix(i, j++) = .8180;\n\tmatrix(i, j++) = .3093;\n\tmatrix(i, j++) = .6946;\n\tmatrix(i, j++) = .9797;\n\tmatrix(i, j++) = .8939;\n\tj = 0;\n\ti++;\n\t//Third Row\n\tmatrix(i, j++) = .6822;\n\tmatrix(i, j++) = .8537;\n\tmatrix(i, j++) = .6602;\n\tmatrix(i, j++) = .8385;\n\tmatrix(i, j++) = .6213;\n\tmatrix(i, j++) = .2714;\n\tmatrix(i, j++) = .1991;\n\tj = 0;\n\ti++;\n\t//FourthRow\n\tmatrix(i, j++) = .3028;\n\tmatrix(i, j++) = .5936;\n\tmatrix(i, j++) = .3420;\n\tmatrix(i, j++) = .5681;\n\tmatrix(i, j++) = .7948;\n\tmatrix(i, j++) = .2523;\n\tmatrix(i, j++) = .2987;\n\tj = 0;\n\ti++;\n\t//Fifth Row\n\tmatrix(i, j++) = .5417;\n\tmatrix(i, j++) = .4966;\n\tmatrix(i, j++) = .2897;\n\tmatrix(i, j++) = .3704;\n\tmatrix(i, j++) = .9568;\n\tmatrix(i, j++) = .8757;\n\tmatrix(i, j++) = .6614;\n\tj = 0;\n\ti++;\n\t//6th Row\n\tmatrix(i, j++) = .1509;\n\tmatrix(i, j++) = .8998;\n\tmatrix(i, j++) = .3412;\n\tmatrix(i, j++) = .7027;\n\tmatrix(i, j++) = .5226;\n\tmatrix(i, j++) = .7373;\n\tmatrix(i, j++) = .2844;\n\tj = 0;\n\ti++;\n\t//7th Row\n\tmatrix(i, j++) = .6979;\n\tmatrix(i, j++) = .8216;\n\tmatrix(i, j++) = .5341;\n\tmatrix(i, j++) = .5466;\n\tmatrix(i, j++) = .8801;\n\tmatrix(i, j++) = .1365;\n\tmatrix(i, j++) = .4692;\n\n\treturn matrix;\n}\n\nArrayXf InitVector(ArrayXf vector){\n\tint i = 0;\n\tvector(i++) = .5000;\n\tvector(i++) = -.3000;\n\tvector(i++) = -.2000;\n\tvector(i++) = .7000;\n\tvector(i++) = -.9000;\n\tvector(i++) = .3000;\n\tvector(i++) = .1000;\n\treturn vector;\n}\n", "meta": {"hexsha": "5181d45d1fdd4d379395facab9174e63df8d7d8b", "size": 5235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Main.cpp", "max_stars_repo_name": "DonaldCole33/Gaussian-Elimination", "max_stars_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_stars_repo_licenses": ["MIT"], "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": "DonaldCole33/Gaussian-Elimination", "max_issues_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_issues_repo_licenses": ["MIT"], "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": "DonaldCole33/Gaussian-Elimination", "max_forks_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_forks_repo_licenses": ["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.04784689, "max_line_length": 91, "alphanum_fraction": 0.5866284623, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6638789732318886}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <boost/math/constants/constants.hpp>\n\n#include \"ear/common_types.hpp\"\n#include \"ear/metadata.hpp\"\n\nnamespace bear {\n// internal utilities from libear\n\ntemplate <typename T>\ninline T radians(T d)\n{\n  return d * static_cast<T>(boost::math::constants::pi<double>() / 180.0);\n}\n\ntemplate <typename T>\ninline T degrees(T r)\n{\n  return r * static_cast<T>(180.0 / boost::math::constants::pi<double>());\n}\n\ndouble azimuth(Eigen::Vector3d position);\ndouble elevation(Eigen::Vector3d position);\ndouble distance(Eigen::Vector3d position);\n\nEigen::Vector3d cart(double azimuth, double elevation, double distance);\n\nEigen::Vector3d toCartesianVector3d(ear::PolarPosition position);\nEigen::Vector3d toCartesianVector3d(ear::CartesianPosition position);\nEigen::Vector3d toCartesianVector3d(ear::PolarSpeakerPosition position);\nEigen::Vector3d toCartesianVector3d(ear::CartesianSpeakerPosition position);\n\n}  // namespace bear\n", "meta": {"hexsha": "0b1a57d8f4e01558d094ea62e42a01212980cad7", "size": 955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "visr_bear/src/geom.hpp", "max_stars_repo_name": "ebu/bear", "max_stars_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2022-02-01T16:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:24:59.000Z", "max_issues_repo_path": "visr_bear/src/geom.hpp", "max_issues_repo_name": "ebu/bear", "max_issues_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-03T06:49:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:10:43.000Z", "max_forks_repo_path": "visr_bear/src/geom.hpp", "max_forks_repo_name": "ebu/bear", "max_forks_repo_head_hexsha": "0e4c4f33dfaea9b7c64991515177eb2099887a5a", "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": 27.2857142857, "max_line_length": 76, "alphanum_fraction": 0.7706806283, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6638328903986468}}
{"text": "/* Last Revised Date: 13_DEC_2014 */\n/* Lastest status: All ok    */\n\n/*\n  det_model_hh_post.hpp : implimentation of HH system (similar but not exact for the classical HH equations)  \n  !!!NOTE: all units are in SI system\n\n  Copyright (C) 2015 Anup Gopalakrishna Pillai, Suhita Nadkarni Lab, IISER Pune <anupgpillai@gmail.com>\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 3 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, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef DET_MODEL_HH_POST_HPP_INCLUDED\n#define DET_MODEL_HH_POST_HPP_INCLUDED\n\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n//UNITS: all SI units - seconds, Volts, Ampere, Meters, Simenes, Farads\n\n//DECLARATIONS FOR HH_POST_MODEL\n\nclass DET_MODEL_HH_POST\n{\nprivate:\n  const double pi = boost::math::constants::pi<double>();\n  double Cm = 1.0E-02;   // F/m^2 Specific capacitance\n  //----Reversal potentials for Na, K, channels in mV\n  double ENa = 50.0E-03;   // Reversal potential for Sodium currents in Volts\n  double EK = -85.0E-03;    // Reversal potential for Potassium currents in Volts\n  double ELeak = -81E-03; // Reversal potential for Leak currents in Volts\n\n  double GNa = 130E01;   // Maximum conductance for Sodium channels S/m^2\n  double GK = 36E01;    // Maximum conductance for Potassium channels S/m^2\n  double GLeak = 0.3E01;  // Maximum conductance for Leak channels S/m^2\n\npublic:\n  std::vector<double> X;\n\n  double IExt = 0.0; //extern current in Amps\n  double Area = 0.0;\n  double Cap = 0.0;\n  double V = 0.0;      // Membrane voltage V\n  /* NEURON class explicit constructor */\n  explicit DET_MODEL_HH_POST( std::vector<double> X_ = {0,0,0,0},double Area_ = 8.5E-12): Area(Area_), X(X_), Cap(Cm * Area) // Area in m^2\n  {\n  };\n  //---Equations for bouton Na Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n  double alpha_Na_act(const double V);\n  double beta_Na_act(const double V);\n  double alpha_Na_inact(const double V);\n  double beta_Na_inact(const double V);\n  //---Equations for bouton K Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n  double alpha_K_act(const double V);\n  double beta_K_act(const double V);\n  //---Declaration of the ODE solver\n  template <class State >\n  void operator() ( const State &x, State &dxdt , const double  t );\n};\n//Function declarations\n//------------- Na+ channels --- implimented from classical HH (1952)\ndouble DET_MODEL_HH_POST::alpha_Na_act(const double V)\n{\n  double a = 0.1E03;\n  double b = 45.33E-03;\n  double c = 10E-03;\n  double val = 0.0;\n  val = (- a * ( (V + b) / (exp( -(V + b) / c ) - 1 ) ) );\n  return (val);\n}\ndouble DET_MODEL_HH_POST::beta_Na_act(const double V)\n{\n  double a = 4;\n  double b = 70.33E-03;\n  double c = 18E-03;\n  double val = 0.0;\n  val = ( a * ( exp( - (V + b) / c )) );\n  return (val);\n}\ndouble DET_MODEL_HH_POST::alpha_Na_inact(const double V)\n{\n  double val = 0.0;\n  val = 0.07 * exp( -( V + 70.33E-03) /20E-03 );\n  return (val);\n}\ndouble DET_MODEL_HH_POST::beta_Na_inact(const double V)\n{\n  double val = 0.0;\n  val = ( 1 / ( exp( - (V + 40.33E-03) / 10E-03) + 1) );\n  return (val);\n}\n//--------K+ channel alpha & beta\ndouble DET_MODEL_HH_POST::alpha_K_act(const double V)\n{\n  double val = 0;\n  val = -0.01E03 * (V + 60.33E-03) / ( exp( -(V +  60.33E-03) / 10E-03) - 1 );\n  return (val);\n};\ndouble DET_MODEL_HH_POST::beta_K_act(const double V)\n{\n  double val = 0.0;\n  val = 0.125 * exp (- (V + 70.33E-03) / 80E-03);\n  return (val);\n};\n//-------HH_PRE class ODE Function\n\ntemplate <class State>\nvoid DET_MODEL_HH_POST::operator() ( const State &x, State &dxdt , const double t )\n{\n\n  dxdt[0] = 1E03 * (( alpha_Na_act(x[3]) * (1 - x[0]) ) - (beta_Na_act(x[3]) * x[0]) ); // Na activation\n  dxdt[1] = 1E03 * ( ( alpha_Na_inact(x[3]) * (1 - x[1]) ) - (beta_Na_inact(x[3]) * x[1])) ; // Na inactivation\n  dxdt[2] = 1E03 * ( ( alpha_K_act(x[3]) * (1 - x[2]) ) - (beta_K_act(x[3]) * x[2])); // K activation\n  double INa =   -(Area * GNa * pow(x[0],3) * x[1] * (x[3] - ENa) );\n  double IK =   -(Area * GK * pow(x[2],4) * (x[3] - EK) );\n  double ILeak = -(Area * GLeak *  (x[3] - ELeak) );\n  dxdt[3] =  (1/Cap) * (INa + IK + ILeak  + (IExt * Area)  );\n};\n#endif // DET_MODEL_HH_POST_HPP_INCLUDED\n", "meta": {"hexsha": "578e80798bb53463902374952cad21bc4e9c507d", "size": 4729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/det_model_hh_post.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_hh_post.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_hh_post.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": 35.5563909774, "max_line_length": 139, "alphanum_fraction": 0.6582787059, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6638328812628568}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n\n  //====================\n\n  // Get element matrix for negative laplacian of given cell\n  lf::uscalfe::LinearFELaplaceElementMatrix prov;\n  Eigen::MatrixXd A = prov.Eval(cell);\n\n  // First get the area\n  double K = lf::geometry::Volume(*geo_ptr);\n\n  // Initialize elem. stiffness matrix\n  Eigen::Matrix<double, 4, 4> M;\n\n  if (ref_el == lf::base::RefEl::kTria()) {\n    M << 2.0, 1.0, 1.0, 0.0,\n         1.0, 2.0, 1.0, 0.0,\n         1.0, 1.0, 2.0, 0.0,\n         0.0, 0.0, 0.0, 0.0;\n    M *= K/12.0;\n  } else if (ref_el == lf::base::RefEl::kQuad()) {\n    M << 4.0, 2.0, 1.0, 2.0,\n         2.0, 4.0, 2.0, 1.0,\n         1.0, 2.0, 4.0, 2.0,\n         2.0, 1.0, 2.0, 4.0;\n    M *= K/36.0;\n  }\n\n  elem_mat = A + M;\n\n  //====================\n\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "47179916716ee0c09d74aa7a4a88cdec68919281", "size": 1764, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.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": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.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": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.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": 25.9411764706, "max_line_length": 64, "alphanum_fraction": 0.6224489796, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6637462802890418}}
{"text": "/**\n   \\file conjugate_gradient.hpp\n   \\brief powerll optimization method\n   \\author Junhua Gu\n */\n\n#ifndef CONJUGATE_GRADIENT\n#define CONJUGATE_GRADIENT\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <limits>\n#include <cassert>\n#include <cmath>\n#include \"../linmin/linmin.hpp\"\n#include <math/num_diff.hpp>\n#include <algorithm>\n#include <iostream>\n\nnamespace opt_utilities\n{\n  /**\n     \\brief Impliment of an optimization method\n     \\tparam rT return type of the object function\n     \\tparam pT parameter type of the object function\n   */\n  template <typename rT,typename pT>\n  class conjugate_gradient\n    :public opt_method<rT,pT>\n  {\n  public:\n    typedef pT array1d_type;\n    typedef rT T;\n  private:\n    func_obj<rT,pT>* p_fo;\n    optimizer<rT,pT>* p_optimizer;\n    volatile bool bstop;\n    //typedef blitz::Array<rT,2> array2d_type;\n    \n    const char* do_get_type_name()const\n    {\n      return \"conjugate gradient method\";\n    }\n  private:\n    array1d_type start_point;\n    array1d_type end_point;\n    \n  private:\n    rT threshold;\n    array1d_type g;\n    array1d_type h;\n    array1d_type xi;\n  private:\n    rT func(const pT& x)\n    {\n      assert(p_fo!=0);\n      return p_fo->eval(x);\n    }\n\n   \n  private:\n    void clear_xi()\n    {\n    }\n\n    void init_xi(int n)\n    {\n      clear_xi();\n      g=array1d_type(n);\n      h=array1d_type(n);\n      xi=array1d_type(n);\n    }\n\n\n\n    void cg(array1d_type& p,const T ftol,\n\t   int& iter,T& fret)\n    {\n      const int ITMAX=200;\n      const T EPS=std::numeric_limits<T>::epsilon();\n      \n      int j,its;\n      int n=p.size();\n      T gg,gam,fp,dgg;\n      fp=func(p);\n      xi=gradient(*p_fo,p);\n      for(j=0;j<n;++j)\n\t{\n\t  g[j]=-xi[j];\n\t  xi[j]=h[j]=g[j];\n\t}\n      for(its=1;its<=ITMAX;++its)\n\t{\n\t  iter=its;\n\t  linmin(p,xi,fret,*p_fo);\n\t  //std::cerr<<\"######:\"<<its<<\"\\t\"<<abs(fret-fp)/(abs(fret)+fabs(fp)+EPS)<<std::endl;\n\t  if(2.0*abs(fret-fp)<=ftol*(abs(fret)+fabs(fp)+EPS))\n\t    {\n\t      return;\n\t    }\n\t    fp=func(p);\n\t    xi=gradient(*p_fo,p);\n\t    dgg=gg=0;\n\t    for(j=0;j<n;++j)\n\t      {\n\t\tgg+=g[j]*g[j];\n\t\t//dgg+=(xi[j]+g[j])*xi[j];\n\t\tdgg+=xi[j]*xi[j];\n\t      }\n\t    //std::cerr<<its<<\"\\t\"<<gg<<std::endl;\n\t    if(gg==0.0)\n\t      {\n\t\treturn;\n\t      }\n\t    gam=dgg/gg;\n\t    for(j=0;j<n;++j)\n\t      {\n\t\tg[j]=-xi[j];\n\t\txi[j]=h[j]=g[j]+gam*h[j];\n\t      }\n\t}\n      //std::cerr<<\"Too many iterations in cg\"<<std::endl;\n    }\n\n    \n  public:\n    \n    conjugate_gradient()\n      :threshold(1e-4),g(0),h(0),xi(0)\n    {}\n\n    virtual ~conjugate_gradient()\n    {\n      clear_xi();\n    };\n\n    conjugate_gradient(const conjugate_gradient<rT,pT>& rhs)\n      :opt_method<rT,pT>(rhs),p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n       start_point(rhs.start_point),\n       end_point(rhs.end_point),\n       threshold(rhs.threshold),g(0),h(0),xi(0)\n    {\n    }\n\n    conjugate_gradient<rT,pT>& operator=(const conjugate_gradient<rT,pT>& rhs)\n    {\n      threshold=rhs.threshold;\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      start_point=rhs.start_point;\n      end_point=rhs.end_point;\n      threshold=rhs.threshold;\n    }\n    \n    opt_method<rT,pT>* do_clone()const\n    {\n      return new conjugate_gradient<rT,pT>(*this);\n    }\n    \n    void do_set_start_point(const array1d_type& p)\n    {\n      resize(start_point,get_size(p));\n      opt_eq(start_point,p);\n    }\n\n    array1d_type do_get_start_point()const\n    {\n      return start_point;\n    }\n\n    void do_set_lower_limit(const array1d_type& p)\n    {}\n\n    void do_set_upper_limit(const array1d_type& p)\n    {}\n\n    void do_set_precision(rT t)\n    {\n      threshold=t;\n    }\n\n    rT do_get_precision()const\n    {\n      return threshold;\n    }\n\n    void do_set_optimizer(optimizer<rT,pT>& o)\n    {\n      p_optimizer=&o;\n      p_fo=p_optimizer->ptr_func_obj();\n    }\n    \n    \n    \n    pT do_optimize()\n    {\n      bstop=false;\n      init_xi((int)get_size(start_point));\n      \n      int iter=100;\n      opt_eq(end_point,start_point);\n      rT fret;\n#if 0\n      for(int i=0;i<get_size(start_point);++i)\n\t{\n\t  array1d_type direction(start_point.size());\n\t  direction[i]=1;\n\t  linmin(end_point,direction,fret,(*p_fo));\n\t}\n#endif\n      cg(end_point,threshold,iter,fret);\n      return end_point;\n    }\n    \n    void do_stop()\n    {\n      bstop=true;\n    }\n\n  };\n\n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "95b7eb54081712777ebe5f59af846437c9a290d0", "size": 4332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/conjugate_gradient/conjugate_gradient.hpp", "max_stars_repo_name": "liweitianux/opt_utilities", "max_stars_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/conjugate_gradient/conjugate_gradient.hpp", "max_issues_repo_name": "liweitianux/opt_utilities", "max_issues_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/conjugate_gradient/conjugate_gradient.hpp", "max_forks_repo_name": "liweitianux/opt_utilities", "max_forks_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T16:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T16:14:44.000Z", "avg_line_length": 19.0837004405, "max_line_length": 87, "alphanum_fraction": 0.5796398892, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6637462629503732}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   tstExponentiationAlgorithms.cpp\n//! \\author Alex Robinson\n//! \\brief  Exponentiation algorithm unit tests.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <iostream>\n\n// Boost Includes\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/cgs/length.hpp>\n#include <boost/units/systems/si/length.hpp>\n\n// FRENSIE Includes\n#include \"Utility_ExponentiationAlgorithms.hpp\"\n#include \"Utility_UnitTestHarnessWithMain.hpp\"\n\n//---------------------------------------------------------------------------//\n// Testing Functions.\n//---------------------------------------------------------------------------//\n// Test the recursive exponentiation algorithm\nFRENSIE_UNIT_TEST_TEMPLATE_EXPAND( Exponentiation, recursive,\n\t\t\t\t   std::tuple<int,int>,\n                                   std::tuple<double,long>,\n                                   std::tuple<double,unsigned long long> )\n{\n  FETCH_TEMPLATE_PARAM( 0, BaseScalarType );\n  FETCH_TEMPLATE_PARAM( 1, ExponentOrdinalType );\n  \n  // Compute 2^30\n  BaseScalarType value =\n    Utility::Exponentiation::recursive<BaseScalarType,ExponentOrdinalType>(2,\n\t\t\t\t\t\t\t\t\t   30);\n  FRENSIE_CHECK_EQUAL( value, 1073741824 );\n}\n\n//---------------------------------------------------------------------------//\n// Test the static recursive exponentiation algorithm\nFRENSIE_UNIT_TEST_TEMPLATE( Exponentiation, recursive_static,\n                            double,\n                            boost::units::quantity<boost::units::cgs::length>,\n                            boost::units::quantity<boost::units::si::length> )\n{\n  FETCH_TEMPLATE_PARAM( 0, BaseScalarType );\n  \n  typedef typename Utility::QuantityTraits<BaseScalarType>::template GetQuantityToPowerType<30>::type ReturnType30;\n  \n  // Compute 2^30\n  ReturnType30 value_30 = Utility::Exponentiation::recursive<30>( 2.*Utility::QuantityTraits<BaseScalarType>::one() );\n\n  FRENSIE_CHECK_EQUAL( value_30, Utility::QuantityTraits<ReturnType30>::one()*1073741824. );\n\n  // Compute 2^29\n  typedef typename Utility::QuantityTraits<BaseScalarType>::template GetQuantityToPowerType<29>::type ReturnType29;\n\n  ReturnType29 value_29 = Utility::Exponentiation::recursive<29>( 2.*Utility::QuantityTraits<BaseScalarType>::one() );\n\n  FRENSIE_CHECK_EQUAL( value_29, Utility::QuantityTraits<ReturnType29>::one()*536870912. );\n}\n\n//---------------------------------------------------------------------------//\n// Test the recursive modular exponentiation algorithm\nFRENSIE_UNIT_TEST_TEMPLATE( Exponentiation, recursiveMod,\n                            unsigned,\n                            unsigned long,\n                            unsigned long long )\n{\n  FETCH_TEMPLATE_PARAM( 0, OrdinalType );\n  \n  // Compute (2^30)mod(3)\n  OrdinalType value =\n    Utility::Exponentiation::recursiveMod<OrdinalType>(2,30,3);\n\n  FRENSIE_CHECK_EQUAL( value, 1 );\n\n  OrdinalType value2 =\n    Utility::Exponentiation::recursiveMod<OrdinalType>(2,15,3);\n\n  FRENSIE_CHECK_EQUAL( value2, 2 );\n}\n\n//---------------------------------------------------------------------------//\n// end tstExponentiationAlgorithms.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "130d131390797ca574873ec54fee594442b95851", "size": 3316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/test/tstExponentiationAlgorithms.cpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/core/test/tstExponentiationAlgorithms.cpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/core/test/tstExponentiationAlgorithms.cpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 37.6818181818, "max_line_length": 118, "alphanum_fraction": 0.5597104946, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6637462497345584}}
{"text": "/// \\file\n// --------------------------------------------------------------------------\n// This file is part of the reference implementation for the paper\n//    QFib: Fast and Efficient Brain Tractogram Compression\n//    C. Mercier*, S. Rousseau*, P. Gori, I. Bloch and T. Boubekeur\n//    NeuroInformatics 2020\n//    DOI: 10.1007/s12021-020-09452-0\n//\n// All rights reserved. Use of this source code is governed by a\n// MIT license that can be found in the LICENSE file.\n// --------------------------------------------------------------------------\n#pragma once\n\n#include \"saveload.hpp\"\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nusing namespace std;\n\nnamespace vc\n{\nint my_round(const unsigned type, const float value)\n{\n\tswitch (type) {\n\tcase 0:\n\t\treturn floor(value);\n\t\tbreak;\n\tcase 1:\n\t\treturn ceil(value);\n\t\tbreak;\n\tdefault:\n\t\treturn round(value);\n\t\tbreak;\n\t}\n}\n\n///\n/// \\brief computeTrilinearInterpolatedValue Compute an interpolated value at the position, considering the grid\n/// \\param grid Grid to consider for the interpolated value\n/// \\param dim Dimension of the grid\n/// \\param gridPosition Position at which to compute the interpolated value\n/// \\return Return the computed value\n///\n\nfloat computeTrilinearInterpolatedValue(std::vector<float> const & grid, std::vector<unsigned> const & dim, Vector3f const & gridPosition)\n{\n\tstd::vector<float> value;\n\tfor (unsigned pos2=0; pos2<2; pos2++)\n\t\tfor (unsigned pos3=0; pos3<2; pos3++)\n\t\t\tfor (unsigned pos1=0; pos1<2; pos1++)\n\t\t\t\tvalue.push_back(grid[(int)my_round(pos1,gridPosition(0))+dim[0]*(int)my_round(pos2,gridPosition(1))+dim[0]*dim[1]*(int)my_round(pos3,gridPosition(2))]);\n\tfloat xd = gridPosition(0) - floor(gridPosition(0));\n\tfloat yd = gridPosition(1) - floor(gridPosition(1));\n\tfloat zd = gridPosition(2) - floor(gridPosition(2));\n\n\tfloat c00 = value[0]*(1-xd)+value[1]*xd;\n\tfloat c01 = value[2]*(1-xd)+value[3]*xd;\n\tfloat c10 = value[4]*(1-xd)+value[5]*xd;\n\tfloat c11 = value[6]*(1-xd)+value[7]*xd;\n\n\tfloat c0 = c00*(1-yd)+c10*yd;\n\tfloat c1 = c01*(1-yd)+c11*yd;\n\n\tfloat val = c0*(1-zd)+c1*zd;\n\n\treturn val;\n}\n\n//positive filter\nint getSign(const float value)\n{\n\tif (value>0)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nfloat k(const float x, const float dirX, const float dimV)\n{\n\treturn (getSign(dirX) + round(x/dimV)) * dimV;\n}\n\nfloat k2(const float x, const float dirX)\n{\n\treturn floor(x) + getSign(dirX);\n}\n\n///\n/// \\brief getValueFromSegment Compute the value along a segment\n/// \\param grid Grid to consider\n/// \\param dim Dimensions of the grid\n/// \\param p1 First point of the segment\n/// \\param p2 Second point of the segment\n/// \\return Return the value of the segment\n///\n\nfloat getValueFromSegment(std::vector<float> const & grid, std::vector<unsigned> const & dim, Vector3f const & p1, Vector3f const & p2)\n{\n\tVector3f direction = p2-p1;\n\tVector3f directionN = direction.normalized();\n\tfloat totalDist = direction.norm();\n\t//Number of voxels changes along each axis\n\tunsigned voxelsX = static_cast<unsigned>(fabs(floor(p2.x())-floor(p1.x())));\n\tunsigned voxelsY = static_cast<unsigned>(fabs(floor(p2.y())-floor(p1.y())));\n\tunsigned voxelsZ = static_cast<unsigned>(fabs(floor(p2.z())-floor(p1.z())));\n\tunsigned totalVoxelsCrossed = 1 + voxelsX + voxelsY + voxelsZ;\n\tVector3f pTemp = p1;\n\tfloat value = 0;\n\tfloat epsilon = 0.0001f;\n\tfloat gammaX, gammaY, gammaZ, gamma;\n\n\tfor (unsigned i=0; i<totalVoxelsCrossed - 1; i++)\n\t{\n\t\tif (fabs(directionN.x())<epsilon)\n\t\t\tgammaX =  numeric_limits<float>::max();\n\t\telse\n\t\t\tgammaX = (k2(pTemp.x(), direction.x()) - pTemp.x()) / direction.x();\n\t\tif (fabs(directionN.y())<epsilon)\n\t\t\tgammaY =  numeric_limits<float>::max();\n\t\telse\n\t\t\tgammaY = (k2(pTemp.y(), direction.y()) - pTemp.y()) / direction.y();\n\t\tif (fabs(directionN.z())<epsilon)\n\t\t\tgammaZ =  numeric_limits<float>::max();\n\t\telse\n\t\t\tgammaZ = (k2(pTemp.z(), direction.z()) - pTemp.z()) / direction.z();\n\t\tgamma = min(min(gammaX, gammaY), gammaZ);\n\t\tpTemp += (gamma) * direction;\n\t\tvalue += (grid[(int)floor(pTemp.x())+dim[0]*(int)floor(pTemp.y())+(dim[0]*dim[1]*(int)floor(pTemp.z()))]);\n\t}\n\tvalue += (grid[(int)floor(p2.x())+dim[0]*(int)floor(p2.y())+(dim[0]*dim[1]*(int)floor(p2.z()))]);\n\treturn (value / (float)(totalVoxelsCrossed));\n}\n\n///\n/// \\brief compareFA Function to compare the FA values and display the results\n/// \\param fibers1 First set of fibers\n/// \\param fibers2 Second set of fibers\n/// \\param faFilename FA file to use for FA computation\n///\n\nvoid compareFA(std::vector<std::vector<Vector3f>> const & fibers1, std::vector<std::vector<Vector3f>> const & fibers2, const string & faFilename)\n{\n\tcout << faFilename << endl;\n\tstd::vector<float> faValues, vox;\n\tstd::vector<unsigned> dim;\n\tMatrixXf transform;\n\tfls::loadFAValues(faFilename, faValues, dim, transform, vox);\n\n\ttransform.conservativeResize(4,4);\n\ttransform.row(3) << 0,0,0,1;\n\ttransform = transform.inverse();\n\n\tunsigned maxThreads = std::max(unsigned(1), std::thread::hardware_concurrency());\n\tstd::vector<float> ecartMoyenTab(maxThreads, 0);\n\tstd::vector<uint64_t> nbPointsTab(maxThreads, 0);\n\tstd::vector<float> ecartMaxTab(maxThreads, 0);\n\tstd::vector<float> averageFiber1Error(maxThreads, 0);\n\tstd::vector<float> averageFiber2Error(maxThreads, 0);\n#ifdef USE_OPENMP\n#pragma omp parallel for\n\tfor (unsigned i=0; i<fibers1.size(); i++)\n\t{\n\t\tif (fibers1[i].size() == fibers2[i].size())\n\t\t{\n\t\t\tnbPointsTab[omp_get_thread_num()] += fibers1[i].size();\n\t\t\tfor (unsigned j=0; j<fibers1[i].size(); j++)\n\t\t\t{\n\t\t\t\tVector3f p = fibers1[i][j];\n\t\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t\t\tp(k)/=vox[k];\n\t\t\t\tVector3f gridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\t\tfloat value1 = computeTrilinearInterpolatedValue(faValues, dim, gridPosition);\n\t\t\t\tVector3f p2 = fibers2[i][j];\n\t\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t\t\tp2(k)/=vox[k];\n\t\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\t\tfloat value2=computeTrilinearInterpolatedValue(faValues, dim, gridPosition2);\n\t\t\t\tfloat ecart = fabs(value1-value2);\n\t\t\t\tecartMaxTab[omp_get_thread_num()] = max(ecart, ecartMaxTab[omp_get_thread_num()]);\n\t\t\t\tecartMoyenTab[omp_get_thread_num()]+=ecart;\n\t\t\t}\n\t\t}\n\n\t\t//Per fiber error\n\t\tfloat fiber1Value = 0.f;\n\t\tfloat fiber2Value = 0.f;\n\t\tVector3f p = fibers1[i][0];\n\t\tfor (unsigned k=0; k<3; k++)\n\t\t{\n\t\t\tp(k)/=vox[k];\n\t\t}\n\t\tVector3f gridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\tfiber1Value += faValues[(int)floor(gridPosition.x())+dim[0]*(int)floor(gridPosition.y())+(dim[0]*dim[1]*(int)floor(gridPosition.z()))];\n\t\tfor (unsigned j=0; j<fibers1[i].size()-1; j++)\n\t\t{\n\t\t\tVector3f p1 = fibers1[i][j];\n\t\t\tVector3f p2 = fibers1[i][j+1];\n\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t{\n\t\t\t\tp1(k)/=vox[k];\n\t\t\t\tp2(k)/=vox[k];\n\t\t\t}\n\t\t\tVector3f gridPosition1 = (p1*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tfiber1Value += getValueFromSegment(faValues, dim, gridPosition1, gridPosition2);\n\t\t}\n\t\tp = fibers2[i][0];\n\t\tfor (unsigned k=0; k<3; k++)\n\t\t{\n\t\t\tp(k)/=vox[k];\n\t\t}\n\t\tgridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\tfiber2Value += faValues[(int)floor(gridPosition.x())+dim[0]*(int)floor(gridPosition.y())+(dim[0]*dim[1]*(int)floor(gridPosition.z()))];\n\t\tfor (unsigned j=0; j<fibers2[i].size()-1; j++)\n\t\t{\n\t\t\tVector3f p1 = fibers2[i][j];\n\t\t\tVector3f p2 = fibers2[i][j+1];\n\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t{\n\t\t\t\tp1(k)/=vox[k];\n\t\t\t\tp2(k)/=vox[k];\n\t\t\t}\n\t\t\tVector3f gridPosition1 = (p1*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tfiber2Value += getValueFromSegment(faValues, dim, gridPosition1, gridPosition2);\n\t\t}\n\t\tfiber1Value /= float(fibers1[i].size());\n\t\tfiber2Value /= float(fibers2[i].size());\n\t\taverageFiber1Error[omp_get_thread_num()] += fiber1Value;\n\t\taverageFiber2Error[omp_get_thread_num()] += fiber2Value;\n\t}\n#else\n\tparallel.For<unsigned>(0, fibers1.size(), 1, [&](unsigned i)\n\t{\n\t\tif (fibers1[i].size() == fibers2[i].size())\n\t\t{\n\t\t\tnbPointsTab[parallel.getID()] += fibers1[i].size();\n\t\t\tfor (unsigned j=0; j<fibers1[i].size(); j++)\n\t\t\t{\n\t\t\t\tVector3f p = fibers1[i][j];\n\t\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t\t\tp(k)/=vox[k];\n\t\t\t\tVector3f gridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\t\tfloat value1 = computeTrilinearInterpolatedValue(faValues, dim, gridPosition);\n\t\t\t\tVector3f p2 = fibers2[i][j];\n\t\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t\t\tp2(k)/=vox[k];\n\t\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\t\tfloat value2=computeTrilinearInterpolatedValue(faValues, dim, gridPosition2);\n\t\t\t\tfloat ecart = fabs(value1-value2);\n\t\t\t\tecartMaxTab[parallel.getID()] = max(ecart, ecartMaxTab[parallel.getID()]);\n\t\t\t\tecartMoyenTab[parallel.getID()]+=ecart;\n\t\t\t}\n\t\t}\n\n\t\t//Per fiber error\n\t\tfloat fiber1Value = 0.f;\n\t\tfloat fiber2Value = 0.f;\n\t\tVector3f p = fibers1[i][0];\n\t\tfor (unsigned k=0; k<3; k++)\n\t\t{\n\t\t\tp(k)/=vox[k];\n\t\t}\n\t\tVector3f gridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\tfiber1Value += faValues[(int)floor(gridPosition.x())+dim[0]*(int)floor(gridPosition.y())+(dim[0]*dim[1]*(int)floor(gridPosition.z()))];\n\t\tfor (unsigned j=0; j<fibers1[i].size()-1; j++)\n\t\t{\n\t\t\tVector3f p1 = fibers1[i][j];\n\t\t\tVector3f p2 = fibers1[i][j+1];\n\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t{\n\t\t\t\tp1(k)/=vox[k];\n\t\t\t\tp2(k)/=vox[k];\n\t\t\t}\n\t\t\tVector3f gridPosition1 = (p1*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tfiber1Value += getValueFromSegment(faValues, dim, gridPosition1, gridPosition2);\n\t\t}\n\t\tp = fibers2[i][0];\n\t\tfor (unsigned k=0; k<3; k++)\n\t\t{\n\t\t\tp(k)/=vox[k];\n\t\t}\n\t\tgridPosition = (p*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\tfiber2Value += faValues[(int)floor(gridPosition.x())+dim[0]*(int)floor(gridPosition.y())+(dim[0]*dim[1]*(int)floor(gridPosition.z()))];\n\t\tfor (unsigned j=0; j<fibers2[i].size()-1; j++)\n\t\t{\n\t\t\tVector3f p1 = fibers2[i][j];\n\t\t\tVector3f p2 = fibers2[i][j+1];\n\t\t\tfor (unsigned k=0; k<3; k++)\n\t\t\t{\n\t\t\t\tp1(k)/=vox[k];\n\t\t\t\tp2(k)/=vox[k];\n\t\t\t}\n\t\t\tVector3f gridPosition1 = (p1*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tVector3f gridPosition2 = (p2*transform.block(0,0,3,3)+transform.block(0,3,3,1));\n\t\t\tfiber2Value += getValueFromSegment(faValues, dim, gridPosition1, gridPosition2);\n\t\t}\n\t\tfiber1Value /= float(fibers1[i].size());\n\t\tfiber2Value /= float(fibers2[i].size());\n\t\taverageFiber1Error[parallel.getID()] += fiber1Value;\n\t\taverageFiber2Error[parallel.getID()] += fiber2Value;\n\t});\n#endif\n\n\tfloat ecartMoyen = ecartMoyenTab[0], ecartMax = ecartMaxTab[0];\n\tfloat averageFiber1 = averageFiber1Error[0], averageFiber2 = averageFiber2Error[0];\n\tuint64_t nbPoints = nbPointsTab[0];\n\tfor (unsigned i=1; i<maxThreads; i++)\n\t{\n\t\tnbPoints += nbPointsTab[i];\n\t\tecartMoyen += ecartMoyenTab[i];\n\t\tecartMax = max(ecartMax, ecartMaxTab[i]);\n\t\taverageFiber1 += averageFiber1Error[i];\n\t\taverageFiber2 += averageFiber2Error[i];\n\t}\n\n\tecartMoyen /= nbPoints;\n\taverageFiber1 /= (float)maxThreads;\n\taverageFiber2 /= (float)maxThreads;\n\tcout << \"fa per fiber mean error: \" << fabs(averageFiber2 - averageFiber1) / averageFiber1 * 100 << \"%\" << endl;\n\tcout << \"fa max error: \" << ecartMax << endl;\n\tcout << \"fa mean error: \" << ecartMoyen << endl;\n}\n}\n", "meta": {"hexsha": "7b3111be41fee7fe00a137883b9d05a85819e8b2", "size": 11488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/values.hpp", "max_stars_repo_name": "syrousseau/qfib", "max_stars_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T14:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:23:00.000Z", "max_issues_repo_path": "sources/values.hpp", "max_issues_repo_name": "syrousseau/qfib", "max_issues_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-06T14:54:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T14:58:35.000Z", "max_forks_repo_path": "sources/values.hpp", "max_forks_repo_name": "syrousseau/qfib", "max_forks_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T16:10:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T16:10:22.000Z", "avg_line_length": 34.4984984985, "max_line_length": 156, "alphanum_fraction": 0.657468663, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6636810800107128}}
{"text": "#ifndef CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHODNM_HPP_\n#define CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHODNM_HPP_\n\n#include <cstddef> // size_t\n\n#include <Eigen/Dense>\n\nnamespace cppmath\n{\n    /**\n     * Implementation of the original Downhill Simplex or Nelder-Mead method for nonlinear optimization from 1965.\n     * J. Nelder, R. Mead, \"A Simplex Method for Function Minimization,\" Computer Journal, 1965, 7, 308-313\n     *\n     * \\author cpieloth\n     * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n     */\n    template< size_t DIM >\n    class DownhillSimplexMethodNM\n    {\n    public:\n        typedef Eigen::Matrix< double, DIM, 1 > ParamsT; /**< Abbreviation for a vector of parameters. */\n\n        /**\n         * Enum to indicate how the optimization was converged.\n         */\n        enum Converged\n        {\n            CONVERGED_NO, /**< Optimization was not started. */\n            CONVERGED_EPSILON, /**< Optimization is smaller than epsilon/threshold. */\n            CONVERGED_ITERATIONS, /**< Maximum iterations was reached. */\n            CONVERGED_YES /**< Optimization is converged, but not specified how. */\n        };\n\n        DownhillSimplexMethodNM();\n        virtual ~DownhillSimplexMethodNM();\n\n        /**\n         * Implementation of the function to minimize.\n         *\n         * \\param x  n-dimensional parameter vector.\n         * \\return function value for vector x.\n         */\n        virtual double func( const ParamsT& x ) const = 0;\n\n        /**\n         * Indicates how the optimization was converged.\n         *\n         * \\return Enum::Converged\n         */\n        virtual Converged converged() const;\n\n        double getReflectionCoeff() const;\n\n        void setReflectionCoeff( double alpha );\n\n        double getContractionCoeff() const;\n\n        void setContractionCoeff( double beta );\n\n        double getExpansionCoeff() const;\n\n        void setExpansionCoeff( double gamma );\n\n        size_t getMaximumIterations() const;\n\n        void setMaximumIterations( size_t iterations );\n\n        double getEpsilon() const;\n\n        void setEpsilon( double eps );\n\n        double getInitialFactor() const;\n\n        void setInitialFactor( double factor );\n\n        size_t getResultIterations() const;\n\n        ParamsT getResultParams() const;\n\n        double getResultError() const;\n\n        /**\n         * Starts the optimization.\n         *\n         * \\param initial Initial start point.\n         */\n        void optimize( const ParamsT& initial );\n\n    protected:\n        /**\n         * Orders the parameters x and f(x) from min to max.\n         */\n        virtual void order();\n\n        /**\n         * Creates the initial parameter set and their function values.\n         *\n         * \\param initial Start parameter used to calculate initials.\n         */\n        virtual void createInitials( const ParamsT& initial );\n        double m_initFactor; /**< Factor to create the initial parameter set. */\n\n        ParamsT m_x[DIM + 1]; /**< Vector of all n+1 points. */\n        double m_y[DIM + 1]; /**< Stores the function values to reduce re-calculation. */\n\n        double m_epsilon; /**< Threshold or deviation for convergence. */\n        size_t m_maxIterations; /**< Maximum iterations until the algorithm is canceled. */\n        size_t m_iterations; /**< Iteration counter used for break condition. */\n\n        const size_t DIMENSION; /**< Constant for dimension. */\n        const size_t VALUES; /**< Constant for DIM+1. */\n\n    private:\n        enum Step\n        {\n            STEP_START, STEP_EXIT, STEP_REFLECTION, STEP_EXPANSION, STEP_CONTRACTION\n        };\n\n        double m_alpha; /**< Reflection coefficient. */\n        double m_beta; /**< Contraction coefficient. */\n        double m_gamma; /**< Expansion coefficient. */\n\n        void centroid();\n        Step reflection();\n        Step expansion();\n        Step contraction();\n\n        ParamsT m_xo;\n        ParamsT m_xr;\n        double m_yr;\n    };\n} /* namespace cppmath */\n\n// Load the implementation\n#include \"DownhillSimplexMethodNM-impl.hpp\"\n\n#endif  // CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHODNM_HPP_\n", "meta": {"hexsha": "04642d465e729951c3eb8867f76ea654693f2387", "size": 4160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/optimization/DownhillSimplexMethodNM.hpp", "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/cppmath/optimization/DownhillSimplexMethodNM.hpp", "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/cppmath/optimization/DownhillSimplexMethodNM.hpp", "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": 30.1449275362, "max_line_length": 114, "alphanum_fraction": 0.6189903846, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6636725684697573}}
{"text": "#pragma once\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n\n#include <armadillo>\n#include <fmt/format.h>\n\n#define SIGM 1\n#define TAHN 2\n#define RELU 3\n\nnamespace net{\n    template < typename Scalar >\n    class Perceptron {\n        // friend class Layer;\n        private:\n            Scalar val;\n            Scalar act;\n            Scalar der;\n            int id;\n        public:\n            Perceptron( Scalar val );\n            Scalar& VAL();\n            Scalar& ACT( int FUNC = SIGM );\n            Scalar& DER( int FUNC = SIGM );\n            int& ID() { return id; }\n            void show();\n    };\n\n    template < typename Scalar >\n    Perceptron< Scalar >::Perceptron( Scalar val ) {\n        this->val = val;\n        ACT();\n        DER();\n    }\n    template < typename Scalar >\n    Scalar& Perceptron< Scalar >::VAL() {\n        return this->val;\n    }\n    template < typename Scalar >\n    Scalar& Perceptron< Scalar >::ACT( int FUNC ) {\n        switch( FUNC ) {\n            case SIGM: this->act = 1.0 / ( 1.0 + exp( -this->val ) ); break;               // sigmoid activation\n            case TAHN: this->act = std::tanh( this->val ); break;                          // tahn activation\n            case RELU: this->act = this->val > 0 ? this->val : this->val * 0.01; break;    // LeakyReLU activation\n        }\n        return this->act;\n    }\n    template < typename Scalar >\n    Scalar& Perceptron< Scalar >::DER( int FUNC ) {\n        switch( FUNC ) {\n            case SIGM: this->der = this->act * ( 1.0 - this->act ); break;             // sigmoid derivation\n            case TAHN: this->der = 1.0 - std::exp( std::tanh( this->val ) ); break;    // tahn derivation\n            case RELU: this->der = this->val >= 0 ? 1.0 : 0.01; break;                 // LeakyReLU derivation\n        }\n        return this->der;\n    }\n    template < typename Scalar >\n    void Perceptron< Scalar >::show() {\n        std::string s = fmt::format( \"\\t{0} \\t {1} \\t {2}\\n\", this->VAL(), this->ACT(), this->DER() );\n        fmt::print( s );    // Python-like format string syntax\n    }\n}\n", "meta": {"hexsha": "6030a04dcb0862b5b41f642935127fbc7d72f77b", "size": 2086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mso_header_only/perceptron.hpp", "max_stars_repo_name": "bresilla/mso", "max_stars_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T10:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-26T10:44:20.000Z", "max_issues_repo_path": "include/mso_header_only/perceptron.hpp", "max_issues_repo_name": "bresilla/mso", "max_issues_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_issues_repo_licenses": ["MIT"], "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/mso_header_only/perceptron.hpp", "max_forks_repo_name": "bresilla/mso", "max_forks_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_forks_repo_licenses": ["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.0923076923, "max_line_length": 114, "alphanum_fraction": 0.5086289549, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6636725495595255}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nint main() {\n    Eigen::MatrixXd m(4, 4);\n\n    // Output a matrix that counts from 0 to 15\n    for (size_t i = 0; i < 4; ++i) {\n        for (size_t j = 0; j < 4; ++j) {\n            m(i, j) = i * 4 + j;\n        }\n    }\n\n    std::cout << m;\n\n    return 0;\n}", "meta": {"hexsha": "80d9e71221c3e7f9b2244722744d413a22686b77", "size": 299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen_example.cpp", "max_stars_repo_name": "mark-berobot/motor_sim", "max_stars_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T00:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T01:33:11.000Z", "max_issues_repo_path": "examples/eigen_example.cpp", "max_issues_repo_name": "INKSureIT/motor_sim", "max_issues_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "INKSureIT/motor_sim", "max_forks_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T01:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:35:23.000Z", "avg_line_length": 17.5882352941, "max_line_length": 47, "alphanum_fraction": 0.4548494983, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6636725358159815}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <taylor.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\ntemplate <typename T> class pendulum {\n\nprivate:\n  /// Length of the pendulum\n  double length_;\n  /// Gravitational constant (little g)\n  double g_;\n\npublic:\n  pendulum(double l, double g = 9.81) : length_(l), g_(g) {}\n\n  void operator()(const T &theta, T &dtheta_dt, const double /* t */) {\n    dtheta_dt[0][0] = theta[0][1];\n    dtheta_dt[0][1] = -(g_ / length_) * theta[0][0];\n  }\n};\n\nclass pendulum_exact {\nprivate:\n  /// Length of the pendulum\n  double length_;\n  /// Initial position (angle)\n  double theta0_;\n  /// Gravitational constant (little g)\n  double g_;\n\npublic:\n  pendulum_exact(double l, double theta0, double g = 9.81) : length_(l), theta0_(theta0), g_(g) {}\n  double position(double t) {\n    return theta0_ * std::cos(std::sqrt(g_/length_) * t);\n  }\n  double speed(double t) {\n    return (-theta0_ * std::sqrt(g_/length_) * std::sin(std::sqrt(g_/length_) * t));\n  }\n};\n\nint main() {\n  using namespace std;\n  using namespace boost::numeric::odeint;\n\n  typedef std::vector< taylor<double, 1, 1> > state_type;\n\n  //[ state_initialization\n  state_type x(2);\n  x[0][0] = 1.0; // start at x=1.0, p=0.0\n  x[0][1] = 0.0; // start at x=1.0, p=0.0\n  x[1][0] = 0.0;\n  x[1][1] = 0.0;\n  //]\n\n  double length = 10.0;\n  pendulum<state_type> approx(length);\n  pendulum_exact exact(length, 1.0);\n\n  runge_kutta4< state_type> stepper;\n\n  const double dt = 0.1;\n  const double tstart = 0.0;\n  const double tend = 1.0;\n  for( double t = tstart ; t < tend ; t += dt )\n  {\n    std::cout << t << \"   \" << std::setprecision(16) << exact.position(t) << \"   \" << std::setprecision(16) << exact.speed(t) << std::endl;\n    std::cout << t << \"   \" << std::setprecision(16) << x[0]  << \"   \" << std::setprecision(16) << x[1] << std::endl;\n    stepper.do_step(approx, x, t, dt);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "c21c60b236fcd5e522f4aad73233ab333d924cb0", "size": 1884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/autodiff_odeint.cpp", "max_stars_repo_name": "robertodr/odeint-autodiff", "max_stars_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T10:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T10:05:51.000Z", "max_issues_repo_path": "src/autodiff_odeint.cpp", "max_issues_repo_name": "robertodr/odeint-autodiff", "max_issues_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_issues_repo_licenses": ["MIT"], "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/autodiff_odeint.cpp", "max_forks_repo_name": "robertodr/odeint-autodiff", "max_forks_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_forks_repo_licenses": ["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.7894736842, "max_line_length": 139, "alphanum_fraction": 0.6066878981, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6635968652149559}}
{"text": "#include <CGAL/Random.h>\n#include <CGAL/Cartesian_matrix.h>\n#include <CGAL/sorted_matrix_search.h>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/functional.hpp>\n\ntypedef int                                     Value;\ntypedef std::vector<Value>                      Vector;\ntypedef Vector::iterator                        Value_iterator;\ntypedef std::vector<Vector>                     Vector_cont;\ntypedef CGAL::Cartesian_matrix<std::plus<int>,\n                               Value_iterator,\n                               Value_iterator>  Matrix;\n\nint main()\n{\n  // set of vectors the matrices are build from:\n  Vector_cont vectors;\n\n  // generate a random vector and sort it:\n  Vector a;\n  const int n = 5;\n  for (int i = 0; i < n; ++i)\n    a.push_back(CGAL::get_default_random()(100));\n  std::sort(a.begin(), a.end());\n  std::cout << \"a = ( \";\n  std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout,\" \"));\n  std::cout << \")\\n\";\n\n  // build a Cartesian matrix from a:\n  Matrix M(a.begin(), a.end(), a.begin(), a.end());\n\n  // search for an upper bound for max(a):\n  Value bound = a[n-1];\n  Value upper_bound =\n  CGAL::sorted_matrix_search(\n    &M, &M + 1,\n    CGAL::sorted_matrix_search_traits_adaptor(\n      [&bound](const auto& m){ return std::greater_equal<Value>()(m, bound); }, M));\n  std::cout << \"Upper bound for \" << bound << \" is \"\n            << upper_bound << \".\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a9c261a494cf203b1a8100b1c75920b17e2db644", "size": 1449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Matrix_search/examples/Matrix_search/sorted_matrix_search.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": "Matrix_search/examples/Matrix_search/sorted_matrix_search.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": "Matrix_search/examples/Matrix_search/sorted_matrix_search.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 30.829787234, "max_line_length": 84, "alphanum_fraction": 0.5776397516, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6635515948615409}}
{"text": "/*\n * utilities_cumtrapz_test.cpp Test fixtures for the cumtrapz function\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"utilities/integration.h\"\n\n\nusing namespace utilities;\n\ntemplate<typename T_scalar>\nclass PowFunctor {\npublic:\n    PowFunctor() {};\n    T_scalar operator() (T_scalar eta) const{\n        return pow(eta, 2.0);\n    };\n};\n\nclass IntegrationTest : public ::testing::Test {};\n\n\nTEST_F(IntegrationTest, test_colwise_cumulative_integrate_1_row) {\n\n    // Test that zeros are returned when trying to colwise integrate an array with 1 row\n    Eigen::ArrayXd integrand(1);\n    integrand << 1;\n    Eigen::ArrayXd integral_correct(1);\n    integral_correct << 0;\n    PowFunctor<double> functor;\n    Eigen::ArrayXd integral = cumulative_integrate(integrand, functor);\n    EXPECT_EQ(integral.matrix(), integral_correct.matrix());\n\n}\n\nTEST_F(IntegrationTest, test_colwise_cumulative_integrate) {\n    Eigen::ArrayXd integrand(3);\n    Eigen::ArrayXd integral_correct(3);\n    integrand << 0, 2, 4;\n    integral_correct << 0, 8.0/3.0, 64.0/3.0;\n    PowFunctor<double> pow_functor;\n    Eigen::ArrayXd integral = cumulative_integrate(integrand, pow_functor);\n    ASSERT_TRUE(integral.isApprox(integral_correct));\n}\n", "meta": {"hexsha": "d55f45878970e803c7cdcc52bbc2ebf194718d00", "size": 1352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utilities_integration_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/utilities_integration_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/utilities_integration_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "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.0, "max_line_length": 88, "alphanum_fraction": 0.7048816568, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7718434925908524, "lm_q1q2_score": 0.6635258605469453}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Eigen>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass SpectralShape\n{\n\n  using ArrayXd = Eigen::ArrayXd;\n\npublic:\n  SpectralShape() {}\n\n  void processFrame(Eigen::Ref<ArrayXd> in, double sampleRate, double minFreq,\n                    double maxFreq, double rolloffTarget, bool logFreq,\n                    bool usePower)\n  {\n    using namespace std;\n    maxFreq = (maxFreq == -1) ? (sampleRate / 2) : min(maxFreq, sampleRate / 2);\n    ArrayXd mag = in.max(epsilon);\n    index   nBins = mag.size();\n    double  binHz = sampleRate / ((nBins - 1) * 2.);\n    index   minBin = ceil(minFreq / binHz);\n    index   maxBin =\n        min(static_cast<index>(floorl(maxFreq / binHz)), (nBins - 1));\n    if (maxBin <= minBin)\n    {\n      mOutputBuffer.setZero();\n      return;\n    }\n\n    if (logFreq && minBin == 0)\n    {\n      minBin = 1;\n      mag(1) += mag(0);\n    }\n    ArrayXd amp = usePower ? mag.square() : mag;\n    amp = amp.segment(minBin, maxBin - minBin);\n    double  ampSum = amp.sum();\n    ArrayXd freqs =\n        ArrayXd::LinSpaced(maxBin - minBin, minBin * binHz, maxBin * binHz);\n    if (logFreq)\n    { freqs = 69 + (12 * (freqs / 440).log() * log2E); } // MIDI cents\n\n    double centroid = (amp * freqs).sum() / ampSum;\n    double spread = (amp * (freqs - centroid).square()).sum() / ampSum;\n    double skewness = (amp * (freqs - centroid).pow(3)).sum() /\n                      (spread * sqrt(spread) * ampSum);\n    double kurtosis =\n        (amp * (freqs - centroid).pow(4)).sum() / (spread * spread * ampSum);\n\n    double flatness = exp(amp.log().mean()) / amp.mean();\n    double rolloff = maxBin - 1;\n    double cumSum = 0;\n    double target = ampSum * rolloffTarget / 100.0;\n    for (index i = 0; cumSum <= target && i < amp.size(); i++)\n    {\n      cumSum += amp(i);\n      if (cumSum >= target)\n      {\n        rolloff = (i == 0) ? freqs(i)\n                           : freqs(i) - (freqs(i) - freqs(i - 1)) *\n                                            (cumSum - target) / amp(i);\n        break;\n      }\n    }\n    double crest = amp.maxCoeff() / amp.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                    double sampleRate, double minFreq = 0, double maxFreq = -1,\n                    double rolloffTarget = 0.95, bool logFreq = false,\n                    bool usePower = false)\n  {\n    assert(output.size() == 7);\n    ArrayXd in = _impl::asEigen<Eigen::Array>(input);\n    processFrame(in, sampleRate, minFreq, maxFreq, rolloffTarget, logFreq,\n                 usePower);\n    output = _impl::asFluid(mOutputBuffer);\n  }\n\nprivate:\n  ArrayXd mOutputBuffer{7};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "43de34d5f6f7334e22bc831e1bd1034a4fb8f565", "size": 3560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "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": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "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.5044247788, "max_line_length": 80, "alphanum_fraction": 0.5991573034, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.663457954396445}}
{"text": "#include \"PolyMesh/IOManager.h\"\n#include <Eigen/Sparse>\n#include <Eigen/SVD>\n\nusing namespace acamcad;\nusing namespace polymesh;\nusing namespace Eigen;\n\nvoid MeshInterpolation(PolyMesh* source, PolyMesh* target, double delta_t)\n{\n\tstd::string command = \"mkdir result \";\n\tsystem(command.c_str());\n\n\tint nv = source->numVertices();\n\tint nf = source->numPolygons();\n\n\tstd::vector<Matrix2d> S(nf);\n\tstd::vector<Vector3d> xx(nf);\n\tstd::vector<Vector3d> yy(nf);\n\tstd::vector<double> area(nf);\n\tstd::vector<double> angle(nf);\n\n\tMatrix2d I = MatrixXd::Identity(2, 2);\n\n\tstd::vector<std::vector<int>> v_id(nf);\n\n\t// Initial\n\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t{\n\t\tint id = (*f_it)->index();\n\t\tMHalfedge* heh = (*f_it)->halfEdge();\n\t\tMVert* v0 = heh->fromVertex();\n\t\tMVert* v1 = heh->toVertex();\n\t\tMHalfedge* next_heh = heh->next();\n\t\tMVert* v2 = next_heh->toVertex();\n\n\t\tv_id[id].push_back(v0->index());\n\t\tv_id[id].push_back(v1->index());\n\t\tv_id[id].push_back(v2->index());\n\n\t\tarea[id] = cross(v1->position() - v0->position(), v2->position()- v0->position()).norm() / 2.0;\n\t\t\n\t\txx[id] = Vector3d(v2->position()[0] - v1->position()[0], v0->position()[0] - v2->position()[0], v1->position()[0] - v0->position()[0]);\n\t\tyy[id] = Vector3d(v1->position()[1] - v2->position()[1], v2->position()[1] - v0->position()[1], v0->position()[1] - v1->position()[1]);\n\n\t\tVector3d u(target->vert(v0->index())->position()[0], target->vert(v1->index())->position()[0], target->vert(v2->index())->position()[0]);\n\t\tVector3d v(target->vert(v0->index())->position()[1], target->vert(v1->index())->position()[1], target->vert(v2->index())->position()[1]);\n\n\t\tMatrix2d J;\n\t\tJ << yy[id].dot(u) / (2 * area[id]), xx[id].dot(u) / (2 * area[id]), yy[id].dot(v) / (2 * area[id]), xx[id].dot(v) / (2 * area[id]);\n\t\tJacobiSVD<Matrix2d> svd(J, ComputeFullV | ComputeFullU);\n\n\t\tMatrix2d V = svd.matrixV();\n\t\tMatrix2d U = svd.matrixU();\n\t\tMatrix2d R = U * V.transpose();\n\n\t\tMatrix2d sigma;\n\t\tsigma(0, 1) = sigma(1, 0) = 0;\n\t\tsigma(0, 0) = svd.singularValues()[0];\n\t\tsigma(1, 1) = svd.singularValues()[1];\n\t\tS[id] = V * sigma * V.transpose();\n\t\tangle[id] = atan2(R(1, 0), R(1, 1));\n\t}\n\n\t// fix nv-1\n\tdouble u0 = source->vert(nv - 1)->position()[0];\n\tdouble v0 = source->vert(nv - 1)->position()[1];\n\n\n\tSparseMatrix<double> A(2 * nv - 2, 2 * nv - 2);\n\tstd::vector<Triplet<double>>triplet;\n\n\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t{\n\t\tint id = (*f_it)->index();\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif ((v_id[id][i] == nv - 1) || (v_id[id][j] == nv - 1))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttriplet.push_back(Triplet<double>(2 * v_id[id][i], 2 * v_id[id][j], yy[id][i] * yy[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet<double>(2 * v_id[id][i], 2 * v_id[id][j], xx[id][i] * xx[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet<double>(2 * v_id[id][i] + 1, 2 * v_id[id][j] + 1, yy[id][i] * yy[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet<double>(2 * v_id[id][i] + 1, 2 * v_id[id][j] + 1, xx[id][i] * xx[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tA.setFromTriplets(triplet.begin(), triplet.end());\n\tSparseLU<SparseMatrix<double>> solver;\n\tsolver.analyzePattern(A);\n\tsolver.factorize(A);\n\n\tdouble t = 0;\n\twhile (t <= 1)\n\t{\n\t\tstd::cout << \"iter:\" << t << std::endl;\n\n\t\tVectorXd b(2 * nv - 2);\n\t\tb.setZero();\n\n\t\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t\t{\n\t\t\tint id = (*f_it)->index();\n\t\t\tMatrix2d A, R;\n\t\t\tdouble theta_t = angle[id] * t;\n\n\t\t\tR << cos(theta_t), -sin(theta_t), sin(theta_t), cos(theta_t);\n\t\t\tA = R * ((1.0 - t)*I + t * S[id]);\n\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tif ((v_id[id][i] == nv - 1) || (v_id[id][j] == nv - 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((v_id[id][i] != nv - 1) && (v_id[id][j] == nv - 1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tb[2 * v_id[id][i]] += -yy[id][i] * yy[id][j] * u0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i]] += -xx[id][i] * xx[id][j] * u0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i] + 1] += -yy[id][i] * yy[id][j] * v0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i] + 1] += -xx[id][i] * xx[id][j] * v0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (v_id[id][i] != nv - 1)\n\t\t\t\t{\n\t\t\t\t\tb[2 * v_id[id][i]] += yy[id][i] * A(0, 0) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i]] += xx[id][i] * A(0, 1) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i] + 1] += yy[id][i] * A(1, 0) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i] + 1] += xx[id][i] * A(1, 1) / area[id];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tVectorXd result = solver.solve(b);\n\t\tfor (VertexIter v_it = source->vertices_begin(); v_it != source->vertices_end(); ++v_it)\n\t\t{\n\t\t\tint id = (*v_it)->index();\n\t\t\tif (id != nv - 1)\n\t\t\t{\n\t\t\t\t(*v_it)->setPosition(result[2 * id], result[2 * id + 1], 0);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string string_t = std::to_string(t);\n\t\twriteMesh(\"result\\\\\" + string_t + \".obj\", source);\n\t\tt += delta_t;\n\t}\n}\n\n\nint main(int argc, const char **argv)\n{\n\tif (argc != 4)\n\t{\n\t\tstd::cout << \"========== Hw8 Usage  ==========\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"blablabla.exe\tsource.obj target.obj delta_t\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"=================================================\\n\";\n        return 0;\n\t}\n\tstd::string source_path = argv[1];\n\tstd::string target_path = argv[2];\n\tstd::string t_string = argv[3];\n\n\tPolyMesh* source_mesh = new PolyMesh();\n\tPolyMesh* target_mesh = new PolyMesh();\n\tloadMesh(source_path, source_mesh);\n\tloadMesh(target_path, target_mesh);\n\tdouble delta_t = atof(t_string.c_str());\n\tMeshInterpolation(source_mesh, target_mesh, delta_t);\n    return 0;\n}", "meta": {"hexsha": "13ff506034206968940544a8b327c39f07afbb4b", "size": 5734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/hw8/main.cpp", "max_stars_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_stars_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-03-08T02:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:09:20.000Z", "max_issues_repo_path": "code/src/hw8/main.cpp", "max_issues_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_issues_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/hw8/main.cpp", "max_forks_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_forks_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_forks_repo_licenses": ["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.2134831461, "max_line_length": 139, "alphanum_fraction": 0.5500523195, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.663457954396445}}
{"text": "//  (C) Copyright Thomas Becker 2015. Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears\n//  in all copies. This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n\n#ifndef TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n#define TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n\n#include <boost/math/special_functions/erf.hpp>\n#include \"distribution_specific_pivot_base.hpp\"\n\n/*\n * Pivot calculator for normally distributed data.\n */\n\nnamespace median_project\n{\nnamespace numerical_quick_median_detail\n{\n\n/**\n * Pivot calculator for normal distributions.\n */\nclass normal_distribution_pivot : public distribution_specific_pivot_base\n{\n  private:\n    virtual double cdf(double x) const override\n    {\n        return .5 * (1.0 + boost::math::erf((x - m_total_sequence_mean) / (sqrt(2.0) * m_total_sequence_std_dev)));\n    }\n\n    virtual double quantile(double x) const override\n    {\n        return m_total_sequence_mean + m_total_sequence_std_dev * sqrt(2.0) * boost::math::erf_inv(2.0 * x - 1.0);\n    }\n};\n} // end namespace numerical_quick_median_detail\n} // end namespace median_project\n\n#endif // TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n", "meta": {"hexsha": "5e2afb7a2bac1b9979ac04c37d18e8fc315df2f7", "size": 1284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_stars_repo_name": "walkswiththebear/MedianProject", "max_stars_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-05T21:59:28.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-05T21:59:28.000Z", "max_issues_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_issues_repo_name": "walkswiththebear/MedianProject", "max_issues_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_forks_repo_name": "walkswiththebear/MedianProject", "max_forks_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_forks_repo_licenses": ["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.3170731707, "max_line_length": 115, "alphanum_fraction": 0.7593457944, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6634175688298616}}
{"text": "#include<iostream>\n#include<thread>\n#include<random>\n#include<type_traits>\n#include<vector>\n#include <boost/multiprecision/cpp_int.hpp>\n#include\"printtable.h\"\n#include \"calcSignature.hpp\"\n\nnamespace ExactSignature {\n  using std::vector;\n\n  typedef boost::multiprecision::cpp_rational Number;\n\n  class Signature {\n  public:\n    vector<vector<Number>> m_data;\n\n    template<typename Numeric>\n    void sigOfSegment(int d, int m, const Numeric* segment) {\n      m_data.resize(m);\n      auto& first = m_data[0];\n      first.resize(d);\n      for (int i = 0; i<d; ++i)\n        first[i] = (Number)segment[i];\n      for (int level = 2; level <= m; ++level) {\n        const auto& last = m_data[level - 2];\n        auto& s = m_data[level - 1];\n        s.assign(calcSigLevelLength(d, level), 0);\n        int i = 0;\n        for (auto l : last)\n          for (auto p = segment; p<segment + d; ++p)\n            s[i++] = (Number)(*p * l * Number(1, level));\n      }\n    }\n\n    void sigOfNothing(int d, int m) {\n      m_data.resize(m);\n      m_data[0].assign(d, 0);\n      for (int level = 2; level <= m; ++level) {\n        auto& s = m_data[level - 1];\n        s.assign(calcSigLevelLength(d, level), 0);\n      }\n    }\n\n    //if a is the signature of path A, b of B, then\n    //a.concatenateWith(d,m,b) makes a be the signature of the concatenated path AB\n    //This is also the (concatenation) product of the elements a and b in the tensor algebra.\n    void concatenateWith(int d, int m, const Signature& other) {\n      for (int level = m; level>0; --level) {\n        for (int mylevel = level - 1; mylevel>0; --mylevel) {\n          int otherlevel = level - mylevel;\n          auto& oth = other.m_data[otherlevel - 1];\n          for (auto dest = m_data[level - 1].begin(),\n            my = m_data[mylevel - 1].begin(),\n            myE = m_data[mylevel - 1].end(); my != myE; ++my) {\n            for (const Number& d : oth) {\n              *(dest++) += d * *my;\n            }\n          }\n        }\n        auto source = other.m_data[level - 1].begin();\n        for (auto dest = m_data[level - 1].begin(),\n          e = m_data[level - 1].end();\n          dest != e;)\n          *(dest++) += *(source++);\n\n      }\n    }\n    void swap(Signature& other) {\n      m_data.swap(other.m_data);\n    }\n    void multiplyByConstant(Number c) {\n      for (auto& a : m_data)\n        for (auto& b : a)\n          b *= c;\n    }\n    template<typename Numeric>\n    void writeOut(Numeric* dest) const {\n      for (auto& a : m_data)\n        for (auto& b : a)\n          *(dest++) = (Numeric)b;\n          //*(dest++) = (Numeric)denominator(b);\n    }\n  };\n\n  //This also calculates the concatenation product in the tensor algebra, \n  //but in the case where we assume 0 instead of 1 in the zeroth level.\n  //It is not in-place\n  Signature concatenateWith_zeroFirstLevel(int d, int m,\n    const Signature& a,\n    const Signature& b) {\n    Signature out;\n    out.sigOfNothing(d, m);\n    for (int level = m; level>0; --level) {\n      for (int alevel = level - 1; alevel>0; --alevel) {\n        int blevel = level - alevel;\n        auto& aa = a.m_data[alevel - 1];\n        auto& bb = b.m_data[blevel - 1];\n        auto dest = out.m_data[level - 1].begin();\n        for (const Number& c : aa) {\n          for (const Number& d : bb) {\n            *(dest++) += d * c;\n          }\n        }\n      }\n    }\n    return out;\n  }\n\n  void logTensorHorner(Signature& x) {\n    const int m = (int)x.m_data.size();\n    const int d = (int)x.m_data[0].size();\n    if (m <= 1)\n      return;\n    Signature s, t;\n    s.sigOfNothing(d, m - 1);\n    t.sigOfNothing(d, m);\n    for (int depth = m; depth > 0; --depth) {\n      Number constant = (Number) 1.0 / depth;\n      //make t be x*s up to level (1+m-depth). [this does nothing the first time round]\n      for (int lev = 2; lev <= 1 + m - depth; ++lev) {\n        //t.m_data[lev - 1] = x.m_data[lev - 1];\n        auto& tt = t.m_data[lev - 1];\n        std::fill(tt.begin(), tt.end(), (Number) 0.0);\n        for (int leftLev = 1; leftLev < lev; ++leftLev) {\n          int rightLev = lev - leftLev;\n          auto& aa = x.m_data[leftLev - 1];\n          auto& bb = s.m_data[rightLev - 1];\n          auto dest = t.m_data[lev - 1].begin();\n          for (const Number& c : aa)\n            for (const Number& dd : bb)\n              *(dest++) += dd * c;\n        }\n      }\n      //make s be x*constant-t up to level (1+m-depth)\n      if (depth>1)\n        for (int lev = 1; lev <= 1 + m - depth; ++lev) {\n          auto is = s.m_data[lev - 1].begin();\n          auto ix = x.m_data[lev - 1].begin();\n          auto es = s.m_data[lev - 1].end();\n          auto it = t.m_data[lev - 1].begin();\n          for (; is != es; ++is, ++it, ++ix)\n            *is = constant * *ix - *it;\n        }\n    }\n    //x isn't modified until this next bit.\n    //make x be x-t\n    for (int lev = 2; lev <= m; ++lev) {\n      auto it = t.m_data[lev - 1].begin();\n      auto ix = x.m_data[lev - 1].begin();\n      auto ex = x.m_data[lev - 1].end();\n      for (; ix != ex; ++ix, ++it)\n        *ix -= *it;\n    }\n  }\n\n}\n\nstd::mt19937 g_rnd;\nusing PathReal = double;\nstd::vector<PathReal> randomPath(int pathLength, int d){\n  std::vector<PathReal> out(pathLength*d);\n  std::uniform_real_distribution<PathReal> urd(0, 1);\n  for (auto& d : out)\n    d = urd(g_rnd);\n  return out;\n}\n\ntemplate<bool arbprec>\nusing SignatureType = std::conditional_t<arbprec,\n  ExactSignature::Signature,\n  CalcSignature::Signature>;\n\n//the stroke ending at from ... the stroke ending before to\ntemplate<bool arbprec>\nSignatureType<arbprec> sigPiece(const std::vector<PathReal>& path, int d, int m, size_t from, size_t to) {\n  SignatureType<arbprec> s1, s2;\n  std::vector<PathReal> displacement(d);\n  for (size_t i = from; i < to; ++i) {\n    for (int j = 0; j < d; ++j)\n      displacement[j] = path[i*d + j] - path[(i - 1)*d + j];\n    s1.sigOfSegment(d, m, displacement.data());\n    if (i == from) {\n      s2.swap(s1);\n    }\n    else {\n      s2.concatenateWith(d, m, s1);\n    }\n  }\n  return s2;\n}\n\n//Calculate the signature or log signature of path,\n//using float or arbitrary precision\ntemplate<bool arbprec>\nstd::vector<double> sig(const std::vector<PathReal>& path, int d, int m, bool log) {\n  size_t pathLength = path.size() / d;\n  auto s2 = sigPiece<arbprec>(path, d, m, 1, pathLength);\n  if (log)\n    logTensorHorner(s2);\n  std::vector<double> out(calcSigTotalLength(d, m));\n  s2.writeOut(out.data());\n  return out;\n}\n\n\n//like sig but split the work between processors\ntemplate<bool arbprec>\nstd::vector<double> sigParallel(const std::vector<PathReal>& path, int d, int m, bool log) {\n  size_t pathLength = path.size() / d;\n  size_t nThreads = 4;\n  size_t each = (pathLength - 1) / nThreads;\n  if (each < 1)\n    return sig<arbprec>(path, d, m, log);\n  size_t start = 1;\n  std::vector<SignatureType<arbprec>> pieces(nThreads);\n  std::vector<std::thread> threads;\n  for (size_t thread = 0; thread < nThreads; ++thread) {\n    size_t start = thread*each + 1;\n    size_t end = (thread + 1 == nThreads) ? pathLength : (thread*each + each + 1);\n    threads.emplace_back([&pieces,path,d,m,start, end,thread]() {\n      pieces[thread] = sigPiece<arbprec>(path, d, m, start, end);\n    });\n  }\n  for (auto& t : threads)\n    t.join();\n  auto s2 = pieces[0];\n  for (size_t i = 1; i < nThreads; ++i)\n    s2.concatenateWith(d, m, pieces[i]);\n  if (log)\n    logTensorHorner(s2);\n  std::vector<double> out(calcSigTotalLength(d, m));\n  s2.writeOut(out.data());\n  return out;\n}\n\nvoid test() {\n  using N = boost::multiprecision::cpp_rational;\n  N a = 0.0625;\n  N b = a - N(4, 5);\n  std::cout << b << \" \"<<(double) b << \"\\n\";\n}\n\n\nvoid go() {\n  auto d = 2, m = 4, pathLength=4;\n  auto path = randomPath(pathLength, d);\n  bool log = true;\n  auto s1 = sig<false>(path, d, m, log);\n  //auto s2 = sig<true>(path, d, m, log);\n  auto s2 = sigParallel<true>(path, d, m, log);\n\n  //for (size_t i = 0; i < s1.size(); ++i) {\n  //  std::cout << s1[i] << \"  \" << s2[i] << \"\\n\";\n  //}\n  auto diffs = diffVectors(s1, s2);\n  PrintTable::printTable(s1, s2, diffs);\n  std::cout << \"l2 norm \" << l2norm(s1) << \" \"<< l2norm(s2) << \"\\n\";\n  std::cout << \"l2 diff \" << l2norm(diffs) << \"\\n\";\n  std::cout << \"total diff \"<<l1norm(diffs) << \"\\n\";\n  printMaxDiff(s1, s2);\n  printMaxRelDiff(s1, s2);\n  printGreatestWith0b(s1, s2);\n}\n\nint main() {\n  //test();\n  go();\n}", "meta": {"hexsha": "36fc86eaaa8860e7475bb2a06e1969e34d25f8d8", "size": 8341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/VS/arbprec/arbprec.cpp", "max_stars_repo_name": "vishalbelsare/iisignature", "max_stars_repo_head_hexsha": "fd26aeaddac0577d44163586f8394d4255cca586", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T14:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T12:03:35.000Z", "max_issues_repo_path": "src/VS/arbprec/arbprec.cpp", "max_issues_repo_name": "ViewFuture/iisignature", "max_issues_repo_head_hexsha": "14084c0fb5661943ef944ff23492c6aeb50d7896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T13:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T18:17:37.000Z", "max_forks_repo_path": "src/VS/arbprec/arbprec.cpp", "max_forks_repo_name": "ViewFuture/iisignature", "max_forks_repo_head_hexsha": "14084c0fb5661943ef944ff23492c6aeb50d7896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-12-03T20:41:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T11:40:23.000Z", "avg_line_length": 30.8925925926, "max_line_length": 106, "alphanum_fraction": 0.5596451265, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6634152193528028}}
{"text": "#include <Eigen/Dense>\n#include <chrono>\n#include <thread>\n#include <Eigen/LU>\n#include <cmath> \n\nclass simpleObserver\n{\npublic:\n    simpleObserver(float scalingFactor = 1);\n    Eigen::MatrixXf calculateClosestPoints(Eigen::MatrixXf bodyNodePositions, Eigen::MatrixXf pointCloud);\n    /* First Calculate a Distance Matrix, then find at each column of the Distance matrix the lowest number,\n    // calculate the average Points on the number and return the set of average points\n    // bodyNodePositions(n,3) n = number of Body Nodes\n    \\param pointCloud(l,3) l = number of Points\n    \\param distMatrix(n,l), n rows and l columns\n    // ======== rows ==========\n    // =\n    // s\n    // l\n    // o\n    // c\n    \\return Eigen::MatrixXf avgPoints(n,3)\n    */\n    Eigen::MatrixXf calculateClosestPointsExpFun(Eigen::MatrixXf bodyNodePositions, Eigen::MatrixXf pointCloud);\n    Eigen::MatrixXf calculateClosestPointsWeighted(Eigen::MatrixXf bodyNodePositions, Eigen::MatrixXf pointCloud);\n\nprotected:\n    /*\n    \\int scaling factor is used to define how much the calculated target point should be trusted\n    scaling factor = 1 equals full trust in the target points\n    scaling factor = 0 equals no trust in the target points\n    target points to send = initial points + scaling * numberOfPoints/avgNumberOfPoints * (target-initial)\n    */\n    float mScalingFactor;\n    void distanceMatrix(Eigen::MatrixXf *distMatrix, Eigen::MatrixXf *avgPoints, Eigen::MatrixXf *bodyNodePositions, Eigen::MatrixXf *pointCloud, int lowerRow, int upperRow,int *numberOfPoints);\n    float fun(float x);\n};\n", "meta": {"hexsha": "ccbe7bb68cca272cb1438495821464d7dfa3b834", "size": 1584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Python_bindings/SimpleObserver/simpleObserver.hpp", "max_stars_repo_name": "SiyuChen1/CMakeListsExample", "max_stars_repo_head_hexsha": "3204dbfc5148a578077c9ee9706d1fb13f77c3d7", "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": "Python_bindings/SimpleObserver/simpleObserver.hpp", "max_issues_repo_name": "SiyuChen1/CMakeListsExample", "max_issues_repo_head_hexsha": "3204dbfc5148a578077c9ee9706d1fb13f77c3d7", "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": "Python_bindings/SimpleObserver/simpleObserver.hpp", "max_forks_repo_name": "SiyuChen1/CMakeListsExample", "max_forks_repo_head_hexsha": "3204dbfc5148a578077c9ee9706d1fb13f77c3d7", "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.6153846154, "max_line_length": 194, "alphanum_fraction": 0.7190656566, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6634152121307114}}
{"text": "#include \"uniform_bspline.hpp\"\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\ntemplate <typename T>\nusing EigenAlignedVec = std::vector<T, Eigen::aligned_allocator<T>>;\n\nTEST(UniformBSplineExample, Spline1d1d) {\n    // clang-format off\n    {\n    //! [Spline1d1d_Definition]\n    ubs::UniformBSpline<double, 3, double, double, std::vector<double>> spline;\n    //! [Spline1d1d_Definition]\n    }\n    // clang-format on\n\n    //! [Spline1d1d_DefinitionShort]\n    ubs::UniformBSpline11d<3> spline;\n    //! [Spline1d1d_DefinitionShort]\n\n    //! [Spline1d1d_ControlPoints]\n    std::vector<double> controlPoints{0.0, 1.0, 2.0, 3.0, 4.0};\n    spline.setControlPoints(controlPoints);\n    //! [Spline1d1d_ControlPoints]\n\n    //! [Spline1d1d_Eval]\n    double val0 = spline.evaluate(0.0);\n    double val1 = spline.evaluate(1.0);\n    //! [Spline1d1d_Eval]\n    EXPECT_DOUBLE_EQ(1.0, val0);\n    EXPECT_DOUBLE_EQ(3.0, val1);\n\n    //! [Spline1d1d_Derivative]\n    double deriv1 = spline.derivative(0.0, 1);\n    double deriv2 = spline.derivative(1.0, 2);\n    //! [Spline1d1d_Derivative]\n    EXPECT_DOUBLE_EQ(2.0, deriv1);\n    EXPECT_DOUBLE_EQ(0.0, deriv2);\n\n    //! [Spline1d1d_Smoothness]\n    double smoothness = spline.smoothness<1>();\n    //! [Spline1d1d_Smoothness]\n    EXPECT_DOUBLE_EQ(4.0, smoothness);\n\n    //! [Spline1d1d_Bounds]\n    spline.setBounds(-2.0, 5.0);\n    //! [Spline1d1d_Bounds]\n    EXPECT_EQ(spline.getLowerBound(), -2.0);\n    EXPECT_EQ(spline.getUpperBound(), 5.0);\n}\n\nTEST(UniformBSplineExample, Spline1d3d) {\n    //! [Spline1d3d_Definition]\n    ubs::UniformBSpline<double, 3, double, Eigen::Vector3d, EigenAlignedVec<Eigen::Vector3d>> spline;\n    //! [Spline1d3d_Definition]\n\n    //! [Spline1d3d_Eval]\n    Eigen::Vector3d val0 = spline.evaluate(0.0);\n    Eigen::Vector3d val1 = spline.evaluate(1.0);\n    //! [Spline1d3d_Eval]\n    EXPECT_DOUBLE_EQ(0.0, val0.norm());\n    EXPECT_DOUBLE_EQ(0.0, val1.norm());\n\n    //! [Spline1d3d_Derivative]\n    Eigen::Vector3d deriv1 = spline.derivative(0.0, 1);\n    Eigen::Vector3d deriv2 = spline.derivative(1.0, 2);\n    //! [Spline1d3d_Derivative]\n    EXPECT_DOUBLE_EQ(0.0, deriv1.norm());\n    EXPECT_DOUBLE_EQ(0.0, deriv2.norm());\n\n    //! [Spline1d3d_Smoothness]\n    Eigen::Vector3d smoothness = spline.smoothness<1>();\n    //! [Spline1d3d_Smoothness]\n    EXPECT_DOUBLE_EQ(0.0, smoothness.sum());\n}\n\nTEST(UniformBSplineExample, Spline2d1d) {\n    //! [Spline2d1d_Definition]\n    ubs::UniformBSpline<double, 3, Eigen::Vector2d, double, Eigen::MatrixXd> spline;\n    //! [Spline2d1d_Definition]\n\n    //! [Spline2d1d_Evaluate_Long]\n    double val = spline.evaluate(Eigen::Vector2d{0.0, 0.0});\n    //! [Spline2d1d_Evaluate_Long]\n    EXPECT_DOUBLE_EQ(0.0, val);\n\n    //! [Spline2d1d_Evaluate_Short]\n    val = spline.evaluate({0.0, 0.0});\n    //! [Spline2d1d_Evaluate_Short]\n    EXPECT_DOUBLE_EQ(0.0, val);\n\n    //! [Spline2d1d_Derivative_10]\n    double deriv10 = spline.derivative({0.0, 0.0}, {1, 0});\n    //! [Spline2d1d_Derivative_10]\n    EXPECT_DOUBLE_EQ(0.0, deriv10);\n\n    //! [Spline2d1d_Derivative_11]\n    double deriv11 = spline.derivative({0.0, 0.0}, {1, 1});\n    //! [Spline2d1d_Derivative_11]\n    EXPECT_DOUBLE_EQ(0.0, deriv11);\n}\n\nTEST(UniformBSplineExample, Spline2d3d) {\n    //! [Spline2d3d_Definition]\n    ubs::UniformBSpline<double, 3, Eigen::Vector2d, Eigen::Vector3d, ubs::EigenAlignedMultiArray<Eigen::Vector3d, 2>>\n        spline;\n    //! [Spline2d3d_Definition]\n\n    //! [Spline2d3d_Definition_Short]\n    ubs::EigenUniformBSpline<double, 3, 2, 3> splineS;\n    //! [Spline2d3d_Definition_Short]\n\n    //! [Spline2d3d_Evaluate]\n    Eigen::Vector3d val = spline.evaluate({0.0, 0.2});\n    //! [Spline2d3d_Evaluate]\n    EXPECT_DOUBLE_EQ(0.0, val.norm());\n}\n", "meta": {"hexsha": "cc82b2dfac353dd71710c134f1a1c5a858db55c6", "size": 3727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/examples.cpp", "max_stars_repo_name": "KIT-MRT/uniform_bspline", "max_stars_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:22:33.000Z", "max_issues_repo_path": "test/examples.cpp", "max_issues_repo_name": "KIT-MRT/uniform_bspline", "max_issues_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/examples.cpp", "max_forks_repo_name": "KIT-MRT/uniform_bspline", "max_forks_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T09:22:34.000Z", "avg_line_length": 30.8016528926, "max_line_length": 117, "alphanum_fraction": 0.6721223504, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6634152076082793}}
{"text": "#include <mesh_array.h>\n#include <tiny.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <cmath>   // needed for std::sqrt and std::fabs\n\nBOOST_AUTO_TEST_SUITE(mesh_array);\n\nBOOST_AUTO_TEST_CASE(mesh_array_compute_distance_map_sphere)\n{\n  using std::sqrt;\n  using std::fabs;\n\n  typedef tiny::MathTypes<float> MT;\n  typedef MT::real_type          T;\n  \n  mesh_array::T3Mesh surf;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sX;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sY;\n  mesh_array::VertexAttribute<T,mesh_array::T3Mesh> sZ;\n\n  size_t const slices   = 12u;\n  size_t const segments = 24u;\n  T      const radius   = 12.0f;\n  \n  mesh_array::make_sphere<MT>(radius, slices, segments, surf, sX, sY, sZ);\n  \n  mesh_array::T4Mesh mesh;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> X;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> Y;\n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> Z;\n\n  mesh_array::tetgen(surf, sX, sY, sZ, mesh, X, Y, Z, mesh_array::tetgen_quality_settings() );\n  \n  mesh_array::VertexAttribute<T,mesh_array::T4Mesh> phi;\n  \n  mesh_array::compute_distance_map( mesh, X, Y, Z, phi );\n  \n  for (size_t i = 0u; i < phi.size(); ++i)\n  {\n    T const real_distance = radius - std::sqrt(X(i)*X(i) + Y(i)*Y(i) + Z(i)*Z(i));\n\n    BOOST_CHECK_CLOSE(  phi(i), real_distance, 1.0 );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "7e056d02a6fff9bc4dcd5733c6985d71ec51dae0", "size": 1522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_distance_map/mesh_array_compute_distance_map.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_distance_map/mesh_array_compute_distance_map.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_compute_distance_map/mesh_array_compute_distance_map.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["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.7169811321, "max_line_length": 94, "alphanum_fraction": 0.7109067017, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.663382293472609}}
{"text": "#pragma once\n\n#include \"out.hh\"\n#include \"types.hh\"\n\n#include \"eigen.hh\"\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <sophus/se2.hpp>\n#include <sophus/so2.hpp>\n\nnamespace raytrace {\nusing Vec1 = Vec<1>;\nusing Vec2 = Eigen::Vector2d;\nusing Vec3 = Eigen::Vector3d;\nusing Mat2 = Eigen::Matrix2d;\n\ndouble cost(const Vec3 &eta, const std::vector<Vec2> &x, const std::vector<Vec2> &z) {\n  const se2 T = se2::exp(eta);\n\n  double error_sq = 0.0;\n  for (std::size_t k = 0; k < x.size(); ++k) {\n    const Vec2 error = (T * x[k]) - z[k];\n    error_sq += error.squaredNorm();\n  }\n\n  return error_sq;\n}\n\nVec2 error(const Vec3 &eta, const std::vector<Vec2> &x, const std::vector<Vec2> &z) {\n  const se2 T = se2::exp(eta);\n\n  // double error_sq = 0.0;\n  Vec2 error_sq = Vec2::Zero();\n  for (std::size_t k = 0; k < x.size(); ++k) {\n    const Vec2 error = (T * x[k]) - z[k];\n    error_sq += error.array().square().matrix();\n  }\n\n  return error_sq;\n}\n\nstruct dExpSe2 {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  Eigen::Matrix2d Rprime;\n  Eigen::Matrix2d V;\n  Eigen::Matrix2d Vprime;\n  Vec3            eta;\n\n  Mat<2, 3> jacobian_from_y(const Vec2 &y) const {\n    Mat<2, 3> m;\n    m.setZero();\n    m.block<2, 2>(0, 0) = V;\n    m.block<2, 1>(0, 2) = (Rprime * y) + (Vprime * eta.head<2>());\n    return m;\n  }\n};\n\nvoid dexp_se2(const Vec3 &eta, Out<dExpSe2> jac) {\n  // todo: Use taylor exp instead of explicit sincos for stability near zero\n  const double c          = std::cos(eta(2));\n  const double s          = std::sin(eta(2));\n  const double inv_theta  = 1 / eta(2);\n  const double inv_theta2 = inv_theta * inv_theta;\n\n  const double cos_inv_theta  = c * inv_theta;\n  const double sin_inv_theta  = s * inv_theta;\n  const double sin_inv_theta2 = sin_inv_theta * inv_theta;\n\n  const double cos_m1_invtheta2 = (c - 1) * inv_theta2;\n\n  Eigen::Matrix2d v;\n  v.row(0) << s, (c - 1);\n  v.row(1) << 1 - c, s;\n  v *= inv_theta;\n\n  Eigen::Matrix2d dv_dtheta;\n  dv_dtheta.row(0) << cos_inv_theta - (sin_inv_theta2), -sin_inv_theta - (cos_m1_invtheta2);\n  dv_dtheta.row(1) << sin_inv_theta + cos_m1_invtheta2, cos_inv_theta - sin_inv_theta2;\n\n  Eigen::Matrix2d dR_dtheta;\n  dR_dtheta.row(0) << -s, -c;\n  dR_dtheta.row(1) << c, -s;\n\n  jac->Rprime = dR_dtheta;\n  jac->V      = v;\n  jac->Vprime = dv_dtheta;\n  jac->eta    = eta;\n}\n\nVec3 dcost(const Vec3 &eta, const std::vector<Vec2> &x, const std::vector<Vec2> &z) {\n  const se2 T = se2::exp(eta);\n  dExpSe2   preJ;\n  dexp_se2(eta, out(preJ));\n\n  Vec3 derror_sq_total = Vec3::Zero();\n  for (std::size_t k = 0; k < x.size(); ++k) {\n    const Vec2 error = (T * x[k]) - z[k];\n\n    const Mat<2, 3> derror_deta = preJ.jacobian_from_y(x[k]);\n    const Vec3 derror_sq = (2 * error.transpose()) * derror_deta;\n    derror_sq_total += derror_sq;\n  }\n\n  return derror_sq_total;\n}\n\ntemplate <int cols, typename Callable1, typename Callable2>\nEigen::Matrix<double, cols, 1> gauss_newton(const Eigen::Matrix<double, cols, 1> &x0,\n                                            const Callable1 &fcn,\n                                            const Callable2 &jac,\n                                            const double     feps      = 1e-6,\n                                            const int        max_iters = 15) {\n  using VecX     = Eigen::Matrix<double, 1, cols>;\n  using Gradient = Eigen::Matrix<double, cols, 1>;\n  VecX x         = x0;\n\n  double last_cost = fcn(x);\n  for (int k = 0; k < max_iters; ++k) {\n    // todo: llt\n    const Gradient J = jac(x);\n    const VecX     c = (J.transpose() * J).inverse() * J.transpose() * fcn(x);\n    x                = x - c;\n    double new_cost  = fcn(x);\n\n    if (std::abs(new_cost - last_cost) < feps) {\n      break;\n    }\n\n    last_cost = new_cost;\n  }\n  return x;\n}\n}", "meta": {"hexsha": "8de0b84c3c0aaae269e8e27094376d7ef5c23f11", "size": 3736, "ext": "hh", "lang": "C++", "max_stars_repo_path": "raytracing/optimization.hh", "max_stars_repo_name": "jpanikulam/experiments", "max_stars_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T11:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-14T11:40:28.000Z", "max_issues_repo_path": "raytracing/optimization.hh", "max_issues_repo_name": "IJDykeman/experiments-1", "max_issues_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T20:04:17.000Z", "max_forks_repo_path": "raytracing/optimization.hh", "max_forks_repo_name": "IJDykeman/experiments-1", "max_forks_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-24T03:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T03:45:47.000Z", "avg_line_length": 27.8805970149, "max_line_length": 92, "alphanum_fraction": 0.5885974304, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6633822831989303}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#ifndef NDHIST_STATS_VAR_HPP_INCLUDED\n#define NDHIST_STATS_VAR_HPP_INCLUDED 1\n\n#include <boost/python.hpp>\n\n#include <ndhist/ndhist.hpp>\n#include <ndhist/stats/expectation.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\ndouble\ncalc_axis_var_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    // Do the projection here, so it won't be done twice.\n    ndhist const proj = (h.get_nd() == 1 ? h : h.project(bp::object(axis)));\n\n    double expectation1 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 1, axis);\n    double expectation2 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 2, axis);\n\n    // V[x] = E[x^2] - E[x]^2\n    return expectation2 - expectation1*expectation1;\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the variance along the given axis of the given\n *     ndhist object. As in statistics, the variance is defined as\n *     :math:`V[x] = E[x^2] - E[x]^2`.\n *     This function generates a projection along the given axis and then\n *     calculates the variance.\n *     If None is given as axis, the variance for all individual axes of the\n *     ndhist object will be calculated and returned as a tuple. But if the\n *     dimensionality of the ndhist object is 1, a scalar value is returned.\n *\n * @note This function is only defined for ndhist objects with POD axis values\n *     AND POD weight values.\n */\nboost::python::object\nvar(\n    ndhist const & h\n  , boost::python::object const & axis = boost::python::object()\n);\n\n}// namespace py\n\n}// namespace stats\n}// namespace ndhist\n\n#endif // !NDHIST_STATS_VAR_HPP_INCLUDED\n", "meta": {"hexsha": "926fd19e8e36818ecee3f7d99d8af5ff874002e0", "size": 1880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/var.hpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "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/ndhist/stats/var.hpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "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/ndhist/stats/var.hpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "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.4788732394, "max_line_length": 100, "alphanum_fraction": 0.7015957447, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6633351349165535}}
{"text": "// neural_network.cpp example program using posit arithmetic for a neural network simulation\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#define MTL_WITH_INITLIST 1\n#include <boost/numeric/mtl/mtl.hpp>\n// select number system\n#include <universal/posit/posit>\n\n// Turn it off for now\n#undef USE_POSIT\n\ntemplate<size_t nbits, size_t es>\nsw::unum::posit<nbits, es> Sigmoid(sw::unum::posit<nbits, es>& x, bool derivative = false) {\n\tif (derivative) return x*(1-x);\n\treturn (1);\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\n#ifdef USE_POSIT\n\tusing Ty     = sw::unum::posit<8, 0>;\n\tusing Matrix = mtl::dense2D< Ty >;\n\tusing Vector = mtl::dense_vector< Ty >;\n#else\n\tusing Ty     = float;\n\tusing Matrix = mtl::dense2D<float>;\n\tusing Vector = mtl::dense_vector<float>;\n#endif\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n\tMatrix X = {\n\t\t{0,0,1},\n\t\t{0,1,1},\n\t\t{1,0,1},\n\t\t{1,1,1}\n\t};\n#endif\n\n\t// output data\n\tVector y = { 0.0f, 1.0f, 1.0f, 0.0f };\n\n\tcout << \"Weights are    :\\n\" << X << endl;\n\tcout << \"Training values: \" << y << endl;\n#if 0\n\t// synapse layers: syn0 = 2*np.random.random((3,4)) - 1\n\tMatrix synapse_L0(3,4);\n\tMatrix synapse_L1(4,1);\n\n    constexpr int TRAINING_STEPS     = 50000;\n    constexpr int REPORTING_INTERVAL = 10000;\n\n\t// training \n\tfor ( int j = 0; j < TRAINING_STEPS; j++ ) {\n\t\tMatrix l0 = X;\n\t\tMatrix l1 = Sigmoid<nbits, es>(dot(l0, synapse_L0));\n\t\tMatrix l2 = Sigmoid<nbits, es>(dot(l1, synapse_L1));\n\n\t\tVector l2_error = y - level_2;\n\n\t\tif (j % REPORTING_INTERVAL == 0) {\n\t\t\tcout << \"Error: \" << Mean(Abs(l2_error)) << '\\n';\n\t\t}\n\n\t\tl2_delta = l2_error * Sigmoid<nbits, es>(l2, true);\n\t\tl1_error = l2_delta.dot(Transpose(synapse_L1));\n\t\tl1_delta = l1_error * Sigmoid<nbits, es>(l1, true);\n\n\t\t// update weights\n\t\tsynapse_L1 += dot(Transpose(l1), l2_delta);\n\t\tsynapse_L0 += dot(Transpose(l0), l1_delta);\n\t}\n\n\tcout << \"Output after training\\n\";\n\tcout << l2 << endl;\n#endif\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << 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": "d87450b40b0cf9ac215e9cb634a8ed78d9013730", "size": 2503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/mlp/neural_network.cpp", "max_stars_repo_name": "stillwater-sc/hpr-dsp", "max_stars_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mlp/neural_network.cpp", "max_issues_repo_name": "stillwater-sc/hpr-dsp", "max_issues_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mlp/neural_network.cpp", "max_forks_repo_name": "stillwater-sc/hpr-dsp", "max_forks_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_forks_repo_licenses": ["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.5392156863, "max_line_length": 106, "alphanum_fraction": 0.660407511, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6633351318127639}}
{"text": "#ifndef CGWR_HPP\n#define CGWR_HPP\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n\n//#include <boost/rational.hpp>\n//#include <boost/math/special_functions/factorials.hpp>\n//#include <boost/math/special_functions/powm1.hpp>\n\n/*********************************************************************\n- CG:\n< j1 j2 m1 m2 | J M >\n\n- Wigner 3j or 6j:\n(j1,j2,j3) or {j1,j2,j3}\n(l1,l2,l3)    {m1,m2,m3}\n\n- Wigner 9j:\n{j1 j2 j3}\n{j4 j5 j6}\n{j7 j8 j9}\n\n-Racah:\nW(j1 j2 l2 l1 | j3 l3)\n\nCG translated as array=[j1,j2,m1,m2,J,M] with _CGWR::C_CG token\nor\nWigner 3j translated as array=[j1,j2,j3,m1,m2,m3] with _CGWR::C_W3j token\nor\nWigner 6j translated as array=[j1,j2,j3,l1,l2,l3] with _CGWR::C_W6j token\nor\nand so on with usual notations\n\n*********************************************************************/\n\nclass _CGWR { // Clebsch-Gordan Wigner Racah\npublic:\n    \n    // Token\n    /***********/\n    static const unsigned int C_CG;\n    static const unsigned int C_W3j;\n    static const unsigned int C_W6j;\n    static const unsigned int C_W9j;\n    static const unsigned int C_RACAH;\n    /***********/\n\n    \n    // Init the class with the coeff and the token\n    /***********/\n    _CGWR(double long [], unsigned int);\n    /***********/\n\n    _CGWR& operator= ( const _CGWR& other ); //TODO\n\n    \n    // Public methods\n    /***********/\n    double long CG(void);\n    double long W3j(void);\n    double long W6j(void);\n    double long W9j(void); //TODO\n    double long Racah(void);\n    /***********/\n\nprivate:\n    double long j1, j2, j3, j;\n    double long l1, l2, l3, l;\n    double long m1, m2 , m3, m;\n\n    unsigned int selected_Symb;\n\n    \n    // mid computations\n    /***********/\n    long double fact ( long double n ); // factorial\n    double long Delta(double long , double long , double long ); // triangle relation\n    double long delta_k(double long , double long ); // kronecker\n  \n    // variadic\n    template<typename _T>\n    bool is_integer(_T n); // return true if integer\n    template<typename _T, typename ..._args>\n    bool is_integer(_T, _args...);\n    \n    template<typename _T>\n    bool is_halfinteger(_T); // return true if half integer\n    template<typename _T, typename ..._args>\n    bool is_halfinteger(_T, _args...);\n    /***********/\n\n};\n\n#endif // CGWR_HPP\n\n", "meta": {"hexsha": "d2b774378f46373574ef9e6c0d4735b7c33e5aba", "size": 2283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cgwr.hpp", "max_stars_repo_name": "a-lemonnier/Simple_HFS", "max_stars_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T22:13:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T22:13:28.000Z", "max_issues_repo_path": "include/cgwr.hpp", "max_issues_repo_name": "a-lemonnier/Simple_HFS", "max_issues_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_issues_repo_licenses": ["MIT"], "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/cgwr.hpp", "max_forks_repo_name": "a-lemonnier/Simple_HFS", "max_forks_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_forks_repo_licenses": ["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.2959183673, "max_line_length": 85, "alphanum_fraction": 0.5799386772, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6632983810892937}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/bind.hpp>\n#include <boost/noncopyable.hpp>\n#include \"test_case.hpp\"\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include \"metro/ModifiedNewtonRaphson.hpp\"\n#include \"metro/ModifiedCholesky.hpp\"\n#include \"metro/CholeskyStepper.hpp\"\n\nBOOST_AUTO_TEST_SUITE( test_modified_newton_raphson ) ;\n\nnamespace impl {\n\ttypedef metro::SmoothFunction FunctionBase ;\n\n\tstruct Multimodal1d_1: public FunctionBase {\n\t\t// This function f has two local maxima and one local minimum\n\t\t// f(x) = -x^4 + 2x^2\n\t\t// f'(x) = -4x^3 + 4x\n\t\t// f''(x) = -12 x^2 + 4\n\t\t// maxima are at \\pm 1\n\t\t// minima is at 0\n\t\tvoid evaluate_at( Vector const& point, int const number_of_derivatives = 0 ) {\n\t\t\tassert( point.size() == 1 ) ;\n\t\t\tm_point = point ;\n\t\t}\n\n\t\tvoid evaluate( int const number_of_derivatives = 0 ) {}\n\t\t\n\t\tdouble get_value_of_function() const {\n\t\t\tassert( m_point.size() == 1 ) ;\n\t\t\treturn -std::pow( m_point(0), 4 ) + 2 * std::pow( m_point(0), 2 ) ;\n\t\t}\n\t\tEigen::VectorXd get_value_of_first_derivative() const {\n\t\t\tassert( m_point.size() == 1 ) ;\n\t\t\treturn Eigen::VectorXd::Constant( 1, -4.0 * std::pow( m_point(0), 3 ) + 4 * m_point(0) ) ; \n\t\t}\n\n\t\tEigen::MatrixXd get_value_of_second_derivative() const {\n\t\t\treturn Eigen::MatrixXd::Constant(\n\t\t\t\t1, 1,\n\t\t\t\t-12.0 * std::pow( m_point(0), 2 ) + 4.0\n\t\t\t) ;\n\t\t}\n\t\tint number_of_parameters() const { return 1 ; }\n\t\tVector const& parameters() const { return m_point ; }\n\t\t\n\t\tstd::string get_summary() const { return \"Multimodal1d_1\" ; }\n\tprivate:\n\t\tVector m_point ;\n\t} ;\n\n\tstruct Multimodal2d_1: public FunctionBase {\n\t\t// This function f has four local maxima and one local minimum.\n\t\t// We should walk to one of the maxima depending on where we start.\n\t\t// For appropriately modified NR, we should never walk to the minimum.\n\t\t// f' = -0.1 x^4 - 0.1 y^4 + x^2 + y^2\n\t\t// This has a minimum at (0,0)\n\t\t// And maxima at nonzero solutions of\n\t\t// -0.4 x^3 - 2x = 0 and -0.4 y^3 + 2y = 0\n\t\t// (x,y) = (\\pm sqrt(5), \\pm sqrt(5))\n\t\t//\n\t\t// First derivative is\n\t\t//\n\t\t// f' = ( -0.4 x^3 + 2x, -0.4 y^3 + 2y )\n\t\t//\n\t\t// Diagonals of second derivative are:\n\t\t// f'' = -1.2 x^2 + 2, -1.2 y^2 + 2\n\t\t//\n\t\t// With zeroes on off-diagonals\n\t\t//\n\t\tvoid evaluate_at( Vector const& point, int const number_of_derivatives = 0 ) {\n\t\t\tassert( point.size() == 2 ) ;\n\t\t\tm_point = point ;\n\t\t}\n\n\t\tvoid evaluate( int const number_of_derivatives = 0 ) {}\n\t\t\n\t\tdouble get_value_of_function() const {\n\t\t\treturn -0.1 * ( std::pow( m_point(0), 4 ) + std::pow( m_point(1), 4 ) )\n\t\t\t\t+ m_point(0) * m_point(0)\n\t\t\t\t+ m_point(1) * m_point(1)\n\t\t\t;\n\t\t}\n\t\tEigen::VectorXd get_value_of_first_derivative() const {\n\t\t\tEigen::VectorXd result ;\n\t\t\tresult.setZero(2) ;\n\t\t\tresult(0) = -0.4 * std::pow( m_point(0), 3 ) + 2.0 * m_point(0) ;\n\t\t\tresult(1) = -0.4 * std::pow( m_point(1), 3 ) + 2.0 * m_point(1) ;\n\t\t\treturn result ;\n\t\t}\n\n\t\tEigen::MatrixXd get_value_of_second_derivative() const {\n\t\t\tEigen::MatrixXd result ;\n\t\t\tresult.setZero(2,2) ;\n\t\t\tresult(0,0) = -1.2 * std::pow( m_point(0), 2 ) + 2.0 ;\n\t\t\tresult(1,1) = -1.2 * std::pow( m_point(1), 2 ) + 2.0 ;\n\t\t\treturn result ;\n\t\t}\n\n\t\tint number_of_parameters() const { return 2 ; }\n\t\tVector const& parameters() const { return m_point ; }\n\n\t\tstd::string get_summary() const { return \"Multimodal2d_1\" ; }\n\n\tprivate:\n\t\tVector m_point ;\n\t} ;\n\t\n\tstruct Rosenbrock: public FunctionBase {\n\t\t// Rosenbrock's function\n\t\t// has global minimum at (1,1)\n\t\t// f(x1,x2) = 100*(x2\u2212x1^2)^2+(1\u2212x1)^2\n\t\t// f'(x1,x2) = ( -4 * x1 * (x2\u2212x1^2) -2 * x1,  )\n\t\t// f''(x1,x2) = ( -400*x1-2 \n\t\tvoid evaluate_at( Vector const& point, int const number_of_derivatives = 0 ) {\n\t\t\tassert( point.size() == 2 ) ;\n\t\t\tm_point = point ;\n\t\t}\n\t\tdouble get_value_of_function() const {\n\t\t\tVector const& x = m_point ;\n\t\t\tVector x2 = m_point.array().square() ;\n\t\t\treturn 100.0 * (x(1) - x2(0)) * (x(1) - x2(0)) + (1 - x(0)) * (1 - x(0) )  ;\n\t\t}\n\n\t\tEigen::VectorXd get_value_of_first_derivative() const {\n\t\t\tassert(0) ;\n\t\t}\n\n\t\tEigen::MatrixXd get_value_of_second_derivative() const {\n\t\t\tassert(0) ;\n\t\t}\n\n\t\tint number_of_parameters() const { return 2 ; }\n\t\tVector const& parameters() const { return m_point ; }\n\n\t\tstd::string get_summary() const { return \"Rosenbrock\" ; }\n\n\tprivate:\n\t\tVector m_point ;\n\t} ;\n\t\n\n\t// The line search property of modified newton-raphson\n\t// should enable it to find a maximum even if we tell it to\n\t// jump way past it on each iteration.\n\t// This class heads for the maximum but goes 10 times too far.\n\ttemplate< typename Function >\n\tstruct OvershootTarget: public boost::noncopyable {\n\t\tOvershootTarget( FunctionBase::Vector target ):\n\t\t\tm_target( target )\n\t\t{}\n\t\t\n\t\tbool step( Function& function, FunctionBase::Vector* search_direction ) {\n\t\t\t// walk toward the target but go ten times too far.\n\t\t\tFunctionBase::Vector const& v = function.parameters() ;\n\t\t\tassert( v.size() == m_target.size() ) ;\n\t\t\tFunctionBase::Vector direction = m_target - v ;\n\n\t\t\tif( direction.array().abs().maxCoeff() < 1E-3 ) {\n\t\t\t\treturn false ;\n\t\t\t} else {\n\t\t\t\t(*search_direction) = 10.0 * direction ;\n\t\t\t\treturn true ;\n\t\t\t}\n\t\t}\n\t\t\n\tprivate:\n\t\tFunctionBase::Vector m_target ;\n\t} ;\n\t\n\ttemplate< typename Function >\n\tstruct StoppingCondition {\n\t\tStoppingCondition( double tolerance  = 1E-12 ):\n\t\t\tm_tolerance( tolerance ),\n\t\t\tm_iterations(0)\n\t\t\t{}\n\t\tbool operator()(\n\t\t\tFunction const& function,\n\t\t\tEigen::VectorXd const& step\n\t\t) {\n\t\t\t++m_iterations ;\n\t\t\t// Stop when all elements of the derivative are close to 0\n\t\t\t// and the step size is also close to zero.\n\t\t\treturn\n\t\t\t\tfunction.get_value_of_first_derivative().array().abs().maxCoeff() < m_tolerance\n\t\t\t\t&& step.array().abs().maxCoeff() < m_tolerance ;\n\t\t}\n\t\tstd::size_t iterations() const { return m_iterations ; }\n\tprivate:\n\t\tdouble m_tolerance ;\n\t\tstd::size_t m_iterations ;\n\t} ;\n}\n\nAUTO_TEST_CASE( test_newton_direction_1d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\ttypedef impl::FunctionBase::Matrix Matrix ;\n\timpl::Multimodal1d_1 function ;\n\tEigen::ColPivHouseholderQR< Matrix > solver ;\n\tdouble const one_third = 0.3333333333333333333333333 ;\n\tVector point( 1 ) ;\n\tfor( point(0) = -10; point(0) < 10; point(0) += 0.01 ) {\n\t\t// Check that the solver always finds an ascent direction\n\t\tfunction.evaluate_at( point ) ;\n\t\tsolver.compute( function.get_value_of_second_derivative() ) ;\n\t\tVector h = solver.solve( -function.get_value_of_first_derivative() ) ;\n\t\tdouble directional_derivative = function.get_value_of_first_derivative().transpose() * h ;\n\t\t// f''(x) = -12 x^2 + 4\n\t\t// so 2nd derivative is negative for x < sqtr\n\t\tBOOST_CHECK(\n\t\t\t( std::abs( point(0) ) > std::sqrt( one_third ) && directional_derivative > 0 )\n\t\t\t\t|| \n\t\t\t( std::abs( point(0) ) < std::sqrt( one_third ) && directional_derivative < 0 )\n\t\t) ;\n\t}\n}\n\nnamespace {\n\ttemplate< typename Function >\n\tstruct ModifiedCholeskySolver {\n\t\ttypedef impl::FunctionBase::Vector Vector ;\n\t\ttypedef impl::FunctionBase::Matrix Matrix ;\n\n\t\tVector compute( Function& function, Vector const& point ) {\n\t\t\tfunction.evaluate_at( point ) ;\n\t\t\tm_solver.compute( -function.get_value_of_second_derivative() ) ;\n\t\t\treturn m_solver.solve( function.get_value_of_first_derivative() ) ;\n\t\t} ;\n\t\t\n\tprivate:\n\t\tmetro::ModifiedCholesky< Matrix > m_solver ;\n\t} ;\n}\n\nAUTO_TEST_CASE( test_cholesky_stepper_direction_1d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\ttypedef impl::FunctionBase::Matrix Matrix ;\n\timpl::Multimodal1d_1 function ;\n\tmetro::CholeskyStepper stepper( 1E-12, 100 ) ;\n#if 0\n\t\t[]( int iteration,\n\t\t\tdouble ll,\n\t\t\tdouble target_ll,\n\t\t\tmetro::CholeskyStepper::Vector const& point,\n\t\t\tmetro::CholeskyStepper::Vector const& first_derivative,\n\t\t\tmetro::CholeskyStepper::Vector const& step,\n\t\t\tbool converged\n\t\t) {\n\t\t\tstd::cerr\n\t\t\t\t<< \" ITERATION:\" << iteration << \"\\n\"\n\t\t\t\t<< \"        LL:\" << ll << \"\\n\"\n\t\t\t\t<< \"    TARGET:\" << target_ll << \"\\n\"\n\t\t\t\t<< \"     POINT:\" << point.transpose() << \"\\n\"\n\t\t\t\t<< \"DERIVATIVE:\" << first_derivative.transpose() << \"\\n\"\n\t\t\t\t<< \"      STEP:\" << step.transpose() << \"\\n\"\n\t\t\t\t<< \" CONVERGED:\" << ( converged ? \"yes\" : \"no\" ) << \"\\n\" ;\n\t\t}\n\t ) ;\n#endif\n\tVector point( 1 ) ;\n\t// start at -10.005 to avoid meeting maxima or minima\n\tfor( point(0) = -10.005; point(0) < 10; point(0) += 0.01 ) {\n\t\tstepper.reset() ;\n\t\t// Check that the solver always finds an ascent direction\n\t\tfunction.evaluate_at( point ) ;\n\t\tVector h ;\n\t\tBOOST_CHECK( stepper.step( function, &h ) ) ;\n\t\tdouble directional_derivative = function.get_value_of_first_derivative().transpose() * h ;\n\t\t//std::cerr << \"x = \" << point(0) << \", function = \" << function.get_value_of_function()\n\t\t//\t<< \", derivative = \" << function.get_value_of_first_derivative().transpose() << \", \"\n\t\t//\t<< \"DD = \" << directional_derivative << \".\\n\" ;\n\t\tBOOST_CHECK_GT( directional_derivative, 0 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_cholesky_stepper_direction_2d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\ttypedef impl::FunctionBase::Matrix Matrix ;\n\timpl::Multimodal2d_1 function ;\n\tmetro::CholeskyStepper stepper( 1E-12, 100 ) ;\n\n\tVector point( 2 ) ;\n\t// start at -10.01 so we do not reach 0 (where there is a maximum)\n\tfor( point(0) = -10.01; point(0) < 10; point(0) += 0.025 ) {\n\t\tfor( point(1) = -10.01; point(1) < 10; point(1) += 0.025 ) {\n\t\t\tstepper.reset() ;\n\t\t\tfunction.evaluate_at( point ) ;\n\t\t\tVector h ;\n\t\t\tstepper.step( function, &h ) ;\n\t\t\tdouble const directional_derivative = function.get_value_of_first_derivative().transpose() * h ;\n\t\t\tBOOST_CHECK_GT( directional_derivative, 0 ) ;\n\t\t}\n\t}\n}\n\nAUTO_TEST_CASE( test_modified_ewton_raphson_overshoot_1d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\timpl::Multimodal1d_1 function ;\n\t\n\t// For 1d function 1, maxima are at -1 and 1.\n\tVector target ;\n\ttarget.setZero(1) ;\n\ttarget(0) = -1 ;\n\n\t{\n\t\timpl::OvershootTarget< impl::Multimodal1d_1 > overshoot( target ) ;\n\t\tVector start = Vector::Constant( 1, -0.001 ) ;\n\t\tVector result = metro::find_maximum_by_modified_newton_raphson_with_line_search(\n\t\t\tfunction,\n\t\t\tstart,\n\t\t\tovershoot\n\t\t) ;\n\n\t\tBOOST_CHECK_CLOSE( result(0), -1, 0.1 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_newton_raphson_overshoot_2d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\timpl::Multimodal2d_1 function ;\n\n\tVector maximum ;\n\tmaximum.setZero(2) ;\n\tmaximum(0) = -sqrt(5) ;\n\tmaximum(1) = -sqrt(5) ;\n\n\t{\n\t\timpl::OvershootTarget< impl::Multimodal2d_1 > overshoot( maximum ) ;\n\t\tVector start = Vector::Constant(2,-1) ;\n\t\tVector result = metro::find_maximum_by_modified_newton_raphson_with_line_search(\n\t\t\tfunction,\n\t\t\tstart,\n\t\t\tovershoot\n\t\t) ;\n\n\t\tBOOST_CHECK_CLOSE( result(0), -std::sqrt(5), 0.1 ) ;\n\t\tBOOST_CHECK_CLOSE( result(1), -std::sqrt(5), 0.1 ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_modified_cholesky_newton_raphson_2d ) {\n\ttypedef impl::FunctionBase::Vector Vector ;\n\timpl::Multimodal2d_1 function ;\n\n\t{\n\t\tmetro::CholeskyStepper solver( 1E-12, 100 ) ;\n\t\tVector start = Vector::Constant(2,-1) ;\n\t\tVector result = metro::find_maximum_by_modified_newton_raphson_with_line_search(\n\t\t\tfunction,\n\t\t\tstart,\n\t\t\tsolver\n\t\t) ;\n\t\t\t\n\t\tBOOST_CHECK_CLOSE( result(0), -std::sqrt(5), 0.1 ) ;\n\t\tBOOST_CHECK_CLOSE( result(1), -std::sqrt(5), 0.1 ) ;\n\t\tstd::cerr << \"test_newton_raphson_overshoot_2d: took \" << solver.number_of_iterations() << \" iterations.\\n\" ;\n\t}\n\t{\t\n\t\tmetro::CholeskyStepper solver( 1E-12, 100 ) ;\n\t\tVector start = Vector::Constant(2,-1) ;\n\t\tstart(1) = -0.1 ;\n\t\tVector result = metro::find_maximum_by_modified_newton_raphson_with_line_search(\n\t\t\tfunction,\n\t\t\tstart,\n\t\t\tsolver\n\t\t) ;\n\t\t\t\n\t\tBOOST_CHECK_CLOSE( result(0), -std::sqrt(5), 0.1 ) ;\n\t\tBOOST_CHECK_CLOSE( result(1), -std::sqrt(5), 0.1 ) ;\n\t\tstd::cerr << \"test_newton_raphson_overshoot_2d: took \" << solver.number_of_iterations() << \" iterations.\\n\" ;\n\t}\n\t{\n\t\tmetro::CholeskyStepper solver( 1E-12, 100 ) ;\n\t\tVector start = Vector::Constant(2,-1) ;\n\t\tstart(0) = -100 ;\n\t\tstart(1) = -0.1 ;\n\t\tVector result = metro::find_maximum_by_modified_newton_raphson_with_line_search(\n\t\t\tfunction,\n\t\t\tstart,\n\t\t\tsolver\n\t\t) ;\n\t\t\t\n\t\tBOOST_CHECK_CLOSE( result(0), -std::sqrt(5), 0.1 ) ;\n\t\tBOOST_CHECK_CLOSE( result(1), -std::sqrt(5), 0.1 ) ;\n\t\tstd::cerr << \"test_newton_raphson_overshoot_2d: took \" << solver.number_of_iterations() << \" iterations.\\n\" ;\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a35ba9a27dd3d5fa83d81ea6659089830f6e8919", "size": 12337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/test/test_modified_newton_raphson.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/test/test_modified_newton_raphson.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/test/test_modified_newton_raphson.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "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.0755667506, "max_line_length": 111, "alphanum_fraction": 0.6565615628, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6632983721084316}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include \"args.hxx\"\n\n#include <fstream>\n#include <iostream>\n\nusing ChartType = Eigen::Matrix<double, 24, 3>;\nusing ChartHmType = Eigen::Matrix<double, 24, 4>;\nusing CCMType = Eigen::Matrix<double, 4, 3>;\n\n\nstd::vector<std::string> StringSplit(const std::string &str, char sep) {\n    std::vector<std::string> v;\n    std::stringstream ss(str);\n    std::string buffer;\n    while( std::getline(ss, buffer, sep) ) {\n        v.push_back(buffer);\n    }\n    return v;\n}\n\n\nbool LoadColorchartCsv(const std::string& filename, ChartType& dst_chart) {\n    std::ifstream ifs(filename);\n    if (!ifs) {\n        std::cout << \"Can't open \" << filename << std::endl;\n        return false;\n    }\n\n    std::string str;\n    std::getline(ifs, str); // skip first line\n\n    int i = 0;\n    while (std::getline(ifs, str)) {\n        std::vector<std::string> data_str = StringSplit(str, ',');\n        dst_chart(i, 0) = std::stod(data_str[1]);\n        dst_chart(i, 1) = std::stod(data_str[2]);\n        dst_chart(i, 2) = std::stod(data_str[3]);\n        i++;\n        if (i == 24) break;\n    }\n    return true;\n}\n\nvoid conv_sRGB2XYZ(const ChartType &rgb, ChartType &xyz) {\n    Eigen::Matrix<double, 3, 3> M;\n    M << 0.412391, 0.357584, 0.180481,\n         0.212639, 0.715169, 0.072192,\n         0.019331, 0.119195, 0.950532;\n    xyz = (M * rgb.transpose()).transpose();\n}\n\nvoid SolveCCM(const ChartType& source_xyz, const ChartType& reference_xyz,\n              CCMType &ccm) {\n    // source_xyz * ccm == reference_xyz\n    // (24, 3 + 1) * (4, 3) = (24 * 3)\n    ChartHmType source_xyz_hm;\n    source_xyz_hm.col(0) = source_xyz.col(0);\n    source_xyz_hm.col(1) = source_xyz.col(1);\n    source_xyz_hm.col(2) = source_xyz.col(2);\n    source_xyz_hm.col(3) = Eigen::VectorXd::Ones(24);\n    auto source_xyz_hm_t = source_xyz_hm.transpose();\n    auto pinv = (source_xyz_hm_t * source_xyz_hm).inverse() * source_xyz_hm_t;\n    ccm = pinv * reference_xyz;\n}\n\nvoid WriteCCM(const std::string &filename, const CCMType& ccm) {\n    std::ofstream csv(filename);\n    for (int i = 0; i < 4; i++) {\n        csv << ccm(i, 0) << \",\"\n            << ccm(i, 1) << \",\"\n            << ccm(i, 2) << std::endl;\n    }\n}\n\nbool ParseArgs(const int argc, char** argv, std::string& ref_csv,\n               std::string& src_csv, std::string& out_csv, double& gamma) {\n    args::ArgumentParser parser(\"Compute CCM.\");\n    args::HelpFlag help(parser, \"help\", \"Display this help menu\",\n                        {'h', \"help\"});\n    args::Positional<std::string> ref_csv_arg(parser, \"reference\",\n                                              \"reference csv file\");\n    args::Positional<std::string> src_csv_arg(parser, \"source\",\n                                              \"source csv file\");\n    args::Positional<std::string> out_csv_arg(parser, \"output\",\n                                              \"output csv file\", \"ccm.csv\");\n    args::ValueFlag<double> gamma_arg(parser, \"gamma\",\n                                     \"Gamma value of reference and source data\",\n                                     {'g', \"gamma\"}, 1.0);\n    try {\n        parser.ParseCLI(argc, argv);\n    } catch (args::Help) {\n        std::cout << parser;\n        return false;\n    } catch (args::ParseError e) {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return false;\n    } catch (args::ValidationError e) {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return false;\n    }\n    if (!ref_csv_arg) {\n        std::cout << \"Error: reference is not set\" << std::endl;\n        std::cout << parser;\n        return false;\n    }\n    if (!src_csv_arg) {\n        std::cout << \"Error: src is not set\" << std::endl;\n        std::cout << parser;\n        return false;\n    }\n\n    ref_csv = args::get(ref_csv_arg);\n    src_csv = args::get(src_csv_arg);\n    out_csv = args::get(out_csv_arg);\n    gamma = args::get(gamma_arg);\n\n    return true;\n}\n\nint main(int argc, char** argv) {\n    // Parse arguments\n    std::string ref_csv, src_csv, out_csv;\n    double gamma;\n    if (!ParseArgs(argc, argv, ref_csv, src_csv, out_csv, gamma)) {\n        return 1;\n    }\n\n    // Load color charts\n    ChartType reference_raw, source_raw;\n    if (!LoadColorchartCsv(ref_csv, reference_raw)) {\n        return 1;\n    }\n    if (!LoadColorchartCsv(src_csv, source_raw)) {\n        return 1;\n    }\n\n    // Degamma\n    ChartType reference_linear = reference_raw.array().pow(gamma);\n    ChartType source_linear = source_raw.array().pow(gamma);\n\n    // XYZ\n    ChartType reference_xyz, source_xyz;\n    conv_sRGB2XYZ(reference_linear, reference_xyz);\n    conv_sRGB2XYZ(source_linear, source_xyz);\n\n    // Solve\n    CCMType ccm;\n    SolveCCM(source_xyz, reference_xyz, ccm);\n    std::cout << \"CCM:\" << std::endl;\n    std::cout << ccm << std::endl;\n\n    // Save\n    WriteCCM(out_csv, ccm);\n\n    return 0;\n}\n", "meta": {"hexsha": "69ea3899099b56e42d572c82848bf3ac4ccf696b", "size": 4890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/computeCCM.cc", "max_stars_repo_name": "lighttransport/colorcorrectionmatrix", "max_stars_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2018-04-15T16:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:11:49.000Z", "max_issues_repo_path": "cpp/src/computeCCM.cc", "max_issues_repo_name": "lighttransport/colorcorrectionmatrix", "max_issues_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T18:32:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T14:39:26.000Z", "max_forks_repo_path": "cpp/src/computeCCM.cc", "max_forks_repo_name": "lighttransport/colorcorrectionmatrix", "max_forks_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T01:50:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:52:52.000Z", "avg_line_length": 30.1851851852, "max_line_length": 80, "alphanum_fraction": 0.5701431493, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6632983704565156}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// Based on Ellis, Daniel P.W. \"Chroma feature analysis and synthesis\"\n// https://www.ee.columbia.edu/~dpwe/resources/matlab/chroma-ansyn/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass ChromaFilterBank\n{\npublic:\n  ChromaFilterBank(index maxBins, index maxFFT)\n      : mFiltersStorage(maxBins, maxFFT / 2 + 1)\n  {}\n\n\n  void init(index nChroma, index nBins, double ref, double sampleRate)\n  {\n    using namespace Eigen;\n    const double log2E = 1.44269504088896340736;\n    index fftSize = 2 * (nBins - 1);\n    ArrayXd freqs = ArrayXd::LinSpaced(fftSize, 0, sampleRate);\n    freqs = nChroma * (freqs / (ref / 16)).log() * log2E;\n    freqs[0] = freqs[1] - 1.5 * nChroma;\n\n    ArrayXd widths =  ArrayXd::Ones(fftSize);\n    widths.segment(0, fftSize - 1) =\n        freqs.segment(1, fftSize - 1) -\n        freqs.segment(0, fftSize - 1);\n    widths = widths.max(1.0);\n    ArrayXXd diffs =\n      freqs.replicate(1, nChroma).transpose() -\n      ArrayXd::LinSpaced(nChroma, 0, nChroma - 1).transpose().replicate(fftSize, 1).transpose();\n    index halfChroma = std::lrint(nChroma / 2);\n    ArrayXXd remainder =  diffs.unaryExpr([&](const double x){\n        return std::fmod(x + 10* nChroma + halfChroma, nChroma) - halfChroma;\n    });\n    MatrixXd filters = (-0.5 * (2 * remainder / widths.replicate(1, nChroma).transpose()).square()).exp();\n    filters = filters.block(0, 0, nChroma, nBins);\n    filters.colwise().normalize();\n    mFiltersStorage.setZero();\n    mFiltersStorage.block(0, 0, nChroma, nBins) = filters;\n    mNChroma = nChroma;\n    mNBins = nBins;\n    mScale = 2.0 / (fftSize * mNChroma);\n    mSampleRate = sampleRate;\n  }\n\n  void processFrame(const RealVectorView in, RealVectorView out,\n    double minFreq = 0, double maxFreq = -1, index normalize = 0)\n  {\n    using namespace Eigen;\n    using namespace std;\n    ArrayXd frame = _impl::asEigen<Eigen::Array>(in);\n    Eigen::Ref<Eigen::MatrixXd> filters = mFiltersStorage.block(0, 0, mNChroma, mNBins);\n\n    if(minFreq != 0 || maxFreq != -1){\n        maxFreq = (maxFreq == -1) ? (mSampleRate / 2) : min(maxFreq, mSampleRate / 2);\n        double  binHz = mSampleRate / ((mNBins - 1) * 2.);\n        index   minBin = minFreq == 0? 0 : ceil(minFreq / binHz);\n        index   maxBin =\n            min(static_cast<index>(floorl(maxFreq / binHz)), (mNBins - 1));\n        frame.segment(0, minBin).setZero();\n        frame.segment(maxBin, frame.size() - maxBin).setZero();\n    }\n\n    ArrayXd result = mScale * (filters * frame.square().matrix()).array();\n\n    if (normalize > 0) {\n      double norm = normalize == 1? result.sum() : result.maxCoeff();\n      result = result / std::max(norm, epsilon);\n    }\n    out = _impl::asFluid(result);\n  }\n\n  index mNChroma;\n  index mNBins;\n  double mScale;\n  double mSampleRate;\n  Eigen::MatrixXd mFiltersStorage;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "610da73f6a0d7c9ed4a03da74a2a84624f8f8dc8", "size": 3447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/ChromaFilterBank.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/ChromaFilterBank.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/ChromaFilterBank.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": 34.1287128713, "max_line_length": 106, "alphanum_fraction": 0.6614447346, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346504434783, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.6631785741142865}}
{"text": "/**\n * Contains various primitive datatypes for SISL, most of which derive from\n * Eigen datatypes.\n *\n * @author Joshua Horacsek\n */\n\n#ifndef _SISL_PRIMITIVE_H_\n#define _SISL_PRIMITIVE_H_\n\n#include <Eigen/Dense>\n\n// By default, SISL will do all floating point arithmetic in double precision\n#ifndef sisl_float\n    #define sisl_float double\n#endif\n\nnamespace sisl {\n    \n    // Basic primitive datatypes\n    //! dynamically sized (mathematical) vector datatype\n    using vector       = Eigen::Matrix<sisl_float, Eigen::Dynamic, 1>; \n    //! dynamically size point datatype\n    using point        = Eigen::Matrix<sisl_float, Eigen::Dynamic, 1>; \n    //! Dynamically sized transform (i.e. matrix)\n    using transform    = Eigen::Matrix<sisl_float, Eigen::Dynamic, Eigen::Dynamic>; \n    \n    //! A fixed size 3-vector for holding colours\n    using rgb_color    = Eigen::Matrix<sisl_float, 3, 1>; \n    //! A fixed size 4-vector for holding colours and an alpha channel \n    using rgba_color   = Eigen::Matrix<sisl_float, 4, 1>; \n    //! Lattice_site are integer tuples (vectors)\n    using lattice_site = Eigen::Matrix<int, Eigen::Dynamic, 1>; \n    //! integer tuples (vectors)\n    using int_tuple    = Eigen::Matrix<int, Eigen::Dynamic, 1>; \n\n    /*! The various datatypes SISL can read, mainly used in the raw filetype reader */\n    enum e_datatype {\n        SDT_UNKNOWN = -1,\n        SDT_UINT8 = 0,\n        SDT_UINT16 = 1,\n        SDT_UINT32 = 2,\n        SDT_FLOAT = 3,\n        SDT_DOUBLE = 4\n    };\n\n    /*! \\brief 3D plane class.\n     *\n     * A plain plane class. \n     */\n    struct plane {\n        vector     n; //!< normal direction\n        sisl_float d; //!< normal offset\n        \n        /*! Plane constructor\n         * \\param _n Input normal direction (note, this will get normalized on assignment).\n         * \\param _d Input normal offset.\n         */\n        plane(const vector &_n, const sisl_float &_d) : n(_n), d(_d) { }\n        /*! Plane copy constructor\n         * \\param _p A plane to copy\n         */\n        plane(const plane &_p) : n(_p.n), d(_p.d) { }\n    };\n\n    /*! \\brief 3D vertex.\n     *\n     * A vertex in the graphics sense, i.e. a spatial point, and a normal to help shading \n     * heuristics.\n     */\n    struct vertex3 {\n        vector p; //!< vertex spatial location \n        vector n; //!< vertex normal direction\n\n        /*! Vertex constructor\n         * \\param _p Spatial location of a point.\n         * \\param _n Point normal.\n         */\n        vertex3(const vector &_p, const vector &_n) : p(_p), n(_n) { }\n        \n        /*! Vertex constructor\n         * \\param x,y,z Spatial location of a point.\n         * \\param i,j,k Point normal.\n         */\n        vertex3(\n            const double &x, const double &y, const double &z, \n            const double &i, const double &j, const double &k) : p(vector(3)), n(vector(3)) {\n            p << x,y,z;\n            n << i,j,k;\n        }\n        /*! Vertex copy constructor\n         * \\param _v A vertex to copy\n         */\n        vertex3(const vertex3 &_v) : p(_v.p), n(_v.n) { }\n    };\n\n    /** \\brief Triangle in 3D space.\n     * \n     * A collection of three points that creates a ploygon in space\n     */\n    struct triangle {\n        vertex3 v1; //!< triangle vertex 1 \n        vertex3 v2; //!< triangle vertex 2\n        vertex3 v3; //!< triangle vertex 3 \n\n        /*! Ray constructor\n         * \\param _v1,_v2,_v3 The vertices that make up a triangle.\n         */\n        triangle(const vertex3 &_v1, \n                 const vertex3 &_v2, \n                 const vertex3 &_v3) : v1(_v1), v2(_v2), v3(_v3) { }\n        /*! Plane copy constructor\n         * \\param _p A plane to copy\n         */\n        triangle(const triangle &_t) : v1(_t.v1), v2(_t.v2), v3(_t.v3) { } \n    };\n\n    /*! \\brief A ray in space.\n     * \n     * A ray class, i.e. a half line.\n     */\n    struct ray {\n        point  o; //!< ray origin\n        vector d; //!< ray direction\n\n        /*! Ray constructor\n         * \\param _o Input ray origin.\n         * \\param _d Input ray direction.\n         */\n        ray(const point &_o, const vector &_d) : o(_o), d(_d.normalized()) { }\n\n        /*! Ray copy constructor\n         * \\param _r Ray to copy\n         */\n        ray(const ray &_r) : o(_r.o), d(_r.d.normalized()) { }\n\n        /*! Returns the point at a distinance t away from the ray,\n         *  travelling in the direction of the ray.\n         * \\param t Distance along ray from origin\n         */\n        point at(const sisl_float &t) {return o+t*d;}\n    };\n}\n#endif // _SISL_PRIMITIVE_H_", "meta": {"hexsha": "e4b9dedda79f3a12518fb03f94b603326c85ec82", "size": 4563, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sisl/primitives.hpp", "max_stars_repo_name": "jjh13/sisl_redux", "max_stars_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-01T16:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-19T22:07:44.000Z", "max_issues_repo_path": "include/sisl/primitives.hpp", "max_issues_repo_name": "jjh13/sisl_redux", "max_issues_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:07:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-05T18:36:24.000Z", "max_forks_repo_path": "include/sisl/primitives.hpp", "max_forks_repo_name": "jjh13/sisl", "max_forks_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_forks_repo_licenses": ["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.6875, "max_line_length": 93, "alphanum_fraction": 0.5616918694, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6631375956206159}}
{"text": "#define BOOST_TEST_MODULE Exponentiation test\n#include <boost/test/unit_test.hpp>\n\n#include \"Variable.h\"\n#include \"Sum.h\"\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(Exponentiation_tests)\n{\n    auto a = 2_v ^ 3;\n    BOOST_TEST(a==8);\n    a = 2_v ^ 11;\n    BOOST_TEST(a==(1<<11));\n    Variable x;\n    auto _1 = (x-2)^3;\n    auto _2 = (x-2)*(x-2)*(x-2);\n    BOOST_TEST(_1==_2);\n    _1 = -32;\n    _1 ^= .5;\n    _2 = 4;\n    _2 *= -2_v^(1_v/2);\n    BOOST_TEST(_1==_2);\n    _1 = -1_v*((-4_v)^(1_v/2))*((-16_v)^((1_v/2)));\n    _2 = 8;\n    BOOST_TEST(_1==_2);\n    \n    _1 = (((x-2)^2)+((x+2)^2));\n    _1 = _1(x);\n    _2 = ((-1)^(1_v/2))*2;\n    BOOST_TEST(_1==_2);\n}\n\nBOOST_AUTO_TEST_CASE(Compare_test)\n{\n    auto _1 = 25 ^ Fraction{1_v,-2};\n    auto _2 = (1_v / 5)*(1_v^(1_v/2));\n    if (_1.IsProduct())\n        for(auto&a:_1.as<Product>())\n            std::cout << a.Hash() << std::endl;\n    if (_2.IsProduct())\n        for(auto&a:_2.as<Product>())\n            std::cout << a.Hash() << std::endl;\n    auto c = _1 == _2;\n    BOOST_TEST(c);\n    \n    DECL_VA(x);\n    _1 =(-1_v)^x;\n    _2 = (-1_v)^((1_v/2)*x + _1/4 + ((-1_v)/4));\n    c = _1 != _2;\n    BOOST_TEST(c);\n}\n\nBOOST_AUTO_TEST_CASE(Sqrt_test)\n{\n    auto a = 25_v;\n    auto e = a ^ (1_v/2);\n    auto c = e == (1_v^(1_v/2))*5;\n    BOOST_TEST(c);\n    BOOST_TEST(e != 5);\n    // https://math.stackexchange.com/questions/41784/convert-any-number-to-positive-how/41787#comment5776496_41787\n    e = a.Sqrt();\n    BOOST_TEST(e == 5);\n}\n\nBOOST_AUTO_TEST_CASE(Polynomial_Sqrt_test\n                     ,*disabled()\n                     )\n{\n    Variable x,y;\n    auto a = 4*(x^2)-12*x*y+9*(y^2);\n    auto e = a.Sqrt();\n    BOOST_TEST(e == 2*x-3*y);\n}\n\nBOOST_AUTO_TEST_CASE(Polynomial_Exp_test\n                     ,*disabled()\n                     )\n{\n    auto v = \"v\"_va;\n    auto a = \"a\"_va;\n    auto b = \"b\"_va;\n    \n    auto _ = (4_v*(v^2) + 2048)^(1_v/2);\n    _.SetView(Valuable::View::Solving);\n    _.optimize();\n    \n    auto t=4_v;\n    auto c=2048_v;\n    auto _2ab=2_v*a*b;\n    auto d = (-_2ab).sq() + 4_v*(t-a.Sq())*(b.Sq()-c);\n    auto x = (_2ab+(d^(1_v/2)))/(2_v*(t-a.Sq()));\n    _.eval({{v,x}});\n    auto ab = 0_v;\n    _.eval({{b,ab}});\n    \n    auto& ebs = _.as<Exponentiation>().getBase().as<Sum>();\n    for(auto& m: ebs){\n//        if (m.) {\n//            <#statements#>\n//        }\n    }\n    auto it = ebs.begin();\n    auto m1 = *it;\n    for(auto& v: it->getCommonVars())\n        std::cout << v.first.str() << '^' << v.second.str() << std::endl;\n    auto m2 =*++it;\n    auto ms = m1+m2;\n//    Valuable f = Fraction{\n    \n//    auto av = _(a);\n    _.optimize();\n\n    {\n    DECL_VA(x);\n    auto _ = ((-18_v*(x^2) + 108*x -180)^((1/3)));\n    _.SetView(Valuable::View::Equation);\n    _.optimize();\n    }\n}\n\n// TODO : check with mathematicians which way is correct, fix te test and enable it\nBOOST_AUTO_TEST_CASE(Multival_test\n                    ,*disabled()\n                    )\n{\n    auto a = 1_v ^ (1_v/2);\n    BOOST_TEST(!!a.IsMultival() == true);\n    \n    DECL_VA(x);\n    BOOST_TEST(!!x.IsMultival() == true);\n    a = x / x;\n    \n    // Waht is the value of a?\n    // first impression is that x/x is allways 1\n    // what about multivalue expressions like this?\n    // it equals both values by disjunction: either -1 or 1 at the same time\n    // this would be a circle function on image\n    // the division of multiples we could apply in an alternative way:\n    // permutations of the operation on possible values:\n    // [-1/1, 1/1, 1/-1, -1/-1]  => [1, -1] != 1\n    // so this way the answer should remain multival 1^(1/2)\n    // 1^(1/2) / 1^(1/2) == 1^(1/2)\n    // TODO : check with mathematicians which way is correct, fix te test and enable it\n    BOOST_TEST(a != 1);\n    \n    \n    BOOST_TEST(!!a.IsMultival() == true);\n    BOOST_TEST(a == x/x);\n}\n", "meta": {"hexsha": "6db88dd1097313f25931c235566694d9894b21b8", "size": 3849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/Exponentiation_test.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/test/Exponentiation_test.cpp", "max_issues_repo_name": "ApusDT/openmind", "max_issues_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "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": "omnn/math/test/Exponentiation_test.cpp", "max_forks_repo_name": "ApusDT/openmind", "max_forks_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "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.4900662252, "max_line_length": 115, "alphanum_fraction": 0.5227331774, "num_tokens": 1309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6631375934221515}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"arithmetique_modulaire.h\"\n\nBOOST_AUTO_TEST_SUITE(test_arithmetique_modulaire)\n\n    struct fixure_arithmetiques {\n        std::vector<size_t> premiers;\n\n        explicit fixure_arithmetiques() {\n            premiers = std::vector<size_t>{2, 3, 5, 7, 11, 13, 17, 19, 23, 29,\n                                           31, 37, 41, 43, 47, 53, 59, 61, 67,\n                                           71, 73, 79, 83, 89, 97};\n        }\n\n        ~fixure_arithmetiques() = default;\n    };\n\n    BOOST_FIXTURE_TEST_CASE(inverse1, fixure_arithmetiques) {\n        BOOST_CHECK_EQUAL(arithmetique_modulaire::inverse_modulaire<unsigned long>(3, 11, premiers), 4);\n        BOOST_CHECK_EQUAL(arithmetique_modulaire::inverse_modulaire<unsigned long long>(97643, 456753, premiers),\n                          368123);\n        BOOST_CHECK_EQUAL(\n                arithmetique_modulaire::inverse_modulaire<unsigned long long>(107113, 3246999210ULL, premiers),\n                180730717ULL);\n    }\n\n    BOOST_FIXTURE_TEST_CASE(inverse2, fixure_arithmetiques) {\n        BOOST_CHECK_EQUAL(arithmetique_modulaire::inverse_modulaire<long>(3, 11), 4);\n        BOOST_CHECK_EQUAL(arithmetique_modulaire::inverse_modulaire<long long>(97643, 456753), 368123);\n        BOOST_CHECK_EQUAL(arithmetique_modulaire::inverse_modulaire<long long>(107113, 3246999210LL),\n                          180730717LL);\n    }\n\n    BOOST_FIXTURE_TEST_CASE(chinois1, fixure_arithmetiques) {\n        std::vector<unsigned long> modulos{3, 5, 7};\n        std::vector<unsigned long> restes{2, 3, 2};\n\n        auto reste = arithmetique_modulaire::restes_chinois<unsigned long>(modulos, restes, premiers);\n        BOOST_CHECK_EQUAL(reste, 23);\n    }\n\n    BOOST_FIXTURE_TEST_CASE(chinois2, fixure_arithmetiques) {\n        std::vector<unsigned long> modulos{3, 4, 5};\n        std::vector<unsigned long> restes{2, 3, 1};\n\n        auto reste = arithmetique_modulaire::restes_chinois<unsigned long>(modulos, restes, premiers);\n        BOOST_CHECK_EQUAL(reste, 11);\n    }\n\n    BOOST_FIXTURE_TEST_CASE(chinois3, fixure_arithmetiques) {\n        std::vector<long> modulos{3, 5, 7};\n        std::vector<long> restes{2, 3, 2};\n\n        auto reste = arithmetique_modulaire::restes_chinois<long>(modulos, restes);\n        BOOST_CHECK_EQUAL(reste, 23);\n    }\n\n    BOOST_FIXTURE_TEST_CASE(chinois4, fixure_arithmetiques) {\n        std::vector<long> modulos{3, 4, 5};\n        std::vector<long> restes{2, 3, 1};\n\n        auto reste = arithmetique_modulaire::restes_chinois<long>(modulos, restes);\n        BOOST_CHECK_EQUAL(reste, 11);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cea6345322e7ef418a82b354806c95b1ee93fb9b", "size": 2641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/arithmetique_modulaire.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "tests/arithmetique_modulaire.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/arithmetique_modulaire.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": 38.8382352941, "max_line_length": 113, "alphanum_fraction": 0.6527830367, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6631259080324597}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\ndouble* diff_ts(double *y, int len, double dt)\n{\n  double *dy;\n  dy = new double[len];\n\n  dy[0] = y[0];\n  for (int i = 1; i<len; i++)\n  {\n    dy[i] = (y[i] - y[i-1])/dt;\n  }\n  return dy;\n}\n\nmat diffMat( int len, int DIM, double dt, mat y)\n{\n  mat dy(DIM, len) ;\n  for (int d = 0; d<DIM; d++)\n  {\n    for (int i = 1; i<len; i++)\n    {\n      dy(d,i) = (y(d,i) - y(d,i-1))/dt;\n    }\n    dy(d,0) = dy(d,1);\n\n  }\n  return dy;\n\n}\n", "meta": {"hexsha": "ba4370465afc9b6e383e1eda9657428d5d31938c", "size": 510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/diff.cpp", "max_stars_repo_name": "despargy/KukaImplementation-kinetic", "max_stars_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T12:49:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T12:49:27.000Z", "max_issues_repo_path": "src/diff.cpp", "max_issues_repo_name": "despargy/KukaImplementation-kinetic", "max_issues_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_issues_repo_licenses": ["MIT"], "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/diff.cpp", "max_forks_repo_name": "despargy/KukaImplementation-kinetic", "max_forks_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5714285714, "max_line_length": 48, "alphanum_fraction": 0.5058823529, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.663015723559468}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::vector;\n    using namespace MyDL;\n\n    int n = 1;\n    int c = 1;\n    int h = 2;\n    int w = 2;\n    int Fn = 2;\n    int Fh = 2;\n    int Fw = 2;\n    int stride = 1;\n    int pad = 1;\n\n    Conv2D conv(c, h, w, Fn, Fh, Fw, stride, pad, 0.1);\n\n    vector<MatrixXd> inputs, outs;\n    MatrixXd X = MatrixXd::Zero(n, c*h*w);\n    X << 1,2,3,4;\n    // X << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;\n\n    inputs.push_back(X);\n    outs = conv.forward(inputs);\n\n    cout << outs[0] << endl;\n\n    // ----------------------\n    // col2im\n    // ----------------------\n\n    int Oh = (2*pad+h - Fh) / stride + 1;\n    int Ow = (2*pad+w - Fw) / stride + 1;\n\n    MatrixXd col = MatrixXd::Ones(n*Oh*Ow,c*Fh*Fw);\n    MatrixXd img;\n\n    conv.col2im(col, img);\n\n    cout << img << endl;\n\n    // MatrixXd pad_img, img;\n\n    // conv.col2im(col, pad_img);\n\n    // cout << pad_img << endl;\n\n    // conv.suppress(pad_img, img);\n\n    // cout << img << endl;\n\n    vector<MatrixXd> grads, douts;\n\n    douts.push_back(MatrixXd::Ones(n, Fn*Oh*Ow));\n\n    grads = conv.backward(douts);\n\n    cout << grads[0] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "6c8120442a90718a4522c2e3a47c2429f3fcab06", "size": 1280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_conv.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": "test/test_conv.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": "test/test_conv.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": 18.2857142857, "max_line_length": 55, "alphanum_fraction": 0.51640625, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6630157196498543}}
{"text": "/* Copyright (C) 2018-2019 Thomas Jespersen, TKJ Electronics. All rights reserved.\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the MIT License\n *\n * This program 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.\n * See the MIT License for further details.\n *\n * Contact information\n * ------------------------------------------\n * Thomas Jespersen, TKJ Electronics\n * Web      :  http://www.tkjelectronics.dk\n * e-mail   :  thomasj@tkjelectronics.dk\n * ------------------------------------------\n */\n\n#include <signal.h>\n#include <condition_variable>\n#include <stdlib.h>\n#include <stdio.h>\n\n#include <boost/thread.hpp>\n#include <boost/chrono.hpp>\n#include <boost/format.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"omp.h\"\n\n#include <iostream>\n#include <cstring>\n#include <string>\n\n#include <boost/math/quaternion.hpp> // see https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/quaternions.html\n\nvoid QuaternionIntegration_ForwardEuler(\n        double dt,\n        double omeg_x, double omeg_y, double omeg_z,\n        double& q0, double& q1, double& q2, double& q3);\nvoid QuaternionIntegration_Exponential(\n        double dt,\n        double omeg_x, double omeg_y, double omeg_z,\n        double& q0, double& q1, double& q2, double& q3);\nvoid normalizeQuaternion(double& q0, double& q1, double& q2, double& q3);\n\n#define deg2rad(x) (M_PI*x/180.f)\n#define rad2deg(x) (180.f*x/M_PI)\n\nint main(int argc, char** argv ) {    \n    std::string argv_str(realpath(argv[0], 0));\n    std::string base = argv_str.substr(0, argv_str.find_last_of(\"/\"));\n\n    double angularVelocity[3] = {0.3, 0.2, 0.1};\n    double dt = 1.0/200;\n\n    // Create initial quaternion for testing - using Boost Quaternions: https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/quaternions.html\n    boost::math::quaternion<double> q0(0.9848,0.1736,0,0); // w,x,y,z\n    q0 = q0 / sqrt(boost::math::norm(q0)); // normalize\n\n    // Convert angular velocity vector into a quaternion\n    boost::math::quaternion<double> q_omeg(0, angularVelocity[0], angularVelocity[1], angularVelocity[2]);   // use as body angular velocity\n\n    std::cout << \"Quaternion are printed in order: \\t(w, x, y, z)\" << std::endl << std::endl;\n\n\n    /* Inertial vs Body angular velocity test */\n    std::cout << \">>>>> Inertial vs Body angular velocity test <<<<<\" << std::endl;\n    boost::math::quaternion<double> q_body = q0 * boost::math::exp(0.5*dt*q_omeg); // compute the new quaternion using the quaternion exponential\n    boost::math::quaternion<double> q_inertial = boost::math::exp(0.5*dt*q_omeg) * q0; // compute the new quaternion using the quaternion exponential\n\n    // Print results for comparison\n    std::cout << \"q0 \\t\\t=\\t\" << q0 << std::endl;\n    std::cout << \"q_omeg \\t\\t=\\t\" << q_omeg << std::endl;\n    std::cout << \"q_body \\t\\t=\\t\" << q_body << std::endl;\n    std::cout << \"q_inertial \\t=\\t\" << q_inertial << std::endl;\n\n    std::cout << std::endl;\n\n\n    /* Integration method test - methods are inspired from https://www.ashwinnarayan.com/post/how-to-integrate-quaternions/  */\n    std::cout << \">>>>> Integration method test <<<<<\" << std::endl;\n    // Method 1: Quaternion Exponential\n    boost::math::quaternion<double> q1_exp = q0 * boost::math::exp(0.5*dt*q_omeg);\n\n    // Method 2: Manual Quaternion Exponential\n    boost::math::quaternion<double> q_exp_delta;\n    if (norm(q_omeg) > 0)\n        q_exp_delta = cos(0.5 * dt * sqrt(norm(q_omeg))) + q_omeg / sqrt(norm(q_omeg)) * sin(0.5 * dt * sqrt(norm(q_omeg)));\n    else\n        q_exp_delta = boost::math::quaternion<double>(1, 0, 0, 0); // unit quaternion since the angular velocity is zero (no movement)\n\n    boost::math::quaternion<double> q2_exp_manual = q0 * q_exp_delta;\n\n    // Method 3: Manual Quaternion Exponential\n    double q_1[4] = {q0.R_component_1(), q0.R_component_2(), q0.R_component_3(), q0.R_component_4()};\n    QuaternionIntegration_Exponential(dt, angularVelocity[0],angularVelocity[1],angularVelocity[2], q_1[0],q_1[1],q_1[2],q_1[3]);\n    boost::math::quaternion<double> q3_exp_manual(q_1[0],q_1[1],q_1[2],q_1[3]);\n\n    // Method 4: Delta Quaternion\n    boost::math::quaternion<double> q_delta(1, 0.5*dt*angularVelocity[0], 0.5*dt*angularVelocity[1], 0.5*dt*angularVelocity[2]);\n    boost::math::quaternion<double> q4_delta = q0 * q_delta; // compute the new quaternion using body angular velocity to construct the delta quaternion (hence right multiplication)\n\n    // Method 5: Forward Euler\n    boost::math::quaternion<double> dq = 0.5 * q0 * q_omeg; // quaternion derivative using body angular velocity\n    //boost::math::quaternion<double> dq = 0.5 * q_omeg * q0; // quaternion derivative using inertial angular velocity\n    boost::math::quaternion<double> q5_euler = q0 + dt*dq;\n    q5_euler = q5_euler / sqrt(boost::math::norm(q5_euler)); // normalize\n\n    // Method 6: Forward Euler 2\n    double q_2[4] = {q0.R_component_1(), q0.R_component_2(), q0.R_component_3(), q0.R_component_4()};\n    QuaternionIntegration_ForwardEuler(dt, angularVelocity[0],angularVelocity[1],angularVelocity[2], q_2[0],q_2[1],q_2[2],q_2[3]);\n    boost::math::quaternion<double> q6_euler(q_2[0],q_2[1],q_2[2],q_2[3]);\n\n    // Print results for comparison\n    std::cout << \"Angular Velocity \\t=\\t(\" << angularVelocity[0] << \", \" << angularVelocity[1] << \", \" << angularVelocity[2] << \")\" << std::endl;\n    std::cout << \"Boost Exponential \\t=\\t\" << q1_exp << std::endl;\n    std::cout << \"Manual Exponential \\t=\\t\" << q2_exp_manual << std::endl;\n    std::cout << \"Delta \\t\\t\\t=\\t\" << q4_delta << std::endl;\n    std::cout << \"Forward Euler \\t\\t=\\t\" << q5_euler << std::endl;\n    std::cout << \"Manual Exponential my \\t=\\t\" << q3_exp_manual << std::endl;\n    std::cout << \"Forward Euler my \\t=\\t\" << q6_euler << std::endl;\n\n    return 0;\n}\n\nvoid QuaternionIntegration_ForwardEuler(\n        double dt,\n        double omeg_x, double omeg_y, double omeg_z,\n        double& q0, double& q1, double& q2, double& q3)\n{\n    // The angular velocity is given in body frame\n    /* Forward Euler method\n     * q_new = q + dt * dq\n     * dq = 0.5 * q0 * q_omeg\n     * q_omeg = [0,omeg_x,omeg_y,omeg_z]\n     */\n\n    // dq = 0.5*Phi(q0)*[0,omeg_x,omeg_y,omeg_z]\n    double dq0 = 0.5 * (-q1*omeg_x -q2*omeg_y -q3*omeg_z);\n    double dq1 = 0.5 * (+q0*omeg_x -q3*omeg_y +q2*omeg_z);\n    double dq2 = 0.5 * (+q3*omeg_x +q0*omeg_y -q1*omeg_z);\n    double dq3 = 0.5 * (-q2*omeg_x +q1*omeg_y +q0*omeg_z);\n\n    q0 += dt*dq0;\n    q1 += dt*dq1;\n    q2 += dt*dq2;\n    q3 += dt*dq3;\n\n    normalizeQuaternion(q0, q1, q2, q3);\n}\n\nvoid QuaternionIntegration_Exponential(\n        double dt,\n        double omeg_x, double omeg_y, double omeg_z,\n        double& q0, double& q1, double& q2, double& q3)\n{\n    // The angular velocity is given in body frame\n    /* Quaternion Exponential method\n     * q_new = q0 * exp(1/2*dt*q_omeg)\n     * q_omeg = [0,omeg_x,omeg_y,omeg_z]\n     */\n\n    double omeg_norm = sqrt(omeg_x*omeg_x + omeg_y*omeg_y + omeg_z*omeg_z);\n\n    double q_exp0, q_exp1, q_exp2, q_exp3;\n\n    if (omeg_norm > 0) {\n        double sinOmeg = sin(0.5 * dt * omeg_norm);\n        q_exp0 = cos(0.5 * dt * omeg_norm);\n        q_exp1 = sinOmeg * omeg_x / omeg_norm;\n        q_exp2 = sinOmeg * omeg_y / omeg_norm;\n        q_exp3 = sinOmeg * omeg_z / omeg_norm;\n    } else {\n        // unit quaternion since the angular velocity is zero (no movement)\n        q_exp0 = 1.0;\n        q_exp1 = 0.0;\n        q_exp2 = 0.0;\n        q_exp3 = 0.0;\n    }\n\n    // q_new = Phi(q0) * q_exp\n    double q0_new = +q0*q_exp0 -q1*q_exp1 -q2*q_exp2 -q3*q_exp3;\n    double q1_new = +q1*q_exp0 +q0*q_exp1 -q3*q_exp2 +q2*q_exp3;\n    double q2_new = +q2*q_exp0 +q3*q_exp1 +q0*q_exp2 -q1*q_exp3;\n    double q3_new = +q3*q_exp0 -q2*q_exp1 +q1*q_exp2 +q0*q_exp3;\n\n    // Update quaternion\n    q0 = q0_new;\n    q1 = q1_new;\n    q2 = q2_new;\n    q3 = q3_new;\n}\n\nvoid normalizeQuaternion(double& q0, double& q1, double& q2, double& q3)\n{\n    double norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);\n    q0 /= norm;\n    q1 /= norm;\n    q2 /= norm;\n    q3 /= norm;\n}\n", "meta": {"hexsha": "244d2cd702bb555af0f4159404896895bdac3cd0", "size": 8215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/cpp/src/QuaternionTest/main.cpp", "max_stars_repo_name": "mindThomas/JetsonCar", "max_stars_repo_head_hexsha": "74636d4da1f7f71ca9f2315a1b2347393b081eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T08:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T15:18:36.000Z", "max_issues_repo_path": "src/QuaternionTest/main.cpp", "max_issues_repo_name": "mindThomas/Kugle-Misc", "max_issues_repo_head_hexsha": "4578cce7f9b319cf9bc708a434c5713e9ddb26fa", "max_issues_repo_licenses": ["MIT"], "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/QuaternionTest/main.cpp", "max_forks_repo_name": "mindThomas/Kugle-Misc", "max_forks_repo_head_hexsha": "4578cce7f9b319cf9bc708a434c5713e9ddb26fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-06T10:16:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-05T13:06:43.000Z", "avg_line_length": 40.0731707317, "max_line_length": 181, "alphanum_fraction": 0.6419963481, "num_tokens": 2682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6629714853978277}}
{"text": "#include <gtest/gtest.h>\n#include <boost/lexical_cast.hpp>\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/polar_to_nodal.hpp\"\n#include \"spectral/p2n_factory.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\n\n// Polar-Laguerre coefficients with exponential decay\nvoid test2(int K, const std::function<double(double)>& cfct, double tol)\n{\n  typedef Eigen::VectorXd vec_t;\n\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, K, K, 2, true);\n  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  Polar2Nodal<polar_basis_t> p2n;\n  p2n.init(polar_basis, 1.0);\n\n  unsigned int N = polar_basis.n_dofs();\n  Eigen::VectorXd cp(N);\n  for (unsigned int i = 0; i < N; ++i) {\n    // cp(i) = cfct(float(i)/N);\n    cp(i) = 1;\n  }\n  Eigen::MatrixXd cn(K, K);\n  p2n.to_nodal(cn, cp);\n  Eigen::VectorXd cp2(N);\n  p2n.to_polar(cp2, cn);\n\n  Eigen::VectorXd diff(N);\n  diff.setZero();\n\n  for (unsigned int i = 0; i < N; ++i) {\n    diff(i) = std::abs(cp2(i) - cp(i));\n  }\n\n  double max_diff = diff.cwiseAbs().maxCoeff();\n  cout << \"max_diff: \" << max_diff << \"\\n\";\n  EXPECT_TRUE(max_diff < tol) << max_diff;\n}\n\n// Polar-Laguerre coefficients with exponential decay\nvoid test3(int K, const std::function<double(double)>& cfct, double tol)\n{\n  typedef Eigen::VectorXd vec_t;\n\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, K, K, 2, true);\n  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  const auto& p2n = P2NFactory<polar_basis_t>::GetInstance(polar_basis, 1.0);\n\n  // Polar2Nodal<polar_basis_t> p2n;\n  // p2n.init(polar_basis, 1.0);\n\n  unsigned int N = polar_basis.n_dofs();\n  Eigen::VectorXd cp(N);\n  for (unsigned int i = 0; i < N; ++i) {\n    // cp(i) = cfct(float(i)/N);\n    cp(i) = 1;\n  }\n  Eigen::MatrixXd cn(K, K);\n  p2n.to_nodal(cn, cp);\n  Eigen::VectorXd cp2(N);\n  p2n.to_polar(cp2, cn);\n\n  Eigen::VectorXd diff(N);\n  diff.setZero();\n\n  for (unsigned int i = 0; i < N; ++i) {\n    diff(i) = std::abs(cp2(i) - cp(i));\n  }\n\n  double max_diff = diff.cwiseAbs().maxCoeff();\n  cout << \"max_diff: \" << max_diff << \"\\n\";\n  EXPECT_TRUE(max_diff < tol) << max_diff;\n}\n\nTEST(spectral, polar2nodal)\n{\n  const double tol = 1e-13;\n  cout << \"Tolerance: \" << tol << \"\\n\";\n  std::vector<int> Ks = {6, 10, 20, 30, 40, 50, 70};\n  for (auto K : Ks) {\n    cout << \"running test for K=\" << boost::lexical_cast<string>(K) << \"\\n\";\n    // test2(K, [](double i){return std::exp(-1*i);}, tol);\n    test2(K, [](double i) { return 1; }, tol);\n  }\n}\n", "meta": {"hexsha": "9c637c4b71c25df6470c61946d2690552d1508f9", "size": 2683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_polar2nodal.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gtest/gtest_polar2nodal.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_polar2nodal.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2421052632, "max_line_length": 85, "alphanum_fraction": 0.6593365635, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6629714840151906}}
{"text": "/**\n * @file quasiinterpolation_main.cc\n * @brief NPDE exam TEMPLATE MAIN FILE\n * @author Oliver Rietmann\n * @date 15.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n\n#include \"iohelper.h\"\n#include \"quasiinterpolation.h\"\n\nconstexpr double PI = 3.14159265358979323846;\n// A bump function\ndouble u1(Eigen::Vector2d x) {\n  double abs_x = x.norm();\n  return abs_x < 0.5 ? std::cos(PI * abs_x) : 0.0;\n};\n// The gradient of the bump function\nEigen::Vector2d grad_u1(Eigen::Vector2d x) {\n  double abs_x = x.norm();\n  if (abs_x == 0.0 || abs_x >= 0.5)\n    return Eigen::Vector2d::Zero();\n  else\n    return -PI * std::sin(PI * abs_x) / abs_x * x;\n};\n\n// A simplex auxiliary function\ninline double square(double y) { return y * y; }\n\n// A smoother bump function\ndouble u2(Eigen::Vector2d x) { return square(u1(x)); };\n// ... and its gradient\nEigen::Vector2d grad_u2(Eigen::Vector2d x) { return 2.0 * u1(x) * grad_u1(x); };\n\nint main(int /* argc */, char** /*argv*/) {\n  // Build mesh hierarchy\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory),\n                            CURRENT_SOURCE_DIR \"/../meshes/mesh.msh\");\n  std::shared_ptr<lf::mesh::Mesh> base_mesh_p{reader.mesh()};\n  std::shared_ptr<lf::refinement::MeshHierarchy> mesh_hierarchy_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(base_mesh_p, 6);\n\n  // Compute meshwidth for each refinement\n  int L = mesh_hierarchy_p->NumLevels();\n  Eigen::VectorXd meshwidth(L);\n  for (int k = 0; k < L; ++k) {\n    std::shared_ptr<const lf::mesh::Mesh> mesh_p = mesh_hierarchy_p->getMesh(k);\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n    meshwidth(k) = QuasiInterpolation::maxLength(mesh_p->Entities(1));\n  }\n  {\n    // Errors for u1\n    lf::mesh::utils::MeshFunctionGlobal u1_mf(u1);\n    lf::mesh::utils::MeshFunctionGlobal grad_u1_mf(grad_u1);\n    // Retrieve error norms\n    auto [l2_error, h1_error] = QuasiInterpolation::interpolationError(\n        mesh_hierarchy_p, u1_mf, grad_u1_mf);\n    QuasiInterpolation::printError(meshwidth, l2_error, h1_error,\n                                   \"errors for u1\");\n    QuasiInterpolation::writeCSV(meshwidth, l2_error, h1_error,\n                                 CURRENT_BINARY_DIR \"/convergence_u1.csv\");\n    // Call a Python script to generate plots\n    std::system(\"python3 \" CURRENT_SOURCE_DIR\n                \"/plot_convergence.py \" CURRENT_BINARY_DIR\n                \"/convergence_u1.csv \" CURRENT_BINARY_DIR\n                \"/convergence_u1.eps 'Interpolation error for $u(x)=u_1(x)$'\");\n  }\n  {\n    // Errors for u2\n    lf::mesh::utils::MeshFunctionGlobal u2_mf(u2);\n    lf::mesh::utils::MeshFunctionGlobal grad_u2_mf(grad_u2);\n    auto [l2_error, h1_error] = QuasiInterpolation::interpolationError(\n        mesh_hierarchy_p, u2_mf, grad_u2_mf);\n    QuasiInterpolation::printError(meshwidth, l2_error, h1_error,\n                                   \"errors for u2\");\n    QuasiInterpolation::writeCSV(meshwidth, l2_error, h1_error,\n                                 CURRENT_BINARY_DIR \"/convergence_u2.csv\");\n    std::system(\"python3 \" CURRENT_SOURCE_DIR\n                \"/plot_convergence.py \" CURRENT_BINARY_DIR\n                \"/convergence_u2.csv \" CURRENT_BINARY_DIR\n                \"/convergence_u2.eps 'Interpolation error for $u(x)=u_2(x)$'\");\n  }\n  return 0;\n}\n", "meta": {"hexsha": "9a41882044f024c6638c3504688b30546b2c06c0", "size": 3658, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/QuasiInterpolation/templates/quasiinterpolation_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/QuasiInterpolation/templates/quasiinterpolation_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/QuasiInterpolation/templates/quasiinterpolation_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.7113402062, "max_line_length": 80, "alphanum_fraction": 0.6585565883, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6629280733058207}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass RunningStats\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n\n  void init(index historySize, index inputSize)\n  {\n    mInputBuffer = ArrayXXd::Zero(inputSize, historySize + 1);\n    mInputSquaredBuffer = ArrayXXd::Zero(inputSize, historySize + 1);\n    mXSum = ArrayXd::Zero(inputSize);\n    mXSqSum = ArrayXd::Zero(inputSize);\n    mX1 = ArrayXd::Zero(inputSize);\n    mY1 = ArrayXd::Zero(inputSize);\n    mInputSquared = ArrayXd::Zero(inputSize);\n    mCleanedInput = ArrayXd::Zero(inputSize);\n    mTmpOut = ArrayXd::Zero(inputSize);\n    mHead = 0;\n    mN = 0;\n    mSize = historySize;\n  }\n  \n  template<typename T>\n  void process(FluidTensorView<T, 1> in, FluidTensorView<T, 1> meanOut,\n               FluidTensorView<T, 1> stdDevOut)\n  {\n    // Moving average and _sample_ standard deviation\n    // https://www.dsprelated.com/showthread/comp.dsp/97276-1.php\n\n    // oldest inputs and squared inputs from buffer\n    mX1 = mInputBuffer.col(mHead);\n    mY1 = mInputSquaredBuffer.col(mHead);\n    \n    using MapXd = decltype(_impl::asEigen<Eigen::Array>(in));\n    \n    MapXd inMap = _impl::asEigen<Eigen::Array>(in);\n    mCleanedInput = inMap.isNaN().select(0,inMap).template cast<double>();\n    mInputSquared = mCleanedInput.square();\n\n    // running sums\n    mXSum += (mCleanedInput - mX1);\n    mXSqSum += (mInputSquared - mY1);\n\n    // calculate stats\n    mN = std::min(mN + 1, mSize);\n    _impl::asEigen<Eigen::Array>(meanOut) = (mXSum / mN).template cast<T>();\n    if(mN > 1)\n    {\n     mTmpOut = ((mN * mXSqSum - mXSum.square()) / (mN * (mN - 1))).sqrt();\n     _impl::asEigen<Eigen::Array>(stdDevOut) = mTmpOut.isNaN().select(0,mTmpOut).template cast<T>();\n    }\n    else\n    {\n      std::fill(stdDevOut.begin(),stdDevOut.end(),0);\n    }\n\n    // write new data\n    mInputBuffer.col(mHead) = mCleanedInput;\n    mInputSquaredBuffer.col(mHead) = mInputSquared;\n\n    // move on\n    mHead++;\n    if (mHead >= mInputBuffer.cols() - 1) mHead = 0;\n  }\n\nprivate:\n  ArrayXXd mInputBuffer;\n  ArrayXXd mInputSquaredBuffer;\n  ArrayXd  mXSum;\n  ArrayXd  mXSqSum;\n  ArrayXd  mX1;\n  ArrayXd  mY1;\n  ArrayXd  mCleanedInput;\n  ArrayXd  mInputSquared;\n  ArrayXd  mTmpOut;\n  index    mHead;\n  index    mN;\n  index    mSize;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "626c5bca60c4d3051f21aad24b3562193f59c750", "size": 2892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/RunningStats.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/RunningStats.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/RunningStats.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": 28.0776699029, "max_line_length": 100, "alphanum_fraction": 0.6749654219, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6629068904594156}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. 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_\n\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/random.hpp>\n#include <iostream>\n#include <iomanip>\n\nvoid t1()\n{\n//[random_eg1\n//=#include <boost/multiprecision/gmp.hpp>\n//=#include <boost/multiprecision/random.hpp>\n//=\n//=int main()\n//={\n   using namespace boost::multiprecision;\n   using namespace boost::random;\n\n   //\n   // Declare our random number generator type, the underlying generator\n   // is the Mersenne twister mt19937 engine, and 256 bits are generated:\n   //\n   typedef independent_bits_engine<mt19937, 256, mpz_int> generator_type;\n   generator_type gen;\n   //\n   // Generate some values:\n   //\n   std::cout << std::hex << std::showbase;\n   for(unsigned i = 0; i < 10; ++i)\n      std::cout << gen() << std::endl;\n//=   return 0;\n//=}\n//]\n}\n\nvoid t2()\n{\n//[random_eg2\n//=#include <boost/multiprecision/gmp.hpp>\n//=#include <boost/multiprecision/random.hpp>\n//=\n//=int main()\n//={\n   using namespace boost::multiprecision;\n   using namespace boost::random;\n\n   //\n   // Generate integers in a given range using uniform_int,\n   // the underlying generator is invoked multiple times\n   // to generate enough bits:\n   //\n   mt19937 mt;\n   uniform_int_distribution<mpz_int> ui(0, mpz_int(1) << 256);\n   //\n   // Generate the numbers:\n   //\n   std::cout << std::hex << std::showbase;\n   for(unsigned i = 0; i < 10; ++i)\n      std::cout << ui(mt) << std::endl;\n\n//=   return 0;\n//=}\n//]\n}\n\nvoid t3()\n{\n//[random_eg3\n//=#include <boost/multiprecision/gmp.hpp>\n//=#include <boost/multiprecision/random.hpp>\n//=\n//=int main()\n//={\n   using namespace boost::multiprecision;\n   using namespace boost::random;\n   //\n   // We need an underlying generator with at least as many bits as the\n   // floating point type to generate numbers in [0, 1) with all the bits\n   // in the floating point type randomly filled:\n   //\n   uniform_01<mpf_float_50> uf;\n   independent_bits_engine<mt19937, 50L*1000L/301L, mpz_int> gen;\n   //\n   // Generate the values:\n   //\n   std::cout << std::setprecision(50);\n   for(unsigned i = 0; i < 20; ++i)\n      std::cout << uf(gen) << std::endl;\n//=   return 0;\n//=}\n//]\n}\n\nvoid t4()\n{\n//[random_eg4\n//=#include <boost/multiprecision/gmp.hpp>\n//=#include <boost/multiprecision/random.hpp>\n//=\n//=int main()\n//={\n   using namespace boost::multiprecision;\n   using namespace boost::random;\n   //\n   // We can repeat the above example, with other distributions:\n   //\n   uniform_real_distribution<mpf_float_50> ur(-20, 20);\n   gamma_distribution<mpf_float_50> gd(20);\n   independent_bits_engine<mt19937, 50L*1000L/301L, mpz_int> gen;\n   //\n   // Generate some values:\n   //\n   std::cout << std::setprecision(50);\n   for(unsigned i = 0; i < 20; ++i)\n      std::cout << ur(gen) << std::endl;\n   for(unsigned i = 0; i < 20; ++i)\n      std::cout << gd(gen) << std::endl;\n//=   return 0;\n//=}\n//]\n}\n\nint main()\n{\n   t1();\n   t2();\n   t3();\n   t4();\n   return 0;\n}\n\n", "meta": {"hexsha": "c083bf2f211261667d67cb75ff3bda3d0672d6c2", "size": 3154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/example/random_snips.cpp", "max_stars_repo_name": "fed12345/boost_1_59_0", "max_stars_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-11-07T10:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-24T06:44:25.000Z", "max_issues_repo_path": "libs/multiprecision/example/random_snips.cpp", "max_issues_repo_name": "fed12345/boost_1_59_0", "max_issues_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-18T21:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-11T12:39:57.000Z", "max_forks_repo_path": "libs/multiprecision/example/random_snips.cpp", "max_forks_repo_name": "fed12345/boost_1_59_0", "max_forks_repo_head_hexsha": "2a8cea7df425ffc4252ac641c5359c5dc56cf284", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-03-20T01:55:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-29T12:35:29.000Z", "avg_line_length": 23.362962963, "max_line_length": 73, "alphanum_fraction": 0.6236525048, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6626269845170151}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//               2014 Piotr Smulewicz\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/**\n * @file metric_test.cpp\n * @brief\n * @author Piotr Wygocki ,Piotr Smulewicz\n * @version 1.0\n * @date 2013-02-04\n */\n\n#include \"test_utils/sample_graph.hpp\"\n\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/data_structures/metric/euclidean_metric.hpp\"\n#include \"paal/data_structures/metric/graph_metrics.hpp\"\n#include \"paal/data_structures/metric/basic_metrics.hpp\"\n\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n\nBOOST_AUTO_TEST_CASE(euclidean_metric_test) {\n    auto metric=paal::data_structures::euclidean_metric<int>();\n    std::pair<int,int> a={0,0},b={1,1};\n\n    BOOST_CHECK(paal::utils::compare<double>().e(metric(a,b),std::sqrt(2)));\n}\n\nBOOST_AUTO_TEST_CASE(metric_test) {\n    typedef sample_graphs_metrics SGM;\n    auto gm = SGM::get_graph_metric_small();\n\n    BOOST_CHECK_EQUAL(gm(SGM::A, SGM::B) , 2);\n    BOOST_CHECK_EQUAL(gm(SGM::C, SGM::B) , 3);\n}\n\nBOOST_AUTO_TEST_CASE(copyrectangle_array_metric) {\n    paal::data_structures::rectangle_array_metric<int> m(1, 2);\n    m(0, 0) = 1;\n    m(0, 1) = 2;\n\n    auto r1 = paal::irange(1);\n    auto r2 = paal::irange(2);\n    paal::data_structures::rectangle_array_metric<int> copy(\n        m, r1, r2);\n\n    BOOST_CHECK_EQUAL(copy(0, 0) , 1);\n    BOOST_CHECK_EQUAL(copy(0, 1) , 2);\n}\n\nBOOST_AUTO_TEST_CASE(copyarray_metric) {\n    paal::data_structures::array_metric<int> m(1);\n    m(0, 0) = 13;\n\n    auto r1 = paal::irange(1);\n    paal::data_structures::array_metric<int> copy(m, r1);\n\n    BOOST_CHECK_EQUAL(copy(0, 0) , 13);\n}\n", "meta": {"hexsha": "6cf073b07ce70b848aff094c826cf23d829bc562", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/data_structures/metric_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/data_structures/metric_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/data_structures/metric_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 28.4776119403, "max_line_length": 76, "alphanum_fraction": 0.6352201258, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6626269678050641}}
{"text": "#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n/* Creates a matrix that Rotate vector about the z axis\n * Currently needed for our robot relative coordinate system\n */\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> rotateZMatrix(T theta);\n\n/* Creates a translation matrix\n */\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> translateMatrix(T x, T y, T z);\n\n/* Creates a projection matrix\n */\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> projectionMatrix(T ex, T ey,\n                                                  T ez);\n\n\n/* Creates a DH matrix used in Kinematics\n */\ntemplate <typename T>\nboost::numeric::ublas::matrix<T> createDHMatrix(T a, T alpha,\n                                                T d, T theta);\n\n/* Function to invert matrix\n */\ntemplate <typename T>\nbool invertMatrix(const boost::numeric::ublas::matrix<T>& input,\n                  boost::numeric::ublas::matrix<T>& inverse);\n\n/* Creates a 4,1 vector */\ntemplate <typename T>\ninline boost::numeric::ublas::matrix<T>\nvec4(T a, T b, T c, T d) {\n   boost::numeric::ublas::matrix<T> m(4, 1);\n   m(0, 0) = a;\n   m(1, 0) = b;\n   m(2, 0) = c;\n   m(3, 0) = d;\n   return m;\n}\n\n/* Creates a 4,1 vector from a 4,1 array */\ntemplate <typename T>\ninline boost::numeric::ublas::matrix<T>\nvec4(const T a[]) {\n   boost::numeric::ublas::matrix<T> m(4, 1);\n   m(0, 0) = a[0];\n   m(1, 0) = a[1];\n   m(2, 0) = a[2];\n   m(3, 0) = a[3];\n   return m;\n}\n\n#include \"utils/matrix_helpers.tcc\"\n", "meta": {"hexsha": "840481b9ea316deef5bb7b149b3130b0ab2e1db6", "size": 1553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 25.0483870968, "max_line_length": 64, "alphanum_fraction": 0.6104314231, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6625920304112534}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_functions.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nusing namespace OpenTissue;\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_clamp);\n\n  BOOST_AUTO_TEST_CASE(double_testing)\n  {\n    double const min_val = 0.1;\n    double const max_val = 2.9;\n    double clamped_val;\n\n    // normal clamp tests\n    clamped_val = math::clamp(1.5, min_val, max_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = math::clamp(-1.5, min_val, max_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = math::clamp(3.0, min_val, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp minimum tests\n    clamped_val = math::clamp_min(1.5, min_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = math::clamp_min(-1.5, min_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = math::clamp_min(3.0, min_val);\n    BOOST_CHECK( clamped_val == 3.0 );\n\n\n    // clamp maximum tests\n    clamped_val = math::clamp_max(1.5, max_val);\n    BOOST_CHECK( clamped_val == 1.5 );\n\n    clamped_val = math::clamp_max(-1.5, max_val);\n    BOOST_CHECK( clamped_val == -1.5 );\n\n    clamped_val = math::clamp_max(3.0, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp zero..one tests\n    clamped_val = math::clamp_zero_one(0.5);\n    BOOST_CHECK( clamped_val == 0.5 );\n\n    clamped_val = math::clamp_zero_one(-1.5);\n    BOOST_CHECK( clamped_val == 0.0 );\n\n    clamped_val = math::clamp_zero_one(3.0);\n    BOOST_CHECK( clamped_val == 1.0 );\n  }\n\n\n  BOOST_AUTO_TEST_CASE(float_testing)\n  {\n    float const min_val = 0.1f;\n    float const max_val = 2.9f;\n    float clamped_val;\n\n    // normal clamp tests\n    clamped_val = math::clamp(1.5f, min_val, max_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = math::clamp(-1.5f, min_val, max_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = math::clamp(3.0f, min_val, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp minimum tests\n    clamped_val = math::clamp_min(1.5f, min_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = math::clamp_min(-1.5f, min_val);\n    BOOST_CHECK( clamped_val == min_val );\n\n    clamped_val = math::clamp_min(3.0f, min_val);\n    BOOST_CHECK( clamped_val == 3.0f );\n\n\n    // clamp maximum tests\n    clamped_val = math::clamp_max(1.5f, max_val);\n    BOOST_CHECK( clamped_val == 1.5f );\n\n    clamped_val = math::clamp_max(-1.5f, max_val);\n    BOOST_CHECK( clamped_val == -1.5f );\n\n    clamped_val = math::clamp_max(3.0f, max_val);\n    BOOST_CHECK( clamped_val == max_val );\n\n\n    // clamp zero..one tests\n    clamped_val = math::clamp_zero_one(0.5f);\n    BOOST_CHECK( clamped_val == 0.5f );\n\n    clamped_val = math::clamp_zero_one(-1.5f);\n    BOOST_CHECK( clamped_val == 0.0f );\n\n    clamped_val = math::clamp_zero_one(3.0f);\n    BOOST_CHECK( clamped_val == 1.0f );\n  }\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "dd09cb9ef46e0d8ce4fe1a693a92cc17c486696f", "size": 3366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/clamp/src/unit_clamp.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/clamp/src/unit_clamp.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/clamp/src/unit_clamp.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 27.1451612903, "max_line_length": 78, "alphanum_fraction": 0.6815210933, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6625289361590476}}
{"text": "#include <cylbot_mcl/pose_cloud.h>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/bind.hpp>\n#include <cmath>\n#include <vector>\n#include <utility>\n#include <algorithm>\n#include <tf/transform_datatypes.h>\n#include <limits>\n#include <set>\n\nnamespace cylbot_mcl\n{\n\tPoseCloud::PoseCloud(const RobotModel& model, const int num_samples) :\n\t\tmodel(model)\n\t{\n\t\tthis->pose_array.header.frame_id = \"/map\";\n\n\t\tthis->pose_array.poses = generateUniformPoses(std::make_pair(-20.0, 20.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::make_pair(-20.0, 20.0),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  num_samples).poses;\n\t}\n\n\tPoseCloud::PoseCloud(const RobotModel& model,\n\t\t\t\t\t\t const geometry_msgs::PoseWithCovarianceStamped& initial_pose,\n\t\t\t\t\t\t const int num_particles) :\n\t\tmodel(model)\n\t{\n\t\tthis->pose_array.header.frame_id = \"/map\";\n\t\tthis->resetCloud(initial_pose, num_particles);\n\t}\n\n\tvoid PoseCloud::resetCloud(const geometry_msgs::PoseWithCovarianceStamped& initial_pose, const int num_particles)\n\t{\n\t\tpose_array.poses = generatePoses(initial_pose, num_particles).poses;\n\t}\n\n\tgeometry_msgs::PoseArray PoseCloud::generatePoses(const geometry_msgs::PoseWithCovarianceStamped& initial_pose,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  const int num_particles)\n\t{\n\t\tEigen::VectorXd mean(3);\n\t\tEigen::MatrixXd covar(3,3);\n\n\t\tmean << initial_pose.pose.pose.position.x,\n\t\t\t    initial_pose.pose.pose.position.y,\n\t\t\t    tf::getYaw(initial_pose.pose.pose.orientation);\n\t\tcovar << initial_pose.pose.covariance[0], 0,                                  0,\n\t\t\t     0,                               initial_pose.pose.covariance[7],    0,\n\t\t\t     0,                               0,                                  initial_pose.pose.covariance[35];\n\n\t\tEigen::MatrixXd normTransform(3, 3);\n\t\tEigen::LLT<Eigen::MatrixXd> cholSolver(covar);\n\t\t\n\t\tif(cholSolver.info() == Eigen::Success)\n\t\t{\n\t\t\tnormTransform = cholSolver.matrixL();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar);\n\t\t\tnormTransform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n\t\t}\n\t\t\n\t\tEigen::MatrixXd samples = (normTransform * Eigen::MatrixXd::NullaryExpr(3, num_particles, randn)).colwise() + mean;\n\n\t\tgeometry_msgs::PoseArray new_pose_array;\n\t\tfor(int i=0; i<num_particles; i++)\n\t\t{\n\t\t\tgeometry_msgs::Pose pose;\n\t\t\tpose.position.x = samples(0, i);\n\t\t\tpose.position.y = samples(1, i);\n\t\t\tpose.position.z = 0;\n\n\t\t\t// generate random yaw then convert it to a quaternion\n\t\t\tpose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, samples(2, i));\n\t\t\n\t\t\tnew_pose_array.poses.push_back(pose);\n\t\t}\n\n\t\t\n\t\treturn new_pose_array;\n\t}\n\n\tgeometry_msgs::PoseArray PoseCloud::generateUniformPoses(const std::pair<double, double> x_range,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t const std::pair<double, double> y_range,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t const int num_poses)\n\t{\n\t\tboost::random::uniform_real_distribution<> x_dist(x_range.first, x_range.second);\n\t\tboost::random::uniform_real_distribution<> y_dist(y_range.first, y_range.second);\n\t\tboost::random::uniform_real_distribution<> yaw_dist(0.0, 2*3.14159);\n\n\t\tboost::variate_generator<boost::mt19937, boost::random::uniform_real_distribution<> > x_rand(rng, x_dist);\n\t\tboost::variate_generator<boost::mt19937, boost::random::uniform_real_distribution<> > yaw_rand(rng, yaw_dist);\n\t\t\n\t\tgeometry_msgs::PoseArray new_pose_array;\n\t\tfor(int i=0; i<num_poses; i++)\n\t\t{\n\t\t\tgeometry_msgs::Pose pose;\n\t\t\tpose.position.x = x_rand();\n\t\t\tpose.position.y = x_rand();\n\t\t\tpose.position.z = 0;\n\n\t\t\tpose.orientation = tf::createQuaternionMsgFromYaw(yaw_rand());\n\n\t\t\tnew_pose_array.poses.push_back(pose);\n\t\t}\n\n\t\treturn new_pose_array;\n\t}\n\n\tvoid PoseCloud::motionUpdate(const geometry_msgs::Twist& u, double dt)\n\t{\n\t\tlast_cmd = u;\n\t\t// don't do anything if the robot isn't moving\n\t\tif(fabs(u.linear.y) < 0.1 && fabs(u.angular.z) < 0.1)\n\t\t\treturn;\n\n\t\tdouble v_hat_variance = model.alpha[0]*u.linear.y*u.linear.y + model.alpha[1]*u.angular.z*u.angular.z;\n\t\tdouble w_hat_variance = model.alpha[2]*u.linear.y*u.linear.y + model.alpha[3]*u.angular.z*u.angular.z;\n\t\tdouble gamma_variance = model.alpha[4]*u.linear.y*u.linear.y + model.alpha[5]*u.angular.z*u.angular.z;\n\t\t\n\t\tboost::normal_distribution<> v_hat_dist(0.0, sqrt(v_hat_variance));\n\t\tboost::normal_distribution<> w_hat_dist(0.0, sqrt(w_hat_variance));\n\t\tboost::normal_distribution<> gamma_dist(0.0, sqrt(gamma_variance));\n\t\t\n\t\tdouble v_hat = u.linear.y + v_hat_dist(rng);\n\t\tdouble w_hat = u.angular.z + w_hat_dist(rng);\n\t\tdouble gamma = gamma_dist(rng);\n\t\t\n\t\tdouble v_w_ratio = v_hat/w_hat;\n\n\t\tfor(geometry_msgs::PoseArray::_poses_type::iterator pose = pose_array.poses.begin();\n\t\t\tpose != pose_array.poses.end();\n\t\t\tpose++)\n\t\t{\n\t\t\tdouble yaw = tf::getYaw(pose->orientation);\n\n\t\t\tdouble x_prime = pose->position.x - v_w_ratio*sin(yaw) + v_w_ratio*sin(yaw + w_hat*dt);\n\t\t\tdouble y_prime = pose->position.y + v_w_ratio*cos(yaw) - v_w_ratio*cos(yaw + w_hat*dt);\n\t\t\tdouble yaw_prime = yaw + w_hat*dt + gamma*dt;\n\n\t\t\tpose->position.x = x_prime;\n\t\t\tpose->position.y = y_prime;\n\t\t\tpose->orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, yaw_prime);\n\t\t}\n\n\t}\n\n\tgeometry_msgs::PoseArray PoseCloud::getPoses()\n\t{\n\t\treturn this->pose_array;\n\t}\n\t\n}\n", "meta": {"hexsha": "bb05e6e2de327427f90befe4bfb7fecf5b8fc25d", "size": 5198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cylbot_mcl/src/pose_cloud.cpp", "max_stars_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_stars_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "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/cylbot_mcl/src/pose_cloud.cpp", "max_issues_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_issues_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-22T13:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-23T23:01:57.000Z", "max_forks_repo_path": "src/cylbot_mcl/src/pose_cloud.cpp", "max_forks_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_forks_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "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.3205128205, "max_line_length": 117, "alphanum_fraction": 0.6929588303, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6624878569010417}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of kernel_interpolator class.\n */\n#include \"num_collect/interp/kernel/kernel_interpolator.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"is_finite.h\"\n#include \"num_collect/interp/kernel/calc_kernel_mat.h\"\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nTEST_CASE(\"num_collect::interp::kernel::kernel_interpolator\") {\n    using num_collect::interp::kernel::euclidean_distance;\n    using num_collect::interp::kernel::gaussian_rbf;\n    using num_collect::interp::kernel::kernel_interpolator;\n    using num_collect::interp::kernel::rbf_kernel;\n\n    const auto vars = std::vector<double>{0.0, 0.1, 0.2, 0.4, 0.6, 1.0};\n    const auto data = Eigen::VectorXd{{0.0, 0.2, 0.4, 0.7, 1.0, 2.0}};\n\n    using kernel_type =\n        rbf_kernel<euclidean_distance<double>, gaussian_rbf<double>>;\n\n    SECTION(\"interpolate using defaults\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n\n        interpolator.compute(vars, data);\n        REQUIRE(interpolator.reg_param() == 0.0);  // NOLINT\n        REQUIRE(interpolator.kernel().len_param() > 0.0);\n\n        constexpr double tol_error = 1e-8;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE_THAT(interpolator(vars[i]),\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n        }\n    }\n\n    SECTION(\"interpolate with fixed kernel parameters\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        constexpr double len_param = 0.1;\n        interpolator.fix_kernel_param(std::log10(len_param));\n\n        interpolator.compute(vars, data);\n        REQUIRE(interpolator.reg_param() == 0.0);                 // NOLINT\n        REQUIRE(interpolator.kernel().len_param() == len_param);  // NOLINT\n\n        constexpr double tol_error = 1e-4;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE_THAT(interpolator(vars[i]),\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n        }\n    }\n\n    SECTION(\"interpolate with a fixed regularization parameter\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        constexpr double len_param = 0.1;\n        interpolator.fix_kernel_param(std::log10(len_param));\n        constexpr double reg_param = 1e-4;\n        interpolator.regularize_with(reg_param);\n\n        interpolator.compute(vars, data);\n        REQUIRE(interpolator.reg_param() == reg_param);\n        REQUIRE(interpolator.kernel().len_param() > 0.0);\n\n        constexpr double tol_error = 1e-2;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE_THAT(interpolator(vars[i]),\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n        }\n    }\n\n    SECTION(\"interpolate with automatic regularization\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        constexpr double len_param = 0.1;\n        interpolator.fix_kernel_param(std::log10(len_param));\n        interpolator.regularize_automatically();\n\n        interpolator.compute(vars, data);\n        REQUIRE(interpolator.reg_param() > 0.0);\n        REQUIRE(interpolator.kernel().len_param() > 0.0);\n\n        constexpr double tol_error = 1e-2;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE_THAT(interpolator(vars[i]),\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n        }\n    }\n\n    SECTION(\"interpolate with automatic regularization and kernel parameters\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        interpolator.regularize_automatically();\n\n        interpolator.compute(vars, data);\n        REQUIRE(interpolator.reg_param() > 0.0);\n        REQUIRE(interpolator.kernel().len_param() > 0.0);\n\n        constexpr double tol_error = 1e-2;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            REQUIRE_THAT(interpolator(vars[i]),\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n        }\n    }\n\n    SECTION(\"evaluate variance without regularization\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        constexpr double len_param = 0.1;\n        interpolator.fix_kernel_param(std::log10(len_param));\n        interpolator.disable_regularization();\n\n        interpolator.compute(vars, data);\n\n        constexpr double tol_error = 1e-4;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            const auto [mean, variance] =\n                interpolator.evaluate_mean_and_variance_on(vars[i]);\n            REQUIRE_THAT(mean,\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n\n            REQUIRE(variance >= 0.0);\n            REQUIRE_THAT(variance, Catch::Matchers::WithinAbs(0.0, tol_error));\n        }\n    }\n\n    SECTION(\"evaluate variance with regularization\") {\n        auto interpolator = kernel_interpolator<kernel_type>();\n        constexpr double len_param = 0.1;\n        interpolator.fix_kernel_param(std::log10(len_param));\n        constexpr double reg_param = 1e-4;\n        interpolator.regularize_with(reg_param);\n\n        interpolator.compute(vars, data);\n\n        constexpr double tol_error = 1e-2;\n        for (std::size_t i = 0; i < vars.size(); ++i) {\n            INFO(\"i = \" << i);\n            const auto [mean, variance] =\n                interpolator.evaluate_mean_and_variance_on(vars[i]);\n            REQUIRE_THAT(mean,\n                Catch::Matchers::WithinAbs(\n                    data(static_cast<num_collect::index_type>(i)), tol_error));\n\n            REQUIRE(variance > 0.0);\n            REQUIRE_THAT(variance,\n                Catch::Matchers::WithinAbs(\n                    interpolator.common_coeff() * reg_param, tol_error));\n        }\n    }\n}\n", "meta": {"hexsha": "5b7bae6e09cc67816b5a7cfb0261fab2a01e71b9", "size": 7007, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/interp/kernel/kernel_interpolator_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/interp/kernel/kernel_interpolator_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/interp/kernel/kernel_interpolator_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5, "max_line_length": 80, "alphanum_fraction": 0.6225203368, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6624203702405419}}
{"text": "#ifndef EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP\n#define EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP\n\n#include <armadillo>\n\nnamespace expsum\n{\n\n//\n// Truncation of sum-of-exponentials with small exponents.\n//\n// This class find the optimal sum-of-exponentials with small exponents with\n// smaller number of terms using the modified Prony method proposed by Beylkin\n// and Monzon (2010).\n//\ntemplate <typename T>\nclass modified_prony_truncation\n{\npublic:\n    using size_type    = arma::uword;\n    using value_type   = T;\n    using real_type    = typename arma::get_pod_type<T>::result;\n    using complex_type = std::complex<real_type>;\n\n    using vector_type      = arma::Col<value_type>;\n    using real_vector_type = arma::Col<real_type>;\n    // using complex_vector_type = arma::Col<complex_type>;\n    using complex_vector_type = arma::Col<value_type>;\n\n    using matrix_type = arma::Mat<value_type>;\n    // using complex_matrix_type = arma::Mat<complex_type>;\n    using complex_matrix_type = arma::Mat<value_type>;\n\nprivate:\n    size_type size_;\n    complex_vector_type exponent_;\n    complex_vector_type weight_;\n\n    complex_vector_type vec_work_;\n    complex_matrix_type mat_work_;\n\npublic:\n    template <typename VecP, typename VecW>\n    typename std::enable_if<(arma::is_basevec<VecP>::value &&\n                             arma::is_basevec<VecW>::value),\n                            void>::type\n    run(const VecP& p, const VecW& w, real_type eps);\n\n    void resize(size_type n)\n    {\n        if (exponent_.size() < n)\n        {\n            exponent_.set_size(n);\n            weight_.set_size(n);\n            vec_work_.set_size(2 * n);\n            mat_work_.set_size(2 * n, n);\n        }\n    }\n\n    //\n    // @return number of terms after truncation\n    //\n    size_type size() const\n    {\n        return size_;\n    }\n\n    //\n    // @return Vector view to the exponents.\n    //\n    auto exponents() const -> decltype(exponent_.head(size_))\n    {\n        return exponent_.head(size_);\n    }\n    //\n    // @return Vector view to the weights.\n    //\n    auto weights() const -> decltype(weight_.head(size_))\n    {\n        return weight_.head(size_);\n    }\n};\n\ntemplate <typename T>\ntemplate <typename VecP, typename VecW>\ntypename std::enable_if<(arma::is_basevec<VecP>::value &&\n                         arma::is_basevec<VecW>::value),\n                        void>::type\nmodified_prony_truncation<T>::run(const VecP& p, const VecW& w, real_type eps)\n{\n    const auto n1 = p.n_elem;\n    resize(n1);\n\n    if (n1 == size_type())\n    {\n        size_ = n1;\n        return;\n    }\n\n    value_type* h_ptr = reinterpret_cast<value_type*>(mat_work_.memptr());\n    value_type* v_ptr = h_ptr + n1 * n1;\n\n    vector_type p_pow(h_ptr, n1, false, true);\n    vector_type h_vec(v_ptr, 2 * n1, false, true);\n\n    p_pow = p;\n\n    h_vec(0) = arma::sum(w);\n    h_vec(1) = -arma::sum(w % p_pow);\n\n    size_type n2   = 1;\n    auto factorial = real_type(1);\n    while (n2 < n1)\n    {\n        p_pow %= p;\n        h_vec(2 * n2) = arma::sum(w % p_pow);\n        p_pow %= p;\n        h_vec(2 * n2 + 1) = -arma::sum(w % p_pow);\n\n        factorial *= real_type(2 * n2 * (2 * n2 + 1));\n\n        if (std::abs(h_vec(2 * n2 + 1)) < eps * factorial)\n        {\n            // Taylor expansion converges with the tolerance eps.\n            ++n2;\n            break;\n        }\n        ++n2;\n    }\n\n    size_ = n2;\n    //\n    // Construct a Hankel matrix from the sequence h_vec, and solve the linear\n    // equation, H q = b, with b = -h_vec(m:2m-1).\n    //\n    std::cout << \"***** Hankel matrix\" << std::endl;\n    matrix_type H(h_ptr, n2, n2, false, true);\n\n    for (size_type k = 0; k < n2; ++k)\n    {\n        H.col(k) = h_vec.subvec(k, k + n2 - 1);\n    }\n\n    value_type* q_ptr = reinterpret_cast<value_type*>(exponent_.memptr());\n    vector_type q(q_ptr, n2, false, true);\n    std::cout << \"***** linear solve\" << std::endl;\n    q = arma::solve(H, h_vec.subvec(n2, 2 * n2 - 1));\n\n    //\n    // Find the roots of the Prony polynomial,\n    //\n    // q(z) = \\sum_{k=0}^{m-1} q_k z^{k}.\n    //\n    // The roots of q(z) can be obtained as the eigenvalues of the companion\n    // matrix,\n    //\n    //     (0  0  ...  0 -q[0]  )\n    //     (1  0  ...  0 -q[1]  )\n    // C = (0  1  ...  0 -q[2]  )\n    //     (.. .. ...  .. ..    )\n    //     (0  0  ...  1 -q[m-1])\n    //\n    std::cout << \"***** find roots\" << std::endl;\n    matrix_type& C = H; // overwrite H\n    C.zeros();\n    for (size_type i = 0; i < n2 - 1; ++i)\n    {\n        C(i + 1, i) = real_type(1);\n    }\n    C.col(n2 - 1) = -q;\n    // exponent_.head(n2) = arma::eig_gen(C);\n    // exponent_.head(n2) = -exponent_.head(n2);\n    auto eigvals       = arma::eig_gen(C);\n    exponent_.head(n2) = -arma::real(eigvals);\n\n    //\n    // Solve overdetermined Vandermonde system,\n    //\n    // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)\n    //\n    // by the least square method.\n    //\n    std::cout << \"***** least squares\" << std::endl;\n    complex_vector_type b2(vec_work_.memptr(), 2 * n2, false, true);\n    for (size_type i = 0; i < 2 * n2; ++i)\n    {\n        b2(i) = h_vec(i);\n    }\n    // Construct Vandermonde matrix from exponents\n    complex_matrix_type V(mat_work_.memptr(), 2 * n2, n2, false, true);\n    for (size_type i = 0; i < n2; ++i)\n    {\n        // We assume all the eigenvalues are real here\n        const auto z = exponent_(i);\n        V(0, i) = T(1);\n        for (size_type j = 1; j < V.n_rows; ++j)\n        {\n            V(j, i) = V(j - 1, i) * z; // z[i]**j\n        }\n    }\n\n    weight_.subvec(0, n2 - 1) = arma::solve(V, b2);\n}\n\n} // namespace expsum\n\n#endif /* EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP */\n", "meta": {"hexsha": "24a28344d8f79c31df0844ccffb77b71c22090f5", "size": 5626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/modified_prony_truncation.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/modified_prony_truncation.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/modified_prony_truncation.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.0480769231, "max_line_length": 78, "alphanum_fraction": 0.5558123, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6624203678232529}}
{"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_rpy_hxx__\n#define __pinocchio_math_rpy_hxx__\n\n#include <Eigen/Geometry>\n\n#include \"pinocchio/math/sincos.hpp\"\n\nnamespace pinocchio\n{\n  namespace rpy\n  {\n    template<typename Scalar>\n    Eigen::Matrix<Scalar,3,3>\n    rpyToMatrix(const Scalar& r,\n                const Scalar& p,\n                const Scalar& y)\n    {\n      typedef Eigen::AngleAxis<Scalar> AngleAxis;\n      typedef Eigen::Matrix<Scalar,3,1> Vector3s;\n      return (AngleAxis(y, Vector3s::UnitZ())\n              * AngleAxis(p, Vector3s::UnitY())\n              * AngleAxis(r, Vector3s::UnitX())\n             ).toRotationMatrix();\n    }\n\n\n    template<typename Vector3Like>\n    Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options>\n    rpyToMatrix(const Eigen::MatrixBase<Vector3Like> & rpy)\n    {\n      PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Vector3Like, rpy, 3, 1);\n      return rpyToMatrix(rpy[0], rpy[1], rpy[2]);\n    }\n\n\n    template<typename Matrix3Like>\n    Eigen::Matrix<typename Matrix3Like::Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options>\n    matrixToRpy(const Eigen::MatrixBase<Matrix3Like> & R)\n    {\n      PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like, R, 3, 3);\n      assert(R.isUnitary() && \"R is not a unitary matrix\");\n\n      typedef typename Matrix3Like::Scalar Scalar;\n      typedef Eigen::Matrix<Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options> ReturnType;\n      static const Scalar pi = PI<Scalar>();\n\n      ReturnType res = R.eulerAngles(2,1,0).reverse();\n\n      if(res[1] < -pi/2)\n        res[1] += 2*pi;\n\n      if(res[1] > pi/2)\n      {\n        res[1] = pi - res[1];\n        if(res[0] < Scalar(0))\n          res[0] += pi;\n        else\n          res[0] -= pi;\n        // res[2] > 0 according to Eigen's eulerAngles doc, no need to check its sign\n        res[2] -= pi;\n      }\n\n      return res;\n    }\n\n\n    template<typename Vector3Like>\n    Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options>\n    computeRpyJacobian(const Eigen::MatrixBase<Vector3Like> & rpy, const ReferenceFrame rf)\n    {\n      typedef typename Vector3Like::Scalar Scalar;\n      typedef Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options> ReturnType;\n      ReturnType J;\n      const Scalar p = rpy[1];\n      Scalar sp, cp;\n      SINCOS(p, &sp, &cp);\n      switch (rf)\n      {\n        case LOCAL:\n        {\n          const Scalar r = rpy[0];\n          Scalar sr, cr; SINCOS(r, &sr, &cr);\n          J << Scalar(1.0), Scalar(0.0),   -sp,\n               Scalar(0.0),          cr, sr*cp,\n               Scalar(0.0),         -sr, cr*cp;\n          return J;\n        }\n        case WORLD:\n        case LOCAL_WORLD_ALIGNED:\n        {\n          const Scalar y = rpy[2];\n          Scalar sy, cy; SINCOS(y, &sy, &cy);\n          J << cp*cy,         -sy, Scalar(0.0),\n               cp*sy,          cy, Scalar(0.0),\n                 -sp, Scalar(0.0), Scalar(1.0);\n          return J;\n        }\n        default:\n        {\n          throw std::invalid_argument(\"Bad reference frame.\");\n        }\n      }\n    }\n\n\n    template<typename Vector3Like>\n    Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options>\n    computeRpyJacobianInverse(const Eigen::MatrixBase<Vector3Like> & rpy, const ReferenceFrame rf)\n    {\n      typedef typename Vector3Like::Scalar Scalar;\n      typedef Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options> ReturnType;\n      ReturnType J;\n      const Scalar p = rpy[1];\n      Scalar sp, cp;\n      SINCOS(p, &sp, &cp);\n      Scalar tp = sp/cp;\n      switch (rf)\n      {\n        case LOCAL:\n        {\n          const Scalar r = rpy[0];\n          Scalar sr, cr; SINCOS(r, &sr, &cr);\n          J << Scalar(1.0), sr*tp, cr*tp,\n               Scalar(0.0),    cr,   -sr,\n               Scalar(0.0), sr/cp, cr/cp;\n          return J;\n        }\n        case WORLD:\n        case LOCAL_WORLD_ALIGNED:\n        {\n          const Scalar y = rpy[2];\n          Scalar sy, cy; SINCOS(y, &sy, &cy);\n          J << cy/cp,  sy/cp, Scalar(0.0),\n                 -sy,     cy, Scalar(0.0),\n               cy*tp,  sy*tp, Scalar(1.0);\n          return J;\n        }\n        default:\n        {\n          throw std::invalid_argument(\"Bad reference frame.\");\n        }\n      }\n    }\n\n    template<typename Vector3Like0, typename Vector3Like1>\n    Eigen::Matrix<typename Vector3Like0::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like0)::Options>\n    computeRpyJacobianTimeDerivative(const Eigen::MatrixBase<Vector3Like0> & rpy, const Eigen::MatrixBase<Vector3Like1> & rpydot, const ReferenceFrame rf)\n    {\n      typedef typename Vector3Like0::Scalar Scalar;\n      typedef Eigen::Matrix<typename Vector3Like0::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like0)::Options> ReturnType;\n      ReturnType J;\n      const Scalar p = rpy[1];\n      const Scalar dp = rpydot[1];\n      Scalar sp, cp;\n      SINCOS(p, &sp, &cp);\n      switch (rf)\n      {\n        case LOCAL:\n        {\n          const Scalar r = rpy[0];\n          const Scalar dr = rpydot[0];\n          Scalar sr, cr; SINCOS(r, &sr, &cr);\n          J << Scalar(0.0), Scalar(0.0),               -cp*dp,\n               Scalar(0.0),      -sr*dr,  cr*cp*dr - sr*sp*dp,\n               Scalar(0.0),      -cr*dr, -sr*cp*dr - cr*sp*dp;\n          return J;\n        }\n        case WORLD:\n        case LOCAL_WORLD_ALIGNED:\n        {\n          const Scalar y = rpy[2];\n          const Scalar dy = rpydot[2];\n          Scalar sy, cy; SINCOS(y, &sy, &cy);\n          J << -sp*cy*dp - cp*sy*dy,      -cy*dy, Scalar(0.0),\n                cp*cy*dy - sp*sy*dp,      -sy*dy, Scalar(0.0),\n                             -cp*dp, Scalar(0.0), Scalar(0.0);\n          return J;\n        }\n        default:\n        {\n          throw std::invalid_argument(\"Bad reference frame.\");\n        }\n      }\n    }\n\n  } // namespace rpy\n}\n#endif //#ifndef __pinocchio_math_rpy_hxx__\n", "meta": {"hexsha": "edaff629136ef237bf16b10300a137a13a5bde8b", "size": 6049, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/math/rpy.hxx", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "src/math/rpy.hxx", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "src/math/rpy.hxx", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 31.3419689119, "max_line_length": 154, "alphanum_fraction": 0.5610844768, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6623899647402501}}
{"text": "// Unit test for the isEqualArray1D function in testing_functions.cpp\n// This function determines if each element in two 1D arrays of 1D arrays are equal within some tolerance\n// This is important because there is inherent error in double precision numbers\n// COMPLETE. This function works as intended. 2021/11/21\n\n\n// Include headers\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the isEqualArray1D_of_Array1D function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set a tolerance\n    double TOL = 1e-10;\n\n    // Set an array of values\n    Array<ArrayXd, 3, 1> vals;\n    for (int i = 0; i < 3; i++) {\n        vals(i) = ArrayXd::Zero(4) + 1.1;\n    }    \n\n    // We can test 4 different modes of this function to determine how well it works:\n    // Greater and within tolerance\n    // Greater and outside tolerance\n    // Lower and within tolerance\n    // Lower and outside tolerance\n\n    // Build the test array\n    Array<ArrayXd, 3, 1> testArray;\n    for (int i = 0; i < 3; i++) {\n        // Initialize internal arrays\n        testArray(i) = ArrayXd::Zero(4);\n        \n        // Populate internal arrays\n        testArray(i)(0) = vals(i)(0) + 0.1*TOL;\n        testArray(i)(1) = vals(i)(1) + 1.1*TOL;\n        testArray(i)(2) = vals(i)(2) - 0.1*TOL;\n        testArray(i)(3) = vals(i)(3) - 1.1*TOL;\n    }    \n\n    // Use the isEqualArray1D function to see if these are equal.\n    Array<Array<bool,Dynamic,1>, 3, 1> boolArray = isEqualArray1D_of_Array1D(vals, testArray, TOL);\n\n    // First, we will test to make sure that val+0.1*TOL is considered equal since it will by definition be within the tolerance\n    // This should result in 1\n    if (boolArray(0)(0) == 1 && boolArray(1)(0) == 1 && boolArray(2)(0) == 1 ) {  // \n        cout << \"Test of higher but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }\n\n    // Test to make sure that val+1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    // This should result in 0\n    if (boolArray(0)(1) == 0 && boolArray(1)(1) == 0 && boolArray(2)(1) == 0) {  // \n        cout << \"Test of higher over tolerance is a success.\" << endl;\n    } \n    else {        \n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher over tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }   \n\n    // Test to make sure that val-0.1*TOL is considered equal since it will by definition be within the tolerance\n    // This should result in 1\n    if (boolArray(0)(2) == 1 && boolArray(1)(2) == 1 && boolArray(2)(2) == 1) {  // \n        cout << \"Test of lower but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    // Test to make sure that val-1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    // This should result in 0\n    if (boolArray(0)(3) == 0 && boolArray(1)(3) == 0 && boolArray(2)(3) == 0) {  // \n        cout << \"Test of lower but outside tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but outside tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    cout << endl << endl;\n}", "meta": {"hexsha": "455ddc63b6a3ef18486e62652723786e66e2ba23", "size": 3839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_isEqualArray1D_of_Array1D.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/unitTests/test_isEqualArray1D_of_Array1D.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/unitTests/test_isEqualArray1D_of_Array1D.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": 38.7777777778, "max_line_length": 128, "alphanum_fraction": 0.5415472779, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8221891283434876, "lm_q1q2_score": 0.6623820348977985}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  // Constructor\n  arma::mat x,y;\n\n  x << 0.1778 << 0.1203 << -0.2264 << endr\n    << 0.0957 << 0.2403 << -0.3400 << endr\n    << 0.1397 << 0.1925 << -0.3336 << endr\n    << 0.2256 << 0.3144 << -0.8695 << endr;\n\n  y <<  1  <<  1  << -1  << endr\n    <<  1  << -1  <<  1  << endr\n    << -1  <<  1  <<  1  << endr\n    <<  1  <<  1  <<  1  << endr;\n\n  // Forward\n  arma::mat loss_none = arma::log(1 + arma::exp(-y % x));\n  double loss_sum = arma::sum(arma::sum(loss_none));\n  double loss_mean = loss_sum / x.n_elem;\n\n  // Backward\n  arma::mat output ;\n  output.set_size(size(x));\n  arma::mat numerator = -y % arma::exp(-y % x);\n  arma::mat denominator = 1 + arma::exp(-y % x);\n  output = numerator / denominator;\n\n  // Display\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"USER-PROVIDED MATRICES : \" << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"Input shape : \"<< x.n_rows << \" \" << x.n_cols << endl;\n  cout << \"Input : \" << endl << x << endl;\n  cout << \"Target shape : \"<< y.n_rows << \" \" << y.n_cols << endl;\n  cout << \"Target : \" << endl << y << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"SUM \" << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"FORWARD : \" << endl;\n  cout << \"Loss : \\n\" << loss_none << '\\n';\n  cout << \"Loss (sum):\\n\" << loss_sum << '\\n';\n  cout << \"BACKWARD : \" << endl;\n  cout << \"Output shape : \"<< output.n_rows << \" \" << output.n_cols << endl;\n  cout << \"Output (sum) : \" << endl << output << endl;\n  cout << \"Sum of all values in this matrix : \" << arma::as_scalar(arma::accu(output)) << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"MEAN \" << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  cout << \"FORWARD : \" << endl;\n  cout << \"Loss (mean):\\n\" << loss_mean << '\\n';\n  cout << \"BACKWARD : \" << endl;\n  cout << \"Output shape : \"<< output.n_rows << \" \" << output.n_cols << endl;\n  cout << \"Output (mean) : \" << endl << output / x.n_elem << endl;\n  cout << \"Sum of all values in this matrix : \" << arma::as_scalar(arma::accu(output / x.n_elem)) << endl;\n  cout << \"------------------------------------------------------------------\" << endl;\n  return 0;\n}", "meta": {"hexsha": "ba168f0b6926a37fa8e7f3f4238aefa434d5151d", "size": 2517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soft_margin_loss/test.cpp", "max_stars_repo_name": "iamshnoo/mlpack-testing", "max_stars_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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": "soft_margin_loss/test.cpp", "max_issues_repo_name": "iamshnoo/mlpack-testing", "max_issues_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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": "soft_margin_loss/test.cpp", "max_forks_repo_name": "iamshnoo/mlpack-testing", "max_forks_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "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": 39.9523809524, "max_line_length": 106, "alphanum_fraction": 0.417560588, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6623708140290082}}
{"text": "#include <iostream>\n#include <cmath>\n#include <chrono>\n#include <fstream>\n\n#include <Eigen/Dense>\n\n\nstruct Domain {\n    constexpr Domain(double start, double end) : x_start(start), x_end(end) {}\n    double x_start;\n    double x_end;\n};\n\n\ntemplate <typename Derived>\nvoid init_solution(Eigen::ArrayBase<Derived>& V, const Domain& domain) {\n    const std::size_t nx = V.cols();\n    const double hx = (domain.x_end - domain.x_start) / nx;\n    const double xc = 0.5 * (domain.x_start + domain.x_end) + (nx / 8.0) * hx;\n\n    for(std::size_t i=0; i < nx; ++i) {\n        double x = domain.x_start + (i - 0.5) * hx;\n        V(0, i) = std::abs(x - xc) < 0.2 ? 1. : 0.;\n        V(1, i) = 0.;\n    }           \n}\n\n\nvoid compute_flux(Eigen::Array<double, 2, 1>& flux, double V1, double V2, double tol)\n{\n    flux(0) = V2;\n    if(std::abs(V1) < tol)\n        flux(1) = 0.;\n    else\n        flux(1) = V2 * V2 / V1 + 0.5 * 9.81 * V1 * V1;\n}\n\n\ntemplate<typename ArrayType1d, typename ArrayType2d>\nvoid scheme_LaxFriedrich(ArrayType2d& V, const ArrayType2d& Vold,\n                         const ArrayType1d& lambdas,\n                         double dt, double dx, double tol)\n{\n    std::size_t Nx = lambdas.cols();\n    double Cx = dt / dx;\n\n    Eigen::Array<double, 2, 1> flux, flux1, flux2;\n    compute_flux(flux1, Vold(0, 0), Vold(1, 0), tol);\n\n    V(1, 0) += Cx * (flux1(1) - lambdas(0) * Vold(1, 0));\n    for(std::size_t i=0; i<Nx-1; ++i) {\n        compute_flux(flux2, Vold(0, i+1), Vold(1, i+1), tol);\n        flux = 0.5 * Cx * ((flux2 + flux1) - std::max(lambdas(i), lambdas(i+1)) * (Vold.col(i+1) - Vold.col(i)));\n        V.col(i) -= flux;\n        V.col(i+1) += flux;\n        flux1.swap(flux2);\n    }\n    V(1, Nx-1) -= Cx * (flux1(1) + lambdas(Nx-1) * Vold(1, Nx-1));\n}\n\n\n\ntemplate<typename ArrayType1d, typename ArrayType2d>\ndouble updateCFL(ArrayType1d& lambdas, const ArrayType2d& V,\n                 double dx, double tol)\n{\n    std::size_t Nx = lambdas.cols();\n    double M = 0.;\n\n    for(std::size_t i=0; i<Nx; ++i) {\n        if(std::abs(V(0, i)) < tol) {\n            lambdas(i) = 0.;\n        }\n        else {\n            lambdas(i) = std::abs(V(1, i) / V(0, i)) + std::sqrt(9.81 * V(0, i));\n            M = std::max(M, lambdas(i));\n        }\n    }\n\n    return 0.5 * dx / M;\n}\n\n\ntemplate<typename ArrayType1d, typename ArrayType2d>\ndouble update_to_time(ArrayType2d& V, ArrayType2d& Vold, ArrayType1d& lambdas,\n                      double t, double tframe, double dx, double tol)\n                      \n{    \n    while(t < tframe) {\n        double dt = std::min(updateCFL(lambdas, V, dx, tol),\n                             tframe - t);\n        Vold = V;\n        scheme_LaxFriedrich(V, Vold, lambdas, dt, dx, tol);\n        \n        t += dt;\n    }\n\n    return t;\n}\n\n\n\nint main() {\n    constexpr Domain domain(0., 1.);\n    constexpr std::size_t Nx = 16384;\n    constexpr double T = 2.0;\n    constexpr double dx = (domain.x_end - domain.x_start) / Nx;\n    constexpr double tol = 1e-15;\n\n\n    Eigen::Array<double, 2, Eigen::Dynamic> V(2, Nx);\n    init_solution(V, domain);\n\n    Eigen::Array<double, 2, Eigen::Dynamic> Vold(2, Nx);\n    Eigen::Array<double, 1, Eigen::Dynamic> lambdas(Nx);\n    \n    double t = 0;\n    std::cout << \"Initial time t = \" << t << std::endl;\n\n    auto time_start = std::chrono::high_resolution_clock::now();\n    t = update_to_time(V, Vold, lambdas, t, T, dx, tol);\n    auto time_end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed_seconds = time_end - time_start;\n    \n    std::cout << \"Elapsed time: \" << elapsed_seconds.count() << \"s\" << std::endl;    \n    std::cout << \"End of simulation, t = \" << t << std::endl;\n    \n    std::cout << \"mean(h) = \" << V.row(0).mean() << std::endl;\n\n    const Eigen::IOFormat to_file(Eigen::FullPrecision, Eigen::DontAlignCols, \"\\n\", \"\\n\");\n    std::ofstream file(\"sol-cpu\");\n    file << V.row(0).format(to_file);\n    \n    return 0;\n}\n", "meta": {"hexsha": "24230edd45be31d57c5fe3717837773d1f2527d0", "size": 3925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SaintVenant/C/main1d.cpp", "max_stars_repo_name": "danielcort/benchmarks-python-julia-c", "max_stars_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-03-27T08:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T12:26:54.000Z", "max_issues_repo_path": "SaintVenant/C/main1d.cpp", "max_issues_repo_name": "danielcort/benchmarks-python-julia-c", "max_issues_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T16:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-27T06:33:09.000Z", "max_forks_repo_path": "SaintVenant/C/main1d.cpp", "max_forks_repo_name": "danielcort/benchmarks-python-julia-c", "max_forks_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-29T13:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T17:49:09.000Z", "avg_line_length": 28.6496350365, "max_line_length": 113, "alphanum_fraction": 0.5533757962, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6623707993048674}}
{"text": "//#include <vcp/imats.hpp>\n//#include <vcp/matrix.hpp>\n//#include <vcp/matrix_assist.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n#include \"kv/interval.hpp\"\n// define rounding operations for double\n// if \"rdouble.hpp\" is not included, result of computation is not \"verified\" \n#include \"kv/rdouble.hpp\"\ntypedef kv::interval<double> itv;\nnamespace ub = boost::numeric::ublas;\nitv factorial(int k){\n    itv sum;\n    sum=1.;\n    for (int i = 1; i <= k; ++i)\n    {\n        sum *= i;\n    }\n    return sum;\n}\nint main(void){\nstd::cout.precision(17);\n  int n=2,M=42;\n  /*  vcp::matrix< itv, vcp::imats< double > > A,B,res,sum; \n  sum.zeros(n);\n  A(0,0)=1.;\n  A(0,1)=-3.;\n  A(1,0)=-2.;\n  A(1,1)=5.;\n  for(int N=0;N<=M;N++){\n    sum=sum*A+1/factorial(N);\n  }\n  norm=max(abs(A));\n  error=exp(norm)*pow(norm,M+1)/factorial(M+1);\n  b=max(abs(error));\n  B.ones(n);\n  B=B*itv(-b,b);\n  */\n  // use ublas\n  ub::matrix< itv > A(n, n),B(n, n),res(n, n),sum(n, n),pro(n,n);\n  itv error,norm;\n  double b;\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      sum(i,j)=0.;\n      if(i==j)pro(i,j)=1.;\n      else pro(i,j)=0.;\n    }\n  }\n\tA(0, 0)=1.; A(0, 1)=-3.;\n\tA(1, 0)=-2; A(1, 1)=5.;\n  for(int N=0;N<=M;N++){\n   sum+=(1/factorial(N))*pro;\n   pro=prod(pro,A);\n  }\n  //fprintf( stderr, \"Check\\n\" );\n  //norm=max(abs(A));\n  norm=abs(A(0,0));\n  for(int i1=0;i1<n;i1++){\n    for(int j1=0;j1<n;j1++){\n      if (A(i1,j1)>abs(norm)) norm=abs(A(i1,j1));\n    }\n  }\n\n  error=exp(norm)*pow(norm,M+1)/factorial(M+1);\n  b=(abs(error)).upper();\n\n  for(int k1=0;k1<n;k1++){\n    for(int l1=0;l1<n;l1++){\n      B(k1,l1).assign(-1.,1.);\n      B(k1,l1)=b*B(k1,l1);\n    }\n  }\n  res=sum+B;\n\n  std::cout<<res<<std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "504fc48b2fb50d17ca811ad6615df621c866204d", "size": 1795, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Draft/MatrixExp.cc", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "Draft/MatrixExp.cc", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "Draft/MatrixExp.cc", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["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.1604938272, "max_line_length": 77, "alphanum_fraction": 0.548189415, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6623704918779197}}
{"text": "#include \"LinearRegression.h\"\n#include \"LogisticRegression.h\"\n#include <armadillo>\n#include <assert.h>\n#include <iostream>\nusing namespace std;\nusing namespace arma;\n\nvoid testFailed() {\n  mat x = mat(\"1 0 0; 0 0 1\");\n  vec y = vec(\"0 1\");\n  LinearRegression *A = new LinearRegression(x, y);\n  A->Train(normalEquation);\n  vec p = vec(\"1 0 0\");\n}\n\nvoid testSucc() {\n  mat x = mat(\"3 0; 0 4;2 5; 5 2\");\n  vec y = vec(\"3 8 12 9 \");\n  LinearRegression *A = new LinearRegression(x, y);\n  A->Train(normalEquation);\n  vec p = vec(\"3 0\");\n  std::cout << A->Predict(p) << std::endl;\n  vec q = vec(\"0 8\");\n  std::cout << A->Predict(q) << std::endl;\n  mat ex = mat(\"0 0;\");\n  vec ey = vec(\"0\");\n\n  A->AddData(ex, ey);\n  A->Train(normalEquation);\n  std::cout << A->Predict(q) << std::endl;\n}\n\nvoid testSucc2() {\n  mat x = mat(\"3 0; 0 4;2 5;0 0; 5 2; 7 0; 0 8\");\n  vec y = vec(\"3 8 12 0 9 7 16\");\n  LinearRegression *A = new LinearRegression(x, y);\n  A->Train(gradientDescent, 0.1, 10000);\n  vec p = vec(\"3 0\");\n  std::cout << A->Predict(p) << std::endl;\n  vec q = vec(\"0 8\");\n  std::cout << A->Predict(q) << std::endl;\n  mat ex = mat(\"0 0;\");\n  vec ey = vec(\"0\");\n\n  A->AddData(ex, ey);\n  A->Train(gradientDescent, 0.01, 1000);\n  std::cout << A->Predict(q) << std::endl;\n  std::cout << A->SelfCost() << std::endl;\n}\n\nvoid test3() {\n  mat x = mat(\"2 2; 3 3; 4 4; -1 2; -10 8; 8 9; -4 -4;1 -3; 8 1; 3 -4; 1 -1; \"\n              \"-1 1; 4 -6\");\n  vec y = vec(\"1 1 1 0 0 1 0 0 1 0 0 0 0 \");\n  LogisticRegression *A = new LogisticRegression(x, y);\n  A->Train(gradientDescent, 0.1, 100000);\n\n  vec p = vec(\"3 0\");\n  vec q = vec(\"5 -5\");\n  vec f = vec(\"3 7\");\n  std::cout << A->Predict(p) << std::endl;\n  std::cout << A->Predict(q) << std::endl;\n  std::cout << A->Predict(f) << std::endl;\n  std::cout << A->SelfCost() << std::endl;\n}\n\nint main() {\n  testFailed();\n  testSucc();\n  testSucc2();\n  test3();\n}\n", "meta": {"hexsha": "2bce5036dd15a8e78977490eaa95a0ed130cc6e8", "size": 1885, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LinearModel/test.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/test.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/test.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": 25.472972973, "max_line_length": 78, "alphanum_fraction": 0.5549071618, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778825, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6623704873608883}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <deque>\n#include <map>\n#include <algorithm>\n#include <limits>\n#include <assert.h>\n#include <sstream>\n#include <boost/foreach.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\n#include \"input.h\"\n#include <input.hpp>\n#include <assert.hpp>\n\n// https://rosettacode.org/wiki/Modular_inverse#C.2B.2B\nint256_t modinv(int256_t a, int256_t b) {\n  int256_t b0 = b, t, q;\n  int256_t x0 = 0, x1 = 1;\n  if (b == 1) return 1;\n  while (a > 1) {\n    q = a / b;\n    t = b, b = a % b, a = t;\n    t = x0, x0 = x1 - q * x0, x1 = t;\n  }\n  if (x1 < 0) x1 += b0;\n  return x1;\n}\n\nenum ShuffleKind { Deal = 0, Cut = 1, DealInc = 2 };\n\nstruct Params {\n  int256_t a;\n  int256_t b;\n};\n\nclass Shuffle {\npublic:\n  ShuffleKind kind;\n  int256_t num;\n  Shuffle(string s) {\n    if (s.rfind(\"deal into\", 0) == 0) {\n      kind = Deal;\n      num = 0;\n      return;\n    }\n    num = stoi(s.substr(s.rfind(\" \")+1));\n    if (s.rfind(\"cut\", 0) == 0) {\n      kind = Cut;\n    } else {\n      kind = DealInc;\n    }\n  }\n  Params params(int256_t a, int256_t b, int256_t num_cards) {\n    int256_t na = 0;\n    int256_t nb = 0;\n    switch (this->kind) {\n    case Deal:\n      na = -a;\n      nb = -b-1;\n      break;\n    case Cut:\n      na = a;\n      nb = b - this->num;\n      break;\n    default:\n      na = a * this->num;\n      nb = b * this->num;\n    }\n    return Params{(na+num_cards) % num_cards, (nb+num_cards) % num_cards};\n  }\n  Params reverse_params(int256_t a, int256_t b, int256_t num_cards) {\n    int256_t na = 0;\n    int256_t nb = 0;\n    switch (this->kind) {\n    case Deal:\n      na = -a;\n      nb = -b-1;\n      break;\n    case Cut:\n      na = a;\n      nb = b + this->num;\n      break;\n    default:\n      int256_t m = modinv(this->num, num_cards);\n      na = a * m;\n      nb = b * m;\n    }\n    return Params{(na+num_cards) % num_cards, (nb+num_cards) % num_cards};\n  }\n};\n\nint256_t modpow(int256_t b, int256_t e, int256_t m) {\n  int256_t res = 1;\n  while (e > 0) {\n    if ((e%2) == 1) {\n      res = (res * b) % m;\n    }\n    e = e / 2;\n    b = (b * b) % m;\n  }\n  return res;\n}\n\nclass Game {\n  vector<Shuffle> shuffles;\n  int256_t cards;\npublic:\n  Game(vector<string> &inp, int256_t num_cards) {\n    for (auto l : inp) {\n      shuffles.push_back(Shuffle(l));\n    }\n    cards = num_cards;\n  }\n  Params params() {\n    int256_t a = 1;\n    int256_t b = 0;\n    for (auto s : this->shuffles) {\n      Params p = s.params(a, b, this->cards);\n      a = p.a;\n      b = p.b;\n    }\n    return Params{a, b};\n  }\n  int256_t forward(int256_t card) {\n    Params p = this->params();\n    return (((p.a * card) + p.b) % this->cards);\n  }\n  Params reverse_params() {\n    int256_t a = 1;\n    int256_t b = 0;\n    BOOST_REVERSE_FOREACH(auto s, this->shuffles) {\n      Params p = s.reverse_params(a, b, this->cards);\n      a = p.a;\n      b = p.b;\n    }\n    return Params{a, b};\n  }\n  int256_t backward(int256_t card, int256_t rounds) {\n    Params p = this->reverse_params();\n    int256_t exp = modpow(p.a, rounds, this->cards);\n    int256_t im = modinv(p.a-1, this->cards);\n    return ((((exp-1) * im) * p.b) + (exp * card)) % this->cards;\n  }\n};\n\nvoid tests() {\n}\n\nvoid run(unsigned int inp_len, unsigned char* inp, bool is_bench) {\n  vector<string> ln = lines(inp_len, inp);\n  Game* game = new Game(ln, 10007);\n  auto p1 = game->forward(2019);\n  game = new Game(ln, 119315717514047);\n  int256_t rounds = 101741582076661;\n  auto p2 = game->backward(2020, rounds);\n  if (!is_bench) {\n    cout << \"Part 1: \" << p1 << \"\\n\";\n    cout << \"Part 2: \" << p2 << \"\\n\";\n  }\n}\n\nint main(int argc, char **argv) {\n  if (is_test()) { tests(); }\n  benchme(argc, argv, input_txt_len, input_txt, run);\n}\n", "meta": {"hexsha": "93e464eb0792dbd5fdc08085924f165d62658b7d", "size": 3747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/22/cpp/aoc.cpp", "max_stars_repo_name": "beanz/advent", "max_stars_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2019/22/cpp/aoc.cpp", "max_issues_repo_name": "beanz/advent", "max_issues_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/22/cpp/aoc.cpp", "max_forks_repo_name": "beanz/advent", "max_forks_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_forks_repo_licenses": ["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.9122807018, "max_line_length": 74, "alphanum_fraction": 0.5580464371, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6623704679687661}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n\n#include \"vice/integrate.h\"\n#include \"vice/functors.h\"\n\n\nint main () {\n  double texp = 0.1;\n\n  //double depth    = 0.1;\n  //double duration = 0.1;\n  //double ingress  = 0.2;\n  //vice::functors::TrapFunctor<double> func(depth, duration, ingress);\n\n  double tau = 0.5;\n  double r = 0.1;\n  double b = 0.5;\n  Eigen::VectorXd u(2);\n  u << 0.3, 0.2;\n  vice::functors::StarryFunctor<double> func(u, r, b, tau);\n\n  //double tmin = -duration - 2*ingress;\n  //double tmax =  duration + 2*ingress;\n  double tmin = -tau - texp;\n  double tmax =  tau + texp;\n  int npts = 500;\n  double dt = (tmax - tmin) / (npts - 1);\n\n  int neval = 15;\n  double tol = 1e-9;\n\n  std::cout << \"time,flux,truth,reimann,n_reimann,trap_fixed,n_trap_fixed,simp_fixed,n_simp_fixed,trap_adapt,n_trap_adapt,simp_adapt,n_simp_adapt,\\n\";\n  std::cout.precision(25);\n  std::cout << std::scientific;\n\n  for (int i = 0; i < npts; ++i) {\n    double t = tmin + i * dt;\n    double lower = t - 0.5*texp;\n    double upper = t + 0.5*texp;\n\n    func.reset();\n    double flux = func(t);\n    double truth = func.integrate(lower, upper) / texp;\n\n    std::cout << t << \",\" << flux << \",\" << truth << \",\";\n\n    func.reset();\n    double f_reimann = vice::reimann::integrate_fixed(func, lower, upper, neval) / texp;\n    std::cout << f_reimann << \",\" << func.get_n_eval() << \",\";\n\n    func.reset();\n    double f_trap_fixed = vice::trapezoid::integrate_fixed(func, lower, upper, neval) / texp;\n    std::cout << f_trap_fixed << \",\" << func.get_n_eval() << \",\";\n\n    func.reset();\n    double f_simp_fixed = vice::simpson::integrate_fixed(func, lower, upper, neval) / texp;\n    std::cout << f_simp_fixed << \",\" << func.get_n_eval() << \",\";\n\n    func.reset();\n    double f_trap_adapt = vice::trapezoid::integrate_adapt(func, lower, upper, tol, 50) / texp;\n    std::cout << f_trap_adapt << \",\" << func.get_n_eval() << \",\";\n\n    func.reset();\n    double f_simp_adapt = vice::simpson::integrate_adapt(func, lower, upper, tol, 50) / texp;\n    std::cout << f_simp_adapt << \",\" << func.get_n_eval() << \",\";\n\n    std::cout << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "f181c9adf5187dc91a8407926c26b2d5ef13b985", "size": 2127, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/demo.cc", "max_stars_repo_name": "dfm/confessional", "max_stars_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "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/demo.cc", "max_issues_repo_name": "dfm/confessional", "max_issues_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-02T12:00:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-02T12:00:51.000Z", "max_forks_repo_path": "src/demo.cc", "max_forks_repo_name": "dfm/confessional", "max_forks_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1369863014, "max_line_length": 150, "alphanum_fraction": 0.6046074283, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6623316359097686}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <cstdio>\n#include <string>\n#include \"nn.h\"\n#include <fstream>\n#include <vector>\n#include <sstream>\n\nusing namespace std;\n\nint main(int argc, const char *argv[])\n{\n\tstring filename(argv[1]);\n\tifstream fin;\n\tstring directory(\"../Datasets/\");\n\tstring filepath = directory + filename;\n\tfin.open(filepath);\n\n\tstring str;\n\tint n_input = 0;  // input dimensionality\n\tint n_output = 0; // output dimensionality\n\tint n_sample = 0; // number of training samples\n\n\twhile (fin >> str)\n\t{\n\t\tn_sample++;\n\t}\n\n\tstringstream sst(str);\n\tdouble each_input;\n\twhile (sst >> each_input)\n\t{\n\t\tn_input++;\n\t\tif (sst.peek() == ',')\n\t\t\tsst.ignore();\n\t}\n\tn_output = atoi(argv[2]);\n\tn_input = n_input - n_output;\n\t//cout << n_input << \"  \" << n_output;\n\t\n\tint n_layer = 3;\t\t  // number of layers\n\tint max_steps = 5;\t  // number of optimization steps\n\tint n_epoch = max_steps;\n\tdouble lambda = 0.000001; // regularization parameter\n\n\tmatrix_t X(n_sample, n_input);\n\tmatrix_t Y(n_sample, n_output);\n\n\tfin.clear();\n\tfin.seekg(0, ios::beg);\n\tint row = 0;\n\twhile (fin >> str)\n\t{\n\t\tint col = 0;\n\t\tdouble data;\n\t\tstringstream ss(str);\n\t\twhile (ss >> data)\n\t\t{\n\t\t\tif (col < n_input)\n\t\t\t{\n\t\t\t\tX(row, col) = data;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint pos = col - n_input;\n\t\t\t\tY(row, pos) = data;\n\t\t\t}\n\t\t\tif (ss.peek() == ',')\n\t\t\t{\n\t\t\t\tss.ignore();\n\t\t\t}\n\t\t\tcol++;\n\t\t}\n\t\trow++;\n\t}\n\tfin.close();\n\n\t// cout << \"training input: \" << endl\n\t// \t << X << endl;\n\t// cout << \"training output: \" << endl\n\t// \t << Y << endl;\n\n\t// specify network topology\n\tEigen::VectorXi topo(n_layer);\n\ttopo << n_input, n_input, n_output;\n\t// cout << \"topology: \" << endl\n\t// \t << topo << endl;\n\n\t// initialize a neural network with given topology\n\tNeuralNet nn(topo);\n\n\tnn.autoscale(X, Y);\n\t// train the network\n\tstd::cout << \"starting training\" << endl;\n\tdouble err;\n\tdouble prevAccuracy = 0;\n\tdouble accuracy;\n\tfor (int i = 0; i < max_steps; ++i)\n\t{\n\t\terr = nn.loss(X, Y, lambda);\n\t\tnn.rprop();\n\t\t//nn.forward_pass(X);\n\t\tmatrix_t Y_prime = nn.get_activation();\n\t\taccuracy = nn.measure_accuracy(Y, Y_prime);\n\t\t//cout << \"Accuracys: \" << accuracy << \"  Step No: \" << i<<endl;\n\t\tcout << err << endl;\n\t\tif (accuracy - prevAccuracy < .001 && accuracy>90)\n\t\t{\n\t\t\tn_epoch = i;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprevAccuracy = accuracy;\n\t\t}\n\t\t//printf(\"%3i   %4.4f\\n\", i, err);\n\t}\n\n\t// write model to disk\n\tnn.write(\"example.nn\");\n\n\t// read model from disk\n\tNeuralNet nn2(\"example.nn\");\n\n\t// testing\n\tnn2.forward_pass(X);\n\tmatrix_t Y_test = nn2.get_activation();\n\n\t//std::cout << \"test input:\" << endl\n\t//  << X << endl;\n\t//std::cout << \"test output:\" << endl\n\t//  << Y_test << endl;\n\tint correct = 0;\n\tfor (int i = 0; i < n_sample; i++)\n\t{\n\t\tint j = 0;\n\t\tfor (; j < n_output; j++)\n\t\t{\n\t\t\tint out = Y_test(i, j) > 0.7 ? 1 : 0;\n\t\t\t//printf(\"%3i   %4.4f\", (int)Y(i, j), Y_test(i, j));\n\t\t\tif (out != Y(i, j))\n\t\t\t\tbreak;\n\t\t}\n\t\t//cout << endl;\n\t\tif (j == n_output)\n\t\t\tcorrect++;\n\t}\n\tcout<< \"Dataset: \" << filename << endl;\n\tcout << \"Correct answer \" << correct << \" among \" << n_sample << \" test\" << endl;\n\tcout << \"Accuracy: \" << (double)correct / (double)n_sample * 100 << \"%\" << endl;\n\tcout << \"Step Count: \" << n_epoch << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "1a5d7765b13f665b19bdc0c205c90c19456f6937", "size": 3204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rprop.cpp", "max_stars_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_stars_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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": "rprop.cpp", "max_issues_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_issues_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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": "rprop.cpp", "max_forks_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_forks_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "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.6709677419, "max_line_length": 82, "alphanum_fraction": 0.5820848939, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6623316215811501}}
{"text": "#include <iostream>\n#include <cmath>\n#include <random>\n#include <Eigen/Dense>\n#include <boost/range/irange.hpp>\n#include <unsupported/Eigen/FFT>\n#include \"utils.h\"\n\n// Define aliases with using declarations\nusing Matrix = utils::Matrix;\nusing Vector = utils::Vector;\nusing VectorXcd = utils::VectorXcd;\n\n// Construct Toeplitz matrix from column (symmetric)\nMatrix utils::buildToep(const Vector & col, const Vector & row)\n{\n  auto n = static_cast<int>(col.rows());\n  Matrix toep(n,n);\n  for (auto i : boost::irange(0,n))\n    {\n      toep.diagonal(i) = Eigen::VectorXd::Ones(n-i)*row[i];\n      toep.diagonal(-i) = Eigen::VectorXd::Ones(n-i)*col[i];\n    }\n  return toep;\n};\n\n// Construct Toeplitz matrix from column (symmetric)\nMatrix utils::buildToep(const Vector & col) { return buildToep(col, col); };\n\n// Embed Toeplitz matrix into column of circulant matrix (general)  \nvoid utils::embedToep(Vector & toepCol, Vector & toepRow, VectorXcd & eigVals)\n{\n  // Specify first column of circulant matrix embedding\n  auto n = static_cast<int>(toepCol.rows());\n  Vector embedCol(2*n);\n  embedCol.head(n) = toepCol;\n  embedCol.tail(n-1) = toepRow.tail(n-1).reverse();\n\n  // Compute eigenvalues of cirulant matrix\n  Eigen::FFT<double> fft;\n  fft.fwd(eigVals, embedCol);\n};\n\n\n// Embed Toeplitz matrix into column of circulant matrix (symmetric)\nvoid utils::embedToep(Vector & toepCol, VectorXcd & eigVals) { embedToep(toepCol, toepCol, eigVals); };\n\n\n// Define matvec product for circular matrix using FFT (non-symmetric / complex eigVals)\nvoid utils::circMatVec(const VectorXcd & eigVals, Vector & x, Vector & result)\n{\n  VectorXcd freqvec;\n  Eigen::FFT<double> fft;\n  fft.fwd(freqvec,x);\n  freqvec = eigVals.cwiseProduct(freqvec);\n  fft.inv(result,freqvec);\n};\n\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nVector utils::toepMatVec(Vector & col, Vector & row, Vector & x, bool sym)\n{\n  auto n = static_cast<int>(col.rows());\n  Vector xembed = Eigen::VectorXd::Zero(2*n);\n  xembed.head(n) = x;\n  VectorXcd eigVals(2*n);\n  Vector result(2*n);\n  embedToep(col, row, eigVals);\n\n  // Note: Should be possible to optimize this better using\n  // the fact that eigVals is real in the symmetric case\n  if (sym)\n      circMatVec(eigVals.real(), xembed, result);\n  else\n      circMatVec(eigVals, xembed, result);\n\n  return result.head(n);\n\n};\n\n// Define matvec product for Toeplitz matrix using FFT (symmetric)\nVector utils::toepMatVec(Vector & col, Vector & x) { return toepMatVec(col, col, x, true); };\n\n\n\n// NOTE: the \"fast\" version avoids extra function calls and\n// is marginally faster than the more pedagogical \"toepMatVec\"\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nVector utils::fastToepMatVec(Vector & toepCol, Vector & toepRow, Vector & x)\n{\n  auto n = static_cast<int>(toepCol.rows());\n  Vector result(2*n);\n\n  // Embed RHS into 2n-vector with trailing zeros\n  Vector xembed = Eigen::VectorXd::Zero(2*n);\n  xembed.head(n) = x;\n\n  // Specify first column of circulant matrix embedding\n  Vector embedCol(2*n);\n  embedCol.head(n) = toepCol;\n  embedCol.tail(n-1) = toepRow.tail(n-1).reverse();\n\n  // Compute eigenvalues of cirulant matrix\n  Eigen::FFT<double> fft;\n  VectorXcd eigVals(2*n), freqvec(2*n);\n  fft.fwd(eigVals, embedCol);\n\n  // Apply component-wise multiplication in frequency space\n  fft.fwd(freqvec, xembed);\n  freqvec = eigVals.cwiseProduct(freqvec);\n  fft.inv(result,freqvec);\n\n  // Return first n values corresponding to the original system\n  return result.head(n);\n\n};\n\n// Define matvec product for Toeplitz matrix using FFT (symmetric)\nVector utils::fastToepMatVec(Vector & col, Vector & x) { return fastToepMatVec(col, col, x); };\n\n\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nMatrix utils::fastToepMatMat(Vector & toepCol, Vector & toepRow, Matrix & X)\n{\n  auto n = static_cast<int>(toepCol.rows());\n  auto m = static_cast<int>(X.cols());\n  Matrix result(n,m);\n  for (auto i : boost::irange(0,m))\n    {\n      Vector X_i = X.col(i);\n      result.col(i) = fastToepMatVec(toepCol, toepRow, X_i);\n    }\n  return result;\n}\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nMatrix utils::fastToepMatMat(Vector & toepCol, Matrix & X) { return fastToepMatMat(toepCol, toepCol, X); };\n\n\n\n// Compute Lanczos vectors for matrix-vector pair (A,v)\nvoid utils::Lanczos(Matrix & A, Vector & v, Matrix & Q, Matrix & T, int N)\n{\n  // Use full decomposition if step count N is not specified\n  auto n = static_cast<int>(A.rows());\n  if (N == 0)\n    N = n;\n\n  // Initialize the algorithm's vectors and parameters\n  Vector q = v/v.norm();\n  auto alpha = static_cast<double>( (A*q).dot(q) );\n  Vector r = A*q - alpha*q;\n  Q.col(0) = q;\n  T(0,0) = alpha;\n  Vector u;\n\n  // Define orthogonality and vector norm tolerances\n  //double epsilon = 1.0e-15;\n  //double eta = std::pow(epsilon, 0.75);\n  double tolerance = 0.00001;\n\n  for (auto j : boost::irange(1,N))\n    {\n      auto beta = static_cast<double>(r.norm());    \n      if (beta < tolerance)\n        {\n          std::cout << \"\\nStopped Early\\n\";\n          Q.resize(n,j);\n          break;\n        }\n\n      // Basic implementation\n      //v_k = vt_k/beta;\n      //alpha = v_k.transpose().dot(A*v_k);\n      //vt_k = A*v_k - alpha*v_k - beta*Q.col(k-1);\n\n      // Improved stability implementation \n      q = r/beta;\n      u = A*q - beta*Q.col(j-1);\n      alpha = q.transpose().dot(u);\n      r = u - alpha*q;\n\n      // Complete re-orthogonalization [ roughly ~ O(n^3) for combined iterations ]\n      r = r - Q*(Q.transpose()*r);\n\n      /*\n      // Check if additional re-orthogonalization is necessary\n      for (auto k : boost::irange(0,j))\n        {\n          if ( std::abs((r/r.norm()).dot(Q.col(k))) > eta )\n            {\n              //std::cout << \"Reorthogonalizing...\" << std::endl;\n              r = r/r.norm();\n              r = r - Q*(Q.transpose()*r);\n              break;\n            }\n        }\n      */\n\n      // Assign Lanczos vector and tridiagonal entries\n      Q.col(j) = q;\n      T(j,j) = alpha;\n      T(j,j-1) = T(j-1,j) = beta;\n\n    }\n\n};\n", "meta": {"hexsha": "d2cc252a3f55a51d63eac1ac3672b8e5c35c8f82", "size": 6107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/utils.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/utils.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/utils.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 29.080952381, "max_line_length": 107, "alphanum_fraction": 0.6500736859, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6623002150265664}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <libv/lma/time/tictoc.hpp>\ntemplate<class T> using AlignedVector = std::vector<T,Eigen::aligned_allocator<T>>;\n\n/*\n  dense\n  crs\n  bcrs\n  sbcrs\n*/\n\nEigen::SparseMatrix<double> dense_to_sparse(const Eigen::MatrixXd& m)\n{\n  typedef Eigen::Triplet<double> Triplet;\n\n  std::vector<Triplet> tripletList;\n\n  for(int i = 0 ; i < m.rows() ; ++i)\n    for(int j = 0 ; j < m.cols() ; ++j)\n      if (m(i,j)!=0)\n        tripletList.emplace_back(i,j,m(i,j));\n\n  Eigen::SparseMatrix<double> s(m.rows(),m.cols());\n  s.setFromTriplets(tripletList.begin(), tripletList.end());\n  return s;\n}\n\nstruct Dense\n{\n  Eigen::MatrixXd m;\n  Eigen::VectorXd r,v;\n\n  Dense(int rows, int cols, int block_size):m(rows,cols),r(rows),v(rows)\n  {\n    for(int i = 0 ; i < rows/block_size ; ++i)\n      m.block(i*block_size,i*block_size,block_size,block_size) = Eigen::MatrixXd::Random(block_size,block_size);\n    v = v.Random(rows);\n  }\n};\n\nstruct Sparse\n{\n  Eigen::SparseMatrix<double> m;\n  Eigen::SparseVector<double> r,v;\n\n  Sparse(const Dense& dense)\n  {\n     m = dense_to_sparse(dense.m);\n     v = dense_to_sparse(dense.v);\n  }\n};\n\ntemplate<class Storage> void compute(Storage& st)\n{\n  st.r = st.m * st.v;\n}\n\ntemplate<int BlockSize> struct Blocks\n{\n  AlignedVector<Eigen::Matrix<double,BlockSize,BlockSize>> m;\n  AlignedVector<Eigen::Matrix<double,BlockSize,1>> r,v;\n\n  Blocks(const Dense& dense)\n  {\n    for(int i = 0 ; i < dense.m.rows()/BlockSize ; ++i)\n    {\n      m.push_back(dense.m.block<BlockSize,BlockSize>(i,i));\n      v.push_back(dense.v.block<BlockSize,1>(i,0));\n    }\n    r.resize(v.size());\n  }\n\n  void eval(int i)\n  {\n    r[i] = m[i] * v[i];\n  }\n};\n\ntemplate<int BlockSize> void compute(Blocks<BlockSize>& blocks)\n{\n  for(size_t i = 0 ; i < blocks.r.size(); ++i)\n  {\n    blocks.eval(i);\n  }\n}\n\nint main()\n{\n  size_t nb_block = 1000;\n  static const size_t BlockSize = 6;\n  size_t rows = nb_block*BlockSize, cols = nb_block*BlockSize;\n\n  Dense dense(rows,cols,BlockSize);\n  Sparse sparse(dense);\n  Blocks<BlockSize> blocks(dense);\n\n  utils::Tic<true> ticd(\"dense\");\n  compute(dense);\n  ticd.disp();\n\n  utils::Tic<true> tics(\"sparse\");\n  compute(sparse);\n  tics.disp();\n\n\n  utils::Tic<true> ticb(\"blocks\");\n  compute(blocks);\n  ticb.disp();\n  \n\n  // std::cout << m << std::endl;\n  // std::cout << std::endl;\n  // std::cout << v.transpose() << std::endl;\n\n  //r = s * v;\n\n  return 0;\n}\n", "meta": {"hexsha": "bb7488fc5aea54b4dc7230b73fc8c3f8e0307797", "size": 2439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/compression_storage.cpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "tests/compression_storage.cpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "tests/compression_storage.cpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 20.1570247934, "max_line_length": 112, "alphanum_fraction": 0.6305863059, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7401743505760727, "lm_q1q2_score": 0.6623002098981057}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <map>\n#include <regex>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\nint fuel(int mass) {\n    return int(floor(mass / 3.0)) - 2;\n}\n\nint improved_fuel(int mass) {\n    int f = fuel(mass);\n    if (f > 0) {\n        // Calculate the additional fuel required for this additional fuel\n        return f + improved_fuel(f);\n    }\n    return 0;\n}\n\nint main() {\n    ifstream file (\"2019/1.txt\");\n    if (!file.is_open()) {\n        cout << \"Failed to open file: \" << strerror(errno) << endl;\n        return -1;\n    }\n\n    int answer1 = 0;\n    int answer2 = 0;\n\n    string line; \n    while (getline(file, line, '\\n')) {\n        boost::trim(line);\n\n        if (line == \"\") {\n            continue;\n        }\n\n        int mass = stoi(line);\n        answer1 += fuel(mass);\n        answer2 += improved_fuel(mass);\n    }\n\n    /*\n    cout << improved_fuel(12) << endl;\n    cout << improved_fuel(14) << endl;\n    cout << improved_fuel(1969) << endl;\n    cout << improved_fuel(100756) << endl;\n    */\n\n    cout << \"Answer 1.1: \" << answer1 << endl;\n    cout << \"Answer 1.2: \" << answer2 << endl;\n\n    file.close();\n}", "meta": {"hexsha": "a14fde4b25382db8f1c261ba5e3119fe3187b40f", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/1.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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": "2019/1.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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": "2019/1.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "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.5862068966, "max_line_length": 74, "alphanum_fraction": 0.5469011725, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6622227946973569}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/determinant.hpp>\n#include <fcppt/math/matrix/identity.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_determinant\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t3,\n\t\t3\n\t>\n\tlarge_matrix_type;\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tint,\n\t\t2,\n\t\t2\n\t>\n\tsmall_matrix_type;\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::determinant(\n\t\t\tlarge_matrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t1,2,3\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t4,5,6\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t7,8,9\n\t\t\t\t)\n\t\t\t)\n\t\t),\n\t\t0\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::determinant(\n\t\t\tsmall_matrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t-3,-5\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t-1,-2\n\t\t\t\t)\n\t\t\t)\n\t\t),\n\t\t1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::matrix::determinant(\n\t\t\tfcppt::math::matrix::identity<\n\t\t\t\tlarge_matrix_type\n\t\t\t>()\n\t\t),\n\t\t1\n\t);\n}\n", "meta": {"hexsha": "c807349e8722a7e1ff96a6641cefe14f4228f5b6", "size": 1516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/determinant.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/determinant.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/determinant.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0476190476, "max_line_length": 61, "alphanum_fraction": 0.6754617414, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6622203877114664}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/gamma.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdGammaQ, Fvar) {\n  using boost::math::gamma_q;\n  using stan::math::fvar;\n  using stan::math::gamma_q;\n\n  fvar<double> x(0.5);\n  x.d_ = 1.0;\n  fvar<double> y(1.0);\n  y.d_ = 1.0;\n\n  fvar<double> a = gamma_q(x, y);\n  EXPECT_FLOAT_EQ(gamma_q(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(0.18228334, a.d_);\n\n  double z = 1.0;\n  double w = 0.5;\n\n  a = gamma_q(x, z);\n  EXPECT_FLOAT_EQ(gamma_q(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(0.38983709, a.d_);\n\n  a = gamma_q(w, y);\n  EXPECT_FLOAT_EQ(gamma_q(0.5, 1.0), a.val_);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5, 1.0), a.d_);\n\n  EXPECT_THROW(gamma_q(-x, y), std::domain_error);\n  EXPECT_THROW(gamma_q(x, -y), std::domain_error);\n}\n\nTEST(AgradFwdGammaQ, FvarFvarDouble) {\n  using boost::math::gamma_q;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = gamma_q(x, y);\n\n  EXPECT_FLOAT_EQ(gamma_q(0.5, 1.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(0.38983709, a.val_.d_);\n  EXPECT_FLOAT_EQ(-boost::math::gamma_p_derivative(0.5, 1.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(-0.40753385, a.d_.d_);\n}\n\nstruct gamma_q_fun {\n  template <typename T0, typename T1>\n  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(\n      const T0 arg1, const T1 arg2) const {\n    return gamma_q(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdGammaQ, nan_0) {\n  gamma_q_fun gamma_q_;\n  test_nan_fwd(gamma_q_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "2f3b04d485c9a65b9de20a534fdbc0071f73c7ef", "size": 1644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/gamma_q_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5373134328, "max_line_length": 76, "alphanum_fraction": 0.6630170316, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6622203808178642}}
{"text": "#include <gtest/gtest.h>\n\n#include \"../IntegralImage/integralimage.hh\"\n#include <Eigen/Core>\n\nusing namespace bold;\nusing namespace std;\nusing namespace Eigen;\n\nTEST (IntegralImageTests, create)\n{\n  int rows = 10;\n  int cols = 12;\n  cv::Mat image(cv::Size(cols, rows), CV_8UC1);\n\n  image = cv::Scalar(1);\n\n  for (int x = 0; x < cols; x++)\n  {\n    for (int y = 0; y < rows; y++)\n      ASSERT_EQ(1, image.at<uchar>(y, x));\n  }\n\n  IntegralImage integral = IntegralImage::create(image);\n\n  // 1 1 1 1\n  // 1 1 1 1\n  // 1 1 1 1\n\n  // 1 2 3 4\n  // 2 4 6 8\n  // 3 6 9 12\n\n  for (int y = 0; y < rows; y++)\n  {\n    for (int x = 0; x < cols; x++)\n      ASSERT_EQ((x+1) * (y+1), integral.at(x, y)) << \"Failed when x=\" << x << \", y=\" << y;\n  }\n\n  EXPECT_EQ ( 5*3, integral.getSummedArea(Vector2i(2, 3), Vector2i(6, 5)) );\n  EXPECT_EQ ( 1, integral.getSummedArea(Vector2i(2, 3), Vector2i(2, 3)) );\n  EXPECT_EQ ( rows*cols, integral.getSummedArea(Vector2i(0, 0), Vector2i(cols-1, rows-1)) );\n  EXPECT_EQ ( 2*2, integral.getSummedArea(Vector2i(0, 2), Vector2i(1, 3)) );\n  EXPECT_EQ ( 2*2, integral.getSummedArea(Vector2i(2, 0), Vector2i(3, 1)) );\n  EXPECT_EQ ( 4*2, integral.getSummedArea(Vector2i(0, 0), Vector2i(3, 1)) );\n  EXPECT_EQ ( 2*4, integral.getSummedArea(Vector2i(0, 0), Vector2i(1, 3)) );\n}\n", "meta": {"hexsha": "b0cccc8a62dcf76ec6aebfd8e59261bc2eb958ae", "size": 1288, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/IntegralImageTests.cc", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/IntegralImageTests.cc", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/IntegralImageTests.cc", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8333333333, "max_line_length": 92, "alphanum_fraction": 0.6055900621, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6622203804338842}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  typedef Matrix<double, 5, 3> Matrix5x3;\ntypedef Matrix<double, 5, 5> Matrix5x5;\nMatrix5x3 m = Matrix5x3::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\nEigen::FullPivLU<Matrix5x3> lu(m);\ncout << \"Here is, up to permutations, its LU decomposition matrix:\"\n     << endl << lu.matrixLU() << endl;\ncout << \"Here is the L part:\" << endl;\nMatrix5x5 l = Matrix5x5::Identity();\nl.block<5,3>(0,0).triangularView<StrictlyLower>() = lu.matrixLU();\ncout << l << endl;\ncout << \"Here is the U part:\" << endl;\nMatrix5x3 u = lu.matrixLU().triangularView<Upper>();\ncout << u << endl;\ncout << \"Let us now reconstruct the original matrix m:\" << endl;\ncout << lu.permutationP().inverse() * l * u * lu.permutationQ().inverse() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b49702a6e994fae91b598c3115ff074c121a3e0c", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_class_FullPivLU.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_class_FullPivLU.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_class_FullPivLU.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": 30.4482758621, "max_line_length": 82, "alphanum_fraction": 0.6602491506, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6622203760941356}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_layer.h\"\n\nusing namespace Eigen;\nusing namespace MyDL;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n\n    MatrixXd x = MatrixXd::Zero(2, 2);\n    MatrixXd y, dx;\n    MatrixXd dout = MatrixXd::Ones(2, 2);\n    x <<    1, -0.5,\n         -2.0,  3.0;\n\n    ReLU relu;\n    y = relu.forward(x);\n    cout << \"forward: \" << y << endl;\n    dx = relu.backward(dout);\n    cout << \"backward: \" << dx << endl;\n\n    return 0;\n}", "meta": {"hexsha": "7875e91e75ec1994b8905f0ca5303a4cf084bccd", "size": 502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/relu.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch5/relu.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch5/relu.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.3076923077, "max_line_length": 47, "alphanum_fraction": 0.5677290837, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.662220370218467}}
{"text": "#ifndef helpers_hpp\n#define helpers_hpp\n\n#include <vector>\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <fstream>\n#include <sys/stat.h>\n\nconst double PI = 3.14159265358979;\n\nusing namespace std;\nusing namespace boost::math;\nusing namespace boost::random;\nusing namespace boost::math::tools;\n\ntypedef vector<vector<double> > Table;\ntypedef vector<vector<vector<double> > > Table3D;\n\ntypedef boost::variate_generator<boost::mt19937&, boost::uniform_real<> > RandUnif;\ntypedef boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > RandNorm;\ntypedef boost::variate_generator<boost::mt19937&, boost::uniform_int<> > RandIntUnif;\n\nclass RandomSampleHelper\n{\npublic:\n  RandomSampleHelper(long seedval) : rng(seedval) {}\n  double sampleBeta(double alpha, double beta) \n  {\n    boost::gamma_distribution<> xgamma(alpha);\n    boost::gamma_distribution<> ygamma(beta);\n    boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> > xgen(rng, xgamma);\n    boost::variate_generator<boost::mt19937&, boost::gamma_distribution<> > ygen(rng, ygamma);\n    double xsample = xgen();\n    double ysample = ygen();\n    return xsample/(xsample+ysample);\n  } \n\n  double sampleGaussian(double mu, double sigma)\n  {\n    boost::normal_distribution<> normdist(mu, sigma);\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > sgen(rng, normdist);\n    return sgen();\n  }\nprivate:\n  boost::mt19937 rng;\n};\n\n/* courtesy of http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c */\ninline bool exists_file(const std::string& name) {\n  struct stat buffer;   \n  return (stat (name.c_str(), &buffer) == 0); \n}\n\nvoid loadFromCSV( const std::string& filename, std::vector< std::vector<double> >& matrix, const int maxrows, const int maxcols)\n{\n  if( !exists_file(filename) )\n  {\n    cerr << \"cannot find required file \" << filename << \" to load.\" << endl;\n    exit(1);\n  }\n  std::ifstream  file( filename.c_str() );\n  std::vector<double> row;\n  std::string line;\n  std::string  cell;\n  int rows = 0;\n  while( file && rows < maxrows )\n  {\n    std::getline(file,line);\n    std::stringstream lineStream(line);\n    row.clear();\n    int cols = 0;\n    while( std::getline( lineStream, cell, ',' ) && cols < maxcols)\n    {\n      double number = strtod(cell.c_str(), NULL);\n      row.push_back(number);\n      ++cols;\n    }\n\n    if( !row.empty() )\n    {\n      matrix.push_back(row);\n    }\n    ++rows;\n  }\n}\n\nvoid loadLineFromCSV( const std::string& filename, std::vector<double>& arrs, const int maxentries)\n{\n  std::ifstream       file( filename.c_str() );\n  std::string line;\n  std::string  cell;\n  std::getline(file,line);\n  std::stringstream lineStream(line);\n  int idx = 0;\n  while( std::getline( lineStream, cell, ',' ) && idx < maxentries)\n  {\n    double number = strtod(cell.c_str(), NULL);\n    arrs[idx] = number;\n    ++idx;\n  }\n}\n\ndouble kl(double p1, double p2)\n{\n  return p1*log(p1/p2)+(1-p1)*log((1-p1)/(1-p2));\n}\n\ndouble maxkl(double n, double muh, double delta)\n{\n  double begin = muh + 1e-10;\n  double end = 1.0-1e-10;\n  double mid = (begin+end)/2.0;\n  while (begin < end - 1e-10)\n  {\n    if (n*kl(muh, mid) > delta)\n    {\n      end = mid;\n    }\n    else\n    {\n      begin = mid;\n    }\n    mid = (begin + end)/2.0;\n  }\n  return mid;\n} \n\nconst int NUM_AGI_ITERS = 9;\n\ndouble computeAGI(const double gamma, const double a, const double nn)\n{\n  double p = double(a)/double(nn);\n  const double b = nn - a;\n  const double r = ((double)a/(double)nn);\n  \n  for(int k = 0; k < NUM_AGI_ITERS; ++k)\n  {\n    if((p > 1 || p < r || p != p))\n    {\n      cerr << \"Found that p = \" << p << \". invalid value\" << endl;\n      cerr << \"a = \" << a << endl;\n      cerr << \"b = \" << b << endl;\n      cerr << \"gamma = \" << gamma << endl;\n      exit(1);\n    }\n    const double safe = p/(1-gamma);\n\n    const double lhs = r*(1-ibeta(a+1,b,p));\n    const double expmax = lhs + p*ibeta((double)a,b,p);  \n    const double risky = r+ gamma/(1-gamma)*expmax;\n\n    const double orig = risky - safe;\n    const double deriv = gamma/(1-gamma)*ibeta(a,b,p) - 1/(1-gamma);\n    p -= orig/deriv;\n  }\n  return p;\n}\n\ndouble computeAGIGaussian(const double gamma, const double mu, const double sigma)\n{\n  double lam = mu;\n  boost::math::normal_distribution<> normdist(mu,sigma);\n  for(int k = 0; k < NUM_AGI_ITERS; ++k)\n  {\n    double plam = cdf(normdist, lam);\n    double flam =  pdf(normdist, lam);\n    double f = mu + gamma*sigma/(sqrt(2*PI))*exp(-pow(lam-mu,2)/(2*sigma*sigma)) + gamma*(lam-mu)*plam - lam; \n    double fp = -gamma*(lam - mu)/(sqrt(2*PI)*sigma)*exp(-pow((lam-mu),2)/(2*sigma*sigma)) + gamma*plam + gamma*(lam-mu)*flam - 1;\n    lam -= f/fp;\n  }\n  return lam;\n}\n\ndouble computeDummyProblemVal(double lambda, double gamma, double a, double b, int k, bool take_max = false)\n{\n  double xbar = a/(a+b);\n  double result = 0.0;\n  if (k == 1)\n  {\n    result += xbar;\n    result += gamma/(1.0-gamma) * (xbar * (1.0 - ibeta(a+1, b, lambda)) + lambda*ibeta(a,b,lambda));\n    return take_max ? max(result,lambda/(1.0 - gamma)) : result;\n  }\n  result += xbar * computeDummyProblemVal(lambda, gamma, a+1, b, k-1, true);\n  result += (1.0 - xbar) * computeDummyProblemVal(lambda, gamma, a, b+1, k-1, true);\n  result = xbar + gamma * result;\n  return take_max ? max(result,lambda/(1.0 - gamma)) : result;\n}\n\ndouble computeApproxGI(double gamma, double a, double b, int k, double prec = 0.0001)\n{\n  if (k == 1)\n  {\n    return computeAGI(gamma, a, a + b);\n  }\n  double start = a/(a+b);\n  for (double lambda = start; lambda < 1.0; lambda += prec) \n  {\n    double rightVal = computeDummyProblemVal(lambda, gamma, a, b, k, false);\n    double leftVal = lambda / (1.0 - gamma);\n    if (leftVal > rightVal)\n    {\n      return lambda - prec/2.0;\n    }\n  }\n  return 1.0;\n}\n\nvoid computeIndices(const int a0, const int b0, const int n, const double step, const double beta, vector<vector<double> >& indices)\n{\n  vector<vector<double> > tmpindices(n-1, vector<double>(n-1, 0));\n  for(int a = 1; a < n; ++a)\n  {\n    tmpindices[a-1][n-a-1] = computeAGI(beta, a0 + a - 1, n + a0 + b0 - 2);\n  }\n  for(double p=(step/2.0); p <= 1.0; p+=step)\n  {\n    const double safe = p/(1-beta);\n    for(int nn = n-1; nn >= 2; --nn)\n    {\n      for(int a = 1; a <= nn-1; ++a)\n      {\n        const double r = (double(a - 1 + a0)/double(nn + a0 + b0 - 2));\n        const double risky =  r*(1 + beta*tmpindices[a][nn-a-1]) + (1-r)*beta*tmpindices[a-1][nn-a];\n        if(indices[a-1][nn-a-1] == 0 && safe > risky)\n        {\n          indices[a-1][nn-a-1] = p - step/2.0;\n        }\n        tmpindices[a-1][nn-a-1] = max(safe,risky);\n      }\n    }\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "adb1f00b310afbe3d420b46a564f4307ade675d3", "size": 6732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/helpers.hpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/helpers.hpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "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/helpers.hpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 28.1673640167, "max_line_length": 132, "alphanum_fraction": 0.6140819964, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6621639788130895}}
{"text": "#include <cmath>\n#include <jni.h>\n#include <boost/math/special_functions/erf.hpp>\n\n#ifndef _Included_simianquant_strata_jnibridge_AtomicFunction\n#define _Included_simianquant_strata_jnibridge_AtomicFunction\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJNIEXPORT jdouble JNICALL Java_simianquant_strata_jnibridge_AtomicFunction_normalCdf\n  (JNIEnv * env, jobject obj, jdouble arg){\n  \treturn (0.5 * erfc(-arg * M_SQRT1_2));\n  }\n\nJNIEXPORT jdouble JNICALL Java_simianquant_strata_jnibridge_AtomicFunction_normalQuantile\n  (JNIEnv * env, jobject obj, jdouble arg){\n  \treturn -M_SQRT2 * boost::math::erfc_inv(2 * arg);\n  }\n\n#ifdef __cplusplus\n}\n#endif\n#endif", "meta": {"hexsha": "eebc6843841b17bef73b10314f49ba45fef88bdb", "size": 649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jnibridgeimpl/src/native/library.cpp", "max_stars_repo_name": "SimianQuant/stratabench", "max_stars_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "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": "jnibridgeimpl/src/native/library.cpp", "max_issues_repo_name": "SimianQuant/stratabench", "max_issues_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "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": "jnibridgeimpl/src/native/library.cpp", "max_forks_repo_name": "SimianQuant/stratabench", "max_forks_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "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": 27.0416666667, "max_line_length": 89, "alphanum_fraction": 0.7966101695, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6621138917781533}}
{"text": "/**\n * @date Fri Feb 10 20:02:07 2012 +0200\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <boost/format.hpp>\n\n#include <bob.math/log.h>\n\n/**\n * Computes log(a+b)=log(exp(log(a))+exp(log(b))) from log(a) and log(b),\n * while dealing with numerical issues\n */\ndouble bob::math::Log::logAdd(double log_a, double log_b)\n{\n  if(log_a < log_b)\n  {\n    double tmp = log_a;\n    log_a = log_b;\n    log_b = tmp;\n  }\n\n  double minusdif = log_b - log_a;\n  //#ifdef DEBUG\n  if(std::isnan(minusdif))\n  {\n    boost::format m(\"logadd: minusdif (%f) log_b (%f) or log_a (%f) is nan\");\n    m % minusdif % log_b % log_a;\n    throw std::runtime_error(m.str());\n  }\n  //#endif\n  if(minusdif < MINUS_LOG_THRESHOLD) return log_a;\n  else return log_a + log1p(exp(minusdif));\n}\n\n/**\n * Computes log(a-b)=log(exp(log(a))-exp(log(b))) from log(a) and log(b),\n * while dealing with numerical issues\n */\ndouble bob::math::Log::logSub(double log_a, double log_b)\n{\n  double minusdif;\n\n  if(log_a < log_b)\n  {\n    boost::format m(\"logsub: log_a (%f) should be greater than log_b(%f)\");\n    m % log_a % log_b;\n    throw std::runtime_error(m.str());\n  }\n\n  minusdif = log_b - log_a;\n  //#ifdef DEBUG\n  if(std::isnan(minusdif))\n  {\n    boost::format m(\"logsub: minusdif (%f) log_b (%f) or log_a (%f) is nan\");\n    m % minusdif % log_b % log_a;\n    throw std::runtime_error(m.str());\n  }\n  //#endif\n  if(log_a == log_b) return bob::math::Log::LogZero;\n  else if(minusdif < MINUS_LOG_THRESHOLD) return log_a;\n  else return log_a + log1p(-exp(minusdif));\n}\n", "meta": {"hexsha": "dd27f8c3f59003ef6bcf5221a51c4066ab8bea4e", "size": 1635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/log.cpp", "max_stars_repo_name": "bioidiap/bob.math", "max_stars_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "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": "bob/math/cpp/log.cpp", "max_issues_repo_name": "bioidiap/bob.math", "max_issues_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-12-02T01:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-26T16:37:07.000Z", "max_forks_repo_path": "bob/math/cpp/log.cpp", "max_forks_repo_name": "bioidiap/bob.math", "max_forks_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "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.4029850746, "max_line_length": 77, "alphanum_fraction": 0.6354740061, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6620874141548441}}
{"text": "#include <fstream>\n#include <iostream>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Octree.h>\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n// Type Declarations\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef Kernel::Point_3 Point;\ntypedef CGAL::Point_set_3<Point> Point_set;\ntypedef Point_set::Point_map Point_map;\n\ntypedef CGAL::Octree<Kernel, Point_set, Point_map> Octree;\n\nint main(int argc, char **argv) {\n\n  // Point set will be used to hold our points\n  Point_set points;\n\n  // Load points from a file.\n  std::ifstream stream((argc > 1) ? argv[1] : CGAL::data_file_path(\"points_3/cube.pwn\"));\n  stream >> points;\n  if (0 == points.number_of_points()) {\n\n    std::cerr << \"Error: cannot read file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << \"loaded \" << points.number_of_points() << \" points\" << std::endl;\n\n  // Create an octree from the points\n  Octree octree(points, points.point_map());\n\n  // Build the octree\n  octree.refine(10, 20);\n\n  // Find the nearest points to a few locations\n  std::vector<Point> points_to_find = {\n          {0, 0, 0},\n          {1, 1, 1},\n          {-1, -1, -1},\n          {-0.46026, -0.25353, 0.32051},\n          {-0.460261, -0.253533, 0.320513}\n  };\n  for (const Point& p : points_to_find)\n    octree.nearest_neighbors\n      (p, 1, // k=1 to find the single closest point\n       boost::make_function_output_iterator\n       ([&](const Point& nearest)\n        {\n          std::cout << \"the nearest point to (\" << p <<\n            \") is (\" << nearest << \")\" << std::endl;\n        }));\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e94fca1ee2062d2e361292131e5b7b16e38df663", "size": 1649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Orthtree/examples/Orthtree/octree_find_nearest_neighbor.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": "Orthtree/examples/Orthtree/octree_find_nearest_neighbor.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": "Orthtree/examples/Orthtree/octree_find_nearest_neighbor.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": 27.4833333333, "max_line_length": 89, "alphanum_fraction": 0.6337174045, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6620627457158698}}
{"text": "/*\n * File: dht.hpp\n * Created Date: 2019-12-29\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Sunday December 29th 2019 12:00:12 pm\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\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 * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#ifndef DHT_DHT_H_\n#define DHT_DHT_H_\n\n#include <Eigen/Dense>\n\nclass DiscreteHankelTransform {\n\npublic:\n  DiscreteHankelTransform(int order, int nr);\n  ~DiscreteHankelTransform();\n\n  Eigen::VectorXd r_sampling(double rmax);\n  Eigen::VectorXd k_sampling(double rmax); // k is rho in the paper\n\n  Eigen::VectorXd forward(const Eigen::Ref<const Eigen::VectorXd> &fr);\n  Eigen::VectorXd backward(const Eigen::Ref<const Eigen::VectorXd> &fk);\n\n  Eigen::VectorXd shift(const Eigen::Ref<const Eigen::VectorXd> &raw, int m);\n\n  Eigen::MatrixXd tmatrix() const;\n\nprotected:\n  int order_;\n  double rmax_;\n  int nr_;\n\n  Eigen::VectorXd roots_;\n  Eigen::MatrixXd tmatrix_;\n};\n\n#endif", "meta": {"hexsha": "ff6897df4b0433aaf8bab1ab8fca503c4ce4cd37", "size": 2088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dht.hpp", "max_stars_repo_name": "pan3rock/discrete-hankel-transform", "max_stars_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_stars_repo_licenses": ["MIT"], "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/dht.hpp", "max_issues_repo_name": "pan3rock/discrete-hankel-transform", "max_issues_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_issues_repo_licenses": ["MIT"], "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/dht.hpp", "max_forks_repo_name": "pan3rock/discrete-hankel-transform", "max_forks_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T09:56:44.000Z", "avg_line_length": 31.1641791045, "max_line_length": 80, "alphanum_fraction": 0.7059386973, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6620627243758415}}
{"text": "#include \"RayTracer/Transform.h\"\n\n#include <Eigen/Geometry>\n\nnamespace {\nusing RayTracer::Axes;\n\nEigen::Vector3f getAxisVector(Axes axis)\n{\n    switch (axis)\n    {\n    case Axes::X:\n        return Eigen::Vector3f::UnitX();\n    case Axes::Y:\n        return Eigen::Vector3f::UnitY();\n    case Axes::Z:\n        return Eigen::Vector3f::UnitZ();\n    }\n\n    return Eigen::Vector3f::Zero();\n}\n}\n\nnamespace RayTracer {\n\nTransformation Transformation::IdentityTransformation()\n{\n    return Transformation{};\n}\n\nconst Matrix4f& Transformation::matrix() const\n{\n    return matrix_;\n}\n\nTransformation& Transformation::translate(float x, float y, float z)\n{\n    matrix_ = Transform::Translation(x, y, z) * matrix_;\n    return *this;\n}\n\nTransformation& Transformation::translate(const Vector4f& v)\n{\n    matrix_ = Transform::Translation(v) * matrix_;\n    return *this;\n}\n\n\nTransformation& Transformation::scale(float x, float y, float z)\n{\n    matrix_ = Transform::Scaling(x, y, z) * matrix_;\n    return *this;\n}\n\nTransformation& Transformation::rotate(Axes axis, float angle)\n{\n    matrix_ = Transform::Rotation(axis, angle) * matrix_;\n    return *this;\n}\n\nTransformation& Transformation::shear(float xy, float xz, float yx, float yz, float zx, float zy)\n{\n    matrix_ = Transform::Shearing(xy, xz, yx, yz, zx, zy) * matrix_;\n    return *this;\n}\n\nnamespace Transform {\n\nMatrix4f Translation(float x, float y, float z)\n{\n    Eigen::Affine3f transform{ Eigen::Translation3f(x, y, z) };\n    return transform.matrix();\n}\n\nMatrix4f Translation(const Vector4f& v)\n{\n    return Translation(v.x(), v.y(), v.z());\n}\n\nMatrix4f Scaling(float x, float y, float z)\n{\n    Eigen::Affine3f transform{ Eigen::Scaling(x, y, z) };\n    return transform.matrix();\n}\n\nMatrix4f Rotation(Axes axis, float angle)\n{\n    Eigen::Affine3f transform{ Eigen::AngleAxisf(angle, getAxisVector(axis)) };\n    return transform.matrix();\n}\n\nMatrix4f Shearing(float xy, float xz, float yx, float yz, float zx, float zy)\n{\n    Matrix4f transformationMatrix = Matrix4f::Identity();\n    transformationMatrix(0, 1) = xy;\n    transformationMatrix(0, 2) = xz;\n    transformationMatrix(1, 0) = yx;\n    transformationMatrix(1, 2) = yz;\n    transformationMatrix(2, 0) = zx;\n    transformationMatrix(2, 1) = zy;\n\n    return transformationMatrix;\n}\n\n} // Transform\n\n} // RayTracer\n", "meta": {"hexsha": "0ea8cbc1ba2496c5e3f46647d1e0c9eba9066acb", "size": 2319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RayTracer/RayTracerLib/src/Transform.cpp", "max_stars_repo_name": "vladbologa/raytracer-cpp", "max_stars_repo_head_hexsha": "0d0a7732d5e89917ef57d403d87a065d18eea433", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RayTracer/RayTracerLib/src/Transform.cpp", "max_issues_repo_name": "vladbologa/raytracer-cpp", "max_issues_repo_head_hexsha": "0d0a7732d5e89917ef57d403d87a065d18eea433", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RayTracer/RayTracerLib/src/Transform.cpp", "max_forks_repo_name": "vladbologa/raytracer-cpp", "max_forks_repo_head_hexsha": "0d0a7732d5e89917ef57d403d87a065d18eea433", "max_forks_repo_licenses": ["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.4722222222, "max_line_length": 97, "alphanum_fraction": 0.6770159552, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6619779421683387}}
{"text": "#include \"RBF.h\"\n\n#include <Eigen/Eigen>\n\nnamespace Chaf\n{\n\tRBFInterpolation::RBFInterpolation(const std::vector<glm::f64vec2>& points, double d) :\n\t\tm_d(d)\n\t{\n\t\tEigen::VectorXd y(points.size());\n\t\tEigen::MatrixXd A(points.size(), points.size());\n\t\tm_ps.resize(points.size());\n\t\tm_params.resize(points.size());\n\n\t\tm_constant = 0.f;\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tm_ps[i] = points[i].x;\n\t\t\ty(i) = points[i].y;\n\t\t\tm_constant += points[i].y;\n\t\t}\n\n\t\tm_constant /= static_cast<double>(points.size());\n\t\ty = y.array() - m_constant;\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tfor (uint32_t j = 0; j < points.size(); j++)\n\t\t\t{\n\t\t\t\tA(i, j) = 1.f / ((points[i].x - m_ps[j]) * (points[i].x - m_ps[j]) + m_d);\n\t\t\t}\n\t\t}\n\n\t\tEigen::VectorXd x = A.colPivHouseholderQr().solve(y);\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tm_params[i] = x(i);\n\t\t}\n\t}\n\n\tdouble RBFInterpolation::evaluate(double x)\n\t{\n\t\tdouble result = m_constant;\n\n\t\tfor (uint32_t i = 0; i < m_params.size(); i++)\n\t\t{\n\t\t\tresult += m_params[i] / ((x - m_ps[i]) * (x - m_ps[i]) + m_d);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tstd::vector<double> RBFInterpolation::evaluate(const std::vector<double>& x)\n\t{\n\t\tstd::vector<double> result(x.size());\n\n\t\tfor (uint32_t i = 0; i < result.size(); i++)\n\t\t{\n\t\t\tresult[i] = evaluate(x[i]);\n\t\t}\n\t\treturn result;\n\t}\n}", "meta": {"hexsha": "0a0f78ec1f04396f0a8476bcfad407bc42307a70", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework1/RBF.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/Homework1/RBF.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/Homework1/RBF.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": 20.5538461538, "max_line_length": 88, "alphanum_fraction": 0.5808383234, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6619677355224839}}
{"text": "\n\n\n\n#include \"DenseLattice.h\"\r\n#include \"SparseLattice.h\"\n#include \"MIAConfig.h\"\r\n#include \"LibMIAUtil.h\"\r\n\r\n#include <Eigen/Dense>\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\n\r\ntemplate<typename data_type>\r\nvoid random_matrix(LibMIA::DenseLattice<data_type> & lat,double _prob,bool need_ranked=true, bool LSQR=false)\r\n{\r\n    boost::uniform_real<> uni_dist(0,1);\r\n    boost::variate_generator<boost::random::mt19937&, boost::uniform_real<> > uni(LibMIA::LibMIA_gen(), uni_dist);\r\n    boost::uniform_real<> uni_dist2(-10,10);\r\n    boost::variate_generator<boost::random::mt19937&, boost::uniform_real<> > uni2(LibMIA::LibMIA_gen(), uni_dist2);\r\n    lat.zeros();\r\n    for(size_t k=0;k<(size_t)lat.depth();++k){\r\n        auto _start=lat.data_begin()+k*lat.width()*lat.height();\r\n        auto _end=lat.data_begin()+(k+1)*lat.width()*lat.height();\r\n        bool flag=true;\r\n        while(flag){\r\n            for(auto it=_start;it<_end;++it){\r\n                if(uni()<_prob){\r\n                    *it=uni2();\r\n                }\r\n                else\r\n                    *it=0;\r\n\r\n            }\r\n            if(need_ranked){\r\n                if(LSQR){\r\n                    auto _SVD=lat.tab_matrix(k).jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\r\n                    if(!_SVD.nonzeroSingularValues()!=lat.width())\r\n                        flag=false;\r\n                }\r\n                else{\r\n                    auto _QR=lat.tab_matrix(k).colPivHouseholderQr();\r\n                    if(_QR.rank()==lat.width())\r\n                        flag=false;\r\n                }\r\n            }\r\n            else\r\n                flag=false;\r\n\r\n\r\n\r\n        }\r\n    }\r\n}\r\n\ntemplate<typename data_type>\nvoid solvework(size_t m1, size_t n1, size_t n2, size_t p){\n\r\n    typedef LibMIA::DenseLattice<data_type> denseType;\r\n    typedef LibMIA::SparseLattice<data_type> sparseType;\r\n\r\n\r\n    denseType DenseLat1(m1,n1,p);\n    denseType DenseLat2(m1,n2,p);\r\n\r\n\r\n\n    denseType DenseLat3;\r\n    denseType DenseLat4;\r\n    sparseType SparseLat1(m1,n1,p);\n    sparseType SparseLat2(m1,n2,p);\n    sparseType SparseLat3;\r\n\r\n\r\n\n\n    random_matrix(DenseLat1,0.4);\r\n    random_matrix(DenseLat2,0.4,false);\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1.solve(DenseLat2);\r\n    //SparseLat1.print();\r\n\r\n\r\n    //SparseLat3=SparseLat1.solve(SparseLat2);\r\n\r\n    DenseLat4=SparseLat1.solve(SparseLat2);\r\n\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat4,test_precision<data_type>()),std::string(\"Full Dimension Solve Test for \")+typeid(data_type).name());\r\n\r\n    //do least squares test, comparing against the result with dense computations\r\n    DenseLat1=denseType(m1*2,n1,p);\r\n    DenseLat2=denseType(m1*2,n2,p);\r\n    random_matrix(DenseLat2,0.4);\r\n    random_matrix(DenseLat1,0.4,false,true);\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n    DenseLat3=DenseLat1.solve(DenseLat2);\r\n    DenseLat4=SparseLat1.solve(SparseLat2);\r\n\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(DenseLat4,test_precision<data_type>()),std::string(\"Least-Squares Solve Test for \")+typeid(data_type).name());\r\n\n\n}\n\n\r\n", "meta": {"hexsha": "6efa156ad6a02cef5d0b201c40baa77e277ba9b9", "size": 3216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseLattice/sparse_lattice_solve_test.hpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseLattice/sparse_lattice_solve_test.hpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "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/tests/SparseLattice/sparse_lattice_solve_test.hpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 27.2542372881, "max_line_length": 159, "alphanum_fraction": 0.6125621891, "num_tokens": 837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6619677355224839}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[touches_two_geometries\n//` Checks if two geometries have at least one touching point (tangent - non overlapping)\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Checks if the two geometries touch\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly1;\n    bg::read_wkt(\"POLYGON((0 0,0 4,4 4,4 0,0 0))\", poly1);\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly2;\n    bg::read_wkt(\"POLYGON((0 0,0 -4,-4 -4,-4 0,0 0))\", poly2);\n    bool check_touches = bg::touches(poly1, poly2);\n    if (check_touches) {\n         std::cout << \"Touches: Yes\" << std::endl;\n    } else {\n        std::cout << \"Touches: No\" << std::endl;\n    }\n\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly3;\n    bg::read_wkt(\"POLYGON((1 1,0 -4,-4 -4,-4 0,1 1))\", poly3);\n    check_touches = bg::touches(poly1, poly3);\n    if (check_touches) {\n         std::cout << \"Touches: Yes\" << std::endl;\n    } else {\n        std::cout << \"Touches: No\" << std::endl;\n    }\n\n    return 0;\n}\n\n//]\n\n\n//[touches_two_geometries_output\n/*`\nOutput:\n[pre\nTouches: Yes\n\n[$img/algorithms/touches_two_geometries.png]\n\nTouches: No\n]\n*/\n//]\n", "meta": {"hexsha": "1edba94ccbf345212290ded1fd3cb969b99607be", "size": 1634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/touches_two_geometries.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/touches_two_geometries.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/touches_two_geometries.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 26.3548387097, "max_line_length": 89, "alphanum_fraction": 0.6493268054, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6619415136871306}}
{"text": "#include <iostream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <g2o/core/base_binary_edge.h>\n\n#include <sophus/se3.h>\n#include <sophus/so3.h>\n\n#include <chrono>\n\n/* vertex of lie algebra */\nclass VertexSE3LieAlgebra : public g2o::BaseVertex<6, Sophus::SE3>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    \n    bool read(std::istream& is) {}\n    bool write(std::ostream& os) const {}\n    \n    virtual void setToOriginImpl()\n    {\n        _estimate = Sophus::SE3();\n    }\n    \n    /* update */\n    virtual void oplusImpl(const double* update)\n    {\n        Sophus::SE3 up(\n            Sophus::SO3(update[3], update[4], update[5]),\n            Eigen::Vector3d(update[0], update[1], update[2])\n        );\n        \n        setEstimate(up * _estimate);  // or _estimate = up * _estimate;\n    }\n    \n};\n\nclass VertexPoint3D : public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    \n    virtual bool read(std::istream& is) {}\n    virtual bool write(std::ostream& os) const {}\n    \n    virtual void setToOriginImpl()\n    {\n        _estimate.fill(0);\n    }\n\n    virtual void oplusImpl(const double* update)\n    {\n        Eigen::Map<const Eigen::Vector3d> v(update);\n        _estimate += v;\n    }\n};\n\nclass EdgeProject3D22D : public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexPoint3D, VertexSE3LieAlgebra>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    \n    EdgeProject3D22D()\n    {\n        _cam = nullptr;\n        resizeParameters(1);\n        installParameter(_cam, 0);\n    }\n    \n    virtual bool read(std::istream& is) {}\n    virtual bool write(std::ostream& os) const {}\n    \n    void computeError()\n    {\n        Eigen::Vector3d point3d = static_cast<VertexPoint3D*>(_vertices[0])->estimate();\n        Sophus::SE3 pose = static_cast<VertexSE3LieAlgebra*>(_vertices[1])->estimate();\n        \n        const g2o::CameraParameters * cam = static_cast<const g2o::CameraParameters *>(parameter(0));\n        \n        _error = _measurement - cam->cam_map(pose * point3d);\n    }\n    \n    void linearizeOplus()\n    {\n        Eigen::Vector3d point3d = static_cast<VertexPoint3D*>(_vertices[0])->estimate();\n        Sophus::SE3 pose = static_cast<VertexSE3LieAlgebra*>(_vertices[1])->estimate();\n        \n        Eigen::Vector3d xyz_trans(pose * point3d);\n        \n        double x = xyz_trans[0];\n        double y = xyz_trans[1];\n        double z = xyz_trans[2];\n        double z_2 = z * z;\n        \n        const g2o::CameraParameters * cam = static_cast<const g2o::CameraParameters *>(parameter(0));\n        \n        Eigen::Matrix<double, 2, 3, Eigen::ColMajor> tmp;\n        tmp(0, 0) = -cam->focal_length / z;\n        tmp(0, 1) = 0;\n        tmp(0, 2) = cam->focal_length * x / z_2;\n        tmp(1, 0) = 0;\n        tmp(1, 1) = -cam->focal_length / z;\n        tmp(1, 2) = cam->focal_length * y / z_2;\n        \n        _jacobianOplusXi = tmp * pose.rotation_matrix();\n        \n        _jacobianOplusXj(0, 0) = cam->focal_length * x * y / z_2;\n        _jacobianOplusXj(0, 1) = -cam->focal_length * (1 + x*x/z_2);\n        _jacobianOplusXj(0, 2) = cam->focal_length * y / z;\n        _jacobianOplusXj(0, 3) = -cam->focal_length / z;\n        _jacobianOplusXj(0, 4) = 0;\n        _jacobianOplusXj(0, 5) = cam->focal_length * x / z_2;\n        \n        _jacobianOplusXj(1, 0) = cam->focal_length * (1 + y*y/z_2);\n        _jacobianOplusXj(1, 1) = -cam->focal_length * x * y / z_2;\n        _jacobianOplusXj(1, 2) = -cam->focal_length * x / z;\n        _jacobianOplusXj(1, 3) = 0;\n        _jacobianOplusXj(1, 4) = -cam->focal_length / z;\n        _jacobianOplusXj(1, 5) = cam->focal_length * y / z_2;\n    }\n    \n    g2o::CameraParameters* _cam;\n};\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector<cv::KeyPoint>&, std::vector<cv::KeyPoint>&, std::vector<cv::DMatch>&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\nvoid bundleAdjustment( const std::vector<cv::Point3f>, const std::vector<cv::Point2f>, const cv::Mat&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n    if (argc != 5) {\n        std::cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2.\" << std::endl;\n        return 1;\n    }\n    \n    //-- 1st, read photo\n    cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n    \n    if (img_1.empty() || img_2.empty()) {\n        std::cout << \"img1 or img2 is no find.\" << std::endl;\n        return 1;\n    }\n    \n    //-- 2nd, find the two photo feature matches points\n    std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n    std::vector<cv::DMatch> matches;\n    find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n    std::cout << \"feature matches points total is \" << matches.size() << std::endl;\n    \n    //-- 3rd, create 3 dimensions point correspondences\n    cv::Mat d1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);      // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    std::vector<cv::Point3f> pts_3d;\n    std::vector<cv::Point2f> pts_2d;\n    for (cv::DMatch m:matches) {\n        ushort d = d1.ptr<unsigned short>(int (keypoints_1[m.queryIdx].pt.y))[int (keypoints_1[m.queryIdx].pt.x)];\n        \n        if (d == 0) {   /* bad depth */\n            continue;\n        }\n        float dd = d/5000.0;\n        cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n        pts_3d.push_back(cv::Point3d (p1.x*dd, p1.y*dd, dd));\n        pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n    }\n    std::cout << \"3d-2d pairs: \" << pts_3d.size() << std::endl;\n    \n    //-- 4th, use PnP or bundle adjustment compute camera pose.\n    cv::Mat r, t;\n    cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false);    // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    cv::Mat R;\n    cv::Rodrigues(r, R);    // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n    \n    std::cout << \"R = \" << std::endl << R << std::endl;\n    std::cout << \"t = \" << std::endl << t << std::endl;\n    \n    std::cout << \"calling bundle adjustment\" << std::endl;\n    \n    bundleAdjustment(pts_3d, pts_2d, K, R, t);\n    \n    return 0;\n}\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector<cv::KeyPoint>& keypoints_1, std::vector<cv::KeyPoint>& keypoints_2, std::vector<cv::DMatch>& matches)\n{\n    //-- Initialize\n    cv::Mat descriptors_1, descriptors_2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    \n    //-- 1st: detect Oriented FAST KeyPoint \n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    \n    //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    \n    //-- 3rd: \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    std::vector<cv::DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    \n    //-- 4th: \u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist = 10000, max_dist = 0;\n    \n    /* \u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb */\n    for (int i = 0; i < descriptors_1.rows; i++) {\n        double dist = match[i].distance;\n        if (dist < min_dist) {\n            min_dist = dist;\n        }\n        if (dist > max_dist) {\n            max_dist = dist;\n        }\n    }\n    \n    printf(\"-- Max distance : %f \\r\\n\", max_dist);\n    printf(\"-- Min distance : %f \\r\\n\", min_dist);\n    \n    // \u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for (int i = 0; i < descriptors_2.rows; i ++) {\n        if (match[i].distance <= std::max(2*min_dist, 30.0)) {\n            matches.push_back(match[i]);\n        }\n    }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n    return cv::Point2d\n        (\n            (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n            (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n        );\n}\n\nvoid bundleAdjustment(\n    const std::vector<cv::Point3f> points_3d, \n    const std::vector<cv::Point2f> points_2d,\n    const cv::Mat& K,\n    cv::Mat& R,\n    cv::Mat& t )\n{\n    // Initialize g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> Block;   // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linear_solver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block((std::unique_ptr<Block::LinearSolverType>)(linear_solver));\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg((std::unique_ptr<Block>)solver_ptr);\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    \n    // vertex\n    VertexSE3LieAlgebra * pose = new VertexSE3LieAlgebra();     // camera pose\n    Eigen::Matrix3d R_mat;\n    R_mat << \\\n        R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2), \\\n        R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2), \\\n        R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2);\n    pose->setId(0);\n    pose->setEstimate(\n        Sophus::SE3(\n            R_mat, \n            Eigen::Vector3d(t.at<double>(0, 0), t.at<double>(1, 0), t.at<double>(2, 0))\n        )\n    );\n    optimizer.addVertex(pose);\n    \n    int index = 1;\n    for (const cv::Point3f p:points_3d) {\n        VertexPoint3D* point = new VertexPoint3D();\n        point->setId(index ++);\n        point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));\n        point->setMarginalized(true);   // g2o \u4e2d\u5fc5\u987b\u8bbe\u7f6e marg \n        optimizer.addVertex(point);\n    }\n    \n    // parameter : camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters(\n        K.at<double>(0, 0), Eigen::Vector2d(K.at<double>(0, 2), K.at<double>(1, 2)), 0\n    );\n    camera->setId(0);\n    optimizer.addParameter(camera);\n    \n    // edges\n    index = 1;\n    for (const cv::Point2f p:points_2d) {\n        EdgeProject3D22D* edge = new EdgeProject3D22D();\n        edge->setId(index);\n        edge->setVertex(0, dynamic_cast<VertexPoint3D*>(optimizer.vertex(index)));\n        edge->setVertex(1, pose);\n        edge->setMeasurement(Eigen::Vector2d(p.x, p.y));\n        edge->setParameterId(0, 0);\n        edge->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(edge);\n        index++;\n    }\n    \n    std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    std::cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << std::endl;\n    \n    std::cout << std::endl << \"after optimization: \" << std::endl;\n    std::cout << \"T = \" << std::endl << pose->estimate().matrix() << std::endl;\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0312bd513b7012cdb155c905f7b50f9810db3478", "size": 11637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_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_estimation_3d2d/src/pose_estimation_3d2d_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_estimation_3d2d/src/pose_estimation_3d2d_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": 34.1260997067, "max_line_length": 183, "alphanum_fraction": 0.6092635559, "num_tokens": 3725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6617434213491064}}
{"text": "#define BOOST_TEST_MODULE prime_calculator\n#include <boost/test/included/unit_test.hpp>\n\n#include <iron/math/PrimeCalculator.hpp>\n\nBOOST_AUTO_TEST_SUITE(prime_calculator)\n\nstruct Fixture : public ::iron::math::PrimeCalculator {\n  \n};\n\nBOOST_FIXTURE_TEST_CASE(PrimesUnderTenTest, Fixture)\n{\n  BOOST_CHECK_EQUAL(false, isPrime(0));\n  BOOST_CHECK_EQUAL(false, isPrime(1));\n  BOOST_CHECK_EQUAL(true,  isPrime(2));\n  BOOST_CHECK_EQUAL(true,  isPrime(3));\n  BOOST_CHECK_EQUAL(false, isPrime(4));\n  BOOST_CHECK_EQUAL(true,  isPrime(5));\n  BOOST_CHECK_EQUAL(false, isPrime(6));\n  BOOST_CHECK_EQUAL(true,  isPrime(7));\n  BOOST_CHECK_EQUAL(false, isPrime(8));\n  BOOST_CHECK_EQUAL(false, isPrime(9));\n}\n\nBOOST_FIXTURE_TEST_CASE(LargePrimesTest, Fixture)\n{\n  BOOST_CHECK_EQUAL(true,  isPrime(999983));\n  BOOST_CHECK_EQUAL(false, isPrime(999999));\n}\n\n\nBOOST_FIXTURE_TEST_CASE(CachedResults100Test, Fixture)\n{\n  BOOST_CHECK_EQUAL(false, hasCached(100));\n  BOOST_CHECK_EQUAL(false, hasCached(121));\n  BOOST_CHECK_EQUAL(false, hasCached(122));\n\n  BOOST_CHECK_EQUAL(false, isPrime  (100));\n\n  BOOST_CHECK_EQUAL(true,  hasCached(100));\n  BOOST_CHECK_EQUAL(true,  hasCached(121));\n  BOOST_CHECK_EQUAL(false, hasCached(122));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "85795febedbeffe40a563bcfba763e408fd26e97", "size": 1238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/iron/math/PrimeCalculatorTest.cpp", "max_stars_repo_name": "BradSz/iron-horse", "max_stars_repo_head_hexsha": "d86ed86ce60bdaa7c11bd446d84e5060b3d1c56e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/iron/math/PrimeCalculatorTest.cpp", "max_issues_repo_name": "BradSz/iron-horse", "max_issues_repo_head_hexsha": "d86ed86ce60bdaa7c11bd446d84e5060b3d1c56e", "max_issues_repo_licenses": ["MIT"], "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/iron/math/PrimeCalculatorTest.cpp", "max_forks_repo_name": "BradSz/iron-horse", "max_forks_repo_head_hexsha": "d86ed86ce60bdaa7c11bd446d84e5060b3d1c56e", "max_forks_repo_licenses": ["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.7916666667, "max_line_length": 55, "alphanum_fraction": 0.7705977383, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6617434173139038}}
{"text": "#pragma once\n\n#include <math.h>\n#include <string.h>\n#include <Eigen/Eigen>\n#include <boost/serialization/version.hpp>\n#include \"types/Point.hpp\"\n\nstruct RRCoord {\n   /**\n    * RRCoord\n    * If any param is set to NAN this implies that the value is either\n    * not known or irrelevant to the particular context.\n    *\n    * @param heading       heading from robot to object\n    * @param distance      distance from robot to object\n    * @param orientation   angle between robot front and object front\n    */\n   RRCoord(float distance, float heading = NAN, float orientation = NAN)\n      : vec(distance, heading, orientation)\n   {\n      var.setZero();\n   }\n\n   Point toCartesian() const {\n      return Point(distance()*cosf(heading()), distance()*sinf(heading()));\n   }\n\n   RRCoord() {\n      vec.setZero();\n      var.setZero();\n   }\n   \n   RRCoord(const RRCoord &other) {\n      this->vec = other.vec;\n      this->var = other.var;\n   }\n\n   RRCoord& operator=(const RRCoord &other) {\n      for (unsigned i = 0; i < 3; i++) {\n         this->vec(i, 0) = other.vec(i, 0);\n      }\n      for (unsigned i = 0; i < 9; i++) {\n         this->var[i] = other.var[i];\n      }\n      \n      return *this;\n   }\n   \n   Eigen::Vector3f vec;\n   Eigen::Matrix<float, 3, 3> var;\n\n   /* Distance to object */\n   const float distance() const {\n      return vec[0];\n   }\n\n   float &distance() {\n      return vec[0];\n   }\n\n   /* Heading to object */\n   const float heading() const {\n      return vec[1];\n   }\n\n   float &heading() {\n      return vec[1];\n   }\n\n   /* Angle between robot's front and object's front */\n   const float orientation() const {\n      return vec[2];\n   }\n\n   float &orientation() {\n      return vec[2];\n   }\n\n   bool operator== (const RRCoord &other) const {\n      return vec == other.vec;\n   }\n\n   template<class Archive>\n   void serialize(Archive &ar, const unsigned int file_version);\n};\n\ninline std::ostream& operator<<(std::ostream& os, const RRCoord& coord) {\n   for (unsigned i = 0; i < 3; i++) {\n      float a = coord.vec[i];\n      os.write((char*) &a, sizeof(float));\n   }\n   \n   for (unsigned i = 0; i < 9; i++) {\n      float a = coord.var[i];\n      os.write((char*) &a, sizeof(float));\n   }\n   return os;\n}\n\ninline std::istream& operator>>(std::istream& is, RRCoord& coord) {\n   for (unsigned i = 0; i < 3; i++) {\n      float a;\n      is.read((char*) &a, sizeof(float));\n      coord.vec[i] = a;\n   }\n   \n   for (unsigned i = 0; i < 9; i++) {\n      float a;\n      is.read((char*) &a, sizeof(float));\n      coord.var[i] = a;\n   }\n\n   return is;\n}\n\ntypedef enum {\n   DIST,\n   HEADING,\n   ORIENTATION,\n} RRCoordEnum;\n\n#include \"types/RRCoord.tcc\"\n\n", "meta": {"hexsha": "ce1b82cecc0e37156fd9a08a2ac2559f850c3dbb", "size": 2651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 21.208, "max_line_length": 75, "alphanum_fraction": 0.5654470011, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6617434092434981}}
{"text": "#include <codegenvar/Eigen>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace codegenvar;\n\nint main()\n{\n    const Symbol x(\"x\"), y(\"y\"), dx(\"dx\"), dy(\"dy\"), a(\"a\");\n    \n    const Vec2 p(x, y);\n    const Vec3 P = p.homogeneous();\n    const Vec2 diff(dx, dy);\n\n    std::cout << \"p = \" << p.transpose() << std::endl;\n    std::cout << \"translate by \" << diff.transpose() << std::endl;\n    std::cout << \"rotate by \" << a << std::endl << std::endl;\n    std::cout << \"P = \" << P.transpose() << std::endl << std::endl;\n\n    Mat23 t;\n    t << Symbol(1), Symbol(0), diff(0),\n         Symbol(0), Symbol(1), diff(1);\n\n    std::cout << \"p + diff = \" << (p+diff).transpose() << std::endl << std::endl;\n    std::cout << \"t = \" << std::endl << t << std::endl << std::endl;\n    std::cout << \"t*P = \" << (t*P).transpose() << std::endl << std::endl;\n\n    Mat3 T;\n    T << t(0, 0), t(0, 1), t(0, 2),\n         t(1, 0), t(1, 1), t(1, 2),\n         Symbol(0), Symbol(0), Symbol(1);\n\n    std::cout << \"T = \" << std::endl << T << std::endl << std::endl;\n    std::cout << \"T*P = \" << (T*P).transpose() << std::endl << std::endl;\n\n    Mat2 r;\n    r <<  cos(a), -sin(a),\n          sin(a),  cos(a);\n\n    std::cout << \"r = \" << std::endl << r << std::endl << std::endl;\n    std::cout << \"r*p = \" << (r*p).transpose() << std::endl << std::endl;\n\n    Mat3 R;\n    R << r(0, 0) , r(0, 1), Symbol(0),\n         r(1, 0) , r(1, 1), Symbol(0),\n         Symbol(0), Symbol(0), Symbol(1);\n\n    std::cout << \"R = \" << std::endl << R << std::endl << std::endl;\n    std::cout << \"R*P = \" << (R*P).transpose() << std::endl << std::endl;\n\n    std::cout << \"T*R = \" << std::endl << T*R << std::endl << std::endl;\n    std::cout << \"T*R*P = \" << (T*R*P).transpose() << std::endl << std::endl;\n\n    std::cout << \"R*T = \" << std::endl << R*T << std::endl << std::endl;\n    std::cout << \"R*T*P = \" << (R*T*P).transpose() << std::endl << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "cac2563e46f2138efc6fe54934946099ef721ffd", "size": 1924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen.cpp", "max_stars_repo_name": "bjornpiltz/CppCodeGenVar", "max_stars_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T09:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T05:44:14.000Z", "max_issues_repo_path": "examples/eigen.cpp", "max_issues_repo_name": "bjornpiltz/CppCodeGenVar", "max_issues_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-01-18T13:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-25T21:42:34.000Z", "max_forks_repo_path": "examples/eigen.cpp", "max_forks_repo_name": "bjornpiltz/CppCodeGenVar", "max_forks_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_forks_repo_licenses": ["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.1724137931, "max_line_length": 81, "alphanum_fraction": 0.4641372141, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6616743025183384}}
{"text": "\n#include <NTL/LLL.h>\n\nNTL_CLIENT\n\nint main()\n{\n   mat_ZZ B;\n   long s;\n\n#if 1\n   cin >> B;\n#else\n   long i, j;\n   long n;\n   cerr << \"n: \";\n   cin >> n;\n\n   long m;\n   cerr << \"m: \";\n   cin >> m;\n\n   long k;\n   cerr << \"k: \";\n   cin >> k;\n\n   B.SetDims(n, m);\n   for (i = 1; i <= n; i++)\n      for (j = 1; j <= m; j++) {\n         RandomLen(B(i,j), k);\n         if (RandomBnd(2)) negate(B(i,j), B(i,j));\n      }\n\n\n#endif\n\n   mat_ZZ U, B0, B1, B2;\n\n   B0 = B;\n\n   double t;\n   ZZ d;\n\n   B = B0;\n   cerr << \"LLL_FP...\";\n   t = GetTime();\n   s = LLL_FP(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"LLL_QP...\";\n   t = GetTime();\n   s = LLL_QP(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n\n   B = B0;\n   cerr << \"LLL_XD...\";\n   t = GetTime();\n   s = LLL_XD(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"LLL_RR...\";\n   t = GetTime();\n   s = LLL_RR(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"G_LLL_FP...\";\n   t = GetTime();\n   s = G_LLL_FP(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"G_LLL_QP...\";\n   t = GetTime();\n   s = G_LLL_QP(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"G_LLL_XD...\";\n   t = GetTime();\n   s = G_LLL_XD(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n   B = B0;\n   cerr << \"G_LLL_RR...\";\n   t = GetTime();\n   s = G_LLL_RR(B, U, 0.99);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n   LLL(d, B, 90, 100);\n   if (B1 != B) Error(\"bad LLLTest (2)\");\n\n\n   B = B0;\n   cerr << \"LLL...\";\n   t = GetTime();\n   s = LLL(d, B, U);\n   cerr << (GetTime()-t) << \"\\n\";\n   mul(B1, U, B0);\n   if (B1 != B) Error(\"bad LLLTest (1)\");\n\n   cout << \"rank = \" << s << \"\\n\";\n   cout << \"det = \" << d << \"\\n\";\n   cout << \"B = \" << B << \"\\n\";\n   cout << \"U = \" << U << \"\\n\";\n}\n\n", "meta": {"hexsha": "66bf1efd3a0bed608491a19bc7320a774df752dd", "size": 2732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5142857143, "max_line_length": 50, "alphanum_fraction": 0.4245973646, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6616742978323912}}
{"text": "// Copyright (c) 2016 Copyright Holder All Rights Reserved.\n\n#include <algorithm>\n#include <cstddef>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <numeric>\n\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, directedS, no_property,\n                       property<edge_weight_t, int64_t>>\n    Graph;\n\ntypedef graph_traits<Graph>::vertex_descriptor vertex_descriptor;\ntypedef graph_traits<Graph>::edge_descriptor edge_descriptor;\n\nint main(int argc, char const *argv[]) {\n  std::ifstream fin(\"../priv/edges.txt\");\n  int num_of_nodes, num_of_edges;\n\n  fin >> num_of_nodes >> num_of_edges;\n  std::cout << \"Nodes \" << num_of_nodes << \" Edges \" << num_of_edges\n            << std::endl;\n  Graph g(num_of_nodes);\n  // std::vector<int64_t> weights(num_of_nodes);\n\n  for (auto i = 0; i < num_of_edges; ++i) {\n    int u, v;\n    int64_t weight;\n    fin >> u >> v >> weight;\n    // std::cout << u << \" -> \" << v <<std::endl;\n    add_edge(u, v, weight, g);\n  }\n\n  // this use dijskura, don't allow negative edge weights\n  // std::vector<vertex_descriptor> p(num_vertices(g));\n  // prim_minimum_spanning_tree(g, &p[0]);\n\n  std::vector<edge_descriptor> spanning_tree;\n  kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n  for (auto it = spanning_tree.begin(); it != spanning_tree.end(); ++it) {\n    std::cout << source(*it, g) << \" -- \" << target(*it, g) << \";\" << std::endl;\n    // std::cout << get(edge_weight, g, *it) << std::endl;\n  }\n\n  int64_t mst_weights = std::accumulate(\n      spanning_tree.begin(), spanning_tree.end(), 0,\n      [g](int64_t acc, auto b) { return acc + get(edge_weight, g, b); });\n\n  std::cout << \"MST weights: \" << mst_weights << std::endl;\n\n  /*for (std::size_t i = 0; i != p.size(); ++i)\n    if (p[i] != i)\n      std::cout << \"parent[\" << i << \"] = \" << p[i] << std::endl;\n    else\n      std::cout << \"parent[\" << i << \"] = no parent\" << std::endl;\n*/\n  // write_graphviz(std::cout, g);\n  /*\n    graph_traits<Graph>::edge_iterator ei, eend;\n    for (boost::tie(ei, eend) = edges(g);  ei != eend; ++ei) {\n      std::cout << \"E: \" << *ei << \"   \" << std::endl;\n    }*/\n\n  /*graph_traits<Graph>::vertex_iterator vi, vend;\n  for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n    std::cout << \"V: \" << *vi << std::endl;\n  }*/\n\n  // std::cout << num_edges(g) << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "91d72838430c10b6be099009ce809d2e4e409bef", "size": 2590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-mmgraph/graph.cpp", "max_stars_repo_name": "andelf/codeplay", "max_stars_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-10T04:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-10T08:31:17.000Z", "max_issues_repo_path": "cpp-mmgraph/graph.cpp", "max_issues_repo_name": "andelf/codeplay", "max_issues_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_issues_repo_licenses": ["MIT"], "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-mmgraph/graph.cpp", "max_forks_repo_name": "andelf/codeplay", "max_forks_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_forks_repo_licenses": ["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.2048192771, "max_line_length": 80, "alphanum_fraction": 0.6154440154, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6616525933516783}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"ternary_math.hpp\"\n\nBOOST_AUTO_TEST_SUITE(ternary_math)\n\nBOOST_AUTO_TEST_CASE(abs_test)\n{\n    BOOST_TEST(abs_c(1) == 1);\n    BOOST_TEST(abs_c(-1) == 1);\n    BOOST_TEST(abs_c(0) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(sign_test)\n{\n    BOOST_TEST(sign_c(42) == 1);\n    BOOST_TEST(sign_c(-123) == -1);\n    BOOST_TEST(sign_c(0) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(power_of_3_test)\n{\n    BOOST_TEST(pow3(0) == 1);\n    BOOST_TEST(pow3(1) == 3);\n    BOOST_TEST(pow3(4) == 81);\n}\n\nBOOST_AUTO_TEST_CASE(lowest_trit_test)\n{\n    BOOST_TEST(lowest_trit(0) == 0);\n    BOOST_TEST(lowest_trit(-1) == lowest_trit(2));\n    BOOST_TEST(lowest_trit(31) == 1);\n}\n\nBOOST_AUTO_TEST_CASE(shift_right_test)\n{\n    auto tc1 { 42 };\n    BOOST_TEST(shift_right(tc1, 0) == 42);\n    BOOST_TEST(shift_right(tc1, 1) == 14);\n    BOOST_TEST(shift_right(tc1, 2) == 5);\n    BOOST_TEST(shift_right(tc1, 3) == 2);\n    BOOST_TEST(shift_right(tc1, 4) == 1);\n    BOOST_TEST(shift_right(tc1, 5) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(nth_trit_test)\n{\n    auto tc2 { 52 };    // +-0-+\n    BOOST_TEST(nth_trit(tc2, 0) == 1);\n    BOOST_TEST(nth_trit(tc2, 1) == -1);\n    BOOST_TEST(nth_trit(tc2, 2) == 0);\n    BOOST_TEST(nth_trit(tc2, 3) == -1);\n    BOOST_TEST(nth_trit(tc2, 4) == 1);\n    BOOST_TEST(nth_trit(tc2, 5) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(clamp_test)\n{\n    auto n1 { clamp<int,6>(0) };\n    auto n2 { clamp<int,6>(123) };\n    auto n3 { clamp<int,6>(-1234) };\n    BOOST_TEST(n1 == 0);\n    BOOST_TEST(n2 == 123);\n    BOOST_TEST(n3 == -(pow3(6)/2));\n}\n\nBOOST_AUTO_TEST_CASE(low_trits_test)\n{\n    auto tc3 { 52 };    // +-0-+\n    BOOST_TEST(low_trits(tc3, 0) == 0);\n    BOOST_TEST(low_trits(tc3, 1) == 1);\n    BOOST_TEST(low_trits(tc3, 2) == -2);\n    BOOST_TEST(low_trits(tc3, 3) == -2);\n    BOOST_TEST(low_trits(tc3, 4) == -29);\n    BOOST_TEST(low_trits(tc3, 5) == 52);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "739fab45b0d72811dff7c13b2c81358ed7c44a74", "size": 1882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ternary_math_test.cpp", "max_stars_repo_name": "momikey/trireme", "max_stars_repo_head_hexsha": "9c284882ea0bea13ce02426bfd4c55842edefd6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-05T08:52:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-05T08:52:12.000Z", "max_issues_repo_path": "tests/ternary_math_test.cpp", "max_issues_repo_name": "momikey/trireme", "max_issues_repo_head_hexsha": "9c284882ea0bea13ce02426bfd4c55842edefd6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/ternary_math_test.cpp", "max_forks_repo_name": "momikey/trireme", "max_forks_repo_head_hexsha": "9c284882ea0bea13ce02426bfd4c55842edefd6c", "max_forks_repo_licenses": ["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.1282051282, "max_line_length": 50, "alphanum_fraction": 0.6253985122, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6616480058702888}}
{"text": "#pragma once\n\n#include <boost/container/static_vector.hpp>\n#include <boost/container/vector.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <numeric>\n\nnamespace discreture\n{\n\ntemplate <typename T>\nvoid UNUSED(T&& /*unused*/)\n{}\n\n//////////////////////////////////////////\n/// \\brief This is what operator% should be but isn't (!).\n///\n/// C++ modulo operator%is dumb for negative integers: (-7)%3 returns -1,\n/// instead of 2. This fixes it.\n/// \\return an integer in [0,b)\n//////////////////////////////////////////\ntemplate <class IntType>\ninline IntType modulo(IntType a, IntType b)\n{\n    IntType r = a%b;\n    if (r < 0)\n        r += b;\n    return r;\n}\n\n//////////////////////////////////////////\n/// \\brief This is what operator %= should be but isn't (!).\n///\n/// C++ modulo operator %= is dumb for negative integers: (-7)%3 returns -1,\n/// instead of 2. This fixes it.\n//////////////////////////////////////////\ntemplate <class IntType>\ninline void reduce_modulo(IntType& a, IntType b)\n{\n    a %= b;\n    if (a < 0)\n        a += b;\n}\n\ntemplate <class T>\ninline T pow(T a, std::uint64_t n)\n{\n    T r = 1;\n\n    while (n > 0)\n    {\n        auto division = std::div(n, 2);\n        if (division.rem == 1) // if odd\n            r *= a;\n\n        n = division.quot;\n        a *= a;\n    }\n\n    return r;\n}\n\n// Deprecated in c++17. Here for use in c++14.\ntemplate <class T>\nT gcd(T a, T b)\n{\n    while (b != 0)\n    {\n        T r = a%b;\n        a = b;\n        b = r;\n    }\n    return a;\n}\n\ntemplate <class T, class Container>\nT reduce_fraction(Container Numerator, Container Denominator)\n{\n    for (auto& b : Denominator)\n    {\n        for (auto& a : Numerator)\n        {\n            auto d = gcd(a, b);\n            a /= d;\n            b /= d;\n            if (b == 1)\n                break;\n        }\n    }\n\n    T result = 1;\n    for (auto a : Numerator)\n        result *= a;\n    return result;\n}\n\n} // namespace discreture\n", "meta": {"hexsha": "e5acbb73db566a7d6b74a317fd51bb6f43983d9a", "size": 1986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/Misc.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": "include/Discreture/Misc.hpp", "max_issues_repo_name": "remz1337/discreture", "max_issues_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T18:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-02T22:16:49.000Z", "max_forks_repo_path": "sources/include/external/Discreture/Misc.hpp", "max_forks_repo_name": "greati/logicantsy", "max_forks_repo_head_hexsha": "11d1f33f57df6fc77c3c18b506fc98f9b9a88794", "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": 19.6633663366, "max_line_length": 76, "alphanum_fraction": 0.5005035247, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.661647997134357}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <Eigen/Dense>\n\n#include \"src/liblm/c_api.h\"\n#include \"src/liblm/liblm.h\"\n\nusing namespace Eigen;\n\nvoid test_c() {\n\n    double *X = (double *) malloc(sizeof(double) * 5);\n    double *y = (double *) malloc(sizeof(double) * 5);\n    double *X_test = (double *) malloc(sizeof(double) * 5);\n    for (int i = 0; i < 5; ++i) {\n        X[i] = i;\n        y[i] = 2 * i - 1;\n        X_test[i] = i + 5;\n    }\n    lm_problem *prob = (lm_problem *) malloc(sizeof(lm_problem));\n    dmatrix data;\n    data.data = X;\n    data.row = 5;\n    data.col = 1;\n    prob->X = data;\n    prob->y = y;\n    lm_param param;\n    param.alg = REG;\n    param.regu = NONE;\n    lm_model *model = lm_train(prob, &param);\n    dmatrix d;\n    d.data = X_test;\n    d.row = 5;\n    d.col = 1;\n    y = lm_predict(model, &d);\n    for (int i = 0; i < 5; ++i)\n        printf(\"%.3f \", y[i]);\n    printf(\"\\n\");\n    free_model(model);\n}\n\n\nvoid test_cpp() {\n    MatrixXd X(4, 1);\n    X << 1, 2, 3, 4;\n    VectorXd y(4);\n    y << 1, 2, 3, 4;\n    MatrixXd X_test = X.array() + 5;\n    Regressor *clf = new LinearRegression();\n    clf->fit(X, y);\n    std::cout << clf->predict(X_test) << std::endl;\n    delete clf;\n}\n\nint main() {\n    test_c();\n    std::cout << \"----------------\" << std::endl;\n    test_cpp();\n    return 0;\n}", "meta": {"hexsha": "11dc5b6719c367b58bcd987e565bb8ed49d4b028", "size": 1316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo.cpp", "max_stars_repo_name": "lchmo444/liblm", "max_stars_repo_head_hexsha": "a88f3bfbef12d3eed1a023d03dd42f2ab404f9b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-31T10:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T12:29:59.000Z", "max_issues_repo_path": "demo.cpp", "max_issues_repo_name": "lchmo444/liblm", "max_issues_repo_head_hexsha": "a88f3bfbef12d3eed1a023d03dd42f2ab404f9b4", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "lchmo444/liblm", "max_forks_repo_head_hexsha": "a88f3bfbef12d3eed1a023d03dd42f2ab404f9b4", "max_forks_repo_licenses": ["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.9333333333, "max_line_length": 65, "alphanum_fraction": 0.5182370821, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6616381878441678}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include <functional>\n#include \"plane3d.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef MESH_COMPONENTS_HPP\n#define MESH_COMPONENTS_HPP\n\n\nclass Vertex3d {\n    Vector3d vec;\n    //std::vector<Tetrahedron *> tetrahedrons;\n  public:\n    Vertex3d (array<double, 3> _vec);\n    Vector3d Vec();\n};\n\nclass Tetrahedron {\n    unsigned long int id;\n    vector<reference_wrapper<Vertex3d>> vertices;\n    vector<unsigned long int> neighbors;\n    array<double, 3> sphereCenter;\n    double sphereRadius;\n    double weight;\n    int label;\n  public:\n    Tetrahedron (const int id, const vector<reference_wrapper<Vertex3d>> _vertices, const double _weight, const int _label);\n    void addNeighbor(unsigned long int neighborId);\n    bool contains(const array<double, 3>);\n    vector<reference_wrapper<Vertex3d>> Vertices();\n    vector<unsigned long int> Neighbors();\n    vector<array<double, 3>> intersectsPlane(Plane3d plane);\n    unsigned long int Id();\n    double Weight();\n    int Label();\n};\n\nclass Face {\n    vector<reference_wrapper<Vertex3d>> vertices;\n    unsigned long int tetId;\n  public:\n    Face (vector<reference_wrapper<Vertex3d>> _vertices, unsigned long int _tetId);\n    vector<reference_wrapper<Vertex3d>> Vertices();\n    unsigned long int TetId();\n    bool intersectsPlane(Plane3d plane);\n    //vector<Vertex3d *> Vertices();\n    //Tetrahedron* getTetrahedron();\n};\n\n#endif\n", "meta": {"hexsha": "61b57645915c63632a7d6e82cd307ca59777ea4e", "size": 1443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mesh_components.hpp", "max_stars_repo_name": "myociss/pathfinder", "max_stars_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_stars_repo_licenses": ["MIT"], "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/mesh_components.hpp", "max_issues_repo_name": "myociss/pathfinder", "max_issues_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_issues_repo_licenses": ["MIT"], "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/mesh_components.hpp", "max_forks_repo_name": "myociss/pathfinder", "max_forks_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_forks_repo_licenses": ["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.2363636364, "max_line_length": 124, "alphanum_fraction": 0.7124047124, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6616381827798636}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\r\n\r\nusing namespace boost;\r\n\r\ntemplate < typename Graph, typename ParentMap > \r\nstruct edge_writer\r\n{\r\n  edge_writer(const Graph & g, const ParentMap & p)\r\n  : m_g(g), m_parent(p)\r\n  {\r\n  }\r\n\r\n  template < typename Edge >\r\n    void operator() (std::ostream & out, const Edge & e) const\r\n  {\r\n    out << \"[label=\\\"\" << get(edge_weight, m_g, e) << \"\\\"\";\r\n    typename graph_traits < Graph >::vertex_descriptor\r\n      u = source(e, m_g), v = target(e, m_g);\r\n    if (m_parent[v] == u)\r\n        out << \", color=\\\"black\\\"\";\r\n    else\r\n        out << \", color=\\\"grey\\\"\";\r\n      out << \"]\";\r\n  }\r\n  const Graph & m_g;\r\n  ParentMap m_parent;\r\n};\r\ntemplate < typename Graph, typename Parent >\r\nedge_writer < Graph, Parent >\r\nmake_edge_writer(const Graph & g, const Parent & p)\r\n{\r\n  return edge_writer < Graph, Parent > (g, p);\r\n}\r\n\r\nstruct EdgeProperties {\r\n  int weight;\r\n};\r\n\r\nint\r\nmain()\r\n{\r\n  enum { u, v, x, y, z, N };\r\n  char name[] = { 'u', 'v', 'x', 'y', 'z' };\r\n  typedef std::pair < int, int >E;\r\n  const int n_edges = 10;\r\n  E edge_array[] = { E(u, y), E(u, x), E(u, v), E(v, u),\r\n      E(x, y), E(x, v), E(y, v), E(y, z), E(z, u), E(z,x) };\r\n  int weight[n_edges] = { -4, 8, 5, -2, 9, -3, 7, 2, 6, 7 };\r\n\r\n  typedef adjacency_list < vecS, vecS, directedS,\r\n    no_property, EdgeProperties> Graph;\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ can't handle the iterator constructor\r\n  Graph g(N);\r\n  for (std::size_t j = 0; j < n_edges; ++j)\r\n    add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n  Graph g(edge_array, edge_array + n_edges, N);\r\n#endif\r\n  graph_traits < Graph >::edge_iterator ei, ei_end;\r\n  property_map<Graph, int EdgeProperties::*>::type \r\n    weight_pmap = get(&EdgeProperties::weight, g);\r\n  int i = 0;\r\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\r\n    weight_pmap[*ei] = weight[i];\r\n\r\n  std::vector<int> distance(N, (std::numeric_limits < short >::max)());\r\n  std::vector<std::size_t> parent(N);\r\n  for (i = 0; i < N; ++i)\r\n    parent[i] = i;\r\n  distance[z] = 0;\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  bool r = bellman_ford_shortest_paths\r\n    (g, int(N), weight_pmap, &parent[0], &distance[0], \r\n     closed_plus<int>(), std::less<int>(), default_bellman_visitor());\r\n#else\r\n  bool r = bellman_ford_shortest_paths\r\n    (g, int (N), weight_map(weight_pmap).distance_map(&distance[0]).\r\n     predecessor_map(&parent[0]));\r\n#endif\r\n\r\n  if (r)\r\n    for (i = 0; i < N; ++i)\r\n      std::cout << name[i] << \": \" << std::setw(3) << distance[i]\r\n        << \" \" << name[parent[i]] << std::endl;\r\n  else\r\n    std::cout << \"negative cycle\" << std::endl;\r\n\r\n  std::ofstream dot_file(\"figs/bellman-eg.dot\");\r\n  dot_file << \"digraph D {\\n\"\r\n    << \"  rankdir=LR\\n\"\r\n    << \"  size=\\\"5,3\\\"\\n\"\r\n    << \"  ratio=\\\"fill\\\"\\n\"\r\n    << \"  edge[style=\\\"bold\\\"]\\n\" << \"  node[shape=\\\"circle\\\"]\\n\";\r\n\r\n  {\r\n    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\r\n      graph_traits < Graph >::edge_descriptor e = *ei;\r\n      graph_traits < Graph >::vertex_descriptor\r\n        u = source(e, g), v = target(e, g);\r\n      // VC++ doesn't like the 3-argument get function, so here\r\n      // we workaround by using 2-nested get()'s.\r\n      dot_file << name[u] << \" -> \" << name[v]\r\n        << \"[label=\\\"\" << get(get(&EdgeProperties::weight, g), e) << \"\\\"\";\r\n      if (parent[v] == u)\r\n        dot_file << \", color=\\\"black\\\"\";\r\n      else\r\n        dot_file << \", color=\\\"grey\\\"\";\r\n      dot_file << \"]\";\r\n    }\r\n  }\r\n  dot_file << \"}\";\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "1b61e2533cd77c4e5ec2e7bb5dc5bb7782c446d3", "size": 4120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/bellman-example.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": 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/graph/example/bellman-example.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": 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/graph/example/bellman-example.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": 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": 31.9379844961, "max_line_length": 75, "alphanum_fraction": 0.5487864078, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6616114876132543}}
{"text": "#include <iostream>\n#include <unordered_map>\n#include <string>\n#include <vector>\n#include <boost/functional/hash.hpp>\n\nusing namespace std;\n\n#define DEBUG 0\n\n#define MAX_W 100\n#define MAX_L 100\n\ntypedef tuple<int, int, int, int> quad;\ntemplate<> struct hash<quad> {\n  size_t operator()(const quad& q) const noexcept {\n    size_t seed = 0;\n    boost::hash_combine(seed, get<0>(q));\n    boost::hash_combine(seed, get<1>(q));\n    boost::hash_combine(seed, get<2>(q));\n    boost::hash_combine(seed, get<3>(q));\n    return seed;\n  }\n};\n\nclass AvoidRoads {\nprivate:\n  long dp[MAX_W+1][MAX_L+1] = { 0 };\n  unordered_map<quad, int>bad_m;\n\npublic:\n  long numWays(int w, int l, vector<string> bad) {\n    preparebad(bad);\n\n    dp[0][0] = 1;\n\n    // Initialize bottom row\n    for (int i = 1; i < w + 1; ++i) {\n      quad p = make_tuple(i - 1, 0, i, 0);\n      if (bad_m.find(p) == bad_m.end()) {\n        dp[i][0] = dp[i-1][0];\n      }\n      int j = 0;\n      // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n    }\n    // Initialize left column\n    for (int j = 1; j < l + 1; ++j) {\n      quad p = make_tuple(0, j - 1, 0, j);\n      if (bad_m.find(p) == bad_m.end()) {\n        dp[0][j] = dp[0][j-1];\n      }\n      int i = 0;\n      // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n    }\n    for (int i = 1; i < w + 1; ++i) {\n      for (int j = 1; j < l + 1; ++j) {\n        if (bad_m.find(make_tuple(i - 1, j, i, j)) == bad_m.end()) {\n          dp[i][j] += dp[i-1][j];\n        }\n        if (bad_m.find(make_tuple(i, j - 1, i, j)) == bad_m.end()) {\n          dp[i][j] += dp[i][j-1];\n        }\n        // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n      }\n    }\n\n    // Only for debug\n    // printf(\"\\n\");\n    // for (int j = l; j >= 0; --j) {\n    //   for (int i = 0; i < w + 1; ++i) {\n    //     printf(\"%5ld\", dp[i][j]);\n    //   }\n    //   printf(\"\\n\");\n    // }\n    return dp[w][l];\n  }\n\n  void preparebad(vector<string> bad) {\n    for(auto &s : bad) {\n      // NOTE: read int from bad string\n      int l = s.size();\n      vector<int> space;\n      for (int i = 0; i < l; ++i) {\n        if (s[i] == ' ') {\n          space.push_back(i);\n        }\n      }\n\n      vector<int> pos_list;\n      pos_list.push_back(stoi(s));\n      for(auto &p : space) {\n        pos_list.push_back(stoi(s.substr(p + 1)));\n      }\n\n      quad p;\n      if (pos_list[0] < pos_list[2] || pos_list[1] < pos_list[3]) {\n        p = make_tuple(pos_list[0], pos_list[1], pos_list[2], pos_list[3]);\n      } else {\n        p = make_tuple(pos_list[2], pos_list[3], pos_list[0], pos_list[1]);\n      }\n      bad_m[p] = 1;\n    }\n  }\n};\n\nint main(int argc, char** argv) {\n  AvoidRoads a0;\n  vector<string> bad0 = {\"0 0 0 1\", \"6 6 5 6\"};\n  std::cout << \"a0: Expected 252, Got \" << a0.numWays(6, 6, bad0) << \"\" << std::endl;\n\n  AvoidRoads a1;\n  vector<string> bad1 = {};\n  std::cout << \"a1: Expected 2, Got \" << a1.numWays(1, 1, bad1) << \"\" << std::endl;\n\n  AvoidRoads a2;\n  vector<string> bad2 = {};\n  std::cout << \"a1: Expected 6406484391866534976, Got \" << a2.numWays(35, 31, bad2) << \"\" << std::endl;\n\n  AvoidRoads a3;\n  vector<string> bad3 = {\"0 0 1 0\", \"1 2 2 2\", \"1 1 2 1\"};\n  std::cout << \"a1: Expected 0, Got \" << a3.numWays(2, 2, bad3) << \"\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "cf7e60f16598bb5cd6fbc14efa47418d726b21f0", "size": 3310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AvoidRoads.cpp", "max_stars_repo_name": "south37/topcoder", "max_stars_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AvoidRoads.cpp", "max_issues_repo_name": "south37/topcoder", "max_issues_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AvoidRoads.cpp", "max_forks_repo_name": "south37/topcoder", "max_forks_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_forks_repo_licenses": ["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.48, "max_line_length": 103, "alphanum_fraction": 0.4827794562, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6614266357222751}}
{"text": "#include \"Normals.h\"\n\n#include <Eigen/Geometry>\n\nvoid perVertexNormals(const Eigen::MatrixXd &vertices,\n\tconst Eigen::MatrixXi &triangles,\n\tEigen::MatrixXd &normals,\n\tWeightType::Type weightType)\n{\n\tnormals.setZero(vertices.rows(), vertices.cols());\n\tstd::vector<double> weightSum(vertices.cols(), 0.0);\n\n\tfor (int tri = 0; tri < triangles.cols(); tri++)\n\t{\n\t\tstd::array<int, 3> vIdcs = { triangles(0, tri), triangles(1, tri), triangles(2, tri) };\n\t\tstd::array<Eigen::Vector3d, 3> v;\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tif (vIdcs[i] < 0 || vIdcs[i] >= vertices.cols()) {\n\t\t\t\tthrow std::logic_error(\"err\");\n\t\t\t}\n\t\t\tv[i] = vertices.col(vIdcs[i]);\n\t\t}\n\t\tEigen::Vector3d normal = (v[1] - v[0]).cross(v[2] - v[0]);\n\t\tdouble twiceArea = normal.norm();\n\t\tnormal /= twiceArea;\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tEigen::Vector3d e1 = v[(i + 1) % 3] - v[i];\n\t\t\tEigen::Vector3d e2 = v[(i + 2) % 3] - v[i];\n\t\t\tdouble angleBetween = std::acos(std::min(1.0, std::max(-1.0, e1.normalized().dot(e2.normalized()))));\n\t\t\tdouble weight;\n\t\t\tswitch (weightType)\n\t\t\t{\n\t\t\tcase WeightType::CONSTANT:\n\t\t\t\tweight = 1.0;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::AREA:\n\t\t\t\tweight = twiceArea;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::ANGLE:\n\t\t\t\tweight = angleBetween;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::ANGLE_AREA:\n\t\t\t\tweight = twiceArea * angleBetween;\n\t\t\t\tbreak;\n\t\t\tdefault: assert(false);\n\t\t\t}\n\t\t\t//double weight = 1.0;\n\t\t\tEigen::Vector3d wn = weight*normal;\n\t\t\tnormals.col(vIdcs[i]) += wn;\n\t\t\tweightSum[vIdcs[i]] += weight;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < vertices.cols(); i++)\n\t{\n\t\tif (weightSum[i] != 0.0)\n\t\t{\n\t\t\tnormals.col(i) /= weightSum[i];\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "acab7fc239634c0531bcb4e4b807483d586c83ae", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Normals.cpp", "max_stars_repo_name": "JonasZehn/YAPS", "max_stars_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_stars_repo_licenses": ["MIT"], "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/Normals.cpp", "max_issues_repo_name": "JonasZehn/YAPS", "max_issues_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_issues_repo_licenses": ["MIT"], "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/Normals.cpp", "max_forks_repo_name": "JonasZehn/YAPS", "max_forks_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_forks_repo_licenses": ["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.4920634921, "max_line_length": 104, "alphanum_fraction": 0.599003736, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6614266286469825}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix4f A = MatrixXf::Random(4,4);\ncout << \"Here is a random 4x4 matrix:\" << endl << A << endl;\nHessenbergDecomposition<MatrixXf> hessOfA(A);\nMatrixXf H = hessOfA.matrixH();\ncout << \"The Hessenberg matrix H is:\" << endl << H << endl;\nMatrixXf Q = hessOfA.matrixQ();\ncout << \"The orthogonal matrix Q is:\" << endl << Q << endl;\ncout << \"Q H Q^T is:\" << endl << Q * H * Q.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d0dacdda3c8c52c026b0c15a4c024d163a1988cb", "size": 875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 30.1724137931, "max_line_length": 224, "alphanum_fraction": 0.6605714286, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.661426624203559}}
{"text": "#include \"tests_stats.hxx\"\n\n#include \"gtest/gtest.h\"\n#include \"vec3f.hxx\"\n#include \"util.hxx\"\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/numeric/interval.hpp>\n\n#include <numeric> // for std::accumulate1\n\n\n\n// A review of statistical testing applied to computer graphics!\n// http://www0.cs.ucl.ac.uk/staff/K.Subr/Files/Papers/PG2007.pdf\n\n//http://mathworld.wolfram.com/BinomialDistribution.html\nstd::tuple<double, double> BinomialDistributionMeanStdev(int n, double p)\n{\n  assert(p >= 0.);\n  return std::make_tuple(p*n, std::sqrt(n*p*(1.-p)));\n}\n\nstd::tuple<double, double> BinomialDistributionMeanStdev(int _n, double _p, double _p_err)\n{\n  assert(_p >= 0. && _p_err >= 0.);\n  using namespace boost::numeric;\n  using namespace interval_lib;\n  using I = interval<double>;\n  double pl = std::max(0., _p-_p_err);\n  double ph = std::min(1., _p+_p_err);\n  I p{pl, ph};\n  I n{_n, _n};\n  I mean = p*n;\n  I stddev = sqrt(n*p*(1.-p));\n  double uncertainty = stddev.upper() + 0.5*(mean.upper()-mean.lower());\n  return std::make_tuple(_p*_n, uncertainty);\n}\n\n\nvoid CheckNumberOfSamplesInBin(const char *name, int num_smpl_in_bin, int total_num_smpl, double p_of_bin, double number_of_sigmas_threshold, double p_of_bin_error)\n{\n  double mean, sigma;\n  std::tie(mean, sigma) = BinomialDistributionMeanStdev(total_num_smpl, p_of_bin, p_of_bin_error);\n  std::stringstream additional_output;\n  if (name)\n    additional_output << \"Expected in \" << name << \": \" << mean << \"+/-\" << sigma << \" Actual: \" << num_smpl_in_bin << \" of \" << total_num_smpl << std::endl;\n  EXPECT_NEAR(num_smpl_in_bin, mean, sigma*number_of_sigmas_threshold) << additional_output.str();\n}\n\n\nnamespace ChiSqrInternal\n{\n\nstruct Bin {\n  double count;\n  double expected;\n};\n\n\n// TODO: I wish I had a super lightweight range checked (in debug mode only ofc.) array view.\n\nvoid MergeBinsToGetAboveMinNumSamplesCutoff(Bin *bins, int &num_bins, double low_expected_num_samples_cutoff)\n{\n  //http://en.cppreference.com/w/cpp/algorithm/make_heap\n  // ... and so on.\n  auto cmp = [](const Bin &a, const Bin &b) -> bool { return a.expected > b.expected; }; // Using > instead of < makes it a min-heap.\n  std::make_heap(bins, bins+num_bins, cmp);\n  while (num_bins > 1)\n  {\n    // Get smallest element to the end.\n    std::pop_heap(bins, bins+num_bins, cmp);\n    if (bins[num_bins-1].expected > low_expected_num_samples_cutoff)\n      break;\n    // Get the second smallest element to the second last position.\n    std::pop_heap(bins, bins+num_bins-1, cmp);\n    // Merge them.\n    Bin &merged = bins[num_bins-2];\n    Bin &removed = bins[num_bins-1];\n    merged.count += removed.count;\n    merged.expected += removed.expected;\n    removed.count = 0;\n    removed.expected = 0;\n    --num_bins; \n    // Modifications done. Get last element back into heap.\n    std::push_heap(bins, bins+num_bins, cmp);\n  }\n  assert(num_bins >= 1);\n  assert((num_bins == 1) || (bins[num_bins-1].expected > low_expected_num_samples_cutoff));\n}\n\n}\n\n\ndouble ChiSquaredProbability(const int *counts, const double *weights, int num_bins, double low_expected_num_samples_cutoff)\n{\n  using namespace ChiSqrInternal;\n  \n  int num_samples = std::accumulate(counts, counts+num_bins, 0); // It's the sum.\n  double probability_normalization = std::accumulate(weights, weights+num_bins, 0.);\n\n  probability_normalization = probability_normalization>0. ? 1./probability_normalization : 0.;\n  \n  std::unique_ptr<Bin[]> bins{new Bin[num_bins]};\n  for (int i=0; i<num_bins; ++i)\n    bins[i] = Bin{(double)counts[i], weights[i]*num_samples*probability_normalization};\n\n  int original_num_bins = num_bins;\n  MergeBinsToGetAboveMinNumSamplesCutoff(bins.get(), num_bins, low_expected_num_samples_cutoff);\n  \n  //std::cout << \"Chi Sqr bins: \" << num_bins << std::endl;\n  double chi_sqr = 0.;\n  for (int i=0; i<num_bins; ++i)\n  {\n    //std::cout << strconcat(i, \": e=\", bins[i].expected, \", cnt=\",bins[i].count) << std::endl;\n    chi_sqr += Sqr(bins[i].count - bins[i].expected)/bins[i].expected;\n  }\n\n  if (original_num_bins > num_bins*3)\n  {\n    std::cout << \"Chi-Sqr Test merged \" << (original_num_bins-num_bins) << \" of \" << original_num_bins << \" bins because their sample count was below \" << low_expected_num_samples_cutoff << std::endl;\n  }\n  \n  // https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/math_toolkit/dist_ref/dists/chi_squared_dist.html\n  // https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/math_toolkit/dist_ref/nmp.html#math_toolkit.dist_ref.nmp.cdf\n  boost::math::chi_squared_distribution<double> distribution(num_bins-1);\n  double prob_observe_ge_chi_sqr = cdf(complement(distribution, chi_sqr));\n  \n  //std::cout << \"chi-sqr prob = \" << prob_observe_ge_chi_sqr << std::endl;\n  //EXPECT_GE(prob_observe_ge_chi_sqr, p_threshold);\n  return prob_observe_ge_chi_sqr;  \n}\n\n\ndouble StddevOfAverage(double sample_stddev, int num_samples)\n{\n  return sample_stddev / std::sqrt(num_samples);\n}\n\n\ndouble StddevOfStddev(double sample_stddev, int num_samples)\n{\n  return std::sqrt(2. / (num_samples - 1))*Sqr(sample_stddev);\n}\n\n\ndouble StudentsTValue(double sample_avg, double avg_stddev, double true_mean)\n{\n  return (sample_avg - true_mean) / avg_stddev;\n}\n\n\ndouble StudentsTDistributionOutlierProbability(double t, double num_samples)\n{\n  boost::math::students_t_distribution<double> distribution(num_samples);\n  if (t > 0.)\n    return cdf(complement(distribution, t));\n  else\n    return cdf(distribution, t);\n}\n\n\nvoid TestSampleAverage(double sample_avg, double sample_stddev, double num_samples, double true_mean, double true_mean_error, double p_value)\n{\n  double avg_stddev = StddevOfAverage(sample_stddev, num_samples);\n  if (avg_stddev > 0.)\n  {\n    double prob;\n    // Normally I would use the probability of the distance greater than |(sample_avg - true_mean)| w.r.t. to a normal distribution.\n    // I use normal distribution rather than t-test stuff because I have a lot of samples.\n    // However, since I also have integration errors, I \"split\" the normal distribution in half and move both sides to the edges of\n    // the integration error bounds. Clearly, I the MC estimate is very good, I want to check if sample_avg is precisely within the \n    // integration bounds. On the other hand, if the integration error is zero, I want to use the usual normal distribution as \n    // stated above. My scheme here achives both of these edge cases.\n    if (sample_avg < true_mean - true_mean_error)\n      prob = StudentsTDistributionOutlierProbability(StudentsTValue(sample_avg, avg_stddev, true_mean - true_mean_error), num_samples);\n    else if(sample_avg > true_mean + true_mean_error)\n      prob = StudentsTDistributionOutlierProbability(StudentsTValue(sample_avg, avg_stddev, true_mean + true_mean_error), num_samples);\n    else\n      prob = StudentsTDistributionOutlierProbability(0., num_samples);\n    EXPECT_GE(prob, p_value) << \"Probability to find sample average \" << sample_avg << \" +/- \" << avg_stddev << \" w.r.t. true mean \" << true_mean << \"+/-\" << true_mean_error << \n    \" is \" << prob << \" which is lower than p-value \" << p_value << std::endl;\n    //std::cout << \"Test Sample Avg Prob = \" << prob << std::endl;\n  }\n  else\n  {\n    EXPECT_NEAR(sample_avg, true_mean, true_mean_error);\n  }\n}\n\n\nvoid TestProbabilityOfMeanLowerThanUpperBound(double sample_avg, double sample_stddev, double num_samples, double bound, double p_value)\n{\n  double avg_stddev = StddevOfAverage(sample_stddev, num_samples);\n  if (avg_stddev > 0.)\n  {\n    boost::math::students_t_distribution<double> distribution(num_samples);\n    double prob = cdf(complement(distribution, StudentsTValue(sample_avg, avg_stddev, bound)));\n    EXPECT_GE(prob, p_value) << \"Probability to find the mean smaller than \" << bound << \" is \" << prob << \" which is lower than the p-value \" << p_value << \", given the average \" << sample_avg << \" +/- \" << avg_stddev << std::endl;\n    //std::cout << \"Test Prob Upper Bound = \" << prob << std::endl;\n  }\n  else\n  {\n    EXPECT_LE(sample_avg, bound);\n  }\n}\n\n\n\n\nTEST(BinomialDistribution, WithIntervals)\n{\n  double mean1, stddev1;\n  double mean2, stddev2;\n  std::tie(mean1, stddev1) = BinomialDistributionMeanStdev(10, 0.6);\n  std::tie(mean2, stddev2) = BinomialDistributionMeanStdev(10, 0.6, 0.);\n  EXPECT_NEAR(mean1, mean2, 1.e-9);\n  EXPECT_NEAR(stddev1, stddev2, 1.e-9);\n}\n", "meta": {"hexsha": "91cb20933c9084b5794eb990ea44932e490d2614", "size": 8446, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/tests_stats.cxx", "max_stars_repo_name": "DaWelter/NaiveTrace", "max_stars_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T08:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T06:19:16.000Z", "max_issues_repo_path": "src/tests_stats.cxx", "max_issues_repo_name": "DaWelter/NaiveTrace", "max_issues_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "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": "src/tests_stats.cxx", "max_forks_repo_name": "DaWelter/NaiveTrace", "max_forks_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.045045045, "max_line_length": 232, "alphanum_fraction": 0.7120530429, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.661408845846015}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\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// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n\n#include <boost/compute/algorithm/copy.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/functional/operator.hpp>\n\nnamespace compute = boost::compute;\n\n// this example demonstrates how to use Boost.Compute's STL\n// implementation to add two vectors on the GPU\nint main()\n{\n    // setup input arrays\n    float a[] = { 1, 2, 3, 4 };\n    float b[] = { 5, 6, 7, 8 };\n\n    // make space for the output\n    float c[] = { 0, 0, 0, 0 };\n\n    // create vectors and transfer data for the input arrays 'a' and 'b'\n    compute::vector<float> vector_a(a, a + 4);\n    compute::vector<float> vector_b(b, b + 4);\n\n    // create vector for the output array\n    compute::vector<float> vector_c(4);\n\n    // add the vectors together\n    compute::transform(\n        vector_a.begin(),\n        vector_a.end(),\n        vector_b.begin(),\n        vector_c.begin(),\n        compute::plus<float>()\n    );\n\n    // transfer results back to the host array 'c'\n    compute::copy(vector_c.begin(), vector_c.end(), c);\n\n    // print out results in 'c'\n    std::cout << \"c: [\" << c[0] << \", \"\n                        << c[1] << \", \"\n                        << c[2] << \", \"\n                        << c[3] << \"]\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "ffd9fd8146e4f0cdc5a50585ca273802923f51c6", "size": 1743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/vector_addition.cpp", "max_stars_repo_name": "bastiankoe/compute", "max_stars_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "example/vector_addition.cpp", "max_issues_repo_name": "bastiankoe/compute", "max_issues_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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/vector_addition.cpp", "max_forks_repo_name": "bastiankoe/compute", "max_forks_repo_head_hexsha": "57eec36d20e122a496d3fbfddf8bf4ad8d6f4a4f", "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.0517241379, "max_line_length": 79, "alphanum_fraction": 0.5415949512, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6614088284993181}}
{"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_LDEXP_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LDEXP_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing ldexp capabilities\n\n    The function multiply a floating entry \\f$x\\f$\n    by \\f$2^{n}\\f$\n\n\n    @par Semantic:\n\n    @code\n    auto r = ldexp(x,n);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto r = x*pow(2, trunc(n));\n    @endcode\n\n    @par Decorators\n\n    By default @c ldexp does not take care of denormal or limiting values. Use the @c pedantic_ decorator if these are\n    to be properly computed.\n\n    The @ref cardinal_of and the size of elements value of the types of @c x and @c n must be identical\n\n  **/\n  Value ldexp(Value const & x, Value const& n);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ldexp.hpp>\n#include <boost/simd/function/simd/ldexp.hpp>\n\n#endif\n", "meta": {"hexsha": "0077480ab80966f99eba692f8cd16324e30a57db", "size": 1293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/ldexp.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/ldexp.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/ldexp.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": 23.5090909091, "max_line_length": 118, "alphanum_fraction": 0.5901005414, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6614088208488468}}
{"text": "#include \"Sphere.h\"\n#include \"Ray.h\"\n#include \"Intersection.h\"\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\nstd::unique_ptr<Intersection> Sphere::intersect(const Ray& ray) {\n    auto p = ray.p - center;\n    auto d = ray.d;\n\n    float dp = d.dot(p);\n    float dd = d.dot(d);\n    float pp = p.dot(p);\n\n    float discr = (dp*dp) - (dd*(pp-(radius*radius)));\n\n    if (discr < 0) {\n        return nullptr;\n    } else {\n        // Find both intersections\n        float t0 = (-dp - sqrt(discr)) / dd;\n        float t1 = (-dp + sqrt(discr)) / dd;\n\n        // Entire sphere is behind camera\n        if (t1 < 0)\n            return nullptr;\n\n        // Front of sphere is behind camera\n        float t = t0 < 0 ? t1 : t0;\n\n        // Calculate surface normal\n        auto n = (ray.evaluate(t) - center).normalized();\n\n        return std::unique_ptr<Intersection>(new Intersection(this, n, t));\n    }\n}\n", "meta": {"hexsha": "6395e3dba96bc9c51b37108f46f6b9445ef306d8", "size": 889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Sphere.cpp", "max_stars_repo_name": "fmenozzi/raytracer", "max_stars_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:51.000Z", "max_issues_repo_path": "src/Sphere.cpp", "max_issues_repo_name": "fmenozzi/raytracer", "max_issues_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_issues_repo_licenses": ["MIT"], "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/Sphere.cpp", "max_forks_repo_name": "fmenozzi/raytracer", "max_forks_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_forks_repo_licenses": ["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.7948717949, "max_line_length": 75, "alphanum_fraction": 0.5534308211, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6613978536098015}}
{"text": "#ifndef BOOST_UBLAS_DAVIDON_FLETCHER_POWELL_HPP\n#define BOOST_UBLAS_DAVIDON_FLETCHER_POWELL_HPP\n\n#include <cfloat> // DBL_EPSILON\n#include <boost/assert.hpp>\n#include \"function.hpp\"\n\nnamespace boost {\n    namespace numeric {\n        namespace ublas {\n            namespace details {\n\n                template <class T>\n                T find_min(const Function<T> & f, const vector<T> & x, vector<T> const & d, T a, T b, const double eps = 1E-8) {\n                    T e = 0;\n                    T x_1 = T(0);\n                    T x_2 = T(0);\n\n                    while (std::abs(b - a) >= eps) {\n                        e = (b - a) * 1E-2 * 1E-3;\n                        x_1 = (b + a) / 2 - e;\n                        x_2 = (b + a) / 2 + e;\n\n                        if (f(x + x_1 * d) > f(x + x_2 * d)) {\n                            a = x_1;\n                        }\n                        else {\n                            b = x_2;\n                        }\n                    }\n                    return (a + b) / 2;\n                }\n            } /* namespace details */\n\n            template <class T>\n            vector<T> DavidonFletcherPowell(const Function<T> & f, vector<T> x, const double epsilon, std::size_t & number_iteration) {\n                BOOST_ASSERT(f.function);\n                BOOST_ASSERT(f.gradient);\n\n                vector<T> grad(f.gradient(x));\n                matrix<T> eta(identity_matrix<T>(f.size));\n\n                vector<T> old_x = x;\n                vector<T> old_grad = grad;\n\n                vector<T> d;\n                T alpha = T(0);\n\n                vector<T> delta_x;\n                vector<T> delta_g;\n                matrix<T> A;\n                matrix<T> B;\n\n                for (; ublas::norm_2(grad) >= epsilon && number_iteration < 1E6; old_x = x, old_grad = grad, ++number_iteration) {\n                    d = -prod(eta, grad);\n\n                    // Looking for the minimum of F(x - alpha * d) using the method of one-dimensional optimization.\n                    alpha = details::find_min(f, x, d, T(0.0), T(1E3));\n                    BOOST_ASSERT(alpha >= DBL_EPSILON);\n\n                    x = x + alpha * d;\n                    grad = f.gradient(x);\n\n                    delta_x = x - old_x;\n                    delta_g = grad - old_grad;\n\n                    A = (outer_prod(delta_x, delta_x) / inner_prod(delta_x, delta_g));\n\n                    B = prod(outer_prod(static_cast<vector<T>>(prod(eta, delta_g)), delta_g), trans(eta))\n                        / inner_prod(static_cast<vector<T>>(prod(static_cast<vector<T>>(prod(identity_matrix<T>(f.size), delta_g)), eta)), delta_g);\n\n                    eta = eta + A - B;\n                }\n\n                return x;\n            }\n        } /* namespace ublas */\n    } /* namespace numeric */\n} /* namespace boost */\n#endif", "meta": {"hexsha": "40df98c7ef0e9c2df6ac8bd2a4df4fa45831238f", "size": 2840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublas/Davidon_Fletcher_Powell.hpp", "max_stars_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_stars_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-07-08T03:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-26T19:19:38.000Z", "max_issues_repo_path": "boost/numeric/ublas/Davidon_Fletcher_Powell.hpp", "max_issues_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_issues_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublas/Davidon_Fletcher_Powell.hpp", "max_forks_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_forks_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5, "max_line_length": 148, "alphanum_fraction": 0.435915493, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361628580399, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6613978479414948}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n#include <vector>\n#include <unordered_map>\n#include <string>\n\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"hand_eigen_d.h\"\n#include \"../../shared/defs.h\"\n#include \"../../shared/utils.h\"\n#include \"../../shared/hand_eigen_model.h\"\n\nusing std::vector;\nusing std::unordered_map;\nusing std::string;\nusing Eigen::Map;\nusing Eigen::Vector3d;\nusing Eigen::Matrix3Xd;\nusing Eigen::Matrix4d;\nusing Eigen::aligned_allocator;\nusing Eigen::AngleAxisd;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\n\nvoid angle_axis_to_rotation_matrix_d(\n    const Vector3d& angle_axis,\n    Matrix3d* R,\n    vector<Matrix3d>* pdR)\n{\n    auto& dR = *pdR;\n    double sqnorm = angle_axis.squaredNorm();\n    double norm = sqrt(sqnorm);\n    if (norm < .0001)\n    {\n        R->setIdentity();\n        for (int i = 0; i < 3; i++)\n            dR[i].setZero();\n        return;\n    }\n    double inv_norm = 1. / norm;\n    double inv_sqnorm = 1. / sqnorm;\n    Vector3d d_norm = angle_axis * inv_norm;\n\n    double x = angle_axis(0) * inv_norm;\n    double y = angle_axis(1) * inv_norm;\n    double z = angle_axis(2) * inv_norm;\n    Vector3d dx, dy, dz;\n    for (int i = 0; i < 3; i++)\n    {\n        dx(i) = -angle_axis(0) * d_norm(i) * inv_sqnorm;\n        dy(i) = -angle_axis(1) * d_norm(i) * inv_sqnorm;\n        dz(i) = -angle_axis(2) * d_norm(i) * inv_sqnorm;\n    }\n    dx(0) += norm * inv_sqnorm;\n    dy(1) += norm * inv_sqnorm;\n    dz(2) += norm * inv_sqnorm;\n\n    double s = sin(norm);\n    double c = cos(norm);\n    Vector3d dc, ds;\n    ds = c * d_norm;\n    dc = -s * d_norm;\n\n    *R << x * x + (1 - x * x) * c, x* y* (1 - c) - z * s, x* z* (1 - c) + y * s,\n        x* y* (1 - c) + z * s, y* y + (1 - y * y) * c, y* z* (1 - c) - x * s,\n        x* z* (1 - c) - y * s, z* y* (1 - c) + x * s, z* z + (1 - z * z) * c;\n\n    for (int i = 0; i < 3; i++)\n    {\n        dR[i] << 2 * x * dx(i) - 2 * x * dx(i) * c + (1 - x * x) * dc(i),\n            dx(i) * y * (1 - c) + x * dy(i) * (1 - c) - x * y * dc(i) - dz(i) * s - z * ds(i),\n            dx(i) * z * (1 - c) + x * dz(i) * (1 - c) - x * z * dc(i) + dy(i) * s + y * ds(i),\n            dx(i)* y* (1 - c) + x * dy(i) * (1 - c) - x * y * dc(i) + dz(i) * s + z * ds(i),\n            2 * y * dy(i) - 2 * y * dy(i) * c + (1 - y * y) * dc(i),\n            dy(i) * z * (1 - c) + y * dz(i) * (1 - c) - y * z * dc(i) - dx(i) * s - x * ds(i),\n            dx(i)* z* (1 - c) + x * dz(i) * (1 - c) - x * z * dc(i) - dy(i) * s - y * ds(i),\n            dz(i)* y* (1 - c) + z * dy(i) * (1 - c) - z * y * dc(i) + dx(i) * s + x * ds(i),\n            2 * z * dz(i) - 2 * z * dz(i) * c + (1 - z * z) * dc(i);\n    }\n}\n\nvoid apply_global_transform_d(\n    const vector<int>& corresp,\n    const Matrix3Xd& pose_params,\n    Matrix3Xd* ppositions,\n    double* pJ,\n    Matrix3d* pR)\n{\n    auto& R = *pR;\n    auto& positions = *ppositions;\n    vector<Matrix3d> dR(3);\n    const Vector3d& global_rotation = pose_params.col(0);\n    angle_axis_to_rotation_matrix_d(global_rotation, &R, &dR);\n    R.noalias() = (R.array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n    for (int i = 0; i < 3; i++)\n        dR[i].noalias() = (dR[i].array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n\n    // global rotation\n    size_t npts = corresp.size();\n    for (int i_param = 0; i_param < 3; i_param++)\n    {\n        Map<Matrix3Xd> J_glob_rot(&pJ[i_param * 3 * npts], 3, npts);\n        for (size_t i_pt = 0; i_pt < npts; i_pt++)\n        {\n            J_glob_rot.col(i_pt).noalias() = -dR[i_param] * positions.col(corresp[i_pt]);\n        }\n    }\n\n    // global translation\n    Map<MatrixXd> J_glob_translation(&pJ[3 * 3 * npts], 3 * npts, 3);\n    for (size_t i = 0; i < npts; i++)\n    {\n        J_glob_translation.middleRows(i * 3, 3).setIdentity();\n    }\n    J_glob_translation *= -1.;\n\n    positions = (R * positions).colwise() + pose_params.col(2);\n}\n\nvoid apply_global_transform_d(\n    const double* const us,\n    const vector<Triangle>& triangles,\n    const vector<int>& corresp,\n    const Matrix3Xd& pose_params,\n    Matrix3Xd* ppositions,\n    double* pJ,\n    Matrix3d* pR)\n{\n    auto& R = *pR;\n    auto& positions = *ppositions;\n    vector<Matrix3d> dR(3);\n    const Vector3d& global_rotation = pose_params.col(0);\n    angle_axis_to_rotation_matrix_d(global_rotation, &R, &dR);\n    R.noalias() = (R.array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n    for (int i = 0; i < 3; i++)\n        dR[i].noalias() = (dR[i].array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n\n    // global rotation\n    size_t npts = corresp.size();\n    for (int i_param = 0; i_param < 3; i_param++)\n    {\n        Map<Matrix3Xd> J_glob_rot(&pJ[i_param * 3 * npts], 3, npts);\n        for (size_t i_pt = 0; i_pt < npts; i_pt++)\n        {\n            const auto& verts = triangles[corresp[i_pt]].verts;\n            const double* const u = &us[2 * i_pt];\n\n            Vector3d tmp = u[0] * positions.col(verts[0]) + u[1] * positions.col(verts[1])\n                + (1. - u[0] - u[1]) * positions.col(verts[2]);\n\n            J_glob_rot.col(i_pt).noalias() = -dR[i_param] * tmp;\n        }\n    }\n\n    // global translation\n    Map<MatrixXd> J_glob_translation(&pJ[3 * 3 * npts], 3 * npts, 3);\n    for (size_t i = 0; i < npts; i++)\n    {\n        J_glob_translation.middleRows(i * 3, 3).setIdentity();\n    }\n    J_glob_translation *= -1.;\n\n    positions = (R * positions).colwise() + pose_params.col(2);\n}\n\nvoid relatives_to_absolutes_d(\n    const avector<Matrix4d>& relatives,\n    const avector<Matrix4d>& relatives_d,\n    const vector<int>& parents,\n    avector<Matrix4d>* pabsolutes,\n    vector<avector<Matrix4d>>* pabsolutes_d)\n{\n    auto& absolutes = *pabsolutes;\n    auto& absolutes_d = *pabsolutes_d;\n    absolutes.resize(parents.size());\n    absolutes_d.resize(parents.size());\n    int rel_d_tail = 0;\n    for (size_t i = 0; i < parents.size(); i++)\n    {\n        if (parents[i] == -1)\n            absolutes[i].noalias() = relatives[i];\n        else\n            absolutes[i].noalias() = absolutes[parents[i]] * relatives[i];\n\n        int n_finger_bone = (i - 1) % 4;\n        if (i > 0 && i < parents.size() - 1 && n_finger_bone > 0)\n        {\n            absolutes_d[i].resize(n_finger_bone + 1);\n            int curr_tail = 0;\n\n            for (const auto& absolute_d_parent : absolutes_d[parents[i]])\n                absolutes_d[i][curr_tail++].noalias() = absolute_d_parent * relatives[i];\n\n            absolutes_d[i][curr_tail++].noalias() = absolutes[parents[i]] * relatives_d[rel_d_tail++];\n            if (n_finger_bone == 1)\n                absolutes_d[i][curr_tail++].noalias() = absolutes[parents[i]] * relatives_d[rel_d_tail++];\n        }\n    }\n}\n\nvoid euler_angles_to_rotation_matrix(\n    const Vector3d& xzy,\n    Matrix3d* pR,\n    Matrix3d* pdR0,\n    Matrix3d* pdR1)\n{\n    double tx = xzy(0), ty = xzy(2), tz = xzy(1);\n    Matrix3d Rx = Matrix3d::Identity(),\n        Ry = Matrix3d::Identity(),\n        Rz = Matrix3d::Identity();\n    Rx(1, 1) = cos(tx);\n    Rx(2, 1) = sin(tx);\n    Rx(1, 2) = -Rx(2, 1);\n    Rx(2, 2) = Rx(1, 1);\n\n    Ry(0, 0) = cos(ty);\n    Ry(0, 2) = sin(ty);\n    Ry(2, 0) = -Ry(0, 2);\n    Ry(2, 2) = Ry(0, 0);\n\n    Rz(0, 0) = cos(tz);\n    Rz(1, 0) = sin(tz);\n    Rz(0, 1) = -Rz(1, 0);\n    Rz(1, 1) = Rz(0, 0);\n\n    Matrix3d RzRy = Rz * Ry;\n    if (pdR0)\n    {\n        Matrix3d dRx = Matrix3d::Zero();\n        dRx(1, 1) = -Rx(2, 1);\n        dRx(2, 1) = Rx(1, 1);\n        dRx(1, 2) = -dRx(2, 1);\n        dRx(2, 2) = dRx(1, 1);\n        pdR0->noalias() = RzRy * dRx;\n    }\n    if (pdR1)\n    {\n        Matrix3d dRz = Matrix3d::Zero();\n        dRz(0, 0) = -Rz(1, 0);\n        dRz(1, 0) = Rz(0, 0);\n        dRz(0, 1) = -dRz(1, 0);\n        dRz(1, 1) = dRz(0, 0);\n        pdR1->noalias() = dRz * Ry * Rx;\n    }\n\n    pR->noalias() = RzRy * Rx;\n}\n\nvoid get_posed_relatives_d(\n    const HandModelEigen& model,\n    const Matrix3Xd& pose_params,\n    avector<Matrix4d>* prelatives,\n    avector<Matrix4d>* prelatives_d)\n{\n    auto& relatives = *prelatives;\n    auto& relatives_d = *prelatives_d;\n    relatives.resize(model.base_relatives.size());\n    relatives_d.resize(4 * 5); // 4 parameters in every finger\n\n    int offset = 3;\n    int tail = 0;\n    for (size_t i = 0; i < model.bone_names.size(); i++)\n    {\n        Matrix4d tr = Matrix4d::Identity();\n\n        Matrix3d R;\n        int n_finger_bone = (i - 1) % 4;\n        if (i == 0 || i == model.bone_names.size() - 1 || n_finger_bone == 0)\n        {\n            euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R);\n        }\n        else\n        {\n            Matrix4d dtr0 = Matrix4d::Zero();\n            Matrix3d dR0;\n            if (n_finger_bone == 1)\n            {\n                Matrix4d dtr1 = Matrix4d::Zero();\n                Matrix3d dR1;\n                euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R, &dR0, &dR1);\n                dtr1.block(0, 0, 3, 3) = dR1;\n                relatives_d[tail + 1].noalias() = model.base_relatives[i] * dtr1;\n            }\n            else\n                euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R, &dR0);\n            dtr0.block(0, 0, 3, 3) = dR0;\n            relatives_d[tail++].noalias() = model.base_relatives[i] * dtr0;\n            if (n_finger_bone == 1)\n                tail++;\n        }\n        tr.block(0, 0, 3, 3) = R;\n\n        relatives[i].noalias() = model.base_relatives[i] * tr;\n    }\n}\n\nvoid get_skinned_vertex_positions_d_common(\n    const HandModelEigen& model,\n    const Matrix3Xd& pose_params,\n    const vector<int>& corresp,\n    Matrix3Xd* positions,\n    vector<Matrix3Xd>* positions_d,\n    double* pJ,\n    bool apply_global)\n{\n    avector<Matrix4d> relatives, absolutes, transforms;\n    avector<Matrix4d> relatives_d;\n    vector<avector<Matrix4d>> absolutes_d, transforms_d;\n    get_posed_relatives_d(model, pose_params, &relatives, &relatives_d);\n    relatives_to_absolutes_d(relatives, relatives_d, model.parents, &absolutes, &absolutes_d);\n\n    // Get bone transforms.\n    transforms.resize(absolutes.size());\n    transforms_d.resize(absolutes.size());\n    for (size_t i = 0; i < absolutes.size(); i++)\n    {\n        transforms[i].noalias() = absolutes[i] * model.inverse_base_absolutes[i];\n        transforms_d[i].resize(absolutes_d[i].size());\n        for (size_t j = 0; j < absolutes_d[i].size(); j++)\n            transforms_d[i][j].noalias() = absolutes_d[i][j] * model.inverse_base_absolutes[i];\n    }\n\n    // Transform vertices by necessary transforms. + apply skinning\n    *positions = Matrix3Xd::Zero(3, model.base_positions.cols());\n    positions_d->resize(4 * 5, Matrix3Xd::Zero(3, model.base_positions.cols()));\n    for (int i = 0; i < (int)transforms.size(); i++)\n    {\n        *positions +=\n            ((transforms[i] * model.base_positions.colwise().homogeneous()).array()\n                .rowwise() * model.weights.row(i)).matrix()\n            .topRows(3);\n\n        int i_finger = (i - 1) / 4;\n        for (int j = 0; j < (int)transforms_d[i].size(); j++)\n        {\n            int i_param = j + 4 * i_finger;\n            (*positions_d)[i_param] +=\n                ((transforms_d[i][j] * model.base_positions.colwise().homogeneous()).array()\n                    .rowwise() * model.weights.row(i)).matrix()\n                .topRows(3);\n        }\n    }\n\n    if (model.is_mirrored)\n        positions->row(0) = -positions->row(0);\n}\n\nvoid get_skinned_vertex_positions_d(\n    const HandModelEigen& model,\n    const Matrix3Xd& pose_params,\n    const vector<int>& corresp,\n    Matrix3Xd* positions,\n    double* pJ,\n    bool apply_global)\n{\n    vector<Matrix3Xd> positions_d;\n    get_skinned_vertex_positions_d_common(model, pose_params, corresp, positions,\n        &positions_d, pJ, apply_global);\n\n    Matrix3d Rglob = Matrix3d::Identity();\n    if (apply_global)\n        apply_global_transform_d(corresp, pose_params, positions, pJ, &Rglob);\n\n    // finger parameters\n    size_t ncorresp = corresp.size();\n    for (int i = 0; i < 4 * 5; i++)\n    {\n        Map<Matrix3Xd> curr_J(&pJ[(6 + i) * 3 * ncorresp], 3, ncorresp);// 6 is offset (global params)\n        for (int j = 0; j < curr_J.cols(); j++)\n        {\n            curr_J.col(j).noalias() = -Rglob * positions_d[i].col(corresp[j]);\n        }\n    }\n}\n\nvoid get_skinned_vertex_positions_d(\n    const double* const us,\n    const HandModelEigen& model,\n    const Matrix3Xd& pose_params,\n    const vector<int>& corresp,\n    Matrix3Xd* positions,\n    double* pJ,\n    bool apply_global)\n{\n    vector<Matrix3Xd> positions_d;\n\n    get_skinned_vertex_positions_d_common(model, pose_params, corresp, positions,\n        &positions_d, pJ, apply_global);\n\n    Matrix3d Rglob = Matrix3d::Identity();\n    if (apply_global)\n        apply_global_transform_d(us, model.triangles, corresp, pose_params, positions, pJ, &Rglob);\n\n    // finger parameters\n    size_t ncorresp = corresp.size();\n    Vector3d tmp;\n    for (int i = 0; i < 4 * 5; i++)\n    {\n        Map<Matrix3Xd> curr_J(&pJ[(6 + i) * 3 * ncorresp], 3, ncorresp); // 6 is offset (global params)\n        for (int j = 0; j < curr_J.cols(); j++)\n        {\n            const auto& verts = model.triangles[corresp[j]].verts;\n            const double* const u = &us[2 * j];\n\n            tmp = u[0] * positions_d[i].col(verts[0]) + u[1] * positions_d[i].col(verts[1])\n                + (1. - u[0] - u[1]) * positions_d[i].col(verts[2]);\n\n            curr_J.col(j).noalias() = -Rglob * tmp;\n        }\n    }\n}\n\nvoid to_pose_params_d(const double* const theta,\n    const vector<string>& bone_names,\n    Matrix3Xd* ppose_params)\n{\n    auto& pose_params = *ppose_params;\n    pose_params.resize(3, bone_names.size() + 3);\n    pose_params.setZero();\n\n    pose_params.col(0) = Map<const Vector3d>(&theta[0]);\n    pose_params.col(1).setOnes();\n    pose_params.col(2) = Map<const Vector3d>(&theta[3]);\n\n    int i_theta = 6;\n    int i_pose_params = 5;\n    int n_fingers = 5;\n    for (int i_finger = 0; i_finger < n_fingers; i_finger++)\n    {\n        for (int i = 2; i <= 4; i++)\n        {\n            pose_params(0, i_pose_params) = theta[i_theta++];\n            if (i == 2)\n            {\n                pose_params(1, i_pose_params) = theta[i_theta++];\n            }\n            i_pose_params++;\n        }\n        i_pose_params++;\n    }\n}\n\nvoid hand_objective_d(\n    const double* const theta,\n    const HandDataEigen& data,\n    double* perr,\n    double* pJ)\n{\n    Matrix3Xd pose_params;\n    to_pose_params_d(theta, data.model.bone_names, &pose_params);\n\n    Matrix3Xd vertex_positions;\n    get_skinned_vertex_positions_d(data.model, pose_params, data.correspondences, &vertex_positions, pJ);\n\n    size_t npts = data.correspondences.size();\n    Map<Matrix3Xd> err(perr, 3, npts);\n    for (size_t i = 0; i < data.correspondences.size(); i++)\n    {\n        err.col(i) = data.points.col(i) - vertex_positions.col(data.correspondences[i]);\n    }\n}\n\nvoid hand_objective_d(\n    const double* const theta,\n    const double* const us,\n    const HandDataEigen& data,\n    double* perr,\n    double* pJ)\n{\n    Matrix3Xd pose_params;\n    to_pose_params_d(theta, data.model.bone_names, &pose_params);\n\n    size_t npts = data.correspondences.size();\n    Matrix3Xd vertex_positions;\n    get_skinned_vertex_positions_d(us, data.model, pose_params, data.correspondences, &vertex_positions, &pJ[2 * 3 * npts]);\n\n    Map<Matrix3Xd> err(perr, 3, npts);\n    Map<Matrix3Xd> du0(&pJ[0], 3, npts), du1(&pJ[3 * npts], 3, npts);\n    Vector3d hand_point;\n    for (size_t i = 0; i < data.correspondences.size(); i++)\n    {\n        const auto& verts = data.model.triangles[data.correspondences[i]].verts;\n        const double* const u = &us[2 * i];\n\n        du0.col(i) = -(vertex_positions.col(verts[0]) - vertex_positions.col(verts[2]));\n        du1.col(i) = -(vertex_positions.col(verts[1]) - vertex_positions.col(verts[2]));\n\n        hand_point = u[0] * vertex_positions.col(verts[0]) + u[1] * vertex_positions.col(verts[1])\n            + (1. - u[0] - u[1]) * vertex_positions.col(verts[2]);\n        err.col(i) = data.points.col(i) - hand_point;\n    }\n}\n", "meta": {"hexsha": "2717dc3f8bfb8efcba7fba0e49d56d98a3a0774f", "size": 16107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_stars_repo_name": "dsyme/ADBench", "max_stars_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T16:22:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T12:26:51.000Z", "max_issues_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_issues_repo_name": "dsyme/ADBench", "max_issues_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2019-05-25T07:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T13:55:33.000Z", "max_forks_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_forks_repo_name": "dsyme/ADBench", "max_forks_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T16:37:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T10:14:37.000Z", "avg_line_length": 32.4737903226, "max_line_length": 124, "alphanum_fraction": 0.5641646489, "num_tokens": 5201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6613525305890846}}
{"text": "// Copyright (C) 2017  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/global_optimization.h>\n#include <dlib/statistics.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include <dlib/rand.h>\n\n#include \"tester.h\"\n\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.global_optimization\");\n\n// ----------------------------------------------------------------------------------------\n\n    void test_upper_bound_function(double relative_noise_magnitude, double solver_eps)\n    {\n        print_spinner();\n\n        dlog << LINFO << \"test_upper_bound_function,  relative_noise_magnitude=\"<< relative_noise_magnitude  << \", solver_eps=\" << solver_eps;\n\n        auto rosen = [](const matrix<double,0,1>& x) { return -1*( 100*std::pow(x(1) - x(0)*x(0),2.0) + std::pow(1 - x(0),2)); };\n\n        dlib::rand rnd;\n        auto make_rnd = [&rnd]() { matrix<double,0,1> x(2); x = 2*rnd.get_random_double(), 2*rnd.get_random_double(); return x; };\n\n\n        std::vector<function_evaluation> evals;\n        for (int i = 0; i < 100; ++i)\n        {\n            auto x = make_rnd();\n            evals.emplace_back(x,rosen(x));\n        }\n\n        upper_bound_function ub(evals, relative_noise_magnitude, solver_eps);\n        DLIB_TEST(ub.num_points() == (long)evals.size());\n        DLIB_TEST(ub.dimensionality() == 2);\n        for (auto& ev : evals)\n        {\n            dlog << LINFO << ub(ev.x) - ev.y;\n            DLIB_TEST_MSG(ub(ev.x) - ev.y > -1e10, ub(ev.x) - ev.y);\n        }\n\n\n        for (int i = 0; i < 100; ++i)\n        {\n            auto x = make_rnd();\n            evals.emplace_back(x,rosen(x));\n            ub.add(evals.back());\n        }\n\n        DLIB_TEST(ub.num_points() == (long)evals.size());\n        DLIB_TEST(ub.dimensionality() == 2);\n\n        for (auto& ev : evals)\n        {\n            dlog << LINFO << ub(ev.x) - ev.y;\n            DLIB_TEST_MSG(ub(ev.x) - ev.y > -1e10, ub(ev.x) - ev.y);\n        }\n\n\n        if (solver_eps < 0.001)\n        {\n            dlog << LINFO << \"out of sample points: \";\n            for (int i = 0; i < 10; ++i)\n            {\n                auto x = make_rnd();\n                dlog << LINFO << ub(x) - rosen(x);\n                DLIB_TEST_MSG(ub(x) - rosen(x) > 1e-10, ub(x) - rosen(x));\n            }\n        }\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    double complex_holder_table ( double x0, double x1)\n    {\n        // The regular HolderTable function\n        //return -std::abs(sin(x0)*cos(x1)*exp(std::abs(1-std::sqrt(x0*x0+x1*x1)/pi)));\n\n        // My more complex version of it with discontinuities and more local minima.\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        // HolderTable function tilted towards 10,10\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// ----------------------------------------------------------------------------------------\n\n    void test_global_function_search()\n    {\n\n        function_spec spec{{-10,-10}, {10,10}};\n        function_spec spec2{{-10,-10, -50}, {10,10, 50}};\n        global_function_search opt({spec, spec, spec2});\n\n        dlib::rand rnd;\n        bool found_optimal_point = false;\n        for (int i = 0; i < 400 && !found_optimal_point; ++i)\n        {\n            print_spinner();\n            std::vector<function_evaluation_request> nexts;\n            for (int k = 0; k < rnd.get_integer_in_range(1,4); ++k)\n                nexts.emplace_back(opt.get_next_x());\n\n            for (auto& next : nexts)\n            {\n                switch (next.function_idx())\n                {\n                    case 0: next.set( -complex_holder_table(next.x()(0), next.x()(1))); break;\n                    case 1: next.set( -10*complex_holder_table(next.x()(0), next.x()(1))); break;\n                    case 2: next.set( -2*complex_holder_table(next.x()(0), next.x()(1))); break;\n                    default: DLIB_TEST(false); break;\n                }\n\n                matrix<double,0,1> x;\n                double y;\n                size_t function_idx;\n                opt.get_best_function_eval(x,y,function_idx);\n                /*\n                cout << \"\\ni: \"<< i << endl;\n                cout << \"best eval x: \"<< trans(x);\n                cout << \"best eval y: \"<< y << endl;\n                cout << \"best eval function index: \"<< function_idx << endl;\n                */\n\n                if (std::abs(y  - 10*21.9210397) < 0.0001)\n                {\n                    found_optimal_point = true;\n                    break;\n                }\n            }\n        }\n\n        DLIB_TEST(found_optimal_point);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_find_max_global(\n    )\n    {\n        print_spinner();\n        auto rosen = [](const matrix<double,0,1>& x) { return -1*( 100*std::pow(x(1) - x(0)*x(0),2.0) + std::pow(1 - x(0),2)); };\n\n        auto result = find_max_global(rosen, {0.1, 0.1}, {2, 2}, max_function_calls(100), 0);\n        matrix<double,0,1> true_x = {1,1};\n\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global(rosen, {0.1, 0.1}, {2, 2}, max_function_calls(100));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global(rosen, {0.1, 0.1}, {2, 2}, max_function_calls(100), 0, {function_evaluation({1.1, 0.9}, rosen({1.1, 0.9}))});\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global(rosen, {0.1, 0.1}, {2, 2}, std::chrono::seconds(5));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global(rosen, {0.1, 0.1}, {2, 2}, {false,false}, max_function_calls(100));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global(rosen, {0.1, 0.1}, {0.9, 0.9}, {false,false}, max_function_calls(140));\n        true_x = {0.9, 0.81};\n        dlog << LINFO << \"rosen, bounded at 0.9: \" <<  trans(result.x);\n        DLIB_TEST_MSG(max(abs(true_x-result.x)) < 1e-5, max(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_max_global([](double x){ return -std::pow(x-2,2.0); }, -10, 10, max_function_calls(10), 0);\n        dlog << LINFO << \"(x-2)^2: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 2) < 1e-9);\n        print_spinner();\n\n        result = find_max_global([](double x){ return -std::pow(x-2,2.0); }, -10, 1, max_function_calls(10));\n        dlog << LINFO << \"(x-2)^2, bound at 1: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 1) < 1e-9);\n        print_spinner();\n\n        result = find_max_global([](double x){ return -std::pow(x-2,2.0); }, -10, 1, std::chrono::seconds(2));\n        dlog << LINFO << \"(x-2)^2, bound at 1: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 1) < 1e-9);\n        print_spinner();\n\n\n        result = find_max_global([](double a, double b){ return -complex_holder_table(a,b);}, \n            {-10, -10}, {10, 10}, max_function_calls(400), 0);\n        dlog << LINFO << \"complex_holder_table y: \"<< result.y;\n        DLIB_TEST_MSG(std::abs(result.y  - 21.9210397) < 0.0001, std::abs(result.y  - 21.9210397));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_find_min_global(\n    )\n    {\n        print_spinner();\n        auto rosen = [](const matrix<double,0,1>& x) { return +1*( 100*std::pow(x(1) - x(0)*x(0),2.0) + std::pow(1 - x(0),2)); };\n\n        auto result = find_min_global(rosen, {0.1, 0.1}, {2, 2}, max_function_calls(100), 0);\n        matrix<double,0,1> true_x = {1,1};\n\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(min(abs(true_x-result.x)) < 1e-5, min(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_min_global(rosen, {0.1, 0.1}, {2, 2}, max_function_calls(100));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(min(abs(true_x-result.x)) < 1e-5, min(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_min_global(rosen, {0.1, 0.1}, {2, 2}, std::chrono::seconds(5));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(min(abs(true_x-result.x)) < 1e-5, min(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_min_global(rosen, {0.1, 0.1}, {2, 2}, {false,false}, max_function_calls(100));\n        dlog << LINFO << \"rosen: \" <<  trans(result.x);\n        DLIB_TEST_MSG(min(abs(true_x-result.x)) < 1e-5, min(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_min_global(rosen, {0, 0}, {0.9, 0.9}, {false,false}, max_function_calls(100));\n        true_x = {0.9, 0.81};\n        dlog << LINFO << \"rosen, bounded at 0.9: \" <<  trans(result.x);\n        DLIB_TEST_MSG(min(abs(true_x-result.x)) < 1e-5, min(abs(true_x-result.x)));\n        print_spinner();\n\n        result = find_min_global([](double x){ return std::pow(x-2,2.0); }, -10, 10, max_function_calls(10), 0);\n        dlog << LINFO << \"(x-2)^2: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 2) < 1e-9);\n        print_spinner();\n\n        result = find_min_global([](double x){ return std::pow(x-2,2.0); }, -10, 1, max_function_calls(10));\n        dlog << LINFO << \"(x-2)^2, bound at 1: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 1) < 1e-9);\n        print_spinner();\n\n        result = find_min_global([](double x){ return std::pow(x-2,2.0); }, -10, 1, std::chrono::seconds(2));\n        dlog << LINFO << \"(x-2)^2, bound at 1: \" <<  trans(result.x);\n        DLIB_TEST(result.x.size()==1);\n        DLIB_TEST(std::abs(result.x - 1) < 1e-9);\n        print_spinner();\n\n\n        result = find_min_global([](double a, double b){ return complex_holder_table(a,b);}, \n            {-10, -10}, {10, 10}, max_function_calls(400), 0);\n        dlog << LINFO << \"complex_holder_table y: \"<< result.y;\n        DLIB_TEST_MSG(std::abs(result.y  + 21.9210397) < 0.0001, std::abs(result.y  + 21.9210397));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class global_optimization_tester : public tester\n    {\n    public:\n        global_optimization_tester (\n        ) :\n            tester (\"test_global_optimization\",\n                    \"Runs tests on the global optimization components.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            test_upper_bound_function(0.01, 1e-6);\n            test_upper_bound_function(0.0, 1e-6);\n            test_upper_bound_function(0.0, 1e-1);\n            test_global_function_search();\n            test_find_max_global();\n            test_find_min_global();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "100c69e7dd3e4c39385cfa7fee56e5a5f4188b58", "size": 11750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/global_optimization.cpp", "max_stars_repo_name": "topin89/dlib_pipe_is_headless", "max_stars_repo_head_hexsha": "136973e56697f1a1dc0a323c03a84fa33d527bea", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-06T14:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-11T16:48:33.000Z", "max_issues_repo_path": "dlib/test/global_optimization.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "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": "dlib/test/global_optimization.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "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": 38.1493506494, "max_line_length": 142, "alphanum_fraction": 0.5093617021, "num_tokens": 3374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.7956581097540518, "lm_q1q2_score": 0.6613056997383534}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <Eigen/Dense>\n\n/** @class RobotEstimator\n *  This class implements a Kalman Filter in order to estimate a robot's current state.\n *  The estimated state is then used in motion control to assign wheel velocities accordingly\n *\n *  Explanations:\n *  - https://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/\n *  - https://en.wikipedia.org/wiki/Kalman_filter\n *  - https://www.mathworks.com/videos/series/understanding-kalman-filters.html\n */\nclass RobotEstimator {\nprivate:\n    /**\n     * Number of tracked states (number of states in state vector, x_hat)\n     *\n     * 3 Total:\n     * - X and Y: linear velocities of robot body (m/s)\n     * - W: angular velocity of robot body around z axis (rad/s)\n     */\n    static constexpr int numStates = 3;\n\n    /**\n     * Number of applied inputs (number of control inputs in control vector, u)\n     *\n     * 4 total:\n     * - Motor duty cycle for each motor (% max), controls average applied voltage\n     */\n    static constexpr int numInputs = 4;\n\n    /**\n     * Number of tracked measurable outputs (number of outputs in output vector, y)\n     *\n     * 5 total:\n     * - 4 wheel motor encoders (rad/s)\n     * - Gyro angular velocity (rad/s)\n     */\n    static constexpr int numOutputs = 5;\n\npublic:\n    /**\n     * @param dt_us Expected period of the controller in us\n     */\n    RobotEstimator(uint32_t dt_us);\n\n    /**\n     * Using the previous state and the next input\n     * We can guess where we are this time step\n     * \n     * @param u Last motor command\n     */\n    void predict(Eigen::Matrix<float, numInputs, 1> u);\n\n    /**\n     * Using the next measurements, we can move our prediction\n     * closer to the true target\n     * \n     * @param z Encoders 1-4 then gyro\n     */\n    void update(Eigen::Matrix<float, numOutputs, 1> z);\n\n    /**\n     * @param state Matrix that the current guess will be saved into\n     */\n    void getState(Eigen::Matrix<float, numStates, 1>& state);\n\nprivate:\n\n    static constexpr float processNoise = 0.05;  /**< State noise from unmodeled influences (model errors/omissions) */\n    static constexpr float encoderNoise = 0.04;  /**< Measurement noise in the encoder */\n    static constexpr float gyroNoise = 0.005;    /**< Measurement noise in the gyro */\n    static constexpr float initCovariance = 0.1; /**< The initial covariance value in each entry of `P` */\n\n    /**\n     * State Transition Matrix/Prediction Matrix\n     *\n     * Predict our next state based on our current state using dynamics\n     */\n    Eigen::Matrix<float, numStates,  numStates>  F;\n\n    /**\n     * Control Input Matrix\n     *\n     * Corrects our next state prediction by mapping control input (known influences, `u`) to our next state\n     */\n    Eigen::Matrix<float, numStates,  numInputs>  B;\n\n    /**\n     * Observation Matrix\n     *\n     * Predicts the measurements from our sensors (`z`) from our current state (`x_hat`).\n     */\n    Eigen::Matrix<float, numOutputs, numStates>  H;\n\n    /**\n     * Covariance Matrix for Process Noise\n     *\n     * A matrix whose entries are the estimated covariances between any two state variables.\n     * Entries represent uncertainty in our state vector (`x_hat`) due to unmodeled influences.\n     */\n    Eigen::Matrix<float, numStates,  numStates>  Q;\n\n    /**\n     * Covariance Matrix for Observation Noise\n     *\n     * A matrix whose entries are the estimated covariances between any two state variables.\n     * Entries represent uncertainty in our measurements (`z`) due to random noise\n     */\n    Eigen::Matrix<float, numOutputs, numOutputs> R;\n\n    /**\n     * Covariance Estimate Matrix\n     *\n     * A matrix whose entries are the estimated covariances between any two state variables.\n     * Entries represent our overall uncertainty in our state vector (`x_hat`).\n     */\n    Eigen::Matrix<float, numStates,  numStates>  P;\n\n    /**\n     * Identity Matrix\n     *\n     * A square matrix with only 1s on the diagonals\n     */\n    Eigen::Matrix<float, numStates, numStates> I;\n\n    /**\n     * Current State Vector Estimate\n     *\n     * What the robot estimator believes our current state to be\n     */\n    Eigen::Matrix<float, numStates, 1> x_hat;\n};", "meta": {"hexsha": "f49e9ad45e0b361b5f5f97a54fdbfb92091c1322", "size": 4213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_stars_repo_name": "RRRekkitRalph/robocup-firmware", "max_stars_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T11:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T00:24:02.000Z", "max_issues_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_issues_repo_name": "RRRekkitRalph/robocup-firmware", "max_issues_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 98.0, "max_issues_repo_issues_event_min_datetime": "2016-07-04T22:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T00:12:02.000Z", "max_forks_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_forks_repo_name": "RRRekkitRalph/robocup-firmware", "max_forks_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-07-07T10:50:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T11:20:28.000Z", "avg_line_length": 31.2074074074, "max_line_length": 119, "alphanum_fraction": 0.6482316639, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.6612426307355493}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n *    (See accompanying file LICENSE_1_0.txt or copy at\n *          http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#include \"../config.h\"\n#include <map>\n#include <vector>\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/dynamic_bitset.hpp>\n\n#include \"total_unimodularity.hpp\"\n#include \"combinations.hpp\"\n\nnamespace unimod\n{\n\n  /**\n   * Calculates a subdeterminant of the given matrix.\n   *\n   * @param matrix A given integer matrix\n   * @param submatrix Matrix-indices describing a submatrix\n   * @return The submatrix' determinant\n   */\n\n  int submatrix_determinant(const integer_matrix& matrix, const submatrix_indices& submatrix)\n  {\n    typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t;\n\n    assert (submatrix.rows.size() == submatrix.columns.size());\n\n    const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns);\n\n    boost::numeric::ublas::matrix <float> float_matrix(indirect_matrix);\n    boost::numeric::ublas::permutation_matrix <size_t> permutation_matrix(float_matrix.size1());\n\n    /// LU-factorize\n    int result = boost::numeric::ublas::lu_factorize(float_matrix, permutation_matrix);\n    if (result != 0)\n      return 0;\n\n    /// Calculate the determinant as a product of the diagonal entries, taking the permutation matrix into account.\n    float det = 1.0f;\n    for (size_t i = 0; i < float_matrix.size1(); ++i)\n    {\n      det *= float_matrix(i, i);\n      if (i != permutation_matrix(i))\n        det = -det;\n    }\n\n    return (int) det;\n  }\n\n  /**\n   * Checks Camion's criterion for total unimodularity.\n   *\n   * @param matrix A given integer matrix\n   * @param submatrix Matrix-indices describing a submatrix B of A\n   * @return true iff B is not Eulerian or 1^T * B * 1 = 0 (mod 4)\n   */\n\n  bool submatrix_camion(const integer_matrix& matrix, const submatrix_indices& submatrix)\n  {\n    typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t;\n\n    assert (submatrix.rows.size() == submatrix.columns.size());\n\n    const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns);\n\n    // Test whether submatrix is eulerian.\n    for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n    {\n      size_t count = 0;\n      for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n        count += indirect_matrix(row, column);\n      if (count % 2 == 1)\n        return true;\n    }\n    for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n    {\n      size_t count = 0;\n      for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n        count += indirect_matrix(row, column);\n      if (count % 2 == 1)\n        return true;\n    }\n\n    // Matrix is eulerian.\n    size_t count = 0;\n    for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n    {\n      for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n        count += indirect_matrix(row, column);\n    }\n    return (count % 4 == 0);\n  }\n\n  /**\n   * Checks all subdeterminants to test a given matrix for total unimodularity.\n   *\n   * @param matrix The given matrix\n   * @return true if and only if this matrix is totally unimdular\n   */\n\n  bool determinant_is_totally_unimodular(const integer_matrix& matrix)\n  {\n    submatrix_indices indices;\n\n    return determinant_is_totally_unimodular(matrix, indices);\n  }\n\n  /**\n   * Checks all subdeterminants to test a given matrix for total unimodularity.\n   * If this is not the case, violator describes a violating submatrix.\n   *\n   * @param matrix The given matrix\n   * @param violator The violating submatrix, if the result is false\n   * @return true if and only if the this matrix is totally unimodular\n   */\n\n  bool determinant_is_totally_unimodular(const integer_matrix& matrix, submatrix_indices& violator)\n  {\n    for (size_t size = 1; size <= matrix.size1(); ++size)\n    {\n      combination row_combination(matrix.size1(), size);\n      while (true)\n      {\n        combination column_combination(matrix.size2(), size);\n        while (true)\n        {\n          submatrix_indices sub;\n          submatrix_indices::vector_type indirect_array(size);\n          for (size_t i = 0; i < size; ++i)\n            indirect_array[i] = row_combination[i];\n          sub.rows = submatrix_indices::indirect_array_type(size, indirect_array);\n          for (size_t i = 0; i < size; ++i)\n          {\n            indirect_array[i] = column_combination[i];\n          }\n          sub.columns = submatrix_indices::indirect_array_type(size, indirect_array);\n\n          /// Examine the determinant\n          bool camion = submatrix_camion(matrix, sub);\n\n#ifndef NDEBUG\n          int det = submatrix_determinant(matrix, sub);\n          bool is_violator = det < -1 || det > +1;\n          assert((is_violator && !camion) || (!is_violator && camion));\n#pragma message(\"\\n\\n\\nWARNING: Submatrix Test uses subdeterminants for verification and is much slower!\\n\\n \")\n#endif\n          if (!camion)\n          {\n            violator = sub;\n            return false;\n          }\n\n          if (column_combination.is_last())\n            break;\n          column_combination.next();\n        }\n        if (row_combination.is_last())\n          break;\n        row_combination.next();\n      }\n    }\n    return true;\n  }\n\n}\n", "meta": {"hexsha": "6e6d3e6f9c81ee2ade4785555e1ef15b500de373", "size": 5464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/determinant.cpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/determinant.cpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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/determinant.cpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "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.5838150289, "max_line_length": 132, "alphanum_fraction": 0.6504392387, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6612426250646337}}
{"text": "/*=============================================================================\n\n  SKSURGERYOPENCVCPP: Image-guided surgery functions, in C++, using OpenCV.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"sksTriangulate.h\"\n#include \"sksExceptionMacro.h\"\n\n#include <opencv2/calib3d.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <iostream>\n\nnamespace sks\n{\n\n//-----------------------------------------------------------------------------\ndouble Norm(const cv::Point3d& p1)\n{\n  return std::sqrt(p1.x * p1.x + p1.y * p1.y + p1.z * p1.z);\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d CrossProduct(const cv::Point3d& p1, const cv::Point3d& p2)\n{\n  cv::Point3d cp;\n  cp.x = p1.y * p2.z - p1.z * p2.y;\n  cp.y = p1.z * p2.x - p1.x * p2.z;\n  cp.z = p1.x * p2.y - p1.y * p2.x;\n  return cp;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DotProduct(const cv::Point3d& p1, const cv::Point3d& p2)\n{\n  return p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DistanceToLine(const std::pair<cv::Point3d, cv::Point3d>& line, const cv::Point3d& x0 )\n{\n  // Courtesy of Wolfram Mathworld\n  cv::Point3d x1;\n  cv::Point3d x2;\n\n  x1 = line.first;\n  x2 = line.second;\n\n  cv::Point3d d1 = x1-x0;\n  cv::Point3d d2 = x2-x1;\n\n  return sks::Norm(sks::CrossProduct(d2, d1)) / (sks::Norm(d2));\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenLines(const cv::Point3d& P0, const cv::Point3d& u,\n                            const cv::Point3d& Q0, const cv::Point3d& v,\n                            cv::Point3d& midpoint)\n{\n  // Method 1. Solve for shortest line joining two rays, then get midpoint.\n  // Taken from: http://geomalgorithms.com/a07-_distance.html\n  double sc, tc, a, b, c, d, e;\n  double distance;\n\n  cv::Point3d Psc;\n  cv::Point3d Qtc;\n  cv::Point3d W0;\n\n  // Difference of two origins\n  W0.x = P0.x - Q0.x;\n  W0.y = P0.y - Q0.y;\n  W0.z = P0.z - Q0.z;\n\n  a = u.x*u.x + u.y*u.y + u.z*u.z;\n  b = u.x*v.x + u.y*v.y + u.z*v.z;\n  c = v.x*v.x + v.y*v.y + v.z*v.z;\n  d = u.x*W0.x + u.y*W0.y + u.z*W0.z;\n  e = v.x*W0.x + v.y*W0.y + v.z*W0.z;\n  sc = (b*e - c*d) / (a*c - b*b);\n  tc = (a*e - b*d) / (a*c - b*b);\n\n  if ( boost::math::isnan(sc) || boost::math::isnan(tc) || boost::math::isinf(sc) || boost::math::isinf(tc) )\n  {\n    // Lines are parallel\n    distance = sks::DistanceToLine ( std::pair<cv::Point3d, cv::Point3d> ( P0, P0 + u ), Q0 );\n    midpoint.x = std::numeric_limits<double>::quiet_NaN();\n    midpoint.y = std::numeric_limits<double>::quiet_NaN();\n    midpoint.z = std::numeric_limits<double>::quiet_NaN();\n    return distance;\n  }\n  Psc.x = P0.x + sc*u.x;\n  Psc.y = P0.y + sc*u.y;\n  Psc.z = P0.z + sc*u.z;\n  Qtc.x = Q0.x + tc*v.x;\n  Qtc.y = Q0.y + tc*v.y;\n  Qtc.z = Q0.z + tc*v.z;\n\n  distance = std::sqrt((Psc.x - Qtc.x)*(Psc.x - Qtc.x)\n                        +(Psc.y - Qtc.y)*(Psc.y - Qtc.y)\n                        +(Psc.z - Qtc.z)*(Psc.z - Qtc.z));\n\n  midpoint.x = (Psc.x + Qtc.x)/2.0;\n  midpoint.y = (Psc.y + Qtc.y)/2.0;\n  midpoint.z = (Psc.z + Qtc.z)/2.0;\n\n  return distance;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble ComputeRMSBetweenCorrespondingPoints(const cv::Mat& a, const cv::Mat& b)\n{\n  double rms = 0;\n  double diff = 0;\n  double squaredDiff = 0;\n\n  if (a.rows != b.rows)\n  {\n    sksExceptionThrow() << \"a has \" << a.rows << \" rows, but b has \" << b.rows;\n  }\n\n  if (a.cols != 3)\n  {\n    sksExceptionThrow() << \"a does not have 3 columns.\";\n  }\n\n  if (b.cols != 3)\n  {\n    sksExceptionThrow() << \"b does not have 3 columns.\";\n  }\n\n  for (unsigned int r = 0; r < a.rows; r++)\n  {\n    for (unsigned int c = 0; c < a.cols; c++)\n    {\n      diff = (b.at<double>(r, c) - a.at<double>(r, c));\n      squaredDiff = diff * diff;\n      rms += squaredDiff;\n    }\n  }\n  rms /= static_cast<double>(a.rows);\n  rms = std::sqrt(rms);\n  return rms;\n}\n\n} // end namespace\n", "meta": {"hexsha": "8291c13b3b530f6e571357867f2f595519b88ea8", "size": 4388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/sksMaths.cpp", "max_stars_repo_name": "UCL/scikit-surgeryopencvcpp", "max_stars_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "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": "Code/Lib/sksMaths.cpp", "max_issues_repo_name": "UCL/scikit-surgeryopencvcpp", "max_issues_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-02-23T13:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T14:19:56.000Z", "max_forks_repo_path": "Code/Lib/sksMaths.cpp", "max_forks_repo_name": "UCL/scikit-surgeryopencvcpp", "max_forks_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-31T11:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T20:27:18.000Z", "avg_line_length": 27.5974842767, "max_line_length": 109, "alphanum_fraction": 0.4958979034, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6612047052850055}}
{"text": "/*\nCopyright 2020 Standard Cyborg\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#include \"standard_cyborg/algorithms/PointToPointAlignment.hpp\"\n\n#include \"standard_cyborg/util/IncludeEigen.hpp\"\n\n#include \"standard_cyborg/math/Vec3.hpp\"\n#include \"standard_cyborg/math/Mat3x4.hpp\"\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n#include <Eigen/Jacobi>\n#pragma clang diagnostic pop\n\nnamespace standard_cyborg {\n\nnamespace algorithms {\n\nstandard_cyborg::math::Mat3x4 PointToPointAlignment(const std::vector<standard_cyborg::math::Vec3>& sourcePositions, const std::vector<standard_cyborg::math::Vec3>& targetPositions)\n{\n    int N = (int)sourcePositions.size();\n    \n    Eigen::Matrix3Xf p = Eigen::Matrix3Xf(3, N);\n    Eigen::Matrix3Xf q = Eigen::Matrix3Xf(3, N);\n    Eigen::MatrixXf avgP, avgQ, pNorm, qNorm, C, R, t;\n    \n    for (int iv = 0; iv < N; ++iv) {\n        p.col(iv) = Eigen::Vector3f(sourcePositions[iv].x, sourcePositions[iv].y, sourcePositions[iv].z);\n        q.col(iv) = Eigen::Vector3f(targetPositions[iv].x, targetPositions[iv].y, targetPositions[iv].z);\n    }\n    \n    avgP = p.rowwise().mean();\n    avgQ = q.rowwise().mean();\n    \n    pNorm = p - avgP.replicate(1, p.cols());\n    qNorm = q - avgQ.replicate(1, q.cols());\n    \n    C = pNorm * qNorm.transpose();\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    \n    // rotation\n    R = svd.matrixV() * svd.matrixU().transpose();\n    \n    // translation\n    t = avgQ - R * avgP;\n    \n    standard_cyborg::math::Mat3x4 r = {\n        R(0, 0), R(0, 1), R(0, 2), t(0),\n        R(1, 0), R(1, 1), R(1, 2), t(1),\n        R(2, 0), R(2, 1), R(2, 2), t(2),\n    };\n    \n    return r;\n}\n\n}\n\n}\n", "meta": {"hexsha": "4b57bbc68e549cd461fb4fe34bb696143264f042", "size": 2207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_stars_repo_name": "StandardCyborg/scsdk", "max_stars_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T01:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:45:19.000Z", "max_issues_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_issues_repo_name": "StandardCyborg/scsdk", "max_issues_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "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": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_forks_repo_name": "StandardCyborg/scsdk", "max_forks_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "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.6527777778, "max_line_length": 181, "alphanum_fraction": 0.672405981, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6611958991452033}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// monomials_horner::monomials_properties.hpp                               //\n//  (C) Copyright 2009 Erwann Rogard                                        //\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_MONOMIALS_HORNER_MONOMIALS_PROPERTIES_HPP_ER_2009\n#define BOOST_MONOMIALS_HORNER_MONOMIALS_PROPERTIES_HPP_ER_2009\n#include <boost/math/special_functions/binomial.hpp>\n\nnamespace boost{\nnamespace monomials_horner{\n\n    template<typename T = double>\n    struct monomials_properties{\n        static unsigned long number_degree_less_than(\n            unsigned the_degree,unsigned dim){\n                return static_cast<unsigned long>(math::binomial_coefficient<T>(\n                    the_degree+dim,dim));\n        }\n    };\n\n}// monomials_horner\n}// boost\n\n\n#endif\n", "meta": {"hexsha": "8624aeaaba1392297a6711345c4df53918d38828", "size": 1130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "monomials_horner/boost/monomials_horner/monomials_properties.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "monomials_horner/boost/monomials_horner/monomials_properties.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "monomials_horner/boost/monomials_horner/monomials_properties.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": 38.9655172414, "max_line_length": 80, "alphanum_fraction": 0.5566371681, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6611958920090304}}
{"text": "/**\n * \\file Chebyshev1Filter.cpp\n */\n\n#include <boost/math/special_functions/asinh.hpp>\n\n#include \"Chebyshev1Filter.h\"\n#include \"helpers.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n  template<typename DataType>\n  void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)\n  {\n    z.clear(); // no zeros for this filter type\n    p.clear();\n    if(ripple == 0)\n    {\n      return;\n    }\n    if(order == 0)\n    {\n      k = static_cast<DataType>(std::pow(10, (-ripple / 20)));\n      return;\n    }\n    \n    DataType eps = static_cast<DataType>(std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0));\n    DataType mu = static_cast<DataType>(1.0 / order * boost::math::asinh(1 / eps));\n    \n    for(int i = -order+1; i < order; i += 2)\n    {\n      DataType theta = boost::math::constants::pi<DataType>() * i / (2*order);\n      p.push_back(-std::sinh(std::complex<DataType>(mu, theta)));\n    }\n\n    std::complex<DataType> f = 1;\n    \n    for(int i = 0; i < p.size(); ++i)\n    {\n      f *= -p[i];\n    }\n    k = f.real();\n    if(order % 2 == 0)\n    {\n      k = k / std::sqrt((1 + eps * eps));\n    }\n  }\n  \n  template<typename DataType>\n  void create_default_chebyshev1_coeffs(size_t order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order), ripple, z, p, k);\n    DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() *  Wn / fs);\n    zpk_lp2lp(warped, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n  \n  template<typename DataType>\n  void create_bp_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order/2), ripple, z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n  \n  template<typename DataType>\n  void create_bs_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev1_analog_coefficients(static_cast<int>(order/2), ripple, z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  Chebyshev1LowPassCoefficients<DataType>::Chebyshev1LowPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1LowPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1LowPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1LowPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1LowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void Chebyshev1LowPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev1LowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev1HighPassCoefficients<DataType>::Chebyshev1HighPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1HighPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1HighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1HighPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1HighPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1HighPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev1HighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(int i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n  \n  template <typename DataType>\n  Chebyshev1BandPassCoefficients<DataType>::Chebyshev1BandPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n  \n  template <typename DataType_>\n  std::pair<DataType_, DataType_> Chebyshev1BandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1BandPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev1BandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev1BandStopCoefficients<DataType>::Chebyshev1BandStopCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n  \n  template <typename DataType_>\n  std::pair<DataType_, DataType_> Chebyshev1BandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev1BandStopCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev1BandStopCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n\n  template <typename DataType>\n  void Chebyshev1BandStopCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev1BandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template class Chebyshev1LowPassCoefficients<float>;\n  template class Chebyshev1LowPassCoefficients<double>;\n  template class Chebyshev1HighPassCoefficients<float>;\n  template class Chebyshev1HighPassCoefficients<double>;\n  template class Chebyshev1BandPassCoefficients<float>;\n  template class Chebyshev1BandPassCoefficients<double>;\n  template class Chebyshev1BandStopCoefficients<float>;\n  template class Chebyshev1BandStopCoefficients<double>;\n  \n  template class IIRFilter<Chebyshev1LowPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev1LowPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev1HighPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev1HighPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev1BandPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev1BandPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev1BandStopCoefficients<float> >;\n  template class IIRFilter<Chebyshev1BandStopCoefficients<double> >;\n  \n}\n", "meta": {"hexsha": "9be878475d814f3d94623048a00f8015c0836647", "size": 11492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev1Filter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev1Filter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "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": "ATK/EQ/Chebyshev1Filter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 30.6453333333, "max_line_length": 184, "alphanum_fraction": 0.6907413853, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6611532432396262}}
{"text": "#include \"ematrix.h\"\n\n#include \"defines.h\"\n#include \"fmatrix.h\"\n#include \"triangulation.h\"\n\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace {\n\n    // essential matrix must have exactly two equal non zero singular values\n    void ensureSpectralProperty(matrix3d &Ecv)\n    {\n        Eigen::MatrixXd E;\n        copy(Ecv, E);\n\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n        Eigen::MatrixXd U = svd.matrixU();\n        Eigen::VectorXd s = svd.singularValues();\n        Eigen::MatrixXd V = svd.matrixV();\n\n        Eigen::MatrixXd S = Eigen::MatrixXd(3, 3);\n        S.setZero();\n\n        S(0, 0) = 1.0;\n        S(1, 1) = 1.0;\n        S(2, 2) = 0.0;\n\n        E = U * S * V.transpose();\n\n        copy(E, Ecv);\n    }\n\n}\n\ncv::Matx33d phg::fmatrix2ematrix(const cv::Matx33d &F, const phg::Calibration &calib0, const phg::Calibration &calib1)\n{\n    // TODO check that correct conversion (transpose ok)\n\n    // TODO add separate test for fmatrix (check 1) reprojection errors 2) f matrix singular value property)\n    // TODO add separate test for ematrix (check 1) reprojection errors of normalized coordinates 2) e matrix singular value property)\n    // TODO add separate test for ematrix decomposition: 1) check angle between cameras 2) check translation direction between cameras\n\n    matrix3d E = calib1.K().t() * F * calib0.K();\n\n    ensureSpectralProperty(E);\n\n    return E;\n}\n\nnamespace {\n\n    matrix34d composeP(const Eigen::MatrixXd &R, const Eigen::VectorXd &t)\n    {\n        matrix34d result;\n\n        result(0, 0) = R(0, 0);\n        result(0, 1) = R(0, 1);\n        result(0, 2) = R(0, 2);\n        result(1, 0) = R(1, 0);\n        result(1, 1) = R(1, 1);\n        result(1, 2) = R(1, 2);\n        result(2, 0) = R(2, 0);\n        result(2, 1) = R(2, 1);\n        result(2, 2) = R(2, 2);\n\n        result(0, 3) = t[0];\n        result(1, 3) = t[1];\n        result(2, 3) = t[2];\n\n        return result;\n    }\n\n    double getDepth(const vector2d &m0, const vector2d &m1, const phg::Calibration &calib0, const phg::Calibration &calib1, const matrix34d &P0, const matrix34d &P1)\n    {\n        vector3d p0 = calib0.unproject(m0);\n        vector3d p1 = calib1.unproject(m1);\n\n        vector3d ps[2] = {p0, p1};\n        matrix34d Ps[2] = {P0, P1};\n\n        vector4d X = phg::triangulatePoint(Ps, ps, 2);\n        if (X[3] != 0) {\n            X /= X[3];\n        }\n\n        return p0.dot(P0 * X) > 0 && p1.dot(P1 * X) > 0;\n    }\n}\n\n// \u041c\u0430\u0442\u0440\u0438\u0446\u044b \u043a\u0430\u043c\u0435\u0440 \u0434\u043b\u044f \u0444\u0443\u043d\u0434\u0430\u043c\u0435\u043d\u0442\u0430\u043b\u044c\u043d\u043e\u0439 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u044b \u0441 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c\u044e \u0434\u043e \u043f\u0440\u043e\u0435\u043a\u0442\u0438\u0432\u043d\u043e\u0433\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f\n// \u0422\u043e \u0435\u0441\u0442\u044c, \u043c\u043e\u0436\u043d\u043e \u0438\u0441\u043a\u0430\u0437\u0438\u0442\u044c \u0442\u0440\u0435\u0445\u043c\u0435\u0440\u043d\u044b\u0439 \u043c\u0438\u0440 (\u043f\u0440\u0438\u043c\u0435\u043d\u0438\u0432 4-\u043c\u0435\u0440\u043d\u0443\u044e \u043e\u0434\u043d\u043e\u0440\u043e\u0434\u043d\u0443\u044e \u043c\u0430\u0442\u0440\u0438\u0446\u0443), \u0438 \u043e\u0434\u043d\u043e\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e \u043f\u043e\u043c\u0435\u043d\u044f\u0442\u044c \u043c\u0430\u0442\u0440\u0438\u0446\u044b P0, P1 \u0442\u0430\u043a, \u0447\u0442\u043e \u043f\u0440\u043e\u0435\u043a\u0446\u0438\u0438 \u0432 \u043f\u0438\u043a\u0441\u0435\u043b\u044f\u0445 \u043d\u0435 \u0438\u0437\u043c\u0435\u043d\u044f\u0442\u0441\u044f\n// \u0415\u0441\u043b\u0438 \u043c\u044b \u0437\u043d\u0430\u0435\u043c \u043a\u0430\u043b\u0438\u0431\u0440\u043e\u0432\u043a\u0438 \u043a\u0430\u043c\u0435\u0440 (\u043c\u0430\u0442\u0440\u0438\u0446\u044b K0, K1 \u0432 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0435 \u043c\u0430\u0442\u0440\u0438\u0446 P0, P1), \u0442\u043e \u043c\u043e\u0436\u0435\u043c \u043d\u0430\u043b\u043e\u0436\u0438\u0442\u044c \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u044b\u0435 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u044f, \u0432 \u0447\u0430\u0441\u0442\u043d\u043e\u0441\u0442\u0438, \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u043e, \u0447\u0442\u043e\n// \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u0430\u044f \u043c\u0430\u0442\u0440\u0438\u0446\u0430 (Essential matrix = K1t * F * K0) \u0438\u043c\u0435\u0435\u0442 \u0440\u043e\u0432\u043d\u043e \u0434\u0432\u0430 \u0441\u043e\u0432\u043f\u0430\u0434\u0430\u044e\u0449\u0438\u0445 \u043d\u0435\u043d\u0443\u043b\u0435\u0432\u044b\u0445 \u0441\u0438\u043d\u0433\u0443\u043b\u044f\u0440\u043d\u044b\u0445 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f, \u0442\u043e\u0433\u0434\u0430 \u043a\u0430\u043a \u0434\u043b\u044f \u0444\u0443\u043d\u0434\u0430\u043c\u0435\u043d\u0442\u0430\u043b\u044c\u043d\u043e\u0439 \u043c\u0430\u0442\u0440\u0438\u0446\u044b \u043e\u043d\u0438 \u043c\u043e\u0433\u0443\u0442 \u0440\u0430\u0437\u043b\u0438\u0447\u0430\u0442\u044c\u0441\u044f\n// \u042d\u0442\u043e \u0434\u043e\u043f\u043e\u043b\u043d\u0438\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0435 \u043f\u043e\u0437\u0432\u043e\u043b\u044f\u0435\u0442 \u0440\u0430\u0437\u043b\u043e\u0436\u0438\u0442\u044c \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u0443\u044e \u043c\u0430\u0442\u0440\u0438\u0446\u0443 \u0441 \u0442\u043e\u0447\u043d\u043e\u0441\u0442\u044c\u044e \u0434\u043e 4 \u0440\u0435\u0448\u0435\u043d\u0438\u0439, \u0432\u043c\u0435\u0441\u0442\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u043b\u044c\u043d\u043e\u0433\u043e \u043f\u0440\u043e\u0435\u043a\u0442\u0438\u0432\u043d\u043e\u0433\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u044f (\u0441\u043c. Hartley & Zisserman p.258)\n// \u041e\u0431\u044b\u0447\u043d\u043e \u043c\u044b \u043c\u043e\u0436\u0435\u043c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c \u043e\u0434\u043d\u0443 \u043e\u0431\u0449\u0443\u044e \u043a\u0430\u043b\u0438\u0431\u0440\u043e\u0432\u043a\u0443, \u0431\u043e\u043b\u0435\u0435 \u043c\u0435\u043d\u0435\u0435 \u0432\u0435\u0440\u043d\u0443\u044e \u0434\u043b\u044f \u0431\u043e\u043b\u044c\u0448\u043e\u0433\u043e \u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u0440\u0435\u0430\u043b\u044c\u043d\u044b\u0445 \u043a\u0430\u043c\u0435\u0440 \u0438 \u0441 \u0435\u0435 \u043f\u043e\u043c\u043e\u0449\u044c\u044e \u0432\u044b\u043f\u043e\u043b\u043d\u0438\u0442\u044c\n// \u043f\u0435\u0440\u0432\u0438\u0447\u043d\u043e\u0435 \u0440\u0430\u0437\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0435\u043d\u043d\u043e\u0439 \u043c\u0430\u0442\u0440\u0438\u0446\u044b (\u0430 \u0438\u0437 \u043d\u0435\u0433\u043e, \u0432\u0437\u0430\u0438\u043c\u043d\u043e\u0435 \u0440\u0430\u0441\u043f\u043e\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u043a\u0430\u043c\u0435\u0440) \u0434\u043b\u044f \u043f\u043e\u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0435\u0433\u043e \u0443\u0442\u043e\u0447\u043d\u0435\u043d\u0438\u044f \u043c\u0435\u0442\u043e\u0434\u043e\u043c \u043d\u0435\u043b\u0438\u043d\u0435\u0439\u043d\u043e\u0439 \u043e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u0446\u0438\u0438\nvoid phg::decomposeEMatrix(cv::Matx34d &P0, cv::Matx34d &P1, const cv::Matx33d &Ecv, const std::vector<cv::Vec2d> &m0, const std::vector<cv::Vec2d> &m1, const Calibration &calib0, const Calibration &calib1, bool verbose)\n{\n    if (m0.size() != m1.size()) {\n        throw std::runtime_error(\"decomposeEMatrix : m0.size() != m1.size()\");\n    }\n\n    using mat = Eigen::MatrixXd;\n    using vec = Eigen::VectorXd;\n    \n    mat E;\n    copy(Ecv, E);\n\n    // (\u0441\u043c. Hartley & Zisserman p.258)\n\n    Eigen::JacobiSVD<mat> svd(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    mat U = svd.matrixU();\n    vec s = svd.singularValues();\n    mat V = svd.matrixV();\n\n    // U, V must be rotation matrices, not just orthogonal\n    if (U.determinant() < 0) U = -U;\n    if (V.determinant() < 0) V = -V;\n\n    if (verbose) {\n        std::cout << \"U:\\n\" << U << std::endl;\n        std::cout << \"s:\\n\" << s << std::endl;\n        std::cout << \"V:\\n\" << V << std::endl;\n    }\n\n    mat W(3, 3);\n    W << 0, -1, 0, 1, 0, 0, 0, 0, 1;\n\n    mat Z(3, 3);\n    Z << 0, 1, 0, -1, 0, 0, 0, 0, 0;\n\n    if (verbose) {\n        std::cout << \"W:\\n\" << W << std::endl;\n        std::cout << \"Z:\\n\" << Z << std::endl;\n    }\n\n    mat R0 = U * W * V.transpose();\n    mat R1 = U * W.transpose() * V.transpose();\n\n    if (verbose) {\n        std::cout << \"R0:\\n\" << R0 << std::endl;\n        std::cout << \"R1:\\n\" << R1 << std::endl;\n    }\n\n    vec t0 = U.col(2);\n    vec t1 = -t0;\n\n    if (verbose) {\n        std::cout << \"t0:\\n\" << t0 << std::endl;\n    }\n\n    P0 = matrix34d::eye();\n\n    // 4 possible solutions\n    matrix34d P10 = composeP(R0, t0);\n    matrix34d P11 = composeP(R0, t1);\n    matrix34d P12 = composeP(R1, t0);\n    matrix34d P13 = composeP(R1, t1);\n    matrix34d P1s[4] = {P10, P11, P12, P13};\n\n    // need to select best of 4 solutions: 3d points should be in front of cameras (positive depths)\n    int best_count = 0;\n    int best_idx = -1;\n    for (int i = 0; i < 4; ++i) {\n        int count = 0;\n        for (int j = 0; j < (int) m0.size(); ++j) {\n            if (getDepth(m0[j], m1[j], calib0, calib1, P0, P1s[i]) > 0) {\n                ++count;\n            }\n        }\n        if (verbose) {\n            std::cout << \"decomposeEMatrix: count: \" << count << std::endl;\n        }\n        if (count > best_count) {\n            best_count = count;\n            best_idx = i;\n        }\n    }\n\n    if (best_count == 0) {\n        throw std::runtime_error(\"decomposeEMatrix : can't decompose ematrix\");\n    }\n\n    P1 = P1s[best_idx];\n\n    if (verbose) {\n        std::cout << \"best idx: \" << best_idx << std::endl;\n        std::cout << \"P0: \\n\" << P0 << std::endl;\n        std::cout << \"P1: \\n\" << P1 << std::endl;\n    }\n}\n\nvoid phg::decomposeUndistortedPMatrix(cv::Matx33d &R, cv::Vec3d &O, const cv::Matx34d &P)\n{\n    R = P.get_minor<3, 3>(0, 0);\n\n    cv::Matx31d O_mat = -R.t() * P.get_minor<3, 1>(0, 3);\n    O(0) = O_mat(0);\n    O(1) = O_mat(1);\n    O(2) = O_mat(2);\n\n    if (cv::determinant(R) < 0) {\n        R *= -1;   \n    }\n}\n\ncv::Matx33d phg::composeEMatrixRT(const cv::Matx33d &R, const cv::Vec3d &T)\n{\n    return skew(T) * R;\n}\n\ncv::Matx34d phg::composeCameraMatrixRO(const cv::Matx33d &R, const cv::Vec3d &O)\n{\n    vector3d T = -R * O;\n    return make34(R, T);\n}\n", "meta": {"hexsha": "e13f9843e528a9f0c5d0ac14de76896870f2867e", "size": 6785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/ematrix.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/ematrix.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/ematrix.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5630630631, "max_line_length": 220, "alphanum_fraction": 0.5808400884, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6611503964932771}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  ArrayXXf m(2,2);\n  ArrayXXf n(2,2);\n  \n  ArrayXXf result(2,2);\n\n  //initialize arrays\n  m << 1,2,\n       3,4;\n\n  n << 5,6,\n       7,8;\n\n  \n  // --> array multiplication\n  result = m * n;\n\n  cout << \"-- Array m*n: --\" << endl\n    << result << endl << endl;\n\n\n  // --> Matrix multiplication\n  result = m.matrix() * n.matrix();\n  \n  cout << \"-- Matrix m*n: --\" << endl\n    << result << endl << endl;\n}\n", "meta": {"hexsha": "c2cb6bf3f482181892ff195332491beeb2a2f67c", "size": 503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop_array.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_array.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_array.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": 14.3714285714, "max_line_length": 37, "alphanum_fraction": 0.5268389662, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6611503964932771}}
{"text": "#include <iostream>\n#include <chrono>\n#include <Eigen/Dense>\n#include \"elements.h\"\n\nusing Eigen::Vector3d;\n\nnamespace elements\n{\n    VectorXd elements(Vector3d r, Vector3d v, double mu)\n    {\n        auto r_mag = r.norm();\n        auto v_mag = v.norm();\n        auto v_mag2 = v_mag * v_mag;\n        auto h = r.cross(v);\n        auto h_mag = h.norm();\n        Vector3d k(0,0,1);\n        auto n = k.cross(h);\n        auto n_mag = n.norm();\n        auto xi = v_mag2/2 - mu/r_mag;\n        auto e = ((v_mag2-mu/r_mag)*r - v*r.dot(v))/mu;\n        auto ecc = e.norm();\n        double sma;\n        if (ecc != 1) {\n            sma = -mu/(2*xi);\n        } else {\n            sma = pow(h_mag,2)/mu;\n        }\n        auto inc = acos(h.z()/h_mag);\n        auto node = acos(n.x()/n_mag);\n        auto peri = acos(n.dot(e)/(ecc*n_mag));\n        auto ano = acos(e.dot(r)/(ecc*r_mag));\n        if (n.y() < 0) {\n            node = M_PI*2 - node;\n        }\n        if (e.z() < 0) {\n            peri = M_PI*2 - peri;\n        }\n        if (r.dot(v) < 0) {\n            ano = M_PI*2 - ano;\n        }\n        VectorXd out(6); out << sma, ecc, inc, node, peri, ano;\n        return out;\n    }\n\n    void benchmark(int times) {\n        auto mu = 3.986004418e5;\n        Vector3d r(8.59072560e+02, -4.13720368e+03, 5.29556871e+03);\n        Vector3d v(7.37289205e+00, 2.08223573e+00, 4.39999794e-01);\n\n        auto best = std::numeric_limits<double>::infinity();\n        auto worst = -std::numeric_limits<double>::infinity();\n        double all = 0;\n        for (auto i=0; i < times; i++) {\n            auto begin = std::chrono::high_resolution_clock::now();\n\n            elements(r, v, mu);\n\n            auto end = std::chrono::high_resolution_clock::now();\n            auto current = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count()/1e9;\n            all += current;\n            if (current < best) {\n                best = current;\n            }\n            if (current > worst) {\n                worst = current;\n            }\n        }\n        std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "ddf84da99789fabf014a2d5b8121c3f0cb95377e", "size": 2131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/elements.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/elements.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/elements.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 29.5972222222, "max_line_length": 103, "alphanum_fraction": 0.4800563116, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6611447278120284}}
{"text": "/**\n * Includes\n */\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iomanip>\n#include <complex>\n#include <typeinfo>\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"string.h\"\n/**\n * Compiler const\n */\n#define deflationMethod 1\n#define deflationMethod2 2\n#define mullerMethod 3\n#define laguerreMethod 4\n#define debug\n\nnamespace po = boost::program_options;\nnamespace anpi {\n\t/**\n\t * Deflation class\n\t */\n\ttemplate<typename T> class deflation {\n\t\tpublic :\n\t\t\t/**\n\t\t\t * Deflation class operator () overload\n\t\t\t * @param poly: the polynomial array it can be almost any numerical type.\n\t\t\t * @param root: a known root of the polynomial, has to be the same type as poly.\n\t\t\t * @param order: the size of the polynomial -1, has to be a int.\n\t\t\t * @return\n\t\t\t */\n\t\t\tinline std::vector<T> operator () ( std::vector<T>& poly, T& root, T& res, int order) {\n\t\t\t\tres =poly[order];\n\t\t\t\tpoly[order]=0;\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method started.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t\tstd::cout << poly[i] << \"x^\" << i;\n\t\t\t\t\tif(i!=0) std::cout << \" + \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method ended.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\treturn poly;\n\t\t\t}\n\t};\n\t/**\n\t * Deflation2 class, for the case that both complex conjugate roots have to be deleted \n\t */\n\ttemplate<typename T> class deflation2 {\n\t\tpublic :\n\t\t\t/**\n\t\t\t * Deflation2 class operator () overload\n\t\t\t * @param poly: the polynomial array, has to be a complex<T> type.\n\t\t\t * @param root: a known root of the polynomial, has to be  the same type as poly.\n\t\t\t * @param order: the size of the polynomial -1, has to be a int.\n\t\t\t * @return\n\t\t\t */\n\t\t\tinline std::vector<T> operator () (std::vector<T>& poly, T& root, T& res, int order) {\n\t\t\t\tres =poly[order];\n\t\t\t\tpoly[order]=0;\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method 2 started.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t}\n\t\t\t\tres =poly[--order];\n\t\t\t\troot=std::conj(root);\n\t\t\t\tpoly[order]=0;\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t\tstd::cout << poly[i] << \"x^\" << i;\n\t\t\t\t\tif(i!=0) std::cout << \" + \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method 2 ended.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\treturn poly;\n\t\t\t}\n\t};\n\t/**\n\t * Muller class\n\t */\n\ttemplate <typename T>\n\tclass muller{\n\t\tpublic:\n\t\t\t/**\n\t\t\t * Muller class operator () overload\n\t\t\t * @param x0: \n\t\t\t * @param x1: \n\t\t\t * @param x2: \n\t\t\t * @param coefs:\n\t\t\t * @param max:\n\t\t\t * @param pTolerance:\n\t\t\t * @return\n\t\t\t */\n\t\t\tstd::vector<std::complex<T> > operator()(T x0, T x1, T x2,const std::vector< std::complex<T> >& coefs,unsigned int max, double pTolerance) {\n\t\t\tstd::vector<std::complex<T> > res;\n\t\t\tstd::vector<std::complex<T> > q = coefs;\n\t\t\tstd::complex<T> z;\n\t\t\twhile (q.size() > 2) {\n\t\t\t    z = polinom_zero(x0, x1, x2, q, max, pTolerance);\n\t\t\t    //z = polinom_zero(p, z);\n\t\t\t    q = horner(q, z);\n\t\t\t    res.push_back(z);\n\t\t\t  }\n\t\t\t  res.push_back(-q[0] / q[1]);\n\t\t\t  return res;\n\t\t\t} \n\n\t\t\tstd::complex<T> evaluatePol(std::vector<std::complex<T> >& coef, std::complex<T> * x){\n\t\t\t\tstd::complex<T> result = 0;\n\t\t\t\tfor (int ite = 0; ite<coef.size(); ite++){\n\t\t\t\t\tresult+= coef[ite]*std::pow(*x, ite);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tstd::vector<std::complex<T> > horner(const std::vector<std::complex<T> > &a, std::complex<T> x0) {\n\t\t\t  int n = a.size();\n\t\t\t  std::vector<std::complex<T> >  b(std::max(1, n - 1),0);\n\n\t\t\t  for(int i = n - 1; i > 0; i--)\n\t\t\t    b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0);\n\t\t\t  return b;\n\t\t\t}\n\n\t\t\tstd::complex<T>  polinom_zero (T x0, T x1, T x2,std::vector< std::complex<T> >& coefs,unsigned int max, double pTolerance){\n\t\t\t\tstd::complex<T> xi0, xi1, xi2,xi3, h0,h1,q0,q1,A, B, C,result, tmp1, tmp2;\n\t\t\t\tlong double err;\n\t\t\t\txi0=x0;\n\t\t\t\txi1=x1;\n\t\t\t\txi2=x2;\n\t\t\t\terr=2;\n\t\t\t\ttmp1=0;\n\t\t\t\ttmp2=0;\n\t\t\t\tint ite =0;\n\t\t\t\twhile(ite<max && (long double)err >= pTolerance){\n\n\n\t\t\t\t\th0=xi1-xi0;\n\t\t\t\t\th1=xi2-xi1;\n\t\t\t\t\tq0=(evaluatePol(coefs, &xi1)-evaluatePol(coefs, &xi0))/h0;\n\t\t\t\t\tq1=(evaluatePol(coefs, &xi2)-evaluatePol(coefs, &xi1))/h1;\n\t\t\t\t\t\n\t\t\t\t\tA=(q1-q0)/(h1+h0);\n\t\t\t\t\tB=A*h1+q1;\n\t\t\t\t\tC=(evaluatePol(coefs, &xi2));\n\t\t\t\t\n\t\t\t\t\ttmp1=xi2+((std::complex<T> )-2*C)/(B+std::sqrt(B*B-(std::complex<T> )4*A*C));\n\t\t\t\t\ttmp2=xi2+((std::complex<T> )-2*C)/(B-std::sqrt(B*B-(std::complex<T> )4*A*C));\n\t\t\t\t\t\n\t\t\t\t\tif(B.real()>=0)\n\t\t\t\t\t\txi3=tmp1;\n\t\t\t\t\telse\n\t\t\t\t\t\txi3=tmp2;\n\t\t\t\t\terr=std::abs((((xi3-xi2)/xi3)).real())*100;\n\n\t\t\t\t\txi0=xi1;\n\t\t\t\t\txi1=xi2;\n\t\t\t\t\txi2=xi3;\n\t\t\t\t\tite++;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\treturn xi3;\n\t\t\t};\n\t\t\n\t};\n\ttypedef std::complex<double> cdouble;\n\ttypedef std::vector<cdouble> polyn;\n\t/**\n\t * Laguerre class\n\t */\n\tstd::pair<polyn, cdouble> horner(const polyn &a, cdouble x0) {\n\t  int n = a.size();\n\t  polyn b = polyn(std::max(1, n - 1));\n\n\t  for(int i = n - 1; i > 0; i--)\n\t    b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0);\n\t  return make_pair(b, a[0] + b[0] * x0);\n\t}\n\n\tcdouble eval(const polyn &p, cdouble x) {\n\t  return horner(p, x).second;\n\t}\n\n\tpolyn derivative(const polyn &p) {\n\t  int n = p.size();\n\t  polyn r = polyn(std::max(1, n - 1));\n\t  for(int i = 1; i < n; i++)\n\t    r[i - 1] = p[i] * cdouble(i);\n\t  return r;\n\t}\n\n\tconst double EPS = 1e-9;\n\n\tint cmp(cdouble x, cdouble y) {\n\t  double diff = abs(x) - abs(y);\n\t  return diff < -EPS ? -1 : (diff > EPS ? 1 : 0);\n\t}\n\n\tcdouble find_one_root(const polyn &p0, cdouble x) {\n\t  int n = p0.size() - 1;\n\t  polyn p1 = derivative(p0);\n\t  polyn p2 = derivative(p1);\n\t  for (int step = 0; step < 10000; step++) {\n\t    cdouble y0 = eval(p0, x);\n\t    if (cmp(y0, 0) == 0) break;\n\t    cdouble G = eval(p1, x) / y0;\n\t    cdouble H = G * G - eval(p2, x) - y0;\n\t    cdouble R = sqrt(cdouble(n - 1) * (H * cdouble(n) - G * G));\n\t    cdouble D1 = G + R;\n\t    cdouble D2 = G - R;\n\t    cdouble a = cdouble(n) / (cmp(D1, D2) > 0 ? D1 : D2);\n\t    x -= a;\n\t    if (cmp(a, 0) == 0) break;\n\t  }\n\t  return x;\n\t}\n\n\tstd::vector<cdouble> find_all_roots(const polyn &p) {\n\t  std::vector<cdouble> res;\n\t  polyn q = p;\n\t  while (q.size() > 2) {\n\t    cdouble z(rand() / double(RAND_MAX), rand() / double(RAND_MAX));\n\t    z = find_one_root(q, z);\n\t    z = find_one_root(p, z);\n\t    q = horner(q, z).first;\n\t    res.push_back(z);\n\t  }\n\t  res.push_back(-q[0] / q[1]);\n\t  return res;\n\t}\n}\n\n/**\n * Auxiliar method for the main\n * @param method          Which method will be run (number from 1 to 4 or none for default).\n * @param poly            The polynomial that the method will be run in.\n * @param order           The orther of the polynomial.\n * @param root            The root of the polinomial (use for deflation).\n * @param X               The positions where the method will be started.\n * @param maxIt           The max times the method will be run(muller).\n * @param tolerance       The tolerance the method will have(muller).\n * @param singlePrecision Single precision flag.\n * @param polish          Polish flag.\n */\nvoid mainAux(unsigned short method, std::vector<double>& poly, short order, double root, std::vector<double> X, int maxIt=50, double tolerance=0.00001, bool singlePrecision=0,bool polish=0){\n\tif(poly.size()==0 and method!=0){\n\t\tstd::cout << \"To use a method you need to enter a polynomial with the option --polynomial and the coeficients.\"<< std::endl;\n\t\treturn;\n\t}\n\tswitch(method){\n\t\tcase deflationMethod: //Deflation\n\t\t{\n\t\t\tif(singlePrecision){\n\t\t\t\tstd::complex<float> res =*(new std::complex<float>(0,0));\n\t\t\t\tstd::complex<float> roots=*(new std::complex<float>(root,0));\n\t\t\t\tstd::vector<std::complex<float> > polys;\n\t\t\t\tanpi::deflation<std::complex<float> > defla;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<float> tmp=*(new std::complex<float>(poly[i],0));\n\t\t\t\t\tpolys.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polys,roots, res, (int)order);\n\t\t\t}else{\n\t\t\t\tstd::complex<double> res =*(new std::complex<double>(0,0));\n\t\t\t\tstd::complex<double> rootd=*(new std::complex<double>(root,0));\n\t\t\t\tstd::vector<std::complex<double> > polyd;\n\t\t\t\tanpi::deflation<std::complex<double> > defla;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<float> tmp=*(new std::complex<float>(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase deflationMethod2: //Deflation2\n\t\t{\n\t\t\tif(singlePrecision){\n\t\t\t\tstd::complex<float> res =*(new std::complex<float>(0,0));\n\t\t\t\tstd::complex<float> roots=*(new std::complex<float>(root,0));\n\t\t\t\tstd::vector<std::complex<float> > polys;\n\t\t\t\tanpi::deflation2<std::complex<float> > defla;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<float> tmp=*(new std::complex<float>(poly[i],0));\n\t\t\t\t\tpolys.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polys,roots, res, (int)order);\n\t\t\t}else{\n\t\t\t\tstd::complex<double> res =*(new std::complex<double>(0,0));\n\t\t\t\tstd::complex<double> rootd=*(new std::complex<double>(root,0));\n\t\t\t\tstd::vector<std::complex<double> > polyd;\n\t\t\t\tanpi::deflation2<std::complex<double> > defla;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<float> tmp=*(new std::complex<float>(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase mullerMethod: //Muller\n\t\t{\n\n\t\t\tif(X.size()!=3){\n\t\t\t\tstd::cout << \"Three positions has to be set to use this method. Use the option: --position and the positions space separated.\" << std::endl;\n\t\t\t\treturn ;\n\t\t\t}\n\t\t\tif(singlePrecision){\n\t\t\t\tanpi::muller<float> mull;\n\t\t\t\tstd::vector<std::complex<float> > polyd;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<float> tmp=*(new std::complex<float>(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tstd::vector<std::complex<float> > res;\n\t\t\t\tres = mull((float)X[0], \n\t\t\t\t\t\t\t\t(float)X[1], \n\t\t\t\t\t\t\t\t(float)X[2], \n\t\t\t\t\t\t\t\tpolyd, \n\t\t\t\t\t\t\t\t(unsigned int)maxIt,\n\t\t\t\t\t\t\t\t(float)tolerance);\n\t\t\t\tfor(int i = 0; i < res.size(); i++){\n\t\t\t\t\tstd::cout<< \"x\" << i <<\": \" << res[i] << std::endl; \n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}else{\n\t\t\t\tanpi::muller<double> mull;\n\t\t\t\tstd::vector<std::complex<double> > polyd;\n\t\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\t\tstd::complex<double> tmp=*(new std::complex<double>(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tstd::vector<std::complex<double> > res;\n\t\t\t\tres = mull((double)X[0], \n\t\t\t\t\t\t\t\t(double)X[1], \n\t\t\t\t\t\t\t\t(double)X[2], \n\t\t\t\t\t\t\t\tpolyd, \n\t\t\t\t\t\t\t\t(unsigned int)maxIt,\n\t\t\t\t\t\t\t\t(double)tolerance);\n\t\t\t\tfor(int i = 0; i < res.size(); i++){\n\t\t\t\t\tstd::cout<< \"x\" << i <<\": \" << res[i] << std::endl; \n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcase laguerreMethod:\n\t\t{\n\t\t\tanpi::polyn p;\n\t\t\t// x^3 - 8x^2 - 13x + 140 = (x+4)(x-5)(x-7)\n\t\t\t//X**3 + 2x**2 -109x -110 = (x+11)(x+8)(x-4)\n\t\t\tfor(int i=0; i<poly.size(); i++){\n\t\t\t\tp.push_back(poly[i]);\n\t\t\t}\n\t\t\tstd::vector<anpi::cdouble> roots = anpi::find_all_roots(p);\n\n\t\t\tfor(size_t i = 0; i < roots.size(); i++) {\n\t\t\t\tif (abs(roots[i].real()) < anpi::EPS) roots[i] -= anpi::cdouble(roots[i].real(), 0);\n\t\t\t\t\tif (abs(roots[i].imag()) < anpi::EPS) roots[i] -= anpi::cdouble(0, roots[i].imag());\n\t\t\t\t\t\tstd::cout << std::setprecision(3) << roots[i] << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\t//Deflation method\n\t\t\tstd::cout << \"Deflation of 1x^3+3x^2+4x+12, with 2i as root.\" <<std::endl;\n\t\t\tstd::vector<std::complex<double> >  polyd;\n\t\t\tstd::complex<double> tmp= *(new std::complex<double>(12,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex<double>(4,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex<double>(3,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex<double>(1,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\tstd::complex<double> rootd =*(new std::complex<double>(0,2));\n\t\t\tstd::complex<double> res =*(new std::complex<double>(0,0)); \n\t\t\tanpi::deflation<std::complex<double> > defla;\n\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t//Deflation method 2\n\t\t\tstd::cout << \"Deflation method 2 of 1x^3+3x^2+4x+12, with 2i as root.\" <<std::endl;\n\t\t\trootd =*(new std::complex<double>(0,2));\n\t\t\tres =*(new std::complex<double>(0,0)); \n\t\t\tanpi::deflation2<std::complex<double> > defla2;\n\t\t\tdefla2(polyd,rootd, res, (int)order);\n\t\t\t//Muller method\n\t\t\tstd::cout << \"Muller method roots of 1x^3+2x^2+-5x+-6.\" <<std::endl;\n\t\t\tanpi::muller<double> mull;\n\t\t\tstd::vector<std::complex<double> >coefs;\n\t\t\ttmp=-6;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=-5;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=2;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=1;\n\t\t\tcoefs.push_back(tmp);\n\t\t\tstd::vector<std::complex<double> > result;\n\t\t\tresult = mull((double)-4, \n\t\t\t\t\t\t\t(double)-2, \n\t\t\t\t\t\t\t(double)0, \n\t\t\t\t\t\t\tcoefs, \n\t\t\t\t\t\t\t(unsigned int)50,\n\t\t\t\t\t\t\t(long double)0.000001);\n\t\t\tfor(int i = 0; i < result.size(); i++){\n\t\t\t\tstd::cout<< \"x\" << i <<\": \" << result[i] << std::endl; \n\t\t\t}\n\t\t\t\n\t\t\t//Laguerre method\n\t\t\tstd::cout << \"Laguerre roots of 1x^3-2x^2+-109x+-110.\" <<std::endl;\n\t\t\tanpi::polyn p;\n\t\t\t// x^3 - 8x^2 - 13x + 140 = (x+4)(x-5)(x-7)\n\t\t\t//X**3 + 2x**2 -109x -110 = (x+11)(x+8)(x-4)\n\t\t\tp.push_back(-110);\n\t\t\tp.push_back(-109);\n\t\t\tp.push_back(-2);\n\t\t\tp.push_back(1);\n\n\t\t\tstd::vector<anpi::cdouble> roots = anpi::find_all_roots(p);\n\n\t\t\tfor(size_t i = 0; i < roots.size(); i++) {\n\t\t\t\tif (abs(roots[i].real()) < anpi::EPS) roots[i] -= anpi::cdouble(roots[i].real(), 0);\n\t\t\t\t\tif (abs(roots[i].imag()) < anpi::EPS) roots[i] -= anpi::cdouble(0, roots[i].imag());\n\t\t\t\t\t\tstd::cout << std::setprecision(3) << roots[i] << std::endl;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}\n\n/**\n * Main method, runs all the methods with a default or you can enter options\n * @param Uses program options, call the program plus --help to see detailed description\n * @return the return is depending which method is called\n */\nint main(int argc, char** argv){\n\tusing boost::lexical_cast;\n\tusing boost::bad_lexical_cast;\n\t//Default values for the methods:\n\tshort order=3;\n\tunsigned short method=0;\n\tdouble tolerance=0.000001;\n\tint maxIt=50;\n\tstd::vector<double> poly;\n\tdouble root;\n\tstd::vector<double> position;\n\tbool polish=0;\n\tbool singlePrecision=0;\n\t//Program options definitions\n\tpo::options_description description(\"Project1 Usage\");\n\tdescription.add_options()\n\t(\"help\", \"Display this help message\")\n\t(\"polynomial\", po::value<std::vector<double> >(&poly)->multitoken(), \"The polynomial that the program will use, just add the coeficients space separated.\")\n\t(\"position\", po::value<std::vector<double> >(&position)->multitoken(), \"The positions to start the method space separated.\")\n\t(\"root\", po::value<double>(&root), \"The root to find.\")\n\t(\"order\", po::value<short>(&order), \"The order of the polynomial.\")\n\t(\"muller\", \"Use this option to use the muller method.\")\n\t(\"deflation\", \"Use this option to use deflation method.\")\n\t(\"deflation2\", \"Use this option to use deflation2 method.\")\n\t(\"laguerre\", \"Use this option to use laguerre method.\")\n\t(\"polish\", \"Use this option to polish the roots.\")\n\t(\"tolerance\", po::value<double>(&tolerance), \"The order of the polynomial.\")\n\t(\"maxIterations\", po::value<int>(&maxIt), \"The order of the polynomial.\")\n\t(\"singlePrecision\", \"Use this to set the methods to double singlePrecision, otherwise double precision will be used.\");\n\tpo::positional_options_description p;\n\tp.add(\"file\", -1);\n\tpo::variables_map vm;\n\t//Try to use the entered options\n\ttry {\n\t\tpo::store(po::parse_command_line(argc, argv, description, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\t\tpo::notify(vm);\n\t\tif(vm.count(\"help\")){\n\t\t\tstd::cout << description;\n\t\t\treturn 0;\n\t\t}\n\t\tif(vm.count(\"order\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Polynomial order changed to: \" << order << std::endl;\n\t\t\t#endif\n\t\t\tif(order<0){\n\t\t\t\tstd::cout << \"The order has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif(vm.count(\"tolerance\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"The tolerance for the method will be: \" << tolerance << std::endl;\n\t\t\t#endif\n\t\t\tif(tolerance<0){\n\t\t\t\tstd::cout << \"The tolerance has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t}\n\t\tif(vm.count(\"maxIterations\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Max iterations will be changed to: \" << maxIt << std::endl;\n\t\t\t#endif\n\t\t\tif(maxIt<0){\n\t\t\t\tstd::cout << \"The iterations has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t}\n\t\tif(vm.count(\"singlePrecision\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Polynomial order changed to: \" << singlePrecision << std::endl;\n\t\t\t#endif\n\t\t\tsinglePrecision = 1;\n\t\t}\n\t\tif(vm.count(\"deflation\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Deflation method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = deflationMethod;\n\t\t}\n\t\tif(vm.count(\"deflation2\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Deflation method 2 will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = deflationMethod2;\n\t\t}\n\t\tif(vm.count(\"muller\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Muller method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = mullerMethod;\n\t\t}\n\t\tif(vm.count(\"laguerre\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Laguerre method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = laguerreMethod;\n\t\t}\n\t\tif(vm.count(\"poly\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"A custom polynomial will be used. With size: \" <<poly.size() << std::endl;\n\t\t\t#endif\n\t\t\tif(poly.size()<=0){\n\t\t\t\tstd::cout << \"The polynomial coeficients must be more than 0.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif(vm.count(\"root\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"A custom root will be used: \" << root << std::endl;\n\t\t\t#endif\n\t\t}\n\t\tif(vm.count(\"position\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Custom positions will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tif(poly.size()<=0){\n\t\t\t\tstd::cout << \"The positions must be more than 0.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tmainAux(method, poly, order, root, position,maxIt, tolerance, singlePrecision,polish);\n\t\treturn 0;\n\t}\n\tcatch(const po::error &ex){\n\t\tstd::cerr << ex.what() << '\\n';\n\t}\n\t\n}\n\n\n", "meta": {"hexsha": "4b3c50daf57f842c0260715397b5c1d4bcca4c9d", "size": 17924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analisis_Numerico_para_La_Ingenieria/Proyecto 1/Proyecto1.cpp", "max_stars_repo_name": "malkam03/TEC-CR", "max_stars_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T21:55:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-19T21:55:18.000Z", "max_issues_repo_path": "Analisis_Numerico_para_La_Ingenieria/Proyecto 1/Proyecto1.cpp", "max_issues_repo_name": "malkam03/TEC-CR", "max_issues_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Analisis_Numerico_para_La_Ingenieria/Proyecto 1/Proyecto1.cpp", "max_forks_repo_name": "malkam03/TEC-CR", "max_forks_repo_head_hexsha": "010bfb6df20167bf538bfe9e78fdb9c0467f4ce4", "max_forks_repo_licenses": ["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.4829931973, "max_line_length": 190, "alphanum_fraction": 0.5897679089, "num_tokens": 5874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6611447252329191}}
{"text": "//pca.cpp\n//https://github.com/ihar/EigenPCA/blob/master/pca.cpp\n\n#define NODEBUG\n#include <iostream>\n#ifdef DEBUG\n  #include <iterator>\n#endif\n#include <Eigen/SVD>\n#include \"pca.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint Pca::Calculate(vector<float> &x, \n              const unsigned int &nrows, \n              const unsigned int &ncols, \n              const bool is_corr, \n              const bool is_center, \n              const bool is_scale) {\n  _ncols = ncols;\n  _nrows = nrows;\n  _is_corr = is_corr;\n  _is_center = is_center;\n  _is_scale = is_scale;\n  if (x.size()!= _nrows*_ncols) {\n    return -1;\n  }\n  if ((1 == _ncols) || (1 == nrows)) {\n    return -1;\n  }\n  // Convert vector to Eigen 2-dimensional matrix\n  //Map<MatrixXf> _xXf(x.data(), _nrows, _ncols);\n  _xXf.resize(_nrows, _ncols);\n  for (unsigned int i = 0; i < _nrows; ++i) {\n    for (unsigned int j = 0; j < _ncols; ++j) {\n      _xXf(i, j) = x[j + i*_ncols];\n    }\n  }\n  // Mean and standard deviation for each column\n  VectorXf mean_vector(_ncols);\n  mean_vector = _xXf.colwise().mean();\n  VectorXf sd_vector(_ncols);\n  unsigned int zero_sd_num = 0;\n  float denom = static_cast<float>((_nrows > 1)? _nrows - 1: 1);\n  for (unsigned int i = 0; i < _ncols; ++i) {\n     VectorXf curr_col  = VectorXf::Constant(_nrows, mean_vector(i)); // mean(x) for column x\n     curr_col = _xXf.col(i) - curr_col; // x - mean(x)\n     curr_col = curr_col.array().square(); // (x-mean(x))^2  \n     sd_vector(i) = sqrt((curr_col.sum())/denom);\n     if (0 == sd_vector(i)) {\n      zero_sd_num++;\n     }\n  }\n  // If colums with sd == 0 are too many,\n  // don't continue calculations\n  if (1 > _ncols-zero_sd_num) {\n    return -1;\n  }\n  // Delete columns where sd == 0\n  MatrixXf tmp(_nrows, _ncols-zero_sd_num);\n  VectorXf tmp_mean_vector(_ncols-zero_sd_num);\n  unsigned int curr_col_num = 0;\n  for (unsigned int i = 0; i < _ncols; ++i) {\n    if (0 != sd_vector(i)) {\n      tmp.col(curr_col_num) = _xXf.col(i);\n      tmp_mean_vector(curr_col_num) = mean_vector(i);\n      curr_col_num++;\n    } else {\n      _eliminated_columns.push_back(i);\n    }\n  }\n  _ncols -= zero_sd_num;\n  _xXf = tmp;\n  mean_vector = tmp_mean_vector;\n  tmp.resize(0, 0); tmp_mean_vector.resize(0);\n  // Shift to zero\n  if (true == _is_center) {\n    for (unsigned int i = 0; i < _ncols; ++i) {\n      _xXf.col(i) -= VectorXf::Constant(_nrows, mean_vector(i));\n    }\n  }\n  // Scale to unit variance\n  if ( (false == _is_corr) || (true == _is_scale)) {\n    for (unsigned int i = 0; i < _ncols; ++i) {\n     _xXf.col(i) /= sqrt(_xXf.col(i).array().square().sum()/denom);\n    }\n  }\n  #ifdef DEBUG\n    cout << \"\\nScaled matrix:\\n\";\n    cout << _xXf << endl;\n    cout << \"\\nMean before scaling:\\n\" << mean_vector.transpose();\n    cout << \"\\nStandard deviation before scaling:\\n\" << sd_vector.transpose();\n  #endif\n  // When _nrows < _ncols then svd will be used.\n  // If corr is true and _nrows > _ncols then will be used correlation matrix\n  // (TODO): What about covariance?\n  if ( (_nrows < _ncols) || (false == _is_corr)) { // Singular Value Decomposition is on\n    _method = \"svd\";\n    JacobiSVD<MatrixXf> svd(_xXf, ComputeThinV);\n    VectorXf eigen_singular_values = svd.singularValues();\n    VectorXf tmp_vec = eigen_singular_values.array().square();\n    float tmp_sum = tmp_vec.sum();\n    tmp_vec /= tmp_sum;\n    // PC's standard deviation and\n    // PC's proportion of variance\n    _kaiser = 0;\n    unsigned int lim = (_nrows < _ncols)? _nrows : _ncols;\n    for (unsigned int i = 0; i < lim; ++i) {\n      _sd.push_back(eigen_singular_values(i)/sqrt(denom));\n      if (_sd[i] >= 1) {\n        _kaiser = i + 1;\n      }\n      _prop_of_var.push_back(tmp_vec(i));\n    }\n    #ifdef DEBUG\n      cout << \"\\n\\nStandard deviations for PCs:\\n\";\n      copy(_sd.begin(), _sd.end(),std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\n\\nKaiser criterion: PC #\" << _kaiser << endl;\n    #endif\n    tmp_vec.resize(0);\n    // PC's cumulative proportion\n    _thresh95 = 1;\n    _cum_prop.push_back(_prop_of_var[0]); \n    for (unsigned int i = 1; i < _prop_of_var.size(); ++i) {\n      _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]);\n      if (_cum_prop[i] < 0.95) {\n        _thresh95 = i+1;\n      }\n    }\n    #ifdef DEBUG\n      cout << \"\\nCumulative proportion:\\n\";\n      copy(_cum_prop.begin(), _cum_prop.end(),std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\n\\nThresh95 criterion: PC #\" << _thresh95 << endl;\n    #endif\n    // Scores\n    MatrixXf eigen_scores = _xXf * svd.matrixV();\n    #ifdef DEBUG\n      cout << \"\\n\\nRotated values (scores):\\n\" << eigen_scores;\n    #endif\n    _scores.reserve(lim*lim);\n    for (unsigned int i = 0; i < lim; ++i) {\n      for (unsigned int j = 0; j < lim; ++j) {\n        _scores.push_back(eigen_scores(i, j));\n      }\n    }\n    eigen_scores.resize(0, 0);\n    #ifdef DEBUG\n      cout << \"\\n\\nScores in vector:\\n\";\n      copy(_scores.begin(), _scores.end(),std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\n\";  \n    #endif\n  } else { // COR OR COV MATRICES ARE HERE\n    _method = \"cor\";\n    // Calculate covariance matrix\n    MatrixXf eigen_cov; // = MatrixXf::Zero(_ncols, _ncols);\n    VectorXf sds;\n    // (TODO) Should be weighted cov matrix, even if is_center == false\n    eigen_cov = (1.0 /(_nrows/*-1*/)) * _xXf.transpose() * _xXf;\n    sds = eigen_cov.diagonal().array().sqrt();\n    MatrixXf outer_sds = sds * sds.transpose();\n    eigen_cov = eigen_cov.array() / outer_sds.array();\n    outer_sds.resize(0, 0);\n    // ?If data matrix is scaled, covariance matrix is equal to correlation matrix\n    #ifdef DEBUG\n      cout << eigen_cov << endl;\n    #endif\n    EigenSolver<MatrixXf> edc(eigen_cov);\n    VectorXf eigen_eigenvalues = edc.eigenvalues().real();\n    #ifdef DEBUG\n      cout << endl << eigen_eigenvalues.transpose() << endl;\n    #endif\n    MatrixXf eigen_eigenvectors = edc.eigenvectors().real();\t\n    #ifdef DEBUG\n      cout << endl << eigen_eigenvectors << endl;\n    #endif\n    // The eigenvalues and eigenvectors are not sorted in any particular order.\n    // So, we should sort them\n    typedef pair<float, int> eigen_pair;\n    vector<eigen_pair> ep;\t\n    for (unsigned int i = 0 ; i < _ncols; ++i) {\n\t    ep.push_back(make_pair(eigen_eigenvalues(i), i));\n    }\n    sort(ep.begin(), ep.end()); // Ascending order by default\n    // Sort them all in descending order\n    MatrixXf eigen_eigenvectors_sorted = MatrixXf::Zero(eigen_eigenvectors.rows(), eigen_eigenvectors.cols());\n    VectorXf eigen_eigenvalues_sorted = VectorXf::Zero(_ncols);\n    int colnum = 0;\n    int i = ep.size()-1;\n    for (; i > -1; i--) {\n      eigen_eigenvalues_sorted(colnum) = ep[i].first;\n      eigen_eigenvectors_sorted.col(colnum++) += eigen_eigenvectors.col(ep[i].second);\n    }\n    #ifdef DEBUG\n      cout << endl << eigen_eigenvalues_sorted.transpose() << endl;\n      cout << endl << eigen_eigenvectors_sorted << endl;\n    #endif  \n    // We don't need not sorted arrays anymore\n    eigen_eigenvalues.resize(0);\n    eigen_eigenvectors.resize(0, 0);\n    \n    _sd.clear(); _prop_of_var.clear(); _kaiser = 0;\n    float tmp_sum = eigen_eigenvalues_sorted.sum();\n    for (unsigned int i = 0; i < _ncols; ++i) {\n      _sd.push_back(sqrt(eigen_eigenvalues_sorted(i)));\n      if (_sd[i] >= 1) {\n        _kaiser = i + 1;\n      }\n      _prop_of_var.push_back(eigen_eigenvalues_sorted(i)/tmp_sum);\n    }\n    #ifdef DEBUG\n      cout << \"\\nStandard deviations for PCs:\\n\";\n      copy(_sd.begin(), _sd.end(), std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\nProportion of variance:\\n\";\n      copy(_prop_of_var.begin(), _prop_of_var.end(), std::ostream_iterator<float>(std::cout,\" \")); \n      cout << \"\\nKaiser criterion: PC #\" << _kaiser << endl;\n    #endif\n    // PC's cumulative proportion\n    _cum_prop.clear(); _thresh95 = 1;\n    _cum_prop.push_back(_prop_of_var[0]);\n    for (unsigned int i = 1; i < _prop_of_var.size(); ++i) {\n      _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]);\n      if (_cum_prop[i] < 0.95) {\n        _thresh95 = i+1;\n      }\n    }  \n    #ifdef DEBUG\n      cout << \"\\n\\nCumulative proportions:\\n\";\n      copy(_cum_prop.begin(), _cum_prop.end(), std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\n\\n95% threshold: PC #\" << _thresh95 << endl;\n    #endif\n    // Scores for PCA with correlation matrix\n    // Scale before calculating new values\n    for (unsigned int i = 0; i < _ncols; ++i) {\n     _xXf.col(i) /= sds(i);\n    }\n    sds.resize(0);\n    MatrixXf eigen_scores = _xXf * eigen_eigenvectors_sorted;\n    #ifdef DEBUG\n      cout << \"\\n\\nRotated values (scores):\\n\" << eigen_scores;\n    #endif\n    _scores.clear();\n    _scores.reserve(_ncols*_nrows);\n    for (unsigned int i = 0; i < _nrows; ++i) {\n      for (unsigned int j = 0; j < _ncols; ++j) {\n        _scores.push_back(eigen_scores(i, j));\n      }\n    }\n    eigen_scores.resize(0, 0);\n    #ifdef DEBUG\n      cout << \"\\n\\nScores in vector:\\n\";\n      copy(_scores.begin(), _scores.end(), std::ostream_iterator<float>(std::cout,\" \"));  \n      cout << \"\\n\";  \n    #endif\n  }\n\n  return 0;\n}\nstd::vector<float> Pca::sd(void) { return _sd; };    \nstd::vector<float> Pca::prop_of_var(void) {return _prop_of_var; };\nstd::vector<float> Pca::cum_prop(void) { return _cum_prop; };\nstd::vector<float> Pca::scores(void) { return _scores; };\nstd::vector<unsigned int> Pca::eliminated_columns(void) { return _eliminated_columns; }\nstring Pca::method(void) { return _method; }\nunsigned int Pca::kaiser(void) { return _kaiser; };\nunsigned int Pca::thresh95(void) { return _thresh95; };\nunsigned int Pca::ncols(void) { return _ncols; }\nunsigned int Pca::nrows(void) { return _nrows; }\nbool Pca::is_scale(void) {  return _is_scale; }\nbool Pca::is_center(void) { return _is_center; }\nPca::Pca(void) {\n  _nrows      = 0;\n  _ncols      = 0;\n  // Variables will be scaled by default\n  _is_center  = true;\n  _is_scale   = true;  \n  // By default will be used singular value decomposition\n  _method   = \"svd\";\n  _is_corr  = false;\n\n  _kaiser   = 0;\n  _thresh95 = 1;\n}\nPca::~Pca(void) { \n  _xXf.resize(0, 0);\n  _x.clear();\n}\n\n", "meta": {"hexsha": "60ee5a4111abe3d42fce6ceb34a27b548878efa5", "size": 10093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pca.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/pca.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/pca.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": 34.9238754325, "max_line_length": 110, "alphanum_fraction": 0.6161696225, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6611294328722247}}
{"text": "/**\n * @file tests/metric_test.cpp\n *\n * Unit tests for the various metrics.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <boost/test/unit_test.hpp>\n#include <mlpack/core/metrics/iou_metric.hpp>\n#include <mlpack/core/metrics/non_maximal_supression.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace mlpack::metric;\n\nBOOST_AUTO_TEST_SUITE(LMetricTest);\n\n/**\n * Simple test for L-1 metric.\n */\nBOOST_AUTO_TEST_CASE(L1MetricTest)\n{\n  arma::vec a1(5);\n  a1.randn();\n\n  arma::vec b1(5);\n  b1.randn();\n\n  arma::Col<size_t> a2(5);\n  a2 << 1 << 2 << 1 << 0 << 5;\n\n  arma::Col<size_t> b2(5);\n  b2 << 2 << 5 << 2 << 0 << 1;\n\n  ManhattanDistance lMetric;\n\n  BOOST_REQUIRE_CLOSE((double) arma::accu(arma::abs(a1 - b1)),\n                      lMetric.Evaluate(a1, b1), 1e-5);\n\n  BOOST_REQUIRE_CLOSE((double) arma::accu(arma::abs(a2 - b2)),\n                      lMetric.Evaluate(a2, b2), 1e-5);\n}\n\n/**\n * Simple test for L-2 metric.\n */\nBOOST_AUTO_TEST_CASE(L2MetricTest)\n{\n  arma::vec a1(5);\n  a1.randn();\n\n  arma::vec b1(5);\n  b1.randn();\n\n  arma::vec a2(5);\n  a2 << 1 << 2 << 1 << 0 << 5;\n\n  arma::vec b2(5);\n  b2 << 2 << 5 << 2 << 0 << 1;\n\n  EuclideanDistance lMetric;\n\n  BOOST_REQUIRE_CLOSE((double) sqrt(arma::accu(arma::square(a1 - b1))),\n                      lMetric.Evaluate(a1, b1), 1e-5);\n\n  BOOST_REQUIRE_CLOSE((double) sqrt(arma::accu(arma::square(a2 - b2))),\n                      lMetric.Evaluate(a2, b2), 1e-5);\n}\n\n/**\n * Simple test for L-Infinity metric.\n */\nBOOST_AUTO_TEST_CASE(LINFMetricTest)\n{\n  arma::vec a1(5);\n  a1.randn();\n\n  arma::vec b1(5);\n  b1.randn();\n\n  arma::Col<size_t> a2(5);\n  a2 << 1 << 2 << 1 << 0 << 5;\n\n  arma::Col<size_t> b2(5);\n  b2 << 2 << 5 << 2 << 0 << 1;\n\n  ChebyshevDistance lMetric;\n\n  BOOST_REQUIRE_CLOSE((double) arma::as_scalar(arma::max(arma::abs(a1 - b1))),\n                      lMetric.Evaluate(a1, b1), 1e-5);\n\n  BOOST_REQUIRE_CLOSE((double) arma::as_scalar(arma::max(arma::abs(a2 - b2))),\n                      lMetric.Evaluate(a2, b2), 1e-5);\n}\n\n/**\n * Simple test for IoU metric.\n */\nBOOST_AUTO_TEST_CASE(IoUMetricTest)\n{\n  arma::vec bbox1(4), bbox2(4);\n  bbox1 << 1 << 2 << 100 << 200;\n  bbox2 << 1 << 2 << 100 << 200;\n  // IoU of same bounding boxes equals 1.0.\n  BOOST_REQUIRE_CLOSE(1.0, IoU<>::Evaluate(bbox1, bbox2), 1e-4);\n\n  // Use coordinate system to represent bounding boxes.\n  // Bounding boxes represent {x0, y0, x1, y1}.\n  bbox1 << 39 << 63 << 203 << 112;\n  bbox2 << 54 << 66 << 198 << 114;\n  // Value calculated using Python interpreter.\n  BOOST_REQUIRE_CLOSE(IoU<true>::Evaluate(bbox1, bbox2), 0.7980093, 1e-4);\n\n  bbox1 << 31 << 69 << 201 << 125;\n  bbox2 << 18 << 63 << 235 << 135;\n  // Value calculated using Python interpreter.\n  BOOST_REQUIRE_CLOSE(IoU<true>::Evaluate(bbox1, bbox2), 0.612479577, 1e-4);\n\n  // Use hieght - width representation of bounding boxes.\n  // Bounding boxes represent {x0, y0, h, w}.\n  bbox1 << 49 << 75 << 154 << 50;\n  bbox2 << 42 << 78 << 144 << 48;\n  // Value calculated using Python interpreter.\n  BOOST_REQUIRE_CLOSE(IoU<>::Evaluate(bbox1, bbox2), 0.7898879, 1e-4);\n\n  bbox1 << 35 << 51 << 161 << 59;\n  bbox2 << 36 << 60 << 144 << 48;\n  // Value calculated using Python interpreter.\n  BOOST_REQUIRE_CLOSE(IoU<>::Evaluate(bbox1, bbox2), 0.7309670, 1e-4);\n}\n\nBOOST_AUTO_TEST_CASE(NMSMetricTest)\n{\n  arma::mat bbox, selectedBoundingBox, desiredBoundingBox;\n  arma::vec bbox1(4), bbox2(4), bbox3(4);\n  arma::uvec selectedIndices, desiredIndices;\n\n  // Set values of each bounding box.\n  // Use coordinate system to represent bounding boxes.\n  // Bounding boxes represent {x0, y0, x1, y1}.\n  bbox1 << 0.5 << 0.5 << 41.0 << 31.0;\n  bbox2 << 1.0 << 1.0 << 42.0 << 22.0;\n  bbox3 << 10.0 << 13.0 << 90.0 << 100.0;\n\n  // Fill bounding box.\n  bbox.insert_cols(0, bbox3);\n  bbox.insert_cols(0, bbox2);\n  bbox.insert_cols(0, bbox1);\n\n  // Fill confidence scores for each bounding box.\n  arma::vec confidenceScores(3);\n  confidenceScores << 0.7 << 0.6 << 0.4;\n\n  // Selected bounding box using torchvision.ops.nms().\n  desiredBoundingBox.insert_cols(0, bbox3);\n  desiredBoundingBox.insert_cols(0, bbox1);\n\n  // Selected indices of bounding boxes using\n  // torchvision.ops.nms().\n  desiredIndices = arma::ucolvec(2);\n  desiredIndices << 0 << 2;\n\n  // Evaluate the bounding box.\n  NMS<true>::Evaluate(bbox, confidenceScores,\n      selectedIndices);\n\n  selectedBoundingBox = bbox.cols(selectedIndices);\n\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_cols, 2);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_rows, 4);\n  CheckMatrices(desiredBoundingBox, selectedBoundingBox);\n\n  for (size_t i = 0; i < desiredIndices.n_elem; i++)\n  {\n    BOOST_REQUIRE_EQUAL(desiredIndices[i], selectedIndices[i]);\n  }\n\n  // Clean up.\n  bbox.clear();\n  desiredBoundingBox.clear();\n  selectedBoundingBox.clear();\n\n  // Fill new bounding boxes.\n  bbox.insert_cols(0, bbox1);\n  bbox.insert_cols(0, bbox2);\n  bbox.insert_cols(0, bbox1);\n  confidenceScores << 1.0 << 0.6 << 0.9;\n\n  // Output calculated using using torchvision.ops.nms().\n  desiredBoundingBox.insert_cols(0, bbox2);\n  desiredBoundingBox.insert_cols(0, bbox1);\n\n  NMS<true>::Evaluate(bbox, confidenceScores,\n      selectedIndices, 0.9);\n\n  selectedBoundingBox = bbox.cols(selectedIndices);\n\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_cols, 2);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_rows, 4);\n  CheckMatrices(desiredBoundingBox, selectedBoundingBox);\n\n  // Clean up.\n  bbox.clear();\n  desiredBoundingBox.clear();\n  selectedBoundingBox.clear();\n\n  // Use coordinate system to represent bounding boxes.\n  // Bounding boxes represent {x0, y0, x1, y1}.\n  bbox1 << 39 << 63 << 203 << 112;\n  bbox2 << 31 << 69 << 201 << 125;\n  bbox3 << 54 << 66 << 198 << 114;\n\n  // Fill bounding box.\n  bbox.insert_cols(0, bbox3);\n  bbox.insert_cols(0, bbox2);\n  bbox.insert_cols(0, bbox1);\n\n  // Fill confidence scores of bounding boxes.\n  confidenceScores << 1.0 << 0.6 << 0.9;\n\n  // Selected bounding box using torchvision.ops.nms().\n  desiredBoundingBox.insert_cols(0, bbox2);\n  desiredBoundingBox.insert_cols(0, bbox1);\n\n  NMS<true>::Evaluate(bbox, confidenceScores,\n      selectedIndices, 0.7);\n\n  selectedBoundingBox = bbox.cols(selectedIndices);\n\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_cols, 2);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_rows, 4);\n  CheckMatrices(desiredBoundingBox, selectedBoundingBox);\n\n  // Clean up.\n  bbox.clear();\n  desiredBoundingBox.clear();\n  selectedBoundingBox.clear();\n\n  // Set values of each bounding box.\n  // Use coordinate system to represent bounding boxes.\n  // Bounding boxes represent {x0, y0, h, w}.\n  bbox1 << 0.0 << 0.0 << 41.0 << 31.0;\n  bbox2 << 1.0 << 1.0 << 41.0 << 21.0;\n  bbox3 << 10.0 << 13.0 << 80.0 << 87.0;\n\n  // Fill bounding box.\n  bbox.insert_cols(0, bbox3);\n  bbox.insert_cols(0, bbox2);\n  bbox.insert_cols(0, bbox1);\n\n  // Fill confidence scores for each bounding box.\n  confidenceScores << 0.7 << 0.6 << 0.4;\n\n  // Selected bounding box using torchvision.ops.nms().\n  desiredBoundingBox.insert_cols(0, bbox3);\n  desiredBoundingBox.insert_cols(0, bbox1);\n\n  // Evaluate the bounding box.\n  NMS<>::Evaluate(bbox, confidenceScores,\n    selectedIndices);\n\n  selectedBoundingBox = bbox.cols(selectedIndices);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_cols, 2);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_rows, 4);\n  CheckMatrices(desiredBoundingBox, selectedBoundingBox);\n\n  // Clean up.\n  bbox.clear();\n  desiredBoundingBox.clear();\n  selectedBoundingBox.clear();\n\n  // Use coordinate system to represent bounding boxes.\n  // Bounding boxes represent {x0, y0, h, w}.\n  bbox1 << 39 << 63 << 164 << 49;\n  bbox2 << 31 << 69 << 170 << 56;\n  bbox3 << 54 << 66 << 144 << 48;\n\n  // Fill bounding box.\n  bbox.insert_cols(0, bbox3);\n  bbox.insert_cols(0, bbox2);\n  bbox.insert_cols(0, bbox1);\n\n  // Fill confidence scores of bounding boxes.\n  confidenceScores << 1.0 << 0.6 << 0.4;\n\n  // Selected bounding box using torchvision.ops.nms().\n  desiredBoundingBox.insert_cols(0, bbox2);\n  desiredBoundingBox.insert_cols(0, bbox1);\n\n  NMS<false>::Evaluate(bbox, confidenceScores,\n    selectedIndices, 0.7);\n\n  selectedBoundingBox = bbox.cols(selectedIndices);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_cols, 2);\n  BOOST_REQUIRE_EQUAL(selectedBoundingBox.n_rows, 4);\n  CheckMatrices(desiredBoundingBox, selectedBoundingBox);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "92e6834bc3cd00319c593d1d0228c054233ea2a3", "size": 8662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/metric_test.cpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/tests/metric_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/metric_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 28.4, "max_line_length": 78, "alphanum_fraction": 0.6680905103, "num_tokens": 2598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6611294160801088}}
{"text": "// Author: Abdoul-Nourou Yigo\n//\n\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <sstream> \n#include <vector>\n#include <iostream>\n\nusing namespace boost::multiprecision; \nusing namespace boost::random; \n\nstruct Miller_Rabin \n{\n\t// Create functions prototypes \n\tcpp_int Miller_Rabin_primality_test( cpp_int );\n       \tcpp_int Miller_Rabin_primality_test_2( cpp_int );\t\n\tcpp_int primes_generation( unsigned int = 50, unsigned int  = 60); \n\tcpp_int calculate_large_modulo( cpp_int, cpp_int, cpp_int ); \n\tstd::vector< int >  get_user_input( int, int ); \n};\n", "meta": {"hexsha": "ba8bcbfe22ced3653a4b41d3a93666f279953b0a", "size": 658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Miller-Rabin_algorithm_implementation/Miller_Rabin.hpp", "max_stars_repo_name": "Nouldine/Cryptography", "max_stars_repo_head_hexsha": "a4c44a36de4f5e2ba366bbdbdc664824dbb89478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Miller-Rabin_algorithm_implementation/Miller_Rabin.hpp", "max_issues_repo_name": "Nouldine/Cryptography", "max_issues_repo_head_hexsha": "a4c44a36de4f5e2ba366bbdbdc664824dbb89478", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Miller-Rabin_algorithm_implementation/Miller_Rabin.hpp", "max_forks_repo_name": "Nouldine/Cryptography", "max_forks_repo_head_hexsha": "a4c44a36de4f5e2ba366bbdbdc664824dbb89478", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 68, "alphanum_fraction": 0.7583586626, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6610965083835229}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/differentiation/autodiff.hpp>\n#include <iostream>\n\nint main()\n{\n    using namespace boost::math::differentiation;\n\n    const auto x = make_fvar<double,3>(13);\n    const auto y = make_fvar<double,0,4>(14);\n    const auto z = 10*x*x + 50*x*y + 100*y*y; // promoted to autodiff_fvar<double,3,4>\n    for (int i=0 ; i<=3 ; ++i)\n        for (int j=0 ; j<=4 ; ++j)\n            std::cout << \"z.derivative(\"<<i<<\",\"<<j<<\") = \" << z.derivative(i,j) << std::endl;\n    return 0;\n}\n/*\nOutput:\nz.derivative(2,0) = 20\nz.derivative(1,1) = 50\nz.derivative(0,2) = 200\n**/\n", "meta": {"hexsha": "99ae1465c19da8d763c935b45ef4ef1b6114ae9d", "size": 799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/simple.cpp", "max_stars_repo_name": "kedarbhat/autodiff", "max_stars_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-17T08:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T21:19:42.000Z", "max_issues_repo_path": "example/simple.cpp", "max_issues_repo_name": "kedarbhat/autodiff", "max_issues_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "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/simple.cpp", "max_forks_repo_name": "kedarbhat/autodiff", "max_forks_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "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.5925925926, "max_line_length": 94, "alphanum_fraction": 0.604505632, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6610599356152332}}
{"text": "#pragma once\n\n#include <nanogui/object.h>\n#include <Eigen/Core>\n\nNAMESPACE_BEGIN(QCE);\n\n\nclass Camera : public nanogui::Object {\npublic:\n    template<class T>\n    static Eigen::Matrix<T,4,4> perspective(const T fov, const T aspect, const T near, const T far)\n    {\n        assert(aspect > 0);\n        assert(far > near);\n\n        T fovRad  = (T)nvgDegToRad(fov);\n        T halfFov = (T)tan(fovRad * 0.5);\n\n        Eigen::Matrix<T,4,4> res = Eigen::Matrix<T,4,4>::Zero();\n        res(0,0) = 1.0 / (aspect * halfFov);\n        res(1,1) = 1.0 / (halfFov);\n        res(2,2) = -(far + near) / (far - near);\n        res(3,2) = -1.0;\n        res(2,3) = -(2.0 * far * near) / (far - near);\n\n        return res;\n    }\n\nprivate:\n     Camera() {}\n    ~Camera() {}\n};\n\n\nNAMESPACE_END(QCE);\n", "meta": {"hexsha": "5454dba3a53b68e0d9663c294e2da04bd63c39cd", "size": 777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/camera.hpp", "max_stars_repo_name": "sosterwalder/mte7102-proj2", "max_stars_repo_head_hexsha": "0c554fd45b4e1c05d3daa1e0a885efff56857e7d", "max_stars_repo_licenses": ["MIT"], "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/camera.hpp", "max_issues_repo_name": "sosterwalder/mte7102-proj2", "max_issues_repo_head_hexsha": "0c554fd45b4e1c05d3daa1e0a885efff56857e7d", "max_issues_repo_licenses": ["MIT"], "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/camera.hpp", "max_forks_repo_name": "sosterwalder/mte7102-proj2", "max_forks_repo_head_hexsha": "0c554fd45b4e1c05d3daa1e0a885efff56857e7d", "max_forks_repo_licenses": ["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.0, "max_line_length": 99, "alphanum_fraction": 0.5328185328, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.661015440832394}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/core.hpp>\n#include <eve/module/core.hpp>\n#include <eve/module/math.hpp>\n#include <eve/module/elliptic.hpp>\n#include <boost/math/special_functions/ellint_rj.hpp>\n#include <cmath>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of ellint_rj\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n\n  TTS_EXPR_IS( eve::ellint_rj(T(), T(), T(), T())  , T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), v_t(), v_t(), v_t()), v_t);\n  TTS_EXPR_IS( eve::ellint_rj(T(), v_t(), v_t(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), T(), v_t(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), v_t(), T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(T(), T(), v_t(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), T(), T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(T(), v_t(), T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_rj(T(), v_t(), v_t(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), T(), v_t(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), v_t(), T(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rj(T(), T(), v_t(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rj(v_t(), T(), T(), T()), T);\n  TTS_EXPR_IS( eve::ellint_rj(T(), v_t(), T(), T()), T);\n};\n\n//==================================================================================================\n// ellint_rj  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of ellint_rj on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate( eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0)\n                             , eve::test::randoms(0, 100.0))\n        )\n<typename T>(T const& x, T const& y, T const& z, T const& p)\n{\n  using eve::detail::map;\n  using v_t = eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(eve::ellint_rj(x, y, z, p) , map([](auto e, auto f, auto g, auto h) -> v_t { return boost::math::ellint_rj(e, f, g, h); }, x, y, z, p), 11);\n};\n", "meta": {"hexsha": "ed9a00a01e8b23e437616dc489f1f55a76c2c6a4", "size": 2609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/elliptic/ellint_rj.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/elliptic/ellint_rj.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/elliptic/ellint_rj.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["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.2203389831, "max_line_length": 156, "alphanum_fraction": 0.4396320429, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6610154405217571}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include <Eigen/Dense>\n#include <atomic>\n\nstd::atomic_size_t Ncalls(0);\n\nusing CEGO::EArray;\n\nauto linfit_coeffs(const EArray<double>& x, const EArray<double>& y, const std::size_t Nnum, const std::size_t Nden) {\n    Eigen::MatrixXd A(x.size(), Nnum + Nden);\n    Eigen::MatrixXd b = y;\n    for (auto i = 0; i < Nnum; ++i) {\n        A.col(i) = x.pow(i);\n    }\n    for (auto i = 0; i < Nden; ++i) {\n        A.col(i + Nnum) = -y*x.pow(i+1);\n    }\n    auto c = A.colPivHouseholderQr().solve(b).eval();\n    auto ycheck = (A * c).eval();\n    return c;\n}\n\nclass RatPoly {\npublic:\n    EArray<double> m_T, B2, m_LHS, m_x;\n    std::size_t m_Nnum, m_Nden;\n    \n    RatPoly(const std::size_t Nnum, const std::size_t Nden) : m_Nnum(Nnum), m_Nden(Nden)\n    {\n        // Data from second virial coefficient from Garberoglio for water, DOI: 10.1039/C8FD00092A\n        m_T.resize(21);\n        B2.resize(21);\n        m_T << 200, 225, 250, 273.15, 300, 325, 350, 375, 400, 450, 500, 550, 600, 700, 800, 900, 1000, 1250, 1500, 1750, 2000;\n        B2 << -2.3825E-02, -8.6200E-03, -3.9850E-03, -2.2590E-03, -1.3301E-03, -8.9350E-04, -6.3650E-04, -4.7840E-04, -3.7240E-04, -2.4480E-04, -1.7240E-04, -1.2830E-04, -9.8700E-05, -6.2460E-05, -4.1280E-05, -2.7580E-05, -1.8550E-05, -5.0400E-06, 2.0800E-06, 6.2000E-06, 8.8800E-06;\n        m_LHS = B2;\n        m_x = 200/m_T;\n        //solve_linear();\n    }\n    void solve_linear() {\n        std::cout << \"----------- LINEAR --------- \" << std::endl;\n        Eigen::ArrayXi indices = Eigen::ArrayXi::LinSpaced(m_Nnum + m_Nden, 0L, static_cast<int>(m_x.size()-1));\n        EArray<double> xx = m_x(indices), yy = m_LHS(indices);\n        EArray<double> c = linfit_coeffs(xx, yy, m_Nnum, m_Nden);\n        std::cout << c << std::endl;\n        double o = objective(c);\n        std::cout << \"objective: \" << o << std::endl;\n        EArray<double> devs = abs_rel_deviations(c).eval() * 100;\n        std::cout << \"relative(%) devs: \" << devs << std::endl;\n    }\n    template <typename TYPE> EArray<TYPE> eval_RHS(const EArray<double>& x, const EArray<TYPE> &c) {\n        EArray<TYPE> num = EArray<TYPE>::Zero(x.size()), \n                     den = EArray<TYPE>::Zero(x.size());\n        assert(m_Nnum + m_Nden == c.size());\n        for (auto i = 0; i < m_Nnum; ++i) {\n            num += c[i]*x.pow(i);\n        }\n        for (auto i = 0; i < m_Nden; ++i) {\n            den += c[m_Nnum+i]*x.pow(i+1);\n        }\n        return num/(1+den);\n    }\n    template <typename TYPE> TYPE objective(const EArray<TYPE>& c) {\n        return ((eval_RHS(m_x, c) - m_LHS)/m_LHS).square().sum();\n    }\n    template <typename TYPE> EArray<TYPE> abs_rel_deviations(const EArray<TYPE>& c) {\n        return ((eval_RHS(m_x, c) - m_LHS)/m_LHS).eval();\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const auto &c = dynamic_cast<const CEGO::NumericalIndividual<double>*>(pind)->get_coeff_array<double>();\n        return objective(c);\n    }  \n};\n\nint do_one()\n{\n    //std::srand((unsigned int)time(0));\n    std::size_t Nnum = 3, Nden = 5;\n\n    // Construct the bounds\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < Nnum; ++i) { \n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-1000, 1000)));\n    }\n    for (auto i = 0; i < Nden; ++i){\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-1000, 1000))); \n    }    \n    RatPoly rp(Nnum, Nden);\n   \n    auto Ncalls = 0;\n    CEGO::CostFunction<double> cost_wrapper = [&rp](const CEGO::AbstractIndividual*pind) {return rp.objective(pind); };\n    auto Ntotal_individuals = 1000;\n    auto Nlayers = 7;\n    auto layers = CEGO::Layers<double>(cost_wrapper, bounds.size(), Ntotal_individuals/Nlayers, Nlayers, 3);\n    layers.parallel = true;\n    layers.parallel_threads = 6;\n    layers.set_bounds(bounds);\n    layers.set_generation_mode(CEGO::GenerationOptions::LHS);\n    layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution_best1bin);\n    auto f = [&rp](const CEGO::EArray<double>& c) {return rp.objective<double>(c); };\n    auto f2 = [&rp](const CEGO::EArray<std::complex< double >>& c) {return rp.objective<std::complex<double>>(c); };\n    layers.add_gradient(f, f2);\n\n    auto flags = layers.get_evolver_flags();\n    flags[\"Nelite\"] = 1;\n    flags[\"Fmin\"] = 0.1;\n    flags[\"Fmax\"] = 1.1;\n    flags[\"CR\"] = 0.9;\n    layers.set_evolver_flags(flags);\n\n    std::vector<double> best_costs; \n    const double VTR = 2e-4;\n    auto startTime = std::chrono::system_clock::now();\n    bool success = false;\n    for (auto counter = 0; counter < 15000; ++counter) {\n        layers.do_generation();\n\n        if (counter % 1000 == 0) {\n            layers.gradient_minimizer();\n        }\n        \n        auto [best_cost, best_coeffs] = layers.get_best();\n        if (counter % 50 == 0) {\n            std::cout << counter << \": best: \" << best_cost << std::endl;\n            //std::cout << counter << \": best coeffs: \" << c << \"||\" << std::endl;\n            //std::cout << counter << \": obj again: \" << rp.objective(c) << \"||\" << std::endl;\n        }\n        if (best_cost < VTR) { success = true;  break; }\n    }\n    auto best_layer = layers.get_best();\n    auto best_coeffs = std::get<1>(best_layer);\n    std::cout << rp.abs_rel_deviations(best_coeffs)*100 << std::endl;\n    auto endTime = std::chrono::system_clock::now();\n    double elap = std::chrono::duration<double>(endTime - startTime).count();\n    std::cout << \"run:\" << elap << \" s\\n\";\n    std::cout << \"NFE:\" << Ncalls << std::endl;\n    return success;\n}\n\nint main() {\n    int N = (CEGO::is_CI() ? 3 : 100);\n    int good = 0;\n    for (auto i = 0; i < N; ++i) {\n        good += do_one();\n    }\n    std::cout << \"success:\" << good << \"/\" << N << std::endl;\n}", "meta": {"hexsha": "9b919ae4e42840db175b3c0a2773daeff8edbf0d", "size": 5745, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/fit_ratpoly_virial.cxx", "max_stars_repo_name": "usnistgov/CEGO", "max_stars_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/fit_ratpoly_virial.cxx", "max_issues_repo_name": "usnistgov/CEGO", "max_issues_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/fit_ratpoly_virial.cxx", "max_forks_repo_name": "usnistgov/CEGO", "max_forks_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 39.3493150685, "max_line_length": 283, "alphanum_fraction": 0.5730200174, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6610154315678062}}
{"text": "/*\n * elliptic_functions.cpp\n *\n * Copyright 2009-2012 Karsten Ahnert\n * Copyright 2009-2012 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\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint/config.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< double , 3 > state_type;\n\n/*\n * x1' = x2*x3\n * x2' = -x1*x3\n * x3' = -m*x1*x2\n */\n\nvoid rhs( const state_type &x , state_type &dxdt , const double t )\n{\n    static const double m = 0.51;\n\n    dxdt[0] = x[1]*x[2];\n    dxdt[1] = -x[0]*x[2];\n    dxdt[2] = -m*x[0]*x[1];\n}\n\nofstream out;\n\nvoid write_out( const state_type &x , const double t )\n{\n    out << t << '\\t' << x[0] << '\\t' << x[1] << '\\t' << x[2] << endl;\n}\n\nint main()\n{\n    bulirsch_stoer_dense_out< state_type > stepper( 1E-9 , 1E-9 , 1.0 , 0.0 );\n\n    state_type x1 = {{ 0.0 , 1.0 , 1.0 }};\n\n    double t = 0.0;\n    double dt = 0.01;\n\n    out.open( \"elliptic1.dat\" );\n    out.precision(16);\n    integrate_const( stepper , rhs , x1 , t , 100.0 , dt , write_out );\n    out.close();\n\n    state_type x2 = {{ 0.0 , 1.0 , 1.0 }};\n\n    out.open( \"elliptic2.dat\" );\n    out.precision(16);\n    integrate_adaptive( stepper , rhs , x2 , t , 100.0 , dt , write_out );\n    out.close();\n\n    typedef runge_kutta_dopri5< state_type > dopri5_type;\n    typedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n    typedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\n\n    dense_output_dopri5_type dopri5 = make_dense_output( 1E-9 , 1E-9 , dopri5_type() );\n    //dense_output_dopri5_type dopri5( controlled_dopri5_type( default_error_checker< double >( 1E-9 , 0.0 , 0.0 , 0.0 )  ) );\n\n    state_type x3 = {{ 0.0 , 1.0 , 1.0 }};\n\n    out.open( \"elliptic3.dat\" );\n    out.precision(16);\n    integrate_adaptive( dopri5 , rhs , x3 , t , 100.0 , dt , write_out );\n    out.close();\n}\n", "meta": {"hexsha": "fa9dbc6934489007f9f24fb3c90c4bebe0d889bd", "size": 2219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.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/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.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/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.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": 24.6555555556, "max_line_length": 126, "alphanum_fraction": 0.6421811627, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6610154216819453}}
{"text": "// Copyright Paul A. Bristow 2007.\r\n// Copyright John Maddock 2007.\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// test_normal.cpp\r\n\r\n// http://en.wikipedia.org/wiki/Normal_distribution\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm\r\n// Also:\r\n// Weisstein, Eric W. \"Normal Distribution.\"\r\n// From MathWorld--A Wolfram Web Resource.\r\n// http://mathworld.wolfram.com/NormalDistribution.html\r\n\r\n#include <pch.hpp>\r\n\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127) // conditional expression is constant\r\n// caused by using   if(std::numeric_limits<RealType>::has_infinity)\r\n// and   if (std::numeric_limits<RealType>::has_quiet_NaN)\r\n#endif\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\n#include <boost/math/distributions/normal.hpp>\r\n    using boost::math::normal_distribution;\r\n#include <boost/math/tools/test.hpp>\r\n\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n   using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n\r\ntemplate <class RealType>\r\nRealType NaivePDF(RealType mean, RealType sd, RealType x)\r\n{\r\n   // Deliberately naive PDF calculator again which\r\n   // we'll compare our pdf function.  However some\r\n   // published values to compare against would be better....\r\n   using namespace std;\r\n   return exp(-(x-mean)*(x-mean)/(2*sd*sd))/(sd * sqrt(2*boost::math::constants::pi<RealType>()));\r\n}\r\n\r\ntemplate <class RealType>\r\nvoid check_normal(RealType mean, RealType sd, RealType x, RealType p, RealType q, RealType tol)\r\n{\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         normal_distribution<RealType>(mean, sd),       // distribution.\r\n         x),                                            // random variable.\r\n         p,                                             // probability.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         complement(\r\n            normal_distribution<RealType>(mean, sd),    // distribution.\r\n            x)),                                        // random variable.\r\n         q,                                             // probability complement.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         normal_distribution<RealType>(mean, sd),       // distribution.\r\n         p),                                            // probability.\r\n         x,                                             // random variable.\r\n         tol);                                          // %tolerance.\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         complement(\r\n            normal_distribution<RealType>(mean, sd),    // distribution.\r\n            q)),                                        // probability complement.\r\n         x,                                             // random variable.\r\n         tol);                                          // %tolerance.\r\n}\r\n\r\ntemplate <class RealType>\r\nvoid test_spots(RealType)\r\n{\r\n   // Basic sanity checks\r\n   RealType tolerance = 1e-2f; // 1e-4 (as %)\r\n   // Some tests only pass at 1e-4 because values generated by\r\n   // http://faculty.vassar.edu/lowry/VassarStats.html\r\n   // give only 5 or 6 *fixed* places, so small values have fewer digits.\r\n\r\n  // Check some bad parameters to the distribution,\r\n   BOOST_CHECK_THROW(boost::math::normal_distribution<RealType> nbad1(0, 0), std::domain_error); // zero sd\r\n   BOOST_CHECK_THROW(boost::math::normal_distribution<RealType> nbad1(0, -1), std::domain_error); // negative sd\r\n\r\n  // Tests on extreme values of random variate x, if has numeric_limit infinity etc.\r\n    normal_distribution<RealType> N01;\r\n  if(std::numeric_limits<RealType>::has_infinity)\r\n  {\r\n    BOOST_CHECK_EQUAL(pdf(N01, +std::numeric_limits<RealType>::infinity()), 0); // x = + infinity, pdf = 0\r\n    BOOST_CHECK_EQUAL(pdf(N01, -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, pdf = 0\r\n    BOOST_CHECK_EQUAL(cdf(N01, +std::numeric_limits<RealType>::infinity()), 1); // x = + infinity, cdf = 1\r\n    BOOST_CHECK_EQUAL(cdf(N01, -std::numeric_limits<RealType>::infinity()), 0); // x = - infinity, cdf = 0\r\n    BOOST_CHECK_EQUAL(cdf(complement(N01, +std::numeric_limits<RealType>::infinity())), 0); // x = + infinity, c cdf = 0\r\n    BOOST_CHECK_EQUAL(cdf(complement(N01, -std::numeric_limits<RealType>::infinity())), 1); // x = - infinity, c cdf = 1\r\n    BOOST_CHECK_THROW(boost::math::normal_distribution<RealType> nbad1(std::numeric_limits<RealType>::infinity(), static_cast<RealType>(1)), std::domain_error); // +infinite mean\r\n     BOOST_CHECK_THROW(boost::math::normal_distribution<RealType> nbad1(-std::numeric_limits<RealType>::infinity(),  static_cast<RealType>(1)), std::domain_error); // -infinite mean\r\n     BOOST_CHECK_THROW(boost::math::normal_distribution<RealType> nbad1(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()), std::domain_error); // infinite sd\r\n  }\r\n\r\n  if (std::numeric_limits<RealType>::has_quiet_NaN)\r\n  {\r\n    // No longer allow x to be NaN, then these tests should throw.\r\n    BOOST_CHECK_THROW(pdf(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\r\n    BOOST_CHECK_THROW(cdf(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // x = NaN\r\n    BOOST_CHECK_THROW(cdf(complement(N01, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // x = + infinity\r\n    BOOST_CHECK_THROW(quantile(N01, +std::numeric_limits<RealType>::quiet_NaN()), std::domain_error); // p = + infinity\r\n    BOOST_CHECK_THROW(quantile(complement(N01, +std::numeric_limits<RealType>::quiet_NaN())), std::domain_error); // p = + infinity\r\n  }\r\n\r\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\r\n\r\n   check_normal(\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(4.8),\r\n      static_cast<RealType>(0.46017),\r\n      static_cast<RealType>(1 - 0.46017),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(5.2),\r\n      static_cast<RealType>(1 - 0.46017),\r\n      static_cast<RealType>(0.46017),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(2.2),\r\n      static_cast<RealType>(0.08076),\r\n      static_cast<RealType>(1 - 0.08076),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(7.8),\r\n      static_cast<RealType>(1 - 0.08076),\r\n      static_cast<RealType>(0.08076),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(-3),\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(-4.5),\r\n      static_cast<RealType>(0.38209),\r\n      static_cast<RealType>(1 - 0.38209),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(-3),\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(-1.5),\r\n      static_cast<RealType>(1 - 0.38209),\r\n      static_cast<RealType>(0.38209),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(-3),\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(-8.5),\r\n      static_cast<RealType>(0.13567),\r\n      static_cast<RealType>(1 - 0.13567),\r\n      tolerance);\r\n\r\n   check_normal(\r\n      static_cast<RealType>(-3),\r\n      static_cast<RealType>(5),\r\n      static_cast<RealType>(2.5),\r\n      static_cast<RealType>(1 - 0.13567),\r\n      static_cast<RealType>(0.13567),\r\n      tolerance);\r\n\r\n   //\r\n   // Tests for PDF: we know that the peak value is at 1/sqrt(2*pi)\r\n   //\r\n   tolerance = boost::math::tools::epsilon<RealType>() * 5 * 100; // 5 eps as a percentage\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(normal_distribution<RealType>(), static_cast<RealType>(0)),\r\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L), // 1/sqrt(2*pi)\r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(normal_distribution<RealType>(3), static_cast<RealType>(3)),\r\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L),\r\n      tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      pdf(normal_distribution<RealType>(3, 5), static_cast<RealType>(3)),\r\n      static_cast<RealType>(0.3989422804014326779399460599343818684759L / 5),\r\n      tolerance);\r\n\r\n   //\r\n   // Spot checks for mean = -5, sd = 6:\r\n   //\r\n   for(RealType x = -15; x < 5; x += 0.125)\r\n   {\r\n      BOOST_CHECK_CLOSE(\r\n         pdf(normal_distribution<RealType>(-5, 6), x),\r\n         NaivePDF(RealType(-5), RealType(6), x),\r\n         tolerance);\r\n   }\r\n\r\n    RealType tol2 = boost::math::tools::epsilon<RealType>() * 5;\r\n    normal_distribution<RealType> dist(8, 3);\r\n    RealType x = static_cast<RealType>(0.125);\r\n    using namespace std; // ADL of std names.\r\n    // mean:\r\n    BOOST_CHECK_CLOSE(\r\n       mean(dist)\r\n       , static_cast<RealType>(8), tol2);\r\n    // variance:\r\n    BOOST_CHECK_CLOSE(\r\n       variance(dist)\r\n       , static_cast<RealType>(9), tol2);\r\n    // std deviation:\r\n    BOOST_CHECK_CLOSE(\r\n       standard_deviation(dist)\r\n       , static_cast<RealType>(3), tol2);\r\n    // hazard:\r\n    BOOST_CHECK_CLOSE(\r\n       hazard(dist, x)\r\n       , pdf(dist, x) / cdf(complement(dist, x)), tol2);\r\n    // cumulative hazard:\r\n    BOOST_CHECK_CLOSE(\r\n       chf(dist, x)\r\n       , -log(cdf(complement(dist, x))), tol2);\r\n    // coefficient_of_variation:\r\n    BOOST_CHECK_CLOSE(\r\n       coefficient_of_variation(dist)\r\n       , standard_deviation(dist) / mean(dist), tol2);\r\n    // mode:\r\n    BOOST_CHECK_CLOSE(\r\n       mode(dist)\r\n       , static_cast<RealType>(8), tol2);\r\n\r\n    BOOST_CHECK_CLOSE(\r\n       median(dist)\r\n       , static_cast<RealType>(8), tol2);\r\n\r\n    // skewness:\r\n    BOOST_CHECK_CLOSE(\r\n       skewness(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n    // kertosis:\r\n    BOOST_CHECK_CLOSE(\r\n       kurtosis(dist)\r\n       , static_cast<RealType>(3), tol2);\r\n    // kertosis excess:\r\n    BOOST_CHECK_CLOSE(\r\n       kurtosis_excess(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n\r\n    normal_distribution<RealType> norm01(0, 1); // Test default (0, 1)\r\n    BOOST_CHECK_CLOSE(\r\n       mean(norm01),\r\n       static_cast<RealType>(0), 0); // Mean == zero\r\n\r\n    normal_distribution<RealType> defsd_norm01(0); // Test default (0, sd = 1)\r\n    BOOST_CHECK_CLOSE(\r\n       mean(defsd_norm01),\r\n       static_cast<RealType>(0), 0); // Mean == zero\r\n\r\n    normal_distribution<RealType> def_norm01; // Test default (0, sd = 1)\r\n    BOOST_CHECK_CLOSE(\r\n       mean(def_norm01),\r\n       static_cast<RealType>(0), 0); // Mean == zero\r\n\r\n    BOOST_CHECK_CLOSE(\r\n       standard_deviation(def_norm01),\r\n       static_cast<RealType>(1), 0); // Mean == zero\r\n\r\n\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n    // Check that can generate normal distribution using the two convenience methods:\r\n   boost::math::normal myf1(1., 2); // Using typedef\r\n   normal_distribution<> myf2(1., 2); // Using default RealType double.\r\n  boost::math::normal myn01; // Use default values.\r\n  // Note NOT myn01() as the compiler will interpret as a function!\r\n\r\n  // Check the synonyms, provided to allow generic use of find_location and find_scale.\r\n  BOOST_CHECK_EQUAL(myn01.mean(), myn01.location());\r\n  BOOST_CHECK_EQUAL(myn01.standard_deviation(), myn01.scale());\r\n\r\n    // Basic sanity-check spot values.\r\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n\r\n   return 0;\r\n} // int test_main(int, char* [])\r\n\r\n/*\r\n\r\nOutput:\r\n\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_normal.exe\"\r\nRunning 1 test case...\r\nTolerance for type float is 0.01 %\r\nTolerance for type double is 0.01 %\r\nTolerance for type long double is 0.01 %\r\nTolerance for type class boost::math::concepts::real_concept is 0.01 %\r\n*** No errors detected\r\n\r\n*/\r\n\r\n\r\n", "meta": {"hexsha": "a03963bc4ac2c5c22989b450f791f445fe8b37ee", "size": 12917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_normal.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/test/test_normal.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/test/test_normal.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.906626506, "max_line_length": 182, "alphanum_fraction": 0.6239064798, "num_tokens": 3265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6609147039603557}}
{"text": "#include \"geometrycentral/surface/trace_geodesic.h\"\n\n#include \"geometrycentral/surface/barycentric_coordinate_helpers.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\nnamespace surface {\n\n// The default trace options\nconst TraceOptions defaultTraceOptions;\n\n// Helper functions which support tracing\nnamespace {\n\n\n// === Geometric subroutines for tracing\n\n// a few parameters\nconst double TRACE_EPS_TIGHT = 1e-12;\nconst double TRACE_EPS_LOOSE = 1e-9;\nconst bool TRACE_PRINT = false;\n\ninline std::array<Vector2, 3> vertexCoordinatesInTriangle(IntrinsicGeometryInterface& geom, Face face) {\n  return {Vector2{0., 0.}, geom.halfedgeVectorsInFace[face.halfedge()],\n          -geom.halfedgeVectorsInFace[face.halfedge().next().next()]};\n}\n\ninline Vector3 faceCoordsToBaryCoords(const std::array<Vector2, 3>& vertCoords, Vector2 faceCoord) {\n\n  // Warning: bakes in assumption that vertCoords[0] == (0,0)\n\n  // Invert the system to solve for coordinates\n  double b2 = faceCoord.y / vertCoords[2].y;\n  b2 = clamp(b2, 0.0, 1.0); // comment these to get useful errors rather than clamping\n  double b1 = (faceCoord.x - b2 * vertCoords[2].x) / vertCoords[1].x;\n  b1 = clamp(b1, 0.0, 1.0 - b2);\n  double b0 = 1.0 - b1 - b2;\n  b0 = clamp(b0, 0.0, 1.0);\n  Vector3 result{b0, b1, b2};\n\n  return result;\n}\n\ninline Vector2 baryCoordsToFaceCoords(const std::array<Vector2, 3>& vertCoords, Vector3 baryCoord) {\n  return vertCoords[0] * baryCoord.x + vertCoords[1] * baryCoord.y + vertCoords[2] * baryCoord.z;\n}\n\ninline Vector2 barycentricDisplacementToCartesian(const std::array<Vector2, 3>& vertCoords, Vector3 baryVec) {\n  // Note: happens to be the same as baryCoordsToFaceCoords()\n  return vertCoords[0] * baryVec.x + vertCoords[1] * baryVec.y + vertCoords[2] * baryVec.z;\n}\n\ninline Vector3 cartesianVectorToBarycentric(const std::array<Vector2, 3>& vertCoords, Vector2 faceVec) {\n\n\n  // Build matrix for linear transform problem\n  // (last constraint comes from chosing the displacement vector with sum = 0)\n  Eigen::Matrix3d A;\n  Eigen::Vector3d rhs;\n  const std::array<Vector2, 3>& c = vertCoords; // short name\n  A << c[0].x, c[1].x, c[2].x, c[0].y, c[1].y, c[2].y, 1., 1., 1.;\n  rhs << faceVec.x, faceVec.y, 0.;\n\n  // Solve\n  Eigen::Vector3d result = A.colPivHouseholderQr().solve(rhs);\n  Vector3 resultBary{result(0), result(1), result(2)};\n\n  resultBary = normalizeBarycentricDisplacement(resultBary);\n\n  if (TRACE_PRINT) {\n    cout << \"       cartesianVectorToBarycentric() \" << endl;\n    cout << \"         input = \" << faceVec << endl;\n    cout << \"         positions = \" << vertCoords[0] << \" \" << vertCoords[1] << \" \" << vertCoords[2] << endl;\n    cout << \"         transform result = \" << resultBary << endl;\n    cout << \"         transform back = \" << barycentricDisplacementToCartesian(vertCoords, resultBary) << endl;\n    cout << \" A = \" << endl << A << endl;\n    cout << \" rhs = \" << endl << rhs << endl;\n    cout << \" Ax = \" << endl << A * result << endl;\n  }\n\n  return resultBary;\n}\n\n// Converts tCross from halfedge to edge coordinates, handling sign conventions\ninline double convertTToEdge(Halfedge he, double tCross) {\n  if (he == he.edge().halfedge()) return tCross;\n  return 1.0 - tCross;\n}\n// Converts vectors in halfedge basis from halfedge to edge coordinates, handling sign conventions\ninline Vector2 convertVecToEdge(Halfedge he, Vector2 halfedgeVec) {\n  if (he == he.edge().halfedge()) return halfedgeVec;\n  return -halfedgeVec;\n}\n\n\n// === Tracing subroutines\n\n\n// Return type from tracing subroutines\n// When trace ends, will set newFace = Face() and newVector = Vector3::zero(). only then is incomingDirToPoint 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 traceVectorInHalfedgeDir; // vector to keep tracing, measured against crossHe\n  double traceVectorInHalfedgeLen;  // vector to keep tracing, measured against crossHe\n\n  // If the trace ends (terminated == true)\n  SurfacePoint endPoint;      // ending location\n  Vector2 incomingDirToPoint; // 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 vecCartesianDir, double vecCartesianLen,\n                                             std::array<bool, 3> edgeIsHittable, const TraceOptions& traceOptions) {\n\n  // Gather values\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n  Vector3 triangleLengths{geom.edgeLengths[face.halfedge().edge()], geom.edgeLengths[face.halfedge().next().edge()],\n                          geom.edgeLengths[face.halfedge().next().next().edge()]};\n\n  if (sum(startPoint) < 0.5) {\n    if (TRACE_PRINT) {\n      cout << \"  bad bary point: \" << startPoint << endl;\n    }\n    if (traceOptions.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         << vecCartesianDir << \" \" << vecCartesianLen << endl;\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"  vec bary  = \" << vecBary << endl;\n    cout << \"  reconvert = \" << cartesianVectorToBarycentric(vertexCoords, vecCartesianDir) * vecCartesianLen << 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\n  /*\n  if (isInsideTriangle(endPoint)) {\n    // Fancy test if ending on edges\n    // (to detect when we're within eps of edge)\n    bool foundEpsEdge = false;\n    if (traceOptions.allowEndOnEdge) {\n      double A = 0.5 * cross(vertexCoords[1] - vertexCoords[0], vertexCoords[2] - vertexCoords[0]);\n      Halfedge endHe = face.halfedge();\n      for (int i = 0; i < 3; i++) {\n        double dist = 2. * endPoint[i] * A / triangleLengths[i]; // perp distance to edge\n        if (endPoint[i] > 0 && dist < traceOptions.allowEndOnEdgeEps) {\n          // force the process below to hit this edge, let other logic proceed\n          edgeIsHittable[i] = true;\n          edgeIsHittable[(i + 1) % 3] = false;\n          edgeIsHittable[(i + 2) % 3] = false;\n          foundEpsEdge = true;\n          break;\n        }\n      }\n    }\n    // Simple test if not ending on edges\n    if (!foundEpsEdge) {\n      // The trace ended! Call it a day.\n      TraceSubResult result;\n      result.terminated = true;\n      result.endPoint = SurfacePoint(face, endPoint);\n      result.incomingDirToPoint = vecCartesian;\n      return result;\n    }\n  }\n  */\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.incomingDirToPoint = vecCartesianDir;\n    return result;\n  }\n\n\n  // The vector did not end in this triangle. Pick an appropriate point along some edge\n  double tRay = std::numeric_limits<double>::infinity();\n  Halfedge crossHe = Halfedge();\n  int iOppVertEnd = -777;\n  Halfedge currHe = face.halfedge();\n  for (int i = 0; i < 3; i++) {\n    currHe = currHe.next(); // always opposite the i'th vertex\n\n    // Check the crossing\n    double tRayThisRaw = -startPoint[i] / vecBary[i];\n    double tRayThis = clamp(tRayThisRaw, 0., 1. - TRACE_EPS_LOOSE);\n\n    if (TRACE_PRINT) {\n      cout << \"    considering intersection:\" << endl;\n      cout << std::boolalpha;\n      cout << \"      hittable[(i+1)%3]: \" << edgeIsHittable[(i + 1) % 3] << endl;\n      cout << \"      vecBary[i]: \" << vecBary[i] << endl;\n      cout << \"      startPoint[i]: \" << startPoint[i] << endl;\n      cout << \"      tRayThisRaw: \" << tRayThisRaw << endl;\n      cout << \"      tRayThis: \" << tRayThis << endl;\n    }\n\n\n    if (!edgeIsHittable[(i + 1) % 3] || vecBary[i] >= 0) {\n      // note should ALWAYS satisfy precondition that vecBary[i] is negative for at least one hittable edge.\n      // if not, fix projection of inputs in caller\n      continue;\n    }\n\n    if (tRayThisRaw < tRay) {\n      // This is the new closest intersection\n      tRay = tRayThisRaw;\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  // Clamp to a sane range\n  tRay = clamp(tRay, 0., 1. - TRACE_EPS_LOOSE);\n\n\n  if (crossHe == Halfedge()) {\n    if (traceOptions.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.incomingDirToPoint = vecCartesianDir;\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  double lenRemaining = (1.0 - tRay) * vecCartesianLen;\n  Vector2 crossingEdgeVec = (vertexCoords[(iOppVertEnd + 2) % 3] - vertexCoords[(iOppVertEnd + 1) % 3]);\n  Vector2 remainingDirInHalfedge = vecCartesianDir / crossingEdgeVec.normalize();\n  if (!isfinite(remainingDirInHalfedge)) {\n    if (TRACE_PRINT) {\n      cout << \"    NON FINITE REMAINING TRACE\" << endl;\n      cout << \"    lenRemaining = \" << lenRemaining << endl;\n      cout << \"    crossingEdgeVec = \" << crossingEdgeVec << endl;\n      cout << \"    remainingDirInHalfedge = \" << remainingDirInHalfedge << endl;\n    }\n\n    if (traceOptions.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() || (traceOptions.barrierEdges && (*traceOptions.barrierEdges)[crossHe.edge()])) {\n    // Build the result\n    TraceSubResult result;\n    result.terminated = true;\n    result.endPoint = SurfacePoint(crossHe.edge(), convertTToEdge(crossHe, tCross));\n    result.incomingDirToPoint = remainingDirInHalfedge;\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.traceVectorInHalfedgeDir = remainingDirInHalfedge;\n  result.traceVectorInHalfedgeLen = lenRemaining;\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,\n                                             Vector2 vecCartesianDir, double vecCartesianLen,\n                                             const TraceOptions& traceOptions) {\n\n  // Gather some values\n  Face face = towardsHe.face();\n  Halfedge rootHe = towardsHe.next().next();\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n  if (TRACE_PRINT) {\n    cout << \"  face trace towards edge \" << towardsHe << \" vec = \" << vecCartesianDir << 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, vecCartesianDir) * vecCartesianLen;\n  Vector3 vecBaryFromRoot = permuteBarycentricFromCanonical(vecBaryCanonical, towardsHe.next().next());\n\n  if (TRACE_PRINT) {\n    cout << \"  canonical bary vec\" << vecBaryCanonical << endl;\n    cout << \"  bary vec before projection \" << vecBaryFromRoot << endl;\n  }\n\n  { // Project to ensure the vector is inside the triangle\n    vecBaryFromRoot.x = std::fmin(vecBaryFromRoot.x, TRACE_EPS_TIGHT);\n    vecBaryFromRoot.y = std::fmax(vecBaryFromRoot.y, 0.);\n    vecBaryFromRoot.z = std::fmax(vecBaryFromRoot.z, 0.);\n\n    // Manual displacement projection to sum to 0 while perserving above properties\n    double diff = -sum(vecBaryFromRoot);\n    if (diff > 0) {\n      vecBaryFromRoot.y += diff / 2;\n      vecBaryFromRoot.z += diff / 2;\n    } else {\n      vecBaryFromRoot.x += diff;\n    }\n  }\n\n  if (TRACE_PRINT) {\n    cout << \"  bary vec after projection \" << vecBaryFromRoot << endl;\n  }\n\n  // Assemble data to call the general trace function\n  int iHe = halfedgeIndexInTriangle(towardsHe.next().next());\n  Vector3 startPoint{0., 0., 0.};\n  startPoint[iHe] = 1.0;\n  Vector3 vecBaryCanonicalFixed = permuteBarycentricToCanonical(vecBaryFromRoot, rootHe);\n  std::array<bool, 3> hittable = {{false, false, false}};\n  hittable[(iHe + 1) % 3] = true;\n\n  return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixed, vecCartesianDir, vecCartesianLen,\n                                hittable, traceOptions);\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 traceVecInHalfedgeDir, double traceVecInHalfedgeLen,\n                                          const TraceOptions& traceOptions) {\n\n  // Possibly terminate at this edge\n  /*\n  std::cout << \"  norm tracevec = \" << norm(traceVecInHalfedge) << std::endl;\n  if (traceOptions.allowEndOnEdge && norm(traceVecInHalfedge) < traceOptions.allowEndOnEdgeEps) {\n    std::cout << \"TERMINATING AT EDGE\" << std::endl;\n    TraceSubResult result;\n    result.terminated = true;\n    result.endPoint = SurfacePoint(fromHe, tCrossFrom);\n    result.incomingDirToPoint = traceVecInHalfedge;\n    if (fromHe != fromHe.edge().halfedge()) result.incomingDirToPoint *= -1.;\n    return result;\n  }\n  */\n\n  // Gather some values\n  Halfedge faceHe = fromHe.twin(); // the halfedge in hte face we're heading in to\n  Face face = faceHe.face();\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n  if (TRACE_PRINT) cout << \"  face trace from edge \" << fromHe << \" vec = \" << traceVecInHalfedgeDir << endl;\n\n\n  // Project the cartesian vector to definitely point in the right direction\n  Vector2 traceVecInFaceHalfedgeDir = -traceVecInHalfedgeDir;\n  if (TRACE_PRINT) cout << \"    vec in face before project \" << traceVecInFaceHalfedgeDir << endl;\n  traceVecInFaceHalfedgeDir.y = std::fmax(traceVecInFaceHalfedgeDir.y, TRACE_EPS_LOOSE);\n  if (TRACE_PRINT) cout << \"    vec in face after project \" << traceVecInFaceHalfedgeDir << endl;\n\n  // Convert to face coordinates\n  Vector2 heDir = geom.halfedgeVectorsInFace[faceHe].normalize();\n  Vector2 traceVecInFaceDir = heDir * traceVecInFaceHalfedgeDir;\n  if (TRACE_PRINT) cout << \"    traceVec in face \" << traceVecInFaceDir << endl;\n\n  // Convert to barycentric\n  Vector3 vecBaryCanonicalDir = cartesianVectorToBarycentric(vertexCoords, traceVecInFaceDir);\n  if (TRACE_PRINT) cout << \"    vecBaryCanonical \" << vecBaryCanonicalDir << endl;\n  Vector3 vecBaryFromEdgeDir = permuteBarycentricFromCanonical(vecBaryCanonicalDir, faceHe);\n\n  if (TRACE_PRINT) cout << \"    vec bary before project \" << vecBaryFromEdgeDir << endl;\n  { // Project to ensure the vector is in the right direction\n    vecBaryFromEdgeDir.z = std::fmax(vecBaryFromEdgeDir.z, TRACE_EPS_TIGHT);\n\n    // Manual displacement projection to sum to 0 which perserves above properties\n    double diff = -sum(vecBaryFromEdgeDir);\n    if (diff > 0) {\n      vecBaryFromEdgeDir.z += diff;\n    } else {\n      vecBaryFromEdgeDir.x += diff / 3.;\n      vecBaryFromEdgeDir.y += diff / 3.;\n      vecBaryFromEdgeDir.z += diff / 3.;\n    }\n  }\n  if (TRACE_PRINT) cout << \"    vec bary after project \" << vecBaryFromEdgeDir << 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 vecBaryCanonicalFixedDir = permuteBarycentricToCanonical(vecBaryFromEdgeDir, faceHe);\n  if (TRACE_PRINT) {\n    cout << \"    iHe = \" << iHe << endl;\n    cout << \"    startPoint = \" << startPoint << endl;\n    cout << \"    canonical bary \" << vecBaryCanonicalFixedDir << endl;\n  }\n  std::array<bool, 3> hittable = {{true, true, true}};\n  hittable[iHe] = false;\n\n  return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixedDir * traceVecInHalfedgeLen,\n                                traceVecInFaceDir, traceVecInHalfedgeLen, hittable, traceOptions);\n}\n\n\n// Trace starting from an edge\ninline TraceSubResult traceGeodesic_fromEdge(IntrinsicGeometryInterface& geom, Edge currEdge, double tEdge,\n                                             Vector2 currVecDir, double currVecLen, const TraceOptions& traceOptions) {\n\n  if (TRACE_PRINT) cout << \"  edge trace \" << currEdge << \" tEdge = \" << tEdge << \" edge vec = \" << currVecDir << 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 halfedgeTraceDir;\n  if (currVecDir.y >= 0.) {\n    traceHe = currEdge.halfedge().twin();\n    halfedgeTraceDir = -currVecDir;\n    tEdge = 1.0 - tEdge;\n  } else {\n    traceHe = currEdge.halfedge();\n\n    // Can't go anyywhere if boundary halfedge\n    if (!traceHe.twin().isInterior() || (traceOptions.barrierEdges && (*traceOptions.barrierEdges)[traceHe.edge()])) {\n      TraceSubResult result;\n      result.terminated = true;\n      result.endPoint = SurfacePoint(currEdge, tEdge);\n      result.incomingDirToPoint = currVecDir;\n\n      return result;\n    }\n\n    halfedgeTraceDir = currVecDir;\n  }\n\n  return traceInFaceFromEdge(geom, traceHe, tEdge, halfedgeTraceDir, currVecLen, traceOptions);\n}\n\n// Trace starting from a face\ninline TraceSubResult traceGeodesic_fromFace(IntrinsicGeometryInterface& geom, Face currFace, Vector3 faceBary,\n                                             Vector2 currVecDir, double currVecLen, const TraceOptions& traceOptions) {\n\n  // Convert the vector to barycentric\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, currFace);\n  Vector3 vecBary = cartesianVectorToBarycentric(vertexCoords, currVecDir) * currVecLen;\n\n  return traceInFaceBarycentric(geom, currFace, faceBary, vecBary, currVecDir, currVecLen, {true, true, true},\n                                traceOptions);\n}\n\n\n// Trace starting from a vertex (with a rescaled cartesian vector)\ninline TraceSubResult traceGeodesic_fromVertex(IntrinsicGeometryInterface& geom, Vertex currVert, Vector2 currVecDir,\n                                               double currVecLen, const TraceOptions& traceOptions) {\n  if (TRACE_PRINT) cout << \"  vertex trace \" << currVert << \" edge vec = \" << currVecDir << endl;\n\n  // Find the halfedge opening the wedge where tracing will start\n  Halfedge wedgeHe;\n  Vector2 traceDirRelativeToStart;\n\n  // Normally, one of the interval tests below will return positive and we'll simply launch the trace in to that\n  // interval. However, due to numerical misfortune, it is possible that none of the intervals will test positive. In\n  // that case, we'll simply launch along whichever halfedge was closest.\n  double minCross = std::numeric_limits<double>::infinity();\n  Halfedge minCrossHalfedge;\n  Vector2 minCrossHalfedgeDir; // 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, currVecDir);\n    double crossEnd = cross(intervalEnd, currVecDir);\n    if (crossStart > 0. && crossEnd <= 0.) {\n      wedgeHe = currHe;\n      traceDirRelativeToStart = currVecDir / intervalStart;\n      if (TRACE_PRINT) cout << \"    wedge match! relative angle \" << traceDirRelativeToStart << 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      minCrossHalfedgeDir = Vector2{1, TRACE_EPS_TIGHT};\n    }\n    if (std::fabs(crossEnd) < minCross) {\n      minCross = std::fabs(crossEnd);\n      minCrossHalfedge = nextHe;\n      minCrossHalfedgeDir = Vector2{1, -TRACE_EPS_TIGHT};\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 \" << minCrossHalfedgeDir << endl;\n    // Convert to edge coordinates\n    currVecDir = convertVecToEdge(minCrossHalfedge, minCrossHalfedgeDir);\n    return traceGeodesic_fromEdge(geom, minCrossHalfedge.edge(), convertTToEdge(minCrossHalfedge, 0.), currVecDir,\n                                  currVecLen, traceOptions);\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  traceDirRelativeToStart = traceDirRelativeToStart.pow(geom.vertexAngleSums[currVert] / sum);\n  traceDirRelativeToStart = traceDirRelativeToStart.normalize();\n\n  // Compute the starting vector\n  Vector2 startDirInFace = geom.halfedgeVectorsInFace[wedgeHe].normalize();\n  Vector2 traceDirInFace = traceDirRelativeToStart * 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 dir in face \" << traceDirInFace << endl;\n  }\n\n\n  return traceInFaceTowardsEdge(geom, wedgeHe.next(), traceDirInFace, currVecLen, traceOptions);\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                             const TraceOptions& traceOptions) {\n\n  // Now, points are always in faces. Trace until termination.\n  size_t iter = 0;\n  while (!prevTraceEnd.terminated) {\n\n    // Terminate on iterations\n    if (traceOptions.maxIters != INVALID_IND && iter >= traceOptions.maxIters) {\n\n      // Use the last trace as ending data\n      result.endPoint = SurfacePoint(prevTraceEnd.crossHe, prevTraceEnd.tCross);\n      result.endingDir = prevTraceEnd.traceVectorInHalfedgeDir;\n\n      return;\n    }\n\n\n    // Construct a point where the previous trace ended\n    if (traceOptions.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           << \" dir = \" << prevTraceEnd.traceVectorInHalfedgeDir << endl;\n    }\n\n    // Execute the next step of tracing\n    prevTraceEnd =\n        traceInFaceFromEdge(geom, prevTraceEnd.crossHe, prevTraceEnd.tCross, prevTraceEnd.traceVectorInHalfedgeDir,\n                            prevTraceEnd.traceVectorInHalfedgeLen, traceOptions);\n    iter++;\n  }\n\n  // Add the final ending point\n  if (traceOptions.includePath) {\n    result.pathPoints.push_back(prevTraceEnd.endPoint);\n  }\n  result.endPoint = prevTraceEnd.endPoint;\n  result.endingDir = prevTraceEnd.incomingDirToPoint;\n\n  // if (std::abs(norm(result.endingDir) - 1.) > .1) throw std::runtime_error(\"norm problem\");\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                                  const TraceOptions& traceOptions) {\n  geom.requireVertexAngleSums();\n  geom.requireHalfedgeVectorsInVertex();\n  geom.requireHalfedgeVectorsInFace();\n\n  // The output data\n  TraceGeodesicResult result;\n  result.hasPath = traceOptions.includePath;\n  if (traceOptions.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 (traceOptions.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, unit(traceVec), norm(traceVec), traceOptions);\n    break;\n  }\n  case SurfacePointType::Edge: {\n    prevTraceEnd =\n        traceGeodesic_fromEdge(geom, startP.edge, startP.tEdge, unit(traceVec), norm(traceVec), traceOptions);\n    break;\n  }\n  case SurfacePointType::Face: {\n    prevTraceEnd =\n        traceGeodesic_fromFace(geom, startP.face, startP.faceCoords, unit(traceVec), norm(traceVec), traceOptions);\n    break;\n  }\n  }\n\n  // Keep tracing through triangles until finished\n  traceGeodesic_iterative(geom, result, prevTraceEnd, traceOptions);\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, const TraceOptions& traceOptions) {\n\n\n  geom.requireVertexAngleSums();\n  geom.requireHalfedgeVectorsInVertex();\n  geom.requireHalfedgeVectorsInFace();\n\n  // The output data\n  TraceGeodesicResult result;\n  result.hasPath = traceOptions.includePath;\n  if (traceOptions.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 (traceOptions.errorOnProblem) {\n      throw std::runtime_error(\"zero vec passed to trace, do something good here\");\n    }\n\n    result.endingDir = Vector2::zero();\n    return result;\n  }\n\n  // Make sure the input is sane\n  startBary = projectInsideTriangle(startBary);\n  traceBaryVec -= Vector3::constant(sum(traceBaryVec) / 3);\n\n  // Construct the cartesian equivalent\n  std::array<Vector2, 3> vertexCoords = vertexCoordinatesInTriangle(geom, startFace);\n  Vector2 traceVectorCartesian = barycentricDisplacementToCartesian(vertexCoords, traceBaryVec);\n\n  // Trace the first point starting inside the face\n  TraceSubResult prevTraceEnd =\n      traceInFaceBarycentric(geom, startFace, startBary, traceBaryVec, unit(traceVectorCartesian),\n                             norm(traceVectorCartesian), {true, true, true}, traceOptions);\n\n  // Keep tracing through triangles until finished\n  traceGeodesic_iterative(geom, result, prevTraceEnd, traceOptions);\n\n  geom.unrequireVertexAngleSums();\n  geom.unrequireHalfedgeVectorsInVertex();\n  geom.unrequireHalfedgeVectorsInFace();\n\n  return result;\n}\n\nbool trimTraceResult(TraceGeodesicResult& traceResult, Vertex targetVertex) {\n\n  while (traceResult.pathPoints.size() > 1) {\n    SurfacePoint& b = traceResult.pathPoints.back();\n\n    // Remove any edge crossings connected to the target vertex: they're numerical noise because we're already in the\n    // 1-ring\n    if (b.type == SurfacePointType::Edge &&\n        (b.edge.halfedge().vertex() == targetVertex || b.edge.halfedge().twin().vertex() == targetVertex)) {\n      traceResult.pathPoints.pop_back();\n      traceResult.endingDir = Vector2::undefined();\n      continue;\n    }\n\n    // Always trim face points\n    if (b.type == SurfacePointType::Face) {\n      traceResult.pathPoints.pop_back();\n      traceResult.endingDir = Vector2::undefined();\n      continue;\n    }\n\n    // Always trim vertex points\n    if (b.type == SurfacePointType::Vertex) {\n      traceResult.pathPoints.pop_back();\n      traceResult.endingDir = Vector2::undefined();\n      continue;\n    }\n\n    // we're done here\n    break;\n  }\n\n\n  // Check success\n  if (traceResult.pathPoints.empty()) return false;\n\n  SurfacePoint& b = traceResult.pathPoints.back();\n\n  switch (b.type) {\n  case SurfacePointType::Vertex: {\n    if (b.vertex == targetVertex) return true;\n    for (Vertex n : b.vertex.adjacentVertices()) {\n      if (n == targetVertex) return true;\n    }\n    break;\n  }\n  case SurfacePointType::Edge: {\n    Halfedge bHe = b.edge.halfedge();\n    if (bHe.vertex() == targetVertex) return true;\n    if (bHe.twin().vertex() == targetVertex) return true;\n    if (bHe.next().next().vertex() == targetVertex) return true;\n    if (bHe.twin().next().next().vertex() == targetVertex) return true;\n    return false;\n    break;\n  }\n  case SurfacePointType::Face: {\n    for (Vertex v : b.face.adjacentVertices()) {\n      if (v == targetVertex) return true;\n    }\n    return false;\n    break;\n  }\n  }\n\n  return false;\n}\n\n\n} // namespace surface\n} // namespace geometrycentral\n", "meta": {"hexsha": "2cbaa9057a3bd5287446b11a528b6f7147bac83d", "size": 33307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface/trace_geodesic.cpp", "max_stars_repo_name": "softwarecapital/geometry-central", "max_stars_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 539.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T16:38:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:56:22.000Z", "max_issues_repo_path": "src/surface/trace_geodesic.cpp", "max_issues_repo_name": "softwarecapital/geometry-central", "max_issues_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T13:19:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T18:40:33.000Z", "max_forks_repo_path": "src/surface/trace_geodesic.cpp", "max_forks_repo_name": "softwarecapital/geometry-central", "max_forks_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2018-05-12T17:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T15:01:26.000Z", "avg_line_length": 38.2399540758, "max_line_length": 120, "alphanum_fraction": 0.6775752845, "num_tokens": 8852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6609146942257003}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\r\ntypedef math_types::vector_type                                vector_type;\r\ntypedef std::vector<double>                                    knot_container;\r\ntypedef std::vector<vector_type>                               point_container;\r\n\r\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_compute_point_on_spline);\r\n\r\nBOOST_AUTO_TEST_CASE(test_compute_point_on_spline)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 3\r\n  U.push_back(1.0);\r\n  U.push_back(2.0);\r\n  U.push_back(3.0);\r\n  U.push_back(4.0);  // n = 6  => |P| = 7\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);  // m = 9  => |U| = 10\r\n\r\n  // Indices of basis functions belongs to the interval [0..n]\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n  vector_type p4(2);  p4(0) = 4.0; p4(1) = 0.0;\r\n  vector_type p5(2);  p5(0) = 5.0; p5(1) = 0.0;\r\n  vector_type p6(2);  p6(0) = 6.0; p6(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n  P.push_back(p4);\r\n  P.push_back(p5);\r\n  P.push_back(p6);\r\n\r\n  spline_type spline(3,U,P);\r\n\r\n  double const tolerance = 0.00001;\r\n\r\n  vector_type q0(2);\r\n  vector_type q1(2);\r\n  vector_type q2(2);\r\n  vector_type q3(2);\r\n  vector_type q4(2);\r\n  vector_type q5(2);\r\n  vector_type q6(2);\r\n\r\n  double const du = 5.0/6.0;\r\n  double u = 0.0;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q0);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q1);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q2);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q3);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q4);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q5);\r\n  u += du;\r\n  OpenTissue::spline::compute_point_on_spline(u, spline, q6);\r\n\r\n  BOOST_CHECK_CLOSE( p0(0), q0(0), tolerance );\r\n  BOOST_CHECK_CLOSE( p0(1), q0(1), tolerance );\r\n\r\n  BOOST_CHECK_CLOSE( q0(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q1(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q2(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q3(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q4(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q5(1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( q6(1), 0.0, tolerance );\r\n\r\n  BOOST_CHECK( q1(0) > q0(0));\r\n  BOOST_CHECK( q2(0) > q1(0));\r\n  BOOST_CHECK( q3(0) > q2(0));\r\n  BOOST_CHECK( q4(0) > q3(0));\r\n  BOOST_CHECK( q5(0) > q4(0));\r\n  BOOST_CHECK( q6(0) > q5(0));\r\n\r\n  BOOST_CHECK_CLOSE( p6(0), q6(0), tolerance );\r\n  BOOST_CHECK_CLOSE( p6(1), q6(1), tolerance );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(test_bezier_curve_case)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  \r\n  U.push_back(0.0);   \r\n  U.push_back(1.0);\r\n  U.push_back(1.0);\r\n  U.push_back(1.0);  \r\n  U.push_back(1.0);  \r\n\r\n  // k = 4\r\n  // n = 3  => |P| = 4\r\n  // m = 7  => |U| = 8\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 1.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 1.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n\r\n  spline_type bezier(4,U,P);\r\n\r\n  double const tolerance = 10e-15;\r\n\r\n  // Now we have constructed the equivalent of a bezier curve\r\n  //\r\n  //   B(t) =     a t^3 +   b t^2 + c t + d\r\n  //   B'(t) =  3 a t^2 + 2 b t   + c \r\n  //\r\n  //   B(0) = p0  = d\r\n  //   B(1) = p3  = a + b + c + d\r\n  //   B'(0) = 3*(p1-p0) = c\r\n  //   B'(1) = 3*(p1-p0) = 3 a + 2 b + c\r\n  //\r\n  //  working out the equations one would get\r\n  vector_type a = -1*p0 + 3*p1 - 3*p2 + 1*p3;\r\n  vector_type b =  3*p0 - 6*p1 + 3*p2;\r\n  vector_type c = -3*p0 + 3*p1;\r\n  vector_type d =  1*p0;\r\n\r\n  double u = 0.0;\r\n  int const N = 11;\r\n  double const du = 1.0 / (N-1);\r\n  for(int i=0;i<N;++i)\r\n  {\r\n    vector_type p(2);\r\n    OpenTissue::spline::compute_point_on_spline(u, bezier, p);\r\n    vector_type q(2);\r\n    q = (u*u*u)*a + (u*u)*b + u*c + d;\r\n    BOOST_CHECK( std::fabs( p(0) - q(0) ) < tolerance );\r\n    BOOST_CHECK( std::fabs( p(1) - q(1) ) < tolerance );\r\n    u += du;\r\n  }\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "c188e9d0dc3d974d54f048144c395dedb93ea75d", "size": 5004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/compute_point/src/unit_compute_point.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/compute_point/src/unit_compute_point.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/compute_point/src/unit_compute_point.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 28.7586206897, "max_line_length": 84, "alphanum_fraction": 0.5939248601, "num_tokens": 1856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6608736518255479}}
{"text": "//#define EIGEN_RUNTIME_NO_MALLOC\n\n#include \"linmath.h\"\n#include \"sv_matrix.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <Eigen/SVD>\n\n#include <iostream>\n\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n#define EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v) EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v)\n#else\n#define EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v)\n#endif\n\n#ifdef SV_MATRIX_IS_COL_MAJOR\ntypedef Eigen::Matrix<FLT, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 50, 50> MatrixType;\n#else\ntypedef Eigen::Matrix<FLT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor, 50, 50> MatrixType;\n#endif\ntypedef Eigen::Map<MatrixType> MapType;\n\n#define CONVERT_TO_EIGEN(A) MapType(A ? SV_FLT_PTR(A) : 0, A ? (A)->rows : 0, A ? (A)->cols : 0)\n\ndouble svInvert(const SvMat *srcarr, SvMat *dstarr, enum svInvertMethod method) {\n\tauto src = CONVERT_TO_EIGEN(srcarr);\n\tauto dst = CONVERT_TO_EIGEN(dstarr);\n\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tif (method == SV_INVERT_METHOD_LU) {\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\" void svGEMM(const SvMat *_src1, const SvMat *_src2, double alpha, const SvMat *_src3, double beta,\n\t\t\t\t\t   SvMat *_dst, enum svGEMMFlags tABC) {\n\tauto src1 = CONVERT_TO_EIGEN(_src1);\n\tauto src2 = CONVERT_TO_EIGEN(_src2);\n\n\tauto dst = CONVERT_TO_EIGEN(_dst);\n\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tif (tABC & SV_GEMM_FLAG_A_T)\n\t\tif (tABC & SV_GEMM_FLAG_B_T)\n\t\t\tdst.noalias() = alpha * src1.transpose() * src2.transpose();\n\t\telse\n\t\t\tdst.noalias() = alpha * src1.transpose() * src2;\n\telse {\n\t\tif (tABC & SV_GEMM_FLAG_B_T)\n\t\t\tdst.noalias() = alpha * src1 * src2.transpose();\n\t\telse\n\t\t\tdst.noalias() = alpha * src1 * src2;\n\t}\n\n\tif (_src3) {\n\t\tauto src3 = CONVERT_TO_EIGEN(_src3);\n\t\tif (tABC & SV_GEMM_FLAG_C_T)\n\t\t\tdst.noalias() += beta * src3.transpose();\n\t\telse\n\t\t\tdst.noalias() += beta * src3;\n\t}\n}\n\nconst int DECOMP_SVD = 1;\nconst int DECOMP_LU = 2;\n\nextern \"C\" int svSolve(const SvMat *_Aarr, const SvMat *_Barr, SvMat *_xarr, enum svInvertMethod method) {\n\tauto Aarr = CONVERT_TO_EIGEN(_Aarr);\n\tauto Barr = CONVERT_TO_EIGEN(_Barr);\n\tauto xarr = CONVERT_TO_EIGEN(_xarr);\n\n\tif (method == SV_INVERT_METHOD_LU) {\n\t\txarr.noalias() = Aarr.partialPivLu().solve(Barr);\n\t} else if (method == SV_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 svd = Aarr.bdcSvd(\n\t\t\tEigen::ComputeFullU |\n\t\t\tEigen::ComputeFullV); // Eigen::JacobiSVD<MatrixType>(Aarr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\t\txarr.noalias() = svd.solve(Barr);\n\t}\n\treturn 0;\n}\n\nextern \"C\" void svSVD(SvMat *aarr, SvMat *warr, SvMat *uarr, SvMat *varr, enum svSVDFlags flags) {\n\tauto aarrEigen = CONVERT_TO_EIGEN(aarr);\n\tauto warrEigen = CONVERT_TO_EIGEN(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 svd = aarrEigen.bdcSvd(options);\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\n\tif (warrEigen.cols() == 1) {\n\t\twarrEigen.noalias() = svd.singularValues();\n\t} else if (warrEigen.rows() == 1) {\n\t\twarrEigen.noalias() = svd.singularValues().transpose();\n\t} else {\n\t\twarrEigen.diagonal().noalias() = svd.singularValues();\n\t}\n\n\tif (uarr) {\n\t\tauto uarrEigen = CONVERT_TO_EIGEN(uarr);\n\t\tif (flags & SV_SVD_U_T)\n\t\t\tuarrEigen.noalias() = svd.matrixU().transpose();\n\t\telse\n\t\t\tuarrEigen.noalias() = svd.matrixU();\n\t}\n\n\tif (varr) {\n\t\tauto varrEigen = CONVERT_TO_EIGEN(varr);\n\t\tif (flags & SV_SVD_V_T)\n\t\t\tvarrEigen.noalias() = svd.matrixV().transpose();\n\t\telse\n\t\t\tvarrEigen.noalias() = svd.matrixV();\n\t}\n}\n\nvoid svMulTransposed(const SvMat *src, SvMat *dst, int order, const SvMat *delta, double scale) {\n\tauto srcEigen = CONVERT_TO_EIGEN(src);\n\tauto dstEigen = CONVERT_TO_EIGEN(dst);\n\n\tif (delta) {\n\t\tauto deltaEigen = CONVERT_TO_EIGEN(delta);\n\t\tif (order == 0)\n\t\t\tdstEigen.noalias() = scale * (srcEigen - deltaEigen) * (srcEigen - deltaEigen).transpose();\n\t\telse\n\t\t\tdstEigen.noalias() = scale * (srcEigen - deltaEigen).transpose() * (src - delta);\n\t} else {\n\t\tif (order == 0)\n\t\t\tdstEigen.noalias() = scale * srcEigen * srcEigen.transpose();\n\t\telse\n\t\t\tdstEigen.noalias() = scale * srcEigen.transpose() * srcEigen;\n\t}\n}\n\nvoid svTranspose(const SvMat *M, SvMat *dst) {\n\tauto src = CONVERT_TO_EIGEN(M);\n\tauto dstEigen = CONVERT_TO_EIGEN(dst);\n\tif (SV_FLT_PTR(M) == SV_FLT_PTR(dst))\n\t\tdstEigen = src.transpose().eval();\n\telse\n\t\tdstEigen.noalias() = src.transpose();\n}\n\nvoid print_mat(const SvMat *M);\n\ndouble svDet(const SvMat *M) {\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tauto MEigen = CONVERT_TO_EIGEN(M);\n\treturn MEigen.determinant();\n}", "meta": {"hexsha": "81c418c30aed01b3cafefb5abafeeb9dae7dbfc0", "size": 4777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "redist/sv_matrix.eigen.cpp", "max_stars_repo_name": "humbletim/libsurvive", "max_stars_repo_head_hexsha": "0919a615f2ded7bbdaa4cd9895d68cb6a3ef19d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T04:02:37.000Z", "max_issues_repo_path": "redist/sv_matrix.eigen.cpp", "max_issues_repo_name": "rheaplex/libsurvive", "max_issues_repo_head_hexsha": "66e531e7900a64d832ecf86fce65168c4c99a5d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "redist/sv_matrix.eigen.cpp", "max_forks_repo_name": "rheaplex/libsurvive", "max_forks_repo_head_hexsha": "66e531e7900a64d832ecf86fce65168c4c99a5d9", "max_forks_repo_licenses": ["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.3067484663, "max_line_length": 109, "alphanum_fraction": 0.710069081, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6608499724045481}}
{"text": "/** @file main.cpp Demonstrates purely functional, tail-recursive,\n  * arbitrary-precision factorial and Fibonacci functions using\n  * Boost.Multiprecision.\n  * \n  * @note This implementation uses a concise style, passing and returning\n  * objects by value.\n  */\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\nusing BigInt = boost::multiprecision::cpp_int;\n\nBigInt factorial(int n, BigInt r =1) {\n    return n ? factorial(n - 1, r * n) : r;\n}\n\nBigInt fibonacci(int n, BigInt a =1, BigInt b =1) {\n    return n ? fibonacci(n - 1, b, a + b) : a;\n}\n\nint main() {\n    for (int i = 0; i < 100; ++i)\n        std::cout << i << ' ' << factorial(i) << ' ' << fibonacci(i) << '\\n';\n}\n", "meta": {"hexsha": "cbc95d37a3721e1c01abd537eac4f2a7e2c58126", "size": 692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pretty.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/pretty.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/pretty.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.6153846154, "max_line_length": 77, "alphanum_fraction": 0.6329479769, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6608499573665269}}
{"text": "#pragma once\n\n// C++ standard library\n#include <cmath>\n#include <iostream>\n#include <functional>\n\n// Armadillo\n#include <armadillo>\n\n// Mantella\n#include <mantella>\n\nnamespace mant{\n  namespace itd{\n    \n    double stumpffC(\n        const double parameter){\n      if(parameter > 0){\n        return (1.0 - std::cos(std::sqrt(parameter))) / parameter;\n      }else if (parameter < 0){\n        return (std::cosh(std::sqrt(-parameter)) - 1.0) / -parameter;\n      }else{\n        return 0.5;\n      }\n    }\n    \n    double stumpffS(\n        const double parameter){\n      \n      if(parameter > 0){\n        return (std::sqrt(parameter) - std::sin(std::sqrt(parameter))) / std::pow(std::sqrt(parameter), 3.0);\n      }else if (parameter < 0){\n        return (std::sinh(std::sqrt(-parameter)) - std::sqrt(-parameter)) / std::pow(std::sqrt(-parameter), 3.0);\n      }else{       \n        return 1.0 / 6.0;  \n      }\n    }\n    \n    std::pair<arma::Col<double>::fixed<3>, arma::Col<double>::fixed<3>> lambert(\n        const arma::Col<double>::fixed<3> &startPosition,\n        const arma::Col<double>::fixed<3> &endPosition,\n        const double flightTime,\n        const bool isPrograde){\n      \n      double startPositionNorm = arma::norm(startPosition);\n      double endPositionNorm = arma::norm(endPosition);\n      \n      arma::Col<double> positionsCrossProduct = arma::cross(startPosition, endPosition);\n      double theta = std::acos(arma::norm_dot(startPosition, endPosition));\n      \n      if(isPrograde){\n        if(positionsCrossProduct(2) < 0){\n          theta = 2.0 * arma::datum::pi - theta;\n        }\n      }else{\n        if(positionsCrossProduct(2) >= 0){\n          theta = 2.0 * arma::datum::pi - theta;\n        }\n      }\n\n      double a = std::sin(theta) * std::sqrt((startPositionNorm * endPositionNorm) / (1.0 - std::cos(theta)));\n      \n      std::function<double(const double)> yFunction = [&](\n          const double parameter){ \n        return startPositionNorm + endPositionNorm + a * ((parameter * stumpffS(parameter) - 1.0) / std::sqrt(stumpffC(parameter)));\n      };\n      \n      double z = mant::brent(\n        [&](\n            const double parameter) { \n\n          return stumpffS(parameter) * std::pow(yFunction(parameter) / stumpffC(parameter), 3.0/2.0) + a * std::sqrt(yFunction(parameter)) - std::sqrt(3.986e+5) * flightTime; //heliocentric should be 1.32712440018e11\n          \n        }, -2.0, 2.0, 100); //TODO: remove magic numbers\n      \n      double y = yFunction(z);\n\n      double f = 1.0 - y / startPositionNorm;\n      double g = a * std::sqrt(y / 3.986e+5); //heliocentric should be 1.32712440018e11\n      double gDot = 1.0 - y / endPositionNorm;\n      \n      return {{(1.0 / g) * (endPosition - f * startPosition)}, {(1.0 / g) * (gDot * endPosition - startPosition)}};\n      \n    }\n    \n    \n    std::pair<arma::Col<double>::fixed<3>, arma::Col<double>::fixed<3>> positionAndVelocityOnOrbit(\n        const arma::Col<double>::fixed<6>& keplerValues,\n        const arma::Col<double>::fixed<6>& dKeplerValues,\n        const arma::Col<double>::fixed<6>& date) {\n      // parameters\n      // -keplerValues as known (a, e, i, omega, w, L)\n      // -date in [yyyy,(mon)mon, (d)d, (h)h, (min)min, (s)s]\n      \n      double jd = 367.0 * date(0) - std::trunc((7.0 * (date(0) + std::trunc((date(1) + 9.0) / 12.0))) / 4.0) + std::trunc(275.0 * date(1) / 9.0) + date(2) + 1721013.5 + (date(3) + date(4) / 60.0 + date(5) / 3600.0) / 24;\n      \n      double t0 = (jd - 2451545.0) / 36525.0;  \n      \n      arma::Col<double>::fixed<6> keplerValAtTime = keplerValues + dKeplerValues * t0;\n      keplerValAtTime(0) = keplerValAtTime(0) * 149597871.464; //au to km\n      keplerValAtTime(2) = std::fmod(keplerValAtTime(2), 360.0) * arma::datum::pi / 180.0;\n      keplerValAtTime(3) = std::fmod(keplerValAtTime(3), 360.0) * arma::datum::pi / 180.0;\n      keplerValAtTime(4) = std::fmod(keplerValAtTime(4), 360.0) * arma::datum::pi / 180.0;\n      keplerValAtTime(5) = std::fmod(keplerValAtTime(5), 360.0) * arma::datum::pi / 180.0;   \n      \n      double angularMomentum = std::sqrt(1.32712440018e11 * keplerValAtTime(0) * (1.0 - std::pow(keplerValAtTime(1), 2.0))); //sun gravity!!!\n      \n      double argumentPerihelion = keplerValAtTime(4) - keplerValAtTime(3);\n      double meanAnomaly = keplerValAtTime(5) - keplerValAtTime(4); \n      \n      double eccentricAnomaly0;\n      if(meanAnomaly < arma::datum::pi) {       \n        eccentricAnomaly0 =  meanAnomaly + keplerValAtTime(1) / 2.0;       \n      } else {        \n        eccentricAnomaly0 =  meanAnomaly - keplerValAtTime(1) / 2.0;        \n      }\n      \n      double eccentricAnomaly = mant::brent(\n        [&](\n            const double parameter) {\n\n          return parameter - keplerValAtTime(1) * std::sin(parameter) - meanAnomaly;\n          \n        }, -10.0, 10.0, 100); //TODO: remove magic numbers  \n      \n      double trueAnomaly = std::fmod(2.0 * std::atan(std::sqrt((1.0 + keplerValAtTime(1)) / (1.0 - keplerValAtTime(1))) * std::tan(eccentricAnomaly / 2.0)), 2.0 * arma::datum::pi);\n      \n      arma::Col<double>::fixed<3> helperVectorPos = {std::cos(trueAnomaly), std::sin(trueAnomaly), 0};\n      arma::Col<double>::fixed<3> perifocalPosition = (std::pow(angularMomentum, 2.0) / 1.32712440018e11) * (1.0 / (1.0 + keplerValAtTime(1) * std::cos(trueAnomaly))) * helperVectorPos; //sun gravity!!!\n      \n      arma::Col<double>::fixed<3> helperVectorVel = {-std::sin(trueAnomaly), (keplerValAtTime(1) + std::cos(trueAnomaly)), 0};\n      arma::Col<double>::fixed<3> perifocalVelocity = (1.32712440018e11 / angularMomentum) * helperVectorVel; //sun gravity!!!    \n      \n      arma::Mat<double>::fixed<3, 3> R3_W = {\n        {std::cos(keplerValAtTime(3)),  std::sin(keplerValAtTime(3)), 0.0}, \n        {-std::sin(keplerValAtTime(3)), std::cos(keplerValAtTime(3)), 0.0}, \n        {0.0,                           0.0,                          1.0}\n      };\n      \n      arma::Mat<double>::fixed<3, 3> R1_i = {\n        {1.0, 0.0, 0.0}, \n        {0.0, std::cos(keplerValAtTime(2)), std::sin(keplerValAtTime(2))}, \n        {0.0, std::sin(keplerValAtTime(2)), std::cos(keplerValAtTime(2))}\n      };\n      \n      arma::Mat<double>::fixed<3, 3> R3_w = {\n        {std::cos(argumentPerihelion),  std::sin(argumentPerihelion), 0.0}, \n        {-std::sin(argumentPerihelion), std::cos(argumentPerihelion), 0.0}, \n        {0.0,                           0.0,                          1.0}\n      };\n      \n      arma::Mat<double>::fixed<3, 3> Q_pX = (R3_w * R1_i * R3_W).t();\n      \n      return {{Q_pX * perifocalPosition},{Q_pX * perifocalVelocity}};\n    }\n    \n  }\n}\n", "meta": {"hexsha": "28d88af2e821f67d42198a07bf4963ebb18e54bd", "size": 6629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.43125, "max_line_length": 220, "alphanum_fraction": 0.5685623774, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6608159280318531}}
{"text": "#include <matplotlibcpp.h>\n#include \"../simple_lib/include/simple_activation.h\"\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\n\nint main(){\n    using std::vector;\n\n    VectorXd x = VectorXd::LinSpaced(101, -5, 5);\n    VectorXd y;\n\n    y = x.unaryExpr([](double p){return MyDL::sigmoid<double>(p);});\n\n    // \u5909\u63db\u3059\u308b\u8981\u7d20\u6570\u3067\u521d\u671f\u5316\u3059\u308b\u5fc5\u8981\u3042\u308a\n    vector<double> x_vec(101), y_vec(101);\n\n    // \u76f4\u63a5Eigen\u306eVector\u3092\u6271\u3048\u306a\u3044\u306e\u3067\u3001STL\u306e\u30b3\u30f3\u30c6\u30ca\u306b\u79fb\u3057\u66ff\u3048\u3066\u4f7f\u3046\n    Map<VectorXd>(&x_vec[0], 101) = x;\n    Map<VectorXd>(&y_vec[0], 101) = y;\n\n    plt::named_plot(\"sigmoid\", x_vec, y_vec);\n    plt::grid(true);\n    plt::legend();\n    plt::save(\"./ch3/images/sigmoid.png\");\n\n    return 0;\n}", "meta": {"hexsha": "293ddc7617a575757e93c765e83e7f4877f22707", "size": 689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/visualize_sigmoid.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": "ch3/visualize_sigmoid.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": "ch3/visualize_sigmoid.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": 22.9666666667, "max_line_length": 68, "alphanum_fraction": 0.648766328, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6607287420145066}}
{"text": "/*=============================================================================\n\n  LeastSquaresPackage: A software package for estimating the rotation and translation of rigid bodies.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"catch.hpp\"\n#include \"lsqCatchMain.h\"\n#include \"lsqComputeRotation.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nTEST_CASE( \"Compute the rotation with the SVD methods\", \"[svd_rotation]\" ) {\n\n  std::unique_ptr<lsq::ComputeRotation> algorithm( new lsq::SVDMethod() );\n\n  Eigen::Matrix3d input_H_matrix = Eigen::Matrix3d::Zero(3, 3);\n  Eigen::Matrix3d expected_rotation_matrix = Eigen::Matrix3d::Zero(3, 3);\n  Eigen::Matrix3d obtained_rotation_matrix;\n\n  SECTION( \"The method fails because the rotation has det = -1 and the singular values are non-negative.\" ) {\n    input_H_matrix(0,2) = -0.2;\n    input_H_matrix(1,1) = -0.5;\n    input_H_matrix(2,0) = 1.;\n\n    REQUIRE_THROWS( obtained_rotation_matrix = algorithm->find_rotation(input_H_matrix) );\n  }\n\n  SECTION( \"The method succeeds in finding the rotation, but has to modify the rotation to avoid a reflection.\" ) {\n    input_H_matrix(1,1) = -0.3;\n    input_H_matrix(2,0) = -1.;\n\n    expected_rotation_matrix(0,2) = -1.;\n    expected_rotation_matrix(1,1) = -1.;\n    expected_rotation_matrix(2,0) = -1.;\n\n    obtained_rotation_matrix = algorithm->find_rotation(input_H_matrix);\n\n    REQUIRE( expected_rotation_matrix == obtained_rotation_matrix );\n\n  }\n\n  SECTION( \"The method succeeds in finding the rotation.\" ) {\n    input_H_matrix(1,1) = -0.3;\n    input_H_matrix(2,0) = 1.;\n\n    expected_rotation_matrix(0,2) = 1.;\n    expected_rotation_matrix(1,1) = -1.;\n    expected_rotation_matrix(2,0) = 1.;\n\n    obtained_rotation_matrix = algorithm->find_rotation(input_H_matrix);\n\n    REQUIRE( expected_rotation_matrix == obtained_rotation_matrix );\n\n  }\n\n}\n\nTEST_CASE( \"Compute the rotation with the Quaternion methods\", \"[quad_rotation]\" ) {\n\n  std::unique_ptr<lsq::ComputeRotation> algorithm( new lsq::QuaternionMethod() );\n\n  Eigen::Matrix3d input_H_matrix = Eigen::Matrix3d::Zero(3, 3);\n  Eigen::Matrix3d expected_rotation_matrix = Eigen::Matrix3d::Zero(3, 3);\n  Eigen::Matrix3d obtained_rotation_matrix;\n\n  input_H_matrix(1,1) = -0.3;\n  input_H_matrix(2,0) = 1.;\n\n  expected_rotation_matrix(0,2) = 1.;\n  expected_rotation_matrix(1,1) = -1.;\n  expected_rotation_matrix(2,0) = 1.;\n\n  obtained_rotation_matrix = algorithm->find_rotation(input_H_matrix);\n\n  REQUIRE( obtained_rotation_matrix.isApprox(expected_rotation_matrix, 1.e-10) );\n\n}\n", "meta": {"hexsha": "aac4c23df0fa4ef60f353d3b7bbd18cfe040d64d", "size": 2841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Testing/lsqComputeRotationTest.cpp", "max_stars_repo_name": "carlosparaciari/LeastSquarePackage", "max_stars_repo_head_hexsha": "811d48dd7e8ecd8972da44ea6c7210a3e5a1f343", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Testing/lsqComputeRotationTest.cpp", "max_issues_repo_name": "carlosparaciari/LeastSquarePackage", "max_issues_repo_head_hexsha": "811d48dd7e8ecd8972da44ea6c7210a3e5a1f343", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Testing/lsqComputeRotationTest.cpp", "max_forks_repo_name": "carlosparaciari/LeastSquarePackage", "max_forks_repo_head_hexsha": "811d48dd7e8ecd8972da44ea6c7210a3e5a1f343", "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.6551724138, "max_line_length": 115, "alphanum_fraction": 0.6877859908, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.660682476841122}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <array>\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing Bounds = std::array<double, 2>;\n\nclass ShockTubeSolver\n{\npublic:\n    ShockTubeSolver(Bounds calc_bounds, double endtime, double dt, int n_cell);\n    ~ShockTubeSolver();\n\n    void SetGrid();\n    void SetFlowField(double wall_position, double rhoL, double pL, double rhoR,\n                      double pR);\n    void SetSchemes(std::string convectiveflux_scheme, bool MUSCL, double k);\n    void Solve();\n    void WriteFlowFile(std::string filename);\n\n\n    inline int Get_n_cells() const { return n_cells_; };\n    inline double Get_dx() const { return dx_; };\n\nprivate:\n    std::vector<double> cells;\n    std::vector<Eigen::Vector3d> flowVars;\n    std::vector<Eigen::Vector3d> flowConservatives;\n\n    Eigen::Vector3d PrimToCons(Eigen::Vector3d prim);\n    Eigen::Vector3d ConsToPrim(Eigen::Vector3d cons);\n\n    // Euler flux\n    Eigen::Vector3d Roe(Eigen::Vector3d primL, Eigen::Vector3d primR);\n    Eigen::Vector3d vanLeer(Eigen::Vector3d primL, Eigen::Vector3d primR);\n    Eigen::Vector3d AUSM(Eigen::Vector3d primL, Eigen::Vector3d primR);\n\n    // Limiter\n    double minmod(double a, double b);\n\n\n    int n_cells_;\n    int n_timestep_;\n    double dx_;\n    Bounds calc_bounds_;\n    double endtime_;\n    double dt_;\n    double CFL_;\n\n    const double GAMMA = 1.40;\n\n    std::string convectiveflux_scheme_;\n    bool MUSCL_;\n    //! A coefficient of MUSCL scheme\n    //! k = -1: 2nd order upwind differencing\n    //! k = 0: 2nd order upwind-biased differencing\n    //! k = 1/3: 3rd order upwind-biased differencing\n    double k_;\n};\n", "meta": {"hexsha": "48333de022ae08b5942f23b83624d9c127317b31", "size": 1643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "02_shockTube/include/ShockTubeSolver.hpp", "max_stars_repo_name": "nishiys/CFDbasics", "max_stars_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-19T10:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T10:17:17.000Z", "max_issues_repo_path": "02_shockTube/include/ShockTubeSolver.hpp", "max_issues_repo_name": "nishiys/CFDbasics", "max_issues_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_shockTube/include/ShockTubeSolver.hpp", "max_forks_repo_name": "nishiys/CFDbasics", "max_forks_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-19T10:22:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T10:22:36.000Z", "avg_line_length": 26.0793650794, "max_line_length": 80, "alphanum_fraction": 0.6804625685, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6606824680712473}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <utility>\n\n#include \"../../includes/concave_hull_k_nearest_neighbours_optimized.hpp\"\n\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\nusing bg::dsv;\n\nint main()\n{\n    typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::multi_point<point_t> mpoint_t;\n\n    mpoint_t mpt1, hull;\n    bg::read_wkt(\"MULTIPOINT(0 0,6 0,3 1,3 2,4 2,5 3,5 5,4 4,-2 2)\", mpt1);\n\n    int k = 3;\n    algo3::ConcaveHullKNN(mpt1, hull, k);\n\n    std::cout << \"Dataset: \" << dsv(mpt1) << std::endl;\n    std::cout << \"Concave hull for k = \" << k << \": \" << dsv(hull) << std::endl;\n\n    return 0;\n}\n\n/*\nOutput:\nDataset: ((0, 0), (6, 0), (3, 1), (3, 2), (4, 2), (5, 3), (5, 5), (4, 4), (-2, 2))\nConcave hull for k = 3: ((-2, 2), (0, 0), (3, 1), (6, 0), (5, 5), (-2, 2))\n*/", "meta": {"hexsha": "81cde23e4cdbd80d12656a66d4448454aaefd581", "size": 947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/concave_hull/example_small.cpp", "max_stars_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_stars_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_stars_repo_licenses": ["MIT"], "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/concave_hull/example_small.cpp", "max_issues_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_issues_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_issues_repo_licenses": ["MIT"], "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/concave_hull/example_small.cpp", "max_forks_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_forks_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_forks_repo_licenses": ["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.2820512821, "max_line_length": 82, "alphanum_fraction": 0.5818373812, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6606790217376309}}
{"text": "#include <cmath>\n#include <iostream>\n#include <string>\n#include <boost/mpi.hpp>\n\n#include \"dla.h\"\n#include \"graph_printer.h\"\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n  boost::mpi::environment env{argc, argv};\n  boost::mpi::communicator world;\n\n  int total_num_graphs = stoi(string(argv[1]));\n  int graph_per_process = int(ceil(double(total_num_graphs) / double(world.size())));\n  total_num_graphs = graph_per_process * world.size();\n\n  DLA_params params(world.rank(), argc-2, argv+2);\n  int seed = 577 + world.rank();\n  rgen.seed(seed);\n\n  GraphPrinter graph_printer(string(\"DLA\"), false, true, total_num_graphs);\n  if (world.rank() == printer_rank) {\n    cout << params;\n    cout << \"Producing \" << total_num_graphs << \" on \" << world.size() << \" processes\" << endl;\n    graph_printer.open();\n  }\n  for (int graph_id = 0; graph_id < graph_per_process; ++graph_id) {\n    produce_graph(world, graph_printer, params);\n  }\n}", "meta": {"hexsha": "86f087fe02d27b103cc3b64515befd2ef6e2f325", "size": 938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Algue-Rythme/DiffusionLimitedAgregation", "max_stars_repo_head_hexsha": "6e9456690a6de5e61df3313805ca6e7df71764a9", "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/main.cpp", "max_issues_repo_name": "Algue-Rythme/DiffusionLimitedAgregation", "max_issues_repo_head_hexsha": "6e9456690a6de5e61df3313805ca6e7df71764a9", "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/main.cpp", "max_forks_repo_name": "Algue-Rythme/DiffusionLimitedAgregation", "max_forks_repo_head_hexsha": "6e9456690a6de5e61df3313805ca6e7df71764a9", "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.4242424242, "max_line_length": 95, "alphanum_fraction": 0.6791044776, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6606790124767626}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace icarus\n{\n    template<typename T, size_t N>\n    struct OffsetCalibration\n    {\n        explicit OffsetCalibration()\n        {\n            mOffset.setZero();\n        }\n\n        explicit OffsetCalibration(Eigen::Matrix<T, N, 1> const & offset) :\n            mOffset(-offset)\n        {}\n\n        Eigen::Matrix<T, N, 1> adjust(Eigen::Matrix<T, N, 1> const & reading) const\n        {\n            return reading + mOffset;\n        }\n    private:\n        Eigen::Matrix<T, N, 1> mOffset;\n    };\n}\n", "meta": {"hexsha": "343b3f5ca81c494cacfc4a2a448c2fc11d10a0bd", "size": 537, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/OffsetCalibration.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/OffsetCalibration.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/OffsetCalibration.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": 19.8888888889, "max_line_length": 83, "alphanum_fraction": 0.5400372439, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6605831575638786}}
{"text": "#pragma once\n\n#include \"constants.hpp\"\n#include <Eigen/Core>\n\nnamespace math {\ntemplate <typename T>\nT to_radians(T degree) {\n    return degree / static_cast<T>(180.0) * pi<T>;\n}\n\ntemplate <typename T, int rows, int cols>\nEigen::Matrix<T, rows, cols> to_radians(Eigen::Matrix<T, rows, cols> degree) {\n    return degree / static_cast<T>(180.0) * pi<T>;\n}\n\ntemplate <typename T>\nT to_degree(T radians) {\n    return radians * static_cast<T>(180.0) / pi<T>;\n}\n\ntemplate <typename T, int rows, int cols>\nEigen::Matrix<T, rows, cols> to_degree(Eigen::Matrix<T, rows, cols> radians) {\n    return radians * static_cast<T>(180.0) / pi<T>;\n}\n} // namespace math\n", "meta": {"hexsha": "622a012cc87c6fa075600fca89c3785031823539", "size": 652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vgl/math/math_utils.hpp", "max_stars_repo_name": "alexsr/vgl", "max_stars_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T18:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T18:27:19.000Z", "max_issues_repo_path": "src/vgl/math/math_utils.hpp", "max_issues_repo_name": "alexsr/vgl", "max_issues_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_issues_repo_licenses": ["MIT"], "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/vgl/math/math_utils.hpp", "max_forks_repo_name": "alexsr/vgl", "max_forks_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_forks_repo_licenses": ["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.1481481481, "max_line_length": 78, "alphanum_fraction": 0.6763803681, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6605831530721817}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2018 Prabhsimran Singh\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#pragma once\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include \"functions.hpp\"\n\nnamespace nn {\n\nclass Dense {\n  private:\n    MatrixXf W;\n    RowVectorXf b;\n\n  public:\n    explicit Dense(const int &, const int &);\n\n    MatrixXf operator()(const MatrixXf &);\n\n    MatrixXf forward(const MatrixXf &);\n\n    // MatrixXf backward(const MatrixXf &, const MatrixXf &);\n};\n\nDense::Dense(const int &num_inputs, const int &num_outputs) {\n    W = MatrixXf(num_inputs, num_outputs).setRandom() * F::glorot_uniform(num_inputs, num_outputs);\n    b = RowVectorXf(num_outputs).setZero();\n}\n\nMatrixXf Dense::operator()(const MatrixXf &inputs) {\n    return forward(inputs);\n}\n\nMatrixXf Dense::forward(const MatrixXf &inputs) {\n    MatrixXf Z = inputs * W;\n    Z += b.replicate(inputs.rows(), 1);\n    return Z;\n}\n\n// MatrixXf Dense::backward(const MatrixXf &inputs, const MatrixXf &gradients) {\n// }\n\nclass Embedding {\n  private:\n    MatrixXf embeddings;\n    int n_tokens;\n    int embedding_dim;\n\n  public:\n    explicit Embedding(const int &, const int &);\n\n    inline MatrixXf operator()(const MatrixXf &);\n\n    inline MatrixXf forward(const MatrixXf &);\n\n    // MatrixXf backward(const MatrixXf &, const MatrixXf &);\n};\n\nEmbedding::Embedding(const int &n_tokens, const int &embedding_dim) : n_tokens(n_tokens), embedding_dim(embedding_dim) {\n    this->embeddings = MatrixXf(n_tokens, embedding_dim).setRandom();\n}\n\ninline MatrixXf Embedding::operator()(const MatrixXf &inputs) {\n    return forward(inputs);\n}\n\ninline MatrixXf Embedding::forward(const MatrixXf &inputs) {\n    // here inputs are one-hot encodings\n    return inputs * embeddings;\n}\n\n// MatrixXf Embedding::backward(const MatrixXf &inputs, const MatrixXf &gradients) {\n\n// }\n} // namespace nn", "meta": {"hexsha": "7f10cb2f4b5a5e7e88f9d607119edbf56f1b3e5d", "size": 2947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/layers.hpp", "max_stars_repo_name": "pskrunner14/lstm-from-scratch", "max_stars_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T04:00:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T09:48:40.000Z", "max_issues_repo_path": "include/layers.hpp", "max_issues_repo_name": "pskrunner14/lstm-from-scratch", "max_issues_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-23T06:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-23T06:59:28.000Z", "max_forks_repo_path": "include/layers.hpp", "max_forks_repo_name": "pskrunner14/lstm-from-scratch", "max_forks_repo_head_hexsha": "df61ded892ae7ef576a0c7cc572f6375dd13c99b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T00:16:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T01:39:40.000Z", "avg_line_length": 28.8921568627, "max_line_length": 120, "alphanum_fraction": 0.7207329488, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6605831497644788}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file RotationTests.cpp\n/// \\brief Unit tests for the implementation of the rotation matrix class.\n/// \\details Unit tests for the various Lie Group functions will test both\n/// special cases,\n///          and randomly generated cases.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <lgmath/CommonMath.hpp>\n\n#include <lgmath/so3/Operations.hpp>\n#include <lgmath/so3/Rotation.hpp>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// UNIT TESTS OF ROTATION MATRIX\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of rotation constructors\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, RotationConstructors) {\n  // Generate random transform from most basic constructor\n  Eigen::Matrix3d C_ba_rand = lgmath::so3::vec2rot(Eigen::Vector3d::Random());\n  lgmath::so3::Rotation rand(C_ba_rand);\n\n  // Rotation();\n  {\n    lgmath::so3::Rotation cmatrix;\n    Eigen::Matrix3d test = Eigen::Matrix3d::Identity();\n    std::cout << \"cmat: \" << cmatrix.matrix() << std::endl;\n    std::cout << \"test: \" << test << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(cmatrix.matrix(), test, 1e-6));\n  }\n\n  // Rotation(const Rotation& C);\n  {\n    lgmath::so3::Rotation test(rand);\n    std::cout << \"cmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Rotation(const Eigen::Matrix3d& C);\n  {\n    lgmath::so3::Rotation test = rand;\n    std::cout << \"cmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n\n    // Test forced reprojection (ones to identity)\n    Eigen::Matrix3d notRotation = Eigen::Matrix3d::Ones();\n    lgmath::so3::Rotation test_bad(notRotation);  // forces reprojection\n    std::cout << \"cmat: \" << test_bad.matrix() << std::endl;\n    std::cout << \"test: \" << Eigen::Matrix3d::Identity() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(test_bad.matrix(),\n                                          Eigen::Matrix3d::Identity(), 1e-6));\n  }\n\n  // Rotation& operator=(Rotation C);\n  {\n    lgmath::so3::Rotation test(C_ba_rand);\n    std::cout << \"cmat: \" << rand.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(rand.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Rotation(const Eigen::Vector3d& vec, unsigned int numTerms = 0);\n  {\n    Eigen::Vector3d vec = Eigen::Vector3d::Random();\n    Eigen::Matrix3d cmat = lgmath::so3::vec2rot(vec);\n    lgmath::so3::Rotation testAnalytical(vec);\n    lgmath::so3::Rotation testNumerical(vec, 15);\n    std::cout << \"cmat: \" << cmat << std::endl;\n    std::cout << \"testAnalytical: \" << testAnalytical.matrix() << std::endl;\n    std::cout << \"testNumerical: \" << testNumerical.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(cmat, testAnalytical.matrix(), 1e-6));\n    EXPECT_TRUE(lgmath::common::nearEqual(cmat, testNumerical.matrix(), 1e-6));\n  }\n\n  // Rotation(const Eigen::VectorXd& vec);\n  {\n    Eigen::VectorXd vec = Eigen::Vector3d::Random();\n    Eigen::Matrix3d tmat = lgmath::so3::vec2rot(vec);\n    lgmath::so3::Rotation test(vec);\n    std::cout << \"tmat: \" << tmat << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(tmat, test.matrix(), 1e-6));\n  }\n\n  // Rotation(const Eigen::VectorXd& vec);\n  {\n    Eigen::VectorXd vec = Eigen::Vector3d::Random();\n    lgmath::so3::Rotation test(vec);\n\n    Eigen::VectorXd badvec = Eigen::Matrix<double, 6, 1>::Random();\n    lgmath::so3::Rotation testFailure;\n    try {\n      testFailure = lgmath::so3::Rotation(badvec);\n    } catch (const std::invalid_argument& e) {\n      testFailure = test;\n    }\n    std::cout << \"tmat: \" << testFailure.matrix() << std::endl;\n    std::cout << \"test: \" << test.matrix() << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(testFailure.matrix(), test.matrix(), 1e-6));\n  }\n\n  // Rotation(Rotation&&);\n  {\n    auto rand2 = rand;  // std::move may invalidate the original variable.\n    lgmath::so3::Rotation test(std::move(rand));\n    rand = rand2;\n\n    std::cout << \"tmat: \" << test.matrix() << std::endl;\n    std::cout << \"test: \" << rand2.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(test.matrix(), rand2.matrix(), 1e-6));\n  }\n\n  // Rotation = Rotation&&;\n  {\n    lgmath::so3::Rotation test;\n    auto rand2 = rand;  // std::move may invalidate the original variable.\n    test = std::move(rand);\n    rand = rand2;\n\n    std::cout << \"tmat: \" << test.matrix() << std::endl;\n    std::cout << \"test: \" << rand2.matrix() << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(test.matrix(), rand2.matrix(), 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test exponential map construction and logarithmic vec() method\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, RotationToFromSE3Algebra) {\n  // Add vectors to be tested\n  std::vector<Eigen::Vector3d> trueVecs;\n  Eigen::Vector3d temp;\n  temp << 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Vector3d::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc rotation matrices\n  std::vector<Eigen::Matrix3d> rotMatrices;\n  for (unsigned i = 0; i < numTests; i++) {\n    rotMatrices.push_back(lgmath::so3::vec2rot(trueVecs.at(i)));\n  }\n\n  // Calc rotations\n  std::vector<lgmath::so3::Rotation> rotations;\n  for (unsigned i = 0; i < numTests; i++) {\n    rotations.push_back(lgmath::so3::Rotation(trueVecs.at(i)));\n  }\n\n  // Compare matrices\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"matr: \" << rotMatrices.at(i) << std::endl;\n      std::cout << \"tran: \" << rotations.at(i).matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(rotMatrices.at(i),\n                                            rotations.at(i).matrix(), 1e-6));\n    }\n  }\n\n  // Test logarithmic map\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Vector3d testVec = rotations.at(i).vec();\n      std::cout << \"true: \" << trueVecs.at(i) << std::endl;\n      std::cout << \"func: \" << testVec << std::endl;\n      EXPECT_TRUE(\n          lgmath::common::nearEqualAxisAngle(trueVecs.at(i), testVec, 1e-6));\n    }\n  }\n\n}  // TEST\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Test inverse and operatations\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, RotationInverse) {\n  // Add vectors to be tested\n  std::vector<Eigen::Vector3d> trueVecs;\n  Eigen::Vector3d temp;\n  temp << 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Vector3d::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Vector3d> landmarks;\n  for (unsigned i = 0; i < numTests; i++) {\n    landmarks.push_back(Eigen::Vector3d::Random());\n  }\n\n  // Calc rotation matrices\n  std::vector<Eigen::Matrix3d> rotMatrices;\n  for (unsigned i = 0; i < numTests; i++) {\n    rotMatrices.push_back(lgmath::so3::vec2rot(trueVecs.at(i)));\n  }\n\n  // Calc rotations\n  std::vector<lgmath::so3::Rotation> rotations;\n  for (unsigned i = 0; i < numTests; i++) {\n    rotations.push_back(lgmath::so3::Rotation(trueVecs.at(i)));\n  }\n\n  // Compare inverse to basic matrix inverse\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"matr: \" << rotMatrices.at(i).inverse() << std::endl;\n      std::cout << \"tran: \" << rotations.at(i).inverse().matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(rotMatrices.at(i).inverse(),\n                                            rotations.at(i).inverse().matrix(),\n                                            1e-6));\n    }\n  }\n\n  // Test that product of inverse and self make identity\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      std::cout << \"C*Cinv: \"\n                << rotations.at(i).matrix() * rotations.at(i).inverse().matrix()\n                << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(\n          rotations.at(i).matrix() * rotations.at(i).inverse().matrix(),\n          Eigen::Matrix3d::Identity(), 1e-6));\n    }\n  }\n\n  // Test self-product\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::so3::Rotation test = rotations.at(i);\n      test *= rotations.at(i + 1);\n      Eigen::Matrix3d matrix = rotMatrices.at(i) * rotMatrices.at(i + 1);\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::so3::Rotation test = rotations.at(i) * rotations.at(i + 1);\n      Eigen::Matrix3d matrix = rotMatrices.at(i) * rotMatrices.at(i + 1);\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test self product with inverse\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::so3::Rotation test = rotations.at(i);\n      test /= rotations.at(i + 1);\n      Eigen::Matrix3d matrix =\n          rotMatrices.at(i) * rotMatrices.at(i + 1).inverse();\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product with inverse\n  {\n    for (unsigned i = 0; i < numTests - 1; i++) {\n      lgmath::so3::Rotation test = rotations.at(i) / rotations.at(i + 1);\n      Eigen::Matrix3d matrix =\n          rotMatrices.at(i) * rotMatrices.at(i + 1).inverse();\n      std::cout << \"matr: \" << matrix << std::endl;\n      std::cout << \"tran: \" << test.matrix() << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(matrix, test.matrix(), 1e-6));\n    }\n  }\n\n  // Test product with landmark\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Vector3d mat = rotMatrices.at(i) * landmarks.at(i);\n      Eigen::Vector3d test = rotations.at(i) * landmarks.at(i);\n\n      std::cout << \"matr: \" << mat << std::endl;\n      std::cout << \"test: \" << test << std::endl;\n      EXPECT_TRUE(lgmath::common::nearEqual(mat, test, 1e-6));\n    }\n  }\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "bacfe0252f519fde21efab207d9d21b39246443c", "size": 12725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/RotationTests.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "tests/RotationTests.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "tests/RotationTests.cpp", "max_forks_repo_name": "utiasASRL/lgmath", "max_forks_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-18T11:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-12T15:15:09.000Z", "avg_line_length": 35.8450704225, "max_line_length": 94, "alphanum_fraction": 0.5578781925, "num_tokens": 3678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7718435030872967, "lm_q1q2_score": 0.6605831445586444}}
{"text": "#pragma once\n\n// -*- C++ -*-\n\n// The MIT License (MIT)\n//\n// Copyright (c) 2017 Alexander Samoilov\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#include <cmath>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n#include \"math_consts.hpp\"\n\n/*! \\file elliptic_integral.h\n    \\brief computation of elliptic integrals of the first and second kinds by iteration method\n\n    Details.\n*/\n\n/**\n * \\f$ F\\left(k\\right)\\equiv\\int_0^{\\pi/2}\\frac{d\\eta}{\\sqrt{1-k^2\\cos^2\\eta}} \\f$\n */\ntemplate <typename T>\nvoid elliptic_integral (T const& rk2, T& f, T& e)\n{\n    constexpr T ACCURACY = T(1.0e-6);\n    T rk = std::sqrt(rk2), g = ONE<T>, b = rk, c, d;\n\n    f = HALF<T> * PI<T>;\n    e = ONE<T>;\n    do {\n        c = std::sqrt(ONE<T> - b*b);\n        b = (ONE<T> - c) / (ONE<T> + c);\n        d = f*b;\n        f += d;\n        g = HALF<T>*g*b;\n        e += g;\n    } while (std::fabs(d) > ACCURACY);\n    e = f * (ONE<T> - HALF<T>*rk2*e);\n}\n\ntemplate <typename T>\nvoid elliptic_integral_new (T const& rk2, T& f, T& e)\n{\n    T srk = std::sqrt(rk2);\n    f = boost::math::ellint_1(srk);\n    e = boost::math::ellint_2(srk);\n    // `std::comp_ellint_1` and `std::comp_ellint_2` are too slow\n    // f = std::comp_ellint_1(srk);\n    // e = std::comp_ellint_2(srk);\n}\n", "meta": {"hexsha": "7f035f11205c0dce1a0c7faf3eaac76da3ef827e", "size": 2326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "body_ax/src/elliptic_integral.hpp", "max_stars_repo_name": "alsam/cpp-samples", "max_stars_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-14T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T10:51:29.000Z", "max_issues_repo_path": "body_ax/src/elliptic_integral.hpp", "max_issues_repo_name": "alsam/cpp-samples", "max_issues_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "body_ax/src/elliptic_integral.hpp", "max_forks_repo_name": "alsam/cpp-samples", "max_forks_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T13:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:57:21.000Z", "avg_line_length": 33.2285714286, "max_line_length": 94, "alphanum_fraction": 0.6633705933, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6605831412509422}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\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//! \\file\r\n//!\\brief Tests for the math root-finding utility function TOMS748 of (fixed_point).\r\n\r\n#include <utility>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_math_root_find_toms748\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/math/tools/roots.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_math_root_find_toms748)\r\n{\r\n  typedef boost::fixed_point::negatable<        std::numeric_limits<int>::digits,\r\n                                        -(255 - std::numeric_limits<int>::digits)>\r\n  fixed_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 8);\r\n\r\n  BOOST_CONSTEXPR boost::uintmax_t maximum_allowed_iterations = UINTMAX_C(32);\r\n\r\n  boost::uintmax_t iterations = maximum_allowed_iterations;\r\n\r\n  // Find the first positive real root of [cos(x) - sqrt(x)] = 0,\r\n  // which is near x = 0.64171437087288265839856530031652237185271781360384.\r\n\r\n  using boost::math::tools::toms748_solve;\r\n\r\n  const std::pair<fixed_point_type, fixed_point_type> root =\r\n    toms748_solve([](const fixed_point_type& x) -> fixed_point_type\r\n                  {\r\n                    return (cos(x) - sqrt(x));\r\n                  },\r\n                  ldexp(fixed_point_type(1), -1),\r\n                  fixed_point_type(1),\r\n                  [&tol](const fixed_point_type& a, const fixed_point_type& b) -> bool\r\n                  {\r\n                    using std::fabs;\r\n\r\n                    return (fabs(a - b) < tol);\r\n                  },\r\n                  iterations);\r\n\r\n  // Verify the root with a tight tolerance.\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(cos(root.first), sqrt(root.first), tol * 2);\r\n\r\n  BOOST_CHECK(iterations < maximum_allowed_iterations);\r\n}\r\n", "meta": {"hexsha": "412e04d9ccdd79143c491c37fcfaa246741191d3", "size": 2151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_math_root_find_toms748.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": "test/test_negatable_math_root_find_toms748.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": "test/test_negatable_math_root_find_toms748.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": 35.85, "max_line_length": 93, "alphanum_fraction": 0.619711762, "num_tokens": 489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.8056321959813274, "lm_q1q2_score": 0.6605324615915341}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kurtosis.hpp\n//\n//  Copyright 2006 Olivier Gygi, Daniel Egloff. 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_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005\n#define BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005\n\n#include <limits>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // kurtosis_impl\n    /**\n        @brief Kurtosis estimation\n\n        The kurtosis of a sample distribution is defined as the ratio of the 4th central moment and the square of the 2nd central\n        moment (the variance) of the samples, minus 3. The term \\f$ -3 \\f$ is added in order to ensure that the normal distribution\n        has zero kurtosis. The kurtosis can also be expressed by the simple moments:\n\n        \\f[\n            \\hat{g}_2 =\n                \\frac\n                {\\widehat{m}_n^{(4)}-4\\widehat{m}_n^{(3)}\\hat{\\mu}_n+6\\widehat{m}_n^{(2)}\\hat{\\mu}_n^2-3\\hat{\\mu}_n^4}\n                {\\left(\\widehat{m}_n^{(2)} - \\hat{\\mu}_n^{2}\\right)^2} - 3,\n        \\f]\n\n        where \\f$ \\widehat{m}_n^{(i)} \\f$ are the \\f$ i \\f$-th moment and \\f$ \\hat{\\mu}_n \\f$ the mean (first moment) of the\n        \\f$ n \\f$ samples.\n    */\n    template<typename Sample>\n    struct kurtosis_impl\n      : accumulator_base\n    {\n        // for boost::result_of\n        typedef typename numeric::functional::average<Sample, Sample>::result_type result_type;\n\n        kurtosis_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            return numeric::average(\n                        moment<4>(args)\n                        - 4. * moment<3>(args) * mean(args)\n                        + 6. * moment<2>(args) * mean(args) * mean(args)\n                        - 3. * mean(args) * mean(args) * mean(args) * mean(args)\n                      , ( moment<2>(args) - mean(args) * mean(args) )\n                        * ( moment<2>(args) - mean(args) * mean(args) )\n                    ) - 3.;\n        }\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::kurtosis\n//\nnamespace tag\n{\n    struct kurtosis\n      : depends_on<mean, moment<2>, moment<3>, moment<4> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::kurtosis_impl<mpl::_1> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::kurtosis\n//\nnamespace extract\n{\n    extractor<tag::kurtosis> const kurtosis = {};\n}\n\nusing extract::kurtosis;\n\n// So that kurtosis can be automatically substituted with\n// weighted_kurtosis when the weight parameter is non-void\ntemplate<>\nstruct as_weighted_feature<tag::kurtosis>\n{\n    typedef tag::weighted_kurtosis type;\n};\n\ntemplate<>\nstruct feature_of<tag::weighted_kurtosis>\n  : feature_of<tag::kurtosis>\n{\n};\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "cb384f17b3e7dfc128604a7ce1c69facd89d2850", "size": 3575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "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": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 32.2072072072, "max_line_length": 131, "alphanum_fraction": 0.5756643357, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.660501014463713}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../Optimizer/optimizer\"\nusing namespace std;\nusing namespace Eigen;\n\ndouble func (double x) {\n    return pow(x + 10, 2);\n}\n\ndouble func2 (VectorXd x) {\n    return x.squaredNorm();\n}\n\nint main () {\n    cout << \"Using Function: (x + 10)^2 for single variable algorithms testing.\" << endl;\n    cout << \"Test Bounding Phase:\" << endl;\n    double ipt = 5.4;\n    Vector2d range = BoundingPhase(func, ipt);\n    cout << \"Range from bounding Phase for initial point :\" << ipt << endl;\n    cout << range << endl;\n\n    cout << \"Derivatives at \" << ipt << endl;\n    cout << Derivative(func, ipt) << endl;\n\n    cout << \"Finding optimal point using above range for Newton Rapshon Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << NewtonRapshon (func, range) << endl;;\n\n    cout << \"Testing SVOptimize on (x + 10)^2 with initial point 5.4.\" << endl;\n    cout << \"The Optimal Point obtained is: \";\n    cout << SVOptimize(func, 5.4) << endl;\n\n    cout << \"Testing Gradient function using func2 with 3 variables\" << endl;\n    cout << Gradient(func2, Vector3d(3, 3, 4)) << endl;\n\n    cout << \"Testing DFP on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n    cout << \"The Optimal Point obtained is: \" << endl;\n    Vector3d x(4, -3, 7);\n    cout << DFP(func2, x) << endl;\n\n}\n", "meta": {"hexsha": "80d58d1571bdf36a993c55560b689ba2875d9d72", "size": 1353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/test.cpp", "max_stars_repo_name": "dhairyagada/Optimizer", "max_stars_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/test.cpp", "max_issues_repo_name": "dhairyagada/Optimizer", "max_issues_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/test.cpp", "max_forks_repo_name": "dhairyagada/Optimizer", "max_forks_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_forks_repo_licenses": ["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.4651162791, "max_line_length": 105, "alphanum_fraction": 0.6201034738, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.660487089791331}}
{"text": "#include <Eigen/Eigen>\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <mtvmtl/core/manifold.hpp> \n#include <cmath>\n#include <cstdlib>\n\n\nusing namespace Eigen;\nusing namespace tvmtl;\n\n\ntemplate <typename DerivedY, typename DerivedA>\ndouble F(const MatrixBase<DerivedY>& Y, const MatrixBase<DerivedA>& A){\n return 0.5 * (Y.transpose() * A * Y).trace();\n}\n\ntemplate <typename DerivedY, typename DerivedA>\nMatrixBase<DerivedY> FY(const MatrixBase<DerivedY>& Y, const MatrixBase<DerivedA>& A){\n return A * Y;\n}\n\n\nint main(){\n\nsrand(42);\n\nconst int N=4;\nconst int P=3;\n\ntypedef Matrix<double, P, P> ppmat;\ntypedef Matrix<double, N, P> npmat;\ntypedef Matrix<double, N, N> nnmat;\ntypedef Matrix<double, N*P, N*P> np2mat;\ntypedef Manifold<GRASSMANN, N, P> mf;\n\nnnmat R = nnmat::Random();\nnnmat A = 0.5 * (R + R.transpose());\n\nstd::cout << \"A:\\n\" << A << std::endl;\n\nnpmat Y;\nY = npmat::Random();\nHouseholderQR<npmat> qr(Y);\nnpmat q = qr.householderQ() * npmat::Identity();\nY = q;\n\nstd::cout << \"Y:\\n\" << Y << std::endl;\n\nnnmat HYproj = nnmat::Identity() - Y * Y.transpose();\n\ndouble h = 1e-2;\nnpmat dY;\ndY = npmat::Random(); \nqr.compute(dY);\nq = qr.householderQ() * npmat::Identity();\ndY = h * HYproj * q;\n\nstd::cout << \"DY:\\n\" << dY << std::endl;\n\nVectorXd vecdY = Map<VectorXd>(dY.data(), dY.size());\n\t\nnpmat FY = A * Y;\nstd::cout << \"\\nFY:\\n\" << FY << std::endl;\n\nnp2mat FYY = kroneckerProduct(ppmat::Identity(), A);\nstd::cout << \"FYY:\\n\" << FYY << std::endl;\n\nnpmat YpdY = Y + dY;\n//mf::exp(Y,dY,YpdY);\nmf::projector(YpdY);\n\ndouble exact = F(Y + dY, A);\ndouble exact2 = F(YpdY, A);\ndouble firstorder = F(Y,A) + FY.cwiseProduct(dY).sum();\ndouble secondorder_euc = firstorder + 0.5 * FYY.cwiseProduct(vecdY * vecdY.transpose()).sum() ;\n\nnpmat FYYdY_proj = HYproj * A * dY;\nnpmat FYY_corr_term = dY * Y.transpose() * FY;\ndouble secondorder_grass_nv = firstorder + 0.5 * (FYYdY_proj.cwiseProduct(dY).sum() - FYY_corr_term.cwiseProduct(dY).sum());\n\nnp2mat FYY_proj = kroneckerProduct(ppmat::Identity(), HYproj) * FYY ;\ndouble secondorder_grass_sv = firstorder + 0.5 * (FYY_proj.cwiseProduct(vecdY * vecdY.transpose()).sum() - FYY_corr_term.cwiseProduct(dY).sum());\n\nnp2mat FYY_grass = FYY_proj - kroneckerProduct(FY.transpose() * Y, nnmat::Identity());\ndouble secondorder_grass_fv = firstorder + 0.5 * (FYY_grass.cwiseProduct(vecdY * vecdY.transpose()).sum());\nstd::cout << \"FYY_Grass:\\n\" << FYY_grass << std::endl;\n\nstd::cout << \"\\n\\nFirst order approximation: \" << std::abs(exact-firstorder) << std::endl;\nstd::cout << \"Second order approximation (Euclidian): \" << std::abs(exact-secondorder_euc) << std::endl;\nstd::cout << \"Second order approximation (Grassmann non-vectorized): \" << std::abs(exact2-secondorder_grass_sv) << std::endl;\nstd::cout << \"Second order approximation (Grassmann semi-vectorized): \" << std::abs(exact2-secondorder_grass_sv) << std::endl;\nstd::cout << \"Second order approximation (Grassmann vectorized): \" << std::abs(exact2-secondorder_grass_fv) << std::endl;\n\n\n\nreturn 0;\n}\n", "meta": {"hexsha": "42b12a156f77f4d913436195ae6e344bff7aab2c", "size": 3002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/grassmannDerTest.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/grassmannDerTest.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/grassmannDerTest.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": 30.3232323232, "max_line_length": 145, "alphanum_fraction": 0.6798800799, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6604870882136259}}
{"text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <Eigen/Dense>\n#include <matplotlibcpp.h>\n#include \"../include/numerical_gradient.h\"\n#include \"../include/optimizer.h\"\n\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\ndouble sample_function(MatrixXd &);\nMatrixXd sample_function_gradient(MatrixXd &);\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::unordered_map;\n    using std::vector;\n    using namespace MyDL;\n\n    vector<vector<double>> x, y, z;\n    MatrixXd X = MatrixXd::Zero(1, 2);\n    for (double i = -2; i <= 2; i += 0.1)\n    {\n        vector<double> x_row, y_row, z_row;\n        for (double j = -2; j <= 2; j += 0.1)\n        {\n            X(0) = i;\n            X(1) = j;\n            x_row.push_back(i);\n            y_row.push_back(j);\n            z_row.push_back(sample_function(X));\n        }\n        x.push_back(x_row);\n        y.push_back(y_row);\n        z.push_back(z_row);\n    }\n\n    plt::plot_surface(x, y, z);\n    plt::save(\"suddle_function.png\");\n    plt::clf();\n\n    // x.clear();\n    // y.clear();\n    // vector<double> ux, uy, vx, vy;\n    // MatrixXd grad = MatrixXd::Zero(1, 2);\n    // for (double i = -10; i <= 10; i++)\n    // {\n    //     for (double j = -5; j <= 5; j++)\n    //     {\n    //         ux.push_back(i);\n    //         uy.push_back(j);\n    //         X(0) = i;\n    //         X(1) = j;\n    //         grad = sample_function_gradient(X);\n    //         vx.push_back((double)-grad(0));\n    //         vy.push_back((double)-grad(1));\n    //     }\n    // }\n\n    // Adam optimizer(0.3, 0.7, 0.9);\n    // unordered_map<string, MatrixXd> params, grads;\n    // int num_update = 30;\n    // vector<vector<double>> param_history(2, vector<double>(num_update, 0));\n    // X(0) = -6;\n    // X(1) = 2;\n    // params[\"X\"] = X;\n    // param_history[0][0] = X(0);\n    // param_history[1][0] = X(1);\n\n    // for (int i = 0; i < num_update; i++)\n    // {\n    //     cout << \"iteration: \" << i << endl;\n    //     grads[\"X\"] = sample_function_gradient(params[\"X\"]);\n    //     optimizer.update(params, grads);\n\n    //     param_history[0][i + 1] = (double)params[\"X\"](0);\n    //     param_history[1][i + 1] = (double)params[\"X\"](1);\n    // }\n\n    // plt::quiver(ux, uy, vx, vy);\n    // plt::save(\"SGD_function_gradient.png\");\n\n    // plt::plot(param_history[0], param_history[1], {{\"color\", \"red\"}, {\"marker\", \"o\"}, {\"linestyle\", \"--\"}, {\"label\", \"$f(x, y) = \\\\frac{1}{20}x^{2} + y^{2}$\"}});\n    // plt::plot(vector<double>(1, 0), vector<double>(1, 0), \"b+\");\n    // plt::title(\"Adam: $f(x,y) = 0.05x^{2} + y^{2}$\");\n    // plt::legend();\n    // plt::save(\"Adam_function_gradient_descent.png\");\n    // plt::cla();\n\n    return 0;\n}\n\ndouble sample_function(MatrixXd &x)\n{\n    return 0.25 * (- x(0) * x(0) + x(1) * x(1));\n}\n\n// MatrixXd sample_function_gradient(MatrixXd &x)\n// {\n//     MatrixXd grad(1, 2);\n//     grad(0) = 0.1 * x(0);\n//     grad(1) = 2 * x(1);\n//     return grad;\n// }", "meta": {"hexsha": "409167078b697c9071d12c9f72a8d7a8c1232b0c", "size": 2953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/suddle_point.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": "test/suddle_point.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": "test/suddle_point.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.5981308411, "max_line_length": 164, "alphanum_fraction": 0.5096512022, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6604850163724444}}
{"text": "#ifndef DCS_TESTBED_DETAIL_VARIANCE_HPP\n#define DCS_TESTBED_DETAIL_VARIANCE_HPP\n\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <cmath>\n#include <cstddef>\n\n\nnamespace dcs { namespace testbed { namespace detail {\n\n// See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\ntemplate <typename ValueT, typename IterT>\nValueT compensated_variance(IterT first, IterT last)\n{\n    std::size_t n = 0;\n    ValueT mean = 0;\n\n\tfor (IterT it = first; it != last; ++it)\n\t{\n\t\tconst ValueT x = *it;\n\t\t++n;\n\t\tmean += x;\n\t}\n\tmean /= n;\n\n    ValueT sum1 = 0;\n    ValueT sum2 = 0;\n\tfor (IterT it = first; it != last; ++it)\n\t{\n\t\tconst ValueT x = *it;\n\t\tconst ValueT dev = x-mean;\n\n        sum1 += dev*dev;\n        sum2 += dev;\n\t}\n\n    return (n > 1) ? ((sum1 - sum2*sum2/n)/(n - 1)) : 0;\n}\n\ntemplate <typename ValueT, typename IterT>\nValueT boost_variance(IterT first, IterT last)\n{\n\tboost::accumulators::accumulator_set<ValueT, boost::accumulators::stats<boost::accumulators::tag::variance> > acc;\n\tstd::size_t n = 0;\n\n\twhile (first != last)\n\t{\n\t\tacc(*first);\n\t\t++first;\n\t\t++n;\n\t}\n\n\treturn (n > 1) ? boost::accumulators::variance(acc)*n/static_cast<ValueT>(n-1) : 0;\n}\n\ntemplate <typename ValueT, typename IterT>\nValueT variance(IterT first, IterT last)\n{\n\treturn boost_variance<ValueT>(first, last);\n}\n\ntemplate <typename ValueT, typename IterT>\nValueT stdev(IterT first, IterT last)\n{\n\treturn std::sqrt(variance<ValueT>(first, last));\n}\n\n}}} // Namespace dcs::testbed::detail\n\n\n#endif // DCS_TESTBED_DETAIL_VARIANCE_HPP\n", "meta": {"hexsha": "d242bfa4b4e2b31a0138a8afada92dc865caa57c", "size": 1573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/testbed/detail/variance.hpp", "max_stars_repo_name": "sguazt/dcsxx-testbed", "max_stars_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "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": "inc/dcs/testbed/detail/variance.hpp", "max_issues_repo_name": "sguazt/dcsxx-testbed", "max_issues_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "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": "inc/dcs/testbed/detail/variance.hpp", "max_forks_repo_name": "sguazt/dcsxx-testbed", "max_forks_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "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.2567567568, "max_line_length": 115, "alphanum_fraction": 0.6834075016, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6604850120943754}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd m(2,3);\nm << 1,2,3,4,5,6;\ncout << \"here's the 2x3 matrix m:\" << endl << m << endl;\ncout << \"let's resize m to 3x2. This is a conservative resizing because 2*3==3*2.\" << endl;\nm.resize(3,2);\ncout << \"here's the 3x2 matrix m:\" << endl << m << endl;\ncout << \"now let's resize m to size 2x2. This is NOT a conservative resizing, so it becomes uninitialized:\" << endl;\nm.resize(2,2);\ncout << m << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "862f54ad044b351ea0115ea5d0defa1f10bb8b11", "size": 558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Matrix_resize_int_int.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_Matrix_resize_int_int.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_Matrix_resize_int_int.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.3636363636, "max_line_length": 116, "alphanum_fraction": 0.6397849462, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6604750715365381}}
{"text": "/**\n * test_divround.cpp\n * Tests the following functions for all valid inputs:\n * divround_i8, divround<int8_t>, divround_u8, divround<uint8_t>,\n * divround_i16, divround<int16_t>, divround_u16, and divround<uint16_t>.\n *\n * Tests divround_i32 and divround<int32_t> for all valid combinations\n * of dividend and divisor on the ranges\n * [-2147483648, -2147418112],\n * [-65536, 65536], and\n * [2147418111, 2147483647].\n * Approximately 2^36 tests are conducted on each function.\n *\n * Tests divround_u32 and divround<uint32_t> for all valid combinations\n * of dividend and divisor on the ranges\n * [1, 131072] and\n * [4294836223, 4294967295].\n * Approximately 2^36 tests are conducted on each function.\n *\n * Tests divround_i64 and divround<int64_t> for all valid combinations\n * of dividend and divisor on the ranges\n * [-9223372036854775808, -9223372036854710272],\n * [-65536, 65536], and\n * [9223372036854710271, 9223372036854775807].\n * Approximately 2^36 tests are conducted on each function.\n *\n * Tests divround_u64 and divround<uint64_t> for all valid combinations\n * of dividend and divisor on the ranges\n * [1, 131072] and\n * [18446744073709420543, 18446744073709551615].\n * Approximately 2^36 tests are conducted on each function.\n *\n * Written in 2018 by Ben Tesch.\n * Originally distributed at https://github.com/slugrustle/numerical_routines\n *\n * To the extent possible under law, the author has dedicated all copyright\n * and related and neighboring rights to this software to the public domain\n * worldwide.This software is distributed without any warranty.\n * The text of the CC0 Public Domain Dedication should be reproduced at the\n * end of this file. If not, see http ://creativecommons.org/publicdomain/zero/1.0/\n */\n\n#include <cinttypes>\n#include <cmath>\n#include <cstdio>\n#include <limits>\n#include <thread>\n#include <mutex>\n#include <vector>\n#ifdef __cplusplus\n  extern \"C\"\n  {\n#endif\n    #include \"divround.h\"\n#ifdef __cplusplus\n  }\n#endif\n#include \"divround.hpp\"\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/round.hpp>\n\ntypedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<80, boost::multiprecision::backends::digit_base_2, void, boost::int16_t, -16382, 16383>, boost::multiprecision::et_off> cpp_bin_float_80;\n\n/**\n * Mutex for stdout when running multithreaded.\n */\nstd::mutex print_mutex;\n\n/**\n * Test c style int16_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on [-32768, 32767]\n * for each dividend value.\n */\nvoid test_divround_i16_c(int16_t dividend_start, int16_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int16_t>::max().\n   */\n  int16_t dividend_i16 = dividend_start;\n  while (true) {\n    int16_t divisor = std::numeric_limits<int16_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i16 == std::numeric_limits<int16_t>::lowest()) & (divisor == static_cast<int16_t>(-1))) divisor = static_cast<int16_t>(1);\n      /* Don't divide by 0. */\n      if (divisor == static_cast<int16_t>(0)) divisor = static_cast<int16_t>(1);\n      int16_t dr = divround_i16(dividend_i16, divisor);\n      int16_t dbl_dr = static_cast<int16_t>(std::round(static_cast<double>(dividend_i16) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int16_t quotient = dividend_i16 / divisor;\n        int16_t remainder = dividend_i16 - (quotient * divisor);\n        int16_t div_half = divisor >> 1;\n        if ((divisor & static_cast<uint16_t>(0x8001)) == static_cast<int16_t>(1)) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround_i16 returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i16, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int16_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_i16 == dividend_end) break;\n    dividend_i16++;\n  }\n}\n\n/**\n * Test c++ style int16_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on [-32768, 32767]\n * for each dividend value.\n */\nvoid test_divround_i16_cpp(int16_t dividend_start, int16_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int16_t>::max().\n   */\n  int16_t dividend_i16 = dividend_start;\n  while (true) {\n    int16_t divisor = std::numeric_limits<int16_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i16 == std::numeric_limits<int16_t>::lowest()) & (divisor == static_cast<int16_t>(-1))) divisor = static_cast<int16_t>(1);\n      /* Don't divide by 0. */\n      if (divisor == static_cast<int16_t>(0)) divisor = static_cast<int16_t>(1);\n      int16_t dr = divround<int16_t>(dividend_i16, divisor);\n      int16_t dbl_dr = static_cast<int16_t>(std::round(static_cast<double>(dividend_i16) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int16_t quotient = dividend_i16 / divisor;\n        int16_t remainder = dividend_i16 - (quotient * divisor);\n        int16_t div_half = divisor >> 1;\n        if ((divisor & static_cast<uint16_t>(0x8001)) == static_cast<int16_t>(1)) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround<int16_t> returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i16, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int16_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_i16 == dividend_end) break;\n    dividend_i16++;\n  }\n}\n\n/**\n * Test c style uint16_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on [1, 65535]\n * for each dividend value.\n */\nvoid test_divround_u16_c(uint16_t dividend_start, uint16_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint16_t>::max().\n   */\n  uint16_t dividend_u16 = dividend_start;\n  while (true) {\n    uint16_t divisor = static_cast<uint16_t>(1);\n    while (true) {\n      uint16_t dr = divround_u16(dividend_u16, divisor);\n      uint16_t dbl_dr = static_cast<uint16_t>(std::round(static_cast<double>(dividend_u16) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint16_t quotient = dividend_u16 / divisor;\n        uint16_t remainder = dividend_u16 - (quotient * divisor);\n        uint16_t div_half = divisor >> 1;\n        if (divisor & static_cast<uint16_t>(0x0001)) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround_u16 returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u16, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<uint16_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_u16 == dividend_end) break;\n    dividend_u16++;\n  }\n}\n\n/**\n * Test c++ style uint16_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on [1, 65535]\n * for each dividend value.\n */\nvoid test_divround_u16_cpp(uint16_t dividend_start, uint16_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint16_t>::max().\n   */\n  uint16_t dividend_u16 = dividend_start;\n  while (true) {\n    uint16_t divisor = static_cast<uint16_t>(1);\n    while (true) {\n      uint16_t dr = divround<uint16_t>(dividend_u16, divisor);\n      uint16_t dbl_dr = static_cast<uint16_t>(std::round(static_cast<double>(dividend_u16) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint16_t quotient = dividend_u16 / divisor;\n        uint16_t remainder = dividend_u16 - (quotient * divisor);\n        uint16_t div_half = divisor >> 1;\n        if (divisor & static_cast<uint16_t>(0x0001)) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround<uint16_t> returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u16, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<uint16_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_u16 == dividend_end) break;\n    dividend_u16++;\n  }\n}\n\n/**\n * Test c style int32_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [-2147483648, -2147418112],\n * [-65536, 65536], and\n * [2147418111, 2147483647]\n * for each dividend value.\n */\nvoid test_divround_i32_c(int32_t dividend_start, int32_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int32_t>::max().\n   */\n  int32_t dividend_i32 = dividend_start;\n  while (true) {\n    int32_t divisor = std::numeric_limits<int32_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i32 == std::numeric_limits<int32_t>::lowest()) & (divisor == -1)) divisor = 1;\n      /* Don't divide by 0. */\n      if (divisor == 0) divisor = 1;\n      int32_t dr = divround_i32(dividend_i32, divisor);\n      int32_t dbl_dr = static_cast<int32_t>(std::round(static_cast<double>(dividend_i32) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int32_t quotient = dividend_i32 / divisor;\n        int32_t remainder = dividend_i32 - (quotient * divisor);\n        int32_t div_half = divisor >> 1;\n        if ((divisor & 0x80000001u) == 1) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround_i32 returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i32, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int32_t>::lowest() + (1 << 16)) divisor = -(1 << 16);\n      else if (divisor == (1 << 16)) divisor = std::numeric_limits<int32_t>::max() - (1 << 16);\n      else if (divisor == std::numeric_limits<int32_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_i32 == dividend_end) break;\n    else dividend_i32++;\n  }\n}\n\n/**\n * Test c++ style int32_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [-2147483648, -2147418112],\n * [-65536, 65536], and\n * [2147418111, 2147483647]\n * for each dividend value.\n */\nvoid test_divround_i32_cpp(int32_t dividend_start, int32_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int32_t>::max().\n   */\n  int32_t dividend_i32 = dividend_start;\n  while (true) {\n    int32_t divisor = std::numeric_limits<int32_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i32 == std::numeric_limits<int32_t>::lowest()) & (divisor == -1)) divisor = 1;\n      /* Don't divide by 0. */\n      if (divisor == 0) divisor = 1;\n      int32_t dr = divround<int32_t>(dividend_i32, divisor);\n      int32_t dbl_dr = static_cast<int32_t>(std::round(static_cast<double>(dividend_i32) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int32_t quotient = dividend_i32 / divisor;\n        int32_t remainder = dividend_i32 - (quotient * divisor);\n        int32_t div_half = divisor >> 1;\n        if ((divisor & 0x80000001u) == 1) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround<int32_t> returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i32, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int32_t>::lowest() + (1 << 16)) divisor = -(1 << 16);\n      else if (divisor == (1 << 16)) divisor = std::numeric_limits<int32_t>::max() - (1 << 16);\n      else if (divisor == std::numeric_limits<int32_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_i32 == dividend_end) break;\n    else dividend_i32++;\n  }\n}\n\n/**\n * Test c style uint32_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [1, 131072] and\n * [4294836223, 4294967295]\n * for each dividend value.\n */\nvoid test_divround_u32_c(uint32_t dividend_start, uint32_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint32_t>::max().\n   */\n  uint32_t dividend_u32 = dividend_start;\n  while (true) {\n    uint32_t divisor = 1u;\n    while (true) {\n      uint32_t dr = divround_u32(dividend_u32, divisor);\n      uint32_t dbl_dr = static_cast<uint32_t>(std::round(static_cast<double>(dividend_u32) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint32_t quotient = dividend_u32 / divisor;\n        uint32_t remainder = dividend_u32 - (quotient * divisor);\n        uint32_t div_half = divisor >> 1;\n        if (divisor & 0x00000001u) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround_u32 returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u32, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == (1u << 17)) divisor = std::numeric_limits<uint32_t>::max() - (1u << 17);\n      else if (divisor == std::numeric_limits<uint32_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_u32 == dividend_end) break;\n    else dividend_u32++;\n  }\n}\n\n/**\n * Test c++ style uint32_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [1, 131072] and\n * [4294836223, 4294967295]\n * for each dividend value.\n */\nvoid test_divround_u32_cpp(uint32_t dividend_start, uint32_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint32_t>::max().\n   */\n  uint32_t dividend_u32 = dividend_start;\n  while (true) {\n    uint32_t divisor = 1u;\n    while (true) {\n      uint32_t dr = divround<uint32_t>(dividend_u32, divisor);\n      uint32_t dbl_dr = static_cast<uint32_t>(std::round(static_cast<double>(dividend_u32) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint32_t quotient = dividend_u32 / divisor;\n        uint32_t remainder = dividend_u32 - (quotient * divisor);\n        uint32_t div_half = divisor >> 1;\n        if (divisor & 0x00000001u) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround<uint32_t> returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u32, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == (1u << 17)) divisor = std::numeric_limits<uint32_t>::max() - (1u << 17);\n      else if (divisor == std::numeric_limits<uint32_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_u32 == dividend_end) break;\n    else dividend_u32++;\n  }\n}\n\n/**\n * Test c style int64_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [-9223372036854775808, -9223372036854710272],\n * [-65536, 65536], and\n * [9223372036854710271, 9223372036854775807]\n * for each dividend value.\n */\nvoid test_divround_i64_c(int64_t dividend_start, int64_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int64_t>::max().\n   */\n  int64_t dividend_i64 = dividend_start;\n  while (true) {\n    int64_t divisor = std::numeric_limits<int64_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i64 == std::numeric_limits<int64_t>::lowest()) & (divisor == -1ll)) divisor = 1ll;\n      /* Don't divide by 0. */\n      if (divisor == 0ll) divisor = 1ll;\n      int64_t dr = divround_i64(dividend_i64, divisor);\n      int64_t dbl_dr = boost::math::round(cpp_bin_float_80(dividend_i64) / cpp_bin_float_80(divisor)).convert_to<int64_t>();\n      if (dr != dbl_dr) {\n        int64_t quotient = dividend_i64 / divisor;\n        int64_t remainder = dividend_i64 - (quotient * divisor);\n        int64_t div_half = divisor >> 1;\n        if ((divisor & 0x8000000000000001ull) == 1ll) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%\" PRIi64 \" / %\" PRIi64 \") = %\" PRIi64 \", but divround_i64 returns %\" PRIi64 \"\\n  remainder = %\" PRIi64 \", div_half = %\" PRIi64 \"\\n\\n\", dividend_i64, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int64_t>::lowest() + (1 << 16)) divisor = -(1 << 16);\n      else if (divisor == (1 << 16)) divisor = std::numeric_limits<int64_t>::max() - (1 << 16);\n      else if (divisor == std::numeric_limits<int64_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_i64 == dividend_end) break;\n    else dividend_i64++;\n  }\n}\n\n/**\n * Test c++ style int64_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [-9223372036854775808, -9223372036854710272],\n * [-65536, 65536], and\n * [9223372036854710271, 9223372036854775807]\n * for each dividend value.\n */\nvoid test_divround_i64_cpp(int64_t dividend_start, int64_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<int64_t>::max().\n   */\n  int64_t dividend_i64 = dividend_start;\n  while (true) {\n    int64_t divisor = std::numeric_limits<int64_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i64 == std::numeric_limits<int64_t>::lowest()) & (divisor == -1ll)) divisor = 1ll;\n      /* Don't divide by 0. */\n      if (divisor == 0ll) divisor = 1ll;\n      int64_t dr = divround<int64_t>(dividend_i64, divisor);\n      int64_t dbl_dr = boost::math::round(cpp_bin_float_80(dividend_i64) / cpp_bin_float_80(divisor)).convert_to<int64_t>();\n      if (dr != dbl_dr) {\n        int64_t quotient = dividend_i64 / divisor;\n        int64_t remainder = dividend_i64 - (quotient * divisor);\n        int64_t div_half = divisor >> 1;\n        if ((divisor & 0x8000000000000001ull) == 1ll) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%\" PRIi64 \" / %\" PRIi64 \") = %\" PRIi64 \", but divround<int64_t> returns %\" PRIi64 \"\\n  remainder = %\" PRIi64 \", div_half = %\" PRIi64 \"\\n\\n\", dividend_i64, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int64_t>::lowest() + (1 << 16)) divisor = -(1 << 16);\n      else if (divisor == (1 << 16)) divisor = std::numeric_limits<int64_t>::max() - (1 << 16);\n      else if (divisor == std::numeric_limits<int64_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_i64 == dividend_end) break;\n    else dividend_i64++;\n  }\n}\n\n/**\n * Test c style uint64_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [1, 131072] and\n * [18446744073709420543, 18446744073709551615]\n * for each dividend value.\n */\nvoid test_divround_u64_c(uint64_t dividend_start, uint64_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint64_t>::max().\n   */\n  uint64_t dividend_u64 = dividend_start;\n  while (true) {\n    uint64_t divisor = 1ull;\n    while (true) {\n      uint64_t dr = divround_u64(dividend_u64, divisor);\n      uint64_t dbl_dr = boost::math::round(cpp_bin_float_80(dividend_u64) / cpp_bin_float_80(divisor)).convert_to<uint64_t>();\n      if (dr != dbl_dr) {\n        uint64_t quotient = dividend_u64 / divisor;\n        uint64_t remainder = dividend_u64 - (quotient * divisor);\n        uint64_t div_half = divisor >> 1;\n        if (divisor & 0x0000000000000001ull) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%\" PRIu64 \" / %\" PRIu64 \") = %\" PRIu64 \", but divround_u64 returns %\" PRIu64 \"\\n  remainder = %\" PRIu64 \", div_half = %\" PRIu64 \"\\n\\n\", dividend_u64, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == (1ull << 17)) divisor = std::numeric_limits<uint64_t>::max() - (1ull << 17);\n      else if (divisor == std::numeric_limits<uint64_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_u64 == dividend_end) break;\n    else dividend_u64++;\n  }\n}\n\n/**\n * Test c++ style uint64_t divround for dividend on\n * [dividend_start, dividend_end]\n * and divisor on\n * [1, 131072] and\n * [18446744073709420543, 18446744073709551615]\n * for each dividend value.\n */\nvoid test_divround_u64_cpp(uint64_t dividend_start, uint64_t dividend_end) {\n  /**\n   * The dividend loop is written this way in case\n   * dividend_end is std::numeric_limits<uint64_t>::max().\n   */\n  uint64_t dividend_u64 = dividend_start;\n  while (true) {\n    uint64_t divisor = 1ull;\n    while (true) {\n      uint64_t dr = divround<uint64_t>(dividend_u64, divisor);\n      uint64_t dbl_dr = boost::math::round(cpp_bin_float_80(dividend_u64) / cpp_bin_float_80(divisor)).convert_to<uint64_t>();\n      if (dr != dbl_dr) {\n        uint64_t quotient = dividend_u64 / divisor;\n        uint64_t remainder = dividend_u64 - (quotient * divisor);\n        uint64_t div_half = divisor >> 1;\n        if (divisor & 0x0000000000000001ull) div_half++;\n        std::lock_guard<std::mutex> print_lock(print_mutex);\n        std::printf(\"\\nERROR: ROUND(%\" PRIu64 \" / %\" PRIu64 \") = %\" PRIu64 \", but divround<uint64_t> returns %\" PRIu64 \"\\n  remainder = %\" PRIu64 \", div_half = %\" PRIu64 \"\\n\\n\", dividend_u64, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == (1ull << 17)) divisor = std::numeric_limits<uint64_t>::max() - (1ull << 17);\n      else if (divisor == std::numeric_limits<uint64_t>::max()) break;\n      else divisor++;\n    }\n    if (dividend_u64 == dividend_end) break;\n    else dividend_u64++;\n  }\n}\n\nint main() {\n  std::printf(\"\\nTesting divround_i8\\n\");\n  int8_t dividend_i8 = std::numeric_limits<int8_t>::lowest();\n  while (true) {\n    int8_t divisor = std::numeric_limits<int8_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i8 == std::numeric_limits<int8_t>::lowest()) & (divisor == static_cast<int8_t>(-1))) divisor = static_cast<int8_t>(1);\n      /* Don't divide by 0. */\n      if (divisor == static_cast<int8_t>(0)) divisor = static_cast<int8_t>(1);\n      int8_t dr = divround_i8(dividend_i8, divisor);\n      int8_t dbl_dr = static_cast<int8_t>(std::round(static_cast<double>(dividend_i8) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int8_t quotient = dividend_i8 / divisor;\n        int8_t remainder = dividend_i8 - (quotient * divisor);\n        int8_t div_half = divisor >> 1;\n        if ((divisor & static_cast<uint8_t>(0x81)) == static_cast<int8_t>(0x01)) div_half++;\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround_i8 returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i8, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int8_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_i8 == std::numeric_limits<int8_t>::max()) break;\n    dividend_i8++;\n  }\n\n  std::printf(\"Testing divround_<int8_t>\\n\");\n  dividend_i8 = std::numeric_limits<int8_t>::lowest();\n  while (true) {\n    int8_t divisor = std::numeric_limits<int8_t>::lowest();\n    while (true) {\n      /* This would cause overflow in the result. Skip it. */\n      if ((dividend_i8 == std::numeric_limits<int8_t>::lowest()) & (divisor == static_cast<int8_t>(-1))) divisor = static_cast<int8_t>(1);\n      /* Don't divide by 0. */\n      if (divisor == static_cast<int8_t>(0)) divisor = static_cast<int8_t>(1);\n      int8_t dr = divround<int8_t>(dividend_i8, divisor);\n      int8_t dbl_dr = static_cast<int8_t>(std::round(static_cast<double>(dividend_i8) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        int8_t quotient = dividend_i8 / divisor;\n        int8_t remainder = dividend_i8 - (quotient * divisor);\n        int8_t div_half = divisor >> 1;\n        if ((divisor & static_cast<uint8_t>(0x81)) == static_cast<int8_t>(0x01)) div_half++;\n        std::printf(\"\\nERROR: ROUND(%i / %i) = %i, but divround<int8_t> returns %i\\n  remainder = %i, div_half = %i\\n\\n\", dividend_i8, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<int8_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_i8 == std::numeric_limits<int8_t>::max()) break;\n    dividend_i8++;\n  }\n\n  std::printf(\"Testing divround_u8\\n\");\n  uint8_t dividend_u8 = std::numeric_limits<uint8_t>::lowest();\n  while (true) {\n    uint8_t divisor = static_cast<uint8_t>(1);\n    while (true) {\n      uint8_t dr = divround_u8(dividend_u8, divisor);\n      uint8_t dbl_dr = static_cast<uint8_t>(std::round(static_cast<double>(dividend_u8) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint8_t quotient = dividend_u8 / divisor;\n        uint8_t remainder = dividend_u8 - (quotient * divisor);\n        uint8_t div_half = divisor >> 1;\n        if (divisor & static_cast<uint8_t>(0x01)) div_half++;\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround_u8 returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u8, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<uint8_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_u8 == std::numeric_limits<uint8_t>::max()) break;\n    dividend_u8++;\n  }\n\n  std::printf(\"Testing divround<uint8_t>\\n\");\n  dividend_u8 = std::numeric_limits<uint8_t>::lowest();\n  while (true) {\n    uint8_t divisor = static_cast<uint8_t>(1);\n    while (true) {\n      uint8_t dr = divround<uint8_t>(dividend_u8, divisor);\n      uint8_t dbl_dr = static_cast<uint8_t>(std::round(static_cast<double>(dividend_u8) / static_cast<double>(divisor)));\n      if (dr != dbl_dr) {\n        uint8_t quotient = dividend_u8 / divisor;\n        uint8_t remainder = dividend_u8 - (quotient * divisor);\n        uint8_t div_half = divisor >> 1;\n        if (divisor & static_cast<uint8_t>(0x01)) div_half++;\n        std::printf(\"\\nERROR: ROUND(%u / %u) = %u, but divround<uint8_t> returns %u\\n  remainder = %u, div_half = %u\\n\\n\", dividend_u8, divisor, dbl_dr, dr, remainder, div_half);\n      }\n      if (divisor == std::numeric_limits<uint8_t>::max()) break;\n      divisor++;\n    }\n    if (dividend_u8 == std::numeric_limits<uint8_t>::max()) break;\n    dividend_u8++;\n  }\n  \n  /**\n   * Use one thread if only one hardware thread is available. Otherwise, use\n   * one less than the number of available hardware threads.\n   */\n  uint32_t nThreads = std::thread::hardware_concurrency();\n  if (nThreads <= 2u) nThreads = 1u;\n  else nThreads--;\n\n  /**\n   * Store all threads in vThreads.\n   */\n  std::vector<std::thread> vThreads(nThreads);\n\n  std::printf(\"\\nStarting multithreaded tests with %u threads.\\n\\n\", nThreads);\n\n  std::printf(\"Testing divround_i16\\n\"); \n  /**\n   * Test dividends on the range [-2^15, 2^15-1] multithreaded\n   */\n  {\n    int32_t dividend_start = static_cast<int32_t>(std::numeric_limits<int16_t>::lowest());\n    uint32_t nDividends = (1u << 16);\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i16_c, static_cast<int16_t>(thread_dividend_start), static_cast<int16_t>(thread_dividend_end)));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<int16_t>\\n\");\n  /**\n   * Test dividends on the range [-2^15, 2^15-1] multithreaded\n   */\n  {\n    int32_t dividend_start = static_cast<int32_t>(std::numeric_limits<int16_t>::lowest());\n    uint32_t nDividends = (1u << 16);\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i16_cpp, static_cast<int16_t>(thread_dividend_start), static_cast<int16_t>(thread_dividend_end)));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround_u16\\n\");\n  /**\n   * Test dividends on the range [0, 2^16-1] multithreaded\n   */\n  {\n    uint32_t dividend_start = static_cast<uint32_t>(std::numeric_limits<uint16_t>::lowest());\n    uint32_t nDividends = (1u << 16);\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u16_c, static_cast<uint16_t>(thread_dividend_start), static_cast<uint16_t>(thread_dividend_end)));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<uint16_t>\\n\");\n  /**\n   * Test dividends on the range [0, 2^16-1] multithreaded\n   */\n  {\n    uint32_t dividend_start = static_cast<uint32_t>(std::numeric_limits<uint16_t>::lowest());\n    uint32_t nDividends = (1u << 16);\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u16_cpp, static_cast<uint16_t>(thread_dividend_start), static_cast<uint16_t>(thread_dividend_end)));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround_i32\\n\");\n  /**\n   * Test dividends on the range [-2^31, -2^31+2^16] multithreaded\n   */\n  {\n    int32_t dividend_start = std::numeric_limits<int32_t>::lowest();\n    uint32_t nDividends = (1u << 16) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [-2^16, 2^16] multithreaded\n   */\n  {\n    int32_t dividend_start = -(1 << 16);\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^31-2^16-1, 2^31-1] multithreaded\n   */\n  {\n    int32_t dividend_start = std::numeric_limits<int32_t>::max() - (1 << 16);\n    uint32_t nDividends = (1u << 16) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<int32_t>\\n\");\n  /**\n   * Test dividends on the range [-2^31, -2^31+2^16] multithreaded\n   */\n  {\n    int32_t dividend_start = std::numeric_limits<int32_t>::lowest();\n    uint32_t nDividends = (1u << 16) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [-2^16, 2^16] multithreaded\n   */\n  {\n    int32_t dividend_start = -(1 << 16);\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^31-2^16-1, 2^31-1] multithreaded\n   */\n  {\n    int32_t dividend_start = std::numeric_limits<int32_t>::max() - (1 << 16);\n    uint32_t nDividends = (1u << 16) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    int32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int32_t thread_dividend_end = thread_dividend_start + static_cast<int32_t>(nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i32_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround_u32\\n\");\n  /**\n   * Test dividends on the range [0, 2^17] multithreaded\n   */\n  {\n    uint32_t dividend_start = std::numeric_limits<uint32_t>::lowest();\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u32_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1u;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^32-2^17-1, 2^32-1] multithreaded\n   */\n  {\n    uint32_t dividend_start = std::numeric_limits<uint32_t>::max() - (1u << 17);\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u32_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1u;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<uint32_t>\\n\");\n  /**\n   * Test dividends on the range [0, 2^17] multithreaded\n   */\n  {\n    uint32_t dividend_start = std::numeric_limits<uint32_t>::lowest();\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u32_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1u;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^32-2^17-1, 2^32-1] multithreaded\n   */\n  {\n    uint32_t dividend_start = std::numeric_limits<uint32_t>::max() - (1u << 17);\n    uint32_t nDividends = (1u << 17) + 1u;\n    uint32_t nDividends_per_thread = nDividends / nThreads;\n    uint32_t nDividends_remaining = nDividends % nThreads;\n    uint32_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint32_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1u);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u32_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1u;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround_i64\\n\");\n  /**\n   * Test dividends on the range [-2^63, -2^63+2^16] multithreaded\n   */\n  {\n    int64_t dividend_start = std::numeric_limits<int64_t>::lowest();\n    uint64_t nDividends = (1ull << 16) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [-2^16, 2^16] multithreaded\n   */\n  {\n    int64_t dividend_start = -(1ll << 16);\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_c, thread_dividend_start,thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^63-2^16-1, 2^63-1] multithreaded\n   */\n  {\n    int64_t dividend_start = std::numeric_limits<int64_t>::max() - (1ll << 16);\n    uint64_t nDividends = (1ull << 16) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<int64_t>\\n\");\n    /**\n   * Test dividends on the range [-2^63, -2^63+2^16] multithreaded\n   */\n  {\n    int64_t dividend_start = std::numeric_limits<int64_t>::lowest();\n    uint64_t nDividends = (1ull << 16) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [-2^16, 2^16] multithreaded\n   */\n  {\n    int64_t dividend_start = -(1ll << 16);\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^63-2^16-1, 2^63-1] multithreaded\n   */\n  {\n    int64_t dividend_start = std::numeric_limits<int64_t>::max() - (1ll << 16);\n    uint64_t nDividends = (1ull << 16) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    int64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      int64_t thread_dividend_end = thread_dividend_start + static_cast<int64_t>(nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_i64_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ll;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround_u64\\n\");\n  /**\n   * Test dividends on the range [0, 2^17] multithreaded\n   */\n  {\n    uint64_t dividend_start = std::numeric_limits<uint64_t>::lowest();\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    uint64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint64_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u64_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ull;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^64-2^17-1, 2^64-1] multithreaded\n   */\n  {\n    uint64_t dividend_start = std::numeric_limits<uint64_t>::max() - (1ull << 17);\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    uint64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint64_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u64_c, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ull;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"Testing divround<uint64_t>\\n\");\n  /**\n   * Test dividends on the range [0, 2^17] multithreaded\n   */\n  {\n    uint64_t dividend_start = std::numeric_limits<uint64_t>::lowest();\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    uint64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint64_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u64_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ull;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  /**\n   * Test dividends on the range [2^64-2^17-1, 2^64-1] multithreaded\n   */\n  {\n    uint64_t dividend_start = std::numeric_limits<uint64_t>::max() - (1ull << 17);\n    uint64_t nDividends = (1ull << 17) + 1ull;\n    uint64_t nDividends_per_thread = nDividends / nThreads;\n    uint64_t nDividends_remaining = nDividends % nThreads;\n    uint64_t thread_dividend_start = dividend_start;\n    for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n      uint64_t thread_dividend_end = thread_dividend_start + (nDividends_per_thread-1ull);\n      if (jThread < nDividends_remaining) thread_dividend_end++;\n      vThreads.at(jThread) = std::move(std::thread(test_divround_u64_cpp, thread_dividend_start, thread_dividend_end));\n      thread_dividend_start = thread_dividend_end+1ull;\n    }\n  }\n\n  for (uint32_t jThread = 0u; jThread < nThreads; jThread++) {\n    vThreads.at(jThread).join();\n  }\n\n  std::printf(\"If there are no errors above, the tests were successful.\\n\\n\");\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": "39b00e136e6fc3af009d4e32c667572e825bec14", "size": 55839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integer/test_divround.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/test_divround.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/test_divround.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": 43.9331235248, "max_line_length": 234, "alphanum_fraction": 0.6951951145, "num_tokens": 15989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6604750650599561}}
{"text": "#include <stan/math/prim/arr.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, sumZeroSize) {\n  std::vector<double> x;\n  EXPECT_FLOAT_EQ(0.0, stan::math::sum(x));\n}\n\nTEST(MathFunctions, sum) {\n  std::vector<double> x(3);\n  \n  x[0] = 1.0;\n  x[1] = 2.0;\n  x[2] = 3.0;\n  \n  EXPECT_FLOAT_EQ(6.0, stan::math::sum(x));\n}\n\nTEST(MathFunctions, sub_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  std::vector<double> x(3);\n  \n  x[0] = 1.0;\n  x[1] = 2.0;\n  x[2] = nan;\n\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::sum(x));\n}\nTEST(MathMatrix,sum_vector_int) {\n  std::vector<int> x(3);\n  EXPECT_EQ(0,stan::math::sum(x));\n  x[0] = 1;\n  x[1] = 2;\n  x[2] = 3;\n  EXPECT_EQ(6,stan::math::sum(x));\n}\n", "meta": {"hexsha": "035409a0bc03d0d9065e3b71682ff9d0af3b761c", "size": 782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/sum_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/sum_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/arr/fun/sum_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0512820513, "max_line_length": 56, "alphanum_fraction": 0.6061381074, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.6604750635913558}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <cstdlib>\n#include <time.h>\n#include <fstream>\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\nvoid Maxoff_test(double &max,int &k,int &l);\n\nvoid Ortho_test(mat &S,int N);\n\nint main(){\n    int N = 400; //matrix size; N x N\n    double rhoN = 60;\n    double max;\n    int k,l;\n    Maxoff_test(max,k,l);\n\n    mat A = mat(N,N,fill::zeros); //indexes go from (0) to (N-1)\n    mat S = mat(N,N,fill::eye);\n    vec rho = vec(N,fill::zeros);\n    vec eigen = vec(N);\n\n    RHO_A_FILL(rho,A,N,rhoN);\n    Maxoff(A,N,k,l,max);\n    int iterations = 0;\n\n    double eps = 1E-10;\n\n    double tau, t, s, c, il, ik, kk, ll, s_ik, s_il;\n    double start, finish;\n\n    start = clock();                      //clock value before eigen solve\n    while(max > eps){\n        tau = (A(l,l)-A(k,k))/(double(2)*A(k,l));\n        if(tau>0){\n             t = (-tau - sqrt(1.0 + tau*tau));}\n        else{t = ( -tau + sqrt(1.0 + tau*tau));}\n     \n        //cosine and sine\n        c = double(1)/sqrt(1.+t*t);\n        s = t*c;\n     \n        //Jacobi rotating A round theta in N-dim space\n        for(int i = 0; i<N; i++){\n            if ((i != k) && (i !=l)){\n                ik = A(i,k)*c - A(i,l)*s;\n                il = A(i,l)*c + A(i,k)*s;\n                A(i,k) = ik;\n                A(k,i) = ik;\n                A(i,l) = il;\n                A(l,i) = il;\n                }\n            s_ik = S(i,k);\n            s_il = S(i,l);\n            S(i,k) = c*s_ik - s*s_il;\n            S(i,l) = c*s_il + s*s_ik; \n            }\n\n        kk = A(k,k)*c*c - 2.*A(k,l)*c*s + A(l,l)*s*s;\n        ll = A(l,l)*c*c + 2.*A(k,l)*c*s + A(k,k)*s*s;\n     \n        A(k,k) = kk;\n        A(l,l) = ll;\n        A(k,l) = 0;\n        A(l,k) = 0;\n\n        iterations++;\n        Maxoff(A,N,k,l,max);\n        //Ortho test\n        if (iterations%N*2==0){\n            Ortho_test(S,N);\n            }\n\n        } //end of while\n    finish = clock();                    //clock value after eigen solve\n\n    //[eigen] is now eigenvalues\n    for(int i = 0; i<N;i++){\n        eigen(i) = A(i,i);\n        }\n\n    eigen.print();\n\n    double time = (finish -start)/CLOCKS_PER_SEC/iterations;\n        \n    fstream outfile;\n    outfile.open(\"eigenvectors5.dat\",ios::out);\n\n    for (int i = 0; i<N; i++){\n        for (int j = 0; j<N; j++){\n            if(j%N == 0){outfile<<endl;}                        \n            outfile << S(i,j)<<\" \";\n            }\n        }\n    outfile.close();\n    \n    \n    fstream utfile;\n    utfile.open(\"eigenvalues5.dat\",ios::out);\n\n    for (int i = 0; i<N; i++){\n        utfile << eigen(i)<<endl;\n        }\n    utfile.close();\n    \n    //fstream Outfile;\n    //Outfile.open(\"steps.dat\",ios::out);\n    //Outfile << \"N     epsilon    steps  step_time\"<<endl;\n\n    //Outfile <<N <<\" \"<<eps<<\" \"<<iterations<<\" \"<<time;\n    //Outfile<<endl;\n        \n    //Outfile.close();\n\n} //end of main\n\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN){\n    double h = rhoN/(N);\n    rho(0) = 0.000001;\n    for(int i = 0; i < N;i++){\n        if(i > 0) rho(i) = i*h;   \n        A(i,i) = 2./(h*h)+ double(25)*rho(i)*rho(i)+(double(1)/rho(i));\n        if(i<N-1){\n            A(i+1,i) = -1./(h*h);\n            A(i,i+1) = -1./(h*h);         \n}\n        }\n    }\n\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max){\n    N = A.n_rows;    \n    max = 0;\n    for(int i = 0; i < N ; i++){\n        for(int j = i+1; j < N ; j++){\n            if ( A(i,j)*A(i,j) > max){\n                max =A(i,j)*A(i,j);\n                k = i; \n                l = j;\n                }\n            }\n        }\n    \n    }\n////////////Unit tests\nvoid Maxoff_test(double &max,int &k,int &l){\n    mat matrix = mat(5,5,fill::zeros);\n    matrix(0,3) = -9;\n    matrix(3,0) = -9;\n    matrix(4,4) = -3;\n    matrix(3,4) = -1;\n    matrix(4,3) = -1;\n    Maxoff(matrix,5,k,l,max);\n    if(abs(max-81) < 1E-13){cout << \"Maxoff function passes the test\"<<endl;}\n    else{cout<<\"Maxoff might not be working properly\"<<endl;}\n    }\nvoid Ortho_test(mat &S,int N){\n    double error = 0;\n    error = dot(S.col(int(double(rand())/RAND_MAX*N)),S.col(int(double(rand())/RAND_MAX*N)));\n    if (abs(error) < 1e-10){\n        cout << \"ortho pass\" << endl;}\n    else{cout<<\"ortho fail\" << endl;}\n    }\n\n\n\n", "meta": {"hexsha": "de0292302ec5175b48f8a9c3707eb398a3dc22ce", "size": 4506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project2/code-joseph/jacobi_interact.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_interact.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_interact.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": 25.8965517241, "max_line_length": 98, "alphanum_fraction": 0.4454061252, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6604247243425633}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <pybind11/eigen.h>\n#include <pybind11/operators.h>\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\nPYBIND11_PLUGIN(linear_solver) {\n  py::module m(\"linear_solver\", \"linear_solver\");\n\n  m.def(\"solve\",\n        [](Eigen::Ref<Eigen::MatrixXd> H, Eigen::Ref<Eigen::VectorXd> g) {\n          Eigen::MatrixXd solution = H.fullPivHouseholderQr().solve(g);\n          return solution;\n        });\n  m.def(\"solve\",\n        [](Eigen::Ref<Eigen::MatrixXd> H, Eigen::Ref<Eigen::MatrixXd> g) {\n          Eigen::MatrixXd solution = H.fullPivHouseholderQr().solve(g);\n          return solution;\n        });\n\n  m.def(\"expm\", [](Eigen::Ref<Eigen::MatrixXd> A) {\n    Eigen::MatrixXd solution = A.exp();\n    return solution;\n\n  });\n\n  m.def(\"logm\", [](Eigen::Ref<Eigen::MatrixXd> A) {\n      Eigen::MatrixXd solution = A.log();\n      return solution;\n\n    });\n\n  return m.ptr();\n}\n", "meta": {"hexsha": "54ef42caa202c544f006c784420314435d37c5af", "size": 945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/linear_solver.cpp", "max_stars_repo_name": "tingelst/game", "max_stars_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T08:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T23:05:46.000Z", "max_issues_repo_path": "src/linear_solver.cpp", "max_issues_repo_name": "tingelst/game", "max_issues_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T09:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T09:41:47.000Z", "max_forks_repo_path": "src/linear_solver.cpp", "max_forks_repo_name": "tingelst/game", "max_forks_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T04:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T12:56:45.000Z", "avg_line_length": 25.5405405405, "max_line_length": 74, "alphanum_fraction": 0.619047619, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391621868805, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6603643768775018}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/ceil_div.hpp>\n#include <fcppt/math/ceil_div_signed.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tceil_div\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div(\n\t\t\t0u,\n\t\t\t1u\n\t\t),\n\t\t0u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div(\n\t\t\t1u,\n\t\t\t1u\n\t\t),\n\t\t1u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div(\n\t\t\t5u,\n\t\t\t3u\n\t\t),\n\t\t2u\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div(\n\t\t\t6u,\n\t\t\t3u\n\t\t),\n\t\t2u\n\t);\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tceil_div_signed\n)\n{\nFCPPT_PP_POP_WARNING\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div_signed(\n\t\t\t-3,\n\t\t\t2\n\t\t),\n\t\t-1\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tfcppt::math::ceil_div_signed(\n\t\t\t5,\n\t\t\t3\n\t\t),\n\t\t2\n\t);\n}\n", "meta": {"hexsha": "87f8c0b894335c3f49d83c4ba74a55fa50f38111", "size": 1266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/ceil_div.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/ceil_div.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/ceil_div.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0714285714, "max_line_length": 61, "alphanum_fraction": 0.7014218009, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6603607754085725}}
{"text": "#pragma once\n// hprblas.hpp :  include file containing templated C++ interfaces to High-Performance Reproducible BLAS routines\n//\n// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n#include <universal/number/posit/posit>\n#include <boost/numeric/mtl/mtl.hpp>\n\nnamespace sw {\nnamespace hprblas {\n\n// LEVEL 1 BLAS operators\n\n// 1-norm of a vector: sum of magnitudes of the vector elements, default increment stride is 1\ntemplate<typename Vector>\ntypename Vector::value_type asum(size_t n, const Vector& x, size_t incx = 1) {\n\ttypename Vector::value_type sum = 0;\n\tsize_t ix;\n\tfor (ix = 0; ix < n; ix += incx) {\n\t\tsum += (x[ix] < 0 ? -x[ix] : x[ix]);\n\t}\n\treturn sum;\n}\n\n// sum of the vector elements, default increment stride is 1\ntemplate<typename Vector>\ntypename Vector::value_type sum(size_t n, const Vector& x, size_t incx = 1) {\n\ttypename Vector::value_type sum = 0;\n\tsize_t ix;\n\tfor (ix = 0; ix < n; ix += incx) {\n\t\tsum += x[ix];\n\t}\n\treturn sum;\n}\n\n// a time x plus y\ntemplate<typename Scalar, typename Vector>\nvoid axpy(size_t n, Scalar a, const Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ty[iy] += a * x[ix];\n\t}\n}\n\n// vector copy\ntemplate<typename Vector>\nvoid copy(size_t n, const Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ty[iy] = x[ix];\n\t}\n}\n\n// adapter for STL vectors\n//template<typename Scalar> auto size(const std::vector<Scalar>& v) { return v.size(); }\n\n// dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well\n// The library does support arbitrary posit configuration conversions, but to simplify the \n// behavior of the dot product, the element type of the vectors x and y are declared to be the same.\n// TODO: investigate if the vector<> index is always a 32bit entity?\ntemplate<typename Vector>\ntypename Vector::value_type dot(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tusing namespace mtl;\n\ttypename Vector::value_type product = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < mtl::size(x) && iy < mtl::size(y); ++cnt, ix += incx, iy += incy) {\n\t\tproduct += x[ix] * y[iy];\n\t}\n\treturn product;\n}\n// specialized dot product\ntemplate<typename Vector>\ntypename Vector::value_type dot(const Vector& x, const Vector& y) {\n\tusing namespace mtl;\n\ttypename Vector::value_type product = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < mtl::size(x); ++cnt, ++ix, ++iy) {\n\t\tproduct += x[ix] * y[iy];\n\t}\n\treturn product;\n}\n///\n/// fused dot product operators\n\n// Fused dot product with quire continuation\ntemplate<typename Quire, typename Vector>\nvoid fdp_qr(Quire& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tsum_of_products += sw::universal::quire_mul(x[ix], y[iy]);\n\t}\n}\n// Resolved fused dot product, with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tsw::universal::quire<nbits, es, capacity> q(0);\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tq += sw::universal::quire_mul(x[ix], y[iy]);\n\t\tif (sw::universal::_trace_quire_add) std::cout << q << '\\n';\n\t}\n\ttypename Vector::value_type sum;\n\tsw::universal::convert(q.to_value(), sum);     // one and only rounding step of the fused-dot product\n\treturn sum;\n}\n// Specialized resolved fused dot product that assumes unit stride and a standard vector,\n// with the option to control capacity bits in the quire\ntemplate<typename Vector, size_t capacity = 10>\ntypename Vector::value_type fdp(const Vector& x, const Vector& y) {\n\tusing namespace mtl;\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tsw::universal::quire<nbits, es, capacity> q(0);\n\tsize_t ix, iy, n = mtl::size(x);\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) {\n\t\tq += sw::universal::quire_mul(x[ix], y[iy]);\n\t}\n\ttypename Vector::value_type sum;\n\tsw::universal::convert(q.to_value(), sum);     // one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n// rotation of points in the plane\ntemplate<typename Rotation, typename Vector>\nvoid rot(size_t n, Vector& x, size_t incx, Vector& y, size_t incy, Rotation c, Rotation s) {\n\tusing namespace mtl;\n\t// x_i = c*x_i + s*y_i\n\t// y_i = c*y_i - s*x_i\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\tRotation x_i = c*x[ix] + s*y[iy];\n\t\tRotation y_i = c*y[iy] - s*x[ix];\n\t\ty[iy] = y_i;\n\t\tx[ix] = x_i;\n\t}\n}\n\n// compute parameters for a Givens rotation\ntemplate<typename T>\nvoid rotg(T& a, T& b, T& c, T&s) {\n\t// Given Cartesian coordinates (a,b) of a point, return parameters c,s,r, and z associated with the Givens rotation.\n}\n\n// scale a vector\ntemplate<typename Scalar, typename Vector>\nvoid scale(size_t n, Scalar a, Vector& x, size_t incx) {\n\tusing namespace mtl;\n\tsize_t cnt, ix;\n\tfor (cnt = 0, ix = 0; cnt < n && ix < size(x); ix += incx) {\n\t\tx[ix] *= a;\n\t}\n}\n\n// swap two vectors\ntemplate<typename Vector>\nvoid swap(size_t n, Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ttypename Vector::value_type tmp = x[ix];\n\t\tx[ix] = y[iy];\n\t\ty[iy] = tmp;\n\t}\n}\n\n// find the index of the element with maximum absolute value\ntemplate<typename Vector>\nsize_t amax(size_t n, const Vector& x, size_t incx) {\n\tusing namespace mtl;\n\ttypename Vector::value_type running_max = -INFINITY;\n\tsize_t ix, index;\n\tfor (ix = 0; ix < size(x); ix += incx) {\n\t\tif (x[ix] > running_max) {\n\t\t\tindex = ix;\n\t\t\trunning_max = x[ix];\n\t\t}\n\t}\n\treturn index;\n}\n\n// find the index of the element with minimum absolute value\ntemplate<typename Vector>\nsize_t amin(size_t n, const Vector& x, size_t incx) {\n\tusing namespace mtl;\n\ttypename Vector::value_type running_min = INFINITY;\n\tsize_t ix, index;\n\tfor (ix = 0; ix < size(x); ix += incx) {\n\t\tif (x[ix] < running_min) {\n\t\t\tindex = ix;\n\t\t\trunning_min = x[ix];\n\t\t}\n\t}\n\treturn index;\n}\n\n// absolute value of a complex number\ntemplate<typename T>\nT cabs(T z) {\n}\n\n// print a vector\ntemplate<typename Vector>\nvoid strided_print(std::ostream& ostr, size_t n, Vector& x, size_t incx = 1) {\n\tusing namespace mtl;\n\tsize_t cnt, ix;\n\tfor (cnt = 0, ix = 0; cnt < n && ix < size(x); ++cnt, ix += incx) {\n\t\tcnt == 0 ? ostr << \"[\" << x[ix] : ostr << \", \" << x[ix];\n\t}\n\tostr << \"]\";\n}\n\n\n// LEVEL 2 BLAS operators\n\n// Matrix-vector product: b = A * x\ntemplate<typename Matrix, typename Vector>\nvoid matvec(Vector& b, const Matrix& A, const Vector& x) {\n\tb = A * x;\n}\n\n// Matrix-vector product: b = A * x, posit specialized\ntemplate<size_t nbits, size_t es>\nvoid matvec(mtl::vec::dense_vector< sw::universal::posit<nbits, es> >& b, const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& A, const mtl::vec::dense_vector< sw::universal::posit<nbits, es> >& x) {\n\tusing namespace mtl;\n\t// preconditions\n\tassert(A.num_cols() == size(x));\n\tassert(size(b) == size(x));\n\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tunsigned errors = 0;\n#endif\n\tsize_t nr = size(b);\n\tsize_t nc = size(x);\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tsw::universal::quire<nbits, es> q(0);\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tq += sw::universal::quire_mul(A[i][j], x[j]);\n\t\t}\n\t\tsw::universal::convert(q.to_value(), b[i]);     // one and only rounding step of the fused-dot product\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\t\tsw::universal::quire<nbits, es> qdiff = q;\n\t\tsw::universal::quire<nbits, es> qsum = b[i];\n\t\tqdiff -= qsum;\n\t\tif (!qdiff.iszero()) {\n\t\t\t++errors;\n\t\t\tstd::cout << \"q    : \" << q << std::endl;\n\t\t\tstd::cout << \"qsum : \" << qsum << std::endl;\n\t\t\tstd::cout << \"qdiff: \" << qdiff << std::endl;\n\t\t\tsw::universal::posit<nbits, es> roundingError;\n\t\t\tconvert(qdiff.to_value(), roundingError);\n\t\t\tstd::cout << \"matvec b[\" << i << \"] = \" << posit_format(b[i]) << \" rounding error: \" << posit_format(roundingError) << \" \" << roundingError << std::endl;\n\t\t}\n#endif\n\t}\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tif (errors) {\n\t\tstd::cout << \"HPR-BLAS: tracing found \" << errors << \" rounding errors in matvec operation\\n\";\n\t}\n#endif\n}\n\n// A times x = b fused matrix-vector product\ntemplate<size_t nbits, size_t es>\nmtl::vec::dense_vector< sw::universal::posit<nbits, es> > fmv(const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& A, const mtl::vec::dense_vector< sw::universal::posit<nbits, es> >& x) {\n\tusing namespace mtl;\n\t// preconditions\n\tassert(A.num_cols() == size(x));\n\tmtl::vec::dense_vector< sw::universal::posit<nbits, es> > b(size(x));\n\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tunsigned errors = 0;\n#endif\n\tsize_t nr = size(b);\n\tsize_t nc = size(x);\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tsw::universal::quire<nbits, es> q(0);\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tq += sw::universal::quire_mul(A[i][j], x[j]);\n\t\t}\n\t\tsw::universal::convert(q.to_value(), b[i]);     // one and only rounding step of the fused-dot product\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\t\tsw::universal::quire<nbits, es> qdiff = q;\n\t\tsw::universal::quire<nbits, es> qsum = b[i];\n\t\tqdiff -= qsum;\n\t\tif (!qdiff.iszero()) {\n\t\t\t++errors;\n\t\t\tstd::cout << \"q    : \" << q << std::endl;\n\t\t\tstd::cout << \"qsum : \" << qsum << std::endl;\n\t\t\tstd::cout << \"qdiff: \" << qdiff << std::endl;\n\t\t\tsw::universal::posit<nbits, es> roundingError;\n\t\t\tconvert(qdiff.to_value(), roundingError);\n\t\t\tstd::cout << \"matvec b[\" << i << \"] = \" << posit_format(b[i]) << \" rounding error: \" << posit_format(roundingError) << \" \" << roundingError << std::endl;\n\t\t}\n#endif\n\t}\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tif (errors) {\n\t\tstd::cout << \"HPR-BLAS: tracing found \" << errors << \" rounding errors in matvec operation\\n\";\n\t}\n#endif\n\treturn b;\n}\n\n// LEVEL 3 BLAS operators\n\ntemplate<typename Matrix>\nvoid matmul(Matrix& C, const Matrix& A, const Matrix& B) {\n\tC = A * B;\n}\n\n// C = A * B fused matrix-matrix product when posits are used\ntemplate<size_t nbits, size_t es>\nvoid matmul(mtl::mat::dense2D< sw::universal::posit<nbits, es> >& C, const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& A, const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& B) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tsize_t nr = A.num_rows();\n\tsize_t nc = B.num_cols();\n\tsize_t nk = A.num_cols();\n\t// TODO: add asserts to make certain that C is the right size\n\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tsw::universal::quire<nbits, es> q(0);\n\t\t\tfor (size_t k = 0; k < nk; ++k) {\n\t\t\t\tq += sw::universal::quire_mul(A[i][k], B[k][j]);\n\t\t\t}\n\t\t\tsw::universal::convert(q.to_value(), C[i][j]);     // one and only rounding step of the fused-dot product\n\t\t}\n\t}\n}\n\n// C = A * B fused matrix-matrix product when posits are used\ntemplate<size_t nbits, size_t es>\nmtl::mat::dense2D< sw::universal::posit<nbits, es> > fmm(const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& A, const mtl::mat::dense2D< sw::universal::posit<nbits, es> >& B) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tsize_t nr = A.num_rows();\n\tsize_t nc = B.num_cols();\n\tsize_t nk = A.num_cols();\n\tmtl::mat::dense2D< sw::universal::posit<nbits, es> > C(nr, nc);\n\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tsw::universal::quire<nbits, es> q(0);\n\t\t\tfor (size_t k = 0; k < nk; ++k) {\n\t\t\t\tq += sw::universal::quire_mul(A[i][k], B[k][j]);\n\t\t\t}\n\t\t\tsw::universal::convert(q.to_value(), C[i][j]);     // one and only rounding step of the fused-dot product\n\t\t}\n\t}\n\treturn C;\n}\n\ntemplate<typename Scalar>\ninline Scalar minimum(const Scalar& a, const Scalar& b) {\n\treturn (a < b ? a : b);\n}\n\n// if you only specify one set of block parameters in the specification then by \n// the virtue of doing block matrix multiplication you generate the invariant : blockHeight == blockWidth\n// Thus, no need to specify blockHeight and blockWidth: we can simplify to blockSize\n// blockHeight = blockWidth = blockSize\n\n// subBlockMM generates the partial sums of a sub-block matrix multiply\n// the QuireMatrix is [blockHeight][blockWidth] submatrix\n// A and B matrices are full [n][m] and [m][n] matrices\ntemplate<typename Matrix>\nvoid subBlockMM(Matrix& C_partial, const Matrix& A, unsigned Ai, unsigned Aj, const Matrix& B, unsigned Bi, unsigned Bj) {\n\tassert(mtl::mat::num_rows(C_partial) == mtl::mat::num_cols(C_partial));\n\tusing Scalar = typename Matrix::value_type;\n//\tconstexpr size_t nbits = Scalar::nbits;\n//\tconstexpr size_t es = Scalar::es;\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\tunsigned bRows = unsigned(mtl::mat::num_rows(B));\n\tunsigned bCols = unsigned(mtl::mat::num_cols(B));\n\n\tunsigned blockSize = unsigned(mtl::mat::num_rows(C_partial));\n\n\tunsigned aRow = Ai * blockSize;\n\tunsigned aCol = Aj * blockSize;\n\tunsigned bRow = Bi * blockSize;\n\tunsigned bCol = Bj * blockSize;\n\n\t// calculate the shape of submatrix A\n\tunsigned ar = (aRow + blockSize < aRows) ? blockSize : aRows - aRow;\n\tunsigned ac = (aCol + blockSize < aCols) ? blockSize : aCols - aCol;\n\tunsigned br = (bRow + blockSize < bRows) ? blockSize : bRows - bRow;\n\tunsigned bc = (bCol + blockSize < bCols) ? blockSize : bCols - bCol;\n\t\n//\tstd::cout << \"A=\" << ar << \"x\" << ac << \"  B=\" << br << \"x\" << bc << std::endl;\n\tassert(ac == br);\n\t// A(ar,ac) x B(br,bc) = C(ar,bc) if ac == br\n\tfor (unsigned i = 0; i < ar; ++i) {\n\t\tfor (unsigned j = 0; j < bc; ++j) {\n\t\t\tfor (unsigned k = 0; k < ac; ++k) {\n\t\t\t\tC_partial[i][j] += A[aRow + i][aCol + k] * B[bRow + k][bCol + j];\n\t\t\t}\n//\t\t\tstd::cout << \"A(\" << Ai << \",\" << Aj << \") B(\" << Bi << \",\" << Bj << \") C(\" << i << \",\" << j << \")\\n\";\n//\t\t\tprintMatrix(std::cout, \"partial\", C_partial);\n\t\t}\n\t}\n}\n\n// copySubBlockInto copies a subblock matrix into of the mother matrix\ntemplate<typename Matrix>\nvoid copySubBlockInto(Matrix& A, unsigned ai, unsigned aj, const Matrix& SubBlock) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(SubBlock));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(SubBlock));\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\n\tunsigned aRow = ai * blockHeight;\n\tunsigned aCol = aj * blockWidth;\n\n\tunsigned maxRow = (aRow + blockHeight < aRows) ? blockHeight : aRows - aRow;\n\tunsigned maxCol = (aCol + blockWidth < aCols) ? blockWidth : aCols - aCol;\n\n\tfor (unsigned i = 0; i < maxRow; ++i) {\n\t\tfor (unsigned j = 0; j < maxCol; ++j) {\n\t\t\tA[aRow + i][aCol + j] = SubBlock[i][j];\n\t\t}\n\t}\n}\n\n// bmm is a blocked matrix multply: C = A * B\ntemplate<typename Matrix>\nMatrix bmm(const Matrix& A, const Matrix& B, unsigned blockSize) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tunsigned nr = unsigned(A.num_rows());\n\tunsigned nc = unsigned(B.num_cols());\n\tunsigned nk = unsigned(A.num_cols());\n\tMatrix C(nr, nc);\n\n\tusing Scalar = typename Matrix::value_type;\n\tMatrix C_partial(blockSize, blockSize);\n\n\tunsigned nrRowBlocks = nr % blockSize ? nr / blockSize + 1 : nr / blockSize;\n\tunsigned nrColBlocks = nc % blockSize ? nr / blockSize + 1 : nc / blockSize;\n\tfor (unsigned bi = 0; bi < nrRowBlocks; ++bi) {\t\t\t// row block index\n\t\tfor (unsigned bj = 0; bj < nrColBlocks; ++bj) {\t\t// col block index\n\t\t\tC_partial = Scalar(0);\n\t\t\tfor (unsigned bk = 0; bk < nrRowBlocks; ++bk) { // block iterator\n\t\t\t\tsubBlockMM(C_partial, A, bi, bk, B, bk, bj);\n\t\t\t}\n\t\t\tcopySubBlockInto(C, bi, bj, C_partial);\n\t\t}\n\t}\n\treturn C;\n}\n\n// subBlockMM generates the partial sums of a sub-block matrix multiply\n// the QuireMatrix is a square matrix\n// A and B matrices are full [n][m] and [m][n] matrices\ntemplate<typename QuireMatrix, typename Matrix>\nvoid subBlockMM(QuireMatrix& C, const Matrix& A, unsigned Ai, unsigned Aj, const Matrix& B, unsigned Bi, unsigned Bj) {\n\tassert(mtl::mat::num_rows(C) == mtl::mat::num_cols(C));\n\tusing Scalar = typename Matrix::value_type;\n\tconstexpr size_t nbits = Scalar::nbits;\n\tconstexpr size_t es = Scalar::es;\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\tunsigned bRows = unsigned(mtl::mat::num_rows(B));\n\tunsigned bCols = unsigned(mtl::mat::num_cols(B));\n\n\tunsigned blockSize = unsigned(mtl::mat::num_rows(C));\n\n\tunsigned aRow = Ai * blockSize;\n\tunsigned aCol = Aj * blockSize;\n\tunsigned bRow = Bi * blockSize;\n\tunsigned bCol = Bj * blockSize;\n\n\t// calculate the shape of submatrix A\n\tunsigned ar = (aRow + blockSize < aRows) ? blockSize : aRows - aRow;\n\tunsigned ac = (aCol + blockSize < aCols) ? blockSize : aCols - aCol;\n\tunsigned br = (bRow + blockSize < bRows) ? blockSize : bRows - bRow;\n\tunsigned bc = (bCol + blockSize < bCols) ? blockSize : bCols - bCol;\n\n\t//\tstd::cout << \"A=\" << ar << \"x\" << ac << \"  B=\" << br << \"x\" << bc << std::endl;\n\tassert(ac == br);\n\t// A(ar,ac) x B(br,bc) = C(ar,bc) if ac == br\n\tfor (unsigned i = 0; i < ar; ++i) {\n\t\tfor (unsigned j = 0; j < bc; ++j) {\n\t\t\tfor (unsigned k = 0; k < ac; ++k) {\n\t\t\t\tC[i][j] += sw::universal::quire_mul<nbits,es>(A[aRow+i][aCol+k], B[bRow+k][bCol+j]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// subBlockRound takes a sub-block address and a QuireMatrix and rounds the partial sums\n\ntemplate<typename Matrix, typename QuireMatrix>\nvoid subBlockRound(Matrix& C, unsigned ci, unsigned cj, const QuireMatrix& C_partial) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(C_partial));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(C_partial));\n\n\tunsigned cRows = unsigned(mtl::mat::num_rows(C));\n\tunsigned cCols = unsigned(mtl::mat::num_cols(C));\n\n\tunsigned cRow = ci * blockHeight;\n\tunsigned cCol = cj * blockWidth;\n\n\tunsigned maxRow = (cRow + blockHeight < cRows) ? blockHeight : cRows - cRow;\n\tunsigned maxCol = (cCol + blockWidth < cCols) ? blockWidth : cCols - cCol;\n\n\tfor (unsigned i = 0; i < maxRow; ++i) {\n\t\tfor (unsigned j = 0; j < maxCol; ++j) {\n\t\t\tsw::universal::convert(C_partial[i][j].to_value(), C[cRow + i][cCol + j]);\n\t\t}\n\t}\n}\n\n// copySubBlock copies a subblock matrix out of the mother matrix\n// This function is more generic than used in block matmul, as this can take non-square matrices\ntemplate<typename Matrix>\nvoid copySubBlock(Matrix& SubBlock, const Matrix& M, unsigned bi, unsigned bj) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(SubBlock));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(SubBlock));\n\tfor (unsigned i = 0; i < blockHeight; ++i) {\n\t\tfor (unsigned j = 0; j < blockWidth; ++j) {\n\t\t\tSubBlock[i][j] = M[bi*blockHeight + i][bj*blockWidth + j];\n\t\t}\n\t}\n}\n\n// bfmm is a blocked fused matrix multply: C = A * B\ntemplate<typename Matrix>\nMatrix bfmm(const Matrix& A, const Matrix& B, unsigned blockSize) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tunsigned nr = unsigned(A.num_rows());\n\tunsigned nc = unsigned(B.num_cols());\n\tunsigned nk = unsigned(A.num_cols());\n\tMatrix C(nr, nc);\n\n\tusing Scalar = typename Matrix::value_type;\n\tconstexpr size_t nbits = Scalar::nbits;\n\tconstexpr size_t es = Scalar::es;\n\tusing Quire = typename sw::universal::quire<nbits, es>;\n\tusing QuireMatrix = typename mtl::mat::dense2D<Quire>;\n\tQuireMatrix C_partial(blockSize, blockSize);\n\n\tunsigned nrRowBlocks = nr % blockSize ? nr / blockSize + 1 : nr / blockSize;\n\tunsigned nrColBlocks = nc % blockSize ? nr / blockSize + 1  : nc / blockSize;\n\tfor (unsigned bi = 0; bi < nrRowBlocks; ++bi) {\t\t\t// row block index\n\t\tfor (unsigned bj = 0; bj < nrColBlocks; ++bj) {\t\t// col block index\n\t\t\tC_partial = Scalar(0);\n\t\t\tfor (unsigned bk = 0; bk < nrRowBlocks; ++bk) { // block iterator\n\t\t\t\tsubBlockMM(C_partial, A, bi, bk, B, bk, bj);\n\t\t\t}\n\t\t\tsubBlockRound(C, bi, bj, C_partial);  // C_sub(i,j) = round(QuireMatrix)\n\t\t}\n\t}\n\treturn C;\n}\n\n}} // namespace sw::hprblas\n", "meta": {"hexsha": "4b449a238e2aac08c2fda0e081cfb72ffc2ca8d5", "size": 20270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hprblas.hpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T11:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T11:30:17.000Z", "max_issues_repo_path": "include/hprblas.hpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "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/hprblas.hpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["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.6866197183, "max_line_length": 206, "alphanum_fraction": 0.6525900345, "num_tokens": 6221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.66036075634916}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n */\n\n#include <logog/include/logog.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Point3d.h\"\n#include \"Vector3.h\"\n\n#include \"GeometricBasics.h\"\n\nnamespace MathLib\n{\ndouble orientation3d(MathLib::Point3d const& p,\n                     MathLib::Point3d const& a,\n                     MathLib::Point3d const& b,\n                     MathLib::Point3d const& c)\n{\n    MathLib::Vector3 const ap (a, p);\n    MathLib::Vector3 const bp (b, p);\n    MathLib::Vector3 const cp (c, p);\n    return MathLib::scalarTriple(bp,cp,ap);\n}\n\ndouble calcTetrahedronVolume(MathLib::Point3d const& a,\n                             MathLib::Point3d const& b,\n                             MathLib::Point3d const& c,\n                             MathLib::Point3d const& d)\n{\n    const MathLib::Vector3 ab(a, b);\n    const MathLib::Vector3 ac(a, c);\n    const MathLib::Vector3 ad(a, d);\n    return std::abs(MathLib::scalarTriple(ac, ad, ab)) / 6.0;\n}\n\ndouble calcTriangleArea(MathLib::Point3d const& a, MathLib::Point3d const& b,\n                        MathLib::Point3d const& c)\n{\n    MathLib::Vector3 const u(a, c);\n    MathLib::Vector3 const v(a, b);\n    MathLib::Vector3 const w(MathLib::crossProduct(u, v));\n    return 0.5 * w.getLength();\n}\n\nbool isPointInTetrahedron(MathLib::Point3d const& p, MathLib::Point3d const& a,\n                          MathLib::Point3d const& b, MathLib::Point3d const& c,\n                          MathLib::Point3d const& d, double eps)\n{\n    double const d0 (MathLib::orientation3d(d,a,b,c));\n    // if tetrahedron is not coplanar\n    if (std::abs(d0) > std::numeric_limits<double>::epsilon())\n    {\n        bool const d0_sign (d0>0);\n        // if p is on the same side of bcd as a\n        double const d1 (MathLib::orientation3d(d, p, b, c));\n        if (!(d0_sign == (d1 >= 0) || std::abs(d1) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of acd as b\n        double const d2 (MathLib::orientation3d(d, a, p, c));\n        if (!(d0_sign == (d2 >= 0) || std::abs(d2) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of abd as c\n        double const d3 (MathLib::orientation3d(d, a, b, p));\n        if (!(d0_sign == (d3 >= 0) || std::abs(d3) < eps))\n        {\n            return false;\n        }\n        // if p is on the same side of abc as d\n        double const d4 (MathLib::orientation3d(p, a, b, c));\n        return d0_sign == (d4 >= 0) || std::abs(d4) < eps;\n    }\n    return false;\n}\n\nbool isPointInTriangle(MathLib::Point3d const& p,\n                       MathLib::Point3d const& a,\n                       MathLib::Point3d const& b,\n                       MathLib::Point3d const& c,\n                       double eps_pnt_out_of_plane,\n                       double eps_pnt_out_of_tri,\n                       MathLib::TriangleTest algorithm)\n{\n    switch (algorithm)\n    {\n        case MathLib::GAUSS:\n            return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                        eps_pnt_out_of_tri);\n        case MathLib::BARYCENTRIC:\n            return barycentricPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                              eps_pnt_out_of_tri);\n        default:\n            ERR(\"Selected algorithm for point in triangle testing not found, \"\n                \"falling back on default.\");\n    }\n    return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n                                eps_pnt_out_of_tri);\n}\n\nbool gaussPointInTriangle(MathLib::Point3d const& q,\n                          MathLib::Point3d const& a,\n                          MathLib::Point3d const& b,\n                          MathLib::Point3d const& c,\n                          double eps_pnt_out_of_plane,\n                          double eps_pnt_out_of_tri)\n{\n    MathLib::Vector3 const v(a, b);\n    MathLib::Vector3 const w(a, c);\n\n    Eigen::Matrix2d mat;\n    mat(0, 0) = v.getSqrLength();\n    mat(0, 1) = v[0] * w[0] + v[1] * w[1] + v[2] * w[2];\n    mat(1, 0) = mat(0, 1);\n    mat(1, 1) = w.getSqrLength();\n    Eigen::Vector2d y;\n    y << v[0] * (q[0] - a[0]) + v[1] * (q[1] - a[1]) + v[2] * (q[2] - a[2]),\n        w[0] * (q[0] - a[0]) + w[1] * (q[1] - a[1]) + w[2] * (q[2] - a[2]);\n\n    y = mat.partialPivLu().solve(y);\n\n    const double lower(eps_pnt_out_of_tri);\n    const double upper(1 + lower);\n\n    if (-lower <= y[0] && y[0] <= upper && -lower <= y[1] && y[1] <= upper &&\n        y[0] + y[1] <= upper)\n    {\n        MathLib::Point3d const q_projected(std::array<double, 3>{\n            {a[0] + y[0] * v[0] + y[1] * w[0], a[1] + y[0] * v[1] + y[1] * w[1],\n             a[2] + y[0] * v[2] + y[1] * w[2]}});\n        if (MathLib::sqrDist(q, q_projected) <= eps_pnt_out_of_plane)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool barycentricPointInTriangle(MathLib::Point3d const& p,\n                                MathLib::Point3d const& a,\n                                MathLib::Point3d const& b,\n                                MathLib::Point3d const& c,\n                                double eps_pnt_out_of_plane,\n                                double eps_pnt_out_of_tri)\n{\n    if (std::abs(MathLib::orientation3d(p, a, b, c)) > eps_pnt_out_of_plane)\n    {\n        return false;\n    }\n\n    MathLib::Vector3 const pa(p, a);\n    MathLib::Vector3 const pb(p, b);\n    MathLib::Vector3 const pc(p, c);\n    double const area_x_2(calcTriangleArea(a, b, c) * 2);\n\n    double const alpha((MathLib::crossProduct(pb, pc).getLength()) / area_x_2);\n    if (alpha < -eps_pnt_out_of_tri || alpha > 1 + eps_pnt_out_of_tri)\n    {\n        return false;\n    }\n    double const beta((MathLib::crossProduct(pc, pa).getLength()) / area_x_2);\n    if (beta < -eps_pnt_out_of_tri || beta > 1 + eps_pnt_out_of_tri)\n    {\n        return false;\n    }\n    double const gamma(1 - alpha - beta);\n    return !(gamma < -eps_pnt_out_of_tri || gamma > 1 + eps_pnt_out_of_tri);\n}\n\nbool isPointInTriangleXY(MathLib::Point3d const& p,\n                         MathLib::Point3d const& a,\n                         MathLib::Point3d const& b,\n                         MathLib::Point3d const& c)\n{\n    // criterion: p-a = u0 * (b-a) + u1 * (c-a); 0 <= u0, u1 <= 1, u0+u1 <= 1\n    Eigen::Matrix2d mat;\n    mat(0, 0) = b[0] - a[0];\n    mat(0, 1) = c[0] - a[0];\n    mat(1, 0) = b[1] - a[1];\n    mat(1, 1) = c[1] - a[1];\n    Eigen::Vector2d y;\n    y << p[0] - a[0], p[1] - a[1];\n\n    y = mat.partialPivLu().solve(y);\n\n    // check if u0 and u1 fulfills the condition\n    return 0 <= y[0] && y[0] <= 1 && 0 <= y[1] && y[1] <= 1 && y[0] + y[1] <= 1;\n}\n\nbool dividedByPlane(const MathLib::Point3d& a, const MathLib::Point3d& b,\n                    const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n    for (unsigned x = 0; x < 3; ++x)\n    {\n        const unsigned y = (x + 1) % 3;\n        const double abc =\n            (b[x] - a[x]) * (c[y] - a[y]) - (b[y] - a[y]) * (c[x] - a[x]);\n        const double abd =\n            (b[x] - a[x]) * (d[y] - a[y]) - (b[y] - a[y]) * (d[x] - a[x]);\n\n        if ((abc > 0 && abd < 0) || (abc < 0 && abd > 0))\n        {\n            return true;\n        }\n    }\n    return false;\n}\n\nbool isCoplanar(const MathLib::Point3d& a, const MathLib::Point3d& b,\n                const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n    const MathLib::Vector3 ab(a, b);\n    const MathLib::Vector3 ac(a, c);\n    const MathLib::Vector3 ad(a, d);\n\n    if (ab.getSqrLength() < pow(std::numeric_limits<double>::epsilon(), 2) ||\n        ac.getSqrLength() < pow(std::numeric_limits<double>::epsilon(), 2) ||\n        ad.getSqrLength() < pow(std::numeric_limits<double>::epsilon(), 2))\n    {\n        return true;\n    }\n\n    // In exact arithmetic <ac*ad^T, ab> should be zero\n    // if all four points are coplanar.\n    const double sqr_scalar_triple(\n        pow(MathLib::scalarProduct(MathLib::crossProduct(ac, ad), ab), 2));\n    // Due to evaluating the above numerically some cancellation or rounding\n    // can occur. For this reason a normalisation factor is introduced.\n    const double normalisation_factor =\n        (ab.getSqrLength() * ac.getSqrLength() * ad.getSqrLength());\n\n    // tolerance 1e-11 is choosen such that\n    // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-6) are considered as\n    // coplanar\n    // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-5) are considered as not\n    // coplanar\n    return (sqr_scalar_triple / normalisation_factor < 1e-11);\n}\n\n}  // end namespace MathLib\n", "meta": {"hexsha": "4fc03379471b68cfd9d78aa5334c6cc2e3f00221", "size": 8742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathLib/GeometricBasics.cpp", "max_stars_repo_name": "Bernie2019/ogs", "max_stars_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T13:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T13:43:06.000Z", "max_issues_repo_path": "MathLib/GeometricBasics.cpp", "max_issues_repo_name": "Bernie2019/ogs", "max_issues_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T12:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T12:13:22.000Z", "max_forks_repo_path": "MathLib/GeometricBasics.cpp", "max_forks_repo_name": "Bernie2019/ogs", "max_forks_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-01T13:07:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T13:16:22.000Z", "avg_line_length": 34.828685259, "max_line_length": 80, "alphanum_fraction": 0.5292839167, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6603235482495401}}
{"text": "#include \"stdafx.h\"\n#include \"EigenParameterEstimator.h\"\n\n#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\n\nEigenParameterEstimator::EigenParameterEstimator()\n{\n}\n\nEigenParameterEstimator::EigenParameterEstimator(MeasurementDB * mdb) : _mdb(mdb)\n{\n}\n\nEigenParameterEstimator::~EigenParameterEstimator()\n{\n}\n\nvoid EigenParameterEstimator::estimateParameters(AbstractSolution * sol, double newrelerr)\n{\n\tint m = _mdb->get_size();\n\tint n = 2;\n\n\tMatrixXd A = MatrixXd(m, n);\n\tVectorXd b = VectorXd(m);\n\tVectorXd x = VectorXd(n);\n\n\t// Fill values in vector of right-hand side b\n\tfor (int i = 0; i < m; i++)\n\t\tb[i] = _mdb->getPairAt(i).second;\n\n\t// Zero the solution vector x\n\tfor (int i = 0; i < n; i++)\n\t\tx[i] = 0.0;\n\n\t// Fill the coefficient matrix\n\tfor (int row = 0; row < m; row++) {\n\t\tA(row, 0) = 1.0;\n\t\tA(row, 1) = sol->evaluateConstantTermAt(_mdb->getPairAt(row).first);\n\t}\n\n\tx = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n\n\t// Update Solution\n\tfor (int i = 1; i <= n; ++i) {\n\t\tsol->updateAt(i - 1, x[i - 1]);\n\t}\n}\n", "meta": {"hexsha": "bd239d084a7feb8965a2594fef995b679fd04c0f", "size": 1063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_stars_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_stars_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "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": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_issues_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_issues_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "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": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_forks_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_forks_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "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.8431372549, "max_line_length": 90, "alphanum_fraction": 0.6716839135, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6603235474785153}}
{"text": "#ifndef NONLINEAR_BASIS_HPP\n#define NONLINEAR_BASIS_HPP\n\n#include <armadillo>\n#include <math.h>\n\n\nclass NonLinearBasisFunction : public Basis {\n\npublic:\n\n    int _nX;\n    int _nK;\n    int _nU;\n    int _nM;\n    int _nKU;\n\n    NonLinearBasisFunction(int _nX = 7, int _nK = 25, int _nU = 2 , int _nM = 6, int _nKU = 18) : Basis(_nX,_nK,_nU,_nM,_nKU) {\n        this->_nX = _nX;\n        this->_nK = _nK;\n        this->_nU = _nU;\n        this->_nM = _nM;\n        this->_nKU = _nKU;\n    }\n\n    arma::vec fk(const arma::vec & x, const arma::vec & u ) {\n        return arma::join_cols( fkx(x), fku(x, u) );\n    }\n\n    arma::vec fkx( const arma::vec& x ) {\n        return arma::vec({\n          x[0],\n          x[1],\n          x[2],\n          x[3],\n          x[4],\n          x[5],\n          1\n        });\n    }\n\n    arma::vec fku( const arma::vec & x, const arma::vec& u ) {\n\n        return arma::vec({\n            u[0],\n            u[1],\n            u[0]*x[0],\n            u[0]*x[1],\n            u[0]*x[2],\n            u[0]*x[3],\n            u[0]*x[4],\n            u[0]*x[5],\n            u[1]*x[0],\n            u[1]*x[1],\n            u[1]*x[2],\n            u[1]*x[3],\n            u[1]*x[4],\n            u[1]*x[5],\n            u[0]*cos(x[2]),\n            u[0]*sin(x[2]),\n            u[1]*cos(x[2]),\n            u[1]*sin(x[2])\n          });\n\n    }\n\n    arma::mat fkudu( const arma::vec & x, const arma::vec & u) {\n        return arma::mat({\n            {1,0},\n            {0,1},\n            {x[0],0},\n            {x[1],0},\n            {x[2],0},\n            {x[3],0},\n            {x[4],0},\n            {x[5],0},\n            {0,x[0]},\n            {0,x[1]},\n            {0,x[2]},\n            {0,x[3]},\n            {0,x[4]},\n            {0,x[5]},\n            {cos(x[2]), 0},\n            {sin(x[2]), 0},\n            {0, cos(x[2])},\n            {0, sin(x[2])}\n        });\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "1ef1de4ab112c1c9e610d543f5314514a9d5f47e", "size": 1872, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.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/dynamicalSystems/koopman/basis_functions/nonlinear_basis.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/dynamicalSystems/koopman/basis_functions/nonlinear_basis.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.1290322581, "max_line_length": 127, "alphanum_fraction": 0.3456196581, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6600956707616472}}
{"text": "#include \"utils.h\"\n\n#include <cmath>\n#include <fstream>\n\n#include <boost/format.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <Eigen/Dense>\n\nnamespace masterthesis {\n    double expit(double x) {\n        return x > 0 ? 1 / (1 + std::exp(-x)) : 1 - 1 / (1 + std::exp(x));\n    }\n\n    double log1exp(double x) {\n        return x > 0 ? x + log1p(exp(-x)) : log1p(exp(x));\n    }\n\n    void readFeatureFile(std::string path,\n                         size_t* const nItems, size_t* const mFeatures,\n                         std::vector<double>* const features) {\n        std::fstream features_file_input;\n        features_file_input.open(path, std::ios::in);\n\n        std::string line;\n        std::vector<std::string> tokens;\n        getline(features_file_input, line);\n        boost::split(tokens, line, boost::is_any_of(\",\"));\n        *nItems = stoul(tokens[0]);\n        *mFeatures = stoul(tokens[1]);\n\n        features->reserve(*nItems * *mFeatures);\n        for (size_t i = 0; i < *nItems; ++i) {\n            getline(features_file_input, line);\n            boost::split(tokens, line, boost::is_any_of(\",\"));\n            for (size_t j = 0; j < *mFeatures; ++j) {\n                (*features)[(i * *mFeatures) + j] = stod(tokens[j]);\n            }\n        }\n    }\n\n    void readFeatureFileBoost(std::string path,\n                              size_t &nItems, size_t &mFeatures,\n                              Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> &features) {\n        std::fstream features_file_input;\n        features_file_input.open(path, std::ios::in);\n\n        std::string line;\n        std::vector<std::string> tokens;\n        getline(features_file_input, line);\n        boost::split(tokens, line, boost::is_any_of(\",\"));\n        nItems = stoul(tokens[0]);\n        mFeatures = stoul(tokens[1]);\n\n        features.resize(nItems, mFeatures);\n        for (size_t i = 0; i < nItems; ++i) {\n            getline(features_file_input, line);\n            boost::split(tokens, line, boost::is_any_of(\",\"));\n            for (size_t j = 0; j < mFeatures; ++j) {\n                features(i, j) = stod(tokens[j]);\n            }\n        }\n    }\n}", "meta": {"hexsha": "3862bd4be0be6984c561fcb3b6b96a465ca63b7f", "size": 2167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/utils.cpp", "max_stars_repo_name": "dballesteros7/master-thesis-2015", "max_stars_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppsrc/utils.cpp", "max_issues_repo_name": "dballesteros7/master-thesis-2015", "max_issues_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/utils.cpp", "max_forks_repo_name": "dballesteros7/master-thesis-2015", "max_forks_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_forks_repo_licenses": ["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.3384615385, "max_line_length": 113, "alphanum_fraction": 0.5403784033, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6600956686333126}}
{"text": "#include <iostream>\n#include <cmath>\n#include <random>\n#include <chrono>\n#include <dlib/matrix.h>\n\n\nusing namespace dlib;\nusing namespace std;\n\ndouble nonlin(double x, bool deriv)\n{\n    if (deriv)\n        return x * (1 - x);\n    else\n        return 1/(1+exp(-x));\n}\n/*\ntemplate<class T> T nonlinT(T x, bool deriv)\n{\n    if (deriv)\n        return x * (1 - x);\n    else\n        return 1/(1+exp(-x));\n}\n\n\nvoid foo(std::vector<int> x);\n\nfoo({1,2,3,4});\n*/\n\nint main()\n{\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-1.0,1.0);\n\n    matrix<double,4,3> X, l0;\n    matrix<double,0,1> y, l1, l1_error, l1_delta, l1_tmp;\n    matrix<double,3,1> syn;\n    \n    y.set_size(4);\n    l1.set_size(4);\n    l1_error.set_size(4);\n    l1_delta.set_size(4);\n    l1_tmp.set_size(4);\n    \n    X = 0, 0, 1,\n        0, 1, 1,\n        1, 0, 1,\n        1, 1, 1;\n\n    y = 0,\n        0, \n        1,\n        1;\n        \n    chrono::steady_clock::time_point begin = chrono::steady_clock::now();\n\n    for (int i=0; i<3; i++)\n        syn(i,1) = distribution(generator);\n        \n    cout << syn;\n   \n\n    for (int i=0; i<60000; i++)\n    {\n        l0 = X;\n        l1 = l0 * syn;\n    \n        for (int i=0; i<4; i++)\n            l1(i) = nonlin(l1(i), false);   \n\n        l1_error = y - l1;\n\n        for (int i=0; i<4; i++)\n            l1_tmp(i) = nonlin(l1(i), true);   \n\n        l1_delta = pointwise_multiply(l1_error, l1_tmp);\n\n        syn += trans(l0) * l1_delta;\n    }\n    \n    chrono::steady_clock::time_point end = chrono::steady_clock::now();\n    cout << \"Exec: \" << chrono::duration_cast<chrono::microseconds> (end - begin).count() << endl;\n    \n    cout << \"syn: \\n\" << syn << endl;\n    cout << \"l1: \\n\" << l1 << endl;\n\n}\n\n", "meta": {"hexsha": "6eabe07cdf4a398f064f53c07ca616627d429e56", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dlib_examples/small_neural_network.cpp", "max_stars_repo_name": "ALojdl/HastenedARMDeepLearning", "max_stars_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_stars_repo_licenses": ["MIT"], "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/dlib_examples/small_neural_network.cpp", "max_issues_repo_name": "ALojdl/HastenedARMDeepLearning", "max_issues_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_issues_repo_licenses": ["MIT"], "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/dlib_examples/small_neural_network.cpp", "max_forks_repo_name": "ALojdl/HastenedARMDeepLearning", "max_forks_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-18T13:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T13:16:37.000Z", "avg_line_length": 18.9891304348, "max_line_length": 98, "alphanum_fraction": 0.5163136806, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6600625660605222}}
{"text": "/**\n * ravg.cpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents  are provided as  is,  with no express\n * or implied  warranties,  other  than those  that are  expressly stated  in the\n * License.\n *\n * Copyright \u00a9 2021 Gabriel Moreira. All rights reserved.\n */\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <chrono>\n\n#include <Eigen/Eigenvalues>\n\n#include \"linalg.hpp\"\n#include \"err.hpp\"\n#include \"ravg.hpp\"\n\nusing std::vector;\nusing std::string;\n\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::VectorXd;\nusing Eigen::Ref;\n\nusing namespace std::chrono;\n\ntypedef Eigen::Triplet<double>      Triplet;\ntypedef Eigen::SparseMatrix<double> Sparse;\ntypedef Eigen::PardisoLDLT<Sparse>  PardisoLDLT;\n\n\n/**\n * Cycle graph solver in SO(3).\n *\n * Closed-form cycle graph rotation averaging solver in SO(3).\n *\n * @param edge_r (input) Eigen::MatrixXd - 3 x 3n Eigen matrix with SO(3) blocks. Assumes blocks are stacked as [ R_{1,2} R_{2,3} ... R_{n,1} ]\n * @param num_nodes (input) int - number of variables.\n * @param R (output) Eigen::MatrixXd - 3n x 3 Eigen matrix containing optimal solution.\n */\nvoid cycleSolverSO3(const Ref<MatrixXd> edge_r, int num_nodes, Ref<MatrixXd> R) {\n    auto start = high_resolution_clock::now();\n    \n    // Cycle error E = R_12 * R_23 * R_n-1,n * R_n,1\n    MatrixXd E = Matrix3d::Identity();\n    \n    for (int i = 0; i < num_nodes; ++i)\n        E = E * edge_r.block<3,3>(0, i*3);\n    \n    // Diagonal blocks of change-of-basis matrix U\n    vector<Matrix3d> U(num_nodes);\n    \n    // Build first block\n    Eigen::SelfAdjointEigenSolver<MatrixXd> eig(E + E.transpose());\n    U[0] = eig.eigenvectors();\n    \n    // Build other blocks\n    for (int i = 1; i < num_nodes; ++i)\n        U[i] = edge_r.block<3,3>(0, (i-1)*4).transpose() * U[i-1];\n    \n    /* Change basis according to U^\\top * Rtilde * U\n     * We need only compute the corner block U_n * Rtilde_n1 * U_1 */\n    MatrixXd one_param_edge_r = MatrixXd::Zero(3,3);\n    one_param_edge_r += U[num_nodes-1].transpose() * edge_r.block<3,3>(0, (num_nodes-1)*3) * U[0];\n    \n    // Gamma is the angular cycle error\n    double gamma_cos = 0.5 * (one_param_edge_r(0,0) + one_param_edge_r(1,1));\n    double sine_sign = (double) ((one_param_edge_r(1,0) > 0) - (one_param_edge_r(1,0) < 0));\n    double gamma     = sine_sign * acos(gamma_cos);\n    \n    double gamma_mean = gamma / num_nodes;\n    double theoretical_min = - ((double) num_nodes) * (5.0f + 4.0f * cos(gamma_mean));\n    \n    // Build solution in SO(2) and change basis to produce solution in SO(3)\n    R.block<3,3>(0,0) += U[0];\n    VectorXd theta = VectorXd::Zero(num_nodes,1);\n    \n    for (int i = 1; i < num_nodes; ++i) {\n        theta(i) += theta(i-1) + gamma_mean;\n        double c = cos(theta(i));\n        double s = sin(theta(i));\n        \n        R(i*3,0)   += c;\n        R(i*3,1)   -= s;\n        R(i*3+1,0) += s;\n        R(i*3+1,1) += c;\n        R(i*3+2,2) += 1;\n        \n        // Revert the basis-change\n        R.block<3,3>(i*3,0) = U[i] * R.block<3,3>(i*3,0);\n    };\n    \n    // Fix gauge freedom by setting R_1 = I_3\n    R = R * R.block<3,3>(0,0).transpose();\n\n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<microseconds>(stop - start);\n    \n    // Verbose\n    printf(\"Cycle error (mean): %1.8f\\n\", gamma_mean);\n    printf(\"Theoretical minimum: %1.8f\\n\", theoretical_min);\n    printf(\"CPU time: %.6f\\n\", static_cast<long long int>(duration.count())*1e-6);\n};\n\n\n/**\n * Primal-Dual in SO(3)\n *\n * Primal-dual update method for averaging rotations in SO(3).\n * Finds R in SO(3)^n that minimizes the trace of R^\\top Rtilde R\n *\n * @param Rtilde (input) Eigen::SparseMatrix<double> - 3n x 3n sparse rotation adjacency matrix.\n * @param A (input/output) Eigen::SparseMatrix<double> - n x n symmetric graph adjacency matrix.\n * @param R (output) Eigen::MatrixXd - 3n x 3 solution.\n * @param num_nodes (input) int - number of variables.\n * @param maxiter (input) int - maxiter.\n * @param dual (output) double - value of the dual problem.\n * @param eta (input) double - minimum eigenvalue stopping criterion.\n * @param sigma (input) double - spectral shift.\n */\nvoid primalDualSO3(const Sparse& Rtilde,\n                   const Sparse& A,\n                   Ref<MatrixXd> R,\n                   int num_nodes,\n                   int maxiter,\n                   double& dual,\n                   double eta,\n                   double sigma) {\n    \n    printf(\"\\n%*s SO(3) Primal-dual\\n\", 20, \" \");\n    \n    auto start = high_resolution_clock::now();\n    \n    // Graph degree vector\n    VectorXd D = A * VectorXd::Ones(num_nodes);\n            \n    /* Initialize symmetric block diagonal Lagrange multiplier.\n     * Should initialize all 3x3 blocks instead of just the main\n     * diagonal to ensure the correct NNZ pattern. */\n    vector<Triplet> lambda_buffer(num_nodes * 9);\n    \n    unsigned int k = 0;\n    unsigned int j = 0;\n    for (unsigned int i = 0; i < num_nodes; ++i) {\n        lambda_buffer[j]   = Triplet( k,   k,   D(i) );\n        lambda_buffer[j+1] = Triplet( k+1, k+1, D(i) );\n        lambda_buffer[j+2] = Triplet( k+2, k+2, D(i) );\n        lambda_buffer[j+3] = Triplet( k,   k+1, 1e-15 );\n        lambda_buffer[j+4] = Triplet( k,   k+2, 1e-15 );\n        lambda_buffer[j+5] = Triplet( k+1, k,   1e-15 );\n        lambda_buffer[j+6] = Triplet( k+1, k+2, 1e-15 );\n        lambda_buffer[j+7] = Triplet( k+2, k,   1e-15 );\n        lambda_buffer[j+8] = Triplet( k+2, k+1, 1e-15 );\n        j += 9;\n        k += 3;\n    };\n    \n    Sparse Lambda(num_nodes * 3, num_nodes * 3);\n    Lambda.setFromTriplets(lambda_buffer.begin(), lambda_buffer.end());\n        \n    Sparse L = Lambda - Rtilde;\n    L.makeCompressed();\n    \n    // LDLt solver used in the shift-and-invert spectral transform\n    PardisoLDLT ldlt_solver;\n    \n    // Analyze the NNZ pattern\n    ldlt_solver.analyzePattern(L);\n\n    // Store eigenvalues\n    VectorXd evals = VectorXd::Zero(3, 1);\n        \n    // Main primal-dual loop\n    for (unsigned int i = 0; i < maxiter; ++i) {\n        /* Call symmetric Krylov-Schur LDLt eigensolver on the matrix\n         * Lambda - Rtilde. The three eigenvectors will be stored in R. */\n        alg::symKrylovSchurLDL(&ldlt_solver, L, evals, R, 3, sigma);\n        \n        // Correct gauge freedom\n        Matrix3d gauge = R.block<3,3>(0,0);\n        R = R * gauge.inverse();\n        \n        // SO(3) projection\n        for (unsigned int j = 0; j < 3*num_nodes; j += 3)\n            alg::orthoProcrustesSO3(R.block<3,3>(j, 0));\n        \n        // Build Lambda from triplets for the next iteration\n        MatrixXd RtildeR = Rtilde * R;\n        dual = 3 * num_nodes;\n        for (unsigned int k = 0; k < num_nodes*3; k+=3) {\n            Matrix3d Rk = R.block<3,3>(k,0);\n            Rk.transposeInPlace();\n            MatrixXd block = RtildeR.block<3,3>(k,0) * Rk;\n            \n            // Dual <- + trace(Lambda_i)\n            dual += block(0,0) + block(1,1) + block(2,2);\n            \n            L.coeffRef(k,k)     = block(0,0);\n            L.coeffRef(k+1,k+1) = block(1,1);\n            L.coeffRef(k+2,k+2) = block(2,2);\n            L.coeffRef(k,k+1)   = 0.5 * (block(0,1) + block(1,0));\n            L.coeffRef(k+1,k)   = L.coeffRef(k,k+1);\n            L.coeffRef(k,k+2)   = 0.5 * (block(0,2) + block(2,0));\n            L.coeffRef(k+2,k)   = L.coeffRef(k,k+2);\n            L.coeffRef(k+1,k+2) = 0.5 * (block(1,2) + block(2,1));\n            L.coeffRef(k+2,k+1) = L.coeffRef(k+1,k+2);\n        };\n        \n        // Verbose\n        printf(\"Iteration %d   Dual %.9f   Min eigenvalue %1.3e\\n\", i, dual, abs(evals.minCoeff()));\n\n        // Stopping criterion\n        if (abs(evals.minCoeff()) < eta)\n            break;\n    };\n    \n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<microseconds>(stop - start);\n    printf(\"\\nCPU time : %.6f\\n\", static_cast<long long int>(duration.count())*1e-6);\n};\n", "meta": {"hexsha": "0529547ee16f95609054b02551b77fe75c7c2120", "size": 8017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ravg.cpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "src/ravg.cpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "src/ravg.cpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 34.7056277056, "max_line_length": 143, "alphanum_fraction": 0.5805164026, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6600147507154207}}
{"text": "#define BOOST_TEST_NO_LIB\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"coconut/pulp/math/Angle.hpp\"\n\nusing namespace coconut;\nusing namespace coconut::pulp;\nusing namespace coconut::pulp::math;\n\nnamespace /* anonymous */ {\n\nBOOST_AUTO_TEST_SUITE(PulpTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathAngleTestSuite);\n\nBOOST_AUTO_TEST_CASE(AngleIsConstructibleWithRadians) {\n\tAngle a(3.0_rad);\n\tBOOST_CHECK_EQUAL(a.radians(), 3.0f);\n}\n\nBOOST_AUTO_TEST_CASE(AngleIsConstructibleWithDegrees) {\n\tAngle a(90.0_deg);\n\tBOOST_CHECK_EQUAL(a.degrees(), 90.0f);\n}\n\nBOOST_AUTO_TEST_CASE(AngleConvertsRadiansToDegrees) {\n\tAngle a(radians(PI));\n\tBOOST_CHECK_EQUAL(a.degrees(), 180.0f);\n}\n\nBOOST_AUTO_TEST_CASE(AngleConvertsDegreesToRadians) {\n\tAngle a(degrees(360.0f));\n\tBOOST_CHECK_EQUAL(a.radians(), 2.0f * PI);\n}\n\nBOOST_AUTO_TEST_CASE(AnglesAreAdditive) {\n\tAngle lhs = Angle::RIGHT;\n\tAngle rhs = Angle::HALF_FULL;\n\n\tBOOST_CHECK_EQUAL(lhs + rhs, radians(1.5f * PI));\n\tBOOST_CHECK_EQUAL(rhs - lhs, Angle::RIGHT);\n}\n\nBOOST_AUTO_TEST_CASE(AnglesAreMultiplicativeByScalar) {\n\tBOOST_CHECK_EQUAL(Angle::RIGHT * 4.0f, Angle::FULL);\n\tBOOST_CHECK_EQUAL(Angle::HALF_FULL / 2.0f, Angle::RIGHT);\n}\n\nBOOST_AUTO_TEST_CASE(AnglesAreComparable) {\n\tBOOST_CHECK_EQUAL(degrees(180.0f), radians(PI));\n\tBOOST_CHECK_NE(degrees(180.0f), degrees(180.001f));\n\tBOOST_CHECK_LE(degrees(180.0f), radians(PI));\n\tBOOST_CHECK_LT(degrees(179.0f), radians(PI));\n\tBOOST_CHECK_GT(radians(4.0f), degrees(180.0f));\n\tBOOST_CHECK_GE(radians(4.0f), degrees(180.0f));\n}\n\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathAngleTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpTestSuite */);\n\n} // anonymous namespace\n", "meta": {"hexsha": "535bef9b7e3254e9b31e3aefc7392710687cd428", "size": 1741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Angle.cpp", "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/test/c++/coconut/pulp/math/Angle.cpp", "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/test/c++/coconut/pulp/math/Angle.cpp", "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": 27.6349206349, "max_line_length": 58, "alphanum_fraction": 0.7765651924, "num_tokens": 492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7879311956428946, "lm_q1q2_score": 0.659986905591308}}
{"text": "// standard library\n#include <iostream>\n#include <fstream>\n#include <regex>\n// boost\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/classification.hpp> // is_any_of\n#include <boost/algorithm/string/split.hpp>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/program_options.hpp>\n// Eigen\n#include <Eigen/Dense>\n//\n#include \"gradient_descent_solver.h\"\n\ndouble fn( Eigen::VectorXd x, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n    Eigen::VectorXd t = ( b - A * x );\n    return t.dot( t ) + lambda * x.dot( x );\n}\n\nEigen::VectorXd dfn( Eigen::VectorXd x, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n    return 2 * A.transpose() * ( A * x - b ) + 2 * lambda * x;\n}\n\ndouble errorn( Eigen::VectorXd x, Eigen::VectorXd x_star, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n    return std::abs( fn( x, A, b, lambda ) - fn( x_star, A, b, lambda ) );\n}\n\nbool loadParam( std::string filename, int& degree, Eigen::MatrixXd& A, Eigen::VectorXd& b, double& lambda, Eigen::VectorXd& x_start )\n{\n    std::ifstream ifs( filename );\n    std::string str;\n\n    if ( ifs.fail() ) {\n        return false;\n    } else {\n        std::getline( ifs, str ); //\n        std::getline( ifs, str ); //\n        degree = std::stoi( str );\n\n        A = Eigen::MatrixXd::Identity(degree,degree);\n        b = Eigen::VectorXd::Ones(degree);\n        lambda = 0.0;\n        x_start = b;\n\n        std::getline( ifs, str ); //\n        for ( int i=0; i<degree; i++ ) {\n            std::getline( ifs, str ); //\n            boost::algorithm::trim( str );\n            str = std::regex_replace( str, std::regex(\" +\"), \" \" );\n            std::vector<std::string> result;\n            boost::algorithm::split( result, str, boost::is_any_of(\" \") );\n            for ( int j=0; j<degree; j++ ) {\n                A(i,j) = std::stod( result[j] );\n            }\n        }\n\n        std::getline( ifs, str ); //\n        for ( int i=0; i<degree; i++ ) {\n            std::getline( ifs, str ); //\n            boost::algorithm::trim( str );\n            b(i) = std::stod( str );\n        }\n\n        std::getline( ifs, str ); //\n        std::getline( ifs, str ); //\n        lambda = std::stod( str );\n\n        std::getline( ifs, str ); //\n        for ( int i=0; i<degree; i++ ) {\n            std::getline( ifs, str ); //\n            boost::algorithm::trim( str );\n            x_start(i) = std::stod( str );\n        }\n\n        return true;\n    }\n}\n\nint main( int argc, char **argv )\n{\n    boost::program_options::options_description opt(\"option\");\n    opt.add_options()\n            (\"help,h\", \"shot help\")\n            (\"accel,a\", boost::program_options::value<int>()->default_value(0), \"acceleration method\" )\n            (\"debug\", boost::program_options::value<int>()->default_value(0), \"debug mode\" )\n            (\"degree,d\", boost::program_options::value<int>(), \"size of problem\")\n            (\"error,e\", boost::program_options::value<double>(), \"threshold of error\")\n            (\"lambda,l\", boost::program_options::value<double>(), \"lambda\")\n            (\"printparam\", boost::program_options::value<bool>()->default_value(false), \"print parameter\" )\n            (\"loadparamfile\", boost::program_options::value<std::string>(), \"\" );\n    boost::program_options::variables_map vm;\n    try {\n        boost::program_options::store( boost::program_options::parse_command_line( argc, argv, opt ), vm );\n    } catch ( const boost::program_options::error_with_option_name& e ) {\n        std::cout << e.what() << std::endl;\n        return 0;\n    }\n    boost::program_options::notify( vm );\n\n    srand((unsigned int) time(0));\n\n    int accel;\n    int debug;\n    int degree;\n    double error;\n    bool printparam;\n    Eigen::MatrixXd A;\n    Eigen::VectorXd b, x_start;\n    double lambda;\n    if ( vm.count(\"help\")\n        || ( !vm.count(\"loadparamfile\") and !vm.count(\"degree\") )\n        || !vm.count(\"error\")\n        || ( !vm.count(\"loadparamfile\") and !vm.count(\"lambda\") ) ) {\n        std::cout << opt << std::endl;\n        return 0;\n    } else if ( vm.count(\"loadparamfile\") ) {\n        std::string filename;\n        try {\n            accel = vm[\"accel\"].as<int>();\n            debug = vm[\"debug\"].as<int>();\n            error = vm[\"error\"].as<double>();\n            printparam = vm[\"printparam\"].as<bool>();\n            filename = vm[\"loadparamfile\"].as<std::string>();\n        } catch ( const boost::bad_any_cast& e ) {\n            std::cout << e.what() << std::endl;\n            return 0;\n        }\n        if ( not loadParam( filename, degree, A, b, lambda, x_start ) ) {\n            std::cout << opt << std::endl;\n            return 0;\n        }\n    } else {\n        try {\n            accel = vm[\"accel\"].as<int>();\n            debug = vm[\"debug\"].as<int>();\n            degree = vm[\"degree\"].as<int>();\n            error = vm[\"error\"].as<double>();\n            lambda = vm[\"lambda\"].as<double>();\n            printparam = vm[\"printparam\"].as<bool>();\n        } catch ( const boost::bad_any_cast& e ) {\n            std::cout << e.what() << std::endl;\n            return 0;\n        }\n        double coef = 4.0 / degree;\n        A = Eigen::MatrixXd::Random(degree,degree) * 3 * coef;\n        A = A.transpose() * A;\n        Eigen::VectorXd omega_hat = Eigen::VectorXd::Ones(degree);\n        Eigen::VectorXd eps = Eigen::VectorXd::Random(degree) * coef;\n        b = A * omega_hat + eps;\n        x_start = Eigen::VectorXd::Random(degree) * 10;\n    }\n\n    Eigen::VectorXd x_star = 2 * ( 2 * A.transpose() * A + lambda * Eigen::MatrixXd::Identity( A.rows(), A.cols() ) ).inverse() * A.transpose() * b;\n\n    std::cout << std::fixed;\n\n    if ( printparam ) {\n        std::cout << \"degree:\" << std::endl;\n        std::cout << degree << std::endl;\n        std::cout << \"A:\" << std::endl;\n        std::cout << A << std::endl;\n        std::cout << \"b:\" << std::endl;\n        std::cout << b << std::endl;\n        std::cout << \"lambda:\" << std::endl;\n        std::cout << lambda << std::endl;\n        std::cout << \"x_start:\" << std::endl;\n        std::cout << x_start << std::endl;\n    }\n\n    GradientDescentSolver<Eigen::VectorXd> solver( debug );\n    solver.setf( boost::bind( fn, _1, A, b, lambda ) );\n    solver.setdf( boost::bind( dfn, _1, A, b, lambda ) );\n    solver.seterror( boost::bind( errorn, _1, x_star, A, b, lambda ) );\n    std::vector<Eigen::VectorXd> trajectory;\n    Eigen::VectorXd x_target = solver.solve( x_start, trajectory, error, accel );\n\n    if ( isnan( x_target.norm() ) ) {\n        std::cout << \"diverged.\" << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "44825b692bb8c4b180c7630321a142918d3615bf", "size": 6579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/03_strongconvex.cpp", "max_stars_repo_name": "sktometometo/GradientDescentSolver", "max_stars_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "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/03_strongconvex.cpp", "max_issues_repo_name": "sktometometo/GradientDescentSolver", "max_issues_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "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/03_strongconvex.cpp", "max_forks_repo_name": "sktometometo/GradientDescentSolver", "max_forks_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "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.9946808511, "max_line_length": 148, "alphanum_fraction": 0.537619699, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6599868992035561}}
{"text": "#include \"splines.h\"\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\nstd::vector<double> CalculateCoeffFromPoints(const std::vector<Eigen::Vector3d>& points, bool is3D = true)\n{\n\tstd::vector <double> coeff;\n\tif (points.size() < 4 || points.size() % 4)\n\t\treturn coeff;\n\n\tdouble Ax = 0.0, Bx = 0.0, Cx = 0.0, Dx = 0.0;\n\tdouble Ay = 0.0, By = 0.0, Cy = 0.0, Dy = 0.0;\n\tdouble Az = 0.0, Bz = 0.0, Cz = 0.0, Dz = 0.0;\n\t\n\tEigen::Vector3d cp[4];\n\tfor (size_t i = 0; i < points.size(); i += 4)\n\t{\n\t\tfor (size_t j = 0; j < 4; ++j)\n\t\t{\n\t\t\tcp[j] = points[i + j];\n\t\t}\n\n\t\tAx = cp[3].x() - 3.0 * cp[2].x() + 3.0 * cp[1].x() - cp[0].x();\n\t\tAy = cp[3].y() - 3.0 * cp[2].y() + 3.0 * cp[1].y() - cp[0].y();\n\t\tAz = cp[3].z() - 3.0 * cp[2].z() + 3.0 * cp[1].z() - cp[0].z();\n\n\t\tBx = 3.0 * cp[2].x() - 6.0 * cp[1].x() + 3.0 * cp[0].x();\n\t\tBy = 3.0 * cp[2].y() - 6.0 * cp[1].y() + 3.0 * cp[0].y();\n\t\tBz = 3.0 * cp[2].z() - 6.0 * cp[1].z() + 3.0 * cp[0].z();\n\n\t\tCx = 3.0 * (cp[1].x() - cp[0].x());\n\t\tCy = 3.0 * (cp[1].y() - cp[0].y());\n\t\tCz = 3.0 * (cp[1].z() - cp[0].z());\n\n\t\tDx = cp[0].x();\n\t\tDy = cp[0].y();\n\t\tDz = cp[0].z();\n\n\t\tcoeff.push_back(Ax);\n\t\tcoeff.push_back(Bx);\n\t\tcoeff.push_back(Cx);\n\t\tcoeff.push_back(Dx);\n\n\t\tcoeff.push_back(Ay);\n\t\tcoeff.push_back(By);\n\t\tcoeff.push_back(Cy);\n\t\tcoeff.push_back(Dy);\n\n\t\tif (is3D)\n\t\t{\n\t\t\tcoeff.push_back(Az);\n\t\t\tcoeff.push_back(Bz);\n\t\t\tcoeff.push_back(Cz);\n\t\t\tcoeff.push_back(Dz);\n\t\t}\n\t}\n\treturn coeff;\n}\n\n", "meta": {"hexsha": "d66dcf1f7613bcac4b3dc04b3b50f06c0834ca32", "size": 1451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "splines/splines.cpp", "max_stars_repo_name": "hpmachining/splines", "max_stars_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-22T15:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T21:31:33.000Z", "max_issues_repo_path": "splines/splines.cpp", "max_issues_repo_name": "hpmachining/splines", "max_issues_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "splines/splines.cpp", "max_forks_repo_name": "hpmachining/splines", "max_forks_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7868852459, "max_line_length": 106, "alphanum_fraction": 0.4996554101, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.659986894770474}}
{"text": "// Boost.Geometry\r\n// QuickBook Example\r\n\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\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//[densify\r\n//` Shows how to densify a polygon\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\r\n    typedef boost::geometry::model::polygon<point_type> polygon_type;\r\n\r\n    polygon_type poly;\r\n    boost::geometry::read_wkt(\r\n        \"POLYGON((0 0,0 10,10 10,10 0,0 0),(1 1,4 1,4 4,1 4,1 1))\", poly);\r\n\r\n    polygon_type res;\r\n\r\n    boost::geometry::densify(poly, res, 6.0);\r\n\r\n    std::cout << \"densified: \" << boost::geometry::wkt(res) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[densify_output\r\n/*`\r\nOutput:\r\n[pre\r\ndensified: POLYGON((0 0,0 5,0 10,5 10,10 10,10 5,10 0,5 0,0 0),(1 1,4 1,4 4,1 4,1 1))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "3734cbc10ee97ddd2fd9100f50968fab102e1510", "size": 1177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/densify.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/geometry/doc/src/examples/algorithms/densify.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/geometry/doc/src/examples/algorithms/densify.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": 24.5208333333, "max_line_length": 86, "alphanum_fraction": 0.6516567545, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6599084947538582}}
{"text": "/*\nA class to represent a prime field \n*/\n\n\n#ifndef PRIME_FIELD\n#define PRIME_FIELD\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <boost/bimap.hpp>\n\nusing namespace std;\n\n\n\n//! for debugging purpose only\n//! print the boost map of the cyclic group structure\ntemplate< class MapType >\nvoid print_map(const MapType & map,\n               const std::string & separator,\n               std::ostream & os )\n{\n    typedef typename MapType::const_iterator const_iterator;\n\n    for( const_iterator i = map.begin(), iend = map.end(); i != iend; ++i )\n    {\n        os << i->first << separator << i->second << std::endl;\n    }\n}\n\n\n\n// prime field element (PFE)\n// class template el_t should be interger type\ntemplate<class el_t = int> class PFE:\n\tboost::field_operators< PFE<el_t>,\n\tboost::equality_comparable< PFE<el_t>\n\t> >\n{\npublic: \n\tel_t element;\n\tstatic el_t prime;\n\n\ttypedef boost::bimap< el_t, el_t> bim; \n\t//! maps exponents to elements \n\tstatic bim exp_el;\n\t\n\t//!Constructs a prime f\n\tPFE(el_t el): element(el % prime) {};\n\tPFE(){element = 0;};\n\n\t\n\n\n\n\tstatic void set_prime(const el_t& a){prime = a;}\n\n\t//! for initializying the map exponent to element; \n\t//! takes as parameter a primitive element of GF(prime)\n\t\n\tstatic void initialize_exp_el(el_t priel){\n\t\t\n\t\tel_t el = 1;\n\t\tfor(unsigned i = 0; i < prime-1; ++i){\n\t\t\t// insert (exponent, corresponding element)\n\t\t\t\n\t\t\texp_el.insert(typename bim::value_type(i,el ));\n\t\t\tel = (el*priel) % prime;\n\t\t//cout << i << \"  \" <<  ((int) pow((double) priel,(int) i)) % prime << endl;\n\t\t}\n\t\t\n\t}\n\t\n\tbool isempty() const {return (element==prime);}\n\tvoid setempty() {element = prime;};\n\n\n\n\tPFE& operator += (const PFE& x){\n\t\telement = (element+x.element) % prime;\n\t\treturn *this;\n\t}\n\t\n\tPFE& operator -= (const PFE& x){\n\t\telement = (element-x.element) % prime;\n\t\tif(element < 0) element += prime;\n\t\treturn *this;\n\t}\n\n\tPFE& operator *= (const PFE& x){\n\t\t\n\t\telement = element*x.element % prime;\n\t\treturn *this;\n\t}\n\n\n\t\n\tPFE& operator /= (const PFE& x){\n\t\t//print_map(exp_el.left , \" \" , cout);\n\t\tel_t ea = exp_el.right.at(element);\t\n\t\tel_t eb = exp_el.right.at(x.element);\n\t\tel_t eres = (prime - 1 - eb + ea) % (prime-1);\n\t\telement = exp_el.left.at(eres);\n\t\treturn *this;\n\t}\n\n\t//operator const el_t (){\n\t//\treturn element;\n\t//}\n\t//operator el_t (){return element;}\n\toperator int (){return (int) element;};\n\n\n\tPFE inverse() const {\n\t\treturn pow(*this, -1);\n\t}\n\n\tbool operator ==(const PFE& x) const {\n\t\treturn (x.element == element);\n\t}\n\tbool operator < (const PFE& x) const {\n\t\treturn (element < x.element);\t\n\t}\n\t\n\tbool iszero() const { return (element == 0);  };\n\t//! get the multiplication order of the element\n\tunsigned order() const {\n\t\t// additive zero has no order\n\t\tif(element == 0){ return -1;}\n\t\tel_t tmp = element;\n\t\tunsigned ord = 1;\n\t\twhile(!(tmp == 1)){\n\t\t\tord++;\n\t\t\ttmp = (tmp * element) % prime;\n\t\t\t//cout << tmp << endl;\n\t\t}\n\t\treturn ord;\n\t}\n};\t\n\n template<class el_t>\n    ostream &operator<<(ostream &stream, PFE<el_t> x)\n    {\n      stream << x.element;\n      return stream; // must return stream\n    };\n\n\n template<class el_t>\n    PFE<el_t> pow(PFE<el_t> a, int exp){\n\t\tif( a.iszero() ) return a;\n\t\tif( exp == 0 ) return PFE<el_t>(1);\n\t\tel_t ea = a.exp_el.right.at(a.element);\t\n\t\tint nexp = exp*ea;\n\t\twhile( nexp < 0) {\n\t\t\t\n\t\t\tnexp += a.prime-1;\n\t\t}\n\t\tnexp = nexp % (a.prime-1) ; \n\t\treturn PFE<el_t>( a.exp_el.left.at(nexp ) );\n\t};\t\n\n#endif\n", "meta": {"hexsha": "cda4e7acdb37b12f8abb20ea3b50be5c213d18f0", "size": 3427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/PFE.hpp", "max_stars_repo_name": "zhaofeng-shu33/dna_data_storage", "max_stars_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/PFE.hpp", "max_issues_repo_name": "zhaofeng-shu33/dna_data_storage", "max_issues_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/PFE.hpp", "max_forks_repo_name": "zhaofeng-shu33/dna_data_storage", "max_forks_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6445783133, "max_line_length": 78, "alphanum_fraction": 0.6139480595, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6598735871224225}}
{"text": "// docs : https://boostjp.github.io/tips/multiprec-float.html\n// -I /usr/local/include/\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\nnamespace mp = boost::multiprecision;\n\nusing Bint = mp::cpp_int;\nusing Real = mp::number<mp::cpp_dec_float<30>>;\n", "meta": {"hexsha": "fc3e5720b35aaf71f8d80ab4ce54b62543564960", "size": 296, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp_src/other/Bigdecimal.hpp", "max_stars_repo_name": "satashun/algorithm", "max_stars_repo_head_hexsha": "72f6a4eb7de364319adf668c849c3170594a5a32", "max_stars_repo_licenses": ["MIT"], "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/other/Bigdecimal.hpp", "max_issues_repo_name": "satashun/algorithm", "max_issues_repo_head_hexsha": "72f6a4eb7de364319adf668c849c3170594a5a32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T16:11:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T23:26:03.000Z", "max_forks_repo_path": "cpp_src/other/Bigdecimal.hpp", "max_forks_repo_name": "satashun/algorithm", "max_forks_repo_head_hexsha": "ac844a9d3bff9dfa2f755fe92a28e1972cd7bbf4", "max_forks_repo_licenses": ["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.6, "max_line_length": 61, "alphanum_fraction": 0.75, "num_tokens": 79, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6598540094583669}}
{"text": "#include \"pauli_product.hpp\"\n#include <armadillo>\n#include <cmath>\n#include <stdlib.h>\n\n\nusing namespace std;\nusing namespace arma;\n\n// Applies a Pauli operator i^{xz} X^xZ^z to the k'th qubit to the state psi.\n// This algorithm takes at most 2^n complex number multiplications.\nvoid apply_pauli_fast(int k, bool x, bool z, cx_dvec &psi)\n{\n  int d;\n  d = psi.size();\n  if (pow(2,k) >= d)\n    {\n      throw \"Qubit index out of range.\";\n    }\n  if (z)\n    {\n      if (x)\n\t{\n\t  for (int i=0; i<d; i++)\n\t    {\n\t      if ((i & ( 1 << k )) >> k == 0)\n\t\t{\n\t\t  cx_double temp1, temp2;\n\t\t  temp1 = psi(i) * cx_double(0.0, 1.0);\n\t\t  temp2 = psi((1<<k)|i) * cx_double(0.0, -1.0);\n\t\t  psi(i) = temp2;\n\t\t  psi((1<<k)|i) = temp1;\n\t\t}\n\t    }\n\t}\n      else\n\t{\n\t  for (int i=0; i<d; i++)\n\t    {\n\t      if ((i & ( 1 << k )) >> k == 1)\n\t\t{\n\t\t  psi(i) *= -1.0;\n\t\t}\n\t    }\n\t}\n    }\n  else\n    {\n      if (x)\n\t{\n\t  for (int i=0; i<d; i++)\n\t    {\n\t      if ((i & ( 1 << k )) >> k == 0)\n\t\t{\n\t\t  cx_double temp1, temp2;\n\t\t  temp1 = psi(i);\n\t\t  temp2 = psi((1<<k)|i);\n\t\t  psi(i) = temp2;\n\t\t  psi((1<<k)|i) = temp1;\n\t\t}\n\t    }\n\t}\n    }\n\n}\n\n// Applies a Pauli operator i^{xz} X^xZ^z to the k'th qubit to the state psi.\n// This algorithm takes O(4^n)-time, quadratically worse than the apply_pauli_fast.\n// This function is primarily used as a bookkeeping device, instead of performance.\nvoid apply_pauli_slow(int k, bool x, bool z, cx_dvec &psi)\n{\n  int d, d_1, d_2;\n  cx_mat PI(2, 2, fill::zeros), PX(2, 2, fill::zeros), PY(2, 2, fill::zeros), PZ(2, 2, fill::zeros);\n  cx_mat p;\n\n  PI(0, 0) = cx_double(1.0, 0.0); PI(1, 1) = cx_double(1.0, 0.0);\n  PX(0, 1) = cx_double(1.0, 0.0); PI(1, 0) = cx_double(1.0, 0.0);\n  PY(0, 1) = cx_double(0.0, -1.0); PY(1, 0) = cx_double(0.0, 1.0);\n  PZ(0, 0) = cx_double(1.0, 0.0); PZ(1, 1) = cx_double(-1.0, 0.0);\n  \n  d = psi.size();\n  d_1 = pow(2, k);\n  d_2 = d / 2 / d_1;\n\n  if (x)\n    {\n      if (z)\n\t{\n\t  p = PY;\n\t}\n      else\n\t{\n\t  p = PX;\n\t}\n       \n    }\n  else\n    {\n      if (z)\n\t{\n\t  p = PZ;\n\t}\n      else\n\t{\n\t  p = PI;\n\t}\n    }\n  \n\n  cx_mat I1(d_1, d_1,fill::eye), I2(d_2, d_2, fill::eye);\n\n  cx_mat Pauli;\n  Pauli = kron(kron(I2, p), I1);\n  psi = Pauli * psi;\n      \n}\n\n// Apply exp(iP\u03b8) to psi, where P = i^{x\u00b7z}(\u2a02_k X_k^(x_k)) (\u2a02_k Z_k^(z_k))\nvoid apply_ppr(unsigned int x, unsigned int z, double theta, cx_dvec &psi)\n{\n  int d;\n  d = psi.size();\n  cx_double c, s;\n  c = cos(theta);\n  s = sin(theta);\n  //  cx_double csc;\n  //  csc = 1.0 / cos(theta);\n  bool not_changed[2048];\n  fill_n(not_changed, 2048, true);\n\n  for (int y=0; y<d; y++)\n    {\n      if (not_changed[y])\n\t{\n\t  \n\t    unsigned int xz = __builtin_popcount(x&z);\n\t    unsigned int yz = __builtin_popcount(y&z);\n\t    \n\t    cx_double phase1, phase2;\n\n\t    switch((1 + xz + 2*(yz+xz))%4)\n\t      {\n\t      case 0:\n\t\tphase1 = cx_double(1.0, 0.0);\n\t\tbreak;\n\t      case 1:\n\t\tphase1 = cx_double(0.0, 1.0);\n\t\tbreak;\n\t      case 2:\n\t\tphase1 = cx_double(-1.0, 0.0);\n\t\tbreak;\n\t      case 3:\n\t\tphase1 = cx_double(0.0, -1.0);\n\t\tbreak;\n\t      }\n\t    \n\t    switch((1 + xz + 2 * yz)%4)\n\t      {\n\t      case 0:\n\t\tphase2 = cx_double(1.0, 0.0);\n\t\tbreak;\n\t      case 1:\n\t\tphase2 = cx_double(0.0, 1.0);\n\t\tbreak;\n\t      case 2:\n\t\tphase2 = cx_double(-1.0, 0.0);\n\t\tbreak;\n\t      case 3:\n\t\tphase2 = cx_double(0.0, -1.0);\n\t\tbreak;\n\t      }\n\t    cx_double temp1, temp2;\n\t    temp1 = psi(y) * c + psi(y^x) * s * phase1;\n\t    temp2 = psi(y^x) * c + psi(y) * s * phase2;\n\t    psi(y) = temp1;\n\t    psi(y^x) = temp2;\n\n\t    //psi(y) *= c; psi(y) += s * phase1 * psi(y^x);\n\t    //psi(y^x) += s * phase2 * psi(y);\n\t    //psi(y^x) *= csc;\n\n\t    not_changed[y] = false; not_changed[y^x] = false;\n\t}\n      \n    }\n}\n\nvoid apply_ppr_slow(unsigned int x, unsigned int z, double theta, cx_dvec &psi)\n{\n    int d;\n    d = psi.size();\n    unsigned int bits, n_temp = (d < 0) ? -d : d;\n    for(bits = 0; n_temp != 0; ++bits) n_temp >>= 1;\n    unsigned int n_q = bits - 1;\n    \n    cx_double c, s;\n    c = cos(theta);\n    s = sin(theta);\n\n    cx_dmat PX(2,2, fill::zeros), PY(2,2, fill::zeros), PZ(2,2, fill::zeros), PI(2,2, fill::zeros), P, PString(1,1, fill::ones);\n    PX(0, 1) = 1.0; PX(1, 0) = 1.0;\n    PZ(0, 0) = 1.0; PZ(1, 1) = -1.0;\n    PY(1, 0) = cx_double(0.0, 1.0); PY(0, 1) = cx_double(0.0, -1.0);\n    PI(0, 0) = 1.0; PI(1, 1) = 1.0;\n\t\t   \n    for (int i=0; i<n_q; i++)\n      {\n\t\n\tif (x & (1<< i))\n\t  {\n\t    if (z & (1<< i))\n\t\tP = PY;  \n\t    else\n\t\tP = PX;\n\t  }\n\telse\n\t  {\n\t    if (z & (1<< i))\n\t\tP = PZ;\n\t    else\n\t\tP = PI;\n\t  }\n\tPString = kron(P, PString);\n      }\n\n    psi = c * psi + PString * psi * s * cx_double(0.0, 1.0);\n\n}\n\n// Measure Pauli Product operator (fast)\ndouble measure_pp(unsigned int x, unsigned int z, cx_dvec &psi)\n{\n  int d;\n  d = psi.size();\n  unsigned int bits, n_temp = (d < 0) ? -d : d;\n  for(bits = 0; n_temp != 0; ++bits) n_temp >>= 1;\n  unsigned int n_q = bits - 1;\n\n  cx_double mysum = 0.0;\n  for (int y=0; y<d; y++)\n    {\n      unsigned int xz = __builtin_popcount(x&z);\n      unsigned int yz = __builtin_popcount(y&z);\n      cx_double phase;\n      switch((xz + 2*yz)%4)\n\t{\n\tcase 0:\n\t  phase = cx_double(1.0, 0.0);\n\t  break;\n\tcase 1:\n\t  phase = cx_double(0.0, 1.0);\n\t  break;\n\tcase 2:\n\t  phase = cx_double(-1.0, 0.0);\n\t  break;\n\tcase 3:\n\t  phase = cx_double(0.0, -1.0);\n\t  break;\n\t}\n      mysum += psi(y) * conj(psi(y^x)) * phase;\n    }\n  return real(mysum);\n}\n\n\n// Meausre Pauli Product operator (slow)\ndouble measure_pp_slow(unsigned int x, unsigned int z, cx_dvec &psi)\n{\n  int d;\n  d = psi.size();\n  unsigned int bits, n_temp = (d < 0) ? -d : d;\n  for(bits = 0; n_temp != 0; ++bits) n_temp >>= 1;\n  unsigned int n_q = bits - 1;\n\n  cx_dmat PX(2,2, fill::zeros), PY(2,2, fill::zeros), PZ(2,2, fill::zeros), PI(2,2, fill::zeros), P, PString(1,1, fill::ones);\n  PX(0, 1) = 1.0; PX(1, 0) = 1.0;\n  PZ(0, 0) = 1.0; PZ(1, 1) = -1.0;\n  PY(1, 0) = cx_double(0.0, 1.0); PY(0, 1) = cx_double(0.0, -1.0);\n  PI(0, 0) = 1.0; PI(1, 1) = 1.0;\n  \n  for (int i=0; i<n_q; i++)\n    {\n      \n      if (x & (1<< i))\n\t{\n\t  if (z & (1<< i))\n\t    P = PY;  \n\t  else\n\t    P = PX;\n\t}\n      else\n\t{\n\t  if (z & (1<< i))\n\t    P = PZ;\n\t  else\n\t    P = PI;\n\t}\n      PString = kron(P, PString);\n    }\n  return real(cdot(psi, PString * psi));\n}\n", "meta": {"hexsha": "19e87421b113e83bfba93f2760341379e4bd7c4e", "size": 6194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/pauli_product.cpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/pauli_product.cpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/pauli_product.cpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5099337748, "max_line_length": 128, "alphanum_fraction": 0.5011301259, "num_tokens": 2573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6597938141525179}}
{"text": "#define _USE_MATH_DEFINES\n#include <libtiff/tiffio.h>\n\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <math.h>\n\n#include <filesystem>\nnamespace fs = std::filesystem;\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n\nstruct Point {\n\tuint32 x;\n\tuint32 y;\n};\n\nstruct ellipseABCDEF {\n\tdouble A;\n\tdouble B;\n\tdouble C;\n\tdouble D;\n\tdouble E;\n\tdouble F;\n};\n\nstruct ellipseABCDEF fitEllipse(struct Point p1, struct Point p2, struct Point p3, struct Point p4, struct Point p5) {\n\tMatrix<double, 5, 6> mat56(5, 6);\n\tmat56 << \n\t\t(double)p1.x * (double)p1.x, (double)p1.x * -(double)p1.y, (double)p1.y * (double)p1.y, (double)p1.x, -(double)p1.y, 1,\n\t\t(double)p2.x * (double)p2.x, (double)p2.x * -(double)p2.y, (double)p2.y * (double)p2.y, (double)p2.x, -(double)p2.y, 1,\n\t\t(double)p3.x * (double)p3.x, (double)p3.x * -(double)p3.y, (double)p3.y * (double)p3.y, (double)p3.x, -(double)p3.y, 1,\n\t\t(double)p4.x * (double)p4.x, (double)p4.x * -(double)p4.y, (double)p4.y * (double)p4.y, (double)p4.x, -(double)p4.y, 1,\n\t\t(double)p5.x * (double)p5.x, (double)p5.x * -(double)p5.y, (double)p5.y * (double)p5.y, (double)p5.x, -(double)p5.y, 1;\n\t\n\tCompleteOrthogonalDecomposition<Matrix<double, Dynamic, Dynamic> > cod;\n\tcod.compute(mat56);\n\n\t// Find URV^T\n\tMatrixXd V = cod.matrixZ().transpose();\n\tMatrixXd Null_space = V.block(0, cod.rank(), V.rows(), V.cols() - cod.rank());\n\tMatrixXd P = cod.colsPermutation();\n\tNull_space = P * Null_space; // Unpermute the columns\n\n\n\treturn {\n\t\tNull_space(0) / Null_space(5),\n\t\tNull_space(1) / Null_space(5),\n\t\tNull_space(2) / Null_space(5),\n\t\tNull_space(3) / Null_space(5),\n\t\tNull_space(4) / Null_space(5),\n\t\t1\n\t};\n}\n\n\nstatic uint16 finalAverage;\nstatic std::ofstream outStream(\"out.csv\");\n\ntypedef unsigned long long uint64;\n\n\n\nstruct followReturn {\n\tbool success;\n\tstruct Point point;\n};\n\nbool validateEdge(bool* considered, struct Point point, uint32 width, uint32 height) {\n\tstruct Point nearby[4] = {\n\t\t{point.x + 0, point.y - 1},\n\t\t{point.x - 1, point.y + 0},\n\t\t{point.x + 1, point.y + 0},\n\t\t{point.x + 0, point.y + 1}\n\t};\n\n\tfor (uint32 i = 0; i < 4; i++) {\n\t\tstruct Point tested = nearby[i];\n\n\t\tif (tested.x != 0xFFFFFFFF && tested.y != 0xFFFFFFFF && tested.x != width && tested.y != height) {\n\t\t\tuint32 index = tested.y * width + tested.x;\n\n\t\t\tif (!considered[index]) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nstruct EllipseParams {\n\tdouble fCenterX, fCenterY;\n\tdouble fLongLength, fShortLength;\n\tdouble fAngle;\n};\n\nEllipseParams toEllipseParams(ellipseABCDEF a) {\n\n\tEllipseParams eOutParams;\n\n\teOutParams.fCenterX = ((2 * a.C * a.D) - (a.B * a.E)) / ((a.B * a.B) - (4 * a.A * a.C));\n\teOutParams.fCenterY = ((2 * a.A * a.E) - (a.B * a.D)) / ((a.B * a.B) - (4 * a.A * a.C));\n\n\teOutParams.fLongLength = -sqrt(2 * (a.A * pow(a.E, 2) + a.C * pow(a.D, 2) - a.B * a.D * a.E + (pow(a.B, 2) - 4 * a.A * a.C) * a.F) * ((a.A + a.C) + sqrt(pow((a.A - a.C), 2) + pow(a.B, 2)))) /\n\t\t\t\t\t\t\t ((a.B * a.B) - (4 * a.A * a.C));\n\n\teOutParams.fShortLength = -sqrt(2 * (a.A * pow(a.E, 2) + a.C * pow(a.D, 2) - a.B * a.D * a.E + (pow(a.B, 2) - 4 * a.A * a.C) * a.F) * ((a.A + a.C) - sqrt(pow((a.A - a.C), 2) + pow(a.B, 2)))) /\n\t\t\t\t\t\t\t ((a.B * a.B) - (4 * a.A * a.C));\n\n\tif (a.B != 0)\n\t\teOutParams.fAngle = atan((a.C - a.A - sqrt(pow((a.A - a.C), 2) + pow(a.B, 2))) / a.B);\n\telse if\n\t\t(a.A <= a.C) eOutParams.fAngle = 0;\n\telse\n\t\teOutParams.fAngle = M_PI / 2;\n\n\treturn eOutParams;\n}\n\ndouble rad2Deg(double rad) {\n\treturn (rad * 180) / M_PI;\n}\n\n//filename, ellipse_center_x, ellipse_center_y, ellipse_majoraxis, ellipse_minoraxis, ellipse_angle, elapsed_time\n\nvoid saveEllipse(bool empty, EllipseParams params, float elapsedTime, char* fileName){\n\t\n\tif (empty) {\n\n\t\toutStream << fileName << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << (int)(elapsedTime * 1000) << std::endl;\n\t\treturn;\n\t}\n\n\toutStream << fileName << \",\";\n\toutStream << params.fCenterX << \",\";\n\toutStream << -params.fCenterY << \",\";\n\toutStream << params.fLongLength << \",\";\n\toutStream << params.fShortLength << \",\";\n\toutStream << fmod(180 - rad2Deg(params.fAngle), 360) << \",\";\n\toutStream << (int)(elapsedTime * 1000) << std::endl;\n\n}\n\n\ndouble ratePoint(struct Point point, struct EllipseParams ellipse) {\n\tdouble xi = (double)point.x;\n\tdouble yi = (double)point.y;\n\n\txi = xi - ellipse.fCenterX;\n\tyi = yi + ellipse.fCenterY;\n\n\tdouble x = xi * cos(ellipse.fAngle) + yi * sin(ellipse.fAngle);\n\tdouble y = xi * -sin(ellipse.fAngle) + yi * cos(ellipse.fAngle);\n\n\tdouble angle = atan(y / x);\n\n\tdouble distanceFromCenter = hypot(x, y);\n\n\tdouble distanceFromCenterToEdge = ellipse.fLongLength * ellipse.fShortLength / (sqrt(pow(ellipse.fShortLength * cos(angle), 2) + pow(ellipse.fLongLength * sin(angle), 2)));\n\n\tdouble finalDistance = abs(distanceFromCenter - distanceFromCenterToEdge);\n\n\t//some gaussian trickery right here\n\tdouble rating = exp(-(finalDistance * finalDistance) / 8);\n\treturn rating;\n}\n\n\nvoid ParseEllipse(std::string path) { \n\tTIFF* tif = TIFFOpen(path.c_str(), \"r\");\n\n\tif (tif == nullptr) {\n\t\tstd::cout << path << \" is not a valid TIFF image!\" << std::endl << std::endl;\n\t\treturn;\n\t}\n\n\tuint32 width, height;\n\n\tTIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);           // uint32 width;\n\tTIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);        // uint32 height;\n\n\tstd::cout << std::endl << \"Image: \" << path << std::endl;\n\tprintf(\"Width: %d\\nHeight: %d\\n\", width, height);\n\n\tuint16* raster = (uint16*)_TIFFmalloc(width * height * sizeof(uint16));\n\n\tfor (uint32 row = 0; row < height; row++) {\n\t\tTIFFReadScanline(tif, raster + width * row, row, 0);\n\t}\n\n\t//Time Taken\n\tauto timeStart = std::chrono::system_clock::now();\n\n\tuint64 average = 0;\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\taverage += uint64(raster[i]);\n\t}\n\n\tfinalAverage = average / (uint64(width) * uint64(height)) * 1;\n\n\t/*uint32 maxLuminance = 0;\n\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\tif (raster[i] > maxLuminance) {\n\t\t\tmaxLuminance = raster[i];\n\t\t}\n\t}\n\n\tdouble fmaxLuminance = (double)maxLuminance;\n\n\tdouble average = 0;\n\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\taverage += (1 - pow(exp(-(pow((double)raster[i] / fmaxLuminance, 2) / 0.5)), 64)) * fmaxLuminance;\n\t}\n\n\taverage /= width * height;\n\n\n\tfinalAverage = (uint16)average;*/\n\n\tbool* considered = (bool*)malloc(width * height * sizeof(bool));\n\tbool* alreadyTaken = (bool*)calloc(width * height, sizeof(bool));\n\n\tfor (uint32 y = 0; y < height; y++) {\n\t\tfor (uint32 x = 0; x < width; x++) {\n\t\t\tconst uint32 index = y * width + x;\n\n\t\t\t//considered[index] = bool(raster[index] < fmaxLuminance * 0.45);\n\t\t\tconsidered[index] = bool(raster[index] < finalAverage);\n\t\t}\n\t}\n\n\n\tstd::vector<std::vector<struct Point>> sequences;\n\n\tstd::vector<struct Point> paths[2] = {\n\t\tstd::vector<struct Point>(),\n\t\tstd::vector<struct Point>()\n\t};\n\n\n\n\tfor (uint32 y = 0; y < height; y++) {\n\t\tfor (uint32 x = 0; x < width; x++) {\n\t\t\tuint32 indexInitial = y * width + x;\n\n\t\t\tif (alreadyTaken[indexInitial] || !considered[indexInitial]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!validateEdge(considered, { x, y }, width, height)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tuint32 newX = x, newY = y;\n\n\t\t\tstruct Point nearbyInitial[8] = {\n\t\t\t\t{newX - 1, newY - 1},\n\t\t\t\t{newX + 0, newY - 1},\n\t\t\t\t{newX + 1, newY - 1},\n\t\t\t\t{newX - 1, newY + 0},\n\t\t\t\t{newX + 1, newY + 0},\n\t\t\t\t{newX - 1, newY + 1},\n\t\t\t\t{newX + 0, newY + 1},\n\t\t\t\t{newX + 1, newY + 1}\n\t\t\t};\n\n\t\t\tuint32 part = 0;\n\t\t\tuint32 firstPointIndex = 0;\n\n\n\n\t\t\twhile (part < 2 && firstPointIndex < 8) {\n\t\t\t\tnewX = nearbyInitial[firstPointIndex].x;\n\t\t\t\tnewY = nearbyInitial[firstPointIndex].y;\n\t\t\t\tfirstPointIndex++;\n\n\t\t\t\tif (newX == 0xFFFFFFFF || newY == 0xFFFFFFFF || newX == width || newY == height) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!validateEdge(considered, { newX, newY }, width, height)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool endPath = false;\n\t\t\t\tdo {\n\t\t\t\t\tuint32 indexThis = newY * width + newX;\n\n\n\t\t\t\t\tstruct Point nearby[8] = {\n\t\t\t\t\t\t{newX - 1, newY - 1},\n\t\t\t\t\t\t{newX + 0, newY - 1},\n\t\t\t\t\t\t{newX + 1, newY - 1},\n\t\t\t\t\t\t{newX - 1, newY + 0},\n\t\t\t\t\t\t{newX + 1, newY + 0},\n\t\t\t\t\t\t{newX - 1, newY + 1},\n\t\t\t\t\t\t{newX + 0, newY + 1},\n\t\t\t\t\t\t{newX + 1, newY + 1}\n\t\t\t\t\t};\n\n\t\t\t\t\tendPath = true;\n\n\t\t\t\t\tfor (uint32 i = 0; i < 8; i++) {\n\t\t\t\t\t\tstruct Point tested = nearby[i];\n\n\t\t\t\t\t\tif (tested.x != 0xFFFFFFFF && tested.y != 0xFFFFFFFF && tested.x != width && tested.y != height) {\n\t\t\t\t\t\t\tif (!validateEdge(considered, tested, width, height)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tuint32 testedIndex = tested.y * width + tested.x;\n\n\t\t\t\t\t\t\tif (alreadyTaken[testedIndex] || !considered[testedIndex]) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\tpaths[part].push_back({ newX, newY });\n\n\n\t\t\t\t\t\t\tnewX = tested.x;\n\t\t\t\t\t\t\tnewY = tested.y;\n\n\t\t\t\t\t\t\tendPath = false;\n\n\t\t\t\t\t\t\talreadyTaken[testedIndex] = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t} while (!endPath);\n\n\t\t\t\tpart++;\n\t\t\t}\n\n\t\t\tuint32 sizePart1 = paths[0].size();\n\t\t\tuint32 sizePart2 = paths[1].size();\n\n\t\t\tif (sizePart1 + sizePart2 >= 10) {\n\t\t\t\tstd::vector<struct Point> finalPath = std::vector<struct Point>();\n\n\t\t\t\tfinalPath.reserve(sizePart1 + sizePart2);\n\n\t\t\t\tfor (int i = sizePart1 - 1; i >= 0; i--) {\n\t\t\t\t\tfinalPath.push_back(paths[0][i]);\n\n\t\t\t\t}\n\n\t\t\t\tint a = 0;\n\n\t\t\t\tfor (int i = 0; i < sizePart2; i++) {\n\t\t\t\t\tfinalPath.push_back(paths[1][i]);\n\t\t\t\t}\n\n\t\t\t\tpaths[0] = std::vector<struct Point>();\n\t\t\t\tpaths[1] = std::vector<struct Point>();\n\n\t\t\t\tsequences.push_back(finalPath);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpaths[0].clear();\n\t\t\t\tpaths[1].clear();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (sequences.size() == 0) {\n\n\t\tauto timeEnd = std::chrono::system_clock::now();\n\n\t\tstd::chrono::duration<float> elapsedTime = timeEnd - timeStart;\n\t\tstd::cout << \"No ellipse found!\" << std::endl;\n\n\t\tsaveEllipse(true, {}, elapsedTime.count(), (char*)fs::path(path).filename().string().c_str());\n\t\treturn;\n\t}\n\n\tuint32 maxLength = 0;\n\tuint32 longestIndex = 0;\n\tfor (uint32 i = 0; i < sequences.size(); i++) {\n\t\tif (sequences[i].size() > maxLength) {\n\t\t\tmaxLength = sequences[i].size();\n\t\t\tlongestIndex = i;\n\t\t}\n\t}\n\n\tstd::vector<struct Point> longest = sequences[longestIndex];\n\n\n\n\t//Sampling\n\tPoint pSamples[5];\n\tconst int nMaxSampleItterations = 4; //Linear addition\n\n\tstruct EllipseParams bestFit;\n\tdouble bestFitRating = 0;\n\n\t//Iterate through\n\tfor (int nCurrItteration = 0; nCurrItteration < nMaxSampleItterations; nCurrItteration++) {\n\n\t\t//Populate samples \n\t\tint nPointDistance = longest.size() / (5 + 2 * nCurrItteration);\n\n\t\tif (nPointDistance == 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (int i = 0; i < 5; i++) {\n\t\t\tpSamples[i] = longest[i * nPointDistance];\n\t\t}\n\n\n\t\tint nCurrOffset = 0;\n\t\t//Go through the path\n\n\t\twhile ((4 * nPointDistance + nCurrOffset) < longest.size()) {\n\n\t\t\tfor (int i = 0; i < 5; i++) {\n\t\t\t\tpSamples[i] = longest[i * nPointDistance + nCurrOffset];\n\t\t\t}\n\n\t\t\tEllipseParams eFitEllipse = toEllipseParams(fitEllipse(pSamples[0], pSamples[1], pSamples[2], pSamples[3], pSamples[4]));\n\t\t\t\n\n\n\t\t\tdouble rating = 0;\n\t\t\tfor (int i = 0; i < longest.size(); i++) {\n\t\t\t\trating += ratePoint(longest[i], eFitEllipse);\n\t\t\t}\n\n\t\t\tif (rating > bestFitRating) {\n\t\t\t\tbestFitRating = rating;\n\t\t\t\tbestFit = eFitEllipse;\n\t\t\t}\n\n\t\t\t//Update offset for next iteration\n\t\t\tnCurrOffset++;\n\t\t}\n\t}\n\n\tstd::cout << \"Best fit got rated: \" << bestFitRating << \" (out of \" << longest.size() << \")\" << std::endl;\n\n\tauto timeEnd = std::chrono::system_clock::now();\n\n\tstd::chrono::duration<float> elapsedTime = timeEnd - timeStart;\n\tstd::cout << \"Finding the best ellipse took: \" << elapsedTime.count() << \" s\" << std::endl;\n\n\tsaveEllipse(false, bestFit, elapsedTime.count(), (char*)fs::path(path).filename().string().c_str());\n\n\tTIFFClose(tif);\n\t//free mallocs\n\n\t_TIFFfree(raster);\n\tfree(considered);\n\tfree(alreadyTaken);\n}\n\nint main(int argc, char** argv) {\n\n\toutStream << \"filename,ellipse_center_x,ellipse_center_y,ellipse_majoraxis,ellipse_minoraxis,ellipse_angle,elapsed_time\" << std::endl; //write the header\n\n\tif (argc == 1) {\n\t\tstd::cout << \"No input directory provided! Exiting...\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::string path(argv[1]);\n\ttry {\n\t\tfor (const auto& entry : fs::recursive_directory_iterator(path))\n\t\t\tParseEllipse(entry.path().string());\n\t}\n\tcatch (std::exception e) {\n\t\tstd::cout << argv[1] << \" is not a valid folder!\" << std::endl;\n\t}\n\n\toutStream.close();\n\n\treturn 0;\n}", "meta": {"hexsha": "302f8f0c53a78e16c97a6b268a76b016bf0a271c", "size": 12273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EllipseParser/Main.cpp", "max_stars_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_stars_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "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": "EllipseParser/Main.cpp", "max_issues_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_issues_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "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": "EllipseParser/Main.cpp", "max_forks_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_forks_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "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.0469387755, "max_line_length": 193, "alphanum_fraction": 0.6072679866, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6597433190908656}}
{"text": "/* test_chi_squared.cpp\n *\n * Copyright Steven Watanabe 2011\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 * $Id: test_chi_squared.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::chi_squared_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME chi_squared\n#define BOOST_MATH_DISTRIBUTION boost::math::chi_squared\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME n\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "67839c348cfac3392b687d157da6c61ad865bdba", "size": 860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_chi_squared.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_chi_squared.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_chi_squared.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "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": 34.4, "max_line_length": 75, "alphanum_fraction": 0.8081395349, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6597337147354619}}
{"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_LOG2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing log2 capabilities\n\n    base two logarithm function.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = log2(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  log(x)/log(2);;\n    @endcode\n\n    - log2(x) return Nan for negative enties (peculiarly Mzero\n    for floating numbers).\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see log10, log, log1p, is_negative,  Mzero\n  **/\n  Value log2(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/log2.hpp>\n#include <boost/simd/function/simd/log2.hpp>\n\n#endif\n", "meta": {"hexsha": "0b48f3bdaedf4c199280117f601f3a7dc4746970", "size": 1187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/log2.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/function/log2.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/log2.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 21.1964285714, "max_line_length": 100, "alphanum_fraction": 0.5787700084, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6597337048847839}}
{"text": "#include \"function.h\"\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n\nvoid Function::IndefCoeff()\n{\n\tarma::mat::fixed<5, 5> A;\n\tdouble h = 0;\n\tstd::vector<double> coeff;\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tcoeff.push_back(f[i].first - x);\n\t}\n\tfor (int j = 0; j < 5; j++)\n\t{\n\t\tfor (int i = 0; i < 5; i++)\n\t\t{\n\t\t\tA(j, i) = pow(coeff[i], j);\n\t\t}\n\t}\n\tarma::vec B(5, arma::fill::zeros);\n\tB(1) = 1;\n\tarma::vec X = arma::solve(A, B);\n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tIndefResult += X(i) * f[i].second;\n\t}\n}\n\nvoid Function::FindDerivative()\n{\n\tdouble eps_1 = (e[0].first + e[1].first);\n\tdouble eps_2 = (e[0].first * (e[1].first + e[2].first) + e[1].first * e[2].first);\n\tdouble eps_3 = (e[0].first * e[2].first * (e[1].first + e[3].first) + e[1].first * e[3].first *\n\t\t(e[0].first + e[2].first));\n\tNewtonResult =  FindDivDiff(1) + FindDivDiff(2) * eps_1 + FindDivDiff(3) * eps_2 + FindDivDiff(4) * eps_3;\n\n}\n\ndouble Function::FindDivDiff(int IterationNum)\n{\n\tdouble temp = 1;\n\tdouble sum = 0;\n\tfor (int p = 0; p <= IterationNum; ++p)\n\t{\n\t\tfor (int i = 0; i <= IterationNum; ++i)\n\t\t{\n\t\t\tif (i != p)\n\t\t\t\ttemp *= 1 / (f[p].first - f[i].first);\n\t\t}\n\t\tsum += f[p].second * temp;\n\t\ttemp = 1;\n\t}\n\treturn sum;\n}\n\nFunction::Function(std::vector<std::pair<double, double>> f_, double x_)\n{\n\tf = f_;\n\tx = x_;\n\tstd::pair<double, double> temp;\n\tfor (auto it : f)\n\t{\n\t\ttemp.first = x - it.first;\n\t\ttemp.second = it.second;\n\t\te.push_back(temp);\n\t}\n\tIndefCoeff();\n\tFindDerivative();\n}\n\nvoid Function::Print()\n{\n\tstd::cout << \"Newton method result: \" << NewtonResult << std::endl;\n\tstd::cout << \"Indef coeff method result: \" << IndefResult << std::endl << std::endl;\n}\n\nFunction::~Function()\n{}\n", "meta": {"hexsha": "787c865dbbfe284b30a882db16a451cc53a7483d", "size": 1680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab2/src/function.cpp", "max_stars_repo_name": "KorovinVA/CompMath", "max_stars_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab2/src/function.cpp", "max_issues_repo_name": "KorovinVA/CompMath", "max_issues_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab2/src/function.cpp", "max_forks_repo_name": "KorovinVA/CompMath", "max_forks_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-24T19:39:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-24T19:39:05.000Z", "avg_line_length": 20.7407407407, "max_line_length": 107, "alphanum_fraction": 0.5720238095, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6597337045584045}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\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//[register_multi_polygon\r\n//` Show the use of the macro BOOST_GEOMETRY_REGISTER_MULTI_POLYGON\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <boost/geometry/multi/geometries/register/multi_polygon.hpp>\r\n\r\ntypedef boost::geometry::model::polygon\r\n    <\r\n        boost::tuple<float, float> \r\n    > polygon_type;\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_MULTI_POLYGON(std::vector<polygon_type>)\r\n\r\nint main()\r\n{\r\n    // Normal usage of std::\r\n    std::vector<polygon_type> polygons(2);\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\", polygons[0]);\r\n    boost::geometry::read_wkt(\"POLYGON((3 0,3 1,4 1,4 0,3 0))\", polygons[1]);\r\n    \r\n    // Usage of Boost.Geometry\r\n    std::cout << \"AREA: \"  << boost::geometry::area(polygons) << std::endl;\r\n    \r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[register_multi_polygon_output\r\n/*`\r\nOutput:\r\n[pre\r\nAREA: 2\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "86dbe53067bcfb309e1514076f15d6848a44b485", "size": 1380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/register/multi_polygon.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/doc/src/examples/geometries/register/multi_polygon.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/doc/src/examples/geometries/register/multi_polygon.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": 26.5384615385, "max_line_length": 80, "alphanum_fraction": 0.6869565217, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6596925076701287}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using namespace Eigen;\n\n    MatrixXd A = MatrixXd::Random(3,3);\n\n    Matrix<bool, Dynamic, Dynamic> B = A.array() < 0.5;\n\n    MatrixXd C;\n\n    C = B.cast<double>();\n\n    cout << \"Matrix A: \" << endl;\n    cout << A << endl;\n\n    cout << \"Bool Matrix B:\" << endl;\n    cout << B << endl;\n\n    cout << \"double Matrix C:\" << endl;\n    cout << C << endl;\n\n    cout << \"double Matrix A mul C\" << endl;\n    cout << A.array() * C.array() << endl;\n\n    return 0;\n}", "meta": {"hexsha": "750a0d78e0dfebd7f090241c4216c9f093dd6490", "size": 557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/test_bool_matrix.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": "ch6/test_bool_matrix.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": "ch6/test_bool_matrix.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": 17.9677419355, "max_line_length": 55, "alphanum_fraction": 0.5296229803, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6596925031301611}}
{"text": "// numbers_as_words.cpp : output any positive integer in American usage English\n// Version 1.01 (2020/09/12), MIT License, (c) Richard Spencer 2019\n\n// Optionally compile with BOOST_CPP_INT defined to use arbitrary precision\n// instead of long long as the Integer type, also requires -std=c++17 or later\n\n// Usage: Filename as single argument to test output from \"one\" to \"one million\"\n//        Run without arguments to enter interactive mode\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#ifdef BOOST_CPP_INT\n#include <boost/multiprecision/cpp_int.hpp>\nusing Integer = boost::multiprecision::cpp_int;\n#else\nusing Integer = unsigned long long int;\n#endif\n\nusing std::cin;\nusing std::cout;\nusing std::ofstream;\nusing std::string;\nusing std::vector;\n\nstring number_triplet(unsigned n) {\n    string s{};\n    if (n / 100) {\n        s += number_triplet(n / 100) + \" hundred\" + (n % 100 ? \" \" : \"\");\n    }\n    n %= 100;\n    if (n < 20) {\n        switch (n) {\n            case 1: s += \"one\"; break;\n            case 2: s += \"two\"; break;\n            case 3: s += \"three\"; break;\n            case 4: s += \"four\"; break;\n            case 5: s += \"five\"; break;\n            case 6: s += \"six\"; break;\n            case 7: s += \"seven\"; break;\n            case 8: s += \"eight\"; break;\n            case 9: s += \"nine\"; break;\n            case 10: s += \"ten\"; break;\n            case 11: s += \"eleven\"; break;\n            case 12: s += \"twelve\"; break;\n            case 13: s += \"thirteen\"; break;\n            case 14: s += \"fourteen\"; break;\n            case 15: s += \"fifteen\"; break;\n            case 16: s += \"sixteen\"; break;\n            case 17: s += \"seventeen\"; break;\n            case 18: s += \"eighteen\"; break;\n            case 19: s += \"nineteen\"; break;\n        }\n    }\n    else {\n        switch (n / 10) {\n            case 2: s += \"twenty\"; break;\n            case 3: s += \"thirty\"; break;\n            case 4: s += \"forty\"; break;\n            case 5: s += \"fifty\"; break;\n            case 6: s += \"sixty\"; break;\n            case 7: s += \"seventy\"; break;\n            case 8: s += \"eighty\"; break;\n            case 9: s += \"ninety\"; break;\n        }\n        if (n % 10) {\n            s += '-' + number_triplet(n % 10);\n        }\n    }\n    return s;\n}\n\ntemplate<typename Number>\nvoid number_to_words(Number n, string& s, const unsigned triplet = 0) {\n    if (Number m = n / 1000; m) {\n        number_to_words(m, s, triplet + 1);\n    }\n    const vector triplets = { \"\", \"thousand\", \"million\", \"billion\", \"trillion\", \"quadrillion\", \"quintillion\", \"sextillion\", \"septillion\", \"octillion\", \"nonillion\", \"decillion\", \"undecillion\", \"duodecillion\", \"tredecillion\", \"quattuordecillion\", \"quindecillion\", \"sexdecillion\", \"octodecillion\", \"novemdecillion\", \"vigintillion\" };\n    if (unsigned t = static_cast<unsigned>(n % 1000); t) {\n        s += (s.empty() ? \"\" : \" \") + number_triplet(t) + (triplet ? \" \" : \"\") + triplets.at(triplet);\n    }\n}\n\nint main(const int argc, const char *argv[]) {\n    if (argc == 2) {\n        ofstream file{argv[1]};\n        for (Integer i = 1; i <= 1000000; ++i) {\n            string s;\n            number_to_words(i, s);\n            file << s << '\\n';\n        }\n        return 0;\n    }\n    Integer i{};\n    cout << \"Please enter a positive number (zero to quit): \";\n    cin >> i;\n    while (i) {\n        string s;\n        number_to_words(i, s);\n        cout << s << '\\n';\n        cout << \"Please enter another number: \";\n        cin >> i;\n    }\n}\n", "meta": {"hexsha": "6a498758e8863446c18a6b7f44a22b585acf8658", "size": 3500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "numbers-as-words/numbers_as_words.cpp", "max_stars_repo_name": "cpp-tutor/learnmoderncpp-articles", "max_stars_repo_head_hexsha": "a155e42ef36a16941f064244bd612e8145645188", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numbers-as-words/numbers_as_words.cpp", "max_issues_repo_name": "cpp-tutor/learnmoderncpp-articles", "max_issues_repo_head_hexsha": "a155e42ef36a16941f064244bd612e8145645188", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numbers-as-words/numbers_as_words.cpp", "max_forks_repo_name": "cpp-tutor/learnmoderncpp-articles", "max_forks_repo_head_hexsha": "a155e42ef36a16941f064244bd612e8145645188", "max_forks_repo_licenses": ["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.7102803738, "max_line_length": 330, "alphanum_fraction": 0.5271428571, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6596924985901932}}
{"text": "#pragma once\n#include <type_traits>\n#include <Eigen/Dense>\n\nnamespace ppl {\nnamespace math {\n\n/**\n * Estimates sample variance for n-dimensional data using\n * Welford's online algorithm\n */\nstruct WelfordVar\n{\n    WelfordVar(size_t n_params)\n        : m_{n_params, 2}\n        , mean_{m_.col(0)}\n        , m2n_{m_.col(1)}\n    { m_.setZero(); }\n\n    /*\n     * Update sample mean and sample variance with new sample x.\n     */\n    template <class MatType>\n    void update(const MatType& x)\n    {\n        ++n_;\n        auto delta = x - mean_;\n        mean_ += (1./static_cast<double>(n_)) * delta;\n        m2n_ += (delta.array() * (x - mean_).array()).matrix();\n    }\n\n    const auto& get_variance() const { return m2n_; }\n    size_t get_n_samples() const { return n_; }\n\n    /**\n     * Resets sample mean, sample variance, and number of samples to 0\n     * Equivalent to constructing a new object of this type.\n     */\n    void reset()\n    {\n        m_.setZero();\n        n_ = 0;\n    }\n\nprivate:\n    Eigen::MatrixXd m_; \n\n    using col_t = std::decay_t<decltype(m_.col(0))>;\n    col_t mean_;\n    col_t m2n_;\n\n    size_t n_ = 0;  // number of samples\n};\n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "098cf6a073a897919888b87ebf753dee2b3a853f", "size": 1190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/welford.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/welford.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/welford.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 20.8771929825, "max_line_length": 70, "alphanum_fraction": 0.5857142857, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6596161767707567}}
{"text": "/**\n * @brief       NPolynomialEval class\n * @file        NPolynomial_Eval.hpp\n * @author      Nuno Marques <nuno.marques@dronesolutions.io>\n * @copyright   Copyright (c) 2018, Swift Engineering Inc.\n * @license     Licensed under the MIT license. See LICENSE for details.\n */\n\n#pragma once\n\n#include <boost/array.hpp>\n#include <vector>\n#include <boost/math/tools/rational.hpp>\n\n/// \\brief NPolynomialEval class that implements a N-degree polynomial eval\ntemplate <class T, size_t n>\nclass NPolynomialEval {\n  public:\n    /// \\brief Gets the output from an input value and the poly indeterminates kept on the m_fit_curves set\n    T get_output_from_poly(const size_t &poly_index, const double &input) {\n        BOOST_ASSERT_MSG(poly_index <= (m_fit_curves.size() - 1), \"The chosen polynomial curve does not exist!\");\n        return boost::math::tools::evaluate_polynomial(m_fit_curves[poly_index], input);\n    }\n\n    /// \\brief Gets the output from an input value and input poly indeterminates\n    T get_output_from_poly(const boost::array<T, n> &poly, const double &input) {\n        return boost::math::tools::evaluate_polynomial(poly, input);\n    }\n\n    /// \\brief Loads a polynomial fit curve to be used\n    void load_poly_fit_curve(const boost::array<T, n> &poly) {\n        m_fit_curves.push_back(poly);\n    }\n\n  protected:\n    /// \\brief Array of polynomial fit curves\n    std::vector<boost::array<T, n> > m_fit_curves;\n};  // class NPolynomialEval\n", "meta": {"hexsha": "66cd55a77548ee8a1a60fbd5ac42e221de971baf", "size": 1453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/NPolynomial_Eval.hpp", "max_stars_repo_name": "SwiftEngineering/avionics_sim", "max_stars_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_stars_repo_licenses": ["MIT"], "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/NPolynomial_Eval.hpp", "max_issues_repo_name": "SwiftEngineering/avionics_sim", "max_issues_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_issues_repo_licenses": ["MIT"], "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/NPolynomial_Eval.hpp", "max_forks_repo_name": "SwiftEngineering/avionics_sim", "max_forks_repo_head_hexsha": "8fa3ef497137dd54966ff9de43cbcf2bfbf82d96", "max_forks_repo_licenses": ["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.2564102564, "max_line_length": 113, "alphanum_fraction": 0.7019958706, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6596161653729229}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace std;\nusing namespace boost::multiprecision;\nint main() {\n    cpp_int x, y, a, b, cnt = 0; cin >> x >> y >> a >> b;\n    if (y - x < b) {\n        cout << 0 << endl;\n        return 0;\n    }\n    while (x < b) {\n        if (x * a >= b) break;\n        else {\n            x *= a;\n            cnt++;\n        }\n    }\n    cout << ((y - 1) - x) / b + cnt << endl;\n    return 0;\n}", "meta": {"hexsha": "8678d92e883f76aebbaf732b0a3743ccd5d72026", "size": 504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc180/d/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/abc180/d/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/abc180/d/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 57, "alphanum_fraction": 0.4761904762, "num_tokens": 151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.659616164941633}}
{"text": "#include <Eigen/SPQRSupport>\n#include <igl/per_vertex_normals.h>\n#include <iostream>\n#include \"CommonFunctions.h\"\n#include \"MeshGeometry.h\"\n#include \"IntrinsicGeometry.h\"\n#include \"MeshConnectivity.h\"\n\nEigen::MatrixXd lowRankApprox(Eigen::MatrixXd A)\n{\n    Eigen::MatrixXd posHess = A;\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n    es.compute(posHess);\n    Eigen::VectorXd evals = es.eigenvalues();\n\n    for (int i = 0; i < evals.size(); i++)\n    {\n        if (evals(i) < 0)\n            evals(i) = 0;\n    }\n    Eigen::MatrixXd D = evals.asDiagonal();\n    Eigen::MatrixXd V = es.eigenvectors();\n    posHess = V * D * V.inverse();\n\n    return posHess;\n}\n\nEigen::MatrixXd nullspaceExtraction(const Eigen::SparseMatrix<double> A)\n{\n\tEigen::SPQR<Eigen::SparseMatrix<double>> solver_SPQR(A.transpose());\n\tint r = solver_SPQR.rank();\n\n\tEigen::MatrixXd N(A.cols(), A.cols() - r);\n\tfor (int i = 0; i < A.cols() - r; i++)\n\t{\n\t\tEigen::VectorXd ei(A.cols());\n\t\tei.setZero();\n\t\tei(i + r) = 1;\n\t\tN.col(i) = solver_SPQR.matrixQ() * ei;\n\t}\n\tstd::cout << \"rank of A = \" << r << std::endl;\n\treturn N;\n}\n\ndouble cotan(const Eigen::Vector3d v0, const Eigen::Vector3d v1, const Eigen::Vector3d v2)\n{\n    double e0 = (v2 - v1).norm();\n    double e1 = (v2 - v0).norm();\n    double e2 = (v0 - v1).norm();\n    double angle0 = acos((e1 * e1 + e2 * e2 - e0 * e0) / (2 * e1 * e2));\n    double cot = 1.0 / tan(angle0);\n\n    return cot;\n}\n\n\nvoid locatePotentialPureTensionFaces(const std::vector<Eigen::Matrix2d>& abars, const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, std::set<int>& potentialPureTensionFaces)\n{\n\tMeshConnectivity mesh(F);\n\tMeshGeometry curGeo(V, mesh);\n\tIntrinsicGeometry restGeo(mesh, abars);\n\tassert(abars.size() == F.rows());\n\tint nfaces = F.rows();\n\tint nverts = V.rows();\n\n\tEigen::VectorXd smallestEvals(nfaces);\n\n\tstd::vector<bool> isPureFaces(nfaces, false);\n\tstd::vector<bool> isPureVerts(nverts, false);\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tEigen::Matrix2d abar = abars[i];\n\t\tEigen::Matrix2d a = curGeo.Bs[i].transpose() * curGeo.Bs[i];\n\t\tEigen::Matrix2d diff = a - abar;\n\t\tEigen::GeneralizedSelfAdjointEigenSolver<Eigen::Matrix2d> solver(diff, abar);\n\n\t\tsmallestEvals(i) = std::min(solver.eigenvalues()[0], solver.eigenvalues()[1]);\n\t}\n\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (smallestEvals(i) >= 0)\n\t\t{\n\t\t\tisPureFaces[i] = true;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (isPureFaces[i])\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tisPureVerts[mesh.faceVertex(i, j)] = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t//// if a face is not pure tension, but all its vertices are on the other pure faces, we think it is pure tension\n\t//// this is used to fill the mixed state \"holes\" in the pure tension region\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (!isPureFaces[i])\n\t\t{\n\t\t\tbool isAllPureVerts = true;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\t\tif (isPureVerts[vid] == false)\n\t\t\t\t\tisAllPureVerts = false;\n\t\t\t}\n\t\t\tisPureFaces[i] = isAllPureVerts;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (isPureFaces[i])\n\t\t\tpotentialPureTensionFaces.insert(i);\n\t}\n\t// set this to empty means we never relax the integrability constriant.\n\t// potentialPureTensionFaces.clear();\n}\n\nvoid getPureTensionVertsEdges(const std::set<int>& potentialPureTensionFaces, const Eigen::MatrixXi& F, std::set<int>* pureTensionEdges, std::set<int>* pureTensionVerts)\n{\n\tMeshConnectivity mesh(F);\n\n\tstd::set<int> tmpPureTensionEdges, tmpPureTensionVerts;\n\t\n\tstd::set<int> mixedStateEdges;\n\t// locate the mixed edges: \n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tEigen::Vector2i faceFlags;\n\t\tfaceFlags << 0, 0;\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tint fid = mesh.edgeFace(i, j);\n\t\t\tif (potentialPureTensionFaces.find(fid) != potentialPureTensionFaces.end())\n\t\t\t{\n\t\t\t\tfaceFlags(j) = 1;\n\t\t\t}\n\t\t}\n\t\tif (faceFlags(0) + faceFlags(1) == 1)\n\t\t{\n\t\t\tif (mixedStateEdges.find(i) == mixedStateEdges.end())\n\t\t\t{\n\t\t\t\tmixedStateEdges.insert(i);\n\t\t\t}\n\t\t}\n\n\t\telse if (faceFlags(0) + faceFlags(1) == 2)\n\t\t{\n\t\t\tif (tmpPureTensionEdges.find(i) == tmpPureTensionEdges.end())\n\t\t\t{\n\t\t\t\ttmpPureTensionEdges.insert(i);\n\t\t\t}\n\t\t}\n\t}\n\t// mixedStateEdges.clear();\n\t// tmpPureTensionEdges.clear();\n\tstd::cout << mixedStateEdges.size() << \" edges between compressed and pure tension faces. \" << tmpPureTensionEdges.size() << \" edges are inside the pure tension region\" << std::endl;\n\n\tfor (auto& fid : potentialPureTensionFaces)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(fid, j);\n\t\t\tif (tmpPureTensionVerts.find(vid) == tmpPureTensionVerts.end())\n\t\t\t{\n\t\t\t\ttmpPureTensionVerts.insert(vid);\n\t\t\t}\n\t\t}\n\t}\n\t// tmpPureTensionVerts.clear();\n\tstd::cout << tmpPureTensionVerts.size() << \" vertices are inside the pure tension region (including the boundary)\" << std::endl;\n\n\tif (pureTensionEdges)\n\t{\n\t\t*pureTensionEdges = tmpPureTensionEdges;\n\t}\n\tif (pureTensionVerts)\n\t{\n\t\t*pureTensionVerts = tmpPureTensionVerts;\n\t}\n}\n\n\nvoid trivialOffset(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXd &offsettedV, double d)\n{\n\tEigen::MatrixXd VN;\n\tigl::per_vertex_normals(V, F, VN);\n\toffsettedV = V  + d * VN;\n}\n\nvoid rigidBodyAlignment(const Eigen::MatrixXd& tarPos, const MeshConnectivity& mesh, const Eigen::MatrixXd &pos, Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n\tint nverts = tarPos.rows();\n    int nfaces = mesh.nFaces();\n    Eigen::VectorXd massVec;\n    massVec.resize(nverts);\n    massVec.setZero();\n    \n    Eigen::VectorXd areaList;\n    igl::doublearea(tarPos, mesh.faces(), areaList);\n    areaList = areaList / 2;\n    \n    for(int i=0; i < nfaces; i++)\n    {\n        double faceArea = areaList(i);\n        for(int j=0; j<3; j++)\n        {\n            int vertIdx = mesh.faceVertex(i, j);\n            massVec(vertIdx) += faceArea / 3;\n        }\n    }\n    \n    massVec = massVec / 3;\n    massVec = massVec / massVec.maxCoeff();\n    \n    Eigen::MatrixXd W = Eigen::MatrixXd::Zero(nverts, nverts);\n    W.diagonal() = massVec;\n    \n    Eigen::Vector3d avePos, aveTarPos;\n    avePos.setZero();\n    aveTarPos.setZero();\n    \n    for(int i = 0; i < nverts; i++)\n    {\n        avePos += massVec(i) * pos.row(i);\n        aveTarPos += massVec(i) * tarPos.row(i);\n    }\n    \n    avePos = avePos / massVec.sum();\n    aveTarPos = aveTarPos / massVec.sum();\n    \n    Eigen::MatrixXd onesMat(nverts,1);\n    onesMat.setOnes();\n    \n    Eigen::MatrixXd shiftedPos = pos - onesMat * avePos.transpose();\n    Eigen::MatrixXd shiftedTarPos = tarPos - onesMat * aveTarPos.transpose();\n    \n    Eigen::MatrixXd S = shiftedPos.transpose() * W * shiftedTarPos;\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(3);\n    \n    \n    Eigen::BDCSVD<Eigen::MatrixXd> solver(S);\n    solver.compute(S, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::MatrixXd U = solver.matrixU();\n    Eigen::MatrixXd V = solver.matrixV();\n    \n    Eigen::MatrixXd middleMat(S.rows(), S.cols());\n    middleMat.setIdentity();\n    middleMat(S.rows()-1,S.cols()-1) = (V*U.transpose()).determinant();\n    \n    R = V * middleMat * U.transpose();\n    t = aveTarPos - R*avePos;\n}\n\nbool parse(bool& b, const Json::Value& json) {\n\tif (!json.isBool())\n\t\treturn false;\n\tb = json.asBool();\n\treturn true;\n}\nbool parse(int& n, const Json::Value& json) {\n\tif (!json.isIntegral())\n\t\treturn false;\n\tn = json.asInt();\n\treturn true;\n}\nbool parse(double& x, const Json::Value& json) {\n\tif (!json.isNumeric())\n\t\treturn false;\n\tx = json.asDouble();\n\treturn true;\n}\nbool parse(std::string& s, const Json::Value& json)\n{\n\tif (!json.isString())\n\t\treturn false;\n\ts = json.asString();\n\treturn true;\n}\n\nvoid generateWTFJson(std::string prefix)\n{\n\tstd::string matName = prefix + std::string(\"_material.dat\");\n\tstd::ifstream mfs(matName);\n\tif (!mfs)\n\t{\n\t\tstd::cout << \"Missing \" << matName << std::endl;\n\t\treturn;\n\t}\n\tdouble thickness, youngs, poisson, density, penaltyK, pressure, sphereR;\n\tEigen::Vector3d gravity, sphereCenter;\n\tbool isTFT;\n\tint framefreq, numInterp, bendingType;\n\tJson::Value json;\n\n\tmfs >> thickness;\n\tmfs >> youngs;\n\tmfs >> poisson;\n\tmfs >> density;\n\tmfs >> penaltyK;\n\tmfs >> gravity[0] >> gravity[1] >> gravity[2];\n\tmfs >> isTFT;\n\tmfs >> framefreq;\n\tmfs >> sphereCenter[0] >> sphereCenter[1] >> sphereCenter[2];\n\tmfs >> sphereR;\n\tmfs >> numInterp;\n\tmfs >> bendingType;\n\tmfs >> pressure;\n\n\tjson[\"poisson_ratio\"] = poisson;\n\tjson[\"thickness\"] = thickness;\n\tjson[\"youngs_modulus\"] = youngs;\n\n\tjson[\"nasoq_eps\"] = 1e-6;\n\tjson[\"quadpoints\"] = 3;\n\tjson[\"rest_flat\"] = true;\n\tjson[\"clamp\"] = true;\n\tjson[\"sff_type\"] = \"midedgeTan\";\n\n\tstd::string filePrefix = prefix;\n\tstd::replace(filePrefix.begin(), filePrefix.end(), '\\\\', '/'); // handle the backslash issue for windows\n\n\tint index = filePrefix.rfind(\"/\");\n\tstd::string modelName = filePrefix.substr(index + 1, filePrefix.length() - 1);\n\n\n\tjson[\"rest_mesh\"] = modelName + \".obj\";\n\tjson[\"base_mesh\"] = modelName + \"_simulated.obj\";\n\tjson[\"obs_mesh\"] = modelName + \"_obstacle.obj\";\n\n\tjson[\"clamped_DOFs\"] = modelName + \"_clamped_vertices.dat\";\n\n\tjson[\"dphi_path\"] = modelName + \"_dphi_simulated.txt\";\n\tjson[\"amp_path\"] = modelName + \"_amplitude_simulated.txt\";\n\tjson[\"phi_path\"] = modelName + \"_phi_simulated.txt\";\n\n\tstd::ofstream file((prefix + \"_WTF.json\").c_str());\n\tif (!file)\n\t{\n\t\tstd::cout << \"output path doesn't exist.\" << std::endl;\n\t\treturn;\n\t}\n\tJson::StyledStreamWriter writer;\n\twriter.write(file, json);\n\tfile.close();\n}\n\nvoid generateElasticJson(std::string prefix)\n{\n\tstd::string matName = prefix + std::string(\"_material.dat\");\n\tstd::ifstream mfs(matName);\n\tif (!mfs)\n\t{\n\t\tstd::cout << \"Missing \" << matName << std::endl;\n\t\treturn;\n\t}\n\tdouble thickness, youngs, poisson, density, penaltyK, pressure,sphereR;\n\tEigen::Vector3d gravity, sphereCenter;\n\tbool isTFT;\n\tint framefreq, numInterp, bendingType;\n\tJson::Value json;\n\n\tmfs >> thickness;\n\tmfs >> youngs;\n\tmfs >> poisson;\n\tmfs >> density;\n\tmfs >> penaltyK;\n\tmfs >> gravity[0] >> gravity[1] >> gravity[2];\n\tmfs >> isTFT;\n\tmfs >> framefreq;\n\tmfs >> sphereCenter[0] >> sphereCenter[1] >> sphereCenter[2];\n\tmfs >> sphereR;\n\tmfs >> numInterp;\n\tmfs >> bendingType;\n\tmfs >> pressure;\n\n\tjson[\"poisson_ratio\"] = poisson;\n\tjson[\"thickness\"] = thickness;\n\tjson[\"youngs_modulus\"] = youngs;\n\tjson[\"density\"] = density;\n\tjson[\"collision_penalty\"] = penaltyK;\n\tjson[\"perturb\"] = 0;\n\tjson[\"pressure\"] = pressure;\n\tjson[\"collision_eta\"] = 0.5 * thickness;\n\tjson[\"rest_flat\"] = true;\n\tjson[\"isNeoHookean\"] = false;\n\tjson[\"isTFT\"] = isTFT;\n\tjson[\"bending_type\"] = bendingType == 0 ? \"elastic\" : \"quadratic\";\n\tif (bendingType == 2)\n\t\tjson[\"bending_type\"] = \"None\";\n\n\tjson[\"sff_type\"] = \"midedgeTan\";\n\tjson[\"max_stepsize\"] = 1.0;\n\tjson[\"gravity\"].resize(3);\n\tfor (int i = 0; i < 3; i++)\n\t\tjson[\"gravity\"][i] = gravity(i);\n\n\tjson[\"frame_frequency\"] = framefreq;\n\tjson[\"num_interpolation\"] = numInterp;\n\n\tstd::string filePrefix = prefix;\n\tstd::replace(filePrefix.begin(), filePrefix.end(), '\\\\', '/'); // handle the backslash issue for windows\n\n\tint index = filePrefix.rfind(\"/\");\n\tstd::string modelName = filePrefix.substr(index + 1, filePrefix.length() - 1);\n\n\tjson[\"rest_mesh\"] = modelName + \".obj\";\n\tjson[\"init_mesh\"] = modelName + \"_guess.obj\";\n\tjson[\"cur_mesh\"] = modelName + \"_simulated.obj\";\n\tjson[\"obs_mesh\"] = modelName + \"_obstacle.obj\";\n\n\tjson[\"curedge_DOFs\"] = modelName + \"_edgedofs_simulated.txt\";\n\tjson[\"clamped_DOFs\"] = modelName + \"_clamped_vertices.dat\";\n\n\tstd::ofstream file((prefix + \"_Elastic.json\").c_str());\n\tif (!file)\n\t{\n\t\tstd::cout << \"output path doesn't exist.\" << std::endl;\n\t\treturn;\n\t}\n\tJson::StyledStreamWriter writer;\n\twriter.write(file, json);\n\tfile.close();\n}", "meta": {"hexsha": "d50a7dff910ada517521c00e73089709a00e49c7", "size": 11545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CommonFunctions.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CommonFunctions.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CommonFunctions.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["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.724537037, "max_line_length": 183, "alphanum_fraction": 0.6431355565, "num_tokens": 3487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6596013629080348}}
{"text": "// -*- mode: c++; fill-column: 80; indent-tabs-mode: nil; -*-\n#ifndef MXPFIT_JACOBI_SVD_HPP\n#define MXPFIT_JACOBI_SVD_HPP\n\n#include <cassert>\n#ifdef DEBUG\n#include <iomanip>\n#include <iostream>\n#endif /* DEBUG */\n\n#include <Eigen/Core>\n\nnamespace mxpfit\n{\nnamespace detail\n{\n//\n// Make Jacobi rotation matrix \\c J of the form\n//\n//  J = [ cs conj(sn)]\n//      [-sn conj(cs)]\n//\n// that diagonalize the 2x2 matirix\n//\n// B = [     a  c]\n//     [conj(c) b]\n//\n// as D = J.t() * B * J\n//\n// J.t() = [ conj(cs)    -conj(sn)] = J.inv()\n//         [      sn           cs ]\n//\n// J * [a11 a12] = [ cs*a11 + conj(sn)*a21   cs*a12 + conj(sn)*a22]\n//     [a21 a22]   [-sn*a11 + conj(cs)*a21  -sn*a12 + conj(cs)*a22]\n//\n// [a11 a12] * J = [     cs *a11 -      sn *a12        cs *a21 -      sn *a22]\n// [a21 a22]       [conj(sn)*a11 +E conj(cs)*a12  -conj(sn)*a21 + conj(cs)*a22]\n//\ntemplate <typename RealT, typename ScalarT>\nbool make_jacobi_rotation(RealT a, RealT b, ScalarT c, RealT& cs, ScalarT& sn)\n{\n    using Eigen::numext::abs;\n    using Eigen::numext::abs2;\n    using Eigen::numext::conj;\n    using Eigen::numext::sqrt;\n\n    constexpr const RealT one = RealT(1);\n\n    if (c == ScalarT())\n    {\n        cs = one;\n        sn = ScalarT();\n        return false;\n    }\n\n    auto zeta = (a - b) / (RealT(2) * abs(c));\n    auto w    = sqrt(abs2(zeta) + one);\n    auto t    = (zeta > RealT() ? one / (zeta + w) : one / (zeta - w));\n\n    cs = one / sqrt(abs2(t) + one);\n    sn = -t * cs * (conj(c) / abs(c));\n\n    return true;\n}\n\ntemplate <typename T>\nstruct one_sided_jacobi_helper\n{\n    using Index      = Eigen::Index;\n    using Scalar     = T;\n    using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n    //\n    // Sum of the square of the absolute value of the elments in the i-th column\n    // of the matrix G, i.e. \\f$ \\sum_{k=0}^{n-1} |G_{ki}|^{2}. \\f$\n    //\n    template <typename MatG>\n    static RealScalar submat_diag(const Eigen::MatrixBase<MatG>& G, Index i)\n    {\n        return G.col(i).squaredNorm();\n    }\n\n    template <typename MatG>\n    static Scalar submat_offdiag(const Eigen::MatrixBase<MatG>& G, Index i,\n                                 Index j)\n    {\n        return G.col(i).dot(G.col(j));\n    }\n\n    template <typename MatU>\n    static void update_vecs(Eigen::MatrixBase<MatU>& U, Index i, Index j,\n                            RealScalar cs, const Scalar& sn)\n    {\n        using Eigen::numext::conj;\n        for (Index k = 0; k < U.rows(); ++k)\n        {\n            const auto t1 = U(k, i);\n            const auto t2 = U(k, j);\n            // Apply Jacobi rotation matrix on the right\n            U(k, i) = cs * t1 - sn * t2;\n            U(k, j) = conj(sn) * t1 + cs * t2;\n        }\n    }\n};\n\n} // namespace: detail\n\n///\n/// Compute the singular value decomposition (SVD) by one-sided Jacobi\n/// algorithm.\n///\n/// This function compute the singular value decomposition (SVD) using modified\n/// one-sided Jacobi algorithm.\n///\n/// #### References\n///  - James Demmel and Kresimir Veselic, \"Jacobi's method is more accurate than\n///    QR\", LAPACK working note 15 (lawn15) (1989), Algorithm 4.1.\n///\n/// \\param[in,out] A  On entry, an \\f$m \\times n\\f$ matrix to be decomposed. On\n///     exit, columns of `A` holds left singular vectors.\n/// \\param[out] sigma  singular values of matrix `A`.\n/// \\param[out] V      right singular vectors.\n/// \\param[in] small   positive real number that determines stopping criterion\n///     of Jacobi algorithm.\n///\ntemplate <typename MatA, typename VecS, typename MatV, typename RealT>\nvoid one_sided_jacobi_svd(Eigen::MatrixBase<MatA>& A,\n                          Eigen::MatrixBase<VecS>& sigma,\n                          Eigen::MatrixBase<MatV>& V, RealT tol)\n{\n    using Index      = Eigen::Index;\n    using Scalar     = typename MatA::Scalar;\n    using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n    using jacobi_aux = detail::one_sided_jacobi_helper<Scalar>;\n\n    using Eigen::numext::abs;\n    using Eigen::numext::sqrt;\n    // constexpr const Index max_sweep = 50;\n\n    auto n                = A.cols();\n    const Index max_sweep = n * (n - 1) / 2;\n    assert(V.rows() == A.cols());\n    //\n    // Initialize right singular vectors\n    //\n    V.setIdentity();\n\n    Scalar sn;\n    RealScalar cs;\n    RealScalar max_resid = tol + RealScalar(1);\n    Index nsweep         = max_sweep + 1;\n    while (--nsweep && max_resid > tol)\n    {\n        max_resid = RealScalar();\n        for (Index j = 1; j < n; ++j)\n        {\n            auto b = jacobi_aux::submat_diag(A, j);\n            for (Index i = 0; i < j; ++i)\n            {\n                //\n                // For all pairs i < j, compute the 2x2 submatrix of A.t() * A\n                // constructed from i-th and j-th columns, such as\n                //\n                //   M = [     a   c]\n                //       [conj(c)  b]\n                //\n                // where\n                //\n                //   a = \\sum_{k=0}^{n-1} |A(k,i)|^{2} (computed in outer loop)\n                //   b = \\sum_{k=0}^{n-1} |A(k,j)|^{2}\n                //   c = \\sum_{k=0}^{n-1} conj(A(k,i)) * A(k,j)\n                //\n                auto a    = jacobi_aux::submat_diag(A, i);\n                auto c    = jacobi_aux::submat_offdiag(A, i, j);\n                max_resid = std::max(max_resid, abs(c) / sqrt(a * b));\n                //\n                // Compute the Jacobi rotation matrix which diagonalize M.\n                //\n                if (detail::make_jacobi_rotation(a, b, c, cs, sn))\n                {\n                    // If the return vlaue of make_jacobi_rotation is false, no\n                    // rotation is made.\n                    //\n                    // Update columns i and j of A\n                    //\n                    jacobi_aux::update_vecs(A, i, j, cs, sn);\n                    //\n                    // Update right singular vector V\n                    //\n                    jacobi_aux::update_vecs(V, i, j, cs, sn);\n                }\n            }\n        }\n#ifdef DEBUG\n        std::cout << \"(one_sided_jacobi_svd) iter \" << std::setw(8)\n                  << max_sweep - nsweep << \": max residual = \" << max_resid\n                  << '\\n';\n#endif /* DEBUG */\n    }\n    //\n    // Set singular values and left singular vectors.\n    //\n    for (Index j = 0; j < A.cols(); ++j)\n    {\n        // Singular values are the norms of the columns of the final A\n        sigma(j) = A.col(j).norm();\n        // Left singular vectors are the normalized columns of the final A\n        A.col(j) /= sigma(j);\n    }\n    //\n    // Sort singular values in descending order. The corresponding singular\n    // vectors are also rearranged.\n    //\n    for (Index i = 0; i < n - 1; ++i)\n    {\n        //\n        // Find the index of the maximum value of a sub-array, sigma(i:n-1).\n        //\n        Index imax = i;\n        for (Index k = i + 1; k < n; ++k)\n        {\n            if (sigma(k) > sigma(imax))\n            {\n                imax = k;\n            }\n        }\n\n        if (imax != i)\n        {\n            // Move the largest singular value to the beggining of the\n            // sub-array, and corresponsing singular vectors by swapping columns\n            // of A and V.\n            std::swap(sigma(i), sigma(imax));\n            A.col(i).swap(A.col(imax));\n            V.col(i).swap(V.col(imax));\n        }\n    }\n}\n\n///\n/// Compute the singular value decomposition (SVD) by one-sided Jacobi\n/// algorithm.\n///\n/// This function only computes the singular values and left singular vectors.\n///\n/// \\param[in,out] A  On entry, an \\f$m \\times n\\f$ matrix to be decomposed. On\n///     exit, columns of `A` holds left singular vectors.\n/// \\param[out] sigma  singular values of matrix `A`.\n/// \\param[in] small   positive real number that determines stopping criterion\n///     of Jacobi algorithm.\n///\ntemplate <typename MatA, typename VecS, typename RealT>\nvoid one_sided_jacobi_svd(Eigen::MatrixBase<MatA>& A,\n                          Eigen::MatrixBase<VecS>& sigma, RealT tol)\n{\n    using Index      = Eigen::Index;\n    using Scalar     = typename MatA::Scalar;\n    using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n    using jacobi_aux = detail::one_sided_jacobi_helper<Scalar>;\n\n    using Eigen::numext::abs;\n    using Eigen::numext::sqrt;\n    // constexpr const Index max_sweep = 50;\n\n    auto n                = A.cols();\n    const Index max_sweep = n * (n - 1) / 2;\n\n    Scalar sn;\n    RealScalar cs;\n    RealScalar max_resid = tol + RealScalar(1);\n    Index nsweep         = max_sweep + 1;\n    while (--nsweep && max_resid > tol)\n    {\n        max_resid = RealScalar();\n        for (Index j = 1; j < n; ++j)\n        {\n            auto b = jacobi_aux::submat_diag(A, j);\n            for (Index i = 0; i < j; ++i)\n            {\n                //\n                // For all pairs i < j, compute the 2x2 submatrix of A.t() * A\n                // constructed from i-th and j-th columns, such as\n                //\n                //   M = [     a   c]\n                //       [conj(c)  b]\n                //\n                // where\n                //\n                //   a = \\sum_{k=0}^{n-1} |A(k,i)|^{2} (computed in outer loop)\n                //   b = \\sum_{k=0}^{n-1} |A(k,j)|^{2}\n                //   c = \\sum_{k=0}^{n-1} conj(A(k,i)) * A(k,j)\n                //\n                auto a    = jacobi_aux::submat_diag(A, i);\n                auto c    = jacobi_aux::submat_offdiag(A, i, j);\n                max_resid = std::max(max_resid, abs(c) / sqrt(a * b));\n                //\n                // Compute the Jacobi rotation matrix which diagonalize M.\n                //\n                if (detail::make_jacobi_rotation(a, b, c, cs, sn))\n                {\n                    // If the return vlaue of make_jacobi_rotation is false, no\n                    // rotation is made.\n                    //\n                    // Update columns i and j of A\n                    //\n                    jacobi_aux::update_vecs(A, i, j, cs, sn);\n                }\n            }\n        }\n#ifdef DEBUG\n        std::cout << \"(one_sided_jacobi_svd) iter \" << std::setw(8)\n                  << max_sweep - nsweep << \": max residual = \" << max_resid\n                  << '\\n';\n#endif /* DEBUG */\n    }\n    //\n    // Set singular values and left singular vectors.\n    //\n    for (Index j = 0; j < A.cols(); ++j)\n    {\n        // Singular values are the norms of the columns of the final A\n        sigma(j) = A.col(j).norm();\n        // Left singular vectors are the normalized columns of the final A\n        A.col(j) /= sigma(j);\n    }\n    //\n    // Sort singular values in descending order. The corresponding singular\n    // vectors are also rearranged.\n    //\n    for (Index i = 0; i < n - 1; ++i)\n    {\n        //\n        // Find the index of the maximum value of a sub-array, sigma(i:n-1).\n        //\n        Index imax = i;\n        for (Index k = i + 1; k < n; ++k)\n        {\n            if (sigma(k) > sigma(imax))\n            {\n                imax = k;\n            }\n        }\n\n        if (imax != i)\n        {\n            // Move the largest singular value to the beggining of the\n            // sub-array, and corresponsing singular vectors by swapping columns\n            // of A and V.\n            std::swap(sigma(i), sigma(imax));\n            A.col(i).swap(A.col(imax));\n        }\n    }\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_JACOBI_SVD_HPP */\n", "meta": {"hexsha": "37172a02b7be86a7b598cf153bdd0edaee8dcb96", "size": 11417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["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.9803921569, "max_line_length": 80, "alphanum_fraction": 0.498467198, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6596013567034585}}
{"text": "// RMRayTracer.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <random>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\nusing namespace std;\n\nusing Ray = ParametrizedLine<float, 3>;\nusing Colori = Vector3i;\nusing Colorf = Vector3f;\n\nnamespace rm\n{\n\tclass HitResult\n\t{\n\tpublic:\n\t\tHitResult()\n\t\t\t: t(0.0f)\n\t\t\t, hitPostion(Vector3f::Zero())\n\t\t\t, isHit(false)\n\t\t{}\n\n\t\tvoid Reset()\n\t\t{\n\t\t\tt = 0.0f;\n\t\t\thitPostion = Vector3f::Zero();\n\t\t\tisHit = false;\n\t\t}\n\n\t\tfloat t;\n\t\tVector3f hitPostion;\n\t\tbool isHit;\n\t};\n\n\tclass Camera\n\t{\n\tpublic:\n\t\tCamera(const Vector2i& lScreenSize, const Vector2f& lScreenVirtualSize, const Vector3f& lCameraPosition, const Vector3f& lLeftRightCorner, int lSampleCount)\n\t\t\t: screenSize(lScreenSize)\n\t\t\t, screenVirtualSize(lScreenVirtualSize)\n\t\t\t, screenVirtualHalfSize(lScreenVirtualSize / 2.0f)\n\t\t\t, cameraPosition(lCameraPosition)\n\t\t\t, leftRightCorner(lLeftRightCorner)\n\t\t\t, sampleCount(lSampleCount)\n\t\t{\n\n\t\t}\n\n\t\tconst Vector2i& GetScreenSize() const { return screenSize; }\n\t\tconst Vector2f& GetScreenVirtualSize() const { return screenVirtualSize; }\n\t\tconst Vector2f& GetScreenVirtualHalfSize() const { return screenVirtualHalfSize; }\n\t\tconst Vector3f& GetCameraPosition() const { return cameraPosition; }\n\t\tconst Vector3f& GetLeftRightCorner() const { return leftRightCorner; }\n\t\tint GetSampleCount() const { return sampleCount; }\n\n\tprivate:\n\t\tVector2i screenSize;\n\t\tVector2f screenVirtualSize;\n\t\tVector2f screenVirtualHalfSize;\n\t\tVector3f cameraPosition;\n\t\tVector3f leftRightCorner;\n\t\tint sampleCount;\n\t};\n\n\tclass IHitableObject\n\t{\n\tpublic:\n\t\tvirtual bool\t\tIsHit(const Ray& ray, float minT, float maxT, HitResult& hitResult) const = 0;\n\t\tvirtual Vector3f\tGetNormal(const Vector3f& surfacePosition) const = 0;\n\t\tvirtual Colorf\t\tGetColor() const = 0;\n\t};\n\n\tclass Sphere : public IHitableObject\n\t{\n\tpublic:\n\t\tSphere(const Vector3f& lCenter, float lRadius, const Colorf lColor)\n\t\t\t: center(lCenter)\n\t\t\t, radius(lRadius)\n\t\t\t, color(lColor)\n\t\t{}\n\n\t\tvirtual bool IsHit(const Ray& ray, float minT, float maxT, HitResult& hitResult) const\n\t\t{\n\t\t\thitResult.Reset();\n\n\t\t\tconst Vector3f& vectorA = ray.origin();\n\t\t\tconst Vector3f& vectorB = ray.direction();\n\t\t\tconst Vector3f& vectorC = center;\n\n\t\t\tfloat a = vectorB.dot(vectorB);\n\t\t\tVector3f vectorAC = vectorA - vectorC;\n\t\t\tfloat b = 2 * vectorB.dot(vectorAC);\n\t\t\tfloat c = vectorAC.dot(vectorAC) - radius * radius;\n\n\t\t\tfloat discriminant = b * b - 4 * a * c;\n\n\t\t\tif (discriminant > 0.0f)\n\t\t\t{\n\t\t\t\tfloat t1 = (-b + std::sqrt(discriminant)) / (2.0f * a);\n\t\t\t\tfloat t2 = (-b - std::sqrt(discriminant)) / (2.0f * a);\n\t\t\t\t\n\t\t\t\tfloat t = std::min(t1, t2);\n\n\t\t\t\tif (t >= minT && t < maxT)\n\t\t\t\t{\n\t\t\t\t\thitResult.t = t;\n\t\t\t\t\thitResult.hitPostion = ray.pointAt(t);\n\t\t\t\t\thitResult.isHit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn hitResult.isHit;\n\t\t}\n\n\t\tvirtual Vector3f GetNormal(const Vector3f& surfacePosition) const\n\t\t{\n\t\t\tVector3f normal = surfacePosition - center;\n\t\t\tnormal.normalize();\n\t\t\treturn normal;\n\t\t}\n\n\t\tvirtual Colorf GetColor() const\n\t\t{\n\t\t\treturn color;\n\t\t}\n\n\tprivate:\n\t\tVector3f center;\n\t\tfloat radius;\n\t\tColorf color;\n\t};\n\n\tclass Scene\n\t{\n\tpublic:\n\t\tScene()\n\t\t{\n\t\t\tInitScene();\n\t\t}\n\n\t\t~Scene()\n\t\t{\n\t\t\tDestoryScene();\n\t\t}\n\n\t\tvoid AddHitableObject(IHitableObject* obj)\n\t\t{\n\t\t\tobjectList.push_back(obj);\n\t\t}\n\n\t\tvoid RayTrace(ofstream& fileHandle, const Camera& cam);\n\n\tprotected:\n\t\tvoid InitScene()\n\t\t{\n\n\t\t}\n\n\t\tvoid DestoryScene()\n\t\t{\n\t\t\tfor each (auto obj in objectList)\n\t\t\t{\n\t\t\t\tdelete obj;\n\t\t\t}\n\n\t\t\tobjectList.clear();\n\t\t}\n\n\tprivate:\n\t\tColori GetBackgroundColor(Ray& ray)\n\t\t{\n\t\t\tfloat sqrt = std::sqrt(ray.direction().x() * ray.direction().x() + ray.direction().y() * ray.direction().y());\n\t\t\tfloat lerpValue = std::min(1.0f, sqrt);\n\t\t\tint value = (int)(255.0f * (1.0f - lerpValue));\n\t\t\treturn Colori(value, value, 255);\n\t\t}\n\n\t\tusing HitableObjectList = std::vector<rm::IHitableObject*>;\n\n\t\tHitableObjectList objectList;\n\t};\n\n\tvoid Scene::RayTrace(ofstream& fileHandle, const Camera& cam)\n\t{\n\t\tstd::random_device rd; \n\t\tstd::mt19937 gen(rd());\n\t\tstd::uniform_real_distribution<float> dis(0.0f, 1.0f);\n\n\t\tfor (int y = cam.GetScreenSize().y(); y >= 0; --y)\n\t\t{\n\t\t\tfor (int x = 0; x < cam.GetScreenSize().x(); ++x)\n\t\t\t{\n\t\t\t\tColori color(0, 0, 0);\n\n\t\t\t\tfor (int index = 0; index < cam.GetSampleCount(); ++index)\n\t\t\t\t{\n\t\t\t\t\tfloat sampleX = float(x) + dis(gen);\n\t\t\t\t\tfloat sampleY = float(y) + dis(gen);\n\t\t\t\t\t\n\t\t\t\t\tVector3f offset(sampleX / (float)cam.GetScreenSize().x() * cam.GetScreenVirtualSize().x(),\n\t\t\t\t\t\tsampleY / (float)cam.GetScreenSize().y() * cam.GetScreenVirtualSize().y(), 0.0f);\n\t\t\t\t\toffset = offset + cam.GetLeftRightCorner();\n\t\t\t\t\toffset.normalize();\n\n\t\t\t\t\tRay ray(cam.GetCameraPosition(), offset);\n\n\t\t\t\t\tHitResult hitResult;\n\t\t\t\t\tfloat minT = 0.0f;\n\t\t\t\t\tfloat maxT = FLT_MAX;\n\t\t\t\t\tbool atLeastHitOnce = false;\n\n\t\t\t\t\tfor each (auto obj in objectList)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (obj->IsHit(ray, minT, maxT, hitResult))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tatLeastHitOnce = true;\n\t\t\t\t\t\t\tmaxT = hitResult.t;\n\t\t\t\t\t\t\tVector3f normal = obj->GetNormal(hitResult.hitPostion);\n\t\t\t\t\t\t\tfloat blend = 1.0f - (1.0f + ray.direction().dot(normal)) / 2.0f;\n\t\t\t\t\t\t\tColorf objColor = blend * 256.0f * obj->GetColor();\n\t\t\t\t\t\t\tcolor += Colori((int)objColor.x(), (int)objColor.y(), (int)objColor.z());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!atLeastHitOnce)\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor += GetBackgroundColor(ray);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcolor /= cam.GetSampleCount();\n\n\t\t\t\tfileHandle << color.x() << \" \" << color.y() << \" \" << color.z() << \"\\n\";\n\t\t\t}\n\t\t}\n\t} // end of Scene::RayTrace\n\n} // end of namespace\n\nint main()\n{\n\tofstream ppmFile;\n\tppmFile.open(\"buffer.ppm\");\n\n\tVector2i screenSize(200, 200);\n\tVector2f screenVirtualSize(2, 2);\n\tVector2f screenVirtualHalfSize(screenVirtualSize / 2.0f);\n\tVector3f cameraPosition(0.0f, 0.0f, 1.0f);\n\tVector3f leftRightCorner(-screenVirtualHalfSize.x(), -screenVirtualHalfSize.y(), -1.0f);\n\n\trm::Camera cam(screenSize, screenVirtualSize, cameraPosition, leftRightCorner, 8);\n\n\tppmFile << \"P3\\n\" << screenSize.x() << \" \" << screenSize.y() << \"\\n255\\n\";\n\n\trm::Sphere* sphere1 = new rm::Sphere { Vector3f(0.0f, 0.0f, -1.0f), 0.8f, Colorf(1.0f, 0.0f, 0.0f) };\n\trm::Sphere* sphere2 = new rm::Sphere { Vector3f(0.0f, 0.0f, -2.5f), 1.8f, Colorf(0.0f, 0.0f, 1.0f) };\n\n\trm::Scene scene;\n\tscene.AddHitableObject(sphere1);\n\tscene.AddHitableObject(sphere2);\n\tscene.RayTrace(ppmFile, cam);\n\n\tppmFile.close();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "de16a5ed155000d7eecad3cfa6225b8103f3a682", "size": 6491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RMRayTracer.cpp", "max_stars_repo_name": "cherlix/rmraytracer", "max_stars_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RMRayTracer.cpp", "max_issues_repo_name": "cherlix/rmraytracer", "max_issues_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RMRayTracer.cpp", "max_forks_repo_name": "cherlix/rmraytracer", "max_forks_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_forks_repo_licenses": ["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.518115942, "max_line_length": 158, "alphanum_fraction": 0.6535202588, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657175, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6595645302702531}}
{"text": "// Boost.Geometry\r\n// Unit Test\r\n\r\n// Copyright (c) 2017 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\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#include <geometry_test_common.hpp>\r\n\r\n#include \"test_formula.hpp\"\r\n#include \"vertex_longitude_cases.hpp\"\r\n\r\n#include <boost/geometry/formulas/vertex_latitude.hpp>\r\n#include <boost/geometry/formulas/vertex_longitude.hpp>\r\n#include <boost/geometry/formulas/vincenty_inverse.hpp>\r\n#include <boost/geometry/formulas/thomas_inverse.hpp>\r\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\r\n\r\n#include <boost/geometry/strategies/strategies.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#define BOOST_GEOMETRY_TEST_DEBUG\r\n\r\nnamespace bg = boost::geometry;\r\n\r\ntemplate<typename CT>\r\nCT test_vrt_lon_sph(CT lon1r,\r\n                    CT lat1r,\r\n                    CT lon2r,\r\n                    CT lat2r)\r\n{\r\n    CT a1 = bg::formula::spherical_azimuth(lon1r, lat1r, lon2r, lat2r);\r\n\r\n    typedef bg::model::point<CT, 2,\r\n            bg::cs::spherical_equatorial<bg::radian> > point;\r\n\r\n    bg::model::segment<point> segment(point(lon1r, lat1r),\r\n                                      point(lon2r, lat2r));\r\n    bg::model::box<point> box;\r\n    bg::envelope(segment, box);\r\n\r\n    CT vertex_lat;\r\n    CT lat_sum = lat1r + lat2r;\r\n    if (lat_sum > CT(0))\r\n    {\r\n        vertex_lat = bg::get_as_radian<bg::max_corner, 1>(box);\r\n    } else {\r\n        vertex_lat = bg::get_as_radian<bg::min_corner, 1>(box);\r\n    }\r\n\r\n    bg::strategy::azimuth::spherical<> azimuth;\r\n\r\n    return bg::formula::vertex_longitude\r\n            <CT, bg::spherical_equatorial_tag>::\r\n            apply(lon1r, lat1r,\r\n                  lon2r, lat2r,\r\n                  vertex_lat,\r\n                  a1,\r\n                  azimuth);\r\n}\r\n\r\ntemplate\r\n<\r\n        template <typename, bool, bool, bool, bool, bool> class FormulaPolicy,\r\n        typename CT\r\n        >\r\nCT test_vrt_lon_geo(CT lon1r,\r\n                    CT lat1r,\r\n                    CT lon2r,\r\n                    CT lat2r)\r\n{\r\n    // WGS84\r\n    bg::srs::spheroid<CT> spheroid(6378137.0, 6356752.3142451793);\r\n\r\n    typedef FormulaPolicy<CT, false, true, false, false, false> formula;\r\n    CT a1 = formula::apply(lon1r, lat1r, lon2r, lat2r, spheroid).azimuth;\r\n\r\n    typedef bg::model::point<CT, 2, bg::cs::geographic<bg::radian> > geo_point;\r\n\r\n    bg::model::segment<geo_point> segment(geo_point(lon1r, lat1r),\r\n                                          geo_point(lon2r, lat2r));\r\n    bg::model::box<geo_point> box;\r\n    bg::envelope(segment, box);\r\n\r\n    CT vertex_lat;\r\n    CT lat_sum = lat1r + lat2r;\r\n    if (lat_sum > CT(0))\r\n    {\r\n        vertex_lat = bg::get_as_radian<bg::max_corner, 1>(box);\r\n    } else {\r\n        vertex_lat = bg::get_as_radian<bg::min_corner, 1>(box);\r\n    }\r\n\r\n    bg::strategy::azimuth::geographic<> azimuth_geographic;\r\n\r\n    return bg::formula::vertex_longitude\r\n            <CT, bg::geographic_tag>::apply(lon1r, lat1r,\r\n                                            lon2r, lat2r,\r\n                                            vertex_lat,\r\n                                            a1,\r\n                                            azimuth_geographic);\r\n\r\n}\r\n\r\nvoid test_all(expected_results const& results)\r\n{\r\n    double const d2r = bg::math::d2r<double>();\r\n\r\n    double lon1r = results.p1.lon * d2r;\r\n    double lat1r = results.p1.lat * d2r;\r\n    double lon2r = results.p2.lon * d2r;\r\n    double lat2r = results.p2.lat * d2r;\r\n\r\n    if(lon1r > lon2r)\r\n    {\r\n        std::swap(lon1r, lon2r);\r\n        std::swap(lat1r, lat2r);\r\n    }\r\n\r\n    double res_an = test_vrt_lon_geo<bg::formula::andoyer_inverse>\r\n            (lon1r, lat1r, lon2r, lat2r);\r\n    double res_th = test_vrt_lon_geo<bg::formula::thomas_inverse>\r\n            (lon1r, lat1r, lon2r, lat2r);\r\n    double res_vi = test_vrt_lon_geo<bg::formula::vincenty_inverse>\r\n            (lon1r, lat1r, lon2r, lat2r);\r\n    double res_sh = test_vrt_lon_sph(lon1r, lat1r, lon2r, lat2r);\r\n\r\n    bg::math::normalize_longitude<bg::radian, double>(res_an);\r\n    bg::math::normalize_longitude<bg::radian, double>(res_th);\r\n    bg::math::normalize_longitude<bg::radian, double>(res_vi);\r\n    bg::math::normalize_longitude<bg::radian, double>(res_sh);\r\n\r\n    check_one(res_an, results.andoyer * d2r, res_vi, 0.001);\r\n    check_one(res_th, results.thomas * d2r, res_vi, 0.01);//in some tests thomas gives low accuracy\r\n    check_one(res_vi, results.vincenty * d2r, res_vi, 0.0000001);\r\n    check_one(res_sh, results.spherical * d2r, res_vi, 1);\r\n}\r\n\r\nint test_main(int, char*[])\r\n{\r\n\r\n    for (size_t i = 0; i < expected_size; ++i)\r\n    {\r\n        test_all(expected[i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "49a0a8ee9644bd20591a544161415862815015ab", "size": 4879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/formulas/vertex_longitude.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/geometry/test/formulas/vertex_longitude.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/geometry/test/formulas/vertex_longitude.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": 31.4774193548, "max_line_length": 100, "alphanum_fraction": 0.5927444148, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6595518853307939}}
{"text": "//\n// Copyright Jesse Manning 2007\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\n#include \"convenience.h\"\n#include <boost/numeric/bindings/lapack/gelss.hpp>\n\n// set to 1 to write test output to file, otherwise outputs to console\n#define OUTPUT_TO_FILE 0\n\n// determines which tests to run\n#define TEST_SQUARE 1\n#define TEST_UNDERDETERMINED 1\n#define TEST_OVERDETERMINED 1\n#define TEST_MULTIPLE_SOLUTION_VECTORS 1\n\n// determines if optimal, minimal, or both workspaces are used for testing\n#define USE_OPTIMAL_WORKSPACE 1\n#define USE_MINIMAL_WORKSPACE 1\n\nnamespace lapack = boost::numeric::bindings::lapack;\n\n// test function declarations\ntemplate <typename StreamType, typename MatrType, typename VecType>\nint test_square_gelss(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_under_gelss(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_over_gelss(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_multiple_gelss(StreamType& oss);\n\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_transpose_gel(StreamType& oss, const char& trans);\n\n\nint main()\n{\n\t// stream for test output\n\ttypedef std::ostringstream stream_t;\n\tstream_t oss;\n\n#if TEST_SQUARE\n\toss << \"Start Square Matrix Least Squares Tests\" << std::endl;\n\toss << \"Testing sgelss\" << std::endl;\n\tif (test_square_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)\n\t{\n\t\toss << \"sgelss passed.\" << std::endl;\n\t}\n\toss << \"End sgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing dgelss\" << std::endl;\n\tif (test_square_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)\n\t{\n\t\toss << \"dgelss passed.\" << std::endl;\n\t}\n\toss << \"End dgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing cgelss\" << std::endl;\n\tif (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"cgelss passed.\" << std::endl;\n\t}\n\toss << \"End cgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing zgelss\" << std::endl;\n\tif (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"zgelss passed.\" << std::endl;\n\t}\n\toss << \"End zgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"End Square Matrix Least Squares Tests\" << std::endl;\n#endif\n\n#if TEST_UNDERDETERMINED\n\toss << std::endl;\n\toss << \"Start Under-determined Matrix Least Squares Test\" << std::endl;\n\toss << \"Testing sgelss\" << std::endl;\n\tif (test_under_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)\n\t{\n\t\toss << \"sgelss passed.\" << std::endl;\n\t}\n\toss << \"End sgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing dgelss\" << std::endl;\n\tif (test_under_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)\n\t{\n\t\toss << \"dgelss passed.\" << std::endl;\n\t}\n\toss << \"End dgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing cgelss\" << std::endl;\n\tif (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"cgelss passed.\" << std::endl;\n\t}\n\toss << \"End cgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing zgelss\" << std::endl;\n\tif (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"zgelss passed.\" << std::endl;\n\t}\n\toss << \"End zgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"End Underdetermined Matrix Least Squares Tests\" << std::endl;\n#endif\n\n#if TEST_OVERDETERMINED\n\toss << std::endl;\n\toss << \"Start Overdetermined Matrix Least Squares Test\" << std::endl;\n\toss << \"Testing sgelss\" << std::endl;\n\tif (test_over_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)\n\t{\n\t\toss << \"sgelss passed.\" << std::endl;\n\t}\n\toss << \"End sgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing dgelss\" << std::endl;\n\tif (test_over_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)\n\t{\n\t\toss << \"dgelss passed.\" << std::endl;\n\t}\n\toss << \"End dgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing cgelss\" << std::endl;\n\tif (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"cgelss passed.\" << std::endl;\n\t}\n\toss << \"End cgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing zgelss\" << std::endl;\n\tif (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"zgelss passed.\" << std::endl;\n\t}\n\toss << \"End zgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"End Overdetermined Matrix Least Squares Test\" << std::endl;\n#endif\n\n#if TEST_MULTIPLE_SOLUTION_VECTORS\n\toss << std::endl;\n\toss << \"Start Multiple Solution Vectors Least Squares Test\" << std::endl;\n\toss << \"Testing sgelss\" << std::endl;\n\tif (test_multiple_gelss<stream_t, fmat_t, fvec_t>(oss) == 0)\n\t{\n\t\toss << \"sgelss passed.\" << std::endl;\n\t}\n\toss << \"End sgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing dgelss\" << std::endl;\n\tif (test_multiple_gelss<stream_t, dmat_t, dvec_t>(oss) == 0)\n\t{\n\t\toss << \"dgelss passed.\" << std::endl;\n\t}\n\toss << \"End dgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing cgelss\" << std::endl;\n\tif (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"cgelss passed.\" << std::endl;\n\t}\n\toss << \"End cgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"Testing zgelss\" << std::endl;\n\tif (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0)\n\t{\n\t\toss << \"zgelss passed.\" << std::endl;\n\t}\n\toss << \"End zgelss tests\" << std::endl;\n\toss << std::endl;\n\toss << \"End Multiple Solution Vectors Least Squares Test\" << std::endl;\n#endif\n\n#if OUTPUT_TO_FILE\n\t// Finished testing\n\tstd::cout << std::endl;\n\tstd::cout << \"Tests Completed.\" << std::endl;\n\tstd::cout << std::endl;\n\n\tstd::string filename;\n\tstd::cout << \"Enter filename to write test results: \";\n\tstd::getline(std::cin, filename);\n\n\tstd::ofstream testFile(filename.c_str());\n\n\tif (testFile)\n\t{\n\t\ttestFile << oss.str();\n\t\ttestFile.close();\n\t}\n#else\n\tstd::cout << oss.str() << std::endl;\n\n\t// Finished testing\n\tstd::cout << std::endl;\n\tstd::cout << \"Tests Completed.\" << std::endl;\n\tstd::cout << std::endl;\n#endif\n\n\t// wait for user to finish\n//\tstd::string done;\n//\tstd::cout << \"Press Enter to exit\";\n//\tstd::getline(std::cin, done);\n\n}\n\n// tests square system (m-by-n where m == n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_square_gelss(StreamType& oss)\n{\n\t// return value\n\tint err = 0;\n\n\t// square matrix test\n\tMatType mat(MatrixGenerator<MatType>()(row_size, col_size));\n\tVecType vec(VectorGenerator<VecType>()(row_size));\n\n\t//const int m = traits::matrix_size1(mat);\n\tconst int n = traits::matrix_size2(mat);\n\n#if USE_OPTIMAL_WORKSPACE\n\tMatType optimalmat(mat);\n\tVecType optimalvec(vec);\n\terr += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());\n\tVecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n\tVecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tMatType minimalmat(mat);\n\tVecType minimalvec(vec);\n\terr += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());\n\tVecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n\tVecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n\tmatrix_print(oss, \"A\", mat);\n\toss << std::endl;\n\tvector_print(oss, \"B\", vec);\n\toss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n\tvector_print(oss, \"optimal workspace x\", optimalanswer);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal workspace x\", minimalanswer);\n\toss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n\t// check A*x=B\n\tvector_print(oss, \"optimal A*x=B\", optimal_check);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal A*x=B\", minimal_check);\n\toss << std::endl;\n#endif\n\n\treturn err;\n}\n\n// tests overdetermined system (m-by-n where m < n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_under_gelss(StreamType& oss)\n{\n\t// return value\n\tint err = 0;\n\n\t// under-determined matrix test\n\tMatType mat(MatrixGenerator<MatType>()(row_range, col_size));\n\tVecType vec(VectorGenerator<VecType>()(row_size));\n\n\t//const int m = traits::matrix_size1(mat);\n\tconst int n = traits::matrix_size2(mat);\n\n#if USE_OPTIMAL_WORKSPACE\n\tMatType optimalmat(mat);\n\tVecType optimalvec(vec);\n\terr += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());\n\tVecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n\tVecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tMatType minimalmat(mat);\n\tVecType minimalvec(vec);\n\terr += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());\n\tVecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n\tVecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n\tmatrix_print(oss, \"A\", mat);\n\toss << std::endl;\n\tvector_print(oss, \"B\", vec);\n\toss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n\tvector_print(oss, \"optimal workspace x\", optimalanswer);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal workspace x\", minimalanswer);\n\toss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n\t// check A*x=B\n\tvector_print(oss, \"optimal A*x=B\", optimal_check);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal A*x=B\", minimal_check);\n\toss << std::endl;\n#endif\n\n\treturn err;\n}\n\n// tests overdetermined system (m-by-n where m > n)\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_over_gelss(StreamType& oss)\n{\n\t// return value\n\tint err = 0;\n\n\t// overdetermined matrix test\n\tMatType mat(MatrixGenerator<MatType>()(row_size, col_range));\n\tVecType vec(VectorGenerator<VecType>()(row_size));\n\n\t//const int m = traits::matrix_size1(mat);\n\tconst int n = traits::matrix_size2(mat);\n\n#if USE_OPTIMAL_WORKSPACE\n\tMatType optimalmat(mat);\n\tVecType optimalvec(vec);\n\terr += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());\n\tVecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));\n\tVecType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tMatType minimalmat(mat);\n\tVecType minimalvec(vec);\n\terr += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());\n\tVecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));\n\tVecType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n\tmatrix_print(oss, \"A\", mat);\n\toss << std::endl;\n\tvector_print(oss, \"B\", vec);\n\toss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n\tvector_print(oss, \"optimal workspace x\", optimalanswer);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal workspace x\", minimalanswer);\n\toss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n\t// check A*x=B\n\tvector_print(oss, \"optimal A*x=B\", optimal_check);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tvector_print(oss, \"minimal A*x=B\", minimal_check);\n\toss << std::endl;\n#endif\n\n\treturn err;\n}\n\n// tests multiple solution vectors stored column-wise in B for equation A*x=B\ntemplate <typename StreamType, typename MatType, typename VecType>\nint test_multiple_gelss(StreamType& oss)\n{\n\t// return value\n\tint err = 0;\n\n\t// multiple solutions vectors test\n\tMatType mat(MatrixGenerator<MatType>()(row_size, col_size));\n\tMatType vec(mat.size1(), 2);\n\tublas::column(vec, 0) = VectorGenerator<VecType>()(mat.size1());\n\tublas::column(vec, 1) = VectorGenerator<VecType>()(mat.size1());\n\n\t//const int m = traits::matrix_size1(mat);\n\tconst int n = traits::matrix_size2(mat);\n\tconst int nrhs = traits::matrix_size2(vec);\n\n#if USE_OPTIMAL_WORKSPACE\n\tMatType optimalmat(mat);\n\tMatType optimalvec(vec);\n\terr += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace());\n\tMatType optimalanswer(ublas::project(optimalvec, ublas::range(0, n), ublas::range(0, nrhs)));\n\tMatType optimal_check = ublas::prod(mat, optimalanswer);\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tMatType minimalmat(mat);\n\tMatType minimalvec(vec);\n\terr += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace());\n\tMatType minimalanswer(ublas::project(minimalvec, ublas::range(0, n), ublas::range(0, nrhs)));\n\tMatType minimal_check = ublas::prod(mat, minimalanswer);\n#endif\n\n\tmatrix_print(oss, \"A\", mat);\n\toss << std::endl;\n\tmatrix_print(oss, \"B\", vec);\n\toss << std::endl;\n\n#if USE_OPTIMAL_WORKSPACE\n\tmatrix_print(oss, \"optimal workspace x\", optimalanswer);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tmatrix_print(oss, \"minimal workspace x\", minimalanswer);\n\toss << std::endl;\n#endif\n#if USE_OPTIMAL_WORKSPACE\n\t// check A*x=B\n\tmatrix_print(oss, \"optimal A*x=B\", optimal_check);\n\toss << std::endl;\n#endif\n#if USE_MINIMAL_WORKSPACE\n\tmatrix_print(oss, \"minimal A*x=B\", minimal_check);\n\toss << std::endl;\n#endif\n\n\treturn err;\n}\n", "meta": {"hexsha": "443388b6babb77ef756c43f749b560bb5f1b63f6", "size": 12598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["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.6318181818, "max_line_length": 94, "alphanum_fraction": 0.6982854421, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.659551876597685}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra. Eigen itself is part of the KDE project.\r\n//\r\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\r\n// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n#include <Eigen/LU>\r\n\r\ntemplate<typename MatrixType> void inverse(const MatrixType& m)\r\n{\r\n  /* this test covers the following files:\r\n     Inverse.h\r\n  */\r\n  int rows = m.rows();\r\n  int cols = m.cols();\r\n\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef typename NumTraits<Scalar>::Real RealScalar;\r\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;\r\n\r\n  MatrixType m1 = MatrixType::Random(rows, cols),\r\n             m2(rows, cols),\r\n             mzero = MatrixType::Zero(rows, cols),\r\n             identity = MatrixType::Identity(rows, rows);\r\n\r\n  while(ei_abs(m1.determinant()) < RealScalar(0.1) && rows <= 8)\r\n  {\r\n    m1 = MatrixType::Random(rows, cols);\r\n  }\r\n\r\n  m2 = m1.inverse();\r\n  VERIFY_IS_APPROX(m1, m2.inverse() );\r\n\r\n  m1.computeInverse(&m2);\r\n  VERIFY_IS_APPROX(m1, m2.inverse() );\r\n\r\n  VERIFY_IS_APPROX((Scalar(2)*m2).inverse(), m2.inverse()*Scalar(0.5));\r\n\r\n  VERIFY_IS_APPROX(identity, m1.inverse() * m1 );\r\n  VERIFY_IS_APPROX(identity, m1 * m1.inverse() );\r\n\r\n  VERIFY_IS_APPROX(m1, m1.inverse().inverse() );\r\n\r\n  // since for the general case we implement separately row-major and col-major, test that\r\n  VERIFY_IS_APPROX(m1.transpose().inverse(), m1.inverse().transpose());\r\n}\r\n\r\nvoid test_eigen2_inverse()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1( inverse(Matrix<double,1,1>()) );\r\n    CALL_SUBTEST_2( inverse(Matrix2d()) );\r\n    CALL_SUBTEST_3( inverse(Matrix3f()) );\r\n    CALL_SUBTEST_4( inverse(Matrix4f()) );\r\n    CALL_SUBTEST_5( inverse(MatrixXf(8,8)) );\r\n    CALL_SUBTEST_6( inverse(MatrixXcd(7,7)) );\r\n  }\r\n}\r\n", "meta": {"hexsha": "3d6a30e648895a0f9a8da1a5f1b930ae35db3338", "size": 2075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/test/eigen2/eigen2_inverse.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/test/eigen2/eigen2_inverse.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/test/eigen2/eigen2_inverse.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": 32.421875, "max_line_length": 91, "alphanum_fraction": 0.6573493976, "num_tokens": 574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6595518732810519}}
{"text": "/**\n * @file decision_tree_test.cpp\n * @author Ryan Curtin\n *\n * Tests for the DecisionTree class and related classes.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/decision_tree/decision_tree.hpp>\n#include <mlpack/methods/decision_tree/information_gain.hpp>\n#include <mlpack/methods/decision_tree/gini_gain.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"serialization.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::distribution;\n\nBOOST_AUTO_TEST_SUITE(DecisionTreeTest);\n\n/**\n * Make sure the Gini gain is zero when the labels are perfect.\n */\nBOOST_AUTO_TEST_CASE(GiniGainPerfectTest)\n{\n  arma::Row<size_t> labels;\n  labels.zeros(10);\n\n  // Test that it's perfect regardless of number of classes.\n  for (size_t c = 1; c < 10; ++c)\n    BOOST_REQUIRE_SMALL(GiniGain::Evaluate(labels, c), 1e-5);\n}\n\n/**\n * Make sure the Gini gain is -0.5 when the class split between two classes\n * is even.\n */\nBOOST_AUTO_TEST_CASE(GiniGainEvenSplitTest)\n{\n  arma::Row<size_t> labels(10);\n  for (size_t i = 0; i < 5; ++i)\n    labels[i] = 0;\n  for (size_t i = 5; i < 10; ++i)\n    labels[i] = 1;\n\n  // Test that it's -0.5 regardless of the number of classes.\n  for (size_t c = 2; c < 10; ++c)\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate(labels, c), -0.5, 1e-5);\n}\n\n/**\n * The Gini gain of an empty vector is 0.\n */\nBOOST_AUTO_TEST_CASE(GiniGainEmptyTest)\n{\n  // Test across some numbers of classes.\n  arma::Row<size_t> labels;\n  for (size_t c = 1; c < 10; ++c)\n    BOOST_REQUIRE_SMALL(GiniGain::Evaluate(labels, c), 1e-5);\n}\n\n/**\n * The Gini gain is -(1 - 1/k) for k classes evenly split.\n */\nBOOST_AUTO_TEST_CASE(GiniGainEvenSplitManyClassTest)\n{\n  // Try with many different classes.\n  for (size_t c = 2; c < 30; ++c)\n  {\n    arma::Row<size_t> labels(c);\n    for (size_t i = 0; i < c; ++i)\n      labels[i] = i;\n\n    // Calculate Gini gain and make sure it is correct.\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate(labels, c), -(1.0 - 1.0 / c), 1e-5);\n  }\n}\n\n/**\n * The Gini gain should not be sensitive to the number of points.\n */\nBOOST_AUTO_TEST_CASE(GiniGainManyPoints)\n{\n  for (size_t i = 1; i < 20; ++i)\n  {\n    const size_t numPoints = 100 * i;\n    arma::Row<size_t> labels(numPoints);\n    for (size_t j = 0; j < numPoints / 2; ++j)\n      labels[j] = 0;\n    for (size_t j = numPoints / 2; j < numPoints; ++j)\n      labels[j] = 1;\n\n    BOOST_REQUIRE_CLOSE(GiniGain::Evaluate(labels, 2), -0.5, 1e-5);\n  }\n}\n\n/**\n * The information gain should be zero when the labels are perfect.\n */\nBOOST_AUTO_TEST_CASE(InformationGainPerfectTest)\n{\n  arma::Row<size_t> labels;\n  labels.zeros(10);\n\n  // Test that it's perfect regardless of number of classes.\n  for (size_t c = 1; c < 10; ++c)\n    BOOST_REQUIRE_SMALL(InformationGain::Evaluate(labels, c), 1e-5);\n}\n\n/**\n * If we have an even split, the information gain should be -1.\n */\nBOOST_AUTO_TEST_CASE(InformationGainEvenSplitTest)\n{\n  arma::Row<size_t> labels(10);\n  for (size_t i = 0; i < 5; ++i)\n    labels[i] = 0;\n  for (size_t i = 5; i < 10; ++i)\n    labels[i] = 1;\n\n  // Test that it's -1 regardless of the number of classes.\n  for (size_t c = 2; c < 10; ++c)\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate(labels, c), -1.0, 1e-5);\n}\n\n/**\n * The information gain of an empty vector is 0.\n */\nBOOST_AUTO_TEST_CASE(InformationGainEmptyTest)\n{\n  arma::Row<size_t> labels;\n  for (size_t c = 1; c < 10; ++c)\n    BOOST_REQUIRE_SMALL(InformationGain::Evaluate(labels, c), 1e-5);\n}\n\n/**\n * The information gain is log2(1/k) when splitting equal classes.\n */\nBOOST_AUTO_TEST_CASE(InformationGainEvenSplitManyClassTest)\n{\n  // Try with many different numbers of classes.\n  for (size_t c = 2; c < 30; ++c)\n  {\n    arma::Row<size_t> labels(c);\n    for (size_t i = 0; i < c; ++i)\n      labels[i] = i;\n\n    // Calculate information gain and make sure it is correct.\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate(labels, c),\n        std::log2(1.0 / c), 1e-5);\n  }\n}\n\n/**\n * The information gain should not be sensitive to the number of points.\n */\nBOOST_AUTO_TEST_CASE(InformationGainManyPoints)\n{\n  for (size_t i = 1; i < 20; ++i)\n  {\n    const size_t numPoints = 100 * i;\n    arma::Row<size_t> labels(numPoints);\n    for (size_t j = 0; j < numPoints / 2; ++j)\n      labels[j] = 0;\n    for (size_t j = numPoints / 2; j < numPoints; ++j)\n      labels[j] = 1;\n\n    BOOST_REQUIRE_CLOSE(InformationGain::Evaluate(labels, 2), -1.0, 1e-5);\n  }\n}\n\n/**\n * Check that the BestBinaryNumericSplit will split on an obviously splittable\n * dimension.\n */\nBOOST_AUTO_TEST_CASE(BestBinaryNumericSplitSimpleSplitTest)\n{\n  arma::vec values(\"0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0\");\n  arma::Row<size_t> labels(\"0 0 0 0 0 1 1 1 1 1 1\");\n\n  arma::vec classProbabilities;\n  BestBinaryNumericSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 2);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, labels, 2, 3, classProbabilities, aux);\n\n  // Make sure that a split was made.\n  BOOST_REQUIRE_GT(gain, bestGain);\n\n  // The split is perfect, so we should be able to accomplish a gain of 0.\n  BOOST_REQUIRE_SMALL(gain, 1e-5);\n\n  // The class probabilities, for this split, hold the splitting point, which\n  // should be between 4 and 5.\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 1);\n  BOOST_REQUIRE_GT(classProbabilities[0], 0.4);\n  BOOST_REQUIRE_LT(classProbabilities[0], 0.5);\n}\n\n/**\n * Check that the BestBinaryNumericSplit won't split if not enough points are\n * given.\n */\nBOOST_AUTO_TEST_CASE(BestBinaryNumericSplitMinSamplesTest)\n{\n  arma::vec values(\"0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0\");\n  arma::Row<size_t> labels(\"0 0 0 0 0 1 1 1 1 1 1\");\n\n  arma::vec classProbabilities;\n  BestBinaryNumericSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 2);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, labels, 2, 8, classProbabilities, aux);\n\n  // Make sure that no split was made.\n  BOOST_REQUIRE_EQUAL(gain, bestGain);\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 0);\n}\n\n/**\n * Check that the BestBinaryNumericSplit doesn't split a dimension that gives no\n * gain.\n */\nBOOST_AUTO_TEST_CASE(BestBinaryNumericSplitNoGainTest)\n{\n  arma::vec values(100);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 100; i += 2)\n  {\n    values[i] = i;\n    labels[i] = 0;\n    values[i + 1] = i;\n    labels[i + 1] = 1;\n  }\n\n  arma::vec classProbabilities;\n  BestBinaryNumericSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 2);\n  const double gain = BestBinaryNumericSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, labels, 2, 10, classProbabilities, aux);\n\n  // Make sure there was no split.\n  BOOST_REQUIRE_EQUAL(gain, bestGain);\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 0);\n}\n\n/**\n * Check that the AllCategoricalSplit will split when the split is obviously\n * better.\n */\nBOOST_AUTO_TEST_CASE(AllCategoricalSplitSimpleSplitTest)\n{\n  arma::vec values(\"0 0 0 1 1 1 2 2 2 3 3 3\");\n  arma::Row<size_t> labels(\"0 0 0 2 2 2 1 1 1 2 2 2\");\n\n  arma::vec classProbabilities;\n  AllCategoricalSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 3);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, 4, labels, 3, 3, classProbabilities, aux);\n\n  // Make sure that a split was made.\n  BOOST_REQUIRE_GT(gain, bestGain);\n\n  // Since the split is perfect, make sure the new gain is 0.\n  BOOST_REQUIRE_SMALL(gain, 1e-5);\n\n  // Make sure the class probabilities now hold the number of children.\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 1);\n  BOOST_REQUIRE_EQUAL((size_t) classProbabilities[0], 4);\n}\n\n/**\n * Make sure that AllCategoricalSplit respects the minimum number of samples\n * required to split.\n */\nBOOST_AUTO_TEST_CASE(AllCategoricalSplitMinSamplesTest)\n{\n  arma::vec values(\"0 0 0 1 1 1 2 2 2 3 3 3\");\n  arma::Row<size_t> labels(\"0 0 0 2 2 2 1 1 1 2 2 2\");\n\n  arma::vec classProbabilities;\n  AllCategoricalSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 3);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, 4, labels, 3, 4, classProbabilities, aux);\n\n  // Make sure it's not split.\n  BOOST_REQUIRE_EQUAL(gain, bestGain);\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 0);\n}\n\n/**\n * Check that no split is made when it doesn't get us anything.\n */\nBOOST_AUTO_TEST_CASE(AllCategoricalSplitNoGainTest)\n{\n  arma::vec values(300);\n  arma::Row<size_t> labels(300);\n  for (size_t i = 0; i < 300; i += 3)\n  {\n    values[i] = (i / 3) % 10;\n    labels[i] = 0;\n    values[i + 1] = (i / 3) % 10;\n    labels[i + 1] = 1;\n    values[i + 2] = (i / 3) % 10;\n    labels[i + 2] = 2;\n  }\n\n  arma::vec classProbabilities;\n  AllCategoricalSplit<GiniGain>::template AuxiliarySplitInfo<double> aux;\n\n  // Call the method to do the splitting.\n  const double bestGain = GiniGain::Evaluate(labels, 3);\n  const double gain = AllCategoricalSplit<GiniGain>::SplitIfBetter(bestGain,\n      values, 10, labels, 3, 10, classProbabilities, aux);\n\n  // Make sure that there was no split.\n  BOOST_REQUIRE_EQUAL(gain, bestGain);\n  BOOST_REQUIRE_EQUAL(classProbabilities.n_elem, 0);\n}\n\n/**\n * A basic construction of the decision tree---ensure that we can create the\n * tree and that it split at least once.\n */\nBOOST_AUTO_TEST_CASE(BasicConstructionTest)\n{\n  arma::mat dataset(10, 1000, arma::fill::randu);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 1000; ++i)\n    labels[i] = i % 3; // 3 classes.\n\n  // Use default parameters.\n  DecisionTree<> d(dataset, labels, 3, 50);\n\n  // Now require that we have some children.\n  BOOST_REQUIRE_GT(d.NumChildren(), 0);\n}\n\n/**\n * Construct the decision tree on numeric data only and see that we can fit it\n * exactly and achieve perfect performance on the training set.\n */\nBOOST_AUTO_TEST_CASE(PerfectTrainingSet)\n{\n  // Completely random dataset with no structure.\n  arma::mat dataset(10, 1000, arma::fill::randu);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 1000; ++i)\n    labels[i] = i % 3; // 3 classes.\n\n  DecisionTree<> d(dataset, labels, 3, 1); // Minimum leaf size of 1.\n\n  // Make sure that we can get perfect accuracy on the training set.\n  for (size_t i = 0; i < 1000; ++i)\n  {\n    size_t prediction;\n    arma::vec probabilities;\n    d.Classify(dataset.col(i), prediction, probabilities);\n\n    BOOST_REQUIRE_EQUAL(prediction, labels[i]);\n    BOOST_REQUIRE_EQUAL(probabilities.n_elem, 3);\n    for (size_t j = 0; j < 3; ++j)\n    {\n      if (labels[i] == j)\n        BOOST_REQUIRE_CLOSE(probabilities[j], 1.0, 1e-5);\n      else\n        BOOST_REQUIRE_SMALL(probabilities[j], 1e-5);\n    }\n  }\n}\n\n/**\n * Make sure class probabilities are computed correctly in the root node.\n */\nBOOST_AUTO_TEST_CASE(ClassProbabilityTest)\n{\n  arma::mat dataset(5, 100, arma::fill::randu);\n  arma::Row<size_t> labels(100);\n  for (size_t i = 0; i < 100; i += 2)\n  {\n    labels[i] = 0;\n    labels[i + 1] = 1;\n  }\n\n  // Create a decision tree that can't split.\n  DecisionTree<> d(dataset, labels, 2, 1000);\n\n  BOOST_REQUIRE_EQUAL(d.NumChildren(), 0);\n\n  // Estimate a point's probabilities.\n  arma::vec probabilities;\n  size_t prediction;\n  d.Classify(dataset.col(0), prediction, probabilities);\n\n  BOOST_REQUIRE_EQUAL(probabilities.n_elem, 2);\n  BOOST_REQUIRE_CLOSE(probabilities[0], 0.5, 1e-5);\n  BOOST_REQUIRE_CLOSE(probabilities[1], 0.5, 1e-5);\n}\n\n/**\n * Test that the decision tree generalizes reasonably.\n */\nBOOST_AUTO_TEST_CASE(SimpleGeneralizationTest)\n{\n  arma::mat inputData;\n  if (!data::Load(\"vc2.csv\", inputData))\n    BOOST_FAIL(\"Cannot load test dataset vc2.csv!\");\n\n  arma::Mat<size_t> labels;\n  if (!data::Load(\"vc2_labels.txt\", labels))\n    BOOST_FAIL(\"Cannot load labels for vc2_labels.txt\");\n\n  // Build decision tree.\n  DecisionTree<> d(inputData, labels, 3, 10); // Leaf size of 10.\n\n  // Load testing data.\n  arma::mat testData;\n  if (!data::Load(\"vc2_test.csv\", testData))\n    BOOST_FAIL(\"Cannot load test dataset vc2_test.csv!\");\n\n  arma::Mat<size_t> trueTestLabels;\n  if (!data::Load(\"vc2_test_labels.txt\", trueTestLabels))\n    BOOST_FAIL(\"Cannot load labels for vc2_test_labels.txt\");\n\n  // Get the predicted test labels.\n  arma::Row<size_t> predictions;\n  d.Classify(testData, predictions);\n\n  BOOST_REQUIRE_EQUAL(predictions.n_elem, testData.n_cols);\n\n  // Figure out the accuracy.\n  double correct = 0.0;\n  for (size_t i = 0; i < predictions.n_elem; ++i)\n    if (predictions[i] == trueTestLabels[i])\n      ++correct;\n  correct /= predictions.n_elem;\n\n  BOOST_REQUIRE_GT(correct, 0.75);\n}\n\n/**\n * Test that we can build a decision tree on a simple categorical dataset.\n */\nBOOST_AUTO_TEST_CASE(CategoricalBuildTest)\n{\n  // We'll build a spiral dataset plus two noisy categorical features.  We need\n  // to build the distributions for the categorical features (they'll be\n  // discrete distributions).\n  DiscreteDistribution c1[5];\n  // The distribution will be automatically normalized.\n  for (size_t i = 0; i < 5; ++i)\n  {\n    std::vector<arma::vec> probs;\n    probs.push_back(arma::vec(4, arma::fill::randu));\n    c1[i] = DiscreteDistribution(probs);\n  }\n\n  DiscreteDistribution c2[5];\n  for (size_t i = 0; i < 5; ++i)\n  {\n    std::vector<arma::vec> probs;\n    probs.push_back(arma::vec(2, arma::fill::randu));\n    c2[i] = DiscreteDistribution(probs);\n  }\n\n  arma::mat spiralDataset(4, 10000);\n  arma::Row<size_t> labels(10000);\n  for (size_t i = 0; i < 10000; ++i)\n  {\n    // One circle every 20000 samples.  Plus some noise.\n    const double magnitude = 2.0 + (double(i) / 2000.0) +\n        0.5 * mlpack::math::Random();\n    const double angle = (i % 2000) * (2 * M_PI) + mlpack::math::Random();\n\n    const double x = magnitude * cos(angle);\n    const double y = magnitude * sin(angle);\n\n    spiralDataset(0, i) = x;\n    spiralDataset(1, i) = y;\n\n    // Set categorical features c1 and c2.\n    if (i < 2000)\n    {\n      spiralDataset(2, i) = c1[1].Random()[0];\n      spiralDataset(3, i) = c2[1].Random()[0];\n      labels[i] = 1;\n    }\n    else if (i < 4000)\n    {\n      spiralDataset(2, i) = c1[3].Random()[0];\n      spiralDataset(3, i) = c2[3].Random()[0];\n      labels[i] = 3;\n    }\n    else if (i < 6000)\n    {\n      spiralDataset(2, i) = c1[2].Random()[0];\n      spiralDataset(3, i) = c2[2].Random()[0];\n      labels[i] = 2;\n    }\n    else if (i < 8000)\n    {\n      spiralDataset(2, i) = c1[0].Random()[0];\n      spiralDataset(3, i) = c2[0].Random()[0];\n      labels[i] = 0;\n    }\n    else\n    {\n      spiralDataset(2, i) = c1[4].Random()[0];\n      spiralDataset(3, i) = c2[4].Random()[0];\n      labels[i] = 4;\n    }\n  }\n\n  // Now create the dataset info.\n  data::DatasetInfo di(4);\n  di.Type(2) = data::Datatype::categorical;\n  di.Type(3) = data::Datatype::categorical;\n  // Set mappings.\n  di.MapString<double>(\"0\", 2);\n  di.MapString<double>(\"1\", 2);\n  di.MapString<double>(\"2\", 2);\n  di.MapString<double>(\"3\", 2);\n  di.MapString<double>(\"0\", 3);\n  di.MapString<double>(\"1\", 3);\n\n  // Now shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0, 9999,\n      10000));\n  arma::mat d(4, 10000);\n  arma::Row<size_t> l(10000);\n  for (size_t i = 0; i < 10000; ++i)\n  {\n    d.col(i) = spiralDataset.col(indices[i]);\n    l[i] = labels[indices[i]];\n  }\n\n  // Split into a training set and a test set.\n  arma::mat trainingData = d.cols(0, 4999);\n  arma::mat testData = d.cols(5000, 9999);\n  arma::Row<size_t> trainingLabels = l.subvec(0, 4999);\n  arma::Row<size_t> testLabels = l.subvec(5000, 9999);\n\n  // Build the tree.\n  DecisionTree<> tree(trainingData, di, trainingLabels, 5, 10);\n\n  // Now evaluate the accuracy of the tree.\n  arma::Row<size_t> predictions;\n  tree.Classify(testData, predictions);\n\n  BOOST_REQUIRE_EQUAL(predictions.n_elem, testData.n_cols);\n  size_t correct = 0;\n  for (size_t i = 0; i < testData.n_cols; ++i)\n    if (testLabels[i] == predictions[i])\n      ++correct;\n\n  // Make sure we got at least 70% accuracy.\n  const double correctPct = double(correct) / double(testData.n_cols);\n  BOOST_REQUIRE_GT(correctPct, 0.70);\n}\n\n/**\n * Make sure that when we ask for a decision stump, we get one.\n */\nBOOST_AUTO_TEST_CASE(DecisionStumpTest)\n{\n  // Use a random dataset.\n  arma::mat dataset(10, 1000, arma::fill::randu);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 1000; ++i)\n    labels[i] = i % 3; // 3 classes.\n\n  // Build a decision stump.\n  DecisionTree<GiniGain, BestBinaryNumericSplit, AllCategoricalSplit, double,\n      true> stump(dataset, labels, 3, 1);\n\n  // Check that it has children.\n  BOOST_REQUIRE_EQUAL(stump.NumChildren(), 2);\n  // Check that its children doesn't have children.\n  BOOST_REQUIRE_EQUAL(stump.Child(0).NumChildren(), 0);\n  BOOST_REQUIRE_EQUAL(stump.Child(1).NumChildren(), 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "8ba84c81e26a5779adff4aa6dea7dd9399c1ebd4", "size": 17552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/decision_tree_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/decision_tree_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/decision_tree_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1561461794, "max_line_length": 80, "alphanum_fraction": 0.6712625342, "num_tokens": 5347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6595113270417013}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <gauss/filters.h>\n#include <boost/math/special_functions/factorials.hpp>\n\nnamespace {\n\naf::array savitzkyGolay(af::array &y, int window_size, int order, unsigned int deriv, double rate=1.0) {\n\n    // window_size has to be greater than three\n    if (window_size < 3) {\n        throw std::invalid_argument(\"Window size must be greater or equal to three\");\n    }\n\n    // window_size has to be an odd number\n    if (window_size % 2 == 0) {\n        throw std::invalid_argument(\"Window size must be an odd number.\");\n    }\n\n    if (window_size < (order + 2)) {\n        throw std::invalid_argument(\"Window size is too small for polynomials order\");\n    }\n\n    if (deriv > order) {\n        throw std::invalid_argument(\"Deriv parameter has to be less than order\");\n    }\n\n    auto const half_window = (window_size - 1) / 2;\n    auto const order_range = order + 1;\n\n    // Create a matrix with as many rows as window_size and as many columns as order + 1\n    // The contents of each column is going to be a consecutive range\n    // from -half_window to half_window.\n    // example:\n    //      -half_window + 0, ..., -half_window + 0   (as many columns as order range)\n    //      -half_window + 1, ..., -half_window + 1\n    //      ....    \n    //                    -1, ..., -1\n    //                     0, ..., 0\n    //                     1, ..., 1\n    //      ....\n    //      half_window - 1, ..., half_window - 1\n    //      half_window - 0, ..., half_window - 0\n    auto const b1 = af::iota(af::dim4(window_size), af::dim4(1, order_range), y.type()) - half_window;\n    \n    // This will generate the exponent to each value on b1\n    // example:\n    //      0, 1, 2, 3, 4, ..., order\n    //      0, 1, 2, 3, 4, ..., order\n    //      ...\n    //      0, 1, 2, 3, 4, ..., order\n    //\n    // note the explicit usage of tiling on the first dimension.\n    auto const bExp =  af::range(af::dim4(window_size, order_range), 1, y.type());\n    \n    // we have finally the Vandermonde matrix built.\n    auto const b = af::pow(b1, bExp);\n\n    // b could be also be constructed by the following iterative logic\n    // but, if an accelerated device is present, the above code would work better, \n    // as it doesn't imply an interation with sequential state.\n    // b1(af::span, 0) = 1.0;\n    // b1(af::span, 2) = b1(af::span, 1) * b1(af::span, 1);\n    // b1(af::span, 3) = b1(af::span, 1) * b1(af::span, 2);\n    // b1(af::span, 4) = b1(af::span, 1) * b1(af::span, 3);\n    // etc...\n\n    // now we need to compute the inverse of b\n    auto const bInv = af::pinverse(b);\n\n    // if b is (window_size x order+1), bInv is (order+1 x window_size)\n    // we should select the row corresponding to the required derivative \n    auto const m = bInv(deriv, af::span);\n\n    // scale it\n    auto const mAdj = m * pow(rate, deriv) * boost::math::factorial<double>(deriv);\n    \n    // finally, we need to flip the row before applying the conv operator.\n    auto const mAdjFlip = af::flip(mAdj, 1);\n    return af::convolve(y, mAdjFlip, af::convMode::AF_CONV_DEFAULT);\n}\n\n}", "meta": {"hexsha": "f1537c60f383b88ca41c32bc21d79fe70e4f4988", "size": 3275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/filters.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/filters.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/filters.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "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": 37.2159090909, "max_line_length": 104, "alphanum_fraction": 0.5905343511, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7606506472514405, "lm_q1q2_score": 0.6595113223372971}}
{"text": "#include \"stdafx.h\"\r\n#include \"qmath.h\"\r\n#include \"config.h\"\r\n\r\n// each test module could contain no more then one 'main' file with init function defined\r\n// alternatively you could define init function yourself\r\n#include <boost/test/unit_test.hpp>\r\n\r\n// These are sample tests that show the different features of the framework\r\n\r\nusing namespace math;\r\n\r\nnamespace {\r\n\r\nBOOST_AUTO_TEST_CASE(BINARY)\r\n{\r\n  \t//returns true if the argument is a power of 2.\r\n\tBOOST_CHECK( is_pot(2) == true );\r\n\tBOOST_CHECK( is_pot(3) == false );\r\n\tBOOST_CHECK( is_pot(16) == true );\r\n\t\r\n\tBOOST_CHECK( get_min_pot(127) == 128 );\r\n\tBOOST_CHECK( get_min_pot(128) == 128 );\r\n\tBOOST_CHECK( get_min_pot(129) == 256 );\r\n\t\r\n\t//returns the log2 of the argument\r\n\tBOOST_CHECK( get_pot(4) == 2 );\r\n\tBOOST_CHECK( get_pot(5) == 2 );\r\n\tBOOST_CHECK( get_pot(7) == 2 );\r\n\tBOOST_CHECK( get_pot(8) == 3 );\r\n\t\r\n\t//returns the number of 1 bits in the argument\r\n\tBOOST_CHECK( get_on_bits_count(4) == 1 );\r\n\tBOOST_CHECK( get_on_bits_count(5) == 2 );\r\n\tBOOST_CHECK( get_on_bits_count(7) == 3 );\t\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "47d214d73ad9d6c2550fc1e919078c75df863933", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qmath/test/test_func_binary.cpp", "max_stars_repo_name": "jeanleflambeur/silkopter", "max_stars_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-09T16:47:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T08:32:04.000Z", "max_issues_repo_path": "qmath/test/test_func_binary.cpp", "max_issues_repo_name": "jeanlemotan/silkopter", "max_issues_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2017-02-11T11:15:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T16:00:44.000Z", "max_forks_repo_path": "qmath/test/test_func_binary.cpp", "max_forks_repo_name": "jeanleflambeur/silkopter", "max_forks_repo_head_hexsha": "cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-10-15T05:46:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-11T17:40:36.000Z", "avg_line_length": 27.2820512821, "max_line_length": 90, "alphanum_fraction": 0.6766917293, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6595113118836657}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__gauss_newton_algorithm__hpp_INCLUDED_\n#define _mitrax__gauss_newton_algorithm__hpp_INCLUDED_\n\n#include \"make_matrix.hpp\"\n#include \"gaussian_elimination.hpp\"\n#include \"operator.hpp\"\n#include \"norm.hpp\"\n\n#include \"io/matrix.hpp\"\n\n#include <boost/container/vector.hpp>\n\n#include <iostream>\n\n\nnamespace mitrax{\n\n\n\ttemplate < typename F, typename M, row_t R, typename T, typename ... V >\n\tauto gauss_newton_algorithm(\n\t\tF&& f,\n\t\tcol_vector< M, R > const& start_value,\n\t\tT const& threshold,\n\t\tboost::container::vector< std::tuple< V ... > > const& data\n\t){\n\t\tusing std::abs;\n\n\t\tauto arg = start_value;\n\n\t\tfor(;;){\n\t\t\tstd::cout << arg << std::endl;\n\n\t\t\tauto r = make_vector_fn(rows(data.size()),\n\t\t\t\t[&data, &arg, &f](r_t r){\n\t\t\t\t\treturn f(arg, data[r]);\n\t\t\t\t});\n\n\t\t\tauto d = make_matrix_fn(dim_pair(arg.rows().as_col(), data.size()),\n\t\t\t\t[&data, &arg, &f, &threshold](c_t c, r_t r){\n\t\t\t\t\tauto arg1 = arg;\n\t\t\t\t\targ1[c] += threshold / 128;\n\t\t\t\t\treturn (\n\t\t\t\t\t\tf(arg1, data[r]) - f(arg, data[r])\n\t\t\t\t\t) / (threshold / 128);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tauto trans_d = transpose(d);\n// \t\t\tstd::cout << d << std::endl;\n// \t\t\tstd::cout << trans_d << std::endl;\n// \t\t\tstd::cout << trans_d * d << std::endl;\n// \t\t\tstd::cout << trans_d * r << std::endl;\n\t\t\tauto s = gaussian_elimination(trans_d * d, -trans_d * r);\n\t\t\tauto arg_new = arg + s;\n\n\t\t\tauto diff = arg_new - arg;\n\n\t\t\targ = arg_new;\n\n\t\t\tif(vector_norm_2sqr(diff) < threshold) break;\n\t\t}\n\n\t\treturn arg;\n\t}\n\n\n\ttemplate < typename F, typename M, row_t R, typename T, typename ... V >\n\tauto levenberg_marquardt_algorithm(\n\t\tF&& f,\n\t\tcol_vector< M, R > const& start_value,\n\t\tT const& threshold,\n\t\tT mu,\n\t\tT const& beta0,\n\t\tT const& beta1,\n\t\tboost::container::vector< std::tuple< V ... > > const& data\n\t){\n\t\tusing std::abs;\n\n\t\tauto arg = start_value;\n\n\t\tauto r = make_vector_fn(rows(data.size()),\n\t\t\t[&data, &arg, &f](r_t r){\n\t\t\t\treturn f(arg, data[r]);\n\t\t\t});\n\n\t\tfor(;;){\n// \t\t\tstd::cout << arg << std::endl;\n\n\t\t\tauto d = make_matrix_fn(dim_pair(arg.rows().as_col(), data.size()),\n\t\t\t\t[&data, &arg, &f, &threshold](c_t c, r_t r){\n\t\t\t\t\tauto arg1 = arg;\n\t\t\t\t\targ1[c] += threshold / 128;\n\t\t\t\t\treturn (\n\t\t\t\t\t\tf(arg1, data[r]) - f(arg, data[r])\n\t\t\t\t\t) / (threshold / 128);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tauto s = [&data, &arg, &r, &d, &f, &mu, beta0, beta1]{ for(;;){\n\t\t\t\tauto const mu2_matrix = make_diag_matrix_v< T >(\n\t\t\t\t\targ.rows().as_dim(), mu * mu\n\t\t\t\t);\n\n\t\t\t\tauto trans_d = transpose(d);\n\t\t\t\tauto s = gaussian_elimination(\n\t\t\t\t\ttrans_d * d + mu2_matrix,\n\t\t\t\t\t-trans_d * r\n\t\t\t\t);\n\n\t\t\t\tauto r_new = make_vector_fn(rows(data.size()),\n\t\t\t\t\t[&data, &arg, &s, &f](r_t r){\n\t\t\t\t\t\treturn f(arg + s, data[r]);\n\t\t\t\t\t});\n\n\t\t\t\tauto r_norm = vector_norm_2sqr(r);\n\t\t\t\tauto numerator = (r_norm - vector_norm_2sqr(r_new));\n\t\t\t\tauto denominator = (r_norm - vector_norm_2sqr(r + d * s));\n\t\t\t\tauto eps = numerator / denominator;\n\n\t\t\t\tif(denominator == 0){\n\t\t\t\t\tthrow std::runtime_error(\"eps is infinite\");\n\t\t\t\t}\n\n// \t\t\t\tstd::cout << \"eps: \" << eps << std::endl;\n\t\t\t\tif(eps <= beta0){\n\t\t\t\t\tmu *= 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tr = r_new;\n\n\t\t\t\tif(eps < beta1){\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\n\t\t\t\tmu /= 2;\n\t\t\t\treturn s;\n\t\t\t} }();\n\n// \t\t\tstd::cout << \"s: \" << s << std::endl;\n\t\t\tauto arg_new = arg + s;\n\n\t\t\targ = arg_new;\n\n\t\t\tif(vector_norm_2sqr(s) < threshold) break;\n\t\t}\n\n\t\treturn arg;\n\t}\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "f8ae2b303d728588ee827001d220ba8c8acc01d9", "size": 3697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5426829268, "max_line_length": 79, "alphanum_fraction": 0.5612658913, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6594821100221893}}
{"text": "#ifndef NN_3_LAYER_H\n#define NN_3_LAYER_H\n\n#include <armadillo>\n\nusing namespace arma;\n\nclass NN3Layer {\n    private:\n    mat w;\n    mat v;\n    double learningRate;\n    double sigmoid(double x){\n        return  1 / (1 + exp(-x));\n    }\n    double sigmoid_de(double y){//Differential equation\n        return  y * ( 1 - y );\n    }\n    mat mat_to_sigmoid(mat x){\n      x.for_each( [&](mat::elem_type& val) { val=sigmoid(val); } );\n      return x;\n    }\n    mat mat_to_sigmoid_de(mat x){\n      x.for_each( [&](mat::elem_type& val) { val=sigmoid_de(val); } );\n      return x;\n    }\n    mat mat_to_learning_rate(mat x){\n      x.for_each( [&](mat::elem_type& val) { val=val*this->learningRate; } );\n      return x;\n    }\n    public:\n    NN3Layer(int inputLayer,int hiddenLayer,int outputLayer,double learningRate){\n        this->learningRate = learningRate;\n        this->w =mat(hiddenLayer,inputLayer+1,fill::randu);\n        this->v =mat(outputLayer,hiddenLayer+1,fill::randu);\n    };\n    mat forward_input_to_hidden(mat x){\n        mat h;\n        //set bias\n        mat set_bias(1, 1, fill::ones);\n        x = join_rows(x,set_bias);\n        //h=sigmoid(wx+bias)\n        h=this->mat_to_sigmoid(this->w*x.t());\n        return h;\n    }\n    mat forward_hidden_to_output(mat h){\n        mat o;\n        //set bias\n        mat set_bias(1, 1, fill::ones);\n        h = join_cols(h,set_bias);\n        //o=sigmoid(vh+bias)\n        o=this->mat_to_sigmoid(this->v*h);\n        return o;\n    }\n    //dO\n    mat backward_output_to_hidden(mat o,mat d){\n      mat error = d-o;\n      square(error).print(\"error:\");\n      //-1*(d-o)\n      mat dError =error;\n      dError.for_each( [&](mat::elem_type& val) { val=val*-1; } );\n      //sigmoid_de\n      return this->mat_to_sigmoid_de(o)%dError;\n    }\n    //dH\n    mat backward_hidden_to_input(mat dO,mat h){\n      mat dnet =this->mat_to_sigmoid_de(h);\n      mat dH = this->v;\n      //remove bias\n      dH.reshape(this->v.n_rows,this->v.n_cols-1);\n      return (dH.t()*dO) %dnet;\n    }\n    void backward_update(mat dO,mat h,mat dH,mat x){\n      //set bias\n      mat set_bias(1, 1, fill::ones);\n      //calculate weight update value\n      mat dV = dO * join_cols(h,set_bias).t();\n      mat dW = dH * join_rows(x,set_bias);\n      //update weight\n      this->v = this->v - this->mat_to_learning_rate(dV);\n      this->w = this->w - this->mat_to_learning_rate(dW);\n    }\n    void train_step_sgd(mat x,mat d){\n      //forward\n      mat h = this->forward_input_to_hidden(x);\n      mat o = this->forward_hidden_to_output(h);\n      //backward\n      //calculate gradient\n      mat dO = this->backward_output_to_hidden(o,d);\n      mat dH = this->backward_hidden_to_input(dO,h);\n      //update weight\n      this->backward_update(dO,h,dH,x);\n    }\n    mat only_forward(mat x){\n      //forward\n      mat h = this->forward_input_to_hidden(x);\n      return this->forward_hidden_to_output(h);\n    }\n\n\n\n};\n\n#endif", "meta": {"hexsha": "fc7a420e026e8f9b11c4f40e36eb8406261b057b", "size": 2916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NN3Layer.hpp", "max_stars_repo_name": "ShangHong-CAI/NN3Layer", "max_stars_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T06:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T10:42:13.000Z", "max_issues_repo_path": "NN3Layer.hpp", "max_issues_repo_name": "ShangHong-CAI/NN3Layer", "max_issues_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NN3Layer.hpp", "max_forks_repo_name": "ShangHong-CAI/NN3Layer", "max_forks_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-25T16:13:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T07:37:19.000Z", "avg_line_length": 28.0384615385, "max_line_length": 81, "alphanum_fraction": 0.585733882, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6593568386813116}}
{"text": "#define BOOST_TEST_MODULE Exponentiation test\n#include <boost/test/unit_test.hpp>\n\n#include \"Variable.h\"\n#include \"Sum.h\"\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(Exponentiation_tests)\n{\n    auto a = 2_v ^ 3;\n    BOOST_TEST(a==8);\n    a = 2_v ^ 11;\n    BOOST_TEST(a==(1<<11));\n    Variable x;\n    auto _1 = (x-2)^3;\n    auto _2 = (x-2)*(x-2)*(x-2);\n    BOOST_TEST(_1==_2);\n    _1 = -32;\n    _1 ^= .5;\n    _2 = 4;\n    _2 *= -2_v^(1_v/2);\n    BOOST_TEST(_1==_2);\n    _1 = -1_v*((-4_v)^(1_v/2))*((-16_v)^((1_v/2)));\n    _2 = 8;\n    BOOST_TEST(_1==_2);\n    \n    _1 = (((x-2)^2)+((x+2)^2));\n    _1 = _1(x);\n    _2 = ((-1)^(1_v/2))*2;\n    BOOST_TEST(_1==_2);\n}\n\nBOOST_AUTO_TEST_CASE(Compare_test)\n{\n    auto _1 = 25 ^ Fraction{1_v,-2};\n    auto _2 = (1_v / 5)*(1_v^(1_v/2));\n    auto p =Product::cast(_1);\n    if (p) for(auto&a:*p)\n        std::cout << a.Hash() << std::endl;\n    p =Product::cast(_2);\n    if (p) for(auto&a:*p)\n        std::cout << a.Hash() << std::endl;\n    auto c = _1 == _2;\n    BOOST_TEST(c);\n}\n\nBOOST_AUTO_TEST_CASE(Sqrt_test)\n{\n    auto a = 25_v;\n    auto e = a ^ (1_v/2);\n    auto c = e == (1_v^(1_v/2))*5;\n    BOOST_TEST(c);\n    BOOST_TEST(e != 5);\n    // https://math.stackexchange.com/questions/41784/convert-any-number-to-positive-how/41787#comment5776496_41787\n    e = a.Sqrt();\n    BOOST_TEST(e == 5);\n}\n\nBOOST_AUTO_TEST_CASE(Polynomial_Sqrt_test\n                     ,*disabled()\n                     )\n{\n    Variable x,y;\n    auto a = 4*(x^2)-12*x*y+9*(y^2);\n    auto e = a.Sqrt();\n    BOOST_TEST(e == 2*x-3*y);\n}\n\nBOOST_AUTO_TEST_CASE(Polynomial_Exp_test\n                     ,*disabled()\n                     )\n{\n    auto v = \"v\"_va;\n    auto a = \"a\"_va;\n    auto b = \"b\"_va;\n    \n    auto _ = (4_v*(v^2) + 2048)^(1_v/2);\n    _.SetView(Valuable::View::Solving);\n    _.optimize();\n    \n    auto t=4_v;\n    auto c=2048_v;\n    auto _2ab=2_v*a*b;\n    auto d = (-_2ab).sq() + 4_v*(t-a.Sq())*(b.Sq()-c);\n    auto x = (_2ab+(d^(1_v/2)))/(2_v*(t-a.Sq()));\n    _.eval({{v,x}});\n    auto ab = 0_v;\n    _.eval({{b,ab}});\n    \n    auto e = Exponentiation::cast(_);\n    auto eb = e->getBase();\n    auto ebs = Sum::cast(eb);\n    for(auto&m:*ebs){\n//        if (m.) {\n//            <#statements#>\n//        }\n    }\n    auto it =ebs->begin();\n    auto m1=*it;\n    for(auto& v:it->getCommonVars())\n        std::cout << v.first.str() << '^' << v.second.str() << std::endl;\n    auto m2 =*++it;\n    auto ms = m1+m2;\n//    Valuable f = Fraction{\n    \n//    auto av = _(a);\n    _.optimize();\n}\n\nBOOST_AUTO_TEST_CASE(Multival_test)\n{\n    auto a = 1_v ^ (1_v/2);\n    BOOST_TEST(!!a.IsMultival() == true);\n    \n    DECL_VA(x);\n    BOOST_TEST(!!x.IsMultival() == true);\n    a = x / x;\n    BOOST_TEST(a != 1);\n    BOOST_TEST(!!a.IsMultival() == true);\n    BOOST_TEST(a == x/x);\n}\n", "meta": {"hexsha": "0f4c21b6a0463039e2e1fef4e05800c2bdfe7b31", "size": 2824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/Exponentiation_test.cpp", "max_stars_repo_name": "leannejdong/openmind", "max_stars_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T06:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T06:47:44.000Z", "max_issues_repo_path": "omnn/math/test/Exponentiation_test.cpp", "max_issues_repo_name": "leannejdong/openmind", "max_issues_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "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": "omnn/math/test/Exponentiation_test.cpp", "max_forks_repo_name": "leannejdong/openmind", "max_forks_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "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.9593495935, "max_line_length": 115, "alphanum_fraction": 0.5113314448, "num_tokens": 1001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6593420727471218}}
{"text": "#include <cassert>\n#include <cstdlib>\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <string>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing real_t = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<10000>>;\n\nreal_t operator\"\" _R( long double d ) {\n\treturn real_t{ d };\n}\n\nreal_t get_fibonacci( uintmax_t const n ) {\n\t// Use Binet's formula, limited n to decimal for perf increase\n\tif( n < 1 ) {\n\t\treturn 0.0_R;\n\t}\n\tstatic real_t const sqrt_five = sqrt( 5.0_R );\n\tstatic real_t const a_part = (1.0_R + sqrt_five) / 2.0_R;\n\tstatic real_t const b_part = (1.0_R - sqrt_five) / 2.0_R;\n\t\n\treal_t const a = pow( a_part, n );\n\treal_t const b = pow( b_part, n );\n\treturn round( (a - b)/sqrt_five );\n}\n\nint main( int argc, char **argv ) { \n//\tassert( argc == 2 );\n//\n//\tauto n = strtoull( argv[1], 0, 10 );\n\tuint64_t n = 1234567;\n\tstd::cout << n << \": \" << std::setprecision(std::numeric_limits<real_t>::max_digits10) << get_fibonacci( n ) << '\\n';\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "b49834d7b1b656d3f07b90ef2695c505a0620a15", "size": 1012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fibonacci.cpp", "max_stars_repo_name": "beached/fibonacci", "max_stars_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fibonacci.cpp", "max_issues_repo_name": "beached/fibonacci", "max_issues_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fibonacci.cpp", "max_forks_repo_name": "beached/fibonacci", "max_forks_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_forks_repo_licenses": ["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.6315789474, "max_line_length": 118, "alphanum_fraction": 0.6669960474, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6593377284644676}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <utility> // std::pair, std::make_pair\n#include <cmath> // float comparison\n#include <limits>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"betti_numbers\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n\nstruct MiniSTOptions : Gudhi::Simplex_tree_options_full_featured {\n  // Implicitly use 0 as filtration value for all simplices\n  static const bool store_filtration = false;\n  // The persistence algorithm needs this\n  static const bool store_key = true;\n  // I have few vertices\n  typedef short Vertex_handle;\n};\n\nusing Mini_simplex_tree = Gudhi::Simplex_tree<MiniSTOptions>;\nusing Mini_st_persistence =\n    Gudhi::persistent_cohomology::Persistent_cohomology<Mini_simplex_tree, Gudhi::persistent_cohomology::Field_Zp>;\n\n/*\n * Compare two intervals by dimension, then by length.\n */\ntemplate<class Simplicial_complex>\nstruct cmp_intervals_by_dim_then_length {\n  explicit cmp_intervals_by_dim_then_length(Simplicial_complex * sc)\n      : sc_(sc) { }\n\n  template<typename Persistent_interval>\n  bool operator()(const Persistent_interval & p1, const Persistent_interval & p2) {\n    if (sc_->dimension(get < 0 > (p1)) == sc_->dimension(get < 0 > (p2)))\n      return (sc_->filtration(get < 1 > (p1)) - sc_->filtration(get < 0 > (p1))\n              > sc_->filtration(get < 1 > (p2)) - sc_->filtration(get < 0 > (p2)));\n    else\n      return (sc_->dimension(get < 0 > (p1)) > sc_->dimension(get < 0 > (p2)));\n  }\n  Simplicial_complex* sc_;\n};\n\nBOOST_AUTO_TEST_CASE( plain_homology_betti_numbers )\n{\n  Mini_simplex_tree st;\n\n  /* Complex to build. */\n  /*    1   4          */\n  /*    o---o          */\n  /*   /3\\ /           */\n  /*  o---o   o        */\n  /*  2   0   5        */\n  const short tetra0123[] = {0, 1, 2, 3};\n  const short edge04[] = {0, 4};\n  const short edge14[] = {1, 4};\n  const short vertex5[] = {5};\n  st.insert_simplex_and_subfaces(tetra0123);\n  st.insert_simplex_and_subfaces(edge04);\n  st.insert_simplex(edge14);\n  st.insert_simplex(vertex5);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  // Class for homology computation\n  Mini_st_persistence pcoh(st);\n\n  // Initialize the coefficient field Z/3Z for homology\n  pcoh.init_coefficients(3);\n\n  // Compute the persistence diagram of the complex\n  pcoh.compute_persistent_cohomology();\n\n  // Print the result. The format is, on each line: 2 dim 0 inf\n  // where 2 represents the field, dim the dimension of the feature.\n  // 2  0 0 inf \n  // 2  0 0 inf \n  // 2  1 0 inf \n  // means that in Z/2Z-homology, the Betti numbers are b0=2 and b1=1.\n  \n  std::cout << \"BETTI NUMBERS\" << std::endl;\n\n  BOOST_CHECK(pcoh.betti_number(0) == 2);\n  BOOST_CHECK(pcoh.betti_number(1) == 1);\n  BOOST_CHECK(pcoh.betti_number(2) == 0);\n\n  std::vector<int> bns = pcoh.betti_numbers();\n  BOOST_CHECK(bns.size() == 3);\n  BOOST_CHECK(bns[0] == 2);\n  BOOST_CHECK(bns[1] == 1);\n  BOOST_CHECK(bns[2] == 0);\n\n  std::cout << \"GET PERSISTENT PAIRS\" << std::endl;\n  \n  // Custom sort and output persistence\n  cmp_intervals_by_dim_then_length<Mini_simplex_tree> cmp(&st);\n  auto persistent_pairs = pcoh.get_persistent_pairs();\n  \n  std::sort(std::begin(persistent_pairs), std::end(persistent_pairs), cmp);\n  \n  BOOST_CHECK(persistent_pairs.size() == 3);\n  // persistent_pairs[0] = 2  1 0 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[0])) == 1);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[0])) == 0);\n  BOOST_CHECK(get<1>(persistent_pairs[0]) == st.null_simplex());\n\n  // persistent_pairs[1] = 2  0 0 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[1])) == 0);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[1])) == 0);\n  BOOST_CHECK(get<1>(persistent_pairs[1]) == st.null_simplex());\n\n  // persistent_pairs[2] = 2  0 0 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[2])) == 0);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[2])) == 0);\n  BOOST_CHECK(get<1>(persistent_pairs[2]) == st.null_simplex());\n\n  std::cout << \"INTERVALS IN DIMENSION\" << std::endl;\n\n  auto intervals_in_dimension_0 = pcoh.intervals_in_dimension(0);\n  std::cout << \"intervals_in_dimension_0.size() = \" << intervals_in_dimension_0.size() << std::endl;\n  for (std::size_t i = 0; i < intervals_in_dimension_0.size(); i++)\n    std::cout << \"intervals_in_dimension_0[\" << i << \"] = [\" << intervals_in_dimension_0[i].first << \",\" <<\n                 intervals_in_dimension_0[i].second << \"]\" << std::endl;\n  BOOST_CHECK(intervals_in_dimension_0.size() == 2);\n  BOOST_CHECK(intervals_in_dimension_0[0].first == 0);\n  BOOST_CHECK(intervals_in_dimension_0[0].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n  BOOST_CHECK(intervals_in_dimension_0[1].first == 0);\n  BOOST_CHECK(intervals_in_dimension_0[1].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n\n\n  auto intervals_in_dimension_1 = pcoh.intervals_in_dimension(1);\n  std::cout << \"intervals_in_dimension_1.size() = \" << intervals_in_dimension_1.size() << std::endl;\n  for (std::size_t i = 0; i < intervals_in_dimension_1.size(); i++)\n    std::cout << \"intervals_in_dimension_1[\" << i << \"] = [\" << intervals_in_dimension_1[i].first << \",\" <<\n                 intervals_in_dimension_1[i].second << \"]\" << std::endl;\n  BOOST_CHECK(intervals_in_dimension_1.size() == 1);\n  BOOST_CHECK(intervals_in_dimension_1[0].first == 0);\n  BOOST_CHECK(intervals_in_dimension_1[0].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n\n  auto intervals_in_dimension_2 = pcoh.intervals_in_dimension(2);\n  std::cout << \"intervals_in_dimension_2.size() = \" << intervals_in_dimension_2.size() << std::endl;\n  BOOST_CHECK(intervals_in_dimension_2.size() == 0);\n}\n\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing St_persistence =\n    Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Gudhi::persistent_cohomology::Field_Zp>;\n\nBOOST_AUTO_TEST_CASE( betti_numbers )\n{\n  Simplex_tree st;\n\n  /* Complex to build. */\n  /*    1   4          */\n  /*    o---o          */\n  /*   /3\\ /           */\n  /*  o---o   o        */\n  /*  2   0   5        */\n  const short tetra0123[] = {0, 1, 2, 3};\n  const short edge04[] = {0, 4};\n  const short edge14[] = {1, 4};\n  const short vertex5[] = {5};\n  st.insert_simplex_and_subfaces(tetra0123, 4.0);\n  st.insert_simplex_and_subfaces(edge04, 2.0);\n  st.insert_simplex(edge14, 2.0);\n  st.insert_simplex(vertex5, 1.0);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  // Class for homology computation\n  St_persistence pcoh(st);\n\n  // Initialize the coefficient field Z/3Z for homology\n  pcoh.init_coefficients(3);\n\n  // Compute the persistence diagram of the complex\n  pcoh.compute_persistent_cohomology();\n\n  // Check the Betti numbers are b0=2, b1=1 and b2=0.\n  BOOST_CHECK(pcoh.betti_number(0) == 2);\n  BOOST_CHECK(pcoh.betti_number(1) == 1);\n  BOOST_CHECK(pcoh.betti_number(2) == 0);\n\n  // Check the Betti numbers are b0=2, b1=1 and b2=0.\n  std::vector<int> bns = pcoh.betti_numbers();\n  BOOST_CHECK(bns.size() == 3);\n  BOOST_CHECK(bns[0] == 2);\n  BOOST_CHECK(bns[1] == 1);\n  BOOST_CHECK(bns[2] == 0);\n  \n  // Check the persistent Betti numbers in [4., 10.] are b0=2, b1=1 and b2=0.\n  BOOST_CHECK(pcoh.persistent_betti_number(0, 4., 10.) == 2);\n  BOOST_CHECK(pcoh.persistent_betti_number(1, 4., 10.) == 1);\n  BOOST_CHECK(pcoh.persistent_betti_number(2, 4., 10.) == 0);\n\n  // Check the persistent Betti numbers in [2., 100.] are b0=2, b1=0 and b2=0.\n  BOOST_CHECK(pcoh.persistent_betti_number(0, 2., 100.) == 2);\n  BOOST_CHECK(pcoh.persistent_betti_number(1, 2., 100.) == 0);\n  BOOST_CHECK(pcoh.persistent_betti_number(2, 2., 100.) == 0);\n\n  // Check the persistent Betti numbers in [1., 1000.] are b0=1, b1=0 and b2=0.\n  BOOST_CHECK(pcoh.persistent_betti_number(0, 1., 1000.) == 1);\n  BOOST_CHECK(pcoh.persistent_betti_number(1, 1., 1000.) == 0);\n  BOOST_CHECK(pcoh.persistent_betti_number(2, 1., 1000.) == 0);\n\n  // Check the persistent Betti numbers in [.9, 1000.] are b0=0, b1=0 and b2=0.\n  BOOST_CHECK(pcoh.persistent_betti_number(0, .9, 1000.) == 0);\n  BOOST_CHECK(pcoh.persistent_betti_number(1, .9, 1000.) == 0);\n  BOOST_CHECK(pcoh.persistent_betti_number(2, .9, 1000.) == 0);\n\n  // Check the persistent Betti numbers in [4.1, 10000.] are b0=2, b1=1 and b2=0.\n  bns = pcoh.persistent_betti_numbers(4.1, 10000.);\n  BOOST_CHECK(bns[0] == 2);\n  BOOST_CHECK(bns[1] == 1);\n  BOOST_CHECK(bns[2] == 0);\n  \n  // Check the persistent Betti numbers in [2.1, 100000.] are b0=2, b1=0 and b2=0.\n  bns = pcoh.persistent_betti_numbers(2.1, 100000.);\n  BOOST_CHECK(bns[0] == 2);\n  BOOST_CHECK(bns[1] == 0);\n  BOOST_CHECK(bns[2] == 0);\n\n  // Check the persistent Betti numbers in [1.1, 1000000.] are b0=1, b1=0 and b2=0.\n  bns = pcoh.persistent_betti_numbers(1.1, 1000000.);\n  BOOST_CHECK(bns[0] == 1);\n  BOOST_CHECK(bns[1] == 0);\n  BOOST_CHECK(bns[2] == 0);\n  \n  // Check the persistent Betti numbers in [.1, 10000000.] are b0=0, b1=0 and b2=0.\n  bns = pcoh.persistent_betti_numbers(.1, 10000000.);\n  BOOST_CHECK(bns[0] == 0);\n  BOOST_CHECK(bns[1] == 0);\n  BOOST_CHECK(bns[2] == 0);\n  \n  // Custom sort and output persistence\n  cmp_intervals_by_dim_then_length<Simplex_tree> cmp(&st);\n  auto persistent_pairs = pcoh.get_persistent_pairs();\n  \n  std::sort(std::begin(persistent_pairs), std::end(persistent_pairs), cmp);\n  \n  BOOST_CHECK(persistent_pairs.size() == 3);\n  // persistent_pairs[0] = 2  1 4 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[0])) == 1);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[0])) == 4);\n  BOOST_CHECK(get<1>(persistent_pairs[0]) == st.null_simplex());\n\n  // persistent_pairs[1] = 2  0 2 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[1])) == 0);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[1])) == 2);\n  BOOST_CHECK(get<1>(persistent_pairs[1]) == st.null_simplex());\n\n  // persistent_pairs[2] = 2  0 1 inf\n  BOOST_CHECK(st.dimension(get<0>(persistent_pairs[2])) == 0);\n  BOOST_CHECK(st.filtration(get<0>(persistent_pairs[2])) == 1);\n  BOOST_CHECK(get<1>(persistent_pairs[2]) == st.null_simplex());\n\n  std::cout << \"INTERVALS IN DIMENSION\" << std::endl;\n\n  auto intervals_in_dimension_0 = pcoh.intervals_in_dimension(0);\n  std::cout << \"intervals_in_dimension_0.size() = \" << intervals_in_dimension_0.size() << std::endl;\n  for (std::size_t i = 0; i < intervals_in_dimension_0.size(); i++)\n    std::cout << \"intervals_in_dimension_0[\" << i << \"] = [\" << intervals_in_dimension_0[i].first << \",\" <<\n                 intervals_in_dimension_0[i].second << \"]\" << std::endl;\n  BOOST_CHECK(intervals_in_dimension_0.size() == 2);\n  BOOST_CHECK(intervals_in_dimension_0[0].first == 2);\n  BOOST_CHECK(intervals_in_dimension_0[0].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n  BOOST_CHECK(intervals_in_dimension_0[1].first == 1);\n  BOOST_CHECK(intervals_in_dimension_0[1].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n\n  auto intervals_in_dimension_1 = pcoh.intervals_in_dimension(1);\n  std::cout << \"intervals_in_dimension_1.size() = \" << intervals_in_dimension_1.size() << std::endl;\n  for (std::size_t i = 0; i < intervals_in_dimension_1.size(); i++)\n    std::cout << \"intervals_in_dimension_1[\" << i << \"] = [\" << intervals_in_dimension_1[i].first << \",\" <<\n                 intervals_in_dimension_1[i].second << \"]\" << std::endl;\n  BOOST_CHECK(intervals_in_dimension_1.size() == 1);\n  BOOST_CHECK(intervals_in_dimension_1[0].first == 4);\n  BOOST_CHECK(intervals_in_dimension_1[0].second == std::numeric_limits<Mini_simplex_tree::Filtration_value>::infinity());\n\n  auto intervals_in_dimension_2 = pcoh.intervals_in_dimension(2);\n  std::cout << \"intervals_in_dimension_2.size() = \" << intervals_in_dimension_2.size() << std::endl;\n  BOOST_CHECK(intervals_in_dimension_2.size() == 0);\n\n  std::cout << \"EMPTY COMPLEX\" << std::endl;\n  Simplex_tree empty;\n  empty.initialize_filtration();\n  St_persistence pcoh_empty(empty, false);\n  pcoh_empty.init_coefficients(2);\n  pcoh_empty.compute_persistent_cohomology();\n  BOOST_CHECK(pcoh_empty.betti_numbers().size() == 0);\n  BOOST_CHECK(pcoh_empty.persistent_betti_numbers(0,1).size() == 0);\n}\n", "meta": {"hexsha": "b9f11607f64625c62a7c3b476d476a3ced169461", "size": 12295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/test/betti_numbers_unit_test.cpp", "max_stars_repo_name": "gtauzin/gudhi-devel", "max_stars_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_stars_repo_licenses": ["MIT"], "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/Persistent_cohomology/test/betti_numbers_unit_test.cpp", "max_issues_repo_name": "gtauzin/gudhi-devel", "max_issues_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_issues_repo_licenses": ["MIT"], "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/Persistent_cohomology/test/betti_numbers_unit_test.cpp", "max_forks_repo_name": "gtauzin/gudhi-devel", "max_forks_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3973063973, "max_line_length": 122, "alphanum_fraction": 0.6866205775, "num_tokens": 3808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6591845021439585}}
{"text": "// Copyright (C) 2016 Daniele Panozzo <daniele.panozzo@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"tutorial_nrosy.h\"\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nstd::complex<double> find_root(std::complex<double> c0, int n)\n{\n  // Find the roots of p(t) = (t - c0)^n using\n  // https://en.wikipedia.org/wiki/Companion_matrix\n  Eigen::MatrixXcd M = Eigen::MatrixXcd::Zero(n,n);\n  for (int i=1;i<n;++i)\n    M(i,i-1) = std::complex<double>(1,0);\n  M(0,n-1) = c0;\n  return M.eigenvalues()(0);\n}\n\nMatrixXd tutorial_nrosy\n        (\n        const MatrixXd& V,          // Vertices of the mesh\n        const MatrixXi& F,          // Faces\n        const MatrixXi& TT,         // Adjacency triangle-triangle\n        const VectorXi& soft_id,    // Soft constraints face ids\n        const MatrixXd& soft_value, // Soft constraints 3d vectors\n        const int n                 // Degree of the n-rosy field\n        )\n{\n  assert(soft_id.size() > 0); // One constraint is necessary to make the solution unique\n\n  Matrix<double,Dynamic,3> T1(F.rows(),3), T2(F.rows(),3);\n\n  // Compute the local reference systems for each face\n  for (unsigned i=0;i<F.rows();++i)\n  {\n    Vector3d e1 =  V.row(F(i, 1)) - V.row(F(i, 0));\n    Vector3d e2 =  V.row(F(i, 2)) - V.row(F(i, 0));\n    T1.row(i) = e1.normalized();\n    T2.row(i) = T1.row(i).cross(T1.row(i).cross(e2)).normalized();\n  }\n\n  // Build the sparse matrix, with an energy term for each edge\n  std::vector< Triplet<std::complex<double> > > t;\n  std::vector< Triplet<std::complex<double> > > tb;\n\n  unsigned count = 0;\n  for (unsigned f=0;f<F.rows();++f)\n  {\n    for (unsigned ei=0;ei<F.cols();++ei)\n    {\n      // Look up the opposite face\n      int g = TT(f,ei);\n\n      // If it is a boundary edge, it does not contribute to the energy\n      if (g == -1) continue;\n\n      // Avoid to count every edge twice\n      if (f > g) continue;\n\n      // Compute the complex representation of the common edge\n      Vector3d e  = (V.row(F(f,(ei+1)%3)) - V.row(F(f,ei)));\n      Vector2d vef = Vector2d(e.dot(T1.row(f)),e.dot(T2.row(f))).normalized();\n      std::complex<double> ef(vef(0),vef(1));\n      Vector2d veg = Vector2d(e.dot(T1.row(g)),e.dot(T2.row(g))).normalized();\n      std::complex<double> eg(veg(0),veg(1));\n\n      // Add the term conj(f)^n*ui - conj(g)^n*uj to the energy matrix\n      t.push_back(Triplet<std::complex<double> >(count,f,    std::pow(std::conj(ef),n)));\n      t.push_back(Triplet<std::complex<double> >(count,g,-1.*std::pow(std::conj(eg),n)));\n\n      ++count;\n    }\n  }\n\n  // Convert the constraints into the complex polynomial coefficients and add them as soft constraints\n  double lambda = 10e6;\n  for (unsigned r=0; r<soft_id.size(); ++r)\n  {\n    int f = soft_id(r);\n    Vector3d v = soft_value.row(r);\n    std::complex<double> c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n    t.push_back(Triplet<std::complex<double> >(count,f, sqrt(lambda)));\n    tb.push_back(Triplet<std::complex<double> >(count,0, std::pow(c,n) * std::complex<double>(sqrt(lambda),0)));\n    ++count;\n  }\n\n  // Solve the linear system\n  typedef SparseMatrix<std::complex<double>> SparseMatrixXcd;\n  SparseMatrixXcd A(count,F.rows());\n  A.setFromTriplets(t.begin(), t.end());\n  SparseMatrixXcd b(count,1);\n  b.setFromTriplets(tb.begin(), tb.end());\n  SimplicialLDLT< SparseMatrixXcd > solver;\n  solver.compute(A.adjoint()*A);\n  assert(solver.info()==Success);\n  MatrixXcd u = solver.solve(A.adjoint()*MatrixXcd(b));\n  assert(solver.info()==Success);\n\n  // Convert the interpolated polyvector into Euclidean vectors\n  MatrixXd R(F.rows(),3);\n  for (int f=0; f<F.rows(); ++f)\n  {\n    std::complex<double> root = find_root(u(f),n);\n    R.row(f) = T1.row(f) * root.real() + T2.row(f) * root.imag();\n  }\n\n  return R;\n}\n", "meta": {"hexsha": "0f72be97fbe5fcf79bd0b8069f735a1f0e49ac5c", "size": 4045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_stars_repo_name": "bambrow/geometric-modeling", "max_stars_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T05:20:52.000Z", "max_issues_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_issues_repo_name": "bambrow/geometric-modeling", "max_issues_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_forks_repo_name": "bambrow/geometric-modeling", "max_forks_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_forks_repo_licenses": ["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.5726495726, "max_line_length": 112, "alphanum_fraction": 0.626946848, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6591685380369127}}
{"text": "// Gao Wang and Kushal K. Dey (c) 2016\n// code format configuration: clang-format -style=Google -dump-config >\n// ~/.clang-format\n#ifndef _PFA_HPP\n#define _PFA_HPP\n\n#include <omp.h>\n#include <armadillo>\n#include <map>\n#include <string>\n\nstatic const double INV_SQRT_2PI = 0.3989422804014327;\nstatic const double INV_SQRT_2PI_LOG = -0.91893853320467267;\n\ninline double normal_pdf(double x, double m, double sd) {\n  double a = (x - m) / sd;\n  return INV_SQRT_2PI / sd * std::exp(-0.5 * a * a);\n};\n\ninline double normal_pdf_log(double x, double m, double sd) {\n  double a = (x - m) / sd;\n  return INV_SQRT_2PI_LOG - std::log(sd) - 0.5 * a * a;\n};\n\n/* The digamma function is the derivative of gammaln.\n   Reference:\n    J Bernardo,\n    Psi ( Digamma ) Function,\n    Algorithm AS 103,\n    Applied Statistics,\n    Volume 25, Number 3, pages 315-317, 1976.\n    From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f\n    (with modifications for negative numbers and extra precision)\n*/\ninline double digamma(double x) {\n  double neginf = -INFINITY;\n  static const double c = 12, digamma1 = -0.57721566490153286,\n                      trigamma1 = 1.6449340668482264365, /* pi^2/6 */\n      s = 1e-6, s3 = 1. / 12, s4 = 1. / 120, s5 = 1. / 252, s6 = 1. / 240,\n                      s7 = 1. / 132, s8 = 691. / 32760, s9 = 1. / 12,\n                      s10 = 3617. / 8160;\n  double result;\n  /* Illegal arguments */\n  if ((x == neginf) || std::isnan(x)) {\n    return NAN;\n  }\n  /* Singularities */\n  if ((x <= 0) && (floor(x) == x)) {\n    return neginf;\n  }\n  /* Negative values */\n  /* Use the reflection formula (Jeffrey 11.1.6):\n * digamma(-x) = digamma(x+1) + pi*cot(pi*x)\n *\n * This is related to the identity\n * digamma(-x) = digamma(x+1) - digamma(z) + digamma(1-z)\n * where z is the fractional part of x\n * For example:\n * digamma(-3.1) = 1/3.1 + 1/2.1 + 1/1.1 + 1/0.1 + digamma(1-0.1)\n *               = digamma(4.1) - digamma(0.1) + digamma(1-0.1)\n * Then we use\n * digamma(1-z) - digamma(z) = pi*cot(pi*z)\n */\n  if (x < 0) {\n    return digamma(1 - x) + M_PI / tan(-M_PI * x);\n  }\n  /* Use Taylor series if argument <= S */\n  if (x <= s) return digamma1 - 1 / x + trigamma1 * x;\n  /* Reduce to digamma(X + N) where (X + N) >= C */\n  result = 0;\n  while (x < c) {\n    result -= 1 / x;\n    x++;\n  }\n  /* Use de Moivre's expansion if argument >= C */\n  /* This expansion can be computed in Maple via asympt(Psi(x),x) */\n  if (x >= c) {\n    double r = 1 / x, t;\n    result += log(x) - 0.5 * r;\n    r *= r;\n#if 1\n    result -= r * (s3 - r * (s4 - r * (s5 - r * (s6 - r * s7))));\n#else\n    /* this version for lame compilers */\n    t = (s5 - r * (s6 - r * s7));\n    result -= r * (s3 - r * (s4 - r * t));\n#endif\n  }\n  return result;\n}\n\ntemplate <typename T>\nvoid print(const T &e) {\n  std::cout << e << std::endl;\n}\n\nclass Exception {\n public:\n  /// constructor\n  /// \\param msg error message\n  Exception(const std::string &msg) : m_msg(msg) {}\n\n  /// return error message\n  const char *message() { return m_msg.c_str(); }\n\n  virtual ~Exception(){};\n\n private:\n  /// error message\n  std::string m_msg;\n};\n\n/// exception, thrown if out of memory\nclass StopIteration : public Exception {\n public:\n  StopIteration(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if index out of range\nclass IndexError : public Exception {\n public:\n  IndexError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if value of range etc\nclass ValueError : public Exception {\n public:\n  ValueError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if system error occurs\nclass SystemError : public Exception {\n public:\n  SystemError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if a runtime error occurs\nclass RuntimeError : public Exception {\n public:\n  RuntimeError(const std::string msg) : Exception(msg){};\n};\n\nextern \"C\" int pfa_em(double *, double *, double *, double *, int *, int *,\n                      int *, int *, double *, int *, double *, int *, int *,\n                      double *, double *, double *, double *, int *, int *,\n                      int *, int *, int *, int *);\nextern \"C\" int pfa_model_loglik(double *, double *, double *, double *, int *,\n                                int *, int *, double *);\n\nclass PFA {\n public:\n  PFA(double *cX, double *cF, double *cP, double *cQ, double *cLout, int N,\n      int J, int K, int C)\n      :  // mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true, strict = true)\n        D(cX, N, J, false, true),\n        F(cF, K, J, false, true),\n        P(cP, K, K, false, true),\n        q(cQ, C, false, true),\n        L(cLout, N, K, false, true) {\n    // initialize residual sd with sample sd\n    s = arma::vectorise(arma::stddev(D));\n    W.set_size(F.n_rows, F.n_rows);\n    delta.set_size(int((F.n_rows + 1) * F.n_rows / 2), q.n_elem, D.n_rows);\n    delta.fill(0);\n    n_threads = omp_get_max_threads();\n    n_updates = 0;\n    for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n      for (size_t k2 = 0; k2 <= k1; k2++) {\n        // set factor pair coordinates to avoid\n        // having to compute it at each iteration\n        // (b + 1) * b / 2 - (b - a)\n        size_t k1k2 = size_t(k1 * (k1 + 1) / 2 + k2);\n        F_pair_coord[std::make_pair(k1, k2)] = k1k2;\n        F_pair_coord[std::make_pair(k2, k1)] = k1k2;\n      }\n    }\n  }\n  virtual ~PFA() {}\n\n  virtual PFA *clone() const { return new PFA(*this); }\n\n  virtual void write(std::ostream &out, int info) {\n    throw RuntimeError(\"The base write() function should not be called\");\n  }\n  virtual int E_step() {\n    throw RuntimeError(\"The base E_step() function should not be called\");\n  }\n\n  virtual int M_step() {\n    throw RuntimeError(\"The base M_step() function should not be called\");\n  }\n\n  void update_model_loglik(arma::vec &true_s, arma::mat &true_q);\n  void set_threads(int n) { n_threads = n; }\n  void update_ldelta(int core = 0);\n  void update_loglik_and_delta();\n  void update_factor_model();\n  void update_residual_error();\n  double get_loglik() { return loglik; }\n  double get_bic() {\n    // BIC = -2 * loglik + d * log(N)\n    // number of parameters:\n    // P: (K + 1) * K / 2\n    // L: N * K\n    // F: K * J\n    return -2 * loglik +\n           ((P.n_rows + 1) * P.n_rows / 2 + D.n_rows * P.n_rows +\n            P.n_rows * D.n_cols) *\n               std::log(D.n_rows);\n  }\n\n protected:\n  // N by J matrix of data\n  arma::mat D;\n  // K by K matrix of factor pair frequencies\n  arma::mat P;\n  // K by J matrix of factors\n  arma::mat F;\n  // Q by 1 vector of membership grids\n  arma::vec q;\n  // J by 1 vector of residual standard error\n  arma::vec s;\n  // K1K2 by Q by N tensor\n  arma::cube delta;\n  arma::cube ldelta;\n  std::map<std::pair<size_t, size_t>, size_t> F_pair_coord;\n  // N by K matrix of loadings\n  arma::mat L;\n  // W = L'L is K X K matrix\n  arma::mat W;\n  // loglik\n  double loglik;\n  // number of threads\n  int n_threads;\n  // updates on the model\n  int n_updates;\n};\n\nclass PFA_EM : public PFA {\n public:\n  PFA_EM(double *cX, double *cF, double *cP, double *cQ, double *cLout, int N,\n         int J, int K, int C)\n      : PFA(cX, cF, cP, cQ, cLout, N, J, K, C) {}\n\n  PFA *clone() const { return new PFA_EM(*this); }\n\n  void update_paired_factor_weights();\n  int E_step() {\n    update_ldelta();\n    update_loglik_and_delta();\n    update_paired_factor_weights();\n    return 0;\n  }\n\n  int M_step() {\n    update_factor_model();\n    update_residual_error();\n    n_updates += 1;\n    return 0;\n  }\n\n  void write(std::ostream &out, int info) {\n    if (info == 0) {\n      // D.print(out, \"Data Matrix:\");\n      q.print(out, \"Membership grids:\");\n    }\n    if (info == 1) {\n      F.print(out, \"Factor matrix:\");\n      P.print(out, \"Factor frequency matrix:\");\n      if (n_updates > 0)\n        L.print(out, \"Loading matrix:\");\n      else\n        out << \"Loading matrix:\" << std::endl;\n    }\n    if (info == 2) {\n      // W.print(out, \"E[L'L] matrix:\");\n      s.print(out, \"Residual standard deviation of data columns:\");\n      if (n_updates > 0) {\n        ldelta.print(out, \"log delta tensor\");\n        delta.print(out, \"delta tensor\");\n      }\n    }\n  }\n};\n\nclass PFA_VEM : public PFA {\n public:\n  PFA_VEM(double *cX, double *cF, double *cP, double *cQ, double *cLout,\n          double *calphaout, int N, int J, int K, int C, double alpha0)\n      : PFA(cX, cF, cP, cQ, cLout, N, J, K, C),\n        alpha(calphaout, K, K, false, true),\n        alpha0(alpha0) {\n    alpha.zeros();\n    digamma_alpha.set_size(P.n_rows, P.n_rows);\n    digamma_alpha.fill(digamma(alpha0));\n    digamma_sum_alpha = 0;\n    maxiter = 1000;\n    tol = 1E-3;\n  }\n\n  PFA *clone() const { return new PFA_VEM(*this); }\n\n  void update_variational_ldelta();\n  double get_variational_lowerbound();\n  void update_variational_parameters();\n  void update_paired_factor_weights();\n\n  int E_step() {\n    int status = 0;\n    update_ldelta(1);\n    size_t niter = 0;\n    lowerbound.resize(0);\n    while (niter <= maxiter) {\n      update_variational_ldelta();\n      update_loglik_and_delta();\n      update_variational_parameters();\n      update_paired_factor_weights();\n      lowerbound.push_back(get_variational_lowerbound());\n      if (lowerbound.back() != lowerbound.back()) {\n        std::cerr\n            << \"[ERROR] lower bound nan produced in variational approximation!\"\n            << std::endl;\n        status = 1;\n        break;\n      }\n      niter++;\n      if (niter > 1) {\n        double diff = lowerbound[niter - 1] - lowerbound[niter - 2];\n        if (diff < 0.0) {\n          std::cerr << \"[ERROR] lower bound decreased in variational \"\n                       \"approximation:  \\n\\tfrom \"\n                    << lowerbound[niter - 2] << \" to \" << lowerbound[niter - 1]\n                    << \"!\" << std::endl;\n          status = 1;\n          break;\n        }\n        if (diff < tol) break;\n      }\n      if (niter == maxiter) {\n        std::cerr << \"[WARNIKNG] variational approximation procedure failed to \"\n                     \"converge at tolerance level \"\n                  << tol << \", after \" << maxiter\n                  << \" iterations: \\n\\tlog lower bound starts \"\n                  << lowerbound.front() << \", ends \" << lowerbound.back() << \"!\"\n                  << std::endl;\n        status = 1;\n        break;\n      }\n    }\n    return status;\n  }\n\n  int M_step() {\n    update_factor_model();\n    update_residual_error();\n    n_updates += 1;\n    return 0;\n  }\n\n  void write(std::ostream &out, int info) {\n    if (info == 0) {\n      // D.print(out, \"Data Matrix:\");\n      q.print(out, \"Membership grids:\");\n    }\n    if (info == 1) {\n      F.print(out, \"Factor matrix:\");\n      P.print(out, \"Factor frequency matrix:\");\n      if (n_updates > 0)\n        L.print(out, \"Loading matrix:\");\n      else\n        out << \"Loading matrix:\" << std::endl;\n    }\n    if (info == 2) {\n      // W.print(out, \"E[L'L] matrix:\");\n      s.print(out, \"Residual standard deviation of data columns:\");\n      if (n_updates > 0) {\n        alpha.print(out, \"Dirichlet parameter for factor pairs:\");\n        out << \"log lower bound:\" << std::endl;\n        for (size_t i = 0; i < lowerbound.size(); ++i) {\n          out << lowerbound[i] << \", \";\n        }\n        out << std::endl;\n      }\n    }\n  }\n\n private:\n  // Dirichlet priors for factors and grids\n  double alpha0;\n  // K by K matrix of digamma of variational parameter for factor pair\n  // frequencies\n  arma::mat digamma_alpha;\n  arma::mat alpha;\n  double digamma_sum_alpha;\n  size_t maxiter;\n  double tol;\n  std::vector<double> lowerbound;\n};\n#endif\n", "meta": {"hexsha": "11086ca2444623d0688dd840b0b4fbc55482f9b7", "size": 11549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pfa.hpp", "max_stars_repo_name": "gaow/pfar", "max_stars_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-20T20:16:08.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-14T19:16:25.000Z", "max_issues_repo_path": "src/pfa.hpp", "max_issues_repo_name": "gaow/pfar", "max_issues_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-15T03:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-12T21:59:19.000Z", "max_forks_repo_path": "src/pfa.hpp", "max_forks_repo_name": "gaow/pfar", "max_forks_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_forks_repo_licenses": ["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.8725, "max_line_length": 80, "alphanum_fraction": 0.572517101, "num_tokens": 3476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6591252121184943}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <ctime>\n#include <armadillo>\n#include \"boost/program_options.hpp\"\n\nusing namespace std;\nusing namespace arma;\nnamespace po = boost::program_options;\n\n// m: numRows, n: numCols\ninline double simpleDenseTest_Arma(int m, int n, int num_trials) {\n\n  mat A = randu<mat>(m, n);\n  mat B = randu<mat>(m, n);\n  mat C = randu<mat>(m, n);\n  mat D = randu<mat>(m, n);\n  mat E = randu<mat>(m, n);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    mat res = ((A + B) / C - D) % E;\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmSanityTest_Arma(int m, int n, int k, int num_trials) {\n\n  mat A = randu<mat>(m, n);\n  mat C = randu<mat>(n, k);\n  mat E = randu<mat>(m, k);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E += A * C;\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n  return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmDenseTest_Arma(int m, int n, int k, int num_trials) {\n\n  mat A = randu<mat>(m, n);\n  mat B = randu<mat>(m, n);\n  mat C = randu<mat>(n, k);\n  mat D = randu<mat>(n, k);\n  mat E = randu<mat>(m, k);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E += (A + B) * (C - D);\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  \n  return duration / num_trials;\n\n}\n\ninline double mulDenseTest_Arma(int a, int b, int c, int d, int num_trials) {\n\n  mat A = randu<mat>(a, a);\n  mat B = randu<mat>(a, b);\n  mat C = randu<mat>(b, c);\n  mat D = randu<mat>(c, d);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    mat res = A * B * C * D;\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double denseVectorTest_Arma(int l, int num_trials) {\n\n  vec a = randu<vec>(l);\n  vec b = randu<vec>(l);\n  vec c = randu<vec>(l);\n  vec d = randu<vec>(l);\n  vec e = randu<vec>(l);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n    e = a + b + c + d;\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n  return duration / num_trials;\n}\n\nvoid runArmaTests(int num_trials, int l, int m, int n, int k, int a, int b, int c, int d, \n    bool skip_vec, bool skip_simple, bool skip_gemm, bool skip_mult) {\n\n  if (!skip_vec)\n    cout << \"Armadillo Vectors Test:\\t\" << denseVectorTest_Arma(l, num_trials) << endl;\n  if (!skip_simple)\n    cout << \"Armadillo Simple Test:\\t\" << simpleDenseTest_Arma(m, n, num_trials) << endl;\n  if (!skip_gemm) {\n    cout << \"Armadillo gemmSanity Test:\\t\" << gemmDenseTest_Arma(m, n, k, num_trials) << endl;\n    cout << \"Armadillo gemm Test:\\t\" << gemmDenseTest_Arma(m, n, k, num_trials) << endl;\n  }\n  if (!skip_mult)\n    cout << \"Armadillo mulDense Test:\\t\" << mulDenseTest_Arma(a, b, c, d, num_trials) << endl;\n\n}\n\nint main(int argc, char *argv[]) {\n\n    int l, m, n, k, a, b, c, d, trials;\n    bool skip_vec, skip_simple, skip_gemm, skip_mult;\n    \n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"l\", po::value<int>(&l)->default_value(1048576),\n                    \"length of vectors in vector addition test\")\n        (\"m\", po::value<int>(&m)->default_value(1024),\n            \"numRows of matrices in Simple Test, and gemm Test\")\n        (\"n\", po::value<int>(&n)->default_value(1024),\n            \"numCols of matrices in Simple Test, and gemm Test\")\n        (\"k\", po::value<int>(&k)->default_value(1024),\n            \"numCols of B in gemm Test\")\n        (\"trials\", po::value<int>(&trials)->default_value(10), \"number of trials\")\n        (\"a\", po::value<int>(&a)->default_value(1024),\n            \"size matrix A in mulDense Test\")\n        (\"b\", po::value<int>(&b)->default_value(512),\n            \"size matrix B in mulDense Test\")\n        (\"c\", po::value<int>(&c)->default_value(256),\n            \"size matrix C in mulDense Test\")\n        (\"d\", po::value<int>(&d)->default_value(128),\n            \"size matrix D in mulDense Test\")\n        (\"skip-vec\", po::value<bool>(&skip_vec)->default_value(false),\n            \"skip vectors Test\")\n        (\"skip-simple\", po::value<bool>(&skip_simple)->default_value(false),\n            \"skip simple Test\")\n        (\"skip-gemm\", po::value<bool>(&skip_gemm)->default_value(false),\n            \"skip gemm Tests\")\n        (\"skip-mult\", po::value<bool>(&skip_mult)->default_value(false),\n            \"skip mulDense Test\")\n    ;\n    \n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    runArmaTests(trials, l, m, n, k, a, b, c, d, skip_vec, skip_simple, skip_gemm, skip_mult);\n\n    return 0;\n}\n", "meta": {"hexsha": "cdf3a1a3cfbdb08f4311752724cd14fd59f760ff", "size": 5064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/arma.cpp", "max_stars_repo_name": "brkyvz/linalg-benchmarks", "max_stars_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "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/main/cpp/arma.cpp", "max_issues_repo_name": "brkyvz/linalg-benchmarks", "max_issues_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "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/main/cpp/arma.cpp", "max_forks_repo_name": "brkyvz/linalg-benchmarks", "max_forks_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7882352941, "max_line_length": 94, "alphanum_fraction": 0.5963665087, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6591252045473374}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix4d X = Matrix4d::Random(4,4);\nMatrix4d A = X + X.transpose();\ncout << \"Here is a random symmetric 4x4 matrix:\" << endl << A << endl;\nTridiagonalization<Matrix4d> triOfA(A);\nMatrix4d pm = triOfA.packedMatrix();\ncout << \"The packed matrix M is:\" << endl << pm << endl;\ncout << \"The diagonal and subdiagonal corresponds to the matrix T, which is:\" \n     << endl << triOfA.matrixT() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "86e5a8913a23c2ee5510ac75e26e5e5ad676bcdc", "size": 545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_packedMatrix.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_packedMatrix.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_packedMatrix.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.9523809524, "max_line_length": 78, "alphanum_fraction": 0.6697247706, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6590870220471323}}
{"text": "#include \"include/MMVII_all.h\"\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace MMVII\n{\n\n// return the variance of  exponential distribution of parameter \"a\" ( i.e proportiona to  \"a^|x|\")\ndouble Sigma2FromFactExp(double a)\n{\n   return (2*a) / Square(1-a);\n}\n\n// return the value of \"a\" such that  exponential distribution of parameter \"a\" has variance S2\n// i.e. this the \"inverse\" function of Sigma2FromFactExp\n\ndouble FactExpFromSigma2(double aS2)\n{\n    return (aS2+1 - sqrt(Square(aS2+1)-Square(aS2))  ) / aS2 ;\n}\n\n\n/* *********************************************** */\n/*                                                 */\n/*        cComputeStdDev<Dim>                     */\n/*                                                 */\n/* *********************************************** */\n\n#if (0)\n///  Class to compute non biased variance from a statisic \n\n/** Class to compute non biased variance from a statisic\n    This generalise the standard formula\n            EstimVar = N/(N-1) EmpirVar\n    To the case where there is a weighting.\n\n    It can be uses with N variable to factorize the computation on Weight\n */\n\ntemplate <const int Dim> class cComputeStdDev\n{\n    public :\n        typedef  double tTab[Dim];\n\n        cComputeStdDev();\n\n        void Add(const  double * aVal,const double & aPds);\n        const double  *  ComputeUnBiasedVar() ;\n        const double  *  ComputeBiasedVar() ;\n        double  DeBiasFactor() const;\n\n    private :\n        double    mSomW; ///< Sum of Weight\n        double    mSomWW; ///< Sum of Weight ^2\n        tTab      mSomWV;  ///< Weighted som of vals\n        tTab      mSomWVV; ///< Weighted som of vals ^2\n        tTab      mVar;   ///< Buffer to compute the unbiased variance\n        tTab      mBVar;   ///< Buffer to compute the empirical variance\n};\n#endif\n\ntemplate  <const int Dim> cComputeStdDev<Dim>::cComputeStdDev() :\n    mSomW   (0.0),\n    mSomWW  (0.0)\n{\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        mSomWV[aD] = 0.0;\n        mSomWVV[aD] = 0.0;\n    }\n}\n\ntemplate  <const int Dim> void cComputeStdDev<Dim>::Add(const  double *  aVal,const double & aPds)\n{\n    mSomW += aPds;\n    mSomWW += Square(aPds);\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        mSomWV[aD] += aPds * aVal[aD];\n        mSomWVV[aD] += aPds * Square(aVal[aD]);\n    }\n}\ntemplate  <const int Dim>  double cComputeStdDev<Dim>::DeBiasFactor() const\n{\n    MMVII_INTERNAL_ASSERT_strong(mSomW>0,\"No value in DeBiasFactor\");\n    return   1 - mSomWW/Square(mSomW);\n}\n\ntemplate  <const int Dim> bool    cComputeStdDev<Dim>::OkForUnBiasedVar() const\n{\n   return (mSomW>0)  && (DeBiasFactor()!=0);\n}\n\ntemplate  <const int Dim> const double *   cComputeStdDev<Dim>::ComputeUnBiasedVar()\n{\n    /* At least, this formula is correct :\n         - when all weight are equal => 1-1/N\n         - when all but one weight are 0 => 0 \n         - and finally if all are equal or 0\n    */\n    double aDebias = DeBiasFactor();\n    MMVII_INTERNAL_ASSERT_strong(aDebias>0,\"No var can be computed in ComputeVar\");\n\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        double aAver = mSomWV[aD] / mSomW;\n        double aVar  = mSomWVV[aD] / mSomW;\n        aVar = aVar - Square(aAver);\n        mVar[aD] = std::max(0.0,aVar) /aDebias;\n    }\n\n   return mVar;\n}\n\ntemplate  <const int Dim> const double *   cComputeStdDev<Dim>::ComputeBiasedVar()\n{\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        double aAver = mSomWV[aD] / mSomW;\n        double aVar  = mSomWVV[aD] / mSomW;\n        aVar = aVar - Square(aAver);\n        mBVar[aD] = std::max(0.0,aVar);\n    }\n\n   return mBVar;\n}\n\n\n\n\n\ntemplate class cComputeStdDev<1>;\n\nvoid BenchUnbiasedStdDev()\n{\n    for (int aNbTest = 0 ; aNbTest<1000 ; aNbTest++)\n    {\n         int aNbVar = 1 + RandUnif_N(3);\n         int aNbTir = aNbVar;\n         int aNbComb = pow(aNbVar,aNbTir);\n         std::vector<double> aVecVals = VRandUnif_0_1(aNbVar);\n         std::vector<double> aVecWeight = VRandUnif_0_1(aNbVar);\n// aVecWeight =  std::vector<double> (aNbVar,1.0);\n\n         // compute the average of all empirical variance\n         double aMoyVar=0;\n         for (int aFlag=0 ; aFlag < aNbComb ; aFlag++) // Explore all combinaison\n         {\n             cComputeStdDev<1> aUBS;\n             for (int aVar=0 ; aVar < aNbVar ; aVar++) // All Variable of this realization\n             {\n                 int aNumVar = (aFlag / round_ni(pow(aNbVar,aVar))) % aNbVar; // \"Majic\" formula to exdtrac p-adic decomp\n                 aUBS.Add(&(aVecVals.at(aNumVar)),aVecWeight.at(aNumVar));\n             }\n             aMoyVar += aUBS.ComputeBiasedVar()[0];\n         }\n         aMoyVar /= aNbComb;\n\n         cComputeStdDev<1> aUBS;\nStdOut() << \"WWW=\" ;\n         for (int aK=0 ; aK<aNbVar ; aK++)\n         {\nStdOut() << \" \" << aVecWeight.at(aK) ;\n            aUBS.Add(&(aVecVals.at(aK)),aVecWeight.at(aK));\n         }\nStdOut() << \"\\n\" ;\n         StdOut() << \"MOYVAR \" << aMoyVar <<  \" \" <<  aUBS.DeBiasFactor() *  aUBS.ComputeBiasedVar()[0] \n                  << \" DBF=\" <<  aUBS.DeBiasFactor() << \"\\n\";\ngetchar();\n    }\n}\n\n/* *********************************************** */\n/*                                                 */\n/*            Test Exp Filtre                      */\n/*                                                 */\n/* *********************************************** */\n\n// Test Sigma2FromFactExp\ntemplate <class Type> void TestVarFilterExp(cPt2di aP0,cPt2di aP1,const Type & aV0,double aFx,double aFy,int aNbIt)\n{\n   cPt2di aPMil = (aP0+aP1) / 2;\n   cRect2 aRect2(aP0,aP1);\n\n   cIm2D<Type> aIm(aP0,aP1,nullptr,eModeInitImage::eMIA_Null);\n   cDataIm2D<Type> & aDIm = aIm.DIm();\n\n   // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n   aDIm.InitDirac(aPMil,aV0);\n\n   ExponentialFilter(true,aDIm,aNbIt,aRect2,aFx,aFy);\n   cMatIner2Var<double>  aMat = StatFromImageDist(aDIm);\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S1() - aPMil.x()) < 1e-5  ,\"Average Exp\")\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S2() - aPMil.y()) < 1e-5  ,\"Average Exp\")\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Sigma2FromFactExp(aFx) * aNbIt)<1e-5,\"Var Exp\");\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S22()-Sigma2FromFactExp(aFy) * aNbIt)<1e-5,\"Var Exp\");\n}\n\n\n\ntemplate <class Type> void TestVarFilterExp(cPt2di aSz,double aStdDev,int aNbIter,double aEps)\n{\n   cIm2D<Type> aIm(cPt2di(0,0),aSz,nullptr,eModeInitImage::eMIA_Null);\n   cDataIm2D<Type> & aDIm = aIm.DIm();\n   cPt2di aPMil = aSz / 2;\n   double aV0 = 2.0;\n\n   // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n   aDIm.InitDirac(aPMil,aV0);\n\n   ExpFilterOfStdDev(aDIm,aNbIter,aStdDev);\n   cMatIner2Var<double>  aMat = StatFromImageDist(aDIm);\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Square(aStdDev))<aEps,\"Std dev\");\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S22()-Square(aStdDev))<aEps,\"Std dev\");\n}\n\nvoid BenchStat()\n{\n   TestVarFilterExp<double>(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,1);\n   TestVarFilterExp<double>(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,3);\n\n   // Test Sigma2FromFactExp\n   for (int aK=1 ; aK<100 ; aK++)\n   {\n        double aS2 = aK / 5.0;\n        double aF = FactExpFromSigma2(aS2);\n        {\n           // Check both formula are inverse of each others\n           double aCheckS2 = Sigma2FromFactExp(aF);\n           MMVII_INTERNAL_ASSERT_bench(std::abs( aS2 - aCheckS2 ) < 1e-5  ,\"Sigma2FromFactExp\")\n         \n        }\n        {\n           // Check formula Sigma2FromFactExp on exponential filters\n           TestVarFilterExp<double>(cPt2di(0,0),cPt2di(4000,3),2.0,aF,0,1);\n        }\n   }\n\n   TestVarFilterExp<double>(cPt2di(300,300),2.0,2,1e-6);\n   TestVarFilterExp<float>(cPt2di(300,300),5.0,3,1e-3);\n}\n\n\n\n};\n\n", "meta": {"hexsha": "adc3d8908d740a266eda2424b0ec1d97ae721e70", "size": 7722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_stars_repo_name": "nguyenign/micmac4wasm", "max_stars_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T06:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:20:23.000Z", "max_issues_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_issues_repo_name": "nguyenign/micmac4wasm", "max_issues_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_forks_repo_name": "nguyenign/micmac4wasm", "max_forks_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-07T08:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-07T08:29:49.000Z", "avg_line_length": 31.0120481928, "max_line_length": 121, "alphanum_fraction": 0.5788655789, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.659086997479158}}
{"text": "\n#define _wassert wassert_awf\n#include <cassert>\n#define _USE_MATH_DEFINES \n#include <cmath>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Eigen>\n#include <Eigen/SparseQR>\n\n#include \"eigen_extras.h\"\n\n#include <unsupported/Eigen/LevenbergMarquardt>\n#include <unsupported/Eigen/SparseExtra>\n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n#include \"MeshTopology.h\"\n#include \"SubdivEvaluator.h\"\n#include \"log3d.h\"\n\nusing namespace Eigen;\n\nstruct Subdiv3D_Functor : Eigen::SparseFunctor<Scalar>\n{\n  typedef Eigen::SparseFunctor<Scalar> Base;\n  typedef typename Base::JacobianType JacobianType;\n\n  // Input data\n  Matrix3X data_points;\n\n  // Topology (faces as vertex indices, fixed during shape optimization)\n  MeshTopology mesh;\n\n  SubdivEvaluator evaluator;\n\n  // Functor constructor\n  Subdiv3D_Functor(const Matrix3X& data_points, const MeshTopology& mesh) :\n    Base(mesh.num_vertices*3 + data_points.cols()*2,   /* number of parameters */\n         data_points.cols()*3),                        /* number of residuals */\n    data_points(data_points), \n    mesh(mesh),\n    evaluator(mesh)\n  {\n    initWorkspace();\n  }\n\n  // Variables for optimization live in InputType\n  struct InputType {\n    Matrix3X control_vertices;\n    std::vector<SurfacePoint> us;\n\n    Index nVertices() const { return control_vertices.cols();  }\n  };\n\n  // And the optimization steps are computed using VectorType.\n  // For subdivs (see xx), the correspondences are of type (int, Vec2) while the updates are of type (Vec2).\n  // The iteractions between InputType and VectorType are restricted to:\n  //   The Jacobian computation takeas an InputType, and its worows must easily convert to VectorType\n  //   The increment_in_place operation takes InputType and StepType. \n  typedef VectorX VectorType;\n\n  // Workspace variables for evaluation\n  Matrix3X S;\n  Matrix3X dSdu;\n  Matrix3X dSdv;\n  SubdivEvaluator::triplets_t dSdX, dSudX, dSvdX;\n  void initWorkspace()\n  {\n    Index nPoints = data_points.cols();\n    S.resize(3, nPoints);\n    dSdu.resize(3, nPoints);\n    dSdv.resize(3, nPoints);\n  }\n\n  // Functor functions\n  // 1. Evaluate the residuals at x\n  int operator()(const InputType& x, ValueType& fvec) {\n    evaluator.evaluateSubdivSurface(x.control_vertices, x.us, &S);\n\n    // Fill residuals\n    for (int i = 0; i < data_points.cols(); i++)\n      fvec.segment(i * 3, 3) = S.col(i) - data_points.col(i);\n\n    return 0;\n  }\n\n  // 2. Evaluate jacobian at x\n  int df(const InputType& x, JacobianType& fjac) \n  {\n    // Evaluate surface at x\n    evaluator.evaluateSubdivSurface(x.control_vertices, x.us, &S, &dSdX, &dSudX, &dSvdX, &dSdu, &dSdv);\n\n    Index nPoints = data_points.cols();\n    Index X_base = nPoints * 2;\n    Index ubase = 0;\n\n    // Fill Jacobian columns.  \n    // 1. Derivatives wrt control vertices.\n    Eigen::TripletArray<Scalar, typename JacobianType::Index> jvals(nPoints * 3 * 3);\n    for (int i = 0; i < dSdX.size(); ++i) {\n      auto const& triplet = dSdX[i];\n      assert(0 <= triplet.row() && triplet.row() < nPoints);\n      assert(0 <= triplet.col() && triplet.col() < x.nVertices());\n      jvals.add(triplet.row() * 3 + 0, X_base + triplet.col() * 3 + 0, triplet.value());\n      jvals.add(triplet.row() * 3 + 1, X_base + triplet.col() * 3 + 1, triplet.value());\n      jvals.add(triplet.row() * 3 + 2, X_base + triplet.col() * 3 + 2, triplet.value());\n    }\n\n    // 2. Derivatives wrt correspondences\n    for (int i = 0; i < nPoints; i++) {\n      jvals.add(3 * i + 0, ubase + 2 * i + 0, dSdu(0, i));\n      jvals.add(3 * i + 1, ubase + 2 * i + 0, dSdu(1, i));\n      jvals.add(3 * i + 2, ubase + 2 * i + 0, dSdu(2, i));\n\n      jvals.add(3 * i + 0, ubase + 2 * i + 1, dSdv(0, i));\n      jvals.add(3 * i + 1, ubase + 2 * i + 1, dSdv(1, i));\n      jvals.add(3 * i + 2, ubase + 2 * i + 1, dSdv(2, i));\n    }\n\n    fjac.resize(3 * nPoints, 2 * nPoints + 3 * x.nVertices());\n    fjac.setFromTriplets(jvals.begin(), jvals.end());\n    fjac.makeCompressed();\n\n    return 0;\n  }\n\n  void increment_in_place(InputType* x, StepType const& p)\n  {\n    Index nPoints = data_points.cols();\n    Index X_base = nPoints * 2;\n    Index ubase = 0;\n\n    // Increment control vertices\n    Index nVertices = x->nVertices();\n\n    assert(p.size() == nVertices * 3 + nPoints * 2);\n    assert(x->us.size() == nPoints);\n\n    Map<VectorX>(x->control_vertices.data(), nVertices * 3) += p.tail(nVertices * 3);\n    \n    // Increment surface correspondences\n    int loopers = 0;\n    int totalhops = 0;\n    for (int i = 0; i < nPoints; ++i) {\n      Vector2 du = p.segment<2>(ubase + 2 * i);\n      int nhops = increment_u_crossing_edges(x->control_vertices, x->us[i].face, x->us[i].u, du, &x->us[i].face, &x->us[i].u);\n      if (nhops < 0)\n        ++loopers;\n      totalhops += std::abs(nhops);\n    }\n    if (loopers > 0)\n      std::cerr << \"[\" << totalhops / Scalar(nPoints) << \" hops, \" << loopers << \" points looped]\";\n    else if (totalhops > 0)\n      std::cerr << \"[\" << totalhops << \"/\"  << Scalar(nPoints) << \" hops]\";\n  }\n\n  // \"Mesh walking\" to update correspondences, as in Fig 3, Taylor et al, CVPR 2014, \"Hand shape..\"\n  int increment_u_crossing_edges(Matrix3X const& X, int face, const Vector2& u, const Vector2& du, int* new_face_out, Vector2* new_u_out)\n  {\n    const int MAX_HOPS = 7;\n\n    Scalar u1_old = u[0];\n    Scalar u2_old = u[1];\n    Scalar du1 = du[0];\n    Scalar du2 = du[1];\n    Scalar u1_new = u1_old + du1;\n    Scalar u2_new = u2_old + du2;\n\n    for (int count = 0; ; ++count) {\n      bool crossing = (u1_new < 0.f) || (u1_new > 1.f) || (u2_new < 0.f) || (u2_new > 1.f);\n\n      if (!crossing) {\n        *new_face_out = face;\n        *new_u_out << u1_new, u2_new;\n        return count;\n      }\n\n      //Find the new face\tand the coordinates of the crossing point within the old face and the new face\n      int face_new;\n\n      bool face_found = false;\n\n      Scalar dif, aux, u1_cross, u2_cross;\n\n      if (u1_new < 0.f)\n      {\n        dif = u1_old;\n        const Scalar u2t = u2_old - du2*dif / du1;\n        if ((u2t >= 0.f) && (u2t <= 1.f))\n        {\n          face_new = mesh.face_adj(3, face); aux = u2t; face_found = true;\n          u1_cross = 0.f; u2_cross = u2t;\n        }\n      }\n      if ((u1_new > 1.f) && (!face_found))\n      {\n        dif = 1.f - u1_old;\n        const Scalar u2t = u2_old + du2*dif / du1;\n        if ((u2t >= 0.f) && (u2t <= 1.f))\n        {\n          face_new = mesh.face_adj(1, face); aux = 1.f - u2t; face_found = true;\n          u1_cross = 1.f; u2_cross = u2t;\n        }\n      }\n      if ((u2_new < 0.f) && (!face_found))\n      {\n        dif = u2_old;\n        const Scalar u1t = u1_old - du1*dif / du2;\n        if ((u1t >= 0.f) && (u1t <= 1.f))\n        {\n          face_new = mesh.face_adj(0, face); aux = 1.f - u1t; face_found = true;\n          u1_cross = u1t; u2_cross = 0.f;\n        }\n      }\n      if ((u2_new > 1.f) && (!face_found))\n      {\n        dif = 1.f - u2_old;\n        const Scalar u1t = u1_old + du1*dif / du2;\n        if ((u1t >= 0.f) && (u1t <= 1.f))\n        {\n          face_new = mesh.face_adj(2, face); aux = u1t; face_found = true;\n          u1_cross = u1t; u2_cross = 1.f;\n        }\n      }\n      assert(face_found);\n\n      // Find the coordinates of the crossing point as part of the new face, and update u_old (as that will be new u in next iter).\n      unsigned int conf;\n      for (unsigned int f = 0; f < 4; f++)\n        if (mesh.face_adj(f, face_new) == face) { conf = f; }\n\n      switch (conf)\n      {\n      case 0: u1_old = aux; u2_old = 0.f; break;\n      case 1: u1_old = 1.f; u2_old = aux; break;\n      case 2:\tu1_old = 1.f - aux; u2_old = 1.f; break;\n      case 3:\tu1_old = 0.f; u2_old = 1.f - aux; break;\n      }\n\n      // Evaluate the subdivision surface at the edge (with respect to the original face)\n      std::vector<SurfacePoint> pts;\n      pts.push_back({ face,{ u1_cross, u2_cross } });\n      pts.push_back({ face_new, { u1_old, u2_old } });\n      Matrix3X S(3, 2);\n      Matrix3X Su(3, 2);\n      Matrix3X Sv(3, 2);\n      evaluator.evaluateSubdivSurface(X, pts, &S, 0, 0, 0, &Su, &Sv);\n\n      Matrix<Scalar, 3, 2> J_Sa;\n      J_Sa.col(0) = Su.col(0);\n      J_Sa.col(1) = Sv.col(0);\n\n      Matrix<Scalar, 3, 2> J_Sb;\n      J_Sb.col(0) = Su.col(1);\n      J_Sb.col(1) = Sv.col(1);\n\n      //Compute the new u increments\n      Vector2 du_remaining; \n      du_remaining << u1_new - u1_cross, u2_new - u2_cross;\n      Vector3 prod = J_Sa*du_remaining;\n      Matrix22 AtA = J_Sb.transpose()*J_Sb;\n      Vector2 AtB = J_Sb.transpose()*prod;\n\n      //Vector2 du_new = AtA.ldlt().solve(AtB);\n      Vector2  u_incr = AtA.inverse()*AtB;\n\n      du1 = u_incr[0];\n      du2 = u_incr[1];\n\n      if (count == MAX_HOPS) {\n        //std::cerr << \"Problem!!! Many jumps between the mesh faces for the update of one correspondence. I remove the remaining u_increment!\\n\";\n        auto dmax = std::max(du1, du2);\n        Scalar scale = Scalar(0.5 / dmax);\n        *new_face_out = face;\n        //*new_u_out << u1_old + du1 * scale, u2_old + du2 * scale;\n        *new_u_out << 0.5, 0.5;\n\n        assert((*new_u_out)[0] >= 0 && (*new_u_out)[1] <= 1.0 && (*new_u_out)[1] >= 0 && (*new_u_out)[1] <= 1.0);\n        return -count;\n      }\n\n      u1_new = u1_old + du1;\n      u2_new = u2_old + du2;\n      face = face_new;\n    }\n  }\n\n  Scalar estimateNorm(InputType const& x, StepType const& diag)\n  {\n    Index nVertices = x.nVertices();\n    Map<VectorX> xtop{ (Scalar*)x.control_vertices.data(), nVertices * 3 };\n    double total = xtop.cwiseProduct(diag.tail(nVertices*3)).stableNorm();\n    total = total*total;\n    for (int i = 0; i < x.us.size(); ++i) {\n      Vector2 const& u = x.us[i].u;\n      Vector2 di = diag.segment<2>(2 * i);\n      total += u.cwiseProduct(di).squaredNorm();\n    }\n    return Scalar(sqrt(total));\n  }\n\n  // 5. Describe the QR solvers\n  // For generic Jacobian, one might use this Dense QR solver.\n  typedef SparseQR<JacobianType, COLAMDOrdering<int> > GeneralQRSolver;\n\n  // But for optimal performance, declare QRSolver that understands the sparsity structure.\n  // Here it's block-diagonal LHS with dense RHS\n  //\n  // J1 = [J11   0   0 ... 0\n  //         0 J12   0 ... 0\n  //                   ...\n  //         0   0   0 ... J1N];\n  // And \n  // J = [J1 J2];\n\n  // QR for J1 subblocks is 2x1\n  typedef ColPivHouseholderQR<Matrix<Scalar, 3, 2> > DenseQRSolver3x2;\n\n  // QR for J1 is block diagonal\n  typedef BlockDiagonalSparseQR<JacobianType, DenseQRSolver3x2> LeftSuperBlockSolver;\n\n  // QR for J1'J2 is general dense (faster than general sparse by about 1.5x for n=500K)\n  typedef ColPivHouseholderQR<Matrix<Scalar, Dynamic, Dynamic> > RightSuperBlockSolver;\n\n  // QR for J is concatenation of the above.\n  typedef BlockSparseQR<JacobianType, LeftSuperBlockSolver, RightSuperBlockSolver> SchurlikeQRSolver;\n\n  typedef SchurlikeQRSolver QRSolver;\n\n  // And tell the algorithm how to set the QR parameters.\n  void initQRSolver(SchurlikeQRSolver &qr) {\n    // set block size\n    qr.setBlockParams(data_points.cols() * 2);\n    qr.getLeftSolver().setSparseBlockParams(3, 2);\n  }\n};\n\nvoid logmesh(log3d& log, MeshTopology const& mesh, Matrix3X const& vertices)\n{\n  Matrix3Xi tris(3, mesh.quads.cols() * 2);\n  tris.block(0, 0, 1, mesh.quads.cols()) = mesh.quads.row(0);\n  tris.block(1, 0, 1, mesh.quads.cols()) = mesh.quads.row(2);\n  tris.block(2, 0, 1, mesh.quads.cols()) = mesh.quads.row(1);\n  tris.block(0, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(0);\n  tris.block(1, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(3);\n  tris.block(2, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(2);\n  log.mesh(tris, vertices);\n}\n\nvoid logsubdivmesh(log3d& log, MeshTopology const& mesh, Matrix3X const& vertices)\n{\n  log.wiremesh(mesh.quads, vertices);\n  SubdivEvaluator evaluator(mesh);\n  MeshTopology refined_mesh;\n  Matrix3X refined_verts;\n  evaluator.generate_refined_mesh(vertices, 3, &refined_mesh, &refined_verts);\n  logmesh(log, refined_mesh, refined_verts);\n}\n\nint main()\n{\n  std::cout << \"Go\\n\";\n  log3d log(\"log3d.html\", \"fit-subdiv-to-3d-points\");\n  log.ArcRotateCamera();\n  log.axes();\n\n  // CREATE DATA SAMPLES\n  int nDataPoints = 200;\n  Matrix3X data(3, nDataPoints);\n  for (int i = 0; i < nDataPoints; i++) {\n    if (0) {\n      float t = float(i) / float(nDataPoints);\n      data(0, i) = 0.1f + 1.3f*cos(80*t);\n      data(1, i) = -0.2f + 0.7f*sin(80*t);\n      data(2, i) = t;\n    }\n    else {\n      Scalar t = rand() / Scalar(RAND_MAX);\n      Scalar s = rand() / Scalar(RAND_MAX);\n\n      auto u = Scalar(2 * EIGEN_PI * t);\n      auto v = Scalar(EIGEN_PI * (s - 0.5));\n      data(0, i) = 0.1f + 1.3f*cos(u)*cos(v);\n      data(1, i) = -0.2f + 0.7f*sin(u)*cos(v);\n      data(2, i) = sin(v);\n    }\n    if (1)\n      log.position(log.CreateSphere(0, 0.02), data(0, i), data(1, i), data(2, i));\n    else\n      log.star(data.col(i));\n  }\n  \n\n  MeshTopology mesh;\n  Matrix3X control_vertices_gt;\n  makeCube(&mesh, &control_vertices_gt);\n  int nFaces = int(mesh.quads.cols());\n\n  // INITIAL PARAMS\n  typedef Subdiv3D_Functor Functor;\n  \n  Functor::InputType params;\n  params.control_vertices = control_vertices_gt + 0.1 * MatrixXX::Random(3, control_vertices_gt.cols());\n  params.us.resize(nDataPoints);\n\n  // Initialize uvs.\n  {\n    // 1. Make a list of test points, e.g. centre point of each face\n    Matrix3X test_points(3, nFaces);\n    std::vector<SurfacePoint> uvs{ size_t(nFaces),{ 0,{ 0.5, 0.5 } } };\n    for (int i = 0; i < nFaces; ++i)\n      uvs[i].face = i;\n\n    SubdivEvaluator evaluator(mesh);\n    evaluator.evaluateSubdivSurface(params.control_vertices, uvs, &test_points);\n\n    for (int i = 0; i < nDataPoints; i++) {\n      // Closest test point\n      Eigen::Index test_pt_index;\n      (test_points.colwise() - data.col(i)).colwise().squaredNorm().minCoeff(&test_pt_index);\n      params.us[i] = uvs[test_pt_index];\n    }\n  }\n\n  logsubdivmesh(log, mesh, params.control_vertices);\n\n  Functor functor(data, mesh);\n\n  // Check Jacobian\n  if (0)\n  for (float eps = 1e-8f; eps < 1.1e-3f; eps*=10.f) {\n    NumericalDiff<Functor> fd{ functor, Functor::Scalar(eps) };\n    Functor::JacobianType J;\n    Functor::JacobianType J_fd;\n    functor.df(params, J);\n    fd.df(params, J_fd);\n    double diff = (J - J_fd).norm();\n    if (diff > 0) {\n      std::cerr << \"Jacobian diff(eps=\" << eps <<\"), = \" << diff << std::endl;\n      write(J, \"c:\\\\tmp\\\\J.txt\");\n      write(J_fd, \"c:\\\\tmp\\\\J_fd.txt\");\n    }\n  }\n\n  Eigen::LevenbergMarquardt< Functor > lm(functor);\n  lm.setVerbose(true);\n  lm.setMaxfev(10);\n\n  Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n  log.color(0, 1, 0);\n  logsubdivmesh(log, mesh, params.control_vertices);\n\n  std::cerr << \"Done: err = \"<< lm.fnorm() <<\"\\n\";\n\n  // Now, on a refined mesh.\n  if (1) {\n    log.color(.5, .8, 0);\n\n    MeshTopology mesh1;\n    Matrix3X verts1;\n    SubdivEvaluator evaluator(mesh);\n    evaluator.generate_refined_mesh(params.control_vertices, 1, &mesh1, &verts1);\n    \n    {\n      log3d log2(\"log2.html\");\n      log2.ArcRotateCamera();\n      log2.axes();\n      log2.wiremesh(mesh1.quads, verts1);\n    }\n\n    params.control_vertices = verts1;\n\n    // Initialize uvs.\n    {\n      // 1. Make a list of test points, e.g. centre point of each face\n      int nFaces = mesh1.num_faces();\n      Matrix3X test_points(3, nFaces);\n      std::vector<SurfacePoint> uvs{ size_t(nFaces),{ 0,{ 0.5, 0.5 } } };\n      for (int i = 0; i < nFaces; ++i)\n        uvs[i].face = i;\n\n      SubdivEvaluator evaluator(mesh1);\n      evaluator.evaluateSubdivSurface(params.control_vertices, uvs, &test_points);\n\n      for (int i = 0; i < nDataPoints; i++) {\n        // Closest test point\n        Eigen::Index test_pt_index;\n        (test_points.colwise() - data.col(i)).colwise().squaredNorm().minCoeff(&test_pt_index);\n        params.us[i] = uvs[test_pt_index];\n      }\n    }\n\n\n    Functor functor1(data, mesh1);\n\n    Eigen::LevenbergMarquardt< Functor > lm(functor1);\n    lm.setVerbose(true);\n    lm.setMaxfev(40);\n\n    Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n    logsubdivmesh(log, mesh1, params.control_vertices);\n\n    std::cerr << \"Done: err = \" << lm.fnorm() << \"\\n\";\n  }\n}\n\n// Override system assert so one can set a breakpoint in it rather than clicking \"Retry\" and \"Break\"\nvoid __cdecl _wassert(_In_z_ wchar_t const* _Message,_In_z_ wchar_t const* _File, _In_ unsigned _Line)\n{\n  std::wcerr << _File << \"(\" << _Line << \"): ASSERT FAILED [\" << _Message << \"]\\n\";\n\n  abort();\n}\n", "meta": {"hexsha": "a751adf0a6254460a70f41dbe65643d5d3a5e597", "size": 16540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_stars_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_stars_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-09-08T09:37:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:59:12.000Z", "max_issues_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_issues_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_issues_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T16:25:31.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-24T09:53:35.000Z", "max_forks_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_forks_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_forks_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-09-08T17:40:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T17:23:12.000Z", "avg_line_length": 31.9922630561, "max_line_length": 146, "alphanum_fraction": 0.6085852479, "num_tokens": 5293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6590603163780507}}
{"text": "#include <math/distributions/gammadistribution.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace QLExtension {\n\n\tInverseCumulativeGamma::InverseCumulativeGamma(Real shape, Real scale)\n\t\t: dist_(boost::math::gamma_distribution<>(shape, scale))\n\t{}\n\t\t\n\n\tReal InverseCumulativeGamma::operator()(Real x) const {\n\t\treturn boost::math::quantile(dist_, x);\n\t}\n}\n", "meta": {"hexsha": "080235fedf4b8c712be92ef656168f05d7fb5bf1", "size": 371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.cpp", "max_stars_repo_name": "qg0/EliteQuant_Excel", "max_stars_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:29:10.000Z", "max_issues_repo_path": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.cpp", "max_issues_repo_name": "qg0/EliteQuant_Excel", "max_issues_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "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": "CppCoreLibrary/QLExtension/math/distributions/gammadistribution.cpp", "max_forks_repo_name": "qg0/EliteQuant_Excel", "max_forks_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 24.7333333333, "max_line_length": 71, "alphanum_fraction": 0.7601078167, "num_tokens": 92, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6590156535862566}}
{"text": "/*\n * This example was gathered from Stack Overflow. Only small modification were introduced.\n *\n * Check here: https://stackoverflow.com/questions/35656237/dynamic-eigen-vectors-in-boostodeint\n *\n * Credit: Sjonnie (user nickname)\n */\n\n#include <iostream>\n#include <Eigen/Core>\n#include <cstdlib>\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n\nusing namespace boost::numeric::odeint;\n\ntypedef Eigen::VectorXd state_type;\n\nEigen::MatrixXd A;\n\nvoid ODE_function (const state_type &x, state_type &dxdt, const double &t)\n{\n    dxdt = A * x;\n}\n\nvoid write_states(const state_type &x, const double &t)\n{\n    std::cout << t << \"\\t\";\n    for (int i = 0; i < x.size(); i++)\n    {\n        std::cout << *(x.data()+i) << \"\\t\";\n    }\n    std::cout << std::endl;\n}\n\nint main()\n{\n    int nr_of_states = 10;\n    state_type x;\n\n    std::cout << \"Simulation with \" << nr_of_states << \" states\\n\";\n\n    x = state_type(nr_of_states);\n    A = Eigen::MatrixXd(nr_of_states, nr_of_states);\n\n    srand(365);\n\n    for (int i = 0; i < A.size(); i++)\n    {\n        *(A.data()+i) = ((double)rand()/(double)RAND_MAX);\n    }\n\n    for (int i = 0; i < x.size(); i++)\n    {\n        *(x.data()+i) = i;\n    }\n\n    typedef runge_kutta_dopri5<state_type, double, state_type, double, vector_space_algebra> stepper;\n    integrate_adaptive(stepper(), ODE_function, x, 0.0, 25.0, 0.1, write_states);\n\n    std::cout <<std::endl << \"final state vector: \" << std::endl << x << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "fee27fe4d64effccf925e02cdc8eb46b3ea187f3", "size": 1516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/standalones/dynamic_eigen.cpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "examples/boost/standalones/dynamic_eigen.cpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "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/boost/standalones/dynamic_eigen.cpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 23.6875, "max_line_length": 101, "alphanum_fraction": 0.6233509235, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.659015642336458}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n#include \"Adam.hpp\"\n\n#define EIGEN_MPL2_ONLY\nusing namespace Eigen;\nusing namespace std;\n\nAdam::Adam(int _N,int _d,MatrixXd _x,VectorXd _label,double _C,double _alpha,double _beta1,double _beta2,double _epsilon,double _lambda,int iter):\n  N(_N),\n  d(_d),\n  alpha(_alpha),\n  beta1(_beta1),\n  beta2(_beta2),\n  epsilon(_epsilon),\n  lambda(_lambda),\n  C(_C),\n  X(_x),\n  m(VectorXd::Zero(d)),\n  v(VectorXd::Zero(d)),\n  label(_label),\n  iteration(iter),\n  w(VectorXd::Zero(d))\n{}\n\ndouble Adam::Acc(vector<double>& pred,VectorXd &l){\n  int t =0;\n  double loss =0;\n  for(int i = 0; i< pred.size();i++){\n    loss += (l(i) - pred[i]) * (l(i) - pred[i]);\n    int s = pred[i] > 0.5 ? 1 : 0;\n    if(s == l(i)){\n      t++;\n    }\n  }\n  return (double)t/pred.size();\n}\n\nvoid Adam::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 tbeta = 1-(1-beta1) * pow(lambda,iter);\n          double grad = (pred - label(i)) * X(i,idx)+ C * w(idx);\n          m[idx] = tbeta * grad + (1-tbeta) * m[idx];\n          v[idx] = beta2*pow(grad,2) + (1-beta2) * v[idx];\n          double hat_m = m[idx]/(1-pow((1-beta1),iter+1));\n          double hat_v = v[idx]/(1-pow((1-beta2),iter+1));\n          w(idx) -= alpha*hat_m/(sqrt(hat_v) + epsilon);\n        }\n      }\n    }\n    vector<double> ret;\n    predict(X,label,ret);\n    iterscores.push_back(Acc(ret,label));\n  }\n}\n\ndouble Adam::sigma(const MatrixXd& _x, int i){\n  return sigmoid(_x.row(i).dot(w));\n}\n\ndouble Adam::sigmoid(double z){\n  return 1.0 / (1.0 + exp(-z));\n}\n\nvoid Adam::predict(MatrixXd& _x,VectorXd& _l,vector<double>& ret){\n  for(int i = 0; i < _x.rows(); i++){\n    ret.push_back(sigma(_x,i));\n  }\n}\n\n", "meta": {"hexsha": "20f253feb4c92757115340b85937ad909fb48127", "size": 1840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Adam.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": "Adam.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": "Adam.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": 24.2105263158, "max_line_length": 146, "alphanum_fraction": 0.564673913, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6590156407356154}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nint main()\n{\n  Eigen::MatrixXd xn;\n  Eigen::MatrixXd mu;\n  Eigen::VectorXi gk;\n  Eigen::VectorXi numk;\n  Eigen::MatrixXd::Index minIndex;\n  int ni;\n  int nn;\n  int kk;\n  int i;\n  int j;\n  int l;\n  int sum_gk;\n  int bef_sum_gk;\n\n  // after :: from file input\n  ni = 10;\n  kk = 3;\n\n  nn = ni*kk;\n  std::cout << \"nn \" <<  nn << std::endl;\n\n  xn = Eigen::MatrixXd::Random(2, nn);\n  gk = Eigen::VectorXi(nn);\n  numk = Eigen::VectorXi::Zero(kk);\n  std::cout << \"xn =\" << std::endl << xn << std::endl;\n\n  xn.block(0, nn/kk, 1, nn/kk).array() += 2.0;\n  xn.block(0, 2*nn/kk, 1, nn/kk).array() += 4.0;\n\n  mu = xn.block(0, 0, 2, kk);\n\n  std::cout << \"mu =\" << std::endl << mu << std::endl;\n\n  bef_sum_gk = 0;\n  for(i = 0; i < 100; i++){\n    std::cout << \"loop =\" << i << std::endl;\n    for(j = 0; j < nn; j++){\n\n// Is which better?\n      (mu.colwise() - xn.col(j)).colwise().squaredNorm().minCoeff(&minIndex);\n//      (xn.col(j).replicate(1, 3) - mu).colwise().squaredNorm().minCoeff(&minIndex);\n\n      gk(j) = minIndex;\n    }\n    numk.array() = 0;\n    for(l = 0; l < kk; l++){\n      mu.col(l).array() = 0.0;\n      for(j = 0; j < nn; j++){\n\tif(gk(j) == l){\n\t  numk(l) += 1;\n\t  mu.col(l) += xn.col(j);\n\t}\n      }\n// Is which better?\n      mu.col(l).array() /= static_cast<double> (numk(l));\n//      mu.col(l) /= static_cast<double> (numk(l));\n    }\n    sum_gk = gk.sum();\n    if(bef_sum_gk == sum_gk) break;\n    bef_sum_gk = sum_gk;\n  }\n\n  std::cout << \"numk =\" << std::endl << numk << std::endl;\n  std::cout << \"gk =\" << std::endl << gk << std::endl;\n  std::cout << \"mu =\" << std::endl << mu << std::endl;\n}\n", "meta": {"hexsha": "e222b4c3ceef982bda556a1b1e6970b19fc54223", "size": 1641, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/k_means_cc", "max_stars_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_stars_repo_licenses": ["MIT"], "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.cc", "max_issues_repo_name": "ya-mat/k_means_cc", "max_issues_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_issues_repo_licenses": ["MIT"], "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/k_means_cc", "max_forks_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_forks_repo_licenses": ["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.7916666667, "max_line_length": 85, "alphanum_fraction": 0.5149299208, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6590156326984775}}
{"text": "\n#include <Eigen/Jacobi>\n#include <Eigen/SVD>\n\n#include <sphericalsfm/so3.h>\n#include <sphericalsfm/spherical_utils.h>\n\nnamespace sphericalsfm {\n    void make_spherical_essential_matrix( const Eigen::Matrix3d &R, bool inward, Eigen::Matrix3d &E )\n    {\n        Eigen::Vector3d t( R(0,2), R(1,2), R(2,2)-1 );\n        if ( inward ) t = -t;\n        E = skew3(t)*R;\n    }\n\n    void decompose_spherical_essential_matrix( const Eigen::Matrix3d &E, bool inward, Eigen::Vector3d &r, Eigen::Vector3d &t )\n    {\n        Eigen::JacobiSVD<Eigen::Matrix3d> svdE(E,Eigen::ComputeFullU|Eigen::ComputeFullV);\n        \n        Eigen::Matrix3d U = svdE.matrixU();\n        Eigen::Matrix3d V = svdE.matrixV();\n        \n        // from theia sfm\n        if (U.determinant() < 0) {\n            U.col(2) *= -1.0;\n        }\n        \n        if (V.determinant() < 0) {\n            V.col(2) *= -1.0;\n        }\n        \n        Eigen::Matrix3d D;\n        D <<\n        0,1,0,\n        -1,0,0,\n        0,0,1;\n        \n        Eigen::Matrix3d DT;\n        DT <<\n        0,-1,0,\n        1,0,0,\n        0,0,1;\n        \n        Eigen::Matrix3d VT = V.transpose().eval();\n        \n        Eigen::Vector3d tu = U.col(2);\n        \n        Eigen::Matrix3d R1 = U*D*VT;\n        Eigen::Matrix3d R2 = U*DT*VT;\n        \n        Eigen::Vector3d t1( R1(0,2), R1(1,2), R1(2,2)-1 );\n        Eigen::Vector3d t2( R2(0,2), R2(1,2), R2(2,2)-1 );\n        \n        if ( inward ) { t1 = -t1; t2 = -t2; }\n        \n        Eigen::Vector3d myt1 = t1/t1.norm();\n        Eigen::Vector3d myt2 = t2/t2.norm();\n        \n        Eigen::Vector3d r1 = so3ln(R1);\n        Eigen::Vector3d r2 = so3ln(R2);\n        \n        double score1 = fabs(myt1.dot(tu));\n        double score2 = fabs(myt2.dot(tu));\n        \n        if ( score1 > score2 ) { r = r1; t = t1; }\n        else { r = r2; t = t2; }\n    }\n\n    static Eigen::Vector3d triangulateMidpoint( const Eigen::Matrix4d &rel_pose, const Eigen::Vector3d &u, const Eigen::Vector3d &v )\n    {\n        Eigen::Vector3d cu( 0, 0, 0 );\n        Eigen::Vector3d cv( -rel_pose.block<3,3>(0,0).transpose() * rel_pose.block<3,1>(0,3) );\n        \n        Eigen::Matrix3d A;\n        A <<\n        u(0), -v(0), cu(0) - cv(0),\n        u(1), -v(1), cu(1) - cv(1),\n        u(2), -v(2), cu(2) - cv(2);\n        \n        const Eigen::Vector3d soln = A.jacobiSvd( Eigen::ComputeFullV ).matrixV().col(2);\n        const double du = soln(0)/soln(2);\n        const double dv = soln(1)/soln(2);\n        \n        const Eigen::Vector3d Xu = cu + u*du;\n        const Eigen::Vector3d Xv = cv + v*dv;\n        \n        return (Xu+Xv)*0.5;\n    }\n\n    void decompose_spherical_essential_matrix( const Eigen::Matrix3d &E, bool inward,\n                     RayPairList::iterator begin, RayPairList::iterator end, const std::vector<bool> &inliers,\n                     Eigen::Vector3d &r, Eigen::Vector3d &t )\n    {\n        Eigen::JacobiSVD<Eigen::Matrix3d> svdE(E,Eigen::ComputeFullU|Eigen::ComputeFullV);\n        \n        Eigen::Matrix3d U = svdE.matrixU();\n        Eigen::Matrix3d V = svdE.matrixV();\n        \n        // from theia sfm\n        if (U.determinant() < 0) {\n            U.col(2) *= -1.0;\n        }\n        \n        if (V.determinant() < 0) {\n            V.col(2) *= -1.0;\n        }\n\n        Eigen::Matrix3d D;\n        D <<\n        0,1,0,\n        -1,0,0,\n        0,0,1;\n\n        Eigen::Matrix3d DT;\n        DT <<\n        0,-1,0,\n        1,0,0,\n        0,0,1;\n\n        Eigen::Matrix3d VT = V.transpose().eval();\n        \n        Eigen::Matrix3d R1 = U*D*VT;\n        Eigen::Matrix3d R2 = U*DT*VT;\n        \n        Eigen::Vector3d t1( R1(0,2), R1(1,2), (inward) ? R1(2,2)+1 : R1(2,2)-1 );\n        Eigen::Vector3d t2( R2(0,2), R2(1,2), (inward) ? R2(2,2)+1 : R2(2,2)-1 );\n        \n        Eigen::Vector3d r1 = so3ln(R1);\n        Eigen::Vector3d r2 = so3ln(R2);\n\n        double r1test = r1.norm();\n        double r2test = r2.norm();\n        \n        if ( r2test > M_PI/2 && r1test < M_PI/2 ) { r = r1; t = t1; return; }\n        if ( r1test > M_PI/2 && r2test < M_PI/2 ) { r = r2; t = t2; return; }\n\n        Eigen::Matrix4d P1( Eigen::Matrix4d::Identity() );\n        Eigen::Matrix4d P2( Eigen::Matrix4d::Identity() );\n        \n        P1.block(0,0,3,3) = R1;\n        P1.block(0,3,3,1) = t1;\n\n        P2.block(0,0,3,3) = R2;\n        P2.block(0,3,3,1) = t2;\n        \n        int ninfront1 = 0;\n        int ninfront2 = 0;\n        \n        int i = 0;\n        for ( RayPairList::iterator it = begin; it != end; it++,i++ )\n        {\n            if ( !inliers[i] ) continue;\n            \n            Eigen::Vector3d u = it->first.head(3);\n            Eigen::Vector3d v = it->second.head(3);\n            \n            Eigen::Vector3d X1 = triangulateMidpoint(P1, u, v);\n            Eigen::Vector3d X2 = triangulateMidpoint(P2, u, v);\n\n            if ( X1(2) > 0 ) ninfront1++;\n            if ( X2(2) > 0 ) ninfront2++;\n        }\n        \n        if ( ninfront1 > ninfront2 )\n        {\n            r = so3ln(R1);\n            t = t1;\n        }\n        else\n        {\n            r = so3ln(R2);\n            t = t2;\n        }\n    }\n}\n", "meta": {"hexsha": "3cf22f136bf311853994119df149b6fd7e1aa971", "size": 5076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spherical_utils.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/spherical_utils.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/spherical_utils.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": 28.8409090909, "max_line_length": 133, "alphanum_fraction": 0.4686761229, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6589785547313854}}
{"text": "#include <ros/ros.h>\n#include <geometry_msgs/PoseArray.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <tf/transform_datatypes.h>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <cmath>\n#include <cylbot_motion_model/multivariate_normal.h>\n#include <iostream>\n\n#define NUM_POSES 1000\n\ngeometry_msgs::PoseArray pose_array;\n\nEigen::internal::scalar_normal_dist_op<double> randN;\n//Eigen::internal::scalar_normal_dist_op<double>::rng.seed(1);\n\ndouble alpha[6];\n\n// random number generator\nboost::mt19937 rng;\n\ngeometry_msgs::TwistStamped::ConstPtr curr_vel_cmd;\n\nvoid sampleVelocityMotionModel(const geometry_msgs::Twist& u, \\\n\t\t\t\t\t\t\t   geometry_msgs::PoseArray::_poses_type::iterator x,\n\t\t\t\t\t\t\t   double dt,\n\t\t\t\t\t\t\t   const double (&alpha)[6],\n\t\t\t\t\t\t\t   boost::mt19937& rng)\n{\n\tdouble v_hat_variance = alpha[0]*u.linear.y*u.linear.y + alpha[1]*u.angular.z*u.angular.z;\n\tdouble w_hat_variance = alpha[2]*u.linear.y*u.linear.y + alpha[3]*u.angular.z*u.angular.z;\n\tdouble gamma_variance = alpha[4]*u.linear.y*u.linear.y + alpha[5]*u.angular.z*u.angular.z;\n\n\tboost::normal_distribution<> v_hat_dist(0.0, sqrt(v_hat_variance));\n\tboost::normal_distribution<> w_hat_dist(0.0, sqrt(w_hat_variance));\n\tboost::normal_distribution<> gamma_dist(0.0, sqrt(gamma_variance));\n\n\tdouble v_hat = u.linear.y + v_hat_dist(rng);\n\tdouble w_hat = u.angular.z + w_hat_dist(rng);\n\tdouble gamma = gamma_dist(rng);\n\n\tdouble v_w_ratio = v_hat/w_hat;\n\n\tdouble yaw = tf::getYaw(x->orientation);\n\n\tdouble x_prime = x->position.x - v_w_ratio*sin(yaw) + v_w_ratio*sin(yaw + w_hat*dt);\n\tdouble y_prime = x->position.y + v_w_ratio*cos(yaw) - v_w_ratio*cos(yaw + w_hat*dt);\n\tdouble yaw_prime = yaw + w_hat*dt + gamma*dt;\n\n\tx->position.x = x_prime;\n\tx->position.y = y_prime;\n\tx->orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, yaw_prime);\n}\n\nvoid initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& pose_with_cov)\n{\n\tROS_INFO(\"Received a new pose\");\n\n\tEigen::VectorXd mean(3);\n\tEigen::MatrixXd covar(3, 3);\n\n\tmean << pose_with_cov->pose.pose.position.x,\n\t\tpose_with_cov->pose.pose.position.y,\n\t\ttf::getYaw(pose_with_cov->pose.pose.orientation);\n\tcovar << pose_with_cov->pose.covariance[0], 0,                                  0,\n\t\t     0,                                 pose_with_cov->pose.covariance[7],  0,\n\t\t     0,                            0,                                       pose_with_cov->pose.covariance[35];\n\n\tEigen::MatrixXd normTransform(3, 3);\n\tEigen::LLT<Eigen::MatrixXd> cholSolver(covar);\n\n\tif(cholSolver.info() == Eigen::Success)\n\t{\n\t\tnormTransform = cholSolver.matrixL();\n\t}\n\telse\n\t{\n\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar);\n\t\tnormTransform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n\t}\n\n\tEigen::MatrixXd samples = (normTransform * Eigen::MatrixXd::NullaryExpr(3, NUM_POSES, randN)).colwise() + mean;\n\n\tROS_INFO_STREAM(\"\\nMean:\\n\" << mean << \"\\n\");\n\tROS_INFO_STREAM(\"\\nCov:\\n\" << covar << \"\\n\");\n\n\t// remove existing pose estimates\n\tpose_array.poses.clear();\n\tfor(int i=0; i<NUM_POSES; i++)\n\t{\n\t\tgeometry_msgs::Pose pose;\n\t\tpose.position.x = samples(0, i);\n\t\tpose.position.y = samples(1, i);\n\t\tpose.position.z = 0;\n\n\t\t// generate random yaw then convert it to a quaternion\n\t\tpose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, samples(2, i));\n\t\t\n\t\tpose_array.poses.push_back(pose);\n\t}\n}\n\nvoid velocityCallback(const geometry_msgs::TwistStamped::ConstPtr& twist_msg)\n{\n\tcurr_vel_cmd = twist_msg;\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"pose_array_test\");\n\tros::NodeHandle nh;\n\n\t// initialize alpha\n\tfor(int i=0; i<6; i++)\n\t\talpha[i] = .1;\n\n\talpha[0] = .5;\n\talpha[3] = .5;\n\t\n\tros::Publisher pose_array_pub = nh.advertise<geometry_msgs::PoseArray>(\"pose_array_test\", 1);\n\t//ros::Subscriber initial_pose_sub = nh.subscribe<geometry_msgs::PoseWithCovarianceStamped>(\"/initialpose\", 10, &initialPoseCallback, ros::TransportHints().tcpNoDelay(false));\n\tros::Subscriber velocity_sub = nh.subscribe<geometry_msgs::TwistStamped>(\"/cylbot/velocity\", 1, &velocityCallback);\n\n\n\tpose_array.header.frame_id = \"/map\";\n\n\tgeometry_msgs::Pose starting_pose;\n\tstarting_pose.orientation.w = 1.0;\n\tfor(int i=0; i<1000; i++)\n\t{\n\t\tpose_array.poses.push_back(starting_pose);\n\t}\n\n\tpose_array_pub.publish(pose_array);\n\n\tros::Time last_time = ros::Time::now();\n\tros::Rate loop_rate(100);\n\twhile(ros::ok())\n\t{\n\t\tif(curr_vel_cmd != NULL)\n\t\t{\n\t\t\t// get the time delta\n\t\t\tros::Time curr_time = ros::Time::now();\n\t\t\tros::Duration dt = curr_time - last_time;\n\t\t\tlast_time = curr_time;\n\t\t\t\n\t\t\t// skip when commands are at 0\n\t\t\tif(fabs(curr_vel_cmd->twist.linear.y) > 0.1 ||\n\t\t\t   fabs(curr_vel_cmd->twist.angular.z) > 0.1)\n\t\t\t{\n\n\t\t\t\tROS_INFO_STREAM(\"Updating pose estimates with command\\n\" << curr_vel_cmd->twist);\n\t\t\t\tROS_INFO_STREAM(\"\\tdt: \" << dt.toSec());\n\n\t\t\t\t// update the pose estimates with the probabilistic motion model\n\t\t\t\tfor(geometry_msgs::PoseArray::_poses_type::iterator pose = pose_array.poses.begin();\n\t\t\t\t\tpose != pose_array.poses.end();\n\t\t\t\t\tpose++)\n\t\t\t\t{\n\t\t\t\t\tsampleVelocityMotionModel(curr_vel_cmd->twist, pose, dt.toSec(), alpha, rng);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpose_array.header.stamp = ros::Time::now();\n\t\tpose_array_pub.publish(pose_array);\n\t\t\n\t\tros::spinOnce();\n\t\tloop_rate.sleep();\n\t}\n\t\n}\n", "meta": {"hexsha": "aa4cfaa91428473be0dd9c383ac3219266273714", "size": 5391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cylbot_motion_model/src/motion_model_test.cpp", "max_stars_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_stars_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "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/cylbot_motion_model/src/motion_model_test.cpp", "max_issues_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_issues_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-22T13:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-23T23:01:57.000Z", "max_forks_repo_path": "src/cylbot_motion_model/src/motion_model_test.cpp", "max_forks_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_forks_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "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.8057142857, "max_line_length": 176, "alphanum_fraction": 0.6935633463, "num_tokens": 1511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303293, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.658978551794554}}
{"text": "/*\n * polynomial_splines.hpp\n *\n *  Created on: Mar 7, 2017\n *      Author: Dario Bellicoso\n */\n\n#pragma once\n\n// stl\n#include <vector>\n#include <iostream>\n\n// eigen\n#include <Eigen/Core>\n#include <Eigen/QR>\n\n// boost\n#include <boost/math/special_functions/pow.hpp>\n\nnamespace curves {\n\nstruct SplineOptions {\n\n  SplineOptions()\n      : tf_(0.0),\n        pos0_(0.0), posT_(0.0),\n        vel0_(0.0), velT_(0.0),\n        acc0_(0.0), accT_(0.0)\n  {\n\n  }\n\n  constexpr SplineOptions(double tf, double pos0, double posT, double vel0,\n                          double velT, double acc0, double accT)\n      : tf_(tf),\n        pos0_(pos0), posT_(posT),\n        vel0_(vel0), velT_(velT),\n        acc0_(acc0), accT_(accT)\n  {\n\n  }\n\n  //! The total duration of the spline in seconds.\n  double tf_;\n\n  //! The scalar position at time 0.\n  double pos0_;\n\n  //! The scalar position at time tf.\n  double posT_;\n\n  //! The scalar velocity at time 0.\n  double vel0_;\n\n  //! The scalar velocity at time tf.\n  double velT_;\n\n  //! The scalar acceleration at time 0.\n  double acc0_;\n\n  //! The scalar acceleration at time tf.\n  double accT_;\n};\n\nnamespace spline_traits {\n\n// Main struct template.\ntemplate<typename Core_, int SplineOrder_>\nstruct spline_rep {\n\n  static constexpr unsigned int splineOrder = SplineOrder_;\n  static constexpr unsigned int numCoefficients = SplineOrder_+1;\n\n  using TimeVectorType = std::array<Core_, numCoefficients>;\n  using SplineCoefficients = std::array<Core_, numCoefficients>;\n\n  static inline TimeVectorType tau(Core_ tk) noexcept;\n  static inline TimeVectorType dtau(Core_ tk) noexcept;\n  static inline TimeVectorType ddtau(Core_ tk) noexcept;\n\n  static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients);\n};\n\n// Specialization for third order splines.\ntemplate<>\nstruct spline_rep<double, 3> {\n\n  static constexpr unsigned int splineOrder = 3;\n  static constexpr unsigned int numCoefficients = splineOrder+1;\n\n  using TimeVectorType = std::array<double, numCoefficients>;\n  using SplineCoefficients = std::array<double, numCoefficients>;\n\n  static inline TimeVectorType tau(double tk) noexcept {\n    return { boost::math::pow<3>(tk), boost::math::pow<2>(tk), tk, 1.0 };\n  }\n\n  static inline TimeVectorType dtau(double tk) noexcept {\n    return { 3.0*boost::math::pow<2>(tk), 2.0*tk, 1.0, 0.0 };\n  }\n\n  static inline TimeVectorType ddtau(double tk) noexcept {\n    return { 6.0*tk, 2.0, 0.0, 0.0 };\n  }\n\n  static constexpr TimeVectorType   tauZero{{ 0.0, 0.0, 0.0, 1.0 }};\n  static constexpr TimeVectorType  dtauZero{{ 0.0, 0.0, 1.0, 0.0 }};\n  static constexpr TimeVectorType ddtauZero{{ 0.0, 2.0, 0.0, 0.0 }};\n\n  static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients) {\n\n    Eigen::Matrix<double, numCoefficients, 1> b;\n    b << opts.pos0_, opts.vel0_, opts.posT_, opts.velT_;\n\n    Eigen::Matrix<double, numCoefficients, numCoefficients> A;\n    A << Eigen::Map<const Eigen::Matrix<double, 1, numCoefficients>>(tauZero.data()),\n         Eigen::Map<const Eigen::Matrix<double, 1, numCoefficients>>(dtauZero.data()),\n         Eigen::Map<Eigen::Matrix<double, 1, numCoefficients>>((tau(opts.tf_)).data()),\n         Eigen::Map<Eigen::Matrix<double, 1, numCoefficients>>((dtau(opts.tf_)).data());\n\n    Eigen::Map<Eigen::VectorXd>(coefficients.data(), numCoefficients, 1) = A.colPivHouseholderQr().solve(b);\n\n    return true;\n  }\n};\n\n\n// Specialization for fifth order splines.\ntemplate<>\nstruct spline_rep<double, 5> {\n\n  static constexpr unsigned int splineOrder = 5;\n  static constexpr unsigned int numCoefficients = splineOrder+1;\n\n  using TimeVectorType = std::array<double, numCoefficients>;\n  using SplineCoefficients = std::array<double, numCoefficients>;\n\n  static inline TimeVectorType tau(double tk) noexcept {\n    return { boost::math::pow<5>(tk), boost::math::pow<4>(tk), boost::math::pow<3>(tk),\n             boost::math::pow<2>(tk), tk, 1.0};\n  }\n\n  static inline TimeVectorType dtau(double tk) noexcept {\n    return { 5.0*boost::math::pow<4>(tk), 4.0*boost::math::pow<3>(tk), 3.0*boost::math::pow<2>(tk),\n             2.0*tk, 1.0, 0.0};\n  }\n\n  static inline TimeVectorType ddtau(double tk) noexcept {\n    return { 20.0*boost::math::pow<3>(tk), 12.0*boost::math::pow<2>(tk), 6.0*tk,\n              2.0, 0.0, 0.0};\n  }\n\n  static constexpr TimeVectorType   tauZero{{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }};\n  static constexpr TimeVectorType  dtauZero{{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }};\n  static constexpr TimeVectorType ddtauZero{{ 0.0, 0.0, 0.0, 2.0, 0.0, 0.0 }};\n\n  static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients) {\n    Eigen::Matrix<double, numCoefficients, 1> b;\n    b << opts.pos0_, opts.vel0_, opts.acc0_, opts.posT_, opts.velT_, opts.accT_;\n\n    Eigen::Matrix<double, numCoefficients, numCoefficients> A;\n    A << Eigen::Map<const Eigen::Matrix<double, 1, numCoefficients>>(tauZero.data()),\n         Eigen::Map<const Eigen::Matrix<double, 1, numCoefficients>>(dtauZero.data()),\n         Eigen::Map<const Eigen::Matrix<double, 1, numCoefficients>>(ddtauZero.data()),\n         Eigen::Map<Eigen::Matrix<double, 1, numCoefficients>>((tau(opts.tf_)).data()),\n         Eigen::Map<Eigen::Matrix<double, 1, numCoefficients>>((dtau(opts.tf_)).data()),\n         Eigen::Map<Eigen::Matrix<double, 1, numCoefficients>>((ddtau(opts.tf_)).data());\n\n    Eigen::Map<Eigen::VectorXd>(coefficients.data(), numCoefficients, 1) = A.colPivHouseholderQr().solve(b);\n\n    return true;\n  }\n\n};\n\n}\n\n}\n", "meta": {"hexsha": "8b2941466475822bfbf7300e1da4afb102d5148e", "size": 5481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/polynomial_splines_traits.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/polynomial_splines_traits.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/polynomial_splines_traits.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": 30.45, "max_line_length": 108, "alphanum_fraction": 0.669585842, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6589729702585957}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <autoppl/math/autocorrelation.hpp>\n\nnamespace ppl {\nnamespace math {\nnamespace details {\n\ntemplate <class T>\nusing vec_cref_t = std::vector<\n    std::reference_wrapper<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> >;\n\n} // namespace details\n\n/**\n * Computes the effective sample size (ESS) for a given vector of samples (matrices).\n * Every element of the vector is a matrix of samples for each chain.\n * Every matrix contains the samples as rows, i.e.\n * every row is a sample of an p-dimensional vector, where p\n * is the number of columns of the matrix (number of parameters).\n *\n * The algorithm assumes that every sample matrix has the same dimensions.\n *\n * @tparam  T           underlying Eigen expression type\n * @param   samples     vector of samples\n *\n * @return  a vector of ESS for each component\n *          If number of samples is 1 or less, or there are 0 components,\n *          or number of chains is 0, return an empty vector.\n *          In either case, the dimension of the return vector is same\n *          as the number of components.\n */\ntemplate <class T>\ninline auto ess(const details::vec_cref_t<T>& samples)\n{\n    using value_t = T;\n    using vec_t = Eigen::Matrix<value_t, Eigen::Dynamic, 1>;\n    using mat_t = Eigen::Matrix<value_t, Eigen::Dynamic, Eigen::Dynamic>;\n\n    vec_t tau_hat;\n\n    size_t M = samples.size();      // number of chains\n\n    if (M == 0) return tau_hat;\n\n    size_t dim = samples[0].get().cols();    // sample dimension\n    size_t N = samples[0].get().rows();      // number of samples\n\n    if (N <= 1 || dim == 0) return tau_hat;\n\n    tau_hat = vec_t::Zero(dim);\n\n    auto var = [N](const auto& mat) {\n        return (mat.rowwise() - \n                mat.colwise().mean()).colwise()\n                                     .squaredNorm() / (N-1);\n    };\n\n    // use N-1 scaling to compute variance\n    // each col is the sample variance per chain\n    mat_t sample_vars(dim, M);\n    for (size_t i = 0; i < M; ++i) {\n        sample_vars.col(i) = var(samples[i].get());\n    }\n\n    // column vector of average of sample variances\n    vec_t W = sample_vars.rowwise().mean();\n\n    // compute variance estimator\n    vec_t var_est = static_cast<T>(N-1) / N * W;\n\n    // if there is more than 1 chain, then update by N * B\n    // where B is the between-chain variance\n    if (M > 1) {\n        mat_t sample_mean(dim, M);\n        for (size_t i = 0; i < M; ++i) {\n            sample_mean.col(i) = samples[i].get().colwise().mean();\n        }\n        var_est += var(sample_mean.transpose());\n    }\n\n    // compute autocorrelation vector for each component\n    // every column vector (every component) is average AC over chains\n    mat_t acov_mean(N, dim);\n    acov_mean.setZero();\n\n    for (size_t m = 1; m <= M; ++m) {\n        mat_t next_acov = autocorrelation(samples[m-1].get());\n        for (int j = 0; j < next_acov.cols(); ++j) {\n            next_acov.col(j) *= sample_vars(j,m-1);\n        }\n        value_t m_inv = 1./m;\n        acov_mean = m_inv * next_acov + (m-1) * m_inv * acov_mean;\n    }\n    \n    // compute rho-hat at lag t for dimension d\n    auto rho_hat = [&](size_t t, size_t d) {\n        return 1. - (W(d) - acov_mean(t,d))/var_est(d);\n    };\n\n    // compute tau-hat directly to save memory\n    for (size_t d = 0; d < dim; ++d) {\n        \n        // first two should not be corrected for positive and monotoneness\n        value_t curr_rho_hat_even = rho_hat(0,d);\n        value_t curr_p_hat = curr_rho_hat_even + rho_hat(1,d);  // current P_hat(t)\n        value_t curr_min = curr_p_hat;                          // current min of P_hat(t)\n        tau_hat(d) = curr_min;                                  // update with P_hat(0)\n\n        // only estimate up to 3 samples before the end\n        // and Geyer's positive condition holds\n        size_t t = 2;\n        for (; t < (N-3) && curr_p_hat > 0; t += 2) {\n            curr_rho_hat_even = rho_hat(t,d);\n            curr_p_hat = curr_rho_hat_even + rho_hat(t+1,d);\n\n            // if positive condition holds, take the min \n            // of current P_hat(t) with the min of previous P_hat's\n            // to create a monotone sequence and accumulate to tau_hat\n            if (curr_p_hat >= 0) {\n                curr_min = std::min(curr_min, curr_p_hat);\n                tau_hat(d) += curr_min;\n            }\n        }\n\n        // correct to improve estimate (see STAN's implementation)\n        value_t correction = (curr_rho_hat_even > 0) ? \n                curr_rho_hat_even : rho_hat(t,d);\n\n        tau_hat(d) *= 2.; // 2 * sum of adjusted P_hat(t)\n        tau_hat(d) -= 1.; // -1 + 2 * sum of adjusted P_hat(t) \n        tau_hat(d) += correction;   \n    }\n\n    vec_t n_eff = N*M*(1./tau_hat.array()).min(std::log10(N)).matrix();\n\n    return n_eff;\n}\n\n/**\n * Computes the effective sample size (ESS) for a given sample matrix.\n * This is an overload for when there is only chain and can supply\n * a single matrix instead.\n * See above overload for more details.\n *\n * @tparam  T           underlying Eigen expression type\n * @param   samples     sample matrix (1 chain)\n *\n * @return  a vector of ESS for each component\n */\ntemplate <class T>\ninline auto ess(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& samples)\n{\n    details::vec_cref_t<T> v;\n    v.emplace_back(samples);\n    return ess(v);\n}\n    \n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "e37298482ba30b4c43d749f7df81ce5e7068ef0d", "size": 5416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/ess.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/ess.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/ess.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 33.4320987654, "max_line_length": 90, "alphanum_fraction": 0.5961964549, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6589729586923893}}
{"text": "#include <deal.II/base/point.h>\n\n#include <gtest/gtest.h>\n\nusing namespace dealii;\n\n\nTEST(Pythagoras, Norm)\n{\n  Point<2> x(3, 4);\n  ASSERT_EQ(x.norm(), 5);\n}\n\n\nTEST(Pythagoras, Distance)\n{\n  Point<2> x(4, 5);\n  Point<2> y(1, 1);\n  ASSERT_EQ(x.distance(y), 5);\n}\n\n\nTEST(Pythagoras, ScalarProduct)\n{\n  Point<2> x(3, 4);\n  ASSERT_EQ(x * x, 25);\n}\n\nTEST(Pythagoras3, Norm)\n{\n  Point<3> x(20, 4, 5);\n  ASSERT_EQ(x.norm(), 21);\n}\n\n\nTEST(Pythagoras3, Distance)\n{\n  Point<3> x(21, 5, 6);\n  Point<3> y(1, 1, 1);\n  ASSERT_EQ(x.distance(y), 21);\n}\n\n\nTEST(Pythagoras3, ScalarProduct)\n{\n  Point<3> x(20, 4, 5);\n  ASSERT_EQ(x * x, 441);\n}\n\n", "meta": {"hexsha": "8bc1a2cc0cac591629e91f1ad5ca354dd000b275", "size": 626, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/point_tests.cc", "max_stars_repo_name": "mathLab/lab-01-davydenk", "max_stars_repo_head_hexsha": "69c5280bc8dfe7f770d6d137b73f51539b8a08a5", "max_stars_repo_licenses": ["MIT"], "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/point_tests.cc", "max_issues_repo_name": "mathLab/lab-01-davydenk", "max_issues_repo_head_hexsha": "69c5280bc8dfe7f770d6d137b73f51539b8a08a5", "max_issues_repo_licenses": ["MIT"], "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/point_tests.cc", "max_forks_repo_name": "mathLab/lab-01-davydenk", "max_forks_repo_head_hexsha": "69c5280bc8dfe7f770d6d137b73f51539b8a08a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.52, "max_line_length": 32, "alphanum_fraction": 0.6006389776, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6589729557441967}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestTransform3D\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include \"minimath/rotation3d.hpp\"\n#include \"minimath/transform3d.hpp\"\n#include \"minimath/point3d.hpp\"\n#include \"minimath/geom3d_ops.hpp\"\n#include \"TestRotation3DUtils.h\"\n\nusing namespace minimath;\n\nnamespace\n{\nstruct setup\n{\n    setup() { std::cout << std::setprecision(18); }\n};\n\n}\n\nBOOST_FIXTURE_TEST_SUITE(TestTransform3D, setup)\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  rotation3d<double> rot1, rot2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n  BOOST_CHECK(rotation3d<double>()==rotation3d<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultIsIdentity)\n{\n  transform3d<double> t;\n  BOOST_CHECK(p100 == t*p100);\n  BOOST_CHECK(p010 == t*p010);\n  BOOST_CHECK(p001 == t*p001);\n  BOOST_CHECK(p111 == t*p111);\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  rotation3d<double> rot1;\n  rotation3d<double> rot2(rot1);\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  rotation3d<double> rot1, rot2;\n  rot2 = rot1;\n  BOOST_CHECK(rot1 == rot2);\n\n}\n\nBOOST_AUTO_TEST_CASE(testTranslation)\n{\n  transform3d<double> transf(translation3d<double>(111., 222., 333.));\n  pointxyzd p;\n  p = transf*p;\n  BOOST_CHECK(p==pointxyzd(111., 222., 333.));\n\n}\n\nBOOST_AUTO_TEST_CASE(testRotation3D)\n{\n  rotation3d<double> rot;\n  transform3d<double> transf(rot);\n  pointxyzd p;\n  p = transf*p;\n  BOOST_CHECK(p==pointxyzd());\n}\n\nBOOST_AUTO_TEST_CASE(testRotationX45)\n{\n  rotation3d<double> rot(rotation3dx<double>(PI/4.));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., cos45, cos45));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -cos45, cos45));\n}\n\n\nBOOST_AUTO_TEST_CASE(testRotationX90)\n{\n  rotation3d<double> rot(rotation3dx<double>(PI/2.));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationX180)\n{\n  rotation3d<double> rot(rotation3dx<double>(1.*PI));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1, 0));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0, -1));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationY45)\n{\n  rotation3d<double> rot(rotation3dy<double>(PI/4.)); \n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0., -cos45));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0., cos45));\n}\n\n\nBOOST_AUTO_TEST_CASE(testRotationY90)\n{\n  rotation3d<double> rot(rotation3dy<double>(PI/2.));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationY180)\n{\n  rotation3d<double> rot(rotation3dy<double>(1.*PI));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationZ45)\n{\n  rotation3d<double> rot(rotation3dz<double>(PI/4.));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, cos45, 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(-cos45, cos45, 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationZ90)\n{\n  rotation3d<double> rot(rotation3dz<double>(PI/2.));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationZ180)\n{\n  rotation3d<double> rot(rotation3dz<double>(1.*PI));\n  transform3d<double> transf(rot);\n  pointxyzd pTest = transf*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = transf*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = transf*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\n\nBOOST_AUTO_TEST_CASE(testNullRotationAndTranslation)\n{\n  transform3d<double> transf(rotation3d<double>(), translation3d<double>(111., 222, 333.));\n  pointxyzd p;\n  p = transf*p;\n  BOOST_CHECK(p==pointxyzd(111., 222., 333.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotationXAndTranslation)\n{\n  for (unsigned int i = 1; i<9; ++i) \n  {\n    rotation3d<double> rot(rotation3dx<double>(PI/i));\n    transform3d<double> transf(rot, translation3d<double>(111., 222, 333.));\n    pointxyzd translation(111.,222.,333.);\n    pointxyzd pTest = transf*p100;\n    BOOST_CHECK(minimath::equal(pTest, rot*p100 + translation));\n\n    pTest = transf*p010;\n    bool test = minimath::equal(pTest, rot*p010 + translation);\n    if (!test) {\n      std::cout << \"\\nFail i = \" << i << \" pTest = \" << pTest\n          << \" rot*p010 = \" << (rot*p010) << \"\\n\"; \n      std::cout << \" rot*p010 + trans = \" << (rot*p010 + translation) << \"\\n\"; \n    }\n\n    BOOST_CHECK(minimath::equal(pTest, rot*p010 + translation));\n\n    pTest = transf*p001;\n    BOOST_CHECK(minimath::equal(pTest,rot*p001 + translation));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testRotationYAndTranslation)\n{\n  for (unsigned int i = 1; i<9; ++i)\n  {\n    rotation3d<double> rot(rotation3dy<double>(PI/i));\n    transform3d<double> transf(rot, translation3d<double>(111., 222, 333.));\n    pointxyzd translation(111.,222.,333.);\n    pointxyzd pTest = transf*p100;\n    BOOST_CHECK(minimath::equal(pTest, rot*p100 + translation));\n\n    pTest = transf*p010;\n    BOOST_CHECK(minimath::equal(pTest, rot*p010 + translation));\n\n    pTest = transf*p001;\n    BOOST_CHECK(minimath::equal(pTest, rot*p001 + translation));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testRotationZAndTranslation)\n{\n  for (unsigned int i = 1; i<9; ++i)\n  {\n    rotation3d<double> rot(rotation3dz<double>(PI/i));\n    transform3d<double> transf(rot, translation3d<double>(111., 222, 333.));\n    pointxyzd translation(111.,222.,333.);\n    pointxyzd pTest = transf*p100;\n    BOOST_CHECK(minimath::equal(pTest, rot*p100 + translation));\n\n    pTest = transf*p010;\n    BOOST_CHECK(minimath::equal(pTest, rot*p010 + translation));\n\n    pTest = transf*p001;\n    BOOST_CHECK(minimath::equal(pTest, rot*p001 + translation));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndNullRotation)\n{\n  transform3d<double> transf(translation3d<double>(111., 222, 333.), rotation3d<double>());\n  pointxyzd p;\n  p = transf*p;\n  BOOST_CHECK(p==pointxyzd(111., 222., 333.));\n}\n\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotationX)\n{\n  for (unsigned int i = 1; i<9; ++i) \n  {\n    rotation3d<double> rot(rotation3dx<double>(PI/i));\n    pointxyzd translation(999.,999.,999.);\n    transform3d<double> transf(translation3d<double>(translation), rot);\n\n    pointxyzd pTest = transf*p100;\n\n    pointxyzd res100 = rot*translation + rot*p100;\n    BOOST_CHECK(minimath::equal(pTest, res100));\n\n    pTest = transf*p010;\n    pointxyzd res010 = rot*translation + rot*p010;\n    BOOST_CHECK(minimath::equal(pTest, res010));\n\n    pTest = transf*p001;\n    pointxyzd res001 = rot*translation + rot*p001;\n    BOOST_CHECK(minimath::equal(pTest, res001));\n\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotationY)\n{\n  for (unsigned int i = 1; i<9; ++i) \n  {\n    rotation3d<double> rot(rotation3dy<double>(PI/i));\n    pointxyzd translation(999.,999.,999.);\n    transform3d<double> transf(translation3d<double>(translation), rot);\n\n    pointxyzd pTest = transf*p100;\n    pointxyzd res100 = rot*translation + rot*p100;\n    BOOST_CHECK(minimath::equal(pTest, res100, 200));\n\n    pTest = transf*p010;\n    pointxyzd res010 = rot*translation + rot*p010;\n    BOOST_CHECK(minimath::equal(pTest, res010));\n\n    pTest = transf*p001;\n    pointxyzd res001 = rot*translation + rot*p001;\n    BOOST_CHECK(minimath::equal(pTest, res001));\n\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(testTranslationAndRotationZ)\n{\n  for (unsigned int i = 1; i<9; ++i) \n  {\n    rotation3d<double> rot(rotation3dz<double>(PI/i));\n    pointxyzd translation(999.,999.,999.);\n    transform3d<double> transf(translation3d<double>(translation), rot);\n\n    pointxyzd pTest = transf*p100;\n    pointxyzd res100 = rot*translation + rot*p100;\n    BOOST_CHECK(minimath::equal(pTest, res100, 2000));\n\n    pTest = transf*p010;\n    pointxyzd res010 = rot*translation + rot*p010;\n    BOOST_CHECK(minimath::equal(pTest, res010));\n\n    pTest = transf*p001;\n    pointxyzd res001 = rot*translation + rot*p001;\n    BOOST_CHECK(minimath::equal(pTest, res001));\n  }\n}\n\n// test that a multiplication of Transform3Ds is the same as applying\n// the individual transformations to a point one by one.\n// Since we are chaining many operations, we use a \"loose\" tolerance of\n// ~1000 epsilons.\nBOOST_AUTO_TEST_CASE(testMultiplication)\n{\n  for (unsigned int i = 0; i < 10; ++i)\n  {\n\n    // get some random rotations and translations\n    rotation3d<double> rot0 = TestUtils::randomRotation();\n    rotation3d<double> rot1 = TestUtils::randomRotation();\n    rotation3d<double> rot2 = TestUtils::randomRotation();\n    translation3d<double> transl0 = TestUtils::randomTranslation(100.);\n    translation3d<double> transl1 = TestUtils::randomTranslation(10.);\n    translation3d<double> transl2 = TestUtils::randomTranslation(50.);\n\n    // multiply the rotations and translations together\n    transform3d<double> trans = transform3d<double>(rot0)*transform3d<double>(transl0)*transform3d<double>(rot1)*transform3d<double>(transl1)*transform3d<double>(rot2)*transform3d<double>(transl2);\n\n    // get a sets of random points\n    for (unsigned int j = 0; j < 10; ++j)\n    {\n      pointxyzd r = TestUtils::randomPoint(999);\n      pointxyzd p0 = trans*r;\n      pointxyzd p1 = transl2*r;\n      p1 = rot2*p1;\n      p1 = transl1*p1;\n      p1 = rot1*p1;\n      p1 = transl0*p1;\n      p1 = rot0*p1;\n      // check the resulting transformation is equivalent to the\n      // product of transformations, by applying to the random points.\n\n      BOOST_CHECK(minimath::equal(p0,p1, 2048));\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  BOOST_CHECK(TestUtils::testInverseTransform3D<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInverseTransform3D<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInverseTransform3D<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  BOOST_CHECK(TestUtils::testInvertTransform3D<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInvertTransform3D<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInvertTransform3D<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d696a7a173e8ba5630469786ed3ae6ee5a6deab9", "size": 11393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestTransform3D.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestTransform3D.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestTransform3D.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 27.3870192308, "max_line_length": 197, "alphanum_fraction": 0.6941981919, "num_tokens": 3407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6588653479240736}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <memory>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n\n#include <gtest/gtest.h>\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include \"../../meshes/mesh.h\"\n#include \"../mylinearfeelementmatrix.h\"\n#include \"../mylinearloadvector.h\"\n#include \"../solve.h\"\n\nnamespace ElementMatrixComputation::test {\n\ndouble numericalPrecision = 1e-8;\n\ndouble f(Eigen::Vector2d x) { return 1 + x(0) * x(0) + x(1) * x(1); };\n\n// useful functors\nEigen::Matrix<double, 2, 2> zeroMatrixFunctor(Eigen::Vector2d x) {\n  return Eigen::MatrixXd::Zero(2, 2);\n};\n\ndouble zeroScalar(Eigen::Vector2d x) { return 0.0; };\n\nEigen::Matrix<double, 2, 2> identityMatrixFunctor(Eigen::Vector2d x) {\n  return Eigen::MatrixXd::Identity(2, 2);\n};\n\ndouble identityScalarFunctor(Eigen::Vector2d x) { return 1.0; };\n\n//////////////////////\n// Test solve\n//////////////////////\nTEST(Solve, test) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(8, 1.0 / 3.0);\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::mesh::Mesh &mesh{*(fe_space->Mesh())};\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n  const lf::base::size_type N_dofs(dofh.NumDofs());\n\n  lf::mesh::utils::MeshFunctionGlobal mf_alpha{identityMatrixFunctor};\n  lf::mesh::utils::MeshFunctionGlobal mf_gamma{identityScalarFunctor};\n\n  // Galerkin matrix\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider<\n      double, decltype(mf_alpha), decltype(mf_gamma)>\n      elmat_builder(fe_space, mf_alpha, mf_gamma);\n\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  // Right hand side\n  lf::mesh::utils::MeshFunctionGlobal mf_f{ElementMatrixComputation::f};\n\n  lf::uscalfe::LinearFELocalLoadVector<double, decltype(mf_f)> elvec_builder(\n      mf_f);\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  // solve\n  Eigen::VectorXd sol_vec = Eigen::VectorXd::Zero(N_dofs);\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_crs);\n  sol_vec = solver.solve(phi);\n\n  double error =\n      (sol_vec - ElementMatrixComputation::solve(elmat_builder, elvec_builder))\n          .norm();\n\n  EXPECT_LT(error, numericalPrecision);\n}\n\n//////////////////////\n// Test SolvePoissonBVP\n//////////////////////\nTEST(SolvePoissonBVP, test) {\n  lf::mesh::utils::MeshFunctionGlobal mf_f{ElementMatrixComputation::f};\n\n  lf::uscalfe::LinearFELaplaceElementMatrix elmat_builder;\n  lf::uscalfe::LinearFELocalLoadVector<double, decltype(mf_f)> elvec_builder(\n      mf_f);\n\n  Eigen::VectorXd solution =\n      ElementMatrixComputation::solve(elmat_builder, elvec_builder);\n\n  Eigen::VectorXd student_solution =\n      ElementMatrixComputation::solvePoissonBVP();\n\n  if (student_solution.norm() < numericalPrecision) {\n    EXPECT_TRUE(false);\n  } else {\n    double error = (solution - student_solution).norm();\n\n    EXPECT_LT(error, numericalPrecision);\n  }\n}\n\n//////////////////////\n// Test MyLinearLoadVector\n//////////////////////\nTEST(MyLinearLoadVector, testTriangles) {\n  std::shared_ptr<lf::mesh::Mesh> mesh_p =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(0, 1.0 / 3.0);\n\n  lf::mesh::utils::MeshFunctionGlobal mf_f{ElementMatrixComputation::f};\n\n  ElementMatrixComputation::MyLinearLoadVector elvec_builder(\n      ElementMatrixComputation::f);\n  lf::uscalfe::LinearFELocalLoadVector<double, decltype(mf_f)>\n      elvec_builder_exact(mf_f);\n\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    if (cell->RefEl() == lf::base::RefEl::kTria()) {\n      auto elem_vec = elvec_builder.Eval(*cell);\n      auto elem_vec_exact = elvec_builder_exact.Eval(*cell);\n      double error = (elem_vec - elem_vec_exact).norm();\n      EXPECT_LT(error, numericalPrecision);\n    }\n  }\n}\n\nTEST(MyLinearLoadVector, testQuads) {\n  auto mesh_p = Generate2DTestMesh();\n\n  lf::mesh::utils::MeshFunctionGlobal mf_f{ElementMatrixComputation::f};\n\n  ElementMatrixComputation::MyLinearLoadVector elvec_builder(\n      ElementMatrixComputation::f);\n  lf::uscalfe::LinearFELocalLoadVector<double, decltype(mf_f)>\n      elvec_builder_exact(mf_f);\n\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    if (cell->RefEl() == lf::base::RefEl::kQuad()) {\n      auto elem_vec = elvec_builder.Eval(*cell);\n      auto elem_vec_exact = elvec_builder_exact.Eval(*cell);\n      double error = (elem_vec - elem_vec_exact).norm();\n      EXPECT_LT(error, numericalPrecision);\n    }\n  }\n}\n\n//////////////////////\n// Test MyLinearFEElementMatrix\n//////////////////////\nTEST(MyLinearFEElementMatrix, testTriangles) {\n  std::shared_ptr<lf::mesh::Mesh> mesh_p =\n      lf::mesh::test_utils::GenerateHybrid2DTestMesh(0, 1.0 / 3.0);\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::mesh::Mesh &mesh{*(fe_space->Mesh())};\n\n  lf::mesh::utils::MeshFunctionGlobal mf_alpha{identityMatrixFunctor};\n  lf::mesh::utils::MeshFunctionGlobal mf_gamma{identityScalarFunctor};\n\n  ElementMatrixComputation::MyLinearFEElementMatrix elmat_builder;\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider<\n      double, decltype(mf_alpha), decltype(mf_gamma)>\n      elmat_builder_exact(fe_space, mf_alpha, mf_gamma);\n\n  for (const lf::mesh::Entity *cell : mesh.Entities(0)) {\n    if (cell->RefEl() == lf::base::RefEl::kTria()) {\n      auto elem_mat = elmat_builder.Eval(*cell);\n      auto elem_mat_exact = elmat_builder_exact.Eval(*cell);\n      double error = (elem_mat.block(0, 0, 3, 3) - elem_mat_exact).norm();\n      EXPECT_LT(error, numericalPrecision);\n    }\n  }\n}\n\nTEST(MyLinearFEElementMatrix, testQuads) {\n  // std::shared_ptr<lf::mesh::Mesh> mesh_p =\n  //     lf::mesh::test_utils::GenerateHybrid2DTestMesh(0, 1.0 / 3.0);\n  auto mesh_p = Generate2DTestMesh();\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::mesh::Mesh &mesh{*(fe_space->Mesh())};\n\n  lf::mesh::utils::MeshFunctionGlobal mf_alpha{identityMatrixFunctor};\n  lf::mesh::utils::MeshFunctionGlobal mf_gamma{identityScalarFunctor};\n\n  ElementMatrixComputation::MyLinearFEElementMatrix elmat_builder;\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider<\n      double, decltype(mf_alpha), decltype(mf_gamma)>\n      elmat_builder_exact(fe_space, mf_alpha, mf_gamma);\n\n  for (const lf::mesh::Entity *cell : mesh.Entities(0)) {\n    if (cell->RefEl() == lf::base::RefEl::kQuad()) {\n      auto elem_mat = elmat_builder.Eval(*cell);\n      auto elem_mat_exact = elmat_builder_exact.Eval(*cell);\n      double error = (elem_mat - elem_mat_exact).norm();\n      EXPECT_LT(error, numericalPrecision);\n    }\n  }\n}\n\n//////////////////////\n// Test solveNeumannEq\n//////////////////////\nTEST(solveNeumannEq, test) {\n  ElementMatrixComputation::MyLinearFEElementMatrix elmat_builder;\n  ElementMatrixComputation::MyLinearLoadVector elvec_builder(\n      ElementMatrixComputation::f);\n\n  Eigen::VectorXd solution =\n      ElementMatrixComputation::solve(elmat_builder, elvec_builder);\n  Eigen::VectorXd student_solution = ElementMatrixComputation::solveNeumannEq();\n\n  if (student_solution.norm() < numericalPrecision) {\n    EXPECT_TRUE(false);\n  } else {\n    double error = (solution - student_solution).norm();\n\n    EXPECT_LT(error, numericalPrecision);\n  }\n}\n\n}  // namespace ElementMatrixComputation::test\n", "meta": {"hexsha": "29632891859fa4d08dff46fb7d0f796ddd0774f4", "size": 7685, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/templates/test/elementmatrixcomputation_test.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": "homeworks/ElementMatrixComputation/templates/test/elementmatrixcomputation_test.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": "homeworks/ElementMatrixComputation/templates/test/elementmatrixcomputation_test.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": 32.7021276596, "max_line_length": 80, "alphanum_fraction": 0.6977228367, "num_tokens": 2134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.8128673223709251, "lm_q1q2_score": 0.6588118277711149}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef META_MATH_IS_PRIME_INCLUDE\n#define META_MATH_IS_PRIME_INCLUDE\n\n#include <boost/mpl/bool.hpp>\n#include <boost/numeric/meta_math/sqrt.hpp>\n// #include <boost/config/concept_macros.hpp>\n#ifdef __GXX_CONCEPTS__\n#   include <concepts>\n#endif\n\n\nnamespace meta_math {\n\nnamespace mpl = boost::mpl;\n\nnamespace impl {\n\n    // Checks if 'x' is divisible by some odd number >= max_odd, checking decreasingly\n    template <long int x, long int max_odd>\n    struct is_prime_to_max_odd\n    {\n\tstatic bool const value = x % max_odd != 0\n                                  && is_prime_to_max_odd<x, max_odd-2>::value;\n    };\n\n    // Once we reach 1, it's prime\n    template <long int x> struct is_prime_to_max_odd<x, 1> : mpl::true_ {};\n\n\n    // Returns the largest number that x is tried to divided by.\n    // This is a odd number slightly larger than the approximated square root.\n    template <long int x>\n    struct max_prime_compare\n    {\n\tstatic long int const tmp = sqrt<x>::value,\n                              value = tmp % 2 == 0 ? tmp + 1 : tmp + 2;\n    };\n\n\n    // Checks if there is an odd number between 3 and sqrt(x)+1 that divides x\n    // if there is no divisor found then x is prime (otherwise not)\n    // must be disabled when x is even\n    template <long int x, bool Disable>\n    struct check_odd\n    {\n\tstatic bool const value = is_prime_to_max_odd<x, max_prime_compare<x>::value>::value;\n    };\n\n    // Intended for even numbers (> 2) which are always prime\n    template <long int x>\n    struct check_odd<x, true>\n    {\n\tstatic bool const value = false;\n    };\n\n}\n\ntemplate <long int x>\nstruct is_prime\n{\n  static bool const value = impl::check_odd<x, x % 2 == 0>::value;\n};\n\ntemplate <> struct is_prime<0> : mpl::false_ {};\ntemplate <> struct is_prime<1> : mpl::false_ {};\ntemplate <> struct is_prime<2> : mpl::true_ {};\ntemplate <> struct is_prime<3> : mpl::true_ {};\ntemplate <> struct is_prime<5> : mpl::true_ {};\n\n\n#ifdef __GXX_CONCEPTS__\n    concept Prime<long int N> {}\n\n    template <long int N>\n        where std::True<is_prime<N>::value> \n    concept_map Prime<N> {}\n#endif\n\n\n\n} // namespace meta_math\n\n#endif // META_MATH_IS_PRIME_INCLUDE\n", "meta": {"hexsha": "e6aa21de3e5a55bf7fe37ab9164f1f774c934617", "size": 2606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/meta_math/is_prime.hpp", "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": "lib/mtl4/boost/numeric/meta_math/is_prime.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "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": "lib/mtl4/boost/numeric/meta_math/is_prime.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "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": 27.1458333333, "max_line_length": 94, "alphanum_fraction": 0.6623177283, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6586301077019208}}
{"text": "#pragma once\n#include \"PolynomialRootSolver.h\"\n#include <opencv2/core/core.hpp>\n#include <Eigenvalues>\n#include <opencv2/core/eigen.hpp>\n\n\nPolynomialRootSolver::PolynomialRootSolver()\n{\n\n}\n\nPolynomialRootSolver::~PolynomialRootSolver()\n{\n\n}\n\nEigen::MatrixXd computeCompanionMatrix(const cv::Mat rowOfCoefficientsInAscendingDegreeOrder)\n{\n    int numberOfColumns  = rowOfCoefficientsInAscendingDegreeOrder.size().width  -1 ;\n    Eigen::MatrixXd eigenCoefficients(1,numberOfColumns+1);\n    Eigen::MatrixXd companionMatrix(numberOfColumns,numberOfColumns);\n    companionMatrix.setZero();\n    Eigen::MatrixXd identitySubmatrix = Eigen::MatrixXd::Identity(numberOfColumns-1,numberOfColumns-1);\n    cv::cv2eigen(rowOfCoefficientsInAscendingDegreeOrder, eigenCoefficients);\n    eigenCoefficients /= eigenCoefficients(numberOfColumns);\n\n    companionMatrix.block(0,1,numberOfColumns-1,numberOfColumns-1) = identitySubmatrix;\n    companionMatrix.block(numberOfColumns-1,0,1,numberOfColumns) -= eigenCoefficients.block(0,0,1,numberOfColumns);\n    return companionMatrix;\n}\n\ncv::Mat PolynomialRootSolver::computeRoots(const cv::Mat& rowOfCoefficientsInAscendingDegreeOrder)\n{\n    Eigen::MatrixXd eigenCompanionMatrix = computeCompanionMatrix(rowOfCoefficientsInAscendingDegreeOrder);\n    Eigen::EigenSolver<Eigen::MatrixXd> eigenSolver(eigenCompanionMatrix);\n    Eigen::MatrixXd realEigenvalues = eigenSolver.eigenvalues().real();\n    realEigenvalues.transposeInPlace();\n    cv::Mat roots;\n    cv::eigen2cv(realEigenvalues, roots);\n    return roots;\n}\n", "meta": {"hexsha": "23004f8eccfc5f1351b383e2ff2ec19824737397", "size": 1541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_stars_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_stars_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_issues_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_issues_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_forks_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_forks_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_forks_repo_licenses": ["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.8372093023, "max_line_length": 115, "alphanum_fraction": 0.7942894225, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6585576018118462}}
{"text": "// (C) Copyright Andrew Sutton 2007\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 http://www.boost.org/LICENSE_1_0.txt)\n\n//[mean_geodesic_example\n#include <iostream>\n#include <iomanip>\n\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/geodesic_distance.hpp>\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// The Actor type stores the name of each vertex in the graph.\nstruct Actor\n{\n    string name;\n};\n\n// Declare the graph type and its vertex and edge types.\ntypedef undirected_graph<Actor> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef graph_traits<Graph>::edge_descriptor Edge;\n\n// The name map provides an abstract accessor for the names of\n// each vertex. This is used during graph creation.\ntypedef property_map<Graph, string Actor::*>::type NameMap;\n\n// Declare a matrix type and its corresponding property map that\n// will contain the distances between each pair of vertices.\ntypedef exterior_vertex_property<Graph, int> DistanceProperty;\ntypedef DistanceProperty::matrix_type DistanceMatrix;\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\n\n// Declare the weight map so that each edge returns the same value.\ntypedef constant_property_map<Edge, int> WeightMap;\n\n// Declare a container and its corresponding property map that\n// will contain the resulting mean geodesic distances of each\n// vertex in the graph.\ntypedef exterior_vertex_property<Graph, float> GeodesicProperty;\ntypedef GeodesicProperty::container_type GeodesicContainer;\ntypedef GeodesicProperty::map_type GeodesicMap;\n\nint\nmain(int argc, char *argv[])\n{\n    // Create the graph and a property map that provides access\n    // to the actor names.\n    Graph g;\n    NameMap nm(get(&Actor::name, g));\n\n    // Read the graph from standad input.\n    read_graph(g, nm, cin);\n\n    // Compute the distances between all pairs of vertices using\n    // the Floyd-Warshall algorithm. Note that the weight map is\n    // created so that every edge has a weight of 1.\n    DistanceMatrix distances(num_vertices(g));\n    DistanceMatrixMap dm(distances, g);\n    WeightMap wm(1);\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\n\n    // Compute the mean geodesic distances for each vertex in\n    // the graph and get the average mean geodesic distace (the\n    // so-called small-world distance) as a result.\n    GeodesicContainer geodesics(num_vertices(g));\n    GeodesicMap gm(geodesics, g);\n    float sw = all_mean_geodesics(g, dm, gm);\n\n    // Print the mean geodesic distance of each vertex and finally,\n    // the graph itself.\n    graph_traits<Graph>::vertex_iterator i, end;\n    for(tie(i, end) = vertices(g); i != end; ++i) {\n        cout << setw(12) << setiosflags(ios::left)\n             << g[*i].name << get(gm, *i) << endl;\n    }\n    cout << \"small world distance: \" << sw << endl;\n\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "f6b6892c06147751a2025ef2e8ccc78eaebb0126", "size": 3058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/mean_geodesic.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "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/graph/example/mean_geodesic.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/graph/example/mean_geodesic.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": 33.9777777778, "max_line_length": 67, "alphanum_fraction": 0.7361020275, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6585481096051392}}
{"text": "#define BOOST_TEST_MODULE \"Test Cosine class\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Cosine.hpp\"\n\nusing namespace genex;\n\n#define TOLERANCE 1e-9\n\nstruct MockData\n{\n  data_t dat_1[10] = {5, 0, 3, 0, 2, 0, 0, 2, 0, 0};\n  data_t dat_2[10] = {3, 0, 2, 0, 1, 1, 0, 1, 0, 1};\n};\n\nBOOST_AUTO_TEST_CASE( cosine_test, *boost::unit_test::tolerance(TOLERANCE)  )\n{\n  MockData data;\n  TimeSeries ts_1(data.dat_1, 0, 0, 5);\n  TimeSeries ts_2(data.dat_2, 0, 0, 5);\n  Cosine dist;\n\n  data_t* total = dist.init();\n\n  for (int i = 0; i < ts_1.getLength(); i++) {\n    total = dist.reduce(total, total, ts_1[i], ts_2[i]);\n  }\n\n  BOOST_TEST( dist.norm(total, ts_1, ts_2), 0.94 );\n\n  delete total;\n}\n", "meta": {"hexsha": "d799fa8c5737af71425de3a0dcaca56182da4410", "size": 697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/CosineTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/CosineTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/CosineTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 20.5, "max_line_length": 77, "alphanum_fraction": 0.6398852224, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.658548096877834}}
{"text": "// This file is part of PoseEstimation.\n// Copyright (c) 2021, Eijiro Shibusawa <phd_kimberlite@yahoo.co.jp>\n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef THREE_POINT_HPP_\n#define THREE_POINT_HPP_\n\n#include <Eigen/Dense>\n\nclass ThreePointTest;\n\nnamespace ThreePoint\n{\ntemplate <typename FloatType>\nclass ThreePoint\n{\n\tfriend ::ThreePointTest;\n\nprivate:\n\ttypedef Eigen::Matrix<FloatType, Eigen::Dynamic, 1> Matrix_Dx1;\n\ttypedef Eigen::Matrix<FloatType, 3, 1> Matrix_3x1;\n\ttypedef Eigen::Matrix<FloatType, 3, 3> Matrix_3x3;\n\ttypedef Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> Matrix_3x3R;\n\ttypedef Eigen::Matrix<FloatType, 3, Eigen::Dynamic> Matrix_3xD;\n\ttypedef Eigen::Matrix<FloatType, 4, 4> Matrix_4x4;\n\ttypedef Eigen::Matrix<FloatType, 4, 1> Matrix_4x1;\n\npublic:\n\t// q = [x, y, z, w] = w + x*i + y*j + z*k\n\tstatic inline void getRotation(const FloatType *q, FloatType *R)\n\t{\n\t\tconst FloatType q0_2 = 2 * q[0], q1_2 = 2 * q[1], q2_2 = 2 * q[2];\n\t\tconst FloatType q03_2 = q0_2 * q[3], q13_2 = q1_2 * q[3], q23_2 = q2_2 * q[3];\n\t\tconst FloatType q00_2 = q0_2 * q[0], q01_2 = q0_2 * q[1], q02_2 = q0_2 * q[2];\n\t\tconst FloatType q11_2 = q1_2 * q[1], q12_2 = q1_2 * q[2], q22_2 = q2_2 * q[2];\n\t\tR[0] = 1 - (q11_2 + q22_2);\n\t\tR[1] = q01_2 - q23_2;\n\t\tR[2] = q02_2 + q13_2;\n\t\tR[3] = q01_2 + q23_2;\n\t\tR[4] = 1 - (q00_2 + q22_2);\n\t\tR[5] = q12_2 - q03_2;\n\t\tR[6] = q02_2 - q13_2;\n\t\tR[7] = q12_2 + q03_2;\n\t\tR[8] = 1 - (q00_2 + q11_2);\n\t}\n\n\tstatic inline void transformPoints(int n, FloatType s, const FloatType *R, const FloatType *t, const FloatType *X1, FloatType *X2)\n\t{\n\t\tEigen::Map<const Matrix_3x3R> mR(R);\n\t\tEigen::Map<const Matrix_3x1> mt(t);\n\t\tEigen::Map<const Matrix_3xD> mX1(X1, 3, n);\n\t\tEigen::Map<Matrix_3xD> mX2(X2, 3, n);\n\t\tmX2 = (s * mR * mX1).colwise() + mt;\n\t}\n\n\t// X1 = [X11 Y11 Z11 X12 Y12 ... X1n Y1n Z1n]\n\t// X2 = [X21 Y21 Z21 X22 Y22 ... X2n Y2n Z2n]\n\t// X2 = s*R*X1 + t\n\tstatic void getRT(int n, const FloatType *X1, const FloatType *X2, FloatType *R, FloatType *t, FloatType &s)\n\t{\n\t\tEigen::Map<const Matrix_3xD> mX1(X1, 3, n);\n\t\tEigen::Map<const Matrix_3xD> mX2(X2, 3, n);\n\t\t// centroid\n\t\tMatrix_3x1 mc1 = mX1.rowwise().sum() / mX1.cols();\n\t\tMatrix_3x1 mc2 = mX2.rowwise().sum() / mX2.cols();\n\t\t// translate origin to centroid\n\t\tMatrix_3xD mX1c = mX1.colwise() - mc1;\n\t\tMatrix_3xD mX2c = mX2.colwise() - mc2;\n\n\t\t// estimate scale\n\t\tMatrix_Dx1 mX1n = mX1c.colwise().norm();\n\t\tMatrix_Dx1 mX2n = mX2c.colwise().norm();\n\t\ts = (mX1n.array() * mX2n.array()).sum() / (mX1n.array() * mX1n.array()).sum();\n\t\tmX2c *= s;\n\n\t\t// corrrelation matrix\n\t\tMatrix_3x3 mC = mX1c * mX2c.transpose();\n\t\t// system matrix\n\t\tMatrix_4x4 A;\n\t\tA(3, 3) = mC(0, 0) + mC(1, 1) + mC(2, 2);\n\t\tA(3, 0) = A(0, 3) = mC(1, 2) - mC(2, 1);\n\t\tA(3, 1) = A(1, 3) = mC(2, 0) - mC(0, 2);\n\t\tA(3, 2) = A(2, 3) = mC(0, 1) - mC(1, 0);\n\t\tA(0, 0) = mC(0, 0) - mC(1, 1) - mC(2, 2);\n\t\tA(0, 1) = A(1, 0) = mC(0, 1) + mC(1, 0);\n\t\tA(0, 2) = A(2, 0) = mC(2, 0) + mC(0, 2);\n\t\tA(1, 1) = -mC(0, 0) + mC(1, 1) - mC(2, 2);\n\t\tA(1, 2) = A(2, 1) = mC(1, 2) + mC(2, 1);\n\t\tA(2, 2) = -mC(0, 0) - mC(1, 1) + mC(2, 2);\n\n\t\t// estimate quaternion from eiven vector\n\t\tEigen::SelfAdjointEigenSolver<Matrix_4x4> eig(A, Eigen::ComputeEigenvectors);\n\t\tgetRotation(eig.eigenvectors().col(3).data(), R);\n\t\tEigen::Map<Matrix_3x3R> mR(R);\n\t\tEigen::Map<Matrix_3x1> mt(t);\n\t\tmt = -mR * mc1 * s + mc2;\n\t}\n};\n\n}\n\n#endif // THREE_POINT_HPP_", "meta": {"hexsha": "68af23f1882a04193ea7179a0fce29d8eda4e603", "size": 4656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ThreePoint.hpp", "max_stars_repo_name": "eshibusawa/PoseEstimation", "max_stars_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/ThreePoint.hpp", "max_issues_repo_name": "eshibusawa/PoseEstimation", "max_issues_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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/ThreePoint.hpp", "max_forks_repo_name": "eshibusawa/PoseEstimation", "max_forks_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "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": 38.1639344262, "max_line_length": 131, "alphanum_fraction": 0.6580756014, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.658413847354251}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// MetaData.hpp\n// This file is part of the Garamon Generator.\n// Authors: Stephane Breuils and Vincent Nozick\n// Contact: vincent.nozick@u-pem.fr\n//\n// Licence MIT\n// A a copy of the MIT License is given along with this program\n\n/// \\file MetaData.hpp\n/// \\author Stephane Breuils, Vincent Nozick\n/// \\brief Contains all the required information to define and create an algebra (dimension, metric, name, code options, ...)\n\n\n#ifndef GARAGEN_METADATA_HPP__\n#define GARAGEN_METADATA_HPP__\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <Eigen/Core>\n#include \"MetricTools.hpp\"\n\n// data required to build a Geometric Algebra Library\nclass MetaData\n{\npublic:\n\n    // namespace of the generated lib (ex: cga::)\n    std::string namespaceName;\n\n    // dimension of the algebra vector space (grade 1)\n    unsigned int dimension;\n\n    // metric = inner product of vectors, should be a symetric matrix\n    Eigen::MatrixXd metric;\n\n    // name of each basis vector, without the first letter (1,2,3 => e1, e2, e3, e12, ...).\n    // for hig dimensions, add a '_' at the end of the name to avoid: 1, 2, 3, ..., 16 => e114 : 11,4 ou 1,14 ?? => e11_4_\n    std::vector<std::string> basisVectorName;\n\n    // true if the proposed metric is diagonal\n    bool inputMetricDiagonal;\n\n    // true if the final (or initial) diagonal metric is actually identity\n    bool identityMetric;\n\n    // true if the metric has rank = dimension of the vector space supporting the algebra\n    bool fullRankMetric;\n\n    // true if the initial metric is a permutation of a diagonal matrix\n    bool inputMetricPermutationOfDiagonal;\n\n    // numerical refinement of the eigen vectors / values\n    bool useEigenRefinement;\n\n    // replace near zeros by zeros, near integers by integers, ...\n    bool useNumericalCleanUp;\n\n    // Each multivector component of grade k can have a dedicated precomputed product if its cardinality (max number of element of grade k) is lower than this threshold.\n    // Else, the product is performed recursively (this is only for high dimensional Geometric Algebra).\n    unsigned int maxDimPrecomputedProducts;\n\n    // Each multivector component of grade k can have a dedicated basis accessor constant (E123 in \"mv[E123]=42;\") if its cardinality (max number of element of grade k) is lower than this threshold.\n    // Else, this accessor is not created (this is only for high dimensional Geometric Algebra).\n    unsigned int maxDimBasisAccessor;\n\n    // numerical threshold for the numerical clean up\n    double epsilon;\n\n    // diagonal form of the metric after eigen vector/value decomposition\n    Eigen::VectorXd diagonalMetric;\n\n    // eigen vectors of the decomposition of the metric\n    Eigen::MatrixXd transformationMatrix;\n\n    // eigen vectors of the decomposition of the metric\n    Eigen::MatrixXd inverseTransformationMatrix;\n\n\n\npublic:\n\n    MetaData();\n\n    MetaData(const std::string &filename);\n\n    ~MetaData();\n\n    void display() const;\n\n    bool checkConsistency() const;\n\n    bool metricDiagonalization();\n};\n\n\n#endif // GARAGEN_METADATA_HPP__\n", "meta": {"hexsha": "cfb8ee249cc51d47d379c58ccf414faaa4ad1ea3", "size": 3132, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MetaData.hpp", "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/MetaData.hpp", "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/MetaData.hpp", "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": 31.6363636364, "max_line_length": 198, "alphanum_fraction": 0.7222222222, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6583735496834829}}
{"text": "#include <tagloc/tracking.h>\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <boost/program_options/cmdline.hpp>\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n\nusing namespace std;\nusing namespace RSN;\nnamespace po = boost::program_options;\n#define DEF_R .1\n\nint main(int argc, char** argv){\n\n\tdouble R;\n\tpo::options_description desc(\"estimator options\");\n\tdesc.add_options()\n\t\t(\"help,h\",\"produce help message\")\n\t\t(\"iwls,w\",\"(Default) Use Iterated Weighted Least Squares estimator. The line-intersection of all bearings is used as an initial estimate\")\n\t\t(\"ekf,e\",\"Use Extended Kalman Filter. The first two measurements are used to form the initial estimate\")\n\t\t(\"iekf,i\",\"Use Iterated Extended Kalman Filter. The first two measurements are used to form the initial estimate, and the update equations are re-linearized and iterated until convergence\")\n\t\t(\"grad,g\",\"Use gradient ascent. The line intersection is the initial estimate\")\n\t\t(\"line,l\",\"Use simple intersection of lines. R is ignored\")\n\t\t(\"ambig,a\",\"use ambiguous measurements\")\n\t\t(\"degrees,d\",\"measurements given in degrees\")\n\t\t(\"noise,R\", po::value<double>()->default_value(DEF_R), \"set sensor noise in radians\")\n\t\t(\"sequence,s\",po::value<vector<double> > ()->multitoken(), \"A full sequence of the form x y z x2 y2 z2 ... xn yn zn\")\n\t\t;\n\n\ttry{\n\t\tpo::variables_map vm;\n\t\tpo::positional_options_description p;\n\t\tp.add(\"sequence\",-1);\n\t\t//po::store(po::parse_command_line(argc, argv,desc),vm);\n\t\tpo::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(),vm);\n\t\tpo::notify(vm);    \n\n\t\tif (vm.count(\"help\") || argc == 1) {\n\t\t\tthrow -1;\n\t\t}\n\n\t\tR=vm[\"noise\"].as<double>();\n\t\tvector<double> sequence = vm[\"sequence\"].as<vector<double> >();\n\t\tif (((int)sequence.size()) % 3 !=0 ){\n\t\t\tcerr<<\"Incorrect number of args: \"<<sequence.size()<<endl;\n\t\t\tthrow -2;\n\t\t}\n\t\tbool degrees = (bool) vm.count(\"degrees\");\n\t\tvector<double> px;\n\t\tvector<double> py;\n\t\tvector<double> r;\n\t\tvector<double> z;\n\t\tdouble t[2];\n\t\tdouble c[4];\n\t\tfor (unsigned int i=0;i<sequence.size();){\n\t\t\tpx.push_back(sequence[i++]);\n\t\t\tpy.push_back(sequence[i++]);\n\t\t\tif (degrees){\n\t\t\t\tz.push_back((sequence[i++]/180.0)*M_PI);\n\t\t\t} else {\n\t\t\t\tz.push_back(sequence[i++]);\n\t\t\t}\n\t\t\tr.push_back(R);\n\t\t}\n\t\tint n = sequence.size()/3;\n\n\t\tbool ambig = (bool) vm.count(\"ambig\");\n\t\tbool done=false;\n\t\tif (vm.count(\"grad\") ) {\n\t\t\tRSN::line_intersection(n,px,py,z,t[0],t[1],c);\n\t\t\tRSN::BOT::Ml_Grad_Asc_2D(n,px,py,z,r,t,c,ambig);\n\t\t\tcout<<\"grad: (\";\n\t\t\tcout<<t[0]<<\",\"<<t[1]<<\")\";\n\t\t\tcout<<\" (\";\n\t\t\tcout<<c[0]<<\",\";\n\t\t\tcout<<c[1]<<\",\";\n\t\t\tcout<<c[2]<<\",\";\n\t\t\tcout<<c[3]<<\")\";\n\t\t\tcout<<endl;\n\t\t\tdone = true;\n\t\t}\n\t\tif (vm.count(\"line\") ) {\n\t\t\tRSN::line_intersection(n,px,py,z,t[0],t[1],c);\n\t\t\tcout<<\"line: (\";\n\t\t\tcout<<t[0]<<\",\"<<t[1]<<\")\";\n\t\t\tcout<<\" (\";\n\t\t\tcout<<c[0]<<\",\";\n\t\t\tcout<<c[1]<<\",\";\n\t\t\tcout<<c[2]<<\",\";\n\t\t\tcout<<c[3]<<\")\";\n\t\t\tcout<<endl;\n\t\t\tdone = true;\n\t\t}\n\t\tif (vm.count(\"ekf\") ) {\n\t\t\tvector<double> pxp(2);\n\t\t\tvector<double> pyp(2);\n\t\t\tfor (int i=0;i<2;i++){\n\t\t\t\tpxp[i] = px[i];\n\t\t\t\tpyp[i] = py[i];\n\t\t\t}\n\t\t\tRSN::line_intersection(n,pxp,pyp,z,t[0],t[1],c);\n\t\t\tfor (int i=2;i<n;i++){\n\t\t\t\tRSN::BOT::EKF_UP_2D(px[i],py[i],z[i],r[i],t,c,ambig);\n\t\t\t}\n\t\t\tcout<<\"ekf: (\";\n\t\t\tcout<<t[0]<<\",\"<<t[1]<<\")\";\n\t\t\tcout<<\" (\";\n\t\t\tcout<<c[0]<<\",\";\n\t\t\tcout<<c[1]<<\",\";\n\t\t\tcout<<c[2]<<\",\";\n\t\t\tcout<<c[3]<<\")\";\n\t\t\tcout<<endl;\n\t\t\tdone = true;\n\t\t}\n\t\tif (vm.count(\"iekf\") ) {\n\t\t\tvector<double> pxp(2);\n\t\t\tvector<double> pyp(2);\n\t\t\tfor (int i=0;i<2;i++){\n\t\t\t\tpxp[i] = px[i];\n\t\t\t\tpyp[i] = py[i];\n\t\t\t}\n\t\t\tRSN::line_intersection(n,pxp,pyp,z,t[0],t[1],c);\n\t\t\tfor (int i=2;i<n;i++){\n\t\t\t\tRSN::BOT::IEKF_2D(px[i],py[i],z[i],r[i],t,c,ambig);\n\t\t\t}\n\t\t\tcout<<\"iekf: (\";\n\t\t\tcout<<t[0]<<\",\"<<t[1]<<\")\";\n\t\t\tcout<<\" (\";\n\t\t\tcout<<c[0]<<\",\";\n\t\t\tcout<<c[1]<<\",\";\n\t\t\tcout<<c[2]<<\",\";\n\t\t\tcout<<c[3]<<\")\";\n\t\t\tcout<<endl;\n\t\t\tdone = true;\n\t\t}\n\t\tif (vm.count(\"iwls\") || !done) {\n\t\t\tRSN::line_intersection(n,px,py,z,t[0],t[1],c);\n\t\t\tRSN::BOT::IWLS_2D(n,px,py,z,r,t,c,ambig);\n\t\t\tcout<<\"iwls: (\";\n\t\t\tcout<<t[0]<<\",\"<<t[1]<<\")\";\n\t\t\tcout<<\" (\";\n\t\t\tcout<<c[0]<<\",\";\n\t\t\tcout<<c[1]<<\",\";\n\t\t\tcout<<c[2]<<\",\";\n\t\t\tcout<<c[3]<<\")\";\n\t\t\tcout<<endl;\n\t\t}\n\t} catch (int err){\n\t\tswitch(err){\n\t\t\tcase -2:{cerr<<\"Bad arg count\"<<endl;}\n\t\t}\n\t\tcerr<<desc<<endl;\n\t\treturn EXIT_FAILURE;\n\t} catch (...){\n\t\tcerr<<\"Error from boost?\"<<endl;\n\t\tcerr<<desc<<endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "9e5e2ec574f8d6c5d599c4215fc2ff78e91a9c58", "size": 4498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/estimator.cpp", "max_stars_repo_name": "jodavaho/tracking", "max_stars_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T00:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T09:01:59.000Z", "max_issues_repo_path": "src/estimator.cpp", "max_issues_repo_name": "jodavaho/tracking", "max_issues_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T16:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T16:14:20.000Z", "max_forks_repo_path": "src/estimator.cpp", "max_forks_repo_name": "jodavaho/tracking", "max_forks_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_forks_repo_licenses": ["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.5950920245, "max_line_length": 191, "alphanum_fraction": 0.5800355714, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6583735423314966}}
{"text": "/* test_lognormal.cpp\n *\n * Copyright Steven Watanabe 2011\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 * $Id: test_lognormal.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/lognormal_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/lognormal.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::lognormal_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME lognormal\n#define BOOST_MATH_DISTRIBUTION boost::math::lognormal\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME m\n#define BOOST_RANDOM_ARG1_DEFAULT 10.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(-n, n)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME s\n#define BOOST_RANDOM_ARG2_DEFAULT 10.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.0001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "cd92e2e891f1cbbfa51e38510538b0d3d4d1524b", "size": 1024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_lognormal.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_lognormal.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_lognormal.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "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": 35.3103448276, "max_line_length": 74, "alphanum_fraction": 0.8115234375, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6583735379085836}}
{"text": "#include <shift/math/intersection.hpp>\n#include <shift/math/interval.hpp>\n#include <shift/core/algorithm.hpp>\n#include <shift/platform/fpexceptions.hpp>\n#include <shift/core/boost_disable_warnings.hpp>\n#include <boost/test/unit_test.hpp>\n#include <shift/core/boost_restore_warnings.hpp>\n\nusing namespace shift;\nusing namespace shift::math;\n\nBOOST_AUTO_TEST_CASE(intersect_rectangle_rectangle)\n{\n  platform::floating_point_exceptions fpexceptions;\n\n  auto p = [](auto x, auto y) { return make_vector_from(x, y); };\n  auto r = [](auto p1, auto p2) { return make_interval_from(p1, p2); };\n\n  // Same rectangles.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(1, 1), p(4, 4)), r(p(1, 1), p(4, 4))));\n  // First fully inside second.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(2, 2), p(3, 3)), r(p(1, 1), p(4, 4))));\n  // Second fully inside first.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(1, 1), p(4, 4)), r(p(2, 2), p(3, 3))));\n  // Second fully outside of first.\n  BOOST_CHECK(\n    !intersection::rect_rect<true>(r(p(1, 1), p(4, 4)), r(p(5, 1), p(8, 4))));\n\n  // Only edge overlaps.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(1, 1), p(3, 4)), r(p(3, 2), p(6, 5))));\n  BOOST_CHECK(\n    !intersection::rect_rect<false>(r(p(1, 1), p(3, 4)), r(p(3, 2), p(6, 5))));\n\n  // Only top right corder overlaps.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(1, 1), p(4, 4)), r(p(4, 4), p(8, 8))));\n  BOOST_CHECK(\n    !intersection::rect_rect<false>(r(p(1, 1), p(4, 4)), r(p(4, 4), p(8, 8))));\n\n  // Only bottom left corder overlaps.\n  BOOST_CHECK(\n    intersection::rect_rect<true>(r(p(4, 4), p(8, 8)), r(p(1, 1), p(4, 4))));\n  BOOST_CHECK(\n    !intersection::rect_rect<false>(r(p(4, 4), p(8, 8)), r(p(1, 1), p(4, 4))));\n}\n\nBOOST_AUTO_TEST_CASE(intersect_point_triangle)\n{\n  auto v0 = make_vector_from(403.0f, 162.0f);\n  auto v1 = make_vector_from(197.0f, 19.0f);\n  auto v2 = make_vector_from(77.0f, 272.0f);\n\n  // Check if the triangle corner points are within the triangle.\n  BOOST_CHECK(intersection::point_triangle<true>(v0, v0, v1, v2));\n  BOOST_CHECK(intersection::point_triangle<true>(v1, v0, v1, v2));\n  BOOST_CHECK(intersection::point_triangle<true>(v2, v0, v1, v2));\n\n  // Check three points that are known to be inside.\n  auto i1 = make_vector_from(295.0f, 91.0f);\n  auto i2 = make_vector_from(112.0f, 213.0f);\n  auto i3 = make_vector_from(315.0f, 187.0f);\n  BOOST_CHECK(intersection::point_triangle<true>(i1, v0, v1, v2));\n  BOOST_CHECK(intersection::point_triangle<true>(i2, v0, v1, v2));\n  BOOST_CHECK(intersection::point_triangle<true>(i3, v0, v1, v2));\n\n  // Check three points that are known to be outside.\n  auto o1 = make_vector_from(300.0f, 83.0f);\n  auto o2 = make_vector_from(131.0f, 129.0f);\n  auto o3 = make_vector_from(150.0f, 257.0f);\n  BOOST_CHECK(!intersection::point_triangle<true>(o1, v0, v1, v2));\n  BOOST_CHECK(!intersection::point_triangle<true>(o2, v0, v1, v2));\n  BOOST_CHECK(!intersection::point_triangle<true>(o3, v0, v1, v2));\n}\n", "meta": {"hexsha": "ace82cf61791d5d70c0401f88b12183aaeefce2a", "size": 2996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shift/math/test/intersection.cpp", "max_stars_repo_name": "cspanier/shift", "max_stars_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T18:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T07:44:36.000Z", "max_issues_repo_path": "shift/math/test/intersection.cpp", "max_issues_repo_name": "cspanier/shift", "max_issues_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T21:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T07:52:52.000Z", "max_forks_repo_path": "shift/math/test/intersection.cpp", "max_forks_repo_name": "cspanier/shift", "max_forks_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4102564103, "max_line_length": 79, "alphanum_fraction": 0.6685580774, "num_tokens": 1050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6583112384724275}}
{"text": "#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf.h>\n#include <math.h>\n#include <complex>\n#include <boost/math/special_functions/jacobi_elliptic.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n\n\ndouble am(double x, double m) {\n\tif (m == 0) {\n\t\treturn x;\n\t} else if (x == 0) {\n\t\treturn 0;\n\t} else {\n\t\t// function to calculate jacobi amplitude for real input\n\t\t// \"borrowed\" from sagemath\n\t\tdouble sn, cn, dn;\n\t\tif (fabs(m) == 1) {\n\t\t\tdouble tanhx = tanh(x);\n\t\t\treturn asin(tanhx);\n\t\t} else if (fabs(m) > 1){\n\t\t\tgsl_sf_elljac_e(x, m, &sn, &cn, &dn);\n\t\t\treturn atan2(sn, cn);\n\t\t}\n\t\telse{\n\t\t\tdouble K = gsl_sf_ellint_Kcomp(sqrt(m), GSL_PREC_DOUBLE);\n\t\t\tif (fabs(x) <= K) {\n\t\t\t\tgsl_sf_elljac_e(x, m, &sn, &cn, &dn);\n\t\t\t\treturn atan2(sn, cn);\n\t\t\t} else {\n\t\t\t\t// Do argument reduction on x to end up with z = x - 2nK, with\n\t\t\t\t// abs(z) <= K\n\t\t\t\tdouble tK = 2 * K;\n\t\t\t\tint n = floor(x / tK);\n\t\t\t\tdouble tnK = n * tK;\n\t\t\t\tdouble npi = n * M_PI;\n\t\t\t\tdouble z = x - tnK;\n\n\t\t\t\tgsl_sf_elljac_e(z, m, &sn, &cn, &dn);\n\t\t\t\treturn atan2(sn, cn) + npi;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\ndouble calc_radius(double psi, double slr, double ecc) {\n\tdouble r = slr / (1 + ecc * cos(psi));\n\t// printf(\"slr = %.17g \\n\", slr);\n\t// printf(\"ecc = %.17g \\n\", ecc);\n\t// printf(\"psi = %.17g \\n\", psi);\n\treturn r;\n}\n\n\ndouble calc_lambda_r(double r, double r1, double r2, double r3,\n\tdouble r4, double En) {\n\n\t// compute function to change from t[lambda] -> t[psi] with psi an angle\n\t// associated with radial motion. \n\n\tdouble yr, F_asin, kr;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\t// there is some problem here because of the high precision part of the\n\t// code. r can be less than r2 (peribothron).\n\t// TODO: fix the code, but for now a temporary fix:\n\tif (r < r2) {\n\t\tr = r2;\n\t\tyr = sqrt(((r - r2)*(r1 - r3))/((r1 - r2)*(r - r3)));\n\t}\n\telse {\n\t\tyr = sqrt(((r - r2)*(r1 - r3))/((r1 - r2)*(r - r3)));\n\t}\n\t// printf(\"r = %.17g \\n\", r);\n\t// printf(\"r2 = %.17g \\n\", r2);\n\tF_asin = gsl_sf_ellint_F(asin(yr), sqrt(kr), GSL_PREC_DOUBLE);\n\treturn (2*F_asin)/(sqrt(1 - En * En)*sqrt((r1 - r3)*(r2 - r4)));\n}\n\n\ndouble calc_lambda_psi(double psi, double ups_r, double r1,\n\tdouble r2, double r3, double r4, double En, double slr, double ecc) {\n\n\tdouble lam_r, lam_r1, r, turns, res, kr;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\tr = calc_radius(psi, slr, ecc);\n\tlam_r = 2 * M_PI / ups_r;  // radial period\n\tlam_r1 = calc_lambda_r(r2, r1, r2, r3, r4, En);\n\tturns = floor(psi / (2 * M_PI));\n\tif (fmod(psi, 2 * M_PI) <= M_PI) {\n\t\t// printf(\"psi = %.17g\\n\", psi);\n\t\tres = calc_lambda_r(r, r1, r2, r3, r4, En) - lam_r1;\n\t\t// printf(\"res = %.17g\\n\", res);\n\t} else {\n\t\tres = lam_r1 - calc_lambda_r(r, r1, r2, r3, r4, En);\n\t}\n\t// printf(\"two\\n\");\n\n\treturn lam_r * turns + res;\n}\n\n\ndouble calc_lambda_chi(double chi, double zp, double zm, double En, double aa) {\n\t// compute function to change from t[lambda] -> t[chi] with chi an angle\n\t// associated with polar motion. \n\tdouble beta, k, k2, prefactor, ellipticK_k, ellipticF;\n\tbeta = aa * aa * (1 - En * En);\n\tk = sqrt(zm / zp);\n\tk2 = k * k;\n\tprefactor = 1 / sqrt(beta * zp);\n\tellipticK_k = gsl_sf_ellint_Kcomp(sqrt(k2), GSL_PREC_DOUBLE);\n\tellipticF = gsl_sf_ellint_F(M_PI / 2 - chi, sqrt(k2), GSL_PREC_DOUBLE);\n\n\treturn prefactor * (ellipticK_k - ellipticF);\n}\n\n// routines used to find t, r, theta, phi\n\n\ndouble calc_theta_chi(double chi, double zm) {\n\treturn acos(zm * cos(chi));\n}\n\n\ndouble calc_rq(double qr, double r1, double r2,\n\tdouble r3, double r4) {\n\n\tdouble arg, sn2, sn, cn, dn, kr;\n\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\n\targ = (qr*gsl_sf_ellint_Kcomp(sqrt(kr), GSL_PREC_DOUBLE))/M_PI;\n\tgsl_sf_elljac_e(arg, kr, &sn, &cn, &dn);\n\tsn2 = sn * sn;\n\n\treturn ((-(r2*(r1 - r3)) + (r1 - r2)*r3*sn2)/ (-r1 + r3 + (r1 - r2)*sn2));\n}\n\n\ndouble calc_zq(double qz, double zp, double zm, double En, double aa) {\n\tdouble ktheta, sn, dn, cn, ellipticK_k, arg1, arg2;\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\tellipticK_k = gsl_sf_ellint_Kcomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\targ1 = (2*(M_PI/2. + qz)*ellipticK_k)/M_PI;\n\targ2 = ktheta;\n\tgsl_sf_elljac_e(arg1, arg2, &sn, &cn, &dn);\n\n\treturn zm * sn;\n}\n\n\ndouble calc_psi_r(double qr, double r1, double r2, double r3, double r4) {\n\tdouble kr, amplitude;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\tamplitude = am((qr * gsl_sf_ellint_Kcomp(sqrt(kr), GSL_PREC_DOUBLE))/M_PI,\n\t\t\t\t   kr);\n\treturn amplitude;\n}\n\n\ndouble calc_t_r(double qr, double r1, double r2, double r3, double r4,\n\tdouble En, double Lz, double aa, double M=1) {\n\tdouble psi_r, kr, rp, rm, hr, hp, hm, aa2, En2, sin_psi_r, ellipe_k, ince_k;\n\tdouble ellippi_hm, ellippi_hr, ellippi_hp, inc_pi_hm, inc_pi_hr, inc_pi_hp;\n\taa2 = aa * aa;\n\tEn2 = En * En;\n\tpsi_r = calc_psi_r(qr, r1, r2, r3, r4);\n\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\n\trp = M + sqrt(-aa*aa + M*M);\n\trm = M - sqrt(-aa*aa + M*M);\n\n\thr = (r1 - r2)/(r1 - r3);\n\thp = ((r1 - r2)*(r3 - rp))/((r1 - r3)*(r2 - rp));\n\thm = ((r1 - r2)*(r3 - rm))/((r1 - r3)*(r2 - rm));\n\n\tsin_psi_r = pow(sin(psi_r), 2);\n\tince_k = gsl_sf_ellint_E(psi_r, sqrt(kr), GSL_PREC_DOUBLE);\n\tellipe_k = gsl_sf_ellint_Ecomp(sqrt(kr), GSL_PREC_DOUBLE);\n\tellippi_hm = gsl_sf_ellint_Pcomp(sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tellippi_hp = gsl_sf_ellint_Pcomp(sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tellippi_hr = gsl_sf_ellint_Pcomp(sqrt(kr), -hr, GSL_PREC_DOUBLE);\n\n\t// printf(\"ellippi_hm = %.17g \\n\", ellippi_hm);\n\n\tinc_pi_hm = gsl_sf_ellint_P(psi_r, sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tinc_pi_hp = gsl_sf_ellint_P(psi_r, sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tinc_pi_hr = gsl_sf_ellint_P(psi_r, sqrt(kr), -hr, GSL_PREC_DOUBLE);\n\n\n\treturn  (-((En * ((-4*(r2 - r3)*(-(((-2*aa2 + (4 - (aa*Lz)/En)*rm)*\n\t\t\t((qr*ellippi_hm)/M_PI - inc_pi_hm))/\n\t\t\t((r2 - rm)*(r3 - rm))) + \n\t\t\t((-2*aa2 + (4 - (aa*Lz)/En)*rp)*\n\t\t\t((qr*ellippi_hp)/M_PI - inc_pi_hp))/\n\t\t\t((r2 - rp)*(r3 - rp))))/(-rm + rp) + \n\t\t\t4*(r2 - r3)*((qr*ellippi_hr)/M_PI - inc_pi_hr) + \n\t\t\t(r2 - r3)*(r1 + r2 + r3 + r4)*\n\t\t\t((qr*ellippi_hr)/M_PI - inc_pi_hr) + \n\t\t\t(r1 - r3)*(r2 - r4)*((qr*ellipe_k)/M_PI - ince_k + \n\t\t\t(hr*cos(psi_r)*sin(psi_r)*sqrt(1 - kr*sin_psi_r))/\n\t\t\t(1 - hr*sin_psi_r))))/sqrt((1 - En2)*(r1 - r3)*(r2 - r4))));\n\n}\n\n\ndouble calc_phi_r(double qr, double r1, double r2, double r3, double r4,\n\tdouble En, double Lz, double aa, double M=1){\n\n\tdouble psi_r, kr, rp, rm, hp, hm, aa2, En2;\n\tdouble ellpi_hp, ellpi_hm, incpi_hp, incpi_hm;\n\taa2 = aa * aa;\n\tEn2 = En * En;\n\tpsi_r = calc_psi_r(qr, r1, r2, r3, r4);\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\trp = M + sqrt(-aa2 + M*M);\n\trm = M - sqrt(-aa2 + M*M);\n\n\thp = ((r1 - r2)*(r3 - rp))/((r1 - r3)*(r2 - rp));\n\thm = ((r1 - r2)*(r3 - rm))/((r1 - r3)*(r2 - rm));\n\n\tellpi_hp = gsl_sf_ellint_Pcomp(sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tellpi_hm = gsl_sf_ellint_Pcomp(sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tincpi_hp = gsl_sf_ellint_P(psi_r, sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tincpi_hm = gsl_sf_ellint_P(psi_r, sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\n\treturn ((2*aa*En*(-(((r2 - r3)*(-((aa*Lz)/En) + 2*rm)*\n\t\t\t((qr*ellpi_hm)/M_PI - incpi_hm))/\n\t\t\t((r2 - rm)*(r3 - rm))) + \n\t\t\t((r2 - r3)*(-((aa*Lz)/En) + 2*rp)*\n\t\t\t((qr*ellpi_hp)/M_PI - incpi_hp))/\n\t\t\t((r2 - rp)*(r3 - rp))))/\n\t\t\t(sqrt((1 - En2)*(r1 - r3)*(r2 - r4))*(-rm + rp)));\n\n}\n\n\ndouble calc_psi_z(double qz, double zp, double zm, double En, double aa){\n\tdouble ktheta, ellK_k;\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\tellK_k = gsl_sf_ellint_Kcomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\treturn am((2*(M_PI/2. + qz) * ellK_k)/M_PI, ktheta);\n}\n\n\ndouble calc_t_z(double qz, double zp, double zm, double En, double aa){\n\tdouble psi_z, ktheta, elle_k, ince_k;\n\tpsi_z = calc_psi_z(qz, zp, zm, En, aa);\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\telle_k = gsl_sf_ellint_Ecomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\tince_k = gsl_sf_ellint_E(psi_z, sqrt(ktheta), GSL_PREC_DOUBLE);\n\treturn ((En*zp*((2*(M_PI/2. + qz)*elle_k)/M_PI - ince_k))/\n\t\t\t(1 - En*En));\n}\n\n\ndouble calc_phi_z(double qz, double zp, double zm, double En, double Lz,\n\tdouble aa){\n\n\tdouble psi_z, ktheta, ellpi_k, incpi_k;\n\tpsi_z = calc_psi_z(qz, zp, zm, En, aa);\n\tktheta = (aa*aa * (1 - En*En)*zm*zm)/zp*zp;\n\tellpi_k = gsl_sf_ellint_Pcomp(sqrt(ktheta), -zm*zm, GSL_PREC_DOUBLE);\n\tincpi_k = gsl_sf_ellint_P(psi_z, sqrt(ktheta), -zm*zm, GSL_PREC_DOUBLE);\n\treturn (-((Lz*((2*(M_PI/2. + qz)*ellpi_k)/M_PI - \n\t\t\tincpi_k))/zp));\n}\n\n\ndouble calc_Ct(double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa) {\n\n\tdouble t_r, t_z;\n\tt_r = calc_t_r(qr0, r1, r2, r3, r4, En, Lz, aa);\n\tt_z = calc_t_z(qz0, zp, zm, En, aa);\n\treturn t_r + t_z;\n}\n\n\ndouble calc_Cz(double qr0, double qz0, double r1, double r2, double r3, double r4,\n\tdouble zp, double zm, double En, double Lz, double aa) {\n\n\tdouble phi_r, phi_z;\n\tphi_r = calc_phi_r(qr0, r1, r2, r3, r4, En, Lz, aa);\n\tphi_z = calc_phi_z(qz0, zp, zm, En, Lz, aa);\n\treturn phi_r + phi_z;\n}\n\n\ndouble calc_t(double mino_t, double ups_r, double ups_theta, double gamma,\n\tdouble qt0, double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa){\n\n\tdouble eta_t, eta_r, eta_z, t_r, t_z, Ct;\n\teta_t = qt0 + gamma * mino_t;\n\teta_r = qr0 + ups_r * mino_t;\n\teta_z = qz0 + ups_theta * mino_t;\n\tif (r1 == r2) {\n\t\tt_r = 0;\n\t} else {\n\t\tt_r = calc_t_r(eta_r, r1, r2, r3, r4, En, Lz, aa);\n\t\t// printf(\"t_r = %.17g \\n\", t_r);\n\t}\n\tif (zm == 0){\n\t\tt_z = 0;\n\t} else {\n\t\tt_z = calc_t_z(eta_z, zp, zm, En, aa);\n\t}\n\tif (qr0 == 0 && qz0 == 0) {\n\t\tCt = 0;\n\t} else {\n\t\tCt = calc_Ct(qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\t}\n\treturn eta_t + t_r + t_z - Ct;\n}\n\n\ndouble calc_r(double mino_t, double ups_r, double qr0, double r1, double r2,\n\tdouble r3, double r4){\n\n\tdouble eta;\n\teta = ups_r * mino_t + qr0;\n\treturn calc_rq(eta, r1, r2, r3, r4);\n}\n\n\ndouble calc_theta(double mino_t, double ups_theta, double qz0, double zp,\n\tdouble zm, double En, double aa){\n\n\tdouble eta;\n\teta = ups_theta * mino_t + qz0;\n\treturn acos(calc_zq(eta, zp, zm, En, aa));\n}\n\n\ndouble calc_phi(double mino_t, double ups_r, double ups_theta, double ups_phi,\n\tdouble qphi0, double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa){\n\n\tdouble eta_phi, eta_r, eta_theta, phi_r, phi_z, Cz;\n\teta_phi = ups_phi * mino_t + qphi0;\n\teta_r = ups_r * mino_t + qr0;\n\teta_theta = ups_theta * mino_t + qz0;\n\tif (r1 == r2) {\n\t\tphi_r = 0;\n\t} else {\n\t\tphi_r = calc_phi_r(eta_r, r1, r2, r3, r4, En, Lz, aa);\n\t}\n\n\tif (zm == 0) {\n\t\tphi_z = 0;\n\t}\n\telse {\n\t\tphi_z = calc_phi_z(eta_theta, zp, zm, En, Lz, aa);\n\t}\n\n\tif (qr0 == 0 && qz0 == 0){\n\t\tCz = 0;\n\t} else {\n\t\tCz = calc_Cz(qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\t}\n\treturn eta_phi + phi_r + phi_z - Cz;\n}\n\n\ndouble calc_J(double chi, double En, double Lz, double Q, double aa, double slr, double ecc) {\n    // \"\"\"\n    // Schmidt's J function.\n\n    // Parameters:\n    //     chi (float): radial angle\n    //     En (float): energy\n    //     Lz (float): angular momentum\n    //     Q (float): Carter constant\n    //     aa (float): spin\n    //     slr (float): semi-latus rectum\n    //     ecc (float): eccentricity\n\n    // Returns:\n    //     J (float)\n    // \"\"\"\n    double En2 = En * En;\n    double ecc2 = ecc * ecc;\n    double aa2 = aa * aa;\n    double Lz2 = Lz * Lz;\n    double slr2 = slr * slr;\n\n    double eta = 1 + ecc * cos(chi);\n    double eta2 = eta * eta;\n\n    double J = (\n        (1 - ecc2) * (1 - En2)\n        + 2 * (1 - En2 - (1 - ecc2) / slr) * eta\n        + (\n            ((3 + ecc2) * (1 - En2)) / (1 - ecc2)\n            + ((1 - ecc2) * (aa2 * (1 - En2) + Lz2 + Q)) / slr2\n            - 4 / slr\n        )\n        * eta2\n    );\n\n    return J;\n}\n\n\n// double calc_wr(double psi, double ups_r, double En, double Lz,\n// \t\t\t   double Q, double aa, double slr, double ecc, double x) {\n// \t// note that this has only been checked for psi in [0, pi]\n// \tdouble aa2 = aa * aa;\n// \tdouble slr2 = slr * slr;\n// \tdouble ecc2 = ecc * ecc;\n// \tdouble En2 = En * En;\n// \tdouble Lz2 = Lz * Lz;\n// \tdouble a1 = (1 - ecc2) * (1 - En2);\n//     double b1 = 2 * (1 - En2 - (1 - ecc2) / slr);\n//     double c1 = (((3 + ecc2)*(1 - En2))/(1 - ecc2) - 4/slr + \n//           \t\t ((1 - ecc2) * (aa2*(1 - En2) + Lz2 + Q)) / slr2);\n\n// \tdouble b12 = b1 * b1;\n// \tif (psi == M_PI) {\n// \t\treturn M_PI;\n// \t} else {\n// \t\tcomplex<double> phi {0, asinh(sqrt((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))/\n//        \t\t\t\t\t\t (a1 + b1 + c1 - c1*ecc2 + sqrt(b12 - 4*a1*c1)*ecc2)))* tan(psi/2.))};\n\n// \t \tdouble m = ((a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2))/\n//   \t\t\t\t    (a1 + b1 + c1 - c1*ecc2 - sqrt((b12 - 4*a1*c1)*ecc2)));\n// \t\tdouble k = sqrt(m);\n// \t\tcomplex<double> ellint_f = ellint_1(k, phi);\n// \t\tcomplex<double> res {0, ((-2*(1 - ecc2) * ellint_f * ups_r * power(cos(psi/2.),2)*\n// \t\t\t\tsqrt(2 + (2*(a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))*power(tan(psi/2.),2))/\n// \t\t\t\t\t(a1 + b1 + c1 - c1*ecc2 - sqrt(b12 - 4*a1*c1)*ecc2)))*\n// \t\t\t\tsqrt(1 + ((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))*power(tan(psi/2.),2))/\n// \t\t\t\t\t(a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2))))/\n// \t\t\t(sqrt((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))/\n// \t\t\t\t(a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2)))*\n// \t\t\t\tslr*sqrt(2*a1 + 2*b1 + 2*c1 + c1*ecc2 + 2*(b1 + 2*c1)*ecc*cos(psi) + \n// \t\t\t\tc1*ecc2*cos(2*psi))))};\n// \t\tdouble re_res = real(res);\n\t\t\n// \t\treturn re_res;\n// \t}\n// }\n\n\ndouble calc_dwr_dpsi(double psi, double ups_r, double En, double Lz,\n\t\t\t\t\t double Q, double aa, double slr, double ecc) {\n    double J = calc_J(psi, En, Lz, Q, aa, slr, ecc);\n\tdouble ecc2 = ecc * ecc;\n    return (1 - ecc2) / slr * ups_r / sqrt(J);\n}\n\n\n// double calc_wtheta(double chi, double ups_theta, double zp, double zm,\n// \t\t\t\t   double En, double Lz, double aa, double slr, double x) {\n//     // \"\"\"\n//     // w_theta = ups_theta * lambda as a function of polar angle chi\n\n//     // Parameters:\n//     //     chi (float): polar angle\n//     //     ups_theta (float): theta mino frequency\n//     //     En (float): energy\n//     //     Lz (float): angular momentum\n//     //     aa (float): spin\n//     //     slr (float): semi-latus rectum\n//     //     x (float): inclination\n\n//     // Returns:\n//     //     w_theta (float)\n//     // \"\"\"\n//     double pi = M_PI;\n//     if (chi >= 0 && chi <= pi / 2) {\n//         return ups_theta * calc_lambda_chi(chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > pi / 2 && chi <= pi) {\n//         return pi - ups_theta * calc_lambda_chi(pi - chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > pi && chi <= 3 * pi / 2) {\n//         return pi + ups_theta * calc_lambda_chi(chi - pi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > 3 * pi / 2 && chi <= 2 * pi) {\n//         return 2 * pi - ups_theta * calc_lambda_chi(2 * pi - chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else {\n//         // print(\"Something went wrong in calc_wtheta!\")\n//         return 0.0;  // this case should not occur, but is required by C++\n// \t}\n// }\n\n\ndouble calc_dwtheta_dchi(double chi, double zp, double zm) {\n    // \"\"\"\n    // derivative of w_theta\n\n    // Parameters:\n    //     chi (float): polar angle\n    //     zp (float): polar root\n    //     zm (float): polar root\n\n    // Returns:\n    //     dw_dtheta (float)\n    // \"\"\"\n    double k = sqrt(zm / zp);\n    double ellipticK_k = gsl_sf_ellint_Kcomp(k, GSL_PREC_DOUBLE);\n    return M_PI / (2 * ellipticK_k) * (1 / (1 - k * k * pow(cos(chi),2)));\n}\n\n\nvoid calc_circular_eq_coords(double &t, double &r, double &theta, double &phi,\n\t\t\t\t\t\t\t double psi, double En, double Lz, double aa, double slr, double M) {\n    // lam_psi is used to cross check with circular orbits in BHPTK\n    // lam_psi = (psi / (sqrt(1 - En**2 + 3*(1 - En**2) + 2*(1 - En**2 - 1/slr) + \n    //            (aa**2*(1 - En**2) + Lz**2)/slr**2 - 4/slr)*slr))\n    // print(lam_psi)\n\n\tdouble x, Vr, Vphi, Vt, J, denom;\n\tdouble aa2 = aa * aa;\n\tdouble slr2 = slr * slr;\n\tx = Lz - aa * En;\n\tdouble x2 = x * x;\n\n    Vr = aa2 + x2 + 2 * aa * x * En - 6 * M * x2 / slr;\n    Vphi = x + aa * En - 2 * M * x / slr;\n    Vt = aa2 * En - 2 * aa * M * x / slr + En * slr2;\n    J = 1 - 2 * M / slr + aa2 / slr2;\n    denom = J * sqrt(Vr);\n\tt = Vt / denom * psi;\n    phi = Vphi / denom * psi;\n    r = slr;\n\ttheta = M_PI / 2;\n}\n\n\nvoid calc_equatorial_coords(double &t, double &r, double &theta, double &phi,\n\tdouble psi, double ups_r, double ups_theta,\n\tdouble ups_phi, double gamma, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa,\n\tdouble slr, double ecc, double qt0, double qr0, double qz0,\n\tdouble qphi0) {\n\n\tdouble lam_psi;\n\tif (zm != 0){\n\t\tprintf(\"The orbit specified is not equatorial.\\n\");\n\t}\n\tr = calc_radius(psi, slr, ecc);\n\tlam_psi = calc_lambda_psi(psi, ups_r, r1, r2, r3, r4, En, slr, ecc);\n\tt = calc_t(lam_psi, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4,\n\t\t\t   zp, zm, En, Lz, aa);\n\ttheta = M_PI / 2;  // TODO(aaron): check generic theta\n\tphi = calc_phi(lam_psi, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2,\n\t\t\t\t   r3, r4, zp, zm, En, Lz, aa);\n\n}\n\n\nvoid calc_gen_coords_mino(double &t, double &r, double &theta, double &phi,\n\tdouble mino_t, double ups_r, double ups_theta, double ups_phi, double gamma,\n    double r1, double r2, double r3, double r4, double zp, double zm, double En,\n    double Lz, double aa, double qphi0, double qr0, double qz0, double qt0) {\n\n\tt = calc_t(mino_t, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\tr = calc_r(mino_t, ups_r, qr0, r1, r2, r3, r4);\n\ttheta = calc_theta(mino_t, ups_theta, qz0, zp, zm, En, aa);\n\tphi = calc_phi(mino_t, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n}\n\n\n// void calc_gen_coords_psi(double &t, double &r, double &theta, double &phi,\n// \tdouble psi, double ups_r, double ups_theta, double ups_phi, double gamma,\n//     double r1, double r2, double r3, double r4, double zp, double zm, double En,\n// \tdouble Lz, double Q, double aa, double slr, double ecc, double x,\n// \tdouble qphi0, double qr0, double qz0, double qt0) {\n\n// \tdouble wr = calc_wr(psi, ups_r, En, Lz, Q, aa, slr, ecc, x);\n// \tdouble mino_t = wr / ups_r;\n// \tt = calc_t(mino_t, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n// \tr = calc_r(mino_t, ups_r, qr0, r1, r2, r3, r4);\n// \ttheta = calc_theta(mino_t, ups_theta, qz0, zp, zm, En, aa);\n// \tphi = calc_phi(mino_t, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n// }\n\n\n", "meta": {"hexsha": "40cf51612f45bd324d669560aa635fb5f9bbca6f", "size": 18431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geodesic/coordsc.cpp", "max_stars_repo_name": "AaronDJohnson/fbtpoint", "max_stars_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-19T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T19:14:03.000Z", "max_issues_repo_path": "geodesic/coordsc.cpp", "max_issues_repo_name": "AaronDJohnson/fbtpoint", "max_issues_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geodesic/coordsc.cpp", "max_forks_repo_name": "AaronDJohnson/fbtpoint", "max_forks_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_forks_repo_licenses": ["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.7775862069, "max_line_length": 107, "alphanum_fraction": 0.582985188, "num_tokens": 7272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6583112318889769}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2006 - 2016 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level directory of deal.II.\n *\n * ---------------------------------------------------------------------\n *\n * Author: Ivan Christov, Wolfgang Bangerth, Texas A&M University, 2006\n */\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <fstream>\n#include <iostream>\nnamespace Step25\n{\n  using namespace dealii;\n  template <int dim>\n  class SineGordonProblem\n  {\n  public:\n    SineGordonProblem();\n    void run();\n  private:\n    void         make_grid_and_dofs();\n    void         assemble_system();\n    void         compute_nl_term(const Vector<double> &old_data,\n                                 const Vector<double> &new_data,\n                                 Vector<double> &      nl_term) const;\n    void         compute_nl_matrix(const Vector<double> &old_data,\n                                   const Vector<double> &new_data,\n                                   SparseMatrix<double> &nl_matrix) const;\n    unsigned int solve();\n    void         output_results(const unsigned int timestep_number) const;\n    Triangulation<dim> triangulation;\n    FE_Q<dim>          fe;\n    DoFHandler<dim>    dof_handler;\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    SparseMatrix<double> mass_matrix;\n    SparseMatrix<double> laplace_matrix;\n    const unsigned int n_global_refinements;\n    double       time;\n    const double final_time, time_step;\n    const double theta;\n    Vector<double> solution, solution_update, old_solution;\n    Vector<double> M_x_velocity;\n    Vector<double> system_rhs;\n    const unsigned int output_timestep_skip;\n  };\n  template <int dim>\n  class ExactSolution : public Function<dim>\n  {\n  public:\n    ExactSolution(const unsigned int n_components = 1, const double time = 0.)\n      : Function<dim>(n_components, time)\n    {}\n    virtual double value(const Point<dim> & p,\n                         const unsigned int component = 0) const override;\n  };\n  template <int dim>\n  double ExactSolution<dim>::value(const Point<dim> &p,\n                                   const unsigned int /*component*/) const\n  {\n    double t = this->get_time();\n    switch (dim)\n      {\n        case 1:\n          {\n            const double m  = 0.5;\n            const double c1 = 0.;\n            const double c2 = 0.;\n            return -4. * std::atan(m / std::sqrt(1. - m * m) *\n                                   std::sin(std::sqrt(1. - m * m) * t + c2) /\n                                   std::cosh(m * p[0] + c1));\n          }\n        case 2:\n          {\n            const double theta  = numbers::PI / 4.;\n            const double lambda = 1.;\n            const double a0     = 1.;\n            const double s      = 1.;\n            const double arg    = p[0] * std::cos(theta) +\n                               std::sin(theta) * (p[1] * std::cosh(lambda) +\n                                                  t * std::sinh(lambda));\n            return 4. * std::atan(a0 * std::exp(s * arg));\n          }\n        case 3:\n          {\n            const double theta = numbers::PI / 4;\n            const double phi   = numbers::PI / 4;\n            const double tau   = 1.;\n            const double c0    = 1.;\n            const double s     = 1.;\n            const double arg   = p[0] * std::cos(theta) +\n                               p[1] * std::sin(theta) * std::cos(phi) +\n                               std::sin(theta) * std::sin(phi) *\n                                 (p[2] * std::cosh(tau) + t * std::sinh(tau));\n            return 4. * std::atan(c0 * std::exp(s * arg));\n          }\n        default:\n          Assert(false, ExcNotImplemented());\n          return -1e8;\n      }\n  }\n  template <int dim>\n  class InitialValues : public Function<dim>\n  {\n  public:\n    InitialValues(const unsigned int n_components = 1, const double time = 0.)\n      : Function<dim>(n_components, time)\n    {}\n    virtual double value(const Point<dim> & p,\n                         const unsigned int component = 0) const override;\n  };\n  template <int dim>\n  double InitialValues<dim>::value(const Point<dim> & p,\n                                   const unsigned int component) const\n  {\n    return ExactSolution<dim>(1, this->get_time()).value(p, component);\n  }\n  template <int dim>\n  SineGordonProblem<dim>::SineGordonProblem()\n    : fe(1)\n    , dof_handler(triangulation)\n    , n_global_refinements(6)\n    , time(-5.4414)\n    , final_time(2.7207)\n    , time_step(10 * 1. / std::pow(2., 1. * n_global_refinements))\n    , theta(0.5)\n    , output_timestep_skip(1)\n  {}\n  template <int dim>\n  void SineGordonProblem<dim>::make_grid_and_dofs()\n  {\n    GridGenerator::hyper_cube(triangulation, -10, 10);\n    triangulation.refine_global(n_global_refinements);\n    std::cout << \"   Number of active cells: \" << triangulation.n_active_cells()\n              << std::endl\n              << \"   Total number of cells: \" << triangulation.n_cells()\n              << std::endl;\n    dof_handler.distribute_dofs(fe);\n    std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n              << std::endl;\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern(dof_handler, dsp);\n    sparsity_pattern.copy_from(dsp);\n    system_matrix.reinit(sparsity_pattern);\n    mass_matrix.reinit(sparsity_pattern);\n    laplace_matrix.reinit(sparsity_pattern);\n    MatrixCreator::create_mass_matrix(dof_handler,\n                                      QGauss<dim>(fe.degree + 1),\n                                      mass_matrix);\n    MatrixCreator::create_laplace_matrix(dof_handler,\n                                         QGauss<dim>(fe.degree + 1),\n                                         laplace_matrix);\n    solution.reinit(dof_handler.n_dofs());\n    solution_update.reinit(dof_handler.n_dofs());\n    old_solution.reinit(dof_handler.n_dofs());\n    M_x_velocity.reinit(dof_handler.n_dofs());\n    system_rhs.reinit(dof_handler.n_dofs());\n  }\n  template <int dim>\n  void SineGordonProblem<dim>::assemble_system()\n  {\n    system_matrix.copy_from(mass_matrix);\n    system_matrix.add(std::pow(time_step * theta, 2), laplace_matrix);\n    SparseMatrix<double> tmp_matrix(sparsity_pattern);\n    compute_nl_matrix(old_solution, solution, tmp_matrix);\n    system_matrix.add(std::pow(time_step * theta, 2), tmp_matrix);\n    system_rhs = 0.;\n    Vector<double> tmp_vector(solution.size());\n    mass_matrix.vmult(system_rhs, solution);\n    laplace_matrix.vmult(tmp_vector, solution);\n    system_rhs.add(std::pow(time_step * theta, 2), tmp_vector);\n    mass_matrix.vmult(tmp_vector, old_solution);\n    system_rhs.add(-1.0, tmp_vector);\n    laplace_matrix.vmult(tmp_vector, old_solution);\n    system_rhs.add(std::pow(time_step, 2) * theta * (1 - theta), tmp_vector);\n    system_rhs.add(-time_step, M_x_velocity);\n    compute_nl_term(old_solution, solution, tmp_vector);\n    system_rhs.add(std::pow(time_step, 2) * theta, tmp_vector);\n    system_rhs *= -1.;\n  }\n  template <int dim>\n  void SineGordonProblem<dim>::compute_nl_term(const Vector<double> &old_data,\n                                               const Vector<double> &new_data,\n                                               Vector<double> &nl_term) const\n  {\n    nl_term = 0;\n    const QGauss<dim> quadrature_formula(fe.degree + 1);\n    FEValues<dim>     fe_values(fe,\n                            quadrature_formula,\n                            update_values | update_JxW_values |\n                              update_quadrature_points);\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size();\n    Vector<double>                       local_nl_term(dofs_per_cell);\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n    std::vector<double>                  old_data_values(n_q_points);\n    std::vector<double>                  new_data_values(n_q_points);\n    typename DoFHandler<dim>::active_cell_iterator cell =\n                                                     dof_handler.begin_active(),\n                                                   endc = dof_handler.end();\n    for (; cell != endc; ++cell)\n      {\n        local_nl_term = 0;\n        fe_values.reinit(cell);\n        fe_values.get_function_values(old_data, old_data_values);\n        fe_values.get_function_values(new_data, new_data_values);\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            local_nl_term(i) +=\n              (std::sin(theta * new_data_values[q_point] +\n                        (1 - theta) * old_data_values[q_point]) *\n               fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n        cell->get_dof_indices(local_dof_indices);\n        for (unsigned int i = 0; i < dofs_per_cell; ++i)\n          nl_term(local_dof_indices[i]) += local_nl_term(i);\n      }\n  }\n  template <int dim>\n  void SineGordonProblem<dim>::compute_nl_matrix(\n    const Vector<double> &old_data,\n    const Vector<double> &new_data,\n    SparseMatrix<double> &nl_matrix) const\n  {\n    QGauss<dim>   quadrature_formula(fe.degree + 1);\n    FEValues<dim> fe_values(fe,\n                            quadrature_formula,\n                            update_values | update_JxW_values |\n                              update_quadrature_points);\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size();\n    FullMatrix<double> local_nl_matrix(dofs_per_cell, dofs_per_cell);\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n    std::vector<double>                  old_data_values(n_q_points);\n    std::vector<double>                  new_data_values(n_q_points);\n    typename DoFHandler<dim>::active_cell_iterator cell =\n                                                     dof_handler.begin_active(),\n                                                   endc = dof_handler.end();\n    for (; cell != endc; ++cell)\n      {\n        local_nl_matrix = 0;\n        fe_values.reinit(cell);\n        fe_values.get_function_values(old_data, old_data_values);\n        fe_values.get_function_values(new_data, new_data_values);\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            for (unsigned int j = 0; j < dofs_per_cell; ++j)\n              local_nl_matrix(i, j) +=\n                (std::cos(theta * new_data_values[q_point] +\n                          (1 - theta) * old_data_values[q_point]) *\n                 fe_values.shape_value(i, q_point) *\n                 fe_values.shape_value(j, q_point) * fe_values.JxW(q_point));\n        cell->get_dof_indices(local_dof_indices);\n        for (unsigned int i = 0; i < dofs_per_cell; ++i)\n          for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            nl_matrix.add(local_dof_indices[i],\n                          local_dof_indices[j],\n                          local_nl_matrix(i, j));\n      }\n  }\n  template <int dim>\n  unsigned int SineGordonProblem<dim>::solve()\n  {\n    SolverControl solver_control(1000, 1e-12 * system_rhs.l2_norm());\n    SolverCG<>    cg(solver_control);\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n    cg.solve(system_matrix, solution_update, system_rhs, preconditioner);\n    return solver_control.last_step();\n  }\n  template <int dim>\n  void SineGordonProblem<dim>::output_results(\n    const unsigned int timestep_number) const\n  {\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler(dof_handler);\n    data_out.add_data_vector(solution, \"u\");\n    data_out.build_patches();\n    const std::string filename =\n      \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtk\";\n    std::ofstream output(filename);\n    data_out.write_vtk(output);\n  }\n  template <int dim>\n  void SineGordonProblem<dim>::run()\n  {\n    make_grid_and_dofs();\n    {\n      AffineConstraints<double> constraints;\n      constraints.close();\n      VectorTools::project(dof_handler,\n                           constraints,\n                           QGauss<dim>(fe.degree + 1),\n                           InitialValues<dim>(1, time),\n                           solution);\n    }\n    output_results(0);\n    unsigned int timestep_number = 1;\n    for (time += time_step; time <= final_time;\n         time += time_step, ++timestep_number)\n      {\n        old_solution = solution;\n        std::cout << std::endl\n                  << \"Time step #\" << timestep_number << \"; \"\n                  << \"advancing to t = \" << time << \".\" << std::endl;\n        double initial_rhs_norm = 0.;\n        bool   first_iteration  = true;\n        do\n          {\n            assemble_system();\n            if (first_iteration == true)\n              initial_rhs_norm = system_rhs.l2_norm();\n            const unsigned int n_iterations = solve();\n            solution += solution_update;\n            if (first_iteration == true)\n              std::cout << \"    \" << n_iterations;\n            else\n              std::cout << '+' << n_iterations;\n            first_iteration = false;\n          }\n        while (system_rhs.l2_norm() > 1e-6 * initial_rhs_norm);\n        std::cout << \" CG iterations per nonlinear step.\" << std::endl;\n        Vector<double> tmp_vector(solution.size());\n        laplace_matrix.vmult(tmp_vector, solution);\n        M_x_velocity.add(-time_step * theta, tmp_vector);\n        laplace_matrix.vmult(tmp_vector, old_solution);\n        M_x_velocity.add(-time_step * (1 - theta), tmp_vector);\n        compute_nl_term(old_solution, solution, tmp_vector);\n        M_x_velocity.add(-time_step, tmp_vector);\n        if (timestep_number % output_timestep_skip == 0)\n          output_results(timestep_number);\n      }\n  }\n} // namespace Step25\nint main()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step25;\n      SineGordonProblem<1> sg_problem;\n      sg_problem.run();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  return 0;\n}\n", "meta": {"hexsha": "3e2c6ef2d116ec92e7a57479956ab76cc485a5ba", "size": 16188, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/DEALII/sine-GordonEquation/main.cc", "max_stars_repo_name": "chtld/Finite_Element_Method", "max_stars_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-09-03T14:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:12:55.000Z", "max_issues_repo_path": "src/DEALII/sine-GordonEquation/main.cc", "max_issues_repo_name": "chtld/Finite_Element_Method_for_1D_Possion_Equation", "max_issues_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_issues_repo_licenses": ["MIT"], "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/DEALII/sine-GordonEquation/main.cc", "max_forks_repo_name": "chtld/Finite_Element_Method_for_1D_Possion_Equation", "max_forks_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T07:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T09:04:07.000Z", "avg_line_length": 40.2686567164, "max_line_length": 80, "alphanum_fraction": 0.5690017297, "num_tokens": 3774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.658311220263703}}
{"text": "#include <Eigen/LU>\n#include <Eigen/QR>\n#include <array>\n\n#include <jrl-qp/test/kkt.h>\n#include <jrl-qp/test/randomMatrices.h>\n#include <jrl-qp/test/randomProblems.h>\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS\n#include \"doctest/doctest.h\"\n\nusing namespace jrl::qp::test;\n\n// TEST_CASE(\"Random orthogonal matrices\")\n//{\n//  const int N = 1000;\n//  int positive = 0;\n//  for (int i = 0; i < N; ++i)\n//  {\n//    int s = 5 + (10 * i) / N;\n//    Eigen::MatrixXd Q = randOrtho(s);\n//    FAST_REQUIRE_EQ(Q.rows(), Q.cols());\n//    FAST_CHECK_EQ(Q.cols(), s);\n//\n//    double det = Q.lu().determinant();\n//    FAST_CHECK_EQ(std::abs(det), doctest::Approx(1).epsilon(1e-8));\n//    if (det > 0) ++positive;\n//\n//    FAST_CHECK_UNARY((Q.transpose() * Q).isIdentity(1e-8));\n//    FAST_CHECK_UNARY((Q * Q.transpose()).isIdentity(1e-8));\n//  }\n//  FAST_CHECK_UNARY(429 <= positive && positive <= 571); //this can fails in less than 0.001% of cases.\n//\n//  for (int i = 0; i < N; ++i)\n//  {\n//    int s = 5 + (10 * i) / N;\n//    Eigen::MatrixXd Q = randOrtho(s, true);\n//    double det = Q.lu().determinant();\n//    FAST_CHECK_EQ(det, doctest::Approx(1).epsilon(1e-8));\n//  }\n//}\n//\n// TEST_CASE(\"Random rank deficient matrices\")\n//{\n//  std::array<Eigen::Index, 5> sizes = {10,25,50,75,100};\n//  Eigen::Index n = 0;\n//  double mean = 0;\n//  double var = 0;\n//  Precompute the required size for storing all coefficients\n//  for (auto rows : sizes)\n//  {\n//    for (auto cols : sizes)\n//    {\n//      for (auto rank : sizes)\n//      {\n//        if (rank <= rows && rank <= cols)\n//          n += rows * cols;\n//      }\n//    }\n//  }\n//  std::vector<double> val;\n//  val.reserve(n);\n//\n//  Testing the rank of generated matrices\n//  for (auto rows: sizes)\n//  {\n//    for (auto cols: sizes)\n//    {\n//      for (auto rank: sizes)\n//      {\n//        if (rank > rows || rank > cols) //we skip when rank > min(rows,cols)\n//          continue;\n//        Eigen::MatrixXd M = randn(rows, cols, rank);\n//        FAST_CHECK_EQ(M.colPivHouseholderQr().rank(), rank);\n//        std::copy(M.data(), M.data() + rows * cols, std::back_inserter(val));\n//      }\n//    }\n//  }\n//\n//  Computing and testing mean and variance\n//  for (int i = 0; i < n; ++i)\n//  {\n//    mean += val[i];\n//  }\n//  mean /= n;\n//  for (int i = 0; i < n; ++i)\n//  {\n//    var += (val[i] - mean) * (val[i] - mean);\n//  }\n//  var /= n;\n//\n//  FAST_CHECK_EQ(std::abs(mean), doctest::Approx(0).epsilon(1e-2));\n//  FAST_CHECK_EQ(var, doctest::Approx(1).epsilon(2.5e-2));\n//}\n//\n// TEST_CASE(\"Random dependent matrices\")\n//{\n//  std::vector<std::array<Eigen::Index, 6>> params = {\n//    { 15, 5, 4, 7, 7, 9 },\n//    { 15, 5, 4, 7, 5, 9 },\n//    { 10, 5, 4, 7, 7, 9 },\n//    { 7, 8, 4, 12, 6, 7 },\n//    { 7, 8, 4, 12, 6, 6 } };\n//  for (const auto& p: params)\n//  {\n//    auto [cols, rowsA, rankA, rowsB, rankB, rankAB] = p;\n//    auto [A, B] = randDependent(cols, rowsA, rankA, rowsB, rankB, rankAB);\n//    FAST_REQUIRE_EQ(A.rows(), rowsA);\n//    FAST_REQUIRE_EQ(A.cols(), cols);\n//    FAST_REQUIRE_EQ(B.rows(), rowsB);\n//    FAST_REQUIRE_EQ(B.cols(), cols);\n//    Eigen::MatrixXd M(rowsA+rowsB, cols); M << A, B;\n//    FAST_CHECK_EQ(A.colPivHouseholderQr().rank(), rankA);\n//    FAST_CHECK_EQ(B.colPivHouseholderQr().rank(), rankB);\n//    FAST_CHECK_EQ(M.colPivHouseholderQr().rank(), rankAB);\n//  }\n//}\n\nvoid testRandomProblem(const RandomLeastSquare & pb)\n{\n  FAST_CHECK_UNARY(pb.wellFormed());\n  Eigen::VectorXd mult(pb.l.size() + pb.f.size() + pb.xl.size());\n  mult << pb.lambdaEq, pb.lambdaIneq, pb.lambdaBnd;\n  FAST_CHECK_UNARY(testKKT(pb.x, mult, pb));\n}\n\nTEST_CASE(\"Random Least Squares\")\n{\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 3)));\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 3).nEq(2)));\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 0).nEq(2)));\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 3).nIneq(5)));\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 3).nIneq(5).nStrongActIneq(2)));\n  testRandomProblem(randomProblem(ProblemCharacteristics(5, 3).nIneq(5).nStrongActIneq(4)));\n  testRandomProblem(randomProblem({5, 3, 2, 5, 3, 0, 2, 0, 0, 0, false, false, false}));\n  testRandomProblem(randomProblem({5, 3, 1, 5, 3, 0, 1, 0, 0, 0, false, false, false}));\n}\n", "meta": {"hexsha": "940818d2115f03e19c1dca8e65b2b5d66999ad6e", "size": 4337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/RandomProblemsTest.cpp", "max_stars_repo_name": "mehdi-benallegue/jrl-qp", "max_stars_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T09:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:42:58.000Z", "max_issues_repo_path": "tests/RandomProblemsTest.cpp", "max_issues_repo_name": "mehdi-benallegue/jrl-qp", "max_issues_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-21T10:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-21T11:13:41.000Z", "max_forks_repo_path": "tests/RandomProblemsTest.cpp", "max_forks_repo_name": "mehdi-benallegue/jrl-qp", "max_forks_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:11:44.000Z", "avg_line_length": 31.2014388489, "max_line_length": 104, "alphanum_fraction": 0.5951118285, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.8354835289107309, "lm_q1q2_score": 0.6583035358745771}}
{"text": "#include <cap_gait/contrib/KalmanFilter.h>\r\n#include <Eigen/LU>\r\n\r\nusing namespace margait_contrib;\r\n\r\nKalmanFilter::KalmanFilter()\r\n{\r\n\tlastX = 0;\r\n\tlastV = 0;\r\n\tsmoothing = 0.1;\r\n\ttimeStep = 0.010;\r\n\tx = 0;\r\n\tv = 0;\r\n\ta = 0;\r\n\tpx = 0;\r\n\tpv = 0;\r\n\tpa = 0;\r\n\r\n\t// When the gain is adaptive, the smoothing config parameters don't make any difference.\r\n\tadaptiveGain = true;\r\n\r\n\tinit();\r\n}\r\n\r\n// Prepares (resets) the noise matrices and the kalman gain, but preserves the current state.\r\n// This is good for changing the smoothing on the fly without messing with the state estimate.\r\nvoid KalmanFilter::init()\r\n{\r\n\t// Process noise.\r\n\tQ = Eigen::Matrix3d::Identity();\r\n\r\n\t// Measurement noise.\r\n\tR = (0.001 + smoothing*100.0) * Eigen::Matrix3d::Identity();\r\n\r\n\t// Passive linear system dynamics matrix A.\r\n\tA << 1.0, timeStep,   0.0   ,\r\n\t     0.0,   1.0   , timeStep,\r\n\t     0.0,   0.0   ,   1.0   ;\r\n\r\n\t// State and measurement vectors.\r\n\tX << x, v, a;\r\n\tZ.setZero();\r\n\r\n\t// Other matrices\r\n\tH = I = K = Eigen::Matrix3d::Identity();\r\n\tP.setZero();\r\n}\r\n\r\n// Sets the smoothing parameter.\r\nvoid KalmanFilter::setSmoothing(double s)\r\n{\r\n\tsmoothing = s;\r\n\tinit();\r\n}\r\n\r\n// Sets the time interval between the updates. It's set to 10 milliseconds by default.\r\nvoid KalmanFilter::setTimeStep(double t)\r\n{\r\n\ttimeStep = t;\r\n\tinit();\r\n}\r\n\r\n// Resets the state to the provided parameters, but doesn't change the noise and the kalman gain.\r\n// This is good to set the state estimate on the fly without messing with the Kalman gain.\r\nvoid KalmanFilter::reset(double xx, double vv, double aa)\r\n{\r\n\tx = xx;\r\n\tv = vv;\r\n\ta = aa;\r\n\r\n\tX << x, v, a;\r\n\r\n\tlastX = x;\r\n\tlastV = v;\r\n}\r\n\r\n// Updates the process. Provide a position measurement z.\r\nvoid KalmanFilter::update(double z)\r\n{\r\n\tdouble Zv = (z - lastX)/timeStep;\r\n\tZ << z, Zv, (Zv - lastV)/timeStep;\r\n\tlastX = Z(0);\r\n\tlastV = Z(1);\r\n\r\n\tif (adaptiveGain)\r\n\t{\r\n\t\tX = A*X;\r\n\t\tP = A*P*A.transpose() + Q;\r\n\t\tK = P*H.transpose() * (H*P*H.transpose() + R).inverse();\r\n\t\tX = X + K*(Z - H*X);\r\n\t\tP = (I - K*H)*P;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tX = A*X;\r\n\t\tK = Q*H.transpose() * (H*Q*H.transpose() + R).inverse();\r\n\t\tX = X + K*(Z - H*X);\r\n\t}\r\n\r\n\tx = X(0);\r\n\tv = X(1);\r\n\ta = X(2);\r\n\r\n\tpx = P(0,0);\r\n\tpv = P(1,1);\r\n\tpa = P(2,2);\r\n}\r\n", "meta": {"hexsha": "200a6bf9f3ea53ecc200c046c949b388b3f6e99a", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 20.7685185185, "max_line_length": 98, "alphanum_fraction": 0.5898350424, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6582596035682807}}
{"text": "#include <NTL/RR.h>\n\n#include \"FactorBase.h\"\n\n#ifdef DEBUG\n#include<iostream>\n#endif\n\nFactorBase::FactorBase(ZZ bound)\n{\n    setBound(bound);\n}\n\nbool FactorBase::factor(std::vector<long>& f, const ZZ& _n)const\n{\n    /*\n     * Factorization of a number over a rational factor base.\n     */\n#ifdef DEBUG\n    std::cerr<<\"Value of factored num is: \"<<_n<<std::endl;\n#endif\n    if(_n == 0)\n    {\n        return false;\n    }\n    f.resize(r.size());\n    for(int i = 0; i < r.size(); ++i)\n    {\n        f[i] = 0;\n    }\n    ZZ n(_n);\n    if(n < 0)\n    {\n        f[0] = 1;\n        n = -n;\n    }\n    else\n    {\n        f[0] = 0;\n    }\n    ZZ q;\n    for(long i=1; i<smallInd; ++i)\n    {\n        while(n % r[i]  == 0)\n        {\n#ifdef DEBUG\n            std::cerr<<\"N=\"<<n<<\" is divisible by r=\"<<r[i]<<std::endl;\n#endif\n            n = n / r[i];\n            ++f[i];\n        }\n\n        if(n == 1)\n        {\n            return true;\n        }\n    }\n\n    if(n <= r[r.size()-1])\n    {\n        for(long i=0; i<r.size(); ++i)\n        {\n            if (n == r[i])\n            {\n                ++f[i];\n                return true;\n            }\n        }\n    }\n\n    for(long i=smallInd; i<r.size(); ++i)\n    {\n        if(n % r[i] == 0)\n        {\n            n = n / r[i];\n            ++f[i];\n        }\n        while(n % r[i]  == 0)\n        {\n            n = n / r[i];\n            ++f[i];\n        }\n        if(n <= r[r.size()-1])\n        {\n            if (n == 1)\n            {\n                return true;\n            }\n            for(long j=i+1; j<r.size(); ++j)\n            {\n                if (n == r[j])\n                {\n                    ++f[j];\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nFactorBase::FactorBase() {\n    count = 0;\n    smallInd = -1;\n    r.reserve(0);\n}\n\nvoid FactorBase::setBound(ZZ bound) {\n    /*\n     * Generating a rational factor base with upper bound of bound.\n     */\n    ZZ q = ZZ(-1);\n    ZZ elem;\n    smallInd = 0;\n#ifdef DEBUG\n    std::cerr<<\"Rational factor base elements are:\\n\";\n#endif\n    while(q<bound)\n    {\n#ifdef DEBUG\n        std::cerr<<q<<\" \";\n#endif\n        elem = q;\n        r.push_back(elem);\n        count++;\n        q = NextPrime(q+1);\n    }\n    while(r[smallInd] < TruncToZZ(sqrt(conv<RR>(r[r.size()-1]))))\n    {\n        ++smallInd;\n    }\n#ifdef DEBUG\n    std::cerr<<\"\\n\";\n#endif\n}\n\nunsigned long FactorBase::getSize() const\n{\n    return r.size();\n}\n", "meta": {"hexsha": "638b12c9009e4e692b0db35174755cec433cbfb5", "size": 2443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FactorBase.cpp", "max_stars_repo_name": "Saviero/discrete-log", "max_stars_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FactorBase.cpp", "max_issues_repo_name": "Saviero/discrete-log", "max_issues_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FactorBase.cpp", "max_forks_repo_name": "Saviero/discrete-log", "max_forks_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_forks_repo_licenses": ["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.3262411348, "max_line_length": 71, "alphanum_fraction": 0.3905034793, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.658232197183446}}
{"text": "/////////////////////////////////////////\n// Double integrator dynamics template //\n/////////////////////////////////////////\n\n#include <array>\n#include <Eigen/Core>\n\n#include \"dynamic_system.hh\"\n\n// Foward declaration, REQUIRED for template code to work\nclass DoubleIntegrator;\n\n// Template specialization of traits class to define the state, control and output type\ntemplate <> struct DynamicSystem_traits<DoubleIntegrator> {\n    enum { POS=0,\n           VEL,\n           x_dim_};\n    enum { ACCEL=0,\n           u_dim_};\n    using StateVector   = Eigen::Matrix<double, x_dim_, 1>;\n    using ControlVector = Eigen::Matrix<double, u_dim_, 1>;\n};\n\n// Curiously recurring template pattern (CRTP) is used here\nclass DoubleIntegrator : public DynamicSystem <DoubleIntegrator>\n{\npublic:\n    inline static int x_dim() { return DynamicSystem_traits<DoubleIntegrator>::x_dim_;}\n    inline static int u_dim() { return DynamicSystem_traits<DoubleIntegrator>::u_dim_;}\n\n    //Here we use a functor to make it work with function calling that requires non-static functions\n    struct\n    {\n        StateVector operator() (const StateVector & x, const ControlVector & u)\n        {\n            StateVector dxdt;\n            dxdt[0] = x[1];\n            dxdt[1] = u[0];\n            return dxdt;\n        }\n    } continuous_dynamics_impl;\n};\n", "meta": {"hexsha": "4bbe72c9600f6b4959891be2ea65327a79137c62", "size": 1322, "ext": "hh", "lang": "C++", "max_stars_repo_path": "double_integrator.hh", "max_stars_repo_name": "cgliu/dynamics", "max_stars_repo_head_hexsha": "83fd07c6eb6953806624403e5efc76bd88ea6f26", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-09T05:55:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T22:24:25.000Z", "max_issues_repo_path": "double_integrator.hh", "max_issues_repo_name": "cgliu/dynamics", "max_issues_repo_head_hexsha": "83fd07c6eb6953806624403e5efc76bd88ea6f26", "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": "double_integrator.hh", "max_forks_repo_name": "cgliu/dynamics", "max_forks_repo_head_hexsha": "83fd07c6eb6953806624403e5efc76bd88ea6f26", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-09T05:55:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-09T05:55:58.000Z", "avg_line_length": 30.7441860465, "max_line_length": 100, "alphanum_fraction": 0.6301059002, "num_tokens": 293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6582321867430281}}
{"text": "#include <iostream>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"Geometry/ParameterDesign/Bezier.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\nclass BezierVisualizer :public Visualizer\n{\nprotected:\n\tvoid AddPoint();\n\tvoid DragPoint();\n\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tbool updated = true;\n\n\tvoid evaluate_bezier()\n\t{\n\t\tBezierBernstein bezier(points);\n\t\t//Bezier bezier(points);\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = bezier(ctr_points[i]).x();\n\t\t\tys[i] = bezier(ctr_points[i]).y();\n\t\t}\n\t\tctr_xs.resize(points.size());\n\t\tctr_ys.resize(points.size());\n\n\t\tfor (int i = 0; i < points.size(); ++i)\n\t\t{\n\t\t\tctr_xs[i] = points[i].x();\n\t\t\tctr_ys[i] = points[i].y();\n\t\t}\n\t}\n\npublic:\n\tBezierVisualizer() {\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tctr_points[i] = Float(i) / (Length - 1);\n\t\t}\n\t}\n\tconst float Length = 1001;\n\n\tstd::vector<float> ctr_points = std::vector<float>(Length);\n\tstd::vector<float> xs = std::vector<float>(Length);\n\tstd::vector<float> ys = std::vector<float>(Length);\n\n\tstd::vector<float> ctr_xs = std::vector<float>(0);\n\tstd::vector<float> ctr_ys = std::vector<float>(0);\n};\n\nvoid BezierVisualizer::AddPoint()\n{\n\tif (ImGui::IsMouseClicked(ImGuiMouseButton_Right))\n\t{\n\t\tauto pos = ImPlot::GetPlotMousePos();\n\t\tpoints.emplace_back(pos.x, pos.y);\n\t\tupdated = true;\n\t}\n}\n\nvoid BezierVisualizer::DragPoint()\n{\n\tfor (int i = 0; i < points.size(); ++i)\n\t{\n\t\tauto& point = points[i];\n\t\tupdated |= ImPlot::DragPoint((\"Point \" + std::to_string(i)).c_str(), &point.x(), &point.y());\n\t}\n}\n\nvoid BezierVisualizer::draw(bool* p_open)\n{\n\tif (updated)\n\t{\n\t\tevaluate_bezier();\n\t\tupdated = false;\n\t}\n\tif (ImGui::BeginTabBar(\"Homework 2\")) {\n\t\tif (ImGui::BeginTabItem(\"Interpolation\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail(), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"Bezier\", &xs[0], &ys[0], Length);\n\t\t\t\tif (!ctr_xs.empty())\n\t\t\t\t{\n\t\t\t\t\tImPlot::PlotLine(\"ControlBox\", &ctr_xs[0], &ctr_ys[0], ctr_xs.size());\n\t\t\t\t}\n\t\t\t\tAddPoint();\n\t\t\t\tDragPoint();\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tImGui::EndTabBar();\n\t}\n\tImGui::End();\n}\n\nint main()\n{\n\tBezierVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "4d9ab950c8795c4f6b63a4cc231ccfa7aadf1ff5", "size": 2272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/Bezier/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/Bezier/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/Bezier/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": 20.6545454545, "max_line_length": 132, "alphanum_fraction": 0.6377640845, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6582182086622065}}
{"text": "/**\n * @file matode.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n\nnamespace MatODE {\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::MatrixXd eeulstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n                         double h) {\n  return Y0 + h * A * 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  int n = A.rows();\n  return (Eigen::MatrixXd::Identity(n, n) - h * A).partialPivLu().solve(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  int n = A.rows();\n  return (Eigen::MatrixXd::Identity(n, n) - h * 0.5 * A)\n      .partialPivLu()\n      .solve(Y0 + h * 0.5 * A * Y0);\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace MatODE\n", "meta": {"hexsha": "0fa8b2cc7da99cc5385ac2f0a36645ebbe1739ff", "size": 930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mastersolution/matode.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/MatODE/mastersolution/matode.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/MatODE/mastersolution/matode.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": 25.1351351351, "max_line_length": 77, "alphanum_fraction": 0.6032258065, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.6582182072483636}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of triangular lattice Ising model\n\n#include <iomanip>\n#include <iostream>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"triangular.hpp\"\n\nstruct options {\n  unsigned int prec;\n  std::string Ja, Jb, Jc, Tmin, Tmax, dT;\n  bool valid;\n  options(unsigned int argc, char *argv[]) :\n    prec(15), Ja(\"1\"), Jb(\"1\"), Jc(\"1\"), valid(true) {\n    if (argc == 1) { valid = false; return; }\n    for (unsigned i = 1; i < argc; ++i) {\n      switch (argv[i][0]) {\n      case '-' :\n        switch (argv[i][1]) {\n        case 'p' :\n          if (++i == argc) { valid = false; return; }\n          prec = std::atoi(argv[i]); break;\n        default :\n          valid = false; return;\n        }\n        break;\n      default :\n        switch (argc - i) {\n        case 1:\n          Ja = Jb = Jc = \"1\";\n          Tmin = Tmax = dT = argv[i];\n          return;\n        case 2:\n          Ja = Jb = Jc = argv[i];\n          Tmin = Tmax = dT = argv[i+1];\n          return;\n        case 4:\n          Ja = argv[i];\n          Jb = argv[i+1];\n          Jc = argv[i+2];\n          Tmin = Tmax = dT = argv[i+3];\n          return;\n        case 6:\n          Ja = argv[i];\n          Jb = argv[i+1];\n          Jc = argv[i+2];\n          Tmin = argv[i+3];\n          Tmax = argv[i+4];\n          dT = argv[i+5];\n          return;\n        default:\n          valid = false; return;\n        }\n      }\n    }\n  }\n};\n\ntemplate<typename T>\nvoid calc(const options& opt) {\n  using namespace ising::free_energy;\n  typedef T real_t;\n  real_t Ja = convert<real_t>(opt.Ja);\n  real_t Jb = convert<real_t>(opt.Jb);\n  real_t Jc = convert<real_t>(opt.Jc);\n  real_t Tmin = convert<real_t>(opt.Tmin);\n  real_t Tmax = convert<real_t>(opt.Tmax);\n  real_t dT = convert<real_t>(opt.dT);\n  if (Tmin > Tmax) throw(std::invalid_argument(\"Tmax should be larger than Tmin\"));\n  if (dT <= 0) throw(std::invalid_argument(\"dT should be positive\"));\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"# lattice: triangular\\n\"\n            << \"# precision: \" << std::numeric_limits<real_t>::digits10 << std::endl\n            << \"# Lx Ly Ja Jb Jc T 1/T F/N E/N C/N\\n\";\n  for (auto t = Tmin; t < Tmax + 1e-4 * dT; t += dT) {\n    auto beta = boost::math::differentiation::make_fvar<real_t, 2>(1 / t);\n    auto f = triangular::infinite(Ja, Jb, Jc, beta);\n    std::cout << \"inf inf \" << Ja << ' ' << Jb << ' ' << Jc << ' ' << t << ' ' << (1 / t) << ' '\n              << free_energy(f, beta) << ' ' << energy(f, beta) << ' '\n              << specific_heat(f, beta) << std::endl;\n  }\n}\n\n\nint main(int argc, char **argv) {\n  using namespace boost::multiprecision;\n  options opt(argc, argv);\n  if (!opt.valid) {\n    std::cerr << \"Usage: \" << argv[0] << \" [-p prec] T\\n\"\n              << \"       \" << argv[0] << \" [-p prec] J T\\n\"\n              << \"       \" << argv[0] << \" [-p prec] Ja Jb Jc T\\n\"\n              << \"       \" << argv[0] << \" [-p prec] Ja Jb Jc Tmin Tmax dT\\n\"; return 127;\n  }\n  if (opt.prec <= std::numeric_limits<float>::digits10) {\n    calc<float>(opt);\n  } else if (opt.prec <= std::numeric_limits<double>::digits10) {\n    calc<double>(opt);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<cpp_dec_float_50>>::digits10) {\n    calc<mp_wrapper<cpp_dec_float_50>>(opt);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<cpp_dec_float_100>>::digits10) {\n    calc<mp_wrapper<cpp_dec_float_100>>(opt);\n  } else {\n    std::cerr << \"Error: Required precision is too high\\n\"; return 127;\n  }\n}\n", "meta": {"hexsha": "28952c1043775de32612f2340b0d373a8c8614be", "size": 4254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/triangular.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/triangular.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/triangular.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": 34.5853658537, "max_line_length": 96, "alphanum_fraction": 0.5620592384, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6582182064111053}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/componentwise_equal.hpp>\n#include <fcppt/math/matrix/exponential_pade.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <ostream>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(exponential_pade)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tdouble,\n\t\t3,\n\t\t3\n\t>\n\tmatrix_type;\n\n\tmatrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t2.0, -1.0, 1.0\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t0.0, 3.0, -1.0\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t2.0, 1.0, 3.0\n\t\t)\n\t);\n\n\tdouble const epsilon =\n\t\t0.01;\n\n\tmatrix_type const result(\n\t        fcppt::math::matrix::exponential_pade(\n\t\t        t\n\t\t)\n\t);\n\n\tstd::cout\n\t\t<< result\n\t\t<< '\\n';\n\n\tBOOST_CHECK(\n\t\tfcppt::math::matrix::componentwise_equal(\n\t\t\tresult,\n\t\t\tmatrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t23.6045,-7.38906,23.6045\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t-16.2155,14.7781,-23.6045\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t30.9936,7.38906,30.9936\n\t\t\t\t)\n\t\t\t),\n\t\t\tepsilon\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "288847540915fee6fe73555952c0a14230db08cf", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/exponential_pade.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/exponential_pade.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/exponential_pade.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.075, "max_line_length": 61, "alphanum_fraction": 0.6755915318, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6582182018812839}}
{"text": "#include <vector>\n#include <random>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n\nstd::random_device rd;\nstd::mt19937 rng(rd());\t\n\nint reed_frost(int n, int s0, double Q, double beta, double alpha, double k)\n{\n\tstd::binomial_distribution<int> outside(s0,1-Q);\n\n\tdouble gamma_mean = beta/pow(n,alpha);\n\tdouble gamma_shape = k;\n\tstd::gamma_distribution<double> hazard(gamma_shape,\n\t\tgamma_mean/gamma_shape);\n\n\tint infected = outside(rd);\n\tint total_infected = infected;\n\tint susceptibles = s0-total_infected;\n\n\twhile(infected!=0)\n\t{\n\t\tdouble cum_hazard=0.;\n\t\tfor (int i = 0; i < infected; ++i)\n\t\t{\n\t\t\tdouble h = hazard(rd);\n\t\t\tcum_hazard += h;\n\t\t}\n\t\tdouble trans_prob = std::exp(-cum_hazard);\n\t\tstd::binomial_distribution<int> next_gen(susceptibles,1-trans_prob);\n\t\tinfected = next_gen(rd);\n\t\ttotal_infected += infected;\n\t\tsusceptibles -= infected;\n\t}\n\treturn total_infected;\n}\n\nint single_household(int n,std::vector<double> &params)\n{\n\n\t/* Les param\u00e8tres sont dans l'ordre (cf Fraser et al. 2011) :\n\n\t- La proba d'\u00e9chappement Q\n\t- La proba d'infection asymptomatique et infectieuse p_asx\n\t- La proba d'infection asymptomatique et non-infectieuse p_r\n\t- La proba d'\u00e9chappement \u00e0 une infection ant\u00e9rieure Q_prior\n\t- H\u00e9t\u00e9rog\u00e9n\u00e9it\u00e9 des infectivit\u00e9s k\n\t- Facteur de taille du domicile beta\n\t- Exposant de la taille du domicile alpha\n\n\t*/\n\n\tstd::binomial_distribution<int> protection(n,params[2]);\n\n\tint prot = protection(rd);\n\tint susceptibles = n-prot;\n\n\tint prev_infected = reed_frost(n,susceptibles,params[3],params[5],params\n\t\t[6],params[4]);\n\n\tsusceptibles -= prev_infected;\n\n\tint new_infected = reed_frost(n,susceptibles,params[0],params[5],params\n\t\t[6],params[4]);\n\n\tstd::binomial_distribution<int> asympt(new_infected,params[1]);\n\tint asymptomatics = asympt(rd);\n\tint symptomatics = new_infected - asymptomatics;\n\treturn symptomatics;\n}\n\n\nint main(int argc, char const *argv[])\n{\n\n\tstd::vector<double> test_params { 0.8,0,0,0.88,0.94,0.37,0.35 } ;\n\tstd::vector<double> params=test_params;\n\n\tstd::vector<int> test_numbers {244,1126,1342,1378,1017,680,434,\n\t  284,117,74,25,23,5,3,0,0,1 };\n\n\tint max_n = test_numbers.size();\n\n\tEigen::MatrixXi table(max_n+1,max_n);\n\n\tfor (int n = 0; n < max_n; ++n)\n\t{\n\t\tstd::vector<int> symptomatics;\n\t\tint num_households = test_numbers[n];\n\t\tfor (int i = 0; i < num_households; ++i)\n\t\t{\n\t\t\tint infected = single_household(n+1,params);\n\t\t\tsymptomatics.push_back(infected);\n\t\t}\n\n\t\tfor (int m = 0; m <= n+1; ++m)\n\t\t{\n\t\t\tint occurrences = std::count(symptomatics.begin(),\n\t\t\t\tsymptomatics.end(),m);\n\t\t\ttable(m,n) = occurrences;\n\t\t}\n\t}\n\n\tstd::cout << table << std::endl;\n\n\tstd::ofstream outfile(\"sim_matrix.txt\");\n\toutfile << table;\n\n\treturn 0;\n}", "meta": {"hexsha": "fe39a7c9628513ecb41de44998d7e65e2a7515ef", "size": 2711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/fraser_model_optim/simulator.cpp", "max_stars_repo_name": "phoscheit/reed_frost", "max_stars_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_stars_repo_licenses": ["MIT"], "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/fraser_model_optim/simulator.cpp", "max_issues_repo_name": "phoscheit/reed_frost", "max_issues_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_issues_repo_licenses": ["MIT"], "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/fraser_model_optim/simulator.cpp", "max_forks_repo_name": "phoscheit/reed_frost", "max_forks_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_forks_repo_licenses": ["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.9911504425, "max_line_length": 76, "alphanum_fraction": 0.7001106603, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.658203561255796}}
{"text": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ntypedef long long ll;\ntypedef vector <int> vi;\n#define mod 10000000000000007\n\ncpp_int pow(ll b, ll p){\n    cpp_int res = 1, a = b;\n    while(p){\n        if(p & 1){\n            res =  (res * a) % mod;\n        }\n        a = (a * a) % mod;\n        a %= mod;\n        p >>= 1;\n    }\n    return res;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    freopen(\"in.txt\", \"r\", stdin);\n    freopen(\"out.txt\", \"w\", stdout);\n    int tc; cin >> tc;\n    ll n, m, p, q;\n    while(tc--){\n        cin >> p >> q;\n        n = (p*q)/2;\n        m = p*q - n;\n        cout << (pow(n, m-1)*pow(m, n-1)) % mod << \"\\n\";\n    }\n    return 0;\n}", "meta": {"hexsha": "b9f9ae09d69e808380391ca8a4f26c5702fbcf13", "size": 772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_stars_repo_name": "satvik007/uva", "max_stars_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T06:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-16T02:31:27.000Z", "max_issues_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_issues_repo_name": "satvik007/uva", "max_issues_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_forks_repo_name": "satvik007/uva", "max_forks_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_forks_repo_licenses": ["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.4444444444, "max_line_length": 56, "alphanum_fraction": 0.4948186528, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6582035472973077}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n#include \"Properties.h\"\n#include \"Utils/Geometry/AtomCollection.h\"\n#include \"Utils/Geometry/ElementInfo.h\"\n#include <Eigen/Eigenvalues>\n\nnamespace Scine {\nnamespace Utils {\nnamespace Geometry {\nnamespace Properties {\n\nstd::vector<double> getMasses(const ElementTypeCollection& elements) {\n  std::vector<double> masses;\n  masses.reserve(elements.size());\n  std::transform(elements.begin(), elements.end(), std::back_inserter(masses), ElementInfo::mass);\n  return masses;\n}\n\nPosition getCenterOfMass(const PositionCollection& positions, const std::vector<double>& masses) {\n  Position P;\n  P.setZero();\n  double totalMass = 0;\n  for (int i = 0; i < positions.rows(); ++i) {\n    P += masses[i] * positions.row(i);\n    totalMass += masses[i];\n  }\n  P /= totalMass;\n  return P;\n}\n\nPosition getCenterOfMass(const AtomCollection& structure) {\n  auto masses = getMasses(structure.getElements());\n  return getCenterOfMass(structure.getPositions(), masses);\n}\n\nPosition getAveragePosition(const PositionCollection& positions) {\n  return positions.colwise().sum() / positions.rows();\n}\n\nEigen::Matrix3d calculateInertiaTensor(const PositionCollection& positions, const std::vector<double>& masses,\n                                       const Position& centerOfMass) {\n  double Ixx = 0, Iyy = 0, Izz = 0, Ixy = 0, Ixz = 0, Iyz = 0;\n  for (int i = 0; i < positions.rows(); ++i) {\n    double m = masses[i];\n    auto dp = positions.row(i) - centerOfMass;\n    double x = dp.x();\n    double y = dp.y();\n    double z = dp.z();\n    Ixx += m * (y * y + z * z);\n    Iyy += m * (x * x + z * z);\n    Izz += m * (x * x + y * y);\n    Ixy -= m * x * y;\n    Ixz -= m * x * z;\n    Iyz -= m * y * z;\n  }\n  Eigen::Matrix3d In;\n  In << Ixx, Ixy, Ixz, Ixy, Iyy, Iyz, Ixz, Iyz, Izz;\n  return In;\n}\n\nPrincipalMomentsOfInertia calculatePrincipalMoments(const PositionCollection& positions,\n                                                    const std::vector<double>& masses, const Position& centerOfMass) {\n  auto In = calculateInertiaTensor(positions, masses, centerOfMass);\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n  es.compute(In);\n\n  PrincipalMomentsOfInertia pmi;\n  pmi.eigenvalues = es.eigenvalues();\n  pmi.eigenvectors = es.eigenvectors();\n  return pmi;\n}\n\nbool operator==(const PositionCollection& lhs, const PositionCollection& rhs) {\n  return lhs.isApprox(rhs);\n}\n\nbool operator!=(const PositionCollection& lhs, const PositionCollection& rhs) {\n  return !(lhs == rhs);\n}\n\n} /* namespace Properties */\n} /* namespace Geometry */\n} /* namespace Utils */\n} /* namespace Scine */\n", "meta": {"hexsha": "46e22a717a0ae39946de367a600085bd0d644892", "size": 2783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "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/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 30.5824175824, "max_line_length": 118, "alphanum_fraction": 0.6550485088, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.658133248448225}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost::numeric::ublas;\n\nint main()\n{\n\tstd::cout << \"\\nVector\" << std::endl;\n\t// basic Vector Usage\n\tvector<double> v(3);\n\tfor (unsigned i = 0; i < v.size(); ++ i)\n\t{\n\t\tv(i) = i;\n\t}\n\tstd::cout << \"vector \\t\\t\" << v << std::endl;\n\n\t// unit_vector\n\tfor (int i = 0; i < 3; ++ i) \n\t{\n\t\tunit_vector<double> v_unit(3, i);\n\t\tstd::cout << \"unit_vector \\t\" << v_unit << std::endl;\n\t}\n\n\t// zero_vector\n\tzero_vector<double> v_zero(3);\n\tstd::cout << \"zero_vector \\t\" << v_zero << std::endl;\n\n\t// scalr_vector\n\tscalar_vector<double> v_scalar(3,100);\n\tstd::cout << \"scalar_vector \\t\" << v_scalar << std::endl;\n\n\tstd::cout << \"\\nMatrix\" << std::endl;\n\t// basic matrix\n\tmatrix<double> m(3, 3);\n\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t{\n\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t{\n\t\t\tm(i, j) = 3 * i + j;\n\t\t}\n\t}\n\tstd::cout << \"matrix \\t\\t\" << m << std::endl;\n\n\t// identity matrix\n\tidentity_matrix<double> m_identity(3);\n    std::cout << \"eye matrix\\t\" << m_identity << std::endl;\n\n    // zero matrix\n    zero_matrix<double> m_zero(3, 3);\n    std::cout << \"zero matrix\\t\" << m_zero << std::endl;\n\n    // scalar matrix\n    scalar_matrix<double> m_scalar(3, 3, 100);\n    std::cout << \"scalar matrix\\t\" << m_scalar << std::endl;\n\n    // lower and upper triangular matrix\n    triangular_matrix<double, lower> ml(3, 3);\n    for (unsigned i = 0; i < ml.size1 (); ++ i)\n        for (unsigned j = 0; j <= i; ++ j)\n            ml(i, j) = 3 * i + j;\n    std::cout << \"lower triangular matrix\\t\" << ml << std::endl;\n\n    triangular_matrix<double, upper> mu(3, 3);\n    for (unsigned i = 0; i < mu.size1 (); ++ i)\n        for (unsigned j = i; j < mu.size2 (); ++ j)\n            mu(i, j) = 3 * i + j;\n    std::cout << \"upper triangular matrix\\t\" << mu << std::endl;\n\n    // lower and upper symmetric matrix\n    symmetric_matrix<double, lower> ml_symm(3, 3);\n    for (unsigned i = 0; i < ml_symm.size1 (); ++ i)\n        for (unsigned j = 0; j <= i; ++ j)\n            ml_symm(i, j) = 3 * i + j;\n    std::cout << \"lower symmetric matrix\\t\" << ml_symm << std::endl;\n\n    symmetric_matrix<double, upper> mu_symm(3, 3);\n    for (unsigned i = 0; i < mu_symm.size1 (); ++ i)\n        for (unsigned j = i; j < mu_symm.size2 (); ++ j)\n            mu_symm(i, j) = 3 * i + j;\n    std::cout << \"upper symmetric matrix\\t\" << mu_symm << std::endl;\n\n    // banded matrix\n    banded_matrix<double> m_banded (3, 3, 1, 1);\n    for (signed i = 0; i < signed (m_banded.size1 ()); ++ i)\n        for (signed j = std::max (i - 1, 0); j < std::min (i + 2, signed (m_banded.size2 ())); ++ j)\n            m_banded (i, j) = 3 * i + j;\n    std::cout << \"banded matrix\\t\" << m_banded << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "8905f7750eb12b6bdcba75bae87187110c1815ad", "size": 2928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "yoon-gu/la-table", "max_stars_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_stars_repo_licenses": ["MIT"], "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": "yoon-gu/la-table", "max_issues_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_issues_repo_licenses": ["MIT"], "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": "yoon-gu/la-table", "max_forks_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_forks_repo_licenses": ["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.4838709677, "max_line_length": 100, "alphanum_fraction": 0.5642076503, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6579556308493133}}
{"text": "#include \"../params.h\"\n#include \"../sigmaplus_prover.h\"\n#include \"../sigmaplus_verifier.h\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"../../test/fixtures.h\"\n\nBOOST_FIXTURE_TEST_SUITE(sigma_protocol_tests, ZerocoinTestingSetup200)\n\nBOOST_AUTO_TEST_CASE(one_out_of_n)\n{\n    auto params = sigma::Params::get_default();\n    std::size_t N = 16384;\n    std::size_t n = params->get_n();\n    std::size_t m = params->get_m();\n    std::size_t index = 0;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for (std::size_t i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for (std::size_t i = 0; i < N; ++i) {\n        if (i == index) {\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(uint64_t(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else {\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    BOOST_CHECK(verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_n_batch)\n{\n    auto params = sigma::Params::get_default();\n    const secp_primitives::Scalar zero(uint64_t(0));\n    const std::size_t N = 16000; // n^m == 16384\n    const std::size_t n = params->get_n();\n    const std::size_t m = params->get_m();\n    const std::vector<std::size_t> index = { 0, 1, 2, N - 1 };\n    const std::vector<std::size_t> set_sizes = { N, N - 1, N - 1, 16 };\n    const std::vector<secp_primitives::Scalar> serials = { zero, zero, zero, zero };\n    const std::vector<bool> fPadding = { true, true, true, true };\n\n    // Generators\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for (std::size_t i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g, h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n\n    // All commitments\n    for (std::size_t i = 0; i < N; ++i) {\n        commits.push_back(secp_primitives::GroupElement());\n        commits[i].randomize();\n    }\n\n    // Known commitments\n    std::vector<Scalar> r;\n    r.resize(index.size());\n    for (std::size_t i = 0; i < index.size(); i++) {\n        r[i].randomize();\n        commits[index[i]] = h_gens[0] * r[i];\n    }\n\n    // Build the proofs\n    std::vector<sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement>> proofs;\n    proofs.reserve(index.size());\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    for (std::size_t i = 0; i < index.size(); i++) {\n        sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n        std::vector<secp_primitives::GroupElement> commits_(commits.begin() + N - set_sizes[i], commits.end());\n\n        // Check commitment validity and prove\n        BOOST_CHECK(h_gens[0] * r[i] == commits[index[i]]);\n        BOOST_CHECK(h_gens[0] * r[i] == commits_[index[i] - (N - set_sizes[i])]);\n        prover.proof(commits_, index[i] - (N - set_sizes[i]), r[i], true, proof);\n        proofs.emplace_back(proof);\n\n        // Test individual verification\n        BOOST_CHECK(verifier.verify(commits_, proof, true));\n        BOOST_CHECK(verifier.verify(commits, proof, true, set_sizes[i]));\n    }\n\n    // Test batch verification\n    BOOST_CHECK(verifier.batch_verify(commits, serials, fPadding, set_sizes, proofs));\n\n    // Invalidate the batch\n    proofs[0] = proofs[1];\n    BOOST_CHECK(!verifier.batch_verify(commits, serials, fPadding, set_sizes, proofs));\n}\n\nBOOST_AUTO_TEST_CASE(one_out_of_n_padding)\n{\n    auto params = sigma::Params::get_default();\n    int N = 10000;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 9999;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(uint64_t(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    BOOST_CHECK(verifier.verify(commits, proof, true));\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proofNew(n, m);\n    prover.proof(commits, 11111, r, true, proofNew);\n    BOOST_CHECK(verifier.verify(commits, proofNew, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_and_verify_in_different_set)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 0;\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        if(i == index){\n            secp_primitives::GroupElement c;\n            secp_primitives::Scalar zero(uint64_t(0));\n            c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n            commits.push_back(c);\n\n        }\n        else{\n            commits.push_back(secp_primitives::GroupElement());\n            commits[i].randomize();\n        }\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n\n    // Add more commit\n    secp_primitives::GroupElement c;\n    secp_primitives::Scalar zero(uint64_t(0));\n    c = sigma::SigmaPrimitives<secp_primitives::Scalar,secp_primitives::GroupElement>::commit(g, zero, h_gens[0], r);\n    commits.push_back(c);\n\n    BOOST_CHECK(!verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_coin_out_of_index)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        commits.push_back(secp_primitives::GroupElement());\n        commits[i].randomize();\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, commits.size(), r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_CASE(prove_coin_not_in_set)\n{\n    auto params = sigma::Params::get_default();\n    int N = 16384;\n    int n = params->get_n();\n    int m = params->get_m();\n    int index = 0;\n    secp_primitives::GroupElement g;\n    g.randomize();\n    std::vector<secp_primitives::GroupElement> h_gens;\n    h_gens.resize(n * m);\n    for(int i = 0; i < n * m; ++i ){\n        h_gens[i].randomize();\n    }\n    secp_primitives::Scalar r;\n    r.randomize();\n    sigma::SigmaPlusProver<secp_primitives::Scalar,secp_primitives::GroupElement> prover(g,h_gens, n, m);\n\n    std::vector<secp_primitives::GroupElement> commits;\n    for(int i = 0; i < N; ++i){\n        commits.push_back(secp_primitives::GroupElement());\n        commits[i].randomize();\n    }\n\n    sigma::SigmaPlusProof<secp_primitives::Scalar,secp_primitives::GroupElement> proof(n, m);\n\n    prover.proof(commits, index, r, true, proof);\n\n    sigma::SigmaPlusVerifier<secp_primitives::Scalar,secp_primitives::GroupElement> verifier(g, h_gens, n, m);\n    BOOST_CHECK(!verifier.verify(commits, proof, true));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5c8acd3c691715ddb6d2735db3c88597eb2f8afe", "size": 9707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sigma/test/protocol_tests.cpp", "max_stars_repo_name": "arjundashrath/firo", "max_stars_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 582.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T00:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-25T19:07:24.000Z", "max_issues_repo_path": "src/sigma/test/protocol_tests.cpp", "max_issues_repo_name": "arjundashrath/firo", "max_issues_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 570.0, "max_issues_repo_issues_event_min_datetime": "2016-09-28T07:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T10:24:19.000Z", "max_forks_repo_path": "src/sigma/test/protocol_tests.cpp", "max_forks_repo_name": "arjundashrath/firo", "max_forks_repo_head_hexsha": "78e29d68b7354be702965fdd4f033709750776e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 409.0, "max_forks_repo_forks_event_min_datetime": "2016-09-21T12:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-18T14:54:17.000Z", "avg_line_length": 34.9172661871, "max_line_length": 125, "alphanum_fraction": 0.6533429484, "num_tokens": 2785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6579556276701336}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <fstream>\n\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \"\\t\", \"\\n\");\n\nint main()\n{\n\t// Initialization of vectors and matrices\n    Eigen::VectorXd v(3);\n\tEigen::MatrixXd matA(3,3);\n\n\tv << 0, 1, 2;\n\tmatA << v, v, v;\n \n\tstd::ofstream output;\n\toutput.open(\"bin/Aufgabe1.txt\", std::ofstream::out | std::ofstream::trunc);\n\toutput << \"Matrix matA:\\n\" << matA.format(CSVFormat) << std::endl;\n\toutput.close();\n\n    return 0;\n}", "meta": {"hexsha": "9e928e20d8a5a1ceed9d2af542611d071f78451e", "size": 527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "template/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": "template/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": "template/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": 22.9130434783, "max_line_length": 97, "alphanum_fraction": 0.6622390892, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6578364744286189}}
{"text": "// This file implements the Levenberg-Marquardt method\n// for pose projection matrix refinement\n#include \"marker.hpp\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <limits>\n#include <iostream>\n\n#define ERROR_EPS       0.001\n#define MAX_ITER        10\n\n/////////////////////////////////////////////////////////////////\n// objective: min(sum(p - K M q)^2)\n// where\n// K: 3x3 matrix\n// M: 3x4 matrix\n// q: 4x1 vector (obj points)\n// p: 3x1 vector (img points)\n// variable: M\n/////////////////////////////////////////////////////////////////\n// let's say an update of delta on M\n// brings us closer to local minimum\n// S = sum(p - K M q - J delta)^2\n// where\n// J: gradient of function (K M q) with respect to M\n// take derivative of S with respect to delta and set to zero:\n// (J^T J) delta = J^T (p - K M q)\n// which is replaced to: (by Levenberg)\n// (J^T J + lambda I) delta = J^T (p - K M q)\n// where\n// lambda: a damping factor adjusted each iteration\n// finally, to make solution scale invariant:\n// (J^T J + lambda diag(J^T J)) delta = J^T (p - K M q)\n/////////////////////////////////////////////////////////////////\n\n// refer to: https://github.com/opencv/opencv/blob/master/modules/calib3d/src/compat_ptsetreg.cpp#L121\n// refer to book \"Augmented Reality: Principles and Practice\"\n// refer to: https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm\n// refine pose matrix\nvoid Marker::refinePoseM(\n    const glm::mat3& cameraInvK,\n    const std::vector<glm::vec2>& objPoints,\n    const std::vector<glm::vec2>& imgPoints\n)\n{\n    if(objPoints.size() < 4 || imgPoints.size() < 4)\n        return;\n    // camera matrix in eigen\n    Eigen::Matrix3f Kinv;\n    Kinv << cameraInvK[0][0], cameraInvK[1][0], cameraInvK[2][0],\n            cameraInvK[0][1], cameraInvK[1][1], cameraInvK[2][1],\n            cameraInvK[0][2], cameraInvK[1][2], cameraInvK[2][2];\n    // pose matrix\n    Eigen::Matrix<float, 3, 4> M;\n    M << _poseM[0][0], _poseM[1][0], _poseM[2][0], _poseM[3][0],\n         _poseM[0][1], _poseM[1][1], _poseM[2][1], _poseM[3][1],\n         _poseM[0][2], _poseM[1][2], _poseM[2][2], _poseM[3][2];\n    Eigen::Matrix<float, 3, 4> Mshaped = Eigen::MatrixXf::Constant(3, 4, 0.0f);\n    // point matrix\n    Eigen::Matrix4f objMatrix;\n    objMatrix << objPoints[0].x, objPoints[1].x, objPoints[2].x, objPoints[3].x,\n                 objPoints[0].y, objPoints[1].y, objPoints[2].y, objPoints[3].y,\n                 0.0f,           0.0f,           0.0f,           0.0f,\n                 1.0f,           1.0f,           1.0f,           1.0f;\n    Eigen::Matrix<float, 3, 4> imgMatrix;\n    imgMatrix << imgPoints[0].x, imgPoints[1].x, imgPoints[2].x, imgPoints[3].x,\n                 imgPoints[0].y, imgPoints[1].y, imgPoints[2].y, imgPoints[3].y,\n                 0.0f,           0.0f,           0.0f,           0.0f;\n    // here we are minimizing sum(K^-1 p - M q)^2\n    // if K M q = p, then M q = K^-1 p\n    imgMatrix = Kinv * imgMatrix;\n    // Jacobian\n    // mxn matrix\n    // m: number of points\n    // n: number of parameters\n    Eigen::Matrix<float, 12, 12> J = Eigen::MatrixXf::Constant(12, 12, 0.0f);\n    // initialize Jacobian\n    for(int i = 0; i < 4; i++)\n    {\n        // J(i+0, Eigen::seqN(0, 4)) = objMatrix.col(i);\n        // J(i+4, Eigen::seqN(4, 4)) = objMatrix.col(i);\n        // J(i+8, Eigen::seqN(8, 4)) = objMatrix.col(i);\n        J(i*3+0, Eigen::seqN(0, 4)) = objMatrix.col(i);\n        J(i*3+1, Eigen::seqN(4, 4)) = objMatrix.col(i);\n        J(i*3+2, Eigen::seqN(8, 4)) = objMatrix.col(i);\n    }\n    Eigen::Matrix<float, 12, 12> JT = J.transpose();\n    Eigen::Matrix<float, 12, 12> JTJ = JT * J;\n    Eigen::Matrix<float, 12, 12> JTJdiag = Eigen::MatrixXf::Constant(12, 12, 0.0f);\n    JTJdiag.diagonal() += JTJ.diagonal();\n    // delta matrix\n    Eigen::Vector<float, 12> delta = Eigen::VectorXf::Constant(12, 0.0f);\n    // left and right hand side of equation\n    Eigen::Matrix<float, 12, 12> eqLeft;\n    Eigen::Vector<float, 12> eqRight;\n    // damping factor (same as OpenCV)\n    // lambda = 1.0 + exp(lambdaLog10 * log10val)\n    const float log10val = std::log(10.0f);\n    int lambdaLog10 = -3;\n    // start iteration\n    int iter = 0;\n    float err = std::numeric_limits<float>::max();\n    float prevErr = std::numeric_limits<float>::max();\n    while(iter++ < MAX_ITER)\n    {\n        float lambda = 1.0f + std::exp(lambdaLog10 * log10val);\n        // (J^T J + lambda diag(J^T J)) delta = J^T (p - K M q)\n        eqLeft = JTJ + lambda * JTJdiag;\n        Mshaped = imgMatrix - M * objMatrix;\n        Eigen::Map<Eigen::VectorXf> flatten(Mshaped.data(), Mshaped.size());\n        eqRight = JT * flatten;\n        delta = eqLeft.colPivHouseholderQr().solve(eqRight);\n        // update M\n        M.row(0) += delta(Eigen::seqN(0, 4));\n        M.row(1) += delta(Eigen::seqN(4, 4));\n        M.row(2) += delta(Eigen::seqN(8, 4));\n        // compute error\n        prevErr = err;\n        err = 0.0f;\n        Eigen::Matrix<float, 3, 4> residual = imgMatrix - M * objMatrix;\n        Eigen::Map<Eigen::VectorXf> residualVec(residual.data(), residual.size());\n        for(int i = 0; i < 12; i++)\n            err += residualVec[i] * residualVec[i];\n        // std::cout << iter << \",\" << lambdaLog10 << \"|\" << err << std::endl;\n        if(err <= ERROR_EPS) break;\n        if(err > prevErr)\n        {\n            lambdaLog10 = std::min(lambdaLog10+1, 16);\n            err = std::numeric_limits<float>::max();\n            continue;\n        }\n        // update lambda\n        lambdaLog10 = std::max(lambdaLog10-1, -16);\n    }\n    _err_LM = err;\n    // std::cout << \"LM err: \" << err << \"(\" << iter << \")\" << std::endl;\n    // record new M and interpolate\n    if(_poseMRefined[3][2] == 0.0f)\n    {\n        _poseMRefined = glm::mat4x3(\n            glm::vec3(M.col(0)[0], M.col(0)[1], M.col(0)[2]),\n            glm::vec3(M.col(1)[0], M.col(1)[1], M.col(1)[2]),\n            glm::vec3(M.col(2)[0], M.col(2)[1], M.col(2)[2]),\n            glm::vec3(M.col(3)[0], M.col(3)[1], M.col(3)[2])\n        );\n    }\n    else\n    {\n        _poseMRefined = _poseM_interpolate * _poseMRefined +\n            (1.0f - _poseM_interpolate) * glm::mat4x3(\n            glm::vec3(M.col(0)[0], M.col(0)[1], M.col(0)[2]),\n            glm::vec3(M.col(1)[0], M.col(1)[1], M.col(1)[2]),\n            glm::vec3(M.col(2)[0], M.col(2)[1], M.col(2)[2]),\n            glm::vec3(M.col(3)[0], M.col(3)[1], M.col(3)[2])\n        );\n    }\n}", "meta": {"hexsha": "e68ca7247a107bbb962ad9a6908f1f959480f358", "size": 6408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PC/src/markerLM.cpp", "max_stars_repo_name": "teamclouday/Marker", "max_stars_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PC/src/markerLM.cpp", "max_issues_repo_name": "teamclouday/Marker", "max_issues_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PC/src/markerLM.cpp", "max_forks_repo_name": "teamclouday/Marker", "max_forks_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_forks_repo_licenses": ["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.8152866242, "max_line_length": 102, "alphanum_fraction": 0.5349563046, "num_tokens": 2155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6578364642562851}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\nTEST(AgradRev,falling_factorial_var_double) {\n  double a(2);\n  AVAR b(4.0);\n  AVAR f = stan::math::falling_factorial(b,a);\n  EXPECT_FLOAT_EQ(12, f.val());\n\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n  EXPECT_FLOAT_EQ((boost::math::digamma(5) - boost::math::digamma(3))\n                  * 12.0, g[1]);\n\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::falling_factorial(4.0 + eps, 2.0)\n                  - stan::math::falling_factorial(4.0 - eps, 2.0))\n                  / (2 * eps), g[1]);\n}\n\nTEST(AgradRev, falling_factorial_exceptions) {\n  double a = 1;\n  AVAR b(-3.0);\n  EXPECT_THROW(stan::math::falling_factorial(b,a), std::domain_error);\n  EXPECT_THROW(stan::math::falling_factorial(b,b), std::domain_error);\n}\n\nTEST(AgradRev, falling_factorial_double_var) {\n  double a(5);\n  AVAR b(4.0);\n  AVAR f = stan::math::falling_factorial(a,b);\n  EXPECT_FLOAT_EQ(120.0, f.val());\n  AVEC x = createAVEC(a,b);\n  VEC g;  \n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::digamma(2) * 120.0, g[1]);\n\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::falling_factorial(5.0, 4.0 + eps)\n                  - stan::math::falling_factorial(5.0, 4.0 - eps))\n                  / (2 * eps), g[1]);\n}\nTEST(AgradRev, falling_factorial_var_var) {\n  AVAR a(6.0);\n  AVAR b(4.0);\n  AVAR f = stan::math::falling_factorial(a,b);\n  EXPECT_FLOAT_EQ(360.0, f.val());\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ((boost::math::digamma(7) - boost::math::digamma(3))\n                  * 360.0, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::digamma(3) * 360.0, g[1]);\n  \n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::falling_factorial(6.0 + eps, 4.0)\n                  - stan::math::falling_factorial(6.0 - eps, 4.0))\n                  / (2 * eps), g[0]);\n  EXPECT_FLOAT_EQ((stan::math::falling_factorial(6.0, 4.0 + eps)\n                  - stan::math::falling_factorial(6.0, 4.0 - eps))\n                  / (2 * eps), g[1]);\n}\n\nstruct falling_factorial_fun {\n  template <typename T0, typename T1>\n  inline \n  typename stan::return_type<T0,T1>::type\n  operator()(const T0& arg1,\n             const T1& arg2) const {\n    return falling_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradRev, falling_factorial_nan) {\n  falling_factorial_fun falling_factorial_;\n  test_nan(falling_factorial_,4.0,1.0,false,true);\n\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a(2);\n  AVAR b(4.0);\n  test::check_varis_on_stack(stan::math::falling_factorial(b,a));\n  test::check_varis_on_stack(stan::math::falling_factorial(b,2));\n  test::check_varis_on_stack(stan::math::falling_factorial(4,a));\n}\n", "meta": {"hexsha": "4d722fdefb31a246139d2db871a56839ab38f3f8", "size": 2838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/falling_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/falling_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/falling_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5161290323, "max_line_length": 70, "alphanum_fraction": 0.6321353066, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.6577799373729685}}
{"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 of the kernel ridge regression \n    object from the dlib C++ Library.  \n\n    This example creates a simple set of data to train on and then shows\n    you how to use the kernel ridge regression tool to find a good decision \n    function that can classify examples in our data set.\n\n\n    The data used in this example will be 2 dimensional data and will\n    come from a distribution where points with a distance less than 13\n    from the origin are labeled +1 and all other points are labeled\n    as -1.  All together, the dataset will contain 10201 sample points.\n        \n*/\n\n\n#include <iostream>\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_krr_classification_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the\n    // object that contains each of our 2 dimensional samples.   (Note that if you wanted \n    // more than 2 features in this vector you can simply change the 2 to something else.\n    // Or if you don't know how many features you want until runtime then you can put a 0\n    // here and use the matrix.set_size() member function)\n    typedef matrix<double, 2, 1> sample_type;\n\n    // This is a typedef for the type of kernel we are going to use in this example.\n    // In this case I have selected the radial basis kernel that can operate on our\n    // 2D sample_type objects\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n\n    // Now we make objects to contain our samples and their respective labels.\n    std::vector<sample_type> samples;\n    std::vector<double> labels;\n\n    // Now let's put some data into our samples and labels objects.  We do this\n    // by looping over a bunch of points and labeling them according to their\n    // distance from the origin.\n    for (double r = -20; r <= 20; r += 0.4)\n    {\n        for (double c = -20; c <= 20; c += 0.4)\n        {\n            sample_type samp;\n            samp(0) = r;\n            samp(1) = c;\n            samples.push_back(samp);\n\n            // if this point is less than 13 from the origin\n            if (sqrt((double)r*r + c*c) <= 13)\n                labels.push_back(+1);\n            else\n                labels.push_back(-1);\n\n        }\n    }\n\n    cout << \"samples generated: \" << samples.size() << endl;\n    cout << \"  number of +1 samples: \" << sum(mat(labels) > 0) << endl;\n    cout << \"  number of -1 samples: \" << sum(mat(labels) < 0) << endl;\n\n    // Here we normalize all the samples by subtracting their mean and dividing by their standard deviation.\n    // This is generally a good idea since it often heads off numerical stability problems and also \n    // prevents one large feature from smothering others.  Doing this doesn't matter much in this example\n    // so I'm just doing this here so you can see an easy way to accomplish this with \n    // the library.  \n    vector_normalizer<sample_type> normalizer;\n    // let the normalizer learn the mean and standard deviation of the samples\n    normalizer.train(samples);\n    // now normalize each sample\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        samples[i] = normalizer(samples[i]); \n\n\n    // here we make an instance of the krr_trainer object that uses our kernel type.\n    krr_trainer<kernel_type> trainer;\n\n    // The krr_trainer has the ability to perform leave-one-out cross-validation.\n    // It does this to automatically determine the regularization parameter.  Since\n    // we are performing classification instead of regression we should be sure to\n    // call use_classification_loss_for_loo_cv().  This function tells it to measure \n    // errors in terms of the number of classification mistakes instead of mean squared \n    // error between decision function output values and labels.  \n    trainer.use_classification_loss_for_loo_cv();\n\n\n    // Now we loop over some different gamma values to see how good they are.  \n    cout << \"\\ndoing leave-one-out cross-validation\" << endl;\n    for (double gamma = 0.000001; gamma <= 1; gamma *= 5)\n    {\n        // tell the trainer the parameters we want to use\n        trainer.set_kernel(kernel_type(gamma));\n\n        // loo_values will contain the LOO predictions for each sample.  In the case\n        // of perfect prediction it will end up being a copy of labels.\n        std::vector<double> loo_values; \n        trainer.train(samples, labels, loo_values);\n\n        // Print gamma and the fraction of samples correctly classified during LOO cross-validation.\n        const double classification_accuracy = mean_sign_agreement(labels, loo_values);\n        cout << \"gamma: \" << gamma << \"     LOO accuracy: \" << classification_accuracy << endl;\n    }\n\n\n    // From looking at the output of the above loop it turns out that a good value for \n    // gamma for this problem is 0.000625.  So that is what we will use.\n    trainer.set_kernel(kernel_type(0.000625));\n    typedef decision_function<kernel_type> dec_funct_type;\n    typedef normalized_function<dec_funct_type> funct_type;\n\n\n    // Here we are making an instance of the normalized_function object.  This object provides a convenient \n    // way to store the vector normalization information along with the decision function we are\n    // going to learn.  \n    funct_type learned_function;\n    learned_function.normalizer = normalizer;  // save normalization information\n    learned_function.function = trainer.train(samples, labels); // perform the actual training and save the results\n\n    // print out the number of basis vectors in the resulting decision function\n    cout << \"\\nnumber of basis vectors in our learned_function is \" \n         << learned_function.function.basis_vectors.size() << endl;\n\n    // Now let's try this decision_function on some samples we haven't seen before.\n    // The decision function will return values >= 0 for samples it predicts\n    // are in the +1 class and numbers < 0 for samples it predicts to be in the -1 class.\n    sample_type sample;\n\n    sample(0) = 3.123;\n    sample(1) = 2;\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 9.3545;\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 9.3545;\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 0;\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\n\n\n    // We can also train a decision function that reports a well conditioned probability \n    // instead of just a number > 0 for the +1 class and < 0 for the -1 class.  An example \n    // of doing that follows:\n    typedef probabilistic_decision_function<kernel_type> probabilistic_funct_type;  \n    typedef normalized_function<probabilistic_funct_type> pfunct_type;\n\n    // The train_probabilistic_decision_function() is going to perform 3-fold cross-validation.\n    // So it is important that the +1 and -1 samples be distributed uniformly across all the folds.\n    // calling randomize_samples() will make sure that is the case.   \n    randomize_samples(samples, labels);\n\n    pfunct_type learned_pfunct; \n    learned_pfunct.normalizer = normalizer;\n    learned_pfunct.function = train_probabilistic_decision_function(trainer, samples, labels, 3);\n    // Now we have a function that returns the probability that a given sample is of the +1 class.  \n\n    // print out the number of basis vectors in the resulting decision function.  \n    // (it should be the same as in the one above)\n    cout << \"\\nnumber of basis vectors in our learned_pfunct is \" \n         << learned_pfunct.function.decision_funct.basis_vectors.size() << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 2;\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 3.123;\n    sample(1) = 9.3545;\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 9.3545;\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n    sample(0) = 13.123;\n    sample(1) = 0;\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \n         << learned_pfunct(sample) << endl;\n\n\n\n    // Another thing that is worth knowing is that just about everything in dlib is serializable.\n    // So for example, you can save the learned_pfunct object to disk and recall it later like so:\n    serialize(\"saved_function.dat\") << learned_pfunct;\n\n    // Now let's open that file back up and load the function object it contains.\n    deserialize(\"saved_function.dat\") >> learned_pfunct;\n\n}\n\n", "meta": {"hexsha": "e4c3e62a9897e27889d5a09188088f40f1a7e197", "size": 9144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/krr_classification_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/krr_classification_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/krr_classification_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": 43.1320754717, "max_line_length": 115, "alphanum_fraction": 0.6858048994, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6577799353700736}}
{"text": "#include <ctime>\n#include <gtest/gtest.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n\n#include \"slick/math/so2.h\"\n#include \"slick/test/unittest/util.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace slick;\n\n// constructors tests ==========================================================\ntemplate <typename T>\nvoid DefaultConstructor_Test() {\n  // for double precision\n  SO2Group<T> rot;\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 2, 2>::Identity(), rot.get_matrix(),\n                     Gap<T>());\n}\n\nTEST(SO2Test, DefaultConstructor) {\n  DefaultConstructor_Test<double>();\n  DefaultConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromMatrixConstructor_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 2, 2> mrot;\n  mrot = Eigen::Rotation2D<T>(angle);\n  SO2Group<T> rot(mrot);\n  EXPECT_MATRIX_NEAR(mrot, rot.get_matrix(), Gap<T>());\n}\n\nTEST(SO2Test, FromMatrixConstructor) {\n  FromMatrixConstructor_Test<double>();\n  FromMatrixConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromAngleConstructor_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 2, 2> mrot;\n  mrot = Eigen::Rotation2D<T>(angle);\n  SO2Group<T> rot(angle);\n  EXPECT_MATRIX_NEAR(mrot, rot.get_matrix(), Gap<T>());\n}\n\nTEST(SO2Test, FromAngleConstructor) {\n  FromAngleConstructor_Test<double>();\n  FromAngleConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromListInitializerConstructor_Test() {\n  SO2Group<T> rot{1, 0, 0, 1};\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 2, 2>::Identity(), rot.get_matrix(),\n                     Gap<T>());\n\n  EXPECT_NEAR(0.0, rot.ln(), Gap<T>());\n}\n\nTEST(SO2Test, FromListInitializerConstructor) {\n  FromListInitializerConstructor_Test<double>();\n  FromListInitializerConstructor_Test<float>();\n}\n\n// so2 specific functions ======================================================\ntemplate <typename T>\nvoid Ln_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand()) / T(RAND_MAX) * 2 * M_PI;\n  SO2Group<T> rot(angle);\n  auto est = rot.ln();\n  est = (est > 0) ? est : 2 * M_PI + est;\n  EXPECT_NEAR(angle, est, Gap<T>());\n}\n\nTEST(SO2Test, Ln) {\n  Ln_Test<double>();\n  Ln_Test<float>();\n}\n\ntemplate <typename T>\nvoid Inverse_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n  SO2Group<T> rot(angle);\n  Eigen::Matrix<T, 2, 2> m_inv = rot.get_matrix().inverse();\n  EXPECT_MATRIX_NEAR(m_inv, rot.inverse().get_matrix(), Gap<T>());\n}\n\nTEST(SO2Test, Inverse) {\n  Inverse_Test<double>();\n  Inverse_Test<float>();\n}\n\ntemplate <typename T>\nvoid SO2RightHandMulOperator_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 2, 2> mrot1;\n  mrot1 = Eigen::Rotation2D<T>(angle);\n  SO2Group<T> rot1(angle);\n\n  std::srand(std::time(0));  // use current time as seed for random generator\n  angle = T(std::rand());\n  Eigen::Matrix<T, 2, 2> mrot2;\n  mrot2 = Eigen::Rotation2D<T>(angle);\n  SO2Group<T> rot2(angle);\n\n  SO2Group<T> rot(2.0);\n  EXPECT_MATRIX_NEAR(mrot1 * mrot2, (rot1 * rot2).get_matrix(), Gap<T>());\n}\n\nTEST(SO2Test, SO2RightHandMulOperator) {\n  SO2RightHandMulOperator_Test<double>();\n  SO2RightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixRightHandMulOperator_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 2, 2> mrot;\n  mrot = Eigen::Rotation2D<T>(angle);\n\n  SO2Group<T> rot(angle);\n\n  Eigen::Matrix<T, 2, 2> mrand = Eigen::Matrix<T, 2, 2>::Random();\n  EXPECT_MATRIX_NEAR(mrot * mrand, rot * mrand, Gap<T>());\n}\n\nTEST(SO2Test, MatrixRightHandMulOperator) {\n  MatrixRightHandMulOperator_Test<double>();\n  MatrixRightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixLeftHandMulOperator_Test() {\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 2, 2> mrot;\n  mrot = Eigen::Rotation2D<T>(angle);\n\n  SO2Group<T> rot(angle);\n\n  Eigen::Matrix<T, 2, 2> mrand = Eigen::Matrix<T, 2, 2>::Random();\n  EXPECT_MATRIX_NEAR(mrand * mrot, mrand * rot, Gap<T>());\n}\n\nTEST(SO2Test, MatrixLeftHandMulOperator) {\n  MatrixLeftHandMulOperator_Test<double>();\n  MatrixLeftHandMulOperator_Test<float>();\n}\n\nint main(int argc, char** argv) {\n  std::vector<char*> vars(argc+1);\n  for (int i = 0; i < argc; ++i)\n    vars[i] = argv[i];\n  char ca[50];\n  sprintf(ca, \"--gtest_repeat=%d\", NSAMPLES);\n  vars[argc] = ca;\n  argc++;\n  ::testing::InitGoogleTest(&argc, &vars.front());\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c58e4c028f53b71dd7369e26810a09173fb5e866", "size": 4807, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/unittest/math_so2_unittest.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/unittest/math_so2_unittest.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "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": "slick/test/unittest/math_so2_unittest.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "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.3125, "max_line_length": 80, "alphanum_fraction": 0.6629914708, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6577704345822333}}
{"text": "/*************************************************************************\n\t> File Name: main.cpp\n\t> Author: TAI Lei\n\t> Mail: ltai@ust.hk\n\t> Created Time: Thu Mar  7 19:39:14 2019\n ************************************************************************/\n\n#include <iostream>\n#include <random>\n#include <cmath>\n#include <Eigen/Eigen>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#define SIM_TIME 50.0\n#define DT 0.1\n#define PI 3.141592653\n\n\n// x_{t+1} = F@x_{t}+B@u_t\nEigen::Vector4f motion_model(Eigen::Vector4f x, Eigen::Vector2f u){\n  Eigen::Matrix4f F_;\n  F_<<1.0,   0,   0,   0,\n        0, 1.0,   0,   0,\n        0,   0, 1.0,   0,\n        0,   0,   0, 1.0;\n\n  Eigen::Matrix<float, 4, 2> B_;\n  B_<< DT * std::cos(x(2,0)),  0,\n       DT * std::sin(x(2,0)),  0,\n                        0.0,  DT,\n                        1.0,  0.0;\n\n  return F_ * x + B_ * u;\n};\n\nEigen::Matrix4f jacobF(Eigen::Vector4f x, Eigen::Vector2f u){\n  Eigen::Matrix4f jF_ = Eigen::Matrix4f::Identity();\n  float yaw = x(2);\n  float v = u(0);\n  jF_(0,2) = -DT * v * std::sin(yaw);\n  jF_(0,3) = DT * std::cos(yaw);\n  jF_(1,2) = DT * v * std::cos(yaw);\n  jF_(1,3) = DT * std::sin(yaw);\n  return jF_;\n};\n\n//observation mode H\nEigen::Vector2f observation_model(Eigen::Vector4f x){\n  Eigen::Matrix<float, 2, 4> H_;\n  H_<< 1, 0, 0, 0,\n       0, 1, 0, 0;\n  return H_ * x;\n};\n\nEigen::Matrix<float, 2, 4> jacobH(){\n  Eigen::Matrix<float, 2, 4> jH_;\n  jH_<< 1, 0, 0, 0,\n        0, 1, 0, 0;\n  return jH_;\n};\n\nvoid ekf_estimation(Eigen::Vector4f& xEst, Eigen::Matrix4f& PEst,\n  Eigen::Vector2f z, Eigen::Vector2f u,\n  Eigen::Matrix4f Q, Eigen::Matrix2f R){\n    Eigen::Vector4f xPred = motion_model(xEst, u);\n    Eigen::Matrix4f jF = jacobF(xPred, u);\n    Eigen::Matrix4f PPred = jF * PEst * jF.transpose() + Q;\n\n    Eigen::Matrix<float, 2, 4> jH = jacobH();\n    Eigen::Vector2f zPred = observation_model(xPred);\n    Eigen::Vector2f y = z - zPred;\n    Eigen::Matrix2f S = jH * PPred * jH.transpose() + R;\n    Eigen::Matrix<float, 4, 2> K = PPred * jH.transpose() * S.inverse();\n    xEst = xPred + K * y;\n    PEst = (Eigen::Matrix4f::Identity() - K * jH) * PPred;\n};\n\ncv::Point2i cv_offset(\n    Eigen::Vector2f e_p, int image_width=2000, int image_height=2000){\n  cv::Point2i output;\n  output.x = int(e_p(0) * 100) + image_width/2;\n  output.y = image_height - int(e_p(1) * 100) - image_height/3;\n  return output;\n};\n\nvoid ellipse_drawing(\n  cv::Mat bg_img, Eigen::Matrix2f pest, Eigen::Vector2f center,\n  cv::Scalar ellipse_color=cv::Scalar(0, 0, 255)\n){\n  Eigen::EigenSolver<Eigen::Matrix2f> ces(pest);\n  Eigen::Matrix2f e_value = ces.pseudoEigenvalueMatrix();\n  Eigen::Matrix2f e_vector = ces.pseudoEigenvectors();\n\n  double angle = std::atan2(e_vector(0, 1), e_vector(0, 0));\n  cv::ellipse(\n    bg_img,\n    cv_offset(center, bg_img.cols, bg_img.rows),\n    cv::Size(e_value(0,0)*1000, e_value(1,1)*1000),\n    angle / PI * 180,\n    0,\n    360,\n    ellipse_color,\n    2,\n    4);\n};\n\nint main(){\n  float time=0.0;\n\n  // control input\n  Eigen::Vector2f u;\n  u<<1.0, 0.1;\n\n  // nosie control input\n  Eigen::Vector2f ud;\n\n  // observation z\n  Eigen::Vector2f z;\n\n  // dead reckoning\n  Eigen::Vector4f xDR;\n  xDR<<0.0,0.0,0.0,0.0;\n\n  // ground truth reading\n  Eigen::Vector4f xTrue;\n  xTrue<<0.0,0.0,0.0,0.0;\n\n  // Estimation\n  Eigen::Vector4f xEst;\n  xEst<<0.0,0.0,0.0,0.0;\n\n  std::vector<Eigen::Vector4f> hxDR;\n  std::vector<Eigen::Vector4f> hxTrue;\n  std::vector<Eigen::Vector4f> hxEst;\n  std::vector<Eigen::Vector2f> hz;\n\n  Eigen::Matrix4f PEst = Eigen::Matrix4f::Identity();\n\n  // Motional model covariance\n  Eigen::Matrix4f Q = Eigen::Matrix4f::Identity();\n  Q(0,0)=0.1 * 0.1;\n  Q(1,1)=0.1 * 0.1;\n  Q(2,2)=(1.0/180 * M_PI) * (1.0/180 * M_PI);\n  Q(3,3)=0.1 * 0.1;\n\n  // Observation model covariance\n  Eigen::Matrix2f  R = Eigen::Matrix2f::Identity();\n  R(0,0)=1.0;\n  R(1,1)=1.0;\n\n  // Motion model simulation error\n  Eigen::Matrix2f Qsim = Eigen::Matrix2f::Identity();\n  Qsim(0,0)=1.0;\n  Qsim(1,1)=(30.0/180 * M_PI) * (30.0/180 * M_PI);\n\n  // Observation model simulation error\n  Eigen::Matrix2f Rsim = Eigen::Matrix2f::Identity();\n  Rsim(0,0)=0.5 * 0.5;\n  Rsim(1,1)=0.5 * 0.5;\n\n  std::random_device rd{};\n  std::mt19937 gen{rd()};\n  std::normal_distribution<> gaussian_d{0,1};\n\n  //for visualization\n  cv::namedWindow(\"ekf\", cv::WINDOW_NORMAL);\n  int count = 0;\n\n  while(time <= SIM_TIME){\n    time += DT;\n\n    ud(0) = u(0) + gaussian_d(gen) * Qsim(0,0);\n    ud(1) = u(1) + gaussian_d(gen) * Qsim(1,1);\n\n    xTrue = motion_model(xTrue, u);\n    xDR = motion_model(xDR, ud);\n\n    z(0) = xTrue(0) + gaussian_d(gen) * Rsim(0,0);\n    z(1) = xTrue(1) + gaussian_d(gen) * Rsim(1,1);\n\n    ekf_estimation(xEst, PEst, z, ud, Q, R);\n\n    hxDR.push_back(xDR);\n    hxTrue.push_back(xTrue);\n    hxEst.push_back(xEst);\n    hz.push_back(z);\n\n    //visualization\n    cv::Mat bg(3500,3500, CV_8UC3, cv::Scalar(255,255,255));\n    for(unsigned int j=0; j<hxDR.size(); j++){\n\n      // green groundtruth\n      cv::circle(bg, cv_offset(hxTrue[j].head(2), bg.cols, bg.rows),\n                 7, cv::Scalar(0,255,0), -1);\n\n      // blue estimation\n      cv::circle(bg, cv_offset(hxEst[j].head(2), bg.cols, bg.rows),\n                 10, cv::Scalar(255,0,0), 5);\n\n      // black dead reckoning\n      cv::circle(bg, cv_offset(hxDR[j].head(2), bg.cols, bg.rows),\n                 7, cv::Scalar(0, 0, 0), -1);\n    }\n\n    // red observation\n    for(unsigned int i=0; i<hz.size(); i++){\n      cv::circle(bg, cv_offset(hz[i], bg.cols, bg.rows),\n               7, cv::Scalar(0, 0, 255), -1);\n    }\n\n    ellipse_drawing(bg, PEst.block(0,0,2,2), xEst.head(2));\n\n    cv::imshow(\"ekf\", bg);\n    cv::waitKey(5);\n\n    // std::string int_count = std::to_string(count);\n    // cv::imwrite(\"./pngs/\"+std::string(5-int_count.length(), '0').append(int_count)+\".png\", bg);\n\n    count++;\n  }\n}\n", "meta": {"hexsha": "99f854a3f9048294a3c1006ee0013267a5b26c79", "size": 5867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extended_kalman_filter.cpp", "max_stars_repo_name": "Singh-sid930/CppRobotics", "max_stars_repo_head_hexsha": "0e4ced2cf1c927156cd3745dee2b2e7250ce95d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-27T07:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:54:34.000Z", "max_issues_repo_path": "src/extended_kalman_filter.cpp", "max_issues_repo_name": "sweetquiet/CppRobotics", "max_issues_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_issues_repo_licenses": ["MIT"], "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/extended_kalman_filter.cpp", "max_forks_repo_name": "sweetquiet/CppRobotics", "max_forks_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-11T13:53:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T13:53:59.000Z", "avg_line_length": 26.1919642857, "max_line_length": 98, "alphanum_fraction": 0.575421851, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6577704253093366}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\n\ntypedef Eigen::Matrix<float, 3, 3> MyMatrix33f;\ntypedef Eigen::Matrix<float, 3, 1> MyVector3f;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MyMatrix;\n\n\n\nint main() {\n  //Definitions\n  MyMatrix33f a;\n  MyVector3f v;\n  MyMatrix mym(10, 15);\n  MatrixXd m(2, 2);\n\n  // Initializations\n  a = MyMatrix33f::Zero(); \n  a = MyMatrix33f::Identity(); \n  v = MyVector3f::Random();\n\n  // Assignments\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  a << 1,2,3,\n       4,5,6,\n       7,8,9;\n\n  // Output\n  std::cout << m << std::endl;\n\n  // Mapping (shallow copy)\n  int data[] = {1, 2, 3, 4};\n  Eigen::Map<Eigen::RowVectorXi> r(data, 4);\n  std::vector<float> data2 = {1,2,3,4,5,6,8,9};\n  Eigen::Map<MyMatrix33f> n(data2.data());\n\n  // Math\n  // what are the types?\n  auto x = Eigen::Matrix2d::Random();\n  auto y = Eigen::Matrix2d::Random();\n  auto res = x + y;\n  auto res2 = x.array() * y.array(); // element wise multiplication\n  // x = y + x;\n  auto res3 = x.array() / y.array();\n  //x += y;\n  //r = x * y;  // matrix multi\n  auto res4 = x.array() * 3;\n\n}\n", "meta": {"hexsha": "0f0a84ff40715e872a7d9476dcb0cd1fe5bfeec4", "size": 1154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/linear_algebra/main.cpp", "max_stars_repo_name": "weberdaniel/ml", "max_stars_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/linear_algebra/main.cpp", "max_issues_repo_name": "weberdaniel/ml", "max_issues_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T18:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T22:57:31.000Z", "max_forks_repo_path": "app/linear_algebra/main.cpp", "max_forks_repo_name": "weberdaniel/ml", "max_forks_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_forks_repo_licenses": ["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.9818181818, "max_line_length": 71, "alphanum_fraction": 0.5771230503, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574298, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6576769296873297}}
{"text": "/* Copyright (C) 2016-2018 Alibaba Group Holding Limited\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#include \"orthogonal_initializer.h\"\n\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <memory>\n#include <Eigen/SVD>  \n#include <Eigen/Dense>    \n\n#include \"ps-plus/common/types.h\"\n#include \"random/random.h\"\n#include \"random/random_ops.h\"\n#include \"normal_initializer.h\"\n\nusing namespace Eigen;    \nusing namespace Eigen::internal;    \nusing namespace Eigen::Architecture;    \n\nnamespace ps {\nnamespace initializer {\n\nOrthogonalInitializer::OrthogonalInitializer(\n    int64_t dim, int seed, float gain)\n  : dim_(dim)\n  , seed_(seed)\n  , gain_(gain) {\n  normal_initializer_.reset(new NormalInitializer(seed, 0.0, 1.0));\n}\n\nbool OrthogonalInitializer::Accept(DataType type) {\n  if (type == DataType::kFloat || \n      type == DataType::kDouble) {\n    return true;\n  }\n\n  return false;\n}\n\nvoid OrthogonalInitializer::Init(void* data, \n                                 DataType type, \n                                 size_t size) {\n  if (size % dim_ != 0) {\n    printf(\"error size\\n\");\n    abort();\n  }\n\n  normal_initializer_->Init(data, type, size);\n  int64_t row = size / dim_;\n  int64_t col = dim_;\n  if (type == DataType::kFloat) {\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> m((float*)data, row, col);  \n    Eigen::JacobiSVD<Eigen::MatrixXf> svd(m, Eigen::ComputeThinV | Eigen::ComputeThinU);\n    Eigen::MatrixXf u = svd.matrixU() * gain_;\n    Eigen::MatrixXf v = svd.matrixV() * gain_;      \n    if ((row == u.rows() && col == u.cols()) ||\n        (row == u.cols() && col == u.rows())) {\n      Eigen::MatrixXf trans_u = u.transpose();\n      memcpy(data, trans_u.data(), size * sizeof(float));\n    } else if ((row == v.rows() && col == v.cols()) ||\n               (row == v.cols() && col == v.rows())) {\n      memcpy(data, v.data(), size * sizeof(float));       \n    } else {\n      printf(\"svd result shape[%d,%d|%d,%d] not match\\n\", u.rows(), u.cols(), v.rows(), v.cols());\n      abort();\n    }\n  } else {\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> m((double*)data, row, col);      \n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(m, Eigen::ComputeThinV | Eigen::ComputeThinU);\n    Eigen::MatrixXd u = svd.matrixU() * gain_;\n    Eigen::MatrixXd v = svd.matrixV() * gain_;\n    if ((row == u.rows() && col == u.cols()) ||\n        (row == u.cols() && col == u.rows())) {\n      Eigen::MatrixXd trans_u = u.transpose();\n      memcpy(data, trans_u.data(), size * sizeof(double));\n    } else if ((row == v.rows() && col == v.cols()) ||\n               (row == v.cols() && col == v.rows())) {\n      memcpy(data, v.data(), size * sizeof(double));       \n    } else {\n      printf(\"svd result shape[%d,%d|%d,%d] not match\\n\", u.rows(), u.cols(), v.rows(), v.cols());\n      abort();\n    }\n  }\n}\n\nInitializer* OrthogonalInitializer::Clone() {\n  return new OrthogonalInitializer(\n      dim_, seed_, gain_);\n}\n\n} //namespace initializer\n} //ps\n\n", "meta": {"hexsha": "957587ccff02ee9ebd9da11339348c156ba68057", "size": 3589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_stars_repo_name": "Ru-Xiang/x-deeplearning", "max_stars_repo_head_hexsha": "04cc0497150920c64b06bb8c314ef89977a3427a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4071.0, "max_stars_repo_stars_event_min_datetime": "2018-12-13T04:17:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:29:35.000Z", "max_issues_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_issues_repo_name": "laozhuang727/x-deeplearning", "max_issues_repo_head_hexsha": "781545783a4e2bbbda48fc64318fb2c6d8bbb3cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 359.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T01:14:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T07:18:02.000Z", "max_forks_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_forks_repo_name": "laozhuang727/x-deeplearning", "max_forks_repo_head_hexsha": "781545783a4e2bbbda48fc64318fb2c6d8bbb3cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1054.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T09:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:16:53.000Z", "avg_line_length": 33.2314814815, "max_line_length": 120, "alphanum_fraction": 0.6057397604, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.657637765648437}}
{"text": "#include <Eigen/Dense>\r\n#include \"partitionlist.hpp\"\r\n\r\nusing namespace Eigen;\r\n\r\n\r\ntemplate <class uint>\r\nclass AssemblyOp : public EigenBase< AssemblyOp<uint> > {\r\n\tprivate:\r\n\t\tconst MatrixXd& A;\r\n\t\tconst MatrixXd& B;\r\n\t\tconst PartitionList<uint>& states;\r\n\r\n\tpublic:\r\n\t\t// eigen boilerplate\r\n\t\ttypedef double Scalar;\r\n\t\ttypedef double RealScalar;\r\n\t\ttypedef int StorageIndex;\r\n\t\tenum {\r\n\t\t\tColsAtCompileTime = Eigen::Dynamic,\r\n\t\t\tMaxColsAtCompileTime = Eigen::Dynamic,\r\n\t\t\tIsRowMajor = true\r\n\t\t};\r\n\t\tIndex rows() const { return states.size(); }\r\n\t\tIndex cols() const { return states.size(); }\r\n\t\ttemplate <typename Rhs>\r\n\t\tProduct< AssemblyOp<uint>, Rhs, AliasFreeProduct > operator*(const Eigen::MatrixBase<Rhs>& x) const {\r\n\t\t\treturn Product< AssemblyOp<uint>, Rhs, AliasFreeProduct >(*this, x.derived()); \r\n\t\t}\r\n\r\n\r\n\r\n\t\tAssemblyOp() {}\r\n\t\tAssemblyOp(const PartitionList<uint>& states_, const MatrixXd& A_, const MatrixXd& B_) : states(states_), A(A_), B(B_) {}\r\n\t\t//VectorXd operator*(const VectorXd& x) const { return this->apply(x); }\r\n\r\n\t\tVectorXd apply(const VectorXd& x) const {\r\n\t\t\tVectorXd b = VectorXd::Zero(x.size());\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\tb(index) += B(j-1,i-j-1) * (double) n * (x(index) - x(nbrIndex));\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,i-1) * (double) (n*(n-1)) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}\r\n\r\n\t\tVectorXd adjointApply(const VectorXd& x) const {\r\n\t\t\tVectorXd b = VectorXd::Zero(x.size());\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\t\t\tdouble rate;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\trate = B(j-1,i-j-1) * (double) n * x(index);\r\n\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}\r\n/*\r\n\t\tMatrix<double,Dynamic,4> split_apply(const VectorXd& x) const {\r\n\t\t\tMatrix<double,Dynamic,4> b(x.size(),4);\r\n\t\t\tb.setConstant(0.0);\r\n\t\t\t\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\r\n\t\t\tdouble rate = 0.0;\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\r\n\t\t\t\t\t\trate = B(j-1,i-j-1) * (double) n;\r\n\t\t\t\t\t\tb(index,0) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\tb(index,1) += rate * x(index);\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1));\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}*/\r\n\r\n\t\tVectorXd solve_diagonal(const VectorXd& b) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\t\t\tdouble currentRate, totalRate = 0.0;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\ttotalRate += B(j-1,i-j-1) * (double) n;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttotalRate += A(i-1,i-1) * (double) (n*(n-1));\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate;\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n\r\n\r\n\r\n\t\tVectorXd solve_lower(const VectorXd& b, double omega) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\t\t\tdouble currentRate, totalRate;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\ttotalRate = 0.0;\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\tcurrentRate = B(j-1,i-j-1) * (double) n;\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttotalRate += A(i-1,i-1) * (double) (n*(n-1));\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate/omega;\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n\r\n\t\tVectorXd solve_upper(const VectorXd& b, double omega) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition<uint> nbr;\r\n\t\t\tdouble currentRate, totalRate;\r\n\r\n\t\t\tindex = states.size();\r\n\t\t\tauto stateit = states.end();\r\n\t\t\twhile (index-->0) {\r\n\t\t\t\t--stateit;\r\n\r\n\t\t\t\tauto state = *stateit;\r\n\t\t\t\ttotalRate = 0.0;\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\ttotalRate += B(j-1,i-j-1) * (double) n;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tcurrentRate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tcurrentRate = A(i-1,i-1) * (double) (n*(n-1));\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tcurrentRate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate/omega;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n};\r\n\r\n\r\n\r\nnamespace Eigen {\r\nnamespace internal {\r\n  template<typename uint>\r\n  struct traits< AssemblyOp<uint> > :  public Eigen::internal::traits<Eigen::SparseMatrix<double> > {};\r\n}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n// Implementation of MatrixReplacement * Eigen::DenseVector though a specialization of internal::generic_product_impl:\r\nnamespace Eigen {\r\nnamespace internal {\r\n  template<typename Rhs, typename uint>\r\n  struct generic_product_impl<AssemblyOp<uint>, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\r\n  : generic_product_impl_base<AssemblyOp<uint>,Rhs,generic_product_impl<AssemblyOp<uint>,Rhs> >\r\n  {\r\n    typedef typename Product<AssemblyOp<uint>,Rhs>::Scalar Scalar;\r\n    template<typename Dest>\r\n    static void scaleAndAddTo(Dest& dst, const AssemblyOp<uint>& lhs, const Rhs& rhs, const Scalar& alpha)\r\n    {\r\n      // This method should implement \"dst += alpha * lhs * rhs\" inplace,\r\n      // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it.\r\n      assert(alpha==Scalar(1) && \"scaling is not implemented\");\r\n      // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs,\r\n      // but let's do something fancier (and less efficient):\r\n      dst.noalias() += lhs.apply(rhs.matrix());\r\n    }\r\n  };\r\n}\r\n}\r\n", "meta": {"hexsha": "48470bb31211f9110df72c231cdee6999a01f05e", "size": 12414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moment-solver/src/assemblyop.hpp", "max_stars_repo_name": "jasondark/dissertation", "max_stars_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "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": "moment-solver/src/assemblyop.hpp", "max_issues_repo_name": "jasondark/dissertation", "max_issues_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "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": "moment-solver/src/assemblyop.hpp", "max_forks_repo_name": "jasondark/dissertation", "max_forks_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T01:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T01:05:58.000Z", "avg_line_length": 26.0798319328, "max_line_length": 124, "alphanum_fraction": 0.4992750121, "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.65763774580606}}
{"text": "#include <cmath>\n#include <vector>\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\nusing std::vector;\n\n\ndouble interest(double rate, int years)\n{\n    return pow(1 + rate, years);\n}\n\ndouble compound(double rate, int compound_amount, int years)\n{\n    double acutal_rate = rate / compound_amount;\n    double result = pow(1 + acutal_rate, years * compound_amount);\n    return result;\n}\n\ndouble continous_compound(double rate, int years)\n{\n    double rT = rate * years;\n    return pow(M_E, rT);\n}\n\ndouble annuity(vector<double>payments_per_year)\n{\n    double increase = 0;\n    for (auto&& amount : payments_per_year) {\n        increase += amount;\n    }\n    return increase;\n}\n\n\nBOOST_PYTHON_MODULE(finance_formulas)\n{\n    using namespace boost::python;\n    class_<vector<double> >(\"double_vector\")\n                .def(vector_indexing_suite<vector<double> >() );\n    def(\"interest\", interest);\n    def(\"compound\", compound);\n    def(\"continous_compound\", continous_compound);\n    def(\"annuity\", annuity);\n}\n", "meta": {"hexsha": "ea45439bc52aa03e327999d8b42ed533f9dfb9b1", "size": 1048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "formulas/finance_formulas.cpp", "max_stars_repo_name": "banjocat/finance-fun", "max_stars_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "formulas/finance_formulas.cpp", "max_issues_repo_name": "banjocat/finance-fun", "max_issues_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formulas/finance_formulas.cpp", "max_forks_repo_name": "banjocat/finance-fun", "max_forks_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_forks_repo_licenses": ["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.2978723404, "max_line_length": 66, "alphanum_fraction": 0.6870229008, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.6576377458060599}}
{"text": "// Deal.ii\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/smartpointer.h>\n#include <deal.II/base/convergence_table.h>\n#include <deal.II/base/numbers.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/affine_constraints.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/dofs/dof_renumbering.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n\n// STL\n#include <array>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n\n\nnamespace Helmholtz\n{\n  using namespace dealii;\n\n  ///////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////\n\n  template <int dim>\n  class Solution : public Function<dim>\n  {\n  public:\n    virtual double value(const Point<dim> & p,\n                         const unsigned int component = 0) const override;\n\n    virtual Tensor<1, dim>\n    gradient(const Point<dim> & p,\n             const unsigned int component = 0) const override;\n  };\n\n\n  template <int dim>\n  double Solution<dim>::value(const Point<dim> &p, const unsigned int) const\n  {\n    double return_value = 1;\n\n    for (unsigned int i = 0; i<dim; ++i)\n        \treturn_value *= cos(2*numbers::PI*p(i));\n\n    return return_value;\n  }\n\n\n  template <>\n  Tensor<1, 1> Solution<1>::gradient(const Point<1> &p,\n                                         const unsigned int) const\n  {\n    Tensor<1, 1> return_value;\n\n\treturn_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0));\n\n    return return_value;\n  }\n\n\n  template <>\n  Tensor<1, 2> Solution<2>::gradient(const Point<2> &p,\n                                         const unsigned int) const\n  {\n    Tensor<1, 2> return_value;\n\n\treturn_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1));\n\treturn_value[1] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * sin(2*numbers::PI*p(1));\n\n    return return_value;\n  }\n\n\n  template <>\n    Tensor<1, 3> Solution<3>::gradient(const Point<3> &p,\n                                           const unsigned int) const\n    {\n      Tensor<1, 3> return_value;\n\n      return_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1)) * cos(2*numbers::PI*p(2));\n      return_value[1] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * sin(2*numbers::PI*p(1)) * cos(2*numbers::PI*p(2));\n      return_value[2] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1)) * sin(2*numbers::PI*p(2));\n\n      return return_value;\n    }\n\n\n  ///////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////\n\n\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    virtual double value(const Point<dim> & p,\n                         const unsigned int component = 0) const override;\n  };\n\n\n  template <int dim>\n  double RightHandSide<dim>::value(const Point<dim> &p,\n                                   const unsigned int) const\n  {\n    double return_value = (1 + 4 * dim * std::pow(numbers::PI,2));\n\n    for (unsigned int i = 0; i<dim; ++i)\n    \treturn_value *= cos(2*numbers::PI*p(i));\n\n    return return_value;\n  }\n\n\n  ///////////////////////////////////////////////////////\n  ///////////////////////////////////////////////////////\n\n\n  template <int dim>\n  class HelmholtzSolver\n  {\n  public:\n    HelmholtzSolver(const FiniteElement<dim> &fe);\n\n    ~HelmholtzSolver();\n\n    void run();\n\n  private:\n    void setup_system();\n    void assemble_system();\n    void solve();\n    void process_solution(const unsigned int cycle);\n    void output_vtk(const unsigned int cycle);\n\n    Triangulation<dim> triangulation;\n    DoFHandler<dim>    dof_handler;\n\n    SmartPointer<const FiniteElement<dim>> fe;\n\n    AffineConstraints<double> constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    Vector<double> solution;\n    Vector<double> system_rhs;\n\n    ConvergenceTable convergence_table;\n  };\n\n\n  template <int dim>\n  HelmholtzSolver<dim>::HelmholtzSolver(const FiniteElement<dim> &fe)\n    : dof_handler(triangulation)\n    , fe(&fe)\n  {}\n\n\n  template <int dim>\n  HelmholtzSolver<dim>::~HelmholtzSolver()\n  {\n    dof_handler.clear();\n  }\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::setup_system()\n  {\n    dof_handler.distribute_dofs(*fe);\n    DoFRenumbering::Cuthill_McKee(dof_handler);\n\n    constraints.clear();\n    DoFTools::make_hanging_node_constraints(dof_handler,\n                                            constraints);\n\n    Solution<dim>\texact_solution;\n\n    VectorTools::interpolate_boundary_values(dof_handler,\n                                               0,\n                                               exact_solution,\n                                               constraints);\n\n    constraints.close();\n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern(dof_handler, dsp);\n    constraints.condense(dsp);\n    sparsity_pattern.copy_from(dsp);\n\n    system_matrix.reinit(sparsity_pattern);\n\n    solution.reinit(dof_handler.n_dofs());\n    system_rhs.reinit(dof_handler.n_dofs());\n  }\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::assemble_system()\n  {\n    QGauss<dim>     quadrature_formula(fe->degree + 1);\n\n    const unsigned int n_q_points      = quadrature_formula.size();\n\n    const unsigned int dofs_per_cell = fe->dofs_per_cell;\n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n    Vector<double>     cell_rhs(dofs_per_cell);\n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n    FEValues<dim> fe_values(*fe,\n                            quadrature_formula,\n                            update_values | update_gradients |\n                              update_quadrature_points | update_JxW_values);\n\n    RightHandSide<dim>  right_hand_side;\n    std::vector<double> rhs_values(n_q_points);\n\n    for (const auto &cell : dof_handler.active_cell_iterators())\n      {\n        cell_matrix = 0.;\n        cell_rhs    = 0.;\n\n        fe_values.reinit(cell);\n\n        right_hand_side.value_list(fe_values.get_quadrature_points(),\n                                   rhs_values);\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            {\n              for (unsigned int j = 0; j < dofs_per_cell; ++j)\n                cell_matrix(i, j) +=\n                  ((fe_values.shape_grad(i, q_point) *     // grad phi_i(x_q)\n                      fe_values.shape_grad(j, q_point)     // grad phi_j(x_q)\n                    +                                      //\n                    fe_values.shape_value(i, q_point) *    // phi_i(x_q)\n                      fe_values.shape_value(j, q_point)) * // phi_j(x_q)\n                   fe_values.JxW(q_point));                // dx\n\n\n              cell_rhs(i) += (fe_values.shape_value(i, q_point) * // phi_i(x_q)\n                              rhs_values[q_point] *               // f(x_q)\n                              fe_values.JxW(q_point));            // dx\n            }\n\n        cell->get_dof_indices(local_dof_indices);\n        constraints.distribute_local_to_global(\n                cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs);\n      }\n  }\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::solve()\n  {\n    SolverControl solver_control(1000, 1e-12);\n    SolverCG<>    cg(solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner);\n\n    std::cout << \"   \" << solver_control.last_step()\n                << \" CG iterations needed to obtain convergence.\" << std::endl;\n\n    constraints.distribute(solution);\n  }\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::process_solution(const unsigned int cycle)\n  {\n\tSolution<dim> exact_solution;\n\n    Vector<float> difference_per_cell(triangulation.n_active_cells());\n    VectorTools::integrate_difference(dof_handler,\n                                      solution,\n                                      exact_solution,\n                                      difference_per_cell,\n                                      QGauss<dim>(fe->degree + 1),\n                                      VectorTools::L2_norm);\n    const double L2_error =\n      VectorTools::compute_global_error(triangulation,\n                                        difference_per_cell,\n                                        VectorTools::L2_norm);\n\n\n    VectorTools::integrate_difference(dof_handler,\n                                      solution,\n                                      Solution<dim>(),\n                                      difference_per_cell,\n                                      QGauss<dim>(fe->degree + 1),\n                                      VectorTools::H1_seminorm);\n    const double H1_error =\n      VectorTools::compute_global_error(triangulation,\n                                        difference_per_cell,\n                                        VectorTools::H1_seminorm);\n\n\n    const unsigned int n_active_cells = triangulation.n_active_cells();\n    const unsigned int n_dofs         = dof_handler.n_dofs();\n\n    std::cout << \"Cycle \" << cycle << ':' << std::endl\n              << \"   Number of active cells:       \" << n_active_cells\n              << std::endl\n              << \"   Number of degrees of freedom: \" << n_dofs << std::endl;\n\n    convergence_table.add_value(\"cycle\", cycle);\n    convergence_table.add_value(\"cells\", n_active_cells);\n    convergence_table.add_value(\"dofs\", n_dofs);\n    convergence_table.add_value(\"L2\", L2_error);\n    convergence_table.add_value(\"H1\", H1_error);\n  }\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::output_vtk(const unsigned int cycle)\n  {\n\tstd::string vtk_filename\n\t\t= \"solution-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n\tswitch (fe->degree)\n\t  {\n\t\tcase 1:\n\t\t  vtk_filename += \"_q1\";\n\t\t  break;\n\t\tcase 2:\n\t\t  vtk_filename += \"_q2\";\n\t\t  break;\n\t\tdefault:\n\t\t  Assert(false, ExcNotImplemented());\n\t  }\n\n\tvtk_filename += \"_cycle-\" + Utilities::int_to_string(cycle,1);\n\tvtk_filename += \".vtk\";\n\n\tstd::ofstream output(vtk_filename);\n\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler(dof_handler);\n\tdata_out.add_data_vector(solution, \"solution\");\n\n\tdata_out.build_patches(fe->degree);\n\tdata_out.write_vtk(output);\n}\n\n\n  template <int dim>\n  void HelmholtzSolver<dim>::run()\n  {\n\n    const unsigned int n_cycles = 6;\n\n    for (unsigned int cycle = 0; cycle < n_cycles; ++cycle)\n      {\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_cube(triangulation, 0, 1);\n            triangulation.refine_global(1);\n          }\n        else\n        \ttriangulation.refine_global();\n\n        setup_system();\n\n        assemble_system();\n        solve();\n\n        process_solution(cycle);\n\n        output_vtk(cycle);\n      }\n\n\n    convergence_table.set_precision(\"L2\", 3);\n    convergence_table.set_precision(\"H1\", 3);\n\n    convergence_table.set_scientific(\"L2\", true);\n    convergence_table.set_scientific(\"H1\", true);\n\n    convergence_table.set_tex_caption(\"cells\", \"\\\\# cells\");\n    convergence_table.set_tex_caption(\"dofs\", \"\\\\# dofs\");\n    convergence_table.set_tex_caption(\"L2\", \"$L^2$-error\");\n    convergence_table.set_tex_caption(\"H1\", \"$H^1$-error\");\n\n    convergence_table.set_tex_format(\"cells\", \"r\");\n    convergence_table.set_tex_format(\"dofs\", \"r\");\n\n    std::cout << std::endl;\n    convergence_table.write_text(std::cout);\n\n    // Write table into a LaTeX file.\n    std::string error_filename\n\t\t= \"error-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n    switch (fe->degree)\n      {\n        case 1:\n          error_filename += \"_q1\";\n          break;\n        case 2:\n          error_filename += \"_q2\";\n          break;\n        default:\n          Assert(false, ExcNotImplemented());\n      }\n\n    error_filename += \".tex\";\n    std::ofstream error_table_file(error_filename);\n\n    convergence_table.write_tex(error_table_file);\n\n    /////////////////\n\n\tconvergence_table.add_column_to_supercolumn(\"cycle\", \"n cells\");\n\tconvergence_table.add_column_to_supercolumn(\"cells\", \"n cells\");\n\n\tstd::vector<std::string> new_order;\n\tnew_order.emplace_back(\"n cells\");\n\tnew_order.emplace_back(\"H1\");\n\tnew_order.emplace_back(\"L2\");\n\tconvergence_table.set_column_order(new_order);\n\n\tconvergence_table.evaluate_convergence_rates(\n\t  \"L2\", ConvergenceTable::reduction_rate);\n\tconvergence_table.evaluate_convergence_rates(\n\t  \"L2\", ConvergenceTable::reduction_rate_log2);\n\tconvergence_table.evaluate_convergence_rates(\n\t  \"H1\", ConvergenceTable::reduction_rate);\n\tconvergence_table.evaluate_convergence_rates(\n\t  \"H1\", ConvergenceTable::reduction_rate_log2);\n\n\tstd::cout << std::endl;\n\tconvergence_table.write_text(std::cout);\n\n\tstd::string conv_filename\n\t\t= \"convergence-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n\tswitch (fe->degree)\n\t  {\n\t\tcase 1:\n\t\t  conv_filename += \"_q1\";\n\t\t  break;\n\t\tcase 2:\n\t\t  conv_filename += \"_q2\";\n\t\t  break;\n\t\tdefault:\n\t\t  Assert(false, ExcNotImplemented());\n\t  }\n\tconv_filename += \".tex\";\n\n\tstd::ofstream table_file(conv_filename);\n\tconvergence_table.write_tex(table_file);\n  }\n\n} // namespace Helmholtz\n\n\n  ///////////////////////////////////////////\n  ///////////////////////////////////////////\n  ///////////////////////////////////////////\n\n\nint main()\n{\n  const unsigned int dim = 1;\n\n  try\n    {\n      using namespace dealii;\n\n      {\n        std::cout << \"Solving with Q1 elements in \" << dim << \"D\" << std::endl\n                  << std::endl\n                  << \"==============================\"\n                  << std::endl\n                  << std::endl;\n\n        FE_Q<dim>             fe(1);\n        Helmholtz::HelmholtzSolver<dim> helmholtz_problem_2d(fe);\n\n        helmholtz_problem_2d.run();\n\n        std::cout << std::endl;\n      }\n\n      {\n        std::cout << \"Solving with Q2 elements in \" << dim << \"D\" << std::endl\n                  << \"==============================\" << std::endl\n                  << std::endl;\n\n        FE_Q<dim>             fe(2);\n        Helmholtz::HelmholtzSolver<dim> helmholtz_problem_2d(fe);\n\n        helmholtz_problem_2d.run();\n\n        std::cout << std::endl;\n      }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "6e0291a83520e1bfeee5cc3958a26cb68af49a87", "size": 15786, "ext": "cc", "lang": "C++", "max_stars_repo_path": "helmholtz.cc", "max_stars_repo_name": "konsim83/Demo_Dealii", "max_stars_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T10:10:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T10:10:47.000Z", "max_issues_repo_path": "helmholtz.cc", "max_issues_repo_name": "konsim83/Demo_Dealii", "max_issues_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helmholtz.cc", "max_forks_repo_name": "konsim83/Demo_Dealii", "max_forks_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_forks_repo_licenses": ["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.3920863309, "max_line_length": 120, "alphanum_fraction": 0.5591030027, "num_tokens": 3736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6575760113049395}}
{"text": "#ifndef _EIGEN_SPACE_\n#define _EIGEN_SPACE_ 1\n\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n#include <exception>\n#include <algorithm>\n\n#include \"naive_bayes.cpp\"\n\n#define _l_ std::cout<<__LINE__<<std::endl;\n\ntypedef struct {\n  Eigen::VectorXd longMean;\n  Eigen::MatrixXd transformationMatrix;\n  ClassInfo ci;\n} ReducedDimClassInfo;\n\n\nbool\nEigenvectorCompare(\n    const std::pair<double, Eigen::VectorXd>& p,\n    const std::pair<double, Eigen::VectorXd>& q) {\n\n  return p.first < q.first;\n}\n\nEigen::MatrixXd\nGetSortedEigenvectors(const Eigen::MatrixXd& matrix) {\n  Eigen::EigenSolver<Eigen::MatrixXd> eigenSolver;\n  eigenSolver.compute(matrix, true);\n\n  std::vector<std::pair<double, Eigen::VectorXd>> sortedEigenvectors;\n  for (unsigned i = 0; i < eigenSolver.eigenvalues().size(); ++i) {\n    if (eigenSolver.eigenvalues().imag()(i) == 0) {\n      sortedEigenvectors.push_back(\n        {\n          eigenSolver.eigenvalues().real()(i),\n          eigenSolver.eigenvectors().col(i).real()\n        }\n      );\n    }\n  }\n  std::sort(sortedEigenvectors.begin(), sortedEigenvectors.end(), EigenvectorCompare);\n\n  Eigen::MatrixXd rowMatrixOfSortedEigenvectors;\n  rowMatrixOfSortedEigenvectors.resizeLike(matrix);\n\n  for (unsigned i = 0; i < matrix.cols(); ++i) {\n\tif (sortedEigenvectors[i].second.rows() == rowMatrixOfSortedEigenvectors.rows()) {\t\n \t   rowMatrixOfSortedEigenvectors.col(i) = sortedEigenvectors[i].second;\n\t} else {\n\t\trowMatrixOfSortedEigenvectors.col(i).setZero();\n\t}\n  }\n\n  return rowMatrixOfSortedEigenvectors.transpose();\n}\n\n\nReducedDimClassInfo\nComputeClassInfoInPcaDimensionReducedSpace(\n    const std::vector<ClassificationObject>& data,\n    const ClassInfo& cartesianClassInfo,\n    const unsigned reducedDimensionality) {\n\n  // create the space transformation matrix\n  unsigned originalDimensionality = cartesianClassInfo.mean.size();\n  Eigen::MatrixXd eigenspaceTransformMatrix(\n    reducedDimensionality,\n    originalDimensionality\n  );\n\n  eigenspaceTransformMatrix =\n    (GetSortedEigenvectors(cartesianClassInfo.covariance)).topLeftCorner(\n      reducedDimensionality,\n      originalDimensionality\n    );\n\n  // transform all of the data to the new space\n  std::vector<ClassificationObject> reducedData;\n  reducedData.reserve(data.size());\n  for (unsigned i = 0; i < data.size(); ++i) {\n    ClassificationObject temp;\n    temp.label = data[i].label;\n\n    temp.features.resize(reducedDimensionality);\n    temp.features = eigenspaceTransformMatrix * data[i].features;\n\n    reducedData.push_back(temp);\n  }\n\n  // compute the new class info\n  ReducedDimClassInfo info;\n  info.longMean = cartesianClassInfo.mean;\n  info.transformationMatrix = eigenspaceTransformMatrix;\n  info.ci = ComputeClassInfo(\n    reducedData,\n    cartesianClassInfo.label,\n    reducedDimensionality\n  );\n\n  return info;\n}\n\nunsigned\nPcaClassifyObject(const ClassificationObject& object, const std::vector<ReducedDimClassInfo>& classSummaries) {\n  unsigned mostLikelyClass = classSummaries.front().ci.label;\n  double highestProbability = 0.0;\n\n  for (const ReducedDimClassInfo& classSummary : classSummaries) {\n    Eigen::VectorXd scaledFeatureVector = object.features - classSummary.longMean;\n    Eigen::VectorXd reducedFeatureVector = classSummary.transformationMatrix * scaledFeatureVector;\n    double probability = GaussianPdf(reducedFeatureVector, classSummary.ci) * classSummary.ci.prior;\n    if (probability > highestProbability) {\n      mostLikelyClass = classSummary.ci.label;\n      highestProbability = probability;\n    }\n  }\n\nstd::cout<<highestProbability<<std::endl;\n\n  return mostLikelyClass;\n}\n\n#endif //_EIGEN_SPACE_", "meta": {"hexsha": "d4aa534f9747303a5f25f73991ba8888b3de918e", "size": 3646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW03/eigen_space.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/eigen_space.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/eigen_space.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": 28.484375, "max_line_length": 111, "alphanum_fraction": 0.73834339, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6575759987478786}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// Copyright 2021 - 2021, the Anboto author and contributors\n#include <Core/Core.h>\n#include <ScatterDraw/ScatterDraw.h>\n#include <Eigen/Eigen.h>\n#include <Functions4U/Functions4U.h>\n#include <STEM4U/Mooring.h>\n#include <plugin/png/png.h>\n\n\nusing namespace Upp;\n\n\nvoid TestMooring(bool test) {\n\tUppLog() << \"\\n\\nCatenary mooring demo\";\n\t\n\tdouble rho_m = 346.7;\t\t// Kg/m   \n\tdouble rho_m3 = 7850;\n\tdouble rho_water = 1025;\n\t\n\tdouble BL = 1.49E9;\t\t\t// Mooring line break load\n\tdouble moorlen = 490;\n\t\n\tdouble xanchorvessel = 480;\t\n\tdouble zanchor = 0;\n\tdouble zvessel = 54;\n\n\tdouble Fhanchorvessel, Fvanchor, Fvvessel, xonfloor;\n\tVector<double> x, z;\n\tMooringStatus status;\n\t\n\tCatenary(moorlen, xanchorvessel, zanchor, zvessel, xonfloor);\n\n\tdouble moorlen2;\n\tCatenaryGetLen(xonfloor, xanchorvessel, zanchor, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(moorlen, moorlen2, 4));\n\n\tCatenaryGetLen(0.1*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(484.4677, moorlen2, 4));\n\tCatenaryGetLen(0.15*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(484.7264, moorlen2, 4));\n\tCatenaryGetLen(0.2*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.0166, moorlen2, 4));\n\tCatenaryGetLen(0.25*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.3445, moorlen2, 4));\n\tCatenaryGetLen(0.3*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.7176, moorlen2, 4));\n\t\n\tstatus = Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, zanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 10);\n\tUppLog() << \"\\nStatus is: \" << MooringStatusStr(status);\n\tVERIFY(status == CATENARY_ON_FLOOR);\n\tVERIFY(EqualDecimals(xonfloor, 292.5933, 4));\n\tVERIFY(EqualDecimals(Fhanchorvessel, 987138.9765, 4));\n\tVERIFY(EqualDecimals(Fvvessel, 583737.6409, 4));\n\t\n\tdouble Fanchor = sqrt(sqr(Fhanchorvessel) + sqr(Fvanchor));\n\tdouble anganchor = atan2(Fvanchor, Fhanchorvessel)*180./M_PI;\n\tdouble Fvessel = sqrt(sqr(Fhanchorvessel) + sqr(Fvvessel));\n\tdouble angvessel = atan2(Fvvessel, Fhanchorvessel)*180./M_PI;\n\tUppLog() << Format(\"\\nFhanchorvessel=%.2f, Fvanchor=%.2f, Fanchor=%.2f, ang_anchor=%.1f grad\\nFvvessel=%.2f, Fvessel=%.2f, ang_vessel=%.1f, xonfloor=%.1f\", \n\t\tFhanchorvessel, -Fvanchor, Fanchor, anganchor, -Fvvessel, Fvessel, angvessel, xonfloor);\n\tVERIFY(FormatF(angvessel, 4) == \"30.5976\");\n\t\t\n\tUppLog() << \"\\nX\\tY\";\n\tfor (int i = 0; i < x.size(); ++i) \n\t\tUppLog() << Format(\"\\n%.2f\\t%.4f\", x[i], z[i]);\n\tVERIFY(FormatF(z[7], 4) == \"9.8116\");\n\t\n\tif (!test) {\n\t\tint num = 100;\n\t\tVector<Vector<double>> xx(5), zz(5);\n\t\tString dir = AppendFileNameX(GetDesktopFolder(), \"STEM4U_Demo\");\n\t\tRealizeDirectory(dir);\n\t\tScatterDraw scatter;\n\t\tscatter.SetLabelX(\"Distance from anchor to vessel [m]\").\n\t\t\t\tSetLabelY(\"Height from floor to vessel [m]\").\n\t\t\t\tSetLeftMargin(70).SetBottomMargin(50).SetSize(Size(1000, 400)).\n\t\t\t\tSetLegendAnchor(ScatterDraw::LEFT_TOP);\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Shifting the vessel to the anchor\");\n\t\t\tfor (int iz = 0; iz < 5; ++iz) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel-iz*15, zanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Xanchorvessel:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\txanchorvessel-iz*15, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor xanchorvessel.png\"), scatter.GetImage());\n\t\t}\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Raising the vessel\");\n\t\t\tfor (int iz = 0; iz < 5; iz++) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel, zanchor, zvessel+iz*10, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Zvessel:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\tzvessel+iz*10, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor zvessel.png\"), scatter.GetImage());\n\t\t}\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Raising the anchor\");\n\t\t\tfor (int iz = 0; iz < 5; iz++) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel, zanchor+iz*30, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Zanchor:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\tzanchor+iz*30, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle<CircleMarkPlot>().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor zanchor.png\"), scatter.GetImage());\n\t\t}\n\t}\n}", "meta": {"hexsha": "49e85e940268d9893094f379602a752606abc264", "size": 5688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_stars_repo_name": "anboto/Anboto", "max_stars_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:40:45.000Z", "max_issues_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_issues_repo_name": "anboto/Anboto", "max_issues_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T10:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:50:32.000Z", "max_forks_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_forks_repo_name": "anboto/Anboto", "max_forks_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T09:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:15:18.000Z", "avg_line_length": 45.504, "max_line_length": 157, "alphanum_fraction": 0.6965541491, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6575509494838334}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/pi.hpp>\n#include <fcppt/math/matrix/componentwise_equal.hpp>\n#include <fcppt/math/matrix/identity.hpp>\n#include <fcppt/math/matrix/output.hpp>\n#include <fcppt/math/matrix/rotation_axis.hpp>\n#include <fcppt/math/matrix/rotation_x.hpp>\n#include <fcppt/math/matrix/rotation_y.hpp>\n#include <fcppt/math/matrix/rotation_z.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/math/matrix/vector.hpp>\n#include <fcppt/math/vector/componentwise_equal.hpp>\n#include <fcppt/math/vector/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace\n{\n\nfloat const epsilon{\n\t0.001f\n};\n\ntemplate<\n\ttypename Matrix\n>\nbool\ncompare_matrices(\n\tMatrix const &_m1,\n\tMatrix const &_m2\n)\n{\n\treturn\n\t\tfcppt::math::matrix::componentwise_equal(\n\t\t\t_m1,\n\t\t\t_m2,\n\t\t\tepsilon\n\t\t);\n}\n\n}\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_rotation_axis\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tfloat,\n\t\t4,\n\t\t4\n\t>\n\tmatrix_type;\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tfloat,\n\t\t3\n\t>\n\tvector_rotation_type;\n\n\tmatrix_type const trans(\n\t\tfcppt::math::matrix::rotation_axis(\n\t\t\tfcppt::math::pi<\n\t\t\t\tfloat\n\t\t\t>(),\n\t\t\tvector_rotation_type(\n\t\t\t\t1.f,\n\t\t\t\t0.f,\n\t\t\t\t0.f\n\t\t\t)\n\t\t)\n\t);\n\n\ttypedef\n\tfcppt::math::vector::static_<\n\t\tfloat,\n\t\t4\n\t>\n\tvector_type;\n\n\tvector_type const vec(\n\t\t0.f,\n\t\t1.f,\n\t\t0.f,\n\t\t1.f\n\t);\n\n\tBOOST_CHECK(\n\t\tfcppt::math::vector::componentwise_equal(\n\t\t\ttrans\n\t\t\t*\n\t\t\tvec,\n\t\t\tvector_type(\n\t\t\t\t0.f,\n\t\t\t\t-1.f,\n\t\t\t\t0.f,\n\t\t\t\t1.f\n\t\t\t),\n\t\t\tepsilon\n\t\t)\n\t);\n\n\tBOOST_CHECK((\n\t\t::compare_matrices(\n\t\t\tfcppt::math::matrix::rotation_axis(\n\t\t\t\t0.0f,\n\t\t\t\tvector_rotation_type(\n\t\t\t\t\t0.f,\n\t\t\t\t\t0.f,\n\t\t\t\t\t0.f\n\t\t\t\t)\n\t\t\t),\n\t\t\tfcppt::math::matrix::identity<\n\t\t\t\tmatrix_type\n\t\t\t>()\n\t\t)\n\t));\n\n\tfloat const angle{\n\t\tfcppt::math::pi<\n\t\t\tfloat\n\t\t>()\n\t\t/\n\t\t2.f\n\t};\n\n\tBOOST_CHECK((\n\t\t::compare_matrices(\n\t\t\tfcppt::math::matrix::rotation_axis(\n\t\t\t\tangle,\n\t\t\t\tvector_rotation_type(\n\t\t\t\t\t1.0f,\n\t\t\t\t\t0.0f,\n\t\t\t\t\t0.0f\n\t\t\t\t)\n\t\t\t),\n\t\t\tfcppt::math::matrix::rotation_x(\n\t\t\t\tangle\n\t\t\t)\n\t\t)\n\t));\n\n\tBOOST_CHECK((\n\t\t::compare_matrices(\n\t\t\tfcppt::math::matrix::rotation_axis(\n\t\t\t\tangle,\n\t\t\t\tvector_rotation_type(\n\t\t\t\t\t0.0f,\n\t\t\t\t\t1.0f,\n\t\t\t\t\t0.0f\n\t\t\t\t)\n\t\t\t),\n\t\t\tfcppt::math::matrix::rotation_y(\n\t\t\t\tangle\n\t\t\t)\n\t\t)\n\t));\n\n\tBOOST_CHECK((\n\t\t::compare_matrices(\n\t\t\tfcppt::math::matrix::rotation_axis(\n\t\t\t\tangle,\n\t\t\t\tvector_rotation_type(\n\t\t\t\t\t0.0f,\n\t\t\t\t\t0.0f,\n\t\t\t\t\t1.0f\n\t\t\t\t)\n\t\t\t),\n\t\t\tfcppt::math::matrix::rotation_z(\n\t\t\t\tangle\n\t\t\t)\n\t\t)\n\t));\n}\n", "meta": {"hexsha": "09a9026f595ce79a63f3cf6d9c77fe01d346c88c", "size": 2927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/rotation_axis.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/rotation_axis.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/rotation_axis.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.3246073298, "max_line_length": 61, "alphanum_fraction": 0.650153741, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6575509330436963}}
{"text": "\ufeff\r\n#include <limbus/OpenglWindow.hpp>\r\n#include <limbus/Timer.hpp>\r\n#include <limbus/opengl.h>\r\n#include <pingo/SpriteBuffer.hpp>\r\n#include <pingo/Texture.hpp>\r\n\r\n#include <iostream>\r\n#include <complex>\r\n#include <cmath>\r\n#include <boost/thread.hpp>\r\n\r\nclass FractalRenderer\r\n{\r\npublic:\r\n\tstruct Color\r\n\t{\r\n\t\tColor() {}\r\n\t\tColor(double r, double g, double b) : r(r), g(g), b(b) {}\r\n\t\tdouble r, g, b;\r\n\r\n\t\tColor operator * (double factor)\r\n\t\t{\r\n\t\t\treturn Color(r*factor, g*factor, b*factor);\r\n\t\t}\r\n\r\n\t\tColor operator + (const Color& other)\r\n\t\t{\r\n\t\t\treturn Color(r + other.r, g + other.g, b + other.b);\r\n\t\t}\r\n\t};\r\n\r\n\tstruct Job\r\n\t{\r\n\t\tsize_t y_start;\r\n\t\tsize_t y_count;\r\n\t\tdouble scale;\r\n\t\tstd::complex<double> offset;\r\n\t};\r\n\r\n\tstatic const int max_iterations = 1000;\r\n\tstatic const int max_colors = 50;\r\n\r\n\tFractalRenderer(unsigned char* texture_data, Color* color_ramp, double texture_width, double texture_height)\r\n\t\t: texture_data(texture_data), color_ramp(color_ramp), texture_width(texture_width), texture_height(texture_height), job_done(false), running(true)\r\n\t{\r\n\t}\r\n\r\n\ttypedef boost::lock_guard<boost::mutex> lock_guard;\r\n\r\n\tvoid setJob(Job new_job)\r\n\t{\r\n\t\tcurrent_job = new_job;\r\n\t\tlock_guard lock(job_mutex);\r\n\t\tjob_done = false;\r\n\t}\r\n\r\n\tbool jobDone()\r\n\t{\r\n\t\tlock_guard lock(job_mutex);\r\n\t\treturn job_done;\r\n\t}\r\n\r\n\tvoid stop()\r\n\t{\r\n\t\tlock_guard lock(running_mutex);\r\n\t\trunning = false;\r\n\t}\r\n\r\n\tvoid operator () ()\r\n\t{\r\n\t\tbool _running;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\tbool done;\r\n\t\t\t{\r\n\t\t\t\tlock_guard lock(job_mutex);\r\n\t\t\t\tdone = job_done;\r\n\t\t\t}\r\n\r\n\t\t\tif (!done)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t _y = current_job.y_start; _y < current_job.y_start + current_job.y_count; ++_y)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t _x = 0; _x < (size_t)texture_width; ++_x)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::complex<double> c(((double)_x / texture_width) * 2.0 - 1.0,\r\n\t\t\t\t\t\t\t\t\t\t\t   ((double)_y / texture_height) * 2.0 - 1.0);\r\n\r\n\t\t\t\t\t\tc *= current_job.scale;\r\n\t\t\t\t\t\tc += current_job.offset;\r\n\r\n\t\t\t\t\t\tstd::complex<double> z(0.0, 0.0);\r\n\r\n\t\t\t\t\t\tdouble q = (z.real() - 1/4)*(z.real() - 1/4) + z.imag()*z.imag();\r\n\t\t\t\t\t\tbool inside_cardioid = q * (q + (z.real() - 1/4)) < (1/4)*z.imag()*z.imag();\r\n\t\t\t\t\t\tbool inside_period2_bulb = (z.real() + 1)*(z.real() + 1) + z.imag()*z.imag() < 1/16;\r\n\r\n\t\t\t\t\t\tsize_t i = 0;\r\n\t\t\t\t\t\tif (!inside_cardioid || !inside_period2_bulb)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\twhile (i < max_iterations && z.real()*z.real() + z.imag()*z.imag() < 2.0*2.0)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tz = z*z + c;\r\n\t\t\t\t\t\t\t\ti += 1;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ti = max_iterations;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (z.real()*z.real() + z.imag()*z.imag() < 2.0*2.0 || i == max_iterations)\r\n\t\t\t\t\t\t\tWritePixel(_x, _y, -1, 0, 0.0);\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble s = i + (log(log((double)max_iterations)) - log(log(abs(z))))/log(2.0);\r\n\r\n\t\t\t\t\t\t\tint first = (int)s;\r\n\t\t\t\t\t\t\tint second = first + 1;\r\n\t\t\t\t\t\t\tdouble factor = s - first;\r\n\t\t\t\t\t\t\tWritePixel(_x, _y, first, second, factor);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tlock_guard lock(job_mutex);\r\n\t\t\t\tjob_done = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tboost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(1));\r\n\t\t\t}\r\n\r\n\t\t\tlock_guard lock(running_mutex);\r\n\t\t\t_running = running;\r\n\t\t} while (_running);\r\n\t}\r\n\r\nprivate:\r\n\tFractalRenderer(FractalRenderer& other);\r\n\r\n\tJob current_job;\r\n\tbool job_done;\r\n\tbool running;\r\n\r\n\tboost::mutex job_mutex, running_mutex;\r\n\r\n\tdouble texture_width;\r\n\tdouble texture_height;\r\n\r\n\tunsigned char* texture_data;\r\n\tColor* color_ramp;\r\n\r\n\tvoid WritePixel(size_t x, size_t y, int first, int second, double factor)\r\n\t{\r\n\t\tsize_t offset = y * (size_t)texture_width + x;\r\n\t\t\r\n\t\tColor color;\r\n\t\tif (first == -1)\r\n\t\t\tcolor = Color(0, 0, 0);\r\n\t\telse\r\n\t\t\tcolor = color_ramp[second % (max_colors*2)] * factor + color_ramp[first % (max_colors*2)] * (1.0 - factor);\r\n\r\n\t\ttexture_data[offset * 3 + 0] = (unsigned char)(color.r * 255.0);\r\n\t\ttexture_data[offset * 3 + 1] = (unsigned char)(color.g * 255.0);\r\n\t\ttexture_data[offset * 3 + 2] = (unsigned char)(color.b * 255.0);\r\n\t}\r\n};\r\n\r\nclass Application : public Limbus::OpenglWindow::EventHandler\r\n{\r\n\tbool running;\r\n\r\n\tvoid onClose(Limbus::OpenglWindow& self)\r\n\t{\r\n\t\trunning = false;\r\n\t}\r\n\r\n\tLimbus::OpenglWindow window;\r\n\tPingo::SpriteBuffer* sprite_buffer;\r\n\tPingo::Texture* texture;\r\n\tunsigned char* texture_data;\r\n\r\n\tFractalRenderer::Color color_ramp[FractalRenderer::max_colors*2];\r\n\r\npublic:\r\n\tvoid run()\r\n\t{\r\n\t\trunning = true;\r\n\t\twindow.setCaption(\"Fractal Demo\");\r\n\t\twindow.addEventHandler(this);\r\n\t\twindow.setWidth(256);\r\n\t\twindow.setHeight(256);\r\n\t\twindow.create();\r\n\r\n\t\tglClearColor( 0.0f, 0.0f, 0.0f, 0.0f );\r\n\t\tglDisable( GL_DEPTH_TEST );\r\n\t\tglEnable( GL_BLEND );\r\n\t\tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\r\n\t\tglEnable( GL_TEXTURE_2D );\r\n\r\n\t\tglMatrixMode( GL_PROJECTION );\r\n\t\tglLoadIdentity();\r\n\t\tglOrtho( 0.0f, window.getWidth(), window.getHeight(), 0.0f, -100.0f, 100.0f );\r\n\t\tglMatrixMode( GL_MODELVIEW );\r\n\t\tglLoadIdentity();\r\n\r\n\t\ttexture_data = new unsigned char[window.getWidth() * window.getHeight() * 3];\r\n\r\n\t\ttexture = new Pingo::Texture();\r\n\t\ttexture->loadFromMemory(texture_data, window.getWidth(), window.getHeight(), 3);\r\n\t\tsprite_buffer = new Pingo::SpriteBuffer(texture, 1, true);\r\n\t\t\r\n\t\tsprite_buffer->setWritable(true);\r\n\t\tsprite_buffer->setRectangle(0, 0.0f, 0.0f, (float)window.getWidth(), (float)window.getHeight());\r\n\t\tsprite_buffer->setColor(0, 1.0f, 1.0f, 1.0f, 1.0f);\r\n\t\tsprite_buffer->setTextureRectangle(0, 0.0f, 0.0f, (float)window.getWidth(), (float)window.getHeight());\r\n\t\tsprite_buffer->setWritable(false);\r\n\r\n\t\tfor (size_t i = 0; i < FractalRenderer::max_colors; ++i)\r\n\t\t{\r\n\t\t\tfloat factor = (float)i / FractalRenderer::max_colors;\r\n\t\t\tfloat inverse_factor = (float)(FractalRenderer::max_colors - i) / FractalRenderer::max_colors;\r\n\r\n\t\t\tcolor_ramp[i] = FractalRenderer::Color(sqrt(sqrt(factor)), factor, inverse_factor * 0.5f);\r\n\t\t\tcolor_ramp[FractalRenderer::max_colors*2 - 1 - i] = color_ramp[i];\r\n\t\t}\r\n\r\n\t\tFractalRenderer worker(texture_data, color_ramp, (double)window.getWidth(), (double)window.getHeight());\r\n\t\tFractalRenderer worker2(texture_data, color_ramp, (double)window.getWidth(), (double)window.getHeight());\r\n\t\t\r\n\t\tFractalRenderer::Job job;\r\n\t\tjob.offset = std::complex<double>(+0.001643721971153, +0.822467633298876);\r\n\t\tjob.scale = 2.0;\r\n\t\tjob.y_start = 0;\r\n\t\tjob.y_count = window.getHeight() / 2;\r\n\r\n\t\tFractalRenderer::Job job2;\r\n\t\tjob2.offset = std::complex<double>(+0.001643721971153, +0.822467633298876);\r\n\t\tjob2.scale = 2.0;\r\n\t\tjob2.y_start = window.getHeight() / 2;\r\n\t\tjob2.y_count = window.getHeight() - job2.y_start;\r\n\t\t\r\n\t\tworker.setJob(job);\r\n\t\tworker2.setJob(job2);\r\n\t\t\r\n\t\tboost::thread worker_thread(boost::ref(worker));\r\n\t\tboost::thread worker_thread2(boost::ref(worker2));\r\n\r\n\t\tLimbus::Timer timer;\r\n\t\twhile (running)\r\n\t\t{\r\n\t\t\twindow.pollEvents();\r\n\t\t\tdouble elapsed = 1.0f + timer.getElapsed() * 0.005;\r\n\t\t\t\r\n\t\t\tif (worker.jobDone() && worker2.jobDone())\r\n\t\t\t{\r\n\t\t\t\ttexture->update(texture_data);\r\n\r\n\t\t\t\tjob.scale = 1.0 / (elapsed * (1.0 / job.scale));\r\n\t\t\t\tif (job.scale < 0.00000000001)\r\n\t\t\t\t\tjob.scale = 0.00000000001;\r\n\t\t\t\tworker.setJob(job);\r\n\r\n\t\t\t\tjob2.scale = job.scale;\r\n\t\t\t\tworker2.setJob(job2);\r\n\t\t\t}\r\n\r\n\t\t\tsprite_buffer->draw(0, 1, 0, 0);\r\n\t\t\twindow.swapBuffers();\r\n\t\t}\r\n\r\n\t\tworker.stop();\r\n\t\tworker2.stop();\r\n\t\tworker_thread.join();\r\n\t\tworker_thread2.join();\r\n\r\n\t\tdelete sprite_buffer;\r\n\t\tdelete texture;\r\n\t\tdelete [] texture_data;\r\n\t}\r\n};\r\n\r\nvoid main()\r\n{\r\n\tApplication app;\r\n\tapp.run();\r\n}\r\n", "meta": {"hexsha": "b93558489a6ae07eb30a62b1656ffe7bbadd1e22", "size": 7447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/main.cpp", "max_stars_repo_name": "redien/mandelbrot", "max_stars_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T02:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-04T02:29:50.000Z", "max_issues_repo_path": "source/main.cpp", "max_issues_repo_name": "redien/mandelbrot", "max_issues_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "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": "source/main.cpp", "max_forks_repo_name": "redien/mandelbrot", "max_forks_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "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.5910652921, "max_line_length": 149, "alphanum_fraction": 0.6240096683, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6575183191601658}}
{"text": "/*\n* compile with flags:   g++ test.cc softmax_classifier.cc   ../datasets/datasets.cc -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.3.29 10:55\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <logistic/logistic_classifier.h>\n#include <logistic/softmax_classifier.h>\n#include <datasets/datasets.h>\n\nusing namespace std;\nusing namespace arma;\n\n\n\nint main() {\n    Datasets dataset = Datasets(\"iris\");\n\n    // Logistic classifier testing\n    // vec y = dataset.y.subvec(0, 99);\n    // mat x = dataset.x.submat(0, 0, 3, 99);\n    // Logisitic_Classifier lr_classifier = Logisitic_Classifier();\n    // lr_classifier.train(x, y);\n    // vec res = lr_classifier.predict(mat({{6.1, 2.9, 4.7, 1.4}, {5.1, 3.5, 1.4, 0.2}}).t());\n    // res.print();\n\n\n    // softmax classifier test (for multiple classies)\n    Softmax_Classifier softmax_classifier = Softmax_Classifier();\n    softmax_classifier.train(dataset.x, dataset.y, 3);\n    vec res = softmax_classifier.predict(dataset.x);\n    // vec res = softmax_classifier.predict(mat({{6.1, 2.9, 4.7, 1.4}, {5.1, 3.5, 1.4, 0.2}, {6.1, 2.6, 5.6, 1.4}}).t());\n    res.print();\n    return 0;\n}\n\n", "meta": {"hexsha": "533bdf8145e8ced29ef785069eb92696e69034fa", "size": 1176, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/logistic_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/logistic_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/logistic_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 29.4, "max_line_length": 124, "alphanum_fraction": 0.6488095238, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6575183163049446}}
{"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_INTERNAL_HPP\n#define POLYNOMIAL_INTERNAL_HPP\n\n#include <Eigen/Core>\n#include <vector>\n#include <queue>\n\nnamespace polynomial\n{\n    namespace Internal\n    {\n        \n        template<int a,int b> struct max{ static const int value=(a<b)?b:a; };\n        template<int a,int b> struct min{ static const int value=(a>b)?b:a; };\n        \n        template <int length>\n        inline\n        Eigen::Map< Eigen::Matrix<double,1,length> > vecmap(double *data)\n        {\n            return Eigen::Map< Eigen::Matrix<double,1,length> >(data);\n        }\n        \n        template <int length>\n        inline\n        Eigen::Map< const Eigen::Matrix<double,1,length> > vecmap(const double *data)\n        {\n            return Eigen::Map< const Eigen::Matrix<double,1,length> >(data);\n        }\n        \n        template <int deg1,int deg2,int k>\n        struct\n        _PolyConv\n        {\n            static void\n            compute( double *coefout, const double *coef1, const double *coef2 )\n            {\n                coefout[k] =\n                (\n                 vecmap<min<k,deg1>::value-max<0,k-deg2>::value+1>\n                 (\n                  coef1+max<0,k-deg2>::value\n                  )\n                 .array()\n                 *\n                 vecmap<min<k,deg1>::value-max<0,k-deg2>::value+1>\n                 (\n                  coef2+k-min<k,deg1>::value\n                  ).reverse().array()\n                 ).sum();\n                _PolyConv<deg1,deg2,k-1>::compute( coefout, coef1, coef2 );\n            }\n        };\n        \n        template <int deg1,int deg2>\n        struct\n        _PolyConv<deg1,deg2,-1>\n        {\n            static void\n            compute( double *coefout, const double *coef1, const double *coef2 )\n            {\n            }\n        };\n        \n        template <int deg1,int deg2>\n        struct\n        PolyConv\n        {\n            static void\n            compute( Eigen::Matrix<double,deg1+deg2+1,1> &coefout, const Eigen::Matrix<double,deg1+1,1> &coef1, const Eigen::Matrix<double,deg2+1,1> &coef2 )\n            {\n                _PolyConv<deg1,deg2,deg1+deg2>::compute(coefout.data(),coef1.data(),coef2.data());\n            }\n        };\n\n        template <>\n        struct\n        PolyConv<Eigen::Dynamic,Eigen::Dynamic>\n        {\n            static void\n            compute( Eigen::VectorXd &coefout, const Eigen::VectorXd &coef1, const Eigen::VectorXd &coef2 )\n            {\n                int deg1 = coef1.rows()-1;\n                int deg2 = coef2.rows()-1;\n                \n                for ( int k = deg1+deg2; k >= 0; k-- )\n                {\n                    coefout[k] =\n                    (\n                     coef1.block(\n                                 std::max(0,k-deg2),0,\n                                 std::min(k,deg1)-std::max(0,k-deg2)+1,1\n                                 ).array()\n                     *\n                     coef2.block(\n                                 k-std::min(k,deg1),0,\n                                 std::min(k,deg1)-std::max(0,k-deg2)+1,1\n                                 ).reverse().array()\n                     ).sum();\n                }\n            }\n        };\n\n        template<int deg,int k>\n        struct\n        _PolyVal\n        {\n            static double\n            compute( const Eigen::Matrix<double,deg+1,1> &coef, const double &x )\n            {\n                return coef[k] + x*_PolyVal<deg,k-1>::compute(coef,x);\n            }\n        };\n        \n        template<int deg>\n        struct\n        _PolyVal<deg,0>\n        {\n            static double\n            compute( const Eigen::Matrix<double,deg+1,1> &coef, const double &x )\n            {\n                return coef[0];\n            }\n        };\n        \n        template<int deg>\n        struct\n        PolyVal\n        {\n            static double\n            compute( const Eigen::Matrix<double,deg+1,1> &coef, const double &x )\n            {\n                return Internal::_PolyVal<deg,deg>::compute( coef, x );\n            }\n        };\n\n        template<>\n        struct\n        PolyVal<Eigen::Dynamic>\n        {\n            static double\n            compute( const Eigen::VectorXd &coef, const double &x )\n            {\n                int deg = coef.rows()-1;\n                double val = 0;\n                for ( int i = 0; i <= deg; i++ ) val = coef(i) + x*val;\n                return val;\n            }\n        };\n\n        template<int deg>\n        struct BisectionMethod\n        {\n            static double compute(const Eigen::Matrix<double,deg+1,1> &coef, const double lower, const double upper )\n            {\n                double a = lower;\n                double fa = PolyVal<deg>::compute(coef,a);\n                char fapos = (fa>0);\n                double b = upper;\n                double c = 0.5*(a+b);\n                \n                for ( int i = 0; i < 24; i++ )\n                {\n                    const double fc = PolyVal<deg>::compute(coef,c);\n                    const char fcpos = (fc>0);\n                    if ( fcpos == fapos )\n                    {\n                        a = c;\n                        fa = fc;\n                    } else {\n                        b = c;\n                    }\n                    c = 0.5*(a+b);\n                }\n                \n                return c;\n            }\n        };\n\n        template<>\n        struct BisectionMethod<Eigen::Dynamic>\n        {\n            static double compute(const Eigen::VectorXd &coef, const double lower, const double upper )\n            {\n                double a = lower;\n                double fa = PolyVal<Eigen::Dynamic>::compute(coef,a);\n                char fapos = (fa>0);\n                double b = upper;\n                double c = 0.5*(a+b);\n                \n                for ( int i = 0; i < 100; i++ )\n                {\n                    const double fc = PolyVal<Eigen::Dynamic>::compute(coef,c);\n                    const char fcpos = (fc>0);\n                    if ( fcpos == fapos )\n                    {\n                        a = c;\n                        fa = fc;\n                    } else {\n                        b = c;\n                    }\n                    c = 0.5*(a+b);\n                }\n                \n                return c;\n            }\n        };\n        \n        template<int deg>\n        struct SturmChain\n        {\n            Eigen::Matrix<double,deg+1,1> coef;\n            SturmChain<deg-1> next;\n        };\n        \n        template<>\n        struct SturmChain<0>\n        {\n            Eigen::Matrix<double,1,1> coef;\n        };\n        \n        template<int degin,int degout,int k>\n        struct _GetSturmChain\n        {\n            static SturmChain<degout>& compute( SturmChain<degin> &sc )\n            {\n                return _GetSturmChain<degin-1,degout,k-1>::compute(sc.next);\n            }\n        };\n        \n        template<int degin,int degout>\n        struct _GetSturmChain<degin,degout,0>\n        {\n            static SturmChain<degout>& compute( SturmChain<degin> &sc )\n            {\n                return sc;\n            }\n        };\n        \n        template<int degin,int degout>\n        struct GetSturmChain\n        {\n            static SturmChain<degout>& compute( SturmChain<degin> &sc )\n            {\n                return _GetSturmChain<degin,degout,degin-degout>::compute(sc);\n            }\n        };\n        \n        template <int deg,int k>\n        struct _ModPoly\n        {\n            static const void compute( SturmChain<deg> &sc )\n            {\n                const Eigen::Matrix<double,k+3,1> &u( GetSturmChain<deg,k+2>::compute(sc).coef );\n                const Eigen::Matrix<double,k+2,1> &v( GetSturmChain<deg,k+1>::compute(sc).coef );\n                Eigen::Matrix<double,k+3,1> r = u;\n                const double s = v(0)/fabs(v(0));\n                r(k+2) *= s;\n                const int blocklength = k+1;\n                r.block(1,0,blocklength,1) = s * r.block(1,0,blocklength,1) - r(0) * v.block(1,0,blocklength,1);\n                r.block(2,0,blocklength,1) = s * r.block(2,0,blocklength,1) - r(1) * v.block(1,0,blocklength,1);\n                Eigen::Matrix<double,k+1,1> &rout( GetSturmChain<deg,k>::compute(sc).coef );\n                rout = r.block(2,0,k+1,1);\n                double f = -fabs(rout(0));\n                rout /= f;\n                _ModPoly<deg,k-1>::compute(sc);\n            }\n        };\n        \n        template <int deg>\n        struct _ModPoly<deg,0>\n        {\n            static const void compute( SturmChain<deg> &sc )\n            {\n                const Eigen::Matrix<double,3,1> &u( GetSturmChain<deg,2>::compute(sc).coef );\n                const Eigen::Matrix<double,2,1> &v( GetSturmChain<deg,1>::compute(sc).coef );\n                Eigen::Matrix<double,3,1> r = u;\n                const double s = v(0)/fabs(v(0));\n                r(2) *= s;\n                r(1) = s * r(1) - r(0) * v(1);\n                r(2) = s * r(2) - r(1) * v(1);\n                GetSturmChain<deg,0>::compute(sc).coef[0] = -r(2);\n            }\n        };\n        \n        template <int deg>\n        struct ModPoly\n        {\n            static const void compute( SturmChain<deg> &sc )\n            {\n                _ModPoly<deg,deg-2>::compute(sc);\n            }\n        };\n        \n        template <int deg>\n        struct _SignChanges\n        {\n            static const void compute( SturmChain<deg> &sc, const double x, const double lf, int &count )\n            {\n                double f = PolyVal<deg>::compute( sc.coef, x );\n                count += (f*lf<0);\n                _SignChanges<deg-1>::compute( sc.next, x, f, count );\n            }\n        };\n        \n        template <>\n        struct _SignChanges<0>\n        {\n            static const void compute( SturmChain<0> &sc, const double x, const double lf, int &count )\n            {\n                double f = sc.coef[0];\n                count += (f*lf<0);\n            }\n        };\n        \n        template <int deg>\n        struct SignChanges\n        {\n            static const void compute( SturmChain<deg> &sc, const double x, int &count )\n            {\n                double f = PolyVal<deg>::compute( sc.coef, x );\n                count = 0;\n                _SignChanges<deg-1>::compute( sc.next, x, f, count );\n            }\n        };\n        \n        template <>\n        struct SignChanges<0>\n        {\n            static const void compute( SturmChain<0> &sc, const double x, int &count )\n            {\n                count = 0;\n            }\n        };\n        \n        struct SturmInterval\n        {\n            double lb, ub;\n            int sclb, scub;\n            SturmInterval(const double _lb, const double _ub, const int _sclb, const int _scub)\n            : lb(_lb), ub(_ub), sclb(_sclb), scub(_scub) { }\n        };\n        \n        struct RootInterval\n        {\n            double lb, ub;\n            RootInterval(const double _lb, const double _ub)\n            : lb(_lb), ub(_ub) { }\n        };\n        \n        template<int deg>\n        class SturmRootFinder\n        {\n            void bisection(const double lb, const double ub, std::vector<double> &roots)\n            {\n                int sclb = 0;\n                int scub = 0;\n                SignChanges<deg>::compute(sc,lb,sclb);\n                SignChanges<deg>::compute(sc,ub,scub);\n                std::queue<SturmInterval> intervals;\n                intervals.push( SturmInterval(lb,ub,sclb,scub) );\n                \n                std::vector<RootInterval> root_intervals;\n                \n                while ( !intervals.empty() )\n                {\n                    SturmInterval interval = intervals.front();\n                    intervals.pop();\n                    \n                    // get num roots in interval\n                    int n = interval.sclb-interval.scub;\n                    \n                    if ( n == 0 )\n                    {\n                        \n                    }\n                    else if ( n == 1 )\n                    {\n                        root_intervals.push_back( RootInterval(interval.lb,interval.ub) );\n                    }\n                    else if ( fabs(interval.ub-interval.lb)>1e-15 )\n                    {\n                        double m = (interval.lb+interval.ub)*0.5;\n                        \n                        // get sign changes at m\n                        int scm = 0;\n                        SignChanges<deg>::compute(sc,m,scm);\n                        \n                        // add [lb,m] interval\n                        intervals.push( SturmInterval(interval.lb,m,interval.sclb,scm) );\n                        \n                        // add [m,ub] interval\n                        intervals.push( SturmInterval(m,interval.ub,scm,interval.scub) );\n                    }\n                }\n                \n                roots.resize(root_intervals.size());\n                for ( int i = 0; i < root_intervals.size(); i++ )\n                {\n                    roots[i] = BisectionMethod<deg>::compute(sc.coef,root_intervals[i].lb,root_intervals[i].ub);\n                }\n            }\n        public:\n            SturmChain<deg> sc;\n            \n            SturmRootFinder( const Eigen::Matrix<double,deg+1,1> &coef )\n            {\n                sc.coef = coef;\n                sc.next.coef = coef.head(deg);\n                double f = fabs(sc.coef[0] * deg);\n                for ( int i = 0; i < deg; i++ ) sc.next.coef[i] *= (deg-i)/f;\n                ModPoly<deg>::compute(sc);\n            }\n            \n            void realRoots(const double lb, const double ub, std::vector<double> &roots)\n            {\n                bisection(lb,ub,roots);\n            }\n        };\n\n        template<>\n        class SturmRootFinder<Eigen::Dynamic>\n        {\n            std::vector<Eigen::VectorXd> sc;\n\n            Eigen::VectorXd modpoly( const Eigen::VectorXd &u, const Eigen::VectorXd &v )\n            {\n                int udeg = u.rows()-1;\n                Eigen::VectorXd r = u;\n                double s = v(0)/fabs(v(0));\n                r(udeg) *= s;\n                int blocklength = udeg-1;\n                r.block(1,0,blocklength,1) = s * r.block(1,0,blocklength,1) - r(0) * v.block(1,0,blocklength,1);\n                r.block(2,0,blocklength,1) = s * r.block(2,0,blocklength,1) - r(1) * v.block(1,0,blocklength,1);\n                return r.block(2,0,blocklength,1);\n            }\n            \n            int signchanges(double x)\n            {\n                int deg = sc[0].rows()-1;\n                Eigen::VectorXd f(deg+1);\n                for ( int i = 0; i < deg+1; i++ ) f[i] = PolyVal<Eigen::Dynamic>::compute(sc[i],x);\n                int n = 0;\n                // NB: not skipping zeros here\n                for ( int i = 1; i < deg+1; i++ ) n += (f[i]*f[i-1]<0);\n                return n;\n            }\n            \n            void bisection(const double lb, const double ub, std::vector<double> &roots)\n            {\n                int sclb = signchanges(lb);\n                int scub = signchanges(ub);\n                std::queue<SturmInterval> intervals;\n                intervals.push( SturmInterval(lb,ub,sclb,scub) );\n                \n                std::vector<RootInterval> root_intervals;\n                \n                while ( !intervals.empty() )\n                {\n                    SturmInterval interval = intervals.front();\n                    intervals.pop();\n                    \n                    // get num roots in interval\n                    int n = interval.sclb-interval.scub;\n                    \n                    if ( n == 0 )\n                    {\n                        \n                    }\n                    else if ( n == 1 )\n                    {\n                        root_intervals.push_back( RootInterval(interval.lb,interval.ub) );\n                    }\n                    else if ( fabs(interval.ub-interval.lb)>1e-15 )\n                    {\n                        double m = (interval.lb+interval.ub)*0.5;\n                        \n                        // get sign changes at m\n                        int scm = signchanges(m);\n                        \n                        // add [lb,m] interval\n                        intervals.push( SturmInterval(interval.lb,m,interval.sclb,scm) );\n                        \n                        // add [m,ub] interval\n                        intervals.push( SturmInterval(m,interval.ub,scm,interval.scub) );\n                    }\n                }\n                \n                roots.resize(root_intervals.size());\n                for ( int i = 0; i < root_intervals.size(); i++ )\n                {\n                    roots[i] = BisectionMethod<Eigen::Dynamic>::compute(sc[0],root_intervals[i].lb,root_intervals[i].ub);\n                }\n            }\n        public:\n            SturmRootFinder( const Eigen::VectorXd &coef )\n            {\n                int deg = coef.rows()-1;\n                sc.resize(deg+1);\n                \n                sc[0] = coef;\n                \n                double f = fabs(sc[0](0) * deg);\n                sc[1] = sc[0].block(0,0,deg,1);\n                for ( int i = 0; i < deg; i++ ) sc[1][i] *= (deg-i)/f;\n                \n                for ( int i = 2; i < deg+1; i++ )\n                {\n                    sc[i] = modpoly(sc[i-2],sc[i-1]);\n                    if ( i != deg )\n                    {\n                        double f = -fabs(sc[i](0));\n                        sc[i] /= f;\n                    }\n                    else\n                    {\n                        sc[i] = -sc[i];\n                    }\n                }\n            }\n            \n            void realRoots(const double lb, const double ub, std::vector<double> &roots)\n            {\n                bisection(lb,ub,roots);\n            }\n        };\n\n        template<int deg>\n        struct RootFinder\n        {\n            static void compute( const Eigen::Matrix<double,deg+1,1> &p, std::vector<double> &roots )\n            {\n                Eigen::PolynomialSolver<double,deg> ps;\n                ps.compute(p.reverse());\n                ps.realRoots(roots);\n            }\n        };\n\n        template<>\n        struct RootFinder<Eigen::Dynamic>\n        {\n            static void compute( const Eigen::Matrix<double,Eigen::Dynamic,1> &p, std::vector<double> &roots )\n            {\n                Eigen::PolynomialSolver<double,Eigen::Dynamic> ps;\n                ps.compute(p.reverse());\n                ps.realRoots(roots);\n            }\n        };\n        \n        template<>\n        struct RootFinder<2>\n        {\n            static void compute( const Eigen::Matrix<double,3,1> &p, std::vector<double> &roots )\n            {\n                const double discrim = p[1]*p[1] - 4.*p[0]*p[2];\n                if ( discrim < 0 )\n                {\n                    roots.clear();\n                }\n                else if ( discrim == 0 )\n                {\n                    roots.resize(1);\n                    roots[0] = -p[1] / ( 2. * p[0] );\n                }\n                else\n                {\n                    const double twoa = 2. * p[0];\n                    const double sqrt_discrim = sqrt(discrim);\n                    roots.resize(2);\n                    roots[0] = (-p[1] + sqrt_discrim) / twoa;\n                    roots[1] = (-p[1] - sqrt_discrim) / twoa;\n                }\n            }\n        };\n\n    } // end namespace Internal\n    \n} // end namespace Polynomial\n\n#endif\n", "meta": {"hexsha": "7449519270c59563830c678816560870ca79ad8b", "size": 20850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Polynomial/PolynomialInternal.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/PolynomialInternal.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/PolynomialInternal.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": 35.1602023609, "max_line_length": 758, "alphanum_fraction": 0.4289208633, "num_tokens": 4743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.657442693836752}}
{"text": "#include <iostream>\n#include <boost/dynamic_bitset.hpp>\n\n// Actually, you may replace dynamic bitset with anything else\n// like std::bitset or std::vector, I made my choice because of\n// this totally reliable (random link from google) research:\n// https://www.researchgate.net/publication/220803585_Performance_of_C_bit-vector_implementations\n\nstatic bool buildAtkinSieve(boost::dynamic_bitset<>& sieve) {\n\tif (&sieve == nullptr || sieve.size() < 2)\n\t\treturn false;\n\tint size = sieve.size() - 1;\n\tsieve[2] = true;\n\tsieve[3] = true;\n\tint n, x = 0, y;\n\tint sizeSqrt = sqrt(size);\n\tfor (int i = 1; i <= sizeSqrt; ++i) {\n\t\tx += (i << 1) - 1;\n\t\ty = 0;\n\t\tfor (int j = 1; j <= sizeSqrt; ++j) {\n\t\t\ty += (j << 1) - 1;\n\t\t\tn = (x << 2) + y;\n\t\t\tif ((n <= size) && (n % 12 == 1 || n % 12 == 5))\n\t\t\t\tsieve[n].flip();\n\t\t\tn -= x;\n\t\t\tif ((n <= size) && (n % 12 == 7))\n\t\t\t\tsieve[n].flip();\n\t\t\tn -= (y << 1);\n\t\t\tif ((i > j) && (n <= size) && (n % 12 == 11))\n\t\t\t\tsieve[n].flip();\n\t\t}\n\t}\n\tfor (int i = 5; i <= sizeSqrt; ++i) {\n\t\tif (sieve[i]) {\n\t\t\tn = i * i;\n\t\t\tfor (int j = n; j <= size; j += n)\n\t\t\t\tsieve[j] = false;\n\t\t}\n\t}\n\treturn true;\n}\n\nint main() {\n\tstd::cout << \"Enter the initial capacity of the sieve: \";\n\tint size;\n\tstd::cin >> size;\n\tboost::dynamic_bitset<> sieve(size + 1);\n\tif (!buildAtkinSieve(sieve)) {\n\t\tstd::cout << \"It's too small for me to work with, so I'm done\";\n\t\treturn 1;\n\t}\n\tint answer;\n\twhile (true) {\t// feel free to Alt + F4\n\t\tstd::cout << \"\\nEnter the number to check if it's prime: \";\n\t\tstd::cin >> answer;\n\t\tif (answer >= sieve.size() || answer < 1) {\n\t\t\tstd::cout << \"Wrong input\\n\";\n\t\t\tstd::cin.clear();\n\t\t\tstd::cin.ignore(INT_MAX, '\\n');\t\t// ignores current input just in case\n\t\t}\n\t\telse\n\t\t\tstd::cout << (sieve[answer] ? \"It's prime.\\n\" : \"It's not prime.\\n\");\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "efd64dfe58fd0bf9a9e4e363695fa9bde19c3c0d", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_stars_repo_name": "antessial/algorithms", "max_stars_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_issues_repo_name": "antessial/algorithms", "max_issues_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_forks_repo_name": "antessial/algorithms", "max_forks_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_forks_repo_licenses": ["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.1363636364, "max_line_length": 97, "alphanum_fraction": 0.5633724176, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6574363026698756}}
{"text": "\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <basalt/vi_estimator/marg_helper.h>\n\n#include \"gtest/gtest.h\"\n\nTEST(QRTestSuite, QRvsLLT) {\n  Eigen::MatrixXd J;\n  J.setRandom(10, 6);\n\n  Eigen::HouseholderQR<Eigen::MatrixXd> qr(J);\n  Eigen::MatrixXd R = qr.matrixQR().triangularView<Eigen::Upper>();\n  Eigen::MatrixXd LT = (J.transpose() * J).llt().matrixU();\n\n  std::cout << \"J\\n\" << J << \"\\ncol_norms: \" << J.colwise().norm() << std::endl;\n  std::cout << \"R\\n\" << R << \"\\ncol_norms: \" << R.colwise().norm() << std::endl;\n  std::cout << \"LT\\n\"\n            << LT << \"\\ncol_norms: \" << LT.colwise().norm() << std::endl;\n}\n\nTEST(QRTestSuite, QRvsLLTRankDef) {\n  Eigen::MatrixXd J;\n  J.setRandom(10, 6);\n\n  J.col(2) = J.col(4);\n\n  Eigen::HouseholderQR<Eigen::MatrixXd> qr(J);\n  Eigen::MatrixXd R = qr.matrixQR().triangularView<Eigen::Upper>();\n  Eigen::MatrixXd LT = (J.transpose() * J).llt().matrixU();\n\n  std::cout << \"J\\n\" << J << \"\\ncol_norms: \" << J.colwise().norm() << std::endl;\n  std::cout << \"R\\n\" << R << \"\\ncol_norms: \" << R.colwise().norm() << std::endl;\n  std::cout << \"LT\\n\"\n            << LT << \"\\ncol_norms: \" << LT.colwise().norm() << std::endl;\n}\n\n#ifdef BASALT_INSTANTIATIONS_DOUBLE\nTEST(QRTestSuite, RankDefLeastSquares) {\n  Eigen::MatrixXd J;\n  Eigen::VectorXd r;\n  J.setRandom(10, 6);\n  r.setRandom(10);\n\n  J.col(1) = J.col(4);\n\n  auto decomp = J.completeOrthogonalDecomposition();\n\n  Eigen::VectorXd original_solution = decomp.solve(r);\n\n  std::cout << \"full solution: \" << original_solution.transpose() << std::endl;\n  std::cout << \"Rank \" << decomp.rank() << std::endl;\n\n  std::cout << \"sol OR:\\t\" << original_solution.tail<4>().transpose()\n            << std::endl;\n\n  std::set<int> idx_to_marg = {0, 1};\n  std::set<int> idx_to_keep = {2, 3, 4, 5};\n\n  Eigen::VectorXd sol_sc, sol_sqrt_sc, sol_sqrt_sc2, sol_qr;\n\n  // sqrt SC version\n  {\n    Eigen::MatrixXd H = J.transpose() * J;\n    Eigen::VectorXd b = J.transpose() * r;\n\n    Eigen::MatrixXd marg_sqrt_H;\n    Eigen::VectorXd marg_sqrt_b;\n\n    basalt::MargHelper<double>::marginalizeHelperSqToSqrt(\n        H, b, idx_to_keep, idx_to_marg, marg_sqrt_H, marg_sqrt_b);\n\n    auto dec = marg_sqrt_H.completeOrthogonalDecomposition();\n\n    sol_sqrt_sc = dec.solve(marg_sqrt_b);\n    std::cout << \"sol SQ:\\t\" << sol_sqrt_sc.transpose() << std::endl;\n    std::cout << \"rank \" << dec.rank() << std::endl;\n\n    auto dec2 = (marg_sqrt_H.transpose() * marg_sqrt_H)\n                    .completeOrthogonalDecomposition();\n\n    sol_sqrt_sc2 = dec2.solve(marg_sqrt_H.transpose() * marg_sqrt_b);\n    std::cout << \"sol SH:\\t\" << sol_sqrt_sc2.transpose() << std::endl;\n    std::cout << \"rank \" << dec2.rank() << std::endl;\n  }\n\n  // SC version\n  {\n    Eigen::MatrixXd H = J.transpose() * J;\n    Eigen::VectorXd b = J.transpose() * r;\n\n    Eigen::MatrixXd marg_H;\n    Eigen::VectorXd marg_b;\n\n    basalt::MargHelper<double>::marginalizeHelperSqToSq(\n        H, b, idx_to_keep, idx_to_marg, marg_H, marg_b);\n\n    auto dec = marg_H.completeOrthogonalDecomposition();\n\n    sol_sc = dec.solve(marg_b);\n    std::cout << \"sol SC:\\t\" << sol_sc.transpose() << std::endl;\n    std::cout << \"rank \" << dec.rank() << std::endl;\n  }\n\n  // QR version\n  {\n    Eigen::MatrixXd J1 = J;\n    Eigen::VectorXd r1 = r;\n\n    Eigen::MatrixXd marg_sqrt_H;\n    Eigen::VectorXd marg_sqrt_b;\n\n    basalt::MargHelper<double>::marginalizeHelperSqrtToSqrt(\n        J1, r1, idx_to_keep, idx_to_marg, marg_sqrt_H, marg_sqrt_b);\n\n    auto dec = marg_sqrt_H.completeOrthogonalDecomposition();\n\n    sol_qr = dec.solve(marg_sqrt_b);\n    std::cout << \"sol QR:\\t\" << sol_qr.transpose() << std::endl;\n    std::cout << \"rank \" << dec.rank() << std::endl;\n  }\n\n  EXPECT_TRUE(sol_qr.isApprox(sol_sc));\n  EXPECT_TRUE(sol_qr.isApprox(sol_sqrt_sc2));\n}\n#endif\n", "meta": {"hexsha": "4df65cd13354d4a7d447f2eccbe624127870ece8", "size": 3773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/test_qr.cpp", "max_stars_repo_name": "kwang-12/basalt-mirror", "max_stars_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 445.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T01:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:54:45.000Z", "max_issues_repo_path": "test/src/test_qr.cpp", "max_issues_repo_name": "kwang-12/basalt-mirror", "max_issues_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/src/test_qr.cpp", "max_forks_repo_name": "kwang-12/basalt-mirror", "max_forks_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 162.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T09:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:35:39.000Z", "avg_line_length": 29.4765625, "max_line_length": 80, "alphanum_fraction": 0.6225815001, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039738, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6574181888540781}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2018-2019 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2019.\n// Modifications copyright (c) 2019, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/arithmetic/infinite_line_functions.hpp>\n#include <boost/geometry/geometries/infinite_line.hpp>\n#include <boost/geometry/algorithms/detail/make/make.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/io/wkt/wkt.hpp>\n\nnamespace\n{\n    // Boost.Test does not support BOOST_CHECK_CLOSE for integral types\n    template <typename T>\n    bool is_small(T const& value)\n    {\n        static long double const epsilon = 1.0e-5;\n        return bg::math::abs(value) < epsilon;\n    }\n}\n\ntemplate <typename T, typename C>\nvoid verify_point_on_line(bg::model::infinite_line<T> const& line,\n                          C const& x, C const& y)\n{\n    BOOST_CHECK_MESSAGE(is_small(line.a * x + line.b * y + line.c),\n                        \"Point is not located on the line\");\n}\n\ntemplate <typename T>\nvoid test_side_value()\n{\n    typedef bg::model::infinite_line<T> line_type;\n\n    // Horizontal line going right\n    line_type line = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n\n    // Point above (= on left side)\n    T d = bg::arithmetic::side_value(line, 5, 5);\n    BOOST_CHECK_MESSAGE(d > 0, \"point not on left side\");\n\n    // Point below (= on right side)\n    d = bg::arithmetic::side_value(line, 5, -5);\n    BOOST_CHECK_MESSAGE(d < 0, \"point not on right side\");\n\n    // Diagonal not through origin, from right (down) to left (up)\n    line = bg::detail::make::make_infinite_line<T>(5, 2, -7, 10);\n    d = bg::arithmetic::side_value(line, 5, 2);\n    BOOST_CHECK_MESSAGE(is_small(d), \"point not on line\");\n    d = bg::arithmetic::side_value(line, -7, 10);\n    BOOST_CHECK_MESSAGE(is_small(d), \"point not on line\");\n\n    // vector is (-12, 8), move (-3,2) on the line from (5,2)\n    d = bg::arithmetic::side_value(line, 2, 4);\n    BOOST_CHECK_MESSAGE(is_small(d), \"point not on line\");\n\n    // Go perpendicular (2,3) from (2,4) up, so right of the line (negative)\n    d = bg::arithmetic::side_value(line, 4, 7);\n    BOOST_CHECK_MESSAGE(d < 0, \"point not on right side\");\n\n    // Go perpendicular (2,3) from (2,4) down, so left of the line (positive)\n    d = bg::arithmetic::side_value(line, 0, 1);\n    BOOST_CHECK_MESSAGE(d > 0, \"point not on left side\");\n}\n\n\ntemplate <typename T>\nvoid test_get_intersection()\n{\n    typedef bg::model::infinite_line<T> line_type;\n\n    // Diagonal lines (first is same as in distance measure,\n    // second is perpendicular and used there for distance measures)\n    line_type p = bg::detail::make::make_infinite_line<T>(5, 2, -7, 10);\n    line_type q = bg::detail::make::make_infinite_line<T>(4, 7, 0, 1);\n\n    typedef bg::model::point<T, 2, bg::cs::cartesian> point_type;\n    point_type ip;\n    BOOST_CHECK(bg::arithmetic::intersection_point(p, q, ip));\n\n    BOOST_CHECK_MESSAGE(is_small(bg::get<0>(ip) - 2), \"x-coordinate wrong\");\n    BOOST_CHECK_MESSAGE(is_small(bg::get<1>(ip) - 4), \"y-coordinate wrong\");\n\n    verify_point_on_line(p, bg::get<0>(ip), bg::get<1>(ip));\n    verify_point_on_line(q, bg::get<0>(ip), bg::get<1>(ip));\n}\n\ntemplate <typename T>\nvoid test_same_direction()\n{\n    bg::model::infinite_line<T> p, q;\n\n    // Exactly opposite, diagonal\n    p = bg::detail::make::make_infinite_line<T>(2, 1, 12, 11);\n    q = bg::detail::make::make_infinite_line<T>(12, 11, 2, 1);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // Exactly opposite, horizontal\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n    q = bg::detail::make::make_infinite_line<T>(10, 0, 0, 0);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // Exactly opposite, vertical\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 10, 0, 0);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // Exactly equal, diagonal\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    BOOST_CHECK(bg::arithmetic::similar_direction(p, q));\n\n    // Exactly equal, horizontal\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n    BOOST_CHECK(bg::arithmetic::similar_direction(p, q));\n\n    // Exactly equal, vertical\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    BOOST_CHECK(bg::arithmetic::similar_direction(p, q));\n\n    // Coming together, diagonal\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(20, 20, 10, 10);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // Leaving from common point, diagonal\n    p = bg::detail::make::make_infinite_line<T>(10, 10, 0, 0);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // Continuing each other, diagonal\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(10, 10, 20, 20);\n    BOOST_CHECK(bg::arithmetic::similar_direction(p, q));\n\n    // (Nearly) perpendicular\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, -10, 10);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // 45 deg\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    BOOST_CHECK(bg::arithmetic::similar_direction(p, q));\n\n    // a bit more than 45 deg\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, -1, 10);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n\n    // 135 deg\n    p = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    q = bg::detail::make::make_infinite_line<T>(0, 0, -10, 0);\n    BOOST_CHECK(! bg::arithmetic::similar_direction(p, q));\n}\n\ntemplate <typename T>\nvoid test_degenerate()\n{\n    typedef bg::model::infinite_line<T> line_type;\n\n    line_type line = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n    BOOST_CHECK(! bg::arithmetic::is_degenerate(line));\n\n    line = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    BOOST_CHECK(! bg::arithmetic::is_degenerate(line));\n\n    line = bg::detail::make::make_infinite_line<T>(0, 0, 10, 10);\n    BOOST_CHECK(! bg::arithmetic::is_degenerate(line));\n\n    line = bg::detail::make::make_infinite_line<T>(0, 0, 0, 0);\n    BOOST_CHECK(bg::arithmetic::is_degenerate(line));\n}\n\n\ntemplate <typename T>\nvoid test_all()\n{\n    test_side_value<T>();\n    test_get_intersection<T>();\n    test_same_direction<T>();\n    test_degenerate<T>();\n}\n\nint test_main(int, char* [])\n{\n    test_all<double>();\n    test_all<long double>();\n    test_all<float>();\n    test_all<int>();\n    return 0;\n}\n", "meta": {"hexsha": "9c879178cc9fdb5af917de098fd2ca6a7ecaeb78", "size": 7372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/geometry/test/arithmetic/infinite_line_functions.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/geometry/test/arithmetic/infinite_line_functions.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/geometry/test/arithmetic/infinite_line_functions.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-27T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:24:22.000Z", "avg_line_length": 35.786407767, "max_line_length": 79, "alphanum_fraction": 0.6557243625, "num_tokens": 2253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6574057904576589}}
{"text": "#include <boost/geometry.hpp>\n#include <iostream>\n#include <vector>\n\nconst int dimension = 2;\nusing point = boost::geometry::model::point<int, dimension, boost::geometry::cs::cartesian>;\nusing box = boost::geometry::model::box<point>;\nusing boost::geometry::max_corner;\nusing boost::geometry::min_corner;\n\n\nbool difference_correct(const box& minuend, const box& subtrahend, const std::vector<box>& result) {\n\tbool valid = true;\n\tauto total_area = boost::geometry::area(minuend);\n\tbox intersection;\n\tboost::geometry::intersection(minuend,subtrahend,intersection);\n\ttotal_area -= boost::geometry::area(intersection);\n\tfor(int i=0;i<result.size();++i) {\n\t\tconst auto& r = result[i];\n\t\ttotal_area -= boost::geometry::area(r);\n\t\tvalid = valid && boost::geometry::within(r,minuend);\n\t\tboost::geometry::intersection(r,subtrahend,intersection);\n\t\tvalid = valid && (boost::geometry::area(intersection)==0);\n\t\tfor(int j=i+1;j<result.size();++j) {\n\t\t\tconst auto& r2 = result[j];\n\t\t\tboost::geometry::intersection(r,r2,intersection);\n\t\t\tvalid = valid && (boost::geometry::area(intersection)==0);\n\t\t}\n\t}\n\t\n\treturn valid && total_area == 0;\n}\n\nint main(int, char **)\n{\n\tstd::vector<box> result;\n\tbox a(point(0, 0), point(10, 10)), b(point(3, 3), point(7, 7));\n\tboost::geometry::difference(a,b,result);\n\tstd::cout << \"BOX(0 0, 10 10)\\\\BOX(3 3, 7 7)\\n\\n\";\n\tfor(const auto &r : result)\n\t{\n\t\tstd::cout << \"BOX( \" << boost::geometry::get<min_corner, 0>(r) << \" \" << boost::geometry::get<min_corner, 1>(r) << \" , \"\n\t\t\t<< boost::geometry::get<max_corner, 0>(r) << \" \" << boost::geometry::get<max_corner, 1>(r) << \" )\\n\";\n\t}\n\tstd::cout << \"correct? \" << (difference_correct(a,b,result)?\"yes\":\"no\") << \"\\n\";\n\treturn 0;\n}\n", "meta": {"hexsha": "08402b5e023befa3f6002e9bbdda79dcaa945922", "size": 1697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "tinko92/boost_geometry_difference_demo", "max_stars_repo_head_hexsha": "f650750bc2ea1235c1fa870200162839743d4b83", "max_stars_repo_licenses": ["MIT"], "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": "tinko92/boost_geometry_difference_demo", "max_issues_repo_head_hexsha": "f650750bc2ea1235c1fa870200162839743d4b83", "max_issues_repo_licenses": ["MIT"], "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": "tinko92/boost_geometry_difference_demo", "max_forks_repo_head_hexsha": "f650750bc2ea1235c1fa870200162839743d4b83", "max_forks_repo_licenses": ["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.3541666667, "max_line_length": 122, "alphanum_fraction": 0.6564525633, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6573170786814998}}
{"text": "/*\n * Copyright (c) 2014-2015 Kartik Kumar, Dinamica Srl\n * Copyright (c) 2014-2015 Marko Jankovic, DFKI GmbH\n * Copyright (c) 2014-2015 Natalia Ortiz, University of Southampton\n * Copyright (c) 2014-2015 Juan Romero, University of Strathclyde\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n#include <cmath>\n#include <vector>\n\n#include <catch.hpp>\n\n#include <Eigen/Core>\n\n#include \"astro/centralBodyAccelerationModel.hpp\"\n\nnamespace astro\n{\nnamespace tests\n{\n\ntypedef double Real;\ntypedef Eigen::Matrix< Real, Eigen::Dynamic, 1> Vector;\n\nTEST_CASE( \"Compute acceleration vector for a GEO spacecraft using a custom made MATLAB script\",\n           \"[central_gravity, acceleration, models]\" )\n{\n    // Benchmark values for test case obtained using custom MATLAB script: https://goo.gl/8BQztN\n\n    // Set expected acceleration vector [km s^-2].\n    Vector expectedAcceleration( 3 );\n    expectedAcceleration[ 0 ] = -2.242096133923724e-4;\n    expectedAcceleration[ 1 ] =  0.0;\n    expectedAcceleration[ 2 ] =  0.0;\n\n     // Set tolerance = error between expected value and computed value.\n    const Real tolerance = 1.0e-15;\n\n    // Set value of gravitational parameter of central body [km^3 s^-2].\n    // In this case the used value is that of the planet Earth (Wertz, 1999; page 132).\n    const Real gravitationalParameter = 3.986005e5;\n\n    // Set position vector of the spacecraft relative to the origin of the reference frame [km].\n    // In the following example the Earth-fixed reference frame is used ((Wertz, 1999; page 96).\n    // Moreover, the spacecraft is assumed to be in positioned in Geostationary Orbit\n    // (GEO) and on the Greenwich Meridian.\n    Vector positionVector( 3 );\n    positionVector[ 0 ] = 4.2164e4;\n    positionVector[ 1 ] = 0.0;\n    positionVector[ 2 ] = 0.0;\n\n    // Compute the acceleration vector [km s^-2].\n    const Vector computedAcceleration = computeCentralBodyAcceleration( gravitationalParameter,\n                                                                        positionVector );\n\n    // Check if computed acceleration matches expected values.\n    REQUIRE( computedAcceleration[ 0 ]\n             == Approx( expectedAcceleration[ 0 ] ).epsilon( tolerance ) );\n    REQUIRE( computedAcceleration[ 1 ]\n             == Approx( expectedAcceleration[ 1 ] ).epsilon( tolerance ) );\n    REQUIRE( computedAcceleration[ 2 ]\n             == Approx( expectedAcceleration[ 2 ] ).epsilon( tolerance ) );\n}\n\nTEST_CASE( \"Compute acceleration vector for arbitrary case using Tudat library values\",\n           \"[central_gravity, acceleration, models]\" )\n{\n    // Test case computed using the data of the Tudat library calculated using the planet Mercury as\n    // a central body. More info can be found at the following link: http://goo.gl/MyXBJE.\n\n    // Set expected acceleration vector [m s^-2].\n    Vector expectedAcceleration( 3 );\n    expectedAcceleration[ 0 ] = -6.174552714649318e-2;\n    expectedAcceleration[ 1 ] =  3.024510782481964e-1;\n    expectedAcceleration[ 2 ] = -1.228994266291893e-1;\n\n     // Set tolerance = error between expected value and computed value.\n    const Real tolerance = 1.0e-15;\n\n    // Set value of gravitational parameter of central body [m^3 s^-2].\n    const Real gravitationalParameter = 2.2032e13;\n\n    // Set position vector of the body relative to the origin of the reference frame [m].\n    Vector positionVector( 3 );\n    positionVector[ 0 ] =  1513.3e3;\n    positionVector[ 1 ] = -7412.67e3;\n    positionVector[ 2 ] =  3012.1e3;\n\n    // Compute the acceleration vector [m s^-2].\n    const Vector computedAcceleration = computeCentralBodyAcceleration( gravitationalParameter,\n                                                                        positionVector);\n\n    // Check if computed acceleration matches expected values.\n    REQUIRE( computedAcceleration[ 0 ]\n             == Approx( expectedAcceleration[ 0 ] ).epsilon( tolerance ) );\n    REQUIRE( computedAcceleration[ 1 ]\n             == Approx( expectedAcceleration[ 1 ] ).epsilon( tolerance ) );\n    REQUIRE( computedAcceleration[ 2 ]\n             == Approx( expectedAcceleration[ 2 ] ).epsilon( tolerance ) );\n}\n\n} // namespace tests\n} // namespace astro\n\n/*\n * Wertz, J.R. & Larson, W.J., Space mission analysis and design, Springer Netherlands\n */\n", "meta": {"hexsha": "820db6d8b03f93d72208fbc3868bc1c73e725378", "size": 4360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/testCentralBodyAccelerationModelEigen.cpp", "max_stars_repo_name": "srikarad07/astro", "max_stars_repo_head_hexsha": "e7beea121e26780ba3dcbde058271ffe03699d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/testCentralBodyAccelerationModelEigen.cpp", "max_issues_repo_name": "srikarad07/astro", "max_issues_repo_head_hexsha": "e7beea121e26780ba3dcbde058271ffe03699d76", "max_issues_repo_licenses": ["MIT"], "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/testCentralBodyAccelerationModelEigen.cpp", "max_forks_repo_name": "srikarad07/astro", "max_forks_repo_head_hexsha": "e7beea121e26780ba3dcbde058271ffe03699d76", "max_forks_repo_licenses": ["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.6363636364, "max_line_length": 100, "alphanum_fraction": 0.6740825688, "num_tokens": 1052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6573170687388272}}
{"text": "#include \"basic_functions.h\"\n#include \"mlfe/device_context/cpu_context.h\"\n#include <Eigen/Dense>\n\nnamespace mlfe{ namespace math{\n\ntemplate <>\nvoid squared_difference<float, CPUContext>(const int size,\n                                           const float *x1_ptr,\n                                           const float *x2_ptr,\n                                           float *y_ptr){\n    for(int n = 0; n < size; ++n){\n        y_ptr[n] = std::pow(x1_ptr[n] - x2_ptr[n], 2);\n    }\n}\n\ntemplate <>\nvoid squared_difference<double, CPUContext>(const int size,\n                                            const double *x1_ptr,\n                                            const double *x2_ptr,\n                                            double *y_ptr){\n    for(int n = 0; n < size; ++n){\n        y_ptr[n] = std::pow(x1_ptr[n] - x2_ptr[n], 2);\n    }\n}\n\ntemplate <>\nvoid rowwise_max<float, CPUContext>(const int m,\n                                    const int n,\n                                    const float *a_ptr,\n                                    float *b_ptr\n                                    )\n{\n    Eigen::Map<Eigen::VectorXf>(b_ptr, m) =\n    Eigen::Map<const Eigen::MatrixXf>(a_ptr, n, m).colwise().maxCoeff();\n}\n\ntemplate <>\nvoid rowwise_max<double, CPUContext>(const int m,\n                                     const int n,\n                                     const double *a_ptr,\n                                     double *b_ptr\n                                     )\n{\n    Eigen::Map<Eigen::VectorXd>(b_ptr, m) =\n    Eigen::Map<const Eigen::MatrixXd>(a_ptr, n, m).colwise().maxCoeff();\n}\n\ntemplate <>\nvoid rowwise_normalize<float, CPUContext>(const int m, const int n,\n                                          const float *scaler_ptr,\n                                          float *norm_dest\n                                          )\n{\n    for(int i = 0; i < m; ++i){\n        for(int j = 0; j < n; ++j){\n            norm_dest[i * n + j] /= scaler_ptr[i];\n        }\n    }\n}\n\ntemplate <>\nvoid rowwise_normalize<double, CPUContext>(const int m,\n                                           const int n,\n                                           const double *scaler_ptr,\n                                           double *norm_dest\n                                           )\n{\n    for(int i = 0; i < m; ++i){\n        for(int j = 0; j < n; ++j){\n            norm_dest[i * n + j] /= scaler_ptr[i];\n        }\n    }\n}\n\n\ntemplate<>\nvoid exp<float, CPUContext>(const int size,\n                            const float *x_ptr,\n                            float *y_ptr\n                           )\n{\n    Eigen::Map<Eigen::VectorXf>(y_ptr, size) =\n    Eigen::Map<const Eigen::VectorXf>(x_ptr, size).array().exp();\n}\n\ntemplate<>\nvoid exp<double, CPUContext>(const int size,\n                             const double *x_ptr,\n                             double *y_ptr\n                            )\n{\n    Eigen::Map<Eigen::VectorXd>(y_ptr, size) =\n    Eigen::Map<const Eigen::VectorXd>(x_ptr, size).array().exp();\n}\n\ntemplate<>\nvoid axpy<float, CPUContext>(int size,\n                             const float alpha,\n                             const float *x_ptr,\n                             float *y_ptr\n                            )\n{\n    Eigen::Map<Eigen::VectorXf>(y_ptr, size) +=\n    alpha * Eigen::Map<const Eigen::VectorXf>(x_ptr, size);\n}\n\ntemplate<>\nvoid axpy<double, CPUContext>(int size,\n                              const double alpha,\n                              const double *x_ptr,\n                              double *y_ptr\n                             )\n{\n    Eigen::Map<Eigen::VectorXd>(y_ptr, size) +=\n    alpha * Eigen::Map<const Eigen::VectorXd>(x_ptr, size);\n}\n\ntemplate <>\nvoid scal<float, CPUContext>(const int size,\n                             const float alpha,\n                             const float *x_ptr,\n                             float *y_ptr\n                            )\n{\n    Eigen::Map<Eigen::VectorXf> y(y_ptr, size);\n    if(alpha != 0.f){\n        y = alpha * Eigen::Map<const Eigen::VectorXf>(x_ptr, size);\n    }\n    else{\n        y.setZero();\n    }\n}\n\ntemplate <>\nvoid scal<double, CPUContext>(const int size,\n                              const double alpha,\n                              const double *x_ptr,\n                              double *y_ptr\n                             )\n{\n    Eigen::Map<Eigen::VectorXd> y(y_ptr, size);\n    if(alpha != 0.){\n        y = alpha * Eigen::Map<const Eigen::VectorXd>(x_ptr, size);\n    }\n    else{\n        y.setZero();\n    }\n}\n\ntemplate <>\nvoid sum<float, CPUContext>(\n                            const int size,\n                            const float *x_ptr,\n                            float *y_ptr\n                           )\n{\n    y_ptr[0] = Eigen::Map<const Eigen::VectorXf>(x_ptr, size).sum();\n}\n\ntemplate <>\nvoid sum<double, CPUContext>(\n                             const int size,\n                             const double *x_ptr,\n                             double *y_ptr\n                            )\n{\n    y_ptr[0] = Eigen::Map<const Eigen::VectorXd>(x_ptr, size).sum();\n}\n\ntemplate<>\nvoid set<float, CPUContext>(\n                            const int size,\n                            const float val,\n                            float *x_ptr\n                           )\n{\n    Eigen::Map<Eigen::VectorXf>(x_ptr, size).setConstant(val);\n}\n\ntemplate<>\nvoid set<double, CPUContext>(const int size,\n                             const double val,\n                             double *x_ptr\n                             )\n{\n    Eigen::Map<Eigen::VectorXd>(x_ptr, size).setConstant(val);\n}\n\n} // end namespace math\n} // end namespace mlfe\n", "meta": {"hexsha": "f3dc940997d6e64f04583d84fa6780a7bba6404f", "size": 5649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mlfe/math/basic_functions.cc", "max_stars_repo_name": "shi510/mlfe", "max_stars_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T11:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T18:25:11.000Z", "max_issues_repo_path": "mlfe/math/basic_functions.cc", "max_issues_repo_name": "shi510/mlfe", "max_issues_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlfe/math/basic_functions.cc", "max_forks_repo_name": "shi510/mlfe", "max_forks_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T12:40:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T05:23:36.000Z", "avg_line_length": 29.421875, "max_line_length": 72, "alphanum_fraction": 0.4253850239, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6573104085957557}}
{"text": "#ifndef _NB_SAMPLE_HPP\n#define _NB_SAMPLE_HPP\n\n#include <vector>\n#include <cmath>\n#include <numeric>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include <dlib/optimization.h>\n\n\n#include \"misc.hpp\" \n\ntypedef dlib::matrix<double,0,1> column_vector;\nusing namespace std::placeholders;\n\nclass NBModelC {\n\n    public:\n        NBModelC (std::vector<long> lvec) : sample_vec(lvec){\n\n        }\n\n        double value(const column_vector &m) {\n\n            double r_val = m(0);\n            double lmean = do_mean(sample_vec);\n            double lpval = lmean / (lmean + r_val);\n            double total_ll = 0;\n\n            for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n                double xi_val = (double)sample_vec[j_ind];\n\n                double lval1 = lgamma(xi_val + r_val) -lgamma(xi_val + 1) -\n                    lgamma(r_val) + xi_val * log (lpval) + \n                    r_val * log(1 - lpval);\n                total_ll += lval1;\n            }\n\n            return (total_ll);\n        }\n\n\n        const column_vector gradient(const column_vector &m) {\n           \n            double r_val = m(0);\n            double lmean = do_mean(sample_vec);\n            double lpval = lmean / (lmean + r_val);\n         \n            double total_derivative = 0;\n\n            for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n                double xi_val = sample_vec[j_ind];\n\n                double lval1 = boost::math::digamma(xi_val + r_val) -\n                    boost::math::digamma(r_val) + log(1-lpval);\n                \n                total_derivative += lval1;\n            }\n            const column_vector final_grad = {total_derivative};\n            return final_grad;\n\n        }\n\n\n        double get_r_val_0 () {\n            int n = sample_vec.size();\n            double lmean = do_mean(sample_vec);\n\n            double lsum = 0;\n            for (int j = 0; j < n; j++) {\n                lsum += pow((sample_vec[j] - lmean), 2.0);\n            }\n            double lvar = lsum / (n-1);\n\n            double r_val_0 = 0;\n            if (lvar > lmean) {\n                r_val_0 = pow(lmean, 2.0) / (lvar - lmean);\n            } else {\n                r_val_0 = 100;\n            }\n            return r_val_0;\n        }\n\n        double find_r_val() {\n        \n            if (r_val_ready) {\n                return (final_r_val);\n            }\n\n            auto value_funct = std::bind(&NBModelC::value, this, _1);\n            auto gradient_funct = std::bind(&NBModelC::gradient, this, _1);\n            double r_val_0 = get_r_val_0();\n            column_vector starting_point = {r_val_0};\n            const column_vector x_lower1 = {0.0000001};\n            const column_vector x_upper1 = {1000000};\n\n\n            find_max_box_constrained(dlib::bfgs_search_strategy(),\n                                     dlib::objective_delta_stop_strategy(1e-9),\n                                     value_funct, gradient_funct, \n                                    starting_point,\n                                    x_lower1, x_upper1);\n\n            final_r_val = starting_point(0);\n            r_val_ready = true;\n            return final_r_val;\n        }\n\n        double find_p_val() {\n\n            if (p_val_ready) {\n                return (final_p_val);\n            }\n            double lrval = find_r_val();\n \n            double lmean = do_mean(sample_vec);\n            final_p_val = lmean / (lmean + lrval);\n            p_val_ready = true;\n            return (final_p_val);\n            \n        }\n\n        double find_mean_val() {\n\n            double lmean = do_mean(sample_vec);\n            return (lmean);\n        }\n\n\n    private:\n        std::vector<long> sample_vec;\n        double final_p_val;\n        double final_r_val;\n        bool p_val_ready = false;\n        bool r_val_ready = false;\n\n};\n\n#endif\n", "meta": {"hexsha": "c23ea359cf043de420cd94f5e9c71680243aa252", "size": 3877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NBModel.hpp", "max_stars_repo_name": "nirmalya-broad/NB_EM", "max_stars_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "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": "NBModel.hpp", "max_issues_repo_name": "nirmalya-broad/NB_EM", "max_issues_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "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": "NBModel.hpp", "max_forks_repo_name": "nirmalya-broad/NB_EM", "max_forks_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "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.1118881119, "max_line_length": 79, "alphanum_fraction": 0.5006448285, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.657310401351212}}
{"text": "#define BOOST_TEST_MODULE math_test_module\n#include <boost/test/unit_test.hpp>\n#include <vector>\n#include <iostream>\n\n#include \"math_lib.h\"\n\nusing namespace std;\nnamespace tt = boost::test_tools;\nnamespace utf = boost::unit_test;\n\n/*\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& out, std::vector<T> vec) {\n    for (const auto& v : vec) {\n        out << v << \" \";\n    }\n    return out;\n}\n*/\n\nBOOST_AUTO_TEST_SUITE(math_lib_test_suite)\n\n    BOOST_AUTO_TEST_CASE(test_factorial) {\n        // integer\n        BOOST_TEST(factorial(0) == 1);\n        BOOST_TEST(factorial(1) == 1);\n        BOOST_TEST(factorial(2) == 2);\n        BOOST_TEST(factorial(3) == 6);\n        BOOST_TEST(factorial(10) == 3628800);\n        BOOST_TEST(factorial(-1) == 1);\n        // double\n        BOOST_TEST(factorial(0.5) == 1);\n        BOOST_TEST(factorial(1.5) == 1.5);\n        BOOST_TEST(factorial(2.5) == 3.75);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_round_to, * utf::tolerance(0.000001)) {\n        BOOST_TEST(roundTo(125, 1) == 130);\n        BOOST_TEST(roundTo(125, 2) == 100);\n        BOOST_TEST(roundTo(125.456, 1) == 130);\n        BOOST_TEST(roundTo(125.456, 0) == 125);\n        BOOST_TEST(roundTo(125.456, -1) == 125.5);\n        // less one\n        BOOST_TEST(roundTo(0.416, 1) == 0);\n        BOOST_TEST(roundTo(0.416, 0) == 0);\n        BOOST_TEST(roundTo(0.416, -1) == 0.4);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_odd) {\n        BOOST_TEST(!odd(2));\n        BOOST_TEST(odd(1));\n        BOOST_TEST(odd(3));\n        BOOST_TEST(!odd(0));\n        BOOST_TEST(odd(-1));\n    }\n\n    BOOST_AUTO_TEST_CASE(test_average_1) {\n        // contract: double average(double x, double y);\n        BOOST_TEST(average(2, 4) == 3);\n        BOOST_TEST(average(2, 5) == 3.5);\n        BOOST_TEST(average(0, 1) == 0.5);\n        BOOST_TEST(average(-1, 1) == 0);\n        BOOST_TEST(average(2.5, 0.5) == 1.5);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_average_2) {\n        // contract: double average(const std::vector<double>& vals);\n        BOOST_TEST(average({2, 4}) == 3);\n        BOOST_TEST(average({2, 5}) == 3.5);\n        BOOST_TEST(average({0, 1}) == 0.5);\n        BOOST_TEST(average({-1, 1}) == 0);\n        BOOST_TEST(average({2.5, 0.5}) == 1.5);\n        BOOST_TEST(average({-2, 2, 3}) == 1);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_average_3, * utf::tolerance(0.000001)) {\n        // contract: void average(const std::vector<double>& vals, double &mean, double &err);\n        {const vector<double> input {4, 5, 7, 2};\n            double mean, err;\n            average(input, mean, err);\n            BOOST_TEST(mean == 4.5);\n            BOOST_TEST(err == 1.04083299973307);\n        }\n        {const vector<double> input {2, 5};\n            double mean, err;\n            average(input, mean, err);\n            BOOST_TEST(mean == 3.5);\n            BOOST_TEST(err == 1.5);\n        }\n    }\n\n    BOOST_AUTO_TEST_CASE(test_sqr_add, * utf::tolerance(0.000001)) {\n        // contract: double sqrAdd(const std::vector<double>& vals);\n        BOOST_TEST(sqrAdd({3, 4}) == 5);\n        BOOST_TEST(sqrAdd({3, 4, 5}) == sqrt(50));\n        BOOST_TEST(sqrAdd({7.1, 3.2, 78.5, 0.56}) == 78.8873475279781);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_poly) {\n        // f(x) = 2*x^2 + x + 3.5; f(0)\n        const vector<double> coeffs = {3.5, 1, 2};\n        BOOST_TEST(poly(0, coeffs) == 3.5);\n        BOOST_TEST(poly(1, coeffs) == 6.5);\n        BOOST_TEST(poly(-1, coeffs) == 4.5);\n    }\n\n    BOOST_AUTO_TEST_CASE(test_calculate_pdf) {\n        // weights: 1, 1, 1, 1 => pdf: 0.25, 0.5, 0.75, 1 and sum = 4\n        {\n            vector<double> weights = {1, 1, 1, 1};\n            auto sum = calculate_pdf(weights);\n            BOOST_TEST(sum == 4);\n            const vector<double> res = {0.25, 0.5, 0.75, 1};\n            BOOST_TEST(weights == res);\n        }\n        {\n            vector<double> weights = {1};\n            auto sum = calculate_pdf(weights);\n            BOOST_TEST(sum == 1);\n            const vector<double> res = {1};\n            BOOST_TEST(weights == res);\n        }\n        {\n            vector<double> weights = {0.5, 2, 1};\n            auto sum = calculate_pdf(weights);\n            BOOST_TEST(sum == 3.5);\n            const vector<double> res = {5./35, 25./35, 1};\n            BOOST_TEST(weights == res);\n        }\n        // test with predicate: e.g. cont with struct a.weight:\n        {\n            struct Tmp {double weight = 0;};\n            vector<Tmp> weights = {Tmp{0.5}, Tmp{2}, Tmp{1}};\n            vector<double> res;\n            auto sum = calculate_pdf(weights, [](const Tmp& t){ return t.weight;}, res);\n            BOOST_TEST(sum == 3.5);\n            const vector<double> expected = {5./35, 25./35, 1};\n            BOOST_TEST(res == expected);\n        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "04fb8235fe32c31b7e28f472abeb83df0f6d0fed", "size": 4765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Math/tests/test_math_lib.cpp", "max_stars_repo_name": "gwlsrm/Units", "max_stars_repo_head_hexsha": "e7e4b33179313a3b01a055695ba0326a3a6442a9", "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": "Math/tests/test_math_lib.cpp", "max_issues_repo_name": "gwlsrm/Units", "max_issues_repo_head_hexsha": "e7e4b33179313a3b01a055695ba0326a3a6442a9", "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": "Math/tests/test_math_lib.cpp", "max_forks_repo_name": "gwlsrm/Units", "max_forks_repo_head_hexsha": "e7e4b33179313a3b01a055695ba0326a3a6442a9", "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.3216783217, "max_line_length": 94, "alphanum_fraction": 0.5376705142, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6573066413076362}}
{"text": "#include <stdexcept>\n\n#include <boost/math/constants/constants.hpp>\n#include <Eigen/Eigenvalues>\n#include <Euclid/Math/Statistics.h>\n#include <Euclid/Math/Vector.h>\n\nnamespace Euclid\n{\n\ntemplate<typename Kernel>\nvoid OBB<Kernel>::build(const std::vector<FT>& positions)\n{\n    if (positions.empty()) {\n        throw std::invalid_argument(\"Input is empty.\");\n    }\n    if (positions.size() % 3 != 0) {\n        throw std::runtime_error(\"Size of input is not divisble by 3.\");\n    }\n\n    Eigen::Map<const Eigen::\n                   Matrix<FT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n        v(positions.data(), positions.size() / 3, 3);\n    _build(v);\n}\n\ntemplate<typename Kernel>\ntemplate<typename ForwardIterator, typename VPMap>\nvoid OBB<Kernel>::build(ForwardIterator first,\n                        ForwardIterator beyond,\n                        VPMap vpmap)\n{\n    std::vector<FT> positions;\n    while (first != beyond) {\n        positions.push_back(get(vpmap, *first).x());\n        positions.push_back(get(vpmap, *first).y());\n        positions.push_back(get(vpmap, *first).z());\n        ++first;\n    }\n    build(positions);\n}\n\ntemplate<typename Kernel>\ntemplate<typename Derived>\nvoid OBB<Kernel>::build(const Eigen::MatrixBase<Derived>& v)\n{\n    if (v.rows() == 0) {\n        throw std::invalid_argument(\"Input is empty.\");\n    }\n\n    _build(v);\n}\n\ntemplate<typename Kernel>\ntypename OBB<Kernel>::Point_3 OBB<Kernel>::center() const\n{\n    return _center;\n}\n\ntemplate<typename Kernel>\ntypename OBB<Kernel>::Vector_3 OBB<Kernel>::axis(int n) const\n{\n    if (n < 0 || n >= 3) {\n        throw std::invalid_argument(\"Invalid argument for OBB::length(int).\");\n    }\n    return Euclid::normalized(_directions[n]);\n}\n\ntemplate<typename Kernel>\ntypename OBB<Kernel>::FT OBB<Kernel>::length(int n) const\n{\n    if (n < 0 || n >= 3) {\n        throw std::invalid_argument(\"Invalid argument for OBB::length(int).\");\n    }\n    return Euclid::length(_directions[n]) * 2;\n}\n\ntemplate<typename Kernel>\ntemplate<typename Derived>\nvoid OBB<Kernel>::_build(const Eigen::MatrixBase<Derived>& points)\n{\n    using namespace boost::math::constants;\n\n    // Conduct pca by eigen decompose the covariance matrix of points\n    Eigen::Matrix<FT, 3, 3> covariance;\n    Euclid::covariance_matrix(points, covariance);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<FT, 3, 3>> eigs;\n    eigs.compute(covariance);\n    if (eigs.info() != Eigen::Success) {\n        throw std::runtime_error(\"PCA no convergence.\");\n    }\n\n    // Unit lengh, sorted in descending order w.r.t. eigen values\n    Euclid::eigen_to_cgal(eigs.eigenvectors().col(2), _directions[0]);\n    Euclid::eigen_to_cgal(eigs.eigenvectors().col(1), _directions[1]);\n    Euclid::eigen_to_cgal(eigs.eigenvectors().col(0), _directions[2]);\n\n    // Transform points to pca coordinate system\n    Eigen::Matrix<FT, Eigen::Dynamic, 3> tpoints = points * eigs.eigenvectors();\n    Eigen::Matrix<FT, Eigen::Dynamic, 1> tmax = tpoints.colwise().maxCoeff();\n    Eigen::Matrix<FT, Eigen::Dynamic, 1> tmin = tpoints.colwise().minCoeff();\n\n    // Record center and length of box\n    _center = CGAL::ORIGIN + half<FT>() * (tmax(2) + tmin(2)) * _directions[0] +\n              half<FT>() * (tmax(1) + tmin(1)) * _directions[1] +\n              half<FT>() * (tmax(0) + tmin(0)) * _directions[2];\n    _directions[0] *= half<FT>() * (tmax(2) - tmin(2));\n    _directions[1] *= half<FT>() * (tmax(1) - tmin(1));\n    _directions[2] *= half<FT>() * (tmax(0) - tmin(0));\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "4c6a5159c38652111025a4950d0322e7fc8a4a53", "size": 3510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/BoundingVolume/src/OBB.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/BoundingVolume/src/OBB.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/BoundingVolume/src/OBB.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.0619469027, "max_line_length": 80, "alphanum_fraction": 0.6387464387, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6573066366222741}}
{"text": "#include <ceres/ceres.h>\n#include <Eigen/Dense>\n#include <fstream>\n#include <string>\n#include <thread>\n#include <random>\n#include \"pose_estimator.h\"\n#include \"re_projection_error.h\"\n#include \"timer.h\"\n#include \"type.h\"\n#include \"viewer/viewer.h\"\n\nusing ceres::Problem;\nusing ceres::AutoDiffCostFunction;\nusing ceres::SizedCostFunction;\n\nVec6d isoMat2Vector(const Eigen::Matrix4d pose) {\n  Eigen::Matrix3d rotation = pose.block(0, 0, 3, 3);\n  Eigen::AngleAxisd angle_axis(rotation);\n  Eigen::Vector3d rv = angle_axis.angle() * angle_axis.axis();\n  Vec6d v;\n  v << rv.x(), rv.y(), rv.z(), pose(0, 3), pose(1, 3), pose(2, 3);\n  return v;\n}\n\nEigen::Matrix4d vector2IsoMat(const Vec6d &v) {\n  double angle = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n  Eigen::Vector3d axis(v[0], v[1], v[2]);\n  axis /= angle;\n  Eigen::AngleAxisd angle_axis(angle, axis);\n\n  Eigen::MatrixX4d pose = Eigen::Matrix4d::Identity();\n  pose.block(0, 0, 3, 3) = angle_axis.toRotationMatrix();\n\n  pose(0, 3) = v[3];\n  pose(1, 3) = v[4];\n  pose(2, 3) = v[5];\n  return pose;\n}\n\nvoid addNoise(Vec6d &v, double rotation_noise, double translation_noise) {\n  const double mean = 0.0;\n  std::default_random_engine generator;\n  std::normal_distribution<double> dist_rotation(mean, rotation_noise);\n  std::normal_distribution<double> dist_translation(mean, translation_noise);\n  for (int i = 0; i < 3; i++) {\n    v[i] += dist_rotation(generator);\n    v[i + 3] += dist_translation(generator);\n  }\n}\n\nint main(int argc, char **argv) {\n  if (argc != 3) {\n    std::cout << \" args error \" << std::endl;\n    return 1;\n  }\n  bool use_analytic = false;\n\n  std::cout << kColorGreen << (use_analytic ? \" Use Analytic Derivatives \"\n                                            : \" Use Automatic Derivatives\")\n            << kColorReset << std::endl;\n\n  std::string str_map_points = std::string(argv[1]);\n  std::string str_observation = std::string(argv[2]);\n\n  Mat44d ground_truth_pose;\n  ground_truth_pose << -0.38773203, -0.29730779, 0.872509, -1.8075688,\n      0.29847804, 0.85506284, 0.42400289, 0.0065075331, -0.87210935, 0.42482427,\n      -0.24279539, 0.75284511, 0, 0, 0, 1;\n\n  auto init_parameter = isoMat2Vector(ground_truth_pose);\n\n  // add noise to ground_truth\n  addNoise(init_parameter, 0.1, 0.2);\n\n  // Setup Viewer\n\n  Viewer viewer;\n  viewer.LoadMappoints(str_map_points);\n  viewer.SetGroundTruthPose(ground_truth_pose);\n  viewer.SetInitialPose(vector2IsoMat(init_parameter));\n  std::thread *viewer_thread = new std::thread(&Viewer::Run, &viewer);\n  viewer_thread->detach();\n\n  // start solving pose estimation problem\n\n  std::shared_ptr<PoseEstimationProblem> pose_estimation =\n      std::make_shared<PoseEstimationProblem>();\n  pose_estimation->loadFile(str_observation);\n  pose_estimation->setInitialParameter(init_parameter.data());\n\n  ceres::Problem problem;\n\n  // camera intrinsic parameters\n  double fx = 458.65399169921875;\n  double fy = 457.29598999023438;\n  double cx = 367.21499633789062;\n  double cy = 248.375;\n  CameraInt cam_int(fx, fy, cx, cy);\n\n  if (use_analytic) {\n    problem.AddParameterBlock(pose_estimation->mutable_camera_pose(), 6,\n                              new PoseSE3Parameterization());\n  } else {\n    problem.AddParameterBlock(pose_estimation->mutable_camera_pose(), 6);\n  }\n  for (int i = 0; i < pose_estimation->num_observations(); ++i) {\n    auto point = pose_estimation->point_position_for_observation(i);\n    auto observation = pose_estimation->observation(i);\n\n    if (use_analytic) {\n      ceres::CostFunction *cost_function =\n          new ReprojectionErrorSE3(cam_int, observation.x(), observation.y(),\n                                   point.x(), point.y(), point.z());\n      problem.AddResidualBlock(cost_function, NULL,\n                               pose_estimation->mutable_camera_pose());\n    } else  // auto-diff\n    {\n      ceres::CostFunction *cost_function =\n          ReprojectionError::create(cam_int, observation.x(), observation.y(),\n                                    point[0], point[1], point[2]);\n      problem.AddResidualBlock(cost_function, nullptr /* squared loss */,\n                               pose_estimation->mutable_camera_pose());\n    }\n  }\n\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\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  // display optimized result\n  auto final_result = pose_estimation->mutable_camera_pose();\n  Eigen::Map<Vec6d> final_result_vector = Eigen::Map<Vec6d>(final_result);\n  viewer.SetEstimatePose(vector2IsoMat(final_result_vector));\n\n  while (true) {\n    std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n  }\n\n  return 1;\n}\n", "meta": {"hexsha": "9181499e6d6eb819511bab73a8e1cbb98e6729df", "size": 4772, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose_estimation_test.cc", "max_stars_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_stars_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_stars_repo_licenses": ["MIT"], "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/pose_estimation_test.cc", "max_issues_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_issues_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose_estimation_test.cc", "max_forks_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_forks_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_forks_repo_licenses": ["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.6849315068, "max_line_length": 80, "alphanum_fraction": 0.6670159262, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6573066362775212}}
{"text": "//\tObjective: To implement the option class that is defined in the header file: AsianGeometricOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n#include \"AsianGeometricOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble AsianGeometricOption::CallPrice() const\r\n{\r\n\treturn ::AsianGeometricCallPrice(S, K, T, r, sig, b, type);\r\n}\r\n\r\ndouble AsianGeometricOption::PutPrice() const\r\n{\r\n\treturn ::AsianGeometricPutPrice(S, K, T, r, sig, b, type);\r\n}\r\n\r\n\r\nvoid AsianGeometricOption::init()\t\t\t\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 0.25;\r\n\tr = 0.05;\r\n\tsig = 0.2;\r\n\tK = 85;\r\n\tS = 80;\t\t\t\r\n\tb = 0.08;\t\t\t\r\n\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n\r\n}\r\n\r\nvoid AsianGeometricOption::copy(const AsianGeometricOption& option)\r\n{\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\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\nAsianGeometricOption::AsianGeometricOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nAsianGeometricOption::AsianGeometricOption(const AsianGeometricOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nAsianGeometricOption::AsianGeometricOption(const double& S1, const double& K1, const double& T1, const double& r1, const double& sig1,\r\n\tconst double& b1, const string type1) : Option(), S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nAsianGeometricOption::~AsianGeometricOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nAsianGeometricOption& AsianGeometricOption::operator = (const AsianGeometricOption& 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 AsianGeometricOption::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 AsianGeometricOption::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 AsianGeometricCallPrice(const double S, const double K, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble sig_adj = sig / sqrt(3);\t\t\t\t\t\t//\tadjusted volatility \r\n\tdouble b_adj = 0.5 * (b - ((sig * sig) / 6));\t\t//\tadjusted cost-of-carry\r\n\r\n\tdouble d1 = (log(S / K) + (b_adj + (sig_adj * sig_adj * 0.5)) * T) / sig_adj * sqrt(T);\r\n\tdouble d2 = d1 - sig_adj * sqrt(T);\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn ((S * exp((b_adj - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2)));\r\n}\r\n\r\ndouble AsianGeometricPutPrice(const double S, const double K, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble sig_adj = sig / sqrt(3);\t\t\t\t\t\t//\tadjusted volatility \r\n\tdouble b_adj = 0.5 * (b - ((sig * sig) / 6));\t\t//\tadjusted cost-of-carry\r\n\r\n\tdouble d1 = (log(S / K) + (b_adj + (sig_adj * sig_adj * 0.5)) * T) / sig_adj * sqrt(T);\r\n\tdouble d2 = d1 - sig_adj * sqrt(T);\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn ((K * exp(-r * T) * cdf(standard_normal, -d2)) - (S * exp((b_adj - r) * T) * cdf(standard_normal, -d1)));\r\n}\r\n\r\n", "meta": {"hexsha": "28412f2f25cc68e0527452cf76621d67f40ce53d", "size": 3396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AsianGeometricOption.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": "AsianGeometricOption.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": "AsianGeometricOption.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": 26.3255813953, "max_line_length": 148, "alphanum_fraction": 0.6472320377, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6573022415177014}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <string>\n#include <sstream>\n\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"wali/QueueWorklist.hpp\"\n#include \"wali/wpds/WPDS.hpp\"\n#include \"wali/wfa/WFA.hpp\"\n#include \"wali/witness/Witness.hpp\"\n#include \"wali/witness/WitnessWrapper.hpp\"\n#include \"wali/domains/matrix/Matrix.hpp\"\n#include \"wali/domains/matrix/MatrixRanker.hpp\"\n\n#include \"opennwa/query/ShortWitnessVisitor.hpp\"\n#include \"opennwa/query/PathVisitor.hpp\"\n\n#include \"matrix-equal.hpp\"\n\nusing namespace wali::witness;\n\nnamespace wali {\nnamespace domains {\n\nnamespace {\n\nconst int inf = std::numeric_limits<MinPlusIntMatrix::value_type::value_type>::max();\n\nstruct Weights1\n{\n    MinPlusIntMatrix::BackingMatrix\n        bm_id,\n        bm_initial,\n        bm_loop,\n        bm_step,\n        bm_expected;\n\n    ref_ptr<MinPlusIntMatrix>\n        zero,\n        id,\n        initial,\n        loop,\n        step,\n        expected;\n\n    Weights1()\n        : bm_id(2,2)\n        , bm_initial(2,2)\n        , bm_loop(2,2)\n        , bm_step(2,2)\n        , bm_expected(2,2)\n    {\n        int m_id[2][2] = {\n            {   0, inf},\n            { inf,   0},\n        };\n\n        int m_initial[2][2] = {\n            {   1, inf},\n            { inf, inf},\n        };\n\n        int m_loop[2][2] = {\n            {   1,   1},\n            { inf,   1},\n        };\n\n        int m_step[2][2] = {\n            {   1, inf},\n            { inf,   1},\n        };\n\n        int m_expected[2][2] = {\n            {   2,   3},\n            { inf, inf},\n        };\n\n        for (size_t i = 0; i < 2; ++i) {\n            for (size_t j = 0; j < 2; ++j) {\n                bm_id(i, j).set_value(m_id[i][j]);\n                bm_initial(i, j).set_value(m_initial[i][j]);\n                bm_loop(i, j).set_value(m_loop[i][j]);\n                bm_step(i, j).set_value(m_step[i][j]);\n                bm_expected(i, j).set_value(m_expected[i][j]);\n            }\n        }\n\n        id       = new MinPlusIntMatrix(bm_id);\n        initial  = new MinPlusIntMatrix(bm_initial);\n        loop     = new MinPlusIntMatrix(bm_loop);\n        step     = new MinPlusIntMatrix(bm_step);\n        expected = new MinPlusIntMatrix(bm_expected);\n\n        zero = dynamic_cast<MinPlusIntMatrix*>(id->zero().get_ptr());\n    }\n};\n\nstruct Keys\n{\n    Key start, loop, finish, top, bottom, join, middle, p, acc;\n\n    Keys()\n        : start(getKey(\"start\"))\n        , loop(getKey(\"loop\"))\n        , finish(getKey(\"finish\"))\n        , top(getKey(\"top\"))\n        , bottom(getKey(\"bottom\"))\n        , join(getKey(\"join\"))\n        , middle(getKey(\"middle\"))\n        , p(getKey(\"p\"))\n        , acc(getKey(\"acc\"))\n    {}\n};\n\nstruct WpdsWfa1\n{\n    wpds::WPDS wpds;\n    wfa::WFA wfa;\n\n    Weights1 weights;\n    Keys keys;\n\n    WpdsWfa1(ref_ptr<wpds::Wrapper> wrapper)\n        : wpds(wrapper)\n    {\n        // WPDS for the following CFG:\n        //\n        //                     ___\n        //                    /   \\ <loop>\n        //                    \\   /\n        // (start) --------> (loop) --------> (finish)\n        //         <inital>         <step>\n        //\n        // <...> indicate the weight\n\n        wpds.add_rule(keys.p, keys.start, keys.p, keys.loop,   weights.initial);\n        wpds.add_rule(keys.p, keys.loop,  keys.p, keys.loop,   weights.loop);\n        wpds.add_rule(keys.p, keys.loop,  keys.p, keys.finish, weights.step);\n\n        // And the automaton for poststar:\n        //\n        //          (start) <id>\n        //  (p) ----------------------> (acc)\n\n        wfa.addState(keys.p,   weights.zero);\n        wfa.addState(keys.acc, weights.zero);\n\n        wfa.setInitialState(keys.p);\n        wfa.addFinalState(keys.acc);\n\n        wfa.addTrans(keys.p, keys.start, keys.acc, weights.id);\n    }\n\n    sem_elem_t\n    poststar_finish_weight()\n    {\n        wfa::WFA ps_wfa = wpds.poststar(wfa);\n\n        wfa::TransSet ts = ps_wfa.match(keys.p, keys.finish);\n\n        if (ts.size() != 1) {\n            return NULL;\n        }\n        else {\n            return (*ts.begin())->weight();\n        }\n    }\n\n    ref_ptr<MinPlusIntMatrix>\n    poststar_finish_matrix()\n    {\n        return dynamic_cast<MinPlusIntMatrix*>(\n            poststar_finish_weight().get_ptr());\n    }\n\n    ref_ptr<Witness>\n    poststar_finish_witness()\n    {\n        return dynamic_cast<Witness*>(\n            poststar_finish_weight().get_ptr());\n    }\n};\n\n///////////////////////\n\nclass PathVisitor\n    : public CalculatingVisitor<std::string>\n{\npublic:\n    //! Overload to calculate the value of an extend node. Modifications to\n    //! the AnswerType& parameters will not persist.\n    virtual std::string calculateExtend(\n        WitnessExtend * w ATTR_UNUSED, std::string & leftValue, std::string & rightValue )\n    {\n        return leftValue + rightValue;\n    }\n\n    //! Overload to calculate the value of an combine node. Modifications to\n    //! the list parameter will not persist.\n    virtual std::string calculateCombine(\n        WitnessCombine * w ATTR_UNUSED,\n        std::list<std::string> & childrenValues ATTR_UNUSED)\n    {\n        return \"[!COMBINE NODE!]\";\n    }\n\n    //! Overload to calculate the value of an merge node. Modifications to\n    //! the std::string& parameters will not persist.\n    virtual std::string calculateMerge(\n        WitnessMerge * w ATTR_UNUSED,\n        std::string & callerValue ATTR_UNUSED,\n        std::string & ruleValue ATTR_UNUSED,\n        std::string & calleeValue ATTR_UNUSED)\n    {\n        return \"[!MERGE NODE!]\";\n    }\n\n    //! Overload to calculate the value of a rule node.\n    virtual std::string calculateRule( WitnessRule * w)\n    {\n        std::stringstream ss;\n        ss << \"[\" << key2str(w->getRuleStub().from_stack())\n           << \"->\" << key2str(w->getRuleStub().to_stack1())\n           << \"]\";\n        if (w->getRuleStub().to_stack2() != WALI_EPSILON) {\n            ss << \" !! \" << key2str(w->getRuleStub().to_stack2());\n        }\n        return ss.str();\n    }\n\n    //! Overload to calculate the value of a trans node.\n    virtual std::string calculateTrans( WitnessTrans * w ATTR_UNUSED)\n    {\n        return \"\";\n    }\n};\n\n}\n\n\nTEST(example$matrix$shortest$path, no$witness$gets$right$matrix)\n{\n    WpdsWfa1 f(NULL);\n    ref_ptr<MinPlusIntMatrix> m = f.poststar_finish_matrix();\n\n    ASSERT_TRUE(m.is_valid());\n    EXPECT_EQ(m->matrix(), f.weights.bm_expected);\n}\n\n\nstatic std::string s_get_path1(\n    MatrixRanker<MinPlusIntMatrix> const * ranker)\n{\n    WpdsWfa1 f(new WitnessWrapper());\n    ref_ptr<Witness> w = f.poststar_finish_witness();\n\n    opennwa::query::ShortWitnessVisitor swv(ranker);\n    w->accept(swv);\n\n    if (swv.answer()->equal(swv.answer()->zero())) {\n        return \"[!!ZERO WITNESS!!]\";\n    }\n\n    PathVisitor pv;\n    swv.answer()->accept(pv);\n\n    return pv.answer();\n}\n\n\nTEST(example$matrix$shortest$path, witness$gets$shortest$path)\n{\n    EXPECT_EQ(\n        \"[start->loop][loop->finish]\",\n        s_get_path1(NULL));\n}\n\nTEST(example$matrix$shortest$path, witness$gets$shortest$path$to$state$0)\n{\n    details::MinPlus<int> d_zero;\n    d_zero.set_value(0);\n\n    MatrixRanker<MinPlusIntMatrix> ranker(2);\n    ranker.set_initial(0, d_zero);\n    ranker.set_final(0, d_zero);\n\n    EXPECT_EQ(\n        \"[start->loop][loop->finish]\",\n        s_get_path1(&ranker));\n}\n\nTEST(example$matrix$shortest$path, witness$gets$shortest$path$to$state$1)\n{\n    details::MinPlus<int> d_zero;\n    d_zero.set_value(0);\n\n    MatrixRanker<MinPlusIntMatrix> ranker(2);\n    ranker.set_initial(0, d_zero);\n    ranker.set_final(1, d_zero);\n\n    EXPECT_EQ(\n        \"[start->loop][loop->loop][loop->finish]\",\n        s_get_path1(&ranker));\n}\n\n\n\n/////////////////////////\n\nstruct Weights2\n{\n    MinPlusIntMatrix::BackingMatrix\n        bm_s1_to_s1,\n        bm_s2_to_s2,\n        bm_reverse;\n\n    ref_ptr<MinPlusIntMatrix>\n        id,\n        s1_to_s1,\n        s2_to_s2,\n        reverse,\n        zero;\n\n    Weights2()\n        : bm_s1_to_s1(2,2)\n        , bm_s2_to_s2(2,2)\n        , bm_reverse(2,2)\n    {\n        int m_s1[2][2] = {\n            {   1, inf},\n            { inf, inf},\n        };\n\n        int m_s2[2][2] = {\n            { inf, inf},\n            { inf,   1},\n        };\n\n        int m_reverse[2][2] = {\n            { inf,   1},\n            {   1, inf},\n        };\n\n        for (size_t i = 0; i < 2; ++i) {\n            for (size_t j = 0; j < 2; ++j) {\n                bm_s1_to_s1(i, j).set_value(m_s1[i][j]);\n                bm_s2_to_s2(i, j).set_value(m_s2[i][j]);\n                bm_reverse(i, j).set_value(m_reverse[i][j]);\n            }\n        }\n\n        s1_to_s1  = new MinPlusIntMatrix(bm_s1_to_s1);\n        s2_to_s2  = new MinPlusIntMatrix(bm_s2_to_s2);\n        reverse   = new MinPlusIntMatrix(bm_reverse);\n\n        Weights1 w1;\n        id = w1.id;\n        zero = w1.zero;\n    }\n};\n\nstruct WpdsWfa2\n{\n    wpds::WPDS wpds;\n    wfa::WFA wfa;\n\n    Weights2 weights;\n    Keys keys;\n\n    WpdsWfa2(ref_ptr<wpds::Wrapper> wrapper)\n        : wpds(wrapper)\n    {\n        wpds.setWorklist(new QueueWorklist<wali::wfa::ITrans>());\n\n        // WPDS for the following CFG:\n        //\n        //       <1 to 1>       <id>\n        //         /--> (top) --\\.\n        //        /              \\.\n        // (start)               (join)---->(middle)---->(finish)\n        //        \\             /      <id>        <reverse>\n        //         \\->(bottom)-/\n        //      <2 to 2>      <id>\n        //\n        // <...> indicate the weight.\n        //\n        // If you want to wind up in state 1, it looks like you should\n        // take the top path if you don't look past\n        // join/middle.\n\n        wpds.add_rule(keys.p, keys.start,  keys.p, keys.top,    weights.s1_to_s1);\n        wpds.add_rule(keys.p, keys.start,  keys.p, keys.bottom, weights.s2_to_s2);\n\n        wpds.add_rule(keys.p, keys.top,    keys.p, keys.join,   weights.id);\n        wpds.add_rule(keys.p, keys.bottom, keys.p, keys.join,   weights.id);\n\n        wpds.add_rule(keys.p, keys.join,   keys.p, keys.middle, weights.id);\n        wpds.add_rule(keys.p, keys.middle, keys.p, keys.finish, weights.reverse);\n\n        // And the automaton for poststar:\n        //\n        //          (start) <id>\n        //  (p) ----------------------> (acc)\n\n        wfa.addState(keys.p,   weights.zero);\n        wfa.addState(keys.acc, weights.zero);\n\n        wfa.setInitialState(keys.p);\n        wfa.addFinalState(keys.acc);\n\n        wfa.addTrans(keys.p, keys.start, keys.acc, weights.id);\n    }\n\n    sem_elem_t\n    poststar_finish_weight()\n    {\n        wfa::WFA ps_wfa = wpds.poststar(wfa);\n\n        wfa::TransSet ts = ps_wfa.match(keys.p, keys.finish);\n\n        if (ts.size() != 1) {\n            return NULL;\n        }\n        else {\n            return (*ts.begin())->weight();\n        }\n    }\n\n    ref_ptr<Witness>\n    poststar_finish_witness()\n    {\n        return dynamic_cast<Witness*>(\n            poststar_finish_weight().get_ptr());\n    }\n};\n\nstatic std::string s_get_path2(\n    MatrixRanker<MinPlusIntMatrix> const * ranker)\n{\n    WpdsWfa2 f(new WitnessWrapper());\n    ref_ptr<Witness> w = f.poststar_finish_witness();\n\n    opennwa::query::ShortWitnessVisitor swv(ranker);\n    w->accept(swv);\n\n    if (swv.answer()->equal(swv.answer()->zero())) {\n        return \"[!!ZERO WITNESS!!]\";\n    }\n\n    PathVisitor pv;\n    swv.answer()->accept(pv);\n\n    return pv.answer();\n}\n\n\nTEST(example$matrix$shortest$path$midpath$combine, witness$gets$shortest$path$to$state$1)\n{\n    details::MinPlus<int> d_zero;\n    d_zero.set_value(0);\n\n    MatrixRanker<MinPlusIntMatrix> ranker(2);\n    ranker.set_initial(0, d_zero);\n    ranker.set_initial(1, d_zero);\n    ranker.set_final(0, d_zero);\n\n    EXPECT_EQ(\n        \"[start->bottom][bottom->join][join->middle][middle->finish]\",\n        s_get_path2(&ranker));\n}\n\n\n}\n}\n\n", "meta": {"hexsha": "fca8f31f0bc1b4fd0d7cb7f13727f2ab89efa507", "size": 11720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/example-matrix-shortest-path.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/example-matrix-shortest-path.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/example-matrix-shortest-path.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 24.570230608, "max_line_length": 90, "alphanum_fraction": 0.5397610922, "num_tokens": 3210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6573022303729028}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[centroid\n//` Shows calculation of a centroid of a polygon\n\n#include <iostream>\n#include <list>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\n/*<-*/ #include \"create_svg_two.hpp\" /*->*/\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\n    typedef boost::geometry::model::polygon<point_type> polygon_type;\n\n    polygon_type poly;\n    boost::geometry::read_wkt(\n        \"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)\"\n            \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", poly);\n\n    point_type p;\n    boost::geometry::centroid(poly, p);\n\n    std::cout << \"centroid: \" << boost::geometry::dsv(p) << std::endl;\n    /*<-*/ create_svg(\"centroid.svg\", poly, p); /*->*/\n    return 0;\n}\n\n//]\n\n//[centroid_output\n/*`\nOutput:\n[pre\ncentroid: (4.04663, 1.6349)\n[$img/algorithms/centroid.png]\n]\nNote that the centroid might be located in a hole or outside a polygon, easily.\n*/\n//]\n", "meta": {"hexsha": "ce4380072cf09ebbd0f23efe820e9748cad64743", "size": 1434, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/centroid.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/centroid.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/centroid.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "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.0566037736, "max_line_length": 107, "alphanum_fraction": 0.6645746165, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6573022257947977}}
{"text": "/*\n * tracer/avg_voltage.hpp --\n *\n * This file is part of nettcl2d application.\n *\n * Copyright (c) 2012 Andrey V. Nakin <andrey.nakin@gmail.com>\n * All rights reserved.\n *\n * See the file \"COPYING\" for information on usage and redistribution\n * of this file, and for a DISCLAIMER OF ALL WARRANTIES.\n *\n */\n\n#ifndef AVG_VOLTAGE_HPP_\n#define AVG_VOLTAGE_HPP_\n\n#include <math.h>\n#include <string>\n#include <fstream>\n#include <iomanip>\n#include <boost/scoped_ptr.hpp>\n#include <phlib/tracestream.h>\n#include \"../calc/abstract_tracer.hpp\"\n#include \"../util/statistics.hpp\"\n#include \"contact_tracer.hpp\"\n\nnamespace tracer {\n\n\tclass AverageVoltage : public ContactTracer {\n\n\t\tvirtual void doTrace(const Network& network, double const time, std::ostream& s) {\n\t\t\tconst Statistics stat = calcStat(network);\n\t\t\ts << stat.getMean();\n\t\t}\n\n\t\tvirtual void writeHeader(std::ostream& s) {\n\t\t\ts << \"# time\\t<voltage>\\n\";\n\t\t}\n\n\tpublic:\n\n\t\tstruct Params : public ContactTracerParams {\n\t\t\tParams() : ContactTracerParams(\"s\") {}\n\t\t};\n\n\t\tAverageVoltage(const Params& params) : ContactTracer(new Params(params)) {}\n\n\tprivate:\n\n\t\tStatistics calcStat(const Network& network) {\n\t\t\tStatistics stat;\n\n\t\t\tfor (Network::IndexVector::const_iterator i = indices.begin(), last = indices.end(); i != last; ++i) {\n\t\t\t\tstat.accum(network.contact(*i).voltage);\n\t\t\t}\n\n\t\t\treturn stat;\n\t\t}\n\n\t};\n\n}\n\n#endif /* AVG_VOLTAGE_HPP_ */\n", "meta": {"hexsha": "476113ae90c12b6bd766177d3bc761563d4908e7", "size": 1391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nettcl2d/tracer/avg_voltage.hpp", "max_stars_repo_name": "andrey-nakin/nettcl2d", "max_stars_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/nettcl2d/tracer/avg_voltage.hpp", "max_issues_repo_name": "andrey-nakin/nettcl2d", "max_issues_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nettcl2d/tracer/avg_voltage.hpp", "max_forks_repo_name": "andrey-nakin/nettcl2d", "max_forks_repo_head_hexsha": "d35d9dee6d108e7a09345a06aa4a6349bef1c0fb", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4, "max_line_length": 105, "alphanum_fraction": 0.691588785, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6572282730563151}}
{"text": "#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef struct {\n    MatrixXd A;\n    MatrixXd B;\n    VectorXd states0;\n    double dt;\n} ReferenceModel_Config_t;\n\nclass ReferenceModel {\nprotected:\n    double dt;\n    unsigned int nStates, nInputs, nOutputs;\n    \n    VectorXd states0;\n    VectorXd states;\n    MatrixXd Aref, Bref, Cref;\n    \npublic:\n    ReferenceModel(void);\n    ~ReferenceModel(void);\n    \n    void initialize(const ReferenceModel_Config_t _config);\n    void reset();\n    void update(const VectorXd _inputs);\n    void get_outputs(VectorXd &_outputs);\n    void get_states(VectorXd &_states);\n};\n\n", "meta": {"hexsha": "b1741d474639ba9d2b9df3dd79994b5cc02d5bc9", "size": 632, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "crazyflie_mrac_controllers/include/ReferenceModel.hpp", "max_stars_repo_name": "fjctp/crazyflie_mrac_ros", "max_stars_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-09T03:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T06:00:12.000Z", "max_issues_repo_path": "crazyflie_mrac_controllers/include/ReferenceModel.hpp", "max_issues_repo_name": "fjctp/crazyflie_mrac_ros", "max_issues_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crazyflie_mrac_controllers/include/ReferenceModel.hpp", "max_forks_repo_name": "fjctp/crazyflie_mrac_ros", "max_forks_repo_head_hexsha": "d43df1832860addd0ff7fbad391c7871cb3c6577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T22:48:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T22:48:29.000Z", "avg_line_length": 19.1515151515, "max_line_length": 59, "alphanum_fraction": 0.6930379747, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.657226925984972}}
{"text": "/*\n *  (C) Copyright Nick Thompson 2018.\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"multiprecision_config.hpp\"\n\n#ifndef DISABLE_MP_TESTS\n#include <boost/integer/mod_inverse.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/optional/optional.hpp>\n#include <boost/core/lightweight_test.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/integer/common_factor.hpp>\n\nusing boost::multiprecision::int128_t;\nusing boost::multiprecision::int256_t;\nusing boost::integer::mod_inverse;\nusing boost::integer::gcd;\n\ntemplate<class Z>\nvoid test_mod_inverse()\n{\n    //Z max_arg = std::numeric_limits<Z>::max();\n    Z max_arg = 500;\n    for (Z modulus = 2; modulus < max_arg; ++modulus)\n    {\n        if (modulus % 1000 == 0)\n        {\n            std::cout << \"Testing all inverses modulo \" << modulus << std::endl;\n        }\n        for (Z a = 1; a < modulus; ++a)\n        {\n            Z gcdam = gcd(a, modulus);\n            Z inv_a = mod_inverse(a, modulus);\n            // Should fail if gcd(a, mod) != 1:\n            if (gcdam > 1)\n            {\n                BOOST_TEST(inv_a == 0);\n            }\n            else\n            {\n                BOOST_TEST(inv_a > 0);\n                // Cast to a bigger type so the multiplication won't overflow.\n                int256_t a_inv = inv_a;\n                int256_t big_a = a;\n                int256_t m = modulus;\n                int256_t outta_be_one = (a_inv*big_a) % m;\n                BOOST_TEST_EQ(outta_be_one, 1);\n            }\n        }\n    }\n}\n\nint main()\n{\n    test_mod_inverse<boost::int16_t>();\n    test_mod_inverse<boost::int32_t>();\n    test_mod_inverse<boost::int64_t>();\n    test_mod_inverse<int128_t>();\n\n    return boost::report_errors();\n}\n#else\nint main()\n{\n  return 0;\n}\n#endif\n", "meta": {"hexsha": "16d17c23003a8414f388afcc9dcaf4f7c354ce69", "size": 1917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/integer/test/mod_inverse_test.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/integer/test/mod_inverse_test.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": "Libs/boost_1_76_0/libs/integer/test/mod_inverse_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "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": 26.625, "max_line_length": 80, "alphanum_fraction": 0.5894627021, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6572269254474908}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <opencv2/core/eigen.hpp>\n#include <Eigen/Geometry>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\nvoid find_feature_matches (\n    const Mat& img_1, const Mat& img_2,\n    std::vector<KeyPoint>& keypoints_1,\n    std::vector<KeyPoint>& keypoints_2,\n    std::vector< DMatch >& matches );\n\n// \u50cf\u7d20\u5750\u6807\u8f6c\u76f8\u673a\u5f52\u4e00\u5316\u5750\u6807\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nPoint2d cam2pixel ( const Mat& p, const Mat& K );\n\nvoid bundleAdjustment (\n    const vector<Point3f> points_3d,\n    const vector<Point2f> points_2d,\n    const Mat& K,\n    Mat& R, Mat& t\n);\n\nint main ( int argc, char** argv )\n{\n    if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    //-- \u8bfb\u53d6\u56fe\u50cf\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    // \u5339\u914d\u5bf9\u53ea\u662f\u4eceRGB\u56fe\u91cc\u627e\uff0c\u6df1\u5ea6\u56fe\u4f5c\u4e3a3D\u5750\u6807\u503c\u6765\u6e90\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"\u4e00\u5171\u627e\u5230\u4e86\"<<matches.size() <<\"\u7ec4\u5339\u914d\u70b9\"<<endl;\n\n    // \u5efa\u7acb3D\u70b9\uff0c\u8fd9\u662f\u4e16\u754c\u5750\u6807\u7cfb\u7684\u5750\u6807\n    // \u95ee\u9898\uff1a\u4e0d\u9700\u8981\u7b2c2\u4e2aview\u7684depth\u56fe\uff1f\n    // \u539f\u56e0\uff1a3D2D\u6c42\u89e3\uff0c\u4e00\u822cassume first image\u662f\u4e16\u754c\u5750\u6807\u7cfb\uff0c\u56e0\u6b64\u53ea\u9700\u8981second image\u76842d\u5750\u6807\u5373\u53ef\uff01\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED ); // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    // \u7528\u4e8e\u5b58\u50a8\u4e16\u754c\u5750\u6807\u7cfb\u76843D\u70b9\n    vector<Point3f> pts_3d;\n    vector<Point2f> pts_2d;\n    // \u51c6\u5907solve_pnp\u7684\u8f93\u5165\uff0c\u5206\u522b\u662f2d\u548c3d\u7684\u5339\u914d\u5bf9\uff0c\u5176\u4e2d3d\u5373\u4e3a\u7b2c1\u4e2aview\u7684\u4e16\u754c\u5750\u6807\u7cfb\u4e0b\u7684\u5750\u6807\u503c\n    for ( DMatch m:matches )\n    {\n        // ()[]\u662f\u57fa\u672c\u7684mat\u64cd\u4f5c\uff0c\u53d6\u6570\u636e\u503c\u7684\u65b9\u6cd5\n        // []()\u662fLambda expression\n        // \u9996\u5148\u5b9a\u4e49\u4e86\u4e00\u4e2a\u6307\u9488d1.ptr<..> (int i)\uff0c\u8868\u793a\u7b2ci\u884c\n        // \u7136\u540e\u6839\u636e\u9996\u5730\u5740\uff0c\u53d6\u5176\u4e2d\u7684\u5143\u7d20\uff0c\u76f4\u63a5\u8c03\u53d6\u7b2cj\u4e2a\u5143\u7d20\uff0c\u4ece\u800c\u83b7\u5f97\u4e86\u6df1\u5ea6\u503c\n        ushort d = d1.ptr<unsigned short> (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n        // VIP\uff1adepth\u5f02\u5e38\u503c\u5904\u7406\uff0c\u76f4\u63a5\u8df3\u8fc7\n        if ( d == 0 )   // bad depth\n            continue;\n        // TUM\u5b9a\u4e49\uff1aThe depth images are scaled by a factor of 5000\n        // \u4e0d\u540c\u7684dataset\u7684\u8bbe\u5b9a\u4e0d\u540c\uff0c\u4e4b\u540e\u81ea\u5df1\u5b9e\u73b0\u8981\u6ce8\u610f\u7ec6\u8282\n        float dd = d/5000.0;\n        // \u56fe\u50cf\u5750\u6807\u7cfb\u8f6c\u5316\u6210\u76f8\u673a\u5750\u6807\u7cfb\u7684\u5f52\u4e00\u5316\u5750\u6807\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n        // \u518d\u8f6c\u6210\u76f8\u673a\u5750\u6807\u7cfb\u7684\u5750\u6807\n        pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );\n        // \u95ee\u9898\uff1atrainIdx\u548cqueryIdx\u7684\u533a\u522b\uff1f\n        // queryIdx refers to keypoints1 and trainIdx refers to keypoints2\n        pts_2d.push_back ( keypoints_2[m.trainIdx].pt );\n    }\n    cout<<\"3d-2d pairs: \"<<pts_3d.size() <<endl;\n    \n    \n    Mat r, t;\n    // OutputArray\u5728opencv\u91cc\u662f\u4e00\u4e2atemplate\uff0c_OutputArray (Mat &m)\n    // InputArray\u662f_InputArray (const Mat &m)\uff0c\u52a0\u4e86const\u4fdd\u8bc1\u4e0d\u80fd\u4fee\u6539\u8f93\u5165\n    // \u8f93\u5165\u9700\u8981intrinsic matrix\uff0c\u7528\u4e8e\u6295\u5f71\u53d8\u6362\n    // \u5176\u4e2d\uff0cMat()\u5bf9\u5e94distortion matrix\n    // \u9ed8\u8ba4\u65b9\u6cd5\uff1aSOLVEPNP_EPNP\uff0c\u8fd9\u4e2a\u4e0d\u597d\u89e3\uff0c\u7ed3\u679c\u4e0d\u7a33\u5b9a\uff01\n    // TO-DO: \u56de\u5934\u81ea\u5df1\u4e5f\u91cd\u65b0\u5199\u4e0b\u5e95\u5c42\u7684\u5b9e\u73b0\n    solvePnP ( pts_3d, pts_2d, K, Mat(), r, t, false ); // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    // \u8f93\u51fa\u7684r\u662f\u4e00\u4e2a\u5411\u91cf\n    cout<<\"r: \"<<r<<\" t: \"<<t<<endl;\n    Mat R;\n    // opencv\u5b9e\u73b0\u4e86\u7f57\u5fb7\u91cc\u683c\u65af\u516c\u5f0f\uff0c\u5c06\u65cb\u8f6c\u5411\u91cf\u8f6c\u6362\u4e3a\u65cb\u8f6c\u77e9\u9635\n    cv::Rodrigues ( r, R ); // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\n    // R=\n    // [0.9979193252225623, -0.05138618904650231, 0.03894200717249974;\n    //  0.05033852907726567, 0.9983556574294724, 0.02742286945057129;\n    //  -0.04028712992610883, -0.02540552801740052, 0.998865109165634]\n    // t=\n    // [-0.1255867099726712;\n    //  -0.007363525262960201;\n    //  0.06099926588593754]\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n    \n\n    cout<<\"calling bundle adjustment\"<<endl;\n    // \u95ee\u9898: PNP\u95ee\u9898\u4e0d\u5c31\u662f\u7528ba\u89e3\u7684\u5417\uff1f\u4e3a\u4f55\u91cd\u590d\u4e24\u6b21\u64cd\u4f5c\uff1f\n    // \u4e00\u822c\u662f\u62ff\u666e\u901a\u89e3\u6cd5\uff08\u5982P3P\u6216EPNP\uff09\u5f97\u5230\u4e00\u4e2a\u597d\u7684\u521d\u503c\uff0c\u7528BA\u505a\u8fdb\u4e00\u6b65\u4f18\u5316\n    // \u5982\u679c\u76f4\u63a5\u7528BA\u4f1a\u62a5segment fault:11\uff0c\u662f\u5185\u5b58\u7528\u5c3d\n    // \u8bf4\u660e\u521d\u503c\u7ed9\u7684\u4e0d\u597d\uff0c\u65e0\u6cd5\u6536\u655b\n    // \u6709\u610f\u601d\u7684\u662f\uff0c\u6bcf\u6b21\u4f18\u5316\u7684\u7ed3\u679c\u662f\u4e00\u6837\u7684\uff0c\n    // \u800c\u4e14BA\u540e\u7ed3\u679c\u5dee\u5f97\u4e0d\u591a\uff0c\u8bf4\u660esolvepnp\u7684\u7ed3\u679c\u5df2\u7ecf\u4e0d\u9519\u4e86\uff01\n    bundleAdjustment ( pts_3d, pts_2d, K, R, t );\n    \n    // reprojection error\u7684\u5355\u4f4d\u4e3aPixel\n    float avg_err;\n    float error = 0;\n    for ( int i=0; i<pts_3d.size(); i++ )\n    {\n        // \u5c06p1_3d->\u7b2c2\u4e2aview\uff0c\u5f97\u5230p1_2_3d\n        Mat_<double> p1_2_3d = R * (Mat_<double>(3,1)<<pts_3d[i].x, pts_3d[i].y, pts_3d[i].z) + t;\n        // \u5c06p1_2_3d\u8f6c\u53d8\u62102d\u56fe\u50cf\u5750\u6807\u7cfb\uff0c\u5e94\u8be5\u4e0ep2\u63a5\u8fd1\n        Point2d p1_2_2d = cam2pixel(p1_2_3d, K);\n        // calculate error\n        float e = abs(p1_2_2d.x - pts_2d[i].x) + \n                  abs(p1_2_2d.y - pts_2d[i].y);\n        error += e;\n    }\n    // \u8bef\u5dee\u91cf\u7ea7\u5927\u6982\u662f\u6a2a\u7ad6\u5404\u5dee1.5\u4e2apixel\n    // \u90a3\u6bd42D2D\u8981\u591a\u554a\uff0c\u4e4b\u524d\u662f0.5\u4e2apixel\n    avg_err = error / pts_3d.size();\n    cout<<\"average error is \"<<avg_err<<endl;\n}\n\nvoid find_feature_matches ( const Mat& img_1, const Mat& img_2,\n                            std::vector<KeyPoint>& keypoints_1,\n                            std::vector<KeyPoint>& keypoints_2,\n                            std::vector< DMatch >& matches )\n{\n    //-- \u521d\u59cb\u5316\n    Mat descriptors_1, descriptors_2;\n    // used in OpenCV3\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    // use this if you are in OpenCV2\n    // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n    // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n    //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist=10000, max_dist=0;\n\n    //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = match[i].distance;\n        if ( dist < min_dist ) min_dist = dist;\n        if ( dist > max_dist ) max_dist = dist;\n    }\n\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            matches.push_back ( match[i] );\n        }\n    }\n}\n\nPoint2d pixel2cam ( const Point2d& p, const Mat& K )\n{\n    return Point2d\n           (\n               ( p.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( p.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n}\n\n// 3d\u76f8\u673a\u5750\u6807\u7cfb\u8f6c\u6362\u62102d\u56fe\u50cf\u5750\u6807\u7cfb\nPoint2d cam2pixel ( const Mat& p, const Mat& K )\n{\n    return Point2d\n           (\n               p.at<double> ( 0,0 ) * K.at<double> ( 0,0 ) / p.at<double> ( 2,0 ) + K.at<double> ( 0,2 ),\n               p.at<double> ( 1,0 ) * K.at<double> ( 0,0 ) / p.at<double> ( 2,0 ) + K.at<double> ( 1,2 )\n           );\n}\n\n// \u7528\u5230\u4e86g2o\u6c42\u89e3\u5668\nvoid bundleAdjustment (\n    const vector< Point3f > points_3d,\n    const vector< Point2f > points_2d,\n    const Mat& K,\n    Mat& R, Mat& t )\n{\n    // \u521d\u59cb\u5316g2o\n    // pose:XYZ,3\u4e2a\u89d2\u5ea6;landmark:XYZ\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose \u7ef4\u5ea6\u4e3a 6, landmark \u7ef4\u5ea6\u4e3a 3\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // \u7ebf\u6027\u65b9\u7a0b\u6c42\u89e3\u5668\n    Block* solver_ptr = new Block ( linearSolver );     // \u77e9\u9635\u5757\u6c42\u89e3\u5668\n    // \u4ece\u7ed3\u679c\u4e0a\u6765\u770b\uff0c3D2D\u6bd43D3D\u8981\u96be\uff0c3D2D\u5fc5\u987b\u8981\u7ed9\u5b9a\u597d\u7684\u521d\u503c\uff0c\u800c3D3D\u8981\u6c42\u5f88\u5bbd\u677e\n    // \u4ece\u539f\u7406\u4e0a\uff0c\u662f\u56e0\u4e3aICP\u7684\u6781\u5c0f\u503c\u5c31\u662f\u5168\u5c40\u6700\u4f18\u503c\uff0c\u56e0\u6b64\u53ef\u4ee5\u4efb\u610f\u9009\u62e9\u521d\u503c\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n    // vertex\uff0c\u9996\u5148\u8bbe\u7f6e\u9876\u70b9\n    // se3\u7ecf\u8fc7\u6307\u6570\u6620\u5c04\u5f97\u5230SE3\n    // se3-\u674e\u4ee3\u6570\uff0cSE3-\u674e\u7fa4\n    // \u6700\u7ec8\u5e0c\u671b\u7528\u674e\u4ee3\u6570\uff0c\u5373se3\u8868\u793a\u7684\u76f8\u673a\u4f4d\u59ff\n    // \u4f7f\u7528g2o\u81ea\u5e26\u7684\u76f8\u673a\u4f4d\u59ff\u9876\u70b9\u7c7bVertexSE3Expmap\n    // SE3 Vertex parameterized internally with a transformation matrix\n    // and externally with its exponential map\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n    Eigen::Matrix3d R_mat;\n    // \u62f7\u8d1d\u4e00\u4e0brotation matrix\uff0c\u4e0d\u76f4\u63a5\u7528\u53ef\u80fd\u662f\u6015\u88ab\u4fee\u6539\u4e86\n    R_mat <<\n               R.at<double> ( 0,0 ), R.at<double> ( 0,1 ), R.at<double> ( 0,2 ),\n               R.at<double> ( 1,0 ), R.at<double> ( 1,1 ), R.at<double> ( 1,2 ),\n               R.at<double> ( 2,0 ), R.at<double> ( 2,1 ), R.at<double> ( 2,2 );\n    pose->setId ( 0 ); // \u9996\u5148\u8bbe\u7f6eId\n    // Quat\u5c31\u662fquaternion\uff0c\u56db\u5143\u6570\n    // sets the initial estimate from an array of double\n    // \u6b64\u5904\u9700\u8981\u5916\u754c\u7684\u521d\u59cb\u5316\uff0c\u56e0\u6b64\u5fc5\u987b\u5148\u7528solvepnp\n    // \u5f53\u7136\u4e5f\u53ef\u4ee5\u628a\u8fd9\u91cc\u7684\u521d\u503c\u4eba\u4e3a\u8bbe\u5b9a\u4e86\n    pose->setEstimate ( g2o::SE3Quat (\n                            R_mat,\n                            // translation vector\n                            Eigen::Vector3d ( t.at<double> ( 0,0 ), t.at<double> ( 1,0 ), t.at<double> ( 2,0 ) )\n                            // \u4ee5\u4e0b\u7528\u4e8e\u6d4b\u8bd5\uff0c\u5373\u7ed9\u5b9a\u4e00\u4e2a\u56fa\u5b9a\u7684\u521d\u503c\n                            // Eigen::Matrix3d::Identity(),\n                            // Eigen::Vector3d( 0,0,0 )\n                        ) );\n    optimizer.addVertex ( pose );\n\n    // \u52a0\u5b8c\u4e86pose\uff0c\u63a5\u4e0b\u6765\u52a03D\u5750\u6807\u70b9\n    int index = 1;\n    for ( const Point3f p:points_3d )   // landmarks\n    {\n        // 3D\u8def\u6807\u70b9\u7c7bVertexSBAPointXYZ\n        g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n        // \u8bbe\u7f6eId\n        point->setId ( index++ );\n        // \u8bbe\u7f6e\u521d\u59cb\u503c\uff0c\u5c06landmark\u5750\u6807\u8d4b\u503c\n        point->setEstimate ( Eigen::Vector3d ( p.x, p.y, p.z ) );\n        // TO-DO: \u7b49\u4e4b\u540e\u7814\u7a76\uff0c\u5373\u4e3amarginalization\n        point->setMarginalized ( true ); // g2o \u4e2d\u5fc5\u987b\u8bbe\u7f6e marg \u53c2\u89c1\u7b2c\u5341\u8bb2\u5185\u5bb9\n        // \u6700\u540e\u52a0\u5230optimizer\u91cc\u53bb\n        optimizer.addVertex ( point );\n    }\n\n    // parameter: camera intrinsics\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n        // f\u548c(cx,cy)\uff0c\u9ed8\u8ba4fx=fy\n        K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0\n    );\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // edges\uff0c\u7136\u540e\u8bbe\u7f6e\u8fb9\n    index = 1;\n    for ( const Point2f p:points_2d )\n    {\n        // \u91cd\u6295\u5f71\u8bef\u5dee\u8fb9\u7c7bEdgeProjectXYZ2UV\n        // \u628aXYZ\u6295\u5f71\u5230UV\u5e73\u9762\u4e0a\uff0c\u505a\u6210\u4e86\u4e00\u4e2a\u8bef\u5dee\n        // \u5728\u8fd9\u91cc\u6709\u4e00\u4e2acomputeError\u51fd\u6570\uff0c\u53ef\u4ee5\u770b\u5230reprojection error\u7684\u5b9a\u4e49\uff01\n        g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n        // \u8bbe\u7f6eId\n        edge->setId ( index );\n        // \u6bcf\u4e2a\u8fb9\u7684\u4e24\u4fa7\u5206\u522b\u662fpose\u548cLandmark\n        edge->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( index ) ) );\n        edge->setVertex ( 1, pose );\n        edge->setMeasurement ( Eigen::Vector2d ( p.x, p.y ) );\n        edge->setParameterId ( 0,0 );\n        edge->setInformation ( Eigen::Matrix2d::Identity() );\n        optimizer.addEdge ( edge );\n        index++;\n    }\n\n    // \u6700\u540e\u6c42\u89e3\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.setVerbose ( true ); // \u6253\u5f00\u8c03\u8bd5\u8f93\u51fa\n    optimizer.initializeOptimization();\n    optimizer.optimize ( 100 );\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> ( t2-t1 );\n    cout<<\"optimization costs time: \"<<time_used.count() <<\" seconds.\"<<endl;\n    cout<<endl<<\"after optimization:\"<<endl;\n    // \u8fd9\u91cc\u7684T\u8868\u793atransformation matrix\uff0c\u662f4*4\u7684\u77e9\u9635\n    cout<<\"Transformation matrix=\"<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;\n    // assign value to R,T\n    Eigen::Matrix4d output = Eigen::Isometry3d( pose->estimate() ).matrix();\n    Eigen::Matrix3d R_out = output.block(0,0,3,3); // \u5229\u7528Eigen\u7684block\u51fd\u6570\u83b7\u53d6\u5b50\u77e9\u9635\n    Eigen::Vector3d T_out = output.block(0,3,3,4);\n    cout<<\"R_out=\"<<endl<<R_out<<endl;\n    cout<<\"T_out=\"<<endl<<T_out<<endl;\n    // \u5c06eigen\u7684matrix\u548cvector\u5f62\u5f0f\u8f6c\u6362\u6210Mat\u683c\u5f0f\n    eigen2cv(R_out, R);\n    eigen2cv(T_out, t);\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"T=\"<<endl<<t<<endl;\n}\n", "meta": {"hexsha": "9dc06b5b8da6afe770c4f2f0f8fee1d326e5ff4e", "size": 12051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_stars_repo_name": "billamiable/slambook", "max_stars_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:27:43.000Z", "max_issues_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_issues_repo_name": "billamiable/slambook", "max_issues_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/pose_estimation_3d2d.cpp", "max_forks_repo_name": "billamiable/slambook", "max_forks_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T11:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T02:59:20.000Z", "avg_line_length": 36.7408536585, "max_line_length": 122, "alphanum_fraction": 0.6116504854, "num_tokens": 4650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6572269229128939}}
{"text": "/*MinimalFEM\n\nAuthor: Stanislav Pidhorskyi (Podgorskiy)\nstanislav@podgorskiy.com\nstpidhorskyi@mix.wvu.edu\n\nThe source code available here: https://github.com/podgorskiy/MinimalFEM/\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 Stanislav Pidhorskyi\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#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <string>\n#include <vector>\n#include <iostream>\n#include <fstream>\n\nstruct Element\n{\n\tvoid CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets);\n\n\tEigen::Matrix<float, 3, 6> B;\n\tint nodesIds[3];\n};\n\nstruct Constraint\n{\n\tenum Type\n\t{\n\t\tUX = 1 << 0,\n\t\tUY = 1 << 1,\n\t\tUXY = UX | UY\n\t};\n\tint node;\n\tType type;\n};\n\nint                      \tnodesCount;\nEigen::VectorXf          \tnodesX;\nEigen::VectorXf          \tnodesY;\nEigen::VectorXf          \tloads;\nstd::vector< Element >   \telements;\nstd::vector< Constraint >\tconstraints;\n\nvoid Element::CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector<Eigen::Triplet<float> >& triplets)\n{\n\tEigen::Vector3f x, y;\n\tx << nodesX[nodesIds[0]], nodesX[nodesIds[1]], nodesX[nodesIds[2]];\n\ty << nodesY[nodesIds[0]], nodesY[nodesIds[1]], nodesY[nodesIds[2]];\n\t\n\tEigen::Matrix3f C;\n\tC << Eigen::Vector3f(1.0f, 1.0f, 1.0f), x, y;\n\t\n\tEigen::Matrix3f IC = C.inverse();\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tB(0, 2 * i + 0) = IC(1, i);\n\t\tB(0, 2 * i + 1) = 0.0f;\n\t\tB(1, 2 * i + 0) = 0.0f;\n\t\tB(1, 2 * i + 1) = IC(2, i);\n\t\tB(2, 2 * i + 0) = IC(2, i);\n\t\tB(2, 2 * i + 1) = IC(1, i);\n\t}\n\tEigen::Matrix<float, 6, 6> K = B.transpose() * D * B * std::abs(C.determinant()) / 2.0f;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tEigen::Triplet<float> trplt11(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 0, K(2 * i + 0, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt12(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 1, K(2 * i + 0, 2 * j + 1));\n\t\t\tEigen::Triplet<float> trplt21(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 0, K(2 * i + 1, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt22(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 1, K(2 * i + 1, 2 * j + 1));\n\n\t\t\ttriplets.push_back(trplt11);\n\t\t\ttriplets.push_back(trplt12);\n\t\t\ttriplets.push_back(trplt21);\n\t\t\ttriplets.push_back(trplt22);\n\t\t}\n\t}\n}\n\nvoid SetConstraints(Eigen::SparseMatrix<float>::InnerIterator& it, int index)\n{\n\tif (it.row() == index || it.col() == index)\n\t{\n\t\tit.valueRef() = it.row() == it.col() ? 1.0f : 0.0f;\n\t}\n}\n\nvoid ApplyConstraints(Eigen::SparseMatrix<float>& K, const std::vector<Constraint>& constraints)\n{\n\tstd::vector<int> indicesToConstraint;\n\n\tfor (std::vector<Constraint>::const_iterator it = constraints.begin(); it != constraints.end(); ++it)\n\t{\n\t\tif (it->type & Constraint::UX)\n\t\t{\n\t\t\tindicesToConstraint.push_back(2 * it->node + 0);\n\t\t}\n\t\tif (it->type & Constraint::UY)\n\t\t{\n\t\t\tindicesToConstraint.push_back(2 * it->node + 1);\n\t\t}\n\t}\n\n\tfor (int k = 0; k < K.outerSize(); ++k)\n\t{\n\t\tfor (Eigen::SparseMatrix<float>::InnerIterator it(K, k); it; ++it)\n\t\t{\n\t\t\tfor (std::vector<int>::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit)\n\t\t\t{\n\t\t\t\tSetConstraints(it, *idit);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tif ( argc != 3 )\n    {\n        std::cout<<\"usage: \"<< argv[0] <<\" <input file> <output file>\\n\";\n        return 1;\n    }\n\t\n\tstd::ifstream infile(argv[1]);\n\tstd::ofstream outfile(argv[2]);\n\t\n\tfloat poissonRatio, youngModulus;\n\tinfile >> poissonRatio >> youngModulus;\n\n\tEigen::Matrix3f D;\n\tD <<\n\t\t1.0f,        \tpoissonRatio,\t0.0f,\n\t\tpoissonRatio,\t1.0,         \t0.0f,\n\t\t0.0f,        \t0.0f,        \t(1.0f - poissonRatio) / 2.0f;\n\n\tD *= youngModulus / (1.0f - pow(poissonRatio, 2.0f));\n\n\tinfile >> nodesCount;\n\tnodesX.resize(nodesCount);\n\tnodesY.resize(nodesCount);\n\n\tfor (int i = 0; i < nodesCount; ++i)\n\t{\n\t\tinfile >> nodesX[i] >> nodesY[i];\n\t}\n\n\tint elementCount;\n\tinfile >> elementCount;\n\n\tfor (int i = 0; i < elementCount; ++i)\n\t{\n\t\tElement element;\n\t\tinfile >> element.nodesIds[0] >> element.nodesIds[1] >> element.nodesIds[2];\n\t\telements.push_back(element);\n\t}\n\n\tint constraintCount;\n\tinfile >> constraintCount;\n\n\tfor (int i = 0; i < constraintCount; ++i)\n\t{\n\t\tConstraint constraint;\n\t\tint type;\n\t\tinfile >> constraint.node >> type;\n\t\tconstraint.type = static_cast<Constraint::Type>(type);\n\t\tconstraints.push_back(constraint);\n\t}\n\n\tloads.resize(2 * nodesCount);\n\tloads.setZero();\n\n\tint loadsCount;\n\tinfile >> loadsCount;\n\n\tfor (int i = 0; i < loadsCount; ++i)\n\t{\n\t\tint node;\n\t\tfloat x, y;\n\t\tinfile >> node >> x >> y;\n\t\tloads[2 * node + 0] = x;\n\t\tloads[2 * node + 1] = y;\n\t}\n\t\n\tstd::vector<Eigen::Triplet<float> > triplets;\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\n\t{\n\t\tit->CalculateStiffnessMatrix(D, triplets);\n\t}\n\n\tEigen::SparseMatrix<float> globalK(2 * nodesCount, 2 * nodesCount);\n\tglobalK.setFromTriplets(triplets.begin(), triplets.end());\n\n\tApplyConstraints(globalK, constraints);\n\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<float> > solver(globalK);\n\n\tEigen::VectorXf displacements = solver.solve(loads);\n\n\toutfile << displacements << std::endl;\n\n\tfor (std::vector<Element>::iterator it = elements.begin(); it != elements.end(); ++it)\n\t{\n\t\tEigen::Matrix<float, 6, 1> delta;\n\t\tdelta << displacements.segment<2>(2 * it->nodesIds[0]),\n\t\t         displacements.segment<2>(2 * it->nodesIds[1]),\n\t\t         displacements.segment<2>(2 * it->nodesIds[2]);\n\n\t\tEigen::Vector3f sigma = D * it->B * delta;\n\t\tfloat sigma_mises = sqrt(sigma[0] * sigma[0] - sigma[0] * sigma[1] + sigma[1] * sigma[1] + 3.0f * sigma[2] * sigma[2]);\n\n\t\toutfile << sigma_mises << std::endl;\n\t}\n\treturn 0;\n}", "meta": {"hexsha": "803ee3b42929d1b7cbfb86d193199bdfdbf68817", "size": 6554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "podgorskiy/MinimalFem", "max_stars_repo_head_hexsha": "a9b559da28c8466b76e0ad30325925238ebca7a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-01T14:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-06T01:36:27.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "podgorskiy/MinimalFem", "max_issues_repo_head_hexsha": "a9b559da28c8466b76e0ad30325925238ebca7a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-18T02:30:10.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-04T13:00:39.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "podgorskiy/MinimalFem", "max_forks_repo_head_hexsha": "a9b559da28c8466b76e0ad30325925238ebca7a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-03-22T08:17:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T03:49:51.000Z", "avg_line_length": 27.5378151261, "max_line_length": 121, "alphanum_fraction": 0.6461702777, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6572269209157786}}
{"text": "// fir_filter.cpp example program showing a FIR filter using error-free custom posit configurations\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPR-DSP project, which is released under an MIT Open Source license.\n\n#define MTL_INITIALIZER_LISTS\n#include <boost/numeric/mtl/mtl.hpp>\n// select and configure the number system \n#include <universal/posit/posit>\n\n\nconst double pi = 3.14159265358979323846;  // best practice for C++\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\tint nrOfFailedTestCases = 0;\n\n\tposit<nbits, es> p;\n\tvector< posit<nbits, es> > sinusoid(vecSize), weights(vecSize);\n\n\tfor (int i = 0; i < vecSize; i++) {\n\t\tsinusoid[i] = sin((float(i) / float(vecSize)) *2.0 * pi);\n\n\t\tweights[i] = 0.5f;\n\t}\n\n\t// dot product\n\tposit<nbits, es> fir;\n\tfir = 0.0f;\n\tfor (int i = 0; i < vecSize; i++) {\n\t\tfir += sinusoid[i] * weights[i];\n\t}\n\tcout << \"Value is \" << fir << endl;\n\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << 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": "ccf77c1f41524303a1b4ee9a7a585b7db4cdd200", "size": 1386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/dsp/fir_filter.cpp", "max_stars_repo_name": "stillwater-sc/hpr-dsp", "max_stars_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/dsp/fir_filter.cpp", "max_issues_repo_name": "stillwater-sc/hpr-dsp", "max_issues_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/dsp/fir_filter.cpp", "max_forks_repo_name": "stillwater-sc/hpr-dsp", "max_forks_repo_head_hexsha": "54d5e469367c81ab851a7bbdbd0d11a4df9fb214", "max_forks_repo_licenses": ["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.75, "max_line_length": 99, "alphanum_fraction": 0.6746031746, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.870597268408361, "lm_q2_score": 0.7549149813536516, "lm_q1q2_score": 0.6572269206470379}}
{"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#include <stapl/array.hpp>\n#include <stapl/algorithm.hpp>\n#include <stapl/utility/do_once.hpp>\n#include <boost/lexical_cast.hpp>\n\ntypedef unsigned long long ulong_type;\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Determines whether a number is fibonacci or not.\n///        If the fibonacci number is even, we then keep the number.\n///        If the number is not fibonacci number and even, 0 is returned.\n////////////////////////////////////////////////////////////////////////////////\nstruct not_even_fib\n{\n  typedef ulong_type result_type;\n  template <typename T>\n  ulong_type operator()(T i)\n  {\n    // Statements used to determine if a number is Fibonacci or not is\n    //   (5*(N^2))-4 OR (5*(N^2))+4\n    //   If the result of either statement is a perfect square number,\n    //   Then N is a fibonacci number.\n    ulong_type fib_check_1 = 5 * (static_cast <ulong_type>(\n      pow(static_cast <long double>(i), 2.0))) - 4;\n    ulong_type fib_check_2 = 5 * (static_cast <ulong_type>(\n      pow(static_cast <long double>(i), 2.0))) + 4;\n\n    // Square root taken to determine if the number is a perfect square.\n    ulong_type root_1 = static_cast <ulong_type>(\n      sqrt(static_cast<long double>(fib_check_1)));\n    ulong_type root_2 = static_cast <ulong_type>(\n      sqrt(static_cast<long double>(fib_check_2)));\n\n    // Checks if the number is even and verifies as a perfect square\n    //   number.\n    if ((root_1 * root_1 == fib_check_1 ||\n         root_2 * root_2 == fib_check_2) && (i%2 == 0))\n      return i;\n\n   return 0;\n  }\n};\n\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n  ulong_type num = boost::lexical_cast<ulong_type> (argv[1]);\n\n  // Creates a non-storage view in counting order from 1 to n.\n  auto view_2 = stapl::counting_view<ulong_type>(num, 1);\n\n  // Maps not_even_fib functor to set numbers in the view that are not\n  //   divisible by 3 or 5 to 0. Then stapl::plus is called to add the numbers\n  //   in the view.\n  ulong_type ans = stapl::map_reduce(\n   not_even_fib(), stapl::plus<ulong_type>(), view_2\n  );\n\n  // Prints the total sum.\n  stapl::do_once([&]{\n    std::cout << \"The total is: \" << ans << std::endl;\n  });\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "57aca88d23798e3af01639a8efc2b0c3d19b3bff", "size": 2601, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_2b.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_2b.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_2b.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": 33.7792207792, "max_line_length": 80, "alphanum_fraction": 0.6370626682, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6572269206470379}}
{"text": "\n#include <Eigen/Geometry>\n\n#include <sphericalsfm/sfm_types.h>\n#include <sphericalsfm/so3.h>\n\nnamespace sphericalsfm {\n    Pose::Pose()\n    : t( Eigen::Vector3d::Zero() ), r( Eigen::Vector3d::Zero() ), P( Eigen::Matrix4d::Identity() )\n    {\n        \n    }\n\n    Pose::Pose( const Eigen::Vector3d &_t, const Eigen::Vector3d &_r )\n    : t( _t ), r( _r ), P( Eigen::Matrix4d::Identity() )\n    {\n        P.block<3,3>(0,0) = so3exp(r);\n        P.block<3,1>(0,3) = t;\n    }\n\n    Pose Pose::inverse() const\n    {\n        Pose poseinv;\n        poseinv.P.block<3,3>(0,0) = P.block<3,3>(0,0).transpose();\n        poseinv.t = -P.block<3,3>(0,0).transpose()*t;\n        poseinv.r = -r;\n        poseinv.P.block<3,1>(0,3) = poseinv.t;\n        return poseinv;\n    }\n\n    void Pose::postMultiply( const Pose &pose )\n    {\n        P = P * pose.P;\n        t = P.block<3,1>(0,3);\n        r = so3ln( P.block<3,3>(0,0) );\n    }\n\n    Point Pose::apply( const Point &point ) const\n    {\n        return P.block<3,3>(0,0) * point + t;\n    }\n\n    Point Pose::applyInverse( const Point &point ) const\n    {\n        return P.block<3,3>(0,0).transpose() * ( point - t );\n    }\n\n    Eigen::Vector3d Pose::getCenter() const\n    {\n        return P.block<3,3>(0,0).transpose() * (-t);\n    }\n}\n", "meta": {"hexsha": "02f3235715e5b5f13fcf6af89487b73cf7cb3ca8", "size": 1259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sfm_types.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/sfm_types.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/sfm_types.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": 23.7547169811, "max_line_length": 98, "alphanum_fraction": 0.5218427323, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6572269155778441}}
{"text": "#include \"sir.h\"\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing State = boost::array<double, 3>;\nusing Stepper = boost::numeric::odeint::runge_kutta_dopri5<State>;\n\ndouble smooth_trans(double u0, double u1, double t, double tc, double teps)\n{\n  const double t0 = tc - teps;\n  const double t1 = tc + teps;\n  return t <= t0 ? u0 : t >= t1 ? u1 : u0 + (u1 - u0) * (1 - std::cos(M_PI / (t1 - t0) * (t - t0))) * 0.5;\n}\n\ndouble linear_trans(double u0, double u1, double t, double tc, double teps)\n{\n  const double t0 = tc - teps;\n  const double t1 = tc + teps;\n  return t <= t0 ? u0 : t >= t1 ? u1 : u0 + (u1 - u0) * (t - t0) / (t1 - t0);\n}\n\nstatic auto make_sir_rhs(double N, double beta, double gamma, double tint, double dint, double kbeta)\n{\n  /// RHS of the SIR model. We preprocess beta/N for efficiency.\n  return [beta_over_N = beta / N, gamma, tint, dint, kbeta](const State &x, State &dxdt, double t) {\n    double S = x[0];\n    double I = x[1];\n    double R = x[2];\n\n    //auto trans = smooth_trans;\n    auto trans = linear_trans;\n    const double b_N = beta_over_N * trans(1., kbeta, t, tint, dint * 0.5);\n    double A = b_N * S * I;\n    double B = gamma * I;\n    dxdt[0] = -A;\n    dxdt[1] = A - B;\n    dxdt[2] = B;\n  };\n}\n\n/**\n    Arguments:\n        S0, I0, R0: Initial state (at day=0)\n        days: Number of days to evaluate.\n        N: Population\n        beta, gamma: SIR parameters\n\n    Return value:\n        Array {N - S(t) | t = 1, ..., days}\n  */\nstd::vector<double>\nsir_infected_so_far(double S0, double I0, double R0, int days, long long N, double beta, double gamma, double tint, double dint, double kbeta)\n{\n  const int steps_per_day = 10;\n  const double dt = 1.0 / steps_per_day;\n\n  auto rhs = make_sir_rhs(N, beta, gamma, tint, dint, kbeta);\n\n  std::vector<double> result;\n  result.reserve(days);\n\n  // Observer gets called for each time step evaluated by the integrator.\n  // We consider only every `steps_per_day` steps\n  // (skipping the first one as well), and store N - S(t).\n  auto observer = [&result, N, cnt = 0](State y, double t) mutable {\n    if (cnt % steps_per_day == 0 && cnt > 0)\n    {\n      // printf(\"t=%g  y=%g %g %g\\n\", t, y[0], y[1], y[2]);\n      result.push_back(N - y[0]);\n    }\n    ++cnt;\n  };\n\n  State y0{S0, I0, R0};\n  boost::numeric::odeint::integrate_n_steps(\n    Stepper{}, rhs, y0, 0.0, dt, days * steps_per_day, observer);\n  return result;\n}\n", "meta": {"hexsha": "2af7f796c1044ef6e0859ec7ae43c30aadb2e242", "size": 2414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/study.cases/covid19/src/cpp/sir.cpp", "max_stars_repo_name": "JonathanLehner/korali", "max_stars_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2018-07-26T07:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:23:12.000Z", "max_issues_repo_path": "examples/study.cases/covid19/src/cpp/sir.cpp", "max_issues_repo_name": "JonathanLehner/korali", "max_issues_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212.0, "max_issues_repo_issues_event_min_datetime": "2018-09-21T10:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:33:05.000Z", "max_forks_repo_path": "examples/study.cases/covid19/src/cpp/sir.cpp", "max_forks_repo_name": "JonathanLehner/korali", "max_forks_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T15:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:19:46.000Z", "avg_line_length": 30.5569620253, "max_line_length": 142, "alphanum_fraction": 0.6089478045, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6571970541656776}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2012 Dominic Marcello\n//  Copyright (c) 2012 Bryce Adelstein-Lelbach\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#if !defined(OCTOPUS_754BFB65_F28B_4F97_83FF_69C5DEAB500F)\n#define OCTOPUS_754BFB65_F28B_4F97_83FF_69C5DEAB500F\n\n#include <octopus/assert.hpp>\n#include <octopus/trivial_serialization.hpp>\n#include <octopus/state.hpp>\n\n#include <boost/cstdint.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\nnamespace octopus\n{\n\ntemplate <typename T>\ninline bool compare_real(T x, T y)\n{\n    T const epsilon = std::numeric_limits<T>::epsilon();\n \n    if ((x + epsilon >= y) && (x - epsilon <= y))\n        return true;\n    else\n        return false;\n}\n\ntemplate <typename T>\ninline bool compare_real(T x, T y, T epsilon)\n{\n    if ((x + epsilon >= y) && (x - epsilon <= y))\n        return true;\n    else\n        return false;\n}\n\ntemplate <typename T>\ninline boost::uint64_t hex_real(T x)\n{\n    boost::uint64_t* hex = (boost::uint64_t*) &x;\n    return *hex;\n}\n\ninline double maximum(double a, double b)\n{\n    return (std::max)(a, b);\n}\n\ninline double maximum(double a, double b, double c)\n{\n    return (std::max)(a, (std::max)(b, c));\n}\n\ninline double minimum(double a, double b)\n{\n    return (std::min)(a, b);\n}\n\ninline double minimum(double a, double b, double c)\n{\n    return (std::min)(a, (std::min)(b, c));\n}\n\n// Serializable minimum\nstruct minimum_functor : octopus::trivial_serialization\n{\n    template <typename T>\n    T const& operator()(T const& a, T const& b) const\n    {\n        return (std::min)(a, b);\n    }\n};\n\n// Serializable maximum\nstruct maximum_functor : octopus::trivial_serialization\n{\n    template <typename T>\n    T const& operator()(T const& a, T const& b) const\n    {\n        return (std::max)(a, b);\n    }\n};\n\ntemplate <typename T>\ninline T sign(T a)\n{\n    if (a > 0) \n        return 1;\n    else if (a < 0) \n        return -1;\n    else \n        return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////\ninline double minmod(double a, double b)\n{\n    return 0.5 * (sign(a) + sign(b)) * (std::min)(std::fabs(a), std::fabs(b));\n}\n\ninline double minmod(double a, double b, double c)\n{\n    return minmod(a, minmod(b, c));\n}\n\ninline double minmod_theta(double a, double b, double theta)\n{\n    return minmod(theta * a, theta * b, 0.5 * (a + b));\n}\n\n///////////////////////////////////////////////////////////////////////////////\ntemplate <std::size_t Size, typename Rep0, typename Rep1>\ninline array<double, Size> minmod(\n    array<double, Size, Rep0> const& v1\n  , array<double, Size, Rep1> const& v2\n    )\n{\n    //OCTOPUS_ASSERT(v1.size() == v2.size());\n\n    array<double, Size> mm;\n    //mm.reserve(v1.size());\n\n    for (std::size_t i = 0; i < v1.size(); ++i) \n        mm[i] = minmod(v1[i], v2[i]);\n\n    return mm;\n}\n\ntemplate <std::size_t Size, typename Rep0, typename Rep1, typename Rep2>\ninline array<double, Size> minmod(\n    array<double, Size, Rep0> const& v1\n  , array<double, Size, Rep1> const& v2\n  , array<double, Size, Rep2> const& v3)\n{\n    //OCTOPUS_ASSERT(v1.size() == v2.size());\n    //OCTOPUS_ASSERT(v1.size() == v3.size());\n\n    array<double, Size> mm;\n    //mm.reserve(v1.size());\n\n    for (std::size_t i = 0; i < v1.size(); ++i) \n        mm[i] = minmod(v1[i], v2[i], v3[i]);\n\n    return mm;\n}\n\ntemplate <std::size_t Size, typename Rep0, typename Rep1>\ninline array<double, Size> minmod_theta(\n    array<double, Size, Rep0> const& v1\n  , array<double, Size, Rep1> const& v2\n  , double theta\n    )\n{\n    OCTOPUS_ASSERT(v1.size() == v2.size());\n\n    array<double, Size> mm;\n    //mm.reserve(v1.size());\n\n    for (std::size_t i = 0; i < v1.size(); ++i) \n        mm[i] = minmod(\n            theta * v1[i]\n          , theta * v2[i]\n          , 0.5 * (v1[i] + v2[i]));\n\n    return mm;\n}\n\n}\n\n#endif // OCTOPUS_754BFB65_F28B_4F97_83FF_69C5DEAB500F\n\n", "meta": {"hexsha": "fd5e38a635e1744fcce4f0ba8d8c556184fc07a1", "size": 4119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "octopus/math.hpp", "max_stars_repo_name": "STEllAR-GROUP/octopus", "max_stars_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-30T14:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-19T19:03:19.000Z", "max_issues_repo_path": "octopus/math.hpp", "max_issues_repo_name": "STEllAR-GROUP/octopus", "max_issues_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "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": "octopus/math.hpp", "max_forks_repo_name": "STEllAR-GROUP/octopus", "max_forks_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8833333333, "max_line_length": 80, "alphanum_fraction": 0.5685846079, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6571970445241401}}
{"text": "#include <Eigen/Dense>\n\n#include \"LJLike_0.hpp\"\n\n\nstruct ModelSystem {\n  // Calculate the objective function value at position x.\n  double value(const Eigen::VectorXd& x) const;\n\n  // Calculate the gradient at position x.\n  Eigen::VectorXd gradient(const Eigen::VectorXd& x) const;\n\n  // Get the initial step length in the direction of p.\n  double initial_step_length(\n      const Eigen::VectorXd& x, // the current set of parameters\n      const Eigen::VectorXd& p  // the current search direction\n  ) const;\n\n  // Check if change from old to new parameter set is acceptable.\n  double change_acceptable(\n      const Eigen::VectorXd& x_old, // the current set of parameters\n      const Eigen::VectorXd& x_new  // the new set of parameters\n  ) const;\n\n  // Convert representation to Cartesian coordinates.\n  Eigen::Vector2d to_cartesian(const Eigen::VectorXd& x) const;\n\n  ModelSystem(const Eigen::Vector2d& x0 = Eigen::Vector2d(1.0, 1.0));\n\n  Eigen::Vector2d x0;\n  double d_max = 0.5;\n  double r;\n\n  AutoGeneratedSplines::LJLike_0::Spline spline;\n};\n", "meta": {"hexsha": "d9f0beab55aec499c3b90d6aba42a492c48ed2fb", "size": 1049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PaperExamples/ModelSystem.hpp", "max_stars_repo_name": "flachsenberg/LSLOpt", "max_stars_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T14:09:06.000Z", "max_issues_repo_path": "src/PaperExamples/ModelSystem.hpp", "max_issues_repo_name": "flachsenberg/LSLOpt", "max_issues_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "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/PaperExamples/ModelSystem.hpp", "max_forks_repo_name": "flachsenberg/LSLOpt", "max_forks_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T12:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:12:51.000Z", "avg_line_length": 29.1388888889, "max_line_length": 69, "alphanum_fraction": 0.7149666349, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6571970395520187}}
{"text": "#include \"fast_mass_springs_precomputation_dense.h\"\n#include \"signed_incidence_matrix_dense.h\"\n#include <Eigen/Dense>\n\nbool fast_mass_springs_precomputation_dense(\n  const Eigen::MatrixXd & V,\n  const Eigen::MatrixXi & E,\n  const double k,\n  const Eigen::VectorXd & m,\n  const Eigen::VectorXi & b,\n  const double delta_t,\n  Eigen::VectorXd & r,\n  Eigen::MatrixXd & M,\n  Eigen::MatrixXd & A,\n  Eigen::MatrixXd & C,\n  Eigen::LLT<Eigen::MatrixXd> & prefactorization)\n{\n  /////////////////////////////////////////////////////////////////////////////\n  // Set up the list of edge lengths (rest spring length)\n  r.resize(E.rows());\n  for (int e = 0; e < E.rows(); e++) {\n    int i = E(e, 0);\n    int j = E(e, 1);\n\n    // Eigen::Vector3d p0(V(i, 0), V(i, 1), V(i, 2));\n    Eigen::Vector3d p_i = V.row(i);\n    Eigen::Vector3d p_j = V.row(j);\n\n    // Set r\n    r(e) = (p_i - p_j).norm();\n  }\n\n  // Get the mass matrix\n  M = m.asDiagonal();\n\n  // Get the signed incidence matrix A\n  signed_incidence_matrix_dense(V.rows(), E, A);\n\n  // Set the selection matrix\n  C = Eigen::MatrixXd::Zero(b.size(), V.rows());\n  for (int i = 0; i < b.size(); i++) {\n    for (int j = 0; j < V.rows(); j++) {\n      if (b(i) == j) {\n        C(i, j) = 1;\n      } else {\n        C(i, j) = 0;\n      }\n    }\n  }\n\n  // Compute W = w C^T * C                         See iPad\n  Eigen::MatrixXd W = 1.0e10 * C.transpose() * C;\n\n  // Compute Q --- NOTE: We add W to Q for the pinned vertices\n  Eigen::MatrixXd Q = k * A.transpose() * A + (1.0 / pow(delta_t, 2.0)) * M + W;\n  /////////////////////////////////////////////////////////////////////////////\n  prefactorization.compute(Q);\n  return prefactorization.info() != Eigen::NumericalIssue;\n}\n", "meta": {"hexsha": "75a27e0c48a2ba3b9b858cceff73bb001ce7d22e", "size": 1706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fast_mass_springs_precomputation_dense.cpp", "max_stars_repo_name": "ericpko/computer-graphics-mass-spring-systems", "max_stars_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_stars_repo_licenses": ["MIT"], "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/fast_mass_springs_precomputation_dense.cpp", "max_issues_repo_name": "ericpko/computer-graphics-mass-spring-systems", "max_issues_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_issues_repo_licenses": ["MIT"], "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/fast_mass_springs_precomputation_dense.cpp", "max_forks_repo_name": "ericpko/computer-graphics-mass-spring-systems", "max_forks_repo_head_hexsha": "9cb5875745bded1a6bb854556139a294927ce330", "max_forks_repo_licenses": ["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.4333333333, "max_line_length": 80, "alphanum_fraction": 0.5240328253, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6571970348826025}}
{"text": "#include \"gtest.h\"\n\n#include <fstream>\n#include <utility>\n#include <iomanip>\n\n#include <Eigen/MPRealSupport>\n#include <Eigen/SVD>\n#include <irlib/common.hpp>\n#include <irlib/detail/gauss_legendre.hpp>\n#include <irlib/detail/legendre_polynomials.hpp>\n\nusing namespace irlib;\n\nTEST(mpmath, cast) {\n    ir_set_default_prec<mpreal>(167);\n\n    for (int i=0; i<100; ++i) {\n        ASSERT_TRUE(mpreal(i) - mpreal(std::to_string(i)) == 0);\n    }\n\n    ASSERT_TRUE(mpreal(0.5) - mpreal(\"0.5\") == 0);\n\n}\n\nTEST(mpmath, SVD) {\n\n    ir_set_default_prec<mpreal>(167);\n\n    //mpreal x{1};\n    //test<mpreal>(x, x);\n    //make_pair_test<mpreal,mpreal>(x, x);\n\n    // Declare matrix and vector types with multi-precision scalar type\n    typedef Eigen::Matrix<mpreal,Eigen::Dynamic,Eigen::Dynamic>  MatrixXmp;\n    typedef Eigen::Matrix<mpreal,Eigen::Dynamic,1>        VectorXmp;\n\n    int N = 10;\n    MatrixXmp A = MatrixXmp::Random(N,N);\n    VectorXmp b = VectorXmp::Random(N);\n\n    Eigen::BDCSVD<MatrixXmp> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    ASSERT_TRUE(svd.matrixU().rows() == N);\n    ASSERT_TRUE(svd.matrixU().cols() == N);\n    ASSERT_TRUE(svd.matrixV().rows() == N);\n    ASSERT_TRUE(svd.matrixV().cols() == N);\n    MatrixXmp A_reconst = svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().adjoint();\n\n    ASSERT_TRUE((A - A_reconst).cwiseAbs().maxCoeff() < 1e-40);\n}\n\nTEST(mpmath, gauss_legenre) {\n    ir_set_default_prec<mpreal>(167);\n\n    //Integrate x**2 over [-1, 1]\n    for (int degree : std::vector<int>{6, 12, 24}) {\n        std::vector<std::pair<mpreal,mpreal>> nodes = irlib::detail::gauss_legendre_nodes<mpreal>(degree);\n\n        mpreal sum = 0.0;\n        for (auto n : nodes) {\n            sum += (n.first*n.first) * n.second;\n        }\n        ASSERT_TRUE(abs(sum - mpreal(2.0)/mpreal(3.0)) < 1e-48);\n    }\n}\n\nTEST(mpmath, legendre_polynomials) {\n    ir_set_default_prec<mpreal>(167);\n\n    int Nl = 100;\n\n    mpreal x(\"0.5\");\n\n    std::vector<mpreal> vals(Nl);\n\n    for (int l=0; l<Nl; ++l) {\n        vals[l] = irlib::legendre_p(l, x);\n    }\n\n    for (int l=1; l<Nl-1; ++l) {\n        auto mp_l(l);\n        auto left_side = (mp_l+1) * vals[l+1];\n        auto right_side = (2*mp_l+1) * x * vals[l] - mp_l * vals[l-1];\n        ASSERT_TRUE(abs(left_side-right_side) < 1e-40);\n    }\n}\n\n\nTEST(mpmath, normalized_legendre_polynomials_derivatives) {\n    ir_set_default_prec<mpreal>(167);\n\n    int Nl = 3;\n    mpreal x(1);\n    auto deriv = irlib::normalized_legendre_p_derivatives(Nl, x);\n\n    //0-th normalized Legendre polynomial\n    ASSERT_TRUE(abs(deriv[0][0]-1/sqrt(2)) < 1e-40);\n    ASSERT_TRUE(abs(deriv[0][1]) < 1e-40);\n\n    //1-th normalized Legendre polynomial\n    ASSERT_TRUE(abs(deriv[1][0]-sqrt(mpreal(3)/mpreal(2))) < 1e-40);\n    ASSERT_TRUE(abs(deriv[1][1]-sqrt(mpreal(3)/mpreal(2))) < 1e-40);\n\n    //2-th normalized Legendre polynomial\n    auto f0 = sqrt(mpreal(5)/mpreal(2));\n    auto f1 = sqrt(mpreal(5)/mpreal(2)) * mpreal(3);\n    ASSERT_TRUE(abs(deriv[2][0]-f0) < 1e-40);\n    ASSERT_TRUE(abs(deriv[2][1]-f1) < 1e-40);\n    ASSERT_TRUE(abs(deriv[2][2]-f1) < 1e-40);\n\n}\n\n/*\nTEST(mpmath, io) {\n    ir_set_default_prec<mpreal>(200);\n\n    mpreal mp_tmp = mpreal(\"0.000001\")/mpreal(\"3\");\n    ir_set_default_prec<mpreal>(20);\n\n    {\n        std::ofstream ofs(\"mp_math_io.txt\");\n        ofs << std::setprecision(mpfr::bits2digits(mp_tmp.get_prec())) << mp_tmp << std::endl;\n        std::cout << std::setprecision(mpfr::bits2digits(mp_tmp.get_prec())) << mp_tmp << std::endl;\n    }\n\n    {\n        mpreal mp_tmp2;\n        std::ifstream ifs(\"mp_math_io.txt\");\n        ir_set_default_prec<mpreal>(20);\n        ifs >> mp_tmp2;\n\n\n        mpreal mp_tmp3 = mpreal(\"0.000001\")/mpreal(\"3\");\n        mpreal diff = mp_tmp - mp_tmp2;\n        std::cout << \"diff \" << mp_tmp.get_prec() << \" \" << mp_tmp2.get_prec() << \" \" << diff.get_prec() << \" \" << mp_tmp3.get_prec() << std::endl;\n        std::cout << std::setprecision(mpfr::bits2digits(mp_tmp.get_prec())) << mp_tmp - mp_tmp2 << std::endl;\n    }\n\n}\n*/\n", "meta": {"hexsha": "e18377e70213a8d5f08d8c31330ae033f97b324f", "size": 4025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test/mpmath.cpp", "max_stars_repo_name": "dombrno/irlib", "max_stars_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-09T09:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-23T20:16:05.000Z", "max_issues_repo_path": "c++/test/mpmath.cpp", "max_issues_repo_name": "dombrno/irlib", "max_issues_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-31T10:35:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T13:04:25.000Z", "max_forks_repo_path": "c++/test/mpmath.cpp", "max_forks_repo_name": "dombrno/irlib", "max_forks_repo_head_hexsha": "c081ac6af6d0f80424e6f3651f02ce5028942e0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-05-30T19:31:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T21:52:47.000Z", "avg_line_length": 28.5460992908, "max_line_length": 147, "alphanum_fraction": 0.6116770186, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6570348310253676}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/big/big_types.h>\n\n#include <OpenTissue/core/math/optimization/optimization_blocking_constraint_search.h>\n#include <OpenTissue/core/math/optimization/optimization_make_constant_bounds.h>\n#include <OpenTissue/core/math/optimization/optimization_bounds2constraint.h>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_blocking_constraint);\n\nBOOST_AUTO_TEST_CASE(compile_test_case)\n{\n  double tau = 0.0;\n  size_t blocking_idx = 1000;\n\n  ublas::vector<double> x;\n  ublas::vector<double> p;\n  ublas::vector<double> values;\n\n  x.resize(3,false);\n  p.resize(3,false);\n  values.resize(3,false);\n\n  values(0) = 1.0;\n  values(1) = 2.0;\n  values(2) = 3.0;\n  x(0) = 4.0;\n  x(1) = 4.0;\n  x(2) = 4.0;\n  p(0) = 0.0;\n  p(1) = -4.0;\n  p(2) = 0.0;\n\n  bool is_blocked = OpenTissue::math::optimization::blocking_constraint_search( \n    x\n    , p\n    , OpenTissue::math::optimization::make_constraint_from_lower_bounds( OpenTissue::math::optimization::make_constant_bounds( values ) )\n    , tau \n    , blocking_idx\n    );\n\n  BOOST_CHECK(is_blocked);\n  BOOST_CHECK(blocking_idx == 1);\n  BOOST_CHECK_CLOSE( tau, 0.5, 0.1 );\n\n  values(0) = -2.0;\n  values(1) = -2.0;\n  values(2) = -2.0;\n  x(0) = 0.0;\n  x(1) = 0.0;\n  x(2) = 0.0;\n  p(0) = -1.0;\n  p(1) = -1.0;\n  p(2) = -1.0;\n\n  is_blocked = OpenTissue::math::optimization::blocking_constraint_search( \n    x\n    , p\n    , OpenTissue::math::optimization::make_constraint_from_lower_bounds( OpenTissue::math::optimization::make_constant_bounds( values ) )\n    , tau \n    , blocking_idx\n    );\n\n  BOOST_CHECK(!is_blocked);\n  BOOST_CHECK(blocking_idx == 4);\n  BOOST_CHECK_CLOSE( tau, 1.0, 0.1 );\n\n  values(0) = 2.0;\n  values(1) = 2.0;\n  values(2) = 2.0;\n  x(0) = 0.0;\n  x(1) = 0.0;\n  x(2) = 0.0;\n  p(0) = 1.0;\n  p(1) = 4.0;\n  p(2) = 1.0;\n\n  is_blocked = OpenTissue::math::optimization::blocking_constraint_search( \n    x\n    , p\n    , OpenTissue::math::optimization::make_constraint_from_upper_bounds(   OpenTissue::math::optimization::make_constant_bounds( values ) )\n    , tau \n    , blocking_idx\n    );\n\n  BOOST_CHECK(is_blocked);\n  BOOST_CHECK(blocking_idx == 1);\n  BOOST_CHECK_CLOSE( tau, 0.5, 0.1 );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2c719faa4714dc3c7a9f17d358d4d4053accaff9", "size": 2692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/optimization/blocking_constraint/src/unit_blocking_constraint.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/optimization/blocking_constraint/src/unit_blocking_constraint.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/optimization/blocking_constraint/src/unit_blocking_constraint.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 25.6380952381, "max_line_length": 139, "alphanum_fraction": 0.691307578, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6570348184719162}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_vector3_norm_1);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double,size_t> math_types;\n\n  typedef math_types::real_type        T;\n  typedef math_types::vector3_type     V;\n\n  V v0 = V(0.1, -0.01, 0.0 );\n  T n0 = OpenTissue::math::norm_1( v0 );\n  BOOST_CHECK_CLOSE( n0, 0.1, 0.01);\n\n  V v1 = V(-0.1, -0.01, 0.0 );\n  T n1 = OpenTissue::math::norm_1( v1 );\n  BOOST_CHECK_CLOSE( n1, 0.1, 0.01);\n\n  V v2 = V( -0.01, 0.1, 0.0 );\n  T n2 = OpenTissue::math::norm_1( v2 );\n  BOOST_CHECK_CLOSE( n2, 0.1, 0.01);\n\n  V v3 = V( -0.01, -0.1, 0.0 );\n  T n3 = OpenTissue::math::norm_1( v3 );\n  BOOST_CHECK_CLOSE( n3, 0.1, 0.01);\n\n  V v4 = V( -0.01, 0.0, 0.1 );\n  T n4 = OpenTissue::math::norm_1( v4 );\n  BOOST_CHECK_CLOSE( n4, 0.1, 0.01);\n\n  V v5 = V( -0.01, 0.0, -0.1 );\n  T n5 = OpenTissue::math::norm_1( v5 );\n  BOOST_CHECK_CLOSE( n5, 0.1, 0.01);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "0ca31bbdc2a3890a1bbbd1855759c273bcb36952", "size": 1503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/norm_1/src/unit_norm_1.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/norm_1/src/unit_norm_1.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/norm_1/src/unit_norm_1.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 28.9038461538, "max_line_length": 78, "alphanum_fraction": 0.6906187625, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6569897266610909}}
{"text": "\n/*\n * distributions_boost.hpp\n *\n *  Created on: 7 Sep 2018\n *      Author: admin\n */\n\n#ifndef SRC_DISTRIBUTIONS_BOOST_HPP_\n#define SRC_DISTRIBUTIONS_BOOST_HPP_\n\n\n#include <random>\n#include <Eigen/Eigen>\n#include \"boost/random.hpp\"\n#include \"boost/generator_iterator.hpp\"\nclass Distributions_boost{\n    boost::mt19937 rng;\n    unsigned int seed;\npublic:\n    Distributions_boost(unsigned int seed);\n    virtual ~Distributions_boost();\n    double rgamma(double shape, double scale);\n    Eigen::VectorXd dirichlet_rng(Eigen::VectorXd alpha);\n    double inv_gamma_rng(double shape,double scale);\n    double gamma_rng(double shape,double scale);\n    double inv_gamma_rate_rng(double shape,double rate);\n    double gamma_rate_rng(double shape,double rate);\n    double inv_scaled_chisq_rng(double dof,double scale);\n    double norm_rng(double mu, double sigma2);\n    double component_probs(double b,Eigen::VectorXd pi);\n    double categorical(Eigen::VectorXd probs);\n    double exp_rng(double a);\n    double unif_rng();\n};\n\n\n\n\n#endif /* SRC_DISTRIBUTIONS_BOOST_HPP_ */\n", "meta": {"hexsha": "f8b5d4f6fb0c08dad83901c7e86cd6719f6bf3b9", "size": 1063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distributions_boost.hpp", "max_stars_repo_name": "ctggroup/BayesMap", "max_stars_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-06T14:43:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:05:05.000Z", "max_issues_repo_path": "src/distributions_boost.hpp", "max_issues_repo_name": "ctggroup/BayesMap", "max_issues_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-01T17:22:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T04:43:18.000Z", "max_forks_repo_path": "src/distributions_boost.hpp", "max_forks_repo_name": "ctggroup/BayesRRcmd", "max_forks_repo_head_hexsha": "a56ab3769389ecaa315ff4bae9db58948fb94e55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-03T10:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T10:01:55.000Z", "avg_line_length": 25.9268292683, "max_line_length": 57, "alphanum_fraction": 0.7422389464, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6569897080094279}}
{"text": "#define BZ_TAU_PROFILING\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    TAU_PROFILE(\"main()\", \"int ()\", TAU_DEFAULT);\n\n    const int N = 32;\n\n    Array<float,2> A(N,N), B(N,N), C(N,N), D(N,N), E(N,N);\n    A = 5.0;\n    B = 0.0;\n    C = 0.0;\n\n    for (int i=0; i < 20; ++i)\n    {\n        D = A + B + C;\n        D /= sum(pow2(D));\n        A = B * cos(D) + C * sin(D);\n        B += exp(-D);\n\n        float x = sum(A);\n        float y = sum(A+B);\n        float z = sum(sqr(A)+sqr(B));\n        C = x*A+y*B+z*C;\n\n        D = exp(-sqr(A)-sqr(B));\n        E = A + B + C + D;\n        float q = min(A);\n        float r = max(B);\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "efbb0046e4466e3ac2016140a5ce45fa7a7c490f", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/profile.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/profile.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/profile.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": 17.0769230769, "max_line_length": 58, "alphanum_fraction": 0.4129129129, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6568824133514652}}
{"text": "/* test_chi_squared.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id: test_chi_squared.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/chi_squared_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/chi_squared.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::chi_squared_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME chi_squared\r\n#define BOOST_MATH_DISTRIBUTION boost::math::chi_squared\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME n\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "2976c7940a9158b03fb090162fcc0fb4f5564e34", "size": 884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_chi_squared.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/random/test/test_chi_squared.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_chi_squared.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": 35.36, "max_line_length": 76, "alphanum_fraction": 0.786199095, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6568217330740691}}
{"text": "/* Cam Mannett 2020\n *\n * See LICENSE file\n */\n\n#pragma once\n\n#include <boost/mp11.hpp>\n\nnamespace malbolge\n{\nnamespace math\n{\n/** Compile-time integral exponentiation.\n *\n * Raises @a Base to the power @a Expo.\n * @tparam R Return type\n * @tparam Base Base value\n * @tparam Expo Exponent value\n * @return @a Base raised to the power @a Expo\n */\ntemplate <typename R, auto Base, auto Expo>\n[[nodiscard]]\nconstexpr R ipow() noexcept\n{\n    static_assert(std::is_unsigned_v<R> &&\n                  std::is_unsigned_v<decltype(Base)> &&\n                  std::is_unsigned_v<decltype(Expo)>,\n                  \"All parameters must be unsigned integrals\");\n\n    using seq = boost::mp11::mp_drop_c<boost::mp11::mp_iota_c<Expo+1>, 1>;\n\n    auto result = R{1};\n    boost::mp11::mp_for_each<seq>([&](auto) {\n        result *= Base;\n    });\n\n    return result;\n}\n\n/** Overload that allows for runtime integral exponentiation.\n *\n * Raises @a base to the power @a expo.\n * @tparam R Return type\n * @tparam B Base type\n * @tparam E Exponent type\n * @param base Base value\n * @param expo Exponent value\n * @return @a base raised to the power @a expo\n */\ntemplate <typename R, typename B, typename E>\n[[nodiscard]]\nconstexpr R ipow(B&& base, E&& expo) noexcept\n{\n    static_assert(std::is_unsigned_v<std::decay_t<R>> &&\n                  std::is_unsigned_v<std::decay_t<B>> &&\n                  std::is_unsigned_v<std::decay_t<E>>,\n                  \"All parameters must be unsigned integrals\");\n\n    auto result = R{1};\n    for (auto i = 1u; i <= expo; ++i) {\n        result *= base;\n    }\n\n    return result;\n}\n}\n}\n", "meta": {"hexsha": "abf6715c7ec2f841b2ba11ba42f92cde3287b263", "size": 1602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/malbolge/math/ipow.hpp", "max_stars_repo_name": "cmannett85/malbolge", "max_stars_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T12:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T12:34:27.000Z", "max_issues_repo_path": "include/malbolge/math/ipow.hpp", "max_issues_repo_name": "cmannett85/malbolge", "max_issues_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T07:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-22T15:30:20.000Z", "max_forks_repo_path": "include/malbolge/math/ipow.hpp", "max_forks_repo_name": "cmannett85/malbolge", "max_forks_repo_head_hexsha": "a3216af7b029d1b942af1dd3678d43fbb5d3c017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T12:34:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T12:34:30.000Z", "avg_line_length": 23.2173913043, "max_line_length": 74, "alphanum_fraction": 0.6173533084, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6567393976530129}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/tools/big_constant.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"functor.hpp\"\n\n#include \"handle_test_result.hpp\"\n#include \"table_type.hpp\"\n\n#include <boost/math/special_functions/hypergeometric_1F1.hpp>\n#include <boost/math/quadrature/exp_sinh.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(disable:4127)\n#endif\n\ntemplate <class Real, class T>\nvoid do_test_1F1(const T& data, const char* type_name, const char* test_name)\n{\n   typedef Real                   value_type;\n\n   typedef value_type(*pg)(value_type, value_type, value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   pg funcp = boost::math::log_hypergeometric_1F1<value_type, value_type>;\n#else\n   pg funcp = boost::math::log_hypergeometric_1F1;\n#endif\n\n   boost::math::tools::test_result<value_type> result;\n\n   std::cout << \"Testing \" << test_name << \" with type \" << type_name\n      << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n   //\n   // test hypergeometric_2F0 against data:\n   //\n   result = boost::math::tools::test_hetero<Real>(\n      data,\n      bind_func<Real>(funcp, 0, 1, 2),\n      extract_result<Real>(3));\n   handle_test_result(result, data[result.worst()], result.worst(), type_name, \"log_hypergeometric_1F1\", test_name);\n   std::cout << std::endl;\n}\n\n#ifndef SC_\n#define SC_(x) BOOST_MATH_BIG_CONSTANT(T, 1000000, x)\n#endif\n\ntemplate <class T>\nvoid test_spots1(T, const char* type_name)\n{\n#include \"hypergeometric_1f1_log_large.ipp\"\n\n   do_test_1F1<T>(hypergeometric_1f1_log_large, type_name, \"Large random values - log\");\n}\n\ntemplate <class T>\nvoid test_spots2(T, const char* type_name)\n{\n#include \"hypergeometric_1f1_log_large_unsolved.ipp\"\n\n   do_test_1F1<T>(hypergeometric_1f1_log_large_unsolved, type_name, \"Large random values - log - unsolved\");\n}\n\ntemplate <class T>\nvoid test_spots(T z, const char* type_name)\n{\n   test_spots1(z, type_name);\n#ifdef TEST_UNSOLVED\n   test_spots2(z, type_name);\n#endif\n}\n\n", "meta": {"hexsha": "28ec4c0d5b1f9d4bbbf8f89023b7c56c7bb31198", "size": 2654, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_1F1_log.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": "test/test_1F1_log.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": "test/test_1F1_log.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": 29.8202247191, "max_line_length": 116, "alphanum_fraction": 0.72720422, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6567393963272824}}
{"text": "//\n// Created by yujie on 2020-04-16.\n//\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <iterator>\n#include <string>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include \"CSV_reader.h\"\n#include \"dataset.h\"\n#include <iomanip>\n#include <blaze/math/DynamicMatrix.h>\n#include <blaze/math/Columns.h>\n\nusing namespace std;\nusing blaze::DynamicMatrix;\n\n\nint main()\n{\n\n    // Creating an object of CSVWriter\n    CSV_reader reader(\"/home/yujie/project/regression_algorithm/data/raw/housing.data\");\n\n\n    // Get the data from CSV File\n    std::vector<std::vector<std::string> > dataList = reader.getData();\n\n\n    // set train and test ratio\n    float test_ratio = 0.1;\n\n    int test_size = int(test_ratio*dataList.size());\n    int train_size = dataList.size() - test_size;\n\n    cout << \"train_size is \"<< train_size << endl;\n    cout << \"test_size is \"<< test_size << endl;\n\n    cout << dataList.size() <<endl;\n\n    DynamicMatrix<float> A(dataList.size(), 14);\n\n    size_t row = 0;\n    size_t col = 0;\n\n\n\n//    CRIM: Per capita crime rate by town\n//    ZN: Proportion of residential land zoned for lots over 25,000 sq. ft\n//    INDUS: Proportion of non-retail business acres per town\n//    CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n//    NOX: Nitric oxide concentration (parts per 10 million)\n//    RM: Average number of rooms per dwelling\n//    AGE: Proportion of owner-occupied units built prior to 1940\n//    DIS: Weighted distances to five Boston employment centers\n//    RAD: Index of accessibility to radial highways\n//    TAX: Full-value property tax rate per $10,000\n//    PTRATIO: Pupil-teacher ratio by town\n//    B: 1000(Bk \u2014 0.63)\u00b2, where Bk is the proportion of [people of African American descent] by town\n//    LSTAT: Percentage of lower status of the population\n//    MEDV: Median value of owner-occupied homes in $1000s\n\n    vector<string> column_names({\"crime\", \"zn\",\n    \"indus\", \"chas\", \"nox\", \"rm\", \"age\", \"dis\", \"rad\", \"tax\",\n    \"ptratio\", \"bk\", \"lstat\", \"medv\"});\n\n\n//    dataList.insert(dataList.begin(), column_names);\n\n    // Print the content of row by row on screen\n    for(std::vector<std::string> vec : dataList)\n    {\n        //for(std::string data : vec)\n        vector<float> vec_tmp;\n\n        col = 0;\n\n        for(auto it=vec.begin(); it<vec.end(); it++)\n        {\n            string a = *it;\n            int b = a.compare(\"\");\n            if((*it).compare(\"\")== 0) {\n//                vec.erase(it);\n            }\n            else{\n//                std::cout<<*it<<\" \"<<left<<std::setw(9);\n                float ft_num = stof(*it);\n\n                 A(row, col) = ft_num;\n\n\n                col++;\n\n            }\n\n\n        }\n\n        row++;\n\n\n    }\n\n    // fill the data into the the dataset\n\n    DynamicMatrix<float> train_set(train_size, 14);\n    DynamicMatrix<float> test_set(test_size, 14);\n\n    size_t train_row = 0;\n    size_t train_col = 0;\n\n    size_t test_row = 0;\n    size_t test_col = 0;\n\n    // fill in the train set\n    for( size_t i=0; i<train_size; ++i) {\n\n        train_col =0;\n        for( DynamicMatrix<float,rowMajor>::Iterator it=A.begin(i); it!=A.end(i); ++it ) {\n\n            train_set(train_row, train_col) = *it;\n            train_col ++;\n\n        }\n\n        train_row ++;\n    }\n\n\n\n\n    // create a final dataset for training and testing\n\n    dataset final_data(train_set, test_set, test_ratio);\n\n\n    // get the scaler\n\n    for(size_t col_new = 0; col_new < train_set.columns(); col_new++ ){\n\n        auto col_vec = columns(train_set, {col_new});\n\n        float col_mean = mean(col_vec);\n\n        float col_std = stddev(col_vec);\n\n        if(col_new < (train_set.columns()-1)) {\n            final_data.set_X_scaler(col_mean, col_std);\n        }\n        else{\n            final_data.set_y_scaler(col_mean, col_std);\n        }\n    }\n\n    vector<float> X_mean_vec = final_data.get_X_mean();\n    vector<float> X_std_vec = final_data.get_X_std();\n\n    vector<float> y_mean_vec = final_data.get_y_mean();\n    vector<float> y_std_vec = final_data.get_y_std();\n\n\n    // fill in the test set\n\n    // fill in the train set\n    for( size_t i=0; i<train_size; ++i) {\n\n        train_col =0;\n        for( DynamicMatrix<float,rowMajor>::Iterator it=A.begin(i); it!=A.end(i); ++it ) {\n\n            if(it < (A.end(i)-1)){\n                train_set(train_row, train_col) =  (train_set(train_row, train_col)-X_mean_vec.at(test_col))/X_std_vec.at(test_col);\n                train_col ++;\n            }\n            else{\n                train_set(test_row, test_col) = (train_set(train_row, train_col)-y_mean_vec.at(test_col))/y_std_vec.at(test_col);\n            }\n\n\n\n        }\n\n        train_row ++;\n    }\n\n\n    for( size_t i=train_size; i<A.rows(); ++i) {\n\n        test_col =0;\n\n        for( DynamicMatrix<float,rowMajor>::Iterator it=A.begin(i); it!=A.end(i); ++it ) {\n\n            if(it < (A.end(i)-1)){\n                test_set(test_row, test_col) = (test_set(test_row, test_col)-X_mean_vec.at(test_col))/X_std_vec.at(test_col);\n                test_col ++;}\n            else{\n                test_set(test_row, test_col) = (test_set(test_row, test_col)-y_mean_vec.at(0))/y_std_vec.at(0);\n            }\n\n\n        }\n\n        test_row ++;\n    }\n\n\n\n\n\n\n    return 0;\n\n}\n\n", "meta": {"hexsha": "3d7f452dc347f49c747243e88062144eb65c1b76", "size": 5272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data/make_dataset.cpp", "max_stars_repo_name": "Yujie-Xu/regression_algorithm", "max_stars_repo_head_hexsha": "26ce68443610a0e4804498ecd1b4c831837caede", "max_stars_repo_licenses": ["MIT"], "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/data/make_dataset.cpp", "max_issues_repo_name": "Yujie-Xu/regression_algorithm", "max_issues_repo_head_hexsha": "26ce68443610a0e4804498ecd1b4c831837caede", "max_issues_repo_licenses": ["MIT"], "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/data/make_dataset.cpp", "max_forks_repo_name": "Yujie-Xu/regression_algorithm", "max_forks_repo_head_hexsha": "26ce68443610a0e4804498ecd1b4c831837caede", "max_forks_repo_licenses": ["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.2949308756, "max_line_length": 132, "alphanum_fraction": 0.5876327769, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6567393762630253}}
{"text": "#ifndef GLAPLACE_HPP\n#define GLAPLACE_HPP\n\n#include <concepts>\n#include <vector>\n#include <armadillo>\n\n#include \"gauss_lobatto.hpp\"\n#include \"Quad.hpp\"\n\n// computes the Galerkin projection of the laplaction of u: (-Lu, v) ==> (Du, Dv)\n// algorithm 105 in:\n// D. A. Kopriva. Implementing Spectral Methods for Partial Differential\n// Equations: Algorithms for Scientists and Engineers. Scientific computation.\n// Springer Netherlands, Dordrecht, 1. aufl. edition, 2009. ISBN 9048122600.\ntemplate <std::floating_point real>\nmatrix<real> glaplace(const matrix<real>& u, const Quad<real>& element, const matrix<real>& D, const quad_rule<real>& quadrature)\n{\n    matrix<real> u_xi = D * u;\n    matrix<real> u_eta = u * D.t();\n\n    matrix<real> F = D.t() * (arma::diagmat(quadrature.w) * (element.A % u_xi - element.B % u_eta));\n    matrix<real> G = ((element.C % u_eta - element.B % u_xi) * arma::diagmat(quadrature.w)) * D;\n\n    matrix<real> lap_u = F * arma::diagmat(quadrature.w) + arma::diagmat(quadrature.w) * G;\n    \n    return lap_u;\n}\n\n#endif", "meta": {"hexsha": "4cc406090904a36121d3917df12481dbc8af3851", "size": 1044, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/glaplace.hpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/glaplace.hpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/glaplace.hpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8, "max_line_length": 129, "alphanum_fraction": 0.6925287356, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545274901876, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6567316262233319}}
{"text": "/** @file statistics.cc\n * @author David F. Gleich\n * @date 2006-04-21\n * @copyright Stanford University, 2006-2008\n * Graph statistics wrappers\n */\n\n/** History\n *  2007-04-18: Implemented topological order function\n *  2007-07-05: Implemented matchings\n *  2007-07-05: Implemented core_numbers\n *  2007-07-11: Implemented directed and weighted clustering coefficients\n *  2007-07-12: Implemented dominator tree\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/simple_row_and_column_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n\n#include <vector>\n\n#include <boost/graph/iteration_macros.hpp>\n//#include <boost/graph/betweenness_centrality.hpp>\n#include <yasmic/boost_mod/betweenness_centrality.hpp>\n#include <boost/graph/topological_sort.hpp>\n\n#include <boost/iterator/reverse_iterator.hpp>\n\n#include <boost/graph/max_cardinality_matching.hpp>\n#include <yasmic/boost_mod/core_numbers.hpp>\n#include <boost/graph/dominator_tree.hpp>\n\n#include <iostream>\n\n#include <math.h>\n\ntemplate <class Vertex, class IndMap>\nstruct in_indicator_pred\n\t: public std::unary_function<Vertex, bool>\n{\n\tin_indicator_pred(IndMap indmap, Vertex src)\n\t\t: i(indmap), u(src)\n\t{}\n\n\tIndMap i;\n    Vertex u;\n\n\tbool operator() (const Vertex &v) const\n\t{\n\t\treturn (i[v] > 0) && (u != v);\n\t}\n};\n\n/* Clustering Coefficients Code */\ntemplate <class Graph, class CCMap, class IndMap>\nvoid cluster_coefficients(const Graph& g, CCMap cc, IndMap ind)\n{\n\tusing namespace boost;\n\n\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t{\n\t\tcc[v] = 0;\n\t\tind[v] = 0;\n\t}\n\n\n\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t{\n\t\tBGL_FORALL_ADJ_T(v,w,g,Graph)\n\t\t{\n\t\t\tind[w] = 1;\n\t\t}\n\n        ind[v] = 0;\n\n\t\ttypename property_traits<CCMap>::value_type cur_cc = 0;\n\t\ttypename graph_traits<Graph>::degree_size_type d = out_degree(v, g);\n\n\n\n\t\tBGL_FORALL_ADJ_T(v,w,g,Graph)\n\t\t{\n            // if we are adjacent to ourselves, skip the iteration\n            if (v == w) { --d; continue; }\n\n            in_indicator_pred<\n    \t\t\ttypename graph_traits<Graph>::vertex_descriptor,\n\t\t\t    IndMap> p(ind,w);\n\n\t\t\ttypename graph_traits<Graph>::adjacency_iterator ai, aiend;\n\t\t\tboost::tie(ai, aiend) = adjacent_vertices(w,g);\n\n\t\t\t// count if this is in the indicator predicate\n\t\t\tcur_cc += (int)count_if(ai, aiend, p);\n\t\t}\n\n        if (d > 1)\n        {\n\t\t    cc[v] = (double)cur_cc/(double)((d*(d-1)));\n        }\n        else\n        {\n            cc[v] = 0.0;\n        }\n\n\t\t// reset the indicator\n\t\tBGL_FORALL_ADJ_T(v,w,g,Graph)\n\t\t{\n\t\t\tind[w] = 0;\n\t\t}\n\t}\n}\n\ntemplate <class Graph, class CCMap, class EdgeWeightMap, class IndMap>\nvoid undirected_clustering_coefficients(const Graph& g, CCMap cc, EdgeWeightMap wm,\n    IndMap ind)\n{\n    using namespace boost;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex;\n    typename graph_traits<Graph>::vertex_iterator vi,vi_end;\n    for (tie(vi,vi_end)=vertices(g);vi!=vi_end;++vi) {\n        put(cc,*vi,0);\n        put(ind,*vi,0);\n    }\n    // a lazy cache for the temp weights for each vertex, could be more\n    // efficient using the maximum degree\n    std::vector<typename property_traits<EdgeWeightMap>::value_type> cache(num_vertices(g));\n    std::vector<typename graph_traits<Graph>::degree_size_type> degs;\n    for (tie(vi,vi_end)=vertices(g);vi!=vi_end;++vi) {\n        vertex v = *vi;\n        typename graph_traits<Graph>::out_edge_iterator oi,oi_end;\n        typename graph_traits<Graph>::out_edge_iterator oi2,oi2_end;\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            // check to ignore self edges\n            if (target(*oi,g) != v) {\n                put(ind,target(*oi,g),1);\n                cache[target(*oi,g)] = pow(get(wm,*oi),1.0/3.0);\n            }\n        }\n        typename property_traits<CCMap>::value_type cur_cc = 0;\n        typename graph_traits<Graph>::degree_size_type d = out_degree(v,g);\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            vertex w = target(*oi,g);\n            if (v==w) { --d; }\n            for (tie(oi2,oi2_end)=out_edges(w,g);oi2!=oi2_end;++oi2) {\n                if (target(*oi2,g) == w) { continue; }\n                if (get(ind,target(*oi2,g))) {\n                    // cache is cached with its power\n                    cur_cc += pow(get(wm,*oi2),1.0/3.0)*pow(get(wm,*oi),1.0/3.0)*cache[target(*oi2,g)];\n                }\n            }\n        }\n        if (d > 1) {\n            put(cc,v,cur_cc/((typename property_traits<CCMap>::value_type)(d*(d-1))));\n        } else {\n            put(cc,v,(typename property_traits<CCMap>::value_type)0);\n        }\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            put(ind,target(*oi,g),0);\n            cache[target(*oi,g)] = 0;\n        }\n    }\n}\n\n// graph must be a bidirectional graph\ntemplate <class Graph, class CCMap, class EdgeWeightMap, class IndMap>\nvoid directed_clustering_coefficients(const Graph& g,\n    CCMap cc, EdgeWeightMap wm, IndMap ind)\n{\n    using namespace boost;\n    typedef typename property_traits<CCMap>::value_type value_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex;\n    typename graph_traits<Graph>::vertex_iterator vi,vi_end;\n    for (tie(vi,vi_end)=vertices(g);vi!=vi_end;++vi) {\n        put(cc,*vi,0);\n        put(ind,*vi,0);\n    }\n    // a lazy cache for the temp weights for each vertex, could be more\n    // efficient using the maximum degree\n    std::vector<typename property_traits<EdgeWeightMap>::value_type> cache(num_vertices(g));\n    std::vector<typename graph_traits<Graph>::degree_size_type> degs(num_vertices(g));\n    typename graph_traits<Graph>::edge_iterator ei,ei_end;\n    for (tie(ei,ei_end)=edges(g);ei!=ei_end;++ei) {\n        vertex u = source(*ei,g);\n        vertex v = target(*ei,g);\n        if (u==v) { continue; }\n        degs[u]++;\n        degs[v]++;\n    }\n    for (tie(vi,vi_end)=vertices(g);vi!=vi_end;++vi) {\n        vertex v = *vi;\n        typename graph_traits<Graph>::out_edge_iterator oi,oi_end;\n        typename graph_traits<Graph>::out_edge_iterator oi2,oi2_end;\n        typename graph_traits<Graph>::in_edge_iterator ii, ii_end;\n        for (tie(ii,ii_end)=in_edges(v,g);ii!=ii_end;++ii) {\n            if (source(*ii,g) != v) {\n                put(ind,source(*ii,g),1);\n                cache[source(*ii,g)] += pow(get(wm,*ii),1.0/3.0);\n            }\n        }\n        // we've precomputed the set of in-edges, so we know how\n        // to get back to v to complete a triangle that ends\n        // with an edge to v.\n        typename graph_traits<Graph>::degree_size_type bilateral_edges = 0;\n        value_type cur_cc_cyc=0, cur_cc_mid=0, cur_cc_in=0, cur_cc_out=0;\n        // cycles are out-out-out.\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            vertex w = target(*oi,g);\n            if (v == w) { continue; }\n            value_type cache_w = pow(get(wm,*oi),1.0/3.0);\n            for (tie(oi2,oi2_end)=out_edges(w,g);oi2!=oi2_end;++oi2) {\n                vertex u = target(*oi2,g);\n                if (u == v) { ++bilateral_edges; continue; }\n                if (u == w) { continue; }\n                if (get(ind,u)) {\n                    // cache is cached with its power\n                    cur_cc_cyc += pow(get(wm,*oi2),1.0/3.0)*cache_w*cache[u];\n                }\n            }\n        }\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            vertex w = target(*oi,g);\n            if (v == w) { continue; }\n            value_type cache_w = pow(get(wm,*oi),1.0/3.0);\n            for (tie(ii,ii_end)=in_edges(w,g);ii!=ii_end;++ii) {\n                vertex u = source(*ii,g);\n                if (u == w) { continue; }\n                if (get(ind,u)) {\n                    // cache is cached with its power\n                    cur_cc_mid += pow(get(wm,*ii),1.0/3.0)*cache_w*cache[u];\n                }\n            }\n        }\n        for (tie(ii,ii_end)=in_edges(v,g);ii!=ii_end;++ii) {\n            vertex w = source(*ii,g);\n            if (v == w) { continue; }\n            value_type cache_w = pow(get(wm,*ii),1.0/3.0);\n            for (tie(oi,oi_end)=out_edges(w,g);oi!=oi_end;++oi) {\n                vertex u = target(*oi,g);\n                if (u == w) { continue; }\n                if (get(ind,u)) {\n                    // cache is cached with its power\n                    cur_cc_in += pow(get(wm,*oi),1.0/3.0)*cache_w*cache[u];\n                }\n            }\n        }\n\n        // reset the cache\n        for (tie(ii,ii_end)=in_edges(v,g);ii!=ii_end;++ii) {\n            if (source(*ii,g) != v) {\n                put(ind,source(*ii,g),0);\n                cache[source(*ii,g)] = 0;\n            }\n        }\n\n        // re-init the cache with out-edges\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            // check to ignore self edges\n            if (target(*oi,g) != v) {\n                put(ind,target(*oi,g),1);\n                cache[target(*oi,g)] += pow(get(wm,*oi),1.0/3.0);\n            }\n        }\n\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            vertex w = target(*oi,g);\n            if (v == w) { continue; }\n            value_type cache_w = pow(get(wm,*oi),1.0/3.0);\n            for (tie(oi2,oi2_end)=out_edges(w,g);oi2!=oi2_end;++oi2) {\n                vertex u = target(*oi2,g);\n                if (u == w) { continue; }\n                if (get(ind,u)) {\n                    // cache is cached with its power\n                    cur_cc_out += pow(get(wm,*oi2),1.0/3.0)*cache_w*cache[u];\n                }\n            }\n        }\n\n        // store the value\n        typename graph_traits<Graph>::degree_size_type\n            norm_factor = degs[v]*(degs[v] - 1) - 2*bilateral_edges;\n        if (norm_factor > 0) {\n            put(cc,v,\n                (value_type)(cur_cc_cyc + cur_cc_mid + cur_cc_in + cur_cc_out)/\n                    ((value_type)(norm_factor)));\n        } else {\n            put(cc,v,(value_type)0);\n        }\n\n        //std::cout << std::endl;\n        //std::cout << v << \" \" <<  cur_cc_cyc << \" \" << cur_cc_mid << \" \" << cur_cc_in << \" \" << cur_cc_out << \" \" << degs[v] << \" \" << bilateral_edges << std::endl;\n\n        for (tie(oi,oi_end)=out_edges(v,g);oi!=oi_end;++oi) {\n            // check to ignore self edges\n            if (target(*oi,g) != v) {\n                put(ind,target(*oi,g),0);\n                cache[target(*oi,g)] = 0;\n            }\n        }\n    }\n}\n\nint clustering_coefficients(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    double* ccfs, int directed)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_matrix;\n    crs_matrix g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    std::vector<int> indicator_map(num_vertices(g));\n\n    if (directed) {\n        std::vector<mbglIndex> ati(nverts+1);\n        std::vector<mbglIndex> atj(ia[nverts]);\n        std::vector<mbglIndex> atid(ia[nverts]);\n\n        build_row_and_column_from_csr(g, &ati[0], &atj[0], &atid[0]);\n\n        typedef simple_row_and_column_matrix<mbglIndex,double> bidir_graph;\n        bidir_graph bg(nverts, nverts, ia[nverts], ia, ja, NULL, &ati[0], &atj[0], &atid[0]);\n\n        directed_clustering_coefficients(bg,\n            make_iterator_property_map(ccfs, get(vertex_index,bg)),\n            boost::detail::constant_value_property_map<double>(1.0),\n            make_iterator_property_map(indicator_map.begin(),get(vertex_index,bg)));\n    } else {\n        undirected_clustering_coefficients(g,\n            make_iterator_property_map(ccfs, get(vertex_index,g)),\n            boost::detail::constant_value_property_map<double>(1.0),\n            make_iterator_property_map(indicator_map.begin(), get(vertex_index,g)));\n    }\n\n    return (0);\n}\n\nint weighted_clustering_coefficients(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double* ccfs)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_weighted_graph;\n    crs_weighted_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n    std::vector<int> indicator_map(num_vertices(g));\n\n    undirected_clustering_coefficients(g,\n        make_iterator_property_map(\n            ccfs, get(vertex_index,g)),\n        get(edge_weight,g),\n        make_iterator_property_map(\n            indicator_map.begin(), get(vertex_index,g)));\n\n    return (0);\n}\n\nint directed_clustering_coefficients(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double* ccfs)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_matrix;\n    crs_matrix g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n    // early return for trivial input\n    if (nverts==0) { return (0); }\n\n    std::vector<mbglIndex> ati(nverts+1);\n    std::vector<mbglIndex> atj(ia[nverts]);\n    std::vector<mbglIndex> atid(ia[nverts]);\n\n    build_row_and_column_from_csr(g, &ati[0], &atj[0], &atid[0]);\n\n    typedef simple_row_and_column_matrix<mbglIndex,double> bidir_graph;\n    bidir_graph bg(nverts, nverts, ia[nverts], ia, ja, weight, &ati[0], &atj[0], &atid[0]);\n\n    std::vector<int> indicator_map(num_vertices(g));\n\n    directed_clustering_coefficients(bg,\n        make_iterator_property_map(\n            ccfs, get(vertex_index,bg)),\n        get(edge_weight,bg),\n        make_iterator_property_map(\n            indicator_map.begin(),\n            get(vertex_index,bg)));\n\n    return (0);\n}\n\n\n\nint betweenness_centrality(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double *centrality, double *ecentrality)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n    if (weight)\n    {\n        if (ecentrality) {\n            brandes_betweenness_centrality(g,\n\t        \t\tcentrality_map(centrality)\n                    .weight_map(\n                        make_iterator_property_map(weight,\n                            get(edge_index,g)))\n                    .edge_centrality_map(\n                        make_iterator_property_map(\n                            ecentrality, get(edge_index, g))));\n        } else {\n            brandes_betweenness_centrality(g,\n\t        \t\tcentrality_map(centrality)\n                    .weight_map(\n                        make_iterator_property_map(weight,\n                            get(edge_index,g))));\n        }\n    }\n    else\n    {\n        if (ecentrality) {\n            brandes_betweenness_centrality(g,\n\t\t\t    \tcentrality_map(centrality)\n                    .edge_centrality_map(\n                        make_iterator_property_map(\n                            ecentrality, get(edge_index, g))));\n        } else {\n            brandes_betweenness_centrality(g,\n\t\t\t    \tmake_iterator_property_map(centrality,\n\t\t\t\t    \tget(vertex_index, g)));\n        }\n    }\n\n    return (0);\n}\n\n/**\n * Test for a topological order or topological sort of a graph.\n *\n * This function will also test if the graph is a dag.  If the\n * rev_order parameter is null, then the actual topological order\n * is ignored and the function just tests for a dag.\n *\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param topo_order a topological order of the vertices\n * @param is_dag tests if the graph is a dag (optional)\n */\nint topological_order(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglIndex *topo_order, int *is_dag)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    if (is_dag) {\n        *is_dag = 1;\n    }\n\n    if (topo_order == NULL)\n    {\n        return (-1);\n    }\n    else\n    {\n        typedef reverse_iterator<mbglIndex*>\n            reverse_iter;\n\n        // note for the future, boost's reverse iterator is wild in that\n        // it actually dereferences the PRIOR element, so the correct\n        // range of a boost reverse itertor is the same as the original\n        // iterator.  Consequently, the last element is actual topo_order +\n        // nverts because the previous element (what * returns) is the\n        // correct element.\n        reverse_iter output(topo_order + (nverts));\n\n        try {\n            topological_sort(g, output);\n        } catch (not_a_dag) {\n            if (is_dag) {\n                *is_dag = 0;\n            }\n        }\n    }\n\n    return (0);\n}\n\ntemplate <typename Graph,\n        typename MateMap,\n        typename VertexIndexMap>\nbool matching_help(const Graph& g, MateMap mate, VertexIndexMap vm,\n                   int initial_matching, int augmenting_path, int verify)\n{\n    using namespace boost;\n    if (initial_matching == 1)\n    {\n        if (augmenting_path == 1)\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        empty_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        empty_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n        else\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        empty_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        empty_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n    }\n    else if (initial_matching == 2)\n    {\n        if (augmenting_path == 1)\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        greedy_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        greedy_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n        else\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        greedy_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        greedy_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n    }\n    else\n    {\n        if (augmenting_path == 1)\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        extra_greedy_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        no_augmenting_path_finder,\n                        extra_greedy_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n        else\n            if (verify == 1)\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        extra_greedy_matching,\n                        no_matching_verifier>\n                        (g, mate, vm);\n            else\n                return matching<Graph,MateMap,VertexIndexMap,\n                        edmonds_augmenting_path_finder,\n                        extra_greedy_matching,\n                        maximum_cardinality_matching_verifier>\n                        (g, mate, vm);\n    }\n}\n\n/** Wrap a boost graph library call to matching.\n *\n * A matching is a subset of edges with no common vertices in an undirected\n * graph.\n *\n * A maximum cardinality matching has the largest number of edges over all\n * possible matchings.\n *\n * The graph must be undirected.\n *\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param mate an array of size nverts which stores the matching vertex index\n *  or null vertex if there is no match\n * @param initial_matching indicates the initial matching used in the algorithm\n *  1: no_matching\n *  2: greedy_matching\n *  3: extra_greedy_matching\n * @param augmenting_path indicates the algorithm used to find augmenting paths\n *  1: no_augmenting_path_finder\n *  2: edmonds_augmenting_path_finder\n * @param verify indicates if we verify the algorithm ouput\n *  1: no_matching_verifier\n *  2: maximum_cardinality_matching_verifier\n * @param verified the output of the verification algorithm (if run), or\n *  false otherwise\n * @param null_vertex the special index to indicate an unmatched vertex\n * @return an error code if possible\n *   0: indicates success\n *  -1: indicates a parameter error with initial_matching, augmenting_path, or verify\n */\nint maximum_cardinality_matching(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglIndex* mate, int initial_matching, int augmenting_path, int verify,\n    int *verified, mbglIndex *null_vertex)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    if (initial_matching < 1 || initial_matching > 3 ||\n        augmenting_path < 1 || augmenting_path > 2 ||\n        verify < 1 || verify > 2)\n    {\n        return (-1);\n    }\n\n    bool max_matching =\n        matching_help(g,mate,get(vertex_index,g),\n            initial_matching,augmenting_path,verify);\n\n    if (verified) {\n        *verified = 0;\n        if (verify > 1) { *verified = max_matching; }\n    }\n\n    if (null_vertex) {\n        *null_vertex = graph_traits<crs_graph>::null_vertex();\n    }\n\n    return (0);\n}\n\ntemplate <typename Graph, typename MateMap, typename VertexIndexMap>\nbool verify_matching_help(const Graph& g, MateMap mate, VertexIndexMap vm)\n{\n    return boost::maximum_cardinality_matching_verifier<\n                    Graph,MateMap,VertexIndexMap>::verify_matching(g,mate,vm);\n}\n\n/*\n * mate = nverts if unmatched\n */\nint test_maximum_cardinality_matching(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglIndex* mate, int *verified)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    // set the null_vertex to the true null\n    mbglIndex true_null = graph_traits<crs_graph>::null_vertex();\n    for (mbglIndex v=0;v<num_vertices(g);++v) {\n        if (mate[v] == nverts) { mate[v] = true_null; }\n    }\n\n    bool max_matching = verify_matching_help(g, mate, get(vertex_index,g));\n    if (verified) { *verified = 0; }\n    if (max_matching && verified) { *verified = 1; }\n\n    return (0);\n}\n\n/** Compute the core_numbers of a graph\n *\n * For an undirected graph, this function computes the core number of each\n * vertex.  The core number is the minimum number such that removing all\n * vertices of degree <= cn[k] removes vertex k.  For a directed graph\n * we compute the in-degree core number.\n *\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param cn an array of core numbers, length nverts\n * @param rt an array of removal times, length nverts\n * @return an error code if possible\n */\nint core_numbers(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, /* connectivity params */\n    mbglDegreeType *cn, int *rt)\n{\n    // History\n    //\n    // 30 July 2007\n    // added removal time visitor\n    // changed to mbglDegreeType\n    using namespace yasmic;\n    using namespace boost;\n\n    if (!cn || !rt) { return (-1); }\n\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    int time = 0;\n\n    core_numbers(g, make_iterator_property_map(cn, get(vertex_index,g)),\n        make_core_numbers_visitor(stamp_times(rt, time, on_examine_vertex())));\n\n    return (0);\n}\n\n/** Compute the weighted core numbers of a graph\n *\n * For an undirected graph, this function computes the core number of each\n * vertex.  The core number is the minimum number such that removing all\n * vertices of weighted in-degree <= cn[k] removes vertex k.  For a\n * directed graph we compute the weighted in-degree core number.\n *\n * @param nverts the number of vertices in the graph\n * @param ja the connectivity for each vertex\n * @param ia the row connectivity points into ja\n * @param cn an array of core numbers, length nverts\n * @param rt an array of removal times, length nverts\n * @return an error code if possible\n */\nint weighted_core_numbers(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    double *cn, int *rt)\n{\n    // History\n    //\n    // 30 July 2007\n    // added removal time visitor\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n    int time=0;\n\n    weighted_core_numbers(g, make_iterator_property_map(cn, get(vertex_index,g)),\n        make_core_numbers_visitor(stamp_times(rt, time, on_examine_vertex())));\n\n    return (0);\n}\n\n\nint dominator_tree(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    mbglIndex src, mbglIndex *pred)\n{\n    //\n    // History\n    //\n    // 12 July 2007\n    // Initial implementation\n    //\n    // 23 July 2007\n    // Added iterator property map call for pred.\n    //\n    using namespace yasmic;\n    using namespace boost;\n\n    typedef simple_csr_matrix<mbglIndex,double> crs_graph;\n    crs_graph g(nverts, nverts, ia[nverts], ia, ja, NULL);\n\n    std::vector<mbglIndex> ati(nverts+1);\n    std::vector<mbglIndex> atj(ia[nverts]);\n    std::vector<mbglIndex> atid(ia[nverts]);\n\n    build_row_and_column_from_csr(g, &ati[0], &atj[0], &atid[0]);\n\n    typedef simple_row_and_column_matrix<mbglIndex,double> bidir_graph;\n    bidir_graph bg(nverts, nverts, ia[nverts], ia, ja, NULL, &ati[0], &atj[0], &atid[0]);\n\n    // modify the output to conform to what matlab_bgl expects\n    mbglIndex null_vertex = graph_traits<bidir_graph>::null_vertex();\n    for (mbglIndex i=0; i< nverts; i++) { pred[i] = null_vertex; }\n\n    lengauer_tarjan_dominator_tree(bg, src,\n        make_iterator_property_map(pred, get(vertex_index,bg)));\n\n    pred[src] = src;\n\n    // modify the output to conform to what matlab_bgl expects\n    for (mbglIndex i=0; i< nverts; i++) {\n        if (pred[i] == null_vertex) { pred[i] = i; }\n    }\n\n    return (0);\n}\n\n", "meta": {"hexsha": "a9f5da45755c2e981fbbca96a205222fc5bb73ea", "size": 27565, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/statistics.cc", "max_stars_repo_name": "anajmedd/ENSEEIHT-Projects", "max_stars_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T00:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T09:19:03.000Z", "max_issues_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/statistics.cc", "max_issues_repo_name": "anajmedd/ENSEEIHT-Projects", "max_issues_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T19:40:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T06:49:02.000Z", "max_forks_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/statistics.cc", "max_forks_repo_name": "anajmedd/ENSEEIHT-Projects", "max_forks_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 33.6158536585, "max_line_length": 166, "alphanum_fraction": 0.5968801016, "num_tokens": 7065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6567274269973771}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\nusing namespace boost;\nusing namespace std;\n//In this example we will  keep only edges with positive edge weight. \n//First, we create a predicate function object.\n\n//\"typename\" is used for specifying that a dependent name in a template definition or declaration is a type.\ntemplate <typename EdgeWeightMap>\nstruct positive_edge_weight \n{\n  //constructor\n  positive_edge_weight() { }\n  positive_edge_weight(EdgeWeightMap weight) : m_weight(weight) { }\n  \n  template <typename Edge>\n\n  bool operator()(const Edge& e) const \n  {\n    //testing if weight is positive\n    return 0 < get(m_weight, e);\n  }\n  \n  EdgeWeightMap m_weight;\n};\n\n//Now we create a graph and print out the filtered graph.\nint main()\n{\n\n  //defining the graph by an adjacency_list\n  typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_weight_t, int> > Graph;\n\n  //define a syntax for mapping key objects (edge_weight_t) to corresponding value objects (EdgeWeightMap). \n  typedef property_map<Graph, edge_weight_t>::type EdgeWeightMap;\n\n  // a distinct type whose value is restricted to one of several explicitly named constants \n  enum { A, B, C, D, E, N };\n\n  const char* name = \"ABCDE\";\n\n  Graph g(N);\n  add_edge(A, B, 2, g);\n  add_edge(A, C, 4, g);\n  add_edge(C, D, 1, g);\n  add_edge(D, B, -3, g);\n  add_edge(C, E, 0, g);\n  add_edge(E, C, 0, g);\n\n  //filter()bprocesses a data structure (typically a list) in some order to produce a new data structure containing exactly those elements of the original data structure.\n  positive_edge_weight<EdgeWeightMap> filter(get(edge_weight, g));\n  filtered_graph<Graph, positive_edge_weight<EdgeWeightMap> > fg(g, filter);\n\n  cout << \"filtered edge set: \";\n  print_edges(fg, name);\n\n  return 0;\n}\n", "meta": {"hexsha": "9b15c299c2b771ddf64d3308957e7745c7cce093", "size": 1872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4filtered_graph.cpp", "max_stars_repo_name": "mohsenuss91/BGL_workshop", "max_stars_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T18:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-12T18:40:32.000Z", "max_issues_repo_path": "4filtered_graph.cpp", "max_issues_repo_name": "mohsenuss91/IBM_BGL", "max_issues_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4filtered_graph.cpp", "max_forks_repo_name": "mohsenuss91/IBM_BGL", "max_forks_repo_head_hexsha": "03d2bea291d4c6d67e7ddcd562694a0b7ecc5130", "max_forks_repo_licenses": ["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.6885245902, "max_line_length": 170, "alphanum_fraction": 0.7254273504, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6567274248755697}}
{"text": "\n// BLAS level 1 (vector) -- complex numbers\n\n#include <iostream>\n#include <cmath>\n#include <complex> \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include \"utils.h\" \n\nnamespace atlas = boost::numeric::bindings::atlas;\nnamespace ublas = boost::numeric::ublas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t;  \ntypedef ublas::vector<cmplx_t> vct_t; \n\n#ifdef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \nusing ublas::inner_prod; \nusing ublas::norm_2; \nusing ublas::conj; \n#endif \n\nint main() {\n\n  int n = 6; \n\n  cout << endl; \n  vct_t v (n); \n  init_v (v, times_plus<cmplx_t> (cmplx_t (1, -1), cmplx_t (0, .1))); \n  print_v (v, \"v\"); \n\n  atlas::scal (2.0, v); \n  print_v (v, \"2.0 v\"); \n\n  atlas::scal (cmplx_t (-1, 0), v); \n  print_v (v, \"(-1, 0) v\"); \n\n  atlas::scal (cmplx_t (0, 1), v);\n  print_v (v, \"(0, 1) v\"); \n\n  atlas::set (cmplx_t (1, -1), v); \n  print_v (v, \"v\"); \n  vct_t v1 (n); \n  atlas::set (cmplx_t (0, -1), v1); \n  print_v (v1, \"v1\"); \n\n  cout << endl; \n  cout << \"v^T v1 = \" << atlas::dot (v, v1) << \" == \"\n    << atlas::dotu (v, v1) << \" == \"\n    << inner_prod (v, v1) << endl; \n  cout << \"v^T v = \" << atlas::dot (v, v) << \" == \"\n    << atlas::dotu (v, v) << \" == \"\n    << inner_prod (v, v) << endl; \n  cout << \"v1^T v1 = \" << atlas::dot (v1, v1) << \" == \"\n    << atlas::dotu (v1, v1) << \" == \"\n    << inner_prod (v1, v1) << endl; \n\n  cout << endl; \n  cout << \"v^H v1 = \" << atlas::dotc (v, v1) << \" == \"\n    << inner_prod (conj (v), v1) << \" == \"\n    << inner_prod (v1, conj (v)) << \" != \"\n    << inner_prod (v, conj (v1)) << endl; \n  cout << \"v^H v = \" << atlas::dotc (v, v) << \" == \"\n    << inner_prod (conj (v), v) << \" == \"\n    << inner_prod (v, conj (v)) << endl; \n  cout << \"v1^H v1 = \" << atlas::dotc (v1, v1) << \" == \"\n    << inner_prod (conj (v1), v1) << \" == \"\n    << inner_prod (v1, conj (v1)) << endl; \n\n  \n  cout << endl;\n  cout << \"||v||_1 = \" << atlas::asum (v) << endl; \n  cout << \"||v||_2 = \" << atlas::nrm2 (v) << \" == \"\n    << norm_2 (v) << endl; \n  \n  cout << endl;\n}\n", "meta": {"hexsha": "f93252e984b7736824515bfa0edc81debb7cb107", "size": 2216, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cvct.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "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": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cvct.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cvct.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "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": 25.7674418605, "max_line_length": 70, "alphanum_fraction": 0.52933213, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.656727422477815}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <ctime>\n#include <chrono>\n//#include <random>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/random.hpp>\n//#include <gmp.h>\n#include <boost/multiprecision/gmp.hpp>\n//#include <boost/multiprecision/random.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace boost::random;\nusing namespace std;\n\n#include \"ecc_gadget.hpp\"\n#include \"scalarmul.hpp\"\n\n//using namespace libsnark;\nusing namespace std;\n\nint main()\n{    \n  typedef libff::alt_bn128_pp ppT;\n  typedef libff::Fr<ppT> FieldT;\n\n  // Initialize the curve parameters\n  ppT::init_public_params();\n  init_curveparams();\n  \n  // Create protoboard\n\n  libff::start_profiling();\n\n  cout << \"Keypair\" << endl;\n\n  protoboard<FieldT> pb;\n  pb_variable<FieldT> outx, outy;\n  pb_variable<FieldT> s;\n\n  // The constant base point P\n  //const FieldT Px = curveParams<FieldT>::Gx;\n  //const FieldT Py = curveParams<FieldT>::Gy;\n\n  // Allocate variables\n\n  outx.allocate(pb, \"outx\");\n  outy.allocate(pb, \"outy\");\n  s.allocate(pb, \"s\");\n\n  // This sets up the protoboard variables so that the first n of them\n  // represent the public input and the rest is private input\n\n  pb.set_input_sizes(2);\n\n  // Initialize the gadget\n  scalarmul_gadget<FieldT> sm(pb, outx, outy, s, 256);\n  sm.generate_r1cs_constraints();\n\n  const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n  const r1cs_gg_ppzksnark_keypair<default_r1cs_gg_ppzksnark_pp> keypair = r1cs_gg_ppzksnark_generator<default_r1cs_gg_ppzksnark_pp>(constraint_system);\n\n  // Add witness values\n\n  cout << \"Prover\" << endl;\n  \n  //srand(time(0));\n  //pb.val(s) = 0;\n  //for(int i = 0; i < 10; i++){\n      //pb.val(s) += FieldT::random_element();\n      //cout << pb.val(s) << \" \" << sizeof(pb.val(s)) << \"\\n\" ;\n  //}\n  pb.val(s) = FieldT::random_element();\n  sm.generate_r1cs_witness();\n\n  const r1cs_gg_ppzksnark_proof<default_r1cs_gg_ppzksnark_pp> proof = r1cs_gg_ppzksnark_prover<default_r1cs_gg_ppzksnark_pp>(keypair.pk, pb.primary_input(), pb.auxiliary_input());\n\n  cout << \"Verifier\" << endl;\n\n  bool verified = r1cs_gg_ppzksnark_verifier_strong_IC<default_r1cs_gg_ppzksnark_pp>(keypair.vk, pb.primary_input(), proof);\n\t\n  cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n  cout << \"Primary (public) input: \" << pb.primary_input() << endl;\n  cout << \"Auxiliary (private) input length: \" << pb.auxiliary_input().size() << endl;\n//  cout << \"Auxiliary (private) input: \" << pb.auxiliary_input() << endl;\n  cout << \"Verification status: \" << verified << endl;\n  cout << \"Computing \" << pb.val(s) << \"*G\" << endl;\n\n  //pb.val(s) += FieldT::random_element();\n  \n  ofstream pkfile(\"pk_scalarmul\");\n  pkfile << keypair.pk;\n  pkfile.close();\n  ofstream vkfile(\"vk_scalarmul\");\n  vkfile << keypair.vk;\n  vkfile.close();\n  ofstream pffile(\"proof_scalarmul\");\n  pffile << proof;\n  pffile.close();\n\n  cout << pb.val(s) << \"*G\" << \" = (\" << pb.val(outx) << \", \" << pb.val(outy) << \")\" << endl;\n  //cout << \"G\" << \" = (\" << Px << \", \" << Py << \")\" << endl;\n  //cout << FieldT::numbits;\n  return 0;\n}\n\n", "meta": {"hexsha": "a21380624eb6015a0da0fc359257563fae1977a9", "size": 3158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scalarmul_final.cpp", "max_stars_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_stars_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_stars_repo_licenses": ["MIT"], "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/scalarmul_final.cpp", "max_issues_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_issues_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_issues_repo_licenses": ["MIT"], "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/scalarmul_final.cpp", "max_forks_repo_name": "SwaroopReddyBasireddy/Proof-of-Assets", "max_forks_repo_head_hexsha": "011ee85ad4e7941c2bfbf53c1872fbaa40038cf5", "max_forks_repo_licenses": ["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.4504504505, "max_line_length": 179, "alphanum_fraction": 0.6725775807, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6567251003794693}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/Optimization/Lbfgs.h\"\n\nusing namespace Scine::Molassembler;\n\ntemplate<typename FloatType>\nstruct GradientBasedChecker {\n  unsigned iterLimit = 100;\n  FloatType gradientLimit = 1e-5;\n\n  template<typename StepValues>\n  bool shouldContinue(unsigned iteration, const StepValues& step) {\n    return (\n      iteration < iterLimit\n      && step.gradients.current.norm() > gradientLimit\n    );\n  }\n};\n\nBOOST_AUTO_TEST_CASE(LBFGSSimpleMinimization, *boost::unit_test::label(\"Temple\")) {\n  /* Booth function\n   * Ellipsoid f(x, y) = (x + 2y - 7)\u00b2 + (2x + y - 5)\u00b2\n   * Minimum at x = 1, y = 3\n   */\n  const auto gradientTestFunction = [](const Eigen::VectorXd& parameters, double& value, Eigen::Ref<Eigen::VectorXd> gradients) {\n    const double& x = parameters[0];\n    const double& y = parameters[1];\n    const double firstBracket = x + 2 * y - 7;\n    const double secondBracket = 2 * x + y - 5;\n\n    value = (\n      std::pow(firstBracket, 2)\n      + std::pow(secondBracket, 2)\n    );\n    gradients[0] = 2 * firstBracket + 4 * secondBracket;\n    gradients[1] = 4 * firstBracket + 2 * secondBracket;\n  };\n\n  Temple::Lbfgs<double, 16> optimizer;\n  GradientBasedChecker<double> gradientChecker;\n  Eigen::VectorXd positions(2);\n  positions[0] = 0.25 * M_PI;\n  positions[1] = 0.75 * M_PI;\n\n  const auto result = optimizer.minimize(positions, gradientTestFunction, gradientChecker);\n\n  BOOST_CHECK_MESSAGE(\n    result.iterations < 100,\n    \"Expected convergence in less than 100 cycles, got \" << result.iterations\n  );\n  BOOST_CHECK(std::fabs(positions[0] - 1.0) < 1e-3);\n  BOOST_CHECK(std::fabs(positions[1] - 3.0) < 1e-3);\n}\n\nBOOST_AUTO_TEST_CASE(LBFGSSimpleMaximization, *boost::unit_test::label(\"Temple\")) {\n  /* Very simple parabola -((x-4)\u00b2 + (y-2)\u00b2) + 4\n   * Maximum at 4, 2\n   */\n  const auto gradientTestFunction = [](const Eigen::VectorXd& parameters, double& value, Eigen::Ref<Eigen::VectorXd> gradients) {\n    const double& x = parameters[0];\n    const double& y = parameters[1];\n\n    value = -(std::pow(x - 4, 2) + std::pow(y - 2, 2)) + 4;\n    gradients[0] = -2 * (x - 4);\n    gradients[1] = -2 * (y - 2);\n  };\n\n  Temple::Lbfgs<double, 16> optimizer;\n  GradientBasedChecker<double> gradientChecker;\n\n  Eigen::VectorXd positions(2);\n  positions << 2.0, -1.0;\n\n  Eigen::VectorXd expectedMaximum(2);\n  expectedMaximum << 4.0, 2.0;\n\n  const auto result = optimizer.maximize(positions, gradientTestFunction, gradientChecker);\n\n  BOOST_CHECK_MESSAGE(\n    result.iterations < 100,\n    \"Expected convergence in less than 100 cycles, got \" << result.iterations\n  );\n\n  for(unsigned i = 0; i < 2; ++i) {\n    BOOST_CHECK_MESSAGE(\n      std::fabs(positions[i] - expectedMaximum[i]) < 1e-3,\n      \"Position parameter \" << i << \" is not at the expected maximum.\"\n      << \" Expected \" << expectedMaximum[i] << \", got \" << positions[i]\n    );\n  }\n}\n\nBOOST_AUTO_TEST_CASE(LBFGSBraninMinimization, *boost::unit_test::label(\"Temple\")) {\n  /* f(x, y) = (-1.275 * x\u00b2 / pi\u00b2 + 4 x / pi + y - 6)\u00b2 + (10 - 5 / (4 pi)) * cos(x) + 10\n   * Minima at (2n pi, 2n pi)\n   */\n  const auto gradientTestFunction = [](const Eigen::VectorXd& parameters, double& value, Eigen::Ref<Eigen::VectorXd> gradients) {\n    const double& x = parameters[0];\n    const double& y = parameters[1];\n\n    constexpr double alpha = -1.275 / (M_PI * M_PI);\n    constexpr double beta = 4 / M_PI;\n    constexpr double cosinePrefactor = (10 - 5 / (4 * M_PI));\n\n    const double polynomialBracket = (alpha * x * x + beta * x + y - 6);\n\n    value = (\n      std::pow(polynomialBracket, 2)\n      + cosinePrefactor * std::cos(x)\n      + 10\n    );\n\n    gradients[0] = 2 * polynomialBracket * (2 * alpha * x + beta) - cosinePrefactor * std::sin(x);\n    gradients[1] = 2 * polynomialBracket;\n  };\n\n  using OptimizerType = Temple::Lbfgs<double, 16>;\n  OptimizerType optimizer;\n  GradientBasedChecker<double> gradientChecker;\n  Eigen::VectorXd positions(2);\n  positions << M_PI - 0.1, M_PI - 0.1;\n\n  constexpr double expectedResult = 0.39788735772973816;\n\n  const auto result = optimizer.minimize(\n    positions,\n    gradientTestFunction,\n    gradientChecker\n  );\n\n  BOOST_CHECK_MESSAGE(\n    result.iterations < 100,\n    \"Expected convergence in less than 100 cycles, got \" << result.iterations\n  );\n\n  BOOST_CHECK_MESSAGE(\n    std::fabs(result.value - expectedResult) < 1e-3,\n    \"Expected minimum of value \" << expectedResult << \", got \" << result.value << \" instead\"\n  );\n}\n\nBOOST_AUTO_TEST_CASE(LBFGSBoxedMinimization, *boost::unit_test::label(\"Temple\")) {\n  /* f(x, y) = - cos x - 0.5 cos y\n   * Minima at (2n pi, 2n pi)\n   * In box min [0.1, 0], max [pi, pi] minimum should be [0.1, 0]\n   */\n  const auto gradientTestFunction = [](const Eigen::VectorXd& parameters, double& value, Eigen::Ref<Eigen::VectorXd> gradients) {\n    const double& x = parameters[0];\n    const double& y = parameters[1];\n\n    value = (\n      - std::cos(x)\n      - 0.5 * std::cos(y)\n    );\n    gradients[0] = std::sin(x);\n    gradients[1] = 0.5 * std::sin(y);\n  };\n\n  using OptimizerType = Temple::Lbfgs<double, 16>;\n\n  OptimizerType optimizer;\n  GradientBasedChecker<double> gradientChecker;\n  Eigen::VectorXd positions(2);\n  Eigen::VectorXd boxMinima(2);\n  Eigen::VectorXd boxMaxima(2);\n  boxMinima << 0.1, 0;\n  positions << 0.6, 0.5;\n  boxMaxima << M_PI, M_PI;\n\n  const typename OptimizerType::Box box {\n    boxMinima,\n    boxMaxima\n  };\n\n  const auto result = optimizer.minimize(\n    positions,\n    box,\n    gradientTestFunction,\n    gradientChecker\n  );\n\n  BOOST_CHECK_MESSAGE(\n    result.iterations < 100,\n    \"Expected convergence in less than 100 cycles, got \" << result.iterations\n  );\n  BOOST_CHECK_MESSAGE(\n    std::fabs(positions[0] - boxMinima[0]) < 1e-3,\n    \"Expected x_min = x_box_min (0.1), but is \" << positions[0] << \" instead\"\n  );\n  BOOST_CHECK_MESSAGE(\n    std::fabs(positions[1] - boxMinima[1]) < 1e-3,\n    \"Expected y_min = y_box_min (0), but is \" << positions[1] << \" instead\"\n  );\n}\n", "meta": {"hexsha": "e1e33c04e65661ca39ec6fef522b181d6c1a496d", "size": 6177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Optimization/Lbfgs.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/Optimization/Lbfgs.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/Optimization/Lbfgs.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 30.5792079208, "max_line_length": 129, "alphanum_fraction": 0.6495062328, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6567250894747663}}
{"text": "/// @file bealab/scilib/stats.hpp\n/// Analysis of statistical distributions and random number generation.\n\n#ifndef _BEALAB_STATS_\n#define\t_BEALAB_STATS_\n\n#include <random>\n#include <ctime>\n#include <boost/math/distributions/normal.hpp>\n#include <bealab/core/blas.hpp>\n#include <bealab/scilib/calculus.hpp>\n#include <bealab/scilib/linalg.hpp>\n\nnamespace bealab\n{\n/// @defgroup stats Statistics\n/// Analysis of statistical distributions and random number generation.\n/// @{\n\n//------------------------------------------------------------------------------\n/// @name Univariate distributions\ntypedef boost::math::normal_distribution<double> normal;\t\t\t\t\t\t///< Normal distribution\ntypedef std::uniform_real_distribution<double> uniform;\t\t\t\t\t\t\t///< Uniform continuous distribution\ntypedef std::uniform_int_distribution<int> uniform_discrete;\t\t\t\t\t///< Uniform discrete distribution\ntypedef std::bernoulli_distribution bernoulli;\t\t\t\t\t\t\t\t\t///< Bernoulli distribution\n/// @}\n\n//------------------------------------------------------------------------------\n/// @name Multivariate normal distribution\n\n/// Distribution class\nclass multivariate_normal {\n\n\trvec _mean;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Mean vector\n\trmat _covariance;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t///< Covariance matrix\n\trmat _covariance_factor;\t\t\t\t\t\t\t\t\t\t\t\t\t///< Covariance factor (i.e., X such that C = X * trans(X))\n\npublic:\n\n\t/// Constructor\n\tmultivariate_normal( const rvec& m, const rmat& Cf ) : _mean(m), _covariance_factor(Cf)\n\t{\n\t\tassert( m.size()  == Cf.size1() );\n\t}\n\n\t/// Get the mean vector\n\tconst rvec& mean() const { return _mean; }\n\n\t/// Get the covariance matrix\n\tconst rmat covariance() const\n\t{\n\t\tif( _covariance.size1() > 0 )\n\t\t\treturn _covariance;\n\t\telse\n\t\t\treturn _covariance_factor * trans(_covariance_factor);\n\t}\n\n\t/// Set the covariance matrix\n\tvoid covariance( const rmat& cov )\n\t{\n\t\t_covariance = cov;\n\t}\n\n\t/// Dimension of the random vector\n\tuint size() const { return _mean.size(); }\n\n\t/// Generate a random vector\n\ttemplate<class generator>\n\trvec operator()( generator& gen )\n\t{\n\t\tint M = size();\n\t\trvec rv(M);\n\t\tstd::normal_distribution<double> dist( 0, 1 );\n\t\tfor( int m = 0; m < M; m++ )\n\t\t\trv(m) = dist(gen);\n\t\treturn _covariance_factor * rv + _mean;\n\t}\n};\n\n/// Probability density function\ndouble pdf( const multivariate_normal& dist, const rvec& x );\n\n/// Cumulative distribution function over a square region\ndouble cdf( const multivariate_normal& dist, rvec a, rvec b );\n\n/// Cumulative distribution function over a square region\ndouble cdf( const multivariate_normal& dist, const rvec& b );\n\n/// @}\n\n//------------------------------------------------------------------------------\n/// @name Random number generation\n\n/// Private namespace for internal use.\nnamespace _stats\n{\n\n/// Random engine\nextern std::mt19937 engine;\n//extern std::default_random_engine engine;\n\n/// Normal distribution mapping for random number generation\nstd::normal_distribution<double> stats2random(\n\t\tconst boost::math::normal_distribution<double>& dist );\n\n/// multivariate normal distribution mapping for random number generation\ninline\nmultivariate_normal stats2random(\n\t\tconst multivariate_normal& dist )\n{ return dist; }\n\n/// Uniform distribution mapping for random number generation\ninline\nstd::uniform_real_distribution<double> stats2random(\n\t\tconst std::uniform_real_distribution<double>& dist )\n{ return dist; }\n\n/// Uniform discrete distribution mapping for random number generation\ninline\nstd::uniform_int_distribution<int> stats2random(\n\t\tconst std::uniform_int_distribution<int>& dist )\n{ return dist; }\n\n/// Bernoulli distribution mapping for random number generation\ninline\nstd::bernoulli_distribution stats2random(\n\t\tconst std::bernoulli_distribution& dist )\n{ return dist; }\n\n}\n\n/// Initializes the engine with a random seed (obtained from std::time()).\nvoid randomize( unsigned int seed = std::time(0) );\n\n/// Obtain a random sample from any specified distribution.\ntemplate<class T>\nauto rand( T distribution ) -> decltype(_stats::stats2random(distribution)(_stats::engine))\n{\n\treturn _stats::stats2random ( distribution )( _stats::engine );\n}\n\n/// Obtain a vector of random samples from any specified distribution.\ntemplate<class T>\nauto rand( T distribution, int M )\n\t-> vec<decltype(_stats::stats2random(distribution)(_stats::engine))>\n{\n\ttypedef decltype(_stats::stats2random(distribution)(_stats::engine)) R;\n\tvec<R> rv(M);\n\tfor( int m = 0; m < M; m++ )\n\t\trv(m) = _stats::stats2random(distribution)(_stats::engine);\n\treturn rv;\n}\n\n/// Obtain a matrix of random samples from any specified distribution.\ntemplate<class T>\nauto rand( T distribution, int M, int N )\n\t-> mat<decltype(_stats::stats2random(distribution)(_stats::engine))>\n{\n\ttypedef decltype(_stats::stats2random(distribution)(_stats::engine)) R;\n\tmat<R> rv(M,N);\n\tfor( int m = 0; m < M; m++ )\n\t\tfor( int n = 0; n < N; n++ )\n\t\t\trv(m,n) = _stats::stats2random(distribution)(_stats::engine);\n\treturn rv;\n}\n\n/// Obtain a random sample from the normal(0,1) distribution.\ninline double randn() { return rand( normal(0,1) ); }\n\n/// Obtain a random vector from the normal(0,1) distribution.\ninline rvec randn( int M ) { return rand( normal(0,1), M ); }\n\n/// Obtain a random matrix from the normal(0,1) distribution.\ninline rmat randn( int M, int N ) { return rand( normal(0,1), M, N ); }\n\n/// Obtain a random sample from the uniform(0,1) distribution.\ninline double randu() { return rand( uniform(0,1) ); }\n\n/// Obtain a random vector from the uniform(0,1) distribution.\ninline rvec randu( int M ) { return rand( uniform(0,1), M ); }\n\n/// Obtain a random matrix from the uniform(0,1) distribution.\ninline rmat randu( int M, int N ) { return rand( uniform(0,1), M, N ); }\n/// @}\n\n//------------------------------------------------------------------------------\n/// @name Analysis of statistical distributions\nusing boost::math::pdf;\nusing boost::math::cdf;\nusing boost::math::complement;\nusing boost::math::mean;\nusing boost::math::standard_deviation;\nusing boost::math::variance;\n/// @}\n\n/// @}\n}\n#endif\n", "meta": {"hexsha": "2d2575ef8cfdd63b557d0ca23c67c9545f7ec76a", "size": 6021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bealab/scilib/stats.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/scilib/stats.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/scilib/stats.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": 30.256281407, "max_line_length": 99, "alphanum_fraction": 0.6764657034, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.930458251637412, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6567035030330877}}
{"text": "#include \"svd.h\"\n\n#include <Eigen/SVD>\n\nvoid eigenSVD(const Eigen::MatrixXd &A, Eigen::MatrixXd &U, Eigen::VectorXd &sigma, Eigen::MatrixXd &V) {\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    U = svd.matrixU();\n    sigma = svd.singularValues();\n    V = svd.matrixV();\n}\n", "meta": {"hexsha": "7e06fa84529fcc64cac6d4afe5ee97e75858ec47", "size": 317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_programs/cpp/src/icp/svd.cpp", "max_stars_repo_name": "tatsy/cpp-python-beginners", "max_stars_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-23T12:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T12:35:56.000Z", "max_issues_repo_path": "_programs/cpp/src/icp/svd.cpp", "max_issues_repo_name": "tatsy/cpp-python-beginners", "max_issues_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_programs/cpp/src/icp/svd.cpp", "max_forks_repo_name": "tatsy/cpp-python-beginners", "max_forks_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T10:20:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T09:04:47.000Z", "avg_line_length": 28.8181818182, "max_line_length": 105, "alphanum_fraction": 0.6687697161, "num_tokens": 96, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509314, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6567035027190077}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/stl.h>\n#include <ceres/ceres.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <sophus/se3.hpp>\n\nnamespace py = pybind11;\n\n// Example autodiff cost function from ceres tutorial\nstruct ExampleFunctor {\n  template<typename T>\n  bool operator()(const T *const x, T *residual) const {\n    residual[0] = T(10.0) - x[0];\n    return true;\n  }\n\n  static ceres::CostFunction *Create() {\n    return new ceres::AutoDiffCostFunction<ExampleFunctor,\n                                           1,\n                                           1>(new ExampleFunctor);\n  }\n};\n\n// cSE3 conversion functions: to/from pointer/vector\ntemplate<typename T>\nvoid cSE3convert(const T* data, Sophus::SE3<T>& X) {\n  X = Sophus::SE3<T>(Eigen::Quaternion<T>(data+3),\n                     Eigen::Map<const Eigen::Matrix<T,3,1>>(data));\n}\ntemplate<typename T>\nvoid cSE3convert(const Eigen::Matrix<T,7,1> &Xvec, Sophus::SE3<T>& X) {\n  X = Sophus::SE3<T>(Eigen::Quaternion<T>(Xvec.data()+3),\n                     Eigen::Map<const Eigen::Matrix<T,3,1>>(Xvec.data()));\n}\ntemplate<typename T>\nvoid cSE3convert(const Sophus::SE3<T>& X, Eigen::Matrix<T,7,1> &Xvec) {\n  Xvec.template block<3,1>(0,0) = Eigen::Matrix<T,3,1>(X.translation().data());\n  Xvec.template block<4,1>(3,0) = Eigen::Matrix<T,4,1>(X.so3().data());\n}\n\n// AutoDiff cost function (factor) for the difference between a measured 3D\n// relative transform, Xij = (tij_, qij_), and the relative transform between two  \n// estimated poses, Xi_hat and Xj_hat. Weighted by measurement covariance, Qij_.\nclass cSE3Functor\n{\npublic:\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  // store measured relative pose and inverted covariance matrix\n  cSE3Functor(Eigen::Matrix<double,7,1> &Xij_vec, Eigen::Matrix<double,6,6> &Qij)\n  {\n    Sophus::SE3<double> Xij;\n    cSE3convert(Xij_vec, Xij);\n    Xij_inv_ = Xij.inverse();\n    Qij_inv_ = Qij.inverse();\n  }\n\n  // templated residual definition for both doubles and jets\n  // basically a weighted implementation of boxminus using Eigen templated types\n  template<typename T>\n  bool operator()(const T* _Xi_hat, const T* _Xj_hat, T* _res) const\n  {\n    // assign memory to usable objects\n    Sophus::SE3<T> Xi_hat, Xj_hat;\n    cSE3convert(_Xi_hat, Xi_hat);\n    cSE3convert(_Xj_hat, Xj_hat);\n    Eigen::Map<Eigen::Matrix<T,6,1>> r(_res);\n\n    // compute current estimated relative pose\n    const Sophus::SE3<T> Xij_hat = Xi_hat.inverse() * Xj_hat;\n\n    // compute residual via boxminus (i.e., the logarithmic map of the error pose)\n    // weight with inverse covariance\n    r = Qij_inv_.cast<T>() * (Xij_inv_.cast<T>() * Xij_hat).log();  \n\n    return true;\n  }\n\n  // cost function generator--ONLY FOR PYTHON WRAPPER\n  static ceres::CostFunction *Create(Eigen::Matrix<double,7,1> &Xij, Eigen::Matrix<double,6,6> &Qij) {\n    return new ceres::AutoDiffCostFunction<cSE3Functor,\n                                           6,\n                                           7,\n                                           7>(new cSE3Functor(Xij, Qij));\n  }\n\nprivate:\n  Sophus::SE3<double> Xij_inv_;\n  Eigen::Matrix<double,6,6> Qij_inv_;\n};\n\n// AutoDiff cost function (factor) for the difference between a range measurement\n// rij, and the relative range between two estimated poses, Xi_hat and Xj_hat. \n// Weighted by measurement variance, qij_.\nclass RangeFunctor\n{\npublic:\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  // store measured range and inverted variance\n  RangeFunctor(double &rij, double &qij)\n  {\n    rij_ = rij;\n    qij_inv_ = 1.0 / qij;\n  }\n\n  // templated residual definition for both doubles and jets\n  template<typename T>\n  bool operator()(const T* _Xi_hat, const T* _Xj_hat, T* _res) const\n  {\n    // assign memory to usable objects\n    Eigen::Matrix<T,3,1> ti_hat(_Xi_hat), tj_hat(_Xj_hat);\n\n    // range measurement error, scaled by inverse variance\n    *_res = static_cast<T>(qij_inv_) * (static_cast<T>(rij_) - (tj_hat - ti_hat).norm());\n\n    return true;\n  }\n\n  // cost function generator--ONLY FOR PYTHON WRAPPER\n  static ceres::CostFunction *Create(double &rij, double &qij) {\n    return new ceres::AutoDiffCostFunction<RangeFunctor,\n                                           1,\n                                           7,\n                                           7>(new RangeFunctor(rij, qij));\n  }\n\nprivate:\n  double rij_;\n  double qij_inv_;\n};\n\n// AutoDiff cost function (factor) for the difference between an altitude \n// measurement hi, and the altitude of an estimated pose, Xi_hat. \n// Weighted by measurement variance, qij_.\nclass AltFunctor\n{\npublic:\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  // store measured range and inverted variance\n  AltFunctor(double &hi, double &qi)\n  {\n    hi_ = hi;\n    qi_inv_ = 1.0 / qi;\n  }\n\n  // templated residual definition for both doubles and jets\n  template<typename T>\n  bool operator()(const T* _Xi_hat, T* _res) const\n  {\n    // assign memory to usable objects\n    T hi_hat = *(_Xi_hat + 2);\n\n    // altitude measurement error, scaled by inverse variance\n    *_res = static_cast<T>(qi_inv_) * (static_cast<T>(hi_) - hi_hat);\n\n    return true;\n  }\n\n  // cost function generator--ONLY FOR PYTHON WRAPPER\n  static ceres::CostFunction *Create(double &hi, double &qi) {\n    return new ceres::AutoDiffCostFunction<AltFunctor,\n                                           1,\n                                           7>(new AltFunctor(hi, qi));\n  }\n\nprivate:\n  double hi_;\n  double qi_inv_;\n};\n\n// AutoDiff cost function (factor) for the difference between a measured 3D\n// relative transform, Xij_ = (tij_, qij_), and the relative transform between two  \n// estimated poses, Xi_hat and Xj_hat. Weighted by measurement covariance, Qij_.\nclass Transform3DFunctor\n{\npublic:\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  // store measured relative pose and covariance matrix\n  Transform3DFunctor(Eigen::Matrix<double,7,1> &X, Eigen::Matrix<double,6,6> &Q)\n  {\n    tij_ = X.block<3,1>(0,0);\n    qij_ = Eigen::Quaterniond(X.block<4,1>(3,0));\n    // residual weighted by inverse covariance\n    Wij_ = Q.inverse();\n  }\n\n  // templated residual definition for both doubles and jets\n  // basically a weighted implementation of boxminus using Eigen templated types\n  template<typename T>\n  bool operator()(const T* Xi_hat, const T* Xj_hat, T* res) const\n  {\n    // assign memory to usable objects\n    Eigen::Map<const Eigen::Matrix<T,3,1>> ti_hat(Xi_hat);\n    Eigen::Quaternion<T> qi_hat(Xi_hat+3);\n    Eigen::Map<const Eigen::Matrix<T,3,1>> tj_hat(Xj_hat);\n    Eigen::Quaternion<T> qj_hat(Xj_hat+3);\n    Eigen::Map<Eigen::Matrix<T,6,1>> r(res);\n\n    // compute trivial vector subtraction component\n    Eigen::Matrix<T,3,1> t_res = tij_ - (tj_hat - ti_hat);\n\n    // compute quaternion difference component\n    Eigen::Quaternion<T> qij_hat = qi_hat.inverse() * qj_hat;\n    Eigen::Quaternion<T> q_err = qij_hat.inverse() * static_cast<Eigen::Quaternion<T>>(qij_);\n    Eigen::Matrix<T,3,1> q_res;\n    if (q_err.w() < static_cast<T>(0.0))\n    {\n      q_err.coeffs() *= static_cast<T>(-1.0);\n    }\n    const Eigen::Matrix<T,3,1> qv(q_err.vec());\n    T sinha = qv.norm();\n    if (sinha > static_cast<T>(0.0))\n    {\n      T angle = static_cast<T>(2.0) * atan2(sinha, q_err.w());\n      q_res = qv * (angle / sinha);\n    }\n    else\n    {\n      q_res = qv * (static_cast<T>(2.0) / q_err.w());\n    }\n\n    // assign to residual and weight by covariance\n    r.template block<3,1>(0,0) = t_res;\n    r.template block<3,1>(3,0) = q_res;\n    r = Wij_ * r;\n\n    return true;\n  }\n\n  // cost function generator--ONLY FOR PYTHON WRAPPER\n  static ceres::CostFunction *Create(Eigen::Matrix<double,7,1> &X, Eigen::Matrix<double,6,6> &Q) {\n    return new ceres::AutoDiffCostFunction<Transform3DFunctor,\n                                           6,\n                                           7,\n                                           7>(new Transform3DFunctor(X, Q));\n  }\n\nprivate:\n  Eigen::Matrix<double,3,1> tij_;\n  Eigen::Quaternion<double> qij_;\n  Eigen::Matrix<double,6,6> Wij_;\n};\n\n// AutoDiff cost function (factor) for the difference between a measured quaternion, \n// q_, and an estimated quaternion, q_hat.\nclass QuaterniondFunctor\n{\npublic:\n  // store internal measured quaternion\n  QuaterniondFunctor(Eigen::Vector4d &x)\n  {\n    q_ = Eigen::Quaternion<double>(x.data());\n    q_inv_ = q_.inverse();\n  }\n\n  // templated residual definition for both doubles and jets\n  template<typename T>\n  bool operator()(const T* _q_hat, T* res) const\n  {\n    Eigen::Quaternion<T> q_hat(_q_hat);\n    Eigen::Map<Eigen::Matrix<T, 3, 1>> r(res);\n\n    // implementation of boxminus using templated Eigen types\n    // https://eigen.tuxfamily.org/bz/show_bug.cgi?id=1244\n    //  q_err = q^{-1} * q_hat\n    Eigen::Quaternion<T> q_err(static_cast<Eigen::Quaternion<T>>(q_inv_)*(q_hat));\n    //  q_err -> theta vector\n    if (q_err.w() < static_cast<T>(0.0))\n    {\n      q_err.coeffs() *= static_cast<T>(-1.0);\n    }\n    const Eigen::Matrix<T,3,1> qv(q_err.vec());\n    T sinha = qv.norm();\n    if (sinha > static_cast<T>(0.0))\n    {\n      T angle = static_cast<T>(2.0) * atan2(sinha, q_err.w());\n      r = qv * (angle / sinha);\n    }\n    else\n    {\n      r = qv * (static_cast<T>(2.0) / q_err.w());\n    }\n    \n    return true;\n  }\n\n  // cost function generator--ONLY FOR PYTHON WRAPPER\n  static ceres::CostFunction *Create(Eigen::Vector4d &x) {\n    return new ceres::AutoDiffCostFunction<QuaterniondFunctor, 3, 4>(new QuaterniondFunctor(x));\n  }\n\nprivate:\n  Eigen::Quaternion<double> q_;\n  Eigen::Quaternion<double> q_inv_;\n};\n\n// AutoDiff local parameterization for the compact SE3 pose [t q] object. \n// The boxplus operator informs Ceres how the manifold evolves and also  \n// allows for the calculation of derivatives.\nstruct cSE3Plus {\n  // boxplus operator for both doubles and jets\n  template<typename T>\n  bool operator()(const T* x, const T* delta, T* x_plus_delta) const\n  {\n    // capture argument memory\n    Sophus::SE3<T> X;\n    cSE3convert(x, X);\n    Eigen::Map<const Eigen::Matrix<T, 6, 1>> dX(delta);\n    Eigen::Map<Eigen::Matrix<T, 7, 1>>       Yvec(x_plus_delta);\n\n    // increment pose using the exponential map\n    Sophus::SE3<T> Exp_dX = Sophus::SE3<T>::exp(dX);\n    Sophus::SE3<T> Y = X * Exp_dX;\n\n    // assign SE3 coefficients to compact vector\n    Eigen::Matrix<T,7,1> YvecCoef;\n    cSE3convert(Y, YvecCoef);\n    Yvec = YvecCoef;\n\n    return true;\n  }\n  \n  // local parameterization generator--ONLY FOR PYTHON WRAPPER\n  static ceres::LocalParameterization *Create() {\n    return new ceres::AutoDiffLocalParameterization<cSE3Plus,\n                                                    7,\n                                                    6>(new cSE3Plus);\n  }\n};\n\n// AutoDiff local parameterization for the Transform3D object. The boxplus\n// operator informs Ceres how the manifold evolves and also allows for the \n// calculation of derivatives\nstruct Transform3DPlus {\n  // boxplus operator for both doubles and jets\n  template<typename T>\n  bool operator()(const T* x, const T* delta, T* x_plus_delta) const\n  {\n    // capture argument memory\n    Eigen::Map<const Eigen::Matrix<T, 3, 1>> t(x);\n    Eigen::Map<const Eigen::Matrix<T, 3, 1>> dt(delta);\n    const Eigen::Quaternion<T> q(x+3);\n    Eigen::Map<const Eigen::Matrix<T, 3, 1>> dq(delta+3);\n    Eigen::Map<Eigen::Matrix<T, 7, 1>> Tplus(x_plus_delta);\n\n    // compute trivial vector addition component\n    Tplus.template block<3,1>(0,0) = t + dt;\n\n    // compute quaternion oplus component\n    Eigen::Quaternion<T> plusq;\n    T th = dq.norm();\n    if (th > static_cast<T>(0.0))\n    {\n      Eigen::Matrix<T, 3, 1> u = dq / th;\n      T sth2 = sin(th / static_cast<T>(2.0));\n      plusq = Eigen::Quaternion<T>(cos(th / static_cast<T>(2.0)), u.x()*sth2, u.y()*sth2, u.z()*sth2);\n    }\n    else\n    {\n      Eigen::Matrix<T, 3, 1> r2 = dq / static_cast<T>(2.0);\n      plusq = Eigen::Quaternion<T>(static_cast<T>(1.0), r2.x(), r2.y(), r2.z()).normalized();\n    }\n    Eigen::Quaternion<T> qplusq = q * plusq;\n    Tplus.template block<4,1>(3,0) = qplusq.coeffs();\n\n    return true;\n  }\n\n  // local parameterization generator--ONLY FOR PYTHON WRAPPER\n  static ceres::LocalParameterization *Create() {\n    return new ceres::AutoDiffLocalParameterization<Transform3DPlus,\n                                                    7,\n                                                    6>(new Transform3DPlus);\n  }\n};\n\nvoid add_custom_cost_functions(py::module &m) {\n\n  // Use pybind11 code to wrap your own cost function which is defined in C++\n\n  // Transform3DLocalParameterization\n  m.def(\"Transform3DLocalParameterization\", &Transform3DPlus::Create);\n\n  // cSE3LocalParameterization\n  m.def(\"cSE3LocalParameterization\", &cSE3Plus::Create);\n\n  // cSE3Factor\n  m.def(\"cSE3Factor\", &cSE3Functor::Create);\n\n  // RangeFactor\n  m.def(\"RangeFactor\", &RangeFunctor::Create);\n\n  // AltFactor\n  m.def(\"AltFactor\", &AltFunctor::Create);\n\n  // Transform3DFactor\n  m.def(\"Transform3DFactor\", &Transform3DFunctor::Create);\n\n  // Here is an example\n  m.def(\"CreateCustomExampleCostFunction\", &ExampleFunctor::Create);\n\n  // QuaterniondFunctor\n  m.def(\"CreateQuaterniondADCostFunction\", &QuaterniondFunctor::Create);\n\n}\n", "meta": {"hexsha": "c3a879bcd96ce698d083614a165c4a03598c6b93", "size": 13193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python_bindings/custom_cpp_cost_functions.cpp", "max_stars_repo_name": "goromal/ceres_python_bindings", "max_stars_repo_head_hexsha": "f014ca0d367c0fcd7a244a067398dac363428a54", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python_bindings/custom_cpp_cost_functions.cpp", "max_issues_repo_name": "goromal/ceres_python_bindings", "max_issues_repo_head_hexsha": "f014ca0d367c0fcd7a244a067398dac363428a54", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "python_bindings/custom_cpp_cost_functions.cpp", "max_forks_repo_name": "goromal/ceres_python_bindings", "max_forks_repo_head_hexsha": "f014ca0d367c0fcd7a244a067398dac363428a54", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4152334152, "max_line_length": 102, "alphanum_fraction": 0.6363980899, "num_tokens": 3744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.656686105860111}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <Eigen/Eigen>\n#include <vector>\n#include \"calib.h\"\n#include <fstream>\n\nint main()\n{\n\tLeapMotionsCalibration calib;\n\tstd::vector<Eigen::Vector3f> firstSet, secondSet;\n\n\tstd::ifstream o;\n\to.open(\"calib.txt\");\n\tint pairs;\n\to>>pairs;\n\tfor(int i=0;i<pairs;i++)\n\t{\n\t\tEigen::Vector3f tmp;\n\t\to >> tmp[0]; o >> tmp[1]; o >> tmp[2];\n\t\tstd::cout<<\"( \" << tmp[0] <<\" \" <<tmp[1] << \" \"<<tmp[2]<<\" )\"<< std::endl;\n\t\tfirstSet.push_back(tmp);\n\t\t\n\t\to >> tmp[0]; o >> tmp[1]; o >> tmp[2];\n\t\tstd::cout<<\"[ \" << tmp[0] <<\" \" <<tmp[1] << \" \"<<tmp[2]<<\" ]\"<< std::endl;\n\t\tsecondSet.push_back(tmp);\n\t}\n\to.close();\n\t\n\t\n\tcalib.readData(firstSet, secondSet);\n\tEigen::Matrix4f result = calib.calculateTransformation();\n\tdouble error = calib.calculateError(firstSet, secondSet, result); \n\t\n\tstd::cout<<\"Calculated transformation between two LeapMotion coordinate systems is :\"<<std::endl;\n\tstd::cout<<result<<std::endl;\n\tstd::cout<<\"RMS error: \" << error << std::endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "2f8886da20de56d6a56bc41a4e725a325db02cb7", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CalibratingMultipleLM/main.cpp", "max_stars_repo_name": "uiuyuty/vsfh", "max_stars_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T09:30:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T07:07:57.000Z", "max_issues_repo_path": "CalibratingMultipleLM/main.cpp", "max_issues_repo_name": "uiuyuty/vsfh", "max_issues_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-01T21:28:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T21:39:28.000Z", "max_forks_repo_path": "CalibratingMultipleLM/main.cpp", "max_forks_repo_name": "uiuyuty/vsfh", "max_forks_repo_head_hexsha": "49f83a7bf043f7ae872dd759a0d32336d90cf1b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-03-02T18:48:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:44:08.000Z", "avg_line_length": 24.487804878, "max_line_length": 98, "alphanum_fraction": 0.6155378486, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.656686100775123}}
{"text": "#define BOOST_TEST_MODULE \"test_math_functions\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <boost/mpl/list.hpp>\n#include <mjolnir/math/math.hpp>\n\n#include <random>\n#include <chrono>\n#include <array>\n#include <iostream>\n\ntypedef boost::mpl::list<double, float> test_targets;\nconstexpr std::size_t N = 10000;\n\nstatic_assert(mjolnir::compiletime::pow( 2.0, 4) == 16.0, \"mjolnir::compiletime::pow\");\nstatic_assert(mjolnir::compiletime::pow(-2.0, 4) == 16.0, \"mjolnir::compiletime::pow\");\nstatic_assert(mjolnir::compiletime::pow(-2.0, 3) == -8.0, \"mjolnir::compiletime::pow\");\n\nstatic_assert(mjolnir::compiletime::abs( 1.0) == 1.0, \"mjolnir::compiletime::abs\");\nstatic_assert(mjolnir::compiletime::abs(-1.0) == 1.0, \"mjolnir::compiletime::abs\");\nstatic_assert(mjolnir::compiletime::min( 1.0, 2.0) ==  1.0, \"mjolnir::compiletime::min\");\nstatic_assert(mjolnir::compiletime::min(-1.0, 0.1) == -1.0, \"mjolnir::compiletime::min\");\nstatic_assert(mjolnir::compiletime::min(2.0,  1.0) ==  1.0, \"mjolnir::compiletime::min\");\nstatic_assert(mjolnir::compiletime::min(0.1, -1.0) == -1.0, \"mjolnir::compiletime::min\");\nstatic_assert(mjolnir::compiletime::max( 1.0, 2.0) ==  2.0, \"mjolnir::compiletime::max\");\nstatic_assert(mjolnir::compiletime::max(-1.0, 0.1) ==  0.1, \"mjolnir::compiletime::max\");\nstatic_assert(mjolnir::compiletime::max(2.0,  1.0) ==  2.0, \"mjolnir::compiletime::max\");\nstatic_assert(mjolnir::compiletime::max(0.1, -1.0) ==  0.1, \"mjolnir::compiletime::max\");\n\nstatic_assert(mjolnir::compiletime::clamp( 0.1, -1.0, 1.0) ==  0.1, \"mjolnir::compiletime::clamp\");\nstatic_assert(mjolnir::compiletime::clamp( 2.0, -1.0, 1.0) ==  1.0, \"mjolnir::compiletime::clamp\");\nstatic_assert(mjolnir::compiletime::clamp(-2.0, -1.0, 1.0) == -1.0, \"mjolnir::compiletime::clamp\");\n\nnamespace test\n{\ntemplate<typename T>\ndecltype(boost::test_tools::tolerance(std::declval<T>())) tolerance();\n\ntemplate<>\ndecltype(boost::test_tools::tolerance(std::declval<float>()))\ntolerance<float>()\n{return boost::test_tools::tolerance(3.0f / static_cast<float>(std::pow(2, 12)));}\n\ntemplate<>\ndecltype(boost::test_tools::tolerance(std::declval<double>()))\ntolerance<double>()\n{return boost::test_tools::tolerance(2.0 / std::pow(2, 14));}\n} // test\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(rsqrt, Real, test_targets)\n{\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<Real> uni(0.0001, 100.0);\n\n    for(std::size_t i=0; i < N; ++i)\n    {\n        const Real x     = uni(mt);\n        const Real x_sq  = x * x;\n        const Real x_inv = 1 / x;\n        BOOST_TEST(x_inv == mjolnir::math::rsqrt(x_sq), test::tolerance<Real>());\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(clamp, Real, test_targets)\n{\n    std::mt19937 mt(123456789);\n    std::uniform_real_distribution<Real> uni(-100.0, 100.0);\n    const Real maximum =  10.0;\n    const Real minimum = -10.0;\n\n    for(std::size_t i=0; i < N; ++i)\n    {\n        const Real x = uni(mt);\n        BOOST_TEST(mjolnir::math::clamp<Real>(x, minimum, maximum) ==\n                   std::min(std::max(minimum, x), maximum),\n                   test::tolerance<Real>());\n    }\n}\n\n", "meta": {"hexsha": "d6374c7d15a6c2ca3478bcba08d51027890d77dc", "size": 3172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_math.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2017-02-01T08:28:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-25T15:47:51.000Z", "max_issues_repo_path": "test/core/test_math.cpp", "max_issues_repo_name": "Mjolnir-MD/Mjolnir", "max_issues_repo_head_hexsha": "043df4080720837042c6b67a5495ecae198bc2b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T08:11:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T08:26:36.000Z", "max_forks_repo_path": "test/core/test_math.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-01-13T11:03:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T11:38:00.000Z", "avg_line_length": 37.3176470588, "max_line_length": 99, "alphanum_fraction": 0.6689785624, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6566860999076337}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrixXd X = MatrixXd::Random(4,4);\nMatrixXd A = X * X.transpose();\ncout << \"Here is a random positive-definite matrix, A:\" << endl << A << endl << endl;\n\nSelfAdjointEigenSolver<MatrixXd> es(A);\ncout << \"The inverse square root of A is: \" << endl;\ncout << es.operatorInverseSqrt() << endl;\ncout << \"We can also compute it with operatorSqrt() and inverse(). That yields: \" << endl;\ncout << es.operatorSqrt().inverse() << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "2d681447d9d5a69700ebefc55ccd73c86466e378", "size": 959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_SelfAdjointEigenSolver_operatorInverseSqrt.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["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.0606060606, "max_line_length": 224, "alphanum_fraction": 0.6840458811, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6566180324133036}}
{"text": "// (C) Copyright Andrew Sutton 2007\r\n//\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 http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n//[eccentricity_example\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/graph/undirected_graph.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/floyd_warshall_shortest.hpp>\r\n#include <boost/graph/eccentricity.hpp>\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// The Actor type stores the name of each vertex in the graph.\r\nstruct Actor\r\n{\r\n    string name;\r\n};\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef undirected_graph<Actor> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n// The name map provides an abstract accessor for the names of\r\n// each vertex. This is used during graph creation.\r\ntypedef property_map<Graph, string Actor::*>::type NameMap;\r\n\r\n// Declare a matrix type and its corresponding property map that\r\n// will contain the distances between each pair of vertices.\r\ntypedef exterior_vertex_property<Graph, int> DistanceProperty;\r\ntypedef DistanceProperty::matrix_type DistanceMatrix;\r\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n// Declare the weight map so that each edge returns the same value.\r\ntypedef constant_property_map<Edge, int> WeightMap;\r\n\r\n// Declare a container and its corresponding property map that\r\n// will contain the resulting eccentricities of each vertex in\r\n// the graph.\r\ntypedef boost::exterior_vertex_property<Graph, int> EccentricityProperty;\r\ntypedef EccentricityProperty::container_type EccentricityContainer;\r\ntypedef EccentricityProperty::map_type EccentricityMap;\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph and a name map that provides access to\r\n    // then actor names.\r\n    Graph g;\r\n    NameMap nm(get(&Actor::name, g));\r\n\r\n    // Read the graph from standard input.\r\n    read_graph(g, nm, cin);\r\n\r\n    // Compute the distances between all pairs of vertices using\r\n    // the Floyd-Warshall algorithm. Note that the weight map is\r\n    // created so that every edge has a weight of 1.\r\n    DistanceMatrix distances(num_vertices(g));\r\n    DistanceMatrixMap dm(distances, g);\r\n    WeightMap wm(1);\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n\r\n    // Compute the eccentricities for graph - this computation returns\r\n    // both the radius and diameter as well.\r\n    int r, d;\r\n    EccentricityContainer eccs(num_vertices(g));\r\n    EccentricityMap em(eccs, g);\r\n    boost::tie(r, d) = all_eccentricities(g, dm, em);\r\n\r\n    // Print the closeness centrality of each vertex.\r\n    graph_traits<Graph>::vertex_iterator i, end;\r\n    for(boost::tie(i, end) = vertices(g); i != end; ++i) {\r\n        cout << setw(12) << setiosflags(ios::left)\r\n                << g[*i].name << get(em, *i) << endl;\r\n    }\r\n    cout << \"radius: \" << r << endl;\r\n    cout << \"diamter: \" << d << endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "734b802267e58252ec1eec430e4b560a05bc8031", "size": 3107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/eccentricity.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": 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/graph/example/eccentricity.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": 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/graph/example/eccentricity.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": 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": 34.5222222222, "max_line_length": 74, "alphanum_fraction": 0.7096878017, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6566180238027792}}
{"text": "/**\n * @file finitevolumesineconslaw.cc\n * @brief NPDE homework \"FiniteVolumeSineConsLaw\" code\n * @author Oliver Rietmann\n * @date 25.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"finitevolumesineconslaw.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace FiniteVolumeSineConsLaw {\n\n/* SAM_LISTING_BEGIN_1 */\nconstexpr double PI = 3.14159265358979323846;\n\ndouble f(double x) { return std::sin(PI * x); }\n\ndouble sineGodFlux(double v, double w) {\n  double result;\n  //====================\n  // Your code goes here\n  //====================\n\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd sineClawRhs(const Eigen::VectorXd &mu) {\n  int N = mu.size();\n  double h = 12.0 / N;\n  Eigen::VectorXd result(N);\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return result;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nbool blowup(const Eigen::VectorXd &mu) {\n  return mu.minCoeff() < 0.0 || mu.maxCoeff() > 2.0;\n}\n\nunsigned int findTimesteps() {\n  const unsigned int N = 600;\n  unsigned int ML = 100;\n  unsigned int MR = 200;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return MR;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::VectorXd sineClawReactionRhs(const Eigen::VectorXd &mu, double c) {\n  Eigen::VectorXd rhs(mu.size());\n  //====================\n  // Your code goes here\n  //====================\n  return rhs;\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace FiniteVolumeSineConsLaw\n", "meta": {"hexsha": "65d8ca046ef7a5d67194ebc3c35eb83c1c150a61", "size": 1519, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/finitevolumesineconslaw.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/finitevolumesineconslaw.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/FiniteVolumeSineConsLaw/templates/finitevolumesineconslaw.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 20.527027027, "max_line_length": 74, "alphanum_fraction": 0.6043449638, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.6566024480043845}}
{"text": "//!file\n//! \\brief floating-point comparison from Boost.Test\n// Copyright Paul A. Bristow 2015.\n// Copyright John Maddock 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#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/math/special_functions/next.hpp>\n\n#include <iostream>\n#include <limits> // for std::numeric_limits<T>::epsilon().\n\nint main()\n{\n  std::cout << \"Compare floats using Boost.Math functions/classes\" << std::endl;\n\n\n//[compare_floats_using\n/*`Some using statements will ensure that the functions we need are accessible.\n*/\n\n  using namespace boost::math;\n\n//`or\n\n  using boost::math::relative_difference;\n  using boost::math::epsilon_difference;\n  using boost::math::float_next;\n  using boost::math::float_prior;\n\n//] [/compare_floats_using]\n\n\n//[compare_floats_example_1\n/*`The following examples display values with all possibly significant digits.\nNewer compilers should provide `std::numeric_limits<FPT>::max_digits10`\nfor this purpose, and here we use `float` precision where `max_digits10` = 9\nto avoid displaying a distracting number of decimal digits.\n\n[note Older compilers can use this formula to calculate `max_digits10`\nfrom `std::numeric_limits<FPT>::digits10`:[br]\n__spaces `int max_digits10 = 2 + std::numeric_limits<FPT>::digits10 * 3010/10000;`\n] [/note]\n\nOne can set the display including all trailing zeros\n(helpful for this example to show all potentially significant digits),\nand also to display `bool` values as words rather than integers:\n*/\n  std::cout.precision(std::numeric_limits<float>::max_digits10);\n  std::cout << std::boolalpha << std::showpoint << std::endl;\n\n//] [/compare_floats_example_1]\n\n//[compare_floats_example_2]\n/*`\nWhen comparing values that are ['quite close] or ['approximately equal],\nwe could use either `float_distance` or `relative_difference`/`epsilon_difference`, for example\nwith type `float`, these two values are adjacent to each other:\n*/\n\n  float a = 1;\n  float b = 1 + std::numeric_limits<float>::epsilon();\n  std::cout << \"a = \" << a << std::endl;\n  std::cout << \"b = \" << b << std::endl;\n  std::cout << \"float_distance = \" << float_distance(a, b) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(a, b) << std::endl;\n\n/*`\nWhich produces the output:\n\n[pre\na = 1.00000000\nb = 1.00000012\nfloat_distance = 1.00000000\nrelative_difference = 1.19209290e-007\nepsilon_difference = 1.00000000\n]\n*/\n  //] [/compare_floats_example_2]\n\n//[compare_floats_example_3]\n/*`\nIn the example above, it just so happens that the edit distance as measured by `float_distance`, and the\ndifference measured in units of epsilon were equal.  However, due to the way floating point\nvalues are represented, that is not always the case:*/\n\n  a = 2.0f / 3.0f;   // 2/3 inexactly represented as a float\n  b = float_next(float_next(float_next(a))); // 3 floating point values above a\n  std::cout << \"a = \" << a << std::endl;\n  std::cout << \"b = \" << b << std::endl;\n  std::cout << \"float_distance = \" << float_distance(a, b) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(a, b) << std::endl;\n\n/*`\nWhich produces the output:\n\n[pre\na = 0.666666687\nb = 0.666666865\nfloat_distance = 3.00000000\nrelative_difference = 2.68220901e-007\nepsilon_difference = 2.25000000\n]\n\nThere is another important difference between `float_distance` and the\n`relative_difference/epsilon_difference` functions in that `float_distance`\nreturns a signed result that reflects which argument is larger in magnitude,\nwhere as `relative_difference/epsilon_difference` simply return an unsigned\nvalue that represents how far apart the values are.  For example if we swap\nthe order of the arguments:\n*/\n\n  std::cout << \"float_distance = \" << float_distance(b, a) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(b, a) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(b, a) << std::endl;\n\n  /*`\n  The output is now:\n\n  [pre\n  float_distance = -3.00000000\n  relative_difference = 2.68220901e-007\n  epsilon_difference = 2.25000000\n  ]\n*/\n  //] [/compare_floats_example_3]\n\n//[compare_floats_example_4]\n/*`\nZeros are always treated as equal, as are infinities as long as they have the same sign:*/\n\n  a = 0;\n  b = -0;  // signed zero\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  a = b = std::numeric_limits<float>::infinity();\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, -b) << std::endl;\n\n/*`\nWhich produces the output:\n\n[pre\nrelative_difference = 0.000000000\nrelative_difference = 0.000000000\nrelative_difference = 3.40282347e+038\n]\n*/\n//] [/compare_floats_example_4]\n\n//[compare_floats_example_5]\n/*`\nNote that finite values are always infinitely far away from infinities even if those finite values are very large:*/\n\n  a = (std::numeric_limits<float>::max)();\n  b = std::numeric_limits<float>::infinity();\n  std::cout << \"a = \" << a << std::endl;\n  std::cout << \"b = \" << b << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(a, b) << std::endl;\n\n/*`\nWhich produces the output:\n\n[pre\na = 3.40282347e+038\nb = 1.#INF0000\nrelative_difference = 3.40282347e+038\nepsilon_difference = 3.40282347e+038\n]\n*/\n//] [/compare_floats_example_5]\n\n//[compare_floats_example_6]\n/*`\nFinally, all denormalized values and zeros are treated as being effectively equal:*/\n\n  a = std::numeric_limits<float>::denorm_min();\n  b = a * 2;\n  std::cout << \"a = \" << a << std::endl;\n  std::cout << \"b = \" << b << std::endl;\n  std::cout << \"float_distance = \" << float_distance(a, b) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(a, b) << std::endl;\n  a = 0;\n  std::cout << \"a = \" << a << std::endl;\n  std::cout << \"b = \" << b << std::endl;\n  std::cout << \"float_distance = \" << float_distance(a, b) << std::endl;\n  std::cout << \"relative_difference = \" << relative_difference(a, b) << std::endl;\n  std::cout << \"epsilon_difference = \" << epsilon_difference(a, b) << std::endl;\n\n/*`\nWhich produces the output:\n\n[pre\na = 1.40129846e-045\nb = 2.80259693e-045\nfloat_distance = 1.00000000\nrelative_difference = 0.000000000\nepsilon_difference = 0.000000000\na = 0.000000000\nb = 2.80259693e-045\nfloat_distance = 2.00000000\nrelative_difference = 0.000000000\nepsilon_difference = 0.000000000]\n\nNotice how, in the above example, two denormalized values that are a factor of 2 apart are\nnone the less only one representation apart!\n\n*/\n//] [/compare_floats_example_6]\n\n\n#if 0\n//[old_compare_floats_example_3\n//`The simplest use is to compare two values with a tolerance thus:\n\n  bool is_close = is_close_to(1.F, 1.F + epsilon, epsilon); // One epsilon apart is close enough.\n  std::cout << \"is_close_to(1.F, 1.F + epsilon, epsilon); is \" << is_close << std::endl; // true\n\n  is_close = is_close_to(1.F, 1.F + 2 * epsilon, epsilon); // Two epsilon apart isn't close enough.\n  std::cout << \"is_close_to(1.F, 1.F + epsilon, epsilon); is \" << is_close << std::endl; // false\n\n/*`\n[note The type FPT of the tolerance and the type of the values [*must match].\n\nSo `is_close(0.1F, 1., 1.)` will fail to compile because \"template parameter 'FPT' is ambiguous\".\nAlways provide the same type, using `static_cast<FPT>` if necessary.]\n*/\n\n\n/*`An instance of class `close_at_tolerance` is more convenient\nwhen multiple tests with the same conditions are planned.\nA class that stores a tolerance of three epsilon (and the default ['strong] test) is:\n*/\n\n  close_at_tolerance<float> three_rounds(3 * epsilon); // 'strong' by default.\n\n//`and we can confirm these settings:\n\n  std::cout << \"fraction_tolerance = \"\n    << three_rounds.fraction_tolerance()\n    << std::endl; // +3.57627869e-007\n  std::cout << \"strength = \"\n    << (three_rounds.strength() == FPC_STRONG ? \"strong\" : \"weak\")\n    << std::endl; // strong\n\n//`To start, let us use two values that are truly equal (having identical bit patterns)\n\n  float a = 1.23456789F;\n  float b = 1.23456789F;\n\n//`and make a comparison using our 3*epsilon `three_rounds` functor:\n\n  bool close = three_rounds(a, b);\n  std::cout << \"three_rounds(a, b) = \" << close << std::endl; // true\n\n//`Unsurprisingly, the result is true, and the failed fraction is zero.\n\n  std::cout << \"failed_fraction = \" << three_rounds.failed_fraction() << std::endl;\n\n/*`To get some nearby values, it is convenient to use the Boost.Math __next_float functions,\nfor which we need an include\n\n  #include <boost/math/special_functions/next.hpp>\n\nand some using declarations:\n*/\n\n  using boost::math::float_next;\n  using boost::math::float_prior;\n  using boost::math::nextafter;\n  using boost::math::float_distance;\n\n//`To add a few __ulp to one value:\n  b = float_next(a); // Add just one ULP to a.\n  b = float_next(b); // Add another one ULP.\n  b = float_next(b); // Add another one ULP.\n  // 3 epsilon would pass.\n  b = float_next(b); // Add another one ULP.\n\n//`and repeat our comparison:\n\n  close = three_rounds(a, b);\n  std::cout << \"three_rounds(a, b) = \" << close << std::endl; // false\n  std::cout << \"failed_fraction = \" << three_rounds.failed_fraction()\n    << std::endl;  // abs(u-v) / abs(v) = 3.86237957e-007\n\n//`We can also 'measure' the number of bits different using the `float_distance` function:\n\n  std::cout << \"float_distance = \" << float_distance(a, b) << std::endl; // 4\n\n/*`Now consider two values that are much further apart\nthan one might expect from ['computational noise],\nperhaps the result of two measurements of some physical property like length\nwhere an uncertainty of a percent or so might be expected.\n*/\n  float fp1 = 0.01000F;\n  float fp2 = 0.01001F; // Slightly different.\n\n  float tolerance = 0.0001F;\n\n  close_at_tolerance<float> strong(epsilon); // Default is strong.\n  bool rs = strong(fp1, fp2);\n  std::cout << \"strong(fp1, fp2) is \" << rs << std::endl;\n\n//`Or we could contrast using the ['weak] criterion:\n  close_at_tolerance<float> weak(epsilon, FPC_WEAK); // Explicitly weak.\n  bool rw = weak(fp1, fp2); //\n  std::cout << \"weak(fp1, fp2) is \" << rw << std::endl;\n\n//`We can also construct, setting tolerance and strength, and compare in one statement:\n\n  std::cout << a << \" #= \" << b << \" is \"\n    << close_at_tolerance<float>(epsilon, FPC_STRONG)(a, b) << std::endl;\n  std::cout << a << \" ~= \" << b << \" is \"\n    << close_at_tolerance<float>(epsilon, FPC_WEAK)(a, b) << std::endl;\n\n//`but this has little advantage over using function `is_close_to` directly.\n\n//] [/old_compare_floats_example_3]\n\n\n/*When the floating-point values become very small and near zero, using\n//a relative test becomes unhelpful because one is dividing by zero or tiny,\n\n//Instead, an absolute test is needed, comparing one (or usually both) values with zero,\n//using a tolerance.\n//This is provided by the `small_with_tolerance` class and `is_small` function.\n\n  namespace boost {\n  namespace math {\n  namespace fpc {\n\n\n  template<typename FPT>\n  class small_with_tolerance\n  {\n  public:\n  // Public typedefs.\n  typedef bool result_type;\n\n  // Constructor.\n  explicit small_with_tolerance(FPT tolerance); // tolerance >= 0\n\n  // Functor\n  bool operator()(FPT value) const; // return true if <= absolute tolerance (near zero).\n  };\n\n  template<typename FPT>\n  bool\n  is_small(FPT value, FPT tolerance); // return true if value <= absolute tolerance (near zero).\n\n  }}} // namespaces.\n\n/*`\n[note The type FPT of the tolerance and the type of the value [*must match].\n\nSo `is_small(0.1F, 0.000001)` will fail to compile because \"template parameter 'FPT' is ambiguous\".\nAlways provide the same type, using `static_cast<FPT>` if necessary.]\n\nA few values near zero are tested with varying tolerance below.\n*/\n//[compare_floats_small_1\n\n  float c = 0;\n  std::cout << \"0 is_small \" << is_small(c, epsilon) << std::endl; // true\n\n  c = std::numeric_limits<float>::denorm_min(); // 1.40129846e-045\n  std::cout << \"denorm_ min =\" << c << \", is_small is \" << is_small(c, epsilon) << std::endl; // true\n\n  c = (std::numeric_limits<float>::min)(); // 1.17549435e-038\n  std::cout << \"min = \" << c << \", is_small is \" << is_small(c, epsilon) << std::endl; // true\n\n  c = 1 * epsilon; // 1.19209290e-007\n  std::cout << \"epsilon = \" << c << \", is_small is \" << is_small(c, epsilon) << std::endl; // false\n\n  c = 1 * epsilon; // 1.19209290e-007\n  std::cout << \"2 epsilon = \" << c << \", is_small is \" << is_small(c, 2 * epsilon) << std::endl; // true\n\n  c = 2 * epsilon; //2.38418579e-007\n  std::cout << \"4 epsilon = \" << c << \", is_small is \" << is_small(c, 2 * epsilon) << std::endl; // false\n\n  c = 0.00001F;\n  std::cout << \"0.00001 = \" << c << \", is_small is \" << is_small(c, 0.0001F) << std::endl; // true\n\n  c = -0.00001F;\n  std::cout << \"0.00001 = \" << c << \", is_small is \" << is_small(c, 0.0001F) << std::endl; // true\n\n/*`Using the class `small_with_tolerance` allows storage of the tolerance,\nconvenient if you make repeated tests with the same tolerance.\n*/\n\n  small_with_tolerance<float>my_test(0.01F);\n\n  std::cout << \"my_test(0.001F) is \" << my_test(0.001F) << std::endl; // true\n  std::cout << \"my_test(0.001F) is \" << my_test(0.01F) << std::endl; // false\n\n  //] [/compare_floats_small_1]\n#endif\n  return 0;\n}  // int main()\n\n/*\n\nExample output is:\n\n//[compare_floats_output\nCompare floats using Boost.Test functions/classes\n\nfloat epsilon = 1.19209290e-007\nis_close_to(1.F, 1.F + epsilon, epsilon); is true\nis_close_to(1.F, 1.F + epsilon, epsilon); is false\nfraction_tolerance = 3.57627869e-007\nstrength = strong\nthree_rounds(a, b) = true\nfailed_fraction = 0.000000000\nthree_rounds(a, b) = false\nfailed_fraction = 3.86237957e-007\nfloat_distance = 4.00000000\nstrong(fp1, fp2) is false\nweak(fp1, fp2) is false\n1.23456788 #= 1.23456836 is false\n1.23456788 ~= 1.23456836 is false\n0 is_small true\ndenorm_ min =1.40129846e-045, is_small is true\nmin = 1.17549435e-038, is_small is true\nepsilon = 1.19209290e-007, is_small is false\n2 epsilon = 1.19209290e-007, is_small is true\n4 epsilon = 2.38418579e-007, is_small is false\n0.00001 = 9.99999975e-006, is_small is true\n0.00001 = -9.99999975e-006, is_small is true\nmy_test(0.001F) is true\n\nmy_test(0.001F) is false//] [/compare_floats_output]\n*/\n", "meta": {"hexsha": "f39e537818b528b2b2b2f5cbe572d166a25e1a71", "size": 14835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/math/example/float_comparison_example.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/boost/libs/math/example/float_comparison_example.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/boost/libs/math/example/float_comparison_example.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 33.3370786517, "max_line_length": 116, "alphanum_fraction": 0.688776542, "num_tokens": 4317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931190663057, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.6566024357006867}}
{"text": "#include <math.h>\n#include <cstdlib>\n#include <iostream>\n\n#include <adept.h>\n\n#define N 100\n#define FILLITER 10\n\nusing adept::adouble;\n\nvoid laplacian(adouble x[N], adouble y[N])\n{\n    int i, p;\n    y[0] = -2*x[0] + x[1];\n    y[N-1] = -2*x[N-1] + x[N-2];\n    for (i = 1; i < N-1; ++i) {\n        y[i] = x[i-1] - 2*x[i] + x[i+1];\n    }\n    for (p = 0; p < FILLITER; ++p) {\n        for (i = 1; i < N-1; ++i) {\n            y[i] = y[i-1] - 2*y[i] + y[i+1]/(3.1415 + y[i]);\n        }\n    }\n}\n\nvoid doit(double *x, double *y, double *J)\n{\n    adept::Stack stack;\n    adouble xad[N], yad[N];\n    int i;\n\n    adept::set_values(xad, N, x);\n    stack.new_recording();\n\n    laplacian(xad, yad);\n\n    stack.independent(xad, N);\n    stack.dependent(yad, N);\n    stack.jacobian(J);\n\n    for (i = 0; i < N; ++i) {\n\ty[i] = yad[i].value();\n    }\n}\n\n\nint main() {\n    double x[N];\n    double y[N];\n    double J[N*N];\n    int rep, i, j;\n\n    for (i = 0; i < N; ++i) {\n        x[i] = 1.0 + i + 1;\n    }\n\n    for (rep = 0; rep < int(1e8/(N*N)); ++rep) {\n        doit(x, y, J);\n    }\n\n    for (i = 0; i < 5; ++i) {\n        std::cout << y[i] << std::endl;\n    }\n    for (i = 0; i < 5; ++i) {\n        for (j = 0; j < 5; ++j) {\n            std::cout << J[i + N*j] << \" \";\n        }\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "08a0b65d6cc683321a5469ab0a49cd087b2c609f", "size": 1311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bench_simple_adept.cpp", "max_stars_repo_name": "gyzhangqm/adjac", "max_stars_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2017-07-18T18:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T19:01:59.000Z", "max_issues_repo_path": "examples/bench_simple_adept.cpp", "max_issues_repo_name": "pv/adjac", "max_issues_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "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/bench_simple_adept.cpp", "max_forks_repo_name": "pv/adjac", "max_forks_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T21:02:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-23T19:12:17.000Z", "avg_line_length": 17.7162162162, "max_line_length": 60, "alphanum_fraction": 0.4218154081, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6565761089395136}}
{"text": "#include \"stdafx.h\"\n#include \"EllipticOrbit.h\"\n#include <tuple>\n#include <limits>\n#include <boost/math/tools/roots.hpp>\n\nnamespace\n{\n// \u041c\u0430\u0442\u0447\u0430\u0441\u0442\u044c \u0432\u0437\u044f\u0442\u0430 \u043e\u0442\u0441\u044e\u0434\u0430: http://www.astronet.ru/db/msg/1190817/node21.html#ll60\n\n// \u0423\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0435 \u043a\u0435\u043f\u043b\u0435\u0440\u0430, \u0437\u0430\u0434\u0430\u044e\u0449\u0435\u0435 \u0441\u0432\u044f\u0437\u044c \u043c\u0435\u0436\u0434\u0443 \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u043e\u0439 \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u0435\u0439,\n// \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0441\u0438\u0442\u0435\u0442\u043e\u043c \u043e\u0440\u0431\u0438\u0442\u044b \u0438 \u0441\u0440\u0435\u0434\u043d\u0435\u0439 \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u0435\u0439\n//      M = E - e * sin(E)\n// \u0433\u0434\u0435 M - \u0441\u0440\u0435\u0434\u043d\u044f\u044f \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u044f, e - \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0441\u0438\u0442\u0435\u0442 \u043e\u0440\u0431\u0438\u0442\u044b, E - \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u0430\u044f \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u044f\n// \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0435 `M = E - e * sin(E)` \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u0443\u0435\u0442\u0441\u044f \u0442\u0430\u043a, \u0447\u0442\u043e\u0431\u044b \u0441\u043b\u0435\u0432\u0430 \u0431\u044b\u043b\u043e \u0447\u0438\u0441\u043b\u043e 0,\n// \u0430 \u0441\u043f\u0440\u0430\u0432\u0430 - \u043d\u0435\u043a\u043e\u0442\u043e\u0440\u0430\u044f \u0444\u0443\u043d\u043a\u0446\u0438\u044f F(E):\n//      0 = E - M - e * sin(E)\n// \u0424\u0443\u043d\u043a\u0442\u043e\u0440 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u044e \u043e\u0442 E, \u0430 \u0442\u0430\u043a\u0436\u0435 \u0434\u0432\u0435 \u0435\u0451 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u044b\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438.\n//      F(E) = E - M - e * sin(E)\n//      F'(E) = 1 - e * cos(E)\n//      F''(E) = e * sin(E)\nusing FunctionSnapshot = boost::math::tuple<double, double, double>;\nusing EquationFunction = std::function<FunctionSnapshot(const double &x)>;\n\nEquationFunction MakeKeplerEquationFunction(double meanAnomaly, double eccentricity)\n{\n    return [=](const double &x) {\n        return boost::math::make_tuple(\n                    x - meanAnomaly - eccentricity * sin(x),    // \u0444\u0443\u043d\u043a\u0446\u0438\u044f\n                    1 - eccentricity * cos(x),                  // \u0435\u0451 \u043f\u0435\u0440\u0432\u0430\u044f \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u0430\u044f\n                    eccentricity * sin(x));                     // \u0435\u0451 \u0432\u0442\u043e\u0440\u0430\u044f \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u043d\u0430\u044f\n    };\n}\n\n// \u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0432\u044b\u043f\u043e\u043b\u043d\u044f\u0435\u0442 \u0447\u0438\u0441\u043b\u0435\u043d\u043e\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u044f \u043a\u0435\u043f\u043b\u0435\u0440\u0430,\n// \u0432\u044b\u0447\u0438\u0441\u043b\u044f\u044f \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0447\u0435\u0441\u043a\u0443\u044e \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u044e\n// \u043f\u0440\u0438 \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u044b\u0445 \u0441\u0440\u0435\u0434\u043d\u0435\u0439 \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u0438 \u0438 \u044d\u043a\u0441\u0446\u0435\u043d\u0442\u0440\u0438\u0441\u0438\u0442\u0435\u0442\u0435 \u043e\u0440\u0431\u0438\u0442\u044b\n// \u0412 \u043a\u0430\u0447\u0435\u0441\u0442\u0432\u0435 \u0440\u0435\u0448\u0435\u043d\u0438\u044f \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0435\u0442\u0441\u044f \u043c\u0435\u0442\u043e\u0434 Halley\n// (http://en.wikipedia.org/wiki/Halley's_method),\n// \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u0441\u043e\u043e\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b \u0431\u0438\u0431\u043b\u0438\u043e\u0442\u0435\u043a\u0438 boost.\ndouble SolveKeplerEquation(double const& meanAnomaly, double const& eccentricity)\n{\n    const int digits = (std::numeric_limits<double>::digits) >> 1;\n    // \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0438\u0432\u0430\u0435\u043c \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0439,\n    // \u043f\u043e\u0441\u043a\u043e\u043b\u044c\u043a\u0443 \u043c\u044b \u0440\u0438\u0441\u0443\u0435\u043c \u0441\u0438\u0441\u0442\u0435\u043c\u0443 \u043f\u043b\u0430\u043d\u0435\u0442 \u0432 \u0440\u0435\u0430\u043b\u044c\u043d\u043e\u043c \u0432\u0440\u0435\u043c\u0435\u043d\u0438.\n    boost::uintmax_t maxIteractions = 1000;\n\n    return boost::math::tools::halley_iterate(\n        MakeKeplerEquationFunction(meanAnomaly, eccentricity),\n        meanAnomaly,                // \u043f\u0435\u0440\u0432\u043e\u0435 \u043f\u0440\u0438\u0431\u043b\u0438\u0436\u0435\u043d\u0438\u0435 \u043a\u043e\u0440\u043d\u044f\n        meanAnomaly - eccentricity, // \u043c\u0438\u043d\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043a\u043e\u0440\u043d\u044f\n        meanAnomaly + eccentricity, // \u043c\u0430\u043a\u0441\u0438\u043c\u0430\u043b\u044c\u043d\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u043a\u043e\u0440\u043d\u044f\n        digits,                     // \u0447\u0438\u0441\u043b\u043e \u0440\u0430\u0437\u0440\u044f\u0434\u043e\u0432\n        maxIteractions);            // \u043d\u0430\u0438\u0431\u043e\u043b\u044c\u0448\u0435\u0435 \u0447\u0438\u0441\u043b\u043e \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u0439\n}\n}\n\ndouble CEllipticOrbit::Eccentricity() const\n{\n    return m_eccentricity;\n}\n\ndouble CEllipticOrbit::LargeAxis() const\n{\n    return m_largeAxis;\n}\n\ndouble CEllipticOrbit::MeanAnomaly(const double &time) const\n{\n    const double anomaly = 2 * M_PI * m_meanMotion * (time - m_periapsisEpoch);\n    const double wrappedAnomaly = fmod(anomaly, M_PI + M_PI);\n    return wrappedAnomaly;\n}\n\ndouble CEllipticOrbit::EccentricityAnomaly(const double &time) const\n{\n    return SolveKeplerEquation(MeanAnomaly(time), m_eccentricity);\n}\n\ndouble CEllipticOrbit::TrueAnomaly(const double &eccentricityAnomaly) const\n{\n    // \u0422\u0430\u043d\u0433\u0435\u043d\u0441 \u043f\u043e\u043b\u043e\u0432\u0438\u043d\u0447\u0430\u0442\u043e\u0433\u043e \u0443\u0433\u043b\u0430\n    const double tg_v_2 = sqrt((1 + m_eccentricity) / (1 - m_eccentricity)) * tan(eccentricityAnomaly / 2);\n    // \u041f\u043e\u043b\u043e\u0432\u0438\u043d\u0447\u0430\u0442\u044b\u0439 \u0443\u0433\u043e\u043b\n    const double v_2 = atan(tg_v_2);\n    // \u0418\u0441\u0442\u0438\u043d\u043d\u0430\u044f \u0430\u043d\u043e\u043c\u0430\u043b\u0438\u044f\n    return v_2 + v_2;\n}\n\ndouble CEllipticOrbit::RadiusVectorLength(const double &eccentricityAnomaly) const\n{\n    return m_largeAxis * (1 - m_eccentricity * cos(eccentricityAnomaly));\n}\n\nglm::vec2 CEllipticOrbit::PlanetPosition2D(const double &time) const\n{\n    const double e = EccentricityAnomaly(time);\n    const float r = float(RadiusVectorLength(e));\n    const float v = float(TrueAnomaly(e));\n    return { r * cosf(v), r * sinf(v) };\n}\n", "meta": {"hexsha": "4dea2ec029db042fc3ffaa5404fd87aa0727b833", "size": 3644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "chapter_4/lesson_21/EllipticOrbit.cpp", "max_stars_repo_name": "sergey-shambir/cg_course_examples", "max_stars_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-13T20:47:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T18:18:03.000Z", "max_issues_repo_path": "chapter_4/lesson_21/EllipticOrbit.cpp", "max_issues_repo_name": "sergey-shambir/cg_course_examples", "max_issues_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_issues_repo_licenses": ["MIT"], "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_4/lesson_21/EllipticOrbit.cpp", "max_forks_repo_name": "sergey-shambir/cg_course_examples", "max_forks_repo_head_hexsha": "921b6218d71731bcb79ddddcc92c9d04a72c62ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-24T16:24:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T11:23:57.000Z", "avg_line_length": 35.7254901961, "max_line_length": 107, "alphanum_fraction": 0.6863336992, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6565760982938367}}
{"text": "/*\n * @file geosdb.cpp\n *\n * @author a.sanchez@uni-muenster.de\n *\n * @brief Shared library that loads some geospatial functions into SciDB.\n */\n#include <vector>\n#include <boost/assign.hpp>\n#include <math.h>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n\n#include \"query/Operator.h\"\n#include \"query/FunctionLibrary.h\"\n#include \"query/FunctionDescription.h\"\n#include \"query/TypeSystem.h\"\n\nusing namespace std;\nusing namespace scidb;\nusing namespace boost::assign;\nusing namespace boost::geometry;\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\nvoid checkispointinpolygon(const Value** args, Value* res, void*)\n{\n\tdouble x = args[0]->getDouble();\n\tdouble y = args[1]->getDouble();\n\tstd::string wktPolygon = args[2]->getString();\n\n\tmodel::polygon<model::d2::point_xy<double> > poly;\n\tboost::geometry::read_wkt(wktPolygon, poly);\n\tboost::tuple<double, double> p = boost::make_tuple(x, y);\n\tres->setBool(within(p, poly));\n}\n\n\nvoid checkisprime(const Value** args, Value* res, void*)\n{\n\tint64_t i,n;\n\tint8_t r;\n\tstringstream ss;\n\n    n = args[0]->getInt64();\n\tr = 0;\n\tss << n;\n\n\tif(n>1)\n\t\tfor(i=2;i<=sqrt(n);i++)\n\t\t\tif(n%i==0)\n\t\t\t{\n\t\t\t\tr = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\tif(r==0 && n>1)\n\t\tss << \" :prime\";\n\telse\n \t\tss << \" :not prime\";\n\n    res->setString(ss.str().c_str());\n\n}\n\nREGISTER_FUNCTION(isprime, list_of(\"int64\"), \"string\", checkisprime);\nREGISTER_FUNCTION(ispointinpolygon, list_of(\"double\")(\"double\")(\"string\"), \"bool\", checkispointinpolygon);\n\n\n\n", "meta": {"hexsha": "3e4a2e298109d3769c604adf686650ac0f2d0acd", "size": 1596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geosdb.cpp", "max_stars_repo_name": "albhasan/geosdb", "max_stars_repo_head_hexsha": "d0a165fd062c966e5f48703c85cab595929f0c1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geosdb.cpp", "max_issues_repo_name": "albhasan/geosdb", "max_issues_repo_head_hexsha": "d0a165fd062c966e5f48703c85cab595929f0c1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geosdb.cpp", "max_forks_repo_name": "albhasan/geosdb", "max_forks_repo_head_hexsha": "d0a165fd062c966e5f48703c85cab595929f0c1a", "max_forks_repo_licenses": ["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.8630136986, "max_line_length": 106, "alphanum_fraction": 0.6923558897, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6565760968093312}}
{"text": "// This scripts runs the simulations with four populations (Section 6.1)\n\n#include <src/algorithms/neal2_algorithm.h>\n#include <src/algorithms/semihdp_sampler.h>\n#include <src/collectors/file_collector.h>\n#include <src/collectors/memory_collector.h>\n#include <src/includes.h>\n#include <src/utils/rng.h>\n\n#include <Eigen/Dense>\n#include <chrono>\n#include <stan/math/prim.hpp>\n#include <vector>\n\nusing Eigen::MatrixXd;\n\nMatrixXd generate_mixture(double m1, double s1, double m2, double s2, double w,\n                          int n) {\n  auto& rng = bayesmix::Rng::Instance().get();\n  MatrixXd out(n, 1);\n  for (int i = 0; i < n; i++) {\n    if (stan::math::uniform_rng(0, 1, rng) < w) {\n      out(i, 0) = stan::math::normal_rng(m1, s1, rng);\n    } else {\n      out(i, 0) = stan::math::normal_rng(m2, s2, rng);\n    }\n  }\n  return out;\n}\n\nvoid run_semihdp2(const std::vector<MatrixXd> data, std::string chainfile,\n                  std::string update_c = \"full\") {\n  // compute overall mean\n  double mu0 = std::accumulate(\n      data.begin(), data.end(), 0,\n      [&](int curr, const MatrixXd dat) { return curr + dat.sum(); });\n  mu0 /= std::accumulate(\n      data.begin(), data.end(), 0.0,\n      [&](int curr, const MatrixXd dat) { return curr + dat.rows(); });\n  auto hier = std::make_shared<NNIGHierarchy>();\n  bayesmix::NNIGPrior hier_prior;\n  hier_prior.mutable_fixed_values()->set_mean(mu0);\n  hier_prior.mutable_fixed_values()->set_var_scaling(0.1);\n  hier_prior.mutable_fixed_values()->set_shape(2.0);\n  hier_prior.mutable_fixed_values()->set_scale(2.0);\n  hier->get_mutable_prior()->CopyFrom(hier_prior);\n  hier->initialize();\n\n  // Collect pseudo priors\n  std::vector<MemoryCollector> pseudoprior_collectors;\n  pseudoprior_collectors.resize(data.size());\n  bayesmix::DPPrior mix_prior;\n  double totalmass = 1.0;\n  mix_prior.mutable_fixed_value()->set_totalmass(totalmass);\n  for (int i = 0; i < data.size(); i++) {\n    auto mixing = std::make_shared<DirichletMixing>();\n    mixing->get_mutable_prior()->CopyFrom(mix_prior);\n    mixing->set_num_components(5);\n    auto hier = std::make_shared<NNIGHierarchy>();\n    bayesmix::NNIGPrior hier_prior;\n    hier_prior.mutable_fixed_values()->set_mean(data[i].mean());\n    hier_prior.mutable_fixed_values()->set_var_scaling(0.1);\n    hier_prior.mutable_fixed_values()->set_shape(2.0);\n    hier_prior.mutable_fixed_values()->set_scale(2.0);\n    hier->get_mutable_prior()->CopyFrom(hier_prior);\n\n    Neal2Algorithm sampler;\n    sampler.set_maxiter(2000);\n    sampler.set_burnin(1000);\n    sampler.set_mixing(mixing);\n    sampler.set_data(data[i]);\n    sampler.set_hierarchy(hier);\n    sampler.run(&pseudoprior_collectors[i], false);\n  }\n\n  auto start = std::chrono::high_resolution_clock::now();\n  int nadapt = 10000;\n  int nburn = 5000;\n  int niter = 5000;\n  MemoryCollector collector;\n\n  bayesmix::SemiHdpParams params;\n  bayesmix::read_proto_from_file(\n      \"/home/mario/dev/bayesmix/resources/semihdp_params.asciipb\", &params);\n  params.set_rest_allocs_update(update_c);\n\n  SemiHdpSampler sampler(data, hier, params);\n  sampler.run(nadapt, nburn, niter, 5, &collector, pseudoprior_collectors,\n              true, 200);\n  auto end = std::chrono::high_resolution_clock::now();\n  auto duration =\n      std::chrono::duration_cast<std::chrono::seconds>(end - start).count();\n  std::cout << \"Finished running, duration: \" << duration << std::endl;\n\n  collector.write_to_file<bayesmix::SemiHdpState>(chainfile);\n}\n\nint main() {\n  // Scenario IV std::vector<MatrixXd> data1(4);\n  std::vector<MatrixXd> data1(4);\n  std::cout << \"data1.size(): \" << data1.size() << std::endl;\n  for (int i = 0; i < 4; i++) {\n    data1[i] = MatrixXd::Zero(100, 1);\n  }\n  std::cout << data1[0].transpose() << std::endl;\n  std::cout << \"assigning stuff to data1\" << std::endl;\n\n  for (int j = 0; j < 100; j++) {\n    for (int i = 0; i < 3; i++) {\n      auto& rng = bayesmix::Rng::Instance().get();\n      data1[i](j, 0) = stan::math::normal_rng(0.0, 1.0, rng);\n    }\n    auto& rng = bayesmix::Rng::Instance().get();\n    data1[3](j, 0) = stan::math::skew_normal_rng(0.0, 1.0, 1.0, rng);\n  }\n\n  std::cout << data1[0].transpose() << std::endl;\n  std::cout << data1[1].transpose() << std::endl;\n  std::cout << data1[2].transpose() << std::endl;\n  std::cout << data1[3].transpose() << std::endl;\n\n  std::cout << \"Data1 OK\" << std::endl;\n  run_semihdp2(data1,\n               \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n               \"new_chains/s2e1_fullv2.recordio\");\n  // run_semihdp2(data1,\n  //              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n  //              \"new_chains/s2e1_metro_basev2.recordio\",\n  //              \"metro_base\");\n  // run_semihdp2(data1,\n  //              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n  //              \"new_chains/s2e1_metro_distv2.recordio\",\n  //              \"metro_dist\");\n\n  // // Scenario V\n  // auto& rng = bayesmix::Rng::Instance().get();\n  // std::vector<MatrixXd> data2(4);\n  // for (int i = 0; i < 4; i++) {\n  //   data2[i].resize(100, 1);\n  // }\n\n  // for (int j = 0; j < 100; j++) {\n  //   data2[0](j, 0) = stan::math::normal_rng(0, 1, rng);\n  //   data2[3](j, 0) = stan::math::normal_rng(0, 1, rng);\n  //   data2[1](j, 0) = stan::math::normal_rng(0, std::sqrt(2.25), rng);\n  //   data2[2](j, 0) = stan::math::normal_rng(0, std::sqrt(0.25), rng);\n  // }\n\n  // std::cout << \"Data2 OK\" << std::endl;\n  // run_semihdp2(data2,\n  //              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n  //              \"new_chains/s2e2.recordio\");\n\n  // // // Scenario VI\n  // std::vector<MatrixXd> data3(4);\n  // data3[0] = generate_mixture(0, 1, 5, 1, 0.5, 100);\n  // data3[1] = generate_mixture(0, 1, 5, 1, 0.5, 100);\n  // data3[2] = generate_mixture(0, 1, -5, 1, 0.5, 100);\n  // data3[3] = generate_mixture(-5, 1, 5, 1, 0.5, 100);\n\n  // std::cout << \"Data3 OK\" << std::endl;\n\n  // run_semihdp2(data3,\n  //              \"/home/mario/PhD/exchangeability/semihdp-scripts/\"\n  //              \"new_chains/s2e3.recordio\");\n}", "meta": {"hexsha": "a759278ccb50333a0f5bef040200a62a0f776e55", "size": 6011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "run_simulation2.cpp", "max_stars_repo_name": "mberaha/semihdp-scripts", "max_stars_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "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": "run_simulation2.cpp", "max_issues_repo_name": "mberaha/semihdp-scripts", "max_issues_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "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": "run_simulation2.cpp", "max_forks_repo_name": "mberaha/semihdp-scripts", "max_forks_repo_head_hexsha": "fbf5e9c97644096357912c05bb8b4d7715d01b9e", "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.2108433735, "max_line_length": 79, "alphanum_fraction": 0.6266844119, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6565628352332311}}
{"text": "/*\n * Copyright 2017 Mahdi Khanalizadeh\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 HEADER_EXT_VECTOR2_HPP_INCLUDED\n#define HEADER_EXT_VECTOR2_HPP_INCLUDED\n\n#include <cmath>\n\n#include <boost/operators.hpp>\n\nnamespace ext\n{\n\n\ttemplate <typename T>\n\tclass Vector2 :\n\t\tboost::equality_comparable<Vector2<T>,\n\t\tboost::additive<Vector2<T>,\n\t\tboost::multiplicative<Vector2<T>, T\n\t\t>>>\n\t{\n\tpublic:\n\t\tusing Type = T;\n\n\t\tType x;\n\t\tType y;\n\n\t\tVector2() : x{0}, y{0} {}\n\t\tVector2(Type x_, Type y_) : x{x_}, y{y_} {}\n\t\ttemplate <typename U>\n\t\tVector2(Vector2<U> const& v) : x{v.x}, y{v.y} {}\n\t};\n\n\tusing Vector2f = Vector2<float>;\n\tusing Vector2d = Vector2<double>;\n\tusing Vector2ld = Vector2<long double>;\n\n\ttemplate <typename T>\n\tbool operator==(Vector2<T> const& v1, Vector2<T> const& v2)\n\t{\n\t\treturn v1.x == v2.x && v1.y == v2.y;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T>& operator+=(Vector2<T>& v1, Vector2<T> const& v2)\n\t{\n\t\tv1.x += v2.x;\n\t\tv1.y += v2.y;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T>& operator-=(Vector2<T>& v1, Vector2<T> const& v2)\n\t{\n\t\tv1.x -= v2.x;\n\t\tv1.y -= v2.y;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T>& operator*=(Vector2<T>& v, T t)\n\t{\n\t\tv.x *= t;\n\t\tv.y *= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T>& operator/=(Vector2<T>& v, T t)\n\t{\n\t\tv.x /= t;\n\t\tv.y /= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T> operator+(Vector2<T> const& v)\n\t{\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector2<T> operator-(Vector2<T> const& v)\n\t{\n\t\treturn {-v.x, -v.y};\n\t}\n\n\ttemplate <typename T>\n\tT dot(Vector2<T> const& v1, Vector2<T> const& v2)\n\t{\n\t\treturn v1.x * v2.x + v1.y * v2.y;\n\t}\n\n\ttemplate <typename T>\n\tT norm(Vector2<T> const& v)\n\t{\n\t\treturn std::sqrt(dot(v, v));\n\t}\n\n\ttemplate <typename T>\n\tVector2<T> normalize(Vector2<T> const& v)\n\t{\n\t\treturn v / norm(v);\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_VECTOR2_HPP_INCLUDED\n", "meta": {"hexsha": "5bff431f0bda6cf28f77ea7b84ffcbb544679233", "size": 2393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/vector2.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/vector2.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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/ext/vector2.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "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.7768595041, "max_line_length": 75, "alphanum_fraction": 0.6498119515, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6564820366377401}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n#include <map>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass OnsetDetectionFuncs\n{\n\npublic:\n  enum class ODF {\n    kEnergy,\n    kHFC,\n    kSpectralFlux,\n    kMKL,\n    kIS,\n    kCosine,\n    kPhaseDev,\n    kWPhaseDev,\n    kComplexDev,\n    kRComplexDev\n  };\n\n  using ArrayXcd = Eigen::ArrayXcd;\n  using ArrayXd = Eigen::ArrayXd;\n  using ODFMap =\n      std::map<ODF, std::function<double(ArrayXcd, ArrayXcd, ArrayXcd)>>;\n\n  static ArrayXd wrapPhase(ArrayXd phase)\n  {\n    return phase.unaryExpr([=](const double p) {\n      return p > (-pi) && p > pi\n                 ? p\n                 : p + (twoPi) * (1.0 + floor((-pi - p) / twoPi));\n    });\n  }\n\n  static ODFMap& map()\n  {\n    static ODFMap _funcs = {\n\n        {ODF::kEnergy,\n         [](ArrayXcd cur, ArrayXcd /*prev*/, ArrayXcd /*prevprev*/) {\n           return cur.abs().real().square().mean();\n         }},\n        {ODF::kHFC,\n         [](ArrayXcd cur, ArrayXcd /*prev*/, ArrayXcd /*prevprev*/) {\n           index   n = cur.size();\n           ArrayXd space = ArrayXd(n);\n           space.setLinSpaced(0, n);\n           return (space * cur.abs().real().square()).mean();\n         }},\n        {ODF::kSpectralFlux,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n           return (cur.abs().real() - prev.abs().real()).max(0.0).mean();\n         }},\n        {ODF::kMKL,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n           ArrayXd mag1 = cur.abs().real().max(epsilon);\n           ArrayXd mag2 = prev.abs().real().max(epsilon);\n           return (mag1 / mag2).max(epsilon).log().mean();\n         }},\n        {ODF::kIS,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n           ArrayXd mag1 = cur.abs().real().max(epsilon);\n           ArrayXd mag2 = prev.abs().real().max(epsilon);\n           ArrayXd ratio = (mag1 / mag2).square().max(epsilon);\n           return (ratio - ratio.log() - 1).mean();\n         }},\n        {ODF::kCosine,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n           ArrayXd mag1 = cur.abs().real().max(epsilon);\n           ArrayXd mag2 = prev.abs().real().max(epsilon);\n           double  norm = mag1.matrix().norm() * mag2.matrix().norm();\n           double  dot = mag1.matrix().dot(mag2.matrix());\n           return dot / norm;\n         }},\n        {ODF::kPhaseDev,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n           ArrayXd phaseAcc = (cur.atan().real() - prev.atan().real()) -\n                              (prev.atan().real() - prevprev.atan().real());\n           return wrapPhase(phaseAcc).mean();\n         }},\n        {ODF::kWPhaseDev,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n           ArrayXd mag1 = cur.abs().real().max(epsilon);\n           ArrayXd phaseAcc = (cur.atan().real() - prev.atan().real()) -\n                              (prev.atan().real() - prevprev.atan().real());\n           return wrapPhase(mag1 * phaseAcc).mean();\n         }},\n        {ODF::kComplexDev,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n           ArrayXcd target(cur.size());\n           ArrayXd  prevMag = prev.abs().real().max(epsilon);\n           ArrayXd  prevPhase = prev.atan().real();\n           ArrayXd  phaseEst = wrapPhase(\n               prevPhase + (prev.atan().real() - prevprev.atan().real()));\n           target.real() = prevMag * phaseEst.cos();\n           target.imag() = prevMag * phaseEst.sin();\n           return (target - cur).abs().real().mean();\n         }},\n        {ODF::kRComplexDev,\n         [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n           ArrayXcd target(cur.size());\n           ArrayXd  prevMag = prev.abs().real().max(epsilon);\n           ArrayXd  prevPhase = prev.atan().real();\n           ArrayXd  phaseEst = wrapPhase(\n               prevPhase + (prev.atan().real() - prevprev.atan().real()));\n           target.real() = prevMag * phaseEst.cos();\n           target.imag() = prevMag * phaseEst.sin();\n           return (target - cur).abs().real().max(0.0).mean();\n         }},\n    };\n    return _funcs;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "a97f3008163594431c1b5b785e69da83d4d26bbf", "size": 4661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/OnsetDetectionFuncs.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/OnsetDetectionFuncs.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/OnsetDetectionFuncs.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": 34.5259259259, "max_line_length": 76, "alphanum_fraction": 0.5509547307, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6564406787832269}}
{"text": "#include \"BayesFilters/WhiteNoiseAcceleration.h\"\n\n#include <cmath>\n#include <utility>\n\n#include <Eigen/Cholesky>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(float T, float tilde_q, unsigned int seed) noexcept :\n    T_(T), tilde_q_(tilde_q),\n    generator_(std::mt19937_64(seed)), distribution_(std::normal_distribution<float>(0.0, 1.0)), gauss_rnd_sample_([&] { return (distribution_)(generator_); })\n{\n    F_ << 1.0,  T_, 0.0, 0.0,\n          0.0, 1.0, 0.0, 0.0,\n          0.0, 0.0, 1.0,  T_,\n          0.0, 0.0, 0.0, 1.0;\n\n    float q11 = 1.0/3.0 * std::pow(T_, 3.0);\n    float q2  = 1.0/2.0 * std::pow(T_, 2.0);\n    Q_ << q11,  q2, 0.0, 0.0,\n           q2,  T_, 0.0, 0.0,\n          0.0, 0.0, q11,  q2,\n          0.0, 0.0,  q2,  T_;\n    Q_ *= tilde_q;\n\n    LDLT<Matrix4f> chol_ldlt(Q_);\n    sqrt_Q_ = (chol_ldlt.transpositionsP() * Matrix4f::Identity()).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n}\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(float T, float tilde_q) noexcept :\n    WhiteNoiseAcceleration(T, tilde_q, 1) { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration() noexcept :\n    WhiteNoiseAcceleration(1.0, 1.0, 1) { }\n\n\nWhiteNoiseAcceleration::~WhiteNoiseAcceleration() noexcept { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(const WhiteNoiseAcceleration& wna) :\n    T_(wna.T_), F_(wna.F_), Q_(wna.Q_), tilde_q_(wna.tilde_q_),\n    sqrt_Q_(wna.sqrt_Q_), generator_(wna.generator_), distribution_(wna.distribution_), gauss_rnd_sample_(wna.gauss_rnd_sample_) { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(WhiteNoiseAcceleration&& wna) noexcept :\n    T_(wna.T_), F_(std::move(wna.F_)), Q_(std::move(wna.Q_)), tilde_q_(wna.tilde_q_),\n    sqrt_Q_(std::move(wna.sqrt_Q_)), generator_(std::move(wna.generator_)), distribution_(std::move(wna.distribution_)), gauss_rnd_sample_(std::move(wna.gauss_rnd_sample_))\n{\n    wna.T_       = 0.0;\n    wna.tilde_q_ = 0.0;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(const WhiteNoiseAcceleration& wna)\n{\n    WhiteNoiseAcceleration tmp(wna);\n    *this = std::move(tmp);\n\n    return *this;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(WhiteNoiseAcceleration&& wna) noexcept\n{\n    T_       = wna.T_;\n    F_       = std::move(wna.F_);\n    Q_       = std::move(wna.Q_);\n    tilde_q_ = wna.tilde_q_;\n\n    sqrt_Q_           = std::move(wna.sqrt_Q_);\n    generator_        = std::move(wna.generator_);\n    distribution_     = std::move(wna.distribution_);\n    gauss_rnd_sample_ = std::move(wna.gauss_rnd_sample_);\n\n    wna.T_       = 0.0;\n    wna.tilde_q_ = 0.0;\n\n    return *this;\n}\n\n\nvoid WhiteNoiseAcceleration::propagate(const Ref<const MatrixXf>& cur_states, Ref<MatrixXf> prop_states)\n{\n    prop_states = F_ * cur_states;\n}\n\n\nvoid WhiteNoiseAcceleration::motion(const Ref<const MatrixXf>& cur_states, Ref<MatrixXf> prop_states)\n{\n    propagate(cur_states, prop_states);\n\n    prop_states += getNoiseSample(prop_states.cols());\n}\n\n\nMatrixXf WhiteNoiseAcceleration::getNoiseSample(const int num)\n{\n    MatrixXf rand_vectors(4, num);\n    for (int i = 0; i < rand_vectors.size(); i++)\n        *(rand_vectors.data() + i) = gauss_rnd_sample_();\n\n    return sqrt_Q_ * rand_vectors;\n}\n\n\nMatrixXf WhiteNoiseAcceleration::getNoiseCovarianceMatrix()\n{\n    return Q_;\n}\n", "meta": {"hexsha": "7b784c0ccab9c2b68e339677f9861c88820865bb", "size": 3346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_stars_repo_name": "claudiofantacci/bayes-filters-lib", "max_stars_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "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/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_issues_repo_name": "claudiofantacci/bayes-filters-lib", "max_issues_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "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/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_forks_repo_name": "claudiofantacci/bayes-filters-lib", "max_forks_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "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.0956521739, "max_line_length": 172, "alphanum_fraction": 0.6772265392, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.6562876567764888}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nnamespace dr {\n\n/// Calculate average orientation using quaternions\ntemplate<typename DataType, typename ForwardIterator>\nEigen::Quaternion<DataType> averageQuaternions(ForwardIterator const & begin, ForwardIterator const & end) {\n\n\tif (begin == end) {\n\t\tthrow std::logic_error(\"Cannot average orientations over an empty range.\");\n\t}\n\n\tEigen::Matrix<DataType, 4, 4> A = Eigen::Matrix<DataType, 4, 4>::Zero();\n\tuint sum(0);\n\tfor (ForwardIterator it = begin; it != end; ++it) {\n\t\tEigen::Matrix<DataType, 1, 4> q(1,4);\n\t\tq(0) = it->w();\n\t\tq(1) = it->x();\n\t\tq(2) = it->y();\n\t\tq(3) = it->z();\n\t\tA += q.transpose()*q;\n\t\tsum++;\n\t}\n\tA /= sum;\n\n\tEigen::EigenSolver<Eigen::Matrix<DataType, 4, 4>> es(A);\n\n\tEigen::Matrix<std::complex<DataType>, 4, 1> mat(es.eigenvalues());\n\tint index;\n\tmat.real().maxCoeff(&index);\n\tEigen::Matrix<DataType, 4, 1> largest_ev(es.eigenvectors().real().block(0, index, 4, 1));\n\n\treturn Eigen::Quaternion<DataType>(largest_ev(0), largest_ev(1), largest_ev(2), largest_ev(3));\n}\n\n/// Overloaded function to calculate the average quaternion for some container types\ntemplate<typename DataType, typename Container>\ntypename Eigen::Quaternion<DataType> averageQuaternions(Container const & container) {\n\treturn averageQuaternions<DataType>(container.begin(), container.end());\n}\n\n/// Calculate average position\ntemplate<typename DataType, typename ForwardIterator>\nEigen::Matrix<DataType, 3, 1> averagePositions(ForwardIterator const & begin, ForwardIterator const & end) {\n\tif (begin == end) {\n\t\tthrow std::logic_error(\"Cannot average orientations over an empty range.\");\n\t}\n\n\tDataType x(0), y(0), z(0);\n\tuint count(0);\n\tfor (ForwardIterator it = begin; it!=end; ++it) {\n\t\tx += it->x();\n\t\ty += it->y();\n\t\tz += it->z();\n\t\tcount++;\n\t}\n\tx /= count;\n\ty /= count;\n\tz /= count;\n\n\treturn Eigen::Matrix<DataType, 3, 1>(x,y,z);\n}\n\n/// Overloaded function to calculate the average position for some container types\ntemplate<typename DataType, typename Container>\ntypename Eigen::Matrix<DataType, 3, 1> averagePositions(Container const & container) {\n\treturn averagePositions<DataType>(container.begin(), container.end());\n}\n\ntemplate<typename DataType, typename ForwardIterator>\nEigen::Transform<DataType, 3, Eigen::Isometry> averageIsometries(ForwardIterator const & begin, ForwardIterator const & end) {\n\n\tstd::vector<Eigen::Vector3d> positions;\n\tstd::vector<Eigen::Quaterniond> quaternions;\n\n\tfor (auto it = begin; it != end; ++it) {\n\t\tpositions.push_back(it->translation());\n\t\tquaternions.push_back(Eigen::Quaternion<DataType>(it->rotation()));\n\t}\n\n\treturn Eigen::Translation<DataType, 3>(averagePositions<DataType>(positions)) * averageQuaternions<DataType>(quaternions);\n}\n\ntemplate<typename DataType, typename Container>\nEigen::Transform<DataType, 3, Eigen::Isometry> averageIsometries(Container const & container) {\n\treturn averageIsometries<DataType>(container.begin(), container.end());\n}\n\n}\n", "meta": {"hexsha": "c0769803cdbbd8cc75adf1d195661d0fdbdb0b9b", "size": 3000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/average.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/average.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "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/dr_eigen/average.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "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.914893617, "max_line_length": 126, "alphanum_fraction": 0.7153333333, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6562678575545094}}
{"text": "#include \"clarke_transform.h\"\n#include \"config/scalar.h\"\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\nTEST(kClarkeTransform2x3, zero_series_invariant) {\n    const Eigen::Matrix<Scalar, 3, 1> ones =\n        Eigen::Matrix<Scalar, 3, 1>::Ones();\n    const Eigen::Matrix<Scalar, 2, 1> result = kClarkeTransform2x3 * ones;\n\n    EXPECT_LT(result.norm(), 1e-7);\n}\n\nTEST(kClarkeTransform3x3, unitary) {\n    const Eigen::Matrix<Scalar, 3, 3> delta =\n        kClarkeTransform3x3 * kClarkeTransform3x3.transpose() -\n        Eigen::Matrix<Scalar, 3, 3>::Identity();\n\n    EXPECT_LT(delta.norm(), 1e-7);\n}\n", "meta": {"hexsha": "0c399eefeb2dacc18d65de3d191b6f09e603ab80", "size": 596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/clarke_transform_test.cpp", "max_stars_repo_name": "mark-berobot/motor_sim", "max_stars_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T00:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T01:33:11.000Z", "max_issues_repo_path": "util/clarke_transform_test.cpp", "max_issues_repo_name": "INKSureIT/motor_sim", "max_issues_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/clarke_transform_test.cpp", "max_forks_repo_name": "INKSureIT/motor_sim", "max_forks_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T01:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:35:23.000Z", "avg_line_length": 28.380952381, "max_line_length": 74, "alphanum_fraction": 0.6761744966, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6562678297689533}}
{"text": "/*\n * This file is part of the ProVANT simulator project.\n * Licensed under the terms of the MIT open source license. More details at\n * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md\n */\n/**\n * @file This file contains the implementation of the LQRQuadcopter class.\n *\n * @author Jonatan Campos\n */\n\n#include <control_strategies_base/icontroller.hpp>\n#include <Eigen/Eigen>\n#include \"simulator_msgs/Sensor.h\"\n#include <ros/ros.h>\n\nstatic const int NINPUTS = 4;\nstatic const int NSTATES = 12;\n\n/**\n * @brief The LQRQuadcopter implements a Linear Quadratic Regulator control\n * strategy for the quadrotor UAV that is available in the ProVANT simulator.\n *\n * This controller uses a helicoidal reference trajectory.\n *\n * This control strategy expects a state vector composed of the generalized\n * coordinates and their derivatives in the following order:\n * [x y z phi theta psi x_dot y_dot z_dot phi_dot theta_dot psi_dot]\n *\n * x, y and z are the cartesian coordinates of the UAV center of rotation in\n * relation with the inertial reference frame and expressed in meters,\n * phi is the rotation around the x axis, theta is the rotation around the y\n * axis and psi is the rotation around the z axis, all of the angles of rotation\n * are expressed in radians.\n *\n * x_dot, y_dot and z_dot are the time derivatives of the cartesian coordinates,\n * that equal the linear velocities of the UAV in relation with the inertial\n * frame. The values are given in m/s.\n *\n * Finally, phi_dot, theta_dot and psi_dot are the time derivatives of the Euler\n * Angles, given in rad/s.\n *\n * The control inputs of this system are the forces generated by each propeller\n * in the order f1, f2, f3 and f4, where fi is the force of the i-th propeller.\n * All of the forces are expressed in Newtons.\n *\n */\nclass LQRQuadcopter : public Icontroller\n{\nprivate:\n  //! Stores the reference vector\n  Eigen::VectorXd Xref;\n  //! Stores the error vector\n  Eigen::VectorXd Erro;\n  //! Stores the control inputs\n  Eigen::VectorXd Input;\n  //! Stores the gain matrix of the system\n  Eigen::MatrixXd K;\n  //! Stores the state vector\n  Eigen::VectorXd X;\n\npublic:\n  /**\n   * @brief Construct a new LQRQuadcopter object and initialize the size of\n   * the matrices used in the controller.\n   */\n  LQRQuadcopter() : Xref(NSTATES), K(NINPUTS, NSTATES), X(NSTATES), Erro(NSTATES), Input(NINPUTS)\n  {\n    config();\n  }\n\n  /**\n   * @brief Destroy the LQRQuadcopter object.\n   */\n  virtual ~LQRQuadcopter()\n  {\n  }\n\n  /**\n   * @brief Initialize the gain matrix K.\n   */\n  void config()\n  {\n    K << -70.711, 2.1302e-11, 7.0711, -2.3813e-12, -156.46, 5, -165.1, 4.7388e-11, 11.53, 8.2065e-13, -7.5435, 5.7987,\n        1.3204e-11, -70.711, 7.0711, 156.46, 8.257e-11, -5, 3.1756e-11, -165.1, 11.53, 7.5435, 8.1385e-12, -5.7987,\n        70.711, 3.9104e-11, 7.0711, -4.7265e-11, 156.46, 5, 165.1, 8.9701e-11, 11.53, 9.2039e-13, 7.5435, 5.7987,\n        -5.6384e-12, 70.711, 7.0711, -156.46, 6.4636e-11, -5, -8.3103e-12, 165.1, 11.53, -7.5435, 8.4109e-12, -5.7987;\n  }\n\n  /**\n   * @brief Execute the LQR control law.\n   *\n   * This method is called every simulation step.\n   * It is responsible for reading the state vector from the arraymsg,\n   * calculating the reference trajectory, the error vector, and must return\n   * the control inputs to be applied on the system.\n   *\n   * @param arraymsg Array of simulator messages containing the sensors\n   * of the quadrotor model. In this case, the only sensor is the state vector.\n   * @returns Control inputs vector to be applied on the system. See the\n   * class documentation for more details.\n   */\n  std::vector<double> execute(simulator_msgs::SensorArray arraymsg)\n  {\n    // Search for the state vector in the recevied messages\n    simulator_msgs::Sensor msg;\n    bool found = false;\n    for (int i = 0; i < arraymsg.values.size(); i++)\n    {\n      if (arraymsg.values.at(i).name == \"Estados\")\n      {\n        msg = arraymsg.values.at(i);\n        found = true;\n        break;\n      }\n    }\n    if (!found)\n    {\n      // In case of error, report the problem in a ROS_LOG, and returns an\n      // empty array\n      ROS_FATAL(\"[lqr_quadcopter] State vector not found.\");\n      std::vector<double> out(Input.data(), Input.data() + Input.size());\n      return out;\n    }\n\n    // Get the current simulation time and calculate the reference trajectory.\n    ros::Time time = ros::Time::now();\n    double tempo = time.toSec();\n\n    Xref << sin(tempo / 2), cos(tempo / 2), tempo / 10, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n\n    // Read the values of the state vector from the message\n    X << msg.values.at(0),  // x\n        msg.values.at(1),   // y\n        msg.values.at(2),   // z\n        msg.values.at(3),   // roll\n        msg.values.at(4),   // pitch\n        msg.values.at(5),   // yaw\n        msg.values.at(6),   // x_dot\n        msg.values.at(7),   // y_dot\n        msg.values.at(8),   // z_dot\n        msg.values.at(9),   // roll_dot\n        msg.values.at(10),  // pitch_dot\n        msg.values.at(11);  // yaw_dot\n\n    // Calculate the error vector of the system\n    Erro = X - Xref;\n\n    // Execute the control law (Multiply the gain matrix by the error vector)\n    Input = -K * Erro;\n\n    // Add equilibirium forces to the outputs.\n\n    Input(0) = Input(0) + 5.77611;\n    Input(1) = Input(1) + 5.77611;\n    Input(2) = Input(2) + 5.77611;\n    Input(3) = Input(3) + 5.77611;\n\n    ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F1: \" << Input(0));\n    ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F2: \" << Input(1));\n    ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F3: \" << Input(2));\n    ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F4: \" << Input(3));\n    \n    // Copy the control inputs values to the output vector\n    std::vector<double> out(Input.data(), Input.data() + Input.size());\n    return out;\n  }\n\n  /**\n   * @brief Reference()\n   *\n   * This method is called by the logging functions to report the\n   * reference values for the current step.\n   *\n   * @returns Reference vector for the current step. This vector is in the same\n   * order of the state vector.\n   */\n  std::vector<double> Reference()\n  {\n    // Copy the references to a std::vector\n    std::vector<double> out(Xref.data(), Xref.data() + Xref.rows() * Xref.cols());\n    return out;\n  }\n\n  /**\n   * @brief Error()\n   *\n   * This method is called by the logging functions to get the error vector\n   * used in the control law execution.\n   *\n   * @returns The error vector of the system in the current step. The error\n   * vector is in the same order of the state vector.\n   */\n  std::vector<double> Error()\n  {\n    // Copy the references to a std::vector\n    std::vector<double> out(Erro.data(), Erro.data() + Erro.rows() * Erro.cols());\n    return out;\n  }\n\n  /**\n   * @brief State()\n   *\n   * This method is called by the logging functions to get the state vector\n   * used in the control law execution.\n   * Note that if the implmeneted controller uses an augmented state vector,\n   * for example, with integral sates, these values should also be returned\n   * by this function.\n   *\n   * @returns The state vector of the system used in the calculation of the\n   * control law in the current step time. This vector is in the same order\n   * as the states vector.\n   */\n  std::vector<double> State()\n  {\n    std::vector<double> out(X.data(), X.data() + X.rows() * X.cols());\n    return out;\n  }\n};\n\n// Functions used by the ProVANT Simulator to instantiate this control law\nextern \"C\" {\nIcontroller* create(void)\n{\n  return new LQRQuadcopter;\n}\nvoid destroy(Icontroller* p)\n{\n  delete p;\n}\n}\n", "meta": {"hexsha": "a77007091ab3246596ef82739c5a6e0d29253b1e", "size": 7646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_stars_repo_name": "Guiraffo/ProVANT_Simulator", "max_stars_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_stars_repo_licenses": ["MIT"], "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/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_issues_repo_name": "Guiraffo/ProVANT_Simulator", "max_issues_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_issues_repo_licenses": ["MIT"], "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/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_forks_repo_name": "Guiraffo/ProVANT_Simulator", "max_forks_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_forks_repo_licenses": ["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.9568965517, "max_line_length": 118, "alphanum_fraction": 0.655898509, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.656260339629384}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n\n#include <iostream>\n#include <list>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\ntypedef CGAL::Simple_cartesian<double>                               Kernel;\ntypedef Kernel::Point_3                                              Point;\ntypedef CGAL::Polyhedron_3<Kernel,CGAL::Polyhedron_items_with_id_3>  Polyhedron;\n\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Polyhedron>::vertex_iterator   vertex_iterator;\ntypedef boost::graph_traits<Polyhedron>::edge_descriptor   edge_descriptor;\n\n\n\nvoid\nkruskal( const Polyhedron& P)\n{\n\n  // We use the default edge weight which is the length of the edge\n  // This property map is defined in graph_traits_Polyhedron_3.h\n  \n  // This function call requires a vertex_index_map named parameter which\n  // when  ommitted defaults to \"get(vertex_index,graph)\".\n  // That default works here because the vertex type has an \"id()\" method\n  // field which is used by the vertex_index internal property.\n  std::list<edge_descriptor> mst;\n  boost::kruskal_minimum_spanning_tree(P,std::back_inserter(mst));\n  \n  std::cout << \"#VRML V2.0 utf8\\n\"\n    \"Shape {\\n\"\n    \"appearance Appearance {\\n\"\n    \"material Material { emissiveColor 1 0 0}}\\n\"\n    \"geometry\\n\"\n    \"IndexedLineSet {\\n\"\n    \"coord Coordinate {\\n\"\n    \"point [ \\n\";\n  \n  vertex_iterator vb, ve;\n  for(boost::tie(vb,ve) = vertices(P); vb!=ve; ++vb){\n    std::cout << (*vb)->point() << \"\\n\";\n  }\n  \n  std::cout << \"]\\n\"\n    \"}\\n\"\n    \"coordIndex [\\n\";\n  \n  for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it){\n    std::cout << source(*it,P)->id()\n\t      << \", \" << target(*it,P)->id() <<  \", -1\\n\";\n  }\n  \n  std::cout << \"]\\n\"\n    \"}#IndexedLineSet\\n\"\n    \"}# Shape\\n\";\n}\n\n\nint main() {\n  \n  Polyhedron P;\n  \n  Point a(1,0,0);\n  Point b(0,1,0);\n  Point c(0,0,1);\n  Point d(0,0,0);\n  \n  P.make_tetrahedron(a,b,c,d);\n\n  // associate indices to the vertices using the \"id()\" field of the vertex.\n  vertex_iterator vb, ve;\n  int index = 0;\n  \n  // boost::tie assigns the first and second element of the std::pair\n  // returned by boost::vertices to the variables vit and ve\n  for(boost::tie(vb,ve)=vertices(P); vb!=ve; ++vb ){\n    vertex_descriptor  vd = *vb;\n    vd->id() = index++;\n  }\n  \n  kruskal(P);\n  return 0;\n}\n", "meta": {"hexsha": "dc20778f740e507cd905499af2837919e41277c1", "size": 2417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal_with_stored_id.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal_with_stored_id.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_polyhedron_3/kruskal_with_stored_id.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 27.4659090909, "max_line_length": 84, "alphanum_fraction": 0.6425320645, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.656044734203608}}
{"text": "#ifndef _CELERITE2_FORWARD_HPP_DEFINED_\n#define _CELERITE2_FORWARD_HPP_DEFINED_\n\n#include <Eigen/Core>\n#include \"internal.hpp\"\nnamespace celerite2 {\nnamespace core {\n\n/**\n * \\brief Get the dense representation of a celerite matrix\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param a     (N,): The diagonal component\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param K_out (N, N): The dense matrix\n */\ntemplate <typename Input, typename Coeffs, typename Diag, typename LowRank, typename Dense>\nvoid to_dense(const Eigen::MatrixBase<Input> &t,    // (N,)\n              const Eigen::MatrixBase<Coeffs> &c,   // (J,)\n              const Eigen::MatrixBase<Diag> &a,     // (N,)\n              const Eigen::MatrixBase<LowRank> &U,  // (N, J)\n              const Eigen::MatrixBase<LowRank> &V,  // (N, J)\n              Eigen::MatrixBase<Dense> const &K_out // (N,)\n) {\n  typedef typename Eigen::internal::plain_row_type<LowRank>::type RowVector;\n\n  Eigen::Index N = U.rows(), J = U.cols();\n  CAST_MAT(Dense, K, N, N);\n\n  RowVector p(1, J);\n  for (Eigen::Index m = 0; m < N; ++m) {\n    p.setConstant(1.0);\n    K(m, m) = a(m);\n    for (Eigen::Index n = m + 1; n < N; ++n) {\n      p.array() *= exp(-c.array() * (t(n) - t(n - 1)));\n      K(n, m) = (U.row(n).array() * V.row(m).array() * p.array()).sum();\n      K(m, n) = K(n, m);\n    }\n  }\n}\n\n/**\n * \\brief Compute the Cholesky factorization of the system\n *\n * This computes `d` and `W` such that:\n *\n * `K = L*diag(d)*L^T`\n *\n * where `K` is the celerite matrix and\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place: `d_out` can point to `a` and `W_out` can\n * point to `V`, and the memory will be reused. In this particular case, the\n * `celerite2::core::factor_rev` function doesn't use `a` and `V`, but this\n * won't be true for all `_rev` functions.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param a     (N,): The diagonal component\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param d_out (N,): The diagonal component of the Cholesky factor\n * @param W_out (N, J): The second low rank component of the Cholesky factor\n * @param S_out (N, J*J): The cached value of the S matrix at each step\n */\ntemplate <bool update_workspace = true, typename Input, typename Coeffs, typename Diag, typename LowRank, typename DiagOut, typename LowRankOut,\n          typename Work>\nEigen::Index factor(const Eigen::MatrixBase<Input> &t,          // (N,)\n                    const Eigen::MatrixBase<Coeffs> &c,         // (J,)\n                    const Eigen::MatrixBase<Diag> &a,           // (N,)\n                    const Eigen::MatrixBase<LowRank> &U,        // (N, J)\n                    const Eigen::MatrixBase<LowRank> &V,        // (N, J)\n                    Eigen::MatrixBase<DiagOut> const &d_out,    // (N,)\n                    Eigen::MatrixBase<LowRankOut> const &W_out, // (N, J)\n                    Eigen::MatrixBase<Work> const &S_out        // (N, J*J)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename Diag::Scalar Scalar;\n  typedef typename Eigen::internal::plain_row_type<LowRank>::type RowVector;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n\n  Eigen::Index N = U.rows(), J = U.cols();\n  CAST_VEC(DiagOut, d, N);\n  CAST_MAT(LowRankOut, W, N, J);\n  CAST_BASE(Work, S);\n  if (update_workspace) {\n    S.derived().resize(N, J * J);\n    S.row(0).setZero();\n  }\n\n  // This is a temporary vector used to minimize computations internally\n  RowVector tmp;\n  CoeffVector p;\n\n  // This holds the accumulated value of the S matrix at each step\n  Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, LowRank::ColsAtCompileTime, Eigen::ColMajor> Sn(J, J);\n\n  // This is a flattened pointer to Sn that is used for copying the data\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Sn.data(), 1, J * J);\n\n  // First row\n  Sn.setZero();\n  d(0)               = a(0);\n  W.row(0).noalias() = V.row(0) / d(0);\n\n  // The rest of the rows\n  for (Eigen::Index n = 1; n < N; ++n) {\n    p = exp(c.array() * (t(n - 1) - t(n)));\n\n    // Update S_n = diag(P) * (S_n-1 + d*W*W.T) * diag(P)\n    Sn.noalias() += d(n - 1) * W.row(n - 1).transpose() * W.row(n - 1);\n    Sn = p.asDiagonal() * Sn;\n\n    // Save the current value of Sn to the workspace\n    // Note: This is actually `diag(P) * (S + d*W*W.T)` without the final `* diag(P)`\n    internal::update_workspace<update_workspace>::apply(n, ptr, S);\n\n    // Incorporate the second diag(P) that we didn't include above for bookkeeping\n    Sn *= p.asDiagonal();\n\n    // Update d = a - U * S * U.T\n    tmp  = U.row(n) * Sn;\n    d(n) = a(n) - tmp * U.row(n).transpose();\n    if (d(n) <= 0.0) return n;\n\n    // Update W = (V - U * S) / d\n    W.row(n).noalias() = (V.row(n) - tmp) / d(n);\n  }\n\n  return 0;\n}\n\n/**\n * \\brief Apply a strictly lower matrix multiply\n *\n * This computes:\n *\n * `Z += tril(U * V^T) * Y`\n *\n * where `tril` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param W     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate <bool update_workspace = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid solve_lower(const Eigen::MatrixBase<Input> &t,                // (N,)\n                 const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                 const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                 const Eigen::MatrixBase<LowRank> &W,              // (N, J)\n                 const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                 Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                 Eigen::MatrixBase<Work> const &F_out              // (N, J*nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n  CAST_BASE(RightHandSideOut, Z);\n  Z = Y;\n  internal::forward<true, update_workspace>(t, c, U, W, Y, Z, F_out);\n}\n\n/**\n * \\brief Compute the solution of a upper triangular linear equation\n *\n * This computes `Z` such that:\n *\n * `Y = L^T * Y`\n *\n * where\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param W     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The right hand side\n * @param Z_out (N, Nrhs): The solution of this equation\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate <bool update_workspace = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid solve_upper(const Eigen::MatrixBase<Input> &t,                // (N,)\n                 const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                 const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                 const Eigen::MatrixBase<LowRank> &W,              // (N, J)\n                 const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                 Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                 Eigen::MatrixBase<Work> const &F_out              // (N, J*nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n  CAST_BASE(RightHandSideOut, Z);\n  Z = Y;\n  internal::backward<true, update_workspace>(t, c, U, W, Y, Z, F_out);\n}\n\n/**\n * \\brief Apply a strictly lower matrix multiply\n *\n * This computes:\n *\n * `Z += tril(U * V^T) * Y`\n *\n * where `tril` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate <bool update_workspace = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid matmul_lower(const Eigen::MatrixBase<Input> &t,                // (N,)\n                  const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                  const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                  const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n                  const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                  Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                  Eigen::MatrixBase<Work> const &F_out              // (N, J*nrhs)\n) {\n  internal::forward<false, update_workspace>(t, c, U, V, Y, Z_out, F_out);\n}\n\n/**\n * \\brief Apply a strictly upper matrix multiply\n *\n * This computes:\n *\n * `Z += triu(V * U^T) * Y`\n *\n * where `triu` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate <bool update_workspace = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid matmul_upper(const Eigen::MatrixBase<Input> &t,                // (N,)\n                  const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                  const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                  const Eigen::MatrixBase<LowRank> &V,              // (N, J)\n                  const Eigen::MatrixBase<RightHandSide> &Y,        // (N, nrhs)\n                  Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                  Eigen::MatrixBase<Work> const &F_out              // (N, J*nrhs)\n) {\n  internal::backward<false, update_workspace>(t, c, U, V, Y, Z_out, F_out);\n}\n\n/**\n * \\brief The general lower-triangular dot product of a rectangular celerite system\n *\n * @param t1     (N,): The left input coordinates (must be sorted)\n * @param t2     (M,): The right input coordinates (must be sorted)\n * @param c      (J,): The transport coefficients\n * @param U      (N, J): The first low rank matrix\n * @param V      (M, J): The second low rank matrix\n * @param Y      (M, Nrhs): The matrix that will be left multiplied by the celerite model\n * @param Z_out  (N, Nrhs): The result of the operation\n * @param F_out  (M, J*Nrhs): The workspace\n */\ntemplate <bool do_update = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid general_matmul_lower(const Eigen::MatrixBase<Input> &t1,               // (N,)\n                          const Eigen::MatrixBase<Input> &t2,               // (M,)\n                          const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                          const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                          const Eigen::MatrixBase<LowRank> &V,              // (M, J)\n                          const Eigen::MatrixBase<RightHandSide> &Y,        // (M, nrhs)\n                          Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                          Eigen::MatrixBase<Work> const &F_out              // (M, J*nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = t1.rows(), M = t2.rows(), J = c.rows(), nrhs = Y.cols();\n\n  CAST_BASE(RightHandSideOut, Z);\n  CAST_BASE(Work, F);\n  if (do_update) {\n    F.derived().resize(M, J * nrhs);\n    F.row(0).setZero();\n  }\n\n  CoeffVector p(J);\n  Inner Fm = V.row(0).transpose() * Y.row(0);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fm.data(), 1, J * nrhs);\n  internal::update_workspace<do_update>::apply(0, ptr, F);\n\n  Scalar tn = t2(0);\n  Eigen::Index n, m = 1;\n  for (n = 0; n < N; ++n)\n    if (t1(n) >= tn) break;\n  for (; n < N; ++n) {\n    tn = t1(n);\n    while (m < M && t2(m) <= tn) {\n      p  = exp(c.array() * (t2(m - 1) - t2(m)));\n      Fm = p.asDiagonal() * Fm;\n      Fm.noalias() += V.row(m).transpose() * Y.row(m);\n      internal::update_workspace<do_update>::apply(m, ptr, F);\n      m++;\n    }\n    p = exp(c.array() * (t2(m - 1) - tn));\n    Z.row(n).noalias() += U.row(n) * p.asDiagonal() * Fm;\n  }\n}\n\n/**\n * \\brief The general upper-triangular dot product of a rectangular celerite system\n *\n * @param t1     (N,): The left input coordinates (must be sorted)\n * @param t2     (M,): The right input coordinates (must be sorted)\n * @param c      (J,): The transport coefficients\n * @param U      (N, J): The first low rank matrix\n * @param V      (M, J): The second low rank matrix\n * @param Y      (M, Nrhs): The matrix that will be left multiplied by the celerite model\n * @param Z_out  (N, Nrhs): The result of the operation\n * @param F_out  (M, J*Nrhs): The workspace\n */\ntemplate <bool do_update = true, typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut,\n          typename Work>\nvoid general_matmul_upper(const Eigen::MatrixBase<Input> &t1,               // (N,)\n                          const Eigen::MatrixBase<Input> &t2,               // (M,)\n                          const Eigen::MatrixBase<Coeffs> &c,               // (J,)\n                          const Eigen::MatrixBase<LowRank> &U,              // (N, J)\n                          const Eigen::MatrixBase<LowRank> &V,              // (M, J)\n                          const Eigen::MatrixBase<RightHandSide> &Y,        // (M, nrhs)\n                          Eigen::MatrixBase<RightHandSideOut> const &Z_out, // (N, nrhs)\n                          Eigen::MatrixBase<Work> const &F_out              // (M, J*nrhs)\n) {\n  ASSERT_ROW_MAJOR(Work);\n\n  typedef typename LowRank::Scalar Scalar;\n  typedef typename Eigen::internal::plain_col_type<Coeffs>::type CoeffVector;\n  typedef typename Eigen::Matrix<Scalar, LowRank::ColsAtCompileTime, RightHandSide::ColsAtCompileTime> Inner;\n\n  Eigen::Index N = t1.rows(), M = t2.rows(), J = c.rows(), nrhs = Y.cols();\n\n  CAST_BASE(RightHandSideOut, Z);\n  CAST_BASE(Work, F);\n  if (do_update) {\n    F.derived().resize(M, J * nrhs);\n    F.row(0).setZero();\n  }\n\n  CoeffVector p(J);\n  Inner Fm = V.row(M - 1).transpose() * Y.row(M - 1);\n  Eigen::Map<typename Eigen::internal::plain_row_type<Work>::type> ptr(Fm.data(), 1, J * nrhs);\n\n  Scalar tn = t2(M - 1);\n  Eigen::Index n, m = M - 2;\n  for (n = N - 1; n >= 0; --n)\n    if (t1(n) < tn) break;\n  for (; n >= 0; --n) {\n    tn = t1(n);\n    while (m >= 0 && t2(m) > tn) {\n      p  = exp(c.array() * (t2(m) - t2(m + 1)));\n      Fm = p.asDiagonal() * Fm;\n      Fm.noalias() += V.row(m).transpose() * Y.row(m);\n      internal::update_workspace<do_update>::apply(m, ptr, F);\n      m--;\n    }\n    p = exp(c.array() * (tn - t2(m + 1)));\n    Z.row(n).noalias() += U.row(n) * p.asDiagonal() * Fm;\n  }\n}\n\n} // namespace core\n} // namespace celerite2\n\n#endif // _CELERITE2_FORWARD_HPP_DEFINED_\n", "meta": {"hexsha": "b5b9a39ca749422af64c591c003edef599aa3654", "size": 15977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/forward.hpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/include/celerite2/forward.hpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/include/celerite2/forward.hpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 40.1432160804, "max_line_length": 144, "alphanum_fraction": 0.5757651624, "num_tokens": 4677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6560447238761465}}
{"text": "#ifndef SE3_HPP_\n#define SE3_HPP_\n\n#include <Eigen/Geometry>\n\n\n/**\n * @brief Bare-bones implementation of the SE(3) Lie Group\n *\n * For benchmarking purposes only---do not use in important code.\n */\ntemplate<typename _Scalar>\nstruct SE3\n{\n  using Scalar = _Scalar;\n  using Tangent = Eigen::Matrix<Scalar, 6, 1>;\n\n  // group composition\n  SE3<Scalar> operator*(const SE3<Scalar> & other) const\n  {\n    return SE3<Scalar>{q * other.q, t + q * other.t};\n  }\n\n  // in-place group composition\n  SE3<Scalar> & operator*=(const SE3<Scalar> & other)\n  {\n    t += q * other.t;\n    q *= other.q;\n    return *this;\n  }\n\n  // group action on 3-vector\n  template<typename Derived>\n  Derived operator*(const Eigen::EigenBase<Derived> & vec) const\n  {\n    EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3)\n\n    return t + q * vec;\n  }\n\n  // group inverse\n  SE3<Scalar> inv() const\n  {\n    return SE3<Scalar>{q.inverse(), -(q.inverse() * t)};\n  }\n\n  // cast to different scalar type\n  template<typename NewScalar>\n  SE3<NewScalar> cast() const\n  {\n    return SE3<NewScalar>{q.template cast<NewScalar>(), t.template cast<NewScalar>()};\n  }\n\n  // exponential (does not work for special case of zero orientation (yields 0/0))\n  template<typename Derived>\n  static SE3<Scalar> exp(const Eigen::MatrixBase<Derived> & tangent)\n  {\n    EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Tangent, Derived)\n\n    using std::sin, std::cos;\n\n    const Scalar w_norm = tangent.template tail<3>().norm();\n    const Eigen::Matrix<Scalar, 3, 1> q_diff_n = tangent.template tail<3>().normalized();\n\n    Eigen::Matrix<Scalar, 3, 3> what;\n    what << Scalar(0), -q_diff_n(2), q_diff_n(1),\n      q_diff_n(2), Scalar(0), -q_diff_n(0),\n      -q_diff_n(1), q_diff_n(0), Scalar(0);\n\n    const Eigen::Matrix<Scalar, 3, 3> J = Eigen::Matrix<Scalar, 3, 3>::Identity() +\n      ((w_norm - sin(w_norm)) / w_norm) * what * what +\n      ((Scalar(1.) - cos(w_norm)) / w_norm) * what;\n\n    return SE3<Scalar>{\n      Eigen::Quaternion<Scalar>(Eigen::AngleAxis<Scalar>(w_norm, q_diff_n)),\n      J * tangent.template head<3>()\n    };\n  }\n\n  // log (does not work for special case of zero orientation (yields 0/0))\n  Tangent log() const\n  {\n    using std::atan2;\n\n    const Scalar alpha = atan2(q.coeffs().template head<3>().norm(), q.w());\n\n    const Eigen::Matrix<Scalar, 3, 1> so3log =\n      Scalar(2.) * (alpha / sin(alpha)) * q.coeffs().template head<3>();\n\n    // TODO: could derive more efficient expression for the inverse...\n    const Scalar w_norm = so3log.norm();\n    const Eigen::Matrix<Scalar, 3, 1> q_diff_n = so3log.normalized();\n\n    Eigen::Matrix<Scalar, 3, 3> what;\n    what << Scalar(0), -q_diff_n(2), q_diff_n(1),\n      q_diff_n(2), Scalar(0), -q_diff_n(0),\n      -q_diff_n(1), q_diff_n(0), Scalar(0);\n\n    const Eigen::Matrix<Scalar, 3, 3> J = Eigen::Matrix<Scalar, 3, 3>::Identity() +\n      ((w_norm - sin(w_norm)) / w_norm) * what * what +\n      ((Scalar(1.) - cos(w_norm)) / w_norm) * what;\n\n    return (Tangent() << J.inverse() * t, so3log).finished();\n  }\n\n  Eigen::Quaternion<Scalar> q = Eigen::Quaternion<Scalar>::Identity();\n  Eigen::Matrix<Scalar, 3, 1> t = Eigen::Matrix<Scalar, 3, 1>::Zero();\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\n/**\n * @brief boost::numerical::odeint operations for numerical integration on lie groups\n */\nstruct lie_operations\n{\n  template<class Fac1 = double, class Fac2 = Fac1>\n  struct scale_sum2\n  {\n    const Fac2 m_alpha2;\n\n    scale_sum2(Fac1 alpha1, Fac2 alpha2)\n    : m_alpha2(alpha2)\n    {\n      if (alpha1 != Fac1(1.0)) {\n        std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    template<class T1, class T2, class T3>\n    void operator()(T1 & t1, const T2 & t2, const T3 & t3) const\n    {\n      t1 = t2 * T2::exp(t3 * m_alpha2);\n    }\n\n    typedef void result_type;\n  };\n\n\n  template<class Fac1 = double, class Fac2 = Fac1, class Fac3 = Fac2>\n  struct scale_sum3\n  {\n    const Fac2 m_alpha2;\n    const Fac3 m_alpha3;\n\n    scale_sum3(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3)\n    : m_alpha2(alpha2), m_alpha3(alpha3)\n    {\n      if (alpha1 != Fac1(1.0)) {\n        std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    template<class T1, class T2, class T3, class T4>\n    void operator()(T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4) const\n    {\n      t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3);\n    }\n\n    typedef void result_type;\n  };\n\n\n  template<class Fac1 = double, class Fac2 = Fac1, class Fac3 = Fac2, class Fac4 = Fac3>\n  struct scale_sum4\n  {\n    const Fac2 m_alpha2;\n    const Fac3 m_alpha3;\n    const Fac4 m_alpha4;\n\n    scale_sum4(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3, Fac4 alpha4)\n    : m_alpha2(alpha2), m_alpha3(alpha3), m_alpha4(alpha4)\n    {\n      if (alpha1 != Fac1(1.0)) {\n        std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    template<class T1, class T2, class T3, class T4, class T5>\n    void operator()(T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4, const T5 & t5) const\n    {\n      t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3 + t5 * m_alpha4);\n    }\n\n    typedef void result_type;\n  };\n\n\n  template<class Fac1 = double, class Fac2 = Fac1, class Fac3 = Fac2, class Fac4 = Fac3,\n    class Fac5 = Fac4>\n  struct scale_sum5\n  {\n    const Fac2 m_alpha2;\n    const Fac3 m_alpha3;\n    const Fac4 m_alpha4;\n    const Fac5 m_alpha5;\n\n    scale_sum5(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3, Fac4 alpha4, Fac5 alpha5)\n    : m_alpha2(alpha2), m_alpha3(alpha3), m_alpha4(alpha4), m_alpha5(alpha5)\n    {\n      if (alpha1 != Fac1(1.0)) {\n        std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    template<class T1, class T2, class T3, class T4, class T5, class T6>\n    void operator()(\n      T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4, const T5 & t5,\n      const T6 & t6) const\n    {\n      t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3 + t5 * m_alpha4 + t6 * m_alpha5);\n    }\n\n    typedef void result_type;\n  };\n};\n\n#endif  // SE3_HPP_\n", "meta": {"hexsha": "45f02a7f92842826b69a1b6e7cbe7697ca7006a6", "size": 6133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/src/se3.hpp", "max_stars_repo_name": "pettni/autodiff", "max_stars_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/src/se3.hpp", "max_issues_repo_name": "pettni/autodiff", "max_issues_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_issues_repo_licenses": ["MIT"], "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/src/se3.hpp", "max_forks_repo_name": "pettni/autodiff", "max_forks_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_forks_repo_licenses": ["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.3794642857, "max_line_length": 94, "alphanum_fraction": 0.6191097342, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6560408563813768}}
{"text": "#include <cassert>\n#include <cstdio>\n#include <cstring>\n#include <map>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"igl/components.h\"\n#include \"igl/jet.h\"\n#include \"igl/polygon_mesh_to_triangle_mesh.h\"\n#include \"igl/readOFF.h\"\n#include \"igl/viewer/Viewer.h\"\n#include \"igl/writeOFF.h\"\n\ndouble volume(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F) {\n\n  double total_det = 0;\n\n  for (int i = 0; i < F.rows(); ++i) {\n    Eigen::Matrix3d p;\n    p << V(F(i, 0), 0), V(F(i, 1), 0), V(F(i, 2), 0),\n         V(F(i, 0), 1), V(F(i, 1), 1), V(F(i, 2), 1),\n         V(F(i, 0), 2), V(F(i, 1), 2), V(F(i, 2), 2);\n\n    total_det += p.determinant();\n  }\n\n  return std::abs(total_det / 6.0);\n}\n\nvoid selectValidVerts(const Eigen::MatrixXd &Vi, const Eigen::MatrixXi &Fi,\n                      const Eigen::VectorXi &Ci, int comp_num,\n                      Eigen::MatrixXd &Vo, Eigen::MatrixXi &Fo) {\n  printf(\"Extracting component number %d\\n\", comp_num);\n\n  std::map<int, int> old_to_new;\n  int n_i = 0;\n  for (int i = 0; i < Vi.rows(); ++i) {\n    if (Ci(i) == comp_num) {\n      old_to_new[i] = n_i;\n      n_i++;\n    } else {\n      // not valid\n      old_to_new[i] = -1;\n    }\n  }\n  printf(\"  Found %d/%d valid vertices\\n\", n_i, Vi.rows());\n\n  // Resize the vertices to be the number we need.\n  Vo.resize(n_i, 3);\n  int v_idx = 0;\n  for (int i = 0; i < Vi.rows(); ++i) {\n    if (old_to_new[i] != -1) {\n      Vo.row(v_idx++) = Vi.row(i);\n    }\n  }\n  // Same thing for the faces.\n  // Do this twice so we know how many we need.\n  std::vector<int> f_idxs;\n  for (int i = 0; i < Fi.rows(); ++i) {\n    bool contained = true;\n    for (int j = 0; j < Fi.row(i).size(); ++j) {\n      if (old_to_new[Fi(i, j)] == -1) {\n        contained = false;\n        break;\n      }\n    }\n    if (contained) {\n      f_idxs.push_back(i);\n    }\n  }\n  fprintf(stderr,\"  Found %d/%d valid faces\\n\", f_idxs.size(), Fi.rows());\n  Fo.resize(f_idxs.size(), 3);\n  for (int i = 0; i < f_idxs.size(); ++i) {\n    for (int j = 0; j < 3; ++j) {\n      Fo(i, j) = old_to_new[Fi(f_idxs[i], j)];\n    }\n  }\n  printf(\"  Done! has size %dx%d\\n\", Fo.rows(), Fo.cols());\n}\n\nvoid extractValidVerts(const Eigen::MatrixXd &Vi, const Eigen::MatrixXi &Fi,\n                       const Eigen::VectorXi &Ci, const std::vector<bool> &valid,\n                       Eigen::MatrixXd &Vo, Eigen::MatrixXi &Fo, Eigen::VectorXi &Co) {\n  std::map<int, int> old_to_new;\n  int n_i = 0;\n  for (int i = 0; i < Vi.rows(); ++i) {\n    if (valid[Ci(i)]) {\n      old_to_new[i] = n_i;\n      n_i++;\n    } else {\n      // not valid\n      old_to_new[i] = -1;\n    }\n  }\n  printf(\"  Found %d/%d valid vertices\\n\", n_i, Vi.rows());\n\n  // Resize the vertices to be the number we need.\n  Vo.resize(n_i, 3);\n  Co.resize(n_i);\n  int v_idx = 0;\n  for (int i = 0; i < Vi.rows(); ++i) {\n    if (old_to_new[i] != -1) {\n      Co(v_idx) = Ci(i);\n      Vo.row(v_idx++) = Vi.row(i);\n    }\n  }\n  // Same thing for the faces.\n  // Do this twice so we know how many we need.\n  std::vector<int> f_idxs;\n  for (int i = 0; i < Fi.rows(); ++i) {\n    bool contained = true;\n    for (int j = 0; j < Fi.row(i).size(); ++j) {\n      if (old_to_new[Fi(i, j)] == -1) {\n        contained = false;\n        break;\n      }\n    }\n    if (contained) {\n      f_idxs.push_back(i);\n    }\n  }\n  printf(\"  Found %d/%d valid faces\\n\", f_idxs.size(), Fi.rows());\n  Fo.resize(f_idxs.size(), 3);\n  for (int i = 0; i < f_idxs.size(); ++i) {\n    for (int j = 0; j < 3; ++j) {\n      Fo(i, j) = old_to_new[Fi(f_idxs[i], j)];\n    }\n  }\n  printf(\"  Done! has size %dx%d\\n\", Fo.rows(), Fo.cols());\n}\n\nint main(int argc, char* argv[]) {\n  if (argc < 3) {\n    fprintf(stderr, \"Used for selecting connected components and saving them to a file.\\n\");\n    fprintf(stderr, \"usage: %s <input.off> <output.off>\\n\", argv[0]);\n    return -1;\n  }\n\n  Eigen::MatrixXd Vi, Vo;\n  Eigen::MatrixXi Fi, Fo;\n  Eigen::VectorXi Comps;\n\n  // Read in the input file.\n  igl::readOFF(argv[1], Vi, Fi);\n  igl::components(Fi, Comps);\n  // Get the number of components\n  int max_comp = Comps.maxCoeff();\n  std::vector<bool> valid_comps(max_comp + 1);\n\n  int component_num = 0;\n  igl::viewer::Viewer viewer;\n  viewer.callback_init = [&](igl::viewer::Viewer& viewer) {\n    viewer.callback_key_down = [&](igl::viewer::Viewer& viewer, unsigned char key, int modifier) {\n      // Can increase or decrease number of components.\n      if (key == 'C' || key == 'V') {\n        if (key == 'C') {\n          printf(\"Increasing component with %c\\n\", key);\n          component_num++;\n          if (component_num > max_comp) {\n            component_num = 0;\n          }\n        } else {\n          printf(\"Decreasing component with %c\\n\", key);\n          component_num--;\n          component_num = std::max(component_num, 0);\n        }\n        selectValidVerts(Vi,Fi,Comps, component_num, Vo,Fo);\n        double comp_vol = volume(Vo,Fo);\n        printf(\"Selecting component %d with volume %lf. Press 'X' to delete, ' ' to include\\n\",\n               component_num, comp_vol);\n        viewer.data.clear();\n        viewer.data.set_mesh(Vo, Fo);\n        return true;\n\n      } else if (key == ' ' || key == 'X') {\n        if (key == ' ') {\n          valid_comps[component_num] = true;\n        } else {\n          valid_comps[component_num] = false;\n        }\n        \n        Eigen::VectorXi Co;\n        Eigen::MatrixXd cols;\n        extractValidVerts(Vi,Fi,Comps, valid_comps, Vo,Fo,Co);\n        igl::jet(Co, true, cols);\n        viewer.data.clear();\n        viewer.data.set_mesh(Vo, Fo);\n        viewer.data.set_colors(cols);\n        return true;\n      } else if (key == 'w' || key == 'W') {\n        int n_comps = 0;\n        for (int i = 0; i < valid_comps.size(); ++i) {\n          if (valid_comps[i]) ++n_comps;\n        }\n        printf(\"Writing output with %d components to %s\\n\", n_comps, argv[2]);\n        igl::writeOFF(argv[2], Vo,Fo);\n        printf(\"Finished! You may close the program.\\n\");\n      }\n      return false;\n    };\n    viewer.screen->performLayout();\n    return false;\n  };\n\n  Eigen::MatrixXd cols;\n  igl::jet(Comps, true, cols);\n  viewer.data.set_mesh(Vi, Fi);\n  viewer.data.set_colors(cols);\n  printf(\"Press 'C' or 'V' to (respectively) increase or decrease the components id.\\n\");\n  printf(\"Press ' ' to add the current component to the total components\\n\");\n  printf(\"Press 'x' to remove the current component from the total components\\n\");\n  printf(\"Press 'w' to write the resulting mesh to the output file\\n\");\n  viewer.launch();\n}\n\n", "meta": {"hexsha": "ab9156cb53db83a47e1633f2eb406188311c3bb0", "size": 6479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/select_components.cpp", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "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": "cgal_mesh_generation/select_components.cpp", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "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": "cgal_mesh_generation/select_components.cpp", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "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.7201834862, "max_line_length": 98, "alphanum_fraction": 0.5513196481, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6560408515242657}}
{"text": "#include <gtest/gtest.h> \n#include \"../include/model.h\"\n#include \"../include/KalmanFilter.h\"\n#include \"../include/filterModel.h\"\n#include \"../include/mathWrapper/double.h\"\n#include <math.h>\n#include \"../include/Eigen.h\" \n#include <vector>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/operators.hpp>\n#include <iostream>\n\n\nTEST(discreteDiscreteKalmanFilter, test){\n\t\n\tint stateCount = 1;\n\tint sensorCount = 1;\n\tint initialTime = 0;\n\t//VECTOR_double initialEstimate(1);\n\tvectorDouble initialEstimate(1);\n\t//MATRIX_double initialCovariance(1);\n\tmatrixDouble initialCovariance(1);\n\n\tclass stateModel: public discreteModel<vectorDouble>{\n\t\tpublic:\n\t\t\tvectorDouble function(const vectorDouble & val, const int time) const override{\n\t\t\t\tvectorDouble result(val.getSystemValue() + 0.1);\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\n\tclass measurementModel: public discreteModel<vectorDouble>{\n\t\tpublic:\n\t\t\tvectorDouble function(const vectorDouble & val, const int time) const override{\n\t\t\t\tvectorDouble result(val.getSystemValue());\n\t\t\t\treturn result;\n\t\t\t}\n\t};\n\n\tclass transitionJac: public jacobianDiscrete<vectorDouble,matrixDouble>{\n\t\tpublic:\n\t\t\tmatrixDouble function(const vectorDouble & val, int t){\n\t\t\t\treturn matrixDouble(1);\n\t\t\t}\n\t};\n\t\n\tclass measurementJac: public jacobianDiscrete<vectorDouble,matrixDouble>{\n\t\tpublic:\n\t\t\tmatrixDouble function(const vectorDouble & val, int t){\n\t\t\t\treturn matrixDouble(1);\n\t\t\t}\n\t};\n\t\n\tclass processNoise: public discreteNoiseCovariance<vectorDouble,matrixDouble>{\n\t\tmatrixDouble function(const vectorDouble &v, int t) override{\n\t\t\treturn matrixDouble(0.01);\n\t\t}\t\n\t\tmatrixDouble sqrt(const vectorDouble &v, int t) override{\n\t\t\treturn matrixDouble(0.1);\n\t\t}\n\t};\n\n\tclass sensorNoise: public discreteNoiseCovariance<vectorDouble,matrixDouble>{\n\t\tmatrixDouble function(const vectorDouble &v, int t) override{\n\t\t\treturn matrixDouble(0.01);\n\t\t}\t\n\t\tmatrixDouble sqrt(const vectorDouble &v, int t) override{\n\t\t\treturn matrixDouble(0.1);\n\t\t}\n\t};\n\n\tstateModel tm;\n\tmeasurementModel mm;\n\tprocessNoise pn;\n\tsensorNoise sn;\n\ttransitionJac tj;\n\tmeasurementJac mj;\n\n\tdiscreteDiscreteFilterModel<vectorDouble,matrixDouble> ddfm(&tm,&mm,&pn,&sn,&tj,&mj,stateCount,sensorCount);\n\tdiscreteDiscreteKalmanFilter<vectorDouble,matrixDouble>\n\t\tfilter(initialTime,initialEstimate, initialCovariance, &ddfm);\n\tfor(int i = 0; i < 10; i++){\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),1+0.1*i,1e-9);\n\t\tASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),1+0.01*i,1e-9);\n\t\tASSERT_NEAR(filter.getCurrentTime(),i,1e-9);\n\t\tfilter.predict(1);\n\t}\n\n\tfor(int i = 0; i < 10; i++){\n\t\tvectorDouble measurement(i);\t\n\t\t\n\t\tdouble sk = 1*filter.getCurrentCovariance().getSystemValue()*1 + 0.01;\n\t\tdouble kk = filter.getCurrentCovariance().getSystemValue()*(1.0/sk);\n\t\tdouble curEst = filter.getCurrentEstimate().getSystemValue(); \n\n\t\tfilter.update(measurement);\n\t\t\n\t\tASSERT_NEAR(filter.getCurrentEstimate().getSystemValue(),curEst+kk*(double(i) - curEst),1e-9);\n\t\t//ASSERT_NEAR(filter.getCurrentCovariance().getSystemValue(),1+0.01*i,1e-9);\n\t\t//ASSERT_NEAR(filter.getCurrentTime(),i,1e-9);\n\t}\n}\n\nint main(int argc, char **argv){\n\ttesting::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "bf5d9527079e825057c81995a1c8f3b8a66dc8fb", "size": 3246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++_implementation/tests/tests2.cpp", "max_stars_repo_name": "mannyray/KalmanFilter", "max_stars_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-08-12T04:47:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:00:09.000Z", "max_issues_repo_path": "c++_implementation/tests/tests2.cpp", "max_issues_repo_name": "mannyray/KalmanFilter", "max_issues_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-27T00:49:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T02:03:37.000Z", "max_forks_repo_path": "c++_implementation/tests/tests2.cpp", "max_forks_repo_name": "mannyray/KalmanFilter", "max_forks_repo_head_hexsha": "c744b0ef8a004643b373fa4cfd1440f32d5725b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-03T09:05:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-18T15:22:08.000Z", "avg_line_length": 29.7798165138, "max_line_length": 109, "alphanum_fraction": 0.7378311768, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6560408416641822}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_compute_contiguous_angle_interval.h>\n#include <vector>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_contiguous_interval);\n\nBOOST_AUTO_TEST_CASE(zero_to_two_pi_intervals)\n{\n  // precomputed interval end-points \n\n  double const two_pi = OpenTissue::math::detail::pi<double>()*2.0;\n  double const pi_sixth = OpenTissue::math::detail::pi<double>()/6.0;\n  double const pi_third = OpenTissue::math::detail::pi<double>()/3.0;\n\n  double theta[12];\n  theta[0] = 0.0;\n  for(size_t i=1;i<12;++i)\n    theta[i] = theta[i-1] + pi_sixth;\n\n  // number of samples\n  size_t N = 100u; \n\n  // distance between samples\n  double dt = pi_third/(N-1u);\n\n  // container for angle samples\n  std::vector<double> angles;\n  angles.resize( N );\n\n\n\n  // quater sized test is interval  [ (11 pi/6)  .. (pi/6) ]\n  {\n    double t = theta[11];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>two_pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[11],       0.01 );\n    BOOST_CHECK_CLOSE(  t_max, two_pi+pi_sixth, 0.01 );\n  }\n  // test interval is  [ (2 pi/6)  .. (4 pi/6) ]\n  {\n    double t = theta[2];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[2], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[4], 0.01 );\n  }\n  // test interval is  [ (5 pi/6)  .. (7 pi/6) ]\n  {\n    double t = theta[5];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[5], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[7], 0.01 );\n  }\n  // test interval is  [ (8 pi/6)  .. (10 pi/6) ]\n  {\n    double t = theta[8];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[8], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[10], 0.01 );\n  }\n\n  // Now we want bigger intervals, so distance between samples is changed\n  dt = (10.0*pi_sixth)/(N-1u);\n\n  // test interval is  [ (10 pi/6)  .. (8 pi/6) ]\n  {\n    double t = theta[10];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>two_pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[10], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[8]+two_pi, 0.01 );\n  }\n\n  // test interval is  [ (4 pi/6)  .. (2 pi/6) ]\n  {\n    double t = theta[4];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>two_pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[4], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[2]+two_pi, 0.01 );\n  }\n}\n\n\n\n\n\n\n\n\n\nBOOST_AUTO_TEST_CASE(minus_pi_to_plus_pi_intervals)\n{\n  // precomputed interval end-points \n\n  double const pi = OpenTissue::math::detail::pi<double>();\n  double const two_pi = OpenTissue::math::detail::pi<double>()*2.0;\n  double const pi_sixth = OpenTissue::math::detail::pi<double>()/6.0;\n  double const pi_third = OpenTissue::math::detail::pi<double>()/3.0;\n\n  double theta[12];\n  theta[0] = -pi;\n  for(size_t i=1;i<12;++i)\n    theta[i] = theta[i-1] + pi_sixth;\n\n  // number of samples\n  size_t N = 100u; \n\n  // distance between samples\n  double dt = pi_third/(N-1u);\n\n  // container for angle samples\n  std::vector<double> angles;\n  angles.resize( N );\n\n\n\n  // quater sized test is interval  [ (-pi/6)  .. (pi/6) ]\n  {\n    double t = theta[5];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[5]+two_pi,       0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[7]+two_pi, 0.01 );\n  }\n  // test interval is  [ (2 pi/6)  .. (4 pi/6) ]\n  {\n    double t = theta[8];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[8], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[10], 0.01 );\n  }\n  // test interval is  [ (5 pi/6)  .. (-5 pi/6) ]\n  {\n    double t = theta[11];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[11], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[1]+two_pi, 0.01 );\n  }\n  // test interval is  [ (-4 pi/6)  .. (-2 pi/6) ]\n  {\n    double t = theta[2];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[2]+two_pi, 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[4]+two_pi, 0.01 );\n  }\n\n  // Now we want bigger intervals, so distance between samples is changed\n  dt = (10.0*pi_sixth)/(N-1u);\n\n  // test interval is  [ (-2 pi/6)  .. (-4 pi/6) ]\n  {\n    double t = theta[4];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[4]+two_pi, 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[2]+two_pi+two_pi, 0.01 );\n  }\n\n  // test interval is  [ (4 pi/6)  .. (2 pi/6) ]\n  {\n    double t = theta[10];\n    for(size_t i = 0;i < N;++i)\n    {\n      angles[i] = t;\n      t += dt;\n      if(t>pi)\n        t -= two_pi;\n    }\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, theta[10], 0.01 );\n    BOOST_CHECK_CLOSE(  t_max, theta[8]+two_pi, 0.01 );\n  }\n}\n\n\n\n\nBOOST_AUTO_TEST_CASE(real_data_test)\n{\n  // precomputed interval end-points \n  double const two_pi = OpenTissue::math::detail::pi<double>()*2.0;\n  double const four_pi = OpenTissue::math::detail::pi<double>()*4.0;\n\n  // container for angle samples\n  std::vector<double> angles;\n  angles.resize( 84 );\n\n  size_t i = 0u;\n\n  angles[i++] = 0.3;\n  angles[i++] = 0.4;\n  angles[i++] = 0.5;\n  angles[i++] = 0.6;\n  angles[i++] = 0.7;\n  angles[i++] = 0.8;\n  angles[i++] = 0.9;\n  angles[i++] = 1.0;\n  angles[i++] = 1.1;\n  angles[i++] = 1.2;\n  angles[i++] = 1.3;\n  angles[i++] = 1.4;\n  angles[i++] = 1.5;\n  angles[i++] = 1.6;\n  angles[i++] = 1.7;\n  angles[i++] = 1.8;\n  angles[i++] = 1.9;\n  angles[i++] = 2.0;\n  angles[i++] = 2.1;\n  angles[i++] = 2.2;\n  angles[i++] = 2.3;\n  angles[i++] = 2.4;\n  angles[i++] = 2.5;\n  angles[i++] = 2.6;\n  angles[i++] = 2.7;\n  angles[i++] = 2.8;\n  angles[i++] = 2.9;\n  angles[i++] = 3.0;\n  angles[i++] = 3.1;\n  angles[i++] = -3.1;\n  angles[i++] = -3.0;\n  angles[i++] = -2.9;\n  angles[i++] = -2.8;\n  angles[i++] = -2.7;\n  angles[i++] = -2.6;\n  angles[i++] = -2.5;\n  angles[i++] = -2.6;\n  angles[i++] = -2.7;\n  angles[i++] = -2.8;\n  angles[i++] = -2.9;\n  angles[i++] = -3.0;\n  angles[i++] = -3.1;\n  angles[i++] = 3.1;\n  angles[i++] = 3.0;\n  angles[i++] = 2.9;\n  angles[i++] = 2.8;\n  angles[i++] = 2.7;\n  angles[i++] = 2.6;\n  angles[i++] = 2.5;\n  angles[i++] = 2.4;\n  angles[i++] = 2.3;\n  angles[i++] = 2.2;\n  angles[i++] = 2.1;\n  angles[i++] = 2.0;\n  angles[i++] = 1.9;\n  angles[i++] = 1.8;\n  angles[i++] = 1.7;\n  angles[i++] = 1.6;\n  angles[i++] = 1.5;\n  angles[i++] = 1.4;\n  angles[i++] = 1.3;\n  angles[i++] = 1.2;\n  angles[i++] = 1.1;\n  angles[i++] = 1.0;\n  angles[i++] = 0.9;\n  angles[i++] = 0.8;\n  angles[i++] = 0.7;\n  angles[i++] = 0.6;\n  angles[i++] = 0.5;\n  angles[i++] = 0.4;\n  angles[i++] = 0.3;\n  angles[i++] = 0.2;\n  angles[i++] = 0.1;\n  angles[i++] = 0.0;\n  angles[i++] = -0.1;\n  angles[i++] = -0.2;\n  angles[i++] = -0.3;\n  angles[i++] = -0.4;\n  angles[i++] = -0.5;\n  angles[i++] = -0.6;\n  angles[i++] = -0.7;\n  angles[i++] = -0.8;\n  angles[i++] = -0.9;\n  angles[i++] = -1.0;\n\n  BOOST_CHECK( i == angles.size() );\n\n    double t_min, t_max;\n    OpenTissue::math::compute_contiguous_angle_interval( angles.begin(), angles.end(), t_min, t_max );\n    BOOST_CHECK_CLOSE(  t_min, -1.0+two_pi,       0.01 );\n    BOOST_CHECK_CLOSE(  t_max, -2.5+four_pi, 0.01 );\n}\n\n\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d35fdececb8ba400780b7efd785f938dba9d8795", "size": 9592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/contiguous_interval/src/unit_contiguous_interval.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/contiguous_interval/src/unit_contiguous_interval.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/contiguous_interval/src/unit_contiguous_interval.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 25.6470588235, "max_line_length": 102, "alphanum_fraction": 0.5729774812, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6560408416641821}}
{"text": "#ifndef SDM_STATS_HPP_\n#define SDM_STATS_HPP_\n\n#include \"utils.hpp\"\n\n#include <boost/math/distributions.hpp>\n\nnamespace sdm {\n\n// Eigen's Matrix class has mean function\n\ntemplate <typename RealType> double mean(const std::vector<RealType> &vec) {\n  double sum = 0.0;\n  if (!vec.empty()) {\n    for (auto i = vec.begin(); i != vec.end(); ++i)\n      sum += *i;\n    sum /= static_cast<RealType>(vec.size());\n  }\n  return sum;\n}\n\n// trimProb% trimmed mean\ntemplate <typename RealType, int Options>\ninline double\ntrimedMean(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n           const double trimProb = 0.5) {\n  int l = vec.size();\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1> v_copy = vec;\n  std::sort(v_copy.data(), v_copy.data() + v_copy.size());\n  return (v_copy.segment((int)(nearbyint(l * trimProb)),\n                         (int)(nearbyint(l * (1.0 - trimProb))))).mean();\n}\n\n// ----- scale mesure -----\ntemplate <typename RealType, int Options>\ninline double\nvari(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n     const double the_mean) {\n  double v = 0.0;\n  if (vec.size() > 2)\n    v = ((vec.array() - the_mean).square().sum()) / (vec.size() - 1);\n  return v;\n}\n\ntemplate <typename RealType, int Options>\ninline double vari(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &mat,\n    const double the_mean) {\n  double v = 0.0;\n  if (mat.rows() * mat.cols() > 2)\n    v = ((mat.array() - the_mean).square().sum()) /\n        (mat.rows() * mat.cols() - 1);\n  return v;\n}\n\ntemplate <typename RealType, int Options>\ninline double\nvari(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return vari(vec, vec.mean());\n}\n\ntemplate <typename RealType, int Options>\ninline double vari(const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic,\n                                       Options> &mat) {\n  return vari(mat, mat.mean());\n}\n\ntemplate <typename RealType, int Options>\ninline double\nstdv(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n     const double the_mean) {\n  return sqrt(vari(vec, the_mean));\n}\n\ntemplate <typename RealType, int Options>\ninline double stdv(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &mat,\n    const double the_mean) {\n  return sqrt(vari(mat, the_mean));\n}\n\ntemplate <typename RealType, int Options>\ninline double\nstdv(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return sqrt(vari(vec));\n}\n\ntemplate <typename RealType, int Options>\ninline double stdv(const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic,\n                                       Options> &mat) {\n  return sqrt(vari(mat));\n}\n\ntemplate <typename RealType, int Options>\ninline double\nMLvari(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n       const double the_mean) {\n  double v = 0.0;\n  if (!vec.empty())\n    v = ((vec.array() - the_mean).squared().sum()) / (vec.size());\n  return v;\n}\n\ntemplate <typename RealType, int Options>\ninline double MLvari(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &mat,\n    const double the_mean) {\n  double v = 0.0;\n  if (mat.rows() * mat.cols() > 1)\n    v = ((mat.array() - the_mean).square().sum()) / (mat.rows() * mat.cols());\n  return v;\n}\n\ntemplate <typename RealType, int Options>\ninline double\nMLvari(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return MLvari(vec, vec.mean());\n}\n\ntemplate <typename RealType, int Options>\ninline double MLvari(const Eigen::Matrix<RealType, Eigen::Dynamic,\n                                         Eigen::Dynamic, Options> &mat) {\n  return MLvari(mat, mat.mean());\n}\n\ntemplate <typename RealType, int Options>\ninline double\nMLstdv(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n       const double the_mean) {\n  return sqrt(MLvari(vec, the_mean));\n}\n\ntemplate <typename RealType, int Options>\ninline double MLstdv(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &mat,\n    const double the_mean) {\n  return sqrt(MLvari(mat, the_mean));\n}\n\ntemplate <typename RealType, int Options>\ninline double\nMLstdv(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return sqrt(MLvari(vec));\n}\n\ntemplate <typename RealType, int Options>\ninline double MLstdv(const Eigen::Matrix<RealType, Eigen::Dynamic,\n                                         Eigen::Dynamic, Options> &mat) {\n  return sqrt(MLvari(mat));\n}\n\ntemplate <typename RealType, int Options>\ninline double\nquantileSorted(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n               const double order) {\n  // SDMAssert(0.0 <= order && order <= 1.0);\n  int l = vec.size();\n  double tmp = (l - 1) * order;\n  int lowerIndex = int(floor(tmp));\n  int upperIndex = int(ceil(tmp));\n  tmp -= lowerIndex;\n  return (1.0 - tmp) * vec[lowerIndex] + tmp * vec[upperIndex];\n}\n\ntemplate <typename RealType, int Options>\ninline double\nquantileUnsorted(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n                 const double order) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> vv = vec;\n  std::sort(vv.data(), vv.data() + vv.size());\n  return quantileSorted(vv, order);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nquantile(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n         const double order) {\n  return quantileUnsorted(vec, order);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nquartileRange(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> vv = vec;\n  std::sort(vv.data(), vv.data() + vv.size());\n  return quantileSorted(vv, 0.75) - quantileSorted(vv, 0.25);\n}\n\ntemplate <typename RealType, int Options>\ninline double meanAbsoluteDeviation(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return meanAbsoluteDeviation(vec, vec.maen());\n}\n\ntemplate <typename RealType, int Options>\ninline double meanAbsoluteDeviation(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n    const double the_mean) {\n  int l = vec.size();\n  double ans = 0.0;\n  if (!vec.empty()) {\n    for (int i = 0; i < l; ++i)\n      ans += fabs(vec[i] - the_mean);\n    ans /= static_cast<double>(l);\n  }\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nRealType range(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return static_cast<RealType>(vec.maxCoeff() - vec.minCoeff());\n}\n\ntemplate <typename RealType, int Options>\ninline double stdvByQuartileRange(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> vv = vec;\n  std::sort(vv.data(), vv.data() + vv.size());\n  boost::math::normal_distribution<double> n_dstr(0.0, 1.0);\n  double x = boost::math::quantile(n_dstr, 0.75);\n  return (quantileSorted(vv, 0.75) - quantileSorted(vv, 0.25)) / x;\n}\n\ntemplate <typename RealType, int Options>\ninline double\nlpNorm(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n       const int order) {\n  double ans;\n  if (order == 1) {\n    ans = vec.cwiseAbs().sum();\n  } else if (order == 2) {\n    ans = vec.norm();\n  } else {\n    using std::pow;\n    ans = pow(vec.cwiseAbs().array().pow(order).sum(), RealType(1) / order);\n  }\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\ninline double\nmoment(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n       const int order) {\n  double lp = lpNorm(vec, order);\n  return lp / static_cast<double>(vec.size());\n}\n\ntemplate <typename RealType, int Options>\ninline double\nnormalizedMoment(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n                 const int order, const double the_mean,\n                 const double the_stdv) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> vv =\n      ((vec.array() - the_mean) / the_stdv).matrix();\n  return moment(vv, order);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nnormalizedMoment(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n                 const int order) {\n  double m = vec.mean();\n  double s = stdv(vec, m);\n  return normalizedMoment(vec, order, m, s);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nskew(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return normalizedMoment(vec, 3);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nskew(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n     const double the_mean, const double the_stdv) {\n  return normalizedMoment(vec, 3, the_mean, the_stdv);\n}\n\ntemplate <typename RealType, int Options>\ninline double\nkurt(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return normalizedMoment(vec, 4) - 3.0;\n}\n\ntemplate <typename RealType, int Options>\ninline double\nkurt(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n     const double the_mean, const double the_stdv) {\n  return normalizedMoment(vec, 4, the_mean, the_stdv) - 3.0;\n}\n\ntemplate <typename RealType, int Options>\ndouble median(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  return quantile(vec, 0.5);\n}\n\ntemplate <typename RealType, int Options>\ndouble medianAbsoluteDeviation(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n    double the_median) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> mad =\n      ((vec.array() - the_median).abs()).matrix();\n  return median(mad);\n}\n\ntemplate <typename RealType, int Options>\ndouble medianAbsoluteDeviation(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  double the_median = median(vec);\n  return medianAbsoluteDeviation(vec, the_median);\n}\n\ntemplate <typename RealType, int Options>\nvoid meanAndVari(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n                 double &the_mean, double &the_vari) {\n  the_mean = vec.mean();\n  the_vari = vari(vec, the_mean);\n}\n\ntemplate <typename RealType, int Options>\nvoid meanAndStdv(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec,\n                 double &the_mean, double &the_stdv) {\n  the_mean = vec.mean();\n  the_stdv = stdv(vec, the_mean);\n}\n\ntemplate <typename RealType, int Options>\ndouble coefficientOfVariation(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  double m, s;\n  meanAndVari(vec, m, s);\n  // if (fabs(m) < 1e-12)\n  //   SDMError(\"in coefficientOfVariation(...), the mean is almost 0\");\n  return s / m;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> covMat(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &mat,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &mean_vec) {\n  int n = mat.cols();\n  // SDMAssert(2 <= n);\n  int p = mat.rows();\n  Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> ans(p, p);\n  double ans_jk = 0.0;\n  for (int j = 0; j < p; ++j) {\n    for (int k = j; k < p; ++k) {\n      for (int i = 0; i < n; ++i)\n        ans_jk += (mat.coeffRef(i, j) - mean_vec[j]) *\n                  (mat.coeffRef(i, k) - mean_vec[k]);\n      ans.coeffRef(j, k) = ans.coeffRef(k, j) = ans_jk / (n - 1);\n    }\n  }\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options>\ncorrelationMat(const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic,\n                                   Options> &covMat) {\n  int p = covMat.cols();\n  // if (p != covMat.rows())\n  //   SDMError(\"covMat must be square matrix\");\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> diag(p);\n  for (int i = 0; i < p; ++i)\n    diag[i] = sqrt(covMat.coeffRef(i, i));\n  Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> ans = covMat;\n  for (int i = 0; i < p; ++i) {\n    for (int j = i + 1; j < p; ++j)\n      ans.coeffRef(i, j) = ans.coeffRef(j, i) /= (diag[i] * diag[j]);\n    ans.coeffRef(i, i) = 1.0;\n  }\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> pooledCovMat(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &\n        data1,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> &\n        data2,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &meanVec1,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &meanVec2) {\n  int n1 = data1.cols();\n  int n2 = data2.cols();\n  int n = n1 + n2;\n  int p = data1.rows();\n  // SDMAssert(2 <= n1 && 2 <= n2 && data2.rows() == p);\n\n  Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic, Options> ans(p, p);\n  double ans_jk = 0.0;\n  for (int j = 0; j < p; ++j) {\n    for (int k = j; k < p; ++k) {\n      for (int i = 0; i < n1; ++i)\n        ans_jk += (data1.coeffRef(i, j) - meanVec1[j]) *\n                  (data1.coeffRef(i, k) - meanVec1[k]);\n      for (int i = 0; i < n2; ++i)\n        ans_jk += (data2.coeffRef(i, j) - meanVec2[j]) *\n                  (data2.coeffRef(i, k) - meanVec2[k]);\n      ans.coeffRef(j, k) = ans.coeffRef(k, j) = ans_jk / (n - 2);\n    }\n  }\n  return ans;\n\n  // return static_cast<double>(n1 - 1)/(n - 2)*covMat(data1, meanVec1) +\n  // static_cast<double>(n2 - 1)/(n - 2)*covMat(data2, meanVec2);\n}\n\ntemplate <typename RealType, int Options>\nRealType correlationCoefficient(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v1,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v2) {\n  int l = v1.size();\n  // SDMAssert(v2.size() == l);\n  RealType m1 = v1.mean();\n  RealType m2 = v2.mean();\n  RealType enumerator = 0.0, denominator1 = 0.0, denominator2 = 0.0;\n  for (int i = 0; i < l; i++) {\n    RealType tmp1 = v1[i] - m1;\n    RealType tmp2 = v2[i] - m2;\n    enumerator += tmp1 * tmp2;\n    denominator1 += tmp1 * tmp1;\n    denominator2 += tmp2 * tmp2;\n  }\n  return enumerator / sqrt(denominator1) / sqrt(denominator2);\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, 1, Options> correlationCoefficientTest(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v1,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v2) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> ans(3);\n  RealType r = ans[0] = correlationCoefficient(v1, v2);\n  RealType df = static_cast<RealType>(v1.size() - 2.0);\n  RealType t = ans[1] = r * sqrt(df) / sqrt(1.0 - r * r);\n  boost::math::students_t_distribution<RealType> st_dstr(df);\n  ans[2] = 1.0 - boost::math::cdf(st_dstr, t);\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, 1, Options> extractEqualIndices(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v,\n    const RealType &val) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> ans(v.size());\n  int count = 0;\n  for (int i = 0; i < v.size(); ++i)\n    if (val == v[i])\n      ans[count++] = i;\n  ans.conservativeResize(count);\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, 1, Options> doubleMeanRank(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &rank) {\n  int l = v.size();\n  // SDMAssert(l == rank.size());\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> dRank(l);\n  for (int i = 0; i < l; ++i) {\n    Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> tmpVec1 =\n        extractEqualIndices(v, v[i]);\n    int len = tmpVec1.size();\n    if (len > 1) {\n      Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> tmpVec2(len);\n      for (int j = 0; j < len; ++j)\n        tmpVec2[j] = rank[tmpVec1[j]];\n\n      dRank[i] = tmpVec2.mean();\n    } else {\n      dRank[i] = rank[i];\n    }\n  }\n  return dRank;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, 1, Options> argsortDecOrder(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n\n  using pair_sort = std::pair<int, RealType>;\n  std::vector<pair_sort> sort_vec;\n  for (int i = 0; i < vec.size(); ++i)\n    sort_vec.push_back(i, vec[i]);\n  std::sort(sort_vec.begin(), sort_vec.end(), lessPair);\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> ans(vec.size());\n  for (int i = 0; i < vec.size(); ++i)\n    ans[i] = (sort_vec[i])->first;\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\nEigen::Matrix<RealType, Eigen::Dynamic, 1, Options>\nrankDecOrder(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &vec) {\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> idx =\n      argsortDecOrder(vec);\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> ans(vec.size());\n  for (int i = 0; i < vec.size(); ++i)\n    ans[idx[i]] = i;\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\ndouble spearmanRankCorrelation(\n    Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v1,\n    Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v2) {\n  int l = v1.size();\n  // SDMAssert(v2.size() == l);\n  // Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> rank1 =\n  // rankDecOrder(v1);\n  // Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> rank2 =\n  // rankDecOrder(v2);\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> dRank1 =\n      doubleMeanRank(v1, rankDecOrder(v1));\n  Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> dRank2 =\n      doubleMeanRank(v2, rankDecOrder(v2));\n  double sum = 0.0;\n  for (int i = 0; i < l; ++i) {\n    double tmp_i = (dRank1[i] - dRank2[i]);\n    sum += tmp_i * tmp_i;\n  }\n  return 1.0 - 6.0 * sum / (double)(l * (l * l - 1));\n}\n\ntemplate <typename RealType, int Options>\ndouble mixQuantile(const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &v,\n                   const double order) {\n  // SDMAssert(0.0 <= order && order <= 1.0);\n  int numKernel = v.size() / 3;\n  // SDMAssert(numKernel > 3);\n  double ans = 0.0;\n  boost::math::normal_distribution<double> n_dstr(0.0, 1.0);\n  for (int i = 0; i < numKernel; ++i)\n    ans +=\n        (boost::math::quantile(n_dstr, order) * v[i * 3 + 1] + v[i * 3 + 2]) *\n        v[i * 3];\n\n  return ans;\n}\n\ntemplate <typename RealType, int Options>\ndouble quantileFromNormalMixture(\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &coefficient,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &mu,\n    const Eigen::Matrix<RealType, Eigen::Dynamic, 1, Options> &sigma,\n    const double order) {\n  int numComponent = coefficient.size();\n  // SDMAssert(mu.size() == numComponent && sigma.size() == numComponent);\n  // SDMAssert(0.0 <= order && order <= 1.0);\n  double ans = 0.0;\n  boost::math::normal_distribution<double> n_dstr(0.0, 1.0);\n  for (int k = 0; k < numComponent; ++k)\n    ans += coefficient[k] *\n           (boost::math::quantile(n_dstr, order) * sigma[k] + mu[k]);\n  return ans;\n}\n\n} // namespace sdm\n\n#endif\n", "meta": {"hexsha": "72902df189ce34531662f316c3f0aeb90d0710ff", "size": 18829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/stats.hpp", "max_stars_repo_name": "husk214/libsdm", "max_stars_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-01-15T14:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T08:12:45.000Z", "max_issues_repo_path": "lib/stats.hpp", "max_issues_repo_name": "husk214/libsdm", "max_issues_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "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": "lib/stats.hpp", "max_forks_repo_name": "husk214/libsdm", "max_forks_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-06T11:50:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-23T16:48:12.000Z", "avg_line_length": 33.4440497336, "max_line_length": 80, "alphanum_fraction": 0.6487333369, "num_tokens": 5563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6560162042841398}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/range/adaptor/reversed.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nENREGISTRER_PROBLEME(175,\n                     \"Fractions involving the number of different ways a number can be expressed as a sum of powers of 2\") {\n    // Define f(0)=1 and f(n) to be the number of ways to write n as a sum of powers of 2 where no power occurs more\n    // than twice.\n    //\n    // For example, f(10)=5 since there are five different ways to express 10:\n    // 10 = 8+2 = 8+1+1 = 4+4+2 = 4+2+2+1+1 = 4+4+1+1\n    // \n    // It can be shown that for every fraction p/q (p>0, q>0) there exists at least one integer n such that\n    // f(n)/f(n-1)=p/q.\n    // \n    // For instance, the smallest n for which f(n)/f(n-1)=13/17 is 241.\n    // The binary expansion of 241 is 11110001.\n    // Reading this binary number from the most significant bit to the least significant bit there are 4 one's, 3 zeroes\n    // and 1 one. We shall call the string 4,3,1 the Shortened Binary Expansion of 241.\n    // \n    // Find the Shortened Binary Expansion of the smallest n for which\n    // f(n)/f(n-1)=123456789/987654321.\n    //\n    // Give your answer as comma separated integers, without any whitespaces.\n    nombre p = 123456789;\n    nombre q = 987654321;\n\n    vecteur resultat;\n\n    while (q != 0) {\n        if (p > q) {\n            resultat.push_back(p / q - (p % q == 0 ? 1 : 0));\n            p = p % q == 0 ? q : p % q;\n        } else {\n            resultat.push_back(q / p);\n            q %= p;\n        }\n    }\n\n    std::ostringstream oss;\n    bool premier = true;\n    for (auto &i : boost::adaptors::reverse(resultat)) {\n        if (premier)\n            premier = false;\n        else\n            oss << \",\";\n\n        oss << i;\n    }\n\n    return oss.str();\n}\n", "meta": {"hexsha": "eb1053ef8958b7f6c7e0e6c2a801b38e10ecaf48", "size": 1856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme175.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/probleme175.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/probleme175.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": 31.4576271186, "max_line_length": 124, "alphanum_fraction": 0.5856681034, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6560161994357857}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example power-iter.cpp\n*\n*   This tutorial demonstrates the calculation of the eigenvalue with largest modulus using the power iteration method.\n*\n*   We start with including the necessary headers:\n**/\n\n// Sparse matrices in uBLAS are *very* slow if debug mode is enabled. Disable it:\n#ifndef NDEBUG\n  #define BOOST_UBLAS_NDEBUG\n#endif\n\n// Include necessary system headers\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <string>\n\n#define VIENNACL_WITH_UBLAS\n\n// Include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n#include \"viennacl/linalg/power_iter.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n// Some helper functions for this tutorial:\n#include <iostream>\n\n// Boost includes:\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n\n/**\n*  To run the power iteration, we set up a sparse matrix using Boost.uBLAS, transfer it over to a ViennaCL matrix, and then run the algorithm.\n**/\nint main()\n{\n  // This example relies on double precision to be available and will provide only poor results with single precision\n  typedef double     ScalarType;\n\n  /**\n  * Create the sparse uBLAS matrix and read the matrix from the matrix-market file:\n  **/\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;\n\n  if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /**\n  *  Transfer the data from the uBLAS matrix over to the ViennaCL sparse matrix:\n  **/\n  viennacl::compressed_matrix<ScalarType>  vcl_A(ublas_A.size1(), ublas_A.size2());\n  viennacl::copy(ublas_A, vcl_A);\n\n  /**\n  *  Run the power iteration up until the largest eigenvalue changes by less than the specified tolerance.\n  *  Print the results of running with uBLAS as well as ViennaCL and exit.\n  **/\n  viennacl::linalg::power_iter_tag ptag(1e-6);\n\n  std::cout << \"Starting computation of eigenvalue with largest modulus (might take about a minute)...\" << std::endl;\n  std::cout << \"Result of power iteration with ublas matrix (single-threaded): \" << viennacl::linalg::eig(ublas_A, ptag) << std::endl;\n  std::cout << \"Result of power iteration with ViennaCL (OpenCL accelerated): \" << viennacl::linalg::eig(vcl_A, ptag) << std::endl;\n\n  /**\n   *  You can also obtain the associated *approximated* eigenvector by passing it as a third argument to eig()\n   *  Tighten the tolerance passed to ptag above in order to obtain more accurate results.\n   **/\n  viennacl::vector<ScalarType> eigenvector(vcl_A.size1());\n  viennacl::linalg::eig(vcl_A, ptag, eigenvector);\n  std::cout << \"First three entries in eigenvector: \" << eigenvector[0] << \" \" << eigenvector[1] << \" \" << eigenvector[2] << std::endl;\n  viennacl::vector<ScalarType> Ax = viennacl::linalg::prod(vcl_A, eigenvector);\n  std::cout << \"First three entries in A*eigenvector: \" << Ax[0] << \" \" << Ax[1] << \" \" << Ax[2] << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "951d7d7e4841b1a7f65a1b609884759c73386b02", "size": 4089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/power-iter.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/power-iter.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/power-iter.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 38.214953271, "max_line_length": 142, "alphanum_fraction": 0.6651993152, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6560161944443623}}
{"text": "\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/K_neighbor_search.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Timer.h>\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/lexical_cast.hpp>\n\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef CGAL::Search_traits_3<K> TreeTraits_3;\ntypedef K::Point_3 Point_3;\ntypedef CGAL::Euclidean_distance<TreeTraits_3> Distance;\ntypedef CGAL::Sliding_midpoint<TreeTraits_3> Splitter;\ntypedef CGAL::Orthogonal_k_neighbor_search<TreeTraits_3,Distance,Splitter> Neighbor_search_3;\ntypedef Neighbor_search_3::Tree Tree_3;\ntypedef CGAL::Timer Timer;\n\n\ntypedef std::vector<Point_3> Points;\n\n\nvoid read(Points& points, char* argv)\n{\n  int d, n;\n  double x,y,z;\n#if 0\n  std::ifstream data(argv);\n  data >> d >> n;\n  assert(d == 3);\n  points.reserve(n);\n  while(data >> p){\n    points.push_back(p);\n  }\n  data.close();\n\n#else\n std::ifstream data(argv, std::ios::in | std::ios::binary);\n  CGAL::IO::set_binary_mode(data);\n  CGAL::read(data,d);\n  CGAL::read(data,n);\n\n  points.reserve(n);\n  for(int i=0; i < n; i++){\n    CGAL::read(data,x);\n    CGAL::read(data,y);\n    CGAL::read(data,z);\n    points.push_back(Point_3(x,y,z));\n  }\n#endif\n  data.close();\n}\n\nint main(int argc,char *argv[])\n{\n  Points query_points_3, data_points_3;\n\n  Point_3 p;\n  Timer t;\n\n  read(data_points_3, argv[1]);\n  read(query_points_3, argv[2]);\n\n  int runs = (argc>3) ? boost::lexical_cast<int>(argv[3]) : 1;\n  std::cerr << \"runs = \"  << runs <<std::endl;\n\n  int bucketsize = (argc>4) ? boost::lexical_cast<int>(argv[4]) : 10;\n  std::cerr << \"bucketsize = \"  << bucketsize <<std::endl;\n\n  int NN_number = (argc>5) ? boost::lexical_cast<int>(argv[5]) : 10;\n  std::cerr << \"k = \"  << NN_number <<std::endl;\n\n  t.start();\n  // Insert data points in the tree\n  Tree_3 tree(data_points_3.begin(), data_points_3.end(),Splitter(bucketsize));\n  tree.build();\n  t.stop();\n  std::cerr << \"build \" << t.time() << \" sec\\n\";\n  int items=0,leafs=0,internals=0;\n  Points result(NN_number);\n  tree.statistics(std::cerr);\n  double sum=0;\n  bool dump = true;\n\n\n  for(int i = 0 ; i<runs; ++i){\n\n\n    for(Points::iterator it = query_points_3.begin(); it != query_points_3.end(); ++it) {\n      // Initialize the search structure, and search all NN_number neighbors\n       t.reset();t.start();\n      Neighbor_search_3 search(tree, *it, NN_number);\n       t.stop();\n      int i=0;\n      for (Neighbor_search_3::iterator it = search.begin(); it != search.end();it++, i++) {\n        result[i] = it->first;\n        if(dump){\n          std::cerr << result[i].x()<<\" \"<<result[i].y()<<\" \"<<result[i].z()<< std::endl;\n        }\n      }\n      dump = false;\n       sum += t.time();\n       items+=search.items_visited();\n       leafs+=search.leafs_visited();\n       internals+=search.internals_visited();\n    }\n\n  }\n\n  std::cerr << items <<\" items\\n\";\n  std::cerr << leafs <<\" leaf\\n\";\n  std::cerr << internals <<\" internals visited\\n\";\n\n  std::cerr<<std::endl << \"total: \" << sum << \" sec\\n\";\n  if(runs>1){\n    std::cerr << \"average: \" << sum/runs << \" sec\\n\";\n  }\n    std::cerr << \"done\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "58fba65de4de1a319ebf6c7100d918862b560375", "size": 3139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Spatial_searching/benchmark/Spatial_searching/nn3cgal.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": "Spatial_searching/benchmark/Spatial_searching/nn3cgal.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": "Spatial_searching/benchmark/Spatial_searching/nn3cgal.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": 25.314516129, "max_line_length": 93, "alphanum_fraction": 0.6256769672, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782092, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6560161944443623}}
{"text": "// Copyright 2020, Madhur Chauhan\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#ifndef BOOST_MATH_SPECIAL_FIBO_HPP\n#define BOOST_MATH_SPECIAL_FIBO_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <cmath>\n#include <limits>\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\nnamespace boost {\nnamespace math {\n\nnamespace detail {\n   constexpr double fib_bits_phi = 0.69424191363061730173879026;\n   constexpr double fib_bits_deno = 1.1609640474436811739351597;\n} // namespace detail\n\ntemplate <typename T>\ninline BOOST_CXX14_CONSTEXPR T unchecked_fibonacci(unsigned long long n) noexcept(std::is_fundamental<T>::value) {\n    // This function is called by the rest and computes the actual nth fibonacci number\n    // First few fibonacci numbers: 0 (0th), 1 (1st), 1 (2nd), 2 (3rd), ...\n    if (n <= 2) return n == 0 ? 0 : 1;\n    /* \n     * This is based on the following identities by Dijkstra:\n     *   F(2*n)   = F(n)^2 + F(n+1)^2\n     *   F(2*n+1) = (2 * F(n) + F(n+1)) * F(n+1)\n     * The implementation is iterative and is unrolled version of trivial recursive implementation.\n     */\n    unsigned long long mask = 1;\n    for (int ct = 1; ct != std::numeric_limits<unsigned long long>::digits && (mask << 1) <= n; ++ct, mask <<= 1)\n        ;\n    T a{1}, b{1};\n    for (mask >>= 1; mask; mask >>= 1) {\n        T t1 = a * a;\n        a = 2 * a * b - t1, b = b * b + t1;\n        if (mask & n) \n            t1 = b, b = b + a, a = t1; // equivalent to: swap(a,b), b += a;\n    }\n    return a;\n}\n\ntemplate <typename T, class Policy>\nT inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n, const Policy &pol) {\n    // check for overflow using approximation to binet's formula: F_n ~ phi^n / sqrt(5)\n    if (n > 20 && n * detail::fib_bits_phi - detail::fib_bits_deno > std::numeric_limits<T>::digits)\n        return policies::raise_overflow_error<T>(\"boost::math::fibonacci<%1%>(unsigned long long)\", \"Possible overflow detected.\", pol);\n    return unchecked_fibonacci<T>(n);\n}\n\ntemplate <typename T>\nT inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n) {\n    return fibonacci<T>(n, policies::policy<>());\n}\n\n// generator for next fibonacci number (see examples/reciprocal_fibonacci_constant.hpp)\ntemplate <typename T>\nclass fibonacci_generator {\n  public:\n    // return next fibonacci number\n    T operator()() noexcept(std::is_fundamental<T>::value) {\n        T ret = a;\n        a = b, b = b + ret; // could've simply: swap(a, b), b += a;\n        return ret;\n    }\n\n    // after set(nth), subsequent calls to the generator returns consecutive\n    // fibonacci numbers starting with the nth fibonacci number\n    void set(unsigned long long nth) noexcept(std::is_fundamental<T>::value) {\n        n = nth;\n        a = unchecked_fibonacci<T>(n);\n        b = unchecked_fibonacci<T>(n + 1);\n    }\n\n  private:\n    unsigned long long n = 0;\n    T a = 0, b = 1;\n};\n\n} // namespace math\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "7aaf6dd85427bd64d80f51a36aedf817104dda1d", "size": 3112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/fibonacci.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/fibonacci.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/fibonacci.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": 33.4623655914, "max_line_length": 136, "alphanum_fraction": 0.6526349614, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6560161897390773}}
{"text": "#ifndef CRYPT_HPP\n#define CRYPT_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nstruct RSAKey\n{\n\tboost::multiprecision::cpp_int n, exponent;\n};\n\nboost::multiprecision::cpp_int decrypt(const RSAKey& privateKey, const boost::multiprecision::cpp_int& cypher);\nboost::multiprecision::cpp_int encrypt(const RSAKey& publicKey, const boost::multiprecision::cpp_int& plain);\nRSAKey makePrivateKey(const boost::multiprecision::cpp_int& p, const boost::multiprecision::cpp_int& q, const boost::multiprecision::cpp_int& e);\nRSAKey makePublicKey(const boost::multiprecision::cpp_int& n, const boost::multiprecision::cpp_int& e);\n\n#endif /* CRYPT_HPP */\n", "meta": {"hexsha": "c4aa41fccedd89569a065c974bcce3da9f943317", "size": 643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Crypt.hpp", "max_stars_repo_name": "nicoaw/rsa", "max_stars_repo_head_hexsha": "c432dbbc3b5e2fc88a4a49c2a9dd6b6a0693a3bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-13T05:36:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-13T05:36:57.000Z", "max_issues_repo_path": "src/Crypt.hpp", "max_issues_repo_name": "nicoaw/rsa", "max_issues_repo_head_hexsha": "c432dbbc3b5e2fc88a4a49c2a9dd6b6a0693a3bd", "max_issues_repo_licenses": ["MIT"], "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/Crypt.hpp", "max_forks_repo_name": "nicoaw/rsa", "max_forks_repo_head_hexsha": "c432dbbc3b5e2fc88a4a49c2a9dd6b6a0693a3bd", "max_forks_repo_licenses": ["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.8235294118, "max_line_length": 145, "alphanum_fraction": 0.7869362364, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6559656694226097}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/Extreme_points_traits_adapter_3.h>\n#include <CGAL/IO/read_points.h>\n\n#include <boost/iterator/counting_iterator.hpp>\n\n#include <vector>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel      K;\ntypedef K::Point_3                                               Point_3;\n\nint main(int argc, char* argv[])\n{\n  const std::string filename = (argc>1) ? argv[1] : CGAL::data_file_path(\"meshes/star.off\");\n\n  std::vector<Point_3> points;\n  if(!CGAL::IO::read_points(filename, std::back_inserter(points)))\n  {\n    std::cerr<< \"Cannot open input file.\" <<std::endl;\n    return 1;\n  }\n\n  //This will contain the extreme vertices\n  std::vector<std::size_t> extreme_point_indices;\n\n  //call the function with the traits adapter for vertices\n  CGAL::extreme_points_3(CGAL::make_range(boost::counting_iterator<std::size_t>(0),\n                                          boost::counting_iterator<std::size_t>(points.size())),\n                         std::back_inserter(extreme_point_indices),\n                         CGAL::make_extreme_points_traits_adapter(CGAL::make_property_map(points)));\n\n  //print the number of extreme vertices\n  std::cout << \"Indices of points on the convex hull are:\\n\";\n  std::copy(extreme_point_indices.begin(), extreme_point_indices.end(), std::ostream_iterator<std::size_t>(std::cout, \" \"));\n  std::cout << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "04d6cdf41cf9d5f8f7715a74abda01059398bb80", "size": 1483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Convex_hull_3/examples/Convex_hull_3/extreme_indices_3.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": "Convex_hull_3/examples/Convex_hull_3/extreme_indices_3.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": "Convex_hull_3/examples/Convex_hull_3/extreme_indices_3.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": 36.1707317073, "max_line_length": 124, "alphanum_fraction": 0.6729602158, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6559595521650737}}
{"text": "/**************************************************************************\nCopyright (c) 2012, Julio C. Estrada\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n+ Redistributions of source code must retain the above copyright notice,\n  this list of conditions and the following disclaimer.\n\n+ 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\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**************************************************************************/\n\n#include \"utils.h\"\n#include <cmath>\n#include <Eigen/Dense>\n\n#define cimg_display 0\n#include <CImg.h>\n\nvoid gradient(const Eigen::ArrayXXf& I, Eigen::ArrayXXf& dx, Eigen::ArrayXXf& dy)\n{\n  dx.resize(I.rows(), I.cols());\n  dy.resize(I.rows(), I.cols());\n\n  for(int i=0; i<I.rows()-1; i++)\n    for(int j=0; j<I.cols()-1; j++){\n      dx(i,j) = I(i,j+1)-I(i,j);\n      dy(i,j) = I(i+1,j)-I(i,j);\n    }\n  for(int i=0; i<I.rows(); i++)\n    dy(i,I.cols()-1)=dy(i,I.cols()-2);\n  for(int i=0; i<I.cols(); i++)\n    dx(I.rows()-1,i)=dx(I.rows()-2,i);\n}\n\nvoid parabola(Eigen::ArrayXXf& mat, float A)\n{\n  const int M=mat.rows(), N=mat.cols();\n  const float cm=M/2.0, cn=N/2.0;\n\n\n  for(int i=0; i<M; i++)\n    for(int j=0; j<N; j++)\n      mat(i,j)= A*((i-cm)*(i-cm) + (j-cn)*(j-cn));\n}\n\nvoid cosine(const Eigen::ArrayXXf& angle, Eigen::ArrayXXf& cc)\n{\n  const int M=angle.rows(), N=angle.cols();\n  for(int i=0; i<M; i++)\n    for(int j=0; j<N; j++)\n      cc(i,j)=cos(angle(i,j));\n}\n\nvoid linspaced(Eigen::ArrayXXf& X, Eigen::ArrayXXf& Y, const float bx, float ex,\n               const float by, float ey,\n               const int M, const int N)\n{\n  X.resize(M,N);\n  Y.resize(M,N);\n  const float stepx = (ex-bx)/(float)(N-1);\n  const float stepy = (ey-by)/(float)(M-1);\n  float *const __restrict__ ptx=(float*)X.data();\n  float *const __restrict__ pty=(float*)Y.data();\n  size_t idx;\n\n  float x=bx;\n  float y=by;\n  for(int i=0; i<M; i++){\n    idx=N*i;\n    x=bx;\n    for(int j=0; j<N; j++){\n      ptx[idx+j]=x;\n      pty[idx+j]=y;\n      x+=stepx;\n    }\n    y+=stepy;\n  }\n}\n\nEigen::ArrayXXf peaks(const int M, const int N)\n{\n  Eigen::ArrayXXf X, Y;\n  Eigen::ArrayXXf p(M,N);\n  Eigen::ArrayXXf tmp;\n  linspaced(X, Y, -3.0, 3.0, -3.0, 3.0, M, N);\n\n  p = 1 - X/2.0;\n  tmp = X.pow(5);\n  p+= tmp;\n  tmp = Y.pow(3);\n  p+= tmp;\n\n  tmp = (-X*X-Y*Y).exp();\n  p*=tmp;\n\n  return p;\n}\n\nEigen::ArrayXXf ramp(float wx, float wy, const int M, const int N)\n{\n  Eigen::ArrayXXf X, Y, res;\n  linspaced(X, Y, 0, M-1, 0, N-1, M, N);\n  res = wx*X + wy*Y;\n\n  return res;\n}\n\nEigen::ArrayXXf speckle_peaks(const int M, const int N, const float magn,\n               const int speckle_size)\n{\n  using namespace cimg_library;\n  Eigen::ArrayXXf Ic0;\n  Eigen::ArrayXXf Ic1;\n  Eigen::ArrayXXf p = peaks(M,N)*magn;\n  Eigen::ArrayXXf noise0(M,N);\n  Eigen::ArrayXXf noise1(M,N);\n  CImg<float> n0(noise0.data(), noise0.cols(), noise0.rows(), 1, 1, true);\n  CImg<float> n1(noise1.data(), noise1.cols(), noise1.rows(), 1, 1, true);\n  const float pi=M_PI;\n\n  float sigma = speckle_size/6.0;\n  n0.rand(-pi, pi);\n  n1.rand(-pi, pi);\n  n0.blur(sigma);\n  n1.blur(sigma);\n  noise0 = mapRange(noise0, -pi, pi);\n  noise1 = mapRange(noise1, -pi, pi);\n\n  Ic0 = wphase(noise0);\n  Ic1 = wphase(noise1 + p + pi/2.);\n\n  return wphase(Ic0-Ic1);\n}\n\nEigen::ArrayXXf wphase(const Eigen::ArrayXXf& p)\n{\n  Eigen::ArrayXXf wp(p.rows(), p.cols());\n  float *const __restrict__ pt_wp = (float*)wp.data();\n  float *const __restrict__ pt_p = (float*)p.data();\n  size_t idx;\n\n  for(int i=0; i<p.rows(); i++){\n    idx=i*p.cols();\n    for(int j=0; j<p.cols(); j++)\n      pt_wp[idx+j] = atan2(sin(pt_p[idx+j]), cos(pt_p[idx+j]));\n  }\n\n  return wp;\n}\n\nEigen::ArrayXXf mapRange(const Eigen::ArrayXXf& mat, float a, float b)\n{\n  Eigen::ArrayXXf img;\n  double min = mat.minCoeff();\n  double max = mat.maxCoeff();\n\n  float m = (b-a)/(max-min);\n\n  img = m*(mat-min) + a;\n  return img;\n}\n", "meta": {"hexsha": "65a02c8c66dd5e07b02462374194166325e950ad", "size": 4847, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils/utils.cc", "max_stars_repo_name": "trago/fringeproc", "max_stars_repo_head_hexsha": "6a2441bce129a56296f50b9c333609cc3036eb7e", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-17T14:19:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-08T07:03:23.000Z", "max_issues_repo_path": "utils/utils.cc", "max_issues_repo_name": "trago/fringeproc", "max_issues_repo_head_hexsha": "6a2441bce129a56296f50b9c333609cc3036eb7e", "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": "utils/utils.cc", "max_forks_repo_name": "trago/fringeproc", "max_forks_repo_head_hexsha": "6a2441bce129a56296f50b9c333609cc3036eb7e", "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.0782122905, "max_line_length": 81, "alphanum_fraction": 0.619764803, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6559595460616477}}
{"text": "#ifdef STAND_ALONE\n#   define BOOST_TEST_MODULE RayTracerChallengeTests\n#endif\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <shared/Point.h>\n#include <shared/Translation.h>\n#include <shared/Scaling.h>\n#include <shared/RotationX.h>\n#include <shared/RotationY.h>\n#include <shared/RotationZ.h>\n#include <shared/Shearing.h>\n#include <shared/Canvas.h>\n#include <shared/Output.h>\n#include <shared/Environment.h>\n#include <shared/World.h>\n\nBOOST_AUTO_TEST_SUITE(translation_suite)\n\n    BOOST_AUTO_TEST_CASE(multiplying_by_translation_matrix_test) {\n        auto t = Translation(5, -3, 2);\n        auto p = Point(-3, 4, 5);\n\n        BOOST_CHECK_EQUAL(Point(2, 1, 7), t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(multiplying_by_inverse_translation_matrix_test) {\n        auto t = Translation(5, -3, 2);\n        auto inv = t.inverse();\n        auto p = Point(-3, 4, 5);\n\n        BOOST_CHECK_EQUAL(Point(-8, 7, 3), inv.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(translation_does_not_affect_vectors_test) {\n        auto t = Translation(5, -3, 2);\n        auto v = Vector(-3, 4, 5);\n\n        BOOST_CHECK_EQUAL(v, t.multiply(v));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(scaling_matrix_applied_to_a_point_test) {\n        auto s = Scaling(2, 3, 4);\n        auto p = Point(-4, 6, 8);\n        auto pp = Point(-8, 18, 32);\n\n        BOOST_CHECK_EQUAL(pp, s.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(scaling_matrix_applied_to_a_vector_test) {\n        auto s = Scaling(2, 3, 4);\n        auto v = Vector(-4, 6, 8);\n        auto vv = Vector(-8, 18, 32);\n\n        BOOST_CHECK_EQUAL(vv, s.multiply(v));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(multiplying_by_the_inverse_of_a_scaling_matrix_test) {\n        auto s = Scaling(2, 3, 4);\n        auto inv = s.inverse();\n        auto v = Vector(-4, 6, 8);\n        auto vv = Vector(-2, 2, 2);\n\n        BOOST_CHECK_EQUAL(vv, inv.multiply(v));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(reflection_is_scaling_by_a_negative_value_test) {\n        auto s = Scaling(-1, 1, 1);\n        auto p = Point(2, 3, 4);\n        auto pp = Point(-2, 3, 4);\n\n        BOOST_CHECK_EQUAL(pp, s.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(rotating_a_point_around_the_x_axis_test) {\n        auto p = Point(0, 1, 0);\n        auto half_quarter = RotationX(M_PI / 4);\n        auto full_quarter = RotationX(M_PI / 2);\n\n        auto ph = Point(0, sqrt(2) / 2, sqrt(2) / 2);\n        auto pf = Point(0, 0, 1);\n\n        BOOST_CHECK_EQUAL(ph, half_quarter.multiply(p));\n        BOOST_CHECK_EQUAL(pf, full_quarter.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(the_inverse_of_an_x_rotation_rotates_in_the_opposite_direction_test) {\n        auto p = Point(0, 1, 0);\n        auto half_quarter = RotationX(M_PI / 4);\n\n        auto ph = Point(0, sqrt(2) / 2, -sqrt(2) / 2);\n\n        auto inv = half_quarter.inverse();\n\n        BOOST_CHECK_EQUAL(ph, inv.multiply(p));\n\n\n    }\n\n    BOOST_AUTO_TEST_CASE(rotating_a_point_around_the_y_axis_test) {\n        auto p = Point(0, 0, 1);\n        auto half_quarter = RotationY(M_PI / 4);\n        auto full_quarter = RotationY(M_PI / 2);\n\n        auto ph = Point(sqrt(2) / 2, 0, sqrt(2) / 2);\n        auto pf = Point(1, 0, 0);\n\n        BOOST_CHECK_EQUAL(ph, half_quarter.multiply(p));\n        BOOST_CHECK_EQUAL(pf, full_quarter.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(rotating_a_point_around_the_z_axis_test) {\n        auto p = Point(0, 1, 0);\n        auto half_quarter = RotationZ(M_PI / 4);\n        auto full_quarter = RotationZ(M_PI / 2);\n\n        auto ph = Point(-sqrt(2) / 2, sqrt(2) / 2, 0);\n        auto pf = Point(-1, 0, 0);\n\n        BOOST_CHECK_EQUAL(ph, half_quarter.multiply(p));\n        BOOST_CHECK_EQUAL(pf, full_quarter.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_x_in_proportion_to_y_test) {\n        auto t = Shearing(1, 0, 0, 0, 0, 0);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(5, 3, 4);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_x_in_proportion_to_z_test) {\n        auto t = Shearing(0, 1, 0, 0, 0, 0);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(6, 3, 4);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_y_in_proportion_to_x_test) {\n        auto t = Shearing(0, 0, 1, 0, 0, 0);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(2, 5, 4);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_y_in_proportion_to_z_test) {\n        auto t = Shearing(0, 0, 0, 1, 0, 0);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(2, 7, 4);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_z_in_proportion_to_x_test) {\n        auto t = Shearing(0, 0, 0, 0, 1, 0);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(2, 3, 6);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(a_shearing_transformation_moves_z_in_proportion_to_y_test) {\n        auto t = Shearing(0, 0, 0, 0, 0, 1);\n\n        auto p = Point(2, 3, 4);\n\n        auto pp = Point(2, 3, 7);\n\n        BOOST_CHECK_EQUAL(pp, t.multiply(p));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(individual_transformations_are_applied_in_sequence_test) {\n        auto p = Point(1, 0, 1);\n        auto A = RotationX(M_PI / 2);\n        auto B = Scaling(5, 5, 5);\n        auto C = Translation(10, 5, 7);\n\n        auto p2 = A.multiply(p);\n\n        BOOST_CHECK_EQUAL(p2, Point(1, -1, 0));\n\n        auto p3 = B.multiply(p2);\n\n        BOOST_CHECK_EQUAL(p3, Point(5, -5, 0));\n\n        auto p4 = C.multiply(p3);\n\n        BOOST_CHECK_EQUAL(p4, Point(15, 0, 7));\n    }\n\n    BOOST_AUTO_TEST_CASE(chained_transformations_must_be_applied_in_reverse_order_test) {\n        auto p = Point(1, 0, 1);\n        auto A = RotationX(M_PI / 2);\n        auto B = Scaling(5, 5, 5);\n        auto C = Translation(10, 5, 7);\n\n        auto T = C.multiply(B).multiply(A);\n\n        BOOST_CHECK_EQUAL(T.multiply(p), Point(15, 0, 7));\n    }\n\n    BOOST_AUTO_TEST_CASE(watchface_test) {\n        int width = 500;\n        int height = 500;\n\n        auto c = Canvas(width, height);\n\n        const Color &white = Color(1, 1, 1);\n\n        double radius = 3.0 / 8.0 * width;\n        auto scaling = Scaling(radius, 0, radius);\n\n        Tuple twelve = Point(0, 0, 1);\n        Tuple center = Point(0, 0, 0);\n\n        int canvas_center = width / 2;\n\n        c.writePixel(center.x + canvas_center, center.z + canvas_center, white);\n\n        for(int i=0;i<12;i++) {\n            auto rotation = RotationY(i * M_PI / 6);\n\n            auto hour = rotation.multiply(twelve);\n\n            const Tuple &scaled = scaling.multiply(hour);\n            double x = scaled.x + canvas_center;\n            double y = scaled.z + canvas_center;\n\n            c.writePixel(x, y, white);\n\n        }\n\n\n        c.toFile(\"watchface.ppm\");\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "ee82037741e5344382435ed564319e118d2bda00", "size": 6955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_translation.cpp", "max_stars_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_stars_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_translation.cpp", "max_issues_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_issues_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_translation.cpp", "max_forks_repo_name": "RainerBlessing/TheRayTracerChallenge-C-", "max_forks_repo_head_hexsha": "22c990201507f46d5bb1604bc1f6ee88e59cef95", "max_forks_repo_licenses": ["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.8550185874, "max_line_length": 95, "alphanum_fraction": 0.6027318476, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6559595417080564}}
{"text": "#include <iostream>\n#include <dlib/statistics/dpca.h>\n\n#include <sampml/data.hpp>\n#include \"common.hpp\"\n#include \"transform.hpp\"\n\nusing sample_type = output_vector;\n\nvoid compute_pca() {\n    sampml::data::reader<sample_type> data_positive_train(positive_train_data);\n    sampml::data::reader<sample_type> data_negative_train(negative_train_data);\n\n    std::vector<sample_type> samples;\n    for (const auto& v : data_positive_train)\n        samples.push_back(v);\n    \n    for (const auto& v : data_negative_train)\n        samples.push_back(v);\n\n    dlib::vector_normalizer_pca<dlib::matrix<double, 0, 0>> pca;\n    pca.train(samples);\n\n    std::cout << \"Means: \" << pca.means() << '\\n';\n    std::cout << \"Stddev: \" << pca.std_devs() << '\\n';\n    std::cout << \"PCA Matrix: \" << pca.pca_matrix() << '\\n';\n}\n\nint main () {\n    compute_pca();\n    return 0;\n}", "meta": {"hexsha": "27e43db15dc12a8f79102a4845ea1255a49e9d13", "size": 852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/anti-aimbot/training/pca.cpp", "max_stars_repo_name": "YashasSamaga/sampml", "max_stars_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T18:30:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T21:53:36.000Z", "max_issues_repo_path": "examples/anti-aimbot/training/pca.cpp", "max_issues_repo_name": "YashasSamaga/sampml", "max_issues_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-08-21T17:52:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-17T03:28:11.000Z", "max_forks_repo_path": "examples/anti-aimbot/training/pca.cpp", "max_forks_repo_name": "YashasSamaga/sampml", "max_forks_repo_head_hexsha": "dc84110b53b120caeeb4c0234fcfd6ab16793c59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T14:53:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:53:33.000Z", "avg_line_length": 26.625, "max_line_length": 79, "alphanum_fraction": 0.6537558685, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6558903543740928}}
{"text": "#pragma once\n\n#include <algorithm> // std::minmax\n\n#include <boost/variant.hpp> // boost::variant\n\n#include \"convex_polygon.hpp\"\n#include \"point.hpp\"\n#include \"rectangle.hpp\"\n#include \"segment.hpp\"\n\n// TODO uncheck this\n\nnamespace geometry {\n\n// ------------------------------------------------------------------------\n// Segment\n// ------------------------------------------------------------------------\n\n// These could return a point or an interval\ntemplate <typename N, Topology Top>\nboost::variant<N, Interval<N, Top>> project_impl(const N& first, const N& second) {\n\n    const auto order = first.compare(second);\n\n    if (order < 0) {\n        return Interval<N, Top>{first, second};\n    }\n\n    if (order > 0) {\n        return Interval<N, Top>{second, first};\n    }\n\n    // Else they are equal, so just return the point\n    return first;\n}\n\ntemplate <typename N, Topology Top>\nboost::variant<N, Interval<N, Top>> project_x(const Segment<N, Top>& seg) {\n\n    return project_impl<N, Top>(seg.start().x, seg.end().x);\n}\n\ntemplate <typename N, Topology Top>\nboost::variant<N, Interval<N, Top>> project_y(const Segment<N, Top>& seg) {\n\n    return project_impl<N, Top>(seg.start().y, seg.end().y);\n}\n\ntemplate <typename N, Topology Top>\nboost::variant<N, Interval<N, Top>> project(const Segment<N, Top>& seg, const Point<N>& axis) {\n\n    const auto start_dot = Point<N>::dot(seg.start(), axis);\n    const auto end_dot = Point<N>::dot(seg.end(), axis);\n\n    return project_impl<N, Top>(start_dot, end_dot);\n}\n\n// ------------------------------------------------------------------------\n// Rectangle\n// ------------------------------------------------------------------------\n\n// Rectangles are always non-degenerate, so projection will always return intervals,\n// never points.\n\ntemplate <typename N, Topology Top>\nInterval<N, Top> project_x(const Rectangle<N, Top>& rect) {\n    return rect.interval_x;\n}\n\ntemplate <typename N, Topology Top>\nInterval<N, Top> project_y(const Rectangle<N, Top>& rect) {\n    return rect.interval_y;\n}\n\ntemplate <typename N, Topology Top>\nInterval<N, Top> project(const Rectangle<N, Top>& rect, const Point<N>& axis) {\n\n    const auto ll_dot = Point<N>::dot(rect.lower_left(), axis);\n\n    const auto ul_dot = Point<N>::dot(rect.upper_left(), axis);\n\n    const auto ur_dot = Point<N>::dot(rect.upper_right(), axis);\n\n    const auto lr_dot = Point<N>::dot(rect.lower_right(), axis);\n\n    const auto minmax = std::minmax({ll_dot, ul_dot, ur_dot, lr_dot});\n\n    return {minmax.first, minmax.second};\n}\n\n// ------------------------------------------------------------------------\n// Convex Polygon\n// ------------------------------------------------------------------------\n\n// Polygons are also always non-degenerate, so they always return intervals,\n// never points.\n\n// Find the min and max x values of all the points\ntemplate <typename N, Topology Top>\nInterval<N, Top> project_x(const ConvexPolygon<N, Top>& poly) {\n\n    const auto& first = poly.vertex(0);\n\n    // Note: the polygon is normalized, so the first point always has the smallest\n    // x coordinate.\n    const auto min = first.x;\n    auto max = first.x;\n\n    for (size_t i = 1; i < poly.size(); ++i) {\n\n        const auto& point = poly.vertex(i);\n\n        if (point.x > max) {\n            max = point.x;\n        }\n    }\n\n    return {min, max};\n}\n\n// Find the min and max y values of all the points\ntemplate <typename N, Topology Top>\nInterval<N, Top> project_y(const ConvexPolygon<N, Top>& poly) {\n\n    const auto& first = poly.vertex(0);\n\n    auto min = first.y;\n    auto max = first.y;\n\n    for (size_t i = 1; i < poly.size(); ++i) {\n\n        const auto& point = poly.vertex(i);\n\n        // We know min <= max, so we only need to do the following comparisons\n\n        if (point.y < min) {\n            min = point.y;\n        } else if (point.y > max) {\n            max = point.y;\n        }\n\n        // else min <= y <= max, so there are no changes to make\n    }\n\n    return {min, max};\n}\n\ntemplate <typename N, Topology Top>\nInterval<N, Top> project(const ConvexPolygon<N, Top>& poly, const Point<N>& axis) {\n\n    const auto& first = poly.vertex(0);\n\n    const auto first_dot = Point<N>::dot(first, axis);\n\n    auto min = first_dot;\n    auto max = first_dot;\n\n    for (size_t i = 1; i < poly.size(); ++i) {\n\n        const auto& point = poly.vertex(i);\n\n        const auto dot = Point<N>::dot(point, axis);\n\n        // We know min <= max, so we only need to do the following comparisons\n\n        if (dot < min) {\n            min = dot;\n        } else if (dot > max) {\n            max = dot;\n        }\n\n        // else min <= dot <= max, so there are no changes to make\n    }\n\n    return {min, max};\n}\n}\n", "meta": {"hexsha": "02abc4d6342c3cfe68ea4d145799465f35a5a8e8", "size": 4693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/backend/headers/geometry/project.hpp", "max_stars_repo_name": "wadymwadim/normandeau", "max_stars_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_stars_repo_licenses": ["Xnet", "X11"], "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/backend/headers/geometry/project.hpp", "max_issues_repo_name": "wadymwadim/normandeau", "max_issues_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_issues_repo_licenses": ["Xnet", "X11"], "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/backend/headers/geometry/project.hpp", "max_forks_repo_name": "wadymwadim/normandeau", "max_forks_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.217877095, "max_line_length": 95, "alphanum_fraction": 0.564457703, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6558903444553016}}
{"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//==================================================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-arithmetic Arithmetic functions\n\n    Those functions provides scalar and SIMD algorithms for classical arithmetic operators and\n    functions provided by the C and C++ standard library. Other functions are also provided, in particular,\n    provision for saturated operations through the use of a @ref decorator.\n\n     - **Possibly saturated operations**\n\n       The functors:\n       <center>\n         | name       | name            | name         | name             |\n         |:----------:|:---------------:|:------------:|:----------------:|\n         | @ref abs   | @ref minus      | @ref oneminus| @ref unary_minus |\n         | @ref dec   | @ref multiplies | @ref sqr     | @ref unary_plus  |\n         | @ref dist  | @ref plus       | @ref toint   | @ref touint      |\n         | @ref inc   |                 |              |                  |\n       </center>\n\n       can be decorated with the  @ref saturated \"saturated_\" @ref decorator. This decorator has no effect on floating\n       calls,  but on integer calls replaces the operation by its saturated equivalent.\n\n       Typically overflows will be replaced by the @ref Valmin/@ref Valmax proper value instead of providing\n       undefined behaviour for signed integral types or wrapping modulo Valmax+1 for unsigned ones.\n\n       Peculiarly saturated_(@ref abs) and saturated_(@ref dist) ensure that the result will never be stricly\n       negative (which is for instance the case of abs(Valmin<T>()) for T being any signed integral type).\n\n       toint is a rather common operation as it converts floating number to signed integers of the same bit size,\n       nevertheless it probably is its saturated version you have to use because it acts properly on large or not finite\n       values, this is why an alias for saturated_(toint) is provided as @ref ifix.\n\n     - **Rounding operations**\n       <center>\n         | name        | name            | name        | name             |\n         |:-----------:|:---------------:|:-----------:|:----------------:|\n         | @ref ceil   | @ref round      | @ref ifloor |  @ref inearbyint |\n         | @ref floor  | @ref nearbyint  | @ref ifix   |                  |\n         | @ref fix    | @ref iceil      | @ref iround |                  |\n        </center>\n\n          -The operations prefixed by 'i' return a value of the integral type associated to the entry type. (If T is\n         the entry type it is @ref as_integer_t<T>)\n\n          -The other ones return the same type as the entry.\n\n     - **Division operations**\n\n       @ref divides is the function associated to standard division. There is another one which provides more\n       flexibility, namely rounded divisions.\n\n       With two parameters @ref div and @ref divides are equivalent, but @ref div can admit a first option parameter\n       that modifies its behaviour.\n\n       The option parameter is described in the following table where a and b are of type T,  fT is a\n       supposed floating type associated to T (@ref as_floating_t<T> if it exists) and iT is the integer type associated to T\n       (@ref as_integer_t<T>). (fT and iT are here only to support pseudo code description)\n\n       <center>\n         | option             |          call            |      result similar to               |\n         |--------------------|--------------------------|--------------------------------------|\n         | @ref ceil          |   div(ceil, a, b)        |      T(ceil(fT(a)/fT(b)))            |\n         | @ref floor         |   div(floor, a, b)       |      T(floor(fT(a)/fT(b)))           |\n         | @ref fix           |   div(fix, a, b)         |      T(fix(fT(a)/fT(b)))             |\n         | @ref round         |   div(round, a, b)       |      T(round(fT(a)/fT(b)))           |\n         | @ref nearbyint     |   div(nearbyint, a, b)   |      T(nearbyint(fT(a)/fT(b)))       |\n         | @ref iceil         |   div(iceil, a, b)       |      iT(iceil(fT(a)/fT(b)))          |\n         | @ref ifloor        |   div(ifloor, a, b)      |      iT(ifloor(fT(a)/fT(b)))         |\n         | @ref ifix          |   div(ifix, a, b)        |      iT(ifix(fT(a)/fT(b)))           |\n         | @ref iround        |   div(iround, a, b)      |      iT(iround(fT(a)/fT(b)))         |\n         | @ref inearbyint    |   div(inearbyint, a, b)  |      iT(inearbyint(fT(a)/fT(b)))     |\n        </center>\n\n     - **Remainder operations**\n\n       @ref rem is the remander functor providing same kind of facilities as @ref div\n\n       With two parameters rem(a, b) is equivalent to  rem(fix, a, b), but rem can admit\n       a first optional parameter that modifies its behaviour and moreover can use the fast_ decorator if\n       limiting case values are not a problem.\n\n       The option parameter can be chosen between @ref ceil, @ref floor, @ref fix, @ref round, @ref nearbyint and if opt is the option,\n       the call:\n\n         rem(opt, a, b) is equivalent to a-b*div(opt, a, b)\n\n       For floating entries the underlisted corner cases are handled in the following way (unless the @ref fast \"fast_\"\n       decorator is used, the result in this case being undefined)\n        -  if x is \\f$\\pm\\infty\\f$ , @ref Nan is returned\n        -  if x is \\f$\\pm0\\f$ and y is not 0 x is returned\n        -  If y is \\f$\\pm0\\f$, @ref Nan is returned\n        -  If either argument is a nan, @ref a nan is returned\n\n     - **complex operations**\n\n       Boost.SIMD  does not provides complex number operations yet, but it will soon. So the following functors that\n       have a meaning as a restriction to real number of complex functions, can be seen as a prequel:\n\n      <center>\n        | name        | name            | name        | name             | name             |\n        |:-----------:|:---------------:|:-----------:|:----------------:|:----------------:|\n        | @ref arg    | @ref conj       | @ref imag   | @ref real        | @ref sqr_abs     |\n      </center>\n\n        For real entries conj and real are identity,  imag always 0, sqr_abs coincide with sqr\n        and arg results are always in the set \\f$\\{0, \\pi,  Nan\\}\\f$\n\n     - **Fused multiply-add operations**\n\n      <center>\n        | name            | name            | name         | name             |\n        |:---------------:|:---------------:|:------------:|:----------------:|\n        | @ref fma        | @ref fms        | @ref fnma    | @ref fnms        |\n        | @ref correct_fma| @ref two_add,   | @ref two_prod| @ref two_split   |\n      </center>\n\n      Correct fused multiply/add implies\n\n      - only one rounding\n      - no \"intermediate\" overflow\n\n      f?m? and fm? family provides this each time it is reasonable\n      in terms of performance (mainly if the system has the hard\n      wired capability).\n\n      If you need \"real\" fma capabilities in all circumstances in your own\n      code you can use @ref correct_fma (although it can be expansive) or\n      (generally still more expansive) std_(fma) by using the decorator.\n\n      @ref two_add, @ref two_prod and @ref two_split are used internally in @ref correct_fma and\n      can be useful in searching extra-accuracy in other circumstances as double-double\n      computations.\n\n      @ref correct_fma is never used internally by Boost.SIMD\n\n      - **Standard operations**\n\n       The stdlibc++ provides them but only in scalar mode:\n\n       <center>\n         | name       | name            | name         |\n         |:----------:|:---------------:|:------------:|\n         | @ref abs   | @ref hypot      | @ref remquo  |\n         | @ref ceil  | @ref max        | @ref round   |\n         | @ref floor | @ref min        | @ref signbit |\n         | @ref fma   | @ref rem (%)    | @ref sqrt    |\n       </center>\n\n       Boost.SIMD provides its own scalar and simd versions, but allows\n       the use of the @ref std \"std_\" @ref decorator to call the associated system\n       library function if the user needs it.\n\n      - **Other operations**\n\n       <center>\n         | name         | name            | name          |\n         |:------------:|:---------------:|:-------------:|\n         | @ref average | @ref sqrt       | @ref tenpower |\n         | @ref meanof  | @ref sqr        | @ref tofloat  |\n         | @ref minmod  | @ref sqrt1pm1   |               |\n       </center>\n  **/\n} }\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/arg.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/ceil.hpp>\n#include <boost/simd/function/conj.hpp>\n#include <boost/simd/function/correct_fma.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/dist.hpp>\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/extract.hpp>\n#include <boost/simd/function/fix.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/fms.hpp>\n#include <boost/simd/function/fnma.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/hypot.hpp>\n#include <boost/simd/function/iceil.hpp>\n#include <boost/simd/function/ifix.hpp>\n#include <boost/simd/function/ifloor.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/inearbyint.hpp>\n#include <boost/simd/function/iround.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/meanof.hpp>\n#include <boost/simd/function/min.hpp>\n#include <boost/simd/function/minmod.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/rem.hpp>\n#include <boost/simd/function/remquo.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/round.hpp>\n#include <boost/simd/function/rsqrt.hpp>\n#include <boost/simd/function/signbit.hpp>\n#include <boost/simd/function/sqr_abs.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt1pm1.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/function/tenpower.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/touint.hpp>\n#include <boost/simd/function/trunc.hpp>\n#include <boost/simd/function/two_add.hpp>\n#include <boost/simd/function/two_prod.hpp>\n#include <boost/simd/function/two_split.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <boost/simd/function/unary_plus.hpp>\n\n\n#endif\n", "meta": {"hexsha": "dbb3db1089aa07595eb5548512dc9021f018971c", "size": 10959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arithmetic.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": "third_party/boost/simd/arithmetic.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/arithmetic.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "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": 46.6340425532, "max_line_length": 135, "alphanum_fraction": 0.5736837303, "num_tokens": 2657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6558903345365102}}
{"text": "#pragma once\n#ifndef MANIFOLDMATH_H\n#define MANIFOLDMATH_H\n\n#include <vector>\n#include <memory>\n\n#include <Eigen/Core>\n\n#include <engine/Vectormath_Defines.hpp>\n\nnamespace Engine\n{\n\tnamespace Manifoldmath\n\t{\n        // Get the norm of a vectorfield\n        scalar norm(const vectorfield & vf);\n        // Normalize a vectorfield\n        void normalize(vectorfield & vf);\n\n        // TODO: the following functions should maybe be characterised as vectorspace instead of manifold\n        // Project v1 to be parallel to v2\n        //    This assumes normalized vectorfields\n        void project_parallel(vectorfield & vf1, const vectorfield & vf2);\n        // Project v1 to be orthogonal to v2\n        //    This assumes normalized vectorfields\n        void project_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n        // Invert v1's component parallel to v2\n        //    This assumes normalized vectorfields\n        void invert_parallel(vectorfield & vf1, const vectorfield & vf2);\n        // Invert v1's component orthogonal to v2\n        //    This assumes normalized vectorfields\n        void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n        // Project vf1's vectors into the tangent plane of vf2\n        // XXX: vf2 must have normalized vectors\n        void project_tangential(vectorfield & vf1, const vectorfield & vf2);\n\n\t\t// Greatcircle distance between two vectors\n\t\tscalar dist_greatcircle(const Vector3 & v1, const Vector3 & v2);\n\t\t// Geodesic distance between two vectorfields\n\t\tscalar dist_geodesic(const vectorfield & v1, const vectorfield & v2);\n\n\t\t// Calculate the \"tangent\" vectorfields pointing between a set of configurations\n\t\tvoid Tangents(std::vector<std::shared_ptr<vectorfield>> configurations, const std::vector<scalar> & energies, std::vector<vectorfield> & tangents);\n    }\n}\n\n#endif", "meta": {"hexsha": "63724ed824dc54a1629436ab34de79f762ee4616", "size": 1842, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Manifoldmath.hpp", "max_stars_repo_name": "Zeleznyj/spirit", "max_stars_repo_head_hexsha": "5e23bf3be5aa4bacf5aae24514b0b22cbd395619", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/include/engine/Manifoldmath.hpp", "max_issues_repo_name": "SpiritSuperUser/spirit", "max_issues_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_issues_repo_licenses": ["MIT"], "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/include/engine/Manifoldmath.hpp", "max_forks_repo_name": "SpiritSuperUser/spirit", "max_forks_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_forks_repo_licenses": ["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.375, "max_line_length": 149, "alphanum_fraction": 0.7030401737, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6557958785481021}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file random_process.cpp\n *\n * @brief Generate a random number from a random process\n *\n *//* ----------------------------------------------------------------------- */\n\n#include <dbconnector/dbconnector.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include \"random_process.hpp\"\n\nusing boost::poisson_distribution;\nusing boost::gamma_distribution;\nusing boost::variate_generator;\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace sample {\n\n/**\n * @brief Poisson distributed random variables given mean\n */\nAnyType\npoisson_random::run(AnyType &args) {\n    double mean = args[0].getAs<double>();\n    poisson_distribution<int> pdist(mean);\n    NativeRandomNumberGenerator generator;\n    variate_generator<NativeRandomNumberGenerator, poisson_distribution<int> >\n            rvt(generator, pdist);\n\n    return rvt();\n}\n\n/**\n * @brief Gamma distributed random variables given alpha\n */\nAnyType\ngamma_random::run(AnyType &args) {\n    double alpha = args[0].getAs<double>();\n    gamma_distribution<> gdist(alpha);\n    NativeRandomNumberGenerator generator;\n    variate_generator<NativeRandomNumberGenerator, gamma_distribution<> >\n            rvt(generator, gdist);\n\n    return rvt();\n}\n\n} // namespace sample\n\n} // namespace modules\n\n} // namespace madlib\n", "meta": {"hexsha": "26e7974cff49b9870d09dcdae81f14ee043f10db", "size": 1442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/sample/random_process.cpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/sample/random_process.cpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/sample/random_process.cpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 24.4406779661, "max_line_length": 80, "alphanum_fraction": 0.6539528433, "num_tokens": 286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6557921552375869}}
{"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// See: https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/\n// And: https://doi.org/10.1145/321607.321609\n\n#ifndef BOOST_MATH_INTERPOLATORS_MAKIMA_HPP\n#define BOOST_MATH_INTERPOLATORS_MAKIMA_HPP\n#include <memory>\n#include <cmath>\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\n\nnamespace boost {\nnamespace math {\nnamespace interpolators {\n\ntemplate<class RandomAccessContainer>\nclass makima {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n\n    makima(RandomAccessContainer && x, RandomAccessContainer && y,\n           Real left_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN(),\n           Real right_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN())\n    {\n        using std::isnan;\n        using std::abs;\n        if (x.size() < 4)\n        {\n            throw std::domain_error(\"Must be at least four data points.\");\n        }\n        RandomAccessContainer s(x.size(), std::numeric_limits<Real>::quiet_NaN());\n        Real m2 = (y[3]-y[2])/(x[3]-x[2]);\n        Real m1 = (y[2]-y[1])/(x[2]-x[1]);\n        Real m0 = (y[1]-y[0])/(x[1]-x[0]);\n        // Quadratic extrapolation: m_{-1} = 2m_0 - m_1:\n        Real mm1 = 2*m0 - m1;\n        // Quadratic extrapolation: m_{-2} = 2*m_{-1}-m_0:\n        Real mm2 = 2*mm1 - m0;\n        Real w1 = abs(m1-m0) + abs(m1+m0)/2;\n        Real w2 = abs(mm1-mm2) + abs(mm1+mm2)/2;\n        if (isnan(left_endpoint_derivative))\n        {\n            s[0] = (w1*mm1 + w2*m0)/(w1+w2);\n            if (isnan(s[0]))\n            {\n                s[0] = 0;\n            }\n        }\n        else\n        {\n            s[0] = left_endpoint_derivative;\n        }\n\n        w1 = abs(m2-m1) + abs(m2+m1)/2;\n        w2 = abs(m0-mm1) + abs(m0+mm1)/2;\n        s[1] = (w1*m0 + w2*m1)/(w1+w2);\n        if (isnan(s[1])) {\n            s[1] = 0;\n        }\n\n        for (decltype(s.size()) i = 2; i < s.size()-2; ++i) {\n            Real mim2 = (y[i-1]-y[i-2])/(x[i-1]-x[i-2]);\n            Real mim1 = (y[i  ]-y[i-1])/(x[i  ]-x[i-1]);\n            Real mi   = (y[i+1]-y[i  ])/(x[i+1]-x[i  ]);\n            Real mip1 = (y[i+2]-y[i+1])/(x[i+2]-x[i+1]);\n            w1 = abs(mip1-mi) + abs(mip1+mi)/2;\n            w2 = abs(mim1-mim2) + abs(mim1+mim2)/2;\n            s[i] = (w1*mim1 + w2*mi)/(w1+w2);\n            if (isnan(s[i])) {\n                s[i] = 0;\n            }\n        }\n        // Quadratic extrapolation at the other end:\n        \n        decltype(s.size()) n = s.size();\n        Real mnm4 = (y[n-3]-y[n-4])/(x[n-3]-x[n-4]);\n        Real mnm3 = (y[n-2]-y[n-3])/(x[n-2]-x[n-3]);\n        Real mnm2 = (y[n-1]-y[n-2])/(x[n-1]-x[n-2]);\n        Real mnm1 = 2*mnm2 - mnm3;\n        Real mn = 2*mnm1 - mnm2;\n        w1 = abs(mnm1 - mnm2) + abs(mnm1+mnm2)/2;\n        w2 = abs(mnm3 - mnm4) + abs(mnm3+mnm4)/2;\n\n        s[n-2] = (w1*mnm3 + w2*mnm2)/(w1 + w2);\n        if (isnan(s[n-2])) {\n            s[n-2] = 0;\n        }\n\n        w1 = abs(mn - mnm1) + abs(mn+mnm1)/2;\n        w2 = abs(mnm2 - mnm3) + abs(mnm2+mnm3)/2;\n\n\n        if (isnan(right_endpoint_derivative))\n        {\n            s[n-1] = (w1*mnm2 + w2*mnm1)/(w1+w2);\n            if (isnan(s[n-1])) {\n                s[n-1] = 0;\n            }\n        }\n        else\n        {\n            s[n-1] = right_endpoint_derivative;\n        }\n\n        impl_ = std::make_shared<detail::cubic_hermite_detail<RandomAccessContainer>>(std::move(x), std::move(y), std::move(s));\n    }\n\n    Real operator()(Real x) const {\n        return impl_->operator()(x);\n    }\n\n    Real prime(Real x) const {\n        return impl_->prime(x);\n    }\n\n    friend std::ostream& operator<<(std::ostream & os, const makima & m)\n    {\n        os << *m.impl_;\n        return os;\n    }\n\n    void push_back(Real x, Real y) {\n        using std::abs;\n        using std::isnan;\n        if (x <= impl_->x_.back()) {\n             throw std::domain_error(\"Calling push_back must preserve the monotonicity of the x's\");\n        }\n        impl_->x_.push_back(x);\n        impl_->y_.push_back(y);\n        impl_->dydx_.push_back(std::numeric_limits<Real>::quiet_NaN());\n        // dydx_[n-2] was computed by extrapolation. Now dydx_[n-2] -> dydx_[n-3], and it can be computed by the same formula.\n        decltype(impl_->size()) n = impl_->size();\n        auto i = n - 3;\n        Real mim2 = (impl_->y_[i-1]-impl_->y_[i-2])/(impl_->x_[i-1]-impl_->x_[i-2]);\n        Real mim1 = (impl_->y_[i  ]-impl_->y_[i-1])/(impl_->x_[i  ]-impl_->x_[i-1]);\n        Real mi   = (impl_->y_[i+1]-impl_->y_[i  ])/(impl_->x_[i+1]-impl_->x_[i  ]);\n        Real mip1 = (impl_->y_[i+2]-impl_->y_[i+1])/(impl_->x_[i+2]-impl_->x_[i+1]);\n        Real w1 = abs(mip1-mi) + abs(mip1+mi)/2;\n        Real w2 = abs(mim1-mim2) + abs(mim1+mim2)/2;\n        impl_->dydx_[i] = (w1*mim1 + w2*mi)/(w1+w2);\n        if (isnan(impl_->dydx_[i])) {\n            impl_->dydx_[i] = 0;\n        }\n\n        Real mnm4 = (impl_->y_[n-3]-impl_->y_[n-4])/(impl_->x_[n-3]-impl_->x_[n-4]);\n        Real mnm3 = (impl_->y_[n-2]-impl_->y_[n-3])/(impl_->x_[n-2]-impl_->x_[n-3]);\n        Real mnm2 = (impl_->y_[n-1]-impl_->y_[n-2])/(impl_->x_[n-1]-impl_->x_[n-2]);\n        Real mnm1 = 2*mnm2 - mnm3;\n        Real mn = 2*mnm1 - mnm2;\n        w1 = abs(mnm1 - mnm2) + abs(mnm1+mnm2)/2;\n        w2 = abs(mnm3 - mnm4) + abs(mnm3+mnm4)/2;\n\n        impl_->dydx_[n-2] = (w1*mnm3 + w2*mnm2)/(w1 + w2);\n        if (isnan(impl_->dydx_[n-2])) {\n            impl_->dydx_[n-2] = 0;\n        }\n\n        w1 = abs(mn - mnm1) + abs(mn+mnm1)/2;\n        w2 = abs(mnm2 - mnm3) + abs(mnm2+mnm3)/2;\n\n        impl_->dydx_[n-1] = (w1*mnm2 + w2*mnm1)/(w1+w2);\n        if (isnan(impl_->dydx_[n-1])) {\n            impl_->dydx_[n-1] = 0;\n        }\n    }\n\nprivate:\n    std::shared_ptr<detail::cubic_hermite_detail<RandomAccessContainer>> impl_;\n};\n\n}\n}\n}\n#endif\n", "meta": {"hexsha": "f69fe40733a11f70a26d9fb6041eeb34153e2c1e", "size": 6005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/interpolators/makima.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/interpolators/makima.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/interpolators/makima.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": 33.5474860335, "max_line_length": 128, "alphanum_fraction": 0.5097418818, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.655792154813719}}
{"text": "#include <deal.II/lac/solver_control.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n\n#include <deal.II/base/logstream.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_tools.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <filesystem>\n\n#include \"FEM1DWave.h\"\n\nnamespace fs = std::filesystem;\n\n// Class constructor for a vector field\nFEM1DWave::FEM1DWave(unsigned int order, unsigned int problem)\n\t:\n\tn(0),\n\tfe(FE_Q<1>(order), 1),\n\tdof_handler(triangulation),\n\tbasis(QGauss<1>(order + 1)),\n\tsrc(FEM1DGauSrc(Point<1>(0.5), 0.05, 0.05, 0.1 / T))\n{\n\tif (problem == 1 || problem == 2) {\n\t\tprob = problem;\n\t}\n\telse {\n\t\tstd::cout << \"Error: problem number should be 1 or 2.\\n\";\n\t\texit(0);\n\t}\n\n\t//Nodal Solution names - this is for writing the output file\n\tnodal_solution_names.push_back(\"p\");\n\tnodal_data_component_interpretation.push_back(DataComponentInterpretation::component_is_part_of_vector);\n}\n\n//Class destructor\nFEM1DWave::~FEM1DWave() {\n\tdof_handler.clear();\n}\n\n//Define the problem domain and generate the mesh\nvoid FEM1DWave::generate_mesh(unsigned int numberOfElements) {\n\n\t//Define the limits of your domain\n\tL = 1; //EDIT\n\tdouble x_min = 0.;\n\tdouble x_max = L;\n\n\tPoint<1, double> min(x_min), max(x_max);\n\tstd::vector<unsigned int> meshDimensions(1, numberOfElements);\n\tGridGenerator::subdivided_hyper_rectangle(triangulation, meshDimensions, min, max);\n}\n\n//Setup data structures (sparse matrix, vectors)\nvoid FEM1DWave::setup_system() {\n\t//Let deal.II organize degrees of freedom\n\tdof_handler.distribute_dofs(fe);\n\t\n\t//Enter the global node x-coordinates into the vector \"nodeLocation\"\n\tstd::vector< Point<1, double> > dof_coords(dof_handler.n_dofs());\n\tnodeLocation.resize(dof_handler.n_dofs());\n\tDoFTools::map_dofs_to_support_points<1, 1>(mapping, dof_handler, dof_coords);\n\tfor (unsigned int i = 0; i < dof_coords.size(); i++) {\n\t\tnodeLocation[i] = dof_coords[i][0];\n\t}\n\n\t//Specify boundary condtions (call the function)\n\tdefine_boundary_conds();\n\n\t//Define the size of the global matrices and vectors\n\tsparsity_pattern.reinit(dof_handler.n_dofs(), dof_handler.n_dofs(),\n\t\tdof_handler.max_couplings_between_dofs());\n\tDoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern);\n\tsparsity_pattern.compress();\n\tK.reinit(sparsity_pattern);\n\tM.reinit(sparsity_pattern);\n\tAu.reinit(sparsity_pattern);\n\tF.reinit(dof_handler.n_dofs());\n\tP1.reinit(dof_handler.n_dofs());\n\tP2.reinit(dof_handler.n_dofs());\n\tV.reinit(dof_handler.n_dofs());\n\tRHS.reinit(dof_handler.n_dofs());\n\tconstraints.close();\n\t\n\t//Just some notes...\n\tstd::cout << \"   Number of active elems:       \" << triangulation.n_active_cells() << std::endl;\n\tstd::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() << std::endl;\n\n\n\t//make sure solution folder exists\n\tif (!fs::is_directory(\"sln\") || !fs::exists(\"sln\")) { // Check if src folder exists\n\t\tfs::create_directory(\"sln\"); // create src folder\n\t}\n}\n\n//Form elmental vectors and matrices and assemble to the global vector (F) and matrix (K)\nvoid FEM1DWave::assemble_system() {\n\tMatrixCreator::create_mass_matrix(dof_handler, basis, M);\n\tMatrixCreator::create_laplace_matrix(dof_handler, basis,K);\n\tAu.copy_from(M);\n\tAu.add(T*T*theta*theta, K);\n\n\t//zero initial conditions\n\tP1 = 0;\n\tP2 = 0;\n\tV = 0;\n\tF = 0;\n}\n\nvoid FEM1DWave::solve_p()\n{\n\tSolverControl solver_control(1000, 1e-8*RHS.l2_norm());\n\tSolverCG<>    cg(solver_control);\n\n\tcg.solve(Au, P1, RHS, PreconditionIdentity());\n\tstd::cout << \"   u-equation: \" << solver_control.last_step() << \" CG iterations.\" << std::endl;\n}\n\nvoid FEM1DWave::solve_v()\n{\n\tSolverControl           solver_control(1000, 1e-8*RHS.l2_norm());\n\tSolverCG<>              cg(solver_control);\n\tcg.solve(M, P2, RHS, PreconditionIdentity());\n\tV += P2;\n\tstd::cout << \"   v-equation: \" << solver_control.last_step() << \" CG iterations.\" << std::endl;\n}\n\nvoid FEM1DWave::run() {\n\tVector<double> tmp(P1.size());\n\tdouble t;\n\n\tfor (; n <= N;)\n\t{\n\t\t++n;\n\t\tt = n * T;\n\n\t\tstd::cout << \"Time step \" << n << \" at t=\" << t\t<< std::endl;\n\t\t\n\t\tP2 = P1;\n\t\ttmp = P2;\n\t\ttmp *= -T * T*theta*(1 - theta);\n\t\tK.vmult(RHS, tmp);\n\t\ttmp = V;\n\t\ttmp.sadd(T, P2);\n\t\tM.vmult_add(RHS, tmp);\n\n\t\ttmp = F;\n\t\ttmp *= (1 - theta);\n\t\tsrc.set_time(t);\n\t\tVectorTools::create_right_hand_side(mapping, dof_handler, basis, src, F);\n\t\ttmp.add(theta, F);\n\t\tRHS.add(T * T * theta, tmp);\n\n\t\t//if dirichlet boundary required... update matrix here\n\t\tsolve_p();\n\n\t\tRHS = tmp;\n\t\tRHS *= T;\n\t\tP2 *= -T * (1 - theta);\n\t\tP2.add(-T * theta,P1);\n\t\tK.vmult_add(RHS, P2);\n\t\tsolve_v();\n\n\t\t//write output file in vtk format for visualization\n\t\toutput_results();\n\n\t\tstd::cout << \"   Total energy: \" << (M.matrix_norm_square(V) + K.matrix_norm_square(P1)) / 2 << std::endl;\n\t}\n}\n\n//Specify the Dirichlet boundary conditions\nvoid FEM1DWave::define_boundary_conds() {\n\t//const unsigned int totalNodes = dof_handler.n_dofs(); //Total number of nodes\n\n\t//Identify dirichlet boundary nodes and specify their values.\n\t//This function is called from within \"setup_system\"\n\n\t/*The vector \"nodeLocation\" gives the x-coordinate in the real domain of each node,\n\t  organized by the global node number.*/\n\n\t  /*This loops through all nodes in the system and checks to see if they are\n\t\tat one of the boundaries. If at a Dirichlet boundary, it stores the node number\n\t\tand the applied displacement value in the std::map \"boundary_values\". Deal.II\n\t\twill use this information later to apply Dirichlet boundary conditions.\n\t\tNeumann boundary conditions are applied when constructing Flocal in \"assembly\"*/\n\t\t/*\n\t\tfor(unsigned int globalNode=0; globalNode<totalNodes; globalNode++){\n\t\t  if(nodeLocation[globalNode] == 0){\n\t\t\t  boundary_values[globalNode] = g1;\n\t\t  }\n\t\t  if(nodeLocation[globalNode] == L){\n\t\t\t  if(prob == 1){\n\t\t\t  boundary_values[globalNode] = g2;\n\t\t\t  }\n\t\t  }\n\t\t}\n\t\t*/\n}\n\n//Output results\nvoid FEM1DWave::output_results() {\n\tconst std::string tag = \"./sln/wave_o\" + Utilities::int_to_string(basis.size() - 1) + \"_step_\" + Utilities::int_to_string(n) + \".vtk\";\n\t//Write results to VTK file\n\tstd::ofstream output1(tag);\n\tDataOut<1> data_out;\n\tdata_out.attach_dof_handler(dof_handler);\n\n\t//Add nodal DOF data\n\tdata_out.add_data_vector(P1, nodal_solution_names, DataOut<1>::type_dof_data, nodal_data_component_interpretation);\n\tdata_out.build_patches();\n\tdata_out.write_vtk(output1);\n\toutput1.close();\n}\n\ndouble FEM1DWave::u_exact(double x) {\n\tdouble result = 0;\n\t//diriclet bc\n\tif (prob == 2)\n\t{\n\t}\n\telse\n\t{\n\t}\n\treturn result;\n}\n\ndouble FEM1DWave::l2norm_of_error() {\n\t/*\n\tdouble l2norm = 0.;\n\n\t//Find the l2 norm of the error between the finite element sol'n and the exact sol'n\n\tconst unsigned int   \t\t\tdofs_per_elem = fe.dofs_per_cell; //This gives you dofs per element\n\tstd::vector<unsigned int> local_dof_indices(dofs_per_elem);\n\tVector<double> u_ex; u_ex.reinit(dof_handler.n_dofs());\n\tdouble u_h, x, h_e;\n\n\t//loop over elements  \n\tfor (unsigned int q = 0; q < dof_handler.n_dofs(); q++)\n\t\tu_ex[q] = u_exact(nodeLocation[q]);\n\tu_ex.print(std::cout);\n\tfor (auto i = nodeLocation.begin(); i != nodeLocation.end(); ++i)\n\t\tstd::cout << *i << ' ';\n\tstd::cout << std::endl;\n\n\ttypename DoFHandler<1>::active_cell_iterator elem = dof_handler.begin_active(),\n\t\tendc = dof_handler.end();\n\tfor (; elem != endc; ++elem) {\n\t\t//Retrieve the effective \"connectivity matrix\" for this element\n\t\telem->get_dof_indices(local_dof_indices);\n\n\t\t//Find the element length\n\t\th_e = nodeLocation[local_dof_indices[1]] - nodeLocation[local_dof_indices[0]];\n\n\t\tdouble sum = 0.;\n\t\tfor (unsigned int q = 0; q < quadRule; q++) {\n\t\t\tx = 0.;\n\t\t\tu_h = 0.;\n\t\t\t//Find the values of x and u_h (the finite element solution) at the quadrature points\n\t\t\tfor (unsigned int B = 0; B < dofs_per_elem; B++) {\n\t\t\t\tu_h += D[local_dof_indices[B]] * basis_function(B, quad_points[q]);\n\t\t\t\tx += nodeLocation[local_dof_indices[B]] * basis_function(B, quad_points[q]);\n\t\t\t}\n\t\t\t//EDIT - Find the l2-norm of the error through numerical integration.\n\t\t\t//This includes evaluating the exact solution at the quadrature points\n\t\t\tsum += pow(u_exact(x) - u_h, 2) * quad_weight[q];\n\t\t}\n\t\tsum *= h_e / 2;\n\t\tl2norm += sum;\n\t}\n\treturn sqrt(l2norm);\n\t*/\n\treturn 0.0;\n}\n", "meta": {"hexsha": "51589bdaf653cb2c53f850828fff05dd5cd4fdf6", "size": 8482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FEM1D-Wave/FEM1DWave.cpp", "max_stars_repo_name": "lampuiho/FEM1D-Test", "max_stars_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "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": "FEM1D-Wave/FEM1DWave.cpp", "max_issues_repo_name": "lampuiho/FEM1D-Test", "max_issues_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "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": "FEM1D-Wave/FEM1DWave.cpp", "max_forks_repo_name": "lampuiho/FEM1D-Test", "max_forks_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "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": 29.5540069686, "max_line_length": 135, "alphanum_fraction": 0.6953548691, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6557921456223391}}
{"text": "#pragma once\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// offset from center of laser rotation\n#define AXIS_OFFSET 0.0 //-0.015\n\nusing namespace Eigen;\n\n/**\n * get the 3D minimum distance between 2 lines\n * following http://geomalgorithms.com/a07-_distance.html#Distance-between-Lines\n * @param pos0 origin line0\n * @param dir1 direction line0\n * @param pos1 origin line1\n * @param dir2 direction line1\n * @param tri0 point on line0 closest to line1\n * @param tri1 point on line1 closest to line0\n * @return distance between the lines\n */\ndouble dist3D_Line_to_Line( Vector3d &pos0, Vector3d &dir1,\n                            Vector3d &pos1, Vector3d &dir2,\n                            Vector3d &tri0, Vector3d &tri1);\n\n/**\n    * This function triangulates the position of a sensor using the horizontal and vertical angles from two ligthouses\n    * @param angles0 vertical/horizontal angles form first lighthouse\n    * @param angles1 vertical/horizontal angles form second lighthouse\n    * @param RT_0 pose matrix of first lighthouse\n    * @param RT_1 pose matrix of second lighthouses\n    * @param triangulated_position the triangulated position\n    * @param ray0 ligthhouse ray\n    * @param ray1 ligthhouse ray\n    */\ndouble triangulateFromLighthouseAngles(Vector2d &angles0, Vector2d &angles1, Matrix4d &RT_0, Matrix4d &RT_1,\n                                     Vector3d &triangulated_position, Vector3d &ray0, Vector3d &ray1);\n\ndouble triangulateFromRays(Vector3d &ray0, Vector3d &ray1, Matrix4d &RT_0, Matrix4d &RT_1, Vector3d &triangulated_position);\n\nvoid rayFromLighthouseAngles(Vector2d &angles, Vector3d &ray);", "meta": {"hexsha": "bcd5ad35cf7ff0f093dccd421b08c78d8fa02c7b", "size": 1636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/darkroom/Triangulation.hpp", "max_stars_repo_name": "Roboy/DarkRoom_rviz", "max_stars_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T15:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T00:22:54.000Z", "max_issues_repo_path": "include/darkroom/Triangulation.hpp", "max_issues_repo_name": "Roboy/DarkRoom_rviz", "max_issues_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "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/darkroom/Triangulation.hpp", "max_forks_repo_name": "Roboy/DarkRoom_rviz", "max_forks_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "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.9523809524, "max_line_length": 124, "alphanum_fraction": 0.7194376528, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.65578879236537}}
{"text": "#include \"gl_core_3_2.h\"\n#include \"SDL.h\"\n#include \"SDL_keyboard.h\"\n#include \"SDL_opengl.h\"\n#include \"SDL_scancode.h\"\n#include \"SDL_timer.h\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"loadshaders_3_2.h\"\n\n#include <cmath>\n#include <iostream>\n#include <stdint.h>\n\nnamespace {\n\nconstexpr float PI = 2*3.1415926;\nconstexpr float TWO_PI = 2*PI;\n\nconstexpr GLubyte *bufferOffset(size_t bytes)\n{\n    return static_cast<GLubyte *>(0) + bytes;\n}\n\nconstexpr float degToRad(float angle)\n{\n    return angle * PI / 180;\n}\n\nconstexpr float radToDeg(float angle)\n{\n    return angle * 180 / PI;\n}\n\nconst int kWindowWidth = 800;\nconst int kWindowHeight = 600;\n\nenum VAO_IDs { Triangles, NumVAOs };\nenum Buffer_IDs { ArrayBuffer, ColorBuffer, IndexBuffer, NumBuffers };\n\nGLuint VAOs[NumVAOs];\nGLuint Buffers[NumBuffers];\n\nuint32_t oldTime = 0;\nuint32_t currentTime = 0;\n\nconst GLuint NumVertices = 8;\nconst GLuint NumIndices = 36;\n\nGLint vPositionIndex = -1;\nGLint vColorIndex = -1;\nGLint mModelViewIndex = -1;\nGLint mProjectionIndex = -1;\n\nEigen::Matrix4f cameraTransform;\n\nvoid initCube()\n{\n    glGenVertexArrays(NumVAOs, VAOs);\n    glBindVertexArray(VAOs[Triangles]);\n\n    Eigen::Vector3f vertices[NumVertices] = {\n        { -0.5,  0.5,  0.5 },\n        {  0.5,  0.5,  0.5 },\n        {  0.5,  0.5, -0.5 },\n        { -0.5,  0.5, -0.5 },\n\n        { -0.5, -0.5,  0.5 },\n        {  0.5, -0.5,  0.5 },\n        {  0.5, -0.5, -0.5 },\n        { -0.5, -0.5, -0.5 }\n    };\n\n    glGenBuffers(NumBuffers, Buffers);\n    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);\n\n    glVertexAttribPointer(vPositionIndex, 3, GL_FLOAT, GL_FALSE, 0, bufferOffset(0));\n    glEnableVertexAttribArray(vPositionIndex);\n\n    struct { float r, g, b; } colors[NumVertices] = {\n        { 0.0, 1.0, 0.0 },\n        { 0.0, 0.0, 1.0 },\n        { 0.0, 1.0, 0.0 },\n        { 0.0, 0.0, 1.0 },\n\n        { 0.0, 0.0, 1.0 },\n        { 1.0, 0.0, 0.0 },\n        { 0.0, 0.0, 1.0 },\n        { 1.0, 0.0, 0.0 }\n    };\n\n    glBindBuffer(GL_ARRAY_BUFFER, Buffers[ColorBuffer]);\n    glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);\n\n    glVertexAttribPointer(vColorIndex, 3, GL_FLOAT, GL_FALSE, 0, bufferOffset(0));\n    glEnableVertexAttribArray(vColorIndex);\n\n    GLubyte indices[NumIndices] = {\n        // top\n        0, 1, 3,\n        3, 1, 2,\n\n        // front\n        4, 5, 0,\n        0, 5, 1,\n\n        // bottom\n        5, 4, 6,\n        6, 4, 7,\n\n        // back\n        6, 7, 2,\n        2, 7, 3,\n\n        // left side\n        7, 4, 3,\n        3, 4, 0,\n\n        // right side\n        5, 6, 1,\n        1, 6, 2\n    };\n\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[IndexBuffer]);\n    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);\n}\n\nvoid init()\n{\n    glEnable(GL_CULL_FACE);\n    glEnable(GL_DEPTH_TEST);\n    glDepthFunc(GL_LESS);\n\n    ShaderInfo shaders[] = {\n        { GL_VERTEX_SHADER, \"../tests/persp/persp_3_2.vert\" },\n        { GL_FRAGMENT_SHADER, \"../tests/persp/persp_3_2.frag\" },\n        { GL_NONE, NULL }\n    };\n\n    GLuint program = loadShaders(shaders);\n    glUseProgram(program);\n\n    vPositionIndex = glGetAttribLocation(program, \"vPosition\");\n    vColorIndex = glGetAttribLocation(program, \"vColor\");\n    mModelViewIndex = glGetUniformLocation(program, \"mModelView\");\n    mProjectionIndex = glGetUniformLocation(program, \"mProjection\");\n\n    initCube();\n\n    cameraTransform << 1, 0, 0,  0,\n                       0, 1, 0,  0,\n                       0, 0, 1, -1,\n                       0, 0, 0,  1;\n}\n\nEigen::Matrix4f createPerspectiveProjection(float fov, float width, float height, float zNear, float zFar)\n{\n    float h = cos(0.5f * fov) / sin(0.5f * fov);\n    float w = h * height / width;\n    float p = -(zFar+zNear) / (zFar-zNear);\n    float q = -(2*zFar*zNear) / (zFar-zNear);\n\n    Eigen::Matrix4f result;\n    result << w, 0,  0, 0,\n              0, h,  0, 0,\n              0, 0,  p, q,\n              0, 0, -1, 0;\n\n    return result;\n}\n\nconst Eigen::Matrix4f kProjection = createPerspectiveProjection(degToRad(40), kWindowWidth, kWindowHeight, 0.1f, 100);\nfloat rotationAngle = 0;\n\nconst float cameraSpeed = 1.5f;\n\nvoid moveCamera(float deltaTime)\n{\n    const Uint8 *state = SDL_GetKeyboardState(NULL);\n\n    Eigen::Vector3f direction = Eigen::Vector3f::Zero();\n    if (state[SDL_SCANCODE_W]) {\n        direction += Eigen::Vector3f::UnitZ();\n    } else if (state[SDL_SCANCODE_S]) {\n        direction -= Eigen::Vector3f::UnitZ();\n    } else if (state[SDL_SCANCODE_A]) {\n        direction += Eigen::Vector3f::UnitX();\n    } else if (state[SDL_SCANCODE_D]) {\n        direction -= Eigen::Vector3f::UnitX();\n    }\n\n    if (direction.squaredNorm()) {\n        direction.normalize();\n        cameraTransform.block<3, 1>(0, 3) += direction * cameraSpeed * deltaTime;\n    }\n}\n\nvoid display()\n{\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    oldTime = currentTime;\n    currentTime = SDL_GetTicks();\n    float deltaTime = (currentTime - oldTime) / 1000.0f;\n\n    moveCamera(deltaTime);\n\n    Eigen::Matrix4f modelTransform;\n    modelTransform << 1, 0, 0,  cos(rotationAngle),\n                      0, 1, 0,  sin(rotationAngle),\n                      0, 0, 1, -2,\n                      0, 0, 0,  1;\n\n    rotationAngle = fmod(rotationAngle + (deltaTime * (PI / 15.0f)), TWO_PI);\n    Eigen::Matrix4f modelRotation = Eigen::Matrix4f::Identity();\n    modelRotation.topLeftCorner<3, 3>() = Eigen::Matrix3f(\n        Eigen::AngleAxisf(rotationAngle, Eigen::Vector3f::UnitX()) *\n        Eigen::AngleAxisf(rotationAngle, Eigen::Vector3f::UnitY()));\n\n    Eigen::Matrix4f modelView = cameraTransform * modelTransform * modelRotation;\n    glUniformMatrix4fv(mModelViewIndex, 1, GL_FALSE, modelView.data());\n    glUniformMatrix4fv(mProjectionIndex, 1, GL_FALSE, kProjection.data());\n\n    glBindVertexArray(VAOs[Triangles]);\n    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[IndexBuffer]);\n    glDrawElements(GL_TRIANGLES, NumIndices, GL_UNSIGNED_BYTE, bufferOffset(0));\n}\n\n} // namespace\n\nint main(int argc, char *argv[])\n{\n    if (SDL_Init(SDL_INIT_VIDEO) != 0) {\n        std::cerr << SDL_GetError() << std::endl;\n        return -1;\n    }\n\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\n    // Create an OpenGL capable window\n    SDL_Window *window = SDL_CreateWindow(\n        \"Prespective Projection Test\",\n        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n        800, 600,\n        SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE\n    );\n    if (!window) {\n        std::cerr << SDL_GetError() << std::endl;\n        SDL_Quit();\n        return -1;\n    }\n\n    // Create an OpenGL context associated with the window.\n    SDL_GLContext glcontext = SDL_GL_CreateContext(window);\n    if (!glcontext) {\n        std::cerr << SDL_GetError() << std::endl;\n        SDL_Quit();\n        return -1;\n    }\n\n    // Load extensions\n    if (ogl_LoadFunctions() != ogl_LOAD_SUCCEEDED) {\n        SDL_DestroyWindow(window);\n        SDL_Quit();\n        return -1;\n    }\n\n    // Initialize displayables\n    init();\n\n    SDL_Event event;\n    bool keepRunning = true;\n    while (keepRunning) {\n        while (SDL_PollEvent(&event)) {\n            if (event.type == SDL_QUIT) {\n                keepRunning = false;\n            }\n        }\n\n        // Render scene\n        display();\n\n        // Swap buffers\n        SDL_GL_SwapWindow(window);\n    }\n\n    // Once finished with OpenGL functions, the SDL_GLContext can be deleted.\n    SDL_GL_DeleteContext(glcontext);\n\n    // Done! Close the window, clean-up and exit the program.\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n\n    return 0;\n}\n", "meta": {"hexsha": "27cf80ed3752cce6ffc2fda90c4db1ac9591ac0b", "size": 7819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "computer_graphics/junkyard/tests/persp/persp_3_2.cpp", "max_stars_repo_name": "asgeir/old-school-projects", "max_stars_repo_head_hexsha": "96a502589c627e4556f9ee14fc1dc21ed53ce28a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "computer_graphics/junkyard/tests/persp/persp_3_2.cpp", "max_issues_repo_name": "asgeir/old-school-projects", "max_issues_repo_head_hexsha": "96a502589c627e4556f9ee14fc1dc21ed53ce28a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "computer_graphics/junkyard/tests/persp/persp_3_2.cpp", "max_forks_repo_name": "asgeir/old-school-projects", "max_forks_repo_head_hexsha": "96a502589c627e4556f9ee14fc1dc21ed53ce28a", "max_forks_repo_licenses": ["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.0633333333, "max_line_length": 118, "alphanum_fraction": 0.6110755851, "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6557542850855095}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"ConvolutionTools.hpp\"\n#include \"Toeplitz.hpp\"\n#include \"../public/WindowFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Eigen>\n#include <algorithm>\n#include <cmath>\n#include <functional>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass ARModel\n{\n\n  using MatrixXd = Eigen::MatrixXd;\n  using ArrayXd = Eigen::ArrayXd;\n  using VectorXd = Eigen::VectorXd;\n\npublic:\n  ARModel(index order) : mParameters(VectorXd::Zero(order)) {}\n\n  const double* getParameters() const { return mParameters.data(); }\n  double        variance() const { return mVariance; }\n  index         order() const { return mParameters.size(); }\n\n  void estimate(const double* input, index size, index nIterations = 3,\n                double robustFactor = 3.0)\n  {\n    if (nIterations > 0)\n      robustEstimate(input, size, nIterations, robustFactor);\n    else\n      directEstimate(input, size, true);\n  }\n\n  double fowardPrediction(const double* input)\n  {\n    return modelPredict<std::negate<index>>(input);\n  }\n\n  double backwardPrediction(const double* input)\n  {\n    struct Identity\n    {\n      index operator()(index a) { return a; }\n    };\n    return modelPredict<Identity>(input);\n  }\n\n  double forwardError(const double* input)\n  {\n    return modelError<&ARModel::fowardPrediction>(input);\n  }\n\n  double backwardError(const double* input)\n  {\n    return modelError<&ARModel::backwardPrediction>(input);\n  }\n\n  void forwardErrorArray(double* errors, const double* input, index size)\n  {\n    modelErrorArray<&ARModel::forwardError>(errors, input, size);\n  }\n\n  void backwardErrorArray(double* errors, const double* input, index size)\n  {\n    modelErrorArray<&ARModel::backwardError>(errors, input, size);\n  }\n\n  void setMinVariance(double variance) { mMinVariance = variance; }\n\nprivate:\n  template <typename Op>\n  double modelPredict(const double* input)\n  {\n    double estimate = 0.0;\n\n    for (index i = 0; i < mParameters.size(); i++)\n      estimate += mParameters(i) * input[Op()(i + 1)];\n\n    return estimate;\n  }\n\n  template <double (ARModel::*Method)(const double*)>\n  double modelError(const double* input)\n  {\n    return input[0] - (this->*Method)(input);\n  }\n\n  template <double (ARModel::*Method)(const double*)>\n  void modelErrorArray(double* errors, const double* input, index size)\n  {\n    for (index i = 0; i < size; i++) errors[i] = (this->*Method)(input + i);\n  }\n\n  void directEstimate(const double* input, index size, bool updateVariance)\n  {\n    // copy input to a 32 byte aligned block (otherwise risk segfaults on Linux)\n    VectorXd frame = Eigen::Map<const VectorXd>(input, size);\n\n    if (mUseWindow)\n    {\n      if (mWindow.size() != size)\n      {\n        mWindow = ArrayXd::Zero(size);\n        WindowFuncs::map()[WindowFuncs::WindowTypes::kHann](size, mWindow);\n      }\n\n      frame.array() *= mWindow;\n    }\n\n\n    VectorXd autocorrelation(size);\n    algorithm::autocorrelateReal(autocorrelation.data(), frame.data(),\n                                 asUnsigned(size));\n\n    // Resize to the desired order (only keep coefficients for up to the order\n    // we need)\n    double pN = mParameters.size() < size ? autocorrelation(mParameters.size())\n                                          : autocorrelation(0);\n    autocorrelation.conservativeResize(mParameters.size());\n\n    // Form a toeplitz matrix\n    MatrixXd mat = toeplitz(autocorrelation);\n\n    // Yule Walker\n    autocorrelation(0) = pN;\n    std::rotate(autocorrelation.data(), autocorrelation.data() + 1,\n                autocorrelation.data() + mParameters.size());\n    mParameters = mat.llt().solve(autocorrelation);\n\n    if (updateVariance)\n    {\n      // Calculate variance\n      double variance = mat(0, 0);\n\n      for (index i = 0; i < mParameters.size() - 1; i++)\n        variance -= mParameters(i) * mat(0, i + 1);\n\n      setVariance((variance - (mParameters(mParameters.size() - 1) * pN)) /\n                  size);\n    }\n  }\n\n  void robustEstimate(const double* input, index size, index nIterations,\n                      double robustFactor)\n  {\n    std::vector<double> estimates(asUnsigned(size + mParameters.size()));\n\n    // Calculate an initial estimate of parameters\n    directEstimate(input, size, true);\n\n    // Initialise Estimates\n    for (index i = mParameters.size(); i < mParameters.size() + size; i++)\n      estimates[asUnsigned(i)] = input[i - mParameters.size()];\n\n    // Variance\n    robustVariance(estimates.data() + mParameters.size(), input, size,\n                   robustFactor);\n\n    // Iterate\n    for (index iterations = nIterations; iterations--;)\n      robustIteration(estimates.data() + mParameters.size(), input, size,\n                      robustFactor);\n  }\n\n  double robustResidual(double input, double prediction, double cs)\n  {\n    return cs * psiFunction((input - prediction) / cs);\n  }\n\n  void robustVariance(double* estimates, const double* input, index size,\n                      double robustFactor)\n  {\n    double residualSqSum = 0.0;\n\n    // Iterate to find new filtered input\n    for (index i = 0; i < size; i++)\n    {\n      const double residual =\n          robustResidual(input[i], fowardPrediction(estimates + i),\n                         robustFactor * sqrt(mVariance));\n      residualSqSum += residual * residual;\n    }\n\n    setVariance(residualSqSum / size);\n  }\n\n  void robustIteration(double* estimates, const double* input, index size,\n                       double robustFactor)\n  {\n    // Iterate to find new filtered input\n    for (index i = 0; i < size; i++)\n    {\n      const double prediction = fowardPrediction(estimates);\n      estimates[0] =\n          prediction +\n          robustResidual(input[i], prediction, robustFactor * sqrt(mVariance));\n    }\n\n    // New parameters\n    directEstimate(estimates, size, false);\n    robustVariance(estimates, input, size, robustFactor);\n  }\n\n  void setVariance(double variance)\n  {\n    if (variance > 0) variance = std::max(mMinVariance, variance);\n    mVariance = variance;\n  }\n\n  // Huber PSI function\n  double psiFunction(double x)\n  {\n    return fabs(x) > 1 ? std::copysign(1.0, x) : x;\n  }\n\n  VectorXd mParameters;\n  double   mVariance{0.0};\n  ArrayXd  mWindow;\n  bool     mUseWindow{true};\n  double   mMinVariance{0.0};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "76296b350fd7e56640ea6d7a092396f2e15ce630", "size": 6694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/ARModel.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/ARModel.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/ARModel.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": 28.0083682008, "max_line_length": 80, "alphanum_fraction": 0.646997311, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6557542848721257}}
{"text": "#include \"drake/math/discrete_algebraic_riccati_equation.h\"\n\n#include <Eigen/Eigenvalues>\n#include <gtest/gtest.h>\n\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n// #include \"drake/math/autodiff.h\"\n\nusing Eigen::MatrixXd;\n\nnamespace drake {\nnamespace math {\nnamespace {\nvoid SolveDAREandVerify(const Eigen::Ref<const MatrixXd>& A,\n                        const Eigen::Ref<const MatrixXd>& B,\n                        const Eigen::Ref<const MatrixXd>& Q,\n                        const Eigen::Ref<const MatrixXd>& R) {\n  MatrixXd X = DiscreteAlgebraicRiccatiEquation(A, B, Q, R);\n  // Check that X is positive semi-definite.\n  EXPECT_TRUE(\n      CompareMatrices(X, X.transpose(), 1E-10, MatrixCompareType::absolute));\n  int n = X.rows();\n  Eigen::SelfAdjointEigenSolver<MatrixXd> es(X);\n  for (int i = 0; i < n; i++) {\n    EXPECT_GE(es.eigenvalues()[i], 0);\n  }\n  // Check that X is the solution to the discrete time ARE.\n  // clang-format off\n  MatrixXd Y =\n      A.transpose() * X * A\n      - X\n      - (A.transpose() * X * B * (B.transpose() * X * B + R).inverse()\n        * B.transpose() * X * A)\n      + Q;\n  // clang-format on\n  EXPECT_TRUE(CompareMatrices(Y, MatrixXd::Zero(n, n), 1E-10,\n                              MatrixCompareType::absolute));\n}\n\nvoid SolveDAREandVerify(const Eigen::Ref<const MatrixXd>& A,\n                        const Eigen::Ref<const MatrixXd>& B,\n                        const Eigen::Ref<const MatrixXd>& Q,\n                        const Eigen::Ref<const MatrixXd>& R,\n                        const Eigen::Ref<const MatrixXd>& N) {\n  MatrixXd X = DiscreteAlgebraicRiccatiEquation(A, B, Q, R, N);\n  // Check that X is positive semi-definite.\n  EXPECT_TRUE(\n      CompareMatrices(X, X.transpose(), 1E-10, MatrixCompareType::absolute));\n  int n = X.rows();\n  Eigen::SelfAdjointEigenSolver<MatrixXd> es(X);\n  for (int i = 0; i < n; i++) {\n    EXPECT_GE(es.eigenvalues()[i], 0);\n  }\n  // Check that X is the solution to the discrete time ARE.\n  // clang-format off\n  MatrixXd Y =\n      A.transpose() * X * A\n      - X\n      - ((A.transpose() * X * B + N) * (B.transpose() * X * B + R).inverse()\n        * (B.transpose() * X * A + N.transpose()))\n      + Q;\n  // clang-format on\n  EXPECT_TRUE(CompareMatrices(Y, MatrixXd::Zero(n, n), 1E-10,\n                              MatrixCompareType::absolute));\n}\n\nGTEST_TEST(DARE, SolveDAREandVerify) {\n  // Test 1: non-invertible A\n  // Example 2 of \"On the Numerical Solution of the Discrete-Time Algebraic\n  // Riccati Equation\"\n  int n1 = 4, m1 = 1;\n  MatrixXd A1(n1, n1), B1(n1, m1), Q1(n1, n1), R1(m1, m1);\n  A1 << 0.5, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0;\n  B1 << 0, 0, 0, 1;\n  Q1 << 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n  R1 << 0.25;\n  SolveDAREandVerify(A1, B1, Q1, R1);\n\n  MatrixXd Aref1(n1, n1);\n  Aref1 << 0.25, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0;\n  SolveDAREandVerify(A1, B1, (A1 - Aref1).transpose() * Q1 * (A1 - Aref1),\n      B1.transpose() * Q1 * B1 + R1, (A1 - Aref1).transpose() * Q1 * B1);\n\n  // Test 2: invertible A\n  int n2 = 2, m2 = 1;\n  MatrixXd A2(n2, n2), B2(n2, m2), Q2(n2, n2), R2(m2, m2);\n  A2 << 1, 1, 0, 1;\n  B2 << 0, 1;\n  Q2 << 1, 0, 0, 0;\n  R2 << 0.3;\n  SolveDAREandVerify(A2, B2, Q2, R2);\n\n  MatrixXd Aref2(n2, n2);\n  Aref2 << 0.5, 1, 0, 1;\n  SolveDAREandVerify(A2, B2, (A2 - Aref2).transpose() * Q2 * (A2 - Aref2),\n      B2.transpose() * Q2 * B2 + R2, (A2 - Aref2).transpose() * Q2 * B2);\n\n  // Test 3: the first generalized eigenvalue of (S,T) is stable\n  int n3 = 2, m3 = 1;\n  MatrixXd A3(n3, n3), B3(n3, m3), Q3(n3, n3), R3(m3, m3);\n  A3 << 0, 1, 0, 0;\n  B3 << 0, 1;\n  Q3 << 1, 0, 0, 1;\n  R3 << 1;\n  SolveDAREandVerify(A3, B3, Q3, R3);\n\n  MatrixXd Aref3(n3, n3);\n  Aref3 << 0, 0.5, 0, 0;\n  SolveDAREandVerify(A3, B3, (A3 - Aref3).transpose() * Q3 * (A3 - Aref3),\n      B3.transpose() * Q3 * B3 + R3, (A3 - Aref3).transpose() * Q3 * B3);\n\n  // Test 4: A = B = Q = R = I_2 (2-by-2 identity matrix)\n  const Eigen::MatrixXd A4{Eigen::Matrix2d::Identity()};\n  const Eigen::MatrixXd B4{Eigen::Matrix2d::Identity()};\n  const Eigen::MatrixXd Q4{Eigen::Matrix2d::Identity()};\n  const Eigen::MatrixXd R4{Eigen::Matrix2d::Identity()};\n  SolveDAREandVerify(A4, B4, Q4, R4);\n\n  const Eigen::MatrixXd N4{Eigen::Matrix2d::Identity()};\n  SolveDAREandVerify(A4, B4, Q4, R4, N4);\n}\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "8631d6f3c0ad5cbf52bc0664f3b85023fd7aa3e0", "size": 4370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wpimath/src/test/native/cpp/drake/discrete_algebraic_riccati_equation_test.cpp", "max_stars_repo_name": "shueja-personal/allwpilib", "max_stars_repo_head_hexsha": "4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 707.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T16:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:03:15.000Z", "max_issues_repo_path": "wpimath/src/test/native/cpp/drake/discrete_algebraic_riccati_equation_test.cpp", "max_issues_repo_name": "shueja-personal/allwpilib", "max_issues_repo_head_hexsha": "4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2308.0, "max_issues_repo_issues_event_min_datetime": "2016-05-12T00:17:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:08:10.000Z", "max_forks_repo_path": "wpimath/src/test/native/cpp/drake/discrete_algebraic_riccati_equation_test.cpp", "max_forks_repo_name": "shueja-personal/allwpilib", "max_forks_repo_head_hexsha": "4b2f6be29e21986703d9c3ddcd2fe07121b2ff6b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 539.0, "max_forks_repo_forks_event_min_datetime": "2016-05-11T20:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T20:20:25.000Z", "avg_line_length": 34.96, "max_line_length": 77, "alphanum_fraction": 0.5796338673, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.655754283222095}}
{"text": "// test_dorpi.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestDorpi)\n\n\n    double test_dorpi_function_1(double x, double y) {\n        return 3.0*y/x + x*x*x + x;\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_dorpi)\n    {\n        double *y = new double[2];\n        double x0, x, h, expected_answer;\n        short int expected_result, result;\n\n        // Initial points\n        x0 = 1; y[0] = 3;\n\n        x = 2.0;\n\n        expected_result = 0;\n        expected_answer = 36;\n        result = Numerary::ordinary_differential_equations(test_dorpi_function_1, y, x0, h, x, \"dorpi_4_5\");\n        BOOST_CHECK_EQUAL(result, expected_result);\n\n        BOOST_CHECK(fabs(expected_answer - y[1]) < 1.e-4);\n\n        delete[] y;\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "0b2a37b073a325a2450a2f0c1741be81887cc393", "size": 843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_dorpi.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_dorpi.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_dorpi.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 20.0714285714, "max_line_length": 108, "alphanum_fraction": 0.6073546856, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6557542815720637}}
{"text": "/**\n * Copyright 2020, Massachusetts Institute of Technology,\n * Cambridge, MA 02139\n * All Rights Reserved\n * Authors: Jingnan Shi, et al. (see THANKS for the full author list)\n * See LICENSE for the license information\n */\n\n#include \"gtest/gtest.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <chrono>\n#include <cmath>\n#include <random>\n\n#include <Eigen/Eigenvalues>\n\n#include \"teaser/registration.h\"\n#include \"test_utils.h\"\n\nTEST(RotationSolverTest, FGRRotation) {\n  double ALLOWED_ROTATION_ERROR = 1e-5;\n  // Problem 1: Identity\n  {\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src_points(3, 10);\n    for (size_t i = 0; i < src_points.cols(); ++i) {\n      src_points.col(i) = Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, 1);\n    }\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst_points = src_points;\n\n    // Set up FGR\n    teaser::FastGlobalRegistrationSolver::Params params{1000, 0.0337, 1.4,  1e-3};\n    teaser::FastGlobalRegistrationSolver fgr_solver(params);\n\n    Eigen::Matrix3d result;\n    fgr_solver.solveForRotation(src_points, dst_points, &result, nullptr);\n    Eigen::Matrix3d ref_result;\n    ref_result.setIdentity();\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_result << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << result << std::endl;\n\n    EXPECT_TRUE((result - ref_result).norm() < ALLOWED_ROTATION_ERROR);\n  }\n  // Problem 2: Random rotation around x / y / z axis\n  {\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src_points(3, 10);\n    for (size_t i = 0; i < src_points.cols(); ++i) {\n      src_points.col(i) = Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, 1);\n    }\n    Eigen::Matrix3d ref_R;\n    std::uniform_real_distribution<double> unif(0, 2 * M_PI);\n    std::default_random_engine re;\n\n    // Prepare solver\n    teaser::FastGlobalRegistrationSolver::Params params{1000, 0.0337, 1.4, 1e-3};\n    teaser::FastGlobalRegistrationSolver fgr_solver(params);\n    Eigen::Matrix3d R;\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst_points;\n\n    // Rotation around x\n    double theta = unif(re);\n    // clang-format off\n    ref_R << 1, 0,               0,\n             0, std::cos(theta), -std::sin(theta),\n             0, std::sin(theta), std::cos(theta);\n    // clang-format on\n    dst_points = ref_R * src_points;\n    fgr_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n\n    // Rotation around y\n    // clang-format off\n    ref_R << std::cos(theta), 0, std::sin(theta),\n             0,               1, 0,\n             -std::sin(theta),0, std::cos(theta);\n    // clang-format on\n    dst_points = ref_R * src_points;\n    fgr_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n\n    // Rotation around z\n    ref_R << std::cos(theta), -std::sin(theta), 0, std::sin(theta), std::cos(theta), 0, 0, 0, 1;\n    // clang-format on\n    dst_points = ref_R * src_points;\n    fgr_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n  }\n  // Problem 3: A more complex case\n  {\n    // Read in data\n    std::ifstream source_file(\"./data/registration_test/rotation_only_src.csv\");\n    Eigen::Matrix<double, Eigen::Dynamic, 3> source_points =\n        teaser::test::readFileToEigenMatrix<double, Eigen::Dynamic, 3>(source_file);\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src = source_points.transpose();\n\n    // Perform Arbitrary rotation\n    Eigen::Matrix3d expected_R;\n    // clang-format off\n    expected_R << 0.997379773225804, -0.019905935977315, -0.069551000516966,\n                  0.013777311189888, 0.996068297974922, -0.087510750572249,\n                  0.071019530105605, 0.086323226782879, 0.993732623426126;\n    // clang-format on\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst = expected_R * src;\n\n    // Set up FGR\n    // Since we have no noise, 1 iteration should give us the optimal solution.\n    teaser::FastGlobalRegistrationSolver::Params params{1, 0.025, 1.4, 1e-3};\n    teaser::FastGlobalRegistrationSolver fgr_solver(params);\n\n    Eigen::Matrix3d result;\n    fgr_solver.solveForRotation(src, dst, &result, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << expected_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << result << std::endl;\n\n    EXPECT_TRUE(teaser::test::getAngularError(expected_R, result) < ALLOWED_ROTATION_ERROR);\n  }\n}\n\nTEST(RotationSolverTest, GNCTLS) {\n  double ALLOWED_ROTATION_ERROR = 1e-5;\n  // Problem 1: Identity\n  {\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src_points(3, 10);\n    for (size_t i = 0; i < src_points.cols(); ++i) {\n      src_points.col(i) = Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, 1);\n    }\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst_points = src_points;\n\n    // Set up GNC-TLS solver\n    teaser::GNCTLSRotationSolver::Params params{100, 1e-12, 1.4, 1e-3};\n    teaser::GNCTLSRotationSolver tls_solver(params);\n\n    Eigen::Matrix3d result;\n    tls_solver.solveForRotation(src_points, dst_points, &result, nullptr);\n    Eigen::Matrix3d ref_result;\n    ref_result.setIdentity();\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_result << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << result << std::endl;\n\n    EXPECT_TRUE((result - ref_result).norm() < ALLOWED_ROTATION_ERROR);\n  }\n  // Problem 2: Random rotation around x / y / z axis\n  {\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src_points(3, 10);\n    for (size_t i = 0; i < src_points.cols(); ++i) {\n      src_points.col(i) = Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, 1);\n    }\n    Eigen::Matrix3d ref_R;\n    std::uniform_real_distribution<double> unif(0, 2 * M_PI);\n    std::default_random_engine re;\n\n    // Set up GNC-TLS solver\n    teaser::GNCTLSRotationSolver::Params params{100, 1e-12, 1.4, 1e-3};\n    teaser::GNCTLSRotationSolver tls_solver(params);\n    Eigen::Matrix3d R;\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst_points;\n\n    // Rotation around x\n    double theta = unif(re);\n    // clang-format off\n    ref_R << 1, 0,               0,\n        0, std::cos(theta), -std::sin(theta),\n        0, std::sin(theta), std::cos(theta);\n    // clang-format on\n    dst_points = ref_R * src_points;\n    tls_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n\n    // Rotation around y\n    // clang-format off\n    ref_R << std::cos(theta), 0, std::sin(theta),\n        0,                    1, 0,\n        -std::sin(theta),     0, std::cos(theta);\n    // clang-format on\n    dst_points = ref_R * src_points;\n    tls_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n\n    // Rotation around z\n    // clang-format off\n    ref_R << std::cos(theta), -std::sin(theta), 0,\n             std::sin(theta), std::cos(theta),  0,\n             0,               0,                1;\n    // clang-format on\n    dst_points = ref_R * src_points;\n    tls_solver.solveForRotation(src_points, dst_points, &R, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << ref_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << R << std::endl;\n    EXPECT_TRUE(teaser::test::getAngularError(ref_R, R) < ALLOWED_ROTATION_ERROR);\n  }\n  // Problem 3: A more complex case\n  {\n    // Read in data\n    std::ifstream source_file(\"./data/registration_test/rotation_only_src.csv\");\n    Eigen::Matrix<double, Eigen::Dynamic, 3> source_points =\n        teaser::test::readFileToEigenMatrix<double, Eigen::Dynamic, 3>(source_file);\n    Eigen::Matrix<double, 3, Eigen::Dynamic> src = source_points.transpose();\n\n    // Perform Arbitrary rotation\n    Eigen::Matrix3d expected_R;\n    // clang-format off\n    expected_R << 0.997379773225804, -0.019905935977315, -0.069551000516966,\n                  0.013777311189888, 0.996068297974922, -0.087510750572249,\n                  0.071019530105605, 0.086323226782879, 0.993732623426126;\n    // clang-format on\n    Eigen::Matrix<double, 3, Eigen::Dynamic> dst = expected_R * src;\n\n    // Set up TLS\n    teaser::GNCTLSRotationSolver::Params params{100, 1e-12, 1.4, 1e-3};\n    teaser::GNCTLSRotationSolver tls_solver(params);\n\n    Eigen::Matrix3d result;\n    tls_solver.solveForRotation(src, dst, &result, nullptr);\n    std::cout << \"Expected R: \" << std::endl;\n    std::cout << expected_R << std::endl;\n    std::cout << \"R: \" << std::endl;\n    std::cout << result << std::endl;\n\n    EXPECT_TRUE(teaser::test::getAngularError(expected_R, result) < ALLOWED_ROTATION_ERROR);\n  }\n}\n", "meta": {"hexsha": "fd9f3b1cb1e79a9b835fc84fffbabb4eb74ca9c6", "size": 9565, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/teaser/rotation-solver-test.cc", "max_stars_repo_name": "plusk01/TEASER-plusplus", "max_stars_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 962.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T19:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:28:49.000Z", "max_issues_repo_path": "test/teaser/rotation-solver-test.cc", "max_issues_repo_name": "plusk01/TEASER-plusplus", "max_issues_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2020-01-24T15:11:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T02:28:52.000Z", "max_forks_repo_path": "test/teaser/rotation-solver-test.cc", "max_forks_repo_name": "plusk01/TEASER-plusplus", "max_forks_repo_head_hexsha": "0d497521d261b3fa35c4ca29eb86ba7cf9558f9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 234.0, "max_forks_repo_forks_event_min_datetime": "2020-01-21T12:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:41:31.000Z", "avg_line_length": 37.9563492063, "max_line_length": 96, "alphanum_fraction": 0.633350758, "num_tokens": 2841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.655754274118405}}
{"text": "#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n#if 0\n\nBZ_DECLARE_STENCIL2(kinEnergy,A,B)\n    B=Laplacian3D_stencilop(A);\nBZ_END_STENCIL_WITH_SHAPE(shape(-1,-1,-1),shape(1,1,1))\n\ntypedef complex<double> T_num;\n\ntypedef Array<T_num,3> array3d;\n\nint main()\n{\nconst int N=5;\narray3d A(N,N,N);\narray3d B(N,N,N);\n\n// Fill a three-dimensional array with a Gaussian function\nfirstIndex i;\nsecondIndex j;\nthirdIndex k;\nfloat midpoint = 15/2.;\nfloat c = - 1/3.0;\nA = exp(c * (sqr(i-midpoint) + sqr(j-midpoint)\n    + sqr(k-midpoint)));\n\napplyStencil(kinEnergy(), A, B);\n\nArray<T_num,1> out_view(B.data(),shape(N*N*N));\ncout << out_view;\n}\n#endif\n\nBZ_DECLARE_STENCIL2(footprint,A,B)\n    B = Laplacian2D4_stencilop(A);\nBZ_END_STENCIL_WITH_SHAPE(shape(-2,-2),shape(+2,+2))\n\nint main()\n{\n    int N = 9;\n    Array<double,2> A(N,N), B(N,N);\n    A = 0;\n    A(4,4) = 1;\n    applyStencil(footprint(), A, B);\n    cout << B(Range(2,6),Range(2,6)) << endl;\n}\n\n", "meta": {"hexsha": "142971862c3396eee8425fd492ef2f168128d271", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/matthias-troyer-1.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/matthias-troyer-1.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/matthias-troyer-1.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": 18.4901960784, "max_line_length": 58, "alphanum_fraction": 0.6585365854, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.655754272468374}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/norms.hpp>\n#include <boost/numeric/mtl/operation/sum.hpp>\n#include <boost/numeric/mtl/operation/product.hpp>\n#include <boost/numeric/mtl/operation/min.hpp>\n#include <boost/numeric/mtl/operation/max.hpp>\n\nusing namespace std;  \n    \n\ntemplate <typename Vector>\nvoid test(Vector& v, const char* name)\n{\n    typedef typename mtl::Collection<Vector>::value_type value_type;\n    using mtl::sum; using mtl::product; using mtl::one_norm;\n\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= value_type(double(i+1) * pow(-1.0, int(i))); // MSVC considers pow)(, i) ambiguous \n\n    std::cout << \"\\n\" << name << \"  --- v = \" << v; std::cout.flush();\n\n    std::cout << \"\\none_norm(v) = \" << one_norm(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(one_norm(v) != 15.0, mtl::runtime_error(\"one_norm wrong\"));\n\n    std::cout << \"one_norm<4>(v) = \" << one_norm<4>(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(one_norm<4>(v) != 15.0, mtl::runtime_error(\"one_norm<4> wrong\"));\n\n    // asm(\"#two_norm begins here!\");\n    value_type tv= two_norm(v);\n    // asm(\"#two_norm ends here!\");\n\n    std::cout << \"two_norm(v) = \" << tv << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(two_norm(v) < 7.4161 || two_norm(v) > 7.4162, mtl::runtime_error(\"two_norm wrong\"));\n\n    std::cout << \"infinity_norm(v) = \" << infinity_norm(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(infinity_norm(v) != 5.0, mtl::runtime_error(\"infinity_norm wrong\"));\n\n    std::cout << \"sum(v) = \" << sum(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(sum(v) != 3.0, mtl::runtime_error(\"sum wrong\"));\n\n    std::cout << \"sum<3>(v) = \" << sum<3>(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(sum<3>(v) != 3.0, mtl::runtime_error(\"sum<3> wrong\"));\n\n    std::cout << \"product(v) = \" << product(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(product(v) != 120.0, mtl::runtime_error(\"product wrong\"));\n\n    std::cout << \"product<6>(v) = \" << product<6>(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(product<6>(v) != 120.0, mtl::runtime_error(\"product<6> wrong\"));\n\n}\n \ntemplate <typename Vector>\nvoid min_max_test(Vector& v, const char*)\n{\n    typedef typename mtl::Collection<Vector>::value_type value_type;\n    using mtl::sum; using mtl::product; using mtl::one_norm;\n\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= value_type(double(i+1) * pow(-1.0, int(i))); // MSVC considers pow)(, i) ambiguous \n\n    std::cout << \"min(v) = \" << min(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(min(v) != -4.0, mtl::runtime_error(\"min wrong\"));\n    \n    std::cout << \"max(v) = \" << max(v) << \"\\n\"; std::cout.flush();\n    MTL_THROW_IF(max(v) != 5.0, mtl::runtime_error(\"max wrong\"));\n    \n}\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    dense_vector<float>                 u(5);\n    dense_vector<double>                x(5);\n    dense_vector<std::complex<double> > xc(5);\n\n    std::cout << \"Testing vector operations\\n\";\n\n    test(u, \"test float\");\n    min_max_test(u, \"test float\");\n    test(x, \"test double\");\n    min_max_test(x, \"test double\");\n\n    test(xc, \"test complex<double>\");\n\n    dense_vector<float, vec::parameters<row_major> >   ur(5);\n    test(ur, \"test float in row vector\");\n    min_max_test(ur, \"test float in row vector\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "09e15777488644c5c7d8a9c1cd10ef319c18a11f", "size": 3950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_reduction_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/vector_reduction_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/vector_reduction_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.6, "max_line_length": 101, "alphanum_fraction": 0.6194936709, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6556700465210067}}
{"text": "/*\n * @Description: Kalman Filter utilities.\n * @Author: Ge Yao\n * @Date: 2020-11-12 15:14:07\n */\n\n#include \"lidar_localization/models/kalman_filter/kalman_filter.hpp\"\n\n// SVD for observability analysis:\n#include <string>\n#include <vector>\n\n#include <Eigen/SVD>\n\n#include \"lidar_localization/tools/CSVWriter.hpp\"\n\n#include \"lidar_localization/global_defination/global_defination.h\"\n\n#include \"glog/logging.h\"\n\nnamespace lidar_localization {\n\nvoid KalmanFilter::AnalyzeQ(\n    const int DIM_STATE,\n    const double &time, const Eigen::MatrixXd &Q, const Eigen::VectorXd &Y,\n    std::vector<std::vector<double>> &data\n) {\n    // perform SVD analysis, thin for rectangular matrix:\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Q, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // add record:\n    std::vector<double> record;\n\n    // a. record timestamp:\n    record.push_back(time);\n\n    // b. record singular values:\n    for (int i = 0; i < DIM_STATE; ++i) {\n        record.push_back(svd.singularValues()(i, 0));\n    }\n\n    // c. record degree of observability:\n    Eigen::MatrixXd X = (\n        svd.matrixV() * \n        svd.singularValues().asDiagonal().inverse()\n    ) * (\n        svd.matrixU().transpose() * Y\n    ).asDiagonal();\n\n    Eigen::VectorXd degree_of_observability = Eigen::VectorXd::Zero(DIM_STATE);\n    for (int i = 0; i < DIM_STATE; ++i) {\n        // find max. magnitude response in X:\n        Eigen::MatrixXd::Index sv_index;\n        X.col(i).cwiseAbs().maxCoeff(&sv_index);\n\n        // associate with corresponding singular value:\n        degree_of_observability(sv_index) = svd.singularValues()(i);\n    }\n    // normalize:\n    degree_of_observability = 1.0 / svd.singularValues().maxCoeff() * degree_of_observability;\n\n    for (int i = 0; i < DIM_STATE; ++i) {\n        record.push_back(degree_of_observability(i));\n    }\n\n    // add to data:\n    data.push_back(record);\n}\n\nvoid KalmanFilter::WriteAsCSV(\n    const int DIM_STATE,\n    const std::vector<std::vector<double>> &data,\n    const std::string filename\n) {\n    // init:\n    CSVWriter csv(\",\");\n    csv.enableAutoNewRow(1 + 2*DIM_STATE);\n\n    // a. write header:\n    csv << \"T\";\n    for (int i = 0; i < DIM_STATE; ++i) {\n        csv << (\"sv\" + std::to_string(i + 1)); \n    }\n    for (int i = 0; i < DIM_STATE; ++i) {\n        csv << (\"doo\" + std::to_string(i + 1)); \n    }\n\n    // b. write contents:\n    for (const auto &record: data) {\n        // cast timestamp to int:\n        csv << static_cast<int>(record.at(0));\n\n        for (size_t i = 1; i < record.size(); ++i) {\n            csv << std::fabs(record.at(i));\n        }    \n    }\n\n    // save to persistent storage:\n    csv.writeToFile(filename);\n}\n\n} // namespace lidar_localization", "meta": {"hexsha": "6b31a3c79e2a08d6f57f0ea7ee837e1f271c3127", "size": 2706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FILTER/06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T05:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:10:16.000Z", "max_issues_repo_path": "06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_issues_repo_name": "WeihengXia0123/LiDar-SLAM", "max_issues_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_forks_repo_name": "WeihengXia0123/LiDar-SLAM", "max_forks_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T12:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:12:44.000Z", "avg_line_length": 26.5294117647, "max_line_length": 94, "alphanum_fraction": 0.6175166297, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.655661949668016}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nThe lattice in this problem is just a very cleverly disguised combinatorics question. So we just need to calculate the factorials. \r\n*/\r\n\r\n// Generate the n'th term for the factorial sequence.\r\ncpp_int factorial(int n) {\r\n\tif(n > 1) {\r\n\t\treturn n * factorial(n - 1);\r\n\t} else {\r\n\t\treturn 1;\r\n\t}\r\n}\r\n\r\ncpp_int nCr(int n, int r) {\r\n\treturn (factorial(n) / (factorial(r) * factorial(n - r)));\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcout << nCr(40, 20) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "ed4479a535e412ef011b2152b4bd14a4a2fd939b", "size": 611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/15/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/15/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/15/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": 22.6296296296, "max_line_length": 132, "alphanum_fraction": 0.6546644845, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6556525867834221}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_HOUGH_PARAMETER_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HOUGH_PARAMETER_HPP\n\n#include <boost/gil/point.hpp>\n#include <cmath>\n#include <cstddef>\n\nnamespace boost\n{\nnamespace gil\n{\n/// \\ingroup HoughTransform\n/// \\brief A type to encapsulate Hough transform parameter range\n///\n/// This type provides a way to express value range for a parameter\n/// as well as some factory functions to simplify initialization\ntemplate <typename T>\nstruct hough_parameter\n{\n    T start_point;\n    T step_size;\n    std::size_t step_count;\n\n    /// \\ingroup HoughTransform\n    /// \\brief Create Hough parameter from value neighborhood and step count\n    ///\n    /// This function will take start_point as middle point, and in both\n    /// directions will try to walk half_step_count times until distance of\n    /// neighborhood is reached\n    static hough_parameter<T> from_step_count(T start_point, T neighborhood,\n                                              std::size_t half_step_count)\n    {\n        T step_size = neighborhood / half_step_count;\n        std::size_t step_count = half_step_count * 2 + 1;\n        // explicitly fill out members, as aggregate init will error out with narrowing\n        hough_parameter<T> parameter;\n        parameter.start_point = start_point - neighborhood;\n        parameter.step_size = step_size;\n        parameter.step_count = step_count;\n        return parameter;\n    }\n\n    /// \\ingroup HoughTransform\n    /// \\brief Create Hough parameter from value neighborhood and step size\n    ///\n    /// This function will take start_point as middle point, and in both\n    /// directions will try to walk step_size at a time until distance of\n    /// neighborhood is reached\n    static hough_parameter<T> from_step_size(T start_point, T neighborhood, T step_size)\n    {\n        std::size_t step_count =\n            2 * static_cast<std::size_t>(std::floor(neighborhood / step_size)) + 1;\n        // do not use step_size - neighborhood, as step_size might not allow\n        // landing exactly on that value when starting from start_point\n        // also use parentheses on step_count / 2 because flooring is exactly\n        // what we want\n\n        // explicitly fill out members, as aggregate init will error out with narrowing\n        hough_parameter<T> parameter;\n        parameter.start_point = start_point - step_size * (step_count / 2);\n        parameter.step_size = step_size;\n        parameter.step_count = step_count;\n        return parameter;\n    }\n};\n\n/// \\ingroup HoughTransform\n/// \\brief Calculate minimum angle which would be observable if walked on a circle\n///\n/// When drawing a circle or moving around a point in circular motion, it is\n/// important to not do too many steps, but also to not have disconnected\n/// trajectory. This function will calculate the minimum angle that is observable\n/// when walking on a circle or tilting a line.\n/// WARNING: do keep in mind IEEE 754 quirks, e.g. no-associativity,\n/// no-commutativity and precision. Do not expect expressions that are\n/// mathematically the same to produce the same values\ninline double minimum_angle_step(point_t dimensions)\n{\n    auto longer_dimension = dimensions.x > dimensions.y ? dimensions.x : dimensions.y;\n    return std::atan2(1, longer_dimension);\n}\n\n/// \\ingroup HoughTransform\n/// \\brief Create a Hough transform parameter with optimal angle step\n///\n/// Due to computational intensity and noise sensitivity of Hough transform,\n/// having any candidates missed or computed again is problematic. This function\n/// will properly encapsulate optimal value range around approx_angle with amplitude of\n/// neighborhood in each direction.\n/// WARNING: do keep in mind IEEE 754 quirks, e.g. no-associativity,\n/// no-commutativity and precision. Do not expect expressions that are\n/// mathematically the same to produce the same values\ninline hough_parameter<double> make_theta_parameter(double approx_angle, double neighborhood,\n                                                    point_t dimensions)\n{\n    auto angle_step = minimum_angle_step(dimensions);\n\n    // std::size_t step_count =\n    //     2 * static_cast<std::size_t>(std::floor(neighborhood / angle_step)) + 1;\n    // return {approx_angle - angle_step * (step_count / 2), angle_step, step_count};\n    return hough_parameter<double>::from_step_size(approx_angle, neighborhood, angle_step);\n}\n}} // namespace boost::gil\n#endif\n", "meta": {"hexsha": "97fcd8cde5d2e33b8894d0629fde1ffe7f079e69", "size": 4732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 41.8761061947, "max_line_length": 93, "alphanum_fraction": 0.71386306, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6555737338592353}}
{"text": "// Copyright (c) 2020, ETH Zurich, CVG, Mihai Dusmanu (mihai.dusmanu@inf.ethz.ch)\n\n#include <Eigen/Core>\n\n#include \"ceres/ceres.h\"\n\nclass BiquadraticInterpolator {\n    public:\n        explicit BiquadraticInterpolator(\n            const std::vector<double>& data, size_t n_channels\n        ) : data_(data), n_channels_(n_channels) {}\n\n        void Evaluate(double row, double col, double* f, double* dfdrow, double* dfdcol) const {\n            // Clipping.\n            const double row_ = row;\n            const double col_ = col;\n            row = std::max(std::min(row, row_end_), row_start_);\n            col = std::max(std::min(col, col_end_), col_start_);\n            \n            const double lagrange_row[3] = {2. * row * (row - .5), (-4.) * (row - .5) * (row + .5), 2. * row * (row + 0.5)};\n            const double deriv_lagrange_row[3] = {2. * row + 2. * (row - .5), (-4.) * (row - .5) + (-4.) * (row + .5), 2. * row + 2. * (row + 0.5)};\n            const double lagrange_col[3] = {2. * col * (col - .5), (-4.) * (col - .5) * (col + .5), 2. * col * (col + 0.5)};\n            const double deriv_lagrange_col[3] = {2. * col + 2. * (col - .5), (-4.) * (col - .5) + (-4.) * (col + .5), 2. * col + 2. * (col + 0.5)};\n\n            for (size_t k = 0; k < n_channels_; ++k) {\n                f[k] = 0.;\n                if (dfdrow != NULL) {\n                    dfdrow[k] = 0.;\n                    dfdcol[k] = 0.;\n                }\n\n                for (size_t i = 0; i < n_rows_; ++i) {\n                    for (size_t j = 0; j < n_cols_; ++j) {\n                        double data = data_[n_channels_ * (i * n_cols_ + j) + k];\n                        f[k] += lagrange_row[i] * lagrange_col[j] * data;\n\n                        if (dfdrow != NULL) {\n                            if (row_ == row) {\n                                dfdrow[k] += deriv_lagrange_row[i] * lagrange_col[j] * data;\n                            }\n                            if (col_ == col) {\n                                dfdcol[k] += lagrange_row[i] * deriv_lagrange_col[j] * data;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // The following two Evaluate overloads are needed for interfacing with automatic differentiation.\n        // The first is for when a scalar evaluation is done, and the second one is for when Jets are used.\n        void Evaluate(const double& r, const double& c, double* f) const {\n            Evaluate(r, c, f, NULL, NULL);\n        }\n\n        template<typename JetT> void Evaluate(const JetT& x, const JetT& y, JetT* f) const {\n            double frc[n_channels_], dfdr[n_channels_], dfdc[n_channels_];\n            Evaluate(x.a, y.a, frc, dfdr, dfdc);\n            for (size_t k = 0; k < n_channels_; ++k) {\n                f[k].a = frc[k];\n                f[k].v = dfdr[k] * x.v + dfdc[k] * y.v;\n            }\n        }\n\n    private:\n        const std::vector<double> data_;\n        const size_t n_channels_;\n        const double row_start_ = -.5; const double col_start_ = -.5;\n        const double row_end_ = .5; const double col_end_ = .5;\n        const double one_over_row_stride_ = 2.; const double one_over_col_stride_ = 2.;\n        const size_t n_rows_ = 3; const size_t n_cols_ = 3;\n};\n\ntemplate<typename Interpolator> struct InterpolatedCostFunctor {\n    public:\n        explicit InterpolatedCostFunctor(Interpolator&& interpolator) : interpolator_(std::move(interpolator)) {}\n\n    template<typename T> bool operator()(const T* x1, const T* x2, T* residuals) const {\n        const Eigen::Map<const Eigen::Matrix<T, 2, 1>> x1_vec(x1);\n        const Eigen::Map<const Eigen::Matrix<T, 2, 1>> x2_vec(x2);\n\n        Eigen::Matrix<T, 2, 1> disp;\n        interpolator_.Evaluate(x1_vec[0], x1_vec[1], disp.data());\n\n        Eigen::Map<Eigen::Matrix<T, 2, 1>> residuals_vec(residuals);\n\n        residuals_vec = x2_vec - x1_vec - disp;\n\n        return true;\n    }\n\n    static ceres::CostFunction* Create(Interpolator&& interpolator) {\n        return new ceres::AutoDiffCostFunction<InterpolatedCostFunctor, 2, 2, 2>(new InterpolatedCostFunctor(std::move(interpolator)));\n    }\n\n    private:\n        const Interpolator interpolator_;\n};\n", "meta": {"hexsha": "46186b154f7bf559d1f64b7d29330671b2749c2a", "size": 4224, "ext": "cc", "lang": "C++", "max_stars_repo_path": "multi-view-refinement/cost.cc", "max_stars_repo_name": "kudo1026/local-feature-refinement", "max_stars_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 180.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T15:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T01:12:56.000Z", "max_issues_repo_path": "multi-view-refinement/cost.cc", "max_issues_repo_name": "kudo1026/local-feature-refinement", "max_issues_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-09-13T05:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T12:18:27.000Z", "max_forks_repo_path": "multi-view-refinement/cost.cc", "max_forks_repo_name": "kudo1026/local-feature-refinement", "max_forks_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T18:17:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T12:27:12.000Z", "avg_line_length": 42.6666666667, "max_line_length": 148, "alphanum_fraction": 0.5170454545, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6555635767302445}}
{"text": "#include <RcppArmadillo.h>\n// [[Rcpp::depends(\"RcppArmadillo\")]]\n// [[Rcpp::depends(\"BH\")]]\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/random.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/math/distributions.hpp>\n\n#include <numeric>\n#include <algorithm>\n#include <map>\n#include <string>\n#include <iostream>\n\nusing namespace Rcpp;\nusing namespace arma;\nusing namespace std;\nusing namespace boost::multiprecision;\nusing namespace boost::math;\n\nboost::mt19937 rng; // seed for random sampling\n\ndouble rbeta_cpp(double shape1, double shape2) {\n  double u  = rand() / double(RAND_MAX);\n  beta_distribution<> beta_dist(shape1, shape2);\n  return quantile(beta_dist, u);  \n}\n\n// [[Rcpp::export]]\narma::rowvec rDirichlet2(arma::rowvec param, int length) {\n  vector<double> ret;\n  param *= 10000;\n  vector<double> param_vec = conv_to<vector<double> >::from(param);\n  int len = length - 1;\n  \n  double paramSum = std::accumulate(param_vec.begin()+1,param_vec.end(),(double)0);\n  ret.push_back(rbeta_cpp(param_vec[0], paramSum));\n  for (int i=1; i<len;i++) {\n    double paramSum = std::accumulate(param_vec.begin()+i+1,param_vec.end(),(double)0); \n    double phi = rbeta_cpp(param_vec[i], paramSum);\n    double sumRet = std::accumulate(ret.begin(),ret.end(),(double)0);  \n    ret.push_back((1-sumRet) * phi);\n  }   \n  double sumRet = std::accumulate(ret.begin(),ret.end(),(double)0); \n  ret.push_back(1-sumRet);\n  return ret;\n}  \n\n", "meta": {"hexsha": "2647383f88f8ede0cd2dfc9560f5c8953b024972", "size": 1514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/10-Dirichlet.cpp", "max_stars_repo_name": "tchakravarty/Stackoverflow-R", "max_stars_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/10-Dirichlet.cpp", "max_issues_repo_name": "tchakravarty/Stackoverflow-R", "max_issues_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/10-Dirichlet.cpp", "max_forks_repo_name": "tchakravarty/Stackoverflow-R", "max_forks_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T17:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T04:00:43.000Z", "avg_line_length": 29.6862745098, "max_line_length": 88, "alphanum_fraction": 0.7047556143, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6555635699877471}}
{"text": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n#include <iostream>\n#include <cmath>\n#include <iomanip>\n#include <limits>\n#include <exception>\n\nconst int PRECISION = 100;\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<PRECISION> > arbFloat;\n\nbool isStringValid(const std::string & str);\nbool isNumberValid(const arbFloat & x);\nenum returnID {success = 0, invalidString = 1, invalidNumber = 2};\ninline std::string resizeArbtoString(const arbFloat & x);\n\nint main() {\n    // Input and check string\n    std::cout << \"0 <= x < inf\\nW(x), x = \";\n    std::string inputStr;\n    std::getline(std::cin, inputStr);\n    \n    if(!isStringValid(inputStr)) return returnID::invalidString;\n    \n    arbFloat input = static_cast<arbFloat>(inputStr);\n    \n    if(!isNumberValid(input)) return returnID::invalidNumber;\n    \n    // Starting guess\n    arbFloat wnew = (input >= 2) ? log(input) - log(log(input)) + (log(log(input)) / log(input))\n            : static_cast<arbFloat>(0);\n    \n    std::cout << std::setprecision(PRECISION)\n            << \"\\nInitial Guess: \" << wnew << \"\\nConvergence:\\n\";\n    \n    // Calculations\n    int i;\n    std::string preComp, postComp;\n    for(i = 0; i == 0 || preComp != postComp; i++){\n        std::cout << '\\t' << wnew << '\\n';\n        preComp = resizeArbtoString(wnew);\n        wnew -= ((wnew * exp(wnew)) - input) /\n                (exp(wnew) * (wnew + 1) - ((wnew + 2) * (wnew * exp(wnew) - input) / ((2 * wnew) + 2)));\n        postComp = resizeArbtoString(wnew);\n    }\n    \n    std::cout << \"\\nW(\" + inputStr + \") = \" << wnew << \"\\n(rounded up to \"\n            << PRECISION << \" digits, precise after \" << i << \" iterations)\\n\";\n    \n    return 0;\n}\n\n// Check input\nbool isStringValid(const std::string & str){\n    // Check if string contains spaces\n    if(std::count(str.begin(), str.end(), ' ') > 0){\n        std::cout << \"\\nError: Input contains spaces\\n\";\n        return false;\n    }\n    \n    // Check if string contains multiple .\n    if(std::count(str.begin(), str.end(), '.') > 1){\n        std::cout << \"\\nError: Input contains multiple decimal marks\\n\";\n        return false;\n    }\n    \n    // Check if NaN or Out of bounds (due to parsing failure)\n    try{\n        boost::lexical_cast<arbFloat>(str);\n    } catch(std::runtime_error){\n        std::cout << \"\\nError: Unable to parse (value too large or incorrect number type)\\n\";\n        return false;\n    } catch(...){\n        std::cout << \"\\nError: Input is NaN\\n\";\n        return false;\n    }\n    \n    // Check if intentional NaN\n    if(boost::icontains(str, \"nan\")){\n        std::cout << \"\\nError: Intentional NaN\\n\";\n        return false;\n    }\n    \n    return true;\n}\n\n// Check number\nbool isNumberValid(const arbFloat & x){\n    // Check if result is imaginary\n    if(x < 0){\n        std::cout << \"\\nError: Complex result\\n\";\n        return false;\n    }\n    \n    // Check if out of bounds (interpreted as infinity)\n    if(x == std::numeric_limits<arbFloat>::infinity()){\n        std::cout << \"\\nError: Input is out of bounds\\n\";\n        return false;\n    }\n    \n    return true;\n}\n\n// Convert to string and resize using correct precision\ninline std::string resizeArbtoString(const arbFloat & x){\n    std::string resizedStr = static_cast<std::string>(x);\n    resizedStr.resize(PRECISION + 2);\n    return resizedStr;\n}\n", "meta": {"hexsha": "4dbe30b50df35d6c55f9aa16d2baf7b172ccfc61", "size": 3406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lambert-W-function/Lambert-W-function-v4.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": "Lambert-W-function/Lambert-W-function-v4.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": "Lambert-W-function/Lambert-W-function-v4.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": 30.6846846847, "max_line_length": 104, "alphanum_fraction": 0.5957134469, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6555635646731172}}
{"text": "/**\n * \\file dcs/math/stats/distribution/normal.hpp\n *\n * \\brief The Normal probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 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_STATS_DISTRIBUTION_NORMAL_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_NORMAL_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\nusing ::std::size_t;\n\n\n/**\n * The Normal distribution with parameter \\f$\\mu\\f$ (the mean) and \\f$\\sigma\\f$\n * (the standard deviation).\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass normal_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit normal_distribution(support_type mean=0, support_type stddev=1)\n\t\t: dist_(mean,stddev)\n//\t\t: mean_(mean),\n//\t\t  stddev_(stddev)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A random number distributed according to this normal\n\t * distribution.\n\t *\n\t * A \\c normal random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\ttypedef ::boost::normal_distribution<support_type> rdist_type;\n\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n\n\t\treturn variate_type(rng, rdist_type(dist_.mean(), dist_.standard_deviation()))();\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * A \\c normal random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, size_t n)\n\t{\n\t\ttypedef ::boost::normal_distribution<support_type> rdist_type;\n        typedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(variate_type(rng, rdist_type(dist_.mean(), dist_.standard_deviation()))());\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type mean() const\n\t{\n\t\treturn dist_.mean();\n\t}\n\n\n\tpublic: support_type stddev() const\n\t{\n\t\treturn dist_.standard_deviation();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn dist_.location();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn dist_.scale();\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\t//private: support_type mean_;\n\t//private: support_type stddev_;\n\tprivate: ::boost::math::normal_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, normal_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"Normal(\"\n\t\t\t  << \"mean=\" <<  dist.mean()\n\t\t\t  << \", stddev=\" <<  dist.stddev()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_NORMAL_HPP\n", "meta": {"hexsha": "b4d1c6e64125f0ae2364400693f9cc317738a835", "size": 5027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/normal.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "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": "inc/dcs/math/stats/distribution/normal.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "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": "inc/dcs/math/stats/distribution/normal.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "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.8823529412, "max_line_length": 144, "alphanum_fraction": 0.7171275114, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6555217127620131}}
{"text": "//\n// Created by matt on 20/01/2021.\n//\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include \"simple_kf.h\"\n#include \"standard_kf.h\"\n#include \"extended_kf.h\"\n#include \"unscented_kf.h\"\n#include \"system.h\"\n#include \"numeric_differentiation.h\"\n\n\nint main() {\n\n  const int iterations = 3;\n  using SS = systems::SimpleSystem;\n  const SS::MeasurementVector z(1.0, 2.0);\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Simple kalman filter\\n\";\n  kf0::KalmanFilter skf;\n  skf.SetCov(systems::SimpleSystem::StateMatrix::Identity());\n  std::cout << \"Intial state:\\n\";\n  std::cout << skf.GetState().transpose() << '\\n';\n  std::cout << skf.GetCov() << '\\n';\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    std::cout << \"Predict: \" << skf.Predict().transpose() << '\\n';\n    std::cout << skf.GetCov() << '\\n';\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << skf.Update(z * (double) i).transpose() << \"\\n\";\n    std::cout << skf.GetCov() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Templated kalman filter 1\\n\";\n\n  kf1::KalmanFilter<4> kf1;\n  kf1::ProcessModel<4> process = [](const Eigen::Matrix<double, 4, 1>& x) -> Eigen::Matrix<double, 4, 1> {\n    Eigen::Matrix<double, 4, 4> F = Eigen::Matrix<double, 4, 4>::Identity();\n    F(0, 2) = 0.1; // px' = px + vx*dt\n    F(1, 3) = 0.1; // py' = py + vy*dt\n    return F * x;\n  };\n  kf1::MeasurementModel<4, 2> measurement_model = [](\n      const Eigen::Matrix<double, 4, 1>& x) -> Eigen::Matrix<double, 2, 1> {\n    Eigen::Matrix<double, 2, 4> H = Eigen::Matrix<double, 2, 4>::Zero();\n    // Measure position only\n    H(0, 0) = 1.0;\n    H(1, 1) = 1.0;\n    return H * x;\n  };\n\n  kf1.SetCov(Eigen::Matrix4d::Identity());\n  Eigen::Matrix4d Q = Eigen::Matrix4d::Identity() * 2.0;\n  Eigen::Matrix2d R = Eigen::Matrix2d::Identity();\n\n  std::cout << kf1.GetState().transpose() << '\\n';\n  std::cout << kf1.GetCov() << '\\n';\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf1.Predict(process, Q);\n    std::cout << \"Predict: \" << kf1.GetState().transpose() << '\\n';\n    std::cout << kf1.GetCov() << '\\n';\n    kf1.Update<2>(measurement_model, z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf1.GetState().transpose() << \"\\n\\n\";\n    std::cout << kf1.GetCov() << '\\n';\n  }\n\n  ////////////////////////////////////////////////////////////////////\n\n  std::cout << \"Templated kalman filter 2\\n\";\n\n  kf2::KalmanFilter<4, 2>::ProcessModel process_model_2 = [](\n      const Eigen::Matrix<double, 4, 1>& x) -> Eigen::Matrix<double, 4, 1> {\n    Eigen::Matrix<double, 4, 4> F = Eigen::Matrix<double, 4, 4>::Identity();\n    F(0, 2) = 0.1; // px' = px + vx*dt\n    F(1, 3) = 0.1; // py' = py + vy*dt\n    return F * x;\n  };\n  kf2::KalmanFilter<4, 2>::MeasurementModel measurement_model_2 = [](\n      const Eigen::Matrix<double, 4, 1>& x) -> Eigen::Matrix<double, 2, 1> {\n    Eigen::Matrix<double, 2, 4> H = Eigen::Matrix<double, 2, 4>::Zero();\n    // Measure position only\n    H(0, 0) = 1.0;\n    H(1, 1) = 1.0;\n    return H * x;\n  };\n\n  kf2::KalmanFilter<4, 2> kf2(process_model_2, measurement_model_2);\n  kf2.SetCov(Eigen::Matrix4d::Identity());\n\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf2.Predict(Q);\n    std::cout << \"Predict: \" << kf2.GetState().transpose() << '\\n';\n    kf2.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf2.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Templated kalman filter 3\\n\";\n\n  kf3::KalmanFilter<4, 2, SS> kf_3;\n  kf_3.SetCov(Eigen::Matrix4d::Identity());\n\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf_3.Predict(Q);\n    std::cout << \"Predict: \" << kf_3.GetState().transpose() << '\\n';\n    kf_3.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf_3.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Templated kalman filter 4\\n\";\n\n  kf4::KalmanFilter<SS> kf_4;\n  kf_4.SetCov(Eigen::Matrix4d::Identity());\n\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf_4.Predict(Q);\n    std::cout << \"Predict: \" << kf_4.GetState().transpose() << '\\n';\n    kf_4.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf_4.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Another system\\n\";\n\n  const Eigen::Vector3d z3(1.0, 2.0, 0.5);\n  Eigen::Matrix<double, 6, 6> Q3 = Eigen::Matrix<double, 6, 6>::Identity() * 2.0;\n  Eigen::Matrix3d R3 = Eigen::Matrix3d::Identity();\n\n  kf4::KalmanFilter<systems::AnotherSystem> kf_5;\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf_5.Predict(Q3);\n    std::cout << \"Predict: \" << kf_5.GetState().transpose() << '\\n';\n    kf_5.Update(z3 * (double) i, R3);\n    std::cout << \"Measurement: \" << (z3 * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf_5.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Kalman filter using dynamic sized matrices\\n\";\n\n  Eigen::VectorXd starting_state = Eigen::VectorXd::Zero(4);\n  kf5::KalmanFilter<systems_dynamic::SimpleSystem> kf_6(starting_state);\n  kf_6.SetCov(Eigen::MatrixXd::Identity(4, 4));\n\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    kf_6.Predict(Q);\n    std::cout << \"Predict: \" << kf_6.GetState().transpose() << '\\n';\n    kf_6.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << kf_6.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n\n  Eigen::Vector4d current_state = Eigen::Vector4d::Zero();\n\n  SS::StateMatrix JF = numeric_differentiation::CalculateJacobian<SS::kStateSize, SS::kStateSize>(current_state, SS::processModel);\n  std::cout << JF << \"\\n\\n\";\n  Eigen::Matrix<double, SS::kMeasurementSize, SS::kStateSize> JH =\n      numeric_differentiation::CalculateJacobian<SS::kStateSize, SS::kMeasurementSize>(current_state, SS::measurementModel);\n  std::cout << JH << \"\\n\\n\";\n\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"EKF 1 (with linear system) \\n\";\n\n  ekf1::ExtendedKalmanFilter<SS> ekf_1;\n  ekf_1.SetCov(SS::StateMatrix::Identity());\n\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    ekf_1.Predict(Q);\n    std::cout << \"Predict: \" << ekf_1.GetState().transpose() << '\\n';\n    ekf_1.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << ekf_1.GetState().transpose() << \"\\n\\n\";\n  }\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"EKF 1 (with non-linear system) \\n\";\n\n  using NLS = systems::NonLinearSystem;\n  ekf1::ExtendedKalmanFilter<NLS> ekf_2;\n  NLS::ProcessNoiseMatrix Q_nl = NLS::ProcessNoiseMatrix::Identity() * 10.0;\n  NLS::MeasurementNoiseMatrix R_nl = NLS::MeasurementNoiseMatrix::Identity() * 1.0;\n\n  ekf_2.SetCov(Q_nl);\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    ekf_2.Predict(Q_nl);\n    std::cout << \"Predict: \" << ekf_2.GetState().transpose() << '\\n';\n    ekf_2.Update(z, R_nl);\n    std::cout << \"Measurement: \" << z.transpose() << \"\\n\";\n    std::cout << \"Update: \" << ekf_2.GetState().transpose() << \"\\n\\n\";\n  }\n\n // velocity is estimated correctly after a few iterations\n // why doesn't heading work out?\n\n  ////////////////////////////////////////////////////////////////////\n  std::cout << \"Unscented kalman filter 1\\n\";\n\n  ukf1::UnscentedKalmanFilter<SS> ukf_1;\n  ukf_1.SetCov(SS::StateMatrix::Identity());\n\n  std::cout << ukf_1.GetState().transpose() << '\\n';\n  std::cout << ukf_1.GetCov() << '\\n';\n  for (int i = 0; i < iterations; i++) {\n    std::cout << \"Iteration: \" << i << '\\n';\n    ukf_1.Predict(Q);\n    std::cout << \"Predict: \" << ukf_1.GetState().transpose() << '\\n';\n    ukf_1.Update(z * (double) i, R);\n    std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n    std::cout << \"Update: \" << ukf_1.GetState().transpose() << \"\\n\";\n  }\n\n\n\n\n  return 0;\n}\n", "meta": {"hexsha": "03c32456e50ad41fc5ca5121f83d4d6fbb3caa9b", "size": 8809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "matt769/kalman_filters", "max_stars_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_stars_repo_licenses": ["MIT"], "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": "matt769/kalman_filters", "max_issues_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_issues_repo_licenses": ["MIT"], "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": "matt769/kalman_filters", "max_forks_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_forks_repo_licenses": ["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.8577405858, "max_line_length": 131, "alphanum_fraction": 0.5211715291, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6555217095080877}}
{"text": "/* test_exponential.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/exponential_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/exponential.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::exponential_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME exponential\r\n#define BOOST_MATH_DISTRIBUTION boost::math::exponential\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME lambda\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.0001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "704ddeac26911f55dfc926c87c998afdd5ef76fe", "size": 822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_exponential.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_exponential.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_exponential.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 32.88, "max_line_length": 76, "alphanum_fraction": 0.7846715328, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6555217060590789}}
{"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, 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 tools/license/license.mtl.txt in the distribution.\n\n#ifndef MTL_MAT_KRON_INCLUDE\n#define MTL_MAT_KRON_INCLUDE\n\n#include <cstddef>\n\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n\n// #include <boost/numeric/mtl/operation/set_to_zero.hpp>\n\nnamespace mtl { namespace mat {\n\n/// Kronecker product (prototype implementation)\n// A full-fledged version will be in MTL5 (with expression templates and allowing for arbitrary mixed types)    \ntemplate <typename Value, typename Para>\ndense2D<Value, Para> kron(const dense2D<Value, Para>& A, const dense2D<Value, Para>& B)\n{\n    using std::size_t;\n    size_t nra= num_rows(A), nca= num_cols(A), nrb= num_rows(B), ncb= num_cols(B);\n        \n    dense2D<Value, Para> P(nra*nrb, nca*ncb);\n    for (size_t ra= 0; ra < nra; ++ra)  \n        for (size_t ca= 0; ca < nca; ++ca)\n            for (size_t rb= 0; rb < nrb; ++rb)  \n                for (size_t cb= 0; cb < ncb; ++cb)\n                    P[ra*nrb+rb][ca*ncb+cb]= A[ra][ca] * B[rb][cb];\n    return P;\n}\n    \n    \n\n}} // namespace mtl::mat\n\n#endif // MTL_MAT_KRON_INCLUDE\n", "meta": {"hexsha": "2cedee1ad4c9b9e62fc7c53e68e4a04314d0493e", "size": 1449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/kron.hpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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": "boost/numeric/mtl/operation/kron.hpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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": "boost/numeric/mtl/operation/kron.hpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "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": 112, "alphanum_fraction": 0.6535541753, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6553296067185522}}
{"text": "#include <iostream>\n#include <dlib/matrix.h>\n\n\nint main()\n{\n    // declare a matrix\n    dlib::matrix<double, 3, 1> y;\n    dlib::matrix<double, 3, 3> M;\n    // initialize matrices\n    M = 54.2, 65.2, 43,\n        23.4, 12.3, 55.4,\n        11, 34.6, 78.9;\n    y = 3.5,\n        1.2,\n        6.7;\n    // solve this linear system\n    dlib::matrix<double> x = dlib::inv(M)*y;\n    std::cout << \"x: \\n\" << x << \"\\n\";\n    // check if the calculation is correct\n    std::cout << \"Check: M*x- y= \\n\" << M*x - y << \"\\n\";\n\n    // sum the matrix\n    double sumM = 0;\n    for (int r = 0; r < M.nr(); ++r)\n    {\n        for (int c = 0; c < M.nc(); ++c)\n        {\n            sumM += M(r, c);\n        }\n    }\n    std::cout << \"Sum of matrix by looping= \" << sumM << \"\\n\";\n    std::cout << \"Sum of matrix by sum() function= \" << dlib::sum(M) << \"\\n\";\n    // print using comma separator\n    std::cout <<\"print matrix M using comma delimiter: \\n\" <<dlib::csv << M << \"\\n\";\n\n    std::system(\"pause\");\n    return 0;\n}\n", "meta": {"hexsha": "e5251d8239b2b0c9d59f9abc19b5e3cb66d9a594", "size": 995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-projects/tiny-apps/dlib-learning/matrix-basic/main.cpp", "max_stars_repo_name": "juxiangwu/image-processing", "max_stars_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-09-07T02:29:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T08:40:09.000Z", "max_issues_repo_path": "cpp-projects/tiny-apps/dlib-learning/matrix-basic/main.cpp", "max_issues_repo_name": "juxiangwu/image-processing", "max_issues_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "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": "cpp-projects/tiny-apps/dlib-learning/matrix-basic/main.cpp", "max_forks_repo_name": "juxiangwu/image-processing", "max_forks_repo_head_hexsha": "c644ef3386973b2b983c6b6b08f15dc8d52cd39f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-20T00:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-15T10:14:36.000Z", "avg_line_length": 24.875, "max_line_length": 84, "alphanum_fraction": 0.4743718593, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6553295973694019}}
{"text": "/**\n * @file gradientflow.h\n * @brief NPDE homework GradientFlow code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"gradientflow.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <vector>\n\nnamespace GradientFlow {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::MatrixXd ButcherMatrix() {\n  Eigen::MatrixXd A(6, 5);\n  // clang-format off\n  A <<       0.25,          0.,       0.,       0.,   0.,\n    0.5,        0.25,       0.,       0.,   0.,\n    17./50.,     -1./25.,     0.25,       0.,   0.,\n    371./1360., -137./2720., 15./544.,     0.25,   0.,\n    25./24.,    -49./48., 125./16., -85./12., 0.25,\n    25./24.,    -49./48., 125./16., -85./12., 0.25;\n  // clang-format on\n  return A;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector<Eigen::VectorXd> solveGradientFlow(const Eigen::VectorXd &d,\n                                               double lambda,\n                                               const Eigen::VectorXd &y,\n                                               double T, unsigned int N) {\n  std::vector<Eigen::VectorXd> Y(N + 1);\n  // TO DO (0-2.h)\n#if SOLUTION\n  // Define the right hand side of the ODE y' = f(y), and the Jacobian of f.\n  auto f = [d, lambda](const Eigen::VectorXd &yt) {\n    Eigen::VectorXd val =\n        -2. * std::cos(yt.squaredNorm()) * yt - 2. * lambda * d.dot(yt) * d;\n    return val;\n  };\n  auto J = [d, lambda](const Eigen::VectorXd &yt) {\n    int dim = yt.size();\n    Eigen::MatrixXd term1 =\n        4. * std::sin(yt.squaredNorm()) * yt * yt.transpose();\n    Eigen::MatrixXd term2 =\n        -2. * std::cos(yt.squaredNorm()) * Eigen::MatrixXd::Identity(dim, dim);\n    Eigen::MatrixXd term3 = -2. * lambda * d * d.transpose();\n    Eigen::MatrixXd Jval = term1 + term2 + term3;\n    return Jval;\n  };\n\n  // Split the interval [0,T] into N intervals of size h.\n  double h = T / N;\n  Eigen::VectorXd yt = y;\n  Y.at(0) = y;\n  // Evolve up to time T:\n  for (int i = 1; i <= N; i++) {\n    yt = discEvolSDIRK(f, J, yt, h);\n    Y.at(i) = yt;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return Y;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace GradientFlow\n", "meta": {"hexsha": "07127e479aa00cdc771b1fb7a65cfefbf0b60bf9", "size": 2205, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/GradientFlow/mastersolution/gradientflow.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": "developers/GradientFlow/mastersolution/gradientflow.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": "developers/GradientFlow/mastersolution/gradientflow.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": 29.0131578947, "max_line_length": 79, "alphanum_fraction": 0.5188208617, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6553012627204574}}
{"text": "//          Copyright Gunter Winkler 2004 - 2009.\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\r\n#include <iostream>\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\nusing std::cout;\r\nusing std::endl;\r\n\r\n\r\n\r\nnamespace ublas = boost::numeric::ublas;\r\n\r\n\r\nint main(int argc, char * argv[] ) {\r\n\r\n  ublas::matrix<double> M (3, 3);\r\n  for (std::size_t i=0; i < M.data().size(); ++i) { M.data()[i] = 1+i ; }\r\n\r\n  std::cout << \"full         M  = \" << M << \"\\n\" ;\r\n\r\n  ublas::triangular_matrix<double, ublas::lower> L;\r\n  ublas::triangular_matrix<double, ublas::unit_lower> UL;\r\n  ublas::triangular_matrix<double, ublas::strict_lower> SL;\r\n  \r\n  L  = ublas::triangular_adaptor<ublas::matrix<double>, ublas::lower> (M);\r\n  SL = ublas::triangular_adaptor<ublas::matrix<double>, ublas::strict_lower> (M); \r\n  UL = ublas::triangular_adaptor<ublas::matrix<double>, ublas::unit_lower> (M);  \r\n  \r\n  std::cout << \"lower        L  = \" << L << \"\\n\" \r\n            << \"strict lower SL = \" << SL << \"\\n\" \r\n            << \"unit lower   UL = \" << UL << \"\\n\" ;\r\n\r\n  ublas::triangular_matrix<double, ublas::upper> U;\r\n  ublas::triangular_matrix<double, ublas::unit_upper> UU;\r\n  ublas::triangular_matrix<double, ublas::strict_upper> SU;\r\n  \r\n  U =  ublas::triangular_adaptor<ublas::matrix<double>, ublas::upper> (M);\r\n  SU = ublas::triangular_adaptor<ublas::matrix<double>, ublas::strict_upper> (M); \r\n  UU = ublas::triangular_adaptor<ublas::matrix<double>, ublas::unit_upper> (M);  \r\n\r\n  std::cout << \"upper        U  = \" << U << \"\\n\" \r\n            << \"strict upper SU = \" << SU << \"\\n\" \r\n            << \"unit upper   UU = \" << UU << \"\\n\" ;\r\n\r\n  std::cout << \"M = L + SU ? \" << ((norm_inf( M - (L + SU) ) == 0.0)?\"ok\":\"failed\") << \"\\n\";\r\n  std::cout << \"M = U + SL ? \" << ((norm_inf( M - (U + SL) ) == 0.0)?\"ok\":\"failed\") << \"\\n\";\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "dbde0e2dbb8b8b6130f96bec59114b9f5c4a94a8", "size": 2035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/doc/samples/ex_triangular.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": 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/numeric/ublas/doc/samples/ex_triangular.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": 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/numeric/ublas/doc/samples/ex_triangular.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": 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": 34.4915254237, "max_line_length": 93, "alphanum_fraction": 0.572972973, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.6552529558991527}}
{"text": "/**\n * @file matode.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n\nnamespace MatODE {\n\n/* SAM_LISTING_BEGIN_3 */\n\tEigen::MatrixXd eeulstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t                         double h) {\n\t\treturn Y0 + A * Y0 * h;\n\t}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\n\tEigen::MatrixXd ieulstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t                         double h) {\n\n\t\tEigen::MatrixXd Y1 = (Eigen::MatrixXd::Identity(A.rows(), A.cols()) - h * A).lu().solve(Y0);\n\n\t\treturn Y1;\n\t}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\n\tEigen::MatrixXd impstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t                        double h) {\n\n\t\tEigen::MatrixXd I = Eigen::MatrixXd::Identity(A.rows(), A.cols());\n\n\t\treturn \t(I - 0.5 * h * A).lu().solve((I + 0.5 * h * A) * Y0);\n\t}\n/* SAM_LISTING_END_5 */\n\n}  // namespace MatODE\n", "meta": {"hexsha": "53d98561ac9b7c8c36f295072230bc48a9573fc3", "size": 951, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mysolution/matode.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/MatODE/mysolution/matode.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/MatODE/mysolution/matode.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": 24.3846153846, "max_line_length": 94, "alphanum_fraction": 0.5993690852, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.6552529410783635}}
{"text": "#include <boost/log/trivial.hpp>\n#include \"../multivariate_guassian.hpp\"\n#include \"gtest/gtest.h\"\n\nnamespace FilterModel {\nconst double ERROR = 0.0001;\n\nTEST(density, OneDimensionalAtZeroCorrect) {\n    MultivariateGuassian normal({0}, {{1}});\n    ASSERT_NEAR(normal.density({0.0}), 1.0 / std::sqrt(2.0 * M_PI), ERROR);\n}\n\nTEST(density, OneDimensionalAtOneCorrect) {\n    MultivariateGuassian normal({0}, {{1}});\n    ASSERT_NEAR(normal.density({1.0}), std::exp(-1.0 / 2.0) / std::sqrt(2.0 * M_PI), ERROR);\n}\n\nTEST(density, OneDimensionalAtTwoCorrect) {\n    MultivariateGuassian normal({0}, {{1}});\n    ASSERT_NEAR(normal.density({2.0}), std::exp(-4.0 / 2.0) / std::sqrt(2.0 * M_PI), ERROR);\n}\n\nTEST(density, TwoDimensionalAtZeroCorrect) {\n    MultivariateGuassian normal({0, 0}, {{1, 0}, {0, 1}});\n    ASSERT_NEAR(normal.density({0.0, 0.0}), std::exp(0) / (2.0 * M_PI), ERROR);\n}\n\n}  // namespace FilterModel", "meta": {"hexsha": "21b2d5c54efe542665a41ffe60050da68e8adc1f", "size": 906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/tests/multivariate_guassian_tests.cpp", "max_stars_repo_name": "skinnersBoxy/input-filter", "max_stars_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_stars_repo_licenses": ["MIT"], "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++/tests/multivariate_guassian_tests.cpp", "max_issues_repo_name": "skinnersBoxy/input-filter", "max_issues_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_issues_repo_licenses": ["MIT"], "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++/tests/multivariate_guassian_tests.cpp", "max_forks_repo_name": "skinnersBoxy/input-filter", "max_forks_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 92, "alphanum_fraction": 0.6633554084, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6552200732019068}}
{"text": "#pragma once\n#include <simcem/simcem.hpp>\n#include <simcem/sundials.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <memory>\n#include <numeric>\n\n/*\n  Notes:\n  Theo's guide\n\n  There are three PyKiln folders:  \n  - PyKiln - Output from each test\n  - PyKiln2 - Output from each test\n  - Optimize_Heat_Model - Theo's work on optimising the heat transfer coefficients\n\n  You need to install assimulo to use it. Do this by downloading the\n  source code, replacing all StrictVersion by LooseVersion in\n  setup.py, then build/install.\n\n  You also need to install PyChemEng. The folders in dropbox are not\n  installable (old versions) It seems that PyChemEngLocal is the\n  newest version, followed by PyChemEng-Marcus, then PyChemEng. You\n  need to install from git@dynamomd.org:PyChemEng.\n\n  You also need pyopt!\n\n  Each PyKiln folder has the following structure:\n  - Kiln_Classes.py - All pilot kiln trial data.\n  - KilnSolverXXXX.py - The actual workhorse for fitting data, all copies of KilnSolverXXX.py\n  - Kiln_Plotter.py - Plotting of data files from KilnSolver\n  \n  run PyKiln2/KilnSolverAssimulo.py, then run Kiln_Plotter.py\n*/\nnamespace simcem {\n  /*! \\brief Heat transfer correlations and expressions. */\n  namespace HT {\n    /*! \\brief Conductive heat transfer. */\n    namespace conduction {\n      /*! \\brief Conduction resistance for a cylindrical shell of unit length.*/\n      double R_cyl(const double Rout, const double Rin, const double k) {\n\treturn std::log(Rout / Rin) / (2 * Database::pi * k);\n      }\n\n      /*! \\brief The Maxwell model for combining thermal conductivities. \n\t\n\tThis requires that one phase is identified as \"continuous\" and\n\tanother phase is \"discrete\". Then the volume fraction of\n\tdiscontinuous phase is requred.\n      */\n      double maxwell(const double kcont, const double kdisc, const double discfrac) {\n\treturn kcont * (2*kcont + kdisc + 2 * discfrac * (kdisc - kcont)) / (2 * kcont + kdisc + discfrac * (kcont - kdisc));\n      }\n    }\n    \n    /*! \\brief Natural convection heat transfer. */\n    namespace natConv {\n      /*! \\brief The overall convective heat transfer from smooth\n\tcircular cylinders.\n\t\n\tTaken from Heat Transfer, J.P Holman pg 334, VT Morgan.\n\n\tA big collection of available expressions is in Boetcher_2014. \n      */\n      double Nu_horiz_cyl(const double Gr, const double Pr) {\n\tconst double Ra = Gr * Pr;\n\n\t//A wide range expression (Eq.7-36 in Holman, Eq 5-35 in Perrys)\n\t//\tif ((1e-5 <= Ra) && (Ra <= 1e12))\n\t//\t  return std::pow(0.60 + 0.387*std::pow(Ra/std::pow(1+std::pow(0.559/Pr, 9.0/16), 16/9.0), 1.0/6), 2);\n\n\t//The table from Holman favouring the \"preferred\" expressions where possible\n\tif (Ra < 1e-10)\n\t  return 0.4;\n\tif (Ra < 1e-2)\n\t  return 0.675 * std::pow(Ra, 0.058);\n\tif (Ra < 1e2)\n\t  return 1.02 * std::pow(Ra, 0.148);\n\tif (Ra < 1e4)\n\t  return 0.850 * std::pow(Ra, 0.188);\n\tif (Ra < 1e7)\n\t  return 0.480 * std::pow(Ra, 1.0/4);\n\tif (Ra < 1e12)\n\t  return 0.125 * std::cbrt(Ra);\n       \t\n\tstator_throw() << \"Ra=\" << Ra << \" over upper range.\";\n      }\n    }\n\n    /*!\\brief Radiative heat transfer. */\n    namespace rad {\n\n      /*! \\brief Simple radiative heat transfer coefficient.\n\t\n\tThe Steffan-Boltzmann coefficient \n      */\n      double h_rad_simple(const double T1, const double T2, const double emissivity,\n\t\t\t  const double steffanBoltzmannConstant = 5.670367e-8) {\n\treturn emissivity *\n\t  steffanBoltzmannConstant\n\t  * (T1 * T1 + T2 * T2) * (T1 + T2);\n      }\n\n      \n      /*! \\brief Hottel calculation for the emissivity of gases\n\tcontaining CO2 and H2O.\n\t\n\tThis is taken from Perry's Chemical Engineering Handbook,\n\tchapter 5. This assumes that the primary radiative\n\tproperties of the gas are derived from the H2O and CO2\n\tcomponents only. It also uses bilinear\n\tinterpolation/extrapolation.\n\n\tErrors up to 20% are expected. The temperature argument is\n\tonly provided for absorptivity calculations (which should be\n\tcarried out via the Hottel_absorptivity function), and if it\n\tis left at the default of 0 it is taken from the gas phase\n\tautomatically.\n      */\n      double Hottel_emissivity(const simcem::Model& gas, const double pathLength, double Tgas = 0) {\n\tif (Tgas == 0) Tgas = gas.T();\n\t//Fraction of H2O versus CO2+H2O\n\tconst double pw_frac = gas[\"H2O\"] / (gas[\"H2O\"]+gas[\"CO2\"]);\n\n\t//Partial pressure of H2O and CO2 in atms\n\tconst double p = (gas[\"H2O\"]+gas[\"CO2\"]) / gas.N() * gas.p() / 1.01325e5;\n\tconst double pL = p * pathLength;\n\tif (pL > 10)\n\t  stator_throw() << \"pL out of range \" << pL;\n\n\tif (pL < 0.005)\n\t  return 0; //This is an approximation!\n\t  //stator_throw() << \"pL out of range \" << pL;\n\t\n\tconst double logpL = std::log10(pL);\n\n\t//Perform bilinear interpolation where x is T, and y is pw_frac.\n\tconst double x_range[] = {1000, 1500, 2000};\n\tconst double y_range[] = {0, 1.0/3.0, 1.0/2.0, 2.0/3.0, 3.0/4.0, 1.0};\n\n\t//Calculation of the indices of the data points are around the sample point\n\tsize_t x_idx = 0;\n\tif (Tgas > x_range[1]) x_idx = 1;\n\t\n\tsize_t y_idx = 0;\n\tif (pw_frac > y_range[1]) y_idx = 1;\n\tif (pw_frac > y_range[2]) y_idx = 2;\n\tif (pw_frac > y_range[3]) y_idx = 3;\n\tif (pw_frac > y_range[4]) y_idx = 4;\n\t\n\tstatic const double coeffs[] = { 2.2661, 0.1742, -0.0390,  0.0040,\n\t\t\t\t\t 2.3954, 0.2203, -0.0433,  0.00562,\n\t\t\t\t\t 2.4104, 0.2602, -0.0651, -0.00155,\n\t\t\t\t\t 2.5754, 0.2792, -0.0648,  0.0017,\n\t\t\t\t\t 2.6451, 0.3418, -0.0685, -0.0043,\n\t\t\t\t\t 2.6504, 0.4279, -0.0674, -0.0120,\n\t\t\t\t\t 2.6090, 0.2799, -0.0745, -0.0006,\n\t\t\t\t\t 2.6862, 0.3450, -0.0816, -0.0039,\n\t\t\t\t\t 2.7029, 0.4440, -0.0859, -0.0135,\n\t\t\t\t\t 2.6367, 0.2723, -0.0804,  0.0030,\n\t\t\t\t\t 2.7178, 0.3386, -0.0990, -0.0030,\n\t\t\t\t\t 2.7482, 0.4464, -0.1086, -0.0139,\n\t\t\t\t\t 2.6432, 0.2715, -0.0816,  0.0052,\n\t\t\t\t\t 2.7257, 0.3355, -0.0981,  0.0045,\n\t\t\t\t\t 2.7592, 0.4372, -0.1122, -0.0065,\n\t\t\t\t\t 2.5995, 0.3015, -0.0961,  0.0119,\n\t\t\t\t\t 2.7083, 0.3969, -0.1309,  0.00123,\n\t\t\t\t\t 2.7709, 0.5099, -0.1646, -0.0165};\n\n\t//A routine to calculate the offset for the coefficients\n\tauto C = [&](size_t x_idx, size_t y_idx) { return coeffs + 4 * (x_idx + 3 * y_idx); };\n\n\t//A calculation of the function at the index point\n\tauto f = [&](const double* C) { return C[0] + logpL * (C[1] + logpL * (C[2] + logpL * C[3])); };\n\t\n\tconst double x = (Tgas - x_range[x_idx]) / (x_range[x_idx+1] - x_range[x_idx]);\n\tconst double y = (pw_frac   - y_range[y_idx]) / (y_range[y_idx+1] - y_range[y_idx]);\n\n\tdouble log10eT = \n\t  f(C(x_idx, y_idx)) * (1 - x) * (1 - y)\n\t  + f(C(x_idx + 1, y_idx)) * x * (1 - y)\n\t  + f(C(x_idx, y_idx + 1)) * (1 - x) * y\n\t  + f(C(x_idx + 1, y_idx + 1)) * x * y;\n\t\n\treturn std::pow(10, log10eT) / Tgas;\n      }\n\n      /* \\brief Hottel calculation for the absorptivity of gases\n\t containing CO2 and H2O.\n\n\t This assumes ideal gas behaviour!\n      */\n      \n      double Hottel_absorptivity(simcem::Model& gas, double pathLength, double Tsurface) {\n\t//Adjust pathlength, such that pL is scaled (this is a\n\t//horrible hack to adjust the pressure in the emissivity\n\t//calculations according to the ideal gas law!)\n\tconst double L = pathLength * Tsurface / gas.T();\n\tconst double e = Hottel_emissivity(gas, L, Tsurface);\n\treturn e * std::sqrt(gas.T() / Tsurface);\n      }\n\n      /*! \\brief Two-body radiation problem in third region.\n\t\n\t\\image html twobodygas_radiation_network.svg\n\t\n\tWe assume all resistances and the voltages \\f$V_a\\f$, \\f$V_b\\f$, and \\f$V_c\\f$ are known.\n\tThe total currents at the nodes \\f$\\alpha\\f$ and \\f$\\beta\\f$ must sum to zero, thus:\n\t\n\t\\f[\n\t(V_a - V_\\alpha)R^{-1}_1 + (V_\\beta - V_\\alpha)R^{-1}_2 + (V_c - V_\\alpha)R^{-1}_3 = 0\n\t\\f]\n\t\\f[\n\t(V_b - V_\\beta)R^{-1}_4 + (V_\\alpha - V_\\beta)R^{-1}_2 + (V_c - V_\\beta)R^{-1}_5 = 0\n\t\\f]\n\t\n\tSolving for \\f$V_\\beta\\f$:\n\t\n\t\\f[\n\tV_\\beta = \\frac{m_2\\,c_2+c_1}{1-m_1\\,m_2}\n\t\\f]\n\t\\f[\n\tV_\\alpha = m_2\\, V_\\beta + c_2\n\t\\f]\n\t\n\twhere:\n\t\\f[\n\tm_1 = \\frac{1}{R_2^{-1}}\\left(R_1^{-1} + R_2^{-1} + R_3^{-1}\\right)\n\t\\f]\n\t\\f[\n\tc_1 = -V_a\\frac{R_1^{-1}}{R_2^{-1}} -V_c\\frac{R_3^{-1}}{R_2^{-1}}\n\t\\f]\n\t\n\t\\f[\n\tm_2 = \\frac{1}{R_2^{-1}}\\left(R_4^{-1} + R_2^{-1} + R_5^{-1}\\right)\n\t\\f]\n\t\\f[\n\tc_2 = -V_b\\frac{R_4^{-1}}{R_2^{-1}} -V_c\\frac{R_5^{-1}}{R_2^{-1}}\n\t\\f]\n\n\tThe currents are returned as follows:\n\t\\f[\n\tI_a = R_1^{-1}(V_\\alpha-V_a) \\qquad I_b = R_4^{-1}(V_\\beta-V_b) \\qquad I_c = R_3^{-1}(V_\\alpha-V_c) + R_5^{-1}(V_\\beta-V_c)\n\t\\f]\n\t\n\tAs a test, we should have \\f$I_a+I_b+I_c=0\\f$.\n      */\n      std::array<double, 3> twobodygas_network(const std::array<double, 3> V, const std::array<double, 5> Rinv) {\n\tconst double m1 = (Rinv[0]+Rinv[1]+Rinv[2]) / Rinv[1];\n\tconst double m2 = (Rinv[3]+Rinv[1]+Rinv[4]) / Rinv[1];\n\tconst double c1 = -V[0]*Rinv[0]/Rinv[1] - V[2] * Rinv[2] / Rinv[1];\n\tconst double c2 = -V[1]*Rinv[3]/Rinv[1] - V[2] * Rinv[4] / Rinv[1];\n\tconst double Vbeta = (m1 * c2 + c1) / (1 - m1 * m2);\n\tconst double Valpha = m2 * Vbeta + c2;\n\n\treturn std::array<double, 3>{\n\t  {Rinv[0] * (Valpha - V[0]),\n\t      Rinv[3] * (Vbeta - V[1]),\n\t      Rinv[2] * (Valpha - V[2]) + Rinv[4] * (Vbeta - V[2])\n\t      }\n\t};\n      }\n    }\n\n    /*! \\brief Specialised expressions for heat transfer in kilns. */\n    namespace kiln {\n      /*! \\brief Nusselt number correlation for heat transfer between\n\ta cylindrical wall and a granular bed of material which\n\tcovers it.\n\n\tThis is taken from Li_etal_2005. The Nusselt number uses the\n\tgas thermal conductivity and particle diameter as\n\tnormalisation factors.\n\n\t\\param Peclet The Peclet number for the bed (see Pe_bed_wall_Li_etal_2005).\n\t\\param chi A fitting parameter, which appears to be around 0.1, but is in the range 0.096-0.198.\n      */\n      double Nu_bed_wall_Li_etal_2005(const double Peclet, const double chi = 0.1) {\n\treturn 1 / (chi + 0.5 * std::sqrt(Database::pi / Peclet));\n      }\n\n      \n      /*! \\brief Peclet number for Heat transfer between a cylindrical\n\twall and a granular bed of material which covers it.\n\n\tThis is taken from Li_etal_2005.\n\n\t\\param dp Particle diameter \\f$d_p\\f$.\n\t\\param kg Gas thermal conductivity \\f$k_g\\f$.\n\t\\param kb Solid bed thermal conductivity \\f$k_b\\f$.\n\t\\param vol_Cp Solid bed volumetric heat capacity, \\f$\\rho_b\\,c_{p,b}\\f$.\n\t\\param centralangle Central angle of bed, \\f$\\theta\\f$.\n\t\\param angularvel Angular velocity of cylinder, \\f$\\omega\\f$.\n      */\n      double Pe_bed_wall_Li_etal_2005(const double dp, const double kg, const double kb,\n\t\t\t\t      const double vol_Cp, const double centralangle, const double angularvel ) {\n\treturn std::pow(dp/kg, 2) * vol_Cp * kb * angularvel / centralangle;\n      }\n\n      /*! \\brief Heat transfer coefficient between a wall and a\n\tgranular bed of material which covers it.\n\n\tThis is taken from Li_etal_2005.\n\n\t\\param dp Particle diameter \\f$d_p\\f$.\n\t\\param kg Gas thermal conductivity \\f$k_g\\f$.\n\t\\param kb Solid bed thermal conductivity \\f$k_b\\f$.\n\t\\param vol_Cp Solid bed volumetric heat capacity, \\f$\\rho_b\\,c_{p,b}\\f$.\n\t\\param centralangle Central angle of bed, \\f$\\theta\\f$.\n\t\\param angularvel Angular velocity of cylinder, \\f$\\omega\\f$.\n\t\\param chi A fitting parameter, which appears to be around 0.1, but is in the range 0.096-0.198.\n      */\n      double h_bed_wall_Li_etal_2005(const double dp, const double kg, const double kb,\n\t\t\t\t     const double vol_Cp, const double centralangle, const double angularvel,\n\t\t\t\t     const double chi = 0.1) {\n\tconst double Pe = Pe_bed_wall_Li_etal_2005(dp, kg, kb, vol_Cp, centralangle, angularvel);\n\tconst double Nu = Nu_bed_wall_Li_etal_2005(Pe, chi);\n\treturn Nu * kg / dp;\n      }\n\n      /*! \\brief Gas-wall Nusselt number for rotary kilns.\n\t\n\t\\f[\n\t\\text{Nu}_{g-ew} = 1.54\\,\\text{Re}_g^{0.575}\\,\\text{Re}_\\omega^{-0.292}\n\t\\f]\n\t\n\tThis is taken from Eq.9 of Li_etal_2005. This requires\n\t\\f$1600<\\text{Re}_g<7800\\f$ and \\f$20<\\text{Re}_\\omega<800\\f$.\n\t\n\t\\param Re_g Reynolds number for the gas, \\f$\\text{Re}_g\\f$, using the normal hydraulic diameter.\n\t\\param Re_w Angular rotation Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n      */\n      double Nu_gas_wall_Li_etal_2005(const double Re_g, const double Re_w) {\n#ifndef NDEBUG\n\t//if (!((1600 < Re_g) && (Re_g < 7800)))\n\t//stator_throw() << \"Out of range for Re_g \" << Re_g;\n\n\t//if (!((20 < Re_w) && (Re_w < 800)))\n\t//stator_throw() << \"Out of range for Re_w \" << Re_w;\n#endif\n\n\treturn 1.54 * std::pow(Re_g, 0.575) * std::pow(Re_w, -0.292);\n      }\n\n      /*! \\brief Gas-bed Nusselt number for rotary kilns.\n\n\t\\f[\n\t\\text{Nu}_{g-eb} = 0.46\\,\\text{Re}_g^{0.535}\\,\\text{Re}_\\omega^{0.104}\\,\\eta^{-0.341}\n\t\\f]\n\n\tThis is taken from Eq.8 of Li_etal_2005. This requires\n\t\\f$1600<\\text{Re}_g<7800\\f$ and \\f$20<\\text{Re}_\\omega<800\\f$.\n\t\n\t\\param Re_g Reynolds number for the gas, \\f$\\text{Re}_g\\f$, using the normal hydraulic diameter.\n\t\\param Re_w Angular rotation Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n\t\\param bed_frac Fraction of kiln filled with the bed, \\f$\\eta\\f$.\n      */\n      double Nu_gas_bed_Li_etal_2005(const double Re_g, const double Re_w, const double bed_frac) {\n#ifndef NDEBUG\n//\tif (!((1600 < Re_g) && (Re_g < 7800)))\n//\t  stator_throw() << \"Out of range for Re_g \" << Re_g;\n//\n//\tif (!((20 < Re_w) && (Re_w < 800)))\n//\t  stator_throw() << \"Out of range for Re_w \" << Re_w;\n#endif\n\treturn 0.46 * std::pow(Re_g, 0.535) * std::pow(Re_w, 0.104) * std::pow(bed_frac, -0.341);\n      }\n\n      \n      /*! \\brief Correlation for mean beam length in a rotary kiln.\n\t\n\tThis is taken from Eq.50 of Gorog_etal_1981.\n\n\t\\param R Kiln radius.\n\t\\param h Bed height (at its deepest/central point);\n      */\n      double pathLength(const double R, const double h) {\n\treturn 2 * R * 0.95 * (1 - h / (2 * R));\n      }\n    }\n  }\n\n  \n  \n  namespace kiln {\n    struct Slice {\n      Slice(simcem::shared_ptr<simcem::ModelIdealGasTp> gas,\n\t    simcem::shared_ptr<simcem::ModelIncompressible> solid,\n\t    double Z = 0\n\t    ):\n\t_Z(Z)\n      {\n\t//Here we copy the phases to ensure the slice has a unique copy\n\t_gas = simcem::shared_ptr<simcem::ModelIdealGasTp>(new simcem::ModelIdealGasTp(*gas));\n\t_solid = simcem::shared_ptr<simcem::ModelIncompressible>(new simcem::ModelIncompressible(*solid));\n\n\t_T_ext_shell = 0.75*298.15 + 0.25 * _gas->T();\n\t_T_wall = 0.25*298.15 + 0.75 * _gas->T();\n      }\n\n      Slice(const Slice& s):\n\t_gas_k(s._gas_k),\n\t_gas_visc(s._gas_visc),\n\t_gas_density(s._gas_density),\n\t_gas_vel(s._gas_vel),\n\t_solid_k(s._solid_k),\n\t_solid_Cp(s._solid_Cp),\n\t_T_ext_shell(s._T_ext_shell),\n\t_T_wall(s._T_wall),\n\t_Z(s._Z)\n      {\n\t_gas = simcem::shared_ptr<simcem::ModelIdealGasTp>(new simcem::ModelIdealGasTp(*s._gas));\n\t_solid = simcem::shared_ptr<simcem::ModelIncompressible>(new simcem::ModelIncompressible(*s._solid));\n      }\n\n      Slice(const simcem::Components solid,\n\t    const double volAirFlow,\n\t    const double volGasFlow,\n\t    const double volO2Flow,\n\t    const double volSO2Flow,\n\t    const double Tsolid,\n\t    const double Tgas,\n\t    const double Z0,\n\t    const simcem::shared_ptr<simcem::Database> db):\n\t_Z(Z0)\n      {\n\tconst simcem::ModelIdealGasTp air(db, Database::getDryAir(), 298.15, 1.01325e5);\n\tconst simcem::Components inletair = Database::getDryAir() * ((volAirFlow) / air.V());\n    \n\tconst simcem::ModelIdealGasTp oxy(db, Components({{\"O2\",1}}), 298.15, 1.01325e5);\n\tconst simcem::Components inletoxy = Components({{\"O2\",1}}) * ((volO2Flow) / oxy.V());\n\t\n\tconst simcem::ModelIdealGasTp so2(db, Components({{\"SO2\",1}}), 298.15, 1.01325e5);\n\tconst simcem::Components inletso2 = Components({{\"SO2\",1}}) * ((volSO2Flow) / oxy.V());\n\n\tconst simcem::ModelIdealGasTp fuel(db, {{\"CH4\",100.0}}, 298.15, 1.01325e5);\n\tconst simcem::Components inletfuel = Components(fuel) * (volGasFlow / fuel.V());\n\n\tconst simcem::Components combustion_outputs({{\"H2O\",0}, {\"CO2\", 0}});\n\n\t_gas = simcem::shared_ptr<simcem::ModelIdealGasTp>(new simcem::ModelIdealGasTp(db, inletfuel + inletair + inletoxy + inletso2 + combustion_outputs, 298.15, 1.01325e5));\n\tsimcem::System sys(simcem::Objective_t::p, simcem::Objective_t::H, true);\n\tsys.push_back(_gas);\n\n\ttry {\n\t  sys.equilibrate();\n\t} catch (std::exception& e) {\n\t  std::cout << \"Failed to equilibrate initial gas \" << _gas->str() << std::endl;\n\t}\n\n\t_solid = simcem::shared_ptr<simcem::ModelIncompressible>(new simcem::ModelIncompressible(db, solid, 298.15, 1.01325e5, \"solid\"));\n\n\t//Value of Tgas=0 means retain the adiabatic temperature\n\tif (Tgas != 0)\n\t  _gas->set(simcem::Objective_t::T, Tgas, simcem::Objective_t::p);\n\t\n\t_solid->set(simcem::Objective_t::T, Tsolid, simcem::Objective_t::p);\n    \n\t_T_ext_shell = 0.75*298.15 + 0.25 * _gas->T();\n\t_T_wall = 0.25*298.15 + 0.75 * _gas->T();\n      }\n      \n      simcem::shared_ptr<simcem::ModelIdealGasTp> _gas;\n      simcem::shared_ptr<simcem::ModelIncompressible> _solid;\n\n      /*! \\brief Precompute a few frequently used values for the slice. */\n      void compute_properties(const double gas_area, const double solid_k) {\n\t//Gas properties\n\tstd::tie(_gas_visc, _gas_k) = simcem::trans::NASA_transport(_gas);\n\t_gas_density = _gas->M() / _gas->V();\n\n\t//Solid properties\n\t_solid_Cp = _solid->Cp() / _solid->M();\n\t_gas_vel = _gas->V() / gas_area;\n\t_solid_k = solid_k;\n      }\n\t\n      //Cached values of the computed properties of the phases\n      double _gas_k;\n      double _gas_visc;\n      double _gas_density;\n      double _gas_vel;\n      double _solid_k;\n      double _solid_Cp;\n      double _T_ext_shell;\n      double _T_wall;\n      double _Z;\n    };\n        \n    /*! \\brief Abstract base class for models describing the solid bed dynamics.*/\n    class BedModel {\n    public:\n      virtual double bedHeight(const Slice& slice) const = 0;\n    };\n\n    class ConstantHeightBed : public BedModel {\n    public:\n      ConstantHeightBed(double height):\n\t_height(height)\n      {}\n\n      virtual double bedHeight(const Slice& slice) const { return _height; }\n\n      static simcem::shared_ptr<BedModel> fromFillingFraction(double frac, double kiln_radius) {\n\tconst double pi = boost::math::constants::pi<double>();\n\t\n\tstd::pair<double, double> central_angle_limits\n\t  = boost::math::tools::bisect([pi, frac](double x) {return x - std::sin(x) - 2 * pi * frac;},\n\t\t\t\t       0.0, 2 * pi,\n\t\t\t\t       boost::math::tools::eps_tolerance<double>(10));\n\n\tdouble central_angle = (central_angle_limits.first + central_angle_limits.second) / 2;\n\n\treturn simcem::shared_ptr<BedModel>\n\t  (new ConstantHeightBed(kiln_radius * (1.0 - std::cos(central_angle/2))));\n      }\n      \n    protected:\n      double _height;\n    };\n\n\n    /*! \\brief A process model for a rotary kiln.\n     \n      \\image html kiln_balance.svg\n      \n      Performing a differential balance of mass over a phase \\f$\\alpha\\f$:\n      \\f[\n      \\Delta z\\,A_\\alpha\\left(\\rho_\\alpha(z,\\,t+\\Delta t)-\\rho_\\alpha(z,\\,t)\\right)=  \\Delta t\\,A_\\alpha\\left(\\dot{m}_\\alpha\\left(z\\right)-\\dot{m}_\\alpha\\left(z+\\Delta z\\right)\\right) + \\Delta t\\,\\Delta z\\,\\dot{m}_{\\beta\\to\\alpha}\n      \\f]\n\n      where \\f$\\dot{m}_{\\beta\\to\\alpha}\\f$ is the rate of mass\n      transfer between the two phases per unit length of kiln and\n      conservation of mass requires\n      \\f$\\dot{m}_{\\beta\\to\\alpha}=-\\dot{m}_{\\alpha\\to\\beta}\\f$. Dividing\n      by \\f$\\Delta t\\,\\Delta z\\f$ and taking the limit as they go to\n      zero:\n\n      \\f[\n      \\frac{{\\rm d}\\,A_\\alpha\\,\\rho_\\alpha}{{\\rm d}t}= -\\frac{{\\rm d} A_\\alpha\\,\\dot{m}_\\alpha}{{\\rm d}z} + \\dot{m}_{\\beta\\to\\alpha}\n      \\f]\n\n      For enthalpy:\n      \\f[\n      \\Delta z\\,A_\\alpha\\left(\\rho_\\alpha(z,\\,t+\\Delta t)\\,h_\\alpha(z,\\,t+\\Delta t)-\\rho_\\alpha(z,\\,t)\\,h_\\alpha(z,\\,t)\\right)=  \\Delta t\\,A_\\alpha\\left(\\dot{m}_\\alpha\\left(z\\right)\\,h_\\alpha(z,\\,t)-\\dot{m}_\\alpha\\left(z+\\Delta z\\right)\\,h_\\alpha(z+\\Delta z,\\,t)\\right) + \\Delta t\\,\\Delta z\\,Q_{\\to\\alpha}\n      \\f]\n      where \\f$Q_{\\to\\alpha}\\f$ is the heat transfer rate to phase \\f$\\alpha\\f$ per unit length of kiln. Again, a differential form results:\n      \\f[\n      \\frac{{\\rm d}\\,A_\\alpha\\,\\rho_\\alpha\\,h_\\alpha}{{\\rm d}t}= -\\frac{{\\rm d}\\,A_\\alpha\\,\\dot{m}_\\alpha\\,h_\\alpha}{{\\rm d}z} + Q_{\\to\\alpha}\n\n      \n      \\f]\n    */\n    class Kiln {\n    public:\n      struct Layer {\n\tstd::string _material;\n\tdouble _thickness;\n\tsym::Expr _k;\n      };\n    \n      Kiln(double RPM, double innerRadius, double length,\n\t   double particle_diam,\n\t   double shell_emissivity,\n\t   double bed_emissivity,\n\t   double wall_emissivity,\n\t   double solid_density,\n\t   double bed_void_frac,\n\t   sym::Expr solid_k,\n\t   simcem::shared_ptr<Database> db\n\t   ):\n\t_RPM(RPM), _innerRadius(innerRadius), _length(length),\n\t_particle_diam(particle_diam),\n\t_shell_emissivity(shell_emissivity),\n\t_bed_emissivity(bed_emissivity),\n\t_wall_emissivity(wall_emissivity),\n\t_solid_density(solid_density),\n\t_bed_void_frac(bed_void_frac),\n\t_solid_k(solid_k),\n\t_ambient(new simcem::ModelIdealGasTp(db, Database::getDryAir(), 298.15, 1.01325e5))\n      {}\n\n      void setFixedHeightBedModel(const double solidLoading) {\n\t_bedModel = simcem::kiln::ConstantHeightBed::fromFillingFraction(solidLoading, _innerRadius);\n      }\n      \n      void add_layer(std::string material, double thickness, sym::Expr k) {\n\t_layers.push_back(Layer{material, thickness, k});\n      }\n      \n      double solid_k(const double T) {\n\treturn sym::fast_sub(_solid_k, sym::Var<sym::vidx<'T'>>() = T);\n      }\n\n      double innerRadius() const { return _innerRadius; }\n    \n      double outerRadius() const {\n\treturn _innerRadius + std::accumulate(_layers.begin(), _layers.end(), 0.0, [](double a, Layer b){ return a + b._thickness; });\n      }\n\n      /*! \\brief Conductive heat transfer resistance in the kiln wall. */\n      double R_wall_shell(const Slice& slice) const {\n\tdouble Ri = _innerRadius;\n\tdouble Rtotal = 0;\n\tfor (const auto& layer : _layers) {\n\t  const double Ro = Ri + layer._thickness;\n\t  const double k = sym::fast_sub(layer._k, sym::Var<sym::vidx<'T'>>() = slice._T_wall);\n\t  Rtotal += std::log(Ro / Ri) / (2 * simcem::Database::pi * k);\n\t  Ri = Ro;\n\t};\n\n\treturn Rtotal;\n      }\n      \n      const BedModel& bedModel() const { return *_bedModel; }\n\n      const std::vector<Slice>& slices() const { return _slices; }\n      std::vector<Slice>& slices() { return _slices; }\n      \n      /*! \\brief The chord length of the bed.\n\t\n\tThe chord length can be calculated in two ways:\n\t\\f[\n\tL_{chord}= 2\\,R\\,\\sin(\\theta/2) = 2\\sqrt{h(2*R-h)}\n\t\\f]\n\n\tThe latter is used here.\n      */\n      double chordLength(const Slice& slice) const {\n\tconst double h = _bedModel->bedHeight(slice);\n\treturn 2 * std::sqrt(h * (2 * _innerRadius - h));\n      }\n\n      /*! \\brief The central angle is the radians of the cylinder\n\tcovered by the bed.\n      */\n      double centralAngle(const Slice& slice) const {\n\treturn 2 * std::asin(chordLength(slice) / 2 / _innerRadius);\n      }\n\n      double bedArea(const Slice& slice) const {\n\tconst double cAngle = centralAngle(slice);\n\treturn 0.5 * _innerRadius * _innerRadius * (cAngle - std::sin(cAngle));\n      }\n\n      double kilnArea() const {\n\treturn simcem::Database::pi * _innerRadius * _innerRadius;\n      }\n\n      double gasArea(const Slice& slice) const {\n\treturn kilnArea() - bedArea(slice);\n      }\n\n      double gasPerimeter(const Slice& slice) const {\n\treturn (2 * simcem::Database::pi - centralAngle(slice)) * _innerRadius + chordLength(slice);\n      }\n      \n      double hydraulicDiameter(const Slice& slice) const {\n\treturn 4 * gasArea(slice) / gasPerimeter(slice);\n      }\n\n      double exposedWallPerimeter(const Slice& slice) const {\n\tconst double pi = boost::math::constants::pi<double>();\n\tconst double cAngle = centralAngle(slice);\n\treturn (2 * pi - cAngle) * _innerRadius;\n      }\n\n      double coveredWallPerimeter(const Slice& slice) const {\n\tconst double cAngle = centralAngle(slice);\n\treturn cAngle * _innerRadius;\n      }\n      \n      double angular_vel() const {\n\treturn _RPM / 60.0 * 2 * simcem::Database::pi;\n      }\n      \n      /*! \\brief Heat transfer coefficient between the bed and the wall it covers, \\f$h_{cw-s}\\f$.\n       */\n      double h_bed_wall(const Slice& slice) const {\n\tconst double Cp_per_vol = slice._solid_Cp * _solid_density;\n\tconst double kb = HT::conduction::maxwell(slice._gas_k, slice._solid_k, _bed_void_frac);\n\treturn simcem::HT::kiln::h_bed_wall_Li_etal_2005(_particle_diam, slice._gas_k, kb,\n\t\t\t\t\t\t\t Cp_per_vol, centralAngle(slice), angular_vel());\n      }\n\n      /*! \\brief \\f$Q_{w\\to s}^{cd}\\f$ */\n      double Q_wall_bed_cd(const Slice& slice) const {\n\treturn h_bed_wall(slice) * coveredWallPerimeter(slice) * (slice._T_wall - slice._solid->T());\n      }\n      \n      /*! \\brief Free gas Reynolds number, \\f$\\text{Re}_g\\f$.\n\t\n\tThis is the Reynolds number for the gas above the solid bed.\n\t\n\t\\f[\n\t\\text{Re}_g = \\frac{\\rho_g\\,v_g\\,D_e}{\\mu_g}\n\t\\f]\n\n\twhere \\f$D_e\\f$ is the hydraulic diameter.\n      */\n      double Re_g(const Slice& slice) const {\n\tconst double De = hydraulicDiameter(slice);\n\treturn slice._gas_density * slice._gas_vel * De / slice._gas_visc;\n      }\n      \n      /*! \\brief Rotational gas Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n\t\n\tThis is the Reynolds number for the gas within the bed itself.\n\t\n\t\\f[\n\t\\text{Re}_\\omega = \\frac{\\rho_g\\,\\omega\\,D_e^2}{\\mu_g}\n\t\\f]\n\n\twhere \\f$D_e\\f$ is the hydraulic diameter. An example of this\n\tdefinition is given just below Eq.9 in Li_etal_2005.\n      */\n      double Re_w(const Slice& slice) const {\n\tconst double De = hydraulicDiameter(slice);\n\treturn std::pow(De, 2) * angular_vel() * slice._gas_density / slice._gas_visc;\n      }\n      \n      /*! \\brief Heat transfer coefficient between the bed and the gas. \n       */\n      double h_gas_bed(const Slice& slice) const {\n\tconst double bed_frac = bedArea(slice) / kilnArea();\n\tconst double Nu = simcem::HT::kiln::Nu_gas_bed_Li_etal_2005(Re_g(slice), Re_w(slice), bed_frac);\n\tconst double De = hydraulicDiameter(slice);\n\treturn Nu * slice._gas_k / De;\n      }\n\n      /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n      double Q_gas_bed_cv(const Slice& slice) const {\n\treturn h_gas_bed(slice) * chordLength(slice) * (slice._gas->T() - slice._solid->T());\n      }\n      \n      /*! \\brief Heat transfer coefficient between the bed and the gas. \n       */\n      double h_gas_wall(const Slice& slice) const {\n\tconst double Nu = simcem::HT::kiln::Nu_gas_wall_Li_etal_2005(Re_g(slice), Re_w(slice));\n\tconst double De = hydraulicDiameter(slice);\n\treturn Nu * slice._gas_k / De;\n      }\n\n      /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n      double Q_gas_wall_cv(const Slice& slice) const {\n\treturn h_gas_wall(slice) * exposedWallPerimeter(slice) * (slice._gas->T() - slice._T_wall);\n      }\n      \n      double h_ext_amb_conv(const Slice& slice) const {\n\tdouble amb_visc, amb_k;\n\tstd::tie(amb_visc, amb_k) = simcem::trans::NASA_transport(_ambient);\n\tconst double amb_dens = _ambient->M() / _ambient->V();\n\t\n\tconst double outerDiam = 2 * outerRadius();\n\tconst double Pr = (_ambient->Cp() / _ambient->M()) * amb_visc / amb_k;\n\tconst double Tf = (_ambient->T() + slice._T_ext_shell) / 2.0;\n\tconst double Gr = simcem::Database::g * std::pow(amb_dens, 2) * (1/Tf) * std::abs(slice._T_ext_shell - _ambient->T()) * std::pow(outerDiam, 3) / std::pow(amb_visc, 2);\n\t  \n\tconst double Nu = simcem::HT::natConv::Nu_horiz_cyl(Gr, Pr);\n\n\treturn Nu * amb_k / outerDiam;\n      }\n\n      /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n      double R_sh_ext_cv(const Slice& slice) const {\n\treturn 1.0 / (h_ext_amb_conv(slice) * outerRadius() * 2 * simcem::Database::pi);\n      }\n\n      \n      /*! \\brief External radiative heat transfer coefficient. */\n      double h_ext_amb_rad(const Slice& slice) const {\n\treturn simcem::HT::rad::h_rad_simple(_ambient->T(), slice._T_ext_shell,\n\t\t\t\t\t     _shell_emissivity,\n\t\t\t\t\t     _ambient->db()->steffanBoltzmannConstant);\n      }\n      \n      double R_sh_ext_rd(const Slice& slice) const {\n\treturn 1.0 / (h_ext_amb_rad(slice) * outerRadius() * 2 * simcem::Database::pi);\n      }\n\n      double Q_w_ext(const Slice& slice) const {\n\tconst double Rtotal = R_wall_shell(slice) + 1.0 / (1.0 / R_sh_ext_rd(slice) + 1.0 / R_sh_ext_cv(slice));\n\n\treturn (slice._T_wall - _ambient->T()) / Rtotal;\n      }\n\n      double Q_w_sh(const Slice& slice) const {\n\treturn (slice._T_wall - slice._T_ext_shell) / R_wall_shell(slice);\n      }\n      \n      /*! \\brief One-zone radiative network for a kiln slice.\n\n\tThe wall and bed are considered as two thermally homogeneous\n\tgray bodies which exchange radiative heat through a gray gas\n\t(gray implying that we are ignoring the frequency aspects of\n\tradiation). \n\n\tThe same network as Fig.6 in Li_etal_2005, but this is also\n\tFig.8-39 in JP Holman's Heat Transfer, 10th Ed.\n\t\n\t\\image html kiln_radiation_network.svg\n\t\n\tThe electrical resistance analogy is then used. The junctions\n\t(circles) are annotated with their \"potentials\"\n\t(\\f$E_{bed},\\,J_b,\\,J_w,\\,E_{gas}\\f$) whereas the other\n\tannotations are resistances.  As the two nodes \\f$J_b\\f$ and\n\t\\f$J_w\\f$ are merely \"virtual\" junctions they cannot\n\taccumulate heat/current, so their heat/current must sum to\n\tzero:\n\n\t\\f[\n\t\\frac{E_{bed}-J_b}{\\left(1-\\varepsilon_b\\right)\\varepsilon_b^{-1}\\,A_b^{-1}} + \\frac{J_w-J_b}{\\tau_g^{-1}\\,F_{bw}^{-1}\\,A_b^{-1}} + \\frac{E_{gas}-J_b}{\\varepsilon_g^{-1}\\,F_{bg}^{-1}\\,A_b^{-1}}=0\n\t\\f]\\f[\n\t\\frac{E_{wall}-J_w}{\\left(1-\\varepsilon_w\\right)\\varepsilon_w^{-1}\\,A_w^{-1}} + \\frac{J_b-J_w}{\\tau_g^{-1}\\,F_{bw}^{-1}\\,A_b^{-1}} + \\frac{E_{gas}-J_w}{\\varepsilon_g^{-1}\\,F_{wg}^{-1}\\,A_w^{-1}}=0\n\t\\f]\n\n\tThe emission fluxes (potentials) are already known:\n\t\\f[\n\tE_{bed} = \\sigma\\,T^4_{bed} \\qquad E_{gas} = \\sigma\\,T^4_{gas} \\qquad E_{wall} = \\sigma\\,T^4_{wall}\n\t\\f]\n\n\tThus the task is to determine the radiosities \\f$J_{bed}\\f$\n\tand \\f$J_{wall}\\f$ by solving the two simultaneous equations\n\tabove. Once this is complete the heat fluxes/currents from the wall and\n\tbed are obtainable from the network's potentials and\n\tresistances:\n\t\n\t\\f[\n\tq_{bed} = \\frac{E_{bed}-J_b}{\\left(1-\\varepsilon_b\\right)^{-1}\\varepsilon_b\\,A_b}\n\t\\qquad\n\tq_{wall} = \\frac{E_{wall}-J_w}{\\left(1-\\varepsilon_w\\right)^{-1}\\varepsilon_w\\,A_w}\n\t\\f]\n\t\\f[\n\tq_{gas} = \\frac{J_b-E_{gas}}{\\varepsilon_g^{-1}\\,F_{bg}^{-1}\\,A_b^{-1}} + \\frac{J_w-E_{gas}}{\\varepsilon_g^{-1}\\,F_{wg}^{-1}\\,A_w^{-1}} = -q_{bed} -q_{wall}\n\t\\f]\n\tAlthough the reciprocity relationship\n\t(\\f$F_{12}A_{1}=F_{21}A_{2}\\f$) and summation rule (\\f$\\sum_b\n\tF_{ab}=1\\f$) allow us to change the view factors, the\n\tselection above has been made as \\f$F_{bw}=F_{bg}=F_{wg}=1\\f$\n\tthus these can be eliminated.  For simplicity it is assumed\n\tthat spectral effects on the gas absorptivity (resulting from\n\tthe different temperatures of the wall and gas) can be ignored\n\tand \\f$\\tau_g=1-\\varepsilon_g\\f$. The areas are given in terms\n\tof per unit length of kiln, thus\n\t\\f$A_w=R\\left(2\\,\\pi-\\theta\\right)\\f$ and \\f$A_b\\f$ is the\n\tchord length (Li_etal_2005 incorrectly uses the covered\n\tperimeter of the inner kiln surface). All the resistance terms\n\tcan then be determined a priori.\n\t\n      */\n      std::array<double, 3> rad_fluxes(const Slice& slice) const {\n\tconst double Aw = exposedWallPerimeter(slice);\n\tconst double Abed = chordLength(slice);\n\tconst double h = _bedModel->bedHeight(slice);\n\tconst double pathLength = simcem::HT::kiln::pathLength(_innerRadius, h);\n\tconst Model& gas = *slice._gas;\n\tconst Model& solid = *slice._solid;\n\tconst double e_gas = simcem::HT::rad::Hottel_emissivity(gas, pathLength);\n\tconst double sigma = gas.db()->steffanBoltzmannConstant;\n\n\tconst std::array<double, 3> V = {{\n\t    sigma * std::pow(solid.T(), 4),\n\t    sigma * std::pow(slice._T_wall, 4),\n\t    sigma * std::pow(gas.T(), 4)\n\t  }};\n\t\n\tconst std::array<double, 5> Rinv = {{\n\t    _bed_emissivity * Abed / (1 - _bed_emissivity),\n\t    (1 - e_gas) * Abed,\n\t    e_gas * Abed,\n\t    _wall_emissivity * Aw / (1 - _wall_emissivity),\n\t    e_gas * Aw\n\t  }};\n\t\n\treturn simcem::HT::rad::twobodygas_network(V, Rinv);\n      }\t\n\n      void printFluxes(const Slice& slice) const {\n\tauto rad = rad_fluxes(slice);\n\tconst double Q_s_rad = rad[0], Q_w_rad = rad[1], Q_g_rad = rad[2];\n\t\n\tstd::cout << \"Z=\" << slice._Z << \", Tg=\" << slice._gas->T() << \", Ts=\" << slice._solid->T() << \", Tw=\" << slice._T_wall << \", Tshell=\" << slice._T_ext_shell << std::endl;\n\tstd::cout << \"Q_s_rad=\" << Q_s_rad << \", Q_w_rad=\"<<Q_w_rad<<\", Q_g_rad=\"<<Q_g_rad<< std::endl;\n\tstd::cout << \"Q_gs_cv=\" << Q_gas_bed_cv(slice) << std::endl;\n\tstd::cout << \"Q_ws_cd=\" << Q_wall_bed_cd(slice) << std::endl;\n\tstd::cout << \"Q_gw_cv=\" << Q_gas_wall_cv(slice) << std::endl;\n\tstd::cout << \"Q_w_sh=\" << Q_w_sh(slice) << std::endl;\n\tstd::cout << \"Q_w_ext=\" << Q_w_ext(slice) << std::endl;\n      }\n\n      \n      /*! \\brief Solves the system as a steady-state inert system.\n\n\tThe differential equations to be solved are:\n\t\n\t\\f[\n\t\\dot{m}_s\\,c_{p,s} \\frac{\\partial T_s}{\\partial z} = Q_{g\\to s}^{cv}+Q_{w\\to s}^{cd}+Q_{g\\to s}^{rd}+Q_{w\\to s}^{rd}\n\t\\f]\n\t\\f[\n\t\\dot{m}_g\\,c_{p,g} \\frac{\\partial T_g}{\\partial z} = -\\left(Q_{g\\to s}^{cv}+Q_{g\\to w}^{cv}+Q_{g\\to s}^{rd}+Q_{g\\to w}^{rd}\\right)\n\t\\f]\n\n\tThese equations require a solution for the wall \\f$T_w\\f$ and\n\tshell \\f$T_{shell}\\f$ temperatures, which are solved from the\n\tfollowing algebraic equations:\n\n\t\\f[\n\tQ_{sh\\to ext} = Q_{w\\to sh}\n\t\\f]\n\t\\f[\n\tQ_{w\\to sh} = Q_{g\\to w}^{rd} + Q_{g\\to w}^{cv} - Q_{w\\to s}^{rd} - Q_{w\\to s}^{cd}\n\t\\f]\n      */\n      void solve_SS_inert(Slice slice_in, std::vector<realtype> stop_points, bool store_intermediate) {\n\tusing namespace sundials;\n\t\n\t//For debugging, output all kiln settings\n\t//std::cout << \"Kiln setup\" << std::endl;\n\t//std::cout << _RPM << \" \"\n\t//\t  << _innerRadius << \" \"\n\t//\t  << _length << \" \"\n\t//\t  << _particle_diam << \" \"\n\t//\t  << _shell_emissivity << \" \"\n\t//\t  << _bed_emissivity << \" \"\n\t//\t  << _wall_emissivity << \" \"\n\t//\t  << _solid_density << \" \"\n\t//\t  << _solid_k << \" \"\n\t//\t  << _bedModel << \" \"\n\t//\t  << _ambient << \" \"\n\t//\t  << std::endl;\n\t//\n\t//for (const auto& layer : _layers)\n\t//  std::cout << \"Layer: \" << layer._thickness << \" \" << layer._k << std::endl;\n\t//\n\t// TODO: add slice data output\n\t\n\tstruct SolverData {\n\t  Kiln& kiln;\n\t  Slice slice;\n\n\t  void save_state(Serial_Vector& T) const {\n\t    T[0] = slice._gas->T();\n\t    T[1] = slice._solid->T();\n\t    T[2] = slice._T_wall;\n\t    T[3] = slice._T_ext_shell;\n\t  }\n\n\t  void load_state(Serial_Vector& T, const double Z) {\n\t    slice._gas->set  (simcem::Objective_t::T, T[0], simcem::Objective_t::p);\n\t    slice._solid->set(simcem::Objective_t::T, T[1], simcem::Objective_t::p);\n\t    slice._T_wall = T[2];\n\t    slice._T_ext_shell = T[3];\n\t    slice.compute_properties(kiln.gasArea(slice), kiln.solid_k(T[1]));\n\t    slice._Z = Z;\n\t  }\n\n\t  static int resrob(realtype Z, N_Vector T_, N_Vector Tprime_, N_Vector residuals_, void *user_data) {\n\t    Serial_Vector T(T_), Tprime(Tprime_), residuals(residuals_);\n\t    SolverData& data = *((SolverData*)user_data);\n\t    \n\t    //Load the slice state\n\t    data.load_state(T, Z);\n\n\t    auto rad = data.kiln.rad_fluxes(data.slice);\n\t    const double Q_s_rad = rad[0], Q_w_rad = rad[1], Q_g_rad = rad[2];\n\n\t    //The solid energy balance\n\t    //-ve as we're starting at the hot end\n\t    //The gas energy balance\n\t    residuals[0] = -(-data.kiln.Q_gas_bed_cv(data.slice) - data.kiln.Q_gas_wall_cv(data.slice) + Q_g_rad) - data.slice._gas->Cp() * Tprime[0];\n\n\t    residuals[1] = (data.kiln.Q_gas_bed_cv(data.slice) + data.kiln.Q_wall_bed_cd(data.slice) + Q_s_rad) - data.slice._solid->Cp() * Tprime[1];\n\t    \n\t    //The shell-wall relationship\n\t    residuals[2] = Q_w_rad + data.kiln.Q_gas_wall_cv(data.slice) - data.kiln.Q_wall_bed_cd(data.slice) - data.kiln.Q_w_ext(data.slice);\n\t    residuals[3] = data.kiln.Q_w_sh(data.slice) - data.kiln.Q_w_ext(data.slice);\n\n\t    return 0;\n\t  }\n\t};\n\t\n\t//Set up the system data;\n\tSolverData data{*this, slice_in};\n\t\n\tSerial_Vector T(4);\n\tdata.save_state(T);\n\n\tSerial_Vector Tprime(4);\n\tTprime[0] = 0;\n\tTprime[1] = 0;\n\tTprime[2] = Tprime[3] = 0;\n\n\tIDA solver(slice_in._Z, SolverData::resrob, T, Tprime);\n\t\n\tsolver.setTol(1e-4, 1e-2);\n\tsolver.setUserData(data);\n\tsolver.denseSolver(T);\n\n\tSerial_Vector Id(4);\n\tId[0] = Id[1] = 1.0; //Differential \n\tId[2] = Id[3] = 0.0; //Algebraic\n\tsolver.setId(Id);\n\n\tsolver.calcIC(IDA_YA_YDP_INIT, _length);\n\n\tSerial_Vector T_interp(4);\n\tSerial_Vector Tprime_interp(4);\n\n\tstd::sort(stop_points.begin(), stop_points.end());\n\tauto stop_it = stop_points.begin();\n\t\n\twhile (stop_it != stop_points.end()) {\n\t  const realtype Znext = solver.solve(*stop_it, T, Tprime, IDA_ONE_STEP);\n\n\t  while (Znext > *stop_it) {\n\t    solver.interpolate(*stop_it, T_interp, 0);\n\t    solver.interpolate(*stop_it, Tprime_interp, 1);\n\t    data.load_state(T_interp, *stop_it);\n\t    _slices.push_back(data.slice);\n\t    if (++stop_it == stop_points.end()) break;\n\t  }\n\n\t  if (store_intermediate && (stop_it != stop_points.end())) {\n\t    data.load_state(T, Znext);\n\t    _slices.push_back(data.slice);\n\t  }\n\t}\n      }\n\n      std::vector<Slice>& getSlices() { return _slices; }\n\n      double length() const { return _length; }\n      \n    protected:\n      \n      const double _RPM;\n      const double _innerRadius;\n      const double _length;\n      const double _particle_diam;\n      const double _shell_emissivity;\n      const double _bed_emissivity;\n      const double _wall_emissivity;\n      const double _solid_density;\n      const double _bed_void_frac;\n\n      sym::Expr _solid_k;\n      \n      std::vector<Layer> _layers;\n      simcem::shared_ptr<BedModel> _bedModel;\n      simcem::shared_ptr<simcem::ModelIdealGasTp> _ambient;      \n      std::vector<Slice> _slices;\n    };\n  }\n}\n", "meta": {"hexsha": "791ef700042804df3a5f2abe46893857250a97b6", "size": 37266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simcem/simcem/kiln.hpp", "max_stars_repo_name": "toastedcrumpets/SimCem", "max_stars_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T17:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T14:53:37.000Z", "max_issues_repo_path": "src/simcem/simcem/kiln.hpp", "max_issues_repo_name": "toastedcrumpets/SimCem", "max_issues_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "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/simcem/simcem/kiln.hpp", "max_forks_repo_name": "toastedcrumpets/SimCem", "max_forks_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "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.2897727273, "max_line_length": 305, "alphanum_fraction": 0.6451188751, "num_tokens": 12196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6552122363315641}}
{"text": "#include <learning/independences/continuous/linearcorrelation.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nusing boost::math::cdf, boost::math::complement;\nusing boost::math::students_t_distribution;\n\nnamespace learning::independences::continuous {\n\ndouble cor_pvalue(double cor, int df) {\n    double statistic = cor * sqrt(df) / sqrt(1 - cor * cor);\n    students_t_distribution tdist(static_cast<double>(df));\n    return 2 * cdf(complement(tdist, fabs(statistic)));\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1, const std::string& v2) const {\n    double cor = cor_0cond(m_cov, cached_index(v1), cached_index(v2));\n    return cor_pvalue(cor, m_df->num_rows() - 2);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1, const std::string& v2) const {\n    auto [cor, df] = [this, &v1, &v2]() {\n        switch (m_df.col(v1)->type_id()) {\n            case Type::DOUBLE: {\n                auto cov_ptr = m_df.cov<arrow::DoubleType>(v1, v2);\n                auto& cov = *cov_ptr;\n                double cor = cor_0cond(cov, 0, 1);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2) - 2);\n            }\n            case Type::FLOAT: {\n                auto cov_ptr = m_df.cov<arrow::FloatType>(v1, v2);\n                auto& cov = *cov_ptr;\n                double cor = cor_0cond(cov, 0, 1);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2) - 2);\n            }\n            default:\n                throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n        }\n    }();\n\n    return cor_pvalue(cor, df);\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1, const std::string& v2, const std::string& ev) const {\n    double cor = cor_1cond(m_cov, cached_index(v1), cached_index(v2), cached_index(ev));\n    return cor_pvalue(cor, m_df->num_rows() - 3);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1, const std::string& v2, const std::string& ev) const {\n    auto [cor, df] = [this, &v1, &v2, &ev]() {\n        switch (m_df.col(v1)->type_id()) {\n            case Type::DOUBLE: {\n                auto cov_ptr = m_df.cov<arrow::DoubleType>(v1, v2, ev);\n                auto& cov = *cov_ptr;\n                double cor = cor_general(cov);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 3);\n            }\n            case Type::FLOAT: {\n                auto cov_ptr = m_df.cov<arrow::FloatType>(v1, v2, ev);\n                auto& cov = *cov_ptr;\n                double cor = cor_general(cov);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 3);\n            }\n            default:\n                throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n        }\n    }();\n\n    return cor_pvalue(cor, df);\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1,\n                                        const std::string& v2,\n                                        const std::vector<std::string>& ev) const {\n    std::vector<int> cached_indices;\n\n    cached_indices.push_back(cached_index(v1));\n    cached_indices.push_back(cached_index(v2));\n\n    for (auto it = ev.begin(), end = ev.end(); it != end; ++it) {\n        cached_indices.push_back(cached_index(*it));\n    }\n\n    int k = cached_indices.size();\n    MatrixXd cov(k, k);\n\n    for (int i = 0; i < k; ++i) {\n        cov(i, i) = m_cov(cached_indices[i], cached_indices[i]);\n        for (int j = i + 1; j < k; ++j) {\n            cov(i, j) = cov(j, i) = m_cov(cached_indices[i], cached_indices[j]);\n        }\n    }\n\n    double cor = cor_general(cov);\n    return cor_pvalue(cor, m_df->num_rows() - 2 - k);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1,\n                                      const std::string& v2,\n                                      const std::vector<std::string>& ev) const {\n    auto [cor, df] = [this, &v1, &v2, &ev]() {\n        int k = ev.size();\n        switch (m_df.col(v1)->type_id()) {\n            case Type::DOUBLE: {\n                auto cov_ptr = m_df.cov<arrow::DoubleType>(v1, v2, ev);\n                auto& cov = *cov_ptr;\n                double cor = cor_general(cov);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 2 - k);\n            }\n            case Type::FLOAT: {\n                auto cov_ptr = m_df.cov<arrow::FloatType>(v1, v2, ev);\n                auto& cov = *cov_ptr;\n                double cor = cor_general(cov);\n                return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 2 - k);\n            }\n            default:\n                throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n        }\n    }();\n\n    return cor_pvalue(cor, df);\n}\n\n}  // namespace learning::independences::continuous", "meta": {"hexsha": "c1a7440819667a17942fe211186ea937982736c8", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 38.7642276423, "max_line_length": 116, "alphanum_fraction": 0.5503355705, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6551557948869792}}
{"text": "static char help[] = \"hello neural network!\\n\";\n#include <iostream>\n#include <petsc.h>\n\n\n\n\n\n//---------------------------------------------------------------------------\n/* autodiff include */\n#include <autodiff/reverse.hpp>\nusing namespace autodiff;\n\n\n// The multi-variable function for which derivatives are needed\nvar f(var x, var y, var z)\n{\n    return 1 + x + y + z; // + x*y + y*z + x*z + x*y*z + exp(x/y + y/z);\n}\n\n\n\n//---------------------------------------------------------------------------\n// boost automatic differentiation \n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\nusing namespace boost::math::differentiation;\n\n\ntemplate <typename W, typename X, typename Y, typename Z>\npromote<W, X, Y, Z> f(const W& w, const X& x, const Y& y, const Z& z) {\n  using namespace std;\n  return exp(w * sin(x * log(y) / z) + sqrt(w * z / (x * y))) + w * w / tan(z);\n}\n//--------------------------------------------------------------------------\n\n/* main */\n\nint main(int argc, char **argv) {\n  PetscErrorCode     ierr;\n  Vec                b;\n  PetscReal ab[4] = {11.0, 12.0, 13.0, 14.0};\n  PetscInt i, j[4]={0, 1, 2, 3};\n  PetscRandom    rand;\n/*\n  var x = 1.0;         // the input variable x\n  var y = 2.0;         // the input variable y\n  var z = 3.0;         // the input variable z\n  var V[3] = {x,y,z};\n  var u = f(x, y, z);  // the output variable u\n  auto [ux, uy, uz] = derivatives(u, wrt(x, y, z)); // evaluate the derivatives of u with respect to x, y, z\n  std::cout << \"u = \"  << u << std::endl;    // print the evaluated output u\n  std::cout << \"ux = \" << ux << std::endl;  // print the evaluated derivative ux\n  std::cout << \"uy = \" << uy << std::endl;  // print the evaluated derivative uy\n  std::cout << \"uz = \" << uz << std::endl;  // print the evaluated derivative uz\n*/\n\n  ierr = PetscInitialize(&argc, &argv, (char*) 0, help); CHKERRQ(ierr);\n\n  VecCreate(PETSC_COMM_WORLD, &b);\n  VecSetSizes(b, PETSC_DECIDE, 3);\n  VecSetFromOptions(b);\n  \n  PetscRandomCreate(PETSC_COMM_WORLD,&rand);\n  PetscRandomSetFromOptions(rand);\n\n\n  PetscInt nloc;\n  VecGetLocalSize(b,&nloc);\n  var Vs[nloc];\n\n  double *vec_p;\n  VecGetArray(b, &vec_p);\n  for (i=0; i<nloc; i++){\n\t  PetscScalar val;\n\t  PetscRandomGetValue(rand,&val);\n\t  Vs[i] = val;\n\t  vec_p[i] = val;\n  }\n  VecRestoreArray(b, &vec_p);\n\n  var u = f(Vs[0], Vs[1], Vs[2]);  // the output variable u\n  auto [ux, uy, uz] = derivatives(u, wrt(Vs[0], Vs[1], Vs[2])); // evaluate the derivatives of u with respect to x, y, z\n  std::cout << \"u = \"  << u << std::endl;    // print the evaluated output u\n  std::cout << \"ux = \" << ux << std::endl;  // print the evaluated derivative ux\n  std::cout << \"uy = \" << uy << std::endl;  // print the evaluated derivative uy\n  std::cout << \"uz = \" << uz << std::endl;  // print the evaluated derivative uz\n\n/*\n  using float50 = boost::multiprecision::cpp_bin_float_50;\n  // Declare 4 independent variables together into a std::tuple.\n  auto const variables = make_ftuple<float50, 1, 1, 1, 1>(ab[0], ab[1], ab[2], ab[3]);//(11, 12, 13, 14);\n  auto const& w = std::get<0>(variables);\n  auto const& x = std::get<1>(variables); \n  auto const& y = std::get<2>(variables); \n  auto const& z = std::get<3>(variables);  \n  auto const v = f(w, x, y, z);\n  // Calculated from Mathematica symbolic differentiation.\n  std::cout << v.derivative(1, 1, 1, 1) << '\\n';\n*/\n\n\n  VecDestroy(&b);\n  PetscRandomDestroy(&rand);\n  return PetscFinalize();\n}\n\n", "meta": {"hexsha": "5a83a20b7db7b34dccee575beef3e4f33da4c966", "size": 3482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/automatic_diff/obsolete/main_nn.cpp", "max_stars_repo_name": "pourion/OPERA", "max_stars_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "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": "examples/automatic_diff/obsolete/main_nn.cpp", "max_issues_repo_name": "pourion/OPERA", "max_issues_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "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": "examples/automatic_diff/obsolete/main_nn.cpp", "max_forks_repo_name": "pourion/OPERA", "max_forks_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T02:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T02:38:41.000Z", "avg_line_length": 32.2407407407, "max_line_length": 120, "alphanum_fraction": 0.5689259047, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.655155789754949}}
{"text": "/*\n* Copyright 2019 \u00a9 Centre Interdisciplinaire de d\u00e9veloppement en Cartographie des Oc\u00e9ans (CIDCO), Tous droits r\u00e9serv\u00e9s\n*/\n\n#ifndef COORDINATETRANSFORM_HPP\n#define COORDINATETRANSFORM_HPP\n\n#include \"../Position.hpp\"\n#include \"../utils/Constants.hpp\"\n#include <Eigen/Dense>\n\n/*!\n* \\brief Coordinate transform class\n* \\author Guillaume Labbe-Morissette, Jordan McManus\n* \\date September 13, 2018, 3:39 PM\n*/\nclass CoordinateTransform {\npublic:\n\n  // WGS84 ellipsoid Parameters\n\n  /**WGS84 ellipsoid semi-major axis*/\n  static constexpr double a = 6378137.0;\n\n  /**WGS84 ellipsoid first eccentricity squared*/\n  static constexpr double e2 = 0.081819190842622 * 0.081819190842622;\n\n  /**WGS84 ellipsoid inverse flattening*/\n  static constexpr double f = 1.0 / 298.257223563;\n\n  /**WGS84 ellipsoid semi-minor axis*/\n  static constexpr double b = a * (1-f); // semi-minor axis\n\n  /**WGS84 ellipsoid second eccentricity squared*/\n  static constexpr double epsilon = e2 / (1.0 - e2); // second eccentricity squared\n\n  /**\n  * Sets the position in navigation frame\n  *\n  * @param positionInNavigationFrame the value that needs to be set\n  * @param positionGeographic the geographic position\n  * @param navDCM the rotation matrix\n  * @param originECEF the ECEF origin position\n  */\n  static void getPositionInNavigationFrame(Eigen::Vector3d & positionInNavigationFrame, Position & positionGeographic, Eigen::Matrix3d & navDCM, Eigen::Vector3d & originECEF) {\n    Eigen::Vector3d positionECEF;\n    getPositionECEF(positionECEF, positionGeographic);\n\n    Eigen::Vector3d positionVector = navDCM * (positionECEF - originECEF);\n\n    positionInNavigationFrame << positionVector(0), positionVector(1), positionVector(2);\n  };\n\n  /**\n  * Sets the ECEF position by the given position\n  *\n  * @param positionECEF value that needs to be set\n  * @param position the position used to get the ECEF position\n  */\n  static void getPositionECEF(Eigen::Vector3d & positionECEF, Position & position) {\n    double N = a / (sqrt(1 - e2 * position.getSlat() * position.getSlat()));\n    double xTRF = (N + position.getEllipsoidalHeight()) * position.getClat() * position.getClon();\n    double yTRF = (N + position.getEllipsoidalHeight()) * position.getClat() * position.getSlon();\n    double zTRF = (N * (1 - e2) + position.getEllipsoidalHeight()) * position.getSlat();\n\n    positionECEF << xTRF, yTRF, zTRF;\n  };\n\n  /**\n  * Gets the longitude, latitude and elevation of an ECEF position\n  *\n  * @param positionInNavigationFrame the position we need to get the latitude, longitude and elevation\n  * @param positionGeographic the position where the latitude, longitude et elevation will be put in\n  */\n  static void convertECEFToLongitudeLatitudeElevation(Eigen::Vector3d & positionInNavigationFrame, Position & positionGeographic) {\n    double x = positionInNavigationFrame(0);\n    double y = positionInNavigationFrame(1);\n    double z = positionInNavigationFrame(2);\n\n    // Bowring (1985) algorithm\n    double p2 = x * x + y*y;\n    double r2 = p2 + z*z;\n    double p = std::sqrt(p2);\n    double r = std::sqrt(r2);\n\n    double tanu = (1 - f) * (z / p) * (1 + epsilon * b / r);\n    double tan2u = tanu * tanu;\n\n    double cos2u = 1.0 / (1.0 + tan2u);\n    double cosu = std::sqrt(cos2u);\n    double cos3u = cos2u * cosu;\n\n    double sinu = tanu * cosu;\n    double sin2u = 1.0 - cos2u;\n    double sin3u = sin2u * sinu;\n\n    double tanlat = (z + epsilon * b * sin3u) / (p - e2 * a * cos3u);\n    double tan2lat = tanlat * tanlat;\n    double cos2lat = 1.0 / (1.0 + tan2lat);\n    double sin2lat = 1.0 - cos2lat;\n\n    double coslat = std::sqrt(cos2lat);\n    double sinlat = tanlat * coslat;\n\n    double longitude = std::atan2(y, x);\n    double latitude = std::atan(tanlat);\n    double height = p * coslat + z * sinlat - a * sqrt(1.0 - e2 * sin2lat);\n\n    positionGeographic.setLatitude(latitude*R2D);\n    positionGeographic.setLongitude(longitude*R2D);\n    positionGeographic.setEllipsoidalHeight(height);\n  }\n\n  /**\n  * Sets a terrestrial to a local geodetic reference frame matrix by the given position\n  *\n  * @param trf2lgf the terrestrial to local geodetic reference frame matrix that needs to be set\n  * @param position the given position\n  */\n  static void getTerrestialToLocalGeodeticReferenceFrameMatrix(Eigen::Matrix3d & trf2lgf, Position & position) {\n    double m00 = -position.getSlat() * position.getClon();\n    double m01 = -position.getSlat() * position.getSlon();\n    double m02 = position.getClat();\n\n    double m10 = -position.getSlon();\n    double m11 = position.getClon();\n    double m12 = 0;\n\n    double m20 = -position.getClat() * position.getClon();\n    double m21 = -position.getClat() * position.getSlon();\n    double m22 = -position.getSlat();\n\n    trf2lgf <<\n    m00, m01, m02,\n    m10, m11, m12,\n    m20, m21, m22;\n  };\n\n  /**\n  * Sets rotation matrix from neutral/zero position to the given attitude\n  *\n  * @param outputMatrix matrix that needs to be set\n  * @param attitude the given attitude\n  */\n  static void getDCM(Eigen::Matrix3d & outputMatrix,Attitude & attitude){\n    outputMatrix <<         attitude.getCh()*attitude.getCp(),   attitude.getCh()*attitude.getSp()*attitude.getSr()-attitude.getCr()*attitude.getSh(), attitude.getCh()*attitude.getCr()*attitude.getSp()+attitude.getSr()*attitude.getSh(),\n    attitude.getCp()*attitude.getSh(),   attitude.getCh()*attitude.getCr()+attitude.getSp()*attitude.getSr()*attitude.getSh(), attitude.getSh()*attitude.getCr()*attitude.getSp()-attitude.getCh()*attitude.getSr(),\n    -attitude.getSp(),          attitude.getCp()*attitude.getSr(),        attitude.getCr()*attitude.getCp();\n  }\n\n\n  /**\n  * NED Tangent plane at position to WGS84 ECEF\n  *\n  * @param outputMatrix the matrix that needs to be set\n  * @param position the position to convert\n  */\n  static void ned2ecef(Eigen::Matrix3d & outputMatrix,Position & position){\n\n    outputMatrix << -position.getClon()*position.getSlat(),-position.getSlon(),-position.getClat()*position.getClon(),\n    -position.getSlat()*position.getSlon(),position.getClon(),-position.getClat()*position.getSlon(),\n    position.getClat(),0,-position.getSlat();\n\n  }\n\n\n  /**\n  * Converts spherical coordinates to cartesian\n  *\n  * @param outputVector the cartesian coordinates\n  * @param theta the polar angle\n  * @param phi the azimuthal angle\n  * @param r the radial distance\n  */\n  static void spherical2cartesian(Eigen::Vector3d & outputVector,double theta,double phi,double r){\n    outputVector(0) = r * sin(D2R*theta)*cos(D2R*phi);\n    outputVector(1) = r * sin(D2R*theta)*sin(D2R*phi);\n    outputVector(2) = r * cos(D2R*theta);\n  }\n\n  /**\n  * Converts sonar coordinates (alpha,beta,r) to cartesian (NED)\n  *\n  * @param outputVector the cartesian coordinates\n  * @param aphaDegrees the alpha degree\n  * @param betaDegrees the beta degree\n  * @param r the radical distance\n  */\n  static void sonar2cartesian(Eigen::Vector3d & outputVector,double alphaDegrees,double betaDegrees,double r){\n    outputVector(0)=r * sin(alphaDegrees*D2R);\n    outputVector(1)=r * cos(alphaDegrees*D2R) * sin(betaDegrees*D2R);\n    outputVector(2)=r * cos(alphaDegrees*D2R) * cos(betaDegrees*D2R);\n  }\n};\n\n#endif /* COORDINATETRANSFORM_HPP */\n", "meta": {"hexsha": "4dd52d1a2fe90b95dedfba68b8cf84536c155e9e", "size": 7203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/CoordinateTransform.hpp", "max_stars_repo_name": "EmileGagne/MBES-lib", "max_stars_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_stars_repo_licenses": ["MIT"], "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/CoordinateTransform.hpp", "max_issues_repo_name": "EmileGagne/MBES-lib", "max_issues_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_issues_repo_licenses": ["MIT"], "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/CoordinateTransform.hpp", "max_forks_repo_name": "EmileGagne/MBES-lib", "max_forks_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_forks_repo_licenses": ["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.5634517766, "max_line_length": 236, "alphanum_fraction": 0.696931834, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6550764876742737}}
{"text": "/* boost random/negative_binomial_distribution.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2010\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id$\r\n */\r\n\r\n#ifndef BOOST_RANDOM_NEGATIVE_BINOMIAL_DISTRIBUTION_HPP_INCLUDED\r\n#define BOOST_RANDOM_NEGATIVE_BINOMIAL_DISTRIBUTION_HPP_INCLUDED\r\n\r\n#include <iosfwd>\r\n\r\n#include <boost/limits.hpp>\r\n#include <boost/random/detail/config.hpp>\r\n#include <boost/random/gamma_distribution.hpp>\r\n#include <boost/random/poisson_distribution.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\n/**\r\n * The negative binomial distribution is an integer valued\r\n * distribution with two parameters, @c k and @c p.  The\r\n * distribution produces non-negative values.\r\n *\r\n * The distribution function is\r\n * \\f$\\displaystyle P(i) = {k+i-1\\choose i}p^k(1-p)^i\\f$.\r\n *\r\n * This implementation uses a gamma-poisson mixture.\r\n */\r\ntemplate<class IntType = int, class RealType = double>\r\nclass negative_binomial_distribution {\r\npublic:\r\n    typedef IntType result_type;\r\n    typedef RealType input_type;\r\n\r\n    class param_type {\r\n    public:\r\n        typedef negative_binomial_distribution distribution_type;\r\n        /**\r\n         * Construct a param_type object.  @c k and @c p\r\n         * are the parameters of the distribution.\r\n         *\r\n         * Requires: k >=0 && 0 <= p <= 1\r\n         */\r\n        explicit param_type(IntType k_arg = 1, RealType p_arg = RealType (0.5))\r\n          : _k(k_arg), _p(p_arg)\r\n        {}\r\n        /** Returns the @c k parameter of the distribution. */\r\n        IntType k() const { return _k; }\r\n        /** Returns the @c p parameter of the distribution. */\r\n        RealType p() const { return _p; }\r\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\r\n        /** Writes the parameters of the distribution to a @c std::ostream. */\r\n        template<class CharT, class Traits>\r\n        friend std::basic_ostream<CharT,Traits>&\r\n        operator<<(std::basic_ostream<CharT,Traits>& os,\r\n                   const param_type& parm)\r\n        {\r\n            os << parm._p << \" \" << parm._k;\r\n            return os;\r\n        }\r\n    \r\n        /** Reads the parameters of the distribution from a @c std::istream. */\r\n        template<class CharT, class Traits>\r\n        friend std::basic_istream<CharT,Traits>&\r\n        operator>>(std::basic_istream<CharT,Traits>& is, param_type& parm)\r\n        {\r\n            is >> parm._p >> std::ws >> parm._k;\r\n            return is;\r\n        }\r\n#endif\r\n        /** Returns true if the parameters have the same values. */\r\n        friend bool operator==(const param_type& lhs, const param_type& rhs)\r\n        {\r\n            return lhs._k == rhs._k && lhs._p == rhs._p;\r\n        }\r\n        /** Returns true if the parameters have different values. */\r\n        friend bool operator!=(const param_type& lhs, const param_type& rhs)\r\n        {\r\n            return !(lhs == rhs);\r\n        }\r\n    private:\r\n        IntType _k;\r\n        RealType _p;\r\n    };\r\n    \r\n    /**\r\n     * Construct a @c negative_binomial_distribution object. @c k and @c p\r\n     * are the parameters of the distribution.\r\n     *\r\n     * Requires: k >=0 && 0 <= p <= 1\r\n     */\r\n    explicit negative_binomial_distribution(IntType k_arg = 1,\r\n                                            RealType p_arg = RealType(0.5))\r\n      : _k(k_arg), _p(p_arg)\r\n    {}\r\n    \r\n    /**\r\n     * Construct an @c negative_binomial_distribution object from the\r\n     * parameters.\r\n     */\r\n    explicit negative_binomial_distribution(const param_type& parm)\r\n      : _k(parm.k()), _p(parm.p())\r\n    {}\r\n    \r\n    /**\r\n     * Returns a random variate distributed according to the\r\n     * negative binomial distribution.\r\n     */\r\n    template<class URNG>\r\n    IntType operator()(URNG& urng) const\r\n    {\r\n        gamma_distribution<RealType> gamma(_k, (1-_p)/_p);\r\n        poisson_distribution<IntType, RealType> poisson(gamma(urng));\r\n        return poisson(urng);\r\n    }\r\n    \r\n    /**\r\n     * Returns a random variate distributed according to the negative\r\n     * binomial distribution with parameters specified by @c param.\r\n     */\r\n    template<class URNG>\r\n    IntType operator()(URNG& urng, const param_type& parm) const\r\n    {\r\n        return negative_binomial_distribution(parm)(urng);\r\n    }\r\n\r\n    /** Returns the @c k parameter of the distribution. */\r\n    IntType k() const { return _k; }\r\n    /** Returns the @c p parameter of the distribution. */\r\n    RealType p() const { return _p; }\r\n\r\n    /** Returns the smallest value that the distribution can produce. */\r\n    IntType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }\r\n    /** Returns the largest value that the distribution can produce. */\r\n    IntType max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n    { return (std::numeric_limits<IntType>::max)(); }\r\n\r\n    /** Returns the parameters of the distribution. */\r\n    param_type param() const { return param_type(_k, _p); }\r\n    /** Sets parameters of the distribution. */\r\n    void param(const param_type& parm)\r\n    {\r\n        _k = parm.k();\r\n        _p = parm.p();\r\n    }\r\n\r\n    /**\r\n     * Effects: Subsequent uses of the distribution do not depend\r\n     * on values produced by any engine prior to invoking reset.\r\n     */\r\n    void reset() { }\r\n\r\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\r\n    /** Writes the parameters of the distribution to a @c std::ostream. */\r\n    template<class CharT, class Traits>\r\n    friend std::basic_ostream<CharT,Traits>&\r\n    operator<<(std::basic_ostream<CharT,Traits>& os,\r\n               const negative_binomial_distribution& bd)\r\n    {\r\n        os << bd.param();\r\n        return os;\r\n    }\r\n    \r\n    /** Reads the parameters of the distribution from a @c std::istream. */\r\n    template<class CharT, class Traits>\r\n    friend std::basic_istream<CharT,Traits>&\r\n    operator>>(std::basic_istream<CharT,Traits>& is,\r\n               negative_binomial_distribution& bd)\r\n    {\r\n        bd.read(is);\r\n        return is;\r\n    }\r\n#endif\r\n\r\n    /** Returns true if the two distributions will produce the same\r\n        sequence of values, given equal generators. */\r\n    friend bool operator==(const negative_binomial_distribution& lhs,\r\n                           const negative_binomial_distribution& rhs)\r\n    {\r\n        return lhs._k == rhs._k && lhs._p == rhs._p;\r\n    }\r\n    /** Returns true if the two distributions could produce different\r\n        sequences of values, given equal generators. */\r\n    friend bool operator!=(const negative_binomial_distribution& lhs,\r\n                           const negative_binomial_distribution& rhs)\r\n    {\r\n        return !(lhs == rhs);\r\n    }\r\n\r\nprivate:\r\n\r\n    /// @cond \\show_private\r\n\r\n    template<class CharT, class Traits>\r\n    void read(std::basic_istream<CharT, Traits>& is) {\r\n        param_type parm;\r\n        if(is >> parm) {\r\n            param(parm);\r\n        }\r\n    }\r\n\r\n    // parameters\r\n    IntType _k;\r\n    RealType _p;\r\n\r\n    /// @endcond\r\n};\r\n\r\n}\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "825be639beca2d94c132200d464ac7f4fabb0aab", "size": 7131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/random/negative_binomial_distribution.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/random/negative_binomial_distribution.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/random/negative_binomial_distribution.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 32.2669683258, "max_line_length": 80, "alphanum_fraction": 0.6059458701, "num_tokens": 1628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.654999017454397}}
{"text": "/*\nYou are asked to calculate factorials of some small positive integers.\n\n\n */\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::cpp_int;\nusing namespace std;\n\nint main() {\n    \n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    cpp_int t,n;\n    cin>>t;\n    while(t--){\n        cin>>n;\n        cpp_int fac = 1;\n        if(n == 0 || n == 1)\n            cout<<fac<<endl;\n        else{\n            for(cpp_int i = 2; i<=n; i++)\n               fac = fac*i;\n            cout<<fac<<endl;\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "8afa8d1b5554f9cd0b3e38ac5b51bcf6634a100d", "size": 570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Beginner Challenges/Small factorials.cpp", "max_stars_repo_name": "Akashverma247/Coding_Library", "max_stars_repo_head_hexsha": "09c28a71c7ba5b2f192bb8ef26b2d0a41905f011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Beginner Challenges/Small factorials.cpp", "max_issues_repo_name": "Akashverma247/Coding_Library", "max_issues_repo_head_hexsha": "09c28a71c7ba5b2f192bb8ef26b2d0a41905f011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Beginner Challenges/Small factorials.cpp", "max_forks_repo_name": "Akashverma247/Coding_Library", "max_forks_repo_head_hexsha": "09c28a71c7ba5b2f192bb8ef26b2d0a41905f011", "max_forks_repo_licenses": ["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.8125, "max_line_length": 70, "alphanum_fraction": 0.5228070175, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6548920007184271}}
{"text": "// test computeCost\n#include <cassert>\n#include <armadillo>\n#include \"../../ex1/computeCost.hpp\"\n#include \"../../ex1/util.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    fmat X;\n    fvec y, theta;\n\n    parse_mat(&X, \"[1,2; 1,3; 1,4; 1,5]\");\n    parse_mat(&y, \"[7;6;5;4]\");\n    parse_mat(&theta, \"[0.1;0.2]\");\n\n    auto J = computeCost(X, y, theta);\n    cout << \"J = \" << J << endl;\n    assert(J == 11.945f);\n\n    parse_mat(&X, \"[1,2,3; 1,3,4; 1,4,5; 1,5,6]\");\n    parse_mat(&y, \"[7;6;5;4]\");\n    parse_mat(&theta, \"[0.1;0.2;0.3]\");\n\n    J = computeCost(X, y, theta);\n    cout << \"J = \" << J << endl;\n    assert(J == 7.0175f);\n\n    return 0;\n}\n", "meta": {"hexsha": "932e18051a1dab7962704c7066d7ddcedd26f5d9", "size": 662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ex1/computeCost_main.cpp", "max_stars_repo_name": "kolbma/coursera-ml", "max_stars_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T21:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T21:08:21.000Z", "max_issues_repo_path": "tests/ex1/computeCost_main.cpp", "max_issues_repo_name": "kolbma/coursera-ml", "max_issues_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/ex1/computeCost_main.cpp", "max_forks_repo_name": "kolbma/coursera-ml", "max_forks_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "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.0606060606, "max_line_length": 50, "alphanum_fraction": 0.5196374622, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.654883533762547}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <utility> // std::pair, std::make_pair\n#include <cmath> // float comparison\n#include <limits>\n#include <cstdint>  // for std::uint8_t\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"persistent_cohomology\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n\nusing namespace Gudhi;\nusing namespace Gudhi::persistent_cohomology;\nusing namespace boost::unit_test;\n\ntypedef Simplex_tree<> typeST;\n\nstd::string test_rips_persistence(int coefficient, int min_persistence) {\n  // file is copied in CMakeLists.txt\n  std::ifstream simplex_tree_stream;\n  simplex_tree_stream.open(\"simplex_tree_file_for_unit_test.txt\");\n  typeST st;\n  simplex_tree_stream >> st;\n  simplex_tree_stream.close();\n\n  // Display the Simplex_tree\n  std::cout << \"The complex contains \" << st.num_simplices() << \" simplices\" << \" - dimension= \" << st.dimension()\n      << std::endl;\n\n  // Check\n  BOOST_CHECK(st.num_simplices() == 98);\n  BOOST_CHECK(st.dimension() == 3);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology<Simplex_tree<>, Field_Zp> pcoh(st);\n\n  pcoh.init_coefficients( coefficient );  // initializes the coefficient field for homology\n  // Check infinite rips\n  pcoh.compute_persistent_cohomology( min_persistence );  // Minimal lifetime of homology feature to be recorded.\n  std::ostringstream ossInfinite;\n\n  pcoh.output_diagram(ossInfinite);\n  std::string strInfinite = ossInfinite.str();\n  return strInfinite;\n}\n\nvoid test_rips_persistence_in_dimension(int dimension) {\n  std::string value0(\"  0 0.02 1.12\");\n  std::string value1(\"  0 0.03 1.13\");\n  std::string value2(\"  0 0.04 1.14\");\n  std::string value3(\"  0 0.05 1.15\");\n  std::string value4(\"  0 0.06 1.16\");\n  std::string value5(\"  0 0.07 1.17\");\n  std::string value6(\"  0 0.08 1.18\");\n  std::string value7(\"  0 0.09 1.19\");\n  std::string value8(\"  0 0 inf\"    );\n  std::string value9(\"  0 0.01 inf\" );\n\n  value0.insert(0,std::to_string(dimension));\n  value1.insert(0,std::to_string(dimension));\n  value2.insert(0,std::to_string(dimension));\n  value3.insert(0,std::to_string(dimension));\n  value4.insert(0,std::to_string(dimension));\n  value5.insert(0,std::to_string(dimension));\n  value6.insert(0,std::to_string(dimension));\n  value7.insert(0,std::to_string(dimension));\n  value8.insert(0,std::to_string(dimension));\n  value9.insert(0,std::to_string(dimension));\n\n  std::cout << \"********************************************************************\" << std::endl;\n  std::cout << \"TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=\" << dimension << \" MIN_PERS=0\" << std::endl;\n\n  std::string str_rips_persistence = test_rips_persistence(dimension, 0);\n  std::cout << str_rips_persistence << std::endl;\n  \n  BOOST_CHECK(str_rips_persistence.find(value0) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value1) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value2) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value3) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value4) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value5) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value6) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value7) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found\n  std::cout << \"str_rips_persistence=\" << str_rips_persistence << std::endl;\n\n  std::cout << \"********************************************************************\" << std::endl;\n  std::cout << \"TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=\" << dimension << \" MIN_PERS=1\" << std::endl;\n\n  str_rips_persistence = test_rips_persistence(dimension, 1);\n\n  BOOST_CHECK(str_rips_persistence.find(value0) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value1) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value2) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value3) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value4) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value5) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value6) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value7) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found\n  std::cout << \"str_rips_persistence=\" << str_rips_persistence << std::endl;\n\n  std::cout << \"********************************************************************\" << std::endl;\n  std::cout << \"TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=\" << dimension << \" MIN_PERS=2\" << std::endl;\n\n  str_rips_persistence = test_rips_persistence(dimension, 2);\n\n  BOOST_CHECK(str_rips_persistence.find(value0) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value1) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value2) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value3) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value4) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value5) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value6) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value7) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found\n  std::cout << \"str_rips_persistence=\" << str_rips_persistence << std::endl;\n\n  std::cout << \"********************************************************************\" << std::endl;\n  std::cout << \"TEST OF RIPS_PERSISTENT_COHOMOLOGY_SINGLE_FIELD DIM=\" << dimension << \" MIN_PERS=Inf\" << std::endl;\n\n  str_rips_persistence = test_rips_persistence(dimension, (std::numeric_limits<int>::max)());\n\n  BOOST_CHECK(str_rips_persistence.find(value0) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value1) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value2) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value3) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value4) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value5) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value6) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value7) == std::string::npos); // Check not found\n  BOOST_CHECK(str_rips_persistence.find(value8) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value9) != std::string::npos); // Check found\n  std::cout << \"str_rips_persistence=\" << str_rips_persistence << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_1 )\n{\n  test_rips_persistence_in_dimension(1);\n}\n\nBOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_2 )\n{\n  test_rips_persistence_in_dimension(2);\n}\n\nBOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_3 )\n{\n  test_rips_persistence_in_dimension(3);\n}\n\nBOOST_AUTO_TEST_CASE( rips_persistent_cohomology_single_field_dim_5 )\n{\n  test_rips_persistence_in_dimension(5);\n}\n\n// TODO(VR): not working from 6\n// std::string str_rips_persistence = test_rips_persistence(6, 0);\n// TODO(VR): division by zero\n// std::string str_rips_persistence = test_rips_persistence(0, 0);\n\n/** SimplexTree minimal options to test the limits.\n * \n * Maximum number of simplices to compute persistence is <CODE>std::numeric_limits<std::uint8_t>::max()<\\CODE> = 256.*/\nstruct MiniSTOptions {\n  typedef linear_indexing_tag Indexing_tag;\n  typedef short Vertex_handle;\n  typedef double Filtration_value;\n  // Maximum number of simplices to compute persistence is 2^8 - 1 = 255. One is reserved for null_key\n  typedef std::uint8_t Simplex_key;\n  static const bool store_key = true;\n  static const bool store_filtration = false;\n  static const bool contiguous_vertices = false;\n};\n\nusing Mini_simplex_tree = Gudhi::Simplex_tree<MiniSTOptions>;\nusing Mini_st_persistence =\n    Gudhi::persistent_cohomology::Persistent_cohomology<Mini_simplex_tree, Gudhi::persistent_cohomology::Field_Zp>;\n\nBOOST_AUTO_TEST_CASE( persistence_constructor_exception )\n{\n  Mini_simplex_tree st;\n\n  // To make number of simplices = 255\n  const short simplex_0[] = {0, 1, 2, 3, 4, 5, 6, 7};\n  st.insert_simplex_and_subfaces(simplex_0);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  BOOST_CHECK(st.num_simplices() <= std::numeric_limits<MiniSTOptions::Simplex_key>::max());\n  // Class for homology computation\n  BOOST_CHECK_NO_THROW(Mini_st_persistence pcoh(st));\n\n  st.insert_simplex({8});\n  BOOST_CHECK(st.num_simplices() > std::numeric_limits<MiniSTOptions::Simplex_key>::max());\n  // Class for homology computation\n  BOOST_CHECK_THROW(Mini_st_persistence pcoh2(st), std::out_of_range);\n\n}\n", "meta": {"hexsha": "a1c106d53e635f0673d238f6b01781b3959552c4", "size": 9834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test.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/Persistent_cohomology/test/persistent_cohomology_unit_test.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/Persistent_cohomology/test/persistent_cohomology_unit_test.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": 46.1690140845, "max_line_length": 119, "alphanum_fraction": 0.7200528778, "num_tokens": 2697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.8128673133042217, "lm_q1q2_score": 0.654872072968592}}
{"text": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    dense_vector<double>                                        cd(5, 1.0);\n    std::vector<dense_vector<double> >                          v(5, cd);\n \n    for (unsigned i= 0, c= 1; i < size(v); ++i)\n\tfor (unsigned j= 0; j < size(v[i]); ++j, c++)\n\t    v[i][j]= double((i + j) % 5);\n\n    std::cout << \"w initially\\n\";\n    std::vector<dense_vector<double> > \t\t\t\tw(v),x(v);\n    for (unsigned i= 0; i < size(w); ++i)\n\tstd::cout << w[i] << \"\\n\";\n \n    orth(w);\n    std::cout << \"\\nw orthogonalized\\n\";\n    for (unsigned i= 0; i < size(w); ++i)\n\tstd::cout << w[i] << \"\\n\";\n    \n    std::cout << \"\\nTest: dot product of orthogonalized w\\n\";\n    for (unsigned i= 0, c= 1; i < size(w); ++i) {\n\tfor (unsigned j= 0; j < size(w); ++j, ++c)\n\t    std::cout << (dot(w[i], w[j])<1.e-8 ? 0 : dot(w[i], w[j]) )<< \" \" ;\n\tstd::cout << \"\\n\";\n    }   \n    std::cout << \"\\nThe according factors are: \\n\" << orthogonalize_factors(v) << '\\n';\n    \n    orth(x,0); orth(x,1);\n    std::cout << \"\\nw(0), w(1) orthogonalized\\n\";\n    for (unsigned i= 0; i < size(w); ++i)\n\tstd::cout << x[i] << \"\\n\";\n    \n\n    return 0;\n}\n", "meta": {"hexsha": "9156536e642e0abc199f80a8d3115437e113113c", "size": 1233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/orth_example.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/examples/orth_example.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/examples/orth_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.3571428571, "max_line_length": 87, "alphanum_fraction": 0.4809407948, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6548464317578127}}
{"text": "#include \"main.h\"\r\n\r\n#include <Eigen/CXX11/Tensor>\r\n\r\nusing Eigen::Tensor;\r\nusing Eigen::RowMajor;\r\n\r\nstatic void test_comparison_sugar() {\r\n  // we already trust comparisons between tensors, we're simply checking that\r\n  // the sugared versions are doing the same thing\r\n  Tensor<int, 3> t(6, 7, 5);\r\n\r\n  t.setRandom();\r\n  // make sure we have at least one value == 0\r\n  t(0,0,0) = 0;\r\n\r\n  Tensor<bool,0> b;\r\n\r\n#define TEST_TENSOR_EQUAL(e1, e2) \\\r\n  b = ((e1) == (e2)).all();       \\\r\n  VERIFY(b())\r\n\r\n#define TEST_OP(op) TEST_TENSOR_EQUAL(t op 0, t op t.constant(0))\r\n\r\n  TEST_OP(==);\r\n  TEST_OP(!=);\r\n  TEST_OP(<=);\r\n  TEST_OP(>=);\r\n  TEST_OP(<);\r\n  TEST_OP(>);\r\n#undef TEST_OP\r\n#undef TEST_TENSOR_EQUAL\r\n}\r\n\r\n\r\nstatic void test_scalar_sugar_add_mul() {\r\n  Tensor<float, 3> A(6, 7, 5);\r\n  Tensor<float, 3> B(6, 7, 5);\r\n  A.setRandom();\r\n  B.setRandom();\r\n\r\n  const float alpha = 0.43f;\r\n  const float beta = 0.21f;\r\n  const float gamma = 0.14f;\r\n\r\n  Tensor<float, 3> R = A.constant(gamma) + A * A.constant(alpha) + B * B.constant(beta);\r\n  Tensor<float, 3> S = A * alpha + B * beta + gamma;\r\n  Tensor<float, 3> T = gamma + alpha * A + beta * B;\r\n\r\n  for (int i = 0; i < 6*7*5; ++i) {\r\n    VERIFY_IS_APPROX(R(i), S(i));\r\n    VERIFY_IS_APPROX(R(i), T(i));\r\n  }\r\n}\r\n\r\nstatic void test_scalar_sugar_sub_div() {\r\n  Tensor<float, 3> A(6, 7, 5);\r\n  Tensor<float, 3> B(6, 7, 5);\r\n  A.setRandom();\r\n  B.setRandom();\r\n\r\n  const float alpha = 0.43f;\r\n  const float beta = 0.21f;\r\n  const float gamma = 0.14f;\r\n  const float delta = 0.32f;\r\n\r\n  Tensor<float, 3> R = A.constant(gamma) - A / A.constant(alpha)\r\n      - B.constant(beta) / B - A.constant(delta);\r\n  Tensor<float, 3> S = gamma - A / alpha - beta / B - delta;\r\n\r\n  for (int i = 0; i < 6*7*5; ++i) {\r\n    VERIFY_IS_APPROX(R(i), S(i));\r\n  }\r\n}\r\n\r\nvoid test_cxx11_tensor_sugar()\r\n{\r\n  CALL_SUBTEST(test_comparison_sugar());\r\n  CALL_SUBTEST(test_scalar_sugar_add_mul());\r\n  CALL_SUBTEST(test_scalar_sugar_sub_div());\r\n}\r\n", "meta": {"hexsha": "1d739d68e4b261cb6f7f70e31237c3202059d5a8", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_sugar.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/unsupported/test/cxx11_tensor_sugar.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/unsupported/test/cxx11_tensor_sugar.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": 24.012195122, "max_line_length": 89, "alphanum_fraction": 0.5992889792, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173801068221, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.654773379029909}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2015 Basil Fierz\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// VCL configuration\n#include <vcl/config/global.h>\n#include <vcl/config/eigen.h>\n\n// C++ standard library\n#include <random>\n\n// Eigen library\n#include <Eigen/Dense>\n\n// Include the relevant parts from the library\n#include <vcl/core/interleavedarray.h>\n#include <vcl/math/math.h>\n#include <vcl/math/jacobieigen33_selfadjoint.h>\n#include <vcl/math/jacobieigen33_selfadjoint_quat.h>\n\n// Google test\n#include <gtest/gtest.h>\n\n// Common functions\nnamespace\n{\n\ttemplate<typename REAL>\n\tvoid SortEigenvalues(Eigen::Matrix<REAL, 3, 1>& A, Eigen::Matrix<REAL, 3, 3>& B)\n\t{\n\t\t// Bubble sort\n\t\tbool swapped = true;\n\t\tint j = 0;\n\n\t\twhile (swapped)\n\t\t{\n\t\t\tswapped = false;\n\t\t\tj++;\n\n\t\t\tfor (int i = 0; i < 3 - j; i++)\n\t\t\t{\n\t\t\t\tif (A(i) > A(i + 1))\n\t\t\t\t{\n\t\t\t\t\tstd::swap(A(i), A(i + 1));\n\t\t\t\t\tB.col(i).swap(B.col(i + 1));\n\n\t\t\t\t\tswapped = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate<typename Scalar>\n\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1> createProblems(size_t nr_problems)\n\t{\n\t\t// Random number generator\n\t\tstd::mt19937_64 rng;\n\t\tstd::uniform_real_distribution<float> d;\n\n\t\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1> A(nr_problems);\n\t\n\t\t// Initialize data\n\t\tfor (int i = 0; i < (int) nr_problems; i++)\n\t\t{\n\t\t\tEigen::Matrix<Scalar, 3, 3> rnd;\n\t\t\trnd << d(rng), d(rng), d(rng),\n\t\t\t\t   d(rng), d(rng), d(rng),\n\t\t\t\t   d(rng), d(rng), d(rng);\n\t\t\tA.at<Scalar>(i) = rnd.transpose() * rnd;\n\t\t}\n\n\t\treturn std::move(A);\n\t}\n\n\ttemplate<typename Scalar>\n\tvoid computeReferenceSolution\n\t(\n\t\tsize_t nr_problems,\n\t\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& ATA,\n\t\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1>& U,\n\t\tVcl::Core::InterleavedArray<Scalar, 3, 1, -1>& S\n\t)\n\t{\n\t\t// Compute reference using Eigen\n\t\tfor (int i = 0; i < static_cast<int>(nr_problems); i++)\n\t\t{\n\t\t\tVcl::Matrix3f A = ATA.at<Scalar>(i);\n\n\t\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\t\tU.at<Scalar>(i) = solver.eigenvectors();\n\t\t\tS.at<Scalar>(i) = solver.eigenvalues();\n\t\t}\n\t}\n\n\ttemplate<typename Scalar>\n\tvoid checkSolution\n\t(\n\t\tsize_t nr_problems,\n\t\tScalar tol,\n\t\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& refUa,\n\t\tconst Vcl::Core::InterleavedArray<Scalar, 3, 1, -1>& refSa,\n\t\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& resUa,\n\t\tconst Vcl::Core::InterleavedArray<Scalar, 3, 1, -1>& resSa\n\t)\n\t{\n\t\tusing Vcl::Mathematics::equal;\n\n\t\tfor (int i = 0; i < static_cast<int>(nr_problems); i++)\n\t\t{\n\t\t\tVcl::Matrix3f refU = refUa.at<Scalar>(i);\n\t\t\tVcl::Vector3f refS = refSa.at<Scalar>(i);\n\n\t\t\tVcl::Matrix3f resU = resUa.at<Scalar>(i);\n\t\t\tVcl::Vector3f resS = resSa.at<Scalar>(i);\n\t\t\tSortEigenvalues(resS, resU);\n\n\t\t\tScalar sqLenRefUc0 = refU.col(0).squaredNorm();\n\t\t\tScalar sqLenRefUc1 = refU.col(1).squaredNorm();\n\t\t\tScalar sqLenRefUc2 = refU.col(2).squaredNorm();\n\t\t\tEXPECT_TRUE(equal(sqLenRefUc0, Scalar(1), tol)) << \"Reference U(\" << i << \"): Column 0 is not normalized.\";\n\t\t\tEXPECT_TRUE(equal(sqLenRefUc1, Scalar(1), tol)) << \"Reference U(\" << i << \"): Column 1 is not normalized.\";\n\t\t\tEXPECT_TRUE(equal(sqLenRefUc2, Scalar(1), tol)) << \"Reference U(\" << i << \"): Column 2 is not normalized.\";\n\n\t\t\tScalar sqLenResUc0 = resU.col(0).squaredNorm();\n\t\t\tScalar sqLenResUc1 = resU.col(1).squaredNorm();\n\t\t\tScalar sqLenResUc2 = resU.col(2).squaredNorm();\n\t\t\tEXPECT_TRUE(equal(sqLenResUc0, Scalar(1), tol)) << \"Result U(\" << i << \"): Column 0 is not normalized.\";\n\t\t\tEXPECT_TRUE(equal(sqLenResUc1, Scalar(1), tol)) << \"Result U(\" << i << \"): Column 1 is not normalized.\";\n\t\t\tEXPECT_TRUE(equal(sqLenResUc2, Scalar(1), tol)) << \"Result U(\" << i << \"): Column 2 is not normalized.\";\n\n\t\t\tbool eqS = refS.array().abs().isApprox(resS.array().abs(), tol);\n\t\t\tbool eqU = refU.array().abs().isApprox(resU.array().abs(), tol);\n\n\t\t\tEXPECT_TRUE(eqS) << \"S(\" << i << \") - Ref: \" << refS << \", Actual: \" << resS;\n\t\t\tEXPECT_TRUE(eqU) << \"U(\" << i << \") - Ref: \" << refU << \", Actual: \" << resU;\n\t\t}\n\t}\n}\n\ntemplate<typename WideScalar>\nvoid runJacobiEigen33Test(float tol)\n{\n\tusing scalar_t = float;\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\tusing vector3_t = Eigen::Matrix<real_t, 3, 1>;\n\n\tsize_t nr_problems = 128;\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> resU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> resS(nr_problems);\n\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> refU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> refS(nr_problems);\n\n\tauto A = createProblems<scalar_t>(nr_problems);\n\tcomputeReferenceSolution(nr_problems, A, refU, refS);\n\n\t// Strides\n\tsize_t stride = nr_problems;\n\tsize_t width = sizeof(real_t) / sizeof(scalar_t);\n\n\tfor (int i = 0; i < static_cast<int>(stride / width); i++)\n\t{\n\t\tmatrix3_t ATA = A.at<real_t>(i);\n\t\tmatrix3_t U;\n\t\tvector3_t S;\n\n\t\tVcl::Mathematics::SelfAdjointJacobiEigen(ATA, U);\n\t\tS = ATA.diagonal();\n\n\t\tresU.at<real_t>(i) = U;\n\t\tresS.at<real_t>(i) = S;\n\t}\n\n\t// Check against reference solution\n\tcheckSolution(nr_problems, tol, refU, refS, resU, resS);\n}\n\ntemplate<typename WideScalar>\nvoid runJacobiEigenQuat33Test(float tol)\n{\n\tusing scalar_t = float;\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\tusing vector3_t = Eigen::Matrix<real_t, 3, 1>;\n\n\tsize_t nr_problems = 128;\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> resU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> resS(nr_problems);\n\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> refU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> refS(nr_problems);\n\n\tauto A = createProblems<scalar_t>(nr_problems);\n\tcomputeReferenceSolution(nr_problems, A, refU, refS);\n\n\t// Strides\n\tsize_t stride = nr_problems;\n\tsize_t width = sizeof(real_t) / sizeof(scalar_t);\n\n\tfor (int i = 0; i < static_cast<int>(stride / width); i++)\n\t{\n\t\tmatrix3_t ATA = A.at<real_t>(i);\n\t\tmatrix3_t U;\n\t\tvector3_t S;\n\n\t\tVcl::Mathematics::SelfAdjointJacobiEigenQuat(ATA, U);\n\t\tS = ATA.diagonal();\n\n\t\tresU.at<real_t>(i) = U;\n\t\tresS.at<real_t>(i) = S;\n\t}\n\n\t// Check against reference solution\n\tcheckSolution(nr_problems, tol, refU, refS, resU, resS);\n}\n\nTEST(Eigen33, EigenFloat)\n{\n\trunJacobiEigen33Test<float>(1e-5f);\n}\nTEST(Eigen33, EigenFloat4)\n{\n\trunJacobiEigen33Test<Vcl::float4>(1e-5f);\n}\nTEST(Eigen33, EigenFloat8)\n{\n\trunJacobiEigen33Test<Vcl::float8>(1e-5f);\n}\nTEST(Eigen33, EigenFloat16)\n{\n\trunJacobiEigen33Test<Vcl::float16>(1e-5f);\n}\n\nTEST(Eigen33, EigenQuatFloat)\n{\n\trunJacobiEigenQuat33Test<float>(1e-5f);\n}\nTEST(Eigen33, EigenQuatFloat4)\n{\n\trunJacobiEigenQuat33Test<Vcl::float4>(1e-5f);\n}\nTEST(Eigen33, EigenQuatFloat8)\n{\n\trunJacobiEigenQuat33Test<Vcl::float8>(1e-5f);\n}\nTEST(Eigen33, EigenQuatFloat16)\n{\n\trunJacobiEigenQuat33Test<Vcl::float16>(1e-5f);\n}\n", "meta": {"hexsha": "47db709f03599ec1a045c06fe95b3da1a1fa6a7d", "size": 7908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/vcl.math/eigen33.cpp", "max_stars_repo_name": "bschindler/vcl", "max_stars_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_stars_repo_licenses": ["MIT"], "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/tests/vcl.math/eigen33.cpp", "max_issues_repo_name": "bschindler/vcl", "max_issues_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/vcl.math/eigen33.cpp", "max_forks_repo_name": "bschindler/vcl", "max_forks_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_forks_repo_licenses": ["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.967032967, "max_line_length": 110, "alphanum_fraction": 0.6803237228, "num_tokens": 2589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6547733714659227}}
{"text": "/*! @file pitts_tensor2_qb_decomposition.hpp\n* @brief QB-part of the SVQB orthogonalization algorithm (Stathopoulos and Wu, SISC 23 (6), pp. 2165-2182)\n* @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de>\n* @date 2019-10-31\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n#define PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n\n// includes\n#include <exception>\n#include <cmath>\n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include \"pitts_timer.hpp\"\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n  //! QB-part in the SVQB orthogonalization algorithm from Stathopoulos and Wu, SISC 23 (6), pp. 2165-2182\n  //!\n  //! Computes the decomposition B^TB = M using a SVD of M for a symmetric positive semi-definite matrix M\n  //!\n  //! @tparam T     underlying data type (double, complex, ...)\n  //!\n  //! @param  M     Symmetric positive semi-definite input matrix M, overwritten with the output matrix B\n  //! @param  Binv  Pseudo-Inverse of the output matrix\n  //! @return       detected rank of the matrix\n  //!\n  template<typename T>\n  auto qb_decomposition(const Tensor2<T>& M, Tensor2<T>& B, Tensor2<T>& Binv, T rankTolerance)\n  {\n    const auto timer = PITTS::timing::createScopedTimer<Tensor2<T>>();\n\n    // get dimension\n    if( M.r1() != M.r2() )\n      throw std::invalid_argument(\"qb_decomposition requires a quadratic matrix!\");\n    const auto n = M.r1();\n\n    // Helpful types\n    using vec = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n    using mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n    using EigenSolver = Eigen::SelfAdjointEigenSolver<mat>;\n\n    // use Eigen for matrix operations\n    const auto mapM = ConstEigenMap(M);\n\n    // compute sqrt(diag(M)) and its inverse\n    vec d(n), dinv(n);\n    for(int i = 0; i < n; i++)\n    {\n      if( std::abs(M(i,i)) <= rankTolerance )\n      {\n        d(i) = T(0);\n        dinv(i) = T(0);\n      }\n      else\n      {\n        d(i) = std::sqrt(M(i,i));\n        dinv(i) = T(1)/d(i);\n      }\n    }\n\n    // scale input matrix from left and right by diag(dinv), so it's diagonal entries become 1\n    const mat scaledM = dinv.asDiagonal() * mapM * dinv.asDiagonal();\n\n    // compute eigenvalue decomposition\n    EigenSolver eigSolv(scaledM);\n\n    // determine rank of the input matrix and set w = sqrt(lambda), winv = 1/w\n    // Eigen orders eigenvalues with increasing value (smallest first)\n    int rank = n;\n    const auto evMax = std::abs(eigSolv.eigenvalues()(n-1));\n    vec w(n), winv(n);\n    if( evMax <= rankTolerance )\n    {\n      w = vec::Zero(n);\n      winv = vec::Zero(n);\n      rank = 0;\n    }\n    else\n    {\n      for(int i = 0; i < n; i++)\n      {\n        if( eigSolv.eigenvalues()(i) <= rankTolerance*evMax )\n        {\n          rank--;\n          w(i) = T(0);\n          winv(i) = T(0);\n        }\n        else\n        {\n          w(i) = std::sqrt(eigSolv.eigenvalues()(i));\n          winv(i) = T(1)/w(i);\n        }\n      }\n    }\n\n    // calculate B and Binv\n    B.resize(n,n);\n    Binv.resize(n,n);\n    EigenMap(Binv) = dinv.asDiagonal() * eigSolv.eigenvectors() * winv.asDiagonal();\n    EigenMap(B) = w.asDiagonal() * eigSolv.eigenvectors().transpose() * d.asDiagonal();\n\n    // reorder, so the part corresponding to the largest eigenvalues are first\n    for(int i = 0; i < n; i++)\n    {\n      for(int j = 0; j < n/2; j++)\n      {\n        int k = n-j-1;\n        std::swap(B(j,i), B(k,i));\n        std::swap(Binv(i,j), Binv(i,k));\n      }\n    }\n\n    return rank;\n  }\n\n}\n\n\n#endif // PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n", "meta": {"hexsha": "8116c9a12da14750949d1153b73cf089e51c7b17", "size": 3800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_tensor2_qb_decomposition.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_tensor2_qb_decomposition.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "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/pitts_tensor2_qb_decomposition.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "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.0076335878, "max_line_length": 106, "alphanum_fraction": 0.6134210526, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6547711318199639}}
{"text": "#ifndef GENERATE_GALTON_WATSON_HPP\n#define GENERATE_GALTON_WATSON_HPP\n\n#include <cstdlib>\n#include <string>\n#include <queue>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <boost/random.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\n/**\n * Given:\n * (1) Distribution: Poisson, Negative Geometric, Binomial\n * (2) Number of nodes for the conditioned Galton-Watson process.\n * (3) Parameters needed for the distributions:\n *    (a) Probability of success (p)\n *    (b) Lambda if using Poisson distribution\n *    (c) 'k', the total number of trials if we are using Binomial\n *    (d) Seed value for the random number\n */\nstruct generate_Galton_Watson_t {\n  typedef boost::mt19937 engine_type;\n  typedef boost::binomial_distribution<int, double> binomial_type;\n  typedef boost::uniform_real<double> uni_real_type;\n  typedef boost::exponential_distribution<double> exp_real_type;\n  typedef boost::uniform_int<int> uni_int_type;\n\n  typedef boost::adjacency_list\n                   <boost::listS,\n                    boost::vecS,\n                    boost::bidirectionalS,\n                    boost::property<boost::vertex_name_t, std::string,\n                    boost::property<boost::vertex_distance_t, double> >,\n                    boost::property<boost::edge_weight_t, double> > graph_type;\n    typedef boost::property_map<graph_type, boost::vertex_index_t>::type \n                                                vertex_index_map_t;\n    typedef boost::property_map<graph_type, boost::vertex_name_t>::type \n                                                vertex_name_map_t;\n    typedef boost::property_map<graph_type, boost::vertex_distance_t>::type \n                                                vertex_distance_map_t;\n    typedef boost::property_map<graph_type, boost::edge_weight_t>::type\n                                                edge_weight_map_t;\n    typedef boost::graph_traits<graph_type>::vertex_descriptor vertex_t;\n\n  private:\n\n  struct always_1_t {\n    typedef double result_type;\n    result_type operator()() { return 1.0; }\n  };\n\n  struct Poisson_computer_t {\n    typedef boost::poisson_distribution<int, double> dist_type; \n    int lambda;\n\n    Poisson_computer_t (int lambda) : lambda(lambda) {}\n\n    double operator()(int i) const { \n      return (pow(lambda,i)*exp(-lambda)) / boost::math::factorial<double>(i);\n    }\n\n    dist_type operator()() const { return dist_type(lambda); }\n  };\n\n  struct geometric_computer_t {\n    typedef boost::geometric_distribution<int, double> dist_type; \n    double p;\n    geometric_computer_t (double p) : p(p) {}\n\n    double operator()(int i) const { return pow((1-p), i) * p; }\n\n    dist_type operator()() const { return dist_type(p); }\n  };\n\n  struct binomial_computer_t {\n    typedef boost::binomial_distribution<int, double> dist_type; \n    int k;\n    double p;\n    binomial_computer_t (int k, double p) : k(k), p(p) {}\n\n    double operator()(int i) const { \n      return\n      boost::math::binomial_coefficient<double>(k,i)*pow(p,i)*pow((1-p),(k-i));\n    }\n\n    dist_type operator()() const { return dist_type(k,p); }\n  };\n\n  struct binary_0_2_computer_t {\n    struct binary_0_2_distribution {\n      typedef int result_type;\n      boost::bernoulli_distribution<double> distro;\n      \n      binary_0_2_distribution(double p) : distro(p) {}\n\n      template <typename EngineType>\n      int operator()(EngineType& engine) {return (distro(engine))?2:0;}\n    };\n    typedef binary_0_2_distribution dist_type;\n\n    binary_0_2_computer_t (double p) : p(p) {}\n\n    double operator()(int i) const {\n      if (2==i) return p;\n      else if (0==i) return (1-p);\n      else return 0;\n    }\n\n    dist_type operator()() const { return dist_type(p); }\n    \n    private:\n    double p;\n  };\n\n  struct binary_0_1_2_computer_t {\n    typedef boost::uniform_int<int> dist_type;\n    double operator()(int i) const { \n      if (0==i || 1==i || 2==i) return 1./3.;\n      else return 0;\n    }\n\n    dist_type operator()() const { return dist_type(0,2); }\n  };\n\n  /**\n   * Thin wrapper around boost::uniform<> so that it conforms to random_shuffle.\n   */\n  struct random_functor_t : std::unary_function<int, int> {\n    engine_type engine;\n    \n    random_functor_t (engine_type engine) : engine(engine) {}\n\n    int operator()(const int& ULIMIT) {\n      uni_int_type dist (0, ULIMIT-1);\n      return dist(engine);\n    }\n  };\n\n  static void rotate_to_get_tree (std::vector<int>& psi_vec) {\n    /** Get the vector S for the queues in the tree */\n    size_t n = psi_vec.size();\n    std::vector<int> S(n);\n\n    for (size_t i=0; i<n; ++i) S[i] = ((0==i)?1:(S[i-1]))+(psi_vec[i]-1);\n\n    int min_ele=std::numeric_limits<int>::max();\n    int min_index=-1;\n    for (size_t i=0; i<n; ++i)\n      if (min_ele>S[i]) { min_ele=S[i]; min_index=i; }\n\n    std::rotate(psi_vec.begin(), psi_vec.begin()+min_index+1, psi_vec.end());\n  }\n\n  template <typename WDistribution>\n  static graph_type generate_impl (int n, \n                                   const std::vector<int>& psi_vec,\n                                   WDistribution w_prng,\n                                   int verbosity) {\n    graph_type G;\n    vertex_name_map_t name_map = boost::get (boost::vertex_name, G);\n    vertex_distance_map_t dist_map = boost::get (boost::vertex_distance, G);\n    edge_weight_map_t weight_map = boost::get (boost::edge_weight, G);\n\n    /** Set up a queue for the children and add the root vertex */\n    vertex_t root = boost::add_vertex(G);\n    boost::put (name_map, root, boost::lexical_cast<std::string>(0));\n    boost::put (dist_map, root, 0);\n\n    std::queue<vertex_t> vertex_queue;\n    vertex_queue.push(root);\n\n    /** Count the number of children left */\n    int n_left = (n-1);\n\n    /** Iterate till we are left with nothing or we have maxed out children */\n    while ((0<=n_left) && (false==vertex_queue.empty())) {\n      const vertex_t parent = vertex_queue.front();\n      vertex_queue.pop();\n\n#pragma omp critical\n      if (1<verbosity) std::cout << \"Popped \" << parent << std::endl;\n\n      int num_children = psi_vec[parent];\n#pragma omp critical\n      if (1<verbosity) std::cout << \"num children of \" << parent << \" = \" \n                               << num_children << std::endl;\n\n      for (int child_number=0; child_number<num_children; ++child_number) {\n        const vertex_t child = boost::add_vertex(G);\n        vertex_queue.push(child);\n        boost::put (name_map, \n                    child, \n                    boost::get (name_map, parent) +\n                    boost::lexical_cast<std::string>(child_number));\n\n        /** \n         * Duplicating a map here, but I think it's fine. We need the vertex\n         * weights to easily be able to get the Dyck/Harris paths.\n         */ \n        double edge_weight = w_prng();\n        boost::put (dist_map, child, edge_weight);\n        boost::put (weight_map, \n                    (boost::add_edge (parent, child, G)).first,\n                    edge_weight);\n\n        --n_left;\n      }\n\n#pragma omp critical\n      if (1<verbosity) std::cout << \"N Left = \" << n_left << std::endl;\n    }\n\n    return G;\n  }\n\n  template <typename ProbabilityComputer>\n  static graph_type generate_tree_stupid (int n,\n                                          int seed,\n                                          ProbabilityComputer compute,\n                                          bool use_random_weights,\n                                          int verbosity) {\n    // This is the stupid way of generating the required random tree.\n    // We simply want to fill up the tree as long as it has at least\n    // the required number of nodes, we are happy. Please use it only\n    // as a counter example.\n\n    // A vector to hold the number of children for each node\n    std::vector<int> psi_vec (n, 0);\n\n    // Get a new random engine\n    engine_type engine(seed);\n\n    // Get the distribution that we are interested in\n    typename ProbabilityComputer::dist_type prng = compute();\n\n    // Now, all we need to do is iterate over and over again\n    int num_children;\n    do {\n\n      // Start with 0 edges in the beginning\n      num_children = 0;\n\n      // Loop to assign edges/children to nodes\n      for (int i=0; \n           (num_children<(n-1)) && (i<psi_vec.size()); \n           ++i) {\n      \n        // Figure out how many children we want to give this node.\n        int num_children_for_i = prng(engine);\n        if ((num_children_for_i+num_children) > (n-1)) {\n          num_children_for_i = (n-1) - num_children;\n        }\n\n        num_children += num_children_for_i;\n        psi_vec[i] = num_children_for_i; \n      }\n\n    } while (num_children != (n-1));\n\n    random_functor_t shuffle_prng (engine);\n    std::random_shuffle (psi_vec.begin(), psi_vec.end(), shuffle_prng);\n\n    if (2<verbosity) {\n      for (int i=0; i<n; ++i) std::cout<<psi_vec[i]<<\" \"; \n      std::cout<<std::endl;\n    }\n\n    rotate_to_get_tree (psi_vec);\n\n    if (2<verbosity) {\n      for (int i=0; i<n; ++i) std::cout<<psi_vec[i]<<\" \"; \n      std::cout<<std::endl;\n    }\n    \n\n    if (use_random_weights) {\n      boost::variate_generator<engine_type, uni_real_type> \n                            w_prng (engine_type(), uni_real_type(0.0,1.0));\n      return generate_impl (n, psi_vec, w_prng, verbosity);\n    } else {\n      return generate_impl (n, psi_vec, always_1_t(), verbosity);\n    }\n  }\n\n  template <typename ProbabilityComputer>\n  static graph_type generate_tree (int n,\n                                   int seed,\n                                   ProbabilityComputer compute,\n                                   bool use_random_weights,\n                                   int verbosity) {\n\n    std::vector<int> N_j_vec;\n    engine_type engine(seed);\n    int j_times_N_j, j;\n\n    do {\n\n      j_times_N_j = j = 0;\n      int sum_of_N_i = 0;\n      int i = 0;\n      double sum_of_p_i = 0;\n      N_j_vec.resize(0);\n      while (0 != (n-sum_of_N_i)) {\n        const double p_i = compute(i);\n        engine_type new_engine(engine());\n        binomial_type dist((n-sum_of_N_i), p_i/(1-sum_of_p_i));\n        const int N_j = dist(new_engine);\n        N_j_vec.push_back (N_j);\n        sum_of_N_i += N_j;\n        sum_of_p_i += p_i;\n        j_times_N_j += j*N_j;\n        ++i;\n        ++j;\n      }\n\n      if (2 < verbosity) std::cout << \"j*N_j = \" << j_times_N_j << std::endl;\n\n    } while (j_times_N_j != (n-1));\n\n    std::vector<int> psi_vec (n, 0);\n    int offset = 0;\n    for (int j=0; j<N_j_vec.size(); ++j) {\n      for (int i=0; i<N_j_vec[j]; ++i) psi_vec[offset+i] = j;\n      offset += N_j_vec[j];\n    }\n\n    random_functor_t shuffle_prng (engine);\n    std::random_shuffle (psi_vec.begin(), psi_vec.end(), shuffle_prng);\n\n    if (2<verbosity) {\n      for (int i=0; i<n; ++i) std::cout<<psi_vec[i]<<\" \"; \n      std::cout<<std::endl;\n    }\n\n    rotate_to_get_tree (psi_vec);\n\n    if (2<verbosity) {\n      for (int i=0; i<n; ++i) std::cout<<psi_vec[i]<<\" \"; \n      std::cout<<std::endl;\n    }\n\n    if (use_random_weights) {\n      boost::variate_generator<engine_type, uni_real_type> \n                            w_prng (engine_type(), uni_real_type(0.0,1.0));\n      return generate_impl (n, psi_vec, w_prng, verbosity);\n    } else {\n      return generate_impl (n, psi_vec, always_1_t(), verbosity);\n    }\n  }\n\n  template <typename ProbabilityComputer>\n  static graph_type generate_tree_dispatcher (int n,\n                                              int seed,\n                                              ProbabilityComputer compute,\n                                              bool use_random_weights,\n                                              int verbosity,\n                                              bool use_stupid_tree_gen) {\n    if (use_stupid_tree_gen) {\n      return generate_tree_stupid (n, seed, compute, use_random_weights, \n                                   verbosity);\n    } else {\n      return generate_tree (n, seed, compute, use_random_weights, verbosity);\n    }\n  }\n\n  public:\n\n  static graph_type generate_Poisson (int n,\n                                      int seed,\n                                      int lambda,\n                                      bool use_random_weights,\n                                      int verbosity,\n                                      bool use_stupid_tree_gen) {\n    return generate_tree_dispatcher (n, seed, Poisson_computer_t(lambda), \n                          use_random_weights, verbosity, use_stupid_tree_gen);\n  }\n\n  static graph_type generate_Geometric (int n,\n                                        int seed,\n                                        double p,\n                                        bool use_random_weights,\n                                        int verbosity,\n                                        bool use_stupid_tree_gen) {\n    return generate_tree_dispatcher (n, seed, geometric_computer_t(p), \n                          use_random_weights, verbosity, use_stupid_tree_gen);\n  }\n\n  static graph_type generate_Binomial (int n,\n                                       int seed,\n                                       int k,\n                                       double p,\n                                       bool use_random_weights,\n                                       int verbosity,\n                                       bool use_stupid_tree_gen) {\n    return generate_tree_dispatcher (n, seed, binomial_computer_t(k, p), \n                          use_random_weights, verbosity, use_stupid_tree_gen);\n  }\n\n  static graph_type generate_Binary_0_2 (int n,\n                                         int seed,\n                                         double p,\n                                         bool use_random_weights,\n                                         int verbosity,\n                                         bool use_stupid_tree_gen) {\n    return generate_tree_dispatcher (n, seed, binary_0_2_computer_t(p),\n                          use_random_weights, verbosity, use_stupid_tree_gen);\n  }\n\n  static graph_type generate_Binary_0_1_2 (int n,\n                                           int seed,\n                                           bool use_random_weights,\n                                           int verbosity,\n                                           bool use_stupid_tree_gen) {\n    return generate_tree_dispatcher (n, seed, binary_0_1_2_computer_t(), \n               use_random_weights, verbosity, use_stupid_tree_gen);\n  }\n};\n\n#endif // GENERATE_GALTON_WATSON_HPP\n", "meta": {"hexsha": "e1838fb6bfb22115e913bc166063452c58a93c20", "size": 14679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "generate_Galton_Watson.hpp", "max_stars_repo_name": "karthikbharath/Trees_DyckPaths", "max_stars_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_Galton_Watson.hpp", "max_issues_repo_name": "karthikbharath/Trees_DyckPaths", "max_issues_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_Galton_Watson.hpp", "max_forks_repo_name": "karthikbharath/Trees_DyckPaths", "max_forks_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_forks_repo_licenses": ["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.0580046404, "max_line_length": 80, "alphanum_fraction": 0.5620955106, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6547711264511651}}
{"text": "// Copyright (c) 2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n// \n//\n// Author(s)     : Sebastien Loriot, Sylvain Pion\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/CGAL_Ipelet_base.h> \n#include <CGAL/linear_least_squares_fitting_2.h>\n#include <boost/utility.hpp>\n\nnamespace CGAL_pca{\n\n//~ typedef CGAL::Exact_predicates_exact_constructions_kernel                 Kernel;\ntypedef CGAL::Simple_cartesian<double>                 Kernel;\n  \nconst std::string Slab[] = {\n  \"PCA\",\"Help\"\n};\n\nconst std::string Hmsg[] = {\n  \"(Principal Component Analysis) given a set of points, draw a segment that is on the line defined by the eigen vector associated to the highest eigen value of the covariance matrix of the input points\"\n};\n\nclass pcaIpelet \n  : public CGAL::Ipelet_base<Kernel,2>{\npublic:\n  pcaIpelet()\n    :CGAL::Ipelet_base<Kernel,2>(\"PCA\",Slab,Hmsg){}\n  void protected_run(int);\n};\n\n\nvoid pcaIpelet::protected_run(int fn)\n{\n  if (fn==1) {\n    show_help();\n    return;\n  }\n\n  \n  std::list<Point_2> pt_list;\n  std::list<Circle_2> cir_list;\n  std::list<Polygon_2> poly_list;\n  std::list<Kernel::Triangle_2> tri_list;\n  std::list<Segment_2> sg_list;\n  \n  Iso_rectangle_2 bbox=\n    read_active_objects(\n      CGAL::dispatch_or_drop_output<Point_2,Polygon_2,Circle_2,Segment_2>(\n        std::back_inserter(pt_list),\n        std::back_inserter(poly_list),\n        std::back_inserter(cir_list),\n        std::back_inserter(sg_list)\n      )\n    );\n\n  \n  \n  for (std::list<Polygon_2>::iterator it=poly_list.begin();it!=poly_list.end();++it)\n    if (it->size()==3){\n      tri_list.push_back(Kernel::Triangle_2(*(it->vertices_begin()),\n                                            *boost::next(it->vertices_begin()),\n                                            *boost::next(it->vertices_begin(),2)\n                                            ));\n    }\n    else{\n      print_error_message(\"This implementation is limited to triangles\");\n      return;          \n    }\n  \n  \n  int s=0;\n  \n  if (!pt_list.empty()) s=1;\n  if (!cir_list.empty()) s+=2;\n  if (!tri_list.empty()) s+=4;\n  if (!sg_list.empty()) s+=8;\n  \n  \n  if (s==0) {\n    print_error_message(\"Nothing is selected\");\n    return;\n  }\n  \n  \n  Kernel::Line_2 line;\n  Kernel::Point_2 centroid;\n  \n  switch (s){\n    case 1://points\n      linear_least_squares_fitting_2(pt_list.begin(),pt_list.end(),line,centroid,CGAL::Dimension_tag<0>());\n      break;\n    case 2://circles\n      linear_least_squares_fitting_2(cir_list.begin(),cir_list.end(),line,centroid,CGAL::Dimension_tag<2>());\n      break;\n    case 4://triangles\n      linear_least_squares_fitting_2(tri_list.begin(),tri_list.end(),line,centroid,CGAL::Dimension_tag<2>());\n      break;\n    case 8://segments\n      linear_least_squares_fitting_2(sg_list.begin(),sg_list.end(),line,centroid,CGAL::Dimension_tag<1>());\n      break;  \n    default:\n      print_error_message(\"Please select a set of points or segments or triangles or circles\");\n      return;    \n  }\n  \n  \n  \n  CGAL::Object obj_cgal = CGAL::intersection(line,bbox);\n  Segment_2 seg;\n  if (CGAL::assign(seg, obj_cgal))\n    draw_in_ipe(seg);\n\n    \n\n}\n\n}\n\nCGAL_IPELET(CGAL_pca::pcaIpelet)\n\n", "meta": {"hexsha": "0f8a61f87b6fd68c009b90b08763dd8250e1f80f", "size": 3370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/pca.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/CGAL_ipelets/pca.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/CGAL_ipelets/pca.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": 25.9230769231, "max_line_length": 203, "alphanum_fraction": 0.6400593472, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6547686357300774}}
{"text": "/*\n * Copyright 2011-2013 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\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#include <iostream>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\ntypedef boost::numeric::ublas::vector< double > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , const double t )\n{\n    const double sigma( 10.0 );\n    const double R( 28.0 );\n    const double b( 8.0 / 3.0 );\n    \n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nusing namespace boost::numeric::odeint;\n\n//[ublas_main\nint main()\n{\n    state_type x(3);\n    x[0] = 10.0; x[1] = 5.0 ; x[2] = 0.0;\n    typedef runge_kutta_dopri5< state_type > stepper;\n    integrate_const( make_dense_output< stepper >( 1E-6 , 1E-6 ) , lorenz , x ,\n                     0.0 , 10.0 , 0.1 );\n}\n//]\n", "meta": {"hexsha": "0e3958d07bc6a071f278731e0bdf3ae0bb2ae346", "size": 1009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/ublas/lorenz_ublas.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/ublas/lorenz_ublas.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/ublas/lorenz_ublas.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.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": 24.6097560976, "max_line_length": 79, "alphanum_fraction": 0.6075322101, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.654768623014384}}
{"text": "#include <iostream>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operations.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <random>\n#include \"mnist/reader.hpp\"\n#include \"perceptron/PerceptronMonoLayer.hpp\"\n#include \"perceptron/act_funs.hpp\"\n#include \"perceptron/ItemNN.hpp\"\n\nusing namespace cv;\nusing namespace boost;\nusing namespace boost::numeric;\nusing namespace std;\n\n\nvoid randomizeMatrix(boost::numeric::ublas::matrix<double> &matrix);\n\nvoid randomizeVector(boost::numeric::ublas::vector<double> &vect);\n\n\nublas::vector<double> imageToVector(cv::Mat const &mat) {\n    size_t nbPixels = mat.rows * mat.cols;\n    ublas::vector<double> v(nbPixels);\n    for (size_t i = 0; i < nbPixels; i++) {\n        auto a = (double) mat.at<unsigned char>(i);\n        v.insert_element(i, a>(255./2.)?1:0);\n    }\n    return v;\n}\n\nint main(int argc, char ** argv) {\n\n    using namespace boost::numeric::ublas;\n\n    int numCycles;\n    if(argc > 1)\n        numCycles = atoi(argv[1]);\n    else\n        numCycles =25;\n\n\n    double (*seuil)(double) = act_f::noActFun<double>;\n\n\n    string filename = \"../res/train-images-idx3-ubyte\";\n    size_t image_size = 28 * 28;\n\n    std::vector<cv::Mat> vec_entrees;\n    std::vector<double> vec_labels;\n    std::vector<cv::Mat> vec_entrees_test;\n    std::vector<double> vec_labels_test;\n    read_Mnist(filename, vec_entrees);\n    read_Mnist_Label(\"../res/train-labels-idx1-ubyte\", vec_labels);\n    read_Mnist(\"../res/t10k-images-idx3-ubyte\", vec_entrees_test);\n    read_Mnist_Label(\"../res/t10k-labels-idx1-ubyte\", vec_labels_test);\n\n    std::vector<ItemNN<double>> vec_train;\n    for (int i = 0; i < vec_entrees.size(); ++i) {\n        vec_train.emplace_back(vec_labels[i], vec_entrees[i], imageToVector);\n    }\n    vec_entrees.clear();\n    vec_labels.clear();\n    std::vector<ItemNN<double>> vec_test;\n    for (int i = 0; i < vec_entrees_test.size(); ++i) {\n        vec_test.emplace_back(vec_labels_test[i], vec_entrees_test[i], imageToVector);\n    }\n    vec_entrees_test.clear();\n    vec_labels_test.clear();\n\n    std::vector<Neuron> neuronnes;\n    for (int i = 0; i < 10; ++i) {\n        ublas::vector<double> weigthN(image_size);\n        randomizeVector(weigthN);\n        neuronnes.emplace_back(weigthN, seuil);\n    }\n\n\n    PerceptronMonoLayer perceptronMonoLayer(neuronnes);\n    perceptronMonoLayer.learn(vec_train,numCycles);\n    cout << \"End of learning\" << endl;\n    cout << \"Begin tests\" << endl;\n    perceptronMonoLayer.test(vec_test);\n\n    neuronnes.clear();\n\n    cv::Mat imageTest = imread(\"../res/test.png\",cv::ImreadModes::IMREAD_GRAYSCALE);\n\n    ItemNN<double> itemNN(5,imageTest,imageToVector);\n\n    cout << \"test with gimp image(5):\" <<(\n         perceptronMonoLayer.test(itemNN)? \"true\":\"false\") << endl;\n\n\n    return 0;\n}\n\n/**\n * Fonction qui permet d'initialiser un vecteur a des poids al\u00e9atoires\n * entre -1 et 1\n * @param vect \u00e0 initialiser\n */\nvoid randomizeVector(boost::numeric::ublas::vector<double> &vect) {\n    std::random_device rd;\n    std::mt19937 mt(rd());\n    std::uniform_real_distribution<double> dist(0, 1);\n\n    for (size_t i = 0; i < vect.size(); i++) {\n        vect(i) = dist(mt);\n    }\n}\n\n\n", "meta": {"hexsha": "6cd0ea62f35106a948d6e28802d768112dceb589", "size": 3318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "SamBlaise/perceptron_cpp", "max_stars_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_stars_repo_licenses": ["MIT"], "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": "SamBlaise/perceptron_cpp", "max_issues_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T21:44:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T23:10:24.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "SamBlaise/perceptron_cpp", "max_forks_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_forks_repo_licenses": ["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.1186440678, "max_line_length": 86, "alphanum_fraction": 0.6681735986, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6547686209895519}}
{"text": "#define BOOST_TEST_MODULE SRF\n#include <boost/test/included/unit_test.hpp>\n\n#include <limits>\n#include <tuple>\n\ntypedef std::tuple<float, double, long double> test_types;\n\n#include <triumf/numpy.hpp>\n#include <triumf/superconductivity/phenomenology.hpp>\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(halbritter_gap, T, test_types) {\n  BOOST_TEST(triumf::superconductivity::phenomenology::reduced_gap<T>(-10.0) ==\n             static_cast<T>(1.0));\n  BOOST_TEST(triumf::superconductivity::phenomenology::reduced_gap<T>(0.0) ==\n             static_cast<T>(1.0));\n  BOOST_TEST(triumf::superconductivity::phenomenology::reduced_gap<T>(1.0) ==\n             static_cast<T>(0.0));\n  BOOST_TEST(triumf::superconductivity::phenomenology::reduced_gap<T>(10.0) ==\n             static_cast<T>(0.0));\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(penetration_depth, T, test_types) {\n  BOOST_TEST(\n      triumf::superconductivity::phenomenology::reduced_penetration_depth<T>(\n          -10.0, 4) == static_cast<T>(1.0));\n  BOOST_TEST(\n      triumf::superconductivity::phenomenology::reduced_penetration_depth<T>(\n          0.0, 4) == static_cast<T>(1.0));\n  BOOST_TEST(\n      triumf::superconductivity::phenomenology::reduced_penetration_depth<T>(\n          1.0, 4) == std::numeric_limits<T>::infinity());\n  BOOST_TEST(\n      triumf::superconductivity::phenomenology::reduced_penetration_depth<T>(\n          10.0, 4) == std::numeric_limits<T>::infinity());\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(critical_temperature, T, test_types) {\n  // define some constants to use in the tests\n  constexpr T T_c = 9.25; // K\n  constexpr T B_c2 = 400; // mT\n  constexpr T gamma = 2.0;\n  // explicit tests for edge cases\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature<T>(\n                 -1.0 * B_c2, T_c, B_c2, gamma) == static_cast<T>(T_c));\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature<T>(\n                 0.0 * B_c2, T_c, B_c2, gamma) == static_cast<T>(T_c));\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature<T>(\n                 1.1 * B_c2, T_c, B_c2, gamma) == static_cast<T>(0.0));\n  // tests for valid input range\n  for (const auto &B : triumf::numpy::linspace<T>(0.0, B_c2, 100)) {\n    BOOST_TEST(\n        triumf::superconductivity::phenomenology::critical_temperature<T>(\n            B, T_c, B_c2, gamma) <= T_c);\n  }\n}\n\n//\nBOOST_AUTO_TEST_CASE_TEMPLATE(critical_temperature_II, T, test_types) {\n  // define some constants to use in the tests\n  constexpr T T_c = 9.25; // K\n  constexpr T B_c2 = 400; // mT\n  constexpr T gamma = 2.0;\n  // explicit tests for edge cases\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature_II<T>(\n                 -1.0 * B_c2, T_c, B_c2) == static_cast<T>(T_c));\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature_II<T>(\n                 0.0 * B_c2, T_c, B_c2) == static_cast<T>(T_c));\n  BOOST_TEST(triumf::superconductivity::phenomenology::critical_temperature_II<T>(\n                 1.1 * B_c2, T_c, B_c2) == static_cast<T>(0.0));\n  // tests for valid input range\n  for (const auto &B : triumf::numpy::linspace<T>(0.0, B_c2, 100)) {\n    BOOST_TEST(\n        triumf::superconductivity::phenomenology::critical_temperature_II<T>(\n            B, T_c, B_c2) <= T_c);\n  }\n}\n", "meta": {"hexsha": "2bccd3ce6f6459bd259f34c549b1e32ed1a49cbc", "size": 3296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/superconductivity_phenomenology.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/superconductivity_phenomenology.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/superconductivity_phenomenology.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.6913580247, "max_line_length": 82, "alphanum_fraction": 0.6747572816, "num_tokens": 979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6547600826120553}}
{"text": "#include <seir.h>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <iostream>\n#include <functional>\n#include <algorithm>\n#include <limits>\n\n#include <math.h>\n#if !defined(max)\n#define max(a, b) (a > b ? a : b)\n#endif\n\n#if !defined(min)\n#define min(a, b) (a < b ? a : b)\n#endif\n\n#define NSTATES 9\ntypedef std::array<double, NSTATES> StateType;\n\n// odeing namespace access\nnamespace odeint = boost::numeric::odeint;\n\nSEIR::SEIR()\n    : R0Table_(), Tinc_(2.5), Tinf_(5.0), Tfat_(30), Tmrec_(12), Threc_(30),\n      pMild_(0.8), pFat_(0.01), duration_(300), population_(1000000), dt_(1),\n      Hc_(1), pfat_increase_nohospital_(1.0)\n{\n    SetR0(2.5);\n}\n\nstatic bool operator<(const R0TableElement &a, const R0TableElement &b)\n{\n    return (a.time < b.time);\n}\n\nvoid SEIR::SetR0(double R0, double time)\n{\n    if (time < 0) {\n        R0Table_.clear();\n        R0Table_.push_back(R0TableElement(R0, 0));\n        return;\n    }\n    R0Table_.push_back(R0TableElement(R0, time));\n    R0Table_.sort();\n}\n\nResultsType SEIR::compute(void)\n{\n    StateType state0;\n    memset(state0.data(), 0, sizeof(double) * NSTATES);\n    state0[0] = 1.0;\n    state0[1] = 1.0 / (double)population_;\n\n    typedef odeint::runge_kutta_cash_karp54<StateType, double, StateType,\n                                            double>\n        error_stepper_type;\n    typedef odeint::controlled_runge_kutta<error_stepper_type>\n        controlled_stepper_type;\n    // typedef odeint::dense_output_runge_kutta<controlled_stepper_type>\n    //   dense_stepper_type;\n\n    // Create an output\n    double nsteps = (double)duration_ / (double)dt_;\n    if (::fmod(nsteps, 1.0) < std::numeric_limits<double>::epsilon())\n        nsteps = nsteps + 1;\n    else\n        nsteps = ::ceil(nsteps);\n\n    ResultsType results;\n    results.resize((int)nsteps);\n    uint32_t counter = 0;\n\n    error_stepper_type stepper;\n    odeint::integrate_const(\n        stepper,\n        [this](const StateType &state, StateType &statedot, double t) {\n            // statedot.resize(NSTATES);\n\n            double S = state[0];   // susceptible\n            double E = state[1];   // exposed\n            double Inf = state[2]; // Infectious\n            double M = state[3];   // Mild case\n            double Hrec = state[4];\n            double Hfat = state[5];\n\n            // Probability of fatal given hospitalized\n            // and sufficient hospital capacity\n            double pfs_hos = pFat_ / (1.0 - pMild_);\n\n            // Probability of fatal given hospitalized,\n            // and no hospital capacity\n            double pfs_nohos = pfs_hos * (1.0 + pfat_increase_nohospital_);\n\n            // weighted probability of fatal\n            // given hospital capacity\n            double H = Hrec + Hfat;\n            double pfs = pfs_hos;\n            if ((H > Hc_) && (H > 0)) {\n                pfs = (Hc_ / H) * pfs_hos + (H - Hc_) / H * pfs_nohos;\n            }\n\n            // Get the current R0 from the table\n            auto upper = std::lower_bound(R0Table_.begin(), R0Table_.end(),\n                                          R0TableElement(0, t));\n            //[](const R0TableElement &a, double b) { return a.second < b; });\n            if (upper != R0Table_.begin())\n                upper--;\n            double R0 = upper->R0;\n\n            // Update time derivates:\n\n            // Susceptible population:\n            // out: susceptible to exposed\n            auto dS = -R0 / Tinf_ * Inf * S;\n            // Exposed population:\n            // in: susceptible to exposed\n            // out: exposed to infectious\n            auto dE = -dS - E / Tinc_;\n            // Infectious population:\n            // in: exposed to infectious\n            // out: infectious to mild or hospital\n            auto dI = E / Tinc_ - Inf / Tinf_;\n            // Mild case population:\n            // in: infectious to mild\n            // out: mild to recovered (removed)\n            auto dM = pMild_ * Inf / Tinf_ - M / Tmrec_;\n            // Hospitalized population that will recover\n            // in: infectious to hospitalized\n            // out: hospitalized to recovered\n            auto dHrec =\n                (1.0 - pMild_) * (1.0 - pfs) * Inf / Tinf_ - Hrec / Threc_;\n            // Hospitalized population that will not recover\n            // in: infectious to hospitalized\n            // out: hospitalized to fatal\n            auto dHfat = (1.0 - pMild_) * pfs * Inf / Tinf_ - Hfat / Tfat_;\n            // Fatal population:\n            // in: hospitalized to fatal\n            auto dF = Hfat / Tfat_;\n            // Removed population:\n            // in: mild to recovered\n            // in: hospitalized to recovered\n            auto dRm = M / Tmrec_;\n            auto dRh = Hrec / Threc_;\n\n            statedot[0] = dS;\n            statedot[1] = dE;\n            statedot[2] = dI;\n            statedot[3] = dM;\n            statedot[4] = dHrec;\n            statedot[5] = dHfat;\n            statedot[6] = dF;\n            statedot[7] = dRm;\n            statedot[8] = dRh;\n        },\n        state0, 0.0, (double)duration_, dt_,\n        [this, &counter, &results](const StateType &s, double t) {\n            results[counter] = std::vector<double>(s.begin(), s.end());\n            counter++;\n        });\n\n    // Multiply results by population\n    double population = this->population_;\n    for (auto &res : results) {\n        std::transform(res.begin(), res.end(), res.begin(),\n                       [population](double &c) { return population * c; });\n    }\n    return results;\n}\n\n#if 0\nint main(int argc, char *argv[])\n{\n    SEIR seir;\n    seir.Hc_ = .001;\n    seir.R0Table_.clear();\n    seir.R0Table_.push_back(R0TableElement(4.5, 0));\n    seir.R0Table_.push_back(R0TableElement(1.5, 150));\n\n    auto results = seir.compute();\n    auto lr = results[results.size() - 1];\n#if 0\n    for (int i = 0; i < NSTATES; i++) {\n        std::cout << lr[i] << std::endl;\n    }\n#endif\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "ce2b60b59f731e1d0ba8b2da28f4245eee0a9c31", "size": 5923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/seir.cpp", "max_stars_repo_name": "StevenSamirMichael/SEIR", "max_stars_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T15:43:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T15:43:33.000Z", "max_issues_repo_path": "src/seir.cpp", "max_issues_repo_name": "StevenSamirMichael/SEIR", "max_issues_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-12-30T16:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T16:55:44.000Z", "max_forks_repo_path": "src/seir.cpp", "max_forks_repo_name": "StevenSamirMichael/SEIR", "max_forks_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_forks_repo_licenses": ["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.0104712042, "max_line_length": 78, "alphanum_fraction": 0.5461759244, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.654760080136677}}
{"text": "#include <cradle/geometry/polygonal.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <cradle/anonymous.hpp>\n\n#define BOOST_TEST_MODULE polygonal\n#include <cradle/test.hpp>\n\nusing namespace cradle;\nusing namespace boost::assign;\n\n// polygon2\n\nBOOST_AUTO_TEST_CASE(simple_ccw_poly_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(0, 0),\n            make_vector<double>(5, 0),\n            make_vector<double>(2, 2),\n            make_vector<double>(0, 2);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 7.);\n    BOOST_CHECK(!is_inside(poly, make_vector<double>(-1, 1)));\n    BOOST_CHECK(is_inside(poly, make_vector<double>(1, 1)));\n}\n\nBOOST_AUTO_TEST_CASE(simple_cw_poly_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 2),\n            make_vector<double>(2, 2),\n            make_vector<double>(5, 0);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 7.);\n    BOOST_CHECK(!is_inside(poly, make_vector<double>(-1, 1)));\n    BOOST_CHECK(is_inside(poly, make_vector<double>(1, 1)));\n}\n\nBOOST_AUTO_TEST_CASE(triangle_test)\n{\n    triangle<3,double> tri(\n        make_vector<double>(0, 0, 0),\n        make_vector<double>(0, 0, 2),\n        make_vector<double>(0, 1, 0));\n\n    CRADLE_CHECK_ALMOST_EQUAL(get_normal(tri),\n        make_vector<double>(-1, 0, 0));\n}\n\nBOOST_AUTO_TEST_CASE(square_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 16.);\n    BOOST_CHECK(!is_inside(poly, make_vector<double>(-3, 3)));\n    BOOST_CHECK(is_inside(poly, make_vector<double>(-1, 1)));\n}\n\nBOOST_AUTO_TEST_CASE(concave_poly_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 0,  0),\n            make_vector<double>( 2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    CRADLE_CHECK_ALMOST_EQUAL(get_area(poly), 12.);\n    BOOST_CHECK(!is_inside(poly, make_vector<double>(-3, 3)));\n    BOOST_CHECK(!is_inside(poly, make_vector<double>(1, 0)));\n    BOOST_CHECK(is_inside(poly, make_vector<double>(-1, 1)));\n}\n\nBOOST_AUTO_TEST_CASE(edge_view_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(0, 0),\n            make_vector<double>(0, 1),\n            make_vector<double>(1, 1);\n        initialize(&poly.vertices, vertices);\n    }\n\n    vertex2_array::const_iterator\n        vertex_i = poly.vertices.begin(), vertex_j = poly.vertices.end() - 1;\n    for (polygon2_edge_view ev(poly); !ev.done(); ev.advance(),\n        vertex_j = vertex_i++)\n    {\n        BOOST_CHECK_EQUAL(ev.p0(), *vertex_j);\n        BOOST_CHECK_EQUAL(ev.p1(), *vertex_i);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(circle_test)\n{\n    circle<double> circle(make_vector<double>(0, 0), 2);\n    polygon2 poly = as_polygon(circle, 8);\n\n    std::vector<vector<2,double> > correct_vertices;\n    double srt = std::sqrt(2.);\n    correct_vertices +=\n        make_vector<double>(   2,    0),\n        make_vector<double>( srt,  srt),\n        make_vector<double>(   0,    2),\n        make_vector<double>(-srt,  srt),\n        make_vector<double>(  -2,    0),\n        make_vector<double>(-srt, -srt),\n        make_vector<double>(   0,   -2),\n        make_vector<double>( srt, -srt);\n\n    CRADLE_CHECK_RANGES_ALMOST_EQUAL(poly.vertices, correct_vertices);\n}\n\nBOOST_AUTO_TEST_CASE(box_test)\n{\n    box2d box(make_vector<double>(0, 0), make_vector<double>(2, 2));\n    polygon2 poly = as_polygon(box);\n\n    std::vector<vector<2,double> > correct_vertices;\n    correct_vertices +=\n        make_vector<double>(0, 0),\n        make_vector<double>(2, 0),\n        make_vector<double>(2, 2),\n        make_vector<double>(0, 2);\n\n    CRADLE_CHECK_RANGES_ALMOST_EQUAL(poly.vertices, correct_vertices);\n}\n\n// polyset\n\ndouble tolerance = 0.00001;\n\nBOOST_AUTO_TEST_CASE(two_polygons_test)\n{\n    polygon2 poly0, poly1;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 2, -2);\n        initialize(&poly0.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(4, 4),\n            make_vector<double>(4, 5),\n            make_vector<double>(5, 5),\n            make_vector<double>(5, 4);\n        initialize(&poly1.vertices, vertices);\n    }\n\n    polyset region;\n    add_polygon(region, poly0);\n    add_polygon(region, poly1);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(region), 17., tolerance);\n\n    BOOST_CHECK(!is_inside(region, make_vector<double>(-3, 3)));\n    BOOST_CHECK(!is_inside(region, make_vector<double>(3, 3)));\n    BOOST_CHECK(!is_inside(region, make_vector<double>(6, 6)));\n    BOOST_CHECK(is_inside(region, make_vector<double>(-1, 1)));\n    BOOST_CHECK(is_inside(region, make_vector<double>(4.5, 4.5)));\n    BOOST_CHECK(is_inside(region, make_vector<double>(0, 0)));\n}\n\nBOOST_AUTO_TEST_CASE(polygon_with_hole_test)\n{\n    polygon2 poly, hole;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 2, -2);\n        initialize(&poly.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-1, -1),\n            make_vector<double>(-1,  1),\n            make_vector<double>( 1,  1),\n            make_vector<double>( 1, -1);\n        initialize(&hole.vertices, vertices);\n    }\n    polyset frame;\n    add_polygon(frame, poly);\n    add_hole(frame, hole);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(frame), 12., tolerance);\n\n    BOOST_CHECK(!is_inside(frame, make_vector<double>(-3, 3)));\n    BOOST_CHECK(!is_inside(frame, make_vector<double>(0, 0)));\n    BOOST_CHECK(is_inside(frame, make_vector<double>(-1.5, 1.5)));\n}\n\nBOOST_AUTO_TEST_CASE(polyset_as_polygon_list_test)\n{\n    polygon2 outside, hole, inside;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-3, -3),\n            make_vector<double>(-3,  3),\n            make_vector<double>( 3,  3),\n            make_vector<double>( 3, -3);\n        initialize(&outside.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 2, -2);\n        initialize(&hole.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-1, -1),\n            make_vector<double>(-1,  1),\n            make_vector<double>( 1,  1),\n            make_vector<double>( 1, -1);\n        initialize(&inside.vertices, vertices);\n    }\n\n    polyset frame;\n    add_polygon(frame, outside);\n    add_hole(frame, hole);\n    add_polygon(frame, inside);\n\n    std::vector<polygon2> polys = as_polygon_list(frame);\n    BOOST_CHECK_EQUAL(polys.size(), 2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(polys[0]) + get_area(polys[1]),\n        get_area(frame), tolerance);\n\n    polyset reconstructed;\n    add_polygon(reconstructed, polys[0]);\n    add_polygon(reconstructed, polys[1]);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(reconstructed), get_area(frame),\n        tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(polyset_set_operations_test)\n{\n    polygon2 p;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-6, -3),\n            make_vector<double>(-6,  3),\n            make_vector<double>( 6,  3),\n            make_vector<double>( 6, -3);\n        initialize(&p.vertices, vertices);\n    }\n    polyset wide_rect;\n    create_polyset(&wide_rect, p);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(wide_rect), 72., tolerance);\n\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-3, -6),\n            make_vector<double>(-3,  6),\n            make_vector<double>( 3,  6),\n            make_vector<double>( 3, -6);\n        initialize(&p.vertices, vertices);\n    }\n    polyset tall_rect;\n    create_polyset(&tall_rect, p);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(tall_rect), 72., tolerance);\n\n    polyset cross, square;\n    do_set_operation(&cross, set_operation::UNION, wide_rect, tall_rect);\n    do_set_operation(&square, set_operation::INTERSECTION, wide_rect, tall_rect);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(cross), 108., tolerance);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(square), 36., tolerance);\n\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-1, -1),\n            make_vector<double>(-1,  1),\n            make_vector<double>( 1,  1),\n            make_vector<double>( 1, -1);\n        initialize(&p.vertices, vertices);\n    }\n    polyset small_square;\n    create_polyset(&small_square, p);\n    do_set_operation(&cross, set_operation::DIFFERENCE, cross, small_square);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_area(cross), 104., tolerance);\n    BOOST_CHECK(!is_inside(cross, make_vector<double>(0, 0)));\n    BOOST_CHECK(is_inside(cross, make_vector<double>(2, 0)));\n    BOOST_CHECK(!is_inside(cross, make_vector<double>(8, 0)));\n    BOOST_CHECK(is_inside(cross, make_vector<double>(0, -5)));\n}\n\nBOOST_AUTO_TEST_CASE(polyset_comparisons_test)\n{\n    polygon2 poly1, poly2;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-2, -2),\n            make_vector<double>(-2,  2),\n            make_vector<double>( 2,  2),\n            make_vector<double>( 2, -2);\n        initialize(&poly1.vertices, vertices);\n    }\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-1, -1),\n            make_vector<double>(-1,  1),\n            make_vector<double>( 1,  1),\n            make_vector<double>( 1, -1);\n        initialize(&poly2.vertices, vertices);\n    }\n\n    polyset region1;\n    add_polygon(region1, poly1);\n    add_hole(region1, poly2);\n\n    polyset region2;\n    add_polygon(region2, poly1);\n    add_hole(region2, poly2);\n\n    polyset region3;\n    add_polygon(region3, poly1);\n    add_polygon(region3, poly2);\n\n    BOOST_CHECK(almost_equal(region1, region2, 0.001));\n    BOOST_CHECK(!almost_equal(region1, region3, 0.001));\n}\n\n// structure_geometry\n\nBOOST_AUTO_TEST_CASE(structure_geometry_test0)\n{\n    polyset area0, area1, area2;\n\n    add_polygon(area0, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 6),\n        make_vector<double>(3, 3))));\n    BOOST_CHECK_EQUAL(area0.polygons.size(), 1);\n\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(1, 0), make_vector<double>(0, 0),\n        make_vector<double>(0, 1))));\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(1, 3), make_vector<double>(0, 3),\n        make_vector<double>(0, 4))));\n    BOOST_CHECK_EQUAL(area1.polygons.size(), 2);\n\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 1),\n        make_vector<double>(1, 0))));\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(2, 0), make_vector<double>(2, 1),\n        make_vector<double>(3, 0))));\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(4, 0), make_vector<double>(4, 1),\n        make_vector<double>(5, 0))));\n    BOOST_CHECK_EQUAL(area2.polygons.size(), 3);\n\n    structure_geometry volume;\n    volume.slices +=\n        structure_geometry_slice(0.0, 1.5, area0),\n        structure_geometry_slice(1.5, 1.5, area1),\n        structure_geometry_slice(3.0, 1.5, area2);\n\n    BOOST_CHECK(get_slice(volume, -0.8) == 0);\n    BOOST_CHECK(get_slice(volume, -0.7) != 0);\n    BOOST_CHECK(get_slice(volume, 3.7) != 0);\n    BOOST_CHECK(get_slice(volume, 3.8) == 0);\n\n    BOOST_CHECK_EQUAL(get_slice(volume, 1  )->position, 1.5);\n    BOOST_CHECK_EQUAL(get_slice(volume, 1  )->region.polygons.size(), 2);\n    BOOST_CHECK_EQUAL(get_slice(volume, 2.5)->position, 3);\n    BOOST_CHECK_EQUAL(get_slice(volume, 2.5)->region.polygons.size(), 3);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume), 17.25, tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(structure_geometry_test1)\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(area0, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 6),\n        make_vector<double>(3, 3))));\n\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(1, 0), make_vector<double>(0, 0),\n        make_vector<double>(0, 1))));\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(1, 3), make_vector<double>(0, 3),\n        make_vector<double>(0, 4))));\n\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 1),\n        make_vector<double>(1, 0))));\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(2, 0), make_vector<double>(2, 1),\n        make_vector<double>(3, 0))));\n\n    add_polygon(area3, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(4, 0), make_vector<double>(4, 1),\n        make_vector<double>(5, 0))));\n\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 1, area1),\n        structure_geometry_slice(2.0, 1, area2),\n        structure_geometry_slice(2.5, 1, area3);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(0.0, 1, area0),\n        structure_geometry_slice(1.0, 1, area1),\n        structure_geometry_slice(2.0, 1, area2),\n        structure_geometry_slice(2.5, 1, area3);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 11.125, tolerance);\n\n    BOOST_CHECK(almost_equal(volume2, volume2, tolerance));\n    BOOST_CHECK(!almost_equal(volume1, volume2, tolerance));\n}\n\nBOOST_AUTO_TEST_CASE(set_operation_test)\n{\n    polyset area0, area1, area2, area3, area4, area5;\n\n    add_polygon(area0, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 5),\n        make_vector<double>(4, 5), make_vector<double>(4, 0))));\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 5),\n        make_vector<double>(4, 5), make_vector<double>(4, 0))));\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 5),\n        make_vector<double>(4, 5), make_vector<double>(4, 0))));\n\n    add_polygon(area3, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(6, 0), make_vector<double>(6, 5),\n        make_vector<double>(10, 5), make_vector<double>(10, 0))));\n    add_polygon(area4, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(2, 0), make_vector<double>(2, 5),\n        make_vector<double>(6, 5), make_vector<double>(6, 0))));\n    add_polygon(area5, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(0, 5),\n        make_vector<double>(4, 5), make_vector<double>(4, 0))));\n\n    {\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 2, area0),\n        structure_geometry_slice(3.0, 2, area1),\n        structure_geometry_slice(4.5, 1, area2),\n        structure_geometry_slice(6.0, 2, polyset());\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume1), 100., tolerance);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(1.0, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area3),\n        structure_geometry_slice(4.5, 1, area4),\n        structure_geometry_slice(6.0, 2, area5);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 100., tolerance);\n\n    structure_geometry union_;\n    do_set_operation(&union_, set_operation::UNION, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(union_), 190., tolerance);\n\n    structure_geometry intersection;\n    do_set_operation(&intersection, set_operation::INTERSECTION, volume1,\n        volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(intersection), 10., tolerance);\n\n    structure_geometry xor_;\n    do_set_operation(&xor_, set_operation::XOR, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(xor_), 180., tolerance);\n\n    structure_geometry difference;\n    do_set_operation(&difference, set_operation::DIFFERENCE, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 90., tolerance);\n    }\n\n    {\n    structure_geometry volume;\n    volume.slices +=\n        structure_geometry_slice(1.0, 2, area0),\n        structure_geometry_slice(3.0, 2, area1),\n        structure_geometry_slice(4.5, 1, area2),\n        structure_geometry_slice(6.0, 2, polyset());\n\n    structure_geometry result;\n\n    structure_geometry mismatched_volume1;\n    mismatched_volume1.slices +=\n        structure_geometry_slice(1.0, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area3),\n        structure_geometry_slice(4.5, 1, area4);\n    BOOST_CHECK_THROW(\n        do_set_operation(&result, set_operation::UNION,\n            volume, mismatched_volume1),\n        std::exception);\n\n    structure_geometry mismatched_volume2;\n    mismatched_volume2.slices +=\n        structure_geometry_slice(1.0, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area1),\n        structure_geometry_slice(4.5, 1, area2),\n        structure_geometry_slice(6.0, 1, area3);\n    BOOST_CHECK_THROW(\n        do_set_operation(&result, set_operation::UNION,\n            volume, mismatched_volume2),\n        std::exception);\n\n    structure_geometry mismatched_volume3;\n    mismatched_volume3.slices +=\n        structure_geometry_slice(1.1, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area1),\n        structure_geometry_slice(4.5, 1, area2),\n        structure_geometry_slice(6.0, 2, area3);\n    BOOST_CHECK_THROW(\n        do_set_operation(&result, set_operation::UNION,\n            volume, mismatched_volume3),\n        std::exception);\n    }\n\n    {\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area0),\n        structure_geometry_slice(4.5, 1, area1),\n        structure_geometry_slice(6.0, 2, area2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume1), 100., tolerance);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(1.0, 2, area3),\n        structure_geometry_slice(3.0, 2, area4),\n        structure_geometry_slice(4.5, 1, area5),\n        structure_geometry_slice(6.0, 2, polyset());\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 100., tolerance);\n\n    structure_geometry union_;\n    do_set_operation(&union_, set_operation::UNION, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(union_), 160., tolerance);\n\n    structure_geometry intersection;\n    do_set_operation(&intersection, set_operation::INTERSECTION, volume1,\n        volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(intersection), 40., tolerance);\n\n    structure_geometry xor_;\n    do_set_operation(&xor_, set_operation::XOR, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(xor_), 120., tolerance);\n\n    structure_geometry difference;\n    do_set_operation(&difference, set_operation::DIFFERENCE, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 60., tolerance);\n    }\n\n    {\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 2, polyset()),\n        structure_geometry_slice(3.0, 2, area0),\n        structure_geometry_slice(4.5, 1, area1),\n        structure_geometry_slice(6.0, 2, area2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume1), 100., tolerance);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(1.0, 2, area3),\n        structure_geometry_slice(3.0, 2, area4),\n        structure_geometry_slice(4.5, 1, area5),\n        structure_geometry_slice(6.0, 2, polyset());\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 100., tolerance);\n\n    structure_geometry union_;\n    do_set_operation(&union_, set_operation::UNION, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(union_), 160., tolerance);\n\n    structure_geometry intersection;\n    do_set_operation(&intersection, set_operation::INTERSECTION, volume1,\n        volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(intersection), 40., tolerance);\n\n    structure_geometry xor_;\n    do_set_operation(&xor_, set_operation::XOR, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(xor_), 120., tolerance);\n\n    structure_geometry difference;\n    do_set_operation(&difference, set_operation::DIFFERENCE, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 60., tolerance);\n    }\n\n    {\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 2, area0),\n        structure_geometry_slice(3.0, 2, polyset()),\n        structure_geometry_slice(4.5, 1, area1),\n        structure_geometry_slice(6.0, 2, area2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume1), 100., tolerance);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(1.0, 2, area3),\n        structure_geometry_slice(3.0, 2, area4),\n        structure_geometry_slice(4.5, 1, area5),\n        structure_geometry_slice(6.0, 2, polyset());\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 100., tolerance);\n\n    structure_geometry union_;\n    do_set_operation(&union_, set_operation::UNION, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(union_), 180., tolerance);\n\n    structure_geometry intersection;\n    do_set_operation(&intersection, set_operation::INTERSECTION, volume1,\n        volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(intersection), 20., tolerance);\n\n    structure_geometry xor_;\n    do_set_operation(&xor_, set_operation::XOR, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(xor_), 160., tolerance);\n\n    structure_geometry difference;\n    do_set_operation(&difference, set_operation::DIFFERENCE, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 80., tolerance);\n    }\n\n    {\n    structure_geometry volume1;\n    volume1.slices +=\n        structure_geometry_slice(1.0, 2, area0),\n        structure_geometry_slice(3.0, 2, area1),\n        structure_geometry_slice(4.5, 1, area2),\n        structure_geometry_slice(6.0, 2, polyset());\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume1), 100., tolerance);\n\n    structure_geometry volume2;\n    volume2.slices +=\n        structure_geometry_slice(1.0, 2, area3),\n        structure_geometry_slice(3.0, 2, polyset()),\n        structure_geometry_slice(4.5, 1, area4),\n        structure_geometry_slice(6.0, 2, area5);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(volume2), 100., tolerance);\n\n    structure_geometry union_;\n    do_set_operation(&union_, set_operation::UNION, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(union_), 190., tolerance);\n\n    structure_geometry intersection;\n    do_set_operation(&intersection, set_operation::INTERSECTION, volume1,\n        volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(intersection), 10., tolerance);\n\n    structure_geometry xor_;\n    do_set_operation(&xor_, set_operation::XOR, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(xor_), 180., tolerance);\n\n    structure_geometry difference;\n    do_set_operation(&difference, set_operation::DIFFERENCE, volume1, volume2);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(difference), 90., tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(expansion_2d)\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(6, 0),\n        make_vector<double>(6, 6), make_vector<double>(0, 6))));\n\n    add_polygon(area2, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(1, 0),\n        make_vector<double>(1, 1), make_vector<double>(0, 1))));\n\n    structure_geometry original;\n    original.slices +=\n        structure_geometry_slice(1, 1, area1),\n        structure_geometry_slice(2, 1, area2);\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(original), 37., tolerance);\n\n    structure_geometry expanded;\n    expand_in_2d(&expanded, original, 1.);\n\n    BOOST_CHECK(get_volume(expanded) > 65);\n    BOOST_CHECK(get_volume(expanded) < 83);\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.9, 1, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.9, 1, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, 6.9, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, -0.9, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, -0.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.7, -0.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.7, 6.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, 6.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1.9, 1, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.9, 1, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, 1.9, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, -0.9, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, -0.7, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1.7, -0.7, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1.7, 1.7, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, 1.7, 2)));\n}\n\nBOOST_AUTO_TEST_CASE(expansion_3d)\n{\n    polyset area0, area1, area2, area3;\n\n    add_polygon(area1, make_polygon2(anonymous<std::vector<vector2d> >(\n        make_vector<double>(0, 0), make_vector<double>(6, 0),\n        make_vector<double>(6, 6), make_vector<double>(0, 6))));\n\n    structure_geometry original;\n    original.slices +=\n        structure_geometry_slice(-1, 1, polyset()),\n        structure_geometry_slice( 0, 1, polyset()),\n        structure_geometry_slice( 1, 1, area1),\n        structure_geometry_slice( 2, 1, polyset()),\n        structure_geometry_slice( 3, 1, polyset());\n\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(original), 36., tolerance);\n\n    structure_geometry expanded;\n    expand_in_3d(&expanded, original, 1.);\n\n    BOOST_CHECK(get_volume(expanded) > 136);\n    BOOST_CHECK(get_volume(expanded) < 197);\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.9, 1, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.9, 1, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, 6.9, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(1, -0.9, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, -0.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.7, -0.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6.7, 6.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(-0.7, 6.7, 1)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(0, 0, 0)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6, 0, 0)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6, 6, 0)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(0, 6, 0)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(0, 0, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6, 0, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(6, 6, 2)));\n    BOOST_CHECK(is_inside(expanded, make_vector<double>(0, 6, 2)));\n\n    structure_geometry contracted;\n    expand_in_3d(&contracted, original, -1.);\n    CRADLE_CHECK_WITHIN_TOLERANCE(get_volume(contracted), 0., tolerance);\n}\n\nBOOST_AUTO_TEST_CASE(polygon_bounding_box_test)\n{\n    polygon2 poly;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(0, 0),\n            make_vector<double>(-1, -1),\n            make_vector<double>(-3, 0),\n            make_vector<double>(0, 7),\n            make_vector<double>(3, 3),\n            make_vector<double>(3, 2);\n        initialize(&poly.vertices, vertices);\n    }\n    BOOST_CHECK_EQUAL(bounding_box(poly),\n        box2d(make_vector<double>(-3, -1), make_vector<double>(6, 8)));\n}\n\nBOOST_AUTO_TEST_CASE(polyset_bounding_box_test)\n{\n    polygon2 p;\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(-6, -3),\n            make_vector<double>(-6, 3),\n            make_vector<double>(-4, 3),\n            make_vector<double>(-4, -3);\n        initialize(&p.vertices, vertices);\n    }\n    polyset area;\n    create_polyset(&area, p);\n    {\n        std::vector<vertex2> vertices;\n        vertices +=\n            make_vector<double>(2, -6),\n            make_vector<double>(2, -2),\n            make_vector<double>(4, -2),\n            make_vector<double>(4, -6);\n        initialize(&p.vertices, vertices);\n    }\n    add_polygon(area, p);\n\n    box<2,double> bb = bounding_box(area);\n    BOOST_CHECK(almost_equal(bb.corner, make_vector<double>(-6, -6), 0.00001));\n    BOOST_CHECK(almost_equal(bb.size, make_vector<double>(10, 9), 0.00001));\n}\n", "meta": {"hexsha": "06c1d9bcd149ca9754cf80eaeebd47f17b590484", "size": 30225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cradle/tests/geometry/polygonal.cpp", "max_stars_repo_name": "dotdecimal/open-cradle", "max_stars_repo_head_hexsha": "f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cradle/tests/geometry/polygonal.cpp", "max_issues_repo_name": "dotdecimal/open-cradle", "max_issues_repo_head_hexsha": "f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cradle/tests/geometry/polygonal.cpp", "max_forks_repo_name": "dotdecimal/open-cradle", "max_forks_repo_head_hexsha": "f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T17:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T14:22:29.000Z", "avg_line_length": 36.1976047904, "max_line_length": 81, "alphanum_fraction": 0.6600496278, "num_tokens": 8167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.654719649354235}}
{"text": "#include \"k_points_util.h\"\n\n#include <algorithm>\n#include <boost/functional/hash.hpp>\n#include <cmath>\n#include <exception>\n#include <unordered_set>\n#include \"../array_math.h\"\n\nint KPointsUtil::get_n_k_points(const double rcut) {\n  int count = 0;\n  const int n_max = std::floor(static_cast<float>(rcut));\n  double rcut_square = rcut * rcut;\n  for (int i = -n_max; i <= n_max; i++) {\n    for (int j = -n_max; j <= n_max; j++) {\n      for (int k = -n_max; k <= n_max; k++) {\n        if (i * i + j * j + k * k > rcut_square) continue;\n        count++;\n      }\n    }\n  }\n  return count;\n}\n\nstd::vector<std::array<int8_t, 3>> KPointsUtil::generate_k_points(\n    const double rcut) {\n  std::vector<std::array<int8_t, 3>> k_points;\n  const int n_max = std::floor(static_cast<float>(rcut));\n  assert(n_max < 127);\n  double rcut_square = rcut * rcut;\n  for (int i = -n_max; i <= n_max; i++) {\n    for (int j = -n_max; j <= n_max; j++) {\n      for (int k = -n_max; k <= n_max; k++) {\n        if (i * i + j * j + k * k > rcut_square) continue;\n        k_points.push_back(std::array<int8_t, 3>({static_cast<int8_t>(i),\n                                                  static_cast<int8_t>(j),\n                                                  static_cast<int8_t>(k)}));\n      }\n    }\n  }\n  std::stable_sort(\n      k_points.begin(),\n      k_points.end(),\n      [](const auto& a, const auto& b) -> bool {\n        return squared_norm(a) < squared_norm(b);\n      });\n  return k_points;\n}\n\nstd::vector<std::array<int8_t, 3>> KPointsUtil::get_k_diffs(\n    const std::vector<std::array<int8_t, 3>>& k_points) {\n  // Generate all possible differences between two different k points.\n  std::unordered_set<std::array<int8_t, 3>, boost::hash<std::array<int8_t, 3>>>\n      k_diffs_set;\n  std::vector<std::array<int8_t, 3>> k_diffs;\n  const int n_k_points = k_points.size();\n  for (int p = 0; p < n_k_points; p++) {\n    for (int q = 0; q < n_k_points; 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\n  // faster.\n  std::stable_sort(\n      k_diffs.begin(), k_diffs.end(), [](const auto& a, const auto& b) -> bool {\n        return squared_norm(a) < squared_norm(b);\n      });\n\n  return k_diffs;\n}", "meta": {"hexsha": "25599e29ba8c9a8e3e5daaa6111bc765f4776a21", "size": 2423, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/heg/k_points_util.cc", "max_stars_repo_name": "jl2922/hci", "max_stars_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-23T17:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-01T20:15:01.000Z", "max_issues_repo_path": "src/heg/k_points_util.cc", "max_issues_repo_name": "jl2922/hci", "max_issues_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-09-24T14:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-24T14:44:12.000Z", "max_forks_repo_path": "src/heg/k_points_util.cc", "max_forks_repo_name": "jl2922/hci", "max_forks_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_forks_repo_licenses": ["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.3066666667, "max_line_length": 80, "alphanum_fraction": 0.5827486587, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6547196418381726}}
{"text": "#ifndef COORDINATE_CALCULATION\n#define COORDINATE_CALCULATION\n\n#include \"util/coordinate.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/optional.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <utility>\n#include <vector>\n\nnamespace osrm\n{\nnamespace util\n{\nnamespace coordinate_calculation\n{\n\nnamespace detail\n{\nconst constexpr double DEGREE_TO_RAD = 0.017453292519943295769236907684886;\nconst constexpr double RAD_TO_DEGREE = 1. / DEGREE_TO_RAD;\n\ninline double degToRad(const double degree)\n{\n    using namespace boost::math::constants;\n    return degree * (pi<double>() / 180.0);\n}\n\ninline double radToDeg(const double radian)\n{\n    using namespace boost::math::constants;\n    return radian * (180.0 * (1. / pi<double>()));\n}\n}\n\n//! Takes the squared euclidean distance of the input coordinates. Does not return meters!\nstd::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs);\n\ndouble fccApproximateDistance(const Coordinate first_coordinate,\n                              const Coordinate second_coordinate);\n\ndouble haversineDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\ndouble greatCircleDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// get the length of a full coordinate vector, using one of our basic functions to compute distances\ntemplate <class BinaryOperation, typename iterator_type>\ndouble getLength(iterator_type begin, const iterator_type end, BinaryOperation op);\n\n// Find the closest distance and location between coordinate and the line connecting source and\n// target:\n//             coordinate\n//                 |\n//                 |\n// source -------- x -------- target.\n// returns x as well as the distance between source and x as ratio ([0,1])\ninline std::pair<double, FloatCoordinate> projectPointOnSegment(const FloatCoordinate &source,\n                                                                const FloatCoordinate &target,\n                                                                const FloatCoordinate &coordinate);\n\n// find the closest distance between a coordinate and a segment\n// O(1)\ndouble findClosestDistance(const Coordinate coordinate,\n                           const Coordinate segment_begin,\n                           const Coordinate segment_end);\n\n// find the closest distance between a coordinate and a set of coordinates\n// O(|coordinates|)\ntemplate <typename iterator_type>\ndouble findClosestDistance(const Coordinate coordinate,\n                           const iterator_type begin,\n                           const iterator_type end);\n\n// find the closes distance between two sets of coordinates\n// O(|lhs| * |rhs|)\ntemplate <typename iterator_type>\ndouble findClosestDistance(const iterator_type lhs_begin,\n                           const iterator_type lhs_end,\n                           const iterator_type rhs_begin,\n                           const iterator_type rhs_end);\n\n// checks if two sets of coordinates describe a parallel set of ways\ntemplate <typename iterator_type>\nbool areParallel(const iterator_type lhs_begin,\n                 const iterator_type lhs_end,\n                 const iterator_type rhs_begin,\n                 const iterator_type rhs_end);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location,\n                             Coordinate &nearest_location,\n                             double &ratio);\n\nCoordinate centroid(const Coordinate lhs, const Coordinate rhs);\n\ndouble bearing(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// Get angle of line segment (A,C)->(C,B)\ndouble computeAngle(const Coordinate first, const Coordinate second, const Coordinate third);\n\n// find the center of a circle through three coordinates\nboost::optional<Coordinate> circleCenter(const Coordinate first_coordinate,\n                                         const Coordinate second_coordinate,\n                                         const Coordinate third_coordinate);\n\n// find the radius of a circle through three coordinates\ndouble circleRadius(const Coordinate first_coordinate,\n                    const Coordinate second_coordinate,\n                    const Coordinate third_coordinate);\n\n// factor in [0,1]. Returns point along the straight line between from and to. 0 returns from, 1\n// returns to\nCoordinate interpolateLinear(double factor, const Coordinate from, const Coordinate to);\n\n// compute the signed area of a triangle\ndouble signedArea(const Coordinate first_coordinate,\n                  const Coordinate second_coordinate,\n                  const Coordinate third_coordinate);\n\n// check if a set of three coordinates is given in CCW order\nbool isCCW(const Coordinate first_coordinate,\n           const Coordinate second_coordinate,\n           const Coordinate third_coordinate);\n\ntemplate <typename iterator_type>\nstd::pair<Coordinate, Coordinate> leastSquareRegression(const iterator_type begin,\n                                                        const iterator_type end);\n\n// rotates a coordinate around the point (0,0). This function can be used to normalise a few\n// computations around regression vectors\nCoordinate rotateCCWAroundZero(Coordinate coordinate, double angle_in_radians);\n\n// compute the difference vector of two coordinates lhs - rhs\nCoordinate difference(const Coordinate lhs, const Coordinate rhs);\n\n// TEMPLATE/INLINE DEFINITIONS\ninline std::pair<double, FloatCoordinate> projectPointOnSegment(const FloatCoordinate &source,\n                                                                const FloatCoordinate &target,\n                                                                const FloatCoordinate &coordinate)\n{\n    const FloatCoordinate slope_vector{target.lon - source.lon, target.lat - source.lat};\n    const FloatCoordinate rel_coordinate{coordinate.lon - source.lon, coordinate.lat - source.lat};\n    // dot product of two un-normed vectors\n    const auto unnormed_ratio = static_cast<double>(slope_vector.lon * rel_coordinate.lon) +\n                                static_cast<double>(slope_vector.lat * rel_coordinate.lat);\n    // squared length of the slope vector\n    const auto squared_length = static_cast<double>(slope_vector.lon * slope_vector.lon) +\n                                static_cast<double>(slope_vector.lat * slope_vector.lat);\n\n    if (squared_length < std::numeric_limits<double>::epsilon())\n    {\n        return {0, source};\n    }\n\n    const double normed_ratio = unnormed_ratio / squared_length;\n    double clamped_ratio = normed_ratio;\n    if (clamped_ratio > 1.)\n    {\n        clamped_ratio = 1.;\n    }\n    else if (clamped_ratio < 0.)\n    {\n        clamped_ratio = 0.;\n    }\n\n    return {clamped_ratio,\n            {\n                FloatLongitude{1.0 - clamped_ratio} * source.lon +\n                    target.lon * FloatLongitude{clamped_ratio},\n                FloatLatitude{1.0 - clamped_ratio} * source.lat +\n                    target.lat * FloatLatitude{clamped_ratio},\n            }};\n}\n\ntemplate <class BinaryOperation, typename iterator_type>\ndouble getLength(iterator_type begin, const iterator_type end, BinaryOperation op)\n{\n    double result = 0;\n    const auto functor = [&result, op](const Coordinate lhs, const Coordinate rhs) {\n        result += op(lhs, rhs);\n        return false;\n    };\n    // side-effect find adding up distances\n    std::adjacent_find(begin, end, functor);\n\n    return result;\n}\n\ntemplate <typename iterator_type>\ndouble\nfindClosestDistance(const Coordinate coordinate, const iterator_type begin, const iterator_type end)\n{\n    double current_min = std::numeric_limits<double>::max();\n\n    // comparator updating current_min without ever finding an element\n    const auto compute_minimum_distance = [&current_min, coordinate](const Coordinate lhs,\n                                                                     const Coordinate rhs) {\n        current_min = std::min(current_min, findClosestDistance(coordinate, lhs, rhs));\n        return false;\n    };\n\n    std::adjacent_find(begin, end, compute_minimum_distance);\n    return current_min;\n}\n\ntemplate <typename iterator_type>\ndouble findClosestDistance(const iterator_type lhs_begin,\n                           const iterator_type lhs_end,\n                           const iterator_type rhs_begin,\n                           const iterator_type rhs_end)\n{\n    double current_min = std::numeric_limits<double>::max();\n\n    const auto compute_minimum_distance_in_rhs = [&current_min, rhs_begin, rhs_end](\n        const Coordinate coordinate) {\n        current_min = std::min(current_min, findClosestDistance(coordinate, rhs_begin, rhs_end));\n        return false;\n    };\n\n    std::find_if(lhs_begin, lhs_end, compute_minimum_distance_in_rhs);\n    return current_min;\n}\n\ntemplate <typename iterator_type>\nstd::pair<Coordinate, Coordinate> leastSquareRegression(const iterator_type begin,\n                                                        const iterator_type end)\n{\n    // following the formulas of https://faculty.elgin.edu/dkernler/statistics/ch04/4-2.html\n    const auto number_of_coordinates = std::distance(begin, end);\n    BOOST_ASSERT(number_of_coordinates >= 2);\n    const auto extract_lon = [](const Coordinate coordinate) {\n        return static_cast<double>(toFloating(coordinate.lon));\n    };\n\n    const auto extract_lat = [](const Coordinate coordinate) {\n        return static_cast<double>(toFloating(coordinate.lat));\n    };\n\n    double min_lon = extract_lon(*begin);\n    double max_lon = extract_lon(*begin);\n    double min_lat = extract_lat(*begin);\n    double max_lat = extract_lat(*begin);\n\n    for (auto coordinate_iterator = begin; coordinate_iterator != end; ++coordinate_iterator)\n    {\n        const auto c = *coordinate_iterator;\n        const auto lon = extract_lon(c);\n        min_lon = std::min(min_lon, lon);\n        max_lon = std::max(max_lon, lon);\n        const auto lat = extract_lat(c);\n        min_lat = std::min(min_lat, lat);\n        max_lat = std::max(max_lat, lat);\n    }\n    // very small difference in longitude -> would result in inaccurate calculation, check if lat is\n    // better\n    if ((max_lat - min_lat) > 2 * (max_lon - min_lon))\n    {\n        std::vector<util::Coordinate> rotated_coordinates(number_of_coordinates);\n        // rotate all coordinates to the right\n        std::transform(begin, end, rotated_coordinates.begin(), [](const auto coordinate) {\n            return rotateCCWAroundZero(coordinate, detail::degToRad(-90));\n        });\n        const auto rotated_regression =\n            leastSquareRegression(rotated_coordinates.begin(), rotated_coordinates.end());\n        return {rotateCCWAroundZero(rotated_regression.first, detail::degToRad(90)),\n                rotateCCWAroundZero(rotated_regression.second, detail::degToRad(90))};\n    }\n\n    const auto make_accumulate = [](const auto extraction_function) {\n        return [extraction_function](const double sum_so_far, const Coordinate coordinate) {\n            return sum_so_far + extraction_function(coordinate);\n        };\n    };\n\n    const auto accumulated_lon = std::accumulate(begin, end, 0., make_accumulate(extract_lon));\n\n    const auto accumulated_lat = std::accumulate(begin, end, 0., make_accumulate(extract_lat));\n\n    const auto mean_lon = accumulated_lon / number_of_coordinates;\n    const auto mean_lat = accumulated_lat / number_of_coordinates;\n    const auto make_variance = [](const auto mean, const auto extraction_function) {\n        return [extraction_function, mean](const double sum_so_far, const Coordinate coordinate) {\n            const auto difference = extraction_function(coordinate) - mean;\n            return sum_so_far + difference * difference;\n        };\n    };\n\n    // using the unbiased version, we divide by num_samples - 1 (see\n    // http://mathworld.wolfram.com/SampleVariance.html)\n    const auto sample_variance_lon =\n        std::sqrt(std::accumulate(begin, end, 0., make_variance(mean_lon, extract_lon)) /\n                  (number_of_coordinates - 1));\n\n    // if we don't change longitude, return the vertical line as is\n    if (std::abs(sample_variance_lon) <\n        std::numeric_limits<decltype(sample_variance_lon)>::epsilon())\n        return {*begin, *(end - 1)};\n\n    const auto sample_variance_lat =\n        std::sqrt(std::accumulate(begin, end, 0., make_variance(mean_lat, extract_lat)) /\n                  (number_of_coordinates - 1));\n\n    if (std::abs(sample_variance_lat) <\n        std::numeric_limits<decltype(sample_variance_lat)>::epsilon())\n        return {*begin, *(end - 1)};\n    const auto linear_correlation =\n        std::accumulate(begin,\n                        end,\n                        0.,\n                        [&](const auto sum_so_far, const auto current_coordinate) {\n                            return sum_so_far +\n                                   (extract_lon(current_coordinate) - mean_lon) *\n                                       (extract_lat(current_coordinate) - mean_lat) /\n                                       (sample_variance_lon * sample_variance_lat);\n                        }) /\n        (number_of_coordinates - 1);\n\n    const auto slope = linear_correlation * sample_variance_lat / sample_variance_lon;\n    const auto intercept = mean_lat - slope * mean_lon;\n\n    const auto GetLatAtLon = [intercept,\n                              slope](const util::FloatLongitude longitude) -> util::FloatLatitude {\n        return {intercept + slope * static_cast<double>((longitude))};\n    };\n\n    const double offset = 0.00001;\n    const Coordinate regression_first = {\n        toFixed(util::FloatLongitude{min_lon - offset}),\n        toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{min_lon - offset})))};\n    const Coordinate regression_end = {\n        toFixed(util::FloatLongitude{max_lon + offset}),\n        toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{max_lon + offset})))};\n\n    return {regression_first, regression_end};\n}\n\ntemplate <typename iterator_type>\nbool areParallel(const iterator_type lhs_begin,\n                 const iterator_type lhs_end,\n                 const iterator_type rhs_begin,\n                 const iterator_type rhs_end)\n{\n    const auto regression_lhs = leastSquareRegression(lhs_begin, lhs_end);\n    const auto regression_rhs = leastSquareRegression(rhs_begin, rhs_end);\n\n    const auto null_island = Coordinate(FixedLongitude{0}, FixedLatitude{0});\n    const auto difference_lhs = difference(regression_lhs.first, regression_lhs.second);\n    const auto difference_rhs = difference(regression_rhs.first, regression_rhs.second);\n\n    // we normalise the left slope to be zero, so we rotate the coordinates around 0,0 to match 90\n    // degrees\n    const auto bearing_lhs = bearing(null_island, difference_lhs);\n\n    // we rotate to have one of the lines facing horizontally to the right (bearing 90 degree)\n    const auto rotation_angle_radians = detail::degToRad(bearing_lhs - 90);\n    const auto rotated_difference_rhs = rotateCCWAroundZero(difference_rhs, rotation_angle_radians);\n\n    const auto get_slope = [](const Coordinate from, const Coordinate to) {\n        const auto diff_lat = static_cast<int>(from.lat) - static_cast<int>(to.lat);\n        const auto diff_lon = static_cast<int>(from.lon) - static_cast<int>(to.lon);\n        if (diff_lon == 0)\n            return std::numeric_limits<double>::max();\n        return static_cast<double>(diff_lat) / static_cast<double>(diff_lon);\n    };\n\n    const auto slope_rhs = get_slope(null_island, rotated_difference_rhs);\n    // the left hand side has a slope of `0` after the rotation. We can check the slope of the right\n    // hand side to ensure we only considering slight slopes\n    return std::abs(slope_rhs) < 0.20; // twenty percent incline at the most\n}\n\ndouble computeArea(const std::vector<Coordinate> &polygon);\n\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n\n#endif // COORDINATE_CALCULATION\n", "meta": {"hexsha": "884169e4cc338e8b354faa5aaba8b4f398861cf3", "size": 16289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/coordinate_calculation.hpp", "max_stars_repo_name": "curefit/osrm-backend", "max_stars_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "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/util/coordinate_calculation.hpp", "max_issues_repo_name": "curefit/osrm-backend", "max_issues_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "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/util/coordinate_calculation.hpp", "max_forks_repo_name": "curefit/osrm-backend", "max_forks_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "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": 41.9819587629, "max_line_length": 100, "alphanum_fraction": 0.6674442876, "num_tokens": 3172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6547196319314161}}
{"text": "// 2018-03-24\n#include <iostream>\n#include <time.h>\n#include <boost/multiprecision/gmp.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nmpz_int func10(int n)\n{\n  mpz_int it = 1;\n  mpz_int sum = 1;\n  for (int i = 0; i < 10; i++)\n  {\n    it *= (-n);\n    sum += it;\n  }\n  return sum;\n}\n\nmpz_int \n\nvoid work()\n{\n  for (int i = 0; i < 20; i++)\n  {\n    cout << func10(i) << endl;\n  }\n}\n\nint main(int argc, char const *argv[])\n{\n  clock_t t1,t2;\n  t1=clock();\n  work();\n  t2=clock();\n  float diff ((float)t2-(float)t1);\n  cout << \"Running time (s): \" << diff/CLOCKS_PER_SEC << endl;\n  return 0;\n}", "meta": {"hexsha": "5dece5e0034da433d42d5ea86bcd721ebe6efb51", "size": 607, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "junior/p101.cxx", "max_stars_repo_name": "chaonan99/project-euler", "max_stars_repo_head_hexsha": "51e1f1d13afda36da8020bebd88e514212c82a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "junior/p101.cxx", "max_issues_repo_name": "chaonan99/project-euler", "max_issues_repo_head_hexsha": "51e1f1d13afda36da8020bebd88e514212c82a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "junior/p101.cxx", "max_forks_repo_name": "chaonan99/project-euler", "max_forks_repo_head_hexsha": "51e1f1d13afda36da8020bebd88e514212c82a81", "max_forks_repo_licenses": ["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.175, "max_line_length": 62, "alphanum_fraction": 0.5766062603, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6547000927350974}}
{"text": "// Copyright 2019 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_axis_with_transform\n\n#include <boost/histogram/axis/regular.hpp>\n#include <limits>\n\nint main() {\n  using namespace boost::histogram;\n\n  // make a regular axis with a log transform over [10, 100), [100, 1000), [1000, 10000)\n  axis::regular<double, axis::transform::log> r_log{3, 10., 10000.};\n  // log transform:\n  // - useful when values vary dramatically in magnitude, like brightness of stars\n  // - edges are not exactly at 10, 100, 1000, because of finite floating point precision\n  // - value >= 0 below is mapped to -1\n  // - value < 0 below is mapped to `size()`, because the result of std::log is NaN\n  assert(r_log.index(10.1) == 0);\n  assert(r_log.index(100.1) == 1);\n  assert(r_log.index(1000.1) == 2);\n  assert(r_log.index(1) == -1);\n  assert(r_log.index(0) == -1);\n  assert(r_log.index(-1) == 3);\n\n  // make a regular axis with a sqrt transform over [4, 9), [9, 16), [16, 25)\n  axis::regular<double, axis::transform::sqrt> r_sqrt{3, 4., 25.};\n  // sqrt transform:\n  // - bin widths are more mildly increasing compared to log transform\n  // - starting axis at value == 0 is ok, sqrt(0) == 0 unlike log transform\n  // - value < 0 is mapped to `size()`, because the result of std::sqrt is NaN\n  assert(r_sqrt.index(0) == -1);\n  assert(r_sqrt.index(4.1) == 0);\n  assert(r_sqrt.index(9.1) == 1);\n  assert(r_sqrt.index(16.1) == 2);\n  assert(r_sqrt.index(25.1) == 3);\n  assert(r_sqrt.index(-1) == 3);\n\n  // make a regular axis with a power transform x^1/3 over [1, 8), [8, 27), [27, 64)\n  using pow_trans = axis::transform::pow;\n  axis::regular<double, pow_trans> r_pow(pow_trans{1. / 3.}, 3, 1., 64.);\n  // pow transform:\n  // - generalization of the sqrt transform, power index is first argument of ctor\n  // - starting the axis at value == 0 is ok, 0^p == 0 for p != 0\n  // - value < 0 is mapped to `size()`, because the result of std::pow is NaN\n  assert(r_pow.index(0) == -1);\n  assert(r_pow.index(1.1) == 0);\n  assert(r_pow.index(8.1) == 1);\n  assert(r_pow.index(27.1) == 2);\n  assert(r_pow.index(64.1) == 3);\n  assert(r_pow.index(-1) == 3);\n}\n\n//]\n", "meta": {"hexsha": "1caefdbee80b046b133848c1bd55374c92b4f05c", "size": 2264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/histogram/examples/guide_axis_with_transform.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/histogram/examples/guide_axis_with_transform.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/histogram/examples/guide_axis_with_transform.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": 39.0344827586, "max_line_length": 89, "alphanum_fraction": 0.6479681979, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.8006920092299293, "lm_q1q2_score": 0.6546253571566044}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved\uff1aCC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      \u7248\u6743\u90e8\u5206\u6240\u6709\uff0c\u9075\u5faaCC(creativecommons.org)BY-NC-SA\u534f\u8bae\u6388\u6743\u65b9\u5f0f\u4f7f\u7528\n *\n * Filename                : \n * Description             : \u89c6\u89c9SLAM\u5341\u56db\u8bb2/ch4 \u5b66\u4e60\u8bb0\u5f55\n *                           \u674e\u4ee3\u6570\u5e93\n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4FOCUS\u56e2\u961f\n * Modification History\t   : ver1.0, 2018.03.26, William Yu\n                            \n=================================================================================*/\n/// Include files\n#include <iostream>\n#include <cmath>\nusing namespace std; \n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"sophus/so3.h\"\n#include \"sophus/se3.h\"\n\n\n\n/// Global Variables\n\n\n\n/// Function definitions\n\n\n/**\n * @function main\n * @author William Yu\n * @brief \n * @param  None\n * @retval None\n */\nint main( int argc, char** argv )\n{\n    //--------------------------------------------------------------------------------------------------\n    //  \u65cb\u8f6c\u77e9\u9635\n    //--------------------------------------------------------------------------------------\n    // \u6cbfZ\u8f74\u8f6c90\u5ea6\u7684\u65cb\u8f6c\u77e9\u9635\n    // \u3000                                  \u89d2\u5ea6\u3000\u3000                  \u8f74\u3000\u3000\u7f57\u5fb7\u91cc\u683c\u516c\u5f0f\u8fdb\u884c\u8f6c\u6362\u4e3a\u65cb\u8f6c\u77e9\u9635\u3000\n    Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n    \n\n    //--------------------------------------------------------------------------------------------------\n    //  \u674e\u7fa4\n    //--------------------------------------------------------------------------------------\n    Sophus::SO3 SO3_R(R);               // Sophus::SO(3)\u53ef\u4ee5\u76f4\u63a5\u4ece\u65cb\u8f6c\u77e9\u9635\u6784\u9020\n    Sophus::SO3 SO3_v( 0, 0, M_PI/2 );  // \u4ea6\u53ef\u4ece\u65cb\u8f6c\u5411\u91cf\u6784\u9020\n    Eigen::Quaterniond q(R);            // \u6216\u8005\u56db\u5143\u6570\n    Sophus::SO3 SO3_q( q );\n    // \u4e0a\u8ff0\u8868\u8fbe\u65b9\u5f0f\u90fd\u662f\u7b49\u4ef7\u7684\n    // \u8f93\u51faSO(3)\u65f6\uff0c\u4ee5so(3)\u5f62\u5f0f\u8f93\u51fa\n    cout<<\"SO(3) from matrix: \"<<SO3_R<<endl;\n    cout<<\"SO(3) from vector: \"<<SO3_v<<endl;\n    cout<<\"SO(3) from quaternion :\"<<SO3_q<<endl;\n    \n\n    //--------------------------------------------------------------------------------------------------\n    //  \u674e\u4ee3\u6570\n    //--------------------------------------------------------------------------------------\n    // \u4f7f\u7528\u5bf9\u6570\u6620\u5c04\u83b7\u5f97\u5b83\u7684\u674e\u4ee3\u6570\n    Eigen::Vector3d so3 = SO3_R.log();\n    cout<<\"so3 = \"<<so3.transpose()<<endl;\n    // hat \u4e3a\u5411\u91cf\u5230\u53cd\u5bf9\u79f0\u77e9\u9635\n    cout<<\"so3 hat=\\n\"<<Sophus::SO3::hat(so3)<<endl;\n    // \u76f8\u5bf9\u7684\uff0cvee\u4e3a\u53cd\u5bf9\u79f0\u5230\u5411\u91cf\n    cout<<\"so3 hat vee= \"<<Sophus::SO3::vee( Sophus::SO3::hat(so3) ).transpose()<<endl; // transpose\u7eaf\u7cb9\u662f\u4e3a\u4e86\u8f93\u51fa\u7f8e\u89c2\u4e00\u4e9b\n    \n\n    //--------------------------------------------------------------------------------------------------\n    //  \u674e\u4ee3\u6570\u6c42\u5bfc \u66f4\u65b0\n    //--------------------------------------------------------------------------------------\n    // \u589e\u91cf\u6270\u52a8\u6a21\u578b\u7684\u66f4\u65b0\n    Eigen::Vector3d update_so3(1e-4, 0, 0); //\u5047\u8bbe\u66f4\u65b0\u91cf\u4e3a\u8fd9\u4e48\u591a\n    Sophus::SO3 SO3_updated = Sophus::SO3::exp(update_so3)*SO3_R;\n    cout<<\"SO3 updated = \"<<SO3_updated<<endl;\n    \n\n\n\n\n\n    /********************\u6211\u662f\u840c\u840c\u7684\u5206\u5272\u7ebf*****\u840c\u840c\u662f\u8c01\uff1f************************/\n    //\u8bf4\u5b9e\u8bdd\uff0c\u5728\u8fd9\u4efd\u4ee3\u7801\u91cc\u9762\u4f60\u53ef\u80fd\u7ecf\u5e38\u770b\u5230\u4e00\u4e9b\u7565\u5fae\u5356\u840c\u7684\u6210\u5206\uff0c\n    //\u8981\u4e48\u662f\u9ad8\u7fd4\u535a\u58eb\u7684\u539f\u7248\u4ee3\u7801\u5728\u5356\u840c\uff0c\n    //\u8981\u4e48\u662f\u6211\u88ab\u9ad8\u535a\u7684\u4ee3\u7801\u5e26\u4e0a\u4e86\u4e00\u6761\u4e0d\u5f52\u8def\uff0c\u603b\u4e4b\uff0c\u5f00\u5fc3\u5c31\u597d\uff1a\uff09\n    \n    cout<<\"************\u6211\u662f\u5206\u5272\u7ebf*************\"<<endl;\n \n \n    //--------------------------------------------------------------------------------------------------\n    //  \u7279\u6b8a\u6b27\u5f0f\u7fa4  \u53d8\u6362\u77e9\u9635\u7fa4\n    //--------------------------------------------------------------------------------------\n    // \u5bf9SE(3)\u64cd\u4f5c\u5927\u540c\u5c0f\u5f02\n    Eigen::Vector3d t(1,0,0);           // \u6cbfX\u8f74\u5e73\u79fb1\n    Sophus::SE3 SE3_Rt(R, t);           // \u4eceR,t\u6784\u9020SE(3)\n    Sophus::SE3 SE3_qt(q,t);            // \u4eceq,t\u6784\u9020SE(3)\n    cout<<\"SE3 from R,t= \"<<endl<<SE3_Rt<<endl;\n    cout<<\"SE3 from q,t= \"<<endl<<SE3_qt<<endl;\n    // \u674e\u4ee3\u6570se(3) \u662f\u4e00\u4e2a\u516d\u7ef4\u5411\u91cf\uff0c\u65b9\u4fbf\u8d77\u89c1\u5148typedef\u4e00\u4e0b\n    typedef Eigen::Matrix<double,6,1> Vector6d;\n    Vector6d se3 = SE3_Rt.log();\n    cout<<\"se3 = \"<<se3.transpose()<<endl;\n    // \u89c2\u5bdf\u8f93\u51fa\uff0c\u4f1a\u53d1\u73b0\u5728Sophus\u4e2d\uff0cse(3)\u7684\u5e73\u79fb\u5728\u524d\uff0c\u65cb\u8f6c\u5728\u540e.\n    // \u540c\u6837\u7684\uff0c\u6709hat\u548cvee\u4e24\u4e2a\u7b97\u7b26\n    cout<<\"se3 hat = \"<<endl<<Sophus::SE3::hat(se3)<<endl;\n    cout<<\"se3 hat vee = \"<<Sophus::SE3::vee( Sophus::SE3::hat(se3) ).transpose()<<endl;\n    \n    // \u6700\u540e\uff0c\u6f14\u793a\u4e00\u4e0b\u66f4\u65b0\n    Vector6d update_se3; //\u66f4\u65b0\u91cf\n    update_se3.setZero();\n    update_se3(0,0) = 1e-4d;\n    Sophus::SE3 SE3_updated = Sophus::SE3::exp(update_se3)*SE3_Rt;\n    cout<<\"SE3 updated = \"<<endl<<SE3_updated.matrix()<<endl;\n    \n    return 0;\n}", "meta": {"hexsha": "a9f3a3e132136d13384a328c0e7f281142ad380f", "size": 4400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2.useSophus/useSophus.cpp", "max_stars_repo_name": "sunnieeee/VSLAM", "max_stars_repo_head_hexsha": "a0f58b7990f0706ff569481aadac81bb227f3332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "2.useSophus/useSophus.cpp", "max_issues_repo_name": "sunnieeee/VSLAM", "max_issues_repo_head_hexsha": "a0f58b7990f0706ff569481aadac81bb227f3332", "max_issues_repo_licenses": ["MIT"], "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.useSophus/useSophus.cpp", "max_forks_repo_name": "sunnieeee/VSLAM", "max_forks_repo_head_hexsha": "a0f58b7990f0706ff569481aadac81bb227f3332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 34.9206349206, "max_line_length": 111, "alphanum_fraction": 0.4036363636, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6545802200936199}}
{"text": "/* Copyright (C) 2013 Ion Torrent Systems, Inc. All Rights Reserved */\n\n#include <iostream>\n#include <algorithm>\n#include \"PcaSpline.h\"\n#include \"Utils.h\"\n#include <malloc.h>\n//#define EIGEN_USE_MKL_ALL 1\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\nusing namespace std;\nusing namespace Eigen;\n\n/**\n * Create the basis splines for order requested at a particular value of x.\n * From \"A Practical Guide To Splines - Revised Edition\" by Carl de Boor p 111\n * the algorithm for BSPLVB. The value of the spline coefficients can be calculated\n * based on a cool recursion. This is a simplified and numerically stable algorithm\n * that seems to be the basis of most bspline implementations including gsl, matlab,etc.\n * @param all_knots - Original knots vector augmented with order number of endpoints\n * @param n_knots - Total number of knots.\n * @param order - Order or order of polynomials, 4 for cubic splines.\n * @param i - index of value x in knots such that all_knots[i] <= x && all_knots[i+1] > x\n * @param x - value that we want to evaluate spline at.\n * @param b - memory to write our coefficients into, must be at least order long.\n */\nvoid basis_spline_xi(float *all_knots, int n_knots, int order, int i, float x, float *b) {\n  b[0] = 1;\n  double kr[order];\n  double kl[order];\n  double term;\n  double saved;\n  for (int j = 0; j < order - 1; j++) {\n    kr[j] = all_knots[i + j + 1] - x; // k right values\n    kl[j] = x - all_knots[i - j];     // k left values\n    saved = 0;\n    for (int r = 0; r <= j; r++) {\n      term = b[r] / (kr[r] + kl[j-r]);\n      b[r] = saved + kr[r] * term;\n      saved = kl[j-r] * term;\n    }\n    b[j+1] = saved;\n  }\n}\n\n/**\n * Create the augmented knots vector and fill in matrix Xt with the spline basis vectors\n */\nvoid basis_splines_endreps_local(float *knots, int n_knots, int order, int *boundaries, int n_boundaries,  MatrixXf &Xt) {\n  assert(n_boundaries == 2 && boundaries[0] < boundaries[1]);\n  int n_rows = boundaries[1] - boundaries[0]; // this is frames so evaluate at each frame we'll need\n  int n_cols = n_knots + order;  // number of basis vectors we'll have at end \n  Xt.resize(n_cols, n_rows); // swapped to transpose later. This order lets us use it as a scratch space\n  Xt.fill(0);\n  int n_std_knots = n_knots + 2 * order;\n  float std_knots[n_std_knots];\n\n  // Repeat the boundary knots on there to ensure linear out side of knots\n  for (int i = 0; i < order; i++) {\n    std_knots[i] = boundaries[0];\n  }\n  // Our original boundary knots here\n  for (int i = 0; i < n_knots; i++) {\n    std_knots[i+order] = knots[i];\n  }\n  // Repeat the boundary knots on there to ensure linear out side of knots\n  for (int i = 0; i < order; i++) {\n    std_knots[i+order+n_knots] = boundaries[1];\n  }\n  // Evaluate our basis splines at each frame.\n  for (int i = boundaries[0]; i < boundaries[1]; i++) {\n    int idx = -1;\n    // find index such that i >= knots[idx] && i < knots[idx+1]\n    float *val = std::upper_bound(std_knots, std_knots + n_std_knots - 1, 1.0f * i);\n    idx = val - std_knots - 1;\n    assert(idx >= 0);\n    float *f = Xt.data() + i * n_cols + idx - (order - 1); //column offset\n    basis_spline_xi(std_knots, n_std_knots, order, idx, i, f);\n  }\n  // Put in our conventional format where each column is a basis vector\n  Xt.transposeInPlace();\n}\n\n\nvoid PcaSpline::FillInKnots(const std::string &strategy, int n_frame, std::vector<float> &knots) {\n  if (strategy != \"no-knots\") {\n    if (strategy == \"even4\") {\n      float stride = n_frame / 3.0f;\n      knots.push_back(stride);\n      knots.push_back(stride * 2.0f);\n    }\n    else if (strategy == \"middle\") {\n      float stride = n_frame / 2.0f;\n      knots.push_back(stride);\n    }\n    else if (strategy.find(\"explicit:\") == 0) {\n      string spec = strategy.substr(9, strategy.length() - 9);\n      knots = char2Vec<float>(spec.c_str(), ',');\n    }\n    else {\n      assert(false);\n    }\n  }\n}\n\nint PcaSpline::NumBasisVectors(int n_pca, int n_frames, int n_order, const std::string &knot_strategy) {\n  std::vector<float> knots;\n  FillInKnots(knot_strategy, n_frames, knots);\n  int spline_basis = 0;\n  if (knots.size() > 0) {\n    spline_basis = knots.size() + n_order;\n  }\n  return spline_basis + n_pca;\n}\n\nvoid PcaSpline::LossyCompress(int n_wells, int n_frame, float *image, \n\t\t\t      int n_sample_wells, float *image_sample,\n\t\t\t      PcaSplineRegion &compressed) {\n  Map<MatrixXf, Aligned> Ysub(image_sample, n_sample_wells, n_frame);\n  Map<MatrixXf, Aligned> Y(image, n_wells, n_frame);\n  MatrixXf C = Ysub.transpose() * Ysub;\n  SelfAdjointEigenSolver<MatrixXf> es;\n  es.compute(C);\n  MatrixXf Pca_Basis = es.eigenvectors();\n  MatrixXf Spline_Basis;\n  vector<float> knots;\n  FillInKnots(m_knot_strategy, n_frame, knots);\n  if (!knots.empty()) {\n    int boundaries[2];\n    boundaries[0] = 0;\n    boundaries[1] = n_frame;\n    basis_splines_endreps_local(&knots[0], knots.size(), m_order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Spline_Basis);\n  }\n  assert(compressed.n_basis == m_num_pca + Spline_Basis.cols());\n  Map<MatrixXf, Aligned> Basis(compressed.basis_vectors, compressed.n_frames, compressed.n_basis);\n  for(int i = 0; i < m_num_pca; i++) {\n    Basis.col(i) = Pca_Basis.col(Pca_Basis.cols() - i - 1);\n  }\n  for (int i = 0; i < Spline_Basis.cols(); i++) {\n    Basis.col(i+m_num_pca) = Spline_Basis.col(i);\n  }\n  MatrixXf SX;\n  if (m_tikhonov_reg > 0) {\n    MatrixXf diag(Basis.cols(), Basis.cols());\n    diag.fill(0);\n    for (int i = 0; i < diag.rows(); i++) {\n      diag(i,i) = 1.0f * m_tikhonov_reg;\n    }\n    SX = ((Basis.transpose() * Basis) + (diag.transpose() * diag)).inverse() * Basis.transpose();\n  }\n  else { \n    SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  }\n  Map<MatrixXf, Aligned> B(compressed.coefficients, n_wells, Basis.cols());\n  B = Y * SX.transpose();\n}\n\nvoid PcaSpline::SampleImageMatrix(int n_wells, int n_frames, float * __restrict orig, int *__restrict trcs_state, int target_sample,\n\t\t\t\t  int &n_sample, float ** __restrict sample) {\n  int good_wells = 0;\n  int * __restrict state_begin = trcs_state;\n  int * __restrict state_end  = trcs_state + n_wells;\n  while (state_begin != state_end) {\n    if (*state_begin++ >= 0) {\n      good_wells++;\n    }\n  }\n  int sample_rate = max(1,good_wells/target_sample);\n  int n_sample_rows = (int)(ceil((float)good_wells/sample_rate));\n  n_sample = n_sample_rows;\n  *sample = (float *) memalign(32, sizeof(float) * n_frames * n_sample_rows);\n  for (int i = 0; i < n_frames; i++) {\n    float *__restrict col_start = orig + i * n_wells;\n    float *__restrict col_end = col_start + n_wells;\n    state_begin = trcs_state;\n    float *__restrict sample_col_begin = (*sample) + n_sample_rows * i;\n    int check_count = 0;\n    int good_count = sample_rate - 1;\n    while (col_start != col_end) {\n      if (*state_begin >= 0 && ++good_count == sample_rate) {\n\t*sample_col_begin++ = *col_start;\n\tgood_count = 0;\n\tcheck_count++;\n      }\n      col_start++;\n    }\n    assert(check_count == n_sample_rows); \n  }\n}\n\nvoid PcaSpline::LossyUncompress(int n_wells, int n_frame, float *image, \n\t\t\t\tconst PcaSplineRegion &compressed) {\n  Map<MatrixXf, Aligned> Yh(image, n_wells, compressed.n_frames);\n  Map<MatrixXf, Aligned> Basis(compressed.basis_vectors, compressed.n_frames, compressed.n_basis);\n  Map<MatrixXf, Aligned> B(compressed.coefficients, n_wells, compressed.n_basis);\n  Yh = B * Basis.transpose();\n}\n", "meta": {"hexsha": "f83f74e6f4630b96e4753f7da0243dbeedcf94c4", "size": 7403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Image/PcaSpline.cpp", "max_stars_repo_name": "konradotto/TS", "max_stars_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 125.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T05:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:15:59.000Z", "max_issues_repo_path": "Analysis/Image/PcaSpline.cpp", "max_issues_repo_name": "konradotto/TS", "max_issues_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-02-10T09:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T02:32:38.000Z", "max_forks_repo_path": "Analysis/Image/PcaSpline.cpp", "max_forks_repo_name": "konradotto/TS", "max_forks_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T01:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:29:42.000Z", "avg_line_length": 37.2010050251, "max_line_length": 134, "alphanum_fraction": 0.6609482642, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6545802004119526}}
{"text": "/**\n * @file \n * @author Denise Ratasich\n * @date 14.10.2013\n *\n * @brief Implement sampling from specific distributions.\n *\n * Currently only Gaussian distributions can be choosen for process\n * and covariance noise. Hence only sampling from a Gaussian\n * distribution is implemented.\n */\n\n#include \"probability/sampling.h\"\n\n#include <stdexcept>\n#include <cmath>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n\nnamespace probability\n{\n  // create the rng only once (otherwise the numbers generated are\n  // always the same)\n  static boost::mt19937 rng(time(NULL));\n\n  VectorXd sampleNormalDistribution(VectorXd mean, MatrixXd covariance)\n  {\n    // save last covariance (so Cholesky decomposition needs not to\n    // be done every time entering this function)\n    static MatrixXd cov;\t\t\n    static MatrixXd T;\t\t\t// transform matrix when cov is not diagonal\n\n    // additionally needed for rng\n    boost::normal_distribution<> dist(0,1);\t// mean = 0, standard deviation = 1\n    boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > random(rng, dist);\n\n    VectorXd sample = VectorXd::Zero(mean.size());\n\n    // check if covariance is diagonal (set diagonal to zero and\n    // compare with MatrixXD::Zero)\n    if (covariance.isDiagonal())\n    {\n      // sample each variable independently\n      for (int i = 0; i < sample.size(); i++)\n\tsample[i] = mean[i] + random() * sqrt(covariance(i,i));\n    } \n    else\n    {\n      // x ~ N(0,C^-1)\n      // C = L*L^T\n      // sample x = L^-T * z, where z ~ N(0,I)\n      \n      // same covariance as before? (do calculation of L only once!)\n      if (cov.rows() != covariance.rows() ||\n\t  cov.cols() != covariance.cols() ||\n\t  cov != covariance)\n\t{\n\t  cov = covariance;\n\n\t  // Cholesky decomposition of inverse covariance to get L;\n\t  // the covariance must be a symmetric and positive definite\n\t  // matrix (a covariance has these features, but the user\n\t  // must configure it so)\n\t  covariance = covariance.inverse();\n\t  MatrixXd L = covariance.llt().matrixL();\n\t  \n\t  MatrixXd checkLL = L*L.transpose();\n\t  for (int r = 0; r < covariance.rows(); r++)\n\t    for (int c = 0; c < covariance.cols(); c++)\n\t      if (checkLL(r,c) - covariance(r,c)  >  0.000001)\n\t\tthrow std::runtime_error(\"sampleNormalDistribution: Cholesky decomposition failed.\");\n\n\t  T = L.inverse().transpose();\n\t}\n\n      // sample z: z_i ~ N(0,1)\n      for (int i = 0; i < sample.size(); i++)\n\tsample[i] = random();\n\n      // transform to x (and add mean!)\n      sample = mean + T * sample;\n    }\n\n    return sample;\n  }\n\n  VectorXd sampleUniformDistribution(VectorXd a, VectorXd b)\n  {\n    VectorXd sample = VectorXd::Zero(a.size());\n\n    if (a.size() != b.size())\n      throw std::runtime_error(\"sampleUniformDistribution: Bounds a and b must have equal sizes.\");\n\n    // additionally needed for rng\n    boost::uniform_real<> dist(0,1);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> >\n      random(rng, dist);\n\n    // sample each variable independently\n    for (int i = 0; i < sample.size(); i++)\n      sample[i] = a[i] + random() * (b[i]-a[i]);\n\n    return sample;\n  }\n}\n\n", "meta": {"hexsha": "6a4087b28c08d04c3aee67e62960954c1a213101", "size": 3256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 29.871559633, "max_line_length": 99, "alphanum_fraction": 0.648955774, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6545382935453659}}
{"text": "// written for clarity not efficiency.\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <boost/array.hpp>\n#include <boost/circular_buffer.hpp>\n\nclass Subtractive_generator {\nprivate:\n    static const int param_i = 55;\n    static const int param_j = 24;\n    static const int initial_load = 219;\n    static const int mod = 1e9;\n    boost::circular_buffer<int> r;\npublic:\n    Subtractive_generator(int seed);\n    int next();\n    int operator()(){return next();}\n};\n\nSubtractive_generator::Subtractive_generator(int seed)\n:r(param_i)\n{\n    boost::array<int, param_i> s;\n    s[0] = seed;\n    s[1] = 1;\n    for(int n = 2; n < param_i; ++n){\n        int t = s[n-2]-s[n-1];\n        if (t < 0 ) t+= mod;\n        s[n] = t;\n    }\n\n    for(int n = 0; n < param_i; ++n){\n\tint i = (34 * (n+1)) % param_i;\n        r.push_back(s[i]);\n    }\n    for(int n = param_i; n <= initial_load; ++n) next();\n}\n\nint Subtractive_generator::next()\n{\n    int t = r[0]-r[31];\n    if (t < 0) t += mod;\n    r.push_back(t);\n    return r[param_i-1];\n}\n\nint main()\n{\n    Subtractive_generator rg(292929);\n\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n    cout << \"result = \" << rg() << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "8e8150a66e95b024c9986ee6967a36dc226a8a90", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/subtractive-generator.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": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/subtractive-generator.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++/subtractive-generator.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": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 21.703125, "max_line_length": 56, "alphanum_fraction": 0.5471562275, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6545382935453656}}
{"text": "\r\n#ifndef LATTICE_HPP\r\n#define LATTICE_HPP\r\n\r\n#include <vector>\r\n#include <memory>\r\n#include <utility>\r\n#include <complex>\r\n\r\n#include <Eigen/Dense>\r\n\r\n\r\n\r\n/**  class representing a general lattice structure\r\n\tparameters\r\n\t\t- lattice basis vectors\r\n\t\t- which lattice sites are coupled\t\r\n*/\r\n\r\nusing namespace Eigen;\r\n\r\n\r\n\r\n//a structure given for making the lattice \r\nstruct basis{\r\n\t//matrix that contains basis indexes\r\n\tstd::vector<std::pair<int,double>> pairing;\t\t\r\n};\r\n\r\n\r\n\r\n\r\n\r\nclass Lattice{\r\n\t\r\npublic:\r\n\t\r\n\t//lattice basis vectors\r\n\tMatrixXf basis_vectors;\r\n\t\r\n\t//closest particle vectors \r\n\t//  R = r_aa r_ba r_ca\r\n\t//\t\tr_ab r_bb r_cb\r\n\t//\t\tr_ac r_bc r_cc\r\n\tstd::vector<std::shared_ptr<MatrixXf>> R;\r\n\t\r\n\t\r\n\t//t_matrix << 0, -t,-t,\r\n\t//\t\t\t-t, 0, -t,\r\n\t//\t\t\t-t, -t, 0;\r\n\tMatrixXf t_matrix;\r\n\t\r\n\t//dimensions\r\n\tint bands;\r\n\tint dim;\r\n\t\r\n\t//all the kinetic hamiltonians\r\n\tstd::vector<MatrixXcf> H_kin_matrices;\r\n\t\r\n\t//all the k_values\r\n\tstd::vector<MatrixXf> k_vectors;\r\n\t\r\n\tconst std::complex<float> IF = std::complex<float>(0.0f, 1.0f); \r\n\t\r\n\t//constructor \r\n\tLattice(const MatrixXf& basis, const std::vector<std::shared_ptr<MatrixXf>>& r, const MatrixXf& t_mat) : \r\n\t\tbasis_vectors(basis), bands(t_mat.cols()), dim(basis.cols()),\r\n\t\tR(r), t_matrix(t_mat) {}\t\r\n\t\r\n\t//destructor\r\n\t~Lattice() {};\r\n\t\r\n\tint Bands(){\r\n\t\treturn bands;\r\n\t}\r\n\t\r\n\tint Dim(){\r\n\t\treturn dim;\r\n\t}\r\n\t\r\n\t\r\n\t//calculates the kinetic hamiltonian for a given k\r\n\tMatrixXcf KineticHamiltonian(const VectorXf& k){\r\n\t\tMatrixXcf H_kin(bands,bands);\r\n\t\tH_kin = MatrixXcf::Zero(bands,bands);\r\n\t\tfor(int l=0; l<R.size(); l++){\r\n\t\t\tMatrixXf R_iter = *R[l];\r\n\t\t\r\n\t\t\tfor(int i = 0; i<bands; i++){\r\n\t\t\t\tfor(int j =0; j< bands; j++){\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t//make a complex 1by1 matrix\r\n\t\t\t\t\tMatrixXcf dot_ra(1,1);\r\n\t\t\t\t\t//fill the imaginary part with i*dot(k*r_ab)\r\n\t\t\t\t\tdot_ra.imag() = ( R_iter.block(i*dim,j,dim,1).transpose() * k );\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\tdot_ra.real() = MatrixXf::Zero(1,1);\r\n\t\t\t\t\t\r\n\t\t\t\t\t//taking the term to direction -r_ab \r\n\t\t\t\t\tMatrixXcf neg_dot_ra = dot_ra;\t\t\t\t\r\n\t\t\t\t\tneg_dot_ra.imag() = -neg_dot_ra.imag();\r\n\t\t\t\t\t\r\n\t\t\t\t\t//summing the exponentials\r\n\t\t\t\t\tMatrixXcf coupling = dot_ra.array().exp() + neg_dot_ra.array().exp();\r\n\t\t\t\t\t\r\n\t\t\t\t\t//the coupling is multiplied by corresponding t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tH_kin.block(i,j,1,1) += -t_matrix(i,j) * coupling;\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn H_kin;\t\r\n\t}\r\n\t\r\n\t//this saves the h_kin_matrics\r\n\tvoid SaveKineticHamiltonians(const float& k_min, const float& k_max){\r\n\t\tint Nk = 20;\r\n\t\tVectorXf kx = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\t\tVectorXf ky = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\r\n\r\n\t\tfor(int i = 0; i<Nk ; i++){\r\n\t\t\tfor(int j = 0; j<Nk; j++){\r\n\t\t\t\tMatrixXf k(dim,1);\r\n\t\t\t\tk << kx(i),ky(j);\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tk_vectors.push_back(k);\r\n\t\t\t\tH_kin_matrices.push_back(KineticHamiltonian(k) );\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t//solves the eigenvalues of one k by selfadjointeigensolver of Eigen package\r\n\t//@return: column vector of eigenvalues with smallest eigenvalue first\r\n\tMatrixXf EigenvaluesOneK(const VectorXf& k){\r\n\t\t\r\n\t\tSelfAdjointEigenSolver<MatrixXcf> es(bands);\r\n\t\t\r\n\t\tes.compute(KineticHamiltonian(k));\t\t\r\n\t\t\r\n\t\treturn es.eigenvalues();\r\n\t\t\r\n\t}\r\n\t\r\n\t//calculates the dispersion over the first brillouin zone\r\n\t//returns a matrix of [kx ky E1 E2 E3]\r\n\tMatrixXf CalculateDispersion(const float& k_min, const float& k_max){\r\n\t\t\r\n\t\tint Nk = 20;\r\n\t\tVectorXf kx = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\t\tVectorXf ky = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\t\t\r\n\t\tMatrixXf k_values(Nk*Nk, dim);\r\n\t\t\r\n\t\tMatrixXf Energies(Nk*Nk, bands);\r\n\r\n\t\tfor(int i = 0; i<Nk ; i++){\r\n\t\t\tfor(int j = 0; j<Nk; j++){\r\n\t\t\t\tMatrixXf k(1,dim);\r\n\t\t\t\tk << kx(i),ky(j);\r\n\t\t\t\tk_values.row(i*Nk + j) = k;\r\n\t\t\t\t\r\n\t\t\t\tEnergies.row(i*Nk + j) = EigenvaluesOneK(k.transpose()).transpose();\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\tMatrixXf data(Nk*Nk,dim+bands);\r\n\t\tdata.leftCols(dim) = k_values;\r\n\t\tdata.rightCols(bands) = Energies;\r\n\t\treturn data;\r\n\t\t\r\n\t}\r\n\t\r\n\r\n\t\r\n\t\t\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#endif", "meta": {"hexsha": "2f5eddc105597cff4845d14b60e2833c12cc5af9", "size": 4004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lattice.hpp", "max_stars_repo_name": "miikama/cpp-math", "max_stars_repo_head_hexsha": "06125799ab0e684361978a4da657ace46e4e6424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lattice.hpp", "max_issues_repo_name": "miikama/cpp-math", "max_issues_repo_head_hexsha": "06125799ab0e684361978a4da657ace46e4e6424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lattice.hpp", "max_forks_repo_name": "miikama/cpp-math", "max_forks_repo_head_hexsha": "06125799ab0e684361978a4da657ace46e4e6424", "max_forks_repo_licenses": ["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.1206030151, "max_line_length": 107, "alphanum_fraction": 0.6031468531, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6545382692883831}}
{"text": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"../include/core/config.hpp\"\n#include \"../include/core/error.hpp\"\n\n\n/* Test the H1-error computation,\n * implemented in class ComputeH1Error,\n * for quasi-uniform meshes,\n * generated by _serial_ code.\n*/\nTEST(Poisson, computeH1Error1) {\n\n    std::string input_dir\n            = \"../input/poisson_smooth_unitSquare/\";\n\n    int lx1 = 2;\n    int lx2 = 4;\n\n    const std::string mesh_file1\n            = input_dir+\"mesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1\n            = input_dir+\"sol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2\n            = input_dir+\"mesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2\n            = input_dir+\"sol_lx\"+std::to_string(lx2);\n\n    //std::cout << mesh_file1 << std::endl;\n    //std::cout << mesh_file2 << std::endl;\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n\n    std::ifstream sol_ifs1(sol_file1.c_str());\n    std::ifstream sol_ifs2(sol_file2.c_str());\n\n    GridFunction u1(&mesh1, sol_ifs1);\n    GridFunction u2(&mesh2, sol_ifs2);\n\n    ComputeH1Error computeH1Error{};\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    auto [errorL21, u2L21, errorH101, u2H101]\n            = computeH1Error(u1, u2);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    auto start2 = std::chrono::high_resolution_clock::now();\n    auto [errorL22, u2L22, errorH102, u2H102]\n            = computeH1Error.test_slow(u1, u2);\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    double TOL = 1E-8;\n    ASSERT_LE((errorL21/u2L21 - errorL22/u2L22), TOL);\n    ASSERT_LE((errorH101/u2H101 - errorH102/u2H102), TOL);\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Relative L2 error: \"\n              << errorL21/u2L21 << \"\\t\"\n              << errorL22/u2L22 << std::endl;\n    std::cout << \"Relative H10 error: \"\n              << errorH101/u2H101 << \"\\t\"\n              << errorH102/u2H102 << std::endl;\n    std::cout << \"Run times: \"\n              << \"\\t fast  \" << duration1.count()\n              << \"\\t slow  \" << duration2.count()\n            << std::endl;\n}\n\n/* Test the H1-error computation,\n * implemented in class ComputeH1Error,\n * for meshes with local refinement,\n * generated by _serial_ code.\n*/\nTEST(Poisson, computeH1Error2) {\n\n    std::string input_dir\n            = \"../input/\"\n              \"poisson_singular_gammaShaped_bisecRefine/\";\n\n    int lx1 = 2;\n    int lx2 = 4;\n\n    const std::string mesh_file1\n            = input_dir+\"mesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1\n            = input_dir+\"sol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2\n            = input_dir+\"mesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2\n            = input_dir+\"sol_lx\"+std::to_string(lx2);\n\n    //std::cout << mesh_file1 << std::endl;\n    //std::cout << mesh_file2 << std::endl;\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n\n    std::ifstream sol_ifs1(sol_file1.c_str());\n    std::ifstream sol_ifs2(sol_file2.c_str());\n\n    GridFunction u1(&mesh1, sol_ifs1);\n    GridFunction u2(&mesh2, sol_ifs2);\n\n    ComputeH1Error computeH1Error{};\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    auto [errorL21, u2L21, errorH101, u2H101]\n            = computeH1Error(u1, u2);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    auto start2 = std::chrono::high_resolution_clock::now();\n    auto [errorL22, u2L22, errorH102, u2H102]\n            = computeH1Error.test_slow(u1, u2);\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    double TOL1 = 1E-6;\n    double TOL2 = 1E-5;\n    ASSERT_LE((errorL21/u2L21 - errorL22/u2L22), TOL1);\n    ASSERT_LE((errorH101/u2H101 - errorH102/u2H102), TOL2);\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Relative L2 error: \"\n              << errorL21/u2L21 << \"\\t\"\n              << errorL22/u2L22 << std::endl;\n    std::cout << \"Relative H10 error: \"\n              << errorH101/u2H101 << \"\\t\"\n              << errorH102/u2H102 << std::endl;\n    std::cout << \"Run times: \"\n              << \"\\t fast  \" << duration1.count()\n              << \"\\t slow  \" << duration2.count()\n            << std::endl;\n}\n\n/* Test the H1-error computation,\n * implemented in class ComputeH1Error,\n * for quasi-uniform meshes,\n * generated by _parallel_ code.\n*/\nTEST(Poisson, computeH1Error3) {\n\n    std::string input_dir\n            = \"../input/poisson_smooth_unitSquare/\";\n\n    int lx1 = 2;\n    int lx2 = 4;\n\n    const std::string mesh_file1\n            = input_dir+\"mesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1\n            = input_dir+\"sol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2\n            = input_dir+\"mesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2\n            = input_dir+\"sol_lx\"+std::to_string(lx2);\n\n    const std::string mesh_file1p\n            = input_dir+\"pmesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1p\n            = input_dir+\"psol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2p\n            = input_dir+\"pmesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2p\n            = input_dir+\"psol_lx\"+std::to_string(lx2);\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n    Mesh mesh1p(mesh_file1.c_str());\n    Mesh mesh2p(mesh_file2.c_str());\n\n    std::ifstream sol_ifs1(sol_file1.c_str());\n    std::ifstream sol_ifs2(sol_file2.c_str());\n    std::ifstream sol_ifs1p(sol_file1.c_str());\n    std::ifstream sol_ifs2p(sol_file2.c_str());\n\n    GridFunction u1(&mesh1, sol_ifs1);\n    GridFunction u2(&mesh2, sol_ifs2);\n    GridFunction u1p(&mesh1p, sol_ifs1p);\n    GridFunction u2p(&mesh2p, sol_ifs2p);\n\n    ComputeH1Error computeH1Error{};\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    auto [errorL21, u2L21, errorH101, u2H101]\n            = computeH1Error(u1, u2);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    bool has_shared_vertices = true;\n    auto start2 = std::chrono::high_resolution_clock::now();\n    auto [errorL22, u2L22, errorH102, u2H102]\n            = computeH1Error(u1p, u2p, has_shared_vertices);\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    double TOL = 1E-8;\n    ASSERT_LE((errorL21/u2L21 - errorL22/u2L22), TOL);\n    ASSERT_LE((errorH101/u2H101 - errorH102/u2H102), TOL);\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Relative L2 error: \"\n              << errorL21/u2L21 << \"\\t\"\n              << errorL22/u2L22 << std::endl;\n    std::cout << \"Relative H10 error: \"\n              << errorH101/u2H101 << \"\\t\"\n              << errorH102/u2H102 << std::endl;\n    std::cout << \"Run times: \"\n              << \"\\t fast  \" << duration1.count()\n              << \"\\t slow  \" << duration2.count()\n            << std::endl;\n}\n\n/* Test the H1-error computation,\n * implemented in class ComputeH1Error,\n * for meshes with local refinement,\n * generated by _serial_ code.\n*/\nTEST(Poisson, computeH1Error4) {\n\n    std::string input_dir\n            = \"../input/\"\n              \"poisson_singular_gammaShaped_bisecRefine/\";\n\n    int lx1 = 2;\n    int lx2 = 4;\n\n    const std::string mesh_file1\n            = input_dir+\"mesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1\n            = input_dir+\"sol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2\n            = input_dir+\"mesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2\n            = input_dir+\"sol_lx\"+std::to_string(lx2);\n\n    const std::string mesh_file1p\n            = input_dir+\"pmesh_lx\"+std::to_string(lx1);\n    const std::string sol_file1p\n            = input_dir+\"psol_lx\"+std::to_string(lx1);\n\n    const std::string mesh_file2p\n            = input_dir+\"pmesh_lx\"+std::to_string(lx2);\n    const std::string sol_file2p\n            = input_dir+\"psol_lx\"+std::to_string(lx2);\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n    Mesh mesh1p(mesh_file1.c_str());\n    Mesh mesh2p(mesh_file2.c_str());\n\n    std::ifstream sol_ifs1(sol_file1.c_str());\n    std::ifstream sol_ifs2(sol_file2.c_str());\n    std::ifstream sol_ifs1p(sol_file1.c_str());\n    std::ifstream sol_ifs2p(sol_file2.c_str());\n\n    GridFunction u1(&mesh1, sol_ifs1);\n    GridFunction u2(&mesh2, sol_ifs2);\n    GridFunction u1p(&mesh1p, sol_ifs1p);\n    GridFunction u2p(&mesh2p, sol_ifs2p);\n\n    ComputeH1Error computeH1Error{};\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    auto [errorL21, u2L21, errorH101, u2H101]\n            = computeH1Error(u1, u2);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    bool has_shared_vertices = true;\n    auto start2 = std::chrono::high_resolution_clock::now();\n    auto [errorL22, u2L22, errorH102, u2H102]\n            = computeH1Error(u1p, u2p, has_shared_vertices);\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    double TOL = 1E-8;\n    ASSERT_LE((errorL21/u2L21 - errorL22/u2L22), TOL);\n    ASSERT_LE((errorH101/u2H101 - errorH102/u2H102), TOL);\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Relative L2 error: \"\n              << errorL21/u2L21 << \"\\t\"\n              << errorL22/u2L22 << std::endl;\n    std::cout << \"Relative H10 error: \"\n              << errorH101/u2H101 << \"\\t\"\n              << errorH102/u2H102 << std::endl;\n    std::cout << \"Run times: \"\n              << \"\\t fast  \" << duration1.count()\n              << \"\\t slow  \" << duration2.count()\n            << std::endl;\n}\n", "meta": {"hexsha": "0f980237981b721119162ba889decf79d573c27b", "size": 10290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_error.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_error.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_error.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["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.15625, "max_line_length": 60, "alphanum_fraction": 0.6168124393, "num_tokens": 3077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6544984214436497}}
{"text": "//  GAMBIT: Global and Modular BSM Inference Tool\n//  *********************************************\n///  \\file\n///\n///  Multivariate Gaussian prior\n///\n///  *********************************************\n///\n///  Authors (add name and date if you modify):\n///\n///  \\author Ben Farmer\n///  (benjamin.farmer@monash.edu.au)\n///  \\date 2013 Dec\n///\n///  \\author Gregory Martinez\n///  (gregory.david.martinez@gmail.com)\n///  \\date Feb 2014\n///\n///  \\author Andrew Fowlie\n///    (andrew.j.fowlie@qq.com)\n///  \\date August 2020\n///\n///  *********************************************\n\n#ifndef __PRIOR_GAUSSIAN_HPP__\n#define __PRIOR_GAUSSIAN_HPP__\n\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"gambit/ScannerBit/cholesky.hpp\"\n#include \"gambit/ScannerBit/priors.hpp\"\n#include \"gambit/Utils/yaml_options.hpp\"\n\n#include <boost/math/special_functions/erf.hpp>\n\nnamespace Gambit\n{\n  namespace Priors\n  {\n    /**\n     * @brief  Multi-dimensional Gaussian prior\n     *\n     * Defined by a covariance matrix and mean.\n     *\n     * If the covariance matrix is diagonal, it may instead be specified by the square-roots of its \n     * diagonal entries, denoted \\f$\\sigma\\f$.\n     */\n    class Gaussian : public BasePrior\n    {\n     private:\n      std::vector <double> mu;\n      mutable Cholesky col;\n\n     public:\n      // Constructor defined in gaussian.cpp\n      Gaussian(const std::vector<std::string>&, const Options&);\n\n      /** @brief Transformation from unit interval to the Gaussian */\n      void transform(const std::vector <double> &unitpars, std::unordered_map<std::string, double> &outputMap) const\n      {\n        std::vector<double> vec(unitpars.size());\n\n        auto v_it = vec.begin();\n        for (auto elem_it = unitpars.begin(), elem_end = unitpars.end(); elem_it != elem_end; elem_it++, v_it++)\n        {\n          *v_it = M_SQRT2 * boost::math::erf_inv(2. * (*elem_it) - 1.);\n        }\n\n        col.ElMult(vec);\n\n        v_it = vec.begin();\n        auto m_it = mu.begin();\n        for (auto str_it = param_names.begin(), str_end = param_names.end(); str_it != str_end; str_it++)\n        {\n          outputMap[*str_it] = *(v_it++) + *(m_it++);\n        }\n      }\n\n      std::vector<double> inverse_transform(const std::unordered_map<std::string, double> &physical) const override\n      {\n        // subtract mean\n        std::vector<double> central;\n        for (int i = 0, n = this->size(); i < n; i++)\n        {\n          central.push_back(physical.at(param_names[i]) - mu[i]);\n        }\n\n        // invert rotation by Cholesky matrix\n        std::vector<double> rotated = col.invElMult(central);\n\n        // now diagonal; invert Gaussian CDF\n        std::vector<double> u;\n        for (const auto& v : rotated)\n        {\n          u.push_back(0.5 * (boost::math::erf(v / M_SQRT2) + 1.));\n        }\n        return u;\n      }\n\n      double operator()(const std::vector<double> &vec) const\n      {\n        static double norm = 0.5 * std::log(2. * M_PI * std::pow(col.DetSqrt(), 2));\n        return -0.5 * col.Square(vec, mu) - norm;\n      }\n    };\n\n    LOAD_PRIOR(gaussian, Gaussian)\n\n  }  // namespace Priors\n}  // namespace Gambit\n\n#endif  // __PRIOR_GAUSSIAN_HPP__\n", "meta": {"hexsha": "c96290642c926773c451e4baa2a9e47934d4b851", "size": 3234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 27.641025641, "max_line_length": 116, "alphanum_fraction": 0.573283859, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6544524355720398}}
{"text": "#include <boost/ut.hpp>\n\nusing namespace boost::ut;\n\nunsigned int Factorial(unsigned int number) {\n  if(number == 0 or number == 1) return 1;\n  return number * Factorial(number - 1);\n}\n\nsuite errors = []{\n  expect(Factorial(1) == 1_i);\n  expect(Factorial(0) == 1_i);\n};\n", "meta": {"hexsha": "6e13479374c491243884c4d77a00ffe378f2a8d9", "size": 270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tests.cpp", "max_stars_repo_name": "RishabhRD/cpp20_starter_project", "max_stars_repo_head_hexsha": "7c5190df4b441cc2dbc79e4e77f00aadde1f7d14", "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": "test/tests.cpp", "max_issues_repo_name": "RishabhRD/cpp20_starter_project", "max_issues_repo_head_hexsha": "7c5190df4b441cc2dbc79e4e77f00aadde1f7d14", "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": "test/tests.cpp", "max_forks_repo_name": "RishabhRD/cpp20_starter_project", "max_forks_repo_head_hexsha": "7c5190df4b441cc2dbc79e4e77f00aadde1f7d14", "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": 19.2857142857, "max_line_length": 45, "alphanum_fraction": 0.6555555556, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6544280139789255}}
{"text": "// Copyright (C) 2009  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/matrix.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../stl_checked.h\"\n#include \"../array.h\"\n#include \"../rand.h\"\n#include <dlib/string.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.matrix_chol\");\n\n    dlib::rand rnd;\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename mat_type>\n    const matrix<typename mat_type::type> symm(const mat_type& m) { return m*trans(m); }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename type>\n    const matrix<type> randmat(long r, long c)\n    {\n        matrix<type> m(r,c);\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n    template <typename type, long NR, long NC>\n    const matrix<type,NR,NC> randmat()\n    {\n        matrix<type,NR,NC> m;\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename matrix_type>\n    void test_cholesky ( const matrix_type& m)\n    {\n        typedef typename matrix_type::type type;\n        const type eps = 10*max(abs(m))*sqrt(std::numeric_limits<type>::epsilon());\n        dlog << LDEBUG << \"test_cholesky():  \" << m.nr() << \" x \" << m.nc() << \"  eps: \" << eps;\n        print_spinner();\n\n\n        cholesky_decomposition<matrix_type> test(m);\n\n        // none of the matrices we should be passing in to test_cholesky() should be non-spd.  \n        DLIB_TEST(test.is_spd() == true);\n\n        type temp;\n        DLIB_TEST_MSG( (temp= max(abs(test.get_l()*trans(test.get_l()) - m))) < eps,temp);\n\n        {\n            matrix<type> mat = chol(m);\n            DLIB_TEST_MSG( (temp= max(abs(mat*trans(mat) - m))) < eps,temp);\n        }\n\n\n        matrix<type> m2;\n        matrix<type,0,1> col;\n\n        m2 = identity_matrix<type>(m.nr());\n        DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n        m2 = randmat<type>(m.nr(),5);\n        DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n        m2 = randmat<type>(m.nr(),1);\n        DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n        col = randmat<type>(m.nr(),1);\n        DLIB_TEST_MSG(equal(m*test.solve(col), col,eps),max(abs(m*test.solve(m2)- m2)));\n\n        // now make us a non-spd matrix\n        if (m.nr() > 2)\n        {\n            matrix<type> sm(lowerm(m));\n            sm(1,1) = 0;\n\n            cholesky_decomposition<matrix_type> test2(sm);\n            DLIB_TEST_MSG(test2.is_spd() == false,  test2.get_l());\n\n\n            cholesky_decomposition<matrix_type> test3(sm*trans(sm));\n            DLIB_TEST_MSG(test3.is_spd() == false,  test3.get_l());\n\n            sm = sm*trans(sm);\n            sm(1,1) = 5;\n            sm(1,0) -= 1;\n            cholesky_decomposition<matrix_type> test4(sm);\n            DLIB_TEST_MSG(test4.is_spd() == false,  test4.get_l());\n        }\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_double()\n    {\n\n        test_cholesky(uniform_matrix<double>(1,1,1) + 10*symm(randmat<double>(1,1)));\n        test_cholesky(uniform_matrix<double>(2,2,1) + 10*symm(randmat<double>(2,2)));\n        test_cholesky(uniform_matrix<double>(3,3,1) + 10*symm(randmat<double>(3,3)));\n        test_cholesky(uniform_matrix<double>(4,4,1) + 10*symm(randmat<double>(4,4)));\n        test_cholesky(uniform_matrix<double>(15,15,1) + 10*symm(randmat<double>(15,15)));\n        test_cholesky(uniform_matrix<double>(101,101,1) + 10*symm(randmat<double>(101,101)));\n\n        typedef matrix<double,0,0,default_memory_manager, column_major_layout> mat;\n        test_cholesky(mat(uniform_matrix<double>(101,101,1) + 10*symm(randmat<double>(101,101))));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_float()\n    {\n\n        test_cholesky(uniform_matrix<float>(1,1,1) + 2*symm(randmat<float>(1,1)));\n        test_cholesky(uniform_matrix<float>(2,2,1) + 2*symm(randmat<float>(2,2)));\n        test_cholesky(uniform_matrix<float>(3,3,1) + 2*symm(randmat<float>(3,3)));\n\n        typedef matrix<float,0,0,default_memory_manager, column_major_layout> mat;\n        test_cholesky(mat(uniform_matrix<float>(3,3,1) + 2*symm(randmat<float>(3,3))));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class matrix_tester : public tester\n    {\n    public:\n        matrix_tester (\n        ) :\n            tester (\"test_matrix_chol\",\n                    \"Runs tests on the matrix cholesky component.\")\n        {\n            rnd.set_seed(cast_to_string(time(0)));\n        }\n\n        void perform_test (\n        )\n        {\n            dlog << LINFO << \"seed string: \" << rnd.get_seed();\n\n            dlog << LINFO << \"begin testing with double\";\n            matrix_test_double();\n            dlog << LINFO << \"begin testing with float\";\n            matrix_test_float();\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "b46c4866d1f8981c4b4a214f9d7ad0affe322d3c", "size": 5730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/test/matrix_chol.cpp", "max_stars_repo_name": "yatonon/dlib-face", "max_stars_repo_head_hexsha": "0230c1034ee65d0846d007e6145bfe73ca0d6321", "max_stars_repo_licenses": ["BSL-1.0"], "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": "include/dlib/test/matrix_chol.cpp", "max_issues_repo_name": "lwneal/tfasts", "max_issues_repo_head_hexsha": "26528a1e84089f60f31cc51e79bf4c4bf6886937", "max_issues_repo_licenses": ["MIT"], "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": "include/dlib/test/matrix_chol.cpp", "max_forks_repo_name": "lwneal/tfasts", "max_forks_repo_head_hexsha": "26528a1e84089f60f31cc51e79bf4c4bf6886937", "max_forks_repo_licenses": ["MIT"], "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": 31.3114754098, "max_line_length": 98, "alphanum_fraction": 0.5120418848, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6544169660518973}}
{"text": "#include \"functions/transpose.hh\"\n#include <boost/test/unit_test.hpp>\n#include \"data/matrix.hh\"\n\nBOOST_AUTO_TEST_CASE(tranpose_test) {\n  using namespace manifolds;\n  auto m1 = GetRowMatrix<3, 2>(1, 2, 3, 4, 5, 6);\n  auto m2 = GetColMatrix<2, 3>(1, 2, 3, 4, 5, 6);\n  auto check = GetMatrix<2, 3>(1, 3, 5, 2, 4, 6);\n  BOOST_CHECK_EQUAL(check, m2);\n  BOOST_CHECK_EQUAL(transpose(m1), m2);\n}\n", "meta": {"hexsha": "578ce7edc5f07a450cc6ee21c21605a1dac37fb6", "size": 388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_transpose.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_transpose.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_transpose.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.8461538462, "max_line_length": 49, "alphanum_fraction": 0.675257732, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.654347924592171}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n#include \"../../rmse.hpp\"\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> cm1 (\n           make_rowmajor_matrix_local_load<float>(\"./sample_4x4\"));\n    auto cm2 = cm1;\n  \n    // slicing rows\n    auto row1 = make_row_vector<float> (cm1,0);\n    auto row2 = make_row_vector<float> (cm1,1);\n    auto row3 = make_row_vector<float> (cm1,2);\n    auto row4 = make_row_vector<float> (cm1,3);\n\n    // row3-of-cm1 = 5*cm2*row1-of-cm1\n    gemv<float>(cm2,row1,row3,'N',5.0);\n\n    // row4-of-cm1 = 2*trans(cm2)*row2-of-cm1 + 3*row4-of-cm1\n    gemv<float>(cm2,row2,row4,'T',2.0,3.0);\n\n    double tol = 0.01;\n    colmajor_matrix_local<float> ref (\n           make_rowmajor_matrix_local_load<float> (\"./ref_4x4\"));\n    BOOST_CHECK (calc_rms_err<float> (cm1.val, ref.val) < tol);\n}\n\n", "meta": {"hexsha": "ae9c137501b4b125c7080a2494bf80025b10aec3", "size": 1111, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test6.7-2/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test6.7-2/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test6.7-2/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 27.775, "max_line_length": 67, "alphanum_fraction": 0.6660666067, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6543432204291754}}
{"text": "#include <itomp_cio_planner/util/exponential_map.h>\n#include <boost/math/special_functions/sinc.hpp>\n\nnamespace itomp_cio_planner\n{\nnamespace exponential_map\n{\n\nEigen::Vector3d RotationToExponentialMap(const Eigen::Matrix3d& matrix, const Eigen::Vector3d* close_to)\n{\n    if (close_to == NULL)\n        return QuaternionToExponentialMap(Eigen::Quaterniond(matrix));\n    else\n    {\n        Eigen::Quaterniond q0 = Eigen::Quaterniond(matrix);\n        Eigen::Vector3d exp_map0 = QuaternionToExponentialMap(q0);\n\n        Eigen::Quaterniond q1 = q0;\n        q1.coeffs() = -q0.coeffs();\n        Eigen::Vector3d exp_map1 = QuaternionToExponentialMap(q1);\n\n        if ((exp_map0 - *close_to).norm() <= (exp_map1 - *close_to).norm())\n            return exp_map0;\n        else\n            return exp_map1;\n    }\n}\n\nEigen::Matrix3d ExponentialMapToRotation(const Eigen::Vector3d& exponential_rotation)\n{\n\treturn ExponentialMapToQuaternion(exponential_rotation).toRotationMatrix();\n}\n\nEigen::Vector3d QuaternionToExponentialMap(const Eigen::Quaterniond& quaternion)\n{\n\tEigen::Vector3d vec = quaternion.vec();\n    if (vec.norm() < ITOMP_EPS)\n\t\treturn Eigen::Vector3d::Zero();\n\n\tdouble theta = 2.0 * std::acos(quaternion.w());\n\tvec.normalize();\n\treturn theta * vec;\n}\n\nEigen::Quaterniond ExponentialMapToQuaternion(const Eigen::Vector3d& exponential_rotation)\n{\n\tdouble angle = 0.5 * exponential_rotation.norm();\n\tEigen::Quaterniond quaternion;\n\tquaternion.w() = std::cos(angle);\n\tquaternion.vec() = 0.5 * boost::math::sinc_pi(angle) * exponential_rotation;\n\treturn quaternion;\n}\n\n}\n}\n", "meta": {"hexsha": "56764ddd7f2995b7cc66b7eff00bfa28469c9234", "size": 1570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_stars_repo_name": "Chpark/itomp", "max_stars_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T14:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T02:57:19.000Z", "max_issues_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_issues_repo_name": "Chpark/itomp", "max_issues_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-12-16T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-19T05:49:51.000Z", "max_forks_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_forks_repo_name": "Chpark/itomp", "max_forks_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T04:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T04:28:53.000Z", "avg_line_length": 28.0357142857, "max_line_length": 104, "alphanum_fraction": 0.7121019108, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6543432068611125}}
{"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 \"EuropeanOption.hpp\"\r\n#include <cmath>\r\n#include <boost/math/distributions.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\n//\tGaussian functions using boost libraries\r\ndouble EuropeanOption::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 EuropeanOption::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 EuropeanOption::CallPrice() const\r\n{\r\n\treturn ::CallPrice(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutPrice() const\r\n{\r\n\treturn ::PutPrice(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallDelta() const\r\n{\r\n\treturn ::CallDelta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutDelta() const\r\n{\r\n\treturn ::PutDelta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallGamma() const\r\n{\r\n\treturn ::CallGamma(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutGamma() const\r\n{\r\n\treturn ::PutGamma(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallVega() const\r\n{\r\n\treturn ::CallVega(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutVega() const\r\n{\r\n\treturn ::PutVega(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallTheta() const\r\n{\r\n\treturn ::CallTheta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutTheta() const\r\n{\r\n\treturn ::PutTheta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallRho() const\r\n{\r\n\treturn ::CallRho(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutRho() const\r\n{\r\n\treturn ::PutRho(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallCoc() const\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\treturn T * S * exp((b - r) * T) * N(d1);\r\n}\r\n\r\ndouble EuropeanOption::PutCoc() const\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\treturn -T * S * exp((b - r) * T) * N(-d1);\r\n}\r\n\r\n\r\n//\tInitialising all the default values\r\nvoid EuropeanOption::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 EuropeanOption::copy(const EuropeanOption& 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//\tConstructors and destructor\r\nEuropeanOption::EuropeanOption() : Option()\t\t\t\t\t\t//\tDefault constructor\r\n{\r\n\tinit();\r\n}\r\n\r\nEuropeanOption::EuropeanOption(const EuropeanOption& option) : Option(option)\t\t//\tCopy constructor\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nEuropeanOption::EuropeanOption(const double& S1, const double& K1, const double& T1, const double& r1,\r\n\tconst double& sig1, const double& b1, const string type1) : Option(), S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\nEuropeanOption::~EuropeanOption() {}\t\t\t\t\t\t\t//\tDestructor\r\n\r\n\r\n//\tAssignment operator\r\nEuropeanOption& EuropeanOption::operator = (const EuropeanOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\r\n\t}\r\n\tOption::operator = (option);\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 EuropeanOption::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\ndouble EuropeanOption::Delta() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallDelta();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutDelta();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Gamma() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallGamma();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutGamma();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Vega() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallVega();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutVega();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Theta() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallTheta();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutTheta();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Rho() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallRho();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutRho();\r\n\t}\r\n}\r\n\r\n\r\n//\tFunctions that calculates the Cost of carry\r\ndouble EuropeanOption::Coc() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallCoc();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutCoc();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid EuropeanOption::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 CallDelta(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\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn exp((b - r) * T) * cdf(standard_normal, d1);\r\n\r\n}\r\n\r\ndouble PutDelta(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn exp((b - r) * T) * (cdf(standard_normal, d1) - 1.0);\r\n}\r\n\r\n\r\ndouble CallGamma(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\treturn (pdf(standard_normal, d1) * exp((b - r) * T)) / (S * sig * sqrt(T));\r\n}\r\n\r\ndouble PutGamma(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\treturn CallGamma(S, K, T, r, sig, b);\r\n}\r\n\r\n\r\ndouble CallVega(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\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (S * sqrt(T) * exp((b - r) * T) * pdf(standard_normal, d1));\r\n}\r\n\r\n\r\ndouble PutVega(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\treturn CallVega(S, K, T, r, sig, b);\r\n}\r\n\r\n\r\ndouble CallTheta(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\tdouble t1 = (S * sig * exp((b - r) * T) * pdf(standard_normal, d1)) / (2 * sqrt(T));\r\n\tdouble t2 = ((b - r) * S * exp((b - r) * T) * cdf(standard_normal, d1));\r\n\tdouble t3 = (r * K * exp(-r * T) * cdf(standard_normal, d1));\r\n\treturn -(t1 + t2 + t3);\r\n}\r\n\r\ndouble PutTheta(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\tdouble t1 = (S * sig * exp((b - r) * T) * pdf(standard_normal, d1)) / (2 * sqrt(T));\r\n\tdouble t2 = ((b - r) * S * exp((b - r) * T) * cdf(standard_normal, d1));\r\n\tdouble t3 = (r * K * exp(-r * T) * cdf(standard_normal, d1));\r\n\treturn t2 + t3 - t1;\r\n}\r\n\r\n\r\ndouble CallRho(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\tif (b != 0.0)\r\n\t{\r\n\t\treturn T * K * exp(-r * T) * cdf(standard_normal, d2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn -T * CallPrice(S, K, T, r, sig, b);\r\n\t}\r\n}\r\n\r\ndouble PutRho(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\tif (b != 0.0)\r\n\t{\r\n\t\treturn T * K * exp(-r * T) * cdf(standard_normal, -d2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn -T * PutPrice(S, K, T, r, sig, b);\r\n\t}\r\n}\r\n", "meta": {"hexsha": "14ee19d3e2ec9317825d6d2f3cc91bbef5c344a0", "size": 8035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EuropeanOption.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": "EuropeanOption.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": "EuropeanOption.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": 22.8917378917, "max_line_length": 132, "alphanum_fraction": 0.5973864343, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6542733176214486}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/big/big_cholesky.h>\n\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\n#include <cassert>\n#include <limits>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\n/** \n* Make a immutable triangular adaptor from a matrix\n*\n* \\usage: \n<code>\nA = triangular< lower >(B);\nA = triangular(B, lower());\n</code>\n*/\ntemplate < class TYPE, class MATRIX >\nublas::triangular_adaptor<const MATRIX, TYPE>\ntriangular(const MATRIX & A, const TYPE& uplo = TYPE())\n{\n  return ublas::triangular_adaptor<const MATRIX, TYPE>(A);\n}\n\n/** \n* Make a immutable banded adaptor from a matrix\n*\n* \\usage: \n<code>\nA = banded(B, lower, upper);\n</code>\n*/\ntemplate < class MATRIX >\nublas::banded_adaptor<const MATRIX>\nbanded(const MATRIX & A, const size_t lower, const size_t upper)\n{\n  return ublas::banded_adaptor<const MATRIX>(A, lower, upper);\n}\n\n/** \n* Make a immutable symmetric adaptor from a matrix\n*\n* \\usage: \n<code>\nA = symmetric< lower >(B);\nA = symmetric(B, lower());\n</code>\n*/\ntemplate < class TYPE, class MATRIX >\nublas::symmetric_adaptor<const MATRIX, TYPE>\nsymmetric(const MATRIX & A, const TYPE& uplo = TYPE())\n{\n  return ublas::symmetric_adaptor<const MATRIX, TYPE>(A);\n}\n\n\n/** \n* Fill lower triangular matrix L \n*/\ntemplate < class MATRIX >\nvoid fill_symm(MATRIX & L, const size_t bands = std::numeric_limits<size_t>::max() )\n{\n  typedef typename MATRIX::size_type size_type;\n\n  assert(L.size1() == L.size2());\n\n  size_type size = L.size1();\n  for (size_type i=0; i<size; i++) \n  {\n    for (size_type j = ((i>bands)?(i-bands):0); j<i; j++) \n    {\n      L(i,j) = 1 + (1.0 + i)/(1.0 + j) + 1.0 / (0.5 + i - j);\n    }\n    L(i,i) = 1+i+size;\n  }\n\n  return;\n}\n\n\n\n\ntemplate<typename matrix_type,typename vector_type>\nvoid test(matrix_type const & A, vector_type  & x, vector_type const & b, vector_type const & y)\n{\n  using std::min;\n\n  typedef typename matrix_type::value_type real_type;\n  typedef typename matrix_type::size_type  size_type;\n\n  real_type const tol = boost::numeric_cast<real_type>(0.01);\n\n  size_type const m = A.size1();\n  size_type const n = A.size2();\n  matrix_type L;\n  L.resize(m,n);\n\n  // Dense versions\n  OpenTissue::math::big::cholesky_decompose(A,L);\n  x = b;\n  OpenTissue::math::big::cholesky_solve(L, x, ublas::lower());\n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n  x.clear();\n\n  L.assign(A);\n  OpenTissue::math::big::cholesky_decompose(L);\n  x = b;\n  OpenTissue::math::big::cholesky_solve(L, x, ublas::lower());\n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n  x.clear();\n\n  // Easy Dense version\n  L.assign(A);\n  OpenTissue::math::big::cholesky_solve(L,x,b);\n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n  x.clear();\n\n  // sparse version\n  ublas::compressed_matrix<double> C;\n  C.resize(m,n,false);\n  C.assign(A);\n  OpenTissue::math::big::incomplete_cholesky_decompose(C);\n  x = b;\n  OpenTissue::math::big::cholesky_solve(C, x, ublas::lower());\n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n  x.clear();\n\n  // Easy sparse version\n  C.assign(A);\n  OpenTissue::math::big::cholesky_solve(C,x,b);\n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n\n}\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_cholesky);\n\nBOOST_AUTO_TEST_CASE(Gunter_Winkler_Konstantin_Kutzkow_Test)\n{\n  size_t size = 10;\n  {\n    // use dense matrix\n    ublas::matrix<double, ublas::row_major> A (size, size);\n    ublas::matrix<double, ublas::row_major> T (size, size);\n    ublas::matrix<double, ublas::row_major> L (size, size);\n\n    A = ublas::zero_matrix<double>(size, size);\n\n    ublas::vector<double> b (size);\n    ublas::vector<double> x (size);\n    ublas::vector<double> y (size);\n\n    std::fill(y.begin(), y.end(), 1.0);\n\n    fill_symm(T);\n    A = ublas::prod(T, trans(T));\n    b = prod( A, y);\n    size_t res = OpenTissue::math::big::cholesky_decompose(A, L);\n    \n    BOOST_CHECK( res == 0u );\n    \n    x = b;\n    OpenTissue::math::big::cholesky_solve(L, x, ublas::lower());\n    //std::cout << res << \": \" \n    //          << ublas::norm_inf(L-T) << \" \"\n    //          << ublas::norm_2(x-y) << \" \"\n    //          << \" (deco: \" << watch1() << \" sec)\"\n    //          << \" (prod: \" << watch2() << \" sec)\"\n    //          << \" (solve: \" << watch3() << \" sec)\"\n    //          << \" \" << size\n    //          << std::endl;\n  }\n\n  {\n    // use dense triangular matrices\n    ublas::triangular_matrix<double, ublas::lower, ublas::row_major> A (size, size);\n    ublas::triangular_matrix<double, ublas::lower, ublas::row_major> T (size, size);\n    ublas::triangular_matrix<double, ublas::lower, ublas::row_major> L (size, size);\n\n    A = ublas::zero_matrix<double> (size, size) ;\n    A = triangular<ublas::lower>( ublas::zero_matrix<double> (size, size) );\n    A = triangular( ublas::zero_matrix<double> (size, size), ublas::lower() );\n\n    ublas::vector<double> b (size);\n    ublas::vector<double> x (size);\n    ublas::vector<double> y (size);\n\n    std::fill(y.begin(), y.end(), 1.0);\n\n    fill_symm(T);\n    A = triangular<ublas::lower>( ublas::prod(T, trans(T)) );\n    b = prod( symmetric<ublas::lower>(A), y);\n    size_t res = OpenTissue::math::big::cholesky_decompose(A, L);\n    \n    BOOST_CHECK( res == 0u );\n\n    x = b;\n    OpenTissue::math::big::cholesky_solve(L, x, ublas::lower());\n    //std::cout << res << \": \" \n    //          << ublas::norm_inf(L-T) << \" \"\n    //          << ublas::norm_2(x-y) << \" \"\n    //          << \" (deco: \" << watch1() << \" sec)\"\n    //          << \" (prod: \" << watch2() << \" sec)\"\n    //          << \" (solve: \" << watch3() << \" sec)\"\n    //          << \" \" << size\n    //          << std::endl;\n  }\n  {\n    // use banded matrices matrix\n    typedef ublas::banded_matrix<double, ublas::row_major> MAT;\n\n    size_t bands = std::min<size_t>( size, 50 );\n    MAT A (size, size, bands, 0);\n    MAT T (size, size, bands, 0);\n    MAT L (size, size, bands, 0);\n\n    A = ublas::zero_matrix<double> (size, size) ;\n    A = banded( ublas::zero_matrix<double> (size, size), bands, 0 );\n\n    ublas::vector<double> b (size);\n    ublas::vector<double> x (size);\n    ublas::vector<double> y (size);\n\n    std::fill(y.begin(), y.end(), 1.0);\n\n    fill_symm(T, bands);\n    A = banded( ublas::prod(T, trans(T)), bands, 0 );\n    b = prod( symmetric<ublas::lower>(A), y);\n    size_t res = OpenTissue::math::big::cholesky_decompose(A, L);\n    \n    BOOST_CHECK( res == 0u );\n   \n    x = b;\n    OpenTissue::math::big::cholesky_solve(L, x, ublas::lower());\n    //std::cout << res << \": \" \n    //          << ublas::norm_inf(L-T) << \" \"\n    //          << ublas::norm_2(x-y) << \" \"\n    //          << \" (deco: \" << watch1() << \" sec)\"\n    //          << \" (prod: \" << watch2() << \" sec)\"\n    //          << \" (solve: \" << watch3() << \" sec)\"\n    //          << \" \" << size\n    //          << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  typedef ublas::matrix<double>            matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n\n  for(size_type tst=0;tst<1000;++tst)\n  {\n    size_type N = 10;\n\n    matrix_type A;\n    A.resize(N,N,false);\n\n    vector_type x;\n    x.resize(N,false);\n\n    vector_type b;\n    b.resize(N,false);\n\n    vector_type y;\n    y.resize(N,false);\n\n    matrix_type R;\n    R.resize(N,N,false);\n\n    OpenTissue::math::Random<double> value(0.0,1.0);\n    for(size_t i=0;i<R.size1();++i)\n    { \n      b(i) = value();\n      x(i) = value();\n      y(i) = value();\n      for(size_t j=0;j<R.size2();++j)\n        R(i,j) = value();\n    }\n    ublas::noalias(A) = ublas::prod( ublas::trans(R), R );\n    // forcing A to become PD matrix (it should be non-singular at all times)\n    for(size_t i=0;i<R.size1();++i)\n      A(i,i) += 0.5;\n\n    ublas::noalias(b) = ublas::prod(A,x);\n    y.assign(x);\n\n    x.clear();\n    test(A,x,b,y);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d3290db6bcfef8a8f1d6d773088b4cd75cab53cb", "size": 8775, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/cholesky/src/unit_cholesky.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/big/cholesky/src/unit_cholesky.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/big/cholesky/src/unit_cholesky.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 27.421875, "max_line_length": 96, "alphanum_fraction": 0.5964672365, "num_tokens": 2675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6542733063619328}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, rising_factorial) {\n  using stan::math::rising_factorial;\n  \n  EXPECT_FLOAT_EQ(120, rising_factorial(4.0,3));\n  EXPECT_FLOAT_EQ(360, rising_factorial(3.0,4));\n  EXPECT_THROW(rising_factorial(-1, 4),std::domain_error);\n}\n\nTEST(MathFunctions, rising_factorial_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::rising_factorial(4.0, nan));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::rising_factorial(nan, 3.0));\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::rising_factorial(nan, nan));\n}\n", "meta": {"hexsha": "d713eef1becb8f1f7c29f5d2b791a405ee972dfd", "size": 760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/rising_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0434782609, "max_line_length": 58, "alphanum_fraction": 0.7013157895, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6542732975211462}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/trace.hpp\n *\n * \\brief Compute the trace of a matrix.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n\n\n#include <algorithm>\n#include <boost/numeric/ublas/detail/config.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nnamespace ublas = ::boost::numeric::ublas;\n\n\n/**\n * \\brief Compute the trace of a given matrix.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param A The input matrix expression.\n * \\return The trace of \\a A.\n *\n * The trace of a m-by-n matrix \\f$A\\f$ is defined as\n * \\f[\n *   \\operatorname{tr}(A) = \\sum_{i=1}^k a_{ii}\n * \\f]\n * where \\f$k=\\min(m,n)\\f$.\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename ublas::matrix_traits<MatrixExprT>::value_type trace(ublas::matrix_expression<MatrixExprT> const& A)\n{\n    typedef typename ublas::matrix_traits<MatrixExprT>::value_type value_type;\n    typedef typename ublas::matrix_traits<MatrixExprT>::size_type size_type;\n\n    size_type n = ::std::min(num_rows(A), num_columns(A));\n    value_type res = 0;\n\n    for (size_type i = 0; i < n; ++i)\n    {\n        res += A()(i,i);\n    }\n\n    return res;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n", "meta": {"hexsha": "1318471881e0623c131a8de1aaf5e3e5f171d184", "size": 1799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 25.338028169, "max_line_length": 108, "alphanum_fraction": 0.7087270706, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6542732954621198}}
{"text": "#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <random>\n#include <string>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned, K> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Delaunay;\ntypedef Delaunay::Face_circulator Face_circulator;\ntypedef Delaunay::Face_handle Face_handle;\ntypedef Delaunay::Point Point;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> MapM3Xd;\ntypedef Eigen::Ref<Matrix3Xd> RefM3Xd;\n\nint main(int argc, char *argv[]) {\n\n  // We expect three command line arguments:\n  // 1. Path to the data file\n  // 2. Output directory where output files will be created\n  if (argc < 3) {\n    std::cout << \"Usage: ./calcVolume <data_file> <output_dir>\" << std::endl;\n    return 0;\n  }\n\n  clock_t t = clock();\n\n  // Open the data file\n  std::ifstream inputfile(argv[1]);\n  if (!inputfile.is_open()) {\n    std::cout << \"Unable to open file \" << argv[1] << std::endl;\n    return 0;\n  }\n\n  //**********************************************************************//\n  //\n\n  auto outputFile = std::string(argv[2]) + \"/volume.dat\";\n  std::ofstream vol_file(outputFile);\n\n  if (!vol_file) {\n    std::cout << \"Failed to create output file \" << outputFile << std::endl;\n    return 0;\n  }\n\n  //**********************************************************************//\n  // Now read the first( or the header ) line of the data file\n  // The first line contains N, gamma and beta information\n  std::string line, ignore;\n  size_t N;\n  double_t gamma = 0, beta = 0;\n  std::getline(inputfile, line);\n  std::istringstream header(line);\n  header >> ignore >> N >> ignore >> gamma >> ignore >> beta;\n  int lmax = std::floor(std::sqrt(N) - 1);\n\n  // Write column names in the output files\n  vol_file << \"volume\" << std::endl;\n  vol_file.precision(7);\n\n  //**********************************************************************//\n  // Some useful lambda functions\n  //\n\n  // A function to read N rows of a 3xN matrix from a stringstream\n  auto readMatrix3Xd = [](std::istringstream &ss, RefM3Xd X) {\n    auto N = X.cols();\n    size_t valCount = 0;\n    while (valCount < 3 * N && ss.good()) {\n      std::string value;\n      std::getline(ss, value, ',');\n      X(valCount % 3, valCount / 3) = std::stod(value);\n      valCount++;\n    }\n  };\n  //**********************************************************************//\n\n  //***************************** MAIN LOOP ******************************//\n  // Skip the first row which is just zero temperature data\n  std::getline(inputfile, line);\n\n  // Now iterate over the remaining rows\n  auto rowCount = 1;\n  while (std::getline(inputfile, line)) {\n\n    std::istringstream rowStream(line);\n\n    // We will extract 3*N doubles representing particle positions\n    // from the stream and ignore the 3*N rotation vector components\n    Matrix3Xd Xt(3, N), X0(3, N);\n    readMatrix3Xd(rowStream, Xt);\n\n    // Project the points to a unit sphere\n    X0 = Xt.colwise().normalized();\n\n    // Rotate all points of the shell so that the 0th point is along z-axis\n    Vector3d c = X0.col(0);\n    double_t cos_t = c(2);\n    double_t sin_t = std::sin(std::acos(cos_t));\n    Vector3d axis;\n    axis << c(1), -c(0), 0.;\n    axis.normalize();\n    Matrix3d rotMat, axis_cross, outer;\n    axis_cross << 0., -axis(2), axis(1), axis(2), 0., -axis(0), -axis(1),\n        axis(0), 0.;\n    outer.noalias() = axis * axis.transpose();\n    rotMat =\n        cos_t * Matrix3d::Identity() + sin_t * axis_cross + (1 - cos_t) * outer;\n    Matrix3Xd rPts(3, N);\n    rPts = rotMat * X0;\n\n    // Calculate the stereographic projections\n    Vector3d p0;\n    p0 << 0, 0, -1.0; // Point on the plane of projection\n    c = rPts.col(0);  // The point from which we are projecting\n\n    MapM3Xd l0(&(rPts(0, 1)), 3, N - 1);\n    Matrix3Xd l(3, N - 1), proj(3, N - 1);\n    l = (l0.colwise() - c).colwise().normalized(); // dirns of projections\n    for (auto j = 0; j < N - 1; ++j) {\n      proj.col(j) = ((p0(2) - l0(2, j)) / l(2, j)) * l.col(j) + l0.col(j);\n    }\n\n    // Insert the projected points in a CGAL vertex_with_info vector\n    std::vector<std::pair<Point, unsigned>> verts;\n    for (auto j = 0; j < N - 1; ++j) {\n      verts.push_back(std::make_pair(Point(proj(0, j), proj(1, j)), j + 1));\n    }\n\n    // Triangulate\n    Delaunay dt(verts.begin(), verts.end());\n\n    // Iterate over the triangles to calculate volume\n    auto volume = 0.0;\n    for (auto ffi = dt.finite_faces_begin(); ffi != dt.finite_faces_end();\n         ++ffi) {\n      auto i = ffi->vertex(0)->info();\n      auto j = ffi->vertex(2)->info();\n      auto k = ffi->vertex(1)->info();\n      volume += 0.166666667 * (Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n    }\n\n    // Iterate over infinite faces\n    Face_circulator fc = dt.incident_faces(dt.infinite_vertex()), done(fc);\n    if (fc != 0) {\n      do {\n        auto i = dt.is_infinite(fc->vertex(0)) ? 0 : fc->vertex(0)->info();\n        auto j = dt.is_infinite(fc->vertex(2)) ? 0 : fc->vertex(2)->info();\n        auto k = dt.is_infinite(fc->vertex(1)) ? 0 : fc->vertex(1)->info();\n        volume += 0.166666667 * (Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n      } while (++fc != done);\n    }\n    vol_file << volume << std::endl;\n    rowCount++;\n  }\n  inputfile.close();\n  vol_file.close();\n\n  std::cout << \"Time elapsed = \" << ((float)(clock() - t)) / CLOCKS_PER_SEC\n            << \" seconds.\" << std::endl;\n\n  return 1;\n}\n", "meta": {"hexsha": "bca8899401f0c5cff54e7eaf1e448401434ae7c6", "size": 5833, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/PostProcess/CalculateVolume.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/CalculateVolume.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/CalculateVolume.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": 33.3314285714, "max_line_length": 80, "alphanum_fraction": 0.5880336019, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.6542726852355003}}
{"text": "#include <doctest/doctest.h>\n\n#define EIGEN_INITIALIZE_MATRICES_BY_ZERO\n\n#include <Eigen/Core>\n#include <ode/ode.hpp>\n\nTEST_CASE(\"Coupled Test\")\n{\n  using method_type               = ode::explicit_method<ode::forward_euler_tableau<float>>;\n  using second_order_problem_type = ode::higher_order_initial_value_problem<float, Eigen::Vector3f, 2>;\n  using coupled_problem_type      = second_order_problem_type::coupled_type;\n\n  constexpr auto alpha = 1.0f;\n\n  const auto second_order_problem = second_order_problem_type\n  {\n    0.0f,                                                                              /* t0 */\n    std::array {Eigen::Vector3f(0.0f, 0.0f, 0.0f), Eigen::Vector3f(0.0f, 0.0f, 0.0f)}, /* y0, y'0 */\n    [&] (const float h, const Eigen::Vector3f& y, const Eigen::Vector3f& dydt)         /* y'' = f(t, y, y') */\n    {\n      return 2.0f * h * dydt + 2.0f * alpha * y; /* Hermite differential equation */\n    }\n  };\n\n  auto iterator = ode::coupled_fixed_step_iterator<method_type, coupled_problem_type>(second_order_problem.to_coupled_first_order(), 1.0f /* h */);\n  for (auto i = 0; i < 1000; ++i)\n    ++iterator;\n}", "meta": {"hexsha": "8cc9de62af04545a71ee0a6c0fb1878d03b1fee6", "size": 1130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/coupled_test.cpp", "max_stars_repo_name": "acdemiralp/ode", "max_stars_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-18T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:10.000Z", "max_issues_repo_path": "tests/coupled_test.cpp", "max_issues_repo_name": "acdemiralp/ode", "max_issues_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-11-21T20:54:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T23:12:08.000Z", "max_forks_repo_path": "tests/coupled_test.cpp", "max_forks_repo_name": "acdemiralp/ode", "max_forks_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_forks_repo_licenses": ["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.9655172414, "max_line_length": 147, "alphanum_fraction": 0.6274336283, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480248488136, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6541712047815752}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>\n\n#include <CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n\n#include <iostream>\n#include <fstream>\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\ntypedef K::Vector_3 Vector;\n\ntypedef OpenMesh::PolyMesh_ArrayKernelT< > Mesh;\n\ntypedef boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Mesh>::face_descriptor face_descriptor;\n\n\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/eight.off\";\n\n  Mesh mesh;\n  OpenMesh::IO::read_mesh(mesh, filename);\n\n  CGAL::OM_pmap<Mesh, face_descriptor, Vector> fnormals(mesh);\n  CGAL::OM_pmap<Mesh, vertex_descriptor, Vector> vnormals(mesh);\n  mesh.add_property(fnormals.handle());\n  mesh.add_property(vnormals.handle());\n\n  Vector v(0, 0, 0);\n  BOOST_FOREACH(vertex_descriptor vd, vertices(mesh)){\n      put(vnormals, vd, v); \n    }\n  BOOST_FOREACH(face_descriptor fd, faces(mesh)){\n      put(fnormals, fd, v); \n    }\n  CGAL::Polygon_mesh_processing::compute_normals\n    (mesh,\n     vnormals,\n     fnormals,\n     CGAL::Polygon_mesh_processing::parameters::vertex_point_map(get(CGAL::vertex_point, mesh)).\n     geom_traits(K()));\n\n  std::cout << \"Face normals :\" << std::endl;\n  BOOST_FOREACH(face_descriptor fd, faces(mesh)){\n    std::cout << fnormals[fd] << std::endl;\n  }\n  std::cout << \"Normals at vertices :\" << std::endl;\n  BOOST_FOREACH(vertex_descriptor vd, vertices(mesh)){\n    std::cout << vnormals[vd] << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "d5338b102d5271a87491c231e680107aad9b80c9", "size": 1752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/compute_normals_example_OM.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/compute_normals_example_OM.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/compute_normals_example_OM.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 29.2, "max_line_length": 96, "alphanum_fraction": 0.7248858447, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6541435236969703}}
{"text": "#ifndef PYBNESIAN_UTIL_MATH_CONSTANTS_HPP\n#define PYBNESIAN_UTIL_MATH_CONSTANTS_HPP\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace util {\n\ntemplate <typename T>\ninline auto constexpr pi = boost::math::constants::pi<T>();\n\ntemplate <typename T>\ninline auto constexpr root_two = boost::math::constants::root_two<T>();\n\ntemplate <typename T>\ninline auto constexpr one_div_root_two = boost::math::constants::one_div_root_two<T>();\n\ntemplate <typename T>\ninline auto constexpr nan = std::numeric_limits<T>::quiet_NaN();\n\nnamespace detail {\n\ndouble constexpr sqrtNewtonRaphson(double x, double curr, double prev) {\n    return curr == prev ? curr : sqrtNewtonRaphson(x, 0.5 * (curr + x / curr), curr);\n}\n\ndouble constexpr sqrt_constexpr(double x) { return sqrtNewtonRaphson(x, x, 0); }\n\n}  // namespace detail\n\ninline auto constexpr machine_tol = detail::sqrt_constexpr(std::numeric_limits<double>::epsilon());\n\n}  // namespace util\n\n#endif  // PYBNESIAN_UTIL_MATH_CONSTANTS_HPP\n", "meta": {"hexsha": "2c5a3b637431bbd549c97607e00142a0be6675b8", "size": 983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pybnesian/util/math_constants.hpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/util/math_constants.hpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/util/math_constants.hpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 28.0857142857, "max_line_length": 99, "alphanum_fraction": 0.7568667345, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6541435225561165}}
{"text": "//\n// Created by kazem on 2020-05-18.\n//\n\n\n#include \"includes/sympiler_cholesky.h\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n\n namespace sympiler\n {\n  //  Solving Ax=b\n  // Inputs:\n  //   H  n by n sparse Hessian matrix **lower triangle only** (see\n  //     .triangularView<Eigen::Lower>() )\n  //   q  n by 1 vector\n  // Outputs:\n  //   x  n by 1 solution vector\n  // Returns sympiler exit flag\n  //\n  int sympiler_spd_linsolve(\n    // Pass inputs by copy so we get non-const and casted data\n    Eigen::SparseMatrix<double,Eigen::ColMajor,int> A,\n    Eigen::Matrix<double,Eigen::Dynamic,1> b,\n    Eigen::Matrix<double,Eigen::Dynamic,1> & x){\n   assert(A.isApprox(A.triangularView<Eigen::Lower>(),0) &&\n          \"P should be lower triangular\");\n   assert(A.isCompressed());\n   assert(A.rows()==A.cols());\n   assert(A.rows()==b.rows());\n\n   auto *H = new sym_lib::parsy::CSC;\n   H->nzmax = A.nonZeros();\n   H->ncol= H->nrow=A.rows();\n   H->p = A.outerIndexPtr();\n   H->i = A.innerIndexPtr();\n   H->x = A.valuePtr();\n   H->stype=-1;\n   H->xtype=SYMPILER_REAL;\n   H->packed=TRUE;\n   H->nz = NULL;\n   H->sorted = TRUE;\n\n   auto *sym_chol = new sym_lib::parsy::SolverSettings(H,b.data());\n   sym_chol->ldl_variant = 1;\n   sym_chol->solver_mode = 0;\n   sym_chol->symbolic_analysis();\n   sym_chol->numerical_factorization();\n   double *sol = sym_chol->solve_only();\n   //lbl->compute_norms();\n   //std::cout<<\"residual: \"<<lbl->res_l1<<\"\\n\";\n\n   x = Eigen::Map< Eigen::Matrix<double,Eigen::Dynamic,1> >(\n     sol,A.rows(),1);\n\n   // Exitflag TODO\n   int exitflag = 0;\n   delete sym_chol;\n   delete H;\n   return exitflag;\n  }\n\n\n  sym_lib::parsy::CSC* sympiler_csc_format(\n    // Pass inputs by copy so we get non-const and casted data\n    Eigen::SparseMatrix<double,Eigen::ColMajor,int> A) {\n   assert(A.isApprox(A.triangularView<Eigen::Lower>(), 0) &&\n          \"P should be lower triangular\");\n   assert(A.isCompressed());\n   assert(A.rows() == A.cols());\n\n   auto *H = new sym_lib::parsy::CSC;\n   H->nzmax = A.nonZeros();\n   H->ncol = H->nrow = A.rows();\n   H->p = A.outerIndexPtr();\n   H->i = A.innerIndexPtr();\n   H->x = A.valuePtr();\n   H->stype = -1;\n   H->xtype = SYMPILER_REAL;\n   H->packed = TRUE;\n   H->nz = NULL;\n   H->sorted = TRUE;\n   return H;\n  }\n\n  sym_lib::parsy::SolverSettings* sympiler_chol_symbolic(\n    // Pass inputs by copy so we get non-const and casted data\n    sym_lib::parsy::CSC *A){\n\n   auto *sym_chol = new sym_lib::parsy::SolverSettings(A);\n   sym_chol->ldl_variant = 1;\n   sym_chol->solver_mode = 0;\n   sym_chol->symbolic_analysis();\n   return sym_chol;\n  }\n\n\n  sym_lib::parsy::SolverSettings* sympiler_chol_symbolic(\n    // Pass inputs by copy so we get non-const and casted data\n    sym_lib::parsy::CSC *A, int num_threads, sym_lib::parsy::SYM_ORDER  so, int mode){\n\n   auto *sym_chol = new sym_lib::parsy::SolverSettings(A);\n   sym_chol->ldl_variant = mode;\n   sym_chol->num_thread = num_threads;\n   sym_chol->solver_mode = 0;\n   sym_chol->sym_order = so;\n   sym_chol->symbolic_analysis();\n   return sym_chol;\n  }\n\n }\n\n\n\n", "meta": {"hexsha": "e6ec5f32bafcc267a1de5a2ccc34bc25497588b5", "size": 3055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sympiler_cholesky.cpp", "max_stars_repo_name": "sympiler/sympiler-eigen", "max_stars_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sympiler_cholesky.cpp", "max_issues_repo_name": "sympiler/sympiler-eigen", "max_issues_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sympiler_cholesky.cpp", "max_forks_repo_name": "sympiler/sympiler-eigen", "max_forks_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_forks_repo_licenses": ["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.3362068966, "max_line_length": 86, "alphanum_fraction": 0.6337152209, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6541435214152622}}
{"text": "//\n// Created by jianping on 17-9-1.\n//\n\n#ifndef DEPTHPROBABILITY_ESTIMATOR_HPP\n#define DEPTHPROBABILITY_ESTIMATOR_HPP\n\n#include <ceres/ceres.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <math.h>\n\nclass DistributionEstimator {\npublic:\n    struct distributionCostFunctor {\n\n        distributionCostFunctor(double ob_x,double min, double max)\n        :_ob_x(ob_x),_min(min),_max(max)\n        {\n\n        }\n\n        template <typename T>\n        bool operator()(const T* const params, T* residual) const {\n            T part_normal = T(1.0)/(T(std::sqrt(2.0*M_PI))*params[2])\n                            *ceres::exp(-(T(_ob_x)-params[1])*(T(_ob_x)-params[1])/(T(2)*params[2]*params[2]))*params[0];\n            T part_uniform = T(1)/(_max-_min)*(T(1.0)-params[0]);\n            residual[0] = -ceres::log(part_normal+part_uniform);\n            if(params[0] < T(0.3) || params[0]>T(1))\n            {\n                return false;\n            }\n            return true;\n        }\n\n        double _ob_x;\n        double _min;\n        double _max;\n\n    };\n\npublic:\n    DistributionEstimator(const std::vector<double>& data)\n    :_data(data)\n    {\n        _min = *std::min_element(_data.begin(),_data.end());\n        _max = *std::max_element(_data.begin(),_data.end());\n\n\n        //init\n        params.resize(3);\n        params[0] = 1;\n        params[1] = std::accumulate(_data.begin(),_data.end(),0.0)/_data.size();\n        params[2] = 0;\n        for (int i = 0; i < _data.size(); ++i) {\n            params[2] += (_data[i]-params[1])*(_data[i]-params[1]);\n        }\n        params[2]/=_data.size();\n        params[2] = std::sqrt(params[2]);\n        std::cout<<\" mu:\"<<params[1]<<std::endl;\n        std::cout<<\" sigma:\"<<params[2]<<std::endl;\n    }\n\n    void estimate();\n    std::vector<double> params;//pi mu sigma\nprivate:\n    const std::vector<double>& _data;\n    double _min;\n    double _max;\n\n};\n\n\n#endif //DEPTHPROBABILITY_ESTIMATOR_HPP\n", "meta": {"hexsha": "09af78f3ab1a096274edc603af9bb5e8878f8c80", "size": 1941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/estimator.hpp", "max_stars_repo_name": "kafeiyin00/DepthProbability", "max_stars_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T02:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-01T02:10:32.000Z", "max_issues_repo_path": "src/estimator.hpp", "max_issues_repo_name": "kafeiyin00/DepthProbability", "max_issues_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_issues_repo_licenses": ["MIT"], "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/estimator.hpp", "max_forks_repo_name": "kafeiyin00/DepthProbability", "max_forks_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-14T05:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-14T05:32:14.000Z", "avg_line_length": 25.88, "max_line_length": 121, "alphanum_fraction": 0.552807831, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6541435152620255}}
{"text": "#ifndef MOD_EXPONENTIATION_HPP\n#define MOD_EXPONENTIATION_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"big_int_type.hpp\"\n\n/*\n * Para ser realmente segura, a potencia\u00e7\u00e3o modular n\u00e3o deve deixar rastros da chave.\n * https://crypto.stackexchange.com/questions/75408/efficient-function-algorithm-method-to-do-modular-exponentiation\n */\n\n// Mod pow in constant time with conditional copy\nbig_int mod_pow(big_int base_, big_int power_, big_int n_);\n\n// long long mod_pow_fast(long long base, long long power, long long n);\n\n// long long mod_pow_const_time(long long base, long long power, long long n);\n\n#endif", "meta": {"hexsha": "8d6622ddd23d055a12cf2fb6ac2ed71e26206961", "size": 619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mod_exponentiation.hpp", "max_stars_repo_name": "paulora2405/cal-tf", "max_stars_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mod_exponentiation.hpp", "max_issues_repo_name": "paulora2405/cal-tf", "max_issues_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mod_exponentiation.hpp", "max_forks_repo_name": "paulora2405/cal-tf", "max_forks_repo_head_hexsha": "7fc1c5f5b070ff7dc2800ced5951f6e37abc1db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.95, "max_line_length": 116, "alphanum_fraction": 0.7851373183, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6539037882439692}}
{"text": "#include <fstream>\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <boost/tuple/tuple.hpp>\n\n#include \"gnuplot-iostream.h\"\n#include \"casadi/casadi.hpp\"\n\n#include <unistd.h>\ninline void mysleep(unsigned millis) {\n  ::usleep(millis * 1000);\n}\n\nvoid demo_animation() {\n\n    Gnuplot gp;\n\n    std::cout << \"Press Ctrl-C to quit (closing gnuplot window doesn't quit).\" << std::endl;\n\n    gp << \"set yrange [-1:1]\\n\";\n\n    const int N = 1000;\n    std::vector<double> pts(N);\n\n    double theta = 0;\n    while(1) {\n        for(int i=0; i<N; i++) {\n            double alpha = (static_cast<double>(i)/N-0.5) * 10;\n            pts[i] = sin(alpha*8.0 + theta) * exp(-alpha*alpha/2.0);\n        }\n\n        gp << \"plot '-' binary\" << gp.binFmt1d(pts, \"array\") << \"with lines notitle\\n\";\n        gp.sendBinary1d(pts);\n        gp.flush();\n\n        theta += 0.2;\n        mysleep(100);\n    }\n}\n\n\n\nvoid demo_basic() {\n  Gnuplot gp;\n  // For debugging or manual editing of commands:\n  //Gnuplot gp(std::fopen(\"plot.gnu\", \"w\"));\n  // or\n  //Gnuplot gp(\"tee plot.gnu | gnuplot -persist\");\n\n  std::vector<std::pair<double, double>> xy_pts_A;\n  for(double x=-2; x<2; x+=0.01) {\n    double y = x*x*x;\n    xy_pts_A.emplace_back(x, y);\n  }\n\n  std::vector<std::pair<double, double>> xy_pts_B;\n  for(double alpha=0; alpha<1; alpha+=1.0/24.0) {\n    double theta = alpha*2.0*3.14159;\n    xy_pts_B.emplace_back(cos(theta), sin(theta));\n  }\n\n  gp << \"set xrange [-2:2]\\nset yrange [-2:2]\\n\";\n  gp << \"plot '-' with lines title 'cubic', '-' with points title 'circle'\\n\";\n  gp.send1d(xy_pts_A);\n  gp.send1d(xy_pts_B);\n\n}\n\n\nvoid demo_tmpfile() {\n    Gnuplot gp;\n\n    std::vector<std::pair<double, double>> xy_pts_A;\n    for(double x=-2; x<2; x+=0.01) {\n        double y = x*x*x;\n        xy_pts_A.emplace_back(x, y);\n    }\n\n    std::vector<std::pair<double, double>> xy_pts_B;\n    for(double alpha=0; alpha<1; alpha+=1.0/24.0) {\n        double theta = alpha*2.0*3.14159;\n        xy_pts_B.emplace_back(cos(theta), sin(theta));\n    }\n\n    gp << \"set xrange [-2:2]\\nset yrange [-2:2]\\n\";\n    // Data will be sent via a temporary file.  These are erased when you call\n    // gp.clearTmpfiles() or when gp goes out of scope.  If you pass a filename\n    // (i.e. `gp.file1d(pts, \"mydata.dat\")`), then the named file will be created\n    // and won't be deleted.\n    //\n    // Note: you need std::endl here in order to flush the buffer.  The send1d()\n    // function flushes automatically, but we're not using that here.\n    gp << \"plot\" << gp.file1d(xy_pts_A) << \"with lines title 'cubic',\"\n        << gp.file1d(xy_pts_B) << \"with points title 'circle'\" << std::endl;\n\n}\n\n\n\nint main()\n{\n  std::cout << \"Hello\" << std::endl;\n\n  demo_basic();\n // demo_tmpfile();\n  demo_animation();\n\n  return 0;\n}\n", "meta": {"hexsha": "3775ad4926eedc17047d0db9ccf9a8f179c10abc", "size": 2766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/programs/testing.cpp", "max_stars_repo_name": "sintef-ocean/mimir", "max_stars_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "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/programs/testing.cpp", "max_issues_repo_name": "sintef-ocean/mimir", "max_issues_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "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/programs/testing.cpp", "max_forks_repo_name": "sintef-ocean/mimir", "max_forks_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "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.9189189189, "max_line_length": 92, "alphanum_fraction": 0.5929139552, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6539016034494969}}
{"text": "#include <armadillo>\n\nint main()\n{\n\n    size_t dim = 5;\n    double fl = 0.567;\n\n    arma::mat em = arma::eye<arma::mat>(dim, dim);\n    em.print(\"em\");\n\n    // type is arma::SizeMat?\n    // auto s = arma::size(em);\n    // s.print(\"s\");\n\n    arma::mat em2 = arma::eye<arma::mat>(arma::size(em));\n    em2.print(\"em2\");\n\n    arma::mat em3 = fl * arma::eye<arma::mat>(arma::size(em));\n    em3.print(\"em3\");\n\n    return 0;\n\n}\n    \n", "meta": {"hexsha": "b76f452c80068d38d5e796935d807d638e161053", "size": 425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_eye.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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/armadillo/arma_eye.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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/armadillo/arma_eye.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "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": 16.3461538462, "max_line_length": 62, "alphanum_fraction": 0.52, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6538856454288274}}
{"text": "#include \"mex.h\"\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include \"drakeMexUtil.h\"\n#include <drakeGradientUtil.h>\n\nusing namespace Eigen;\nusing namespace std;\n\n/*\n * c++ version of\n *     function [H,C,B] = manipulatorDynamics(obj,q,qd)\n */\n\ntemplate<typename DerivedQ>\nvoid manipulatorDynamics(const mxArray *pobj, const MatrixBase<DerivedQ>& q, const MatrixBase<DerivedQ>& qd,\n                         mxArray **plhs)\n{\n  // keep it readable:\n  double m1 = mxGetScalar(mxGetProperty(pobj, 0, \"m1\"));\n  double m2 = mxGetScalar(mxGetProperty(pobj, 0, \"m2\"));\n  double l1 = mxGetScalar(mxGetProperty(pobj, 0, \"l1\"));\n  double g = mxGetScalar(mxGetProperty(pobj, 0, \"g\"));\n  double lc1 = mxGetScalar(mxGetProperty(pobj, 0, \"lc1\"));\n  double lc2 = mxGetScalar(mxGetProperty(pobj, 0, \"lc2\"));\n  double b1 = mxGetScalar(mxGetProperty(pobj, 0, \"b1\"));\n  double b2 = mxGetScalar(mxGetProperty(pobj, 0, \"b2\"));\n  double I1 = mxGetScalar(mxGetProperty(pobj, 0, \"Ic1\")) + m1 * lc1 * lc1;\n  double I2 = mxGetScalar(mxGetProperty(pobj, 0, \"Ic2\")) + m2 * lc2 * lc2;\n  double m2l1lc2 = m2 * l1 * lc2;  // occurs often!\n\n  auto c2 = cos(q(1));\n  auto s1 = sin(q(0)), s2 = sin(q(1));\n  auto s12 = sin(q(0) + q(1));\n\n  auto h12 = I2 + m2l1lc2 * c2;\n\n  typedef typename DerivedQ::Scalar Scalar;\n  Matrix<Scalar, 2, 2> H;\n  Matrix<Scalar, 2, 1> C;\n  Matrix<Scalar, 2, 1> B;\n\n  H << I1 + I2 + m2 * l1 * l1 + 2 * m2l1lc2 * c2, h12, h12, I2;\n\n  //C = [ -2*m2l1lc2*s(2)*qd(2), -m2l1lc2*s(2)*qd(2); m2l1lc2*s(2)*qd(1), 0 ];\n  //G = g*[ m1*lc1*s(1) + m2*(l1*s(1)+lc2*s12); m2*lc2*s12 ];\n\n  C << -2 * m2l1lc2 * s2 * qd(1) * qd(0) + -m2l1lc2 * s2 * qd(1) * qd(1), m2l1lc2 * s2 * qd(0) * qd(0);\n\n  // add in G terms\n  C(0) += g * m1 * lc1 * s1 + g * m2 * (l1 * s1 + lc2 * s12);\n  C(1) += g * m2 * lc2 * s12;\n\n  // damping terms\n  C(0) += b1 * qd(0);\n  C(1) += b2 * qd(1);\n\n  // input matrix\n  // multiplying by q(0) just to get the size of the derivatives vector right; Matlab TaylorVar operations will complain otherwise. We could handle this case on the Matlab side instead.\n  B << 0.0 * q(0), 1.0;\n\n  plhs[0] = eigenToMatlabGeneral<2, 2>(H);\n  plhs[1] = eigenToMatlabGeneral<2, 1>(C);\n  plhs[2] = eigenToMatlabGeneral<2, 1>(B);\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n  const mxArray *pobj = prhs[0];\n\n  if (mxIsDouble(prhs[1]) && mxIsDouble(prhs[2])) {\n    auto q = matlabToEigenMap<2, 1>(prhs[1]);\n    auto qd = matlabToEigenMap<2, 1>(prhs[2]);\n    manipulatorDynamics(pobj, q, qd, plhs);\n  } else if (isa(prhs[1], \"TrigPoly\") && isa(prhs[2], \"TrigPoly\")) {\n    auto q = trigPolyToEigen(prhs[1]);\n    auto qd = trigPolyToEigen(prhs[2]);\n    manipulatorDynamics(pobj, q, qd, plhs);\n  } else if (isa(prhs[1], \"TaylorVar\") && isa(prhs[2], \"TaylorVar\")) {\n    auto q = taylorVarToEigen<Dynamic, 1>(prhs[1]);\n    auto qd = taylorVarToEigen<Dynamic, 1>(prhs[2]);\n    manipulatorDynamics(pobj, q, qd, plhs);\n  } else {\n    mexErrMsgIdAndTxt(\"Drake:AcrobotPLantCpp:UnknownType\",\n                      \"don't know how to handle the datatypes passed in for q and/or qd (yet)\");\n  }\n}\n\n\n", "meta": {"hexsha": "ac7fde878fff5e9744332f789c5eeac373cfbc4b", "size": 3115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_stars_repo_name": "jhu-asco/drake", "max_stars_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_issues_repo_name": "jhu-asco/drake", "max_issues_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "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": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_forks_repo_name": "jhu-asco/drake", "max_forks_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 34.2307692308, "max_line_length": 185, "alphanum_fraction": 0.6176565008, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6537754876022699}}
{"text": "/*! \\file main.cpp\n    \\brief The main file performing the spectral numerical integration.\n\n    In this file, we perform the computation from the PDF.\n*/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <chrono>\n#include <fstream>\n\n\n\n#include <Eigen/Dense>\n\n\n#include \"chebyshev_differentiation.h\"\n#include \"spectral_integration_utilities.h\"\n\n#include \"tictoc.h\"\n\n\n//  Number od admitted strain fields and number of mode per strain field\nstatic constexpr unsigned int na = 3;  //  Kirkhoff rod\nstatic constexpr unsigned int ne = 3;  // dimesion of qe\n\n//  Number of Chebyshev nodes\nstatic constexpr unsigned int number_of_chebyshev_nodes = 11;\n\n\n/*!\n * \\brief getA Compute the matrix A for the system x' = Ax + b\n * \\param t_qe The current generalized strains coordinates\n * \\tparam t_state_dimension The dimension of the state x\n * \\tparam t_number_of_chebyshev_nodes The number of Chebyshev nodes (which also account for the first one)\n * \\tparam t_na The number of allowed strain coordinates\n * \\tparam t_ne The number of modes per strain coordinate\n * \\return\n */\ntemplate<unsigned int t_state_dimension, unsigned int t_number_of_chebyshev_nodes, unsigned int t_na, unsigned int t_ne>\nEigen::MatrixXd getA(const Eigen::Matrix<double, ne*ne, 1> &t_qe)\n{\n\n    //  Define the Chebyshev points on the unit circle\n    const auto x = ComputeChebyshevPoints<t_number_of_chebyshev_nodes>();\n\n    //  Definition of the problem dymension\n    static constexpr unsigned int problem_dimension = t_state_dimension * t_number_of_chebyshev_nodes;\n\n    std::array<Eigen::Matrix<double, t_state_dimension, t_state_dimension>, t_number_of_chebyshev_nodes> A_stack;\n\n    Eigen::Vector3d K;\n    Eigen::Matrix<double, t_state_dimension, t_state_dimension> A_at_chebyshev_point;\n    for(unsigned int i=0; i<x.size(); i++){\n\n        //  Extract the curvature from the strain\n        K = Phi<t_na, t_ne>(x[i])*t_qe;\n\n        //  Compute the A matrix of Q' = 1/2 A(K) Q\n        A_at_chebyshev_point <<      0, -K(0),  -K(1),  -K(2),\n                                  K(0),     0,   K(2),  -K(1),\n                                  K(1), -K(2),      0,   K(0),\n                                  K(2),  K(1),  -K(0),      0;\n\n\n        A_stack[i] = 0.5*A_at_chebyshev_point;\n    }\n\n    //  Declare the matrix for the system Ax = b\n    Eigen::Matrix<double, problem_dimension, problem_dimension> A = Eigen::Matrix<double, problem_dimension, problem_dimension>::Zero();\n    A.setConstant(0);\n\n    //  Define a vector containing the indexes of the top left corners of the blocks composing the matrix A\n    Eigen::VectorXi block_indexes = Eigen::VectorXi::LinSpaced(t_state_dimension, 0, t_number_of_chebyshev_nodes*(t_state_dimension-1));\n\n    //  Populate this matrix with all the elements in the right order\n    for(unsigned int chebyshev_point=0; chebyshev_point<t_number_of_chebyshev_nodes; chebyshev_point++){\n\n        //  Get the current set of indexes for the coefficients of the matrix A at the current chebyshev point\n        A(block_indexes, block_indexes) = A_stack[chebyshev_point] ;\n\n        block_indexes += Eigen::VectorXi::Constant(t_state_dimension, 1, 1);\n    }\n\n    return A;\n}\n\n\n/*!\n * \\brief writeToFile writes a Eigen matrix into file\n * \\param t_name    name of the file\n * \\param t_matrix  the Eigen matrix to write into the file\n * \\param t_relative_path_from_build the relative path from the build folder to the file location. Default is none so the file is written in the build directory)\n * \\param t_format  the specification for writing. (Default in column major allignment, with comma column separator and 8 digits precision)\n */\nvoid writeToFile(std::string t_name,\n                 const Eigen::MatrixXd &t_matrix,\n                 std::string t_relative_path_from_build=\"\",\n                 const Eigen::IOFormat &t_format=Eigen::IOFormat(16, 0, \",\"));\n\n\n\nEigen::MatrixXd GetQuaternions(const Eigen::Vector4d &t_initial_state, const Eigen::Matrix<double, ne*ne, 1> &t_qe)\n{\n    /*  The state dimension and the number of nodes are known. The state dimension will not change\n     *  (a quaternion will remain a quaternion, a twist will remain a twist ecc..) and the number of\n     *  nodes are not changed at runtime and neither between runs. Typically, once a satisfactory number\n     *  of nodes has been found, it is kept for the whole lifetime of the project.\n     *\n     *  Thus, we can enforce this concept with constexpr classifier so that the values are known at\n     *  compile time and we can use templated function for our matrices and vector, which are a bit faster.\n     */\n        //  Dimension of the state\n        constexpr unsigned int state_dimension = 4;\n\n        //  Problem size is the total number of elements\n        constexpr unsigned int prob_dimension = state_dimension * number_of_chebyshev_nodes;\n        //  The subset of unknows in the problem\n        constexpr unsigned int unknow_state_dimension = state_dimension * (number_of_chebyshev_nodes - 1);\n\n\n    /*  These are a set of type definition in order to have a more neat algorithm in\n     *  terms of matrix and vector dymensions\n     */\n        typedef Eigen::Matrix<double, prob_dimension, prob_dimension> MatrixNpNp;\n        typedef Eigen::Matrix<double, prob_dimension, 1> VectorNp;\n\n        typedef Eigen::Matrix<double, prob_dimension, state_dimension> MatrixNpNs;\n\n        typedef Eigen::Matrix<double, unknow_state_dimension, unknow_state_dimension> MatrixNuNu;\n        typedef Eigen::Matrix<double, unknow_state_dimension, 1> VectorNu;\n\n        typedef Eigen::Matrix<double, number_of_chebyshev_nodes, number_of_chebyshev_nodes> MatrixNchebNcheb;\n\n        typedef Eigen::Matrix<double, number_of_chebyshev_nodes, state_dimension, Eigen::ColMajor> MatrixNchebNs;\n\n    /*  In this first part, we precompute the matrices P and Dn. In fact, once we know the state dimension and the\n     *  number of nodes, these matrices are constant and thus me can compute them beforehand\n     *\n     *  P.S. As we know the number of nodes, the matrix Phi can be computed at every chebyshev point to be stacked\n     *  into a vector. As a result, instead of computing the matrices, we directly access their value in the vector position.\n     *  This can actually be something more than 200 times faster.\n     *\n     */\n\n        const MatrixNpNp  P = getP<state_dimension, number_of_chebyshev_nodes>();\n\n        const MatrixNchebNcheb Dn = getDn<number_of_chebyshev_nodes>();\n        const MatrixNpNp D = Eigen::KroneckerProduct(Eigen::MatrixXd::Identity(state_dimension, state_dimension), Dn);\n\n    /*  In this part we compute the matrix A and the vector b.\n     *  In this case, the elements of the matrix A depends on the strain. As we change the strains during\n     *  simulation, we have to compute the components of A at runtime.\n     *\n     *  Similarly, the vector b contains the values not related to the derivating variable, but that depends on other parameters.\n     *  For example when computing r' = R(Q)*\u0393 it does not depend on r but only on Q and \u0393.\n     *\n     *  We can interpret everything before this point as the setup and everything after as the actual run-time operations.\n     *\n     *  In the following there are some matrices and operation that could be moved in the setup. However I choose to left them\n     *  there for clarity, but feel free to move where you thing it's better.\n     *\n     *  The following is the translation into C++ of the equations presented in the PDF\n     *\n     */\n        //tictoc.tic();\n        const MatrixNpNp A = getA<state_dimension, number_of_chebyshev_nodes, na, ne>(t_qe);\n        //tictoc.toc(\"Time to compute A : \");\n\n\n        const VectorNp b = Eigen::Matrix<double, prob_dimension, 1>::Zero();\n\n\n        //  Apply transformation of initial condition onto ODE's matrices\n\n        const MatrixNpNp Ap = P.transpose() * A * P;\n        const MatrixNpNp Dp = P.transpose() * D * P;    //  Can be moved in setup\n        const VectorNp bp   = P * b;\n\n\n\n        //  Compute the ivp\n        const MatrixNpNs D_IT = Dp.block<prob_dimension, state_dimension>(0, 0);    //  Can be moved in setup\n        const MatrixNpNs A_IT = Ap.block<prob_dimension, state_dimension>(0, 0);\n        const VectorNp b_IT = ( D_IT - A_IT ) * t_initial_state;\n\n\n        //  Obtain the section related to the unknows of the problem\n        const MatrixNuNu D_NN = Dp.block<unknow_state_dimension, unknow_state_dimension>(state_dimension, state_dimension);\n        const MatrixNuNu A_NN = Ap.block<unknow_state_dimension, unknow_state_dimension>(state_dimension, state_dimension);\n        const VectorNu ivp = b_IT.block<unknow_state_dimension, 1>(state_dimension, 0);\n        const VectorNu b_NN   = bp.block<unknow_state_dimension, 1>(state_dimension, 0);\n\n        //  Finally compute the states at the unknows Chebyshev points\n        const VectorNu X_NN = (D_NN - A_NN).inverse() * (b_NN - ivp);\n\n        //  We now stack together the initial state on top of the other we just compute\n        //  Then we need to map back to a more readable stack of states\n        const VectorNp X_tilde = P * (VectorNp() << t_initial_state, X_NN).finished();\n\n        //  Then we write the element row-wise\n        const MatrixNchebNs X_stack = Eigen::Map<const MatrixNchebNs>(X_tilde.data());\n\n        return X_stack;\n\n}\n\n\n\n\nEigen::MatrixXd IntegratePositions(const Eigen::Vector3d &t_initial_state,\n                                   const Eigen::Matrix<double, ne*ne, 1> &t_qe,\n                                   const Eigen::MatrixXd &t_quaternions_stack)\n{\n    /*  The state dimension and the number of nodes are known. The state dimension will not change\n     *  (a quaternion will remain a quaternion, a twist will remain a twist ecc..) and the number of\n     *  nodes are not changed at runtime and neither between runs. Typically, once a satisfactory number\n     *  of nodes has been found, it is kept for the whole lifetime of the project.\n     *\n     *  Thus, we can enforce this concept with constexpr classifier so that the values are known at\n     *  compile time and we can use templated function for our matrices and vector, which are a bit faster.\n     */\n        //  Dimension of the state\n        constexpr unsigned int state_dimension = 3;\n\n        //  Problem size is the total number of elements\n        constexpr unsigned int prob_dimension = state_dimension * number_of_chebyshev_nodes;\n        //  The subset of unknows in the problem\n        constexpr unsigned int unknow_state_dimension = state_dimension * (number_of_chebyshev_nodes - 1);\n\n\n    /*  These are a set of type definition in order to have a more neat algorithm in\n     *  terms of matrix and vector dymensions\n     */\n        typedef Eigen::Matrix<double, prob_dimension, prob_dimension> MatrixNpNp;\n        typedef Eigen::Matrix<double, prob_dimension, 1> VectorNp;\n\n        typedef Eigen::Matrix<double, prob_dimension, state_dimension> MatrixNpNs;\n\n        typedef Eigen::Matrix<double, unknow_state_dimension, unknow_state_dimension> MatrixNuNu;\n        typedef Eigen::Matrix<double, unknow_state_dimension, 1> VectorNu;\n\n        typedef Eigen::Matrix<double, number_of_chebyshev_nodes, number_of_chebyshev_nodes> MatrixNchebNcheb;\n\n        typedef Eigen::Matrix<double, number_of_chebyshev_nodes, state_dimension, Eigen::ColMajor> MatrixNchebNs;\n\n    MatrixNchebNs positions_stack;\n\n    return positions_stack;\n}\n\n\nint main()\n{\n    tictoc tictoc;\n\n    //  Const curvature strain field\n    Eigen::Matrix<double, ne*na, 1> qe;\n    //  Here we give some value for the strain\n    qe <<   0,\n            0,\n            0,\n            1.2877691307032,\n           -1.63807499160786,\n            0.437406679142598,\n            0,\n            0,\n            0;\n\n//  Let's deal with quaternion\n\n    //  Define the initial state\n    const Eigen::Vector4d initial_state(1, 0, 0, 0); // Quaternion case\n    const auto ruaternions_stack = GetQuaternions(initial_state, qe);\n\n\n//  Let's deal with positions\n     const Eigen::Vector3d initial_position(0, 0, 0);\n     const auto positions_stack = IntegratePositions(initial_position, qe, ruaternions_stack);\n\n    Eigen::Quaterniond q;\n    Eigen::Matrix3d R = q.toRotationMatrix();\n\n\n    std::cout<< \"X_stack = \" << std::endl << ruaternions_stack <<std::endl << std::endl;\n\n    writeToFile(\"Q_stack\", ruaternions_stack);\n\n\n    return 0;\n\n\n    /*\n     * Workflow\n     *\n     * 1) Read through, test some values qe Cheb points\n     *\n     * 2) Move the computations in main into a function IntegrateQuaternion (it returns quaternion stack)\n     *\n     * 3) Extend to positions (stack of r)\n     *\n     */\n\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\nvoid writeToFile(std::string t_name,\n                 const Eigen::MatrixXd &t_matrix,\n                 std::string t_relative_path_from_build,\n                 const Eigen::IOFormat &t_format)\n{\n    if(not t_relative_path_from_build.empty()){\n        //  Ensure relative path ends with a backslash only if a path is given\n        if(not t_relative_path_from_build.ends_with('/'))\n            t_relative_path_from_build.append(\"/\");\n    }\n\n\n    //  Ensure it ends with .csv\n    if(t_name.find(\".csv\") == std::string::npos)\n        t_name.append(\".csv\");\n\n    //  The file will be created in the location given by the realtive path and with the given name\n    const auto file_name_and_location = t_relative_path_from_build + t_name;\n\n    //  Create file in given location with given name\n    std::ofstream file(file_name_and_location.c_str());\n\n    //  Put matrix in this file\n    file << t_matrix.format(t_format);\n\n    //  Close the file\n    file.close();\n }\n", "meta": {"hexsha": "eaef9ffdaacf48e4d8e39a5c4b124f654222aae0", "size": 13643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "aGotelli/experimental_gpu_programming_for_a_spectral_numerical_integration", "max_stars_repo_head_hexsha": "fdb9424b7a7f2f8e694b0280e59562f5fbd31662", "max_stars_repo_licenses": ["MIT"], "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": "aGotelli/experimental_gpu_programming_for_a_spectral_numerical_integration", "max_issues_repo_head_hexsha": "fdb9424b7a7f2f8e694b0280e59562f5fbd31662", "max_issues_repo_licenses": ["MIT"], "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": "aGotelli/experimental_gpu_programming_for_a_spectral_numerical_integration", "max_forks_repo_head_hexsha": "fdb9424b7a7f2f8e694b0280e59562f5fbd31662", "max_forks_repo_licenses": ["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.2040229885, "max_line_length": 161, "alphanum_fraction": 0.6856996262, "num_tokens": 3375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6537754841526152}}
{"text": "/*\n * @Description: ceres residual block for lidar frontend relative pose measurement\n * @Author: Ge Yao\n * @Date: 2020-11-29 15:47:49\n */\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_\n\n#include <ceres/ceres.h>\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <sophus/so3.hpp>\n\n#include \"glog/logging.h\"\n\nnamespace sliding_window {\n\nclass FactorPRVAGRelativePose : public ceres::SizedCostFunction<6, 15, 15> {\npublic:\n\tstatic const int INDEX_P = 0;\n\tstatic const int INDEX_R = 3;\n\n  FactorPRVAGRelativePose(void) {};\n\n  void SetMeasurement(const Eigen::VectorXd &m) {\n\t\tm_ = m;\n\t}\n\n  void SetInformation(const Eigen::MatrixXd &I) {\n    I_ = I;\n  }\n\n  virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n    //\n    // parse parameters:\n    //\n    // a. pose i\n    Eigen::Map<const Eigen::Vector3d>     pos_i(&parameters[0][INDEX_P]);\n    Eigen::Map<const Eigen::Vector3d> log_ori_i(&parameters[0][INDEX_R]);\n    const Sophus::SO3d                    ori_i = Sophus::SO3d::exp(log_ori_i);\n\n    // b. pose j\n    Eigen::Map<const Eigen::Vector3d>     pos_j(&parameters[1][INDEX_P]);\n    Eigen::Map<const Eigen::Vector3d> log_ori_j(&parameters[1][INDEX_R]);\n    const Sophus::SO3d                    ori_j = Sophus::SO3d::exp(log_ori_j);\n\n    //\n    // parse measurement:\n    // \n\t\tconst Eigen::Vector3d     &pos_ij = m_.block<3, 1>(INDEX_P, 0);\n\t\tconst Eigen::Vector3d &log_ori_ij = m_.block<3, 1>(INDEX_R, 0);\n    const Sophus::SO3d         ori_ij = Sophus::SO3d::exp(log_ori_ij);\n\n    //\n    // TODO: get square root of information matrix:\n    //\n\n\n    //\n    // TODO: compute residual:\n    //\n\n    //\n    // TODO: compute jacobians:\n    //\n    if ( jacobians ) {\n      // compute shared intermediate results:\n\n      if ( jacobians[0] ) {\n        // implement computing:\n      }\n\n      if ( jacobians[1] ) {\n        // implement computing:\n      }\n    }\n\n    //\n    // TODO: correct residual by square root of information matrix:\n    //\n\n    return true;\n  }\n\nprivate:\n  static Eigen::Matrix3d JacobianRInv(const Eigen::Vector3d &w) {\n      Eigen::Matrix3d J_r_inv = Eigen::Matrix3d::Identity();\n\n      double theta = w.norm();\n\n      if ( theta > 1e-5 ) {\n          Eigen::Vector3d k = w.normalized();\n          Eigen::Matrix3d K = Sophus::SO3d::hat(k);\n          \n          J_r_inv = J_r_inv \n                    + 0.5 * K\n                    + (1.0 - (1.0 + std::cos(theta)) * theta / (2.0 * std::sin(theta))) * K * K;\n      }\n\n      return J_r_inv;\n  }\n  \n  Eigen::VectorXd m_;\n  Eigen::MatrixXd I_;\n};\n\n} // namespace sliding_window\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_RELATIVE_POSE_HPP_\n", "meta": {"hexsha": "3d724e37671d37d0e8e077e7d7dc3f8f00bc8f6a", "size": 2816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_relative_pose.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_relative_pose.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "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": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_relative_pose.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 24.9203539823, "max_line_length": 103, "alphanum_fraction": 0.6218039773, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6537754826139407}}
{"text": "#pragma once\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\nusing namespace autodiff;\n\n#include <samson/so3.hpp>\n\nnamespace samson::se3\n{\n\n    using Vector6dual = Matrix<dual, 6, 1, 0, 6, 1>;\n    using Matrix4dual = Matrix<dual, 4, 4, 0, 4, 4>;\n\n    auto se3(const Vector6dual &v) -> Matrix4dual\n    {\n        Matrix4dual X;\n        X << 0.0, -v(2), v(1), v(3),\n            v(2), 0.0, -v(0), v(4),\n            -v(1), v(0), 0.0, v(5),\n            0.0, 0.0, 0.0, 0.0;\n        return X;\n    }\n\n    auto se3(const Matrix4dual &X) -> Vector6dual\n    {\n        Vector6dual v;\n        v << X(2, 1), X(0, 2), X(1, 0), X(0, 3), X(1, 3), X(2, 3);\n        return v;\n    }\n\n    auto exp(Vector6dual &x) -> Matrix4dual\n    {\n        using samson::so3::from_axis_angle;\n        using samson::so3::so3;\n\n        Vector3dual w = x.head<3>();\n        Vector3dual v = x.tail<3>();\n\n        dual theta = w.norm();\n        Matrix4dual ret = Matrix4dual::Identity();\n        if (theta == 0.0)\n        {\n            ret = Matrix4dual::Identity();\n            ret.block<3, 1>(0, 3) = v;\n            return ret;\n        }\n\n        Vector3dual k = w.normalized();\n        dual sin_theta = sin(theta);\n        dual one_minus_cos_theta = 1.0 - cos(theta);\n        Matrix3dual K = so3(k);\n        Matrix3dual KK = K * K;\n\n        Matrix3dual I = Matrix3dual::Identity();\n\n        ret.block<3, 3>(0, 0) = from_axis_angle(k, theta);\n        ret.block<3, 1>(0, 3) = (I * theta + one_minus_cos_theta * K + (theta - sin_theta) * KK) * (v / theta);\n\n        return ret;\n    }\n\n    auto exp(Matrix4dual &X) -> Matrix4dual\n    {\n        Vector6dual x = se3(X);\n        return exp(x);\n    }\n} // namespace samson::se3", "meta": {"hexsha": "cd2ef1226efa69871d7dba41ad5f9cbff56db706", "size": 1750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/samson/se3.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/se3.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/se3.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": 24.6478873239, "max_line_length": 111, "alphanum_fraction": 0.5188571429, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6537754807029603}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <boost/assign/std/vector.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace QuantLib;\nusing namespace  boost::assign;\n\n\nvoid bdkSmile() {\n\n    std::ofstream out;\n    out.open(\"bdk.dat\");\n\n    Real forward = 0.03;\n    Real expiryTime = 20.0;\n\n    std::vector<Real> sabrParams;\n    sabrParams.push_back(0.15); // alpha\n    sabrParams.push_back(0.8);    // beta\n    sabrParams.push_back(0.50);   // nu\n    sabrParams.push_back(-0.48);  // rho\n\n    boost::shared_ptr<SabrSmileSection> sabr(\n        new SabrSmileSection(expiryTime, forward, sabrParams));\n\n    boost::shared_ptr<BdkSmileSection> bdk(new BdkSmileSection(sabr, 1.0, 1.0, 0.025, 0.06));\n\n    Real strike = 0.0001;\n    while (strike <= 0.10) {\n        out << strike << \" \" << sabr->optionPrice(strike) << \" \"\n            << bdk->optionPrice(strike) << \" \"\n            << sabr->digitalOptionPrice(strike) << \" \"\n            << bdk->digitalOptionPrice(strike) << \" \" << sabr->density(strike)\n            << \" \" << bdk->density(strike) << \" \" << sabr->volatility(strike) << \" \" <<\n            bdk->volatility(strike) << std::endl;\n        strike += 0.0001;\n    }\n\n    out.close();\n\n}\n\nvoid zabrExamples() {\n\n    Real forward = 0.03;\n    Real expiryTime = 15;\n\n    Real alpha = 0.10;\n    Real beta = 0.7;\n    Real nu = 0.20;\n    Real rho = -0.4;\n    Real gamma = 1.0;\n\n    std::vector<Real> sabrParams, zabrParams;\n\n    sabrParams += alpha, beta, nu, rho;\n    zabrParams += alpha, beta, nu, rho, gamma;\n\n    boost::shared_ptr<SabrSmileSection> sabr = boost::make_shared<SabrSmileSection>(expiryTime, forward, sabrParams);\n\n    boost::shared_ptr<ZabrSmileSection> zabrln =\n        boost::make_shared<ZabrSmileSection>(\n            expiryTime, forward, zabrParams,\n            ZabrSmileSection::ShortMaturityLognormal);\n\n    boost::shared_ptr<ZabrSmileSection> zabrfull =\n        boost::make_shared<ZabrSmileSection>(\n            expiryTime, forward, zabrParams,\n            ZabrSmileSection::FullFd, std::vector<Real>(), 2);\n\n    boost::shared_ptr<ZabrSmileSection> zabrfd =\n        boost::make_shared<ZabrSmileSection>(\n            expiryTime, forward, zabrParams,\n            ZabrSmileSection::LocalVolatility, std::vector<Real>(), 2);\n\n    // only for debug\n    boost::shared_ptr<ZabrModel> tmpZabrFull = boost::make_shared<ZabrModel>(\n        expiryTime, forward, alpha, beta, nu, rho, gamma);\n\n    std::ofstream out;\n    out.open(\"smiles.dat\");\n\n    // debug full fd\n    std::vector<Real> tmpFullFd(100);\n    Size tmpIdx = 0;\n#pragma omp parallel for\n    for(Size i=0;i<100;++i)\n        tmpFullFd[i] = 0.0;//tmpZabrFull->fullFdPrice(0.0001+i*0.0010);\n    // end debug full fd\n\n    Real strike = 0.0001;\n    while (strike <= 1.00) {\n        // 1 strike\n        out << strike << \" \";\n        // 2, 3, 4, 5  sabr\n        out << sabr->volatility(strike) << \" \"\n                  << sabr->optionPrice(strike) << \" \"\n                  << sabr->digitalOptionPrice(strike) << \" \"\n                  << sabr->density(strike) << \" \";\n        // 6, 7, 8, 9  zabr (lognormal short mat)\n        out << zabrln->volatility(strike) << \" \"\n                  << zabrln->optionPrice(strike) << \" \"\n                  << zabrln->digitalOptionPrice(strike) << \" \"\n                  << zabrln->density(strike) << \" \";\n        // 10, 11, 12, 13  zabr (full fd)\n        out <<zabrfull->volatility(strike) << \" \"\n                  << zabrfull->optionPrice(strike) << \" \"\n                  << zabrfull->digitalOptionPrice(strike) << \" \"\n                  << zabrfull->density(strike) << \" \";\n        // 14, 15, 16, 17  zabr (fd)\n        out <<zabrfd->volatility(strike) << \" \"\n                  << zabrfd->optionPrice(strike) << \" \"\n                  << zabrfd->digitalOptionPrice(strike) << \" \"\n                  << zabrfd->density(strike) << \" \";\n        // 14 zabr price full fd (debug)\n        out << tmpFullFd[tmpIdx++];\n        strike += 0.0010;\n        out << std::endl;\n    }\n\n    out.close();\n\n}\n\nvoid zabrPaper() {\n\n    // compare different SABR formulas\n\n    std::ofstream out;\n    out.open(\"smiles.dat\");\n\n    // this is an example from the paper, forward is a guess (since not\n    // mentioned there)\n\n    Real forward = 0.0325;\n    Real expiryTime = 10.0;\n\n    std::vector<Real> sabrParams, zabrParams;\n\n    sabrParams.push_back(0.0873); // alpha\n    sabrParams.push_back(0.7);    // beta\n    sabrParams.push_back(0.47);   // nu\n    sabrParams.push_back(-0.48);  // rho\n\n    // Black Scholes with 20%\n    // sabrParams.push_back(0.20); // alpha\n    // Sabrparams.push_back(1.0);    // beta\n    // sabrParams.push_back(0.0001);   // nu\n    // sabrParams.push_back(0.0);  // rho\n\n    // BS beta = 0.7\n    // sabrParams.push_back(0.08); // alpha\n    // sabrParams.push_back(0.7);    // beta\n    // sabrParams.push_back(0.0001);   // nu\n    // sabrParams.push_back(0.0);  // rho\n\n    // BScholes nu = 0.50\n    // sabrParams.push_back(0.20); // alpha\n    // sabrParams.push_back(1.0);    // beta\n    // sabrParams.push_back(0.50);   // nu\n    // sabrParams.push_back(0.0);  // rho\n\n    zabrParams.push_back(sabrParams[0]);\n    zabrParams.push_back(sabrParams[1]);\n    zabrParams.push_back(sabrParams[2]);\n    zabrParams.push_back(sabrParams[3]);\n    zabrParams.push_back(1.0); // gamma\n\n    std::vector<Real> zabrParamsg0(zabrParams);\n    zabrParamsg0[4] = 0.0;\n    std::vector<Real> zabrParamsg05(zabrParams);\n    zabrParamsg05[4] = 0.5;\n    std::vector<Real> zabrParamsg15(zabrParams);\n    zabrParamsg15[4] = 1.5;\n    std::vector<Real> zabrParamsg17(zabrParams);\n    zabrParamsg17[4] = 1.7;\n\n    boost::shared_ptr<SabrSmileSection> sabr(\n        new SabrSmileSection(expiryTime, forward, sabrParams));\n\n    boost::shared_ptr<ZabrSmileSection> zabrln(\n        new ZabrSmileSection(expiryTime, forward, zabrParams,\n                             ZabrSmileSection::ShortMaturityLognormal));\n\n    boost::shared_ptr<ZabrSmileSection> zabrnm(\n        new ZabrSmileSection(expiryTime, forward, zabrParams,\n                             ZabrSmileSection::ShortMaturityNormal));\n\n    boost::shared_ptr<ZabrSmileSection> zabrlv(new ZabrSmileSection(\n        expiryTime, forward, zabrParams, ZabrSmileSection::LocalVolatility));\n\n    boost::shared_ptr<ZabrSmileSection> zabrnmg0(\n        new ZabrSmileSection(expiryTime, forward, zabrParamsg0,\n                             ZabrSmileSection::ShortMaturityNormal));\n    boost::shared_ptr<ZabrSmileSection> zabrnmg05(\n        new ZabrSmileSection(expiryTime, forward, zabrParamsg05,\n                             ZabrSmileSection::ShortMaturityNormal));\n    boost::shared_ptr<ZabrSmileSection> zabrnmg15(\n        new ZabrSmileSection(expiryTime, forward, zabrParamsg15,\n                             ZabrSmileSection::ShortMaturityNormal));\n    boost::shared_ptr<ZabrSmileSection> zabrnmg17(\n        new ZabrSmileSection(expiryTime, forward, zabrParamsg17,\n                             ZabrSmileSection::ShortMaturityNormal));\n\n    // boost::shared_ptr<ZabrSmileSection> zabrfd(new ZabrSmileSection(\n    //     expiryTime, forward, zabrParams, ZabrSmileSection::FullFd));\n\n    boost::shared_ptr<ZabrModel> zabrmodel = zabrln->model();\n\n    Real strike = 0.0001; // we start at 1bp ...\n\n    while (strike <= 0.50) { // ... and go to 50% ...\n\n        // debug: localvol function for sabr hardcoded\n        Real ytmp = strike >= 0.0\n                        ? 1.0 / (sabrParams[0] * (1.0 - sabrParams[1])) *\n                              (pow(forward, 1.0 - sabrParams[1]) -\n                               pow(strike, 1.0 - sabrParams[1]))\n                        : 1.0 / (sabrParams[0] * (1.0 - sabrParams[1])) *\n                              (pow(-strike, 1.0 - sabrParams[1]) +\n                               pow(forward, 1.0 - sabrParams[1]));\n        Real Jtmp = sqrt(1.0 + sabrParams[2] * sabrParams[2] * ytmp * ytmp -\n                         2.0 * sabrParams[3] * sabrParams[2] * ytmp);\n        Real localVol =\n            Jtmp * pow(std::fabs(strike), sabrParams[1]) * sabrParams[0];\n        // end debug\n\n        out << strike << \" \"                           // 1  SABR hagan\n            << sabr->volatility(strike) << \" \"         // 2\n            << sabr->optionPrice(strike) << \" \"        // 3\n            << sabr->digitalOptionPrice(strike) << \" \" // 4\n            << sabr->density(strike) << \" \"            // 5\n            << zabrln->volatility(strike)\n            << \" \" // 6  ZABR short maturity lognormal\n            << zabrln->optionPrice(strike) << \" \"        // 7\n            << zabrln->digitalOptionPrice(strike) << \" \" // 8\n            << zabrln->density(strike) << \" \"            // 9\n            << zabrnm->volatility(strike)\n            << \" \" // 10  ZABR short maturity normal\n            << zabrnm->optionPrice(strike) << \" \"        // 11\n            << zabrnm->digitalOptionPrice(strike) << \" \" // 12\n            << zabrnm->density(strike) << \" \"            // 13\n            << zabrmodel->localVolatility(strike)\n            << \" \" // 14  *** Equivalent deterministic volatility\n            << localVol\n            << \" \" // 15  *** same as 14, but hardcoded for SABR (debug)\n            << zabrlv->volatility(strike) << \" \"  // 16  ZABR local vol\n            << zabrlv->optionPrice(strike) << \" \" // 17\n            << zabrlv->digitalOptionPrice(strike, Option::Call, 1.0, 1E-4)\n            << \" \"                                                // 18\n            << zabrlv->density(strike, Option::Call, 1E-4) << \" \" // 19\n            // << zabrfd->volatility(strike) << \" \"         // 20  ZABR fd\n            // << zabrfd->optionPrice(strike) << \" \"        // 21\n            // << zabrfd->digitalOptionPrice(strike) << \" \" // 22\n            // << zabrfd->density(strike) << \" \"            // 23\n            << zabrnmg0->volatility(strike)\n            << \" \" // 20  ZABR short maturity normal gamma=0.0\n            << zabrnmg05->volatility(strike)\n            << \" \" // 21  ZABR short maturity normal gamma=0.5\n            << zabrnmg15->volatility(strike)\n            << \" \" // 22  ZABR short maturity normal gamma=1.5\n            << zabrnmg17->volatility(strike)\n            << \" \" // 23  ZABR short maturity normal gamma=1.7\n            << std::endl;\n\n        strike += 0.0001; // ... in steps of 5bp\n    }\n\n    out.close();\n}\n\nvoid splineSmiles() {\n\n    std::ofstream out;\n    out.open(\"smiles2.dat\");\n\n    // same example as in zabrPaper\n\n    Real forward = 0.0325;\n    Real expiryTime = 10.0;\n\n    std::vector<Real> sabrParams;\n\n    sabrParams.push_back(0.0873); // alphacd\n    sabrParams.push_back(0.7);    // beta\n    sabrParams.push_back(0.47);   // nu\n    sabrParams.push_back(-0.48);  // rho\n\n    std::vector<Real> money;\n    for(Size i=0;i<40;i++) {\n        money.push_back(i/40.0);\n    }\n    for(Size i=10;i<=100;i++) {\n        money.push_back(i*0.1);\n    }\n    for(Size i=11;i<=100;i++) {\n        money.push_back(i*1.0);\n    }\n\n    boost::shared_ptr<SabrSmileSection> sabr(\n        new SabrSmileSection(expiryTime, forward, sabrParams));\n\n    boost::shared_ptr<SmileSection> flatSmileSection(new FlatSmileSection(expiryTime,0.10,Actual365Fixed(),forward));\n\n    boost::shared_ptr<SplineDensitySmileSection> spline(\n        new SplineDensitySmileSection(flatSmileSection, forward, 0.0, 1.00,\n                                      false, money));\n\n    std::cout << \"arbitrage free region is \" << spline->leftCoreStrike()\n              << \" ... \" << spline->rightCoreStrike() << std::endl;\n\n    Real strike = 0.00001;\n\n    while (strike <= 3.0) {\n\n        Real vol = 0.10;\n        Real mu = std::log(forward) + vol*vol*expiryTime/2.0;\n        Real referencePrice = blackFormula(Option::Call,strike,forward,vol*sqrt(expiryTime));\n        Real referenceDigital = blackFormulaCashItmProbability(Option::Call,strike,forward,vol*sqrt(expiryTime));\n        NormalDistribution norm(mu,vol*sqrt(expiryTime));\n        Real referenceDensity = norm(std::log(strike))/strike;\n\n        out << strike << \" \"                                    // 1\n            // << sabr->volatility(strike) << \" \"                  // 2\n            // << sabr->optionPrice(strike) << \" \"                 // 3\n            // << sabr->digitalOptionPrice(strike) << \" \"          // 4\n            // << sabr->density(strike) << \" \"                     // 5\n            << flatSmileSection->volatility(strike) << \" \"                  // 2\n            << flatSmileSection->optionPrice(strike) << \" \"                 // 3\n            << flatSmileSection->digitalOptionPrice(strike) << \" \"          // 4\n            << flatSmileSection->density(strike) << \" \"                     // 5\n            << spline->volatility(strike) << \" \"                // 6\n            << spline->optionPrice(strike) << \" \"               // 7\n            << spline->digitalOptionPrice(strike) << \" \"        // 8\n            << spline->density(strike) << \" \"                   // 9\n            // << referencePrice << \" \" // 5\n            // << referenceDigital << \" \" //6\n            // << referenceDensity << \" \"  //7\n            // << referenceDigital - spline->digitalOptionPrice(strike) << \" \" // 8\n            << std::endl;\n        strike += 0.0010;\n    }\n\n    out.close();\n}\n\nvoid sbSmiles() {\n\n    std::ofstream out;\n    out.open(\"smiles3.dat\");\n\n    Real forward = 0.0325;\n    Real expiryTime = 10.0;\n\n\n    boost::shared_ptr<SbSmileSection> sb(new SbSmileSection(expiryTime,forward,\n                                                            0.0,0.50,1.0,1.0));\n\n    Real strike = -1.0;\n\n    while (strike <= 1.0) {\n\n        out << strike << \" \"                                    // 1\n            //<< sb->volatility(strike) << \" \"                  // 2\n            << sb->optionPrice(strike) << \" \"                 // 3\n            << sb->digitalOptionPrice(strike) << \" \"          // 4\n            << sb->density(strike) << \" \"                     // 5\n            << std::endl;\n        strike += 0.0010;\n    }\n\n    out.close();\n\n}\n\nvoid interpolation() {\n\n    std::ofstream out;\n    out.open(\"sample.dat\");\n\n    Real x[] = { 0.0, 0.5, 1.0, 1.5, 2.0 };\n    Real y1[] = { 0.0, 0.5, 1.0, 0.5, 0.0 };\n    Real y2[] = { 0.0, 0.5, 0.2, 0.5, 0.0 };\n\n    std::vector<Real> xv(x,x+5);\n    std::vector<Real> yv1(y1,y1+5);\n    std::vector<Real> yv2(y2,y2+5);\n\n    CubicInterpolation i1(xv.begin(), xv.end(), yv1.begin(), CubicInterpolation::Parabolic, false,\n                         CubicInterpolation::FirstDerivative, 0.0, CubicInterpolation::FirstDerivative, 0.0);\n\n    CubicInterpolation i2(xv.begin(), xv.end(), yv2.begin(), CubicInterpolation::Parabolic, false,\n                         CubicInterpolation::FirstDerivative, 0.0, CubicInterpolation::FirstDerivative, 0.0);\n\n    Real h = 0.0;\n    while(h <= 2.01) {\n        out << h << \" \" << i1(h) << \" \" << i2(h) << std::endl;\n        h+=0.01;\n    }\n\n    out.close();\n\n}\n\nint main(int, char * []) {\n    zabrExamples();\n    // splineSmiles();\n}\n", "meta": {"hexsha": "5216bd0eb0d3d78238bc16511d6493f0fe61f626", "size": 14901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "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": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "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": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "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": 36.1674757282, "max_line_length": 117, "alphanum_fraction": 0.5345949936, "num_tokens": 4441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6537754753423252}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n\nusing namespace boost::numeric::odeint;\n\nusing state_t = std::vector<double>;\n\nint mod_subtract(int a, int b, int bound){\n\t//computes a - b mod bound\n\tint res = a - b;\n\tif(res < 0){\n\t\twhile(res < 0){\n\t\t\tres += bound;\n\t\t}\n\t}\n\telse if(res >= bound){\n\t\tres -= bound;\n\t}\n\treturn res;\n}\n\nvoid time_differentiate(const state_t& x, state_t& dxdt, const double /* type param */)\n{\n\tauto J = x.size();\n\n\t//precondition: x and dx/dt have the same length\n\tassert(J == dxdt.size());\n\t\n\tauto bound = static_cast<long long>(J);\n\n\tdouble F = 8;\n\n\tfor(int i = 0; i < bound; i++){\n\t\tdxdt[i] = ( x[(i+1) % bound] - x[mod_subtract(i, 2, bound)] ) * x[mod_subtract(i,1,bound)] - x[i] + F;\n\t}\n}\n\nvoid apply_initial_conditions(state_t& x){\n\t//apply initial conditions from the HW\n\tfor(auto& val : x){\n\t\tval = 0;\n\t}\n\tx[1] = 1.0;\n}\n\nstruct state_storage\n{\n\tstd::vector<state_t>& m_states;\n\n\tstd::vector<double>& m_times;\n\n\tstate_storage(std::vector<state_t>& states, std::vector<double>& times) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_states(states),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_times(times) {};\n\n\tvoid operator()(const state_t& x, double t){\n\t\tm_states.push_back(x);\n\t\tm_times.push_back(t);\n\t}\n\n};\n\nint main(int argc, char** argv){\n\n\tstate_t x(10);\n\n\tstd::vector<state_t> x_stored;\n\tstd::vector<double> times;\n\n\tapply_initial_conditions(x);\n\n\tdouble time_length = 10.0;\n\n\tdouble init_step_size = 0.05;\n\n\tstd::cout << \"Integrating ODE over 10 second total time length.\\n\";\n\t\n\t//solve with runge_kutta54_cash_karp stepper\n\tsize_t steps = integrate(time_differentiate, x, 0.0,\n\t\t\t\t\t\t   \t time_length, init_step_size, \n\t\t\t\t\t\t\t state_storage(x_stored, times) );\n\n\tstd::cout << \"Solved ODE in \" << steps << \" timesteps.\\n\";\n\n\tstd::ofstream filewriter;\n\tfilewriter.open(\"hw1.csv\");\n\tfor(const auto& x : x_stored){\n\t\tfor(const auto& val : x){\n\t\t\tfilewriter << val << \", \";\n\t\t}\n\t\tfilewriter << \"\\n\";\n\t}\n\n\tfilewriter.close();\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "c83fabc644c73a79f1b4775eddab43ba424ad292", "size": 1995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW-Code/HW1/hw1.cpp", "max_stars_repo_name": "DiffeoInvariant/Data-Assimilation", "max_stars_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_stars_repo_licenses": ["MIT"], "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-Code/HW1/hw1.cpp", "max_issues_repo_name": "DiffeoInvariant/Data-Assimilation", "max_issues_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_issues_repo_licenses": ["MIT"], "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-Code/HW1/hw1.cpp", "max_forks_repo_name": "DiffeoInvariant/Data-Assimilation", "max_forks_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_forks_repo_licenses": ["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.7524752475, "max_line_length": 104, "alphanum_fraction": 0.6365914787, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6536671277985026}}
{"text": "// PythagoreanTriples.cpp\n//\n// Solving the classic Pythagorean triples problem with lazy Stream\n//\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"Stream.h\"\n#include \"Triple.h\"\n\nint main(int argc, char* argv[])\n{\n    std::cout << \"--- triples(first 10)\" << std::endl;\n    std::cout << take(triples(), 10) << std::endl;\n    std::cout << \"--- pythagorean triples(within 20)\" << std::endl;\n    std::cout << triples(20, [](int x, int y, int z) { return (x*x + y*y == z*z); }) << std::endl;\n    /// benchmark\n    int count = argc > 1 ? std::atoi(argv[1]) : 50;\n    std::cout << \"--- benchmark (with lazy Stream)\" << std::endl;\n    int sum = 0;\n    boost::timer::cpu_timer t;\n    forEach(take(triples(INT_MAX-1, [&sum](int x, int y, int z) { return (x*x + y*y == z*z); }), count), [&sum](Triple t) { sum += (std::get<0>(t) + std::get<1>(t) + std::get<2>(t)); });\n    std::cout << t.format() << std::endl;\n    std::cout << \"sum: \" << sum << std::endl;\n    /// nested loops\n    std::cout << \"--- benchmark (with nested loops)\" << std::endl;\n    sum = 0;\n    int found = 0;\n    bool done = false;\n    boost::timer::cpu_timer t1;\n    for (int z = 1; !done && z < INT_MAX; ++z) {\n        for (int y = 1; !done && y < z; ++y) {\n            for (int x = 1; !done && x <= y; ++x) {\n                if (x*x + y*y == z*z) {\n                    sum += (x + y + z);\n                    if (++found == count)\n                        done = true;\n                }\n            }\n        }\n    }\n    std::cout << t1.format() << std::endl;\n    std::cout << \"sum: \" << sum << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "16bd23ff905ff06290dc1d9ed0b5c0786a58bf6e", "size": 1599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PythagoreanTriples.cpp", "max_stars_repo_name": "uwydoc/cppfunc", "max_stars_repo_head_hexsha": "de00e1623d081b9efa3815fc7eee5fcd0b01eb62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PythagoreanTriples.cpp", "max_issues_repo_name": "uwydoc/cppfunc", "max_issues_repo_head_hexsha": "de00e1623d081b9efa3815fc7eee5fcd0b01eb62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PythagoreanTriples.cpp", "max_forks_repo_name": "uwydoc/cppfunc", "max_forks_repo_head_hexsha": "de00e1623d081b9efa3815fc7eee5fcd0b01eb62", "max_forks_repo_licenses": ["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.3125, "max_line_length": 186, "alphanum_fraction": 0.4846779237, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6536671139435107}}
{"text": "/*\n * Copyright 2022 Sean McBane under the terms of the MIT license.\n * This file contains validation via method of manufactured solution for the\n * linear elasticity code. The analytical solution for displacement is given\n * by\n *\n * u_x = (-3.0/2.0*pow(x, 3) + (23.0/4.0)*pow(x, 2) - 5*x)*sin(M_PI*y) +\n *  ((3.0/2.0)*pow(x, 3) - 13.0/4.0*pow(x, 2) + 1)*cos(M_PI*y);\n *\n * u_y = -2*x*y + x + 2*y - 1;\n *\n * Young's modulus: E = 1 + sin(M_PI * x) * cos(M_PI * y) / 4;\n * Poisson's ratio: nu = 3 / 10;\n *\n * The functions below are all derived symbolically from these solutions.\n */\n\n#include <Eigen/Core>\n#include <Eigen/SparseCholesky>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n\n#include \"convert_to_eigen.hpp\"\n#include \"elasticity.hpp\"\n#include \"get_triangles.hpp\"\n#include \"mesh_tools.hpp\"\n#include \"read_mesh.hpp\"\n\nusing namespace Elasticity;\nusing namespace std::chrono;\n\ndouble manufactured_ux(double x, double y)\n{\n    return (-3.0 / 2.0 * pow(x, 3) + (23.0 / 4.0) * pow(x, 2) - 5 * x) * sin(M_PI * y) +\n           ((3.0 / 2.0) * pow(x, 3) - 13.0 / 4.0 * pow(x, 2) + 1) * cos(M_PI * y);\n}\n\ndouble manufactured_uy(double x, double y) { return -2 * x * y + x + 2 * y - 1; }\n\nEigen::Vector2d u_true(std::array<double, 2> coord)\n{\n    const auto [x, y] = coord;\n    return Eigen::Vector2d(manufactured_ux(x, y), manufactured_uy(x, y));\n}\n\nEigen::Vector2d u_right(std::array<double, 2> coord) { return u_true(coord); }\n\nEigen::Vector2d u_left(std::array<double, 2> coord) { return u_true(coord); }\n\nEigen::Vector2d u_upper(std::array<double, 2> coord) { return u_true(coord); }\n\nEigen::Vector2d u_lower(std::array<double, 2> coord) { return u_true(coord); }\n\n/*\n * Definitions of the Lame parameters for the manufactured solution.\n */\ndouble manufactured_lambda(std::array<double, 2> coord)\n{\n    auto [x, y] = coord;\n    return (15.0 / 182.0) * sin(M_PI * x) * cos(M_PI * y) + 30.0 / 91.0;\n}\n\ndouble manufactured_mu(std::array<double, 2> coord)\n{\n    auto [x, y] = coord;\n    return (5.0 / 52.0) * sin(M_PI * x) * cos(M_PI * y) + 5.0 / 13.0;\n}\n\n/*\n * Manufactured solution traction boundary condition for the lower boundary.\n */\ndouble traction_lower_x(double x, [[maybe_unused]] double y) noexcept\n{\n    return (5.0 / 208.0) * (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) - 4) * (sin(M_PI * x) + 4);\n}\n\ndouble traction_lower_y(double x, [[maybe_unused]] double y) noexcept\n{\n    return (5.0 / 364.0) * (sin(M_PI * x) + 4) * (-27 * pow(x, 2) + 79 * x - 40);\n}\n\nEigen::Vector2d traction_lower(std::array<double, 2> coord) noexcept\n{\n    auto [x, y] = coord;\n    return Eigen::Vector2d(traction_lower_x(x, y), traction_lower_y(x, y));\n}\n\n/*\n * Manufactured solution traction boundary condition for the upper boundary.\n */\ndouble traction_upper_x(double x, [[maybe_unused]] double y) noexcept\n{\n    return (5.0 / 208.0) * (-M_PI * x * (6 * pow(x, 2) - 23 * x + 20) + 4) * (sin(M_PI * x) - 4);\n}\n\ndouble traction_upper_y(double x, [[maybe_unused]] double y) noexcept\n{\n    return (5.0 / 364.0) * (sin(M_PI * x) - 4) * (27 * pow(x, 2) + x - 40);\n}\n\nEigen::Vector2d traction_upper(std::array<double, 2> coord) noexcept\n{\n    auto [x, y] = coord;\n    return Eigen::Vector2d(traction_upper_x(x, y), traction_upper_y(x, y));\n}\n\n/*\n * Manufactured solution forcing term on \\Omega\n */\ndouble forcing_x(double x, double y) noexcept\n{\n    return (5.0 / 52.0) * ((13 - 18 * x) * cos(M_PI * y) + (18 * x - 23) * sin(M_PI * y)) *\n               (sin(M_PI * x) * cos(M_PI * y) + 4) +\n           (15.0 / 364.0) * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n               ((13 - 18 * x) * cos(M_PI * y) + (18 * x - 23) * sin(M_PI * y) + 4) +\n           (5.0 / 208.0) * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n               (-pow(M_PI, 2) * x * (6 * pow(x, 2) - 23 * x + 20) * sin(M_PI * y) +\n                pow(M_PI, 2) * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * cos(M_PI * y) + 8) -\n           5.0 / 52.0 * M_PI *\n               (x * (9 * x - 13) * cos(M_PI * y) +\n                (-9 * pow(x, 2) + 23 * x - 10) * sin(M_PI * y)) *\n               cos(M_PI * x) * cos(M_PI * y) +\n           (15.0 / 364.0) * M_PI *\n               (-x * (9 * x - 13) * cos(M_PI * y) + 4 * x +\n                (9 * pow(x, 2) - 23 * x + 10) * sin(M_PI * y) - 4) *\n               cos(M_PI * x) * cos(M_PI * y) -\n           5.0 / 208.0 * M_PI *\n               (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) * cos(M_PI * y) + 8 * y +\n                M_PI * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * sin(M_PI * y) - 4) *\n               sin(M_PI * x) * sin(M_PI * y);\n}\n\ndouble forcing_y(double x, double y) noexcept\n{\n    return (5.0 / 1456.0) * M_PI *\n           ((112 - 112 * x) * sin(M_PI * x) * sin(M_PI * y) +\n            26 * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n                (x * (9 * x - 13) * sin(M_PI * y) +\n                 (9 * pow(x, 2) - 23 * x + 10) * cos(M_PI * y)) -\n            12 *\n                (-x * (9 * x - 13) * cos(M_PI * y) + 4 * x +\n                 (9 * pow(x, 2) - 23 * x + 10) * sin(M_PI * y) - 4) *\n                sin(M_PI * x) * sin(M_PI * y) +\n            7 *\n                (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) * cos(M_PI * y) + 8 * y +\n                 M_PI * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * sin(M_PI * y) - 4) *\n                cos(M_PI * x) * cos(M_PI * y));\n}\n\nEigen::Vector2d forcing(std::array<double, 2> coord) noexcept\n{\n    auto [x, y] = coord;\n    return Eigen::Vector2d(forcing_x(x, y), forcing_y(x, y));\n}\n\nauto compute_parameter_functions(const MeshVariant &mv)\n{\n    Eigen::VectorXd lambda = evaluate_on_mesh(mv, manufactured_lambda);\n    Eigen::VectorXd mu = evaluate_on_mesh(mv, manufactured_mu);\n    return std::pair(lambda, mu);\n}\n\nauto get_boundary_conditions(const MeshVariant &mv, size_t right_bound, size_t left_bound)\n{\n    Eigen::Matrix2Xd uright = evaluate_on_boundary(mv, right_bound, u_right);\n    Eigen::Matrix2Xd uleft = evaluate_on_boundary(mv, left_bound, u_left);\n\n    return std::pair(uright, uleft);\n}\n\nnamespace\n{\n\nEigen::Matrix2Xd solve(const MeshVariant &mv)\n{\n    size_t right_bound = find_boundary_with_tag(mv, \"RIGHT\").value();\n    size_t left_bound = find_boundary_with_tag(mv, \"LEFT\").value();\n    size_t upper_bound = find_boundary_with_tag(mv, \"UPPER\").value();\n    size_t lower_bound = find_boundary_with_tag(mv, \"LOWER\").value();\n\n    auto tp_start = steady_clock::now();\n    Eigen::Matrix2Xd force_coefficients = evaluate_on_mesh(mv, forcing);\n    Eigen::Matrix2Xd nodal_forcing = Elasticity::integrate_volume_force(mv, force_coefficients);\n\n    Eigen::Matrix2Xd traction_upper_coefficients =\n        evaluate_on_boundary(mv, upper_bound, traction_upper);\n    Eigen::Matrix2Xd traction_lower_coefficients =\n        evaluate_on_boundary(mv, lower_bound, traction_lower);\n\n    Eigen::Matrix2Xd traction_upper =\n        integrate_traction_force(mv, upper_bound, traction_upper_coefficients);\n    Eigen::Matrix2Xd traction_lower =\n        integrate_traction_force(mv, lower_bound, traction_lower_coefficients);\n\n    add_traction_force(mv, nodal_forcing, upper_bound, traction_upper);\n    add_traction_force(mv, nodal_forcing, lower_bound, traction_lower);\n\n    auto tp_end = steady_clock::now();\n\n    size_t us = duration_cast<microseconds>(tp_end - tp_start).count();\n    printf(\"Assembling forcing took %ld us\\n\", us);\n\n    Eigen::VectorXd lambda, mu;\n    std::tie(lambda, mu) = compute_parameter_functions(mv);\n\n    Eigen::Matrix2Xd uright, uleft;\n    std::tie(uright, uleft) = get_boundary_conditions(mv, right_bound, left_bound);\n\n    tp_start = steady_clock::now();\n    auto K_unassembled = Elasticity::assemble_stiffness(mv, lambda, mu);\n\n    auto flat_forcing = nodal_forcing.reshaped();\n    Elasticity::impose_dirichlet_condition(mv, K_unassembled, flat_forcing, right_bound, uright);\n    Elasticity::impose_dirichlet_condition(mv, K_unassembled, flat_forcing, left_bound, uleft);\n\n    auto K = convert_to_eigen(K_unassembled);\n    tp_end = steady_clock::now();\n    us = duration_cast<microseconds>(tp_end - tp_start).count();\n    printf(\"Assembling stiffness took %ld us\\n\", us);\n\n    tp_start = steady_clock::now();\n    Eigen::Matrix2Xd u(2, nodal_forcing.cols());\n    u.reshaped() = Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>, Eigen::Upper>(K).solve(\n        nodal_forcing.reshaped());\n    tp_end = steady_clock::now();\n    us = duration_cast<microseconds>(tp_end - tp_start).count();\n    printf(\"Linear system solve took %ld us\\n\", us);\n\n    return u;\n}\n\n} // namespace\n\nint main(int argc, char *argv[])\n{\n    if (!(argc > 1))\n    {\n        fprintf(stderr, \"Usage: ./manufactured [mesh order] [mesh files...]\\n\");\n        return 1;\n    }\n\n    int order = atoi(argv[1]);\n    if (!(order >= 1 && order <= 4))\n    {\n        fprintf(stderr, \"Got mesh order %d; order should be 1-4\\n\", order);\n        return 2;\n    }\n\n    for (int fi = 2; fi < argc; ++fi)\n    {\n        FILE *infile = fopen(argv[fi], \"r\");\n        if (!infile)\n        {\n            fprintf(stderr, \"Skipping mesh file %s (couldn't be opened)\\n\", argv[fi]);\n            continue;\n        }\n        fclose(infile);\n        auto mesh = read_mesh(argv[fi], order);\n        FILE *outfile = fopen(\"mesh_elements.dat\", \"wb\");\n        if (!outfile)\n        {\n            fprintf(stderr, \"Skipping output, couldn't open file\\n\");\n        }\n        else\n        {\n            get_triangle_info(mesh).serialize(outfile);\n            fclose(outfile);\n        }\n        Eigen::Matrix2Xd u = solve(mesh);\n        outfile = fopen(\"u.dat\", \"wb\");\n        int64_t dims[] = {u.rows(), u.cols()};\n        fwrite(dims, sizeof(int64_t), 2, outfile);\n        fwrite(u.data(), sizeof(double), u.size(), outfile);\n        fclose(outfile);\n\n        auto [l2_error, u_norm] = Elasticity::integrate_error(mesh, u, u_true);\n\n        printf(\n            \"Error for input file %s:  %E (L^2 error)  %E (L^2 u)\\n\", argv[fi], l2_error, u_norm);\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "3846639175384e640b0f30c864deadac1c023b1f", "size": 9871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "validation/manufactured.cpp", "max_stars_repo_name": "slmcbane/Elasticity", "max_stars_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_stars_repo_licenses": ["MIT", "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": "validation/manufactured.cpp", "max_issues_repo_name": "slmcbane/Elasticity", "max_issues_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_issues_repo_licenses": ["MIT", "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": "validation/manufactured.cpp", "max_forks_repo_name": "slmcbane/Elasticity", "max_forks_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.513986014, "max_line_length": 98, "alphanum_fraction": 0.5858575626, "num_tokens": 3134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6536661147779619}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/StdVector>\n\nusing Vector2d = Eigen::Vector2d;\nusing Vector4d = Eigen::Vector4d;\nusing Matrix4d = Eigen::Matrix4d;\nusing Vectors2d = std::vector<Vector2d, Eigen::aligned_allocator<Vector2d>>;\nusing Vectors4d = std::vector<Vector4d, Eigen::aligned_allocator<Vector4d>>;\n", "meta": {"hexsha": "a39e0f048cac3d5bf2edb8d547bdad7fca87cc15", "size": 319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vector_space.hpp", "max_stars_repo_name": "mabur/rasterizer", "max_stars_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_stars_repo_licenses": ["MIT"], "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/vector_space.hpp", "max_issues_repo_name": "mabur/rasterizer", "max_issues_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_issues_repo_licenses": ["MIT"], "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/vector_space.hpp", "max_forks_repo_name": "mabur/rasterizer", "max_forks_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_forks_repo_licenses": ["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.9, "max_line_length": 76, "alphanum_fraction": 0.7742946708, "num_tokens": 90, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6536661125974979}}
{"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n#include \"math_unit_test.hpp\"\n#include <boost/math/quadrature/tanh_sinh.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n\nusing std::log;\nusing std::sin;\nusing std::abs;\nusing boost::math::quadrature::tanh_sinh;\nusing boost::multiprecision::mpfr_float;\nusing boost::math::constants::pi;\nusing boost::math::constants::zeta_three;\n\nint main() {\n    using Real = mpfr_float;\n    int p = 100;\n    mpfr_float::default_precision(p);\n    auto f = [](Real x)->Real { return x*log(sin(x)); };\n    auto integrator = tanh_sinh<mpfr_float>();\n    Real Q = integrator.integrate(f, Real(0), pi<Real>()/2);\n    // Sanity check: NIntegrate[x*Log[Sin[x]],{x,0,Pi/2}] = -0.329236\n    Real expected = (7*zeta_three<Real>() - pi<Real>()*pi<Real>()*log(static_cast<Real>(4)))/16;\n    CHECK_ULP_CLOSE(expected, Q, 3);\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "d41963f12b2398d4fd73d980ccba0a8cd52739fb", "size": 1112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tanh_sinh_mpfr.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/tanh_sinh_mpfr.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/tanh_sinh_mpfr.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": 35.8709677419, "max_line_length": 96, "alphanum_fraction": 0.6978417266, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6536602294769881}}
{"text": "#include \"clustering/spectral_cluster.h\"\n#include \"clustering/kmeans.h\"\n\n#include <algorithm>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <glog/logging.h>\n\n#include \"util/timer.h\"\n\nnamespace GraphSfM {\n\nstd::unordered_map<int, int> SpectralCluster::ComputeCluster(\n        const std::vector<std::pair<int, int>>& edges,\n        const std::vector<int>& weights,\n        const int num_partitions)\n{\n    if (num_partitions == 1) {\n        for (auto node : nodes_) {\n            labels_[node] = 0;\n        }\n        return labels_;\n    }\n\n    colmap::Timer timer;\n    std::vector<Eigen::Triplet<double>> s_triplets;\n    std::unordered_map<int, int> degrees;\n    const int k = num_partitions;\n    cluster_num_ = num_partitions;\n\n    for (uint i = 0; i < edges.size(); i++) {\n        auto edge = edges[i];\n        nodes_.push_back(edge.first);\n        nodes_.push_back(edge.second);\n    }\n\n    std::sort(nodes_.begin(), nodes_.end());\n    nodes_.erase(std::unique(nodes_.begin(), nodes_.end()), nodes_.end());\n\n    // 1. Compute similarity graph.\n    for (uint i = 0; i < nodes_.size(); i++) {\n        node_mapper_[nodes_[i]] = i;\n    }\n\n    timer.Start();\n    const int N = nodes_.size();\n    Eigen::SparseMatrix<double> S(N, N);\n    for (uint i = 0; i < edges.size(); i++) {\n        int src = edges[i].first, dst = edges[i].second;\n        s_triplets.push_back(Eigen::Triplet<double>(src, dst, weights[i]));\n        s_triplets.push_back(Eigen::Triplet<double>(dst, src, weights[i]));\n        degrees[src] += 2;\n    }\n\n    S.setFromTriplets(s_triplets.begin(), s_triplets.end());\n    S.makeCompressed();\n    timer.Pause();\n    LOG(INFO) << \"1. Similarity Graph Computation Time: \" << timer.ElapsedSeconds();\n\n    // 2. Compute Laplacian matrix.\n    timer.Start();\n    Eigen::SparseMatrix<double> L = ComputeLaplacian(S, degrees);\n    L.makeCompressed();\n    timer.Pause();\n    LOG(INFO) << \"2. Laplacian Matrix Computation Time: \" << timer.ElapsedSeconds();\n\n    // 3. Compute the top-k smallest eigen values and corresponding eigen vectors.\n    timer.Start();\n    Spectra::SparseSymMatProd<double> op(L);\n    Spectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE,\n                          Spectra::SparseSymMatProd<double>> eigs(&op, \n                                                                  k,\n                                                                  std::min(2 * k, N));\n    eigs.init();\n    int nconv = eigs.compute();\n\n    Eigen::VectorXd eigen_values;\n    Eigen::MatrixXd eigen_vectors;\n    if (eigs.info() == Spectra::SUCCESSFUL) {\n        eigen_values = eigs.eigenvalues();\n        eigen_vectors = eigs.eigenvectors();\n    }\n\n    timer.Pause();\n    LOG(INFO) << \"3. EigenValue Computation Time: \" << timer.ElapsedSeconds();\n\n    // 4. Reverse original eigen vectors(as it stored in descending order)\n    timer.Start();\n    uint i = 0, j = k - 1;\n    while (i < j) {\n        const Eigen::VectorXd tmp = eigen_vectors.col(i);\n        eigen_vectors.col(i) = eigen_vectors.col(j);\n        eigen_vectors.col(j) = tmp;\n        i++; j--;\n    }\n\n    std::vector<Eigen::VectorXd> source_data;\n    source_data.reserve(eigen_vectors.rows());\n    for (uint i = 0; i < eigen_vectors.rows(); i++) {\n        source_data.push_back(eigen_vectors.row(i));\n    }\n    timer.Pause();\n    LOG(INFO) << \"4. Eigen Vectors Reverse Time: \" << timer.ElapsedSeconds();\n\n    // 5. Invert K-Means for clustering.\n    timer.Start();\n    std::vector<uint32_t> cluster_assignment;\n    std::vector<Eigen::VectorXd> centers;\n    KMeans(source_data, cluster_assignment, centers, k);\n    timer.Pause();\n    LOG(INFO) << \"5. KMeans Time: \" << timer.ElapsedSeconds();\n\n    for (uint i = 0; i < cluster_assignment.size(); i++) {\n        labels_[nodes_[i]] = cluster_assignment[i];\n    }\n    return labels_;\n}\n\nEigen::SparseMatrix<double> SpectralCluster::ComputeLaplacian(\n                const Eigen::SparseMatrix<double>& S,\n                const std::unordered_map<int, int>& degrees) const\n{\n    // Compute degree matrix.\n    const int N = degrees.size();\n    Eigen::SparseMatrix<double> D(N, N);\n    // Eigen::SparseMatrix<double> D_inv(N, N);\n    // Eigen::SparseMatrix<double> D_sqrt(N, N);\n    for (auto it = degrees.begin(); it != degrees.end(); ++it) {\n        int id = it->first;\n        D.insert(node_mapper_.at(id), node_mapper_.at(id)) = it->second;\n        // D_inv.insert(node_mapper_.at(id), node_mapper_.at(id)) = 1.0 / it->second;\n        // D_sqrt.insert(node_mapper_.at(id), node_mapper_.at(id)) = -1.0 / sqrt(it->second);\n    }\n    D.makeCompressed();\n    // D_inv.makeCompressed();\n    // D_sqrt.makeCompressed();\n\n    // Compute Laplacian matrix.\n    Eigen::SparseMatrix<double> L = D - S;\n    // Eigen::MatrixXd L_random = D_inv * L;\n    // Eigen::MatrixXd L_sym = D_sqrt * L * D_sqrt;\n\n    return L;\n}\n\n} // namespace GraphSfM", "meta": {"hexsha": "d77b298fe3b54dfe2def1889aaf5fab374e637c7", "size": 4953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clustering/spectral_cluster.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/clustering/spectral_cluster.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/clustering/spectral_cluster.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": 33.02, "max_line_length": 93, "alphanum_fraction": 0.6036745407, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.653582385535319}}
{"text": "#include \"stats/rmsd.h\"\n#include <xmd/utils/convert.h>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nnamespace xmd {\n    void compute_rmsd::operator()() const {\n        using matrix_t = Eigen::Matrix<real, Eigen::Dynamic, 3>;\n        matrix_t P = matrix_t::Zero(num_particles, 3);\n        matrix_t Q = matrix_t::Zero(num_particles, 3);\n\n        for (int idx = 0; idx < num_particles; ++idx) {\n            P.row(idx) = convert<real>(r[idx]);\n            Q.row(idx) = convert<real>(ref_r[idx]);\n        }\n\n        Eigen::Matrix<real, 3, 3> H = P.transpose() * Q;\n        auto svd = Eigen::JacobiSVD<decltype(H)>(H,\n            Eigen::ComputeFullU & Eigen::ComputeFullV);\n\n        auto U = svd.matrixU();\n        auto V = svd.matrixV();\n        auto d = (V * U.transpose()).determinant() > 0 ? 1 : -1;\n        auto R = V * Eigen::DiagonalMatrix<real, 3>(1, 1, d) * U.transpose();\n\n        auto D = (P - Q) * R;\n        real rmsd_ = 0.0;\n        for (int idx = 0; idx < num_particles; ++idx) {\n            rmsd_ += D.row(idx).squaredNorm();\n        }\n        *rmsd = sqrt(rmsd_ / num_particles);\n    }\n}", "meta": {"hexsha": "283de0673639a630e8ce753ff4fa4e711681e00c", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xmd/src/stats/rmsd.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/rmsd.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/rmsd.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.2424242424, "max_line_length": 77, "alphanum_fraction": 0.5414767548, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6535682474385669}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\n\nusing namespace std;  \n\n\ntemplate <typename MatrixA>\nvoid test(MatrixA& A, unsigned dim1, unsigned dim2, const char* name)\n{\n    const unsigned max_print_size= 25;\n    cout << \"\\n\" << name << \"\\n\";\n    laplacian_setup(A, dim1, dim2);\n\n    unsigned size= dim1 * dim2;\n    mtl::dense_vector<double> v(size), b(size), r(size);\n\n    for (unsigned i= 0; i < num_cols(A); i++)\n\tv[i]= A[12][i];\n    b= 3.0;\n\n    r= b + A * v;\n\n    if (size <= max_print_size)\n\tcout << \"A= \\n\" << A << \"\\n\\nb + A * v = \" << r << '\\n';\n    \n\n    if (dim1 == 5 && dim2 == 5) {\n\tMTL_THROW_IF(abs(r[12] - 23.0) > 0.0001, mtl::runtime_error(\"r[12] should be 23.\\n\"));\n    }\n\n    r= b - A * v;\n\n    if (size <= max_print_size)\n\tcout << \"\\n\\nb - A * v = \" << r << '\\n';\n    \n    if (dim1 == 5 && dim2 == 5) {\n\tMTL_THROW_IF(abs(r[12] + 17.0) > 0.0001, mtl::runtime_error(\"r[12] should be -17.\\n\"));\n    }\n\n    // typedef mtl::dense_vector<double, mtl::parameters<mtl::row_major> >  vrt;\n    // vrt rt, vt(trans(v));\n\n    // rt= v * A;\n}\n \n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n\n    unsigned dim1= 5, dim2= 5;\n\n    if (argc > 2) {dim1= atoi(argv[1]);dim2= atoi(argv[2]);}\n    unsigned size= dim1 * dim2; \n\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n\n    test(cr, dim1, dim2, \"Row-major sparse\");\n    test(cc, dim1, dim2, \"Column-major sparse\");\n\n    test(dr, dim1, dim2, \"Row-major dense\");\n    test(dc, dim1, dim2, \"Column-major dense\");\n\n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "8aa228fe20a9af7d405a3c65453f08904afe6833", "size": 2226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_vector_product_expression_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/matrix_vector_product_expression_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/matrix_vector_product_expression_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": 22.26, "max_line_length": 94, "alphanum_fraction": 0.5718778077, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6535407488447953}}
{"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <sstream>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n// -- Some typedefs\nusing TScalar = double;\nusing TMatrix = Eigen::Matrix< TScalar, Eigen::Dynamic, Eigen::Dynamic >;\n\n// -- Helper functions\nvoid read_file( TMatrix& X, const std::string& filename );\n\n// -- Main function\nint main( int argc, char** argv )\n{\n  // Check inputs and get them\n  if( argc < 2 )\n  {\n    std::cerr\n      << \"Usage: \" << argv[ 0 ] << \" input.bin\"\n      << std::endl;\n    return( 1 );\n  } // end if\n  std::string input = argv[ 1 ];\n\n  // Read data\n  TMatrix X;\n  std::cout << \"Read... \" << std::flush;\n  read_file( X, input );\n  std::cout << \"done! \" << X.rows( ) << \" \" << X.cols( ) << std::endl;\n\n  // Compute PCA\n  std::cout << \"Mean... \" << std::flush;\n  auto m = X.colwise( ).mean( );\n  std::cout << \"done! \" << m.rows( ) << \" \" << m.cols( ) << std::endl;\n  std::cout << \"Centering... \" << std::flush;\n  auto c = X.rowwise( ) - m;\n  std::cout << \"done! \" << c.rows( ) << \" \" << c.cols( ) << std::endl;\n  std::cout << \"Covariance... \" << std::flush;\n  auto S = ( c.transpose( ) * c ) / TScalar( X.cols( ) );\n  std::cout << \"done! \" << S.rows( ) << \" \" << S.cols( ) << std::endl;\n  std::cout << \"Eigen analysis... \" << std::flush;\n  auto svd = S.bdcSvd( Eigen::ComputeFullU | Eigen::ComputeFullV );\n  std::cout << \"done!\" << std::endl;\n  TMatrix eR = svd.matrixU( );\n  TMatrix ev = svd.singularValues( );\n  TScalar sv = ev.sum( );\n\n  unsigned long i = 0;\n  double s = ev( i, 0 ) / sv;\n  while( i < ev.rows( ) && s <= 0.95 )\n  {\n    i++;\n    s += ev( i, 0 ) / sv;\n  } // end while\n  TMatrix Xp = ( X * eR ).block( 0, 0, X.rows( ), i );\n  std::cout << i << \" \" << Xp.rows( ) << \" \" << Xp.cols( ) << std::endl;\n\n  unsigned long xrows, xcols;\n  xrows = Xp.rows( );\n  xcols = Xp.cols( );\n\n  std::ofstream out = std::ofstream( \"out.bin\", std::ios::binary );\n  out.write( ( char* )( &xrows ), sizeof( unsigned long ) );\n  out.write( ( char* )( &xcols ), sizeof( unsigned long ) );\n  out.write( ( char* )( Xp.data( ) ), sizeof( TScalar ) * xrows * xcols );\n  out.close( );\n\n  /* TODO\n     this->m_EigenValues.SetSize( ps );\n     for( unsigned int d = 0; d < ps; ++d )\n     this->m_EigenValues[ d ] = ev( d, 0 );\n  */\n\n  return( 0 );\n}\n\n// -------------------------------------------------------------------------\nvoid read_file( TMatrix& X, const std::string& filename )\n{\n  std::ifstream Xreader = std::ifstream( filename, std::ios::binary );\n  unsigned long xrows, xcols;\n  Xreader.read( ( char* )( &xrows ), sizeof( unsigned long ) );\n  Xreader.read( ( char* )( &xcols ), sizeof( unsigned long ) );\n  X = TMatrix::Zero( xrows, xcols );\n  Xreader.read( ( char* )( X.data( ) ), sizeof( TScalar ) * xrows * xcols );\n  Xreader.close( );\n}\n\n// eof - pca.cxx\n", "meta": {"hexsha": "2193c4fd979d3e75d597b2c3acf1e1bf045a114d", "size": 3051, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/pca/pca.cxx", "max_stars_repo_name": "DanteCely/PUJ_ML", "max_stars_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:20:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:16:37.000Z", "max_issues_repo_path": "examples/pca/pca.cxx", "max_issues_repo_name": "DanteCely/PUJ_ML", "max_issues_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "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": "examples/pca/pca.cxx", "max_forks_repo_name": "DanteCely/PUJ_ML", "max_forks_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:17:44.000Z", "avg_line_length": 30.8181818182, "max_line_length": 76, "alphanum_fraction": 0.5093411996, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6535001412225011}}
{"text": "///////////////////////////////////////////////////////////////////////////////\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\n#include <app/benchmark/app_benchmark.h>\n#include <app/benchmark/app_benchmark_detail.h>\n\n#if(APP_BENCHMARK_TYPE == APP_BENCHMARK_TYPE_BOOST_MULTIPRECISION_CBRT)\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n#endif\n\n//#define APP_BENCHMARK_TYPE_BOOST_BOOST_MULTIPRECISION_CBRT_USE_BIN_FLOAT\n\n//TGT_INCLUDES  = -IC:/boost/modular_boost/boost/libs/multiprecision/include        \\\n//                -IC:/boost/modular_boost/boost/libs/math/include                  \\\n//                -IC:/boost/modular_boost/boost/libs/config/include\n\n//LINKER_DEFINITION_FILE := $(PATH_TGT_MAKE)/stm32f446_with_stdlib.ld\n\n//C:/boost/modular_boost/boost/libs/multiprecision/include;C:/boost/modular_boost/boost/libs/math/include;C:/boost/modular_boost/boost/libs/config/include;\n\n#if !defined(BOOST_MP_STANDALONE)\n#define BOOST_MP_STANDALONE\n#endif\n\n#if !defined(BOOST_MATH_STANDALONE)\n#define BOOST_MATH_STANDALONE\n#endif\n\n#if !defined(BOOST_NO_RTTI)\n#define BOOST_NO_RTTI\n#endif\n\n#if !defined(BOOST_DISABLE_THREADS)\n#define BOOST_DISABLE_THREADS\n#endif\n\n#if !defined(BOOST_NO_EXCEPTIONS)\n#define BOOST_NO_EXCEPTIONS\n#endif\n\n#if !defined(BOOST_MATH_DISABLE_ERROR_HANDLING)\n#define BOOST_MATH_DISABLE_ERROR_HANDLING\n#endif\n\n#if !defined(BOOST_NO_CXX11_THREAD_LOCAL)\n#define BOOST_NO_CXX11_THREAD_LOCAL\n#endif\n\n#include <boost/config.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#if defined(APP_BENCHMARK_TYPE_BOOST_BOOST_MULTIPRECISION_CBRT_USE_BIN_FLOAT)\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#else\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#endif\n\nbool app::benchmark::run_boost_multiprecision_cbrt()\n{\n  using big_float_backend_type =\n  #if defined(APP_BENCHMARK_TYPE_BOOST_BOOST_MULTIPRECISION_CBRT_USE_BIN_FLOAT)\n    boost::multiprecision::cpp_bin_float<101, boost::multiprecision::backends::digit_base_10, void, std::int32_t>;\n  #else\n    boost::multiprecision::cpp_dec_float<101, std::int32_t, void>;\n  #endif\n\n  using big_float_type =\n    boost::multiprecision::number<big_float_backend_type, boost::multiprecision::et_off>;\n\n  // Compute a square root.\n  static const big_float_type\n    big_float_arg\n    {\n      big_float_type(UINT32_C(123456)) / 100U\n    };\n\n  using std::cbrt;\n  using boost::math::cbrt;\n\n  const big_float_type big_float_result = cbrt(big_float_arg);\n\n  // N[(123456/100)^(1/3), 111]\n  // 10.7276369432283170454869317373527647801772956394047834686224956433128028534945259441672192774907629718402457465\n  static const big_float_type\n    control\n    {\n      \"10.7276369432283170454869317373527647801772956394047834686224956433128028534945259441672192774907629718402457465\"\n    };\n\n  // Compare the calculated result with the known control value.\n  const bool app_benchmark_result_is_ok = detail::is_close_fraction(big_float_result, control);\n\n  return app_benchmark_result_is_ok;\n}\n\n#if defined(APP_BENCHMARK_STANDALONE_MAIN)\nint main()\n{\n  // g++ -Wall -O3 -march=native -I./ref_app/src/mcal/host -I./ref_app/src -DAPP_BENCHMARK_TYPE=APP_BENCHMARK_TYPE_BOOST_MULTIPRECISION_CBRT -DAPP_BENCHMARK_STANDALONE_MAIN ./ref_app/src/app/benchmark/app_benchmark_boost_math_cbrt_tgamma.cpp -o ./ref_app/bin/app_benchmark_boost_multiprecision_cbrt.exe\n\n  bool result_is_ok = true;\n\n  for(unsigned i = 0U; i < 64U; ++i)\n  {\n    result_is_ok &= app::benchmark::run_boost_multiprecision_cbrt();\n  }\n\n  return (result_is_ok ? 0 : -1);\n}\n\n#endif\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n\n#endif // APP_BENCHMARK_TYPE_BOOST_MULTIPRECISION_CBRT\n", "meta": {"hexsha": "53c5481ee95ab882e436dd337b6827d18e62f3a3", "size": 3819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ref_app/src/app/benchmark/app_benchmark_boost_multiprecision_cbrt.cpp", "max_stars_repo_name": "jwinarske/real-time-cpp", "max_stars_repo_head_hexsha": "a48897badce755d31003f23817721e50eba69cd9", "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": "ref_app/src/app/benchmark/app_benchmark_boost_multiprecision_cbrt.cpp", "max_issues_repo_name": "jwinarske/real-time-cpp", "max_issues_repo_head_hexsha": "a48897badce755d31003f23817721e50eba69cd9", "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": "ref_app/src/app/benchmark/app_benchmark_boost_multiprecision_cbrt.cpp", "max_forks_repo_name": "jwinarske/real-time-cpp", "max_forks_repo_head_hexsha": "a48897badce755d31003f23817721e50eba69cd9", "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.7983870968, "max_line_length": 302, "alphanum_fraction": 0.7695731867, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6534588240576298}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>\ntoeplitz(const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>& vec)\n{\n  index size = vec.size();\n\n  Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> mat(size, size);\n\n  for (auto i = 0; i < size; i++)\n  {\n    for (auto j = 0; j < i; j++) mat(j, i) = vec(i - j);\n    for (auto j = i; j < size; j++) mat(j, i) = vec(j - i);\n  }\n\n  return mat;\n}\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "e9f26c1cc304301b7eab260c46244c8d04a87a8e", "size": 994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Toeplitz.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/Toeplitz.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/Toeplitz.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": 26.1578947368, "max_line_length": 74, "alphanum_fraction": 0.6941649899, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6534588191137906}}
{"text": "/*\n * recon.cpp\n *\n *  Created on: Jul 25, 2019\n *      Author: dmarce1\n */\n#include \"../../octotiger/print.hpp\"\n#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <map>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <complex>\n#include <boost/program_options.hpp>\n\nauto band_filter(double t, double Ps, double Pc) {\n\tconst auto x = 2.0 * M_PI * t / Pc;\n\tconst auto y = 2.0 * M_PI * (t / Ps + 0.5);\n\tconst auto sinc = x == 0 ? 1.0 : sin(x) / x;\n\tconstexpr auto a0 = 7938.0 / 18608.0;\n\tconstexpr auto a1 = 9240.0 / 18608.0;\n\tconstexpr auto a2 = 1430.0 / 18608.0;\n\tconst auto blackman = (a0 - a1 * cos(y) + a2 * cos(2 * y));\n\tif (blackman > 0.0) {\n\t\treturn sinc * blackman;\n\t} else {\n\t\treturn 0.0;\n\t}\n}\n\nvoid output_spectrogram(double Ps, double Pc) {\n\tdouble pmin = Pc / 100.0;\n\tdouble pmax = 2.0 * Ps;\n\tdouble dp = (pmax - pmin) / 1000.0;\n\tconst auto dt = Ps / 100000.0;\n\tFILE *fp = fopen(\"filter.dat\", \"wt\");\n\tfor (auto p = pmin; p <= pmax; p += dp) {\n\t\tdouble w = 0.0;\n\t\tconst auto omega = 2.0 * M_PI / p;\n\t\tdouble sum = 0.0;\n\t\tconstexpr std::complex<double> I(0, 1);\n\t\tfor (double t = dt / 2.0; t < Ps / 2.0; t += dt) {\n\t\t\tconst auto bf = band_filter(t, Ps, Pc);\n\t\t\tw += 2.0 * bf * dt;\n\t\t\tsum += 2.0 * bf * cos(omega * t) * dt;\n\t\t}\n\t\tsum /= w;\n\t\tfprintf(fp, \"%.12e %.12e\\n\", p, sum);\n\t}\n\tfclose(fp);\n\n}\n\nauto derivative(const std::vector<std::vector<double>> &f, double omega) {\n\tstd::vector<std::vector<double>> g;\n\tstd::vector<double> u(f[0].size());\n\tconst auto P = 2.0 * M_PI / omega;\n\tfor (int n = 1; n < f.size() - 1; n++) {\n\t\tconst auto nm = n - 1;\n\t\tconst auto np = n + 1;\n\t\tconst auto h1 = (f[n][0] - f[nm][0]);\n\t\tconst auto h2 = (f[np][0] - f[n][0]);\n\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\tu[i] = P * (f[np][i] * h1 * h1 + f[n][i] * (h2 * h2 - h1 * h1) - f[nm][i] * h2 * h2) / (f[0][i] * h1 * h2 * (h1 + h2));\n\t\t}\n\t\tu[0] = f[n][0];\n\t\tg.push_back(u);\n\t}\n\n\treturn g;\n\n}\n\nauto filter(const std::vector<std::vector<double>> &f, double omega, double Pc, double Ps) {\n\tstd::vector<std::vector<double>> g;\n\tstd::vector<double> u(f[0].size());\n\n\tconst auto tmin = f[0][0];\n\tconst auto tmax = f[f.size() - 1][0];\n\tconst auto P = 2.0 * M_PI / omega;\n\tdouble rt = tmin / P;\n\tPc *= P;\n\tPs *= P;\n\tfor (int n = 1; n < f.size() - 1; n++) {\n\t\tdouble t0 = f[n][0];\n\t\tdouble dt;\n\t\tdouble weight = 0.0;\n\n\t\tif (Pc / 2.0 + tmin < t0 && t0 < tmax - Pc / 2.0) {\n\t\t\tstd::fill(u.begin(), u.end(), 0.0);\n\t\t\tfor (int m = 1; m < f.size() - 1; m++) {\n\t\t\t\tdouble t = f[m][0];\n\t\t\t\tif (t0 - Pc / 2.0 < t && t < t0 + Pc / 2.0) {\n\t\t\t\t\tdt = (f[m + 1][0] - f[m - 1][0]) / 2.0;\n\t\t\t\t\tconst auto h1 = f[m][0] - f[m - 1][0];\n\t\t\t\t\tconst auto h2 = f[m + 1][0] - f[m][0];\n\t\t\t\t\tconst auto w1 = (h1 + h2) * (2 * h1 - h2) / h1 / 6.0;\n\t\t\t\t\tconst auto w2 = std::pow(h1 + h2, 3) / h2 / h1 / 6.0;\n\t\t\t\t\tconst auto w3 = (h1 + h2) * (2 * h2 - h1) / h2 / 6.0;\n\t\t\t\t\tdouble y1 = band_filter(f[m - 1][0] - t0, Ps, Pc);\n\t\t\t\t\tdouble y2 = band_filter(f[m][0] - t0, Ps, Pc);\n\t\t\t\t\tdouble y3 = band_filter(f[m + 1][0] - t0, Ps, Pc);\n\t\t\t\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\t\t\t\tu[i] += w1 * f[m - 1][i] * y1 * dt;\n\t\t\t\t\t\tu[i] += w2 * f[m][i] * y2 * dt;\n\t\t\t\t\t\tu[i] += w3 * f[m + 1][i] * y3 * dt;\n\t\t\t\t\t}\n\t\t\t\t\tweight += w1 * y1 * dt;\n\t\t\t\t\tweight += w2 * y2 * dt;\n\t\t\t\t\tweight += w3 * y3 * dt;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\t\tu[i] /= weight;\n\t\t\t}\n\t\t\tu[0] = rt;\n\t\t\tg.push_back(u);\n\t\t}\n\t\tdt = (f[n + 1][0] - f[n - 1][0]) / 2.0;\n\t\trt += dt / P;\n\t}\n\treturn g;\n}\n\nstruct options {\n\tdouble pmin;\n\tdouble pmax;\n\tbool help;\n\tbool normalize;\n\tstd::string input;\n\n\tint read_options(int argc, char *argv[]) {\n\t\tnamespace po = boost::program_options;\n\n\n\t\tpo::options_description command_opts(\"options\");\n\n\t\tcommand_opts.add_options() //\n\t\t(\"input\", po::value<std::string>(&input)->default_value(\"binary.dat\"), \"input filename\")           //\n\t\t(\"pmin\", po::value<double>(&pmin)->default_value(1.25), \"minimum period to allow through filter\")           //\n\t\t(\"pmax\", po::value<double>(&pmax)->default_value(5), \"period where filter allows 100%\")           //\n\t\t(\"normalize\", po::value<bool>(&normalize)->default_value(true), \"normalize averages to t=0 value\")           //\n\t\t(\"help\", po::value<bool>(&help)->default_value(false), \"show the help page\")           //\n\t\t\t\t;\n\t\tboost::program_options::variables_map vm;\n\t\tpo::store(po::parse_command_line(argc, argv, command_opts), vm);\n\t\tpo::notify(vm);\n\n\t\tif (help) {\n\t\t\tstd::cout << command_opts << \"\\n\";\n\t\t\treturn -1;\n\t\t}\n\t\tFILE *fp = fopen(input.c_str(), \"rb\");\n\t\tif (fp == NULL) {\n\t\t\tprint(\"Unable to open %s\\n\", input.c_str());\n\t\t\treturn -1;\n\t\t} else {\n\t\t\tfclose(fp);\n\t\t}\n\n\t\treturn 0;\n\t}\n};\nint main(int argc, char *argv[]) {\n\toptions opts;\n\tif (opts.read_options(argc, argv) == 0) {\n\n\t\tFILE *fp = fopen(opts.input.c_str(), \"rt\");\n\t\tstatic char buffer[100000];\n\t\tstd::map<double, std::vector<double>> values;\n\n\t\twhile (!feof(fp)) {\n\t\t\tconst char* b = fgets(buffer, 100000, fp);\n\t\t\tbool done = false;\n\t\t\tchar *ptr = buffer;\n\t\t\tdouble t;\n\t\t\tint col = 0;\n\t\t\tstd::vector<double> these_values;\n\t\t\tdo {\n\t\t\t\twhile (isspace(*ptr)) {\n\t\t\t\t\tif (*ptr == '\\n') {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t\tif (!done) {\n\t\t\t\t\tdouble number = atof(ptr);\n\t\t\t\t\tif (col == 0) {\n\t\t\t\t\t\tt = number;\n\t\t\t\t\t}\n\t\t\t\t\tthese_values.push_back(number);\n\t\t\t\t\tcol++;\n\t\t\t\t}\n\t\t\t\twhile (!isspace(*ptr)) {\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t} while (!done);\n\t\t\tif (values.find(t) == values.end()) {\n\t\t\t\tvalues.insert(std::make_pair(t, std::move(these_values)));\n\t\t\t}\n\t\t}\n\n\t\tstd::vector<std::vector<double>> v1;\n\t\tfor (auto &v : values) {\n\t\t\tv1.push_back(std::move(v.second));\n\t\t}\n\n\t\tauto Pc = 2.0 * opts.pmax * opts.pmin / (opts.pmax + opts.pmin);\n\t\tauto Ps = 4.0 * opts.pmax * opts.pmin / (opts.pmax - opts.pmin);\n\t\tprint(\"sinc period      = %e\\n\", Pc);\n\t\tprint(\"Blackmann period = %e\\n\", Ps);\n\t\tconst auto P = 2.0 * M_PI / v1[0][2];\n\n\t\tprint(\"Window is +/- %.12e orbits\\n\", Pc / 2.0);\n\n\t\tauto v2 = filter(v1, v1[0][2], Pc, Ps);\n\t\tif (v2.size() == 0) {\n\t\t\tprint(\"Not enough data to produce output\\n\");\n\t\t} else {\n\t\t\tif (opts.normalize) {\n\t\t\t\tfor (auto &line : v2) {\n\t\t\t\t\tfor (int i = 1; i < line.size(); i++) {\n\t\t\t\t\t\tline[i] /= v1[0][i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst auto v4 = derivative(v1, v1[0][2]);\n\t\t\tconst auto v3 = filter(v4, v1[0][2], Pc, Ps);\n\t\t\tFILE *fp1 = fopen(\"avg.dat\", \"wt\");\n\t\t\tFILE *fp2 = fopen(\"drv.dat\", \"wt\");\n\t\t\tfor (const auto &i : v2) {\n\t\t\t\tfor (const auto &j : i) {\n\t\t\t\t\tfprintf(fp1, \" %.12e \", j);\n\t\t\t\t}\n\t\t\t\tfprintf(fp1, \"\\n\");\n\t\t\t}\n\t\t\tfor (const auto &i : v3) {\n\t\t\t\tfor (const auto &j : i) {\n\t\t\t\t\tfprintf(fp2, \" %.12e \", j);\n\t\t\t\t}\n\t\t\t\tfprintf(fp2, \"\\n\");\n\t\t\t}\n\t\t\tfclose(fp1);\n\t\t\tfclose(fp2);\n\t\t\tfclose(fp);\n\t\t}\n\n\t\toutput_spectrogram(Ps, Pc);\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "2094bef1468bfbf89905fbe89fe8de8908a0a1f7", "size": 6694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/bfilter/bfilter.cpp", "max_stars_repo_name": "srinivasyadav18/octotiger", "max_stars_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T22:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:07:36.000Z", "max_issues_repo_path": "tools/bfilter/bfilter.cpp", "max_issues_repo_name": "srinivasyadav18/octotiger", "max_issues_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2016-11-17T21:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T21:40:04.000Z", "max_forks_repo_path": "tools/bfilter/bfilter.cpp", "max_forks_repo_name": "srinivasyadav18/octotiger", "max_forks_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T18:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T12:52:37.000Z", "avg_line_length": 26.1484375, "max_line_length": 122, "alphanum_fraction": 0.5261428145, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6534588141699512}}
{"text": "// Copyright (c) 2021 fortiss GmbH\n//\n// Authors: Klemens Esterle and Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n#ifndef MIQP_COMMON_MATH_HPP_\n#define MIQP_COMMON_MATH_HPP_\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace miqp {\nnamespace common {\nnamespace math {\n\ninline void WrapRadiantTo2Pi(double& x) {\n  x = fmod(x, 2 * boost::math::constants::pi<double>());\n  if (x < 0) {\n    x += 2 * boost::math::constants::pi<double>();\n  }\n  assert(x >= 0);\n  assert(x <= 2 * boost::math::constants::pi<double>());\n}\n\ninline void SwapIfNeeded(float& maxval, float& minval) {\n  if (maxval < minval) {\n    float tmp = maxval;\n    maxval = minval;\n    minval = tmp;\n  }\n}\n\ninline double InterpolateWithBounds(const double x0, const double y0,\n                                    const double x1, const double y1,\n                                    const double xInterp) {\n  double yInterp;\n  if (xInterp > x1) {\n    yInterp = y1;\n  } else if (xInterp < x0) {\n    yInterp = y0;\n  } else {\n    yInterp = (y1 - y0) / (x1 - x0) * (xInterp - x0) + y0;\n  }\n  return yInterp;\n};\n\n}  // namespace math\n}  // namespace common\n}  // namespace miqp\n\n#endif  // MIQP_COMMON_MATH_HPP_\n", "meta": {"hexsha": "9d88d82bea2b46ef0cbedfc830f76d11f0d4de27", "size": 1269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/math/math.hpp", "max_stars_repo_name": "bark-simulator/planner-miqp", "max_stars_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T08:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:33:02.000Z", "max_issues_repo_path": "common/math/math.hpp", "max_issues_repo_name": "bark-simulator/planner-miqp", "max_issues_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/math/math.hpp", "max_forks_repo_name": "bark-simulator/planner-miqp", "max_forks_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_forks_repo_licenses": ["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.9433962264, "max_line_length": 69, "alphanum_fraction": 0.6170212766, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.653428454728821}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n\n  auto lapl_mat = lf::uscalfe::LinearFELaplaceElementMatrix().Eval(cell);\n\n  if (ref_el == lf::base::RefElType::kQuad) {\n    Eigen::Matrix<double, 4, 4> elem_mat;\n    elem_mat << 4,2,1,2,\n                2,4,2,1,\n                1,2,4,2,\n                2,1,2,4;\n\n    double x0 = vertices.row(0).minCoeff();\n    double x1 = vertices.row(0).maxCoeff();\n    double y0 = vertices.row(1).minCoeff();\n    double y1 = vertices.row(1).maxCoeff();\n\n    double area = (x1 - x0) * (y1 - y0);\n\n    return area * elem_mat / 36. + lapl_mat;\n  }\n\n  else if(ref_el == lf::base::RefElType::kTria) {\n      Eigen::Matrix<double, 4, 4> elem_mat;\n      elem_mat << 2,1,1,0,\n                  1,2,1,0,\n                  1,1,2,0,\n                  0,0,0,0;\n\n      Eigen::Matrix2d side_lengths;\n\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 = 0.5 * side_lengths.determinant();\n\n      return area * elem_mat / 12. + lapl_mat;\n\n  }\n  else {\n    assert(0 && \"unsupported cell type\");\n  }\n\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "0efd010f349537dbb314719d735a243b64b136a8", "size": 2035, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.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/mylinearfeelementmatrix.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/mylinearfeelementmatrix.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": 26.7763157895, "max_line_length": 73, "alphanum_fraction": 0.6319410319, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6534284491146021}}
{"text": "//\n// Created by TAADEJOM on 15.05.2021.\n//\n\n#include \"DataSet.hpp\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/**\n * Concatenates two matrices vertically. A at the top and B at the bottom\n */\nMatrixXd vConcat(const MatrixXd& A, const MatrixXd& B) {\n    MatrixXd D(A.rows()+B.rows(), A.cols()); // <-- D(A.rows() + B.rows(), ...)\n    D << A, B;\n    return D;\n}\n\n/**\n * See: https://gist.github.com/gocarlos/c91237b02c120c6319612e42fa196d77\n * Note: matrix index starts at 1 in matlab and at 0 in eigen -> never forget -1!\n */\nQVector<double> DataSet::regression(int degree) const {\n    QSharedPointer<QCPGraphDataContainer> data = graph->data();\n    int m = data->size(); // rows\n    int n = degree; // columns\n    // xPoints = data(:,1);  %x -> A\n    // yPoints = data(:,2); %y -> b\n    MatrixXd xPoints(m, 1); // n rows, 1 column\n    MatrixXd yPoints(m, 1); // n rows, 1 column\n    for (int i = 0; i < m; ++i) {\n        xPoints(i, 0) = data->at(i)->key;\n        yPoints(i, 0) = data->at(i)->value;\n    }\n\n    // x0 = ones(m,1).*80.3e3;\n    MatrixXd x1 = xPoints;\n    MatrixXd x0 = Eigen::MatrixXd::Ones(m, 1) * 80300;\n\n    MatrixXd z1 = (x1 - x0).array() / 50;\n\n    // Set up vector A\n    MatrixXd A(m, n);\n    for (int i = 1; i <= n; ++i) {\n        if (i == n) {\n            // A(1:m, degree) = ones(m,1);\n            A.col(i - 1) = Eigen::MatrixXd::Ones(m, 1);\n        } else {\n            // A(1:m, degree) = xPoints.^(n - degree);\n            A.col(i - 1) = xPoints.array().pow(n - i);\n        }\n    }\n\n    MatrixXd Im = Eigen::MatrixXd::Identity(m, m); // m*m identity matrix\n\n    // QR-Zerlegung von A\n    MatrixXd R = A;\n    MatrixXd Q = Im;\n    for (int k = 1; k <= n; ++k) {\n        MatrixXd x = R.col(k - 1).bottomRows(R.rows() - k + 1); // we wanna show R.rows - k rows from the bottom // fixme: ErrorRowIndexOutOfBounds with 5 data points and degree 10\n\n        // x is a matrix with 1 column and however many rows\n        double lambda = x.coeff(k - 1, 0) < 0 ? x.norm() : -x.norm();\n\n        MatrixXd e = Im.col(k - 1).bottomRows(R.rows() - k + 1);\n        MatrixXd v = (x - lambda * e) / (x - lambda * e).norm(); // use normalize()\n        MatrixXd z = Eigen::MatrixXd::Zero(k - 1, 1);\n\n        // H = eye(m)-2.*[z;v]*[z;v]';\n        MatrixXd H = Eigen::MatrixXd::Identity(m, m) - (2 * (vConcat(z, v) * vConcat(z, v).transpose()));\n\n        Q = Q * H; // mXm * mXm matrix mul => VERY SLOW\n        R = H * R;\n    }\n    // R\u00fcckw\u00e4rtseinsetzen\n    MatrixXd y = Q.transpose() * yPoints;\n\n    MatrixXd x = Eigen::MatrixXd::Zero(1, n);\n    // x(n) = y(n)/R(n,n);\n    x.coeffRef(0, n - 1) = y.coeff(n  - 1, 0) / R.coeff(n - 1, n - 1);\n\n    for (int i = (n - 1); i >= 1; --i) {\n        double s = 0;\n        for (int j = i + 1; j <= n; ++j) {\n            // s = s + x(j)*R(i,j);\n            s += x.coeff(0, j - 1) * R.coeff(i - 1, j - 1);\n        }\n        // x(i) = (y(i) - s)/R(i,i);\n        x.coeffRef(0, i - 1) = (y.coeff(i - 1, 0) - s) / R.coeff(i - 1, i - 1);\n    }\n\n    return QVector<double>(x.data(), x.data() + x.rows() * x.cols());\n}\n\n/**\n * Makes a function string out of a list of coeffs\n */\nQString DataSet::getFunctionString(const QVector<double>& coeffs) {\n    QString regression = \"\";\n    for (int i = 0; i < coeffs.size(); ++i) {\n        regression += QString(\"%1*x^%2+\").arg(QString::number(coeffs.at(i), 'E', 16)).arg(coeffs.length() - i - 1);\n    }\n    regression.truncate(regression.lastIndexOf('+'));\n    return regression;\n}\n\nQDataStream &operator<<(QDataStream &out, const DataSet &dataSet) {\n    out << dataSet.displayName << dataSet.functionString << dataSet.color << quint32(dataSet.graphWidth) << quint32(dataSet.pointDensity);\n    return out;\n}\n\nQDataStream &operator>>(QDataStream &in, DataSet &dataSet) {\n    QString displayName;\n    QString functionString;\n    QColor color;\n    quint32 graphWidth;\n    quint32 pointDensity;\n    in >> displayName >> functionString >> color >> graphWidth >> pointDensity;\n    dataSet.displayName = displayName;\n    dataSet.functionString = functionString;\n    dataSet.color = color;\n    dataSet.graphWidth = graphWidth;\n    dataSet.pointDensity = pointDensity;\n    return in;\n}", "meta": {"hexsha": "99a54b9b1fdd15738fdc33b8ff2baf0eeca0f7fd", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QDataVis/Sources/DataSet.cpp", "max_stars_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_stars_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T21:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T03:39:19.000Z", "max_issues_repo_path": "QDataVis/Sources/DataSet.cpp", "max_issues_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_issues_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T22:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T11:33:06.000Z", "max_forks_repo_path": "QDataVis/Sources/DataSet.cpp", "max_forks_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_forks_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-09T20:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T20:51:29.000Z", "avg_line_length": 33.248, "max_line_length": 180, "alphanum_fraction": 0.5543792108, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686652586891}}
{"text": "#pragma once\r\n\r\n\r\n#include <Discregrid/common.hpp>\r\n#include <Eigen/Dense>\r\n\r\nclass CubicKernel\r\n{\r\npublic:\r\n\t Discregrid::Real getRadius() { return m_radius; }\r\n\t void setRadius(Discregrid::Real val)\r\n\t{\r\n\t\tm_radius = val;\r\n\t\tconst Discregrid::Real pi = static_cast<Discregrid::Real>(M_PI);\r\n\r\n\t\tconst Discregrid::Real h3 = m_radius*m_radius*m_radius;\r\n\t\tm_k = 8.0 / (pi*h3);\r\n\t\tm_l = 48.0 / (pi*h3);\r\n\t\tm_W_zero = W(Discregrid::Vector3r::Zero());\r\n\t}\r\n\r\npublic:\r\n\tDiscregrid::Real W(Discregrid::Vector3r const& r)\r\n\t{\r\n\t\tDiscregrid::Real res = 0.0;\r\n\t\tconst Discregrid::Real rl = r.norm();\r\n\t\tconst Discregrid::Real q = rl/m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (q <= 0.5)\r\n\t\t\t{\r\n\t\t\t\tconst Discregrid::Real q2 = q*q;\r\n\t\t\t\tconst Discregrid::Real q3 = q2*q;\r\n\t\t\t\tres = m_k * (6.0*q3-6.0*q2+1.0);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tauto _1mq = 1.0 - q;\r\n\t\t\t\tres = m_k * (2.0*_1mq*_1mq*_1mq);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\tDiscregrid::Vector3r gradW(const Discregrid::Vector3r &r)\r\n\t{\r\n\t\tusing namespace Eigen;\r\n\t\tDiscregrid::Vector3r res;\r\n\t\tconst Discregrid::Real rl = r.norm();\r\n\t\tconst Discregrid::Real q = rl / m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (rl > 1.0e-6)\r\n\t\t\t{\r\n\t\t\t\tconst Discregrid::Vector3r gradq = r * ((Discregrid::Real) 1.0 / (rl*m_radius));\r\n\t\t\t\tif (q <= 0.5)\r\n\t\t\t\t{\r\n\t\t\t\t\tres = m_l*q*((Discregrid::Real) 3.0*q - (Discregrid::Real) 2.0)*gradq;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tconst Discregrid::Real factor = 1.0 - q;\r\n\t\t\t\t\tres = m_l*(-factor*factor)*gradq;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t\tres.setZero();\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tDiscregrid::Real W_zero()\r\n\t{\r\n\t\treturn m_W_zero;\r\n\t}\r\n\r\nprivate:\r\n\tDiscregrid::Real m_radius;\r\n\tDiscregrid::Real m_k;\r\n\tDiscregrid::Real m_l;\r\n\tDiscregrid::Real m_W_zero;\r\n};\r\n", "meta": {"hexsha": "be8520565e3cc5bfd20e55bd9483f33a797026bc", "size": 1715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_stars_repo_name": "kennychufk/Discregrid", "max_stars_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_issues_repo_name": "kennychufk/Discregrid", "max_issues_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_forks_repo_name": "kennychufk/Discregrid", "max_forks_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 85, "alphanum_fraction": 0.5790087464, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686652586891}}
{"text": "#include \"IntrinsicGeometry.h\"\n#include \"MeshConnectivity.h\"\n#include <Eigen/Dense>\n\nIntrinsicGeometry::IntrinsicGeometry(const MeshConnectivity &mesh, const std::vector<Eigen::Matrix2d> &abars) : abars(abars)\n{\n    int nedges = mesh.nEdges();\n    int nfaces = mesh.nFaces();\n\n    Js.resize(2 * nfaces, 2);\n    for (int i = 0; i < nfaces; i++)\n    {\n        Eigen::Matrix2d Jeuclid;\n        Jeuclid << 0, -1,\n            1, 0;\n        Js.block<2, 2>(2 * i, 0) = std::sqrt(abars[i].determinant()) * abars[i].inverse() * Jeuclid;\n    }\n\n    Ts.resize(2 * nedges, 4);\n    Ts.setZero();\n    for (int i = 0; i < nedges; i++)\n    {\n        int face1 = mesh.edgeFace(i, 0);\n        int face2 = mesh.edgeFace(i, 1);\n        if (face1 == -1 || face2 == -1)\n            continue;\n\n        int vert1 = mesh.edgeVertex(i, 0);\n        int vert2 = mesh.edgeVertex(i, 1);\n\n        // write edge vert1->vert2 in barycentric coordinates on each face\n        Eigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n        Eigen::Vector2d face1e(0, 0);\n        Eigen::Vector2d face2e(0, 0);\n        for (int j = 0; j < 3; j++)\n        {\n            if (vert1 == mesh.faceVertex(face1, j))\n                face1e -= barys[j];\n            else if (vert2 == mesh.faceVertex(face1, j))\n                face1e += barys[j];\n            if (vert1 == mesh.faceVertex(face2, j))\n                face2e -= barys[j];\n            else if (vert2 == mesh.faceVertex(face2, j))\n                face2e += barys[j];\n        }\n\n        Eigen::Vector2d face1eperp = Js.block<2, 2>(2 * face1, 0) * face1e;\n        Eigen::Vector2d face2eperp = Js.block<2, 2>(2 * face2, 0) * face2e;\n        Eigen::Matrix2d face1basis;\n        face1basis.col(0) = face1e;\n        face1basis.col(1) = face1eperp;\n        Eigen::Matrix2d face2basis;\n        face2basis.col(0) = face2e;\n        face2basis.col(1) = face2eperp;\n        Ts.block<2, 2>(2 * i, 0) = face2basis * face1basis.inverse();\n        Ts.block<2, 2>(2 * i, 2) = face1basis * face2basis.inverse();\n    }\n}\n", "meta": {"hexsha": "ba587fabf838b76f77394f7ac435ecc453bd51cd", "size": 2012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IntrinsicGeometry.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IntrinsicGeometry.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IntrinsicGeometry.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["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.1016949153, "max_line_length": 124, "alphanum_fraction": 0.5347912525, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6533686649790916}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <array>\n\nusing namespace Eigen;\nusing namespace std;\n\n#ifndef PLANE3D_HPP\n#define PLANE3D_HPP\n\nclass Plane3d {\n    int id;\n    Vector3d axisX;\n    Vector3d axisY;\n    Vector3d normal;\n    Vector3d target;\n    Matrix3d inverse;\n  public:\n    Plane3d(int _id, double alpha, double theta, Vector3d _target);\n    bool intersectsEdge(Vector3d v0, Vector3d v1);\n    bool containsPoint(Vector3d v0);\n    array<double, 3> findIntersection(Vector3d v0, Vector3d v1);\n    int Id();\n    Vector2d Rotate(array<double, 3> _vec);\n    Vector3d Get3dPoint(Vector3d pt2d);\n};\n\nclass Shape3d {\n    unsigned long int tetId;\n    vector<array<double, 3>> vertices;\n    int label;\n    //tissueId\n    //these should probably all be doubles?\n    double weight;\n  public:\n    Shape3d(unsigned long int _tetId, vector<array<double, 3>> _vertices, double _weight, int _label);\n    unsigned long int TetId();\n    vector<array<double, 3>> Vertices();\n    int Label();\n    double Weight();\n};\n\n#endif\n\n", "meta": {"hexsha": "5132914dee07b0defa16f772d8f3ca90df27239f", "size": 1022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/plane3d.hpp", "max_stars_repo_name": "myociss/pathfinder", "max_stars_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_stars_repo_licenses": ["MIT"], "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/plane3d.hpp", "max_issues_repo_name": "myociss/pathfinder", "max_issues_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_issues_repo_licenses": ["MIT"], "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/plane3d.hpp", "max_forks_repo_name": "myociss/pathfinder", "max_forks_repo_head_hexsha": "4c0b14e074cfc8f0e41836abc056989f2d465c12", "max_forks_repo_licenses": ["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.7111111111, "max_line_length": 102, "alphanum_fraction": 0.6878669276, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6533537619009115}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd A = MatrixXd::Random(6,6);\ncout << \"Here is a random 6x6 matrix, A:\" << endl << A << endl << endl;\n\nRealSchur<MatrixXd> schur(A);\ncout << \"The orthogonal matrix U is:\" << endl << schur.matrixU() << endl;\ncout << \"The quasi-triangular matrix T is:\" << endl << schur.matrixT() << endl << endl;\n\nMatrixXd U = schur.matrixU();\nMatrixXd T = schur.matrixT();\ncout << \"U * T * U^T = \" << endl << U * T * U.transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "29dc5cddb394e399aeb8b6a26f750d4052d14b9a", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_RealSchur_RealSchur_MatrixType.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 29.4516129032, "max_line_length": 224, "alphanum_fraction": 0.6484118291, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6533537524881569}}
{"text": "/*\nA \"C\" interface to libigl's harmonic coordinates.\n*/\n\n#include <cassert>\n\n#define IGL_HEADER_ONLY\n#include <igl/boundary_conditions.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/harmonic.h>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\n#define kVertexDimension 3\n\nextern \"C\"\n{\n\ntypedef double real_t;\ntypedef int index_t;\n\n// Returns 0 for success, anything else is an error.\nint harmonic(\n    /// Input Parameters\n    // 'vertices' is a pointer to num_vertices*kVertexDimension floating point values,\n    // packed: x0, y0, z0, x1, y1, z1, ...\n    // In other words, a num_vertices-by-kVertexDimension matrix packed row-major.\n    int num_vertices, real_t* vertices,\n    // 'faces' is a pointer to num_faces*3 integers,\n    // where each face is three vertex indices: f0.v0, f0.v1, f0.v2, f1.v0, f1.v1, f1.v2, ...\n    // Face i's vertices are: vertices[ faces[3*i]*2 ], vertices[ faces[3*i+1]*2 ], vertices[ faces[3*i+2]*2 ]\n    // In other words, a num_faces-by-3 matrix packed row-major.\n    int num_faces, index_t* faces,\n    // 'boundary_indices' is a pointer to num_boundary_vertices integers,\n    // where each element \"i\" in boundary_indices references the vertex whose data\n    // is located at vertices[ boundary_indices[i]*kVertexDimension ].\n    int num_boundary_indices, index_t* boundary_indices,\n    // Power of the harmonic operation (1 is harmonic, 2 is bi-harmonic, etc ),\n    int power,\n    \n    /// Output Parameters\n    // 'Wout' is a pointer to num_vertices*num_boundary_indices values.\n    // Upon return, W will be filled with each vertex in 'num_vertices' weight for\n    // each boundary vertex in 'boundary_indices'.\n    // The data layout is that all 'num_boundary_indices' weights for vertex 0\n    // appear before all 'num_boundary_indices' weights for vertex 1, and so on.\n    // In other words, a num_vertices-by-num_boundary_indices matrix packed row-major.\n    real_t* Wout\n    )\n{\n    using namespace std;\n    using namespace igl;\n    using namespace Eigen;\n    \n    assert( num_vertices > 0 );\n    assert( vertices );\n    assert( num_faces > 0 );\n    assert( faces );\n    assert( num_boundary_indices > 0 );\n    assert( boundary_indices );\n    \n    assert( Wout );\n    \n    // #V by 2 list of mesh vertex positions\n    // Make this an Eigen::map from 'vertices'\n    MatrixXd V = Eigen::Map< Eigen::Matrix< real_t, Eigen::Dynamic, kVertexDimension, Eigen::RowMajor > >( vertices, num_vertices, kVertexDimension );\n    // #F by 3 list of triangle indices\n    // Make this an Eigen::map from 'faces'\n    MatrixXi F = Eigen::Map< Eigen::Matrix< index_t, Eigen::Dynamic, 3, Eigen::RowMajor > >( faces, num_faces, 3 );\n    \n#define CALL_BOUNDARY_CONDITIONS 0\n#if !CALL_BOUNDARY_CONDITIONS\n    // Make this an Eigen::map from boundary_indices.\n    VectorXi b = Eigen::Map< Eigen::Matrix< index_t, Eigen::Dynamic, 1 > >( boundary_indices, num_boundary_indices, 1 );\n    MatrixXd bc;\n    bc.setIdentity( num_boundary_indices, num_boundary_indices );\n    \n#else\n    \n    // Alec: If your mesh is (V,F) and your control cage is C then first build a #C by 2 MatrixXi of \u201cedge indices\u201d for your control cage. Easy, just:\n    MatrixXd C(num_boundary_indices,kVertexDimension);\n    MatrixXi CE(num_boundary_indices,2);\n    VectorXi P(num_boundary_indices);\n    for( int c = 0; c < num_boundary_indices; ++c )\n    {\n      C.row(c) = V.row( boundary_indices[c] );\n      P(c) = c;\n      CE(c,0) = c;\n      CE(c,1) = (c+1)%C.rows();\n    }\n    // We don't use this, but we need an empty one to pass to boundary_conditions().\n    MatrixXi BE;\n    \n    // Compute boundary conditions (aka fixed value constraints)\n    // List of boundary indices (aka fixed value indices into VV)\n    VectorXi b;\n    // List of boundary conditions of each weight function\n    MatrixXd bc;\n    if(!boundary_conditions(V,F,C,P,BE,CE,b,bc))\n    {\n        return 1;\n    }\n#endif\n    \n    // compute harmonic coordinates\n    // Weights matrix\n    MatrixXd W;\n    if(!harmonic(V,F,b,bc,power,W))\n    {\n        return 2;\n    }\n    \n    // Normalize weights.\n    normalize_row_sums(W,W);\n    \n    // Save output\n    // Copy W to Wout.\n    Eigen::Map< Eigen::Matrix< real_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > >( Wout, num_vertices, num_boundary_indices ) = W;\n    \n    return 0;\n}\n\n}\n", "meta": {"hexsha": "d151028d3fbdd4a2afdb81d30f1c49eef951288d", "size": 4297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bbw_wrapper/harmonic.cpp", "max_stars_repo_name": "songrun/VectorSkinning", "max_stars_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T20:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T17:48:05.000Z", "max_issues_repo_path": "src/bbw_wrapper/harmonic.cpp", "max_issues_repo_name": "songrun/VectorSkinning", "max_issues_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "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/bbw_wrapper/harmonic.cpp", "max_forks_repo_name": "songrun/VectorSkinning", "max_forks_repo_head_hexsha": "a19dff78215b51d824adcd39c7dcdf8dc78ec617", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T17:52:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T11:01:56.000Z", "avg_line_length": 34.1031746032, "max_line_length": 150, "alphanum_fraction": 0.6688387247, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6533537504294838}}
{"text": "#include <blitz/array.h>\n#include <blitz/array/stencil-et.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nvoid setupInitialConditions(Array<float,3>& P1, Array<float,3>& P2,\n    Array<float,3>& P3, Array<float,3>& c, int N);\n\nBZ_DECLARE_STENCIL4(acoustic3D, P1, P2, P3, c)\n    P3 = 2 * P2 + c * Laplacian3D_stencilop(P2) - P1;\nBZ_END_STENCIL\n\nfloat acoustic3D_BlitzStencil(int N, int niters)\n{\n    Array<float,3> P1, P2, P3, c;\n    allocateArrays(shape(N,N,N), P1, P2, P3, c);\n\n    setupInitialConditions(P1, P2, P3, c, N);\n\n    for (int iter=0; iter < niters; ++iter)\n    {\n        applyStencil(acoustic3D(), P1, P2, P3, c);\n        cycleArrays(P1, P2, P3);\n    }\n\n    return P1(N/2,N/2,N/2);\n}\n\n", "meta": {"hexsha": "6fe464442867b6f0ddd3d058ecaf895879906d98", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/acou3db4.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/benchmarks/acou3db4.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/benchmarks/acou3db4.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": 23.4482758621, "max_line_length": 67, "alphanum_fraction": 0.6367647059, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6533537454285903}}
{"text": "#include \"space_vector_modulation.h\"\n#include \"global_debug.h\"\n#include \"util/clarke_transform.h\"\n#include \"util/conversions.h\"\n#include \"util/math_constants.h\"\n#include <Eigen/Dense>\n\nconst std::array<std::complex<Scalar>, 6> kSvmVectors = []() {\n    std::array<std::complex<Scalar>, 6> result;\n    result[0] = {1, 0};\n    for (int i = 0; i < 6; ++i) {\n        result[i] = {std::cos(i * 2 * kPI / 6), std::sin(i * 2 * kPI / 6)};\n    }\n    return result;\n}();\n\nint get_sector(const std::complex<Scalar>& voltage_ab) {\n    const std::complex<Scalar> rot_60_deg = std::conj(kSvmVectors[1]);\n\n    std::complex<Scalar> curr = voltage_ab;\n    std::complex<Scalar> next = voltage_ab * rot_60_deg;\n    int sector;\n    for (sector = 0; sector < 5; ++sector) {\n        if (curr.imag() >= 0 && next.imag() < 0) {\n            // found it\n            break;\n        }\n        // rotate\n        curr = next;\n        next *= rot_60_deg;\n    }\n\n    return sector;\n}\n\nstd::array<Scalar, 3> get_pwm_duties(const Scalar bus_voltage,\n                                     const std::complex<Scalar>& voltage_ab) {\n    const int sector_x = get_sector(voltage_ab);\n    const int sector_y = (sector_x + 1) % 6;\n\n    const std::complex<Scalar> boundary_x =\n        kSvmVectors[sector_x] * kClarkeScale * bus_voltage;\n    const std::complex<Scalar> boundary_y =\n        kSvmVectors[sector_y] * kClarkeScale * bus_voltage;\n\n    Eigen::Matrix<Scalar, 2, 2> boundaries;\n    boundaries <<\n        // clang-format off\n\tboundary_x.real(), boundary_y.real(),\n\tboundary_x.imag(), boundary_y.imag()\n        // clang-format on\n        ;\n    Eigen::Matrix<Scalar, 2, 1> v_ab;\n    v_ab << voltage_ab.real(), voltage_ab.imag();\n\n    Eigen::Matrix<Scalar, 2, 1> coeffs = boundaries.inverse() * v_ab;\n    Scalar cx = coeffs(0);\n    Scalar cy = coeffs(1);\n    Scalar cx_p_cy = cx + cy;\n    Scalar c0 = 1.0 - cx_p_cy;\n    if (cx_p_cy > 1) {\n        c0 = 0;\n        cx /= cx_p_cy;\n        cy /= cx_p_cy;\n    }\n\n    const auto& gx = kSvmStates[sector_x];\n    const auto& gy = kSvmStates[sector_y];\n\n    std::array<Scalar, 3> duties;\n    for (int i = 0; i < 3; ++i) {\n        duties[i] = c0 / 2 + gx[i] * cx + gy[i] * cy;\n    }\n    return duties;\n}\n\nstd::complex<Scalar> get_avg_voltage_ab(const Scalar bus_voltage,\n                                        const std::array<Scalar, 3>& duties) {\n    // optimal sort 3 elements\n    int first_gate_on = 0;\n    int second_gate_on = 1;\n    int third_gate_on = 2;\n    if (duties[second_gate_on] > duties[first_gate_on]) {\n        std::swap(first_gate_on, second_gate_on);\n    }\n    if (duties[third_gate_on] > duties[second_gate_on]) {\n        std::swap(third_gate_on, second_gate_on);\n    }\n    // after these two swaps, duties[third_gate_on] is minimal\n    if (duties[second_gate_on] > duties[first_gate_on]) {\n        std::swap(first_gate_on, second_gate_on);\n    }\n    // duties[first_gate_on] is maximum\n\n    Eigen::Matrix<Scalar, 3, 1> pole_voltages_x =\n        Eigen::Matrix<Scalar, 3, 1>::Zero();\n    pole_voltages_x(first_gate_on) = bus_voltage;\n\n    Eigen::Matrix<Scalar, 3, 1> pole_voltages_y = pole_voltages_x;\n    pole_voltages_y(second_gate_on) = bus_voltage;\n\n    Eigen::Matrix<Scalar, 3, 1> pole_voltages_avg =\n        pole_voltages_x * (duties[first_gate_on] - duties[second_gate_on]) +\n        pole_voltages_y * (duties[second_gate_on] - duties[third_gate_on]);\n\n    return to_complex<Scalar>(kClarkeTransform2x3 * pole_voltages_avg);\n}\n", "meta": {"hexsha": "839f37b0fed0bf78c66cd92077f031b56a2c12d4", "size": 3454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "controls/space_vector_modulation.cpp", "max_stars_repo_name": "mark-berobot/motor_sim", "max_stars_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T00:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T01:33:11.000Z", "max_issues_repo_path": "controls/space_vector_modulation.cpp", "max_issues_repo_name": "INKSureIT/motor_sim", "max_issues_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "controls/space_vector_modulation.cpp", "max_forks_repo_name": "INKSureIT/motor_sim", "max_forks_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T01:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:35:23.000Z", "avg_line_length": 31.9814814815, "max_line_length": 78, "alphanum_fraction": 0.6132020845, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6533537377799918}}
{"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_ROTATION2D_HPP\n#define RW_MATH_ROTATION2D_HPP\n\n/**\n * @file Rotation2D.hpp\n */\n\n#if !defined(SWIG)\n#include \"Vector2D.hpp\"\n\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    template< class T > class Rotation2DVector;\n\n    /** @addtogroup math */\n    /* @{*/\n\n#if !defined(SWIGJAVA)\n\n    /**\n     * @brief A 2x2 rotation matrix \\f$ \\mathbf{R}\\in SO(2) \\f$\n     *\n     * @f$\n     *  \\mathbf{R}=\n     *  \\left[\n     *  \\begin{array}{cc}\n     *  {}^A\\hat{X}_B & {}^A\\hat{Y}_B\n     *  \\end{array}\n     *  \\right]\n     *  =\n     *  \\left[\n     *  \\begin{array}{cc}\n     *  r_{11} & r_{12} \\\\\n     *  r_{21} & r_{22}\n     *  \\end{array}\n     *  \\right]\n     * @f$\n     */\n#endif\n    template< class T = double > class Rotation2D\n    {\n      public:\n        //! Value type.\n        typedef T value_type;\n\n        //! The type of the internal Boost matrix implementation.\n        typedef Eigen::Matrix< T, 2, 2 > EigenMatrix2x2;\n\n        /**\n           @brief A rotation matrix with uninitialized storage.\n         */\n        Rotation2D () {}\n\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Constructs an initialized 2x2 rotation matrix\n         *\n         * @param r11 \\f$ r_{11} \\f$\n         * @param r12 \\f$ r_{12} \\f$\n         * @param r21 \\f$ r_{21} \\f$\n         * @param r22 \\f$ r_{22} \\f$\n         *\n         * @f$\n         *  \\mathbf{R} =\n         *  \\left[\n         *  \\begin{array}{cc}\n         *  r_{11} & r_{12} \\\\\n         *  r_{21} & r_{22}\n         *  \\end{array}\n         *  \\right]\n         * @f$\n         */\n\n#endif\n        Rotation2D (T r11, T r12, T r21, T r22)\n        {\n            _m[0][0] = r11;\n            _m[0][1] = r12;\n            _m[1][0] = r21;\n            _m[1][1] = r22;\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs an initialized 2x2 rotation matrix\n         * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *   \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}}\n         *  \\end{array}\n         * \\right]\n         * @f$\n         *\n         * @param i @f$ \\robabx{a}{b}{\\mathbf{i}} @f$\n         * @param j @f$ \\robabx{a}{b}{\\mathbf{j}} @f$\n         */\n\n#endif\n        Rotation2D (const rw::math::Vector2D< T >& i, const rw::math::Vector2D< T >& j)\n        {\n            _m[0][0] = i[0];\n            _m[0][1] = j[0];\n            _m[1][0] = i[1];\n            _m[1][1] = j[1];\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs an initialized 2x2 rotation matrix\n         * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *   \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}}\n         *  \\end{array}\n         * \\right]\n         * @f$\n         *\n         * @param theta\n         */\n\n#endif\n        Rotation2D (const T theta)\n        {\n            _m[0][0] = cos (theta);\n            _m[0][1] = -sin (theta);\n            _m[1][0] = sin (theta);\n            _m[1][1] = cos (theta);\n        }\n\n        /**\n           @brief Construct an initialized 2x2 rotation matrix.\n\n           The second of column of the matrix is deduced from the first column.\n\n           @param i [in] The first column of the rotation matrix.\n        */\n        Rotation2D (const rw::math::Vector2D< T >& i)\n        {\n            _m[0][0] = i[0];\n            _m[0][1] = -i[1];\n            _m[1][0] = i[1];\n            _m[1][1] = i[0];\n        }\n\n        /**\n           @brief Construct a rotation matrix from an Eigen matrix.\n         */\n        template< class R > explicit Rotation2D (const EigenMatrix2x2& m)\n        {\n            _m[0][0] = m (0, 0);\n            _m[0][1] = m (0, 1);\n            _m[1][0] = m (1, 0);\n            _m[1][1] = m (1, 1);\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs a 2x2 rotation matrix set to identity\n         * @return a 2x2 identity rotation matrix\n         *\n         * @f$\n         * \\mathbf{R} =\n         * \\left[\n         * \\begin{array}{cc}\n         * 1 & 0\\\\\n         * 0 & 1\n         * \\end{array}\n         * \\right]\n         * @f$\n         */\n\n#endif\n        static const Rotation2D& identity ()\n        {\n            static Rotation2D id (1, 0, 0, 1);\n            return id;\n        }\n        \n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        T& operator() (size_t row, size_t column) { return _m[row][column]; }\n\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        const T& operator() (size_t row, size_t column) const { return _m[row][column]; }\n#else\n        MATRIXOPERATOR (T);\n#endif\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true only if all elements are equal.\n         *\n         * @param rhs [in] Rotation2D to compare with\n         * @return True if equal.\n         */\n        bool operator== (const Rotation2D< T >& rhs) const\n        {\n            for (int i = 0; i < 2; ++i) {\n                for (int j = 0; j < 2; ++j) {\n                    if (!(_m[i][j] == rhs (i, j))) {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true if any of the elements are different.\n         *\n         * @param rhs [in] Rotation2D to compare with\n         * @return True if not equal.\n         */\n        bool operator!= (const Rotation2D< T >& rhs) const { return !(*this == rhs); }\n\n        /**\n         * @brief Returns a boost 2x2 matrix @f$ \\mathbf{M}\\in SO(2)\n         * @f$ that represents this rotation\n         *\n         * @return @f$ \\mathbf{M}\\in SO(2) @f$\n         */\n        EigenMatrix2x2 e ()\n        {\n            EigenMatrix2x2 matrix;\n            matrix (0, 0) = _m[0][0];\n            matrix (0, 1) = _m[0][1];\n            matrix (1, 0) = _m[1][0];\n            matrix (1, 1) = _m[1][1];\n            return matrix;\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         *\n         * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n         *\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n         */\n        const Rotation2D operator* (const Rotation2D& bRc) const\n        {\n            return Rotation2D ((*this) (0, 0) * bRc (0, 0) + (*this) (0, 1) * bRc (1, 0),\n                               (*this) (0, 0) * bRc (0, 1) + (*this) (0, 1) * bRc (1, 1),\n                               (*this) (1, 0) * bRc (0, 0) + (*this) (1, 1) * bRc (1, 0),\n                               (*this) (1, 0) * bRc (0, 1) + (*this) (1, 1) * bRc (1, 1));\n        }\n\n        /**\n         * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{v}} =\n         * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{v}} \\f$\n         *\n         * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n         * @param bVc [in] \\f$ \\robabx{b}{c}{\\mathbf{v}} \\f$\n         * @return \\f$ \\robabx{a}{c}{\\mathbf{v}} \\f$\n         */\n        const rw::math::Vector2D< T > operator* (const rw::math::Vector2D< T >& bVc) const\n        {\n            return rw::math::Vector2D< T > ((*this) (0, 0) * bVc (0) + (*this) (0, 1) * bVc (1),\n                                            (*this) (1, 0) * bVc (0) + (*this) (1, 1) * bVc (1));\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Writes rotation matrix to stream\n         * @param os [in/out] output stream to use\n         * @param r [in] rotation matrix to print\n         * @return the updated output stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const Rotation2D& r)\n        {\n            return os << \"Rotation2D {\" << r (0, 0) << \", \" << r (0, 1) << \", \" << r (1, 0) << \", \"\n                      << r (1, 1) << \"}\";\n        }\n#else\n        TOSTRING (rw::math::Rotation2D< T >);\n#endif\n\n      private:\n        T _m[2][2];\n        // Base _atrix;\n    };\n\n    /**\n     * @brief Casts Rotation2D<T> to Rotation2D<Q>\n     * @param rot [in] Rotation2D with type T\n     * @return Rotation2D with type R\n     */\n    template< class R, class T > const Rotation2D< R > cast (const Rotation2D< T >& rot)\n    {\n        Rotation2D< R > res (Rotation2D< R >::identity ());\n        for (size_t i = 0; i < 2; i++)\n            for (size_t j = 0; j < 2; j++)\n                res (i, j) = static_cast< R > (rot (i, j));\n        return res;\n    }\n\n    /**\n     * @brief The inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$ of a rotation matrix\n     *\n     * @relates Rotation2D\n     *\n     * @param aRb [in] the rotation matrix @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n     *\n     * @return the matrix inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n     * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$\n     *\n     * @f$ \\robabx{b}{a}{\\mathbf{R}} = \\robabx{a}{b}{\\mathbf{R}}^{-1} =\n     * \\robabx{a}{b}{\\mathbf{R}}^T @f$\n     */\n    template< class T > const Rotation2D< T > inverse (const Rotation2D< T >& aRb)\n    {\n        return Rotation2D< T > (aRb (0, 0), aRb (1, 0), aRb (0, 1), aRb (1, 1));\n    }\n\n    /**\n     * @brief Find the transpose of \\b aRb.\n     *\n     * The transpose of a rotation matrix is the same as the inverse.\n     */\n    template< class T > const Rotation2D< T > transpose (const Rotation2D< T >& aRb)\n    {\n        return Rotation2D< T > (aRb (0, 0), aRb (1, 0), aRb (0, 1), aRb (1, 1));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::Rotation2D< double >;\n    extern template class rw::math::Rotation2D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Rotation2Dd, rw::math::Rotation2D< double >);\n    SWIG_DECLARE_TEMPLATE (Rotation2Df, rw::math::Rotation2D< float >);\n#endif\n    /**@}*/\n}}    // namespace rw::math\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::Rotation2D\n         */\n        template<>\n        void write (const rw::math::Rotation2D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Rotation2D\n         */\n        template<>\n        void write (const rw::math::Rotation2D< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Rotation2D\n         */\n        template<>\n        void read (rw::math::Rotation2D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Rotation2D\n         */\n        template<>\n        void read (rw::math::Rotation2D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "516d82e1fa26171f83615b317063ece412b3afb8", "size": 12445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Rotation2D.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/Rotation2D.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/Rotation2D.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": 30.1331719128, "max_line_length": 99, "alphanum_fraction": 0.4697468863, "num_tokens": 3843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6533376285903557}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n/***********************************************************************************************/\n\n// Generic functor\n// See http://eigen.tuxfamily.org/index.php?title=Functors\n// C++ version of a function pointer that stores meta-data about the function\ntemplate<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\nstruct Functor\n{\n\n  // Information that tells the caller the numeric type (eg. double) and size (input / output dim)\n  typedef _Scalar Scalar;\n  enum { // Required by numerical differentiation module\n      InputsAtCompileTime = NX,\n      ValuesAtCompileTime = NY\n  };\n\n  // Tell the caller the matrix sizes associated with the input, output, and jacobian\n  typedef Eigen::Matrix<Scalar,InputsAtCompileTime,1> InputType;\n  typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,1> ValueType;\n  typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,InputsAtCompileTime> JacobianType;\n\n  // Local copy of the number of inputs\n  int m_inputs, m_values;\n\n  // Two constructors:\n  Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n  Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n  // Get methods for users to determine function input and output dimensions\n  int inputs() const { return m_inputs; }\n  int values() const { return m_values; }\n\n};\n\n/***********************************************************************************************/\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Booth Function\n// Implement f(x,y) = (x + 2*y -7)^2 + (2*x + y - 5)^2\nstruct BoothFunctor : Functor<double>\n{\n  // Simple constructor\n  BoothFunctor(): Functor<double>(2,3) {}\n\n  // Implementation of the objective function\n  int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const {\n    double a = z(0);\n\t  double b = z(1);\n\t  double c = z(2);\n\t/*\n     * Evaluate the Booth function.\n     * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n     * of squared terms. The algorithm takes this into account: do not do it yourself.\n     * In other words: objFun = sum(fvec(i)^2)\n     */\n    fvec(0) = 3*a -cos(b*c) -0.5;\n    fvec(1) = pow(a,2.0) -81*pow((b+0.1),2.0)+sin(c)+1.06;\n\t  fvec(2) = exp(-a*b)+20*c+(10*M_PI-3.0)/3.0;\n    return 0;\n  }\n};\n\n/***********************************************************************************************/\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Himmelblau's Function\n// Implement f(x,y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2\nstruct HimmelblauFunctor : Functor<double>\n{\n  // Simple constructor\n  HimmelblauFunctor(): Functor<double>(2,2) {}\n  // Implementation of the objective function\n  int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const {\n    double x = z(0);   double y = z(1);\n    /*\n     * Evaluate Himmelblau's function.\n     * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n     * of squared terms. The algorithm takes this into account: do not do it yourself.\n     * In other words: objFun = sum(fvec(i)^2)\n     */\n    fvec(0) = x * x + y - 11;\n    fvec(1) = x + y * y - 7;\n    return 0;\n  }\n};\n\n/***********************************************************************************************/\n\nvoid testBoothFun() {\n  std::cout << \"Testing the Booth function...\" << std::endl;\n  Eigen::VectorXd zInit(3); zInit << 0.1, 0.1, -0.1;\n  std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n\n  BoothFunctor functor;\n  Eigen::NumericalDiff<BoothFunctor> numDiff(functor);\n  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<BoothFunctor>,double> lm(numDiff);\n  lm.parameters.maxfev = 1000;\n  lm.parameters.xtol = 1.0e-10;\n  std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n  std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n  Eigen::VectorXd z = zInit;\n  int ret = lm.minimize(z);\n  std::cout << \"iter count: \" << lm.iter << std::endl;\n  std::cout << \"return status: \" << ret << std::endl;\n  std::cout << \"zSolver: \" << z.transpose() << std::endl;\n  std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n/***********************************************************************************************/\n\nvoid testHimmelblauFun() {\n  std::cout << \"Testing the Himmelblau function...\" << std::endl;\n  // Eigen::VectorXd zInit(2); zInit << 0.0, 0.0;  // soln 1\n  // Eigen::VectorXd zInit(2); zInit << -1, 1;  // soln 2\n  // Eigen::VectorXd zInit(2); zInit << -1, -1;  // soln 3\n  Eigen::VectorXd zInit(2); zInit << 1, -1;  // soln 4\n  std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n  std::cout << \"soln 1: [3.0, 2.0]\" << std::endl;\n  std::cout << \"soln 2: [-2.805118, 3.131312]\" << std::endl;\n  std::cout << \"soln 3: [-3.77931, -3.28316]\" << std::endl;\n  std::cout << \"soln 4: [3.584428, -1.848126]\" << std::endl;\n\n  HimmelblauFunctor functor;\n  Eigen::NumericalDiff<HimmelblauFunctor> numDiff(functor);\n  Eigen::LevenbergMarquardt<Eigen::NumericalDiff<HimmelblauFunctor>,double> lm(numDiff);\n  lm.parameters.maxfev = 1000;\n  lm.parameters.xtol = 1.0e-10;\n  std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n  std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n  Eigen::VectorXd z = zInit;\n  int ret = lm.minimize(z);\n  std::cout << \"iter count: \" << lm.iter << std::endl;\n  std::cout << \"return status: \" << ret << std::endl;\n  std::cout << \"zSolver: \" << z.transpose() << std::endl;\n  std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n/***********************************************************************************************/\n\nint main(int argc, char *argv[])\n{\n\n\tstd::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n\ttestBoothFun();\n\ttestHimmelblauFun();\n\treturn 0;\n}", "meta": {"hexsha": "7c472a9258f2e51524d10af24419efc79bb29d69", "size": 5981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_matrix_solve.cpp", "max_stars_repo_name": "neeldug/404CircuitSim", "max_stars_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_matrix_solve.cpp", "max_issues_repo_name": "neeldug/404CircuitSim", "max_issues_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_matrix_solve.cpp", "max_forks_repo_name": "neeldug/404CircuitSim", "max_forks_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-06T20:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T20:27:56.000Z", "avg_line_length": 38.5870967742, "max_line_length": 98, "alphanum_fraction": 0.5664604581, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6533376265507135}}
{"text": "#ifndef RSVD_STANDARD_NORMAL_RANDOM_HPP_\n#define RSVD_STANDARD_NORMAL_RANDOM_HPP_\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <complex>\n#include <random>\n\nnamespace Rsvd {\n\nnamespace Internal {\n\nnamespace {\n/// \\brief Shortcut for the underlying \\a real type used in the matrix.\n///\n/// \\long E.g. if the matrix is of type \\c std::complex<double>, this typedef equals to \\c double.\ntemplate <typename MatrixType>\nusing RealType = typename Eigen::NumTraits<typename MatrixType::Scalar>::Real;\n} // namespace\n\n/// \\brief Helper struct to do partial specialization in the matrix scalar type\n///\n/// \\tparam MatrixType Eigen matrix type.\n///\n/// \\tparam ScalarType Underlying scalar type used in \\c MatrixType, can be complex or real.\n///\n/// \\tparam RandomEngineType Type of the random engine, e.g. \\c std::default_random_engine or \\c\n/// std::mt19937_64.\ntemplate <typename MatrixType, typename ScalarType, typename RandomEngineType>\nstruct StandardNormalRandomHelper {\n  static inline MatrixType generate(Eigen::Index numRows, Eigen::Index numCols,\n                                    RandomEngineType &engine);\n};\n\n/// \\brief Partial specialization for real matrices.\ntemplate <typename MatrixType, typename RandomEngineType>\nstruct StandardNormalRandomHelper<MatrixType, RealType<MatrixType>, RandomEngineType> {\n  static inline MatrixType generate(const Eigen::Index numRows, const Eigen::Index numCols,\n                                    RandomEngineType &engine) {\n    // Create a standard normal distribution with zero mean (mu = 0) and unity variance (sigma^2 =\n    // 1)\n    std::normal_distribution<RealType<MatrixType>> distribution{0, 1};\n    const auto normal{[&](typename MatrixType::Scalar) { return distribution(engine); }};\n    return MatrixType::NullaryExpr(numRows, numCols, normal);\n  }\n};\n\n/// \\brief Partial specialization for complex matrices.\ntemplate <typename MatrixType, typename RandomEngineType>\nstruct StandardNormalRandomHelper<MatrixType, std::complex<RealType<MatrixType>>,\n                                  RandomEngineType> {\n  static inline MatrixType generate(const Eigen::Index numRows, const Eigen::Index numCols,\n                                    RandomEngineType &engine) {\n    // A complex standard normal distribution has half of its variance in the real variable and\n    // half in the complex. Hence, the each variance is 1/2 and each standard deviation is\n    // 1/sqrt(2)\n    constexpr RealType<MatrixType> stdDev{0.707106781186547};\n    std::normal_distribution<RealType<MatrixType>> distribution{0, stdDev};\n    const auto complexNormal{[&](typename MatrixType::Scalar) {\n      return std::complex<RealType<MatrixType>>(distribution(engine), distribution(engine));\n    }};\n    return MatrixType::NullaryExpr(numRows, numCols, complexNormal);\n  }\n};\n\n/// \\brief Generate a matrix with iid elements from standard normal\n/// distribution.\n///\n/// \\long The matrix elements are drawn from the standard normal distribution (zero mean and unit\n/// variance), i.e. \\f$ [ \\Omega ]_{i,j} \\sim \\mathcal{N}(0, 1) \\f$ for the real case and \\f$ [\n/// \\Omega ]_{i,j} \\sim \\mathcal{N}\\left(0, \\frac{1}{2} \\right) + \\mathcal{N}\\left(0, \\frac{1}{2}\n/// \\right) \\cdot \\mathrm{i}\\f$ for the complex case.\n///\n/// \\tparam MatrixType Eigen matrix type.\n/// \\tparam RandomEngineType Type of the random engine, e.g. \\c std::default_random_engine or \\c\n/// std::mt19937_64.\n///\n/// \\param numRows Number of matrix rows \\f$ m \\f$.\n/// \\param numCols Number of matrix columns \\f$ n \\f$.\n/// \\param engine Reference to the random engine.\n///\n/// \\return Matrix \\f$ \\Omega \\in \\mathbb{F}^{m \\times n} \\f$ with \\f$\\mathbb{F} \\in \\{ \\mathbb{R},\n/// \\mathbb{C} \\} \\f$ with normally distributed elements.\ntemplate <typename MatrixType, typename RandomEngineType>\ninline MatrixType standardNormalRandom(const Eigen::Index numRows, const Eigen::Index numCols,\n                                       RandomEngineType &engine) {\n  return StandardNormalRandomHelper<MatrixType, typename MatrixType::Scalar,\n                                    RandomEngineType>::generate(numRows, numCols, engine);\n}\n\n} // namespace Internal\n\n} // namespace Rsvd\n\n#endif\n", "meta": {"hexsha": "1453a7baaf61579e600b5882c879bbad72adc08a", "size": 4173, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rsvd/StandardNormalRandom.hpp", "max_stars_repo_name": "mooreryan/coda", "max_stars_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T09:12:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T15:40:04.000Z", "max_issues_repo_path": "include/rsvd/StandardNormalRandom.hpp", "max_issues_repo_name": "mooreryan/coda", "max_issues_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_issues_repo_licenses": ["MIT"], "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/rsvd/StandardNormalRandom.hpp", "max_forks_repo_name": "mooreryan/coda", "max_forks_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T18:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T18:45:56.000Z", "avg_line_length": 43.46875, "max_line_length": 99, "alphanum_fraction": 0.6999760364, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.653337625633126}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X * X.transpose();\nX = MatrixXd::Random(5,5);\nMatrixXd B = X * X.transpose();\n\nGeneralizedSelfAdjointEigenSolver<MatrixXd> es(A,B,EigenvaluesOnly);\ncout << \"The eigenvalues of the pencil (A,B) are:\" << endl << es.eigenvalues() << endl;\nes.compute(B,A,false);\ncout << \"The eigenvalues of the pencil (B,A) are:\" << endl << es.eigenvalues() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a79b03f63a62b5f439322d1e051616413dd4f39a", "size": 547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_compute_MatrixType2.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_compute_MatrixType2.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_compute_MatrixType2.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": 24.8636363636, "max_line_length": 87, "alphanum_fraction": 0.6782449726, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6531504835788359}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include <map>\n#include <vector>\n\nusing std::vector;\nusing std::map;\n\n\nnamespace mcl_cpp\n{\n\tclass mcl\n\t{\n\tpublic:\n\t\t//! @brief MCL ctor. Register a callback function to return the cluster results\n\t\tmcl(const Eigen::MatrixXd& Min, std::function< void(size_t cluster_j, size_t member_i) > f) : M(Min), ClusterResultCallback(f) {}\n\n\t\t/*! @brief Apply Markov clustering algorithm with specified parameters and return clusters\n\t\t\tFor each cluster, returns the list of node-ids that belong to that cluster\n\t\t\t*/\n\t\tEigen::MatrixXd cluster_mcl(double expand_factor = 2, double inflate_factor = 2, double max_loop = 10, double mult_factor = 1)\n\t\t{\n\t\t\tEigen::MatrixXd M_selfloop = M + mult_factor * Eigen::MatrixXd::Identity(M.cols(), M.rows());\n\t\t\tEigen::MatrixXd M_normalized = normalize(M_selfloop);\n\t\t\tint i;\n\t\t\tfor (i = 0; i < max_loop && !stop(M_normalized, i); i++)\n\t\t\t{\n\t\t\t\tinflate(M_normalized, inflate_factor);\n\t\t\t\texpand(M_normalized, expand_factor);\n\t\t\t}\n\t\t\tfor (auto row = 0; row<M_normalized.rows(); row++)\n\t\t\t{\n\t\t\t\tif (M_normalized(row, row) > 0)\n\t\t\t\t{\n\t\t\t\t\tfor (auto col = 0; col < M_normalized.cols(); col++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (M_normalized.coeff(row, col) > 0)\n\t\t\t\t\t\t\tClusterResultCallback(row, col);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\tprivate:\n\t\tbool stop(const Eigen::MatrixXd& in, int i)\n\t\t{\n\t\t\tEigen::MatrixXd m = in*in;\n\t\t\tEigen::MatrixXd diff = (m - in);\n\t\t\tdouble mx = diff.maxCoeff(), mn = diff.minCoeff();\n\t\t\treturn (diff.maxCoeff() == diff.minCoeff());\n\t\t}\n\n\t\tEigen::MatrixXd normalize(Eigen::MatrixXd& in)\n\t\t{\n\t\t\tEigen::MatrixXd one_over_col_sum = in.colwise().sum().cwiseInverse();\n\t\t\tEigen::MatrixXd M_normalized = in * one_over_col_sum.asDiagonal();\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\t\tvoid expand(Eigen::MatrixXd& in, double expand_factor)\n\t\t{\n\t\t\tEigen::MatrixPower<Eigen::MatrixXd> Apow(in);\n\t\t\tin = Apow(expand_factor);\n\t\t}\n\n\t\tvoid inflate(Eigen::MatrixXd& in, double inflate_factor)\n\t\t{\n\t\t\tauto lam = [inflate_factor](double x) -> double { return std::pow(x, inflate_factor); };\n\t\t\tin = in.unaryExpr(lam);\n\t\t\tin = normalize(in);\n\t\t}\n\n\t\tconst Eigen::MatrixXd & M;\n\t\tstd::function< void(size_t cls_i, size_t mem_j) > ClusterResultCallback;\n\t};\n\n\n\n\n\n\n}", "meta": {"hexsha": "e7327bc9422f437b117ce29a830bd12e928b9bda", "size": 2286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mcl/mcl.hpp", "max_stars_repo_name": "kgopalak/mcl_cpp", "max_stars_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-04-26T01:15:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T18:01:57.000Z", "max_issues_repo_path": "mcl/mcl.hpp", "max_issues_repo_name": "kgopalak/mcl_cpp", "max_issues_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcl/mcl.hpp", "max_forks_repo_name": "kgopalak/mcl_cpp", "max_forks_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_forks_repo_licenses": ["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.5813953488, "max_line_length": 131, "alphanum_fraction": 0.6688538933, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6531504790016581}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <chrono.h>\n\nvoid buildSystem(Eigen::MatrixXd& A, Eigen::VectorXd& b, const unsigned int dim) {\n    A = Eigen::MatrixXd::Random(dim, dim);\n    A.diagonal() += (dim + 1) * Eigen::VectorXd::Ones(dim);\n    \n    b = Eigen::VectorXd::Random(dim);\n    assert(b.norm() > DBL_EPSILON);\n}\n\nEigen::VectorXd GS(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const unsigned int nbIter) {\n    auto x = b;\n    for (size_t iter = 0; iter < nbIter; ++iter) {\n        for (size_t i = 0; i < A.rows(); i++) {\n            double sum = 0.0;\n            for (size_t j = 0; j < A.cols(); j++) {\n                if (j != i) {\n                    sum += A(i, j) * x(j);\n                }\n                x(i) = (b(i) - sum) / A(i, i);\n            }\n        }\n    }\n    return x;\n}\n\nint main(int argc, char const *argv[]) {\n    const unsigned int arraySize = 5;\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(arraySize, arraySize);\n    Eigen::VectorXd b = Eigen::VectorXd::Random(arraySize);\n    buildSystem(A, b, A.size());\n\n    TP_CPP_IMAC2::Chrono chrono;\n\n    // Jacobi\n    chrono.start();\n    Eigen::VectorXd x = GS(A, b, 28);\n    chrono.stop();\n    std::cout << \"Jacobi : \" << chrono.timeSpan() << std::endl;\n\n    // Lu\n    chrono.start();\n    Eigen::PartialPivLU<Eigen::MatrixXd> lu(A);\n    x = A * lu.solve(b);\n    chrono.stop();\n    std::cout << \"Lu : \" << chrono.timeSpan() << std::endl;\n\n    // QR\n    chrono.start();\n    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> qr(A);\n    x = A * qr.solve(b);\n    chrono.stop();\n    std::cout << \"QR : \" << chrono.timeSpan() << std::endl;\n\n    // SVD\n    chrono.start();\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    x = A * svd.solve(b);\n    chrono.stop();\n    std::cout << \"SVD : \" << chrono.timeSpan() << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "4dbb8771562a76c78d4d6c99296282bd768600e3", "size": 1865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_stars_repo_name": "guillaume-haerinck/imac-c", "max_stars_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_issues_repo_name": "guillaume-haerinck/imac-c", "max_issues_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_forks_repo_name": "guillaume-haerinck/imac-c", "max_forks_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8358208955, "max_line_length": 99, "alphanum_fraction": 0.5378016086, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6530615036717684}}
{"text": "#include <iostream>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nstruct Vertex {\n    double x, y, z;\n};\n    \nint main()\n{\n    Vertex v1, v2, v3;\n    cin >> v1.x >> v1.y >> v1.z\n        >> v2.x >> v2.y >> v2.z\n        >> v3.x >> v3.y >> v3.z;\n    \n    Eigen::Vector3d vec12(v2.x-v1.x, v2.y-v1.y, v2.z-v1.z);\n    Eigen::Vector3d vec23(v3.x-v2.x, v3.y-v2.y, v3.z-v2.z);\n\n    Eigen::Vector3d veccross = vec12.cross(vec23);\n    // veccross /= sqrt(veccross.array().pow(2).sum());\n    veccross.normalize();\n\n    Eigen::Vector4d faceEqn;\n    faceEqn << veccross, -veccross[0]*v1.x -veccross[1]*v1.y -veccross[2]*v1.z;\n\n    cout << veccross << endl << faceEqn << endl;\n    \n}", "meta": {"hexsha": "d9b4fa8f496f4406c9c6e3e246e708872403180e", "size": 686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QmatrixTest.cpp", "max_stars_repo_name": "CalaW/Mesh-Simplification", "max_stars_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-26T04:37:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T04:37:27.000Z", "max_issues_repo_path": "QmatrixTest.cpp", "max_issues_repo_name": "CalaW/Mesh-Simplification", "max_issues_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QmatrixTest.cpp", "max_forks_repo_name": "CalaW/Mesh-Simplification", "max_forks_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_forks_repo_licenses": ["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.8666666667, "max_line_length": 79, "alphanum_fraction": 0.5626822157, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6530134452013466}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n\nEigen::Matrix3d OthMatrix(const Eigen::Matrix3d& input) {\n    Eigen::Quaterniond q(input);\n    q.normalize();\n    return q.toRotationMatrix();\n}\n\n// \u89e3\u51b3\u5982\u4e0b\u95ee\u9898\n// 1. Affine3d, Isomtry3d,  Matrix4d\u8868\u793a\u540c\u4e00\u4e2a\u6b27\u5f0f\u53d8\u6362\u65f6\uff0c\u6c42\u9006\u662f\u5426\u4e0d\u540c\n// \u4ece\u8f93\u51fa\u53ef\u4ee5\u770b\u51fa\u6765\u7ed3\u679c\u4e00\u81f4\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    Eigen::Quaterniond rotation(rz * ry * rx);\n    std::cout << rotation.matrix() << std::endl;\n    Eigen::Translation3d t(1, 2, 3);\n    Eigen::Affine3d matrix_affine = t * rotation;\n    std::cout <<\"matrix_affine : \\n\" << matrix_affine.matrix() << std::endl;\n\n    Eigen::Isometry3d isometry3d(t * rotation);\n    std::cout << \"isometry3 : \\n\" << isometry3d.matrix() << std::endl;\n\n    Eigen::Matrix4d m4d = matrix_affine.matrix();\n    std::cout << \"matrix4d : \\n\" << m4d.matrix() << std::endl;\n\n    std::cout <<\"matrix_affine inverse: \\n\" <<  matrix_affine.inverse().matrix() << std::endl;\n    std::cout << \"matrix4d inverse : \\n\" << m4d.inverse() << std::endl;\n    std::cout << \"isometry3 inverse : \\n\" << isometry3d.inverse().matrix() << std::endl;\n\n}", "meta": {"hexsha": "e08123586f801230358c4938fce51a49da20d8cd", "size": 1538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/space_transform/matrix_representation.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/matrix_representation.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/matrix_representation.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": 36.619047619, "max_line_length": 94, "alphanum_fraction": 0.6417425228, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6530134394755358}}
{"text": "#include <iostream>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"Geometry/ParameterDesign/Interpolation.h\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\nclass InterpolationVisualizer :public Visualizer\n{\nprotected:\n\tvoid AddPoint();\n\tvoid DragPoint();\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tbool updated = true;\n\n\tvoid evaluate_lagrangian()\n\t{\n\t\tBSplineInterpolation lagrangian(points);\n\t\tlagrangian.evaluate();\n\n\t\tRadialInterpolation radial(points);\n\t\tradial.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tys1[i] = lagrangian(xs[i]);\n\t\t\tys2[i] = radial(xs[i]);\n\t\t}\n\t}\n\npublic:\n\tInterpolationVisualizer() {\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = i;\n\t\t}\n\t}\n\tconst float Length = 1001;\n\n\tstd::vector<float> xs = std::vector<float>(Length);\n\tstd::vector<float> ys1 = std::vector<float>(Length, 0);\n\tstd::vector<float> ys2 = std::vector<float>(Length, 0);\n};\n\nvoid DrawRadial()\n{\n}\n\nvoid InterpolationVisualizer::AddPoint()\n{\n\tif (ImGui::IsMouseClicked(ImGuiMouseButton_Right))\n\t{\n\t\tauto pos = ImPlot::GetPlotMousePos();\n\t\tpoints.emplace_back(pos.x, pos.y);\n\t\tupdated = true;\n\t}\n}\n\nvoid InterpolationVisualizer::DragPoint()\n{\n\tfor (int i = 0; i < points.size(); ++i)\n\t{\n\t\tauto& point = points[i];\n\t\tupdated |= ImPlot::DragPoint((\"Point \" + std::to_string(i)).c_str(), &point.x(), &point.y());\n\t}\n}\n\nvoid InterpolationVisualizer::draw(bool* p_open)\n{\n\tif (updated)\n\t{\n\t\tevaluate_lagrangian();\n\t\tupdated = false;\n\t}\n\tif (ImGui::BeginTabBar(\"Homework 1\")) {\n\t\tif (ImGui::BeginTabItem(\"Interpolation\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail(), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"Polynomial\", &xs[0], &ys1[0], Length);\n\t\t\t\tAddPoint();\n\t\t\t\tDragPoint();\n\n\t\t\t\tImPlot::PlotLine(\"Radial\", &xs[0], &ys2[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tImGui::EndTabBar();\n\t}\n\tImGui::End();\n}\n\nint main()\n{\n\tInterpolationVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "2e5ae313d58d91a1e2f5ca9244f41bcaf9603ecb", "size": 2038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/Interpolation/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/Interpolation/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/Interpolation/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": 19.786407767, "max_line_length": 132, "alphanum_fraction": 0.6619234544, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6529351773342364}}
{"text": "/*\n * two_dimensional_phase_lattice.cpp\n *\n * This example show how one can use matrices as state types in odeint.\n *\n * Copyright 2009-2012 Karsten Ahnert and Mario Mulansky.\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\n#include <iostream>\n#include <map>\n#include <string>\n#include <fstream>\n\n#ifndef M_PI //not there on windows\n#define M_PI 3.1415927 //...\n#endif\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ two_dimensional_phase_lattice_definition\ntypedef boost::numeric::ublas::matrix< double > state_type;\n\nstruct two_dimensional_phase_lattice\n{\n    two_dimensional_phase_lattice( double gamma = 0.5 )\n    : m_gamma( gamma ) { }\n\n    void operator()( const state_type &x , state_type &dxdt , double /* t */ ) const\n    {\n        size_t size1 = x.size1() , size2 = x.size2();\n\n        for( size_t i=1 ; i<size1-1 ; ++i )\n        {\n            for( size_t j=1 ; j<size2-1 ; ++j )\n            {\n                dxdt( i , j ) =\n                        coupling_func( x( i + 1 , j ) - x( i , j ) ) +\n                        coupling_func( x( i - 1 , j ) - x( i , j ) ) +\n                        coupling_func( x( i , j + 1 ) - x( i , j ) ) +\n                        coupling_func( x( i , j - 1 ) - x( i , j ) );\n            }\n        }\n\n        for( size_t i=0 ; i<x.size1() ; ++i ) dxdt( i , 0 ) = dxdt( i , x.size2() -1 ) = 0.0;\n        for( size_t j=0 ; j<x.size2() ; ++j ) dxdt( 0 , j ) = dxdt( x.size1() -1 , j ) = 0.0;\n    }\n\n    double coupling_func( double x ) const\n    {\n        return sin( x ) - m_gamma * ( 1.0 - cos( x ) );\n    }\n\n    double m_gamma;\n};\n//]\n\n\nstruct write_for_gnuplot\n{\n    size_t m_every , m_count;\n\n    write_for_gnuplot( size_t every = 10 )\n    : m_every( every ) , m_count( 0 ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        if( ( m_count % m_every ) == 0 )\n        {\n            clog << t << endl;\n            cout << \"sp '-'\" << endl;\n            for( size_t i=0 ; i<x.size1() ; ++i )\n            {\n                for( size_t j=0 ; j<x.size2() ; ++j )\n                {\n                    cout << i << \"\\t\" << j << \"\\t\" << sin( x( i , j ) ) << \"\\n\";\n                }\n                cout << \"\\n\";\n            }\n            cout << \"e\" << endl;\n        }\n\n        ++m_count;\n    }\n};\n\nclass write_snapshots\n{\npublic:\n\n    typedef std::map< size_t , std::string > map_type;\n\n    write_snapshots( void ) : m_count( 0 ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        map< size_t , string >::const_iterator it = m_snapshots.find( m_count );\n        if( it != m_snapshots.end() )\n        {\n            ofstream fout( it->second.c_str() );\n            for( size_t i=0 ; i<x.size1() ; ++i )\n            {\n                for( size_t j=0 ; j<x.size2() ; ++j )\n                {\n                    fout << i << \"\\t\" << j << \"\\t\" << x( i , j ) << \"\\t\" << sin( x( i , j ) ) << \"\\n\";\n                }\n                fout << \"\\n\";\n            }\n        }\n        ++m_count;\n    }\n\n    map_type& snapshots( void ) { return m_snapshots; }\n    const map_type& snapshots( void ) const { return m_snapshots; }\n\nprivate:\n\n    size_t m_count;\n    map_type m_snapshots;\n};\n\n\nint main( int argc , char **argv )\n{\n    size_t size1 = 128 , size2 = 128;\n    state_type x( size1 , size2 , 0.0 );\n\n    for( size_t i=(size1/2-10) ; i<(size1/2+10) ; ++i )\n        for( size_t j=(size2/2-10) ; j<(size2/2+10) ; ++j )\n            x( i , j ) = static_cast<double>( rand() ) / RAND_MAX * 2.0 * M_PI;\n\n    write_snapshots snapshots;\n    snapshots.snapshots().insert( make_pair( size_t( 0 ) , string( \"lat_0000.dat\" ) ) );\n    snapshots.snapshots().insert( make_pair( size_t( 100 ) , string( \"lat_0100.dat\" ) ) );\n    snapshots.snapshots().insert( make_pair( size_t( 1000 ) , string( \"lat_1000.dat\" ) ) );\n    observer_collection< state_type , double > obs;\n    obs.observers().push_back( write_for_gnuplot( 10 ) );\n    obs.observers().push_back( snapshots );\n\n    cout << \"set term x11\" << endl;\n    cout << \"set pm3d map\" << endl;\n\n    integrate_const( runge_kutta4<state_type>() , two_dimensional_phase_lattice( 1.2 ) ,\n                     x , 0.0 , 1001.0 , 0.1 , boost::ref( obs ) );\n\n    // controlled steppers work only after ublas bugfix\n    //integrate_const( make_dense_output< runge_kutta_dopri5< state_type > >( 1E-6 , 1E-6 ) , two_dimensional_phase_lattice( 1.2 ) ,\n    //        x , 0.0 , 1001.0 , 0.1 , boost::ref( obs ) );\n\n\n    return 0;\n}\n", "meta": {"hexsha": "db5bbebfeb0a7d61d38d61ac46f794a3969aa622", "size": 4592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.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/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.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/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.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": 29.0632911392, "max_line_length": 132, "alphanum_fraction": 0.5158972125, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6529351593474146}}
{"text": "\n/**\n\\file   quintic_spline.cpp\n\\brief  quintic_spline parameterization\n *\n\\author  Mahmoud Ali\n\\date    21/6/2019\n*/\n\n\n#include<vector>\n#include<iostream>\n#include \"ros/ros.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n\n//#include<normal_toppra_traj_instant_1.h>\n#include<normal_toppra_traj_instant_3.h>\n#include <Eigen/Dense>\n#include <math.h>\n\n#include <python2.7/Python.h>\n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\nusing namespace std;\nusing Eigen::MatrixXd;\n\nconst double sm=180, vm= 130, am=250, jm=1000; // pos, vel, acc, jrk max limits\n\n\n// finds in which segment time instant tg belons to\nint find_seg_number (double tg, std::vector<double> T_vec){\n    // segment changes from 0 to n-2 which mean n-1 seg\n    int seg = 0;\n    if(tg<= T_vec[0]) //less than tstart\n        return seg;\n    else if(tg>= T_vec[T_vec.size() -2 ] ) //if tg is greater than the starting time of the last segment\n        return T_vec.size() - 2;\n    else {\n        for (int i=0; i< T_vec.size()-2 ; i++) { // between tstart and tend\n            if(tg>= T_vec[i] && tg< T_vec[i+1])\n                seg = i;\n        }\n        return seg;\n    }\n}\n\n\n// to sample trajectory, find state(pos, vel, acc, jrk) at a given time tg, T_vec is time vector of waypoints, cof is coef matrix of quintic spline\nvoid sample (const std::vector<double>& T_vec, const double& tg, const std::vector<std::vector<double>> &cof, std::vector<double> & state){//, bool pos_plt=true, bool vel_plt=true, bool acc_plt=true, bool jrk_plt=true ){\n    std::vector<double> a=cof[0], b=cof[1], c=cof[2], d=cof[3], e=cof[4], f=cof[5];\n    double pos=0, vel=0, acc=0, jrk=0;\n    int n = T_vec.size(), seg=0; // n:number of points\n    double t=0; // to represent tg-tseg\n    //check for vector sizes\n    //    std::cout<<\"\\nsize of a= \"<< a.size() << \" size of T= \"<< T_vec.size();\n    if( a.size() != T_vec.size()-1 )\n        std::cout<<\"error: coef and time have different size\\n\";\n\n\n    // check for tg inside T_vec or not, if yes find corrresponding segment\n    if(tg < T_vec[0]){\n        std::cout<<\"Warn: request time instant is before start time of trajectory\\n\";\n        pos= a[0];\n        vel= b[0];\n        acc= 2*c[0];\n        jrk= 6*d[0];\n    }\n    else if(tg > T_vec[n-1] ){\n        std::cout<<\"Warn: request time instant is after the end time of trajectory\\n \";\n        t = tg - T_vec[n-1];\n        pos=   a[n-2] +   b[n-2]*t +         c[n-2]*pow( t, 2) +        d[n-2]*pow( t, 3) +    e[n-2]*pow( t, 4) +    f[n-2]* pow( t, 5)  ;\n        vel=              b[n-2]        +  2*c[n-2]*t          +      3*d[n-2]*pow( t, 2) +  4*e[n-2]*pow( t, 3) +  5*f[n-2]* pow( t, 4)  ;\n        acc=                               2*c[n-2]                 + 6*d[n-2]*t          + 12*e[n-2]*pow( t, 2) + 20*f[n-2]* pow( t, 3)  ;\n        jrk=                                                          6*d[n-2]                 + 24*e[n-2]*t          + 60*f[n-2]* pow( t, 2)  ;\n    }\n    else{\n        seg= find_seg_number(tg, T_vec);\n        t = tg - T_vec[seg];\n        //        std::cout<<\"      tg= \" <<tg<< \"   seg_number= \"<<  seg<<\"   t= \"<<t<<std::endl;\n        pos=   a[seg] +   b[seg]*t +    c[seg]*pow( t, 2) +   d[seg]*pow( t, 3) +    e[seg]*pow( t, 4) +    f[seg]* pow( t, 5) ;\n        vel=              b[seg]        +  2*c[seg]*t          + 3*d[seg]*pow( t, 2) +  4*e[seg]*pow( t, 3) +  5*f[seg]* pow( t, 4) ;\n        acc=                               2*c[seg]                 + 6*d[seg]*t          + 12*e[seg]*pow( t, 2) + 20*f[seg]* pow( t, 3) ;\n        jrk=                                                          6*d[seg]                 + 24*e[seg]*t          + 60*f[seg]* pow( t, 2) ;\n    }\n    // assign state to state vector\n    state[0] = pos;\n    state[1] = vel;\n    state[2] = acc;\n    state[3] = jrk;\n\n}\n\n\n\n// generate C1 matrix which is depends on the time of each segment, idx is segment indx, h vectore contains segments times\nvoid generate_coef_matrix_c1(const int idx, const VectorXd &h, MatrixXd &C1){\n    MatrixXd C(5,6);\n    C<< 1,  h(idx),  pow(h(idx), 2),    pow(h(idx), 3),    pow(h(idx), 4),     pow(h(idx), 5),\n            0,       1,        2*h(idx),  3*pow(h(idx), 2),  4*pow(h(idx), 3),   5*pow(h(idx), 4),\n            0,       0,               1,          3*h(idx),  6*pow(h(idx), 2),  10*pow(h(idx), 3),\n            0,       0,               0,                 1,          4*h(idx),  10*pow(h(idx), 2),\n            0,       0,               0,                 0,                 1,           5*h(idx);\n    C1 = C;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"quintic_isp\");\n    ros::NodeHandle nh;\n\n    ROS_INFO(\"initializing path .... \");\n    //============ read trajectory ==========\n    trajectory_msgs::JointTrajectory  traj;\n    traj = generate_traj();\n    int n_jts = traj.joint_names.size();\n    int n_pts = traj.points.size();\n\n    // get waypoints from trajectory\n    std::vector< std::vector<double> > P_jt_wpt;\n    P_jt_wpt.resize( n_jts);\n    for(int jt=0; jt<n_jts; jt++){\n        for(int pt=0; pt<n_pts; pt++){\n            P_jt_wpt[jt].push_back( traj.points[pt].positions[jt] );\n        }\n    }\n\n\n    //pos vector\n    VectorXd pos(n_pts);\n    for (int pt=0; pt< n_pts; pt++) {\n        pos(pt) = P_jt_wpt[4][pt];\n    }\n    //    for (int pt=0; pt< n_pts; pt++) {\n    //        pos(pt+n_pts) = P_jt_wpt[5][pt];\n    //    }\n    // put equations in form of AX=B\n    int n = pos.size(); //number of waypoints\n    int n_eqs = 6*(n-1); // number of equations/variables\n    double vel0=0, veln=0, acc0=0, accn=0; // initial/final  conditions(vel, acc)\n\n    // store stop point at which trajectory reverse direction\n    std::vector<int> stp_pts_idx;\n    for (int i=1; i<n-1; i++) {\n        if( (  (pos(i+1) - pos(i))> 0 && (pos(i) - pos(i-1))> 0  ) || ( (pos(i+1) - pos(i))< 0 && (pos(i) - pos(i-1))< 0 ) )\n            continue;\n        stp_pts_idx.push_back( i );\n    }\n    //    ROS_INFO_STREAM(\"stp_pts_idx\"); //check\n    //    for (int i=0; i< stp_pts_idx.size(); i++)\n    //        ROS_INFO_STREAM(\" \"<< stp_pts_idx[i] );\n\n\n\n    //from pos vector: generate initial time for way points. t: time vector of waypoinys times, h is vector for segments times\n    VectorXd t(n), h(n-1); //t0 ==> tn-1  ...   h0 ==> hn-2 (#n of t and #n-1 of h)\n    for (int i = 0; i < n-1; ++i) {\n        h(i) = abs( (abs(pos(i+1)) - abs(pos(i))) ) /vm;\n    }\n    //  ROS_INFO_STREAM(\"h vector: \\n\"<<h);\n    t(0)=0; //starting time of trajectory\n    for (int i = 0; i < n-1; ++i) {\n        t(i+1) = h(i) + t(i);\n    }\n    //  ROS_INFO_STREAM(\"t vector: \\n\"<<t);\n\n\n    // define coef matrix and B matrix: AX=B\n    VectorXd B(n_eqs), X(n_eqs);\n    MatrixXd A =   MatrixXd::Zero(n_eqs, n_eqs);\n    MatrixXd C1 =  MatrixXd::Zero(5, 6);\n    MatrixXd C2 =  MatrixXd::Zero(5, 6);\n\n    // C1 and C2 store coef of 5(n-2) equations\n    for (int i=0; i<5; i++)\n        C2(i,i)=-1.0; // C2(0,0)  to   C2(4,4)\n\n    for (int i=0; i<n-1; i++) {\n        generate_coef_matrix_c1(i, h, C1);\n        ROS_INFO_STREAM(\" C1(\"<<i <<\") initialization:\\n \"<< C1);\n    }\n\n\n    //>>>>>>>>>>>step_1:  3 boundary conditions for first point (pos0, vel0, acc0), 3 rows\n    A(0,0) = 1;\n    A(1,1) = 1;\n    A(2,2) = 1;  // 3 rows are filled so far, so next r=3\n\n\n    //>>>>>>>>>>> step_2:  pos condition for all waypoints except first and last, (n-2) rows\n    int col_idx= 6;\n    for (int r = 3; r < 3+(n-2); ++r) {  //start filling from 4th row, #rows= n-2\n        A(r,col_idx) = 1;\n        col_idx+=6;\n    }  // n-2 rows are filled so far, so total rows are n-2+3= n+1\n\n\n    int count =0; // count no of iteration\n    std::vector<int> seg_idx;  //store segments indices that violate jerk\n    bool update_all_seg_time= false; // select: true=> updates times of all segments, false: update time for segments that voilate jerk\n    //================================================= loop: update time till the jerk become within the limit ================================\n    // bif while loop\n    bool lmtd_jrk = false; //will be set to true when all jrk values are in the limits\n    while (!lmtd_jrk){\n        if(count>0){ //no update in the first loop\n            if(update_all_seg_time) // update all segment time\n                for (int idx = 0; idx < n-1; ++idx)\n                    h(idx)=h(idx)+0.01;\n\n            else{  // only update the time of segment that violate jerk limit\n                for (int idx = 0; idx < seg_idx.size(); ++idx){\n                    ROS_INFO_STREAM(\"seg_idx[\"<<idx<< \"]:  \"<<seg_idx[idx]);\n                    if (seg_idx[idx] == n-1)\n                        seg_idx[idx] = seg_idx[idx] -1;\n                    h(seg_idx[idx])=h(seg_idx[idx])+0.01;\n                }\n            }\n        }\n        seg_idx.clear();\n        for (int i = 0; i < n-1; ++i) {\n            t(i+1) = h(i) + t(i);\n        }\n\n        // checks for velocity and acc limits\n\n        //>>>>>>>>>>>step_3: boundary conditions for last point (posn, veln, accn), 3 rows (depends on time so it is inside the loop)\n        // ROS_INFO(\"3 boundary conditions for last poit\");\n        for (int r = n+1 ; r < 3+(n+1); ++r) {// for 3 row\n            for (int c = n_eqs-6 ; c < n_eqs; ++c) {  // last 6 columns\n                generate_coef_matrix_c1( n-2, h, C1);\n                A(r, c) = C1(r-(n+1), c-(n_eqs-6));     // last h ==> hn-2\n            }\n        }//3+(n-2)+3 = n+4 rows are filled so far,  so next row to fill is (n+5)th row [its is index= n+4]\n        //>>>>>>>>>>>step_4: 5(n-2) coninuity conditions for each waypoints except first and last, 5(n-2) rows (depend on time so it is inside the loop)\n        //   ROS_INFO(\" 5(n-2) continuity conditions for midle poits\");\n        int row_idx = n+4; col_idx=0;  //start filling from (n+2)th row [its is index= n+1],\n        for (int blk=0; blk< n-2; blk++) { // n-2 blks, each blk is 5 equations with 6 coef\n            //       ROS_INFO_STREAM(\"row_idx: \"<< row_idx <<\"   col_idx:\"<< col_idx);\n            for (int r = 0 ; r < 5 ; ++r) {  // 5(n-2) rows\n                for (int c = 0 ; c < 6; ++c) {  // last 6 columns\n                    //               ROS_INFO_STREAM(\"r: \"<< r <<\"   c:\"<< c);\n                    generate_coef_matrix_c1( blk, h, C1);\n                    A(row_idx+r, col_idx+c)   = C1(r,c);     // last h ==> hn-2\n                    A(row_idx+r, col_idx+c+6) = C2(r,c);\n                }\n            }\n            col_idx += 6;\n            row_idx += 5;\n        } //all row s are filled\n\n\n        //====================================check for stop points:==================================\n\n\n        //>>>>>>>>>>>step_5: fill B vector B\n        B(0) = pos(0);\n        B(1) = vel0;\n        B(2) = acc0; //  3 rows so far\n        for (int i=1; i< n-1; i++) // all pos from pos1 to pos(n-1)= (n-2) rows\n            B(i+2)= pos(i); // so far 3+n-2 = n+1\n\n        for (int i=n+4; i< n_eqs; i++) // last 5(n-2) ros\n            B(i)= 0; // so far 3+n-2 = n+1\n\n        B(n+1) = pos(n-1);\n        B(n+2) = veln;\n        B(n+3) = accn;\n        ROS_INFO_STREAM(\"B vector: \\n\"<<B);\n\n\n        //find the solution: using matirx inverse\n        //   MatrixXd A_inv = A.inverse();\n        //   X = A.inverse()*B;  // some times gives nan or inf\n        //   ROS_INFO_STREAM(\"X vector: \\n\"<<X);\n\n        HouseholderQR<MatrixXd> qr(A);\n        X = qr.solve(B); // computes A^-1 * b\n        ROS_INFO_STREAM(\"X vector: \\n\"<<X );\n\n\n\n        // extract spline coefs from the vector  ========================================================\n        std::vector<double> a, b, c, d, e, f;\n        for (int i = 0; i < n_eqs; i+=6) {\n            a.push_back( X(i) );\n            b.push_back( X(i+1) );\n            c.push_back( X(i+2) );\n            d.push_back( X(i+3) );\n            e.push_back( X(i+4) );\n            f.push_back( X(i+5) );\n        }\n\n\n        // sample trajectory using sample func: create variables,  sampling T_vec, Coef_mtrx\n        std::vector<double> T_vec;\n        T_vec.resize(n);\n        for (int i=0; i< n; i++) {\n            T_vec[i] = t(i);\n        }\n        std::vector<double> POS, VEL, ACC, JRK, T;\n        std::vector<std::vector<double>> cof_mtrx;\n        cof_mtrx.push_back(a);\n        cof_mtrx.push_back(b);\n        cof_mtrx.push_back(c);\n        cof_mtrx.push_back(d);\n        cof_mtrx.push_back(e);\n        cof_mtrx.push_back(f);\n        std::vector<double> state;\n        state.resize(4);\n        // states at each intermdiate times\n        double frq =125, tg=0;\n        while (tg< T_vec[n-1]) {\n            sample(T_vec, tg, cof_mtrx, state);\n            //    std::cout<< \"state:\"<< \"p= \"<< state[0]<<\"   v= \"<< state[1]<<\"   a= \"<< state[2]<<\"  j= \"<< state[3] ;\n            T.push_back(tg);\n            POS.push_back( state[0]);\n            VEL.push_back( state[1]);\n            ACC.push_back( state[2]);\n            JRK.push_back( state[3]);\n            tg += 1/frq;\n        }\n\n\n        // states at waypoints and check limit conditions\n        lmtd_jrk = true;\n        std::vector<std::vector<double>> wpt_states;\n        wpt_states.resize(4);\n        for (int pt = 0; pt < n; ++pt) {\n            tg= T_vec[pt];\n            sample(T_vec, tg, cof_mtrx, state);\n            wpt_states[0].push_back( state[0] );\n            wpt_states[1].push_back( state[1] );\n            wpt_states[2].push_back( state[2] );\n            wpt_states[3].push_back( state[3] );\n            std::cout<< \"jrk[\"<<pt<<\"]= \"<< state[3] ;\n            if(  state[3] > 1000 || state[3] < -1000 ){\n                seg_idx.push_back( pt);\n                lmtd_jrk = false;\n            }\n        }\n        // ROS_INFO( \"waypoints times:    \");\n        // for (int i=0; i< n; i++ )\n        //    ROS_INFO_STREAM( \"    \"<< T_vec[i] );\n        // ROS_INFO( \"segment peroids:    \");\n        // for (int i=0; i< n-1; i++ )\n        //    ROS_INFO_STREAM( \"    \"<< h[i] );\n\n        // plot section =================================\n        count++;\n        int plot_per_loop = 3; //to plot 9 iteration to fit on sbplts number\n        int sbplt_rows= 3, sbplt_cols= 3;\n        bool pos_plt=false, vel_plt=true, acc_plt=true, jrk_plt = false;// select states to plot\n        pos_plt=false, vel_plt=false, acc_plt=false, jrk_plt = true;\n        std::string  sbplt_name;\n\n        //   here choose few iterations, plot them  in subplot\n        if(  (count)%plot_per_loop == 0 ){\n            plt::figure(1);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop   );\n            plt::plot( T, POS);\n            plt::plot( T_vec, wpt_states[0],\"r*\");\n            sbplt_name= \"pos_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n            plt::figure(2);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop   );\n            plt::plot(  T, VEL);\n            plt::plot( T_vec, wpt_states[1],\"r*\");\n            sbplt_name= \"vel_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n            plt::figure(3);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop   );\n            plt::plot(  T, ACC);\n            plt::plot( T_vec, wpt_states[2],\"r*\");\n            sbplt_name= \"acc_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n            plt::figure(4);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop   );\n            plt::plot(  T, JRK);\n            plt::plot( T_vec, wpt_states[3],\"r*\");\n            sbplt_name= \"jrk_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n            //    plt::legend(); // Enable legend.\n\n        }\n        if(lmtd_jrk){ // to plot last iteration\n            plt::figure(1);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop  +1);\n            plt::plot( T, POS);\n            plt::plot( T_vec, wpt_states[0],\"r*\");\n            sbplt_name= \"pos_last_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n\n            plt::figure(2);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop    +1);\n            plt::plot(  T, VEL);\n            plt::plot( T_vec, wpt_states[1],\"r*\");\n            sbplt_name= \"vel_last_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n\n            plt::figure(3);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop    +1);\n            plt::plot(  T, ACC);\n            plt::plot( T_vec, wpt_states[2],\"r*\");\n            sbplt_name= \"acc_last_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n\n            plt::figure(4);\n            plt::subplot(  sbplt_rows, sbplt_cols,count/plot_per_loop    +1);\n            plt::plot(  T, JRK);\n            plt::plot( T_vec, wpt_states[3],\"r*\");\n            sbplt_name= \"jrk_last_iter_\" + std::to_string(count);\n            plt::title(  sbplt_name);\n            plt::grid(true);\n\n            //    plt::legend(); // Enable legend.\n        }\n        ROS_INFO_STREAM(\"#iteration= \"<<count <<\"is_lmtd_jrk: \"<< lmtd_jrk);\n    }\n\n    ROS_INFO_STREAM(\"#loops= \"<<count);\n    plt::show();\n\n\n}\n\n", "meta": {"hexsha": "d5c942112072ab3b4c4d84d78b5364cac4ed9c82", "size": 17222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/isp_quintic/src/quintic_isp.cpp", "max_stars_repo_name": "mahmoud-a-ali/quintic_isp", "max_stars_repo_head_hexsha": "20a704d5b005ecf728fed9ab59559fcb83c07ed1", "max_stars_repo_licenses": ["MIT"], "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/isp_quintic/src/quintic_isp.cpp", "max_issues_repo_name": "mahmoud-a-ali/quintic_isp", "max_issues_repo_head_hexsha": "20a704d5b005ecf728fed9ab59559fcb83c07ed1", "max_issues_repo_licenses": ["MIT"], "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/isp_quintic/src/quintic_isp.cpp", "max_forks_repo_name": "mahmoud-a-ali/quintic_isp", "max_forks_repo_head_hexsha": "20a704d5b005ecf728fed9ab59559fcb83c07ed1", "max_forks_repo_licenses": ["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.5279642058, "max_line_length": 220, "alphanum_fraction": 0.4907676228, "num_tokens": 5372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6529351577915006}}
{"text": "#ifndef _glia_type_bignum_hxx_\n#define _glia_type_bignum_hxx_\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"glia_base.hxx\"\n\nnamespace glia {\n\ntypedef boost::multiprecision::int512_t BigInt;\ntypedef boost::multiprecision::cpp_dec_float_100 BigFloat;\n\n};\n\n#endif\n", "meta": {"hexsha": "85b6b3d1ec9487be007f9fd698ca90985f5679c1", "size": 320, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/type/big_num.hxx", "max_stars_repo_name": "lejeunel/glia", "max_stars_repo_head_hexsha": "24b763a230627951139010cd07b0d0ff2356a365", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-08-16T02:26:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T06:51:47.000Z", "max_issues_repo_path": "src/type/big_num.hxx", "max_issues_repo_name": "lejeunel/glia", "max_issues_repo_head_hexsha": "24b763a230627951139010cd07b0d0ff2356a365", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-05-26T15:33:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-27T12:12:24.000Z", "max_forks_repo_path": "src/type/big_num.hxx", "max_forks_repo_name": "lejeunel/glia", "max_forks_repo_head_hexsha": "24b763a230627951139010cd07b0d0ff2356a365", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-07-25T08:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T15:02:41.000Z", "avg_line_length": 20.0, "max_line_length": 58, "alphanum_fraction": 0.81875, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6529253777825543}}
{"text": "//\n// Created by Vlad Argunov on 10/01/2022.\n//\n\n#include \"HestonOption.h\"\n\n#include <Eigen/Dense>\n#include <random>\n#include <string>\n#include <cmath>\n#include <tuple>\n#include <algorithm>\n#include \"Simulation.h\"\n\nHestonOption::HestonOption(std::string type_option_, double tn_, int n_processes_, int n_steps_, double strike_) {\n    sim = Simulation();\n    type_option = type_option_;\n    tn = tn_;\n    n_processes = n_processes_;\n    n_steps = n_steps_;\n    strike = strike_;\n}\n\nvoid HestonOption::set_params_stock_process(double stock_price_start_, double mu_) {\n    stock_price_start = stock_price_start_;\n    mu = mu_;\n}\n\nvoid HestonOption::set_prams_variance_process(double variance_start_, double kappa_, double theta_, double sigma_,\n                                              double rho_) {\n    variance_start = variance_start_;\n    kappa = kappa_;\n    theta = theta_;\n    sigma = sigma_;\n    rho = rho_;\n}\n\ndouble HestonOption::compute_price() {\n    auto [stocks, _] = sim.generate_heston_process(n_processes, tn, stock_price_start, mu, variance_start, kappa, theta, sigma, rho, n_steps);\n    Eigen::Index stocks_cols = stocks.cols();\n    double total_payoffs = 0;\n    for (int row = 0; row < stocks.rows(); ++row) {\n        if (type_option == \"Call\"){\n            total_payoffs += std::max(stocks(row,stocks_cols - 1) - strike, 0.0);\n        }\n        if (type_option == \"Put\"){\n            total_payoffs += std::max(strike - stocks(row,stocks_cols), 0.0);\n        }\n    }\n    return exp(- mu * tn) * total_payoffs / n_processes;\n}\n", "meta": {"hexsha": "077381559446dc03e8f14f5ecd3ec86d5189cabc", "size": 1546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HestonOption.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HestonOption.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HestonOption.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7307692308, "max_line_length": 142, "alphanum_fraction": 0.6520051746, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6529253723680409}}
{"text": "/**\n * @file convolutional_network_test.cpp\n * @author Marcus Edel\n *\n * Tests the convolutional neural network.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n\n#include <mlpack/methods/ann/layer/one_hot_layer.hpp>\n#include <mlpack/methods/ann/layer/conv_layer.hpp>\n#include <mlpack/methods/ann/layer/pooling_layer.hpp>\n#include <mlpack/methods/ann/layer/softmax_layer.hpp>\n#include <mlpack/methods/ann/layer/bias_layer.hpp>\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/core/optimizers/rmsprop/rmsprop.hpp>\n\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/cnn.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\nusing namespace mlpack::optimization;\n\n\nBOOST_AUTO_TEST_SUITE(ConvolutionalNetworkTest);\n\n/**\n * Train and evaluate a vanilla network with the specified structure.\n */\ntemplate<\n    typename PerformanceFunction\n>\nvoid BuildVanillaNetwork()\n{\n  arma::mat X;\n  X.load(\"mnist_first250_training_4s_and_9s.arm\");\n\n  // Normalize each point since these are images.\n  arma::uword nPoints = X.n_cols;\n  for (arma::uword i = 0; i < nPoints; i++)\n  {\n    X.col(i) /= norm(X.col(i), 2);\n  }\n\n  // Build the target matrix.\n  arma::mat Y = arma::zeros<arma::mat>(10, nPoints);\n  for (size_t i = 0; i < nPoints; i++)\n  {\n    if (i < nPoints / 2)\n    {\n      Y.col(i)(5) = 1;\n    }\n    else\n    {\n      Y.col(i)(8) = 1;\n    }\n  }\n\n  arma::cube input = arma::cube(28, 28, nPoints);\n  for (size_t i = 0; i < nPoints; i++)\n    input.slice(i) = arma::mat(X.colptr(i), 28, 28);\n\n  /*\n   * Construct a convolutional neural network with a 28x28x1 input layer,\n   * 24x24x8 convolution layer, 12x12x8 pooling layer, 8x8x12 convolution layer\n   * and a 4x4x12 pooling layer which is fully connected with the output layer.\n   * The network structure looks like:\n   *\n   * Input    Convolution  Pooling      Convolution  Pooling      Output\n   * Layer    Layer        Layer        Layer        Layer        Layer\n   *\n   *          +---+        +---+        +---+        +---+\n   *          | +---+      | +---+      | +---+      | +---+\n   * +---+    | | +---+    | | +---+    | | +---+    | | +---+    +---+\n   * |   |    | | |   |    | | |   |    | | |   |    | | |   |    |   |\n   * |   +--> +-+ |   +--> +-+ |   +--> +-+ |   +--> +-+ |   +--> |   |\n   * |   |      +-+   |      +-+   |      +-+   |      +-+   |    |   |\n   * +---+        +---+        +---+        +---+        +---+    +---+\n   */\n\n  ConvLayer<> convLayer0(1, 8, 5, 5);\n  BiasLayer2D<> biasLayer0(8);\n  BaseLayer2D<> baseLayer0;\n  PoolingLayer<> poolingLayer0(2);\n\n  ConvLayer<> convLayer1(8, 12, 5, 5);\n  BiasLayer2D<> biasLayer1(12);\n  BaseLayer2D<> baseLayer1;\n  PoolingLayer<> poolingLayer1(2);\n\n  LinearMappingLayer<> linearLayer0(192, 10);\n  BiasLayer<> biasLayer2(10);\n  SoftmaxLayer<> softmaxLayer0;\n\n  OneHotLayer outputLayer;\n\n  auto modules = std::tie(convLayer0, biasLayer0, baseLayer0, poolingLayer0,\n                          convLayer1, biasLayer1, baseLayer1, poolingLayer1,\n                          linearLayer0, biasLayer2, softmaxLayer0);\n\n  CNN<decltype(modules), decltype(outputLayer),\n      RandomInitialization, MeanSquaredErrorFunction> net(modules, outputLayer);\n  biasLayer0.Weights().zeros();\n  biasLayer1.Weights().zeros();\n\n  RMSprop<decltype(net)> opt(net, 0.01, 0.88, 1e-8, 10 * input.n_slices, 0);\n\n  net.Train(input, Y, opt);\n\n  arma::mat prediction;\n  net.Predict(input, prediction);\n\n  size_t error = 0;\n  for (size_t i = 0; i < nPoints; i++)\n  {\n    if (arma::sum(arma::sum(\n        arma::abs(prediction.col(i) - Y.col(i)))) == 0)\n    {\n      error++;\n    }\n  }\n\n  double classificationError = 1 - double(error) / nPoints;\n  BOOST_REQUIRE_LE(classificationError, 0.6);\n}\n\n/**\n * Train the vanilla network on a larger dataset.\n */\nBOOST_AUTO_TEST_CASE(VanillaNetworkTest)\n{\n  BuildVanillaNetwork<LogisticFunction>();\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1ca68c2dee5d6b6cf21587be140d05330422de57", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack2", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack2", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/convolutional_network_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack2", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8611111111, "max_line_length": 80, "alphanum_fraction": 0.6068334937, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.652925366801913}}
{"text": "#include \"blas.h\"\n#include \"mlfe/device_context/cpu_context.h\"\n#include <Eigen/Dense>\n\nnamespace mlfe{ namespace math{\n\ntemplate<>\nvoid gemm<float, CPUContext>(const bool trans_a,\n                             const bool trans_b,\n                             const int m,\n                             const int n,\n                             const int k,\n                             const float alpha,\n                             const float *a_ptr,\n                             const int lda,\n                             const float *b_ptr,\n                             const int ldb,\n                             const float beta,\n                             float *c_ptr,\n                             const int ldc,\n                             CPUContext *context\n                            )\n{\n    using ConstMapMatXf = Eigen::Map<const Eigen::MatrixXf>;\n    Eigen::Map<Eigen::MatrixXf> c(c_ptr, n, m);\n    if(beta == 0.f){\n        c.setZero();\n    }\n    else{\n        c *= beta;\n    }\n    if(!trans_a && !trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n                                ConstMapMatXf(a_ptr, k, m)\n                               );\n    }\n    else if(trans_a && !trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n                                ConstMapMatXf(a_ptr, m, k).transpose()\n                               );\n    }\n    else if(!trans_a && trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n                                ConstMapMatXf(a_ptr, k, m)\n                               );\n    }\n    else{\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n                                ConstMapMatXf(a_ptr, m, k).transpose()\n                               );\n    }\n}\n\ntemplate<>\nvoid gemm<double, CPUContext>(const bool trans_a,\n                              const bool trans_b,\n                              const int m,\n                              const int n,\n                              const int k,\n                              const double alpha,\n                              const double *a_ptr,\n                              const int lda,\n                              const double *b_ptr,\n                              const int ldb,\n                              const double beta,\n                              double *c_ptr,\n                              const int ldc,\n                              CPUContext *context\n                             )\n{\n    using ConstMapMatXf = Eigen::Map<const Eigen::MatrixXd>;\n    Eigen::Map<Eigen::MatrixXd> c(c_ptr, n, m);\n    if(beta == 0.){\n        c.setZero();\n    }\n    else{\n        c *= beta;\n    }\n    if(!trans_a && !trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n                                ConstMapMatXf(a_ptr, k, m)\n                               );\n    }\n    else if(trans_a && !trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n                                ConstMapMatXf(a_ptr, m, k).transpose()\n                               );\n    }\n    else if(!trans_a && trans_b){\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n                                ConstMapMatXf(a_ptr, k, m)\n                               );\n    }\n    else{\n        c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n                                ConstMapMatXf(a_ptr, m, k).transpose()\n                               );\n    }\n}\n\ntemplate <>\nvoid gemv<float, CPUContext>(const bool trans_a,\n                             const int m,\n                             const int n,\n                             const float alpha,\n                             const float *a_ptr,\n                             const int lda,\n                             const float *b_ptr,\n                             const float beta,\n                             float *c_ptr,\n                             const int ldc,\n                             CPUContext *context\n                            )\n{\n    using ConstMapMatXf = Eigen::Map<const Eigen::MatrixXf>;\n    using ConstMapVecXf = Eigen::Map<const Eigen::VectorXf>;\n    Eigen::Map<Eigen::VectorXf> c(c_ptr, !trans_a ? m : n);\n    if(beta == 0.f){\n        c.setZero();\n    }\n    else{\n        c *= beta;\n    }\n\n    if(!trans_a){\n        c.noalias() += alpha * (ConstMapMatXf(a_ptr, n, m).transpose() *\n                                ConstMapVecXf(b_ptr, n)\n                                );\n    }\n    else{\n        c.noalias() += alpha * (ConstMapMatXf(a_ptr, n, m) *\n                                ConstMapVecXf(b_ptr, m)\n                                );\n    }\n}\n\ntemplate <>\nvoid gemv<double, CPUContext>(const bool trans_a,\n                              const int m,\n                              const int n,\n                              const double alpha,\n                              const double *a_ptr,\n                              const int lda,\n                              const double *b_ptr,\n                              const double beta,\n                              double *c_ptr,\n                              const int ldc,\n                              CPUContext *context\n                             )\n{\n    using ConstMapMatXf = Eigen::Map<const Eigen::MatrixXd>;\n    using ConstMapVecXf = Eigen::Map<const Eigen::VectorXd>;\n    Eigen::Map<Eigen::VectorXd> c(c_ptr, !trans_a ? m : n);\n    if(beta == 0.){\n        c.setZero();\n    }\n    else{\n        c *= beta;\n    }\n\n    if(!trans_a){\n        c.noalias() += alpha * (\n                                ConstMapMatXf(a_ptr, n, m).transpose() *\n                                ConstMapVecXf(b_ptr, n)\n                                );\n    }\n    else{\n        c.noalias() += alpha * (\n                                ConstMapMatXf(a_ptr, n, m) *\n                                ConstMapVecXf(b_ptr, m)\n                                );\n    }\n}\n\n} // end namespace math\n} // end namespace mlfe\n", "meta": {"hexsha": "6b991ea42792f9d67575745759b9f115ec7d7336", "size": 5969, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mlfe/math/blas.cc", "max_stars_repo_name": "shi510/mlfe", "max_stars_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T11:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T18:25:11.000Z", "max_issues_repo_path": "mlfe/math/blas.cc", "max_issues_repo_name": "shi510/mlfe", "max_issues_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlfe/math/blas.cc", "max_forks_repo_name": "shi510/mlfe", "max_forks_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T12:40:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T05:23:36.000Z", "avg_line_length": 33.7231638418, "max_line_length": 72, "alphanum_fraction": 0.3786228849, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6528952306853628}}
{"text": "// Simple Kalman Filter implementation for one-dimensional processes\n// Author: Marcell Missura <missura@ais.uni-bonn.de>\n// Modified for Eigen by Max Schwarz <max.schwarz@uni-bonn.de>\n\n#include <rc_utils/kalmanfilter.h>\n#include <Eigen/LU>\n\nnamespace rc_utils\n{\n\nKalmanFilter::KalmanFilter()\n : m_smoothing(0.3)\n , m_timeStep(DefaultTimeStep)\n , m_lastZ(0)\n , m_px(0)\n , m_pv(0)\n{\n\tinit();\n}\n\nKalmanFilter::~KalmanFilter()\n{\n}\n\nvoid KalmanFilter::init()\n{\n\t// Process noise\n\tm_Q = Eigen::Matrix2d::Identity();\n\n\t// Measurement noise\n\tm_R << 0.001 + m_smoothing*100.0, 0.0,\n\t       0.0,                       0.001 + m_smoothing*100.0;\n\n\t// Passive linear system dynamics matrix A\n\tm_A << 1.0, m_timeStep,\n\t       0.0, 1.0;\n\n\t// State and measurement vectors\n\tm_X << 0.0, 0.0;\n\n\tm_H = m_I = m_K = m_P = Eigen::Matrix2d::Identity();\n}\n\nvoid KalmanFilter::reset()\n{\n\tm_K = Eigen::Matrix2d::Identity();\n\tm_P = Eigen::Matrix2d::Zero();\n}\n\nvoid KalmanFilter::update(double z)\n{\n\tm_Z << z, (z - m_lastZ) / m_timeStep;\n\n\tm_X = m_A * m_X;\n\tm_P = m_A * m_P * m_A.transpose() + m_Q;\n\tm_K = m_P * m_H.transpose() * (m_H * m_P * m_H.transpose() + m_R).inverse();\n\tm_X = m_X + m_K * (m_Z - m_H * m_X);\n\tm_P = (m_I - m_K * m_H) * m_P;\n\n\tm_lastZ = z;\n\n\tm_px = m_P(0,0);\n\tm_pv = m_P(1,1);\n}\n\nvoid KalmanFilter::setState(double pos, double vel)\n{\n\tm_X << pos, vel;\n\tm_lastZ = pos;\n}\n\n}\n\n", "meta": {"hexsha": "ef6c97bb06fac1500243d85994b415d733c8a6a2", "size": 1370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_stars_repo_name": "nvtienanh/UXA_OP", "max_stars_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-22T08:15:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T07:18:50.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_issues_repo_name": "nvtienanh/UXA_OP", "max_issues_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_forks_repo_name": "nvtienanh/UXA_OP", "max_forks_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5135135135, "max_line_length": 77, "alphanum_fraction": 0.6291970803, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6528952093255118}}
{"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, Part 1. \n//   Pearson Education Inc., 2011.\n\n#ifndef COMBINATION_ITERATOR_HPP\n#define COMBINATION_ITERATOR_HPP\n\n#include <vector>\n#include <numeric>\n#include <cassert>\n#include <cstdint>\n\n#include <boost/iterator/iterator_facade.hpp>\n\ntemplate <typename T>\nclass combination_iterator\n\t: public boost::iterator_facade<\n\tcombination_iterator<T>,\n\tconst std::vector<T>&,\n\tboost::forward_traversal_tag\n\t>\n{\npublic:\n\tcombination_iterator() : end_(true), n_(0), size_(0), comb_() { }\n\n\texplicit combination_iterator(T n, T k) : end_(false), n_(n), size_(k), comb_(k)\n\t{\n\t\tassert(k != 0 && n_ > k);\n\t\tstd::iota(comb_.begin(), comb_.end(), 0);\n\t\tassert(!end_);\n\t}\n\nprivate:\n\tfriend class boost::iterator_core_access;\n\n\tvoid increment()\n\t{\n\t\tstd::int64_t j = size_ - 1;\n\n\t\tfor (const T end = n_ - size_; j >= 0 && comb_[j] >= end + j; --j) { }\n\n\t\tif (j < 0)\n\t\t{\n\t\t\tassert(comb_.front() == n_ - size_);\n\t\t\tend_ = true;\n\t\t\treturn;\n\t\t}\n\n\t\t++comb_[j];\n\n\t\tfor (const std::int64_t end = size_ - 1; j < end; ++j)\n\t\t{\n\t\t\tcomb_[j + 1] = comb_[j] + 1;\n\t\t}\n\n\t\treturn;\n\t}\n\n\tbool equal(const combination_iterator& other) const\n\t{\n\t\treturn end_ == other.end_;\n\t}\n\n\tconst std::vector<T>& dereference() const\n\t{\n\t\treturn comb_;\n\t}\n\n\tbool end_;\n\tconst int n_;\n\tconst int size_;\n\tstd::vector<T> comb_;\n};\n\n#endif\n", "meta": {"hexsha": "347795c538ff6300d9b698a56aed3368d5fcfb18", "size": 1605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "combination_iterator.hpp", "max_stars_repo_name": "euler314/combinatorics", "max_stars_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-12T22:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-21T13:16:09.000Z", "max_issues_repo_path": "combination_iterator.hpp", "max_issues_repo_name": "euler314/combinatorics", "max_issues_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "combination_iterator.hpp", "max_forks_repo_name": "euler314/combinatorics", "max_forks_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T18:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T18:32:14.000Z", "avg_line_length": 19.5731707317, "max_line_length": 83, "alphanum_fraction": 0.6554517134, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6528737403366549}}
{"text": "#include \"ukf.hpp\"\n#include \"house.hpp\"\n#include \"eigen_csv.hpp\"\n#include \"timer.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <random>\n#include <vector>\n#include <string>\n\nusing namespace Eigen;\nusing namespace std;\n\n// One degree (in radians)\nconst double deg = M_PI / 180;\n\n// Dynamical model\nVectorXd ct_prop(double ti, double tf, const VectorXd& x, const VectorXd& w) {\n    VectorXd xf(5);\n    double W = x(4);\n    double T = tf - ti;\n    /*if (fabs(W) < 1E-9) {\n        xf = x;\n        xf(0) += T * xf(1);\n        xf(2) += T * xf(3);\n    } else {*/\n        double sinWT = sin(W*T);\n        double cosWT = cos(W*T);\n        MatrixXd F(5,5);\n        F << 1, sinWT/W,     0, -(1-cosWT)/W, 0,\n             0, cosWT,       0, -sinWT,       0,\n             0, (1-cosWT)/W, 1, sinWT/W,      0,\n             0, sinWT,       0, cosWT,        0,\n             0, 0,           0, 0,            1;\n        xf = F * x;\n    //}\n    return xf + w;\n}\n\n// Measurement model\nVector2d ct_meas(double t, const VectorXd& x) {\n\n    Vector2d z;\n\n    double xi  = x(0);\n    double eta = x(2);\n\n    z << sqrt(xi*xi + eta*eta), atan2(eta, xi);\n\n    return z;\n\n}\n\n// True state as function of time\nVectorXd ct_tru(double t) {\n\n    const double v  = 120;\n    const double w1 =  1 * deg;\n    const double w2 = -3 * deg;\n    const double r1 = fabs(v / w1);\n    const double r2 = fabs(v / w2);\n    const double t1 = 90;\n    const double t2 = 30;\n    const double tl = 125;\n    const double l  = v * tl;\n    const double x0 = 25000;\n    const double y0 = 10000;\n\n    VectorXd x(5);\n    double dt, xc, yc;\n\n    if (t <= tl) {\n        x(0) = x0 - v * t;\n        x(2) = y0;\n        x(1) = -v;\n        x(3) = 0;\n        x(4) = 0;\n    } else if (t <= tl + t1) {\n        dt = t - tl;\n        xc = x0 - l;\n        yc = y0 - r1;\n        x(0) =  xc + r1 * cos(w1 * dt + M_PI/2);\n        x(2) =  yc + r1 * sin(w1 * dt + M_PI/2);\n        x(1) = -w1 * r1 * sin(w1 * dt + M_PI/2);\n        x(3) =  w1 * r1 * cos(w1 * dt + M_PI/2);\n        x(4) =  w1;\n    } else if (t <= 2*tl + t1) {\n        dt = t - tl - t1;\n        x(0) = x0 - l - r1;\n        x(2) = y0 - r1 - v * dt;\n        x(1) = 0;\n        x(3) = -v;\n        x(4) = 0;\n    } else if (t <= 2*tl + t1 + t2) {\n        dt = t - 2*tl - t1;\n        xc = x0 - l - r1 - r2;\n        yc = y0 - l - r1;\n        x(0) =  xc + r2 * cos(w2 * dt);\n        x(2) =  yc + r2 * sin(w2 * dt);\n        x(1) = -w2 * r2 * sin(w2 * dt);\n        x(3) =  w2 * r2 * cos(w2 * dt);\n        x(4) =  w2;\n    } else {\n        dt = t - 2*tl - t1 - t2;\n        x(0) = x0 - l - r1 - r2 - v*dt;\n        x(2) = y0     - r1 - r2 - l;\n        x(1) = -v;\n        x(3) = 0;\n        x(4) = 0;\n    }\n\n    return x;\n\n}\n\n// Generate filename for state estimates\nstd::string est_filename(const std::string& filter, int i, int j) {\n    std::string f = \"out/ct_est_\";\n    f += filter;\n    f += \"_\";\n    f += std::to_string(i+1);\n    f += \"_\";\n    f += std::to_string(j+1);\n    f += \".csv\";\n    return f;\n}\n\nint main() {\n\n    // CUT directory\n    UKF::cut_dir = \"../CUT/\";\n\n    // UKF state & measurement models\n    UKF::dyn_model f = ct_prop;\n    UKF::meas_model h = ct_meas;\n\n    // HOUSE measurement model\n    HOUSE::meas_model hh = [] (double t, const VectorXd& x, const VectorXd& n)\n        -> VectorXd {\n            return ct_meas(t, x) + n;\n        };\n\n    // Constants\n    double sr, sth, l1, l2;\n    sr  = 100;\n    sth = 1 * deg;\n    l1  = 0.16;\n    l2  = 0.01;\n\n    // Measurement noise covariance\n    Matrix2d R;\n    R << sr*sr, 0,\n         0,     sth*sth;\n\n    // Prior mean & covariance\n    VectorXd mxi(5), cxx(5);\n    cxx << 1000, 10, 1000, 10, 1*deg;\n    mxi << 25000, -120, 10000, 0, 0.000001;\n    MatrixXd Pxxi = cxx.cwiseAbs2().asDiagonal();\n\n    // HOUSE distributions\n    HOUSE::Dist distXi(Pxxi), distn(R);\n    distXi.mean = mxi;\n\n    // Normal noise generator\n    mt19937_64 mt;\n    normal_distribution<double> nd;\n\n    // Time step lengths\n    const int Ntimes = 4;\n    VectorXd Ts(Ntimes);\n    Ts << 1, 2.5, 3.9, 5;\n    //Ts.setLinSpaced(Ntimes, 1, 5);\n\n    // Save time step lengths\n    EigenCSV::write(Ts, \"out/times.csv\");\n\n    // Number of tests\n    const int Ntest = 100;\n\n    // Timer\n    Timer timer;\n\n    // Average runtime table\n    MatrixXd runtime_table(Ntimes, 6);\n    runtime_table.col(0) = Ts;\n\n    // Run tests for various time step lengths\n    for (int i = 0; i < Ntimes; i++) {\n\n        // Time step\n        double T = Ts(i);\n\n        //cout << \"-------------------------------------------\" << endl;\n        cout << \"Running T = \" << T << \" s\" << endl;\n        //cout << \"-------------------------------------------\" << endl;\n\n        // Times\n        double Ttot = 125 + 90 + 125 + 30 + 125;\n        int steps = (int) ceil(Ttot / T);\n        VectorXd t(steps);\n        t.setLinSpaced(steps, 0, T*(steps-1));\n\n        // True states\n        vector<VectorXd> Xtru;\n        for (int k = 0; k < steps; k++)\n            Xtru.push_back(ct_tru(t(k)));\n\n        // Save true states\n        MatrixXd xtru_table(steps, 6);\n        xtru_table.col(0) = t;\n        for (int k = 0; k < steps; k++)\n            xtru_table.row(k).tail(5) = Xtru[k];\n        string filename = \"out/ct_true_\";\n        filename += to_string(i+1);\n        filename += \".csv\";\n        vector<string> header(6);\n        header[0] = \"Time (s)\";\n        header[1] = \"x (m)\";\n        header[2] = \"xd (m/s)\";\n        header[3] = \"y (m)\";\n        header[4] = \"yd (m/s)\";\n        header[5] = \"Omega (rad/s)\";\n        EigenCSV::write(xtru_table, header, filename);\n\n        // Process noise covariance\n        double t22 = T * T / 2;\n        double t33 = T * T * T / 3;\n        MatrixXd Q(5,5);\n        Q << t33, t22, 0,   0,   0,\n             t22, T,   0,   0,   0,\n             0,   0,   t33, t22, 0,\n             0,   0,   t22, T,   0,\n             0,   0,   0,   0,   (l2/l1)*T;\n        Q *= l1;\n\n        // HOUSE process noise distributions\n        HOUSE::Dist distw(Q);\n\n        // Initialize UKF & CUT filters\n        UKF ukf (f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::JU,   1);\n        UKF cut4(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT4, 1);\n        UKF cut6(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT6, 1);\n        UKF cut8(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT8, 1);\n\n        // Initialize HOUSE\n        HOUSE house(f, hh, 2, 0, distXi, distw, distn, 0.1);\n\n        // Runtimes\n        MatrixXd runtime(5, Ntest);\n\n        // Run multiple tests\n        for (int j = 0; j < Ntest; j++) {\n\n            //cout << \"Running Trial \" << j+1 << endl;\n\n            // Reset filters\n            ukf.reset(0, mxi, Pxxi);\n            cut4.reset(0, mxi, Pxxi);\n            cut6.reset(0, mxi, Pxxi);\n            cut8.reset(0, mxi, Pxxi);\n            house.reset(0, distXi);\n\n            // Measurements\n            MatrixXd Ztru(2,steps);\n            for (int k = 0; k < steps; k++) {\n                Ztru.col(k) = ct_meas(t(k), Xtru[k]);\n                Ztru(0,k) += sr  * nd(mt);\n                Ztru(1,k) += sth * nd(mt);\n            }\n\n            // Run UKF\n            //cout << \"    UKF\" << endl;\n            timer.tick();\n            ukf.run(t, Ztru);\n            runtime(0, j) = timer.tock();\n            ukf.save(est_filename(\"ukf\", i, j));\n\n            // Run CUT-4\n            //cout << \"    CUT-4\" << endl;\n            timer.tick();\n            cut4.run(t, Ztru);\n            runtime(1, j) = timer.tock();\n            cut4.save(est_filename(\"cut4\", i, j));\n\n            // Run CUT-6\n            //cout << \"    CUT-6\" << endl;\n            timer.tick();\n            cut6.run(t, Ztru);\n            runtime(2, j) = timer.tock();\n            cut6.save(est_filename(\"cut6\", i, j));\n\n            // Run CUT-8\n            //cout << \"    CUT-8\" << endl;\n            timer.tick();\n            cut8.run(t, Ztru);\n            runtime(3, j) = timer.tock();\n            cut8.save(est_filename(\"cut8\", i, j));\n\n            // Run HOUSE\n            //cout << \"    HOUSE\" << endl;\n            timer.tick();\n            house.run(t, Ztru);\n            runtime(4, j) = timer.tock();\n            house.save(est_filename(\"house\", i, j));\n\n        }\n\n        // Average runtimes\n        runtime_table.row(i).tail(5) = runtime.rowwise().mean();\n\n    }\n\n    // Save average runtimes\n    vector<string> rth(6);\n    rth[0] = \"STEP\";\n    rth[1] = \"UKF\";\n    rth[2] = \"CUT-4\";\n    rth[3] = \"CUT-6\";\n    rth[4] = \"CUT-8\";\n    rth[5] = \"HOUSE\";\n    EigenCSV::write(runtime_table, rth, \"out/runtimes.csv\");\n\n    return 0;\n\n}\n", "meta": {"hexsha": "988cabb2a47ed3e418925f3beee94b497a29035f", "size": 8515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CT_Gauss/CT.cpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CT_Gauss/CT.cpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CT_Gauss/CT.cpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["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.8814589666, "max_line_length": 78, "alphanum_fraction": 0.4488549618, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6528688003567672}}
{"text": "// Copyright (c) 2020-2021 The PoWx Core developers\n\n#include <crypto/heavyhash_dummyArray.h>\n\n#include <matrix-utils/singular/Svd.h>\n#include <test/util/setup_common.h>\n#include <boost/test/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(singular_tests, BasicTestingSetup)\n\nusing namespace std;\nconst int N = 4;\nconst int M = 64;\nconst double DATA[] = {\n        1, 7, 7, 5,\n        2, 1, 8, 10,\n        1, 2, 9, 17,\n        1, 2, 10, 2\n};\n\nconst double WRONG_DATA1[] = {\n        1, 7, 7, 5,\n        1, 7, 7, 5,\n        1, 2, 9, 17,\n        1, 2, 10, 2\n};\n\n\nconst double WRONG_DATA2[] = {\n        0, 0, 0, 0,\n        0, 0, 0, 0,\n        0, 0, 0, 0,\n        0, 0, 0, 0\n};\n\nstatic bool CheckCompatibility(const double *data) {\n    singular::Matrix< N, N > matrix;\n    matrix.fill(data);\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            if (data[i * N + j] != matrix(i, j))\n                return false;\n        }\n    }\n    return true;\n}\n\nstatic bool CheckMatrixRank4x4(const double *data) {\n    singular::Matrix< N, N > matrix;\n    matrix.fill(data);\n    singular::Svd< N, N >::USV usv = singular::Svd< N, N >::decomposeUSV(matrix);\n    const singular::DiagonalMatrix< N, N >& sing = singular::Svd< N, N >::getS(usv);\n    cout << sing << endl;\n    cout << endl;\n    return singular::Svd< N, N >::isFullRank(sing, N);\n}\n\n\nstatic bool CheckMatrixRank64x64(const double *data) {\n    singular::Matrix< M, M > matrix;\n    matrix.fill(data);\n    singular::Svd< M, M >::USV usv = singular::Svd< M, M >::decomposeUSV(matrix);\n    const singular::DiagonalMatrix< M, M >& sing = singular::Svd< M, M >::getS(usv);\n    cout << sing << endl;\n    cout << endl;\n    return singular::Svd< M, M >::isFullRank(sing, M);\n}\n\n\nstatic void ConvertReferenceArrayToInline(double* matrix) {\n    for (int i = 0; i < 64; ++i) {\n        for (int j = 0; j < 64; ++j) {\n            matrix[64*i + j] = (double) reference_matrix[i][j];\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(raw_data_to_singular_matrix_conversion) {\n        assert(CheckCompatibility(DATA));\n}\n\nBOOST_AUTO_TEST_CASE(compute_svd_of_a_matrix) {\n        assert(CheckMatrixRank4x4(DATA));\n        assert(!CheckMatrixRank4x4(WRONG_DATA1));\n        assert(!CheckMatrixRank4x4(WRONG_DATA2));\n}\n\nBOOST_AUTO_TEST_CASE(check_full_rank_for_64x64) {\n        double matrix[64*64];\n        ConvertReferenceArrayToInline(matrix);\n        assert(CheckMatrixRank64x64(matrix));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "1f5ab1509a3bf47908d41d93052f83edb71314f2", "size": 2455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/singular_tests.cpp", "max_stars_repo_name": "RevolutionBTC/test-rbtc", "max_stars_repo_head_hexsha": "a75b9180c1eae92872c4afb9bf53e588da984583", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T12:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T11:06:37.000Z", "max_issues_repo_path": "src/test/singular_tests.cpp", "max_issues_repo_name": "RevolutionBTC/test-rbtc", "max_issues_repo_head_hexsha": "a75b9180c1eae92872c4afb9bf53e588da984583", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-11-09T10:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T08:23:29.000Z", "max_forks_repo_path": "src/test/singular_tests.cpp", "max_forks_repo_name": "RevolutionBTC/test-rbtc", "max_forks_repo_head_hexsha": "a75b9180c1eae92872c4afb9bf53e588da984583", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T01:35:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T15:53:50.000Z", "avg_line_length": 25.8421052632, "max_line_length": 84, "alphanum_fraction": 0.5971486762, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6528575045631524}}
{"text": "#include <iostream>\n#include <Eigen/dense>\n#include \"file_manage.h\"\n#include \"model_selection.h\"\n#include \"KMeans.h\"\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tMatrixXd features;\n\tVectorXd labels;\n\n\tread_csv(\"data/iris.csv\", features, labels, 150, 5);\n\t//read_csv(\"data/seeds.csv\", features, labels, 210, 8);\n\n\tKMeans km(3);\n\tkm.fit(features, 1, 5);\n\n\tdouble score = evaluate_model(km, features, labels);\n\tcout << \"Silhouette score : \" << score << endl;\n\n\treturn 0;\n}", "meta": {"hexsha": "889f731cd7497dd3341f1e8163340ac6597dd6c3", "size": 483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "stnamjef/kmeans_clustering", "max_stars_repo_head_hexsha": "d6ac3c4046398060784bc76eb6c8c14d112847c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-08T19:00:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T19:00:22.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "stnamjef/kmeans_clustering", "max_issues_repo_head_hexsha": "d6ac3c4046398060784bc76eb6c8c14d112847c0", "max_issues_repo_licenses": ["MIT"], "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": "stnamjef/kmeans_clustering", "max_forks_repo_head_hexsha": "d6ac3c4046398060784bc76eb6c8c14d112847c0", "max_forks_repo_licenses": ["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.125, "max_line_length": 56, "alphanum_fraction": 0.6956521739, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6528574958192958}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date 8-jun-20\n * @license GPLv3, see 'LICENSE' file\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\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, version 3 of the License.\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, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Quat1\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n#include <boost/math/quaternion.hpp>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n\nusing t_types = std::tuple<long double, double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_equals, t_real, t_types)\n{\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\tusing t_quat = boost::math::quaternion<t_real>;\n\n\tt_real angle = tl2::pi<t_real>/t_real{4};\n\tauto vec = tl2::create<t_vec>({1, 2, 3});\n\tauto quat = tl2::rotation_quat<t_vec, t_quat>(vec, angle);\n\n\tauto [vec2, angle2] = tl2::rotation_axis<t_quat, t_vec>(quat);\n\n\tvec /= tl2::norm(vec);\n\tvec2 /= tl2::norm(vec2);\n\n\tstd::cout << \"q = \" << quat << std::endl;\n\tstd::cout << \"axis1 = \" << vec << \", angle1 = \" << angle << std::endl;\n\tstd::cout << \"axis2 = \" << vec2 << \", angle2 = \" << angle2 << std::endl;\n\n\n\tBOOST_TEST(tl2::equals(vec, vec2, 1e-5));\n\tBOOST_TEST(tl2::equals<t_real>(angle, angle2, 1e-5));\n}\n", "meta": {"hexsha": "d59668d4b6ae297f87857770bb44e215b66319ec", "size": 2238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/quat1.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/quat1.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/quat1.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 34.4307692308, "max_line_length": 79, "alphanum_fraction": 0.6295799821, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6528574958192958}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <random>\n#include <math.h>\n#include \"NN3Layer.hpp\"\nusing namespace std;\nusing namespace arma;\n\nmat gen_and_example(int randNum){\n    mat A(1,3);\n    switch (randNum)\n    {\n    case 1:\n        A={{0,0,0}};\n        break;\n    case 2:\n        A={{0,1,0}};\n        break;\n    case 3:\n        A={{1,0,0}};\n        break;\n    case 4:\n        A={{1,1,1}};\n        break;\n    default:\n        A={{1,1,1}};\n        break;\n    }\n    return A;\n}\nmat gen_or_example(int randNum){\n    mat A(1,3);\n    switch (randNum)\n    {\n    case 1:\n        A={{0,0,0}};\n        break;\n    case 2:\n        A={{0,1,1}};\n        break;\n    case 3:\n        A={{1,0,1}};\n        break;\n    case 4:\n        A={{1,1,1}};\n        break;\n    default:\n        A={{1,1,1}};\n        break;\n    }\n    return A;\n}\nmat gen_xor_example(int randNum){\n    mat A(1,3);\n    switch (randNum)\n    {\n    case 1:\n        A={{0,0,0}};\n        break;\n    case 2:\n        A={{0,1,1}};\n        break;\n    case 3:\n        A={{1,0,1}};\n        break;\n    case 4:\n        A={{1,1,0}};\n        break;\n    default:\n        A={{1,1,0}};\n        break;\n    }\n    return A;\n}\n\n\nint main(int argc, char** argv){\n      /* \u96a8\u6a5f\u8a2d\u5099 */\n  std::random_device rd;\n\n  /* \u4e82\u6578\u7522\u751f\u5668 \u6885\u68ee\u65cb\u8f49\u6f14\u7b97\u6cd5*/\n  std::mt19937 generator( rd() );\n\n  /* \u4e82\u6578\u7684\u6a5f\u7387\u5206\u5e03 */\n  std::uniform_real_distribution<float> unif(0.0, 5.0);\n  NN3Layer nn3Layer(2,2,1,0.1);\n  //train\n  for( int a = 0; a < 100000; a++){\n      /* \u7522\u751f\u4e82\u6578 */\n      float x = unif(generator);\n      mat data = gen_xor_example((int)x);\n      //data.print(\"data:\");\n      nn3Layer.train_step_sgd({data(0,0),data(0,1)},{data(0,2)});\n  }\n  //test\n    while(true){\n        cout << \"Test Neural Net \\n\";\n        cout << \"Input X1:\";\n        double x1=0;\n        cin >> x1;\n        cout << \"Input X2:\";\n        double x2=0;\n        cin >> x2;\n        mat o = nn3Layer.only_forward({x1,x2});\n        o.print(\"o:\");\n        cout << \"\\n result:\";\n        if(o(0,0)>0.5){\n            cout << 1<<\"\\n\";\n        }else{\n            cout << 0<<\"\\n\";\n        };\n        cout << \"Enter 0 to end ,1 to keep testing.\\n\";\n        int c=0;\n        cin>>c;\n        if(!c){\n            break;\n        }\n    }\n}", "meta": {"hexsha": "4ced000cbbe64bb246722d080b6454d994fa338e", "size": 2191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ShangHong-CAI/NN3Layer", "max_stars_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T06:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T10:42:13.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ShangHong-CAI/NN3Layer", "max_issues_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_issues_repo_licenses": ["MIT"], "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": "ShangHong-CAI/NN3Layer", "max_forks_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-25T16:13:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T07:37:19.000Z", "avg_line_length": 18.4117647059, "max_line_length": 65, "alphanum_fraction": 0.4345047923, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6528504582163561}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n\n/** To enforce matrix output from root process only */\n// #define ROOT_OUTPUT\n\n/** To enforce matrix generation for local->local */\n// #define LOCAL\n\n/** To denote whether rowwise sketching is attempted (columnwise otherwise) */\n#define ROWWISE\n\n\n////////////////////////////////////////////////////////////////////////////////\n\n#include <boost/mpi.hpp>\n#include <El.hpp>\n#include <iostream>\n\n#define SKYLARK_NO_ANY\n#include <skylark.hpp>\n\n\n\n/** Aliases */\n\ntypedef El::Matrix<double>     dense_matrix_t;\n\ntypedef El::DistMatrix<double> dist_dense_matrix_t;\ntypedef El::DistMatrix<double, El::VC, El::STAR>\ndist_VC_STAR_dense_matrix_t;\ntypedef El::DistMatrix<double, El::VR, El::STAR>\ndist_VR_STAR_dense_matrix_t;\ntypedef El::DistMatrix<double, El::STAR, El::VC>\ndist_STAR_VC_dense_matrix_t;\ntypedef El::DistMatrix<double, El::STAR, El::VR>\ndist_STAR_VR_dense_matrix_t;\n\ntypedef El::DistMatrix<double, El::CIRC, El::CIRC>\ndist_CIRC_CIRC_dense_matrix_t;\n\ntypedef El::DistMatrix<double, El::STAR, El::STAR>\ndist_STAR_STAR_dense_matrix_t;\n\n\n/* Set the following 2 typedefs for various matrix-type tests */\ntypedef dist_dense_matrix_t input_matrix_t;\ntypedef dist_dense_matrix_t output_matrix_t;\n\ntypedef skylark::sketch::JLT_t<input_matrix_t, output_matrix_t>\nsketch_transform_t;\n\n\nint main(int argc, char* argv[]) {\n\n    /** Initialize MPI  */\n    boost::mpi::environment env(argc, argv);\n    boost::mpi::communicator world;\n\n    /** Initialize Elemental */\n    El::Initialize (argc, argv);\n\n    MPI_Comm mpi_world(world);\n    El::Grid grid(mpi_world);\n\n    /** Example parameters */\n    int height      = 20;\n    int width       = 10;\n    int sketch_size = 5;\n\n    /** Define input matrix A */\n\n#ifdef LOCAL\n    input_matrix_t A;\n    El::Uniform(A, height, width);\n#else\n    dist_CIRC_CIRC_dense_matrix_t A_CIRC_CIRC(grid);\n    input_matrix_t A(grid);\n    El::Uniform(A_CIRC_CIRC, height, width);\n    A = A_CIRC_CIRC;\n#endif\n\n    /** Initialize context */\n    skylark::base::context_t context(0);\n\n#ifdef ROWWISE\n\n    /** Sketch transform (rowwise)*/\n    int size = width;\n    /** Distributed matrix computation */\n    output_matrix_t sketched_A(height, sketch_size);\n    sketch_transform_t sketch_transform(size, sketch_size, context);\n    sketch_transform.apply(A, sketched_A, skylark::sketch::rowwise_tag());\n\n#else\n\n    /** Sketch transform (columnwise)*/\n    int size = height;\n    /** Distributed matrix computation */\n    output_matrix_t sketched_A(sketch_size, width);\n    sketch_transform_t sketch_transform(size, sketch_size, context);\n    sketch_transform.apply(A, sketched_A, skylark::sketch::columnwise_tag());\n\n#endif\n\n#ifdef ROOT_OUTPUT\n    if (world.rank() == 0) {\n#endif\n        El::Print(sketched_A, \"sketched_A\");\n#ifdef ROOT_OUTPUT\n    }\n#endif\n    El::Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "b0d7476b40fbfe1c16a0cd8d9a26c8a9ba2952c6", "size": 2882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hp_dense.cpp", "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": "examples/hp_dense.cpp", "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": "examples/hp_dense.cpp", "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": 25.0608695652, "max_line_length": 80, "alphanum_fraction": 0.6710617627, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6528460254517225}}
{"text": "/**\n * @ file avgvalboundary.cc\n * @ brief NPDE homework AvgValBoundary code\n * @ author Simon Meierhans, edited by Oliver Rietmann\n * @ date 11.03.2019\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"avgvalboundary.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <memory>\n#include <utility>\n#include <vector>\n\nnamespace AvgValBoundary {\n\n/**\n * @brief computes H1 seminorm over the computational domain\n * @param dofh DofHandler of FEspace.\n *        u coefficient vector\n */\n/* SAM_LISTING_BEGIN_1 */\ndouble compH1seminorm(const lf::assemble::DofHandler &dofh,\n                      const Eigen::VectorXd &u) {\n  double result = 0.0;\n\n  // Compute Stiffness matrix with alpha := 1, beta := 0, gamma := 0\n  auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n  auto const_zero = [](Eigen::Vector2d x) -> double { return 0.0; };\n  auto A = compGalerkinMatrix(dofh, const_one, const_zero, const_zero);\n\n  // Compute seminorm using the Stiffness matrix\n  result = u.transpose() * A * u;\n  result = std::sqrt(result);\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief solves pde for some simple test problem with\n *        alpha = beta = gamma := 1.0 and load f := 1.0\n * @param dofh DofHandler of FEspace.\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solveTestProblem(const lf::assemble::DofHandler &dofh) {\n  // Obtain Galerkin matrix for alpha = beta = gamma := 1.0\n  auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n  auto A = compGalerkinMatrix(dofh, const_one, const_one, const_one);\n\n  // Set up load vector\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(dofh.Mesh());\n  lf::mesh::utils::MeshFunctionConstant mf_identity{1.0};\n  lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space,\n                                                             mf_identity);\n  Eigen::VectorXd phi(dofh.NumDofs());\n  phi.setZero();\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  // Solve system of linear equations\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A);\n  Eigen::VectorXd mu = solver.solve(phi);\n\n  return mu;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief generate sequence of nested triangular meshes with L+1 levels */\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr<lf::refinement::MeshHierarchy> generateTestMeshSequence(\n    unsigned int L) {\n  auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1.0 / 3.0);\n  std::shared_ptr<lf::refinement::MeshHierarchy> meshes =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh, L);\n  return meshes;\n}\n/* SAM_LISTING_END_3 */\n\n/**\n * @brief Compute the boundary functional values for a sequence of L meshes\n * @param L The number of meshes in the sequence\n * @returns A vector of pairs containing the number of DOFs and value of the\n *\t    boundary functional for each level\n */\n/* SAM_LISTING_BEGIN_5 */\nstd::vector<std::pair<unsigned int, double>> approxBoundaryFunctionalValues(\n    unsigned int L) {\n  std::vector<std::pair<unsigned int, double>> result;\n  auto meshes = generateTestMeshSequence(L - 1);\n  int num_meshes = meshes->NumLevels();\n  for (int level = 0; level < num_meshes; ++level) {\n    auto mesh_p = meshes->getMesh(level);\n\n    // Set up global FE space; lowest order Lagrangian finite elements\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n    // Obtain local->global index mapping for current finite element space\n    const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n    const lf::base::size_type N_dofs(dofh.NumDofs());\n\n    // compute galerkin matrix with alpha = 1.0, gamma = 1.0, beta = 0.0\n    auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n    auto const_zero = [](Eigen::Vector2d x) -> double { return 0.0; };\n    auto A = compGalerkinMatrix(dofh, const_one, const_one, const_zero);\n\n    // compute load vector for f(x) = x.norm()\n    auto f = [](Eigen::Vector2d x) -> double { return x.norm(); };\n    lf::mesh::utils::MeshFunctionGlobal mf_f{f};\n    lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space, mf_f);\n    Eigen::VectorXd phi(N_dofs);\n    phi.setZero();\n    AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n    // solve system of equations\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n    solver.compute(A);\n    Eigen::VectorXd u = solver.solve(phi);\n\n    // set up weight function\n    auto w = [](Eigen::Vector2d x) -> double { return 1.0; };\n    double functional_value = compBoundaryFunctional(dofh, u, w);\n\n    result.push_back({N_dofs, functional_value});\n  }\n  return result;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace AvgValBoundary\n", "meta": {"hexsha": "8fe3cbe201a4efc72c4b9076c8b65633a7d7b68e", "size": 4888, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.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": 34.6666666667, "max_line_length": 79, "alphanum_fraction": 0.6876022913, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6528460209046553}}
{"text": "#include <blitzml/smooth_loss/squared_loss.h>\n#include <blitzml/base/math_util.h>\n\nnamespace BlitzML {\n\nvalue_t SquaredLoss::compute_loss(value_t a_dot_omega, value_t label) const {\n  value_t residual = a_dot_omega - label;\n  return sq(residual) / 2;\n}\n\n\nvalue_t SquaredLoss::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 SquaredLoss::compute_deriative(value_t a_dot_omega,\n                                       value_t label) const {\n  return a_dot_omega - label;\n}\n\n\nvalue_t SquaredLoss::compute_2nd_derivative(value_t a_dot_omega,\n                                            value_t label) const {\n  return 1.;\n}\n\n\nvalue_t SquaredLoss::compute_bias_update(\n    const std::vector<value_t> &dual_values) const {\n  value_t delta = -sum_vector(dual_values) / dual_values.size();\n  return delta;\n}\n\n\nvalue_t SquaredLoss::lipschitz_constant() const {\n  return 1.;\n}\n\n} // namespace BlitzML\n\n", "meta": {"hexsha": "71b83815d8e006f1634ec130bbdf16ca475bd01f", "size": 1014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smooth_loss/squared_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/squared_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/squared_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": 23.5813953488, "max_line_length": 77, "alphanum_fraction": 0.6686390533, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6528460196908128}}
{"text": "// \n// // Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\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\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/image_processing/numeric.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n#include <string>\n#include <iostream>\n\nnamespace gil = boost::gil;\n\n// Demonstrates the use of Sobel and Scharr filters to detect edges\n// The example generates a couple of images representing respectively the result of\n// applying the filter horizontally and vertically.\n// The functions generating the filters (or kernels) are defined in include/boost/gil/image_processing/numeric.hpp.\n\nint main(int argc, char* argv[])\n{\n    if (argc != 5)\n    {\n        std::cerr << \"usage: \" << argv[0] << \": <input.png> <sobel|scharr> <output-x.png> <output-y.png>\\n\";\n        return -1;\n    }\n\n    gil::gray8_image_t input_image;\n    gil::read_image(argv[1], input_image, gil::png_tag{});\n    auto input = gil::view(input_image);\n    auto filter_type = std::string(argv[2]);\n\n    gil::gray16_image_t dx_image(input_image.dimensions());\n    auto dx = gil::view(dx_image);\n    gil::gray16_image_t dy_image(input_image.dimensions());\n    auto dy = gil::view(dy_image);\n    if (filter_type == \"sobel\")\n    {\n        gil::detail::convolve_2d(input, gil::generate_dx_sobel(1), dx);\n        gil::detail::convolve_2d(input, gil::generate_dy_sobel(1), dy);\n    }\n    else if (filter_type == \"scharr\")\n    {\n        gil::detail::convolve_2d(input, gil::generate_dx_scharr(1), dx);\n        gil::detail::convolve_2d(input, gil::generate_dy_scharr(1), dy);\n    }\n    else\n    {\n        std::cerr << \"unrecognized gradient filter type. Must be either sobel or scharr\\n\";\n        return -1;\n    }\n\n    gil::write_view(argv[3], dx, gil::png_tag{});\n    gil::write_view(argv[4], dy, gil::png_tag{});\n}\n", "meta": {"hexsha": "b37694402fdefb571f858a86676cf7fdb0677768", "size": 1995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/sobel_scharr.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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/sobel_scharr.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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/sobel_scharr.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "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.813559322, "max_line_length": 115, "alphanum_fraction": 0.6721804511, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6528460139299028}}
{"text": "#include \"NeuralNetwork.h\"\n\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <vector>\n\n#include <Eigen/Dense>\n\n\nNeuralNetwork NeuralNetwork::from_stream(std::istream &is)\n{\n\tfloat learning_factor;\n    int num_layers;\n    \n    is.read((char *)&learning_factor, sizeof(learning_factor));\n    is.read((char *)&num_layers, sizeof(num_layers));\n\n\tstd::vector<int> sizes;\n\n\tstd::cout << \"reading size: \";\n\n\tfor (int i = 0; i < num_layers; i++)\n\t{\n\t\tint size;\n\t\tis.read((char *)&size, sizeof(size));\n\t\tsizes.push_back(size);\n\t\tstd::cout << size << \" \";\n\t}\n    \n\tstd::cout << std::endl;\n\n    NeuralNetwork nn(sizes, learning_factor);\n\n\tstd::cout << \"Sizes: \" << std::endl;\n\tfor (int size : nn.m_sizes)\n\t{\n\t\tstd::cout << size << \" \";\n\t}\n\tstd::cout << std::endl;\n\n\tfor (auto & weight_matrix : nn.m_weights)\n\t{\n\t\tfor (int r = 0; r < weight_matrix.rows(); r++)\n\t\t{\n\t\t\tfor (int c = 0; c < weight_matrix.cols(); c++)\n\t\t\t{\n\t\t\t\tis.read((char *)&weight_matrix(r, c), sizeof(float));\n\t\t\t}\n\t\t}\n\t}\n    \n    return nn;\n}\n\n\nNeuralNetwork::NeuralNetwork(std::vector<int> layer_sizes, float learning_factor)\n\t: m_num_layers(layer_sizes.size())\n\t, m_sizes(layer_sizes)\n\t, m_layers()\n\t, m_deltas()\n\t, m_weights()\n\t, m_learning_factor(learning_factor)\n{\n\tif (m_num_layers == 0)\n\t{\n\t\tthrow std::invalid_argument(\"The number of layers must be at least one!\");\n\t}\n\n\tfor (int i = 0; i < m_num_layers - 1; i++)\n\t{\n\t\tm_layers.push_back(Eigen::VectorXf::Ones(m_sizes[i] + 1)); // extra for the bias\n\t}\n\n\tm_layers.push_back(Eigen::VectorXf::Ones(m_sizes[m_num_layers - 1])); // output doesn't get bias\n\n\tfor (int i = 1; i < m_num_layers; i++)\n\t{\n\t\tm_deltas.push_back(Eigen::VectorXf::Ones(m_sizes[i]));\n\t\tm_weights.push_back(Eigen::MatrixXf::Random(m_sizes[i], m_sizes[i - 1] + 1)); // extra for the bias\n\t}\n\n\tstd::cout << m_layers.size() << std::endl;\n}\n\nvoid NeuralNetwork::forward_propagate(const Eigen::VectorXf& input)\n{\n    if (input.size() != m_sizes[0])\n        throw std::invalid_argument(\"The input vector must be of size <\" + std::to_string(m_sizes[0]) + \">\");\n\n\tm_layers[0].head(m_sizes[0]) = input;\n\n\tfor (size_t i = 1; i < m_layers.size(); ++i)\n\t{\n\t\tm_layers[i].head(m_sizes[i]) = (m_weights[i - 1] * m_layers[i - 1]).unaryExpr(&sigmoid);\n\t}\n}\n\nvoid NeuralNetwork::back_propagate(const Eigen::VectorXf& output)\n{\n    if (output.size() != m_sizes[m_num_layers-1])\n        throw std::invalid_argument(\"The output vector must be of size <\" + std::to_string(m_sizes[m_num_layers - 1]) + \">\");\n\n    Eigen::VectorXf error = output - m_layers[m_num_layers - 1];\n\tEigen::VectorXf delta_o = error.array() * (m_layers[m_num_layers - 1].unaryExpr(&sigmoid_prime)).array();\n\tm_deltas[m_deltas.size() - 1] = delta_o;\n\n\tint delta_size = m_deltas.size();\n\tfor (int delta_index = delta_size - 2; delta_index >= 0; delta_index--)\n\t{\n\t\tint layer_index = delta_index + 1;\n\t\tEigen::VectorXf derivative = m_layers[layer_index].head(m_sizes[layer_index]).unaryExpr(&sigmoid_prime);\n\t\tEigen::VectorXf err = (m_weights[delta_index + 1].transpose() * m_deltas[delta_index + 1]).head(m_sizes[layer_index]);\n\n\t\tEigen::VectorXf delta = derivative.array() * err.array();\n\t\t\n\t\tm_deltas[delta_index] = delta;\n\t}\n\n\tint weights_size = m_weights.size();\n\tfor (int i = 0; i < weights_size; ++i)\n\t{\n\t\tm_weights[i] += m_learning_factor * (m_deltas[i] * m_layers[i].transpose());\n\t}\n}\n\nEigen::VectorXf NeuralNetwork::test(const Eigen::VectorXf& input, const Eigen::VectorXf& output)\n{\n    forward_propagate(input);\n    return output - m_layers[m_num_layers - 1];\n}\n\nint NeuralNetwork::classify(const Eigen::VectorXf& input)\n{\n    float max_val = -1;\n    int max_index = -1;\n\n    forward_propagate(input);\n\n    for (int i = 0; i < m_sizes[m_num_layers - 1]; ++i)\n    {\n        if (max_val < m_layers[m_num_layers - 1][i])\n        {\n            max_val = m_layers[m_num_layers - 1][i];\n            max_index = i;\n        }\n    }\n\n    return max_index;\n}\n\nstd::vector<std::pair<int, float>> NeuralNetwork::classification(const Eigen::VectorXf& input)\n{\n\tstd::vector<std::pair<int, float>> classification_vector(m_sizes[m_num_layers - 1]);\n\n\tforward_propagate(input);\n\n\tfor (int i = 0; i < m_sizes[m_num_layers - 1]; i++)\n\t{\n\t\tclassification_vector.push_back({ i, m_layers[m_num_layers - 1][i] });\n\t}\n\n\tstd::sort\n\t(\n\t\tclassification_vector.begin(), classification_vector.end(), \n\t\t[](std::pair<int, float> lhs, std::pair<int, float> rhs) \n\t\t{\n\t\t\treturn lhs.second > rhs.second; \n\t\t}\n\t);\n\n\treturn classification_vector;\n}\n\nvoid NeuralNetwork::serialize(std::ostream &os) const\n{\n\tos.write((char*)&m_learning_factor, sizeof(m_learning_factor));\n\n\tos.write((char *)&m_num_layers, sizeof(m_num_layers));\n\n\tfor (int size : m_sizes)\n\t{\n\t\tos.write((char *)&size, sizeof(size));\n\t}\n\t\n\tfor (const auto & weight_matrix : m_weights)\n\t{\n\t\tfor (int r = 0; r < weight_matrix.rows(); r++)\n\t\t{\n\t\t\tfor (int c = 0; c < weight_matrix.cols(); c++)\n\t\t\t{\n\t\t\t\tos.write((char *)&weight_matrix(r, c), sizeof(float));\n\t\t\t}\n\t\t}\n\t}\n}\n\nint NeuralNetwork::get_num_inputs() const\n{\n    return m_sizes[0];\n}\n\nint NeuralNetwork::get_num_outputs() const\n{\n    return m_sizes[m_num_layers - 1];\n}\n\nvoid NeuralNetwork::set_learning_factor(float learning_factor)\n{\n\tm_learning_factor = learning_factor;\n}\n\nEigen::VectorXf NeuralNetwork::get_output() const\n{\n\treturn m_layers[m_num_layers - 1];\n}\n\nconst Eigen::MatrixXf& NeuralNetwork::get_weights_ih() const\n{\n    return m_weights[0];\n}\n\nconst Eigen::MatrixXf& NeuralNetwork::get_weights_ho() const\n{\n    return m_weights[m_weights.size() - 1];\n}\n", "meta": {"hexsha": "b509b68c570ace6de74cd709005d77f210cfe31f", "size": 5516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NeuralNetwork.cpp", "max_stars_repo_name": "tdriggs/TetrisAI", "max_stars_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "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/NeuralNetwork.cpp", "max_issues_repo_name": "tdriggs/TetrisAI", "max_issues_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "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/NeuralNetwork.cpp", "max_forks_repo_name": "tdriggs/TetrisAI", "max_forks_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "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.2995594714, "max_line_length": 125, "alphanum_fraction": 0.6593546048, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6527787297877244}}
{"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n\n#include <cmath>\n\n// #include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/phenomenology.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// Pippard's phenomenological theory of superconductivity\nnamespace pippard {\n\n///\ntemplate <typename T = double>\nT J_0(T temperature, T critical_temperature, T gap_meV, T exponent) {\n  // Boltzmann constant (meV / K)\n  constexpr T k_B_meV_per_K =\n      1e3 *\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  //\n  // T reduced_temperature = temperature / critical_temperature;\n  //\n  return std::pow(phenomenology::reduced_penetration_depth<T>(\n                      temperature, critical_temperature, exponent),\n                  2) *\n         bcs::reduced_gap<T>(temperature, critical_temperature) *\n         std::tanh(bcs::gap<T>(temperature, critical_temperature, gap_meV) /\n                   (2.0 * k_B_meV_per_K * temperature));\n}\n\n/// temperature dependence of the Pippard coherence length,\n/// \"borrowed\" from BCS theory\ntemplate <typename T = double>\nT coherence_length(T temperature, T critical_temperature, T gap_meV, T exponent,\n                   T xi_0, T mean_free_path) {\n  T fraction_1 =\n      J_0<T>(temperature, critical_temperature, gap_meV, exponent) / xi_0;\n  T fraction_2 = 1.0 / mean_free_path;\n  T fraction = fraction_1 + fraction_2;\n  // handle a some edge cases for very big/small args\n  if (std::isinf(fraction)) {\n    return 0.0;\n  } else if (fraction == 0.0) {\n    return std::numeric_limits<T>::infinity();\n  } else {\n    return 1.0 / fraction;\n  }\n}\n\n/// temperature dependence of the (reduced) Pippard coherence length,\n/// \"borrowed\" from BCS theory\ntemplate <typename T = double>\nT reduced_coherence_length(T temperature, T critical_temperature, T gap_meV,\n                           T exponent, T xi_0, T mean_free_path) {\n  return coherence_length<T>(temperature, critical_temperature, gap_meV,\n                             exponent, xi_0, mean_free_path) /\n         coherence_length<T>(0.0, critical_temperature, gap_meV, exponent, xi_0,\n                             mean_free_path);\n}\n\n/// helper function for the Pippard Kernel\ntemplate <typename T = double> T g(T x) {\n  /*\n  boost::multiprecision::cpp_dec_float_100 value =\n      (3.0 / 2.0) * ((1.0 + x * x) * std::atan(x) - x) / (x * x * x);\n  return value;\n  */\n  // return correct result when x ~ 0.\n  if (x < 1.0e-4) {\n    return 1.0;\n  } else {\n    return (3.0 / 2.0) * ((1.0 + x * x) * std::atan(x) - x) / (x * x * x);\n  }\n}\n\n/// Pippard Kernel\ntemplate <typename T = double>\nT kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n         T mean_free_path, T lambda_0, T exponent) {\n  T x = q * coherence_length<T>(temperature, critical_temperature, gap_meV,\n                                exponent, xi_0, mean_free_path);\n  return std::pow(phenomenology::penetration_depth<T>(\n                      temperature, critical_temperature, exponent, lambda_0),\n                  -2) *\n         reduced_coherence_length<T>(temperature, critical_temperature, gap_meV,\n                                     exponent, xi_0, mean_free_path) *\n         g<T>(x);\n}\n\n/// (reduced) Pippard Kernel\ntemplate <typename T = double>\nT reduced_kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n                 T mean_free_path, T lambda_0, T exponent) {\n  return kernel<T>(q, temperature, critical_temperature, gap_meV, xi_0,\n                   mean_free_path, lambda_0, exponent) /\n         kernel<T>(0.0, temperature, critical_temperature, gap_meV, xi_0,\n                   mean_free_path, lambda_0, exponent);\n}\n\n/// (reduced) magnetic field penetration proifile\ntemplate <typename T = double>\nT reduced_field_penetration(T z, T temperature, T critical_temperature,\n                            T gap_meV, T xi_0, T mean_free_path, T lambda_0,\n                            T exponent) {\n  //\n  if (z <= 0.0) {\n    return 1.0;\n  } else {\n    //\n    auto pippard_integrand = [&](T q) -> T {\n      T K = kernel<T>(q, temperature, critical_temperature, gap_meV, xi_0,\n                      mean_free_path, lambda_0, exponent);\n      return q / (q * q + K);\n    };\n    // create the integrator w/ specific tolerance and evaluation levels\n    // (defaults: root_epsilon and eight levels for type double).\n    // static T tolerance = std::sqrt(std::numeric_limits<T>::epsilon());\n    static T tolerance = std::cbrt(std::numeric_limits<T>::epsilon());\n    std::size_t levels = sizeof(T);\n    static boost::math::quadrature::ooura_fourier_sin<T> pippard_integrator =\n        boost::math::quadrature::ooura_fourier_sin<T>(tolerance, levels);\n    // evaluate the integral, which returns a pair\n    // (first = integral, second = relative error)\n    std::pair<T, T> result = pippard_integrator.integrate(pippard_integrand, z);\n    // return the integral multiplied by the prefactors to get B vs. z\n    return boost::math::constants::two_div_pi<T>() * result.first;\n  }\n}\n\n/// magnetic field penetration proifile\ntemplate <typename T = double>\nT field_penetration(T z, T temperature, T critical_temperature, T gap_meV,\n                    T xi_0, T mean_free_path, T lambda_0, T exponent,\n                    T applied_field) {\n  return applied_field * reduced_field_penetration<T>(\n                             z, temperature, critical_temperature, gap_meV,\n                             xi_0, mean_free_path, lambda_0, exponent);\n}\n\n} // namespace pippard\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n", "meta": {"hexsha": "2ce06799d50354a24db443ce3f9a2932ede406d8", "size": 5808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/superconductivity/pippard.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "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/triumf/superconductivity/pippard.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "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/triumf/superconductivity/pippard.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["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.4709677419, "max_line_length": 80, "alphanum_fraction": 0.6504820937, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.652778728936229}}
{"text": "//\n// This program is used to study how to calculate (SS|SS)^{m}\n// for the recursive relation. Basically, it focus on the \n// fmt function:\n// f_{m}(t) = \\int^{1}_{0} u^{2m} e^{-tu^{2}} du \n// it needs the boost library to calcualte fmt\n// fenglai liu\n// Oct. 2013\n//\n// for reference, see Harris paper and the reference cited inside:\n// Harris, Frank E\n// Evaluation of GTO molecular integrals\n// International Journal of Quantum Chemistry, 1983, Vol. 23, Page 1469--1478\n//\n// note:\n// we found that the approximation of (2m-1)!!/R expression is \n// not numerical stable. Combined with down recursive relation,\n// it introduces greater error compared with other methods. \n// Therefore we finally abadon it.\n//\n//\n//\n\n// common C head files used in the program\n#include<cstdlib>\n#include<cstdio>\n\n// external math functions \n#include<cmath>\n\n// common C++ head files may be used in the program\n#include<iostream>\n#include<fstream>\n#include<iomanip>\n#include<string> \n#include<vector>\n#include<list>\n#include<set>\n#include<map>\n#include<iterator>\n#include<algorithm>\n\n#include <boost/math/special_functions/binomial.hpp>  // special functions in math\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/timer.hpp>\nusing namespace boost::math;\nusing namespace boost;\nusing namespace std;\n#define PI              3.1415926535897932384626E0  \n\ndouble fm(const double& a, const int& m); \ndouble doubleFac(const int& m, const int& n); \n\ndouble fm(const double& a, const int& m) {\n\tdouble x = 1.0E0;\n\tif (fabs(a)<1.0E-14) return (pow(x,2*m+1)/(2*m+1));\n\tdouble f12 = 1.0E0/2.0E0;\n\tdouble p   = 1.0E0/(2.0E0*pow(a,m+f12));\n\tdouble upperLimit = a*pow(x,2.0E0);\n\treturn tgamma_lower(m+f12,upperLimit)*p;\n}\n\ndouble doubleFac(const int& m, const int& n) {\n\t// calculate (2m-1)!!/(2m+2n+1)!!\n\tdouble x = 1.0E0;\n\tfor(int i=0; i<=n; i++) {\n\t\tx *= 1.0E0/(2*m+2*i+1); \n\t}\n\treturn x;\n} \n\nint main() \n{\n\t///////////////////////////////////////////////////\n\t// global settings\n\t// step length and number of claculation for \n\t// time performance\n\t// global error is the error range\n\t// if the difference is less than the error, we \n\t// think the error could be omitted\n\t///////////////////////////////////////////////////\n\tdouble steplength  = 0.000001;\n\tdouble globalError = 1.0E-14;\n\tint top_M_limmit   = 40;\n\tdouble T_max_limit = 100.0E0;\n\n\t///////////////////////////////////////////////////\n\t// testing the fmt from down recursive relation\n\t///////////////////////////////////////////////////\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the comparison between f_{m}(t) and f_{m+1}(t) for m up to \" << top_M_limmit << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from 0 \" << \" to \" <<T_max_limit << endl;\n\tcout << \"===========================================================\" << endl;\n\tint nSteps = T_max_limit/steplength;\n\tfor (int n=1; n<=top_M_limmit; n++) {\n\t\tfor (int j = 0; j<nSteps; j++) {\n\t\t\tdouble T = steplength*j;\n\t\t\tdouble fmt= fm(T,n);\n\t\t\tdouble et = exp(-T);\n\t\t\tdouble e0 = fmt;\n\t\t\tdouble t2 = 2.0*T;\n\t\t\tfor(int i=n-1; i>=0; i--) {\n\t\t\t\tdouble e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tif (e0>e) {\n\t\t\t\t\tdouble d = fabs(e0-e);\n\t\t\t\t\tif (d>globalError) {\n\t\t\t\t\t\tprintf(\"T is %-16.14f\\n\", T);\n\t\t\t\t\t\tprintf(\"for m=%d difference is %-16.14f\\n\", n, d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "360ae0b1e6d00408534ea632548161185de62815", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["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.9416666667, "max_line_length": 103, "alphanum_fraction": 0.5882522315, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6527787242514914}}
{"text": "/*\n * fmath.cpp\n *\n * Created on: Jul 17, 2012\n * @author Ralph Schurade\n */\n#include \"fmath.h\"\n\n#include \"math.h\"\n\n#include \"../thirdparty/newmat10/newmatap.h\"\n#include \"../thirdparty/newmat10/newmatio.h\"\n#include \"../thirdparty/newmat10/newmatrm.h\"\n#include \"../thirdparty/newmat10/precisio.h\"\n\n#include <QDebug>\n#include <qmath.h>\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\n#include <float.h>\n\nFMath::FMath() {}\nFMath::~FMath() {}\n\nColumnVector FMath::vlog( ColumnVector v )\n{\n    // allocate memory of output object:\n    ColumnVector tmp( v.Nrows() );\n\n    // for each element of the vector:\n    for ( int i( 1 ); i <= v.Nrows(); ++i )\n    {\n        if ( v( i ) <= 0.0 )\n            tmp( i ) = -1.0e+17;\n        else\n            tmp( i ) = log( v( i ) );\n    }\n    return tmp;\n}\n\ndouble FMath::legendre_p( int k )\n{\n    double z = 1.0;\n    double n = 1.0;\n\n    for ( int i = 1; i <= k + 1; i += 2 ) z *= i;\n    for ( int i = 2; i <= k - 2; i += 2 ) n *= i;\n\n    if (( k / 2 ) % 2 == 0)\n    {\n        return -1.0 / ( 8 * M_PI ) * ( z / n );\n    }\n    else\n    {\n        return 1.0 / ( 8 * M_PI ) * ( z / n );\n    }\n\n}\n\ndouble FMath::boostLegendre_p( int order, int arg1, double arg2 )\n{\n    return boost::math::legendre_p<double>( order, arg1, arg2 );\n}\n\nMatrix FMath::sh_base( Matrix g, int maxOrder )\n{\n    //qDebug() << \"start calculating sh base\";\n    // allcoate result matrix\n    unsigned long sh_dirs( ( maxOrder + 2 ) * ( maxOrder + 1 ) / 2 );\n    Matrix out( g.Nrows(), sh_dirs );\n    out = 0.0;\n\n    // for each direction\n    for ( int i = 0; i < g.Nrows(); ++i )\n    {\n        // transform current direction to polar coordinates\n        double theta( acos( g( i + 1, 3 ) ) );\n        double phi( atan2( g( i + 1, 2 ), g( i + 1, 1 ) ) );\n\n        // calculate spherical harmonic base\n        for ( int order = 0, j = 0; order <= maxOrder; order += 2 )\n        {\n            for ( int degree( -order ); degree <= order; ++degree, ++j )\n            {\n                out( i + 1, j + 1 ) = sh_base_function( order, degree, theta, phi );\n            }\n        }\n    }\n    //qDebug() << \"finished calculating sh base\";\n    return out;\n}\n\ndouble FMath::sh_base_function( int order, int degree, double theta, double phi )\n{\n    using namespace boost::math;\n#if 0\n    double P = legendre_p<double>( order, abs(degree), cos(theta) );\n\n    if ( degree > 0 )\n    {\n        return P * cos( degree * phi );\n    }\n    else if ( degree < 0 )\n    {\n        return P * sin( -degree * phi );\n    }\n    else\n    {\n        return P;\n    }\n#else\n    if ( degree > 0 )\n    {\n        return spherical_harmonic_r( order, abs( degree ), theta, phi );\n    }\n    else if ( degree < 0 )\n    {\n        return spherical_harmonic_i( order, abs( degree ), theta, phi );\n    }\n    else\n    {\n        return spherical_harmonic_r( order, 0, theta, phi );\n    }\n#endif\n}\n\nSymmetricMatrix FMath::moment_of_inertia( const ColumnVector& values, const QVector<ColumnVector>& points )\n{\n    SymmetricMatrix result( 3 );\n    result = 0.0;\n\n    double sum( 0.0 );\n    for ( int i = 0; i < points.size(); ++i )\n    {\n        double x( points[i]( 1 ) );\n        double y( points[i]( 2 ) );\n        double z( points[i]( 3 ) );\n        double val = fabs( values( i + 1 ) );\n\n        result( 1, 1 ) += x * x * val;\n        result( 1, 2 ) += x * y * val;\n        result( 1, 3 ) += x * z * val;\n        result( 2, 2 ) += y * y * val;\n        result( 2, 3 ) += y * z * val;\n        result( 3, 3 ) += z * z * val;\n\n        sum += val * val;\n    }\n    result = result / sum;\n\n    return result;\n}\n\ndouble FMath::iprod( const ColumnVector& v1, const ColumnVector& v2 )\n{\n    double result( 0.0 );\n\n    if ( v1.Nrows() != v2.Nrows() )\n    {\n        throw std::range_error( \"Vectors in scalar product need same size!\" );\n    }\n\n    for ( int i = 1; i < v1.Nrows() + 1; ++i )\n    {\n        result += v1( i ) * v2( i );\n    }\n\n    return result;\n}\n\nColumnVector FMath::cprod( const ColumnVector& v1, const ColumnVector& v2 )\n{\n    ColumnVector result( 3 );\n\n    if ( v1.Nrows() != 3 || v2.Nrows() != 3 )\n        throw std::range_error( \"Vectors in cross product both need size 3!\" );\n\n    result( 1 ) = v1( 2 ) * v2( 3 ) - v1( 3 ) * v2( 2 );\n    result( 2 ) = v1( 3 ) * v2( 1 ) - v1( 1 ) * v2( 3 );\n    result( 3 ) = v1( 1 ) * v2( 2 ) - v1( 2 ) * v2( 1 );\n\n    result = result / sqrt( FMath::iprod( result, result ) );\n\n    return result;\n}\n\n\nvoid FMath::evd3x3( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals )\n{\n    double i1, i2, i3, v, s, phi, l1, l2, l3;\n    double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;\n\n    double xx = tensor( 1 );\n    double xy = tensor( 2 );\n    double xz = tensor( 3 );\n    double yy = tensor( 4 );\n    double yz = tensor( 5 );\n    double zz = tensor( 6 );\n\n    // three invariants of D (dt)\n    // i1=l1+l2+l3 (trace)\n    // i2=l1*l2+l1*l3+l2*l3\n    // i3=l1*l2*l3 (determinante)\n    i1 = xx + yy + zz;\n    i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n    i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n    v = pow2( i1 / 3 ) - i2 / 3;\n    s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n\n    if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n        phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n    else\n        phi = 0;\n\n    // eigenvalues\n    if ( phi != 0 )\n    {\n        l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n        l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n        l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n    }\n    else\n        l1 = l2 = l3 = 0.0;\n\n    // eigenvectors\n    ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n    ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n    ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n    ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n    ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n    ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n    ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n    ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n    ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n    vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev1_x = ev1_x / vec_norm;\n        ev1_y = ev1_y / vec_norm;\n        ev1_z = ev1_z / vec_norm;\n    }\n    else\n        ev1_x = ev1_y = ev1_z = 0.0;\n\n    vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev2_x = ev2_x / vec_norm;\n        ev2_y = ev2_y / vec_norm;\n        ev2_z = ev2_z / vec_norm;\n    }\n    else\n        ev2_x = ev2_y = ev2_z = 0.0;\n\n    vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev3_x = ev3_x / vec_norm;\n        ev3_y = ev3_y / vec_norm;\n        ev3_z = ev3_z / vec_norm;\n    }\n    else\n        ev3_x = ev3_y = ev3_z = 0.0;\n\n    ColumnVector ev1( 3 );\n    ColumnVector ev2( 3 );\n    ColumnVector ev3( 3 );\n\n    vals(1) = l1;\n    vals(2) = l2;\n    vals(3) = l3;\n\n    ev1( 1 ) = ev1_x;\n    ev1( 2 ) = ev1_y;\n    ev1( 3 ) = ev1_z;\n    ev2( 1 ) = ev2_x;\n    ev2( 2 ) = ev2_y;\n    ev2( 3 ) = ev2_z;\n    ev3( 1 ) = ev3_x;\n    ev3( 2 ) = ev3_y;\n    ev3( 3 ) = ev1_z;\n    vecs.clear();\n    vecs.push_back( ev3 );\n    vecs.push_back( ev2 );\n    vecs.push_back( ev1 );\n}\n\n///* ***************************************************************************\n///* @file math.cpp\n///* @fn Vector cart2sphere(\n///*\n///*     const Vector& input )\n///*\n///* @brief Transforms a cartesian-coordinate vector to spherical coordinates.\n///*\n///* For further information view:                                          <br>\n///*  Wikipedia article on cartesian and spherical coordinates.\n///*\n///* @param Vector: a in cartesian-coordinates\n///*\n///* @return Vector: representation of a in spherical coordinates,\n///*                 order: r, theta, phi.\n///* ***************************************************************************\nColumnVector FMath::cart2sphere( const ColumnVector& input )\n{\n  if ( input.Nrows() != 3 )\n    throw std::range_error(\"Can only transform 3D-vectors.\");\n\n  ColumnVector result( 3 );\n\n    result( 1 ) = sqrt( input( 1 ) * input( 1 ) + input( 2 ) * input( 2 ) + input( 3 ) * input( 3 ) );\n    result( 2 ) = acos( input( 3 ) / result( 1 ) );\n    result( 3 ) = atan2( input( 2 ), input( 1 ) );\n\n  return result;\n}\n\n///* ***************************************************************************\n///* @file math.cpp\n///* @fn Vector sphere2cart(\n///*\n///*     const Vector& input )\n///*\n///* @brief Transforms a spherical-coordinate vector to cartesian-coordinates.\n///*\n///* For further information view:                                          <br>\n///*  Wikipedia article on cartesian and spherical coordinates.             <br>\n///*\n///* @param Vector: a in spherical-coordinates\n///*\n///* @return Vector: represantation of a in cartesian-coordinates, order: x,y,z.\n///* ***************************************************************************\nColumnVector FMath::sphere2cart( const ColumnVector& input )\n{\n    if ( input.Nrows() != 3 )\n        throw std::range_error( \"Can only transform 3D-vectors.\" );\n\n    ColumnVector result( 3 );\n\n    result( 1 ) = input( 1 ) * sin( input( 2 ) ) * cos( input( 3 ) );\n    result( 2 ) = input( 1 ) * sin( input( 2 ) ) * sin( input( 3 ) );\n    result( 3 ) = input( 1 ) * cos( input( 2 ) );\n\n    return result;\n}\n\nColumnVector FMath::SH_opt_max( const ColumnVector& startX, const ColumnVector& coeff )\n{\n    ColumnVector newX( startX );\n    ColumnVector oldX( 3 );\n\n    // set values for computation\n    const double precision( 10.e-6 );\n    const double eps( 10.e-4 );\n\n    double delta( 1.0 );\n    int steps( 0 );\n    while ( delta > precision && steps < 100 )\n    {\n        // Update old value\n        ++steps;\n        oldX = newX;\n        double SH_old( sh_eval( oldX, coeff ) );\n\n        // define the delta steps\n        ColumnVector dt( oldX );\n        ColumnVector dp( oldX );\n        dt( 2 ) += eps;\n        dp( 3 ) += eps;\n\n        // calculate Jacobian\n        double Jt( ( FMath::sh_eval( dt, coeff ) - SH_old ) );\n        double Jp( ( FMath::sh_eval( dp, coeff ) - SH_old ) );\n\n        // do iteration\n        newX( 2 ) = oldX( 2 ) + Jt;\n        newX( 3 ) = oldX( 3 ) + Jp;\n\n        delta = fabs( Jt ) + fabs( Jp );\n        //std::cout<<delta<<\" \";\n    }\n    return newX;\n}\n\n///* ***************************************************************************\n///* @file math.cpp\n///* @fn double sh_eval(\n///*\n///*     const Vector& position,\n///*     const Vector& coeff,\n///*     const unsigned long max_order )\n///*\n///* @brief Evaluates a spherical harmonic function defined by its coefficients\n///* in direction of the position vector.\n///*\n///* important: this function works in place.                               <br>\n///*\n///* For further information view:                                          <br>\n///*  Cormen, Leiversn, Rivest, and Stein: Introduction to Algorithms       <br>\n///*  Wikipedia article on bubble sort.\n///*\n///* @param Vector: values the vector which determies the sorting\n///* @param Vector: indices to be sorted going along\n///*\n///* @return TODO\n///* ***************************************************************************\ndouble FMath::sh_eval( const ColumnVector& position, const ColumnVector& coeff )\n{\n    const int max_order( ( -3 + static_cast<int>( sqrt( 8 * coeff.Nrows() ) + 1 ) ) / 2 );\n\n    const double radius( position( 1 ) );\n    if ( radius == 0.0 )\n    {\n        return 0.0;\n    }\n\n    // for easier readability\n    const double theta( position( 2 ) );\n    const double phi( position( 3 ) );\n\n    double result( 0 );\n    for ( int order( 0 ), j( 1 ); order <= max_order; order += 2 )\n    {\n        for ( int degree( -order ); degree <= order; degree++, ++j )\n        {\n            result += coeff( j ) * FMath::sh_base_function( order, degree, theta, phi );\n        }\n    }\n    return result;\n}\n\n// calculate rotation matrix: http://en.wikipedia.org/wiki/Rotation_matrix\nMatrix FMath::RotationMatrix( const double angle, const ColumnVector& axis )\n{\n    double s( sin( angle ) );\n    double c( cos( angle ) );\n    double d( 1. - c );\n\n    Matrix R( 3, 3 );\n    R( 1, 1 ) = c + axis( 1 ) * axis( 1 ) * d;\n    R( 1, 2 ) = axis( 1 ) * axis( 2 ) * d - axis( 3 ) * s;\n    R( 1, 3 ) = axis( 1 ) * axis( 3 ) * d + axis( 2 ) * s;\n    R( 2, 1 ) = axis( 1 ) * axis( 2 ) * d + axis( 3 ) * s;\n    R( 2, 2 ) = c + axis( 1 ) * axis( 1 ) * d;\n    R( 2, 3 ) = axis( 2 ) * axis( 3 ) * d - axis( 1 ) * s;\n    R( 3, 1 ) = axis( 1 ) * axis( 3 ) * d - axis( 2 ) * s;\n    R( 3, 2 ) = axis( 2 ) * axis( 3 ) * d + axis( 1 ) * s;\n    R( 3, 3 ) = c + axis( 3 ) * axis( 3 ) * d;\n\n    return R;\n}\n\nvoid FMath::debugColumnVector3( const ColumnVector& v, QString name )\n{\n    if ( v.Nrows() != 3 )\n    {\n        qDebug() << name << \"error not 3 elements in vector\";\n    }\n    qDebug() << name << v( 1 ) << v( 2 ) << v( 3 );\n}\n\nMatrix FMath::pseudoInverse( const Matrix& A )\n{\n    /*\n    Matrix U( A.Nrows(), A.Ncols() );\n    DiagonalMatrix D( A.Ncols() );\n    Matrix V( A.Ncols(), A.Ncols() );\n    SVD( A, D, U, V );\n    return ( V * ( D.t() * D ) * D.t() * U.t() );\n    */\n\n    return ( ( A.t() * A ).i() * A.t() );\n}\n\nvoid FMath::fitTensors( QVector<ColumnVector>& data, QVector<float>& b0Images, QVector<QVector3D>& bvecs, QVector<float>& bvals, QVector<Matrix>& out )\n{\n    int N = bvecs.size();\n\n    Matrix B( N, 6 );\n    Matrix U( N, 6 );\n    Matrix V( 6, 6 );\n    Matrix BI( 6, N );\n    DiagonalMatrix D( 6 );\n\n    double mult_c;\n\n    for ( int i = 0; i < N; ++i )\n    {\n        mult_c = bvals[i] / (float) ( bvecs[i].x() * bvecs[i].x() + bvecs[i].y() * bvecs[i].y() + bvecs[i].z() * bvecs[i].z() );\n\n        B( i + 1, 1 ) = mult_c * bvecs[i].x() * bvecs[i].x();\n        B( i + 1, 2 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].y();\n        B( i + 1, 3 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].z();\n        B( i + 1, 4 ) = mult_c * bvecs[i].y() * bvecs[i].y();\n        B( i + 1, 5 ) = 2 * mult_c * bvecs[i].y() * bvecs[i].z();\n        B( i + 1, 6 ) = mult_c * bvecs[i].z() * bvecs[i].z();\n    }\n\n    SVD( B, D, U, V );\n\n    for ( int j = 1; j <= 6; ++j )\n    {\n        D( j ) = 1. / D( j );\n    }\n    BI = V * D * U.t();\n\n    double s0 = 0.0;\n    double si = 0.0;\n    vector<double> log_s0_si_pixel( N );\n\n    out.clear();\n    out.reserve( data.size() );\n\n    Matrix blank( 3, 3 );\n    blank = 0.0;\n\n    for ( int i = 0; i < data.size(); ++i )\n    {\n        s0 = b0Images.at( i );\n\n        if ( s0 > 0 )\n        {\n            // compute log(s0)-log(si)\n            s0 = log( s0 );\n            for ( int j = 0; j < N; ++j )\n            {\n                si = data.at( i )( j + 1 ); //dti[j*blockSize+i];\n                if ( si > 0 )\n                {\n                    si = log( si );\n                }\n                else\n                {\n                    si = 0.0;\n                }\n                log_s0_si_pixel[j] = s0 - si;\n            }\n\n            double value;\n            // compute tensor\n            ColumnVector t( 6 );\n            for ( int l = 0; l < 6; l++ )\n            {\n                value = 0;\n                for ( int m = 1; m <= N; ++m )\n                {\n                    value += BI( l + 1, m ) * log_s0_si_pixel[m - 1];\n                }\n                t( l + 1 ) = (float) ( value ); // save the tensor components in a adjacent memory\n            }\n            Matrix m( 3, 3 );\n            m( 1, 1 ) = t( 1 );\n            m( 1, 2 ) = t( 2 );\n            m( 1, 3 ) = t( 3 );\n            m( 2, 1 ) = t( 2 );\n            m( 2, 2 ) = t( 4 );\n            m( 2, 3 ) = t( 5 );\n            m( 3, 1 ) = t( 3 );\n            m( 3, 2 ) = t( 5 );\n            m( 3, 3 ) = t( 6 );\n\n            out.push_back( m );\n        } // end if s0 > 0\n        else\n        {\n            out.push_back( blank );\n        }\n    }\n}\n\nvoid FMath::fa( QVector<Matrix>& tensors, QVector<float>& faOut )\n{\n    int blockSize = tensors.size();\n\n    faOut.resize( blockSize );\n\n    QVector<float> trace( blockSize );\n    float value = 0;\n    for ( int i = 0; i < blockSize; ++i )\n    {\n        value = tensors.at( i )( 1, 1 );\n        value += tensors.at( i )( 2, 2 );\n        value += tensors.at( i )( 3, 3 );\n        trace[i] = value / 3.0;\n    }\n\n    QVector<float> fa( blockSize );\n\n    double xx, xy, xz, yy, yz, zz, tr, AA, DD;\n\n    for ( int i = 0; i < blockSize; ++i )\n    {\n        xx = tensors.at( i )( 1, 1 );\n        xy = tensors.at( i )( 1, 2 );\n        xz = tensors.at( i )( 1, 3 );\n        yy = tensors.at( i )( 2, 2 );\n        yz = tensors.at( i )( 2, 3 );\n        zz = tensors.at( i )( 3, 3 );\n        tr = trace[i];\n\n        AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n        DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n\n        if ( DD > 0 )\n        {\n            faOut[i] = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );\n        }\n        else\n        {\n            faOut[i] = 0.0;\n        }\n    }\n}\n\nfloat FMath::fa( Matrix tensor )\n{\n    float trace;\n    float value = 0;\n    value = tensor( 1, 1 );\n    value += tensor( 2, 2 );\n    value += tensor( 3, 3 );\n    trace = value / 3.0;\n\n    float fa;\n\n    double xx, xy, xz, yy, yz, zz, tr, AA, DD;\n\n    xx = tensor( 1, 1 );\n    xy = tensor( 1, 2 );\n    xz = tensor( 1, 3 );\n    yy = tensor( 2, 2 );\n    yz = tensor( 2, 3 );\n    zz = tensor( 3, 3 );\n    tr = trace;\n\n    AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n    DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n\n    if ( DD > 0 )\n    {\n        fa = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );\n    }\n    else\n    {\n        fa = 0.0;\n    }\n    return fa;\n}\n\nvoid FMath::evec1( QVector<Matrix>& tensors, QVector<QVector3D>& evec1 )\n{\n    int blockSize = tensors.size();\n\n    evec1.resize( blockSize );\n\n    double xx, xy, xz, yy, yz, zz;\n    double i1, i2, i3, v, s, phi, l1, l2, l3;\n    double vec_norm, ev1_x, ev1_y, ev1_z;\n\n    for ( int i = 0; i < blockSize; ++i )\n    {\n        xx = tensors.at( i )( 1, 1 );\n        xy = tensors.at( i )( 1, 2 );\n        xz = tensors.at( i )( 1, 3 );\n        yy = tensors.at( i )( 2, 2 );\n        yz = tensors.at( i )( 2, 3 );\n        zz = tensors.at( i )( 3, 3 );\n\n        // three invariants of D (dt)\n        // i1=l1+l2+l3 (trace)\n        // i2=l1*l2+l1*l3+l2*l3\n        // i3=l1*l2*l3 (determinante)\n        i1 = xx + yy + zz;\n        i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n        i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n        v = pow2( i1 / 3 ) - i2 / 3;\n        s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n        if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n            phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n        else\n            phi = 0;\n\n        // eigenvalues\n        if ( phi != 0 )\n        {\n            l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n            l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n            l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n        }\n        else\n            l1 = l2 = l3 = 0.0;\n\n        // eigenvectors\n        ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n        ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n        ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n        vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n        if ( vec_norm > 0 )\n        {\n            ev1_x = ev1_x / vec_norm;\n            ev1_y = ev1_y / vec_norm;\n            ev1_z = ev1_z / vec_norm;\n        }\n        else\n            ev1_x = ev1_y = ev1_z = 0.0;\n\n        evec1[i].setX( ev1_x );\n        evec1[i].setY( ev1_y );\n        evec1[i].setZ( ev1_z );\n    }\n}\n\nvoid FMath::evecs( QVector<Matrix>& tensors, QVector<QVector3D>& evec1, QVector<float>& eval1,\n                                               QVector<QVector3D>& evec2, QVector<float>& eval2,\n                                               QVector<QVector3D>& evec3, QVector<float>& eval3 )\n{\n    int blockSize = tensors.size();\n\n    evec1.resize( blockSize );\n    evec2.resize( blockSize );\n    evec3.resize( blockSize );\n    eval1.resize( blockSize );\n    eval2.resize( blockSize );\n    eval3.resize( blockSize );\n\n    double xx, xy, xz, yy, yz, zz;\n    double i1, i2, i3, v, s, phi, l1, l2, l3;\n    double vec_norm, ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z;\n\n    for ( int i = 0; i < blockSize; ++i )\n    {\n        xx = tensors.at( i )( 1, 1 );\n        xy = tensors.at( i )( 1, 2 );\n        xz = tensors.at( i )( 1, 3 );\n        yy = tensors.at( i )( 2, 2 );\n        yz = tensors.at( i )( 2, 3 );\n        zz = tensors.at( i )( 3, 3 );\n\n        // three invariants of D (dt)\n        // i1=l1+l2+l3 (trace)\n        // i2=l1*l2+l1*l3+l2*l3\n        // i3=l1*l2*l3 (determinante)\n        i1 = xx + yy + zz;\n        i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n        i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n        v = pow2( i1 / 3 ) - i2 / 3;\n        s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n        if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n            phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n        else\n            phi = 0;\n\n        // eigenvalues\n        if ( phi != 0 )\n        {\n            l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n            l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n            l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n        }\n        else\n            l1 = l2 = l3 = 0.0;\n\n        eval1[i] = l1;\n        eval2[i] = l2;\n        eval3[i] = l3;\n\n        // eigenvectors\n        ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n        ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n        ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n        ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n        ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n        ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n        ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n        ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n        ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n        vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n        if ( vec_norm > 0 )\n        {\n            ev1_x = ev1_x / vec_norm;\n            ev1_y = ev1_y / vec_norm;\n            ev1_z = ev1_z / vec_norm;\n        }\n        else\n            ev1_x = ev1_y = ev1_z = 0.0;\n\n        vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );\n\n        if ( vec_norm > 0 )\n        {\n            ev2_x = ev2_x / vec_norm;\n            ev2_y = ev2_y / vec_norm;\n            ev2_z = ev2_z / vec_norm;\n        }\n        else\n            ev2_x = ev2_y = ev2_z = 0.0;\n\n        vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );\n\n        if ( vec_norm > 0 )\n        {\n            ev3_x = ev3_x / vec_norm;\n            ev3_y = ev3_y / vec_norm;\n            ev3_z = ev3_z / vec_norm;\n        }\n        else\n            ev3_x = ev3_y = ev3_z = 0.0;\n\n        evec1[i].setX( ev1_x );\n        evec1[i].setY( ev1_y );\n        evec1[i].setZ( ev1_z );\n        evec2[i].setX( ev2_x );\n        evec2[i].setY( ev2_y );\n        evec2[i].setZ( ev2_z );\n        evec3[i].setX( ev3_x );\n        evec3[i].setY( ev3_y );\n        evec3[i].setZ( ev3_z );\n    }\n}\n\nMatrix FMath::expT( Matrix& t )\n{\n    double xx, xy, xz, yy, yz, zz;\n    double i1, i2, i3, v, s, phi, l1, l2, l3;\n    double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;\n\n    xx = t( 1, 1 );\n    xy = t( 1, 2 );\n    xz = t( 1, 3 );\n    yy = t( 2, 2 );\n    yz = t( 2, 3 );\n    zz = t( 3, 3 );\n\n    // three invariants of D (dt)\n    // i1=l1+l2+l3 (trace)\n    // i2=l1*l2+l1*l3+l2*l3\n    // i3=l1*l2*l3 (determinante)\n    i1 = xx + yy + zz;\n    i2 = xx * yy + xx * zz + yy * zz - ( FMath::pow2( xy ) + FMath::pow2( xz ) + FMath::pow2( yz ) );\n    i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * FMath::pow2( xy ) + yy * FMath::pow2( xz ) + xx * FMath::pow2( yz ) );\n\n    v = FMath::pow2( i1 / 3 ) - i2 / 3;\n    s = FMath::pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n    if ( ( v > 0 ) && ( FMath::pow2( s ) < FMath::pow3( v ) ) )\n        phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n    else\n        phi = 0;\n\n    // eigenvalues\n    if ( phi != 0 )\n    {\n        l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n        l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n        l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n    }\n    else\n        l1 = l2 = l3 = 0.0;\n    /*\n     eval1[i] = l1;\n     eval2[i] = l2;\n     eval3[i] = l3;\n     */\n    // eigenvectors\n    ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n    ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n    ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n    ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n    ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n    ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n    ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n    ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n    ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n    vec_norm = sqrt( FMath::pow2( ev1_x ) + FMath::pow2( ev1_y ) + FMath::pow2( ev1_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev1_x = ev1_x / vec_norm;\n        ev1_y = ev1_y / vec_norm;\n        ev1_z = ev1_z / vec_norm;\n    }\n    else\n        ev1_x = ev1_y = ev1_z = 0.0;\n\n    vec_norm = sqrt( FMath::pow2( ev2_x ) + FMath::pow2( ev2_y ) + FMath::pow2( ev2_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev2_x = ev2_x / vec_norm;\n        ev2_y = ev2_y / vec_norm;\n        ev2_z = ev2_z / vec_norm;\n    }\n    else\n        ev2_x = ev2_y = ev2_z = 0.0;\n\n    vec_norm = sqrt( FMath::pow2( ev3_x ) + FMath::pow2( ev3_y ) + FMath::pow2( ev3_z ) );\n\n    if ( vec_norm > 0 )\n    {\n        ev3_x = ev3_x / vec_norm;\n        ev3_y = ev3_y / vec_norm;\n        ev3_z = ev3_z / vec_norm;\n    }\n    else\n        ev3_x = ev3_y = ev3_z = 0.0;\n\n    Matrix U( 3, 3 );\n    DiagonalMatrix D( 3 );\n\n    U( 1, 1 ) = ev1_x;\n    U( 2, 1 ) = ev1_y;\n    U( 3, 1 ) = ev1_z;\n    U( 1, 2 ) = ev2_x;\n    U( 2, 2 ) = ev2_y;\n    U( 3, 2 ) = ev2_z;\n    U( 1, 3 ) = ev3_x;\n    U( 2, 3 ) = ev3_y;\n    U( 3, 3 ) = ev3_z;\n    D( 1 ) = exp( l1 );\n    D( 2 ) = exp( l2 );\n    D( 3 ) = exp( l3 );\n    Matrix expM(3,3);\n    expM = U * D * U.t();\n\n    return expM;\n}\n//void evd3x3_2( ColumnVector tensor, QVector<ColumnVector>& vecs, ColumnVector& vals );\nvoid FMath::evd3x3_2( ColumnVector &d, QVector<ColumnVector>& vec, ColumnVector& val )\n{\n    if ( d.Nrows() != 6 )\n        throw std::invalid_argument( \"Tensor (6-component vector) expected!\" );\n\n    // calculate the eigenvalues:\n    val = ColumnVector( 3 );\n    vec.reserve( 3 );\n    std::vector<int> index( 3 );\n\n    ColumnVector e( 3 );\n    // Create work variables:\n    Matrix A( 3, 3 ), Q( 3, 3 );\n    A( 1, 1 ) = d( 1 );\n    A( 2, 1 ) = A( 1, 2 ) = d( 2 );\n    A( 3, 1 ) = A( 1, 3 ) = d( 3 );\n    A( 2, 2 ) = d( 4 );\n    A( 3, 2 ) = A( 2, 3 ) = d( 5 );\n    A( 3, 3 ) = d( 6 );\n\n    double m, c1, c0;\n\n    // Determine coefficients of characteristic poynomial. We write\n    //       | a   d   f  |\n    //  A =  | d*  b   e  |\n    //       | f*  e*  c  |\n    double de = A( 1, 2 ) * A( 2, 3 );                                    // d * e\n    double dd = A( 1, 2 ) * A( 1, 2 );                                         // d^2\n    double ee = A( 2, 3 ) * A( 2, 3 );                                         // e^2\n    double ff = A( 1, 3 ) * A( 1, 3 );                                         // f^2\n    m = A( 1, 1 ) + A( 2, 2 ) + A( 3, 3 );\n    c1 = ( A( 1, 1 ) * A( 2, 2 ) + A( 1, 1 ) * A( 3, 3 ) + A( 2, 2 ) * A( 3, 3 ) )        // a*b + a*c + b*c - d^2 - e^2 - f^2\n    - ( dd + ee + ff );\n    c0 = A( 3, 3 ) * dd + A( 1, 1 ) * ee + A( 2, 2 ) * ff - A( 1, 1 ) * A( 2, 2 ) * A( 3, 3 ) - 2.0 * A( 1, 3 ) * de; // c*d^2 + a*e^2 + b*f^2 - a*b*c - 2*f*d*e)\n\n    double p, sqrt_p, q, c, s, phi;\n    p = m * m - 3.0 * c1;\n    q = m * ( p - ( 3.0 / 2.0 ) * c1 ) - ( 27.0 / 2.0 ) * c0;\n    sqrt_p = sqrt( fabs( p ) );\n\n    phi = 27.0 * ( 0.25 * c1 * c1 * ( p - c1 ) + c0 * ( q + 27.0 / 4.0 * c0 ) );\n    phi = ( 1.0 / 3.0 ) * atan2( sqrt( fabs( phi ) ), q );\n\n    c = sqrt_p * cos( phi );\n    s = ( 1.0 / sqrt( 3.0 ) ) * sqrt_p * sin( phi );\n\n    e( 2 ) = ( 1.0 / 3.0 ) * ( m - c );\n    e( 3 ) = e( 2 ) + s;\n    e( 1 ) = e( 2 ) + c;\n    e( 2 ) -= s;\n\n    if ( e( 1 ) > e( 2 ) )\n    {\n        if ( e( 1 ) > e( 3 ) )\n        {\n            if ( e( 2 ) > e( 3 ) )\n            {\n                index = { 0,1,2};\n            }\n            else\n            {\n                index = {0,2,1};\n            }\n        }\n        else\n        {\n            index = { 2,0,1};\n        }\n    }\n    else\n    {\n        if( e(2) > e(3) )\n        {\n            if( e(1) > e(3) )\n            {\n                index = {   1,0,2};\n            }\n            else\n            {\n                index = {   1,2,0};\n            }\n        }\n        else\n        {\n            index = {2,1,0};\n        }\n    }\n\n    for ( unsigned long i( 1 ); i < 4; ++i )\n        val( i ) = e( index[i-1]+1 );\n\n    double wmax = ( fabs( val( 1 ) ) > fabs( val( 3 ) ) ) ? val( 1 ) : val( 3 );\n    double thresh = ( 8.0 * DBL_EPSILON * wmax ) * ( 8.0 * DBL_EPSILON * wmax );\n\n    // Prepare calculation of eigenvectors:\n    double n0tmp = A( 1, 2 ) * A( 1, 2 ) + A( 1, 3 ) * A( 1, 3 );\n    double n1tmp = A( 1, 2 ) * A( 1, 2 ) + A( 2, 3 ) * A( 2, 3 );\n    Q( 1, 2 ) = A( 1, 2 ) * A( 2, 3 ) - A( 1, 3 ) * A( 2, 2 );\n    Q( 2, 2 ) = A( 1, 3 ) * A( 2, 1 ) - A( 2, 3 ) * A( 1, 1 );\n    Q( 3, 2 ) = A( 1, 2 ) * A( 1, 2 );\n\n    // Calculate first eigenvector by the formula\n    //   v(0) = (A - w(0)).e1 x (A - w(0)).e2\n    A( 1, 1 ) -= val( 1 );\n    A( 2, 2 ) -= val( 1 );\n    Q( 1, 1 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );\n    Q( 2, 1 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );\n    Q( 3, 1 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );\n    double norm = Q( 1, 1 ) * Q( 1, 1 ) + Q( 2, 1 ) * Q( 2, 1 ) + Q( 3, 1 ) * Q( 3, 1 );\n    double n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );\n    double n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );\n    double error = n0 * n1;\n    double t( 0 ), f( 0 );\n    unsigned long i( 0 ), j( 0 );\n\n    if ( n0 <= thresh )         // If the first column is zero, then (1,0,0) is an eigenvector\n    {\n        Q( 1, 1 ) = 1.0;\n        Q( 2, 1 ) = 0.0;\n        Q( 3, 1 ) = 0.0;\n    }\n    else if ( n1 <= thresh )    // If the second column is zero, then (0,1,0) is an eigenvector\n    {\n        Q( 1, 1 ) = 0.0;\n        Q( 2, 1 ) = 1.0;\n        Q( 3, 1 ) = 0.0;\n    }\n    else if ( norm < 64.0 * 64.0 * DBL_EPSILON * DBL_EPSILON * error )\n    {                         // If angle between A(0) and A(1) is too small, don't use\n        t = A( 1, 2 ) * A( 1, 2 );       // cross product, but calculate v ~ (1, -A0/A1, 0)\n        f = -A( 1, 1 ) / A( 1, 2 );\n        if ( A( 2, 2 ) * A( 2, 2 ) > t )\n        {\n            t = A( 2, 2 ) * A( 2, 2 );\n            f = -A( 1, 2 ) / A( 2, 2 );\n        }\n        if ( A( 2, 3 ) * A( 2, 3 ) > t )\n            f = -A( 1, 3 ) / A( 2, 3 );\n        norm = 1.0 / sqrt( 1 + f * f );\n        Q( 1, 1 ) = norm;\n        Q( 2, 1 ) = f * norm;\n        Q( 3, 1 ) = 0.0;\n    }\n    else                      // This is the standard branch\n    {\n        norm = sqrt( 1.0 / norm );\n        for ( j = 1; j < 4; ++j )\n            Q( j, 1 ) = Q( j, 1 ) * norm;\n    }\n\n    // Prepare calculation of second eigenvector\n    t = val( 1 ) - val( 2 );\n    if ( fabs( t ) > 8.0 * DBL_EPSILON * wmax )\n    {\n        // For non-degenerate eigenvalue, calculate second eigenvector by the formula\n        //   v(1) = (A - w(1)).e1 x (A - w(1)).e2\n        A( 1, 1 ) += t;\n        A( 2, 2 ) += t;\n        Q( 1, 2 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );\n        Q( 2, 2 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );\n        Q( 3, 2 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );\n        norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );\n        n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );\n        n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );\n        error = n0 * n1;\n\n        if ( n0 <= thresh )       // If the first column is zero, then (1,0,0) is an eigenvector\n        {\n            Q( 1, 2 ) = 1.0;\n            Q( 2, 2 ) = 0.0;\n            Q( 3, 2 ) = 0.0;\n        }\n        else if ( n1 <= thresh )  // If the second column is zero, then (0,1,0) is an eigenvector\n        {\n            Q( 1, 2 ) = 0.0;\n            Q( 2, 2 ) = 1.0;\n            Q( 3, 2 ) = 0.0;\n        }\n        else if ( norm < 64.0 * DBL_EPSILON * 64.0 * DBL_EPSILON * error )\n        {                       // If angle between A(0) and A(1) is too small, don't use\n            t = A( 1, 2 ) * A( 1, 2 );     // cross product, but calculate v ~ (1, -A0/A1, 0)\n            f = -A( 1, 1 ) / A( 1, 2 );\n            if ( A( 2, 2 ) * A( 2, 2 ) > t )\n            {\n                t = A( 2, 2 ) * A( 2, 2 );\n                f = -A( 1, 2 ) / A( 2, 2 );\n            }\n            if ( A( 2, 3 ) * A( 2, 3 ) > t )\n                f = -A( 1, 3 ) / A( 2, 3 );\n            norm = 1.0 / sqrt( 1 + f * f );\n            Q( 1, 2 ) = norm;\n            Q( 2, 2 ) = f * norm;\n            Q( 3, 2 ) = 0.0;\n        }\n        else\n        {\n            norm = sqrt( 1.0 / norm );\n            for ( j = 1; j < 4; ++j )\n                Q( j, 2 ) = Q( j, 2 ) * norm;\n        }\n    }\n    else\n    {\n        // For degenerate eigenvalue, calculate second eigenvector according to\n        //   v(1) = v(0) x (A - w(1)).e(i)\n        //\n        // This would really get to complicated if we could not assume all of A to\n        // contain meaningful values.\n        A( 2, 1 ) = A( 1, 2 );\n        A( 3, 1 ) = A( 1, 3 );\n        A( 3, 2 ) = A( 2, 3 );\n        A( 1, 1 ) += val( 1 );\n        A( 2, 2 ) += val( 1 );\n        for ( i = 1; i < 4; ++i )\n        {\n            A( i, i ) -= val( 2 );\n            n0 = A( 1, i ) * A( 1, i ) + A( 2, i ) * A( 2, i ) + A( 3, i ) * A( 3, i );\n            if ( n0 > thresh )\n            {\n                Q( 1, 2 ) = Q( 2, 1 ) * A( 3, i ) - Q( 3, 1 ) * A( 2, i );\n                Q( 2, 2 ) = Q( 3, 1 ) * A( 1, i ) - Q( 1, 1 ) * A( 3, i );\n                Q( 3, 2 ) = Q( 1, 1 ) * A( 2, i ) - Q( 2, 1 ) * A( 1, i );\n                norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );\n                if ( norm > 256.0 * DBL_EPSILON * 256.0 * DBL_EPSILON * n0 ) // Accept cross product only if the angle between\n                {                                         // the two vectors was not too small\n                    norm = sqrt( 1.0 / norm );\n                    for ( j = 1; j < 4; ++j )\n                        Q( j, 2 ) = Q( j, 2 ) * norm;\n                    break;\n                }\n            }\n        }\n\n        if ( i == 4 )    // This means that any vector orthogonal to v(0) is an EV.\n        {\n            for ( j = 1; j < 4; ++j )\n                if ( Q( j, 1 ) != 0.0 )                                   // Find nonzero element of v(0) ...\n                {                                                     // ... and swap it with the next one\n                    norm = 1.0 / sqrt( Q( j, 1 ) * Q( j, 1 ) + Q( ( j + 2 ) % 3 + 1, 1 ) * Q( ( j + 1 ) % 3 + 1, 1 ) );\n                    Q( j, 2 ) = Q( ( j + 1 ) % 3 + 1, 1 ) * norm;\n                    Q( ( j + 1 ) % 3 + 1, 2 ) = -Q( j, 1 ) * norm;\n                    Q( ( j + 2 ) % 3 + 1, 2 ) = 0.0;\n                    break;\n                }\n        }\n    }\n\n    // Calculate third eigenvector according to\n    //   v(2) = v(0) x v(1)\n    Q( 1, 3 ) = Q( 2, 1 ) * Q( 3, 2 ) - Q( 3, 1 ) * Q( 2, 2 );\n    Q( 2, 3 ) = Q( 3, 1 ) * Q( 1, 2 ) - Q( 1, 1 ) * Q( 3, 2 );\n    Q( 3, 3 ) = Q( 1, 1 ) * Q( 2, 2 ) - Q( 2, 1 ) * Q( 1, 2 );\n\n    vec.clear();\n    for ( int ii( 1 ); ii < 4; ++ii )\n    {\n        ColumnVector tmp( 3 );\n\n        tmp( 1 ) = Q( 1, ii );\n        tmp( 2 ) = Q( 2, ii );\n        tmp( 3 ) = Q( 3, ii );\n\n        vec.push_back( tmp );\n    }\n\n}\n\nbool FMath::linePlaneIntersection( QVector3D& contact, QVector3D ray, QVector3D rayOrigin, QVector3D normal, QVector3D coord )\n{\n    // calculate plane\n    float d = QVector3D::dotProduct( normal, coord );\n\n    if ( QVector3D::dotProduct( normal, ray ) == 0 )\n    {\n        return false; // avoid divide by zero\n    }\n\n    // Compute the t value for the directed line ray intersecting the plane\n    float t = ( d - QVector3D::dotProduct( normal, rayOrigin ) ) / QVector3D::dotProduct( normal, ray );\n\n    // scale the ray by t\n    QVector3D newRay = ray * t;\n\n    // calc contact point\n    contact = rayOrigin + newRay;\n\n    if ( t >= 0.0f && t <= 1.0f )\n    {\n        return true; // line intersects plane\n    }\n    return false; // line does not\n}\n", "meta": {"hexsha": "5eca1173bcd8decc94a75037514d66d74e9ecacd", "size": 37582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algos/fmath.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/fmath.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/fmath.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": 30.3570274637, "max_line_length": 161, "alphanum_fraction": 0.4148794636, "num_tokens": 14266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6527787233999957}}
{"text": "#include <optional>\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"decode.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric;\nusing boost::dynamic_bitset;\n\n\nstatic const auto parity_mat = [] {\n    ublas::matrix<bool> parity_m(3, 7);\n    vector<bool> parity_init = {\n        1, 0, 1, 0, 1, 0, 1,\n        0, 1, 1, 0, 0, 1, 1,\n        0, 0, 0, 1, 1, 1, 1\n    };\n\n    copy(parity_init.begin(),\n         parity_init.end(),\n         parity_m.data().begin()\n    );\n\n    return parity_m;\n}();\n\nstatic const auto decode_mat = [] {\n    ublas::matrix<bool> decode_m(4, 7);\n    vector<bool> decode_init = {\n        0, 0, 1, 0, 0, 0, 0,\n        0, 0, 0, 0, 1, 0, 0,\n        0, 0, 0, 0, 0, 1, 0,\n        0, 0, 0, 0, 0, 0, 1\n    };\n\n    copy(decode_init.begin(),\n         decode_init.end(),\n         decode_m.data().begin()\n    );\n\n    return decode_m;\n}();\n\n\noptional<uint8_t> parity_check(const ublas::matrix<bool> &code_mat) {\n    auto syndrome = ublas::prod(parity_mat, code_mat);\n\n    dynamic_bitset<uint8_t> error_bs;\n    for_each(syndrome.begin1(), syndrome.end1(), [&error_bs](auto v) {\n        error_bs.push_back(v % 2);\n    });\n\n    auto error = error_bs.to_ulong();\n\n    if (error == 0) { return {}; }\n    else { return error - 1; }\n}\n\n\nvector<uint8_t> decode(const vector<uint8_t> &bytes) {\n    dynamic_bitset<uint8_t> data;\n    data.init_from_block_range(bytes.begin(), bytes.end());\n\n    bool back = data[data.size() - 1]; data.pop_back();\n    while (!back) {\n        back = data[data.size() - 1]; data.pop_back();\n    }\n\n    dynamic_bitset<uint8_t> result;\n\n    for (auto p = 0u; p < data.size(); p += 7) {\n        ublas::matrix<bool> code_mat(7, 1);\n        vector<bool> code_init;\n\n        for (auto i = 0u; i < 7; ++i) {\n            code_init.push_back(data[p+i]);\n        }\n        \n        copy(code_init.begin(),\n             code_init.end(),\n             code_mat.data().begin()\n        );\n\n        if (auto error = parity_check(code_mat); error) {\n            code_mat(error.value(), 0) ^= true;\n        }\n\n        auto prod = ublas::prod(decode_mat, code_mat);\n\n        for_each(prod.begin1(), prod.end1(), [&result] (auto v) {\n            result.push_back(v % 2);\n        });\n    }\n\n    vector<uint8_t> blocks(result.num_blocks());\n    to_block_range(result, blocks.begin());\n\n    return blocks;\n}", "meta": {"hexsha": "bfd512c1dd665a0471e15d069f36018b1234c5b5", "size": 2357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decode.cpp", "max_stars_repo_name": "Learko/Hamming", "max_stars_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decode.cpp", "max_issues_repo_name": "Learko/Hamming", "max_issues_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decode.cpp", "max_forks_repo_name": "Learko/Hamming", "max_forks_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_forks_repo_licenses": ["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.3366336634, "max_line_length": 70, "alphanum_fraction": 0.5549427238, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6527787204187534}}
{"text": "//\n// Created by Hamza El-Kebir on 4/17/21.\n//\n\n#ifndef LODESTAR_STATESPACE_HPP\n#define LODESTAR_STATESPACE_HPP\n\n#include \"SystemStateless.hpp\"\n#include <Eigen/Dense>\n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\nnamespace ls {\n    namespace systems {\n        template<typename TScalar = double, const int TStateDim = Eigen::Dynamic, const int TInputDim = Eigen::Dynamic, const int TOutputDim = Eigen::Dynamic>\n        class StateSpace : public SystemStateless {\n        public:\n            typedef Eigen::Matrix<TScalar, TStateDim, TStateDim> TDStateMatrix;\n            typedef Eigen::Matrix<TScalar, TStateDim, TInputDim> TDInputMatrix;\n            typedef Eigen::Matrix<TScalar, TOutputDim, TStateDim> TDOutputMatrix;\n            typedef Eigen::Matrix<TScalar, TOutputDim, TInputDim> TDFeedforwardMatrix;\n\n            /**\n             * @brief Default constructor.\n             */\n            StateSpace() : A_(new TDStateMatrix),\n                           B_(new TDInputMatrix),\n                           C_(new TDOutputMatrix),\n                           D_(new TDFeedforwardMatrix),\n                           dt_(-1), isDiscrete_(false)\n            {\n                A_->setIdentity();\n                B_->setIdentity();\n                C_->setIdentity();\n                D_->setZero();\n            };\n\n            /**\n             * @brief Construct a state space system with the given matrices.\n             *\n             * @note TState space systems are assumed to be in continuous time by\n             * default.\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             */\n            StateSpace(TDStateMatrix *A, TDInputMatrix *B,\n                       TDOutputMatrix *C, TDOutputMatrix *D);\n\n            //            /**\n            //             * @brief Construct a state space system with the given matrices.\n            //             *\n            //             * @note TState space systems are assumed to be in continuous time by\n            //             * default.\n            //             *\n            //             * @param A TState matrix.\n            //             * @param B Input matrix.\n            //             * @param C Output matrix.\n            //             * @param D Feedforward matrix.\n            //             */\n            //            StateSpace(const TDStateMatrix &A, const TDInputMatrix &B,\n            //                       const TDOutputMatrix &C, const TDOutputMatrix &D);\n\n            template<typename DerivedA, typename DerivedB, typename DerivedC, typename DerivedD>\n            StateSpace(const Eigen::EigenBase<DerivedA> &A, const Eigen::EigenBase<DerivedB> &B,\n                       const Eigen::EigenBase<DerivedC> &C, const Eigen::EigenBase<DerivedD> &D);\n\n            /**\n             * @brief Copy constructor.\n             *\n             * @param other TState space object to copy.\n             */\n            StateSpace(const StateSpace &other);\n\n            /**\n             * @brief Gets the state matrix.\n             *\n             * @return TState matrix.\n             */\n            const TDStateMatrix &getA() const;\n\n            /**\n             * @brief Sets the state matrix.\n             *\n             * @param A Pointer to state matrix.\n             */\n            void setA(TDStateMatrix *A);\n\n            template<typename Derived>\n            void setA(Eigen::EigenBase<Derived> *A);\n\n            /**\n             * @brief Sets the state matrix.\n             *\n             * @param A TState matrix.\n             */\n            void setA(const TDStateMatrix &A);\n\n            template<typename Derived>\n            void setA(const Eigen::EigenBase<Derived> &A);\n\n            /**\n             * @brief Gets the input matrix.\n             *\n             * @return Input matrix.\n             */\n            const TDInputMatrix &getB() const;\n\n            /**\n             * @brief Sets the input matrix.\n             *\n             * @param B Pointer to input matrix.\n             */\n            void setB(TDInputMatrix *B);\n\n            template<typename Derived>\n            void setB(Eigen::EigenBase<Derived> *B);\n\n            /**\n             * @brief Sets the input matrix.\n             *\n             * @param B Input matrix.\n             */\n            void setB(const TDInputMatrix &B);\n\n            template<typename Derived>\n            void setB(const Eigen::EigenBase<Derived> &B);\n\n            /**\n             * @brief Gets the output matrix.\n             *\n             * @return Output matrix.\n             */\n            const TDOutputMatrix &getC() const;\n\n            /**\n             * @brief Sets the output matrix.\n             *\n             * @param C Pointer to output matrix.\n             */\n            void setC(TDOutputMatrix *C);\n\n            template<typename Derived>\n            void setC(Eigen::EigenBase<Derived> *C);\n\n            /**\n             * @brief Sets the output matrix.\n             *\n             * @param C Output matrix.\n             */\n            void setC(const TDOutputMatrix &C);\n\n            template<typename Derived>\n            void setC(const Eigen::EigenBase<Derived> &C);\n\n            /**\n             * @brief Gets the feedforward matrix.\n             *\n             * @return Feedforward matrix.\n             */\n            const TDFeedforwardMatrix &getD() const;\n\n            /**\n             * @brief Sets the feedforward matrix.\n             *\n             * @param D Feedforward matrix.\n             */\n            void setD(TDFeedforwardMatrix *D);\n\n            template<typename Derived>\n            void setD(Eigen::EigenBase<Derived> *D);\n\n            /**\n             * @brief Sets the feedforward matrix.\n             *\n             * @param D Pointer to feedforward matrix.\n             */\n            void setD(const TDFeedforwardMatrix &D);\n\n            template<typename Derived>\n            void setD(const Eigen::EigenBase<Derived> &D);\n\n            /**\n             * @brief Copies matrices from one state space object to the current\n             * instance.\n             *\n             * @param ss TState space object to copy matrices from.\n             */\n            void copyMatrices(const StateSpace &other);\n\n            /**\n             * @brief Sets the discrete time system parameters.\n             *\n             * @param dt Sampling period.\n             */\n            void setDiscreteParams(double dt);\n\n            /**\n             * @brief Sets the discrete time system parameters.\n             *\n             * @param dt Sampling period.\n             * @param discrete If true, the system is treated as a discrete time\n             * system.\n             */\n            void setDiscreteParams(double dt, bool discrete);\n\n            /**\n             * @brief Returns a bool that tells if the system is discrete.\n             *\n             * @return True if the system is discrete.\n             */\n            inline bool isDiscrete() const;\n\n            /**\n             * @brief Returns the sampling period.\n             *\n             * @return Sampling period.\n             */\n            inline double getSamplingPeriod() const;\n\n            /**\n             * @brief Sets the sampling period.\n             *\n             * @param dt Sampling period.\n             */\n            void setSamplingPeriod(double dt);\n\n            /**\n             * @brief Returns the state dimension.\n             *\n             * @return TState dimension.\n             */\n            IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline stateDim() const\n            {\n                return stateDimDynamic();\n            }\n\n            long inline stateDimDynamic() const\n            {\n                return A_->rows();\n            }\n\n            IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline stateDim() const\n            {\n                return stateDimStatic();\n            }\n\n            long inline stateDimStatic() const\n            {\n                return TStateDim;\n            }\n\n            /**\n             * @brief Returns the input dimension.\n             *\n             * @return Input dimension.\n             */\n            IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline inputDim() const\n            {\n                return inputDimDynamic();\n            }\n\n            long inline inputDimDynamic() const\n            {\n                return B_->cols();\n            }\n\n            IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline inputDim() const\n            {\n                return inputDimStatic();\n            }\n\n            long inline inputDimStatic() const\n            {\n                return TInputDim;\n            }\n\n            /**\n             * @brief Returns the output dimension.\n             *\n             * @return Output dimension\n             */\n            IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline outputDim() const\n            {\n                return outputDimDynamic();\n            }\n\n            long inline outputDimDynamic() const\n            {\n                return C_->rows();\n            }\n\n            IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n            inline outputDim() const\n            {\n                return outputDimStatic();\n            }\n\n            long inline outputDimStatic() const\n            {\n                return TOutputDim;\n            }\n\n            /**\n             * @brief Appends to state space systems.\n             *\n             * If the discrete time parameters do not match the current system,\n             * the input system is altered to match the current system.\n             *\n             * @param ss TState space system to append.\n             */\n            template<int TStateDim2, int TOutputDim2>\n            void append(const StateSpace<TScalar, TStateDim2, TOutputDim, TOutputDim2> &ss);\n\n            /**\n             * @brief Determines if the system is stable based on its\n             * eigenvalues.\n             *\n             * \\p tolerance sets the stability margin that is taken into\n             * account during computation.\n             *\n             * @param tolerance Eigenvalue tolerance.\n             * @return True if system is stable.\n             */\n            inline bool isStable(double tolerance = 0) const;\n\n            /**\n             * @brief Returns a state space representation that adds integral action to the original system.\n             *\n             * @details For details on the discrete time case, see [1].\n             *\n             * @sa D. D. Ruscio, \u201cDiscrete LQ optimal control with integral action: A simple controller on incremental\n             *  form for MIMO systems,\u201d MIC, vol. 33, no. 2, pp. 35\u201344, 2012, doi:\n             *  <a href=\"http://dx.doi.org/10.4173/mic.2012.2.1\">10.4173/mic.2012.2.1</a>.\n             *\n             * @note This particular function gets called when the state space system is dynamic.\n             *\n             * @tparam T_TScalar Copy of \\c TScalar.\n             * @tparam T_TStateDim Copy of \\c TStateDim.\n             * @tparam T_TInputDim Copy of \\c TInputDim.\n             * @tparam T_TOutputDim Copy of \\c TOutputDim.\n             *\n             * @return State space system augmented with integral action.\n             */\n            template<typename T_TScalar = TScalar, const int T_TStateDim = TStateDim, const int T_TInputDim = TInputDim, const int T_TOutputDim = TOutputDim>\n            ls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(\n                    T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim>\n            addIntegralAction(LS_IS_DYNAMIC_DEFAULT(T_TStateDim, T_TInputDim, T_TOutputDim)) const;\n\n            /**\n             * @brief Returns a state space representation that adds integral action to the original system.\n             *\n             * @details For details on the discrete time case, see [1].\n             *\n             * @sa [1] D. D. Ruscio, \u201cDiscrete LQ optimal control with integral action: A simple controller on\n             * incremental form for MIMO systems,\u201d MIC, vol. 33, no. 2, pp. 35\u201344, 2012, doi:\n             *  <a href=\"http://dx.doi.org/10.4173/mic.2012.2.1\">10.4173/mic.2012.2.1</a>.\n             *\n             * @note This particular function gets called when the state space system is static.\n             *\n             * @tparam T_TScalar Copy of \\c TScalar.\n             * @tparam T_TStateDim Copy of \\c TStateDim.\n             * @tparam T_TInputDim Copy of \\c TInputDim.\n             * @tparam T_TOutputDim Copy of \\c TOutputDim.\n             *\n             * @return State space system augmented with integral action.\n             */\n            template<typename T_TScalar = TScalar, const int T_TStateDim = TStateDim, const int T_TInputDim = TInputDim, const int T_TOutputDim = TOutputDim>\n            ls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(\n                    T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim>\n            addIntegralAction(LS_IS_STATIC_DEFAULT(T_TStateDim, T_TInputDim, T_TOutputDim)) const;\n\n        protected:\n            TDStateMatrix *A_; //! TState matrix.\n            TDInputMatrix *B_; //! Input matrix.\n            TDOutputMatrix *C_; //! Output matrix.\n            TDFeedforwardMatrix *D_; //! Feedforward matrix.\n            double dt_; //! Sampling period.\n            bool isDiscrete_; //! Discrete flag.\n        };\n    }\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::StateSpace(\n        const StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> &other):\n        A_(new TDStateMatrix(other.getA())),\n        B_(new TDInputMatrix(other.getB())),\n        C_(new TDOutputMatrix(other.getC())),\n        D_(new TDFeedforwardMatrix(other.getD())),\n        dt_(other.getSamplingPeriod()),\n        isDiscrete_(other.isDiscrete())\n{}\n\n// TODO: Replace constructors by Eigen::EigenBase<*>\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::StateSpace(\n        TDStateMatrix *A, TDInputMatrix *B,\n        TDOutputMatrix *C, TDOutputMatrix *D):\n        A_(new TDStateMatrix(*A)),\n        B_(new TDInputMatrix(*B)),\n        C_(new TDOutputMatrix(*C)),\n        D_(new TDFeedforwardMatrix(*D))\n{\n    //    *A_ = *A;\n    //    *B_ = *B;\n    //    *C_ = *C;\n    //    *D_ = *D;\n    dt_ = -1;\n    isDiscrete_ = false;\n}\n\n//template<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\n//ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::StateSpace(\n//        const TDStateMatrix &A, const TDInputMatrix &B,\n//        const TDOutputMatrix &C, const TDOutputMatrix &D) : A_(new TDStateMatrix(A)), B_(new TDInputMatrix(B)),\n//                                                            C_(new TDOutputMatrix(C)), D_(new TDFeedforwardMatrix(D))\n//{\n////    *A_ = A;\n////    *B_ = B;\n////    *C_ = C;\n////    *D_ = D;\n//    dt_ = -1;\n//    isDiscrete_ = false;\n//}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename DerivedA, typename DerivedB, typename DerivedC, typename DerivedD>\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::StateSpace(const Eigen::EigenBase<DerivedA> &A,\n                                                                               const Eigen::EigenBase<DerivedB> &B,\n                                                                               const Eigen::EigenBase<DerivedC> &C,\n                                                                               const Eigen::EigenBase<DerivedD> &D):\n        A_(new TDStateMatrix(A)),\n        B_(new TDInputMatrix(B)),\n        C_(new TDOutputMatrix(C)),\n        D_(new TDFeedforwardMatrix(D))\n{\n    *A_ = A;\n    *B_ = B;\n    *C_ = C;\n    *D_ = D;\n    dt_ = -1;\n    isDiscrete_ = false;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nconst typename ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::TDStateMatrix &\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::getA() const\n{\n    return *A_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setA(TDStateMatrix *A)\n{\n    *A_ = *A;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setA(Eigen::EigenBase<Derived> *A)\n{\n    *A_ = *A;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setA(\n        const TDStateMatrix &A)\n{\n    *A_ = A;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setA(const Eigen::EigenBase<Derived> &A)\n{\n    *A_ = A;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nconst typename ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::TDInputMatrix &\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::getB() const\n{\n    return *B_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setB(TDInputMatrix *B)\n{\n    *B_ = *B;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setB(Eigen::EigenBase<Derived> *B)\n{\n    *B_ = *B;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setB(\n        const TDInputMatrix &B)\n{\n    *B_ = B;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setB(const Eigen::EigenBase<Derived> &B)\n{\n    *B_ = B;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nconst typename ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::TDOutputMatrix &\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::getC() const\n{\n    return *C_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setC(TDOutputMatrix *C)\n{\n    *C_ = *C;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setC(Eigen::EigenBase<Derived> *C)\n{\n    *C_ = *C;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setC(\n        const TDOutputMatrix &C)\n{\n    *C_ = C;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setC(const Eigen::EigenBase<Derived> &C)\n{\n    *C_ = C;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nconst typename ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::TDFeedforwardMatrix &\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::getD() const\n{\n    return *D_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setD(\n        TDFeedforwardMatrix *D)\n{\n    *D_ = *D;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setD(Eigen::EigenBase<Derived> *D)\n{\n    *D_ = *D;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setD(\n        const TDFeedforwardMatrix &D)\n{\n    *D_ = D;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename Derived>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setD(const Eigen::EigenBase<Derived> &D)\n{\n    *D_ = D;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nbool ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::isDiscrete() const\n{\n    return isDiscrete_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\ndouble ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::getSamplingPeriod() const\n{\n    return dt_;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setSamplingPeriod(double dt)\n{\n    dt_ = dt;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setDiscreteParams(double dt)\n{\n    dt_ = dt;\n    isDiscrete_ = true;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::setDiscreteParams(double dt, bool discrete)\n{\n    dt_ = dt;\n    isDiscrete_ = discrete;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\ntemplate<int TStateDim2, int TOutputDim2>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::append(\n        const ls::systems::StateSpace<TScalar, TStateDim2, TOutputDim, TOutputDim2> &ss)\n{\n    // TODO: Implement state space append function.\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nbool ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::isStable(const double tolerance) const\n{\n    auto eig = A_->eigenvalues();\n\n    if (isDiscrete()) {\n        double tol = (tolerance < 0 ? -tolerance * tolerance : tolerance * tolerance);\n\n        for (int i = 0; i < eig.size(); i++) {\n            if (eig(i).real() * eig(i).real() + eig(i).imag() * eig(i).imag() > 1 + tol)\n                return false;\n        }\n    } else {\n        for (int i = 0; i < eig.size(); i++) {\n            if (eig(i).real() > -tolerance)\n                return false;\n        }\n    }\n\n    return true;\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::copyMatrices(\n        const ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> &other)\n{\n    setA(other.getA());\n    setB(other.getB());\n    setC(other.getC());\n    setD(other.getD());\n\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename T_TScalar, const int T_TStateDim, const int T_TInputDim, const int T_TOutputDim>\nls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim>\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::addIntegralAction(\n        LS_IS_DYNAMIC(T_TStateDim, T_TInputDim, T_TOutputDim)) const\n{\n    Eigen::Matrix<TScalar, Eigen::Dynamic, Eigen::Dynamic> A(stateDim() + outputDim(), stateDim() + outputDim());\n    A.setZero();\n    A.topLeftCorner(stateDim(), stateDim()) = getA();\n    A.bottomLeftCorner(outputDim(), stateDim()) = getC();\n    A.bottomRightCorner(outputDim(), outputDim()).setIdentity();\n\n    Eigen::Matrix<TScalar, Eigen::Dynamic, Eigen::Dynamic> B(stateDim() + outputDim(), inputDim());\n    B.setZero();\n    B.topRows(stateDim()) = getB();\n\n    Eigen::Matrix<TScalar, Eigen::Dynamic, Eigen::Dynamic> C(outputDim(), stateDim() + outputDim());\n    C.setZero();\n    C.leftCols(stateDim()) = getC();\n    C.rightCols(outputDim()).setIdentity();\n\n    Eigen::Matrix<TScalar, Eigen::Dynamic, Eigen::Dynamic> D(outputDim(), inputDim());\n    D = getD();\n\n    ls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(\n            T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim> ssi{A, B, C, D};\n\n    return ssi;\n}\n\ntemplate<typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\ntemplate<typename T_TScalar, const int T_TStateDim, const int T_TInputDim, const int T_TOutputDim>\nls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim>\nls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>::addIntegralAction(\n        LS_IS_STATIC(T_TStateDim, T_TInputDim, T_TOutputDim)) const\n{\n    Eigen::Matrix<TScalar, TStateDim + TOutputDim, TStateDim + TOutputDim> A{};\n    A.setZero();\n    A.template topLeftCorner<TStateDim, TStateDim>() = getA();\n    A.template bottomLeftCorner<TOutputDim, TStateDim>() = getC();\n    A.template bottomRightCorner<TOutputDim, TOutputDim>().setIdentity();\n\n    Eigen::Matrix<TScalar, TStateDim + TOutputDim, TInputDim> B{};\n    B.setZero();\n    B.template topRows<TStateDim>() = getB();\n\n    Eigen::Matrix<TScalar, TOutputDim, TStateDim + TOutputDim> C{};\n    C.setZero();\n    C.template leftCols<TStateDim>() = getC();\n    C.template rightCols<TOutputDim>().setIdentity();\n\n    Eigen::Matrix<TScalar, TOutputDim, TInputDim> D{};\n    D = getD();\n\n    ls::systems::StateSpace<T_TScalar, LS_STATIC_UNLESS_DYNAMIC(\n            T_TStateDim + T_TOutputDim), T_TInputDim, T_TOutputDim> ssi{A, B, C, D};\n\n    return ssi;\n}\n\n#endif //LODESTAR_STATESPACE_HPP", "meta": {"hexsha": "849949f530b85a2be95a6f3c3d0376039ca32174", "size": 26022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/systems/StateSpace.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/systems/StateSpace.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/systems/StateSpace.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": 35.9917012448, "max_line_length": 158, "alphanum_fraction": 0.5929982323, "num_tokens": 6349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6527672616759989}}
{"text": "#include \"miscMANCOVA.h\"\n#include <sstream>\n#include <boost/math/distributions/students_t.hpp>\n#include <itksys/SystemTools.hxx>\n\nusing namespace std;\nvnl_vector<double> TiedRankCalc(vnl_vector<double>& data)\n{\n  // computes ranking of values in data vector, but resolves ties by\n  // returning the average rank\n\n  vnl_vector<double> output(data.size() );\n\n  typedef double T;\n  std::vector<std::pair<T, int> > pairVector;\n  for( unsigned int i = 0; i < data.size(); ++i )\n    {\n    pairVector.push_back(std::pair<T, int>(data(i), i) );\n    }\n\n  std::sort(pairVector.begin(), pairVector.end() );\n\n  // need to go through values and average if there are ties\n\n  unsigned int lastIndex = 0;\n  double       lastValue = (pairVector[lastIndex]).first;\n  unsigned int currentIndex = 0;\n\n  if( data.size() <= 1 ) // there is no data or only one data point, so just return\n    {\n    for( unsigned int i = 0; i < data.size(); ++i )\n      {\n      output(i) = i;\n      }\n    return output;\n    }\n\n  double nextValue = (pairVector[currentIndex + 1]).first;\n\n  bool keepGoing = true;\n\n  do\n    {\n\n    while( lastValue == nextValue ) // check for ties\n      {\n      currentIndex++;\n      if( currentIndex + 1 >= data.size() ) // we are at the end\n        {\n        break;\n        }\n      else\n        {\n        nextValue = (pairVector[currentIndex + 1]).first; // check the\n        // next value\n        }\n      }\n\n    unsigned int nrOfTies = currentIndex - lastIndex + 1;\n    double       averageRankSum = 0;\n    for( unsigned int i = lastIndex; i <= currentIndex; ++i )\n      {\n      // averageRankSum += (pairVector[i]).second;\n      averageRankSum += i;\n      }\n\n    averageRankSum /= nrOfTies;\n    for( unsigned int i = lastIndex; i <= currentIndex; ++i )\n      {\n      output( (pairVector[i]).second) = averageRankSum;\n      }\n\n    if( currentIndex >= data.size() - 1 ) // we are at the end, so stop processing\n      {\n      keepGoing = false;\n      }\n    else\n      {\n      currentIndex++; // let's look at the next values\n      lastIndex = currentIndex;\n      lastValue = (pairVector[lastIndex]).first;\n\n      if( currentIndex + 1 >= data.size() ) // we are now at the end, so\n      // simply return the result\n        {\n        output( currentIndex ) = (pairVector[currentIndex]).second;\n        keepGoing = false;\n        }\n      else\n        { // there is a next value and it is the following ...\n        nextValue = (pairVector[currentIndex + 1]).first;\n        }\n      }\n\n    }\n  while( keepGoing );    // that's all folks ...\n\n  return output;\n\n}\n\ndouble computePearsonCorrelation( vnl_vector<double>& x, vnl_vector<double>& y )\n{\n  unsigned int numSubjects = x.size();\n\n  // first compute the means\n\n  double dXM = 0;\n  double dYM = 0;\n\n  for( unsigned int sub = 0; sub < numSubjects; sub++ )\n    {\n    dXM += x[sub];\n    dYM += y[sub];\n    }\n\n  dXM /= numSubjects;\n  dYM /= numSubjects;\n\n  // now compute the variances\n\n  double dXV = 0;\n  double dYV = 0;\n  for( unsigned int sub = 0; sub < numSubjects; sub++ )\n    {\n    dXV += (x[sub] - dXM) * (x[sub] - dXM);\n    dYV += (y[sub] - dYM) * (y[sub] - dYM);\n    }\n\n  dXV /= (numSubjects - 1);\n  dYV /= (numSubjects - 1);\n\n  // which gives the standard deviations\n\n  double dXS = sqrt( dXV );\n  double dYS = sqrt( dYV );\n\n  // from which we can compute the correlation coefficient\n\n  double dR = 0;\n  for( unsigned int sub = 0; sub < numSubjects; sub++ )\n    {\n    dR += (x[sub] - dXM) * (y[sub] - dYM);\n    }\n  dR /= (numSubjects - 1) * dXS * dYS;\n\n  return dR;\n\n}\n\ndouble computePearsonCorrelationWithP( vnl_vector<double>& x, vnl_vector<double>& y, double & dPDiff,\n                                       double & dPGreater,\n                                       double & dPSmaller )\n{\n\n  // Equations from the book\n  // Handbook of Parametric and Nonparametric Statistical Procedures\n  // David J. Sheskin, Chapman & Hall/CRC\n  //\n  // as well as from the BOOST documentation\n\n  unsigned int numSubjects = x.size();\n\n  double dR = computePearsonCorrelation( x, y );\n\n  // Degrees of freedom:\n  unsigned v = numSubjects - 1;\n  // t-statistic:\n  double t_stat = dR * sqrt(numSubjects - 2) / sqrt(1 - dR * dR);\n\n  boost::math::students_t dist(v);\n  double                  q = boost::math::cdf(boost::math::complement(dist, fabs(t_stat) ) );\n\n  dPDiff = 2 * q; // need to multiply by 2, because this is a two-sided test\n  // just want to reject the possibility that there is no correlation\n\n  dPGreater = boost::math::cdf(boost::math::complement(dist, t_stat) );\n\n  dPSmaller = boost::math::cdf(dist, t_stat);\n\n  return dR;\n\n}\n\nvoid output_vector(vnl_vector<double> data, std::string outbase, std::string toAppend)\n{\n  // Create and write out difference vector file:\n  std::string outFile = outbase + toAppend;\n  // std::cout << \"outputFile: \" << outFile << std::endl\t;\n  std::ofstream outputFile;\n\n  outputFile.open(outFile.c_str(), std::ios::out);\n\n  // Set up header:\n  outputFile << \"NUMBER_OF_POINTS = \" << data.size() << std::endl;\n  outputFile << \"DIMENSION = 1\" << std::endl;\n  outputFile << \"TYPE = Scalar\" << std::endl;\n  for( unsigned int feat = 0; feat < data.size(); ++feat )\n    {\n    outputFile << data(feat) << std::endl;\n    }\n  outputFile.close();\n}\n\nvoid output_matrix(vnl_matrix<double> data, std::string outbase, std::string toAppend)\n{\n  // Create and write out difference vector file:\n  std::string outFile = outbase + toAppend;\n\n  std::ofstream outputFile;\n\n  outputFile.open(outFile.c_str(), std::ios::out);\n\n  // Set up header:\n  outputFile << \"NUMBER_OF_POINTS = \" << data.rows() << std::endl;\n  outputFile << \"DIMENSION = \" << data.columns() << std::endl;\n  outputFile << \"TYPE = Vector\" << std::endl;\n  for( unsigned int feat = 0; feat < data.rows(); ++feat )\n    {\n    for( unsigned int dim = 0; dim < data.columns(); ++dim )\n      {\n      outputFile << data(feat, dim) << \" \";\n      }\n    outputFile << std::endl;\n    }\n  outputFile.close();\n}\n\nvoid write_SubjectPoints( std::string fileName, unsigned int sub,\n                          vnl_matrix<double>  * & featureValue,\n                          unsigned int numFeatures,\n                          MeshType::Pointer & surfaceMesh,\n                          MeshSpatialObjectType::Pointer & SOMesh )\n{\n  // get the points\n  PointsContainerPointer currentPoints;\n\n  currentPoints = surfaceMesh->GetPoints();\n\n  PointType currentPoint;\n  for( unsigned int iI = 0; iI < numFeatures; ++iI )\n    {\n    for( unsigned int iJ = 0; iJ < dimension; iJ++ )\n      {\n      currentPoint[iJ] = (*featureValue)[sub][iI * dimension + iJ];\n      }\n    currentPoints->SetElement(iI, currentPoint);\n    }\n\n  // Write out total mean:\n  surfaceMesh->SetPoints(currentPoints);\n  SOMesh->SetMesh(surfaceMesh);\n  MeshWriterType::Pointer writer = MeshWriterType::New();\n  writer->SetInput(SOMesh);\n  writer->SetFileName(fileName.c_str() );\n  writer->Update();\n\n}\n\nvoid\nload_MeshList_file( std::string filename, int surfaceColumn, unsigned int numIndependent,\n                    unsigned int numGroupTypes, std::vector<int>  groupTypeColumns, std::vector<int> independentColumns,\n                    bool scaleOn, int scaleColumn, unsigned int & numSubjects, unsigned int & numA, unsigned int & numB,\n                    vnl_matrix<int> * & groupLabel, vnl_matrix<double> * & scaleFactor,\n                    std::string * & meshFileNames,  vnl_matrix<double> * & indValue,\n                    bool computeScaleFactorFromVolumes )\n{\n\n  cout << \"filename: \" << filename << \" numIndependent: \" << numIndependent << endl;\n  // bool interactionTest =false; // Replace\n  // unsigned int testColumn=1;\n  const int   MAXLINE  = 5000;\n  static char line[MAXLINE];\n\n  char *        extension = const_cast<char *>(strrchr(filename.c_str(), '.') );\n  std::ifstream datafile(filename.c_str(), std::ios::in);\n\n  if( !datafile.is_open() )\n    {\n    std::cerr << \"ERROR: Mesh list file does not exist\" << filename << std::endl;\n    exit(-1);\n    }\n\n  numSubjects = 0;\n\n  datafile.clear();\n  datafile.getline(line, MAXLINE);\n  while( !datafile.eof() )\n    {\n    if( line[0] != '#' ) // skip over comments\n      {\n      numSubjects++;\n      }\n    datafile.getline(line, MAXLINE);\n\n    }\n\n  // if the input file is a csv file\n  if( !strcmp(extension, \".csv\") )\n    {\n    // because of the header\n    numSubjects = numSubjects - 1;\n\n    if( debug )\n      {\n      std::cout << \"Num Subjects: \" << numSubjects << std::endl;\n      }\n\n    scaleFactor =  new vnl_matrix<double>; scaleFactor->set_size(numSubjects, 1);\n    meshFileNames = new std::string[numSubjects];\n\n    // Create the data matrix:\n    indValue = new vnl_matrix<double>;\n    indValue->set_size(numSubjects, numIndependent); // Each subjects data is flattened, this data will go into X\n\n    groupLabel = new vnl_matrix<int>;\n    groupLabel->set_size(numSubjects, numGroupTypes);\n\n    // read the list\n    unsigned int curLine = 0;\n    // char * cur_token;\n    string Line;\n\n    datafile.clear();\n    datafile.seekg(ios::beg); // go back to the beginning of the\n    // file to read the actual data\n\n    getline(datafile, Line); // skip the csv file header\n\n    int    temp_int = 0;\n    double temp_double = 0;\n    int    indexColumn = 0;\n\n    while( !datafile.eof() )\n      {\n      getline(datafile, Line);\n\n      if( Line[0] != '#' && !(Line.empty() ) )\n        {\n        char filename[MAXLINE];\n        // int retval;\n\n        istringstream buffer(Line);\n        string        cur_token;\n\n        while( getline(buffer, cur_token, ',') )\n          {\n          if( !cur_token.empty() )\n            {\n            for( unsigned int gr = 0; gr < numGroupTypes; ++gr ) // Read all of the group types\n              {\n              if( indexColumn == groupTypeColumns[gr] ) // if the curent column contains a group type\n                {\n                if( cur_token.empty() )\n                  {\n                  std::cerr << \"ERROR: Could not read group types properly.\" << std::endl;\n                  exit(-1);\n                  }\n                temp_int = atoi(cur_token.c_str() );\n                (*groupLabel)[curLine][gr] = temp_int;\n                }\n              }\n            if( scaleOn )\n              {\n              if( indexColumn == scaleColumn ) // if the current column contains a scale factor\n                {\n                if( cur_token.empty() )\n                  {\n                  std::cerr << \"ERROR: Could not read scaling factor properly.\" << std::endl;\n                  exit(-1);\n                  }\n                temp_double = atof(cur_token.c_str() );\n                (*scaleFactor)[curLine][0] = temp_double;\n                }\n              }\n\n            if( indexColumn == surfaceColumn ) // if the current column contains the surface file\n              {\n              if( cur_token.empty() )\n                {\n                std::cerr << \"ERROR: Could not read filename properly.\" << std::endl;\n                exit(-1);\n                }\n              strcpy(filename, cur_token.c_str() );\n              meshFileNames[curLine] = std::string(filename);\n              }\n            for( unsigned int ind_vars = 0; ind_vars < numIndependent; ++ind_vars ) // Read all of the independent\n                                                                                    // variables\n              {\n\n              if( indexColumn == independentColumns[ind_vars] ) // if the current column contain a independent variable\n                {\n                if( cur_token.empty() )\n                  {\n                  std::cerr << \"ERROR: Could not read independent variable properly.\" << std::endl;\n                  exit(-1);\n                  }\n                temp_double = atof(cur_token.c_str() );\n                (*indValue)[curLine][ind_vars] = temp_double;\n                }\n              }\n            indexColumn++;\n            }\n\n          else\n            {\n            std::cerr << \"WARNING: Could not read group token. Skipping line\" << std::endl;\n            }\n\n          }\n\n        curLine++;\n        indexColumn = 0;\n\n        }\n\n      }\n\n    datafile.close();\n    }\n\n  else\n    {\n    if( debug )\n      {\n      std::cout << \"Num Subjects: \" << numSubjects << std::endl;\n      }\n\n    scaleFactor =  new vnl_matrix<double>; scaleFactor->set_size(numSubjects, 1);\n    meshFileNames = new std::string[numSubjects];\n\n    // Create the data matrix:\n    indValue = new vnl_matrix<double>;\n    indValue->set_size(numSubjects, numIndependent); // Each subjects data is flattened, this data will go into X\n\n    groupLabel = new vnl_matrix<int>;\n    groupLabel->set_size(numSubjects, numGroupTypes);\n\n    // read the list\n    unsigned int curLine = 0;\n    char *       cur_token;\n\n    datafile.clear();\n    datafile.seekg(0, std::ios::beg); // go back to the beginning of the\n    // file to read the actual data\n    datafile.getline(line, MAXLINE);\n\n    int    temp_int = 0;\n    double temp_double = 0;\n\n    while( !datafile.eof() )\n      {\n      if( line[0] != '#' && !(line[0] == 0) )\n        {\n        char filename[MAXLINE];\n        int  retval;\n\n        cur_token = strtok(line, \" \\t\");\n\n        if( cur_token != NULL )\n          {\n          for( unsigned int gr = 0; gr < numGroupTypes; ++gr ) // Read all of the group types\n            {\n            if( cur_token == NULL )\n              {\n              std::cerr << \"ERROR: Could not read group types properly.\" << std::endl;\n              exit(-1);\n              }\n            retval = sscanf(cur_token, \"%d\", &temp_int);\n            (*groupLabel)[curLine][gr] = temp_int;\n            cur_token = strtok(NULL, \" \\t\");\n            }\n\n          if( cur_token == NULL )\n            {\n            std::cerr << \"ERROR: Could not read scaling factor properly.\" << std::endl;\n            exit(-1);\n            }\n          retval = sscanf(cur_token, \"%lf\", &temp_double); cur_token = strtok(NULL, \" \\t\");\n          (*scaleFactor)[curLine][0] = temp_double;\n\n          if( cur_token == NULL )\n            {\n            std::cerr << \"ERROR: Could not read filename properly.\" << std::endl;\n            exit(-1);\n            }\n          retval = sscanf(cur_token, \"%s\", filename); cur_token = strtok(NULL, \" \\t\");\n\n          meshFileNames[curLine] = std::string(filename);\n          for( unsigned int ind_vars = 0; ind_vars < numIndependent; ++ind_vars ) // Read all of the independent\n                                                                                  // variables\n            {\n            if( cur_token == NULL )\n              {\n              std::cerr << \"ERROR: Could not read independent variable properly.\" << std::endl;\n              exit(-1);\n              }\n            retval = sscanf(cur_token, \"%lf\", &temp_double); cur_token = strtok(NULL, \" \\t\");\n            (*indValue)[curLine][ind_vars] = temp_double;\n            }\n\n          curLine++;\n\n          }\n        else\n          {\n          std::cerr << \"WARNING: Could not read group token. Skipping line\" << std::endl;\n          }\n        }\n      datafile.getline(line, MAXLINE);\n\n      }\n\n    datafile.close();\n    }\n\n  if( computeScaleFactorFromVolumes )\n    {\n    std::cout << std::endl;\n    std::cout << \"--------------------------------------------------------------------\" << std::endl;\n    std::cout << \"WARNING: Reinterpreting scaling column as volumes.\" << std::endl;\n    std::cout << \"... computing the scaling factor from the volumes.\" << std::endl;\n    std::cout << \"This is different from the old file format.\" << std::endl;\n    std::cout << \"MAKE SURE YOU UNDERSTAND WHAT YOU ENABLED WITH --computeScaleFactorFromVolumes\" << std::endl;\n    std::cout << \"--------------------------------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n\n    // reinterpret the scale column in the file as\n    // volumes and compute the scale factor from them\n\n    // first compute the average volume\n\n    double dAverageVolume = 0;\n    for( unsigned int iI = 0; iI < numSubjects; iI++ )\n      {\n      dAverageVolume += (*scaleFactor)[iI][0];\n      }\n    dAverageVolume /= numSubjects;\n\n    std::cout << \"Average volume is = \" << dAverageVolume << std::endl;\n    std::cout << \"Computing scale factor by (volume/averageVolume)^(1/3)\" << std::endl;\n\n    double one_third = 1.0 / 3;\n    for( unsigned int iI = 0; iI < numSubjects; iI++ )\n      {\n      (*scaleFactor)[iI][0] = pow( ( (*scaleFactor)[iI][0]) / dAverageVolume, one_third);\n      }\n\n    }\n\n  std::cout << std::endl << std::endl;\n\n  // possibly relabel the group associations\n  // TODO: Check if this really should be done for the MANCOVA case\n  // TODO: It may only be a historic remnant from the old\n  // TODO: StatNonParam program\n\n  int          preLabelA, preLabelB;\n  unsigned int i;\n  numA = 0, numB = 0;\n  for( unsigned int group_type = 0; group_type < numGroupTypes; ++group_type )\n    {\n    // change labels to the predefined ones, this will fail if there are more than 2 labels in the file\n    preLabelA = (*groupLabel)[0][group_type];\n    preLabelB = (*groupLabel)[0][group_type];\n    for( i = 0; i < numSubjects; i++ )\n      {\n      if( preLabelA != (*groupLabel)[i][group_type] )\n        {\n        if( preLabelB != preLabelA && preLabelB  != (*groupLabel)[i][group_type] )\n          {\n          std::cout << \"Error: more than 2 labels in file\" << std::endl;\n          }\n        else\n          {\n          preLabelB = (*groupLabel)[i][group_type];\n          }\n        }\n      }\n    for( i = 0; i < numSubjects; i++ )\n      {\n      if( preLabelA == (*groupLabel)[i][group_type] )\n        {\n        (*groupLabel)[i][group_type] = GROUP_A_LABEL;\n        ++numA;\n        }\n      else if( preLabelB == (*groupLabel)[i][group_type] )\n        {\n        (*groupLabel)[i][group_type] = GROUP_B_LABEL;\n        ++numB;\n        }\n      }\n    if( debug )\n      {\n      std::cout << \"data in group_type \" << group_type << \" has been relabeled: \" <<  preLabelA << \" --> group A = \"\n                << GROUP_A_LABEL\n                << \" ; \" << preLabelB << \" --> group B = \" << GROUP_B_LABEL << std::endl;\n      std::cout << \"#(A)= \" << numA << \"; #(B)= \" << numB << std::endl;\n      }\n    } // END of For-loop\n\n  // TODO Remove leading and ending \" from meshFileNames if present\n\n  if( meshFileNames[1].compare(1, 1, \"/\") == 0 )\n    {\n    std::vector<string> meshFileNamesCopy;\n    for( unsigned int i = 0; i < numSubjects; i++ )\n      {\n      meshFileNamesCopy.push_back(\".\");\n      }\n\n    if( debug )\n      {\n      for( unsigned int i = 0; i < numSubjects; i++ )\n        {\n        meshFileNamesCopy.at(i).assign(meshFileNames[i], 1, meshFileNames[i].size() - 2);\n        std::cout << \"reading Mesh.Copy \" << meshFileNamesCopy.at(i) << std::endl;\n        }\n      }\n    for( unsigned int i = 0; i < numSubjects; i++ )\n      {\n      meshFileNames[i] = meshFileNamesCopy[i];\n      }\n    }\n  // debug info\n  if( debug )\n    {\n    for( unsigned int i = 0; i < numSubjects; i++ )\n      {\n      std::cout << meshFileNames[i] << \" \" << (*groupLabel)[i][0] << \" \" << (*scaleFactor)[i][0] << std::endl;\n      }\n    }\n\n}\n\nvoid load_Meshes( bool scaleOn,  unsigned int numSubjects,\n                  unsigned int numIndependent,\n                  vnl_matrix<double> * & scaleFactor,  vnl_matrix<double> * & indValue,\n                  std::string * & meshFileNames, unsigned int & numFeatures, vnl_matrix<double>  * & featureValue,\n                  MeshType::Pointer & surfaceMesh,\n                  MeshSpatialObjectType::Pointer & SOMesh )\n{\n  // Read the meshes\n  featureValue = new vnl_matrix<double>;\n\n  MeshReaderType::Pointer reader = MeshReaderType::New();\n  PointsContainerPointer  points;\n  for( unsigned int index = 0; index < numSubjects; index++ )\n    {\n\n    // if the surface file is a vtk file\n    char *extension = const_cast<char *>(strrchr(meshFileNames[index].c_str(), '.') );\n    std::cout << \"reading Mesh \" << meshFileNames[index].c_str() << \" - \" << extension << std::endl;\n\n    if( !strcmp(extension, \".vtk\") ) // TODO\n      {\n      // read vtk file\n      vtkPolyDataReader *mesh = vtkPolyDataReader::New();\n      mesh->SetFileName(meshFileNames[index].c_str() );\n\n      // std::cout << \"converting vtk to itk\" << std::endl;\n\n      try\n        {\n        mesh->Update();\n        }\n      catch( itk::ExceptionObject ex )\n        {\n        std::cout << \"Error reading VTK meshfile:  \" << meshFileNames[index] << std::endl << \"ITK error: \"\n                  << ex.GetDescription() << std::endl;\n        exit(-3);\n        }\n\n      vtkPolyData *polyData = mesh->GetOutput();\n\n      // convert polydata to itk mesh\n      int length = strlen(meshFileNames[index].c_str() ) - 4;\n\n      char *meshFile = new char[length + 6];\n      strcpy(meshFile, meshFileNames[index].c_str() );\n      meshFile[length] = '\\0';\n      strcat(meshFile, \".meta\");\n\n      vtkPolyDataToitkMesh *vtkItkConverter = new vtkPolyDataToitkMesh();\n      vtkItkConverter->SetInput( polyData );\n\n      // write out the itk meta mesh file\n      MeshConverterType::Pointer itkConverter = MeshConverterType::New();\n      itkMeshSOType::Pointer meshSO = itkMeshSOType::New();\n      meshSO->SetMesh( vtkItkConverter->GetOutput() );\n      itkConverter->WriteMeta( meshSO, meshFile );\n\n      mesh->Delete();\n\n      // read mesh file\n      try\n        {\n        reader->SetFileName(meshFile);\n        reader->Update();\n        }\n      catch( itk::ExceptionObject ex )\n        {\n        std::cout << \"Error reading META meshfile:  \" << meshFileNames[index] << std::endl << \"ITK error: \"\n                  << ex.GetDescription() << std::endl;\n        }\n\n      }\n\n    else\n      {\n      try\n        {\n        reader->SetFileName(meshFileNames[index].c_str() );\n        reader->Update();\n        }\n      catch( itk::ExceptionObject ex )\n        {\n        std::cout << \"Error reading META meshfile:  \" << meshFileNames[index] << std::endl << \"ITK error: \"\n                  << ex.GetDescription() << std::endl;\n        }\n      }\n\n    MeshReaderType::SceneType::Pointer          scene = reader->GetScene();\n    MeshReaderType::SceneType::ObjectListType * objList =  scene->GetObjects(1, NULL);\n\n    MeshReaderType::SceneType::ObjectListType::iterator it = objList->begin();\n\n    itk::SpatialObject<3> * curObj = *it;\n    SOMesh = dynamic_cast<MeshSpatialObjectType *>(curObj);\n    surfaceMesh = SOMesh->GetMesh();\n    points = surfaceMesh->GetPoints();\n\n    if( index == 0 )\n      {\n      numFeatures = points->Size();\n      featureValue->set_size(numSubjects, numFeatures * 3 + numIndependent); // Each subjects data is flattened, this\n                                                                             // data will go into X\n      }\n\n    float xCOG = 0; float yCOG = 0; float zCOG = 0;\n    for( unsigned int pointID = 0; pointID < numFeatures; pointID++ )\n      {\n      PointType curPoint =  points->GetElement(pointID);\n      xCOG = xCOG + curPoint[0];\n      yCOG = yCOG + curPoint[1];\n      zCOG = zCOG + curPoint[2];\n      }\n    xCOG = xCOG / numFeatures;\n    yCOG = yCOG / numFeatures;\n    zCOG = zCOG / numFeatures;\n    float COG[3]; COG[0] = xCOG; COG[1] = yCOG; COG[2] = zCOG;\n    for( unsigned int pointID = 0; pointID < numFeatures; pointID++ )\n      {\n      PointType curPoint =  points->GetElement(pointID);\n      for( unsigned int dim = 0; dim < 3; dim++ )\n        {\n        if( scaleOn )\n          {\n          (*featureValue)[index][pointID * 3 + dim] = (curPoint[dim] - COG[dim]) / (*scaleFactor)[index][0] + COG[dim];\n          }\n        else\n          {\n          (*featureValue)[index][pointID * 3 + dim] = curPoint[dim];\n          }\n        }\n      }\n    // Store Independent variables after tupel data:\n    for( unsigned int ind_vars = 0; ind_vars < numIndependent; ++ind_vars )\n      {\n      featureValue->set_column(numFeatures * 3 + ind_vars, indValue->get_column(ind_vars) );\n      }\n    }\n\n}\n\n//\n// Function added by bp2009\n// Added to include the longitudinal analysis in the study...\n//\nvoid load_KWMreadableInputFile( bool scaleOn,  unsigned int numSubjects,\n                                unsigned int numIndependent,\n                                vnl_matrix<double> * & scaleFactor,  vnl_matrix<double> * & indValue,\n                                std::string * & meshFileNames, unsigned int & numFeatures,\n                                vnl_matrix<double>  * & featureValue, MeshType::Pointer & surfaceMesh,\n                                MeshSpatialObjectType::Pointer & SOMesh )\n{\n  // Read the KWMfile\n  // By now, and only for testing purposes, I am going to ignore a lot of the input parameters to the function... I\n  // copied directly from load_Meshes, and there are a lot of things I dont need\n\n  featureValue = new vnl_matrix<double>;\n  for( unsigned int index = 0; index < numSubjects; index++ )\n    {\n    try\n      {\n      // std::cout<< \"Working on file...  \"<< meshFileNames[index] << std::endl << std::endl;\n\n      char               line[70];\n      ifstream           inputFile;\n      char *             aux;\n      vnl_vector<double> curPoint(3, 0.0);\n      int                NPoints, pointID, pointCont;\n\n      inputFile.open(meshFileNames[index].c_str(), std::ios::in);\n      inputFile.getline(line, 70, '\\n');\n      aux = strtok(line, \" = \");\n      aux = strtok(NULL, \" = \");\n      NPoints = atoi(aux);\n      inputFile.getline(line, 70, '\\n');\n      inputFile.getline(line, 70, '\\n');\n\n      pointID = 0; pointCont = 0;\n      // Start reading the Input File\n      while( !inputFile.getline(line, 70, '\\n').eof() )\n        {\n        aux = strtok(line, \" \");\n        while( aux != NULL )\n          {\n          curPoint[pointCont] = atof(aux);\n          // std::cout<< aux << std::endl;\n          aux = strtok(NULL, \" \");\n          pointCont++;\n          }\n\n        pointCont = 0;\n        // std::cout<< \"\" \"Point \" << pointID << \" values \" << curPoint[0] << \" \" << curPoint[1] << \" \" << curPoint[2]\n        // << std::endl;\n\n        if( index == 0 )\n          {\n          numFeatures = NPoints;\n          featureValue->set_size(numSubjects, numFeatures * 3 + numIndependent); // Each subjects data is flattened,\n                                                                                 // this data will go into X\n          }\n        for( unsigned int dim = 0; dim < 3; dim++ )\n          {\n          if( scaleOn )\n            {\n            // std::cout<< \"Aqui...\" << std::endl;\n            (*featureValue)[index][pointID * 3 + dim] = curPoint[dim] / (*scaleFactor)[index][0];\n            }\n          else\n            {\n            // std::cout<< \"Aqui no scale...\" << std::endl;\n            (*featureValue)[index][pointID * 3 + dim] = curPoint[dim];\n            }\n          }\n\n        // std::cout<< \"File id \" << index << \" Point \" << pointID << \" values \" << curPoint[0] << \" \" << curPoint[1] <<\n        // \" \" << curPoint[2] << std::endl;\n        pointID++;\n        }\n\n      inputFile.close();\n      // End reading the Input File\n\n      } // end FOR index\n    catch( itk::ExceptionObject ex )\n      {\n      std::cout << \"Error reading KWMfile:  \" << meshFileNames[index] << std::endl << \"ITK error: \"\n                << ex.GetDescription() << std::endl;\n      exit(-3);\n      }\n    // std::cout<< \"Finished reading file id \" << index << std::endl;\n    // Store Independent variables after tupel data:\n    for( unsigned int ind_vars = 0; ind_vars < numIndependent; ++ind_vars )\n      {\n      featureValue->set_column(numFeatures * 3 + ind_vars, indValue->get_column(ind_vars) );\n      }\n    }\n\n  std::cout << \"KWM Files Readed...\" << std::endl;\n\n}\n\n//\n// Function modified by bp2009\n// Included new input argument KWMreadableInputFile...\n// Controlling unallowed operations wrt to Mesh Operations (no Meshes appear in a featural analysis)\n//\nvoid write_SurfaceProperties(  std::string outbase,  PointsContainerPointer & meanPoints,\n                               PointsContainerPointer & meanPointsA,  PointsContainerPointer & meanPointsB,\n                               vnl_matrix<double>& diffVectors,\n                               vnl_vector<double>& normProjections, vnl_vector<double>& DiffMagnitude,\n                               vnl_matrix<double>& zScoresProjected,\n                               vnl_matrix<double>& zScores, bool writeOutZScores, MeshType::Pointer & surfaceMesh,\n                               MeshSpatialObjectType::Pointer & SOMesh, std::string * & meshFileNames,\n                               int KWMreadableInputFile)\n{\n\n  // std::cout<< \"Starting to write surface properties...\" << std::endl;\n\n  if( KWMreadableInputFile == 0 )\n    {\n\n    // if the input file is a csv file\n//  char *extension=strchr(outbase.c_str(),'.');\n//  if(!strcmp(extension,\".csv\"))\n//  {\n//    int index=outbase.find(\".csv\",0);\n//    outbase=outbase.erase(index,outbase.size());\n//  }\n// Write out total mean:\n    surfaceMesh->SetPoints(meanPoints);\n    SOMesh->SetMesh(surfaceMesh);\n    MeshWriterType::Pointer writer = MeshWriterType::New();\n    writer->SetInput(SOMesh);\n    std::string FilenameAverage(outbase);\n\n    FilenameAverage = FilenameAverage + std::string(\"_meanAll_uncorrected.meta\");\n    writer->SetFileName(FilenameAverage.c_str() );\n    writer->Update();\n\n    // Write out Group A mean:\n    surfaceMesh->SetPoints(meanPointsA);\n    SOMesh->SetMesh(surfaceMesh);\n    writer->SetInput(SOMesh);\n    std::string FilenameAverageA(outbase);\n    FilenameAverageA = FilenameAverageA + std::string(\"_meanA.meta\");\n    writer->SetFileName(FilenameAverageA.c_str() );\n    writer->Update();\n\n    // Write out group B mean:\n    surfaceMesh->SetPoints(meanPointsB);\n    SOMesh->SetMesh(surfaceMesh);\n    writer->SetInput(SOMesh);\n    std::string FilenameAverageB(outbase);\n    FilenameAverageB = FilenameAverageB + std::string(\"_meanB.meta\");\n    writer->SetFileName(FilenameAverageB.c_str() );\n    writer->Update();\n    } // end if (KWMreadableInputFile == 0)\n\n  // Create and write out difference vector file:\n\n  output_matrix(diffVectors, outbase, std::string(\"_diffMesh.txt\") );\n\n  // normal projections\n\n  output_vector(normProjections, outbase, std::string(\"_normProjections.txt\") );\n  output_vector(DiffMagnitude, outbase, std::string(\"_DiffMagnitude.txt\") );\n\n  // write out z-scores\n\n  if( writeOutZScores )\n    {\n\n    unsigned int numSubjects = zScores.columns();\n    for( unsigned sub = 0; sub < numSubjects; sub++ )\n      {\n      boost::filesystem::path my_path( meshFileNames[sub] );\n\n      std::ostringstream fileNameSuffixP;\n      fileNameSuffixP << \"-\" << my_path.stem() << \"-zScore-projected\" << \".txt\";\n      output_vector(zScoresProjected.get_column(sub), outbase, fileNameSuffixP.str() );\n      std::ostringstream fileNameSuffix;\n      fileNameSuffix << \"-\" << my_path.stem() << \"-zScore-mahalanobis\" << \".txt\";\n      output_vector(zScores.get_column(sub), outbase, fileNameSuffix.str() );\n\n      }\n\n    }\n\n}\n\n//\n// Function modified by bp2009\n// Included new input argument KWMreadableInputFile...\n// Controlling unallowed operations wrt to Mesh Operations (no Meshes appear in a featural analysis)\n//\nvoid compute_SurfaceProperties( PointsContainerPointer & meanPoints, PointsContainerPointer & meanPointsA,\n                                PointsContainerPointer & meanPointsB, vnl_matrix<double> & diffVectors,\n                                vnl_vector<double>& normProjections,\n                                vnl_vector<double>& DiffMagnitude, vnl_matrix<double>& zScores,\n                                vnl_matrix<double>& zScoresProjected,\n                                unsigned int numSubjects, unsigned int numA, unsigned int numB,\n                                unsigned int numFeatures, vnl_matrix<int> * & groupLabel,\n                                vnl_matrix<double> * & featureValue, vtkPolyDataNormals *& MeshNormals,\n                                MeshType::Pointer & surfaceMesh,\n                                std::string outbase, std::string * & meshFileNames,\n                                int KWMreadableInputFile)\n{\n  double       tmp_pnt[dimension], tmpA[dimension], tmpB[dimension];\n  PointType    A_pnt, B_pnt;\n  unsigned int dim;\n\n  // need to make sure that the overall mean\n  // is computed correctly\n  // let's do this by averaging the mean of A and B\n  // rather than by computing the overall mean\n  // which would bias towards the group with more subjects\n  for( unsigned int pointID = 0; pointID < numFeatures; pointID++ )\n    {\n    for( dim = 0; dim < dimension; dim++ )\n      {\n      tmpA[dim] = 0; tmpB[dim] = 0;\n      }\n    for( unsigned int sub = 0; sub < numSubjects; ++sub )\n      {\n      if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n        {\n        for( dim = 0; dim < dimension; ++dim )\n          {\n          tmpA[dim] += (*featureValue)[sub][pointID * dimension + dim];\n          }\n        }\n      else\n        {\n        for( dim = 0; dim < dimension; ++dim )\n          {\n          tmpB[dim] += (*featureValue)[sub][pointID * dimension + dim];\n          }\n        }\n      }\n\n    // normalize to compute the mean shapes\n    // for the individual groups as well as\n    // an overall mean shape\n\n    if( numA > 0 ) // only if there are elements in group A\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmpA[dim] /= numA;\n        }\n      }\n\n    if( numB > 0 ) // only if there are elements in group B\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmpB[dim] /= numB;\n        }\n      }\n\n    if( numA > 0 && numB > 0 )\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmp_pnt[dim] = 0.5 * (tmpA[dim] + tmpB[dim]);\n        }\n      }\n    else if( numA > 0 )\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmp_pnt[dim] = tmpA[dim];\n        }\n      }\n    else if( numB > 0 )\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmp_pnt[dim] = tmpB[dim];\n        }\n      }\n    else\n      {\n      for( dim = 0; dim < dimension; dim++ ) // Normalize\n        {\n        tmp_pnt[dim] = 0;\n        }\n      }\n\n    meanPoints->InsertElement(pointID, PointType(tmp_pnt) );\n    meanPointsA->InsertElement(pointID, PointType(tmpA) );\n    meanPointsB->InsertElement(pointID, PointType(tmpB) );\n\n    if( numA > 0 && numB > 0 )\n      {\n      for( dim = 0; dim < dimension; ++dim ) // Initialize\n        {\n        diffVectors[pointID][dim] = tmpA[dim] - tmpB[dim];\n        }\n      }\n    else // one of the groups is empty, so we cannot compute a\n    // difference and therefore set everything to zero\n      {\n      for( dim = 0; dim < dimension; ++dim ) // Initialize\n        {\n        diffVectors[pointID][dim] = 0;\n        }\n      }\n\n    }\n\n  // compute the mean surface normals\n  // as well as the signed distances by projecting the surface\n  // difference onto the surface normals\n\n  surfaceMesh->SetPoints(meanPoints);\n\n  itkMeshTovtkPolyData *convertMeshToVTK = new itkMeshTovtkPolyData();\n  convertMeshToVTK->SetInput(surfaceMesh);\n  vtkPolyData * vtkMesh = convertMeshToVTK->GetOutput();\n\n  MeshNormals->SetComputePointNormals(1);\n  MeshNormals->SetComputeCellNormals(0);\n  MeshNormals->SetSplitting(0);\n  MeshNormals->AutoOrientNormalsOn();\n  MeshNormals->ConsistencyOn();\n  MeshNormals->FlipNormalsOff();    // all normals are outward pointing\n  MeshNormals->SetInput(vtkMesh);\n  MeshNormals->Update();\n\n  vtkPolyData * vtkMeshNormals = MeshNormals->GetOutput();\n  vtkMeshNormals->Update();\n\n  vtkPointData * NormalPoints = vtkMeshNormals->GetPointData();\n  vtkDataArray * ArrayNormal = NormalPoints->GetNormals();\n\n  // now compute the signed distances\n\n  double *tempNorm;\n  for( unsigned int feat = 0; feat < numFeatures; ++feat )\n    {\n    if( KWMreadableInputFile == 0 )\n      {\n      tempNorm = ArrayNormal->GetTuple(feat);  // here is crashing... why\n\n      // all of this should automatically become zero if there is only\n      // one group, because in this case diffVectors will be all zero\n\n      normProjections(feat) = diffVectors(feat, 0) * tempNorm[0] + diffVectors(feat, 1) * tempNorm[1] + diffVectors(\n          feat, 2) * tempNorm[2];\n      } // end if (KWMreadableInputFile == 0)\n    DiffMagnitude(feat) = sqrt(diffVectors(feat, 0) * diffVectors(feat, 0) + diffVectors(feat, 1) * diffVectors(feat,\n                                                                                                                1)\n                               + diffVectors(feat, 2) * diffVectors(feat, 2) );\n    if( normProjections(feat) < 0 ) // Negative, means pointing in\n      {\n      DiffMagnitude(feat) = -DiffMagnitude(feat);\n      }\n    }\n\n  // Computing the z-scores ...\n\n  // first the projected case\n  // let's compute the mean projected distance of A wrt. B and the\n  // other way around with respect to the mean surface\n\n  if( KWMreadableInputFile == 0 )\n    {\n    for( unsigned int feat = 0; feat < numFeatures; feat++ )\n      {\n      double *           tempNorm = ArrayNormal->GetTuple(feat);\n      PointType          currentMeanPoint =  meanPoints->GetElement(feat);\n      vnl_vector<double> dProj(numSubjects, 0);\n      double             mu_aP = 0;\n      double             mu_bP = 0;\n      for( unsigned int sub = 0; sub < numSubjects; sub++ )\n        {\n        for( unsigned int tup = 0; tup < dimension; ++tup )\n          {\n          // compute the projection along the mean normal\n          dProj(sub) += ( (*featureValue)[sub][feat * dimension + tup] - currentMeanPoint[tup]) * tempNorm[tup];\n          }\n        // now switch depending on type\n\n        if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n          {\n          mu_aP += dProj(sub);\n          }\n        else\n          {\n          mu_bP += dProj(sub);\n          }\n        }\n      // now compute the mean\n      if( numA > 0 )\n        {\n        mu_aP /= numA;\n        }\n      if( numB > 0 )\n        {\n        mu_bP /= numB;\n        }\n\n      // now compute the variance\n\n      double sigma_aP = 0;\n      double sigma_bP = 0;\n      for( unsigned int sub = 0; sub < numSubjects; sub++ )\n        {\n        // now switch depending on type\n\n        if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n          {\n          sigma_aP += (dProj(sub) - mu_aP) * (dProj(sub) - mu_aP);\n          }\n        else\n          {\n          sigma_bP += (dProj(sub) - mu_bP) * (dProj(sub) - mu_bP);\n          }\n        }\n      // now compute the standard deviation\n      if( numA > 0 )\n        {\n        sigma_aP /= numA;\n        sigma_aP = sqrt(sigma_aP);\n        }\n      if( numB > 0 )\n        {\n        sigma_bP /= numB;\n        sigma_bP = sqrt(sigma_bP);\n        }\n      // and finally the z-scores\n      for( unsigned int sub = 0; sub < numSubjects; sub++ )\n        {\n\n        // now switch depending on type\n\n        if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n          {\n          zScoresProjected(feat, sub) = (dProj(sub) - mu_bP) / sigma_bP;\n          }\n        else\n          {\n          zScoresProjected(feat, sub) = (dProj(sub) - mu_aP) / sigma_aP;\n          }\n        }\n      }\n\n    } // end of if KWMreadableInputFile\n  // now do all of the z-score business using the Mahalanobis distance\n  for( unsigned int feat = 0; feat < numFeatures; feat++ )\n    {\n    vnl_vector<double> mu_b(dimension, 0);\n    vnl_vector<double> mu_a(dimension, 0);\n\n    vnl_vector<double> currentVec(dimension, 0);\n    for( unsigned int sub = 0; sub < numSubjects; sub++ )\n      {\n      for( unsigned int tup = 0; tup < dimension; ++tup )\n        {\n        currentVec(tup) = (*featureValue)[sub][feat * dimension + tup];\n        }\n      // now switch depending on type\n\n      if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n        {\n        mu_a += currentVec;\n        }\n      else\n        {\n        mu_b += currentVec;\n        }\n      }\n    // now compute the mean\n    if( numA > 0 )\n      {\n      mu_a /= numA;\n      }\n    if( numB > 0 )\n      {\n      mu_b /= numB;\n      }\n\n    // now compute the variances\n\n    vnl_matrix<double> var_b(dimension, dimension, 0);\n    vnl_matrix<double> var_a(dimension, dimension, 0);\n    for( unsigned int sub = 0; sub < numSubjects; sub++ )\n      {\n      for( unsigned int tup = 0; tup < dimension; ++tup )\n        {\n        currentVec(tup) = (*featureValue)[sub][feat * dimension + tup];\n        }\n\n      // now switch depending on type\n\n      if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n        {\n        var_a += outer_product<double>(currentVec - mu_a, currentVec - mu_a);\n        }\n      else\n        {\n        var_b += outer_product<double>(currentVec - mu_b, currentVec - mu_b);\n        }\n      }\n    // now compute the standard deviation\n    if( numA > 0 )\n      {\n      var_a /= numA;\n      }\n    if( numB > 0 )\n      {\n      var_b /= numB;\n      }\n\n    // and finally compute the z-scores by computing\n    // the Mahalanobis distance\n\n    // compute the inverse of the variance\n\n    vnl_matrix<double> var_bInv(dimension, dimension);\n    vnl_matrix<double> var_aInv(dimension, dimension);\n\n    var_aInv = vnl_matrix_inverse<double>(var_a);\n    var_bInv = vnl_matrix_inverse<double>(var_b);\n    for( unsigned int sub = 0; sub < numSubjects; sub++ )\n      {\n      for( unsigned int tup = 0; tup < dimension; ++tup )\n        {\n        currentVec(tup) = (*featureValue)[sub][feat * dimension + tup];\n        }\n\n      // now switch depending on type\n\n      if( (*groupLabel)[sub][0] == GROUP_A_LABEL )\n        {\n        zScores(feat, sub) = sqrt( dot_product(currentVec - mu_b, var_bInv * (currentVec - mu_b) ) );\n        }\n      else\n        {\n        zScores(feat, sub) = sqrt( dot_product(currentVec - mu_a, var_aInv * (currentVec - mu_a) ) );\n        }\n      }\n\n    }\n}\n\nvnl_vector<double> fdrCorrection( vnl_vector<double>& rawP, double fdrLevel, double & fdrThresh )\n{\n  // to determine the adjusted level, we first need to sort the raw p\n  // values\n\n  vnl_vector<double> pSorted( rawP );\n  std::sort( pSorted.begin(), pSorted.end() );\n\n  fdrThresh = 0;\n\n  unsigned int numFeatures = rawP.size();\n  for( int pointID = (int)(numFeatures - 1); pointID >= 0; --pointID )\n    {\n    if( pSorted(pointID) <= (pointID + 1) * fdrLevel / numFeatures )\n      {\n      fdrThresh = pSorted(pointID);\n      break;\n      }\n    }\n\n  vnl_vector<double> fdrP( rawP );\n  double             fdrFactor = 0;\n  if( fdrThresh > 0 )\n    {\n    fdrFactor = fdrLevel / fdrThresh;\n    }\n  if( fdrFactor < 1.0 )\n    {\n    fdrFactor = 1.0;\n    }\n  for( unsigned int pointID = 0; pointID < numFeatures; ++pointID )\n    {\n    if( fdrThresh > 0 )\n      {\n      fdrP(pointID) = rawP[pointID] * fdrFactor;\n      }\n    else\n      {\n      fdrP(pointID) = 1.0;  // there is nothing signicant (sorry), so let's set the p-value to 1\n      }\n    if( fdrP(pointID) > 1.0 )\n      {\n      fdrP(pointID) = 1.0; // bound the p-value at 1.0, p-values over 1.0 do not make sense\n      }\n    }\n\n  return fdrP;\n\n}\n\nvnl_vector<double> bonferroniCorrection( vnl_vector<double>& rawP )\n{\n  vnl_vector<double> bP( rawP );\n  unsigned int       sz = rawP.size();\n  for( unsigned int iI = 0; iI < sz; iI++ )\n    {\n    bP(iI) = rawP(iI) * sz;\n    if( bP(iI) > 1 )\n      {\n      bP(iI) = 1;\n      }\n    }\n  return bP;\n}\n\nvoid Meta2VTK(char * infile, char* outfile)\n{\n  typedef itk::DefaultDynamicMeshTraits<double, 3, 3, double, double> MeshTraitsType;\n  typedef itk::Mesh<double, 3, MeshTraitsType>                        itkMeshType;\n  typedef itk::MeshSpatialObject<itkMeshType>                         itkMeshSOType;\n  typedef itk::MetaMeshConverter<3, double, MeshTraitsType>           MeshConverterType;\n\n  // read the data in meta format\n  MeshConverterType::Pointer itkConverter = MeshConverterType::New();\n  itkMeshSOType::Pointer meshSO =\n    dynamic_cast<itkMeshSOType *>(itkConverter->ReadMeta(infile).GetPointer() );\n  itkMeshType::Pointer   mesh = meshSO->GetMesh();\n  // delete (itkConverter);\n\n  // convert to vtk format\n  itkMeshTovtkPolyData * ITKVTKConverter = new itkMeshTovtkPolyData;\n  ITKVTKConverter->SetInput( mesh );\n\n  // write out the vtk mesh\n  vtkPolyDataWriter *writer = vtkPolyDataWriter::New();\n  writer->SetInput( ITKVTKConverter->GetOutput() );\n  writer->SetFileName( outfile );\n  writer->Update();\n\n  writer->Delete();\n  // delete (ITKVTKConverter);\n\n}\n\nvoid write_ColorMap(std::string outbase, bool interactionTest, double significanceLevel, double FDRdiscoveryLevel)\n{\n  int end;\n\n  if( interactionTest )\n    {\n    end = 8;\n    }                       // nb of file have to be created\n  else\n    {\n    end = 3;\n    }          // nb of file have to be created\n  char InputMetaFile[512];\n  char InputVTKFile[512];\n  char TextFile[512];\n  char OutputFile[512];\n  strcpy(OutputFile, outbase.c_str() );\n  strcat(OutputFile, \"_meanAll_uncorrected.vtk\");\n  strcpy(InputMetaFile, outbase.c_str() );\n  strcpy(InputVTKFile, outbase.c_str() );\n  strcat(InputVTKFile, \"_meanAll_uncorrected.vtk\");\n  strcat(InputMetaFile, \"_meanAll_uncorrected.meta\");\n  Meta2VTK(InputMetaFile, InputVTKFile);\n  for( int i = 0; i < end; i++ )\n    {\n\n    std::vector<const char *> args;\n    char*                     data = NULL;\n    int                       length;\n    double                    timeout = 0.05;\n    int                       result;\n    std::ostringstream        tmp1;\n    tmp1 << significanceLevel;\n    std::string        RawPvalueColorMapString(tmp1.str() );\n    std::ostringstream tmp2;\n    tmp2 << FDRdiscoveryLevel;\n    std::string FDRPvalueColorMapString(tmp2.str() );\n\n    switch( i )\n      {\n      case 0:\n\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_mancovaRawP.txt\");\n        args.push_back(\"MeshMath\");\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-significanceLevel\");\n        args.push_back(RawPvalueColorMapString.c_str() );\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"RawP\");\n        args.push_back(0);\n        break;\n\n      case 1:\n\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_mancovaFDRP.txt\");\n        args.push_back(\"MeshMath\");\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-significanceLevel\");\n        args.push_back(FDRPvalueColorMapString.c_str() );\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"FDRP\");\n        args.push_back(0);\n        break;\n\n      case 2:\n        if( interactionTest )\n          {\n          strcpy(TextFile, outbase.c_str() );\n          strcat(TextFile, \"_normProjectionsPearsonPval.txt\");\n          args.push_back(\"MeshMath\");\n          args.push_back(OutputFile);\n          args.push_back(OutputFile);\n          args.push_back(\"-significanceLevel\");\n          args.push_back(RawPvalueColorMapString.c_str() );\n          args.push_back(\"-KWMtoPolyData\");\n          args.push_back(TextFile);\n          args.push_back(\"normProjectionsPearsonPval\");\n          }\n\n        else\n          {\n          strcpy(TextFile, outbase.c_str() );\n          strcat(TextFile, \"_DiffMagnitude.txt\");\n          args.push_back(\"MeshMath\");\n          args.push_back(OutputFile);\n          args.push_back(OutputFile);\n          args.push_back(\"-KWMtoPolyData\");\n          args.push_back(TextFile);\n          args.push_back(\"DiffMagnitude\");\n          }\n        args.push_back(0);\n\n        break;\n\n      case 3:\n\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_normProjectionsSpearmanPvalFDR.txt\");\n        args.push_back(\"MeshMath\");\n        std::cout << OutputFile << std::endl;\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"normProjectionsSpearmanPvalFDR\");\n        args.push_back(\"-significanceLevel\");\n        args.push_back(FDRPvalueColorMapString.c_str() );\n        args.push_back(0);\n\n        break;\n\n      // case 6:\n      case 4:\n\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_normProjectionsPearsonPvalFDR.txt\");\n        args.push_back(\"MeshMath\");\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"normProjectionsPearsonPvalFDR\");\n        args.push_back(\"-significanceLevel\");\n        args.push_back(FDRPvalueColorMapString.c_str() );\n        args.push_back(0);\n\n        break;\n\n      // case 7:\n      case 5:\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_normProjectionsPearson.txt\");\n        args.push_back(\"MeshMath\");\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"normProjectionsPearson\");\n        args.push_back(0);\n\n        break;\n\n      // case 8:\n      case 6:\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_normProjectionsSpearman.txt\"); // TODO fichier txt avec les info pour les overlay\n                                                          // (activescalar)\n        args.push_back(\"MeshMath\");                       // PROG appele\n        args.push_back(OutputFile);                       // origine\n        args.push_back(OutputFile);                       // sortie (ou serotn stoquees les info de l overlay\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"normProjectionsSpearman\");   // non de ton active scalar\n        args.push_back(0);\n\n        break;\n\n      // case 9:\n      case 7:\n\n        strcpy(TextFile, outbase.c_str() );\n        strcat(TextFile, \"_normProjectionsSpearmanPval.txt\");\n        args.push_back(\"MeshMath\");\n        args.push_back(OutputFile);\n        args.push_back(OutputFile);\n        args.push_back(\"-KWMtoPolyData\");\n        args.push_back(TextFile);\n        args.push_back(\"normProjectionsSpearmanPval\");\n        args.push_back(\"-significanceLevel\");\n        args.push_back(RawPvalueColorMapString.c_str() );\n        args.push_back(0);\n\n        break;\n\n      }\n\n    // Run the application\n\n    itksysProcess* gp = itksysProcess_New();\n    itksysProcess_SetCommand(gp, &*args.begin() );\n    itksysProcess_SetOption(gp, itksysProcess_Option_HideWindow, 1);\n    itksysProcess_Execute(gp);\n\n    while( int Value = itksysProcess_WaitForData(gp, &data, &length, &timeout) ) // wait for 1s\n      {\n      if( ( (Value == itksysProcess_Pipe_STDOUT) || (Value == itksysProcess_Pipe_STDERR) ) && data[0] == 'D' )\n        {\n        strstream st;\n        for( int i = 0; i < length; i++ )\n          {\n          st << data[i];\n          }\n        string dim = st.str();\n        }\n      timeout = 0.05;\n      }\n\n    itksysProcess_WaitForExit(gp, 0);\n\n    result = 1;\n\n    switch( itksysProcess_GetState(gp) )\n      {\n      case itksysProcess_State_Exited:\n        {\n        result = itksysProcess_GetExitValue(gp);\n        } break;\n      case itksysProcess_State_Error:\n        {\n        std::cerr << \"Error: Could not run \" << args[0] << \":\\n\";\n        std::cerr << itksysProcess_GetErrorString(gp) << \"\\n\";\n        std::cout << \"Error: Could not run \" << args[0] << \":\\n\";\n        std::cout << itksysProcess_GetErrorString(gp) << \"\\n\";\n        } break;\n      case itksysProcess_State_Exception:\n        {\n        std::cerr << \"Error: \" << args[0] << \" terminated with an exception: \"\n                  << itksysProcess_GetExceptionString(gp) << \"\\n\";\n        std::cout << \"Error: \" << args[0] << \" terminated with an exception: \"\n                  << itksysProcess_GetExceptionString(gp) << \"\\n\";\n        } break;\n      case itksysProcess_State_Starting:\n      case itksysProcess_State_Executing:\n      case itksysProcess_State_Expired:\n      case itksysProcess_State_Killed:\n        {\n        // Should not get here.\n        std::cerr << \"Unexpected ending state after running \" << args[0] << std::endl;\n        std::cout << \"Unexpected ending state after running \" << args[0] << std::endl;\n        } break;\n      }\n    itksysProcess_Delete(gp);\n\n    }\n\n}\n\nint minmax(const std::string & filename, double *min, double* max)\n{\n  std::ifstream fichier(filename.c_str(), std::ios::in);\n  std::string   s;\n\n  if( fichier )\n    {\n    *min = 0;\n    *max = 0;\n    double i;\n    while( std::getline(fichier, s) )\n      {\n      const char *x = s.c_str();\n      i = strtod(x, NULL);\n\n      if( i < *min )\n        {\n        *min = i;\n        }\n      else if( i > *max )\n        {\n        *max = i;\n        }\n      }\n\n    }\n  else\n    {\n    std::cout << \"can not open the file \" << filename << std::endl;\n    }\n\n  fichier.close();\n  return 0;\n}\n\nvoid write_MRMLScene(std::string outbase, bool interactionTest)\n{\n\n  string m_directionToDisplay;\n\n  std::vector<const char *> args;\n\n  char*  data = NULL;\n  int    length;\n  double timeout = 0.05;\n  int    result;\n\n  char nameVTK[512];\n  std::strcpy(nameVTK, outbase.c_str() );\n  std::strcat(nameVTK, \"_meanAll_uncorrected.vtk\");\n  stringstream ss;\n  string       s_nameVTK;\n  ss << nameVTK;\n  ss >> s_nameVTK;\n  size_t found;\n  found = s_nameVTK.find_last_of(\"/\\\\\");\n\n  // create a directory to save the transfoms files\n  std::string s_outputdirectory;\n  s_outputdirectory.append(s_nameVTK);\n  s_outputdirectory.erase(found, s_outputdirectory.size() - 1);\n  s_outputdirectory.append(\"/transformFiles\");\n  itksys::SystemTools::MakeDirectory(s_outputdirectory.c_str() );\n\n  // the name of the vtk\n  s_nameVTK.erase(0, found + 1);\n  std::strcpy(nameVTK, s_nameVTK.c_str() );\n\n  vector<double> Dim;\n  char           nameVTK2[512];\n  std::strcpy(nameVTK2, outbase.c_str() );\n  std::strcat(nameVTK2, \"_meanAll_uncorrected.vtk\");\n  Dim = SetImageDimensions( (char *)(nameVTK2) );\n\n  std::string              pos;\n  std::vector<std::string> pos_all;\n  std::string              fidupos;\n  std::vector<std::string> fidupos_all;\n  std::string              meandiff;\n\n  // remove transforms\n  s_outputdirectory.append(\"/\");\n  bool transformDirectoryEmpty = DirectoryIsEmpty(s_outputdirectory.c_str() );\n  if( !transformDirectoryEmpty )\n    {\n    int length = strlen(s_outputdirectory.c_str() );\n    length = length + 10;\n\n    DIR *          pdir = NULL;\n    struct dirent *pent;\n    pdir = opendir(s_outputdirectory.c_str() );\n    while( (pent = readdir(pdir) ) )\n      {\n      char *file = NULL;\n      file = new char[512];\n      strcpy(file, s_outputdirectory.c_str() );\n      strcat(file, pent->d_name);\n      if( file[length] != '.' )\n        {\n        remove(file);\n        }\n      }\n    }\n\n  if( interactionTest )\n    {\n    char mrmlfile[512];\n    std::strcpy(mrmlfile, outbase.c_str() );\n    std::strcat(mrmlfile, \"_InteractionTest_MRMLscene.mrml\");\n\n    args.push_back(\"CreateMRML\");\n    args.push_back(mrmlfile);\n\n    double x, y, z, x2, fidux, fiduy, fiduz, fidux2;\n    x = -165;\n    y = 27;\n    z = -62;\n    /*fidux= x +Dim[0]/2+5;\n    fiduy= y+Dim[1]/2;\n    fiduz=90;*/\n    fidux = x + Dim[4] - 10;\n    fiduy = y + Dim[5];\n    fiduz = (Dim[7] + Dim[8]) / 2 - z;\n\n    // shape and tranfoms\n\n// RawP\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransRawP.tfm\"); args.push_back(\"-n\");\n    args.push_back(\"transRawP\"); args.push_back(\"-l\");\n\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\"RawP\");\n    args.push_back(\"-p\"); args.push_back(\"transRawP\"); args.push_back(\"-as\"); args.push_back(\"RawP\"); args.push_back(\n      \"-cc\"); args.push_back(\"customLUT_RawP.txt\");\n\n    fidupos.append(Convert_Double_To_CharArray(fidux) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"MANCOVA_RawP\"); args.push_back(\"-lbl\"); args.push_back(\n      \"MANCOVA_RawP\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n    pos.clear();\n    fidupos.clear();\n\n// FDRP\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransFDRP.tfm\"); args.push_back(\"-n\");\n    args.push_back(\"transFDRP\"); args.push_back(\"-l\");\n\n    z = z - Dim[2] - 10;\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\"FDRP\");\n    args.push_back(\"-p\"); args.push_back(\"transFDRP\"); args.push_back(\"-as\"); args.push_back(\"FDRP\"); args.push_back(\n      \"-cc\"); args.push_back(\"customLUT_FDRP.txt\");\n\n    fiduz = fiduz + Dim[2] + 5;\n    fidupos.append(Convert_Double_To_CharArray(fidux) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"MANCOVA_FDRP\"); args.push_back(\"-lbl\"); args.push_back(\n      \"MANCOVA_FDRP\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// normProjectionsPearsonPvalFDR\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\n      \"./transformFiles/TransnormProjectionsPearsonPvalFDR.tfm\"); args.push_back(\"-n\"); args.push_back(\n      \"transnormProjectionsPearsonPvalFDR\"); args.push_back(\"-l\");\n\n    z = z - Dim[2] - 10;\n    x2 = x + Dim[0];\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x2) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsPearsonPvalFDR\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsPearsonPvalFDR\");\n    args.push_back(\"-as\"); args.push_back(\"normProjectionsPearsonPvalFDR\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsPearsonPvalFDR.txt\");\n\n    fiduz = fiduz + 2 * Dim[2] + 10;\n    fidux2 = fidux + 2 * Dim[0] + 10;\n    fidupos.append(Convert_Double_To_CharArray(fidux2) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n// -q\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"normProjectionsPearsonPvalFDR\"); args.push_back(\"-lbl\");\n    args.push_back(\"normProjectionsPearsonPvalFDR\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// ProjectionsSpearmanPvalFDR\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\n      \"./transformFiles/TransnormProjectionsSpearmanPvalFDR.tfm\"); args.push_back(\"-n\"); args.push_back(\n      \"transnormProjectionsSpearmanPvalFDR\"); args.push_back(\"-l\");\n\n    //\tz=z-Dim[2]-5;\n    x = x - Dim[0];\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsSpearmanPvalFDR\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsSpearmanPvalFDR\");\n    args.push_back(\"-as\"); args.push_back(\"normProjectionsSpearmanPvalFDR\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsSpearmanPvalFDR.txt\");\n\n    fidux = fidux - 2 * Dim[0] - 10;\n    fidupos.append(Convert_Double_To_CharArray(fidux) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n// -q\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"normProjectionsSpearmanPvalFDR\"); args.push_back(\n      \"-lbl\"); args.push_back(\"normProjectionsSpearmanPvalFDR\"); args.push_back(\"-pos\"); args.push_back(\n      fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// normProjectionsPearsonPval\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransnormProjectionsPearsonPval.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transnormProjectionsPearsonPval\"); args.push_back(\"-l\");\n\n    z = z - Dim[2] - 10;\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x2) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsPearsonPval\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsPearsonPval\");\n    args.push_back(\"-as\"); args.push_back(\"normProjectionsPearsonPval\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsPearsonPval.txt\");\n\n    fiduz = fiduz + Dim[2] + 5;\n    fidupos.append(Convert_Double_To_CharArray(fidux2) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"transnormProjectionsPearsonPval\"); args.push_back(\n      \"-lbl\"); args.push_back(\"transnormProjectionsPearsonPval\"); args.push_back(\"-pos\"); args.push_back(\n      fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// normProjectionsSpearmanPval\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransnormProjectionsSpearmanPval.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transnormProjectionsSpearmanPval\"); args.push_back(\"-l\");\n\n    // z=z-Dim[2]-5;\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsSpearmanPval\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsSpearmanPval\");\n    args.push_back(\"-as\"); args.push_back(\"normProjectionsSpearmanPval\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsSpearmanPval.txt\");\n\n    fidupos.append(Convert_Double_To_CharArray(fidux) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"transnormProjectionsSpearmanPval\"); args.push_back(\n      \"-lbl\"); args.push_back(\"transnormProjectionsSpearmanPval\"); args.push_back(\"-pos\"); args.push_back(\n      fidupos_all.back(\n        ).c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// normProjectionsPearson\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"transformFiles/TransnormProjectionsPearson.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transnormProjectionsPearson\"); args.push_back(\"-l\");\n\n    z = z - Dim[2] - 10;\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x2) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsPearson\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsPearson\"); args.push_back(\n      \"-as\");\n    args.push_back(\"normProjectionsPearson\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsPearson.txt\");\n\n    fiduz = fiduz + Dim[2] + 5;\n    fidupos.append(Convert_Double_To_CharArray(fidux2) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"transnormProjectionsPearson\"); args.push_back(\"-lbl\");\n    args.push_back(\"transnormProjectionsPearson\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n// normProjectionsSpearman\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransnormProjectionsSpearman.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transnormProjectionsSpearman\"); args.push_back(\"-l\");\n\n    // z=z-Dim[2]-5;\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) ); pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"normProjectionsSpearman\"); args.push_back(\"-p\"); args.push_back(\"transnormProjectionsSpearman\"); args.push_back(\n      \"-as\"); args.push_back(\"normProjectionsSpearman\"); args.push_back(\"-cc\"); args.push_back(\n      \"customLUT_normProjectionsSpearman.txt\");\n\n    fidupos.append(Convert_Double_To_CharArray(fidux) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) ); fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"transnormProjectionsSpearman\"); args.push_back(\"-lbl\");\n    args.push_back(\"transnormProjectionsSpearman\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n    fidupos.clear();\n    pos.clear();\n\n    }\n  else\n    {\n\n    char mrmlfile[512];\n    std::strcpy(mrmlfile, outbase.c_str() );\n    std::strcat(mrmlfile, \"_GroupTest_MRMLscene.mrml\");\n\n    char nameMeanA[512];\n    std::strcpy(nameMeanA, outbase.c_str() );\n    std::strcat(nameMeanA, \"_meanA.meta\");\n    stringstream ssa;\n    string       s_nameMeanA;\n    ssa << nameMeanA;\n    ssa >> s_nameMeanA;\n    size_t found1;\n    found1 = s_nameMeanA.find_last_of(\"/\\\\\");\n\n    char nameMeanB[512];\n    std::strcpy(nameMeanB, outbase.c_str() );\n    std::strcat(nameMeanB, \"_meanB.meta\");\n    stringstream ssb;\n    string       s_nameMeanB;\n    ssb << nameMeanB;\n    ssb >> s_nameMeanB;\n    s_nameMeanA.erase(0, found1 + 1);\n    std::strcpy(nameMeanA, s_nameMeanA.c_str() );\n    s_nameMeanB.erase(0, found1 + 1);\n    std::strcpy(nameMeanB, s_nameMeanB.c_str() );\n\n    double x, y, z, x1, x2, fidux, fiduy, fiduz, fidux2;\n    x = 10;\n    y = 0;\n    z = -60;\n    fidux = x + Dim[4] - 10;\n    fiduy = y + Dim[5];\n    fiduz = (Dim[7] + Dim[8]) / 2 - z;\n\n    args.push_back(\"CreateMRML\");\n    args.push_back(mrmlfile);\n\n    // shapes and transforms\n// RawP\n\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransRawP.tfm\"); args.push_back(\"-n\");\n    args.push_back(\"transRawP\"); args.push_back(\"-l\");\n\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\"RawP\");\n    args.push_back(\"-p\"); args.push_back(\"transRawP\"); args.push_back(\"-as\"); args.push_back(\"RawP\"); args.push_back(\n      \"-cc\"); args.push_back(\"customLUT_RawP.txt\");\n\n    fidupos.append(Convert_Double_To_CharArray(fidux) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"RawP\"); args.push_back(\"-lbl\"); args.push_back(\"RawP\");\n    args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n// FDRP\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransFDRP.tfm\"); args.push_back(\"-n\");\n    args.push_back(\"transFDRP\"); args.push_back(\"-l\");\n\n    z = z + Dim[2] + 5; x1 = x;\n    pos.clear();\n    fidupos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\"FDRP\");\n    args.push_back(\"-p\"); args.push_back(\"transFDRP\"); args.push_back(\"-as\"); args.push_back(\"FDRP\"); args.push_back(\n      \"-cc\"); args.push_back(\"customLUT_FDRP.txt\");\n\n    fiduz = fiduz - Dim[2] - 5;\n    fidupos.append(Convert_Double_To_CharArray(fidux) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"FDRP\"); args.push_back(\"-lbl\"); args.push_back(\"FDRP\");\n    args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n// overlays Right\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransMeanOverlayRight.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transMeanOverlayRight\"); args.push_back(\"-l\");\n\n    z = z + Dim[2] + 5;\n    x2 = x + 2 * Dim[0] + 10;\n\n    pos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x2) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanA); args.push_back(\"-n\"); args.push_back(\n      \"MeanAOverlayRight\"); args.push_back(\"-p\"); args.push_back(\"transMeanOverlayRight\"); args.push_back(\"-as\");\n    args.push_back(\"MeanAOverlayRight\"); args.push_back(\"-dc\"); args.push_back(\"1,0,0\"); args.push_back(\"-op\");\n    args.push_back(\"0.6\");\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanB); args.push_back(\"-n\"); args.push_back(\n      \"MeanBOverlayRight\"); args.push_back(\"-p\"); args.push_back(\"transMeanOverlayRight\"); args.push_back(\"-as\");\n    args.push_back(\"MeanBOverlayRight\"); args.push_back(\"-dc\"); args.push_back(\"0,0,1\"); args.push_back(\"-op\");\n    args.push_back(\"0.4\");\n\n// overlays Left\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransMeanOverlayLeft.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transMeanOverlayLeft\"); args.push_back(\"-l\");\n\n    x = x - 2 * Dim[0] - 10;\n    pos.clear();\n    fidupos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanA); args.push_back(\"-n\"); args.push_back(\n      \"MeanAOverlayLeft\"); args.push_back(\"-p\"); args.push_back(\"transMeanOverlayLeft\"); args.push_back(\"-as\");\n    args.push_back(\"MeanAOverlayLeft\"); args.push_back(\"-dc\"); args.push_back(\"1,0,0\"); args.push_back(\"-op\");\n    args.push_back(\"0.4\");\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanB); args.push_back(\"-n\"); args.push_back(\n      \"MeanBOverlayLeft\"); args.push_back(\"-p\"); args.push_back(\"transMeanOverlayLeft\"); args.push_back(\"-as\");\n    args.push_back(\"MeanBOverlayLeft\"); args.push_back(\"-dc\"); args.push_back(\"0,0,1\"); args.push_back(\"-op\");\n    args.push_back(\"0.6\");\n\n    fiduz = fiduz - 1.5 * Dim[2] - 5;\n    fidux = fidux + Dim[4] / 2;\n    fidupos.append(Convert_Double_To_CharArray(fidux) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"Overlays\"); args.push_back(\"-lbl\"); args.push_back(\n      \"Overlays\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n// meanA\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransMeanRight.tfm\"); args.push_back(\n      \"-n\"); args.push_back(\"transMeanRight\"); args.push_back(\"-l\");\n\n    z = z + Dim[2] + 5;\n\n    fidupos.clear();\n    pos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x2) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanA); args.push_back(\"-n\"); args.push_back(\n      \"MeanRight\"); args.push_back(\"-p\"); args.push_back(\"transMeanRight\"); args.push_back(\"-as\"); args.push_back(\n      \"MeanRight\"); args.push_back(\"-dc\"); args.push_back(\"1,0,0\");\n\n    fiduz = fiduz - Dim[2] - 5;\n    fidupos.append(Convert_Double_To_CharArray(fidux) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(\"Means\"); args.push_back(\"-lbl\"); args.push_back(\n      \"Means\"); args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n\n// meanB\n\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransMeanLeft.tfm\"); args.push_back(\n      \"-n\"); args.push_back(\"transMeanLeft\"); args.push_back(\"-l\");\n\n    pos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameMeanB); args.push_back(\"-n\"); args.push_back(\n      \"MeanLeft\"); args.push_back(\"-p\"); args.push_back(\"transMeanLeft\"); args.push_back(\"-as\"); args.push_back(\n      \"MeanLeft\");\n    args.push_back(\"-dc\"); args.push_back(\"0,0,1\");\n\n// Diff\n\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(\"./transformFiles/TransDiffMagnitude.tfm\");\n    args.push_back(\"-n\"); args.push_back(\"transDiffMagnitude\"); args.push_back(\"-l\");\n\n    z = z + Dim[2] + 5;\n    pos.clear();\n    fidupos.clear();\n    pos.append(\"1,0,0,0,1,0,0,0,1,\");\n    pos.append(Convert_Double_To_CharArray(x1) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(y) );\n    pos.append(\",\");\n    pos.append(Convert_Double_To_CharArray(z) );\n    pos_all.push_back(pos);\n    args.push_back( (pos_all.back() ).c_str() );\n\n    args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(nameVTK); args.push_back(\"-n\"); args.push_back(\n      \"DiffMagnitude\"); args.push_back(\"-p\"); args.push_back(\"transDiffMagnitude\"); args.push_back(\"-as\");\n    args.push_back(\n      \"DiffMagnitude\"); args.push_back(\"-cc\"); args.push_back(\"customLUT_DiffMagnitude.txt\");\n\n    fiduz = fiduz - 1.5 * Dim[2] - 5;\n    fidux = fidux + Dim[4] / 2;\n    fidupos.append(Convert_Double_To_CharArray(fidux) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduy) );\n    fidupos.append(\",\");\n    fidupos.append(Convert_Double_To_CharArray(fiduz) );\n    fidupos_all.push_back(fidupos);\n\n    char minmaxf[512];\n    std::strcpy(minmaxf, outbase.c_str() );\n    std::strcat(minmaxf, \"_DiffMagnitude.txt\");\n    double min, max;\n    minmax(minmaxf, &min, &max);\n\n    std::vector<std::string> vec_min_max;\n    meandiff.append(\"Mean_Difference_Min:\");\n    meandiff.append(Convert_Double_To_CharArray(min) );\n    meandiff.append(\"_Max:\");\n    meandiff.append(Convert_Double_To_CharArray(max) );\n    vec_min_max.push_back(meandiff);\n    std::cout << meandiff << std::endl;\n    std::cout << vec_min_max.back() << std::endl;\n\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(meandiff.c_str() ); args.push_back(\"-lbl\");\n    args.push_back(meandiff.c_str() );\n    args.push_back(\"-pos\"); args.push_back(fidupos_all.back().c_str() );\n    }\n  for( int i = 0; i < args.size(); i++ )\n    {\n    std::cout << args.at(i) << \" \";\n    }\n  // end\n  args.push_back(0);\n\n  // Run the application\n\n  itksysProcess* gp = itksysProcess_New();\n  itksysProcess_SetCommand(gp, &*args.begin() );\n  itksysProcess_SetOption(gp, itksysProcess_Option_HideWindow, 1);\n  itksysProcess_Execute(gp);\n\n  while( int Value = itksysProcess_WaitForData(gp, &data, &length, &timeout) ) // wait for 1s\n    {\n    if( ( (Value == itksysProcess_Pipe_STDOUT) || (Value == itksysProcess_Pipe_STDERR) ) && data[0] == 'D' )\n      {\n      strstream st;\n      for( int i = 0; i < length; i++ )\n        {\n        st << data[i];\n        }\n      string dim = st.str();\n      }\n    timeout = 0.05;\n    }\n\n  itksysProcess_WaitForExit(gp, 0);\n\n  result = 1;\n\n  switch( itksysProcess_GetState(gp) )\n    {\n    case itksysProcess_State_Exited:\n      {\n      result = itksysProcess_GetExitValue(gp);\n      } break;\n    case itksysProcess_State_Error:\n      {\n      std::cerr << \"Error: Could not run \" << args[0] << \":\\n\";\n      std::cerr << itksysProcess_GetErrorString(gp) << \"\\n\";\n      std::cout << \"Error: Could not run \" << args[0] << \":\\n\";\n      std::cout << itksysProcess_GetErrorString(gp) << \"\\n\";\n      } break;\n    case itksysProcess_State_Exception:\n      {\n      std::cerr << \"Error: \" << args[0] << \" terminated with an exception: \" << itksysProcess_GetExceptionString(gp)\n                << \"\\n\";\n      std::cout << \"Error: \" << args[0] << \" terminated with an exception: \" << itksysProcess_GetExceptionString(gp)\n                << \"\\n\";\n      } break;\n    case itksysProcess_State_Starting:\n    case itksysProcess_State_Executing:\n    case itksysProcess_State_Expired:\n    case itksysProcess_State_Killed:\n      {\n      // Should not get here.\n      std::cerr << \"Unexpected ending state after running \" << args[0] << std::endl;\n      std::cout << \"Unexpected ending state after running \" << args[0] << std::endl;\n      } break;\n    }\n  itksysProcess_Delete(gp);\n\n}\n\nstd::vector<double> SetImageDimensions(char *filename)\n{\n\n  vector<double> vectDims;\n  // read vtk file\n  vtkPolyDataReader *meshin = vtkPolyDataReader::New();\n  meshin->SetFileName(filename);\n\n  meshin->Update();\n\n  vtkPolyData *poly = vtkPolyData::New();\n  poly = meshin->GetOutput();\n  vtkIdType idNumPointsInFile = poly->GetNumberOfPoints();\n\n  vtkPoints * pts;\n  double      minCoord[3];\n  double      maxCoord[3];\n\n  double *firstCoord;\n\n  // find the max and min coordinates\n  pts = poly->GetPoints();\n  firstCoord = pts->GetPoint(0);\n\n  minCoord[0] = firstCoord[0];\n  minCoord[1] = firstCoord[1];\n  minCoord[2] = firstCoord[2];\n\n  maxCoord[0] = firstCoord[0];\n  maxCoord[1] = firstCoord[1];\n  maxCoord[2] = firstCoord[2];\n  for( unsigned int i = 1; i < idNumPointsInFile; i++ )\n    {\n    double *p;\n    p = pts->GetPoint(i);\n\n    if( p[0] <= minCoord[0] )\n      {\n      minCoord[0] = p[0];\n      }\n\n    if( p[1] <= minCoord[1] )\n      {\n      minCoord[1] = p[1];\n      }\n\n    if( p[2] <= minCoord[2] )\n      {\n      minCoord[2] = p[2];\n      }\n\n    if( p[0] >= maxCoord[0] )\n      {\n      maxCoord[0] = p[0];\n      }\n\n    if( p[1] >= maxCoord[1] )\n      {\n      maxCoord[1] = p[1];\n      }\n\n    if( p[2] >= maxCoord[2] )\n      {\n      maxCoord[2] = p[2];\n      }\n    }\n\n  // vectDims.clear();\n  // find the biggest dimension\n  vectDims.push_back(maxCoord[0] - minCoord[0]);\n  vectDims.push_back(maxCoord[1] - minCoord[1]);\n  vectDims.push_back(maxCoord[2] - minCoord[2]);\n  vectDims.push_back(minCoord[0]);\n  vectDims.push_back(maxCoord[0]); // 4\n  vectDims.push_back(minCoord[1]);\n  vectDims.push_back(maxCoord[1]);\n  vectDims.push_back(minCoord[2]);\n  vectDims.push_back(maxCoord[2]);\n\n  return vectDims;\n\n}\n\n/*\nvector <double> GetImageDimensions()\n{\n  return vectDims;\n}*/\n\nchar * Convert_Double_To_CharArray(double doubleVariable)\n{\n  char *CharArrayOut;\n\n  CharArrayOut = new char[512];\n  std::string       stringVariable;\n  std::stringstream strStream;\n  strStream << doubleVariable;\n  stringVariable = strStream.str();\n  strcpy(CharArrayOut, stringVariable.c_str() );\n\n  return CharArrayOut;\n}\n\n// TODO use this function to reduce the size of the creation MRML function\n\n//\n// add_Shape_MRMLScene(args,\"RawP\",nameVTK,1,\"transRawP\",\"./transformFiles/TransRawP.tfm\",pos_all.back(),1,\"customLUT_RawP.txt\",1,fidupos_all.back());\nvoid add_Shape_MRMLScene(std::vector<const char *>& args, std::string name, std::string mesh, bool transform,\n                         std::string nametransf, std::string pathtransf, std::string trans_value, bool colorMap,\n                         std::string colorMap_value,\n                         bool fidu,\n                         std::string fidu_value)\n// void add_Shape_MRMLScene(std::string name,std::string mesh,bool transform,std::string trans_value,bool\n// colorMap,std::string colorMap_value,bool fidu,std::string fidu_value)\n{\n\n  // transf\n  if( transform )\n    {\n    /*pathtransf.append(\"./transformFiles/\");\n    pathtransf.append(name);\n    pathtransf.append(\".tfm\");\n    nametransf.append(\"trans\");\n    nametransf.append(name);\nstd::cout<<pathtransf<<std::endl;*/\n    /*std::cout<<pathtransf<<std::endl;\n    std::cout<<nametransf.c_str()<<std::endl;\n    std::cout<<trans_value<<std::endl;*/\n\n    args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(pathtransf.c_str() ); args.push_back(\"-n\");\n    args.push_back(nametransf.c_str() ); args.push_back(\"-l\"); args.push_back(trans_value.c_str() );\n\n    // args.push_back(\"-t\"); args.push_back(\"-f\"); args.push_back(pathtransf.c_str()); args.push_back(\"-n\");\n    // args.push_back(nametransf.c_str());args.push_back(\"-l\");args.push_back(trans_value.c_str());\n    }\n\n  // shape\n  args.push_back(\"-m\"); args.push_back(\"-f\"); args.push_back(mesh.c_str() ); args.push_back(\"-n\"); args.push_back(\n    name.c_str() );\n  if( transform )\n    {\n    args.push_back(\"-p\"); args.push_back(nametransf.c_str() );\n    }\n\n  if( colorMap )\n    {\n    args.push_back(\"-as\"); args.push_back(name.c_str() ); args.push_back(\"-cc\"); args.push_back(colorMap_value.c_str() );\n    }\n  else\n    {\n    args.push_back(\"-as\"); args.push_back(name.c_str() ); args.push_back(\"-dc\"); args.push_back(colorMap_value.c_str() );\n    }\n\n  // fidu\n  if( fidu )\n    {\n    args.push_back(\"-q\"); args.push_back(\"-id\"); args.push_back(name.c_str() ); args.push_back(\"-lbl\"); args.push_back(\n      name.c_str() ); args.push_back(\"-pos\"); args.push_back(fidu_value.c_str() );\n    }\n\n}\n\nbool DirectoryIsEmpty(const char * path)\n{\n  DIR *          dir = opendir(path);\n  struct dirent *mydir;\n  int            nbFiles = -2;\n\n  if( dir != NULL )\n    {\n    while( (mydir = readdir(dir) ) != NULL )\n      {\n      nbFiles++;\n\n      }\n    }\n  else\n    {\n    cerr << \" Cannot read the directory \" << path << endl;\n    }\n  if( nbFiles == 0 )\n    {\n    return true;\n    }\n  else\n    {\n    return false;\n    }\n}\n", "meta": {"hexsha": "57ad8bdaaecd17171bfe7f400b30e4f801dd1cbd", "size": 84633, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "StatNonParamTestPDM/miscMANCOVA.cxx", "max_stars_repo_name": "slicersalt/shapeAnalysisMANCOVA", "max_stars_repo_head_hexsha": "7f36668b481876b7b0f8fbfafde7b93b3cb9a333", "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": "StatNonParamTestPDM/miscMANCOVA.cxx", "max_issues_repo_name": "slicersalt/shapeAnalysisMANCOVA", "max_issues_repo_head_hexsha": "7f36668b481876b7b0f8fbfafde7b93b3cb9a333", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T17:58:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T17:58:35.000Z", "max_forks_repo_path": "shapeAnalysisMANCOVA/miscMANCOVA.cxx", "max_forks_repo_name": "slicersalt/shapeAnalysisMANCOVA", "max_forks_repo_head_hexsha": "7f36668b481876b7b0f8fbfafde7b93b3cb9a333", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-28T15:33:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T17:57:32.000Z", "avg_line_length": 33.2938630999, "max_line_length": 150, "alphanum_fraction": 0.595547836, "num_tokens": 22622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6527501249455671}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include <Eigen/Dense>\n\n#include \"timer.h\"\n\n//! \\brief Structure holding a triplet in format (row, col, value)\n//! For convenience, we provide a void constructor and a init constructor. All members are public\n//! Used in the TripletMatrix class to provide a nice wrapper for a triplet\n//! \\tparam scalar represents the type of the triplet (e.g. double)\ntemplate <class scalar>\nstruct Triplet {\n    Triplet(void)\n    : i(0), j(0), v(0) { }\n    \n    Triplet(std::size_t i_, std::size_t j_, scalar v_)\n        : i(i_), j(j_), v(v_) { }\n    \n    std::size_t i, j; //< row and col\n    scalar v; //< value @ (row,col)\n};\n\n//! \\brief Defines a matrix stored in triplet format (using the Triplet<scalar> class.\n//! Triplets may be duplicated and in *any* order. If there is a multiple triplet for (row,col) pair, we assume\n//! that the values are intended to be added together\n//! Also stores dimension\n//! \\tparam scalar represents the scalar type of the matrix (and of the triplet) (e.g. double)\ntemplate <class scalar>\nstruct TripletMatrix {\n    std::size_t rows, cols; //< Sizes: nrows and ncols\n    std::vector< Triplet<scalar> > triplets;\n    \n    //! \\brief Converts *this to an eigen (dense) function, used for visualization\n    //! Loops over all triplets and add value to Zero matrix (read-only)\n    //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1\n    //! \\return Eigen::Matrix of Dynamic size and scalar type\n    Eigen::Matrix<scalar, -1, -1> densify() const {\n        Eigen::Matrix<scalar, -1, -1> M = Eigen::Matrix<scalar, -1, -1>::Zero(rows, cols);\n        for(auto it = triplets.begin(); it != triplets.end(); ++it) {\n            M(it->i, it->j) += it->v;\n        }\n        return M;\n    }\n};\n\n// const TripletMatrix;\n\n//! \\brief Structure holding a pair column index-value to be used in CRS format\n//! Provides handy constructor and comparison operators.\n//! \\tparam scalar represents the scalar type of the value stored (e.g. double)\ntemplate <class scalar>\nstruct ColValPair {\n    ColValPair(std::size_t col_, scalar v_)\n        : col(col_), v(v_) { }\n    \n    //! \\brief Comparison operator for std::sort and std::lower_bound\n    //! Basic sorting operator < for use with std:: functions (i.e. for ordering according to first component (col)\n    //! We keep the column values sorted, either by sorting after insertion of by sorted insertion\n    //! \\return true if this->col < other.col\n    bool operator<(const ColValPair & other) const {\n        return this->col < other.col;\n    }\n    \n    std::size_t col; //< col index\n    scalar v; //< scalar value at col\n};\n\n//! \\brief Defines a matrix stored in CRS format (using the ColValPair<scalar> struct.\n//! The row_pt contains the data, indexed by row and column position\n//! Also stores dimension\n//! \\tparam scalar represents the scalar type of the matrix (and of the ColValPair) (e.g. double)\ntemplate <class scalar>\nstruct CRSMatrix {\n    std::size_t rows, cols; //< Size of the matrix rows, cols\n    std::vector< std::vector< ColValPair<scalar> > > row_pt; //< Vector containing, for each row, al vector of (col, value) pairs (CRS format)\n    \n    //! \\brief Converts *this to an eigen (dense) function, used for visualization\n    //! Loops over all rows and add value at col (in ColValPair) to Zero matrix (read-only)\n    //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1\n    //! \\return Eigen::Matrix of Dynamic size and scalar type\n    Eigen::Matrix<scalar, -1, -1> densify() const {\n        Eigen::Matrix<scalar, -1, -1> M = Eigen::Matrix<scalar, -1, -1>::Zero(rows, cols);\n        std::size_t i = 0;\n        for(auto it = row_pt.begin(); it != row_pt.end(); ++it) {\n            for(auto it2 = it->begin(); it2 != it->end(); ++it2) {\n                M(i, it2->col) = it2->v;\n            }\n            ++i;\n        }\n        return M;\n    }\n};\n\n//! \\brief Converts a matrix given as triplet matrix to a matrix in CRS format\n//! No assumption is made on the triplets, may be unsorted and/or duplicated\n//! In case of duplicated triplets, values are added toghether\n//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)\n//! This version inserts the ColValParis already sorted in the list\n//! Complexity: loops over all triplets (lets say k) and look up over all columns of the row (say n_i), performing a\n//! linear search and an insertion (complexity O(n_i))\n//! Assuming n_i is bounded by n small, complexity is k*n, otherwise k^2\ntemplate <class scalar>\nvoid tripletToCRS(const TripletMatrix<scalar> & T, CRSMatrix<scalar> & C) {\n    // Copy sizes and reserve memory for rows\n    C.rows = T.rows;\n    C.cols = T.cols;\n    C.row_pt.resize(C.rows);\n    \n    // Loop over all triplets\n    for(auto triplet_it = T.triplets.begin(); triplet_it != T.triplets.end(); ++triplet_it) {\n        // Store row (containing the ColValPairs for this row) inside the row_pt vector\n        auto & row = C.row_pt.at(triplet_it->i);\n        // Create a ColVal pair that must be inserted somewhere\n        ColValPair<scalar> col_val(triplet_it->j, triplet_it->v);\n        // Find the place (as iterator) where to insert col_val, i.e. the first place where col_val < C.row_pt.at(i)\n        // WARNING: Costly call (loops over all of row (worts case scenario))\n        auto lb_it = std::lower_bound(row.begin(), row.end(), col_val);\n        // If lower bound has already a col (and is not end()) with some value, just add the value to the column, othervise insert it\n        if(lb_it != row.end() && lb_it->col == triplet_it->j) {\n            lb_it->v += triplet_it->v;\n        } else {\n            // WARNING: Costly call (loops over all of row (worts case scenario))\n            row.insert(lb_it, col_val);\n        }\n    }\n}\n\n//! \\brief Converts a matrix given as triplet matrix to a matrix in CRS format\n//! No assumption is made on the triplets, may be unsorted and/or duplicated\n//! In case of duplicated triplets, values are added toghether\n//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)\n//! This version inserts all the triplets (push_back) then sorts eatch row and cumsum al the duplicated col values\n//! *** Complexity: loops over all triplets (lets say k) and do a cheap (amortized) o(1) push back (complexity k*1). Then sorts an array\n//! of rows (ith quicksort complexity k * log(k))\ntemplate <class scalar>\nvoid tripletToCRS_sortafter(const TripletMatrix<scalar> & T, CRSMatrix<scalar> & C) {\n    // Copy dimensions and reserve known space\n    C.rows = T.rows;\n    C.cols = T.cols;\n    C.row_pt.resize(C.rows);\n    \n    // Loops over all triplets and push them at the ritgh place (cheap)\n    for(auto triplets_it = T.triplets.begin(); triplets_it != T.triplets.end(); ++triplets_it) {\n        ColValPair<scalar> cp(triplets_it->j, triplets_it->v);\n        C.row_pt.at(triplets_it->i).push_back(cp);\n    }\n    // Loops over all rows , sort them (according to col) and sum duplicated values\n    for(auto row_it = C.row_pt.begin(); row_it != C.row_pt.end(); ++row_it) {\n        // WARNING: costly call in this case\n        std::sort(row_it->begin(), row_it->end());\n        // Sum duplicated cols\n        // NOTE: iterating backwards should be faster\n        for(auto col_it = row_it->begin(); col_it != row_it->end(); ++col_it) {\n            // Check that next col is not at the end and that has same col value\n            if((col_it + 1) != row_it->end() && (col_it + 1)->col == col_it->col) {\n                // Last col with same value (starting from next col)\n                auto last_col_it = col_it + 1;\n                while(last_col_it != row_it->end() && last_col_it->col == col_it->col) {\n                    col_it->v += last_col_it->v;\n                    ++last_col_it;\n                }\n                // Remove range from next col to last col with same value\n                // WARNING: std::vector keeps the data as c-array, so mildly costly call (from col_it to end() (at most M)\n                row_it->erase(col_it+1, last_col_it);\n            }\n        }\n    }\n}\n\n//! \\brief overload of operator << for output of Triplet Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! \\param o standard output stream\n//! \\param S matrix in Triplet matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const TripletMatrix<double> & S) {\n    return o << S.densify();\n}\n\n//! \\brief overload of operator << for output of CRS Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! \\param o standard output stream\n//! \\param S matrix in CRS matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const CRSMatrix<double> & S) {\n    return o << S.densify();\n}\n\nint main() {\n    //// Correctness test\n    std::size_t nrows = 7, ncols = 5, ntriplets = 9;\n    \n    TripletMatrix<double> T;\n    CRSMatrix<double> C,D;\n    \n    T.rows = nrows;\n    T.cols = ncols;\n    T.triplets.reserve(ntriplets); // Always reserve space if you can\n    for(auto i = 0u; i < ntriplets; ++i) {\n        // Test unordered triplets, random and maybe repeated triplets\n        T.triplets.push_back(Triplet<double>(rand() % nrows, rand() % ncols, rand() % 1000));\n    }\n    \n    std::cout << \"***Test conversion with random matrices***\" << std::endl;\n    tripletToCRS(T, C);\n    std::cout << \"--> Frobenius norm of T - C: \" << (T.densify()-C.densify()).norm() << std::endl;\n    std::cout << \"T = \" << std::endl << T << std::endl;\n    std::cout << \"C = \" << std::endl << C << std::endl;\n    \n    tripletToCRS_sortafter(T, D);\n    std::cout << \"--> Frobenius norm of T - D: \" << (T.densify()-D.densify()).norm() << std::endl;\n    std::cout << \"D = \" << D << std::endl;\n    \n    // Big benefit of how we defined our functions: can add new triplets to the old ones:\n    std::cout << \"***Test addition with random matrices***\" << std::endl;\n    TripletMatrix<double> T2;\n    T2.rows = nrows;\n    T2.cols = ncols;\n    T2.triplets.reserve(ntriplets); // Always reserve space if you can\n    for(auto i = 0u; i < ntriplets; ++i) {\n        // Test unordered triplets, random and maybe repeated triplets\n        T2.triplets.push_back(Triplet<double>(rand() % nrows, rand() % ncols, rand() % 1000));\n    }\n    tripletToCRS(T2, C);\n    tripletToCRS_sortafter(T2, D);\n    std::cout << \"T = \" << std::endl << T << std::endl;\n    std::cout << \"T2 = \" << std::endl << T2 << std::endl;\n    std::cout << \"C = \" << std::endl << C << std::endl;\n    std::cout << \"D = \" << std::endl << D << std::endl;\n    \n    //// Runtime test\n    bool noruntime = false; // Skip runtime measurments\n    bool noaddition = true; // Do not test addition of new triplets\n    \n    if(noruntime) {\n        return 0;\n    }\n    std::cout << \"***Runtime test***\" << std::endl;\n    \n    // Play around with this parameters (also introducing lambda functions)\n    auto frows = [](std::size_t M) { return 2*M; };\n    auto fcols = [](std::size_t M) { return M; };\n    auto ftriplets = [](std::size_t M) { return M*5; };\n    \n    // Do some timings\n    timer<> sortafter_timer, insertsort_timer;\n    for(std::size_t M = 2u; M < 1024u; M *= 2u) {\n        sortafter_timer.reset();\n        insertsort_timer.reset();\n        std::cout << \"Runtime for \" << M << \"x\" << M/2 << \" matrix (with nnz(A) <= \" << M << \"):\" << std::endl;\n        for(int r = 0; r < 4; ++r) {\n            \n            TripletMatrix<double> A;\n            CRSMatrix<double> B, E;\n            \n            A.rows = frows(M); // nrows\n            A.cols = fcols(M); //ncols\n            A.triplets.reserve(ftriplets(M));\n            for(auto i = 0u; i < ftriplets(M); ++i) {\n                A.triplets.push_back(Triplet<double>(rand() % A.rows, rand() % A.cols, rand() % 1000));\n            }\n            \n            insertsort_timer.start();\n            tripletToCRS(A, B);\n            if(!noaddition) tripletToCRS(A, B);\n            insertsort_timer.stop();\n            \n            sortafter_timer.start();\n            tripletToCRS_sortafter(A, E);\n            if(!noaddition) tripletToCRS_sortafter(A, E);\n            sortafter_timer.stop();\n        }\n        std::cout << \"Insertsort took:  \" << insertsort_timer.min().count() / 1000. << \" ms.\" << std::endl;\n        std::cout << \"Sortafter took:   \" << sortafter_timer.min().count() / 1000. << \" ms.\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "0b96a41d4912a1b489a9b271c001904ecc50cb24", "size": 12548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS3/solutions_ps3/tripletToCRS_solution.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/PS3/tripletToCRS_solution.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/PS3/tripletToCRS_solution.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": 45.1366906475, "max_line_length": 142, "alphanum_fraction": 0.6119700351, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.6527251004831361}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2013-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#include <rokko/localized_matrix.hpp>\n#include <rokko/localized_vector.hpp>\n\n#define BOOST_TEST_MODULE test_distributed_matrix\n#ifndef BOOST_TEST_DYN_LINK\n#include <boost/test/included/unit_test.hpp>\n#else\n#include <boost/test/unit_test.hpp>\n#endif\n\nBOOST_AUTO_TEST_CASE(test_localized_matrix) {\n\n  // M = 1 2 3\n  //     4 5 6\n  //     7 8 9\n  //\n  // a = 5\n  // \n  // u = 1\n  //     2\n  //     3\n  //\n  // v = 4\n  //     5\n  //     6\n  // \n  // w = au + Mv = 37\n  //               87\n  //              137\n\n  int dim = 3;\n  rokko::localized_matrix<double, rokko::matrix_row_major, 3, 3> M(dim,dim);\n  M << 1,2,3,4,5,6,7,8,9;\n  double a = 5.0;\n  rokko::localized_vector<double, 3> u(dim);\n  u << 1,2,3;\n  rokko::localized_vector<double, 3> v(dim);\n  v << 4,5,6;\n\n  rokko::localized_vector<double> w = a*u+M*v;\n  BOOST_CHECK_EQUAL(w[0],37.);\n  BOOST_CHECK_EQUAL(w[1],87.);\n  BOOST_CHECK_EQUAL(w[2],137.);\n\n  // u^t M = 30 36 42\n  BOOST_CHECK_EQUAL( (u.transpose()*M.col(0)), 30.);\n  BOOST_CHECK_EQUAL( (u.transpose()*M.col(1)), 36.);\n  BOOST_CHECK_EQUAL( (u.transpose()*M.col(2)), 42.);\n}\n", "meta": {"hexsha": "e70a567ecbb0c4ec2a89eef9374c3ecddaf81568", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/localized_matrix_fixed_size.cpp", "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": "test/localized_matrix_fixed_size.cpp", "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": "test/localized_matrix_fixed_size.cpp", "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": 25.5409836066, "max_line_length": 79, "alphanum_fraction": 0.5661103979, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6527250964953042}}
{"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_UBLAS_MATRIX_HPP\n#define SPRIG_UBLAS_MATRIX_HPP\n\n#include <sprig/config/config.hpp>\n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include <cstddef>\n#include <cmath>\n#include <boost/array.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace sprig {\n\tnamespace ublas {\n\t\t//\n\t\t// make_scaling_matrix_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> make_scaling_matrix_2d(T const sx, T const sy) {\n\t\t\tboost::numeric::ublas::matrix<T> mat = boost::numeric::ublas::identity_matrix<T>(3);\n\t\t\tmat(0, 0) = sx;\n\t\t\tmat(1, 1) = sy;\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// make_rotation_matrix_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> make_rotation_matrix_2d(T const a) {\n\t\t\tboost::numeric::ublas::matrix<T> mat = boost::numeric::ublas::identity_matrix<T>(3);\n\t\t\tmat(0, 0) = std::cos(a);\n\t\t\tmat(0, 1) = std::sin(a);\n\t\t\tmat(1, 0) = -mat(0, 1);\n\t\t\tmat(1, 1) = mat(0, 0);\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// make_translation_matrix_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> make_translation_matrix_2d(T const tx, T const ty) {\n\t\t\tboost::numeric::ublas::matrix<T> mat = boost::numeric::ublas::identity_matrix<T>(3);\n\t\t\tmat(2, 0) = tx;\n\t\t\tmat(2, 1) = ty;\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// matrix_prod\n\t\t//\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> matrix_prod(\n\t\t\tboost::numeric::ublas::matrix<T> const& m1,\n\t\t\tboost::numeric::ublas::matrix<T> const& m2\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(m1, m2);\n\t\t}\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> matrix_prod(\n\t\t\tboost::numeric::ublas::matrix<T> const& m1,\n\t\t\tboost::numeric::ublas::matrix<T> const& m2,\n\t\t\tboost::numeric::ublas::matrix<T> const& m3\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2), m3);\n\t\t}\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> matrix_prod(\n\t\t\tboost::numeric::ublas::matrix<T> const& m1,\n\t\t\tboost::numeric::ublas::matrix<T> const& m2,\n\t\t\tboost::numeric::ublas::matrix<T> const& m3,\n\t\t\tboost::numeric::ublas::matrix<T> const& m4\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2, m3), m4);\n\t\t}\n\t\ttemplate<typename T>\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix<T> matrix_prod(\n\t\t\tboost::numeric::ublas::matrix<T> const& m1,\n\t\t\tboost::numeric::ublas::matrix<T> const& m2,\n\t\t\tboost::numeric::ublas::matrix<T> const& m3,\n\t\t\tboost::numeric::ublas::matrix<T> const& m4,\n\t\t\tboost::numeric::ublas::matrix<T> const& m5\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2, m3, m4), m5);\n\t\t}\n\t\t//\n\t\t// scaling_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tclass scaling_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix<value_type> matrix_type;\n\t\tprivate:\n\t\t\tboost::array<value_type, 2> elems_;\n\t\tpublic:\n\t\t\tscaling_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t\telems_[1] = value_type();\n\t\t\t}\n\t\t\tscaling_2d(\n\t\t\t\ttypename boost::call_traits<value_type>::param_type v1,\n\t\t\t\ttypename boost::call_traits<value_type>::param_type v2\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t\telems_[1] = v2;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_scaling_matrix_2d(elems_[0], elems_[1]);\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t\t//\n\t\t// rotation_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tclass rotation_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix<value_type> matrix_type;\n\t\tprivate:\n\t\t\tboost::array<value_type, 1> elems_;\n\t\tpublic:\n\t\t\trotation_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t}\n\t\t\trotation_2d(\n\t\t\t\ttypename boost::call_traits<value_type>::param_type v1\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_rotation_matrix_2d(elems_[0]);\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t\t//\n\t\t// translation_2d\n\t\t//\n\t\ttemplate<typename T>\n\t\tclass translation_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix<value_type> matrix_type;\n\t\tprivate:\n\t\t\tboost::array<value_type, 2> elems_;\n\t\tpublic:\n\t\t\ttranslation_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t\telems_[1] = value_type();\n\t\t\t}\n\t\t\ttranslation_2d(\n\t\t\t\ttypename boost::call_traits<value_type>::param_type v1,\n\t\t\t\ttypename boost::call_traits<value_type>::param_type v2\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t\telems_[1] = v2;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_translation_matrix_2d(elems_[0], elems_[1]);\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate<std::size_t N>\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t}\t// namespace ublas\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_UBLAS_MATRIX_HPP\n", "meta": {"hexsha": "c386800b92d4e4430e0c4d282d8091135918cb07", "size": 5349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/ublas/matrix.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/ublas/matrix.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/ublas/matrix.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": 26.2205882353, "max_line_length": 100, "alphanum_fraction": 0.6389979435, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339636614181, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6527250890455691}}
{"text": "#include <utility>\n#include <vector>\n#include <stack>\n#include <algorithm>\n\n#include <boost/geometry/geometry.hpp>\n\nusing namespace boost::geometry;\n\ntemplate\n<\n    typename Point\n>\nstruct triangle {\n    Point p1,p2,p3;\n    std::vector<std::size_t> adjacent_indices;\n};\n\ntemplate\n<\n    typename Area,\n    typename Point\n>\nArea triangle_double_area(const Point& p1, const Point& p2, const Point& p3) {\n    return std::abs(boost::numeric_cast<Area>(get<0>(p1))*boost::numeric_cast<Area>(get<1>(p2))-boost::numeric_cast<Area>(get<0>(p1))*boost::numeric_cast<Area>(get<1>(p3))+boost::numeric_cast<Area>(get<0>(p2))*boost::numeric_cast<Area>(get<1>(p3))-boost::numeric_cast<Area>(get<0>(p2))*boost::numeric_cast<Area>(get<1>(p1))+boost::numeric_cast<Area>(get<0>(p3))*boost::numeric_cast<Area>(get<1>(p1))-boost::numeric_cast<Area>(get<0>(p3))*boost::numeric_cast<Area>(get<1>(p2)));\n}\n\ntemplate\n<\n    typename Point\n>\ndouble circumcircle_diameter(const Point& p1, const Point& p2, const Point& p3)\n{\n    return distance(p1,p2)*distance(p1,p3)*distance(p2,p3)/triangle_double_area<double,Point>(p1,p2,p3);\n}\n\n\ntemplate\n<\n    typename Point\n>\nPoint circumcircle_center(const Point& p1, const Point& p2, const Point& p3)\n{\n    auto ax = get<0>(p1);\n    auto ay = get<1>(p1);\n    auto bx = get<0>(p2);\n    auto by = get<1>(p2);\n    auto cx = get<0>(p3);\n    auto cy = get<1>(p3);\n    auto d = 2*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by));\n    auto x = ((ax*ax+ay*ay)*(by-cy)+(bx*bx+by*by)*(cy-ay)+(cx*cx+cy*cy)*(ay-by))/d;\n    auto y = ((ax*ax+ay*ay)*(cx-bx)+(bx*bx+by*by)*(ax-cx)+(cx*cx+cy*cy)*(bx-ax))/d;\n    return make<Point>(x,y);\n}\n\ntemplate\n<\n    typename Segment\n>\ndouble angle(const Segment& s)\n{\n    return std::atan2(get<1,1>(s)-get<0,1>(s),get<1,0>(s)-get<0,0>(s));\n}\n\ntemplate\n<\n    typename Point,\n    typename Segment\n>\nbool is_left_of(const Point& p, const Segment& s)\n{\n    return (get<0>(p)-get<0,0>(s))*(get<1,1>(s)-get<0,1>(s))-(get<1>(p)-get<0,1>(s))*(get<1,0>(s)-get<0,0>(s))<0;\n}\n\ntemplate\n<\n    typename Point\n>\nbool adjacent_at_edge(const triangle<Point>& t1, const triangle<Point>& t2, const Point& p1, const Point& p2)\n{\n    //Very naive check, not necessary with proper triangulation data structure\n    return (equals(p1,t1.p1) || equals(p1,t1.p2) || equals(p1,t1.p3)) \n        && (equals(p2,t1.p1) || equals(p2,t1.p2) || equals(p2,t1.p3))\n        && (equals(p1,t2.p1) || equals(p1,t2.p2) || equals(p1,t2.p3))\n        && (equals(p2,t2.p1) || equals(p2,t2.p2) || equals(p2,t2.p3));\n}\n\ntemplate\n<\n    typename Point\n>\nstd::vector<std::pair<std::size_t,std::size_t>> flip_if_not_locally_delaunay(std::vector<triangle<Point>>& triangles, std::size_t ti1, std::size_t ti2)\n{\n    triangle<Point>& t1 = triangles[ti1];\n    if(std::find(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),ti2)==t1.adjacent_indices.end())\n        return {};\n    triangle<Point>& t2 = triangles[ti2];\n    Point *p1, *p2, *p3, *p4;\n    if(!equals(t1.p1,t2.p1) && !equals(t1.p1,t2.p2) && !equals(t1.p1, t2.p3)) {\n        p4 = &t1.p1;\n        p1 = &t1.p2;\n        p3 = &t1.p3;\n    }\n    else if(!equals(t1.p2,t2.p1) && !equals(t1.p2,t2.p2) && !equals(t1.p2, t2.p3)) {\n        p4 = &t1.p2;\n        p1 = &t1.p3;\n        p3 = &t1.p1;\n    }\n    else {\n        p4 = &t1.p3;\n        p1 = &t1.p1;\n        p3 = &t1.p2;\n    }\n    if(!equals(t2.p1,*p1) && !equals(t2.p1,*p3))\n        p2 = &t2.p1;\n    else if(!equals(t2.p2,*p1) && !equals(t2.p2,*p3))\n        p2 = &t2.p2;\n    else\n        p2 = &t2.p3;\n    bool loc_delaunay = distance(circumcircle_center(*p1,*p2,*p3),*p4)>circumcircle_diameter(*p1,*p2,*p3)/2;\n    if(loc_delaunay)\n        return {};\n    std::size_t t1a1=-1, t2a1=-1;\n    for(const auto& i : t1.adjacent_indices) {\n        if(i!=ti2)\n            if(adjacent_at_edge(t1, triangles[i], *p3, *p4))\n                t1a1 = i;\n    }\n    for(const auto& i : t2.adjacent_indices) {\n        if(i!=ti1)\n            if(adjacent_at_edge(t2, triangles[i], *p1, *p2))\n                t2a1 = i;\n    }\n    Point temp;\n    assign(temp,*p3);\n    assign(*p3,*p2);\n    if(equals(t2.p1,temp))\n        assign(t2.p2,*p4);\n    else if(equals(t2.p2,temp))\n        assign(t2.p3,*p4);\n    else\n        assign(t2.p1,*p4);\n    if(t1a1!=-1 && t2a1!=-1) {\n        std::replace(triangles[t1a1].adjacent_indices.begin(),triangles[t1a1].adjacent_indices.end(),ti1,ti2);\n        std::replace(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),t1a1,t2a1);\n        std::replace(triangles[t2a1].adjacent_indices.begin(),triangles[t2a1].adjacent_indices.end(),ti2,ti1);\n        std::replace(t2.adjacent_indices.begin(),t2.adjacent_indices.end(),t2a1,t1a1);\n    }\n    else if(t1a1!=-1) {\n        std::replace(triangles[t1a1].adjacent_indices.begin(),triangles[t1a1].adjacent_indices.end(),ti1,ti2);\n        t1.adjacent_indices.erase(std::find(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),t1a1));\n        t2.adjacent_indices.push_back(t1a1);\n    }\n    else if(t2a1!=-1) {\n        std::replace(triangles[t2a1].adjacent_indices.begin(),triangles[t2a1].adjacent_indices.end(),ti2,ti1);\n        t2.adjacent_indices.erase(std::find(t2.adjacent_indices.begin(),t2.adjacent_indices.end(),t2a1));\n        t1.adjacent_indices.push_back(t2a1);\n    }\n    std::vector<std::pair<std::size_t,std::size_t>> outer_edges;\n    for(const auto& t : {ti1,ti2}) {\n        for(const auto& ta : triangles[t].adjacent_indices)\n            if(ta != ti1 && ta != ti2)\n                outer_edges.push_back(std::pair<std::size_t,std::size_t>(t,ta));\n    }\n    return outer_edges;\n}\n\ntemplate\n<\n    typename MultiPoint\n>\nstd::pair<std::vector<triangle<typename boost::range_value<MultiPoint>::type>>,std::vector<model::segment<typename boost::range_value<MultiPoint>::type>>> shull(const MultiPoint& input, bool skip_delaunay = false, double eps=0.0001)\n{\n    typedef typename boost::range_value<MultiPoint>::type Point;\n    typedef triangle<Point> Triangle;\n    std::vector<Point> points;\n    points.reserve(boost::size(input));\n    for(const auto& in : input)\n        points.push_back(in);\n    //Step 2\n    std::sort(points.begin()+1, points.end(), [&points](const Point& p1, const Point& p2) {\n       auto d1 = comparable_distance(points[0],p1);\n       auto d2 = comparable_distance(points[0],p2);\n       if(d1<d2)\n           return true;\n       else if(d2<d1)\n           return false;\n       if(get<0>(p1)<get<0>(p2) || (get<0>(p1)==get<0>(p2) && get<1>(p1)<get<1>(p2) ))\n           return true;\n       return false;});\n    for(auto it=points.end()-1;it!=points.begin();--it) //remove almost-duplicates\n        if(distance(*it,*(it-1))<=eps)\n            it = points.erase(it);\n    //Step 4\n    double min_circumcircle_diameter = circumcircle_diameter(points[0],points[1],points[2]);\n    std::size_t mcd_index = 2;\n    for(std::size_t i=3;i<points.size();++i) {\n        auto d = circumcircle_diameter(points[0],points[1],points[i]);\n        if(d<min_circumcircle_diameter) {\n            mcd_index=i;\n            min_circumcircle_diameter=d;\n        }\n        if(distance(points[0],points[i])>min_circumcircle_diameter)\n            break;\n    }\n    std::swap(points[2],points[mcd_index]);\n    Point C = circumcircle_center(points[0], points[1], points[2]);\n\n    //Step 5\n    typedef typename model::segment<Point> Segment;\n    typedef typename std::pair<Segment,std::size_t> indexed_segment;\n    if(!is_left_of(points[2], Segment{points[0],points[1]}))\n        std::swap(points[1],points[2]);\n    std::sort(points.begin()+2, points.end(), [&C](const Point& p1, const Point& p2) {\n       return comparable_distance(C,p1) < comparable_distance(C,p2);\n    });\n\n    std::vector<indexed_segment> outer_hull = {indexed_segment(Segment{points[0],points[1]},0),indexed_segment(Segment{points[1],points[2]},0),indexed_segment(Segment{points[2],points[0]},0)};\n    std::vector<Triangle> triangles = {Triangle{points[0],points[1],points[2],{}}};\n\n    auto outer_hull_pred = [](const indexed_segment& s1, const indexed_segment& s2) { return angle(s1.first)<angle(s2.first); };\n    //Step 6\n    std::sort(outer_hull.begin(), outer_hull.end(),outer_hull_pred);\n\n    //Step 7\n    for(std::size_t i = 3; i<points.size(); ++i) {\n        const Point& p = points[i];\n        std::size_t end_tri = triangles.size();\n        //The following could (probably) be done faster with binary searches (for large hulls)\n        auto begin = std::find_if(outer_hull.begin(), outer_hull.end(), [&p](const indexed_segment& s) {\n            return !is_left_of(p,s.first);\n        });\n        auto end = std::find_if(begin, outer_hull.end(), [&p](const indexed_segment& s) {\n            return is_left_of(p,s.first);\n        });\n        for(auto it = begin; it != end; ++it) {\n            triangles.push_back(Triangle{it->first.first, p, it->first.second,{it->second}});\n            triangles[it->second].adjacent_indices.push_back(triangles.size()-1);\n            if(it!=begin) {\n                triangles[triangles.size()-1].adjacent_indices.push_back(triangles.size()-2);\n                triangles[triangles.size()-2].adjacent_indices.push_back(triangles.size()-1);\n            }\n        }\n        indexed_segment new_outer1(Segment(begin->first.first,p),end_tri), new_outer2(Segment(p,(end-1)->first.second),triangles.size()-1);\n        if(begin==outer_hull.begin()) {\n            auto begin2 = std::find_if(end, outer_hull.end(), [&p](const indexed_segment& s) {\n                return !is_left_of(p,s.first);\n            });\n            \n            if(begin2 != outer_hull.end()) {\n                std::size_t end_tri2 = triangles.size();\n                for(auto it = begin2; it != outer_hull.end(); ++it) {\n                    triangles.push_back(Triangle{it->first.first, p, it->first.second,{it->second}});\n                    triangles[it->second].adjacent_indices.push_back(triangles.size()-1);\n                    if(it!=begin2) {\n                        triangles[triangles.size()-1].adjacent_indices.push_back(triangles.size()-2);\n                        triangles[triangles.size()-2].adjacent_indices.push_back(triangles.size()-1);\n                    }\n                }\n                triangles.back().adjacent_indices.push_back(end_tri);\n                triangles[end_tri].adjacent_indices.push_back(triangles.size()-1);\n                new_outer1 = indexed_segment(Segment(begin2->first.first,p), end_tri2);\n                outer_hull.erase(begin2, outer_hull.end());\n            }\n        }\n        outer_hull.erase(begin, end);\n        for(const auto& s : {new_outer1, new_outer2})\n            outer_hull.insert(std::upper_bound(outer_hull.begin(), outer_hull.end(), s, outer_hull_pred),s);\n    }\n\n    //Step 9\n    if(!skip_delaunay) {\n        std::stack<std::pair<std::size_t,std::size_t>> L;\n        for(std::size_t i=0; i < triangles.size(); ++i)\n            for(const auto& a : triangles[i].adjacent_indices)\n                if(i<a)\n                    L.emplace(i,a);\n        while(!L.empty()) {\n            auto edge = L.top();\n            L.pop();\n            auto new_edges = flip_if_not_locally_delaunay<Point>(triangles, edge.first, edge.second);\n            for(const auto& ne : new_edges)\n                L.push(ne);\n        }\n    }\n    std::vector<Segment> no_index_hull;\n    no_index_hull.reserve(outer_hull.size());\n    for(const auto& si : outer_hull)\n        no_index_hull.push_back(si.first);\n    return std::make_pair(triangles,no_index_hull);\n}\n", "meta": {"hexsha": "0e416cc3c7364eaedd79bfee68abac175e422b38", "size": 11391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shull.hpp", "max_stars_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_stars_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shull.hpp", "max_issues_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_issues_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shull.hpp", "max_forks_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_forks_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_forks_repo_licenses": ["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.0102739726, "max_line_length": 477, "alphanum_fraction": 0.6055657976, "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6527056278854774}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  int rows=5, cols=5;\nMatrixXf m(rows,cols);\nm << (Matrix3f() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished(),\n     MatrixXf::Zero(3,cols-3),\n     MatrixXf::Zero(rows-3,3),\n     MatrixXf::Identity(rows-3,cols-3);\ncout << m;\n\n  return 0;\n}\n", "meta": {"hexsha": "0e8c97e1c4ac3c228765d963691c29e2dac780ec", "size": 366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_commainit_02.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_Tutorial_commainit_02.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_Tutorial_commainit_02.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": 18.3, "max_line_length": 58, "alphanum_fraction": 0.6174863388, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6524618706609722}}
{"text": "/**\n * @file softmax_regression_test.cpp\n * @author Siddharth Agrawal\n *\n * Test the SoftmaxRegression class.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/softmax_regression/softmax_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::regression;\nusing namespace mlpack::distribution;\nusing namespace mlpack::optimization;\n\nBOOST_AUTO_TEST_SUITE(SoftmaxRegressionTest);\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionFunctionEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 50;\n  const size_t inputSize = 10;\n  const size_t numClasses = 5;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for(size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // Create a SoftmaxRegressionFunction. Regularization term ignored.\n  SoftmaxRegressionFunction srf(data, labels, numClasses, 0);\n\n  // Run a number of trials.\n  for(size_t i = 0; i < trials; i++)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(numClasses, inputSize);\n\n    double logLikelihood = 0;\n\n    // Compute error for each training example.\n    for(size_t j = 0; j < points; j++)\n    {\n      arma::mat hypothesis, probabilities;\n\n      hypothesis = arma::exp(parameters * data.col(j));\n      probabilities = hypothesis / arma::accu(hypothesis);\n\n      logLikelihood += log(probabilities(labels(j), 0));\n    }\n    logLikelihood /= points;\n\n    // Compare with the value returned by the function.\n    BOOST_REQUIRE_CLOSE(srf.Evaluate(parameters), -logLikelihood, 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionFunctionRegularizationEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 50;\n  const size_t inputSize = 10;\n  const size_t numClasses = 5;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for(size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // 3 objects for comparing regularization costs.\n  SoftmaxRegressionFunction srfNoReg(data, labels, numClasses, 0);\n  SoftmaxRegressionFunction srfSmallReg(data, labels, numClasses, 1);\n  SoftmaxRegressionFunction srfBigReg(data, labels, numClasses, 20);\n\n  // Run a number of trials.\n  for (size_t i = 0; i < trials; i++)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(numClasses, inputSize);\n\n    double wL2SquaredNorm;\n    wL2SquaredNorm = arma::accu(parameters % parameters);\n\n    // Calculate regularization terms.\n    const double smallRegTerm = 0.5 * wL2SquaredNorm;\n    const double bigRegTerm = 10 * wL2SquaredNorm;\n\n    BOOST_REQUIRE_CLOSE(srfNoReg.Evaluate(parameters) + smallRegTerm,\n        srfSmallReg.Evaluate(parameters), 1e-5);\n    BOOST_REQUIRE_CLOSE(srfNoReg.Evaluate(parameters) + bigRegTerm,\n        srfBigReg.Evaluate(parameters), 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionFunctionGradient)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 10;\n  const size_t numClasses = 5;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for(size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // 2 objects for 2 terms in the cost function. Each term contributes towards\n  // the gradient and thus need to be checked independently.\n  SoftmaxRegressionFunction srf1(data, labels, numClasses, 0);\n  SoftmaxRegressionFunction srf2(data, labels, numClasses, 20);\n\n  // Create a random set of parameters.\n  arma::mat parameters;\n  parameters.randu(numClasses, inputSize);\n\n  // Get gradients for the current parameters.\n  arma::mat gradient1, gradient2;\n  srf1.Gradient(parameters, gradient1);\n  srf2.Gradient(parameters, gradient2);\n\n  // Perturbation constant.\n  const double epsilon = 0.0001;\n  double costPlus1, costMinus1, numGradient1;\n  double costPlus2, costMinus2, numGradient2;\n\n  // For each parameter.\n  for (size_t i = 0; i < numClasses; i++)\n  {\n    for (size_t j = 0; j < inputSize; j++)\n    {\n      // Perturb parameter with a positive constant and get costs.\n      parameters(i, j) += epsilon;\n      costPlus1 = srf1.Evaluate(parameters);\n      costPlus2 = srf2.Evaluate(parameters);\n\n      // Perturb parameter with a negative constant and get costs.\n      parameters(i, j) -= 2 * epsilon;\n      costMinus1 = srf1.Evaluate(parameters);\n      costMinus2 = srf2.Evaluate(parameters);\n\n      // Compute numerical gradients using the costs calculated above.\n      numGradient1 = (costPlus1 - costMinus1) / (2 * epsilon);\n      numGradient2 = (costPlus2 - costMinus2) / (2 * epsilon);\n\n      // Restore the parameter value.\n      parameters(i, j) += epsilon;\n\n      // Compare numerical and backpropagation gradient values.\n      BOOST_REQUIRE_CLOSE(numGradient1, gradient1(i, j), 1e-2);\n      BOOST_REQUIRE_CLOSE(numGradient2, gradient2(i, j), 1e-2);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionTwoClasses)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 3;\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n\n  // Generate two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Train softmax regression object.\n  SoftmaxRegression<> sr(data, labels, numClasses, lambda);\n\n  // Compare training accuracy to 100.\n  const double acc = sr.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 100.0, 0.5);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) =  0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Compare test accuracy to 100.\n  const double testAcc = sr.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6);\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionFitIntercept)\n{\n  // Generate a two-Gaussian dataset,\n  // which can't be separated without adding the intercept term.\n  GaussianDistribution g1(arma::vec(\"1.0 1.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"9.0 9.0 9.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(3, 1000);\n  arma::Row<size_t> responses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Now train a logistic regression object on it.\n  SoftmaxRegression<> lr(data, responses, 2, 0.01, true);\n\n  // Ensure that the error is close to zero.\n  const double acc = lr.ComputeAccuracy(data, responses);\n  BOOST_REQUIRE_CLOSE(acc, 100.0, 2.0);\n\n  // Create a test set.\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Ensure that the error is close to zero.\n  const double testAcc = lr.ComputeAccuracy(data, responses);\n  BOOST_REQUIRE_CLOSE(testAcc, 100.0, 2.0);\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionMultipleClasses)\n{\n  const size_t points = 5000;\n  const size_t inputSize = 5;\n  const size_t numClasses = 5;\n  const double lambda = 0.5;\n\n  // Generate five-Gaussian dataset.\n  arma::mat identity = arma::eye<arma::mat>(5, 5);\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0 2.0 2.0\"), identity);\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0 2.0 2.0\"), identity);\n  GaussianDistribution g3(arma::vec(\"3.0 2.0 7.0 0.0 5.0\"), identity);\n  GaussianDistribution g4(arma::vec(\"4.0 1.0 1.0 2.0 7.0\"), identity);\n  GaussianDistribution g5(arma::vec(\"1.0 0.0 1.0 8.0 3.0\"), identity);\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Train softmax regression object.\n  SoftmaxRegression<> sr(data, labels, numClasses, lambda);\n\n  // Compare training accuracy to 100.\n  const double acc = sr.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 100.0, 2.0);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Compare test accuracy to 100.\n  const double testAcc = sr.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 100.0, 2.0);\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionTrainTest)\n{\n  // Make sure a SoftmaxRegression object trained with Train() operates the same\n  // as a SoftmaxRegression object trained in the constructor.\n  arma::mat dataset = arma::randu<arma::mat>(5, 1000);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 500; ++i)\n    labels[i] = size_t(0.0);\n  for (size_t i = 500; i < 1000; ++i)\n    labels[i] = size_t(1.0);\n\n\n  // This should be the same as the default parameters given by\n  // SoftmaxRegression.\n  SoftmaxRegressionFunction srf(dataset, labels, 2, 0.0001, false);\n  L_BFGS<SoftmaxRegressionFunction> lbfgs(srf);\n  SoftmaxRegression<> sr(lbfgs);\n\n  SoftmaxRegression<> sr2(dataset.n_rows, 2);\n  sr2.Parameters() = srf.GetInitialPoint(); // Start from the same place.\n  sr2.Train(dataset, labels, 2);\n\n  // Ensure that the parameters are the same.\n  BOOST_REQUIRE_EQUAL(sr.Parameters().n_rows, sr2.Parameters().n_rows);\n  BOOST_REQUIRE_EQUAL(sr.Parameters().n_cols, sr2.Parameters().n_cols);\n  for (size_t i = 0; i < sr.Parameters().n_elem; ++i)\n  {\n    if (std::abs(sr.Parameters()[i]) < 1e-4)\n      BOOST_REQUIRE_SMALL(sr2.Parameters()[i], 1e-4);\n    else\n      BOOST_REQUIRE_CLOSE(sr.Parameters()[i], sr2.Parameters()[i], 1e-4);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(SoftmaxRegressionOptimizerTrainTest)\n{\n  // The same as the previous test, just passing in an instantiated optimizer.\n  arma::mat dataset = arma::randu<arma::mat>(5, 1000);\n  arma::Row<size_t> labels(1000);\n  for (size_t i = 0; i < 500; ++i)\n    labels[i] = size_t(0.0);\n  for (size_t i = 500; i < 1000; ++i)\n    labels[i] = size_t(1.0);\n\n  SoftmaxRegressionFunction srf(dataset, labels, 2, 0.01, true);\n  L_BFGS<SoftmaxRegressionFunction> lbfgs(srf);\n  SoftmaxRegression<> sr(lbfgs);\n\n  SoftmaxRegression<> sr2(dataset.n_rows, 2, true);\n  L_BFGS<SoftmaxRegressionFunction> lbfgs2(srf);\n  sr2.Parameters() = srf.GetInitialPoint();\n  sr2.Train(lbfgs2);\n\n  // Ensure that the parameters are the same.\n  BOOST_REQUIRE_EQUAL(sr.Parameters().n_rows, sr2.Parameters().n_rows);\n  BOOST_REQUIRE_EQUAL(sr.Parameters().n_cols, sr2.Parameters().n_cols);\n  for (size_t i = 0; i < sr.Parameters().n_elem; ++i)\n  {\n    if (std::abs(sr.Parameters()[i]) < 1e-5)\n      BOOST_REQUIRE_SMALL(sr2.Parameters()[i], 1e-5);\n    else\n      BOOST_REQUIRE_CLOSE(sr.Parameters()[i], sr2.Parameters()[i], 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4fe8568eaf4173e9feaa39b30ef21a317f4e4821", "size": 12212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/softmax_regression_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack2", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/softmax_regression_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack2", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/softmax_regression_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack2", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.640776699, "max_line_length": 80, "alphanum_fraction": 0.6595152309, "num_tokens": 3741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6524551936592582}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// Modified Jonker-Volgenant Algorithm\n// DF Crouse. On implementing 2D rectangular assignment algorithms.\n// IEEE Transactions on Aerospace and Electronic Systems, 52(4):1679-1696, August 2016,\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Assign2D\n{\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ArrayXi = Eigen::ArrayXi;\n  static const index UNASSIGNED = -1;\n  bool process(Eigen::Ref<const Eigen::ArrayXXd> costMatrix,\n               Eigen::Ref<Eigen::ArrayXi>        result)\n  {\n    using namespace std;\n    using namespace Eigen;\n    double minCost = costMatrix.minCoeff();\n    if(minCost > 0) minCost = 0;\n    mCost = costMatrix - minCost;\n    if(mCost.cols() > mCost.rows()){\n      mCost.transposeInPlace();\n      mTransposed = true;\n    }\n    else mTransposed = false;\n\n    mRow2Col = ArrayXi::Constant(mCost.rows(), UNASSIGNED);\n    mCol2Row = ArrayXi::Constant(mCost.cols(), UNASSIGNED);\n    mV = ArrayXd::Zero(mCost.rows());\n    mU = ArrayXd::Zero(mCost.cols());\n    for (index c = 0; c < mCost.cols(); c++){\n      index sink = shortestPath(c);\n      if(sink == UNASSIGNED) return false;\n      index j = sink;\n      index h;\n      while(true){\n        index i = mPred(j);\n        mRow2Col(j) = i;\n        h = mCol2Row(i);\n        mCol2Row(i) = j;\n        j = h;\n        if(i == c) break;\n      }\n    }\n    result = mTransposed?mCol2Row:mRow2Col;\n    return true;\n  }\n\n  index shortestPath(index c){\n    using namespace std;\n    mPred = ArrayXi::Zero(mCost.rows());\n    ArrayXi scannedCols = ArrayXi::Zero(mCost.cols());\n    ArrayXi scannedRows = ArrayXi::Zero(mCost.rows());\n    vector<int> row2Scan(mCost.rows());\n    iota(row2Scan.begin(), row2Scan.end(), 0);\n    index nRows2Scan = mCost.rows();\n    index sink = UNASSIGNED;\n    double delta = 0;\n    index currentCol = c;\n    index currentRow, currentClosestRow, closestRow;\n    double minVal, reducedCost;\n    ArrayXd shortestPathCost = ArrayXd::Constant(mCost.rows(), infinity);\n    while(sink == UNASSIGNED){\n      scannedCols(currentCol) = 1;\n      minVal = infinity;\n      for(index r = 0; r < nRows2Scan; r++){\n        currentRow = row2Scan[r];\n        reducedCost = delta\n                    + mCost(currentRow, currentCol)\n                    - mU(currentCol) - mV(currentRow);\n        if(reducedCost < shortestPathCost(currentRow)){\n          mPred(currentRow) = currentCol;\n          shortestPathCost(currentRow) = reducedCost;\n        }\n        if(shortestPathCost(currentRow) < minVal){\n          minVal = shortestPathCost(currentRow);\n          currentClosestRow = r;\n        }\n      }\n      if(isinf(minVal)) return UNASSIGNED;\n      closestRow = row2Scan[currentClosestRow];\n      scannedRows(closestRow) = 1;\n      nRows2Scan--;\n      row2Scan.erase(row2Scan.begin() + currentClosestRow);\n      delta = shortestPathCost(closestRow);\n      if(mRow2Col(closestRow) == UNASSIGNED) sink = closestRow;\n      else currentCol = mRow2Col(closestRow);\n    }\n    mU(c) = mU(c) + delta;\n    for(index i = 0; i < mCost.cols(); i++){\n      if(i !=c && scannedCols(i) != 0){\n        mU(i) = mU(i) + delta - shortestPathCost(mCol2Row(i));\n      }\n    }\n\n    for(index i = 0; i < mCost.rows(); i++){\n      if(scannedRows(i) != 0){\n        mV(i) = mV(i) - delta + shortestPathCost(i);\n      }\n    }\n    return sink;\n}\nprivate:\n  ArrayXXd mCost;\n  ArrayXi  mRow2Col;\n  ArrayXi  mCol2Row;\n  ArrayXd  mU;\n  ArrayXd  mV;\n  ArrayXi mPred;\n  bool mTransposed{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "38188c954253d03b3828b650b0639c297c019115", "size": 4100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Assign2D.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/Assign2D.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/Assign2D.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": 30.3703703704, "max_line_length": 87, "alphanum_fraction": 0.636097561, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6522454745263344}}
{"text": "#include <mex.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include <string>\n\n\nusing namespace Eigen;\nusing namespace std;\n\ndouble amips_param;\ndouble c1_param;\ndouble c2_param;\ndouble d1_param;\n\n\nVector2d energy_derivative(int type, Vector2d S)\n{\n    \n    Vector2d es;\n    double J;\n    double l1;\n    double l2;\n    \n    switch(type)\n    {\n        case 0: //arap\n            es[0] = 2 * (S[0] - 1);\n            es[1] = 2 * (S[1] - 1);\n            break;\n            \n        case 1: // mips\n            es[0] = 1.0 / S[1] - S[1] / (S[0] * S[0]);\n            es[1] = 1.0 / S[0] - S[0] / (S[1] * S[1]);\n            //es[0] *= 100;\n            //es[1] *= 100;\n            break;\n            \n        case 2: // iso\n            es[0] = 2 * S[0] - 2.0 / (S[0] * S[0] * S[0]);\n            es[1] = 2 * S[1] - 2.0 / (S[1] * S[1] * S[1]);\n            break;\n            \n        case 3: // amips\n            es[0] = amips_param * exp(amips_param * (S[0] / S[1] + S[1] / S[0])) * (1.0 / S[1] - S[1] / (S[0] * S[0]));\n            es[1] = amips_param * exp(amips_param * (S[0] / S[1] + S[1] / S[0])) * (1.0 / S[0] - S[0] / (S[1] * S[1]));\n            break;\n            \n        case 4: // conf\n            es[0] = 2 * S[0] / (S[1] * S[1]);\n            es[1] = -2 * S[0] * S[0] / (S[1] * S[1] * S[1]);\n            break;\n            \n        case 5: // gmr\n\t\t\t\t\t\t//            J = S[0] * S[1];\n\t\t\t\t\t\t//            l1 = S[0] * S[0] + S[1] * S[1];\n\t\t\t\t\t\t//            l2 = S[0] * S[0] * S[1] * S[1];\n\t\t\t\t\t\t//            \n\t\t\t\t\t\t//            es[0] = c1_param * (-2.0 / 3.0 * pow(J, -5.0 / 3.0) * S[1] * l1 + pow(J, -2.0 / 3.0) * 2 * S[0]) \n\t\t\t\t\t\t//                    + c2_param * (-4.0 / 3.0 * pow(J, -7.0 / 3.0) * S[1] * l2 + pow(J, -4.0 / 3.0) * 2 * S[1] * S[1] * S[0]) \n\t\t\t\t\t\t//                    + d1_param * 2 * (J - 1) * S[1];\n\t\t\t\t\t\t//            \n\t\t\t\t\t\t//            es[1] = c1_param * (-2.0 / 3.0 * pow(J, -5.0 / 3.0) * S[0] * l1 + pow(J, -2.0 / 3.0) * 2 * S[1]) \n\t\t\t\t\t\t//                    + c2_param * (-4.0 / 3.0 * pow(J, -7.0 / 3.0) * S[0] * l2 + pow(J, -4.0 / 3.0) * 2 * S[0] * S[0] * S[1]) \n\t\t\t\t\t\t//                    + d1_param * 2 * (J - 1) * S[0];\n\n\t\t\t\t\t\tes[0] = c1_param * (1.0 / S[1] - S[1] / (S[0] * S[0])) - d1_param *2.*S[1]*(1.0 - S[0]*S[1]);\n\t\t\t\t\t\tes[1] = c1_param * (1.0 / S[0] - S[0] / (S[1] * S[1])) - d1_param *2.*S[0]*(1.0 - S[0]*S[1]);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\t\n        case 6: // olg\n            \n            if(S[0] > 1.0 / S[1])\n            {\n                es[0] = 1;\n                es[1] = 0;\n            }else{\n                es[0] = 0;\n                es[1] = -1.0 / (S[1] * S[1]);\n            }\n            \n            break;\n    }\n    \n    return es;\n\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    mxArray *output_mex, *J_value_mex, *JT_value_mex, *wu_mex, *bu_mex;\n    const int *dims;\n    double *tri_num, *X_g_inv, *tri_areas, *obj_tri, *q_target, *type, *amips_s, *F_dot, *ver_num, *c1_g, *c2_g, *d1_g, *J_index, *JT_index, *JTJ_info, *x2u;\n    double *output, *J_value, *JT_value, *wu, *bu;\n    \n    tri_num = mxGetPr(prhs[0]);\n    X_g_inv = mxGetPr(prhs[1]);\n    tri_areas = mxGetPr(prhs[2]);\n    obj_tri = mxGetPr(prhs[3]);\n    q_target = mxGetPr(prhs[4]);\n    type = mxGetPr(prhs[5]);\n    amips_s = mxGetPr(prhs[6]);\n    F_dot = mxGetPr(prhs[7]);\n    ver_num = mxGetPr(prhs[8]);\n    c1_g = mxGetPr(prhs[9]);\n    c2_g = mxGetPr(prhs[10]);\n    d1_g = mxGetPr(prhs[11]);\n    J_index = mxGetPr(prhs[12]);\n    JT_index = mxGetPr(prhs[13]);\n    JTJ_info = mxGetPr(prhs[14]);\n    x2u = mxGetPr(prhs[15]);\n    \n    int tri_n = tri_num[0];\n    int ver_n = ver_num[0];\n    int energy_type = type[0];\n    amips_param = amips_s[0];\n    c1_param = c1_g[0];\n    c2_param = c2_g[0];\n    d1_param = d1_g[0];\n    int J_rn = JTJ_info[0];\n    int J_cn = JTJ_info[1];\n    int JT_rn = JTJ_info[2];\n    int JT_cn = JTJ_info[3];\n    \n    output_mex = plhs[0] = mxCreateDoubleMatrix(2 * ver_n, 1, mxREAL);\n    J_value_mex = plhs[1] = mxCreateDoubleMatrix(J_rn * J_cn, 1, mxREAL);\n    JT_value_mex = plhs[2] = mxCreateDoubleMatrix(JT_rn * JT_cn, 1, mxREAL);\n    wu_mex = plhs[3] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n    bu_mex = plhs[4] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n    \n    output = mxGetPr(output_mex);\n    J_value = mxGetPr(J_value_mex);\n    JT_value = mxGetPr(JT_value_mex);\n    wu = mxGetPr(wu_mex);\n    bu = mxGetPr(bu_mex);\n    \n    memset(J_value, 0, J_rn * J_cn * sizeof(double));\n    memset(JT_value, 0, JT_rn * JT_cn * sizeof(double));\n    memset(output, 0, 2 * ver_n * sizeof(double));\n\n    vector<int> offset;\n    \n    offset.resize(2 * ver_n, 0);\n    \n    int tri[3];\n    double tri_area;\n    \n    Matrix2d B, X_f, A, F_d;\n    Vector2d S, u0, u1, v0, v1;\n    Matrix2d U, V;\n    \n    Vector2d es;\n    Vector2d cs;\n    \n    double es1, es2;\n    double d1, d2;\n    double dphi;\n  \n \n    for(int i = 0; i < tri_n; i++)\n    {\n        tri[0] = obj_tri[i] - 1; \n        tri[1] = obj_tri[i + tri_n] - 1; \n        tri[2] = obj_tri[i + 2 * tri_n] - 1; \n        tri_area = tri_areas[i];\n        \n        B(0, 0) = X_g_inv[i];\n        B(0, 1) = X_g_inv[i + tri_n * 2];\n        B(1, 0) = X_g_inv[i + tri_n];\n        B(1, 1) = X_g_inv[i + tri_n * 3];\n        \n        X_f(0, 0) = q_target[2 * tri[1]] - q_target[2 * tri[0]];\n        X_f(1, 0) = q_target[2 * tri[1] + 1] - q_target[2 * tri[0] + 1];  \n        X_f(0, 1) = q_target[2 * tri[2]] - q_target[2 * tri[0]];\n        X_f(1, 1) = q_target[2 * tri[2] + 1] - q_target[2 * tri[0] + 1];\n        \n        A = X_f * B;\n        \n        JacobiSVD<Matrix2d> svd(A, ComputeFullU | ComputeFullV);\n        \n        S = svd.singularValues();\n        U = svd.matrixU();\n        V = svd.matrixV();\n        \n        if(A.determinant() <= 0)\n        {\n            //mexPrintf(\"inverted\\n\");\n        }\n        \n        bu[i] = S[0] * S[1];\n        \n        es = energy_derivative(energy_type, S);\n        \n        cs = S;\n        \n        es1 = es[0];\n        es2 = es[1];\n        \n        ////////////////////////////////////////////\n        \n        wu[i] = 0;\n        \n        u0 = U.col(0);\n        u1 = U.col(1);\n        v0 = V.col(0);\n        v1 = V.col(1);\n        \n        for(int j = 0; j < 6; j++)\n        {\n            \n            F_d(0, 0) = F_dot[i + j * tri_n];\n            F_d(0, 1) = F_dot[i + j * tri_n + 6 * 2 * tri_n];\n            F_d(1, 0) = F_dot[i + j * tri_n + 6 * tri_n];\n            F_d(1, 1) = F_dot[i + j * tri_n + 6 * 3 * tri_n];\n            \n            d1 = u0.transpose() * F_d * v0;\n            d2 = u1.transpose() * F_d * v1;\n            \n            dphi = d1 * es1 + d2 * es2;\n            \n            int cache_1 = 2 * tri[j / 2] + (j % 2);\n            int cache_2 = x2u[cache_1];\n            \n            output[cache_1] += tri_area * dphi;\n            \n            if(cache_2 > 0)\n            {\n                int idx = cache_2 - 1;\n                \n                double value = d1 * cs[1] + d2 * cs[0];\n                \n                J_value[idx * J_cn + offset[cache_1]] = value;\n                \n                offset[cache_1]++;\n                \n                JT_value[i * JT_cn + j] = value;\n                \n                wu[i] += value * value;\n            }\n        }  \n    }\n    \n    return;\n    \n}", "meta": {"hexsha": "c4b9a3c34d5162e5e31b9d293e843c4af330adf2", "size": 7310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 29.24, "max_line_length": 157, "alphanum_fraction": 0.412995896, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6522454688072575}}
{"text": "#include \"Kinematics.h\"\r\n#include <Eigen/SVD>\r\n\r\nusing namespace MotionControl;\r\n\r\nMatrix<double,3,3> Kinematics::Rodrigues(Matrix<double,3,1> a, double q)\r\n{\r\n\treturn AngleAxisd(q,a).toRotationMatrix();\r\n}\r\n\r\nMatrix<double,3,1> Kinematics::rot2omega(Matrix<double,3,3> R)\r\n{\r\n\tdouble alpha = (R(0,0)+R(1,1)+R(2,2)-1)/2;\r\n\tdouble th;\r\n\tMatrix<double,3,1> vector_R(Matrix<double,3,1>::Zero());\r\n\r\n\tif(fabs(alpha-1) < eps)\r\n\t\treturn Matrix<double,3,1>::Zero();\r\n\r\n\tth = std::cos(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/std::sin(th)*vector_R;\r\n}\r\n\r\nEigen::Matrix<double,3,3> Kinematics::computeMatrixFromAngles(double roll, double pitch, double yaw)\r\n{\r\n\tEigen::Matrix<double,3,3> R;\r\n\r\n\tR(0,0) = std::cos(pitch) * std::cos(yaw) - std::sin(roll) * std::sin(pitch) * std::sin(yaw);\r\n\tR(0,1) = -std::cos(roll) * std::sin(yaw);\r\n\tR(0,2) = std::sin(roll) * std::cos(yaw) + std::sin(roll) * std::cos(pitch) * std::sin(yaw);\r\n\tR(1,0) = std::cos(pitch) * std::sin(yaw) + std::sin(roll) * std::sin(pitch) * std::cos(yaw);\r\n\tR(1,1) = std::cos(roll) * std::cos(yaw);\r\n\tR(1,2) = std::sin(pitch) * std::sin(yaw) - std::sin(roll) * std::cos(pitch) * std::cos(yaw);\r\n\tR(2,0) = -std::cos(roll) * std::sin(pitch);\r\n\tR(2,1) = std::sin(roll);\r\n\tR(2,2) = std::cos(roll) * std::cos(pitch);\r\n\r\n\treturn R;\r\n}\r\n\r\nvoid Kinematics::computeAnglesFromMatrix(Eigen::Matrix<double,3,3> R, double &roll, double &pitch, double &yaw)\r\n{\r\n\tfloat threshold = 0.001;\r\n\tif(abs(R(2,1) - 1.0) < threshold){ // R(2,1) = std::sin(x) = 1\u306e\u6642\r\n\t\troll \t= M_PI / 2;\r\n\t\tpitch = 0;\r\n\t\tyaw \t= std::atan2(R(1,0), R(0,0));\r\n\t}else if(abs(R(2,1) + 1.0) < threshold){ // R(2,1) = std::sin(x) = -1\u306e\u6642\r\n\t\troll\t= - M_PI / 2;\r\n\t\tpitch = 0;\r\n\t\tyaw\t\t= std::atan2(R(1,0), R(0,0));\r\n\t}else{\r\n\t\troll\t= std::sin(R(2,1));\r\n\t\tpitch\t= std::atan2(-R(2,0), R(2,2));\r\n\t\tyaw\t\t= std::atan2(-R(0,1), R(1,1));\r\n\t}\r\n}\r\n\r\nvector<int> Kinematics::FindRoute(int to)\r\n{\r\n\tvector<int> idx;\r\n\tint link_num = to;\r\n\r\n\twhile(link_num != 0)\r\n\t{\r\n\t\tidx.push_back(link_num);\r\n\t\tlink_num = ulink[link_num].parent;\r\n\t}\r\n\treverse(idx.begin(), idx.end());\r\n\treturn idx;\r\n}\r\n\r\nMatrix<double,6,1> Kinematics::calcVWerr(Link Cref, Link Cnow)\r\n{\r\n\tMatrix<double,3,1> perr = Cref.p - Cnow.p;\r\n\tMatrix<double,3,3> Rerr = Cref.R - Cnow.R;\r\n\tMatrix<double,3,1> werr = Cnow.R * rot2omega(Rerr);\r\n\tMatrix<double,6,1> err;\r\n\r\n\terr << perr,werr;\r\n\treturn err;\r\n}\r\n\r\nvoid Kinematics::calcForwardKinematics(int rootlink)\r\n{\r\n\tif(rootlink == -1) return;\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\n// \u9006\u904b\u52d5\u5b66\r\nbool Kinematics::calcInverseKinematics(int to, Link target)\r\n{\r\n\tMatrix<double,6,6> J;\r\n\tMatrix<double,6,1> dq, err;\r\n\r\n\tColPivHouseholderQR<MatrixXd> QR; //QR\u5206\u89e3?\r\n\tconst double lambda = 0.5;\r\n\tconst int iteration = 100;\r\n\r\n\tcalcForwardKinematics(CC);\r\n\tvector<int> idx = FindRoute(to);\r\n\r\n\tfor(int n=0;n<iteration;n++){\r\n\t\tJ = calcJacobian(ulink, idx);\r\n\t\terr = calcVWerr(target, ulink[to]);\r\n\t\tif(err.norm() < eps) return true;\r\n\t\tdq = lambda * (J.inverse() * err);\r\n\t\tfor(size_t nn=0;nn<idx.size();nn++){\r\n\t\t\tint j = idx[nn];\r\n\t\t\tulink[j].q += dq(nn);\r\n\t\t}\r\n\t\tcalcForwardKinematics(CC);\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid Kinematics::MoveJoints( vector<int> idx, MatrixXd dq )\r\n{\r\n\tfor(int n=0; n<idx.size(); n++)\r\n\t{\r\n\t\tint j = idx[n];\r\n\t\tulink[j].q += dq(n);\r\n\t}\r\n}\r\n\r\nbool Kinematics::calcLMInverseKinematics(int to, Link target)\r\n{\r\n\tMatrixXd J, Jh, dq;\r\n\tvector<int> idx = FindRoute(to);\r\n\tdouble wn_pos = 1/0.3;\r\n\tdouble wn_ang = 1/(2*pi);\r\n\tdouble lambda, Ek, Ek2;\r\n\tMatrix< double, 6,1 > we, err, gerr;\r\n\twe << wn_pos, wn_pos, wn_pos, wn_ang, wn_ang, wn_ang;\r\n\tMatrix< double, 6,6 >We = we.array().matrix().asDiagonal();\r\n\tMatrixXd Wn = MatrixXd::Identity(idx.size(),idx.size());\r\n\r\n\tcalcForwardKinematics(CC);\r\n\terr = calcVWerr( target, ulink[to]);\r\n\tEk = err.transpose() * We * err;\r\n\r\n\tfor(int i = 0; i < 10; i++)\r\n\t{\r\n\r\n\t\tJ = calcJacobian( ulink, idx );\r\n\t\tlambda = Ek + 0.002;\r\n\t\tJh   = J.transpose() * We * J + Wn * lambda; //Hk + wn\r\n\t\tgerr = J.transpose() * We * err; // gk\r\n\r\n\t\tdq = Jh.inverse() * gerr; // new qk\r\n\t\tMoveJoints(idx, dq);\r\n\r\n\t\tEk2 = gerr.transpose() * We * gerr;\r\n\r\n\t\tif(Ek2 < 1E-12)\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if( Ek2 < Ek ) Ek = Ek2;\r\n\t\telse\r\n\t\t{\r\n\t\t\tMoveJoints(idx, -dq);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n", "meta": {"hexsha": "26a95fe56b0d11e26a9199a0a4b39e5f2ea365ff", "size": 4597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sample/SERIAL/Kinematics.cpp", "max_stars_repo_name": "Akira794/biped-kinematics", "max_stars_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_stars_repo_licenses": ["MIT"], "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/sample/SERIAL/Kinematics.cpp", "max_issues_repo_name": "Akira794/biped-kinematics", "max_issues_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-03-09T00:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T06:21:30.000Z", "max_forks_repo_path": "src/sample/SERIAL/Kinematics.cpp", "max_forks_repo_name": "Akira794/biped-kinematics", "max_forks_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_forks_repo_licenses": ["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.1193181818, "max_line_length": 112, "alphanum_fraction": 0.5975636285, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6522291984113898}}
{"text": "#include <Eigen/Dense>\r\n#include <iostream>\r\n#include <set>\r\n#include <time.h>\r\n#include <fstream>\r\n#include <vector>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n// N * E = B * T\r\n#define N 128*150\t// number of training data samples\r\n#define D 784\t// number of features\r\n#define T 150\t// total number of iterations per epoch\r\n#define B_size 128\t// size of mini-batch\r\n#define ALPHA 128\t// 2^7\r\n#define epoch 1\r\n#define SCALING_FACTOR 8192\r\n\r\ntypedef Matrix<unsigned long long int, Dynamic, Dynamic> MATRIX;\r\ntypedef Matrix<double, Dynamic, Dynamic> MATRIXd;\r\ntypedef Matrix<unsigned long long int, Dynamic, 1, ColMajor> ColVectorXi64;\r\ntypedef Matrix<double, Dynamic, 1, ColMajor> ColVectorXd;\r\ntypedef Matrix<double, 1, Dynamic, RowMajor> RowVectorXd;\r\ntypedef Matrix<unsigned long long int, 1, Dynamic, RowMajor> RowVectorXi64;\r\n\r\n\r\n// Simulates dditive shares created by the clients and distributed to the two servers.\r\nvoid genDataShares(MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1);\r\n\r\n// Initialize W0 and W1 to be random\r\nvoid initializeW(MATRIX& W0, MATRIX& W1);\r\n\r\n// Simulates generation of U, V, Z multiplication triplets\r\nvoid genUVZmultTriplets(MATRIX& U0, MATRIX& U1, MATRIX& V0, MATRIX& V1, MATRIX& Z0, MATRIX& Z1);\r\n\r\n// Simulates generation of V', Z' multiplication triplets\r\nvoid genVZprimeMultTriplets(MATRIX& UB0, MATRIX& UB1, MATRIX& Vp0, MATRIX& Vp1, MATRIX& Zp0, MATRIX& Zp1);\r\n\r\n// Returns set of random indices corresponding to training data for current minibatch(iteration)\r\nset<int> createMiniBatch(set<int>& usedIndices);\r\n\r\n// Reconstructs M, by adding MO and M1\r\nvoid reconstruct(MATRIX M0, MATRIX M1, MATRIX& M);\r\n\r\nvoid maskMatrix(MATRIX Data, MATRIX Mask, MATRIX& Final);\r\n\r\nvoid computeDifference(MATRIX& Dif, MATRIX Y_, MATRIX Y);\r\n\r\nint reverse_int(int i);\r\n\r\nvoid read_MNIST_data(bool train, vector<vector<unsigned long long int>>& vec, int& number_of_images, int& number_of_features);\r\n\r\nvoid read_MNIST_labels(bool train, vector<unsigned long long int>& vec);\r\n\r\nvoid read_MNIST_data_test(bool train, vector<vector<double>>& vec, int& number_of_images, int& number_of_features);\r\n\r\nvoid read_MNIST_labels_test(bool train, vector<double>& vec);\r\n\r\nvoid secretShareData(MATRIX& X, MATRIX& Y, MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1);\r\n\r\n\r\nint main() {\r\n\r\n\tcout << unsigned long int(-28145) % 4294967296 << endl;\r\n\t\r\n\t// READ TRAINING DATA\r\n\tvector<vector<unsigned long long int>> training_data;\r\n\tint param_n= N; int param_d= D;\r\n\tread_MNIST_data(true, training_data, param_n, param_d);\r\n\tMATRIX X(param_n, param_d);\r\n\tfor(int i = 0; i < training_data.size(); i++){\r\n        X.row(i) << Map<RowVectorXi64>(training_data[i].data(), training_data[i].size());\r\n    }\r\n\tX *= SCALING_FACTOR;\r\n\tX /= 255;\r\n\t//cout << X << endl;\r\n\t//cout << X.rows() << \" \" << X.cols() << endl;\r\n\t/*for (int i = 0 ; i < 784 ; ++i) {\r\n\t\tcout << training_data.at(0).at(i) << \" \";\r\n\t}\r\n\tcout << endl<<  X.row(0) << endl;*/\r\n\r\n\t// READ TRAINING LABEL\r\n\tvector<unsigned long long int> training_labels;\r\n\tread_MNIST_labels(true, training_labels);\r\n\tMATRIX Y(N, 1);\r\n\t//for (int i = 0; i < training_labels.size(); ++i) {\r\n\t//\tY(i) = training_labels.at(i);\r\n\t//}\r\n\tY << Map<ColVectorXi64>(training_labels.data(), training_labels.size());\r\n\tY *= SCALING_FACTOR;\r\n\tY /= 10;\r\n\r\n\tcout << sizeof(unsigned long long int) << endl;\r\n\tcout << sizeof(uint64_t) << endl;\r\n\r\n\t// READ TESTING DATA\r\n\tvector<vector<double> > testing_data;\r\n\tint n_;\r\n\t//param_n= N; param_d= D;\r\n\tread_MNIST_data_test(false, testing_data, n_, param_d);\r\n\tMATRIXd Xt(n_, param_d);\r\n\tfor(int i = 0; i < testing_data.size(); i++){\r\n        Xt.row(i) << Map<RowVectorXd>(testing_data[i].data(), testing_data[i].size());\r\n    }\r\n\t//Xt *= SCALING_FACTOR;\t\t\r\n\tXt /= 255;\r\n\r\n\t// READING TESTING LABEL\r\n\tvector<double> testing_labels;\r\n\tread_MNIST_labels_test(false, testing_labels);\r\n\tMATRIXd Yt(n_, 1);\r\n\t//for (int i = 0; i < training_labels.size(); ++i) {\r\n\t//\tY(i) = training_labels.at(i);\r\n\t//}\r\n\tYt << Map<ColVectorXd>(testing_labels.data(), testing_labels.size());\r\n\t//Yt *= SCALING_FACTOR;\t\t\r\n\t//Yt /= 10;\r\n\r\n\r\n\t/*for (long int n : training_labels) {\r\n\t\tcout << n << endl;\r\n\t}\r\n\tcout << training_labels.size() << endl;*/\r\n\t//cout << Yt << endl;\r\n\t//cout << Y.rows() << \" \" << Y.cols() << endl;\r\n\r\n\t//print out numbers\r\n\t/*int c = 0;\r\n\tfor (int i = 0; i < 784; ++i) {\r\n\t\tif (c % 28 == 0) {\r\n\t\t\tcout << endl;\r\n\t\t}\r\n\t\tcout << X(2, i) << \" \";\r\n\t\t++c;\r\n\t}\r\n\tcout << training_labels.at(2) << endl;*/\r\n\t//cout << Xt.row(0) << endl;\r\n\r\n\r\n\r\n\t/*START OF PROTOCOL*/\r\n\r\n\t// shares of training data\r\n\tclock_t start = clock();\r\n\tMATRIX X0(N, D);\tMATRIX X1(N, D);\r\n\tMATRIX Y0(N, 1);\tMATRIX Y1(N, 1);\r\n\t//genDataShares(X0, X1, Y0, Y1);\r\n\tsecretShareData(X, Y, X0, X1, Y0, Y1);\r\n\t\r\n\r\n\t// tests:\r\n\t/*cout << \"X0 MATRIX:\\n\" << X0 << endl;\r\n\tcout << \"X1 MATRIX:\\n\" << X1 << endl;\r\n\tcout << \"<X>:\\n\" << X0 + X1 << endl;*/\r\n\t/*cout << \"Y0 MATRIX:\\n\" << Y0 << endl;\r\n\tcout << \"Y1 MATRIX:\\n\" << Y1 << endl;\r\n\tcout << \"<Y>:\\n\" << Y0 + Y1 << endl;*/\r\n\r\n\t// coefficient vertor w\r\n\tMATRIX W0(D, 1);\tMATRIX W1(D, 1);\r\n\tinitializeW(W0, W1);\r\n\r\n\t// tests:\r\n\t/*cout << \"W0:\\n\" << W0 << endl;\t\r\n\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\r\n\t// generate shared U, V, Z multiplication triplets\r\n\tMATRIX U0(N, D);\tMATRIX U1(N, D);\r\n\tMATRIX V0(D, T);\tMATRIX V1(D, T);\r\n\tMATRIX Z0(N, T);\tMATRIX Z1(N, T);\r\n\tgenUVZmultTriplets(U0, U1, V0, V1, Z0, Z1);\r\n\r\n\t// tests:\r\n\t/*cout << \"MATRIX U0: \\n\" << U0 << endl;\r\n\tcout << \"MATRIX U1: \\n\" << U1 << endl;\r\n\tcout << \"MATRIX V0: \\n\" << V0 << endl;\r\n\tcout << \"MATRIX V1: \\n\" << V1 << endl;\r\n\tcout << \"MATRIX Z0: \\n \" << Z0 << endl;\r\n\tcout << \"MATRIX Z1: \\n \" << Z1 << endl;*/\r\n\r\n\t\r\n\t// * STEP 1: each party runs Ei = Xi - Ui masking\r\n\tMATRIX E0(N, D);\tMATRIX E1(N, D);\tMATRIX E(N, D);\r\n\tmaskMatrix(X0, U0, E0);\r\n\tmaskMatrix(X1, U1, E1);\r\n\treconstruct(E0, E1, E);\t\t// |?| how to code how each party does this independently\r\n\r\n\t// tests:\r\n\t/*cout << \"MATRIX E0:\\n\" << E0 << endl;\r\n\tcout << \"MATRIX E1:\\n\" << E1 << endl;\r\n\tcout << \"MATRIX E: \\n\" << E << endl;*/\r\n\r\n\r\n\t// * STEP 2: start of each iteration\r\n\tset<int> usedIndices;\r\n\tfor (int j = 0; j < T; ++j) {\r\n\r\n\t\t//cout << \"Iteration \" << j+1 << \"...\" << endl;\r\n\r\n\t\t// * STEP 3: select minibatch\r\n\t\tset<int> minibatch = createMiniBatch(usedIndices); // select minibatch indices\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"minibatch:\" << endl;\r\n\t\tfor (int n : minibatch) {\r\n\t\t\tcout << n << \" \";\r\n\t\t}\r\n\t\tcout << endl;*/\r\n\r\n\t\t// submatrices size B\r\n\t\tMATRIX EB(B_size, D);\r\n\t\tMATRIX UB0(B_size, D);\tMATRIX UB1(B_size, D);\r\n\t\tMATRIX XB0(B_size, D);\tMATRIX XB1(B_size, D);\r\n\t\tMATRIX YB0(B_size, 1);\tMATRIX YB1(B_size, 1);\r\n\t\tMATRIX ZB0(B_size, T);\tMATRIX ZB1(B_size, T);\r\n\r\n\t\tint r = 0;\tint k = 0;\r\n\t\tfor (int n : minibatch) {\r\n\t\t\tk = n - 1;\r\n\t\t\tEB.row(r) = E.row(k);\r\n\t\t\tUB0.row(r) = U0.row(k);\r\n\t\t\tUB1.row(r) = U1.row(k);\r\n\t\t\tXB0.row(r) = X0.row(k);\r\n\t\t\tXB1.row(r) = X1.row(k);\r\n\t\t\tYB0.row(r) = Y0.row(k);\r\n\t\t\tYB1.row(r) = Y1.row(k);\r\n\t\t\tZB0.row(r) = Z0.row(k);\r\n\t\t\tZB1.row(r) = Z1.row(k);\r\n\t\t\tr++;\r\n\t\t}\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"MATRIX EB:\\n\" << EB << endl;\r\n\t\tcout << \"MATRIX UB0:\\n\" << UB0 << endl;\r\n\t\tcout << \"MATRIX UB1:\\n\" << UB1 << endl;\r\n\t\tcout << \"MATRIX XB0:\\n\" << XB0 << endl;\r\n\t\tcout << \"MATRIX XB1:\\n\" << XB1 << endl;\r\n\t\tcout << \"MATRIX YB0:\\n\" << YB0 << endl;\r\n\t\tcout << \"MATRIX YB1:\\n\" << YB1 << endl;\r\n\t\tcout << \"MATRIX ZB0:\\n\" << ZB0 << endl;\r\n\t\tcout << \"MATRIX ZB1:\\n\" << ZB1 << endl;*/\r\n\r\n\r\n\t\t// generate V' and Zp multiplication triplets based on minibatch indices\r\n\t\tMATRIX Vp0(B_size, T);\tMATRIX Vp1(B_size, T);\r\n\t\tMATRIX Zp0(D, T);\t\tMATRIX Zp1(D, T);\r\n\t\tgenVZprimeMultTriplets(UB0, UB1, Vp0, Vp1, Zp0, Zp1);\r\n\r\n\t\t// tests:\r\n\t/*\tcout << \"matrix Vp0: \\n\" << Vp0 << endl;\r\n\t\tcout << \"matrix Vp1: \\n\" << Vp1 << endl;\r\n\t\tcout << \"matrix Zp0: \\n\" << Zp0 << endl;\r\n\t\tcout << \"matrix Zp1: \\n\" << Zp1 << endl;*/\r\n\r\n\r\n\t\t//// * STEP 4: each party computes Fji = wi - V[j]i\tjth iteration\r\n\t\tMATRIX F0(D, 1);\tMATRIX F1(D, 1);\tMATRIX F(D, 1);\r\n\t\tMATRIX V0j = V0.col(j);\t\r\n\t\tMATRIX V1j = V1.col(j);\r\n\t\tmaskMatrix(W0, V0j, F0);\r\n\t\tmaskMatrix(W1, V1j, F1);\r\n\t\treconstruct(F0, F1, F);\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"MATRIX V0j: \\n\" << V0j << endl;\r\n\t\tcout << \"MATRIX F0:\\n\" << F0 << endl;\r\n\t\tcout << \"MATRIX V1j: \\n\" << V1j << endl;\r\n\t\tcout << \"MATRIX F1:\\n\" << F1 << endl;\r\n\t\tcout << \"MATRIX F:\\n\" << F << endl;*/\r\n\r\n\r\n\t\t// * STEP 5: calculate predicted output\r\n\t\tMATRIX Ypred_0 = -0 * (EB * F) + (XB0 * F) + (EB * W0) + ZB0.col(j);\t// replace with j\r\n\t\tMATRIX Ypred_1 = -1 * (EB * F) + (XB1 * F) + (EB * W1) + ZB1.col(j);\t// replace with j\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"EB\\n\" << EB << endl;\r\n\t\tcout << \"XB0\\n\" << XB0<< endl;\r\n\t\tcout << \"XB1\\n\" << XB1<< endl;\r\n\t\tcout << \"ZB0.col(0)\\n\" << ZB0.col(0) << endl;\r\n\t\tcout << \"ZB1.col(0)\\n\" << ZB1.col(0) << endl;\r\n\t\tcout << \"Ypred_0:\\n\" << Ypred_0 << endl;\r\n\t\tcout << \"Ypred_1:\\n\" << Ypred_1 << endl;*/\r\n\r\n\r\n\t\t// * STEP 6: \r\n\t\tMATRIX D0; MATRIX D1;\r\n\t\tcomputeDifference(D0, Ypred_0, YB0);\r\n\t\tcomputeDifference(D1, Ypred_1, YB1);\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"Ypred_0:\\n\" << Ypred_0 << endl;\r\n\t\tcout << \"YB0 \\n\" << YB0 << endl;\r\n\t\tcout << \"D0:\\n\" <<D0 << endl;\r\n\t\tcout << \"Ypred_1:\\n\" << Ypred_1 << endl;\r\n\t\tcout << \"YB1 \\n\" << YB1 << endl;\r\n\t\tcout << \"D1:\\n\" <<D1 << endl;*/\r\n\r\n\r\n\t\t// * STEP 7: mask D0, and D1\r\n\t\tMATRIX Fp0;\tMATRIX Fp1; MATRIX Fp;\r\n\t\tMATRIX Vp0j = Vp0.col(j);\r\n\t\tMATRIX Vp1j = Vp1.col(j);\r\n\t\tmaskMatrix(D0, Vp0j, Fp0);\r\n\t\tmaskMatrix(D1, Vp1j, Fp1);\r\n\t\treconstruct(Fp0, Fp1, Fp);\r\n\t\t\r\n\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"MATRIX Fp0: \\n\" << Fp0 << endl;\r\n\t\tcout << \"MATRIX Fp1: \\n\" << Fp1 << endl;\r\n\t\tcout << \"MATRIX Fp: \\n\" << Fp << endl;*/\r\n\r\n\r\n\t\t// * STEP 8: compute shares of delta\r\n\t\tMATRIX delta0 = -0 * (EB.transpose() * Fp) + (XB0.transpose() * Fp) + (EB.transpose() * D0) + Zp0.col(j);\r\n\t\tMATRIX delta1 = -1 * (EB.transpose() * Fp) + (XB1.transpose() * Fp) + (EB.transpose() * D1) + Zp1.col(j);\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"Before truncation:\" << endl;\r\n\t\tcout << \"delta0:\\n\" << delta0 << endl;\r\n\t\tcout << \"delta1:\\n\" << delta1 << endl;*/\r\n\r\n\t\t// *STEP 9: truncation\r\n\t\tint l = 64;\tint x = 32;\tint d = 13;\r\n\r\n\t\tfor (int i = 0; i < D; ++i) {\r\n\t\t\tdelta0(i) = delta0(i) >> d;\r\n\t\t\tdelta1(i) = delta1(i) >> d;\r\n\t\t}\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"After truncation:\" << endl;\r\n\t\tcout << \"delta0:\\n\" << delta0 << endl;\r\n\t\tcout << \"delta1:\\n\" << delta1 << endl;*/\r\n\r\n\t\t// *STEP 10: \r\n\t\t/*cout << \"W0:\\n\" << W0 << endl;\r\n\t\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\t\t//cout << (B_size * ALPHA) << endl;\r\n\r\n\t\tW0 = W0 - (delta0 / (B_size * ALPHA));\r\n\t\tW1 = W1 - (delta1 / (B_size * ALPHA));\r\n\r\n\t\t/*cout << \"W0:\\n\" << W0 << endl;\r\n\t\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\r\n\t}\r\n\r\n\t// *STEP 11: Reconstruct W\r\n\tMATRIX W(D,1);\r\n    reconstruct(W0, W1, W);\r\n\r\n\t// tests:\r\n\t//cout << \"FINAL W:\\n\" << W << endl;\r\n\r\n\tclock_t end = clock();\r\n\tdouble elapsed = (double(end) - double(start)) / CLOCKS_PER_SEC;\r\n\t//cout << \"Time measured : \" << elapsed << \"seconds.\\n\";\r\n\r\n\r\n\tColVectorXd Wd;\r\n\tW /= SCALING_FACTOR;\r\n\tWd = W.cast <double>();\r\n\r\n\r\n\t//cout << Yt << endl;\r\n\r\n\t/*cout << \"Xt size: \" << Xt.rows() << \" \" << Xt.cols() << endl;\t\r\n\tcout << \"Wd size: \" << Wd.rows() << \" \" << Wd.cols() << endl;*/\r\n\t// Xt will always be 10000 x 784, make sure Wd is also 784\r\n\t\r\n\tColVectorXd prediction = Xt * Wd;\r\n\r\n\tprediction /= SCALING_FACTOR;\r\n\tprediction *= 10;\r\n    n_ = Yt.rows();\t// 10000\r\n\tdouble temp1;\r\n\tlong int temp2, temp3;\r\n    prediction = round(prediction.array());\r\n\r\n\tcout << \"SIZE: \" << n_ << endl;\r\n\r\n\r\n\tcout << prediction << endl;\r\n\tint count = 0; int count_zero = 0;\r\n    for (int i = 0; i < n_ ; i++){\r\n\t\ttemp3 = (long long int)prediction(i);\r\n\t\t\r\n\t\t//temp1 = temp3/(double)pow(2,20+8);\r\n\t\ttemp2 = (long long int)Yt(i);\r\n\t\t//if (temp2 == 0) {\r\n\t\t//\tcount_zero++;\r\n\t\t//}\r\n\r\n\r\n\r\n\t\t//if(temp3>0.5 && temp2 == 1){\r\n\t\t//\tcount++;\r\n\t\t//}\r\n\t\t//else if (temp3 < 0.5 && temp2 == 0) {\r\n\t\t//\tcount++;\r\n\t\t//}\r\n\t\t\r\n\t\tif(prediction(i) == Yt(i))\r\n            count++;\r\n\r\n\t\t//cout << \"pred: \" << prediction(i) << \"\ttest label: \" << Yt(i) << endl;\r\n  //      \r\n    }\r\n\r\n\tcout << \"num zeros: \" << count_zero << endl;\r\n\r\n\tcout << \"num correct\" << count << endl;\r\n\tdouble accuracy = count/((double) n_);\r\n\tcout << \"Accuracy on testing the trained model is \" << accuracy * 100 << endl;\r\n\r\n\r\n} // end of main()\r\n\r\n\r\nvoid secretShareData(MATRIX& X, MATRIX& Y, MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1) {\r\n\tunsigned long long int n, n0;\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = X(i, j);\r\n\t\t\tn0 = rand();\r\n\t\t\tX0(i, j) = n0;\r\n\t\t\tX1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tn = Y(i);\r\n\t\tn0 = rand();\r\n\t\tY0(i) = n0;\r\n\t\tY1(i) = (n - n0)  ;\t// add mod 2l ?\r\n\t}\r\n}\r\n\r\nvoid genDataShares(MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1) {\r\n\tunsigned long long int n, n0, n1;\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tn1 = (n - n0); \t\t// add mod 2l ?\r\n\t\t\tX0(i, j) = n0;\r\n\t\t\tX1(i, j) = n1;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tn = rand();\r\n\t\tn0 = rand();\r\n\t\tn1 = (n - n0) ;\t\t// add mod 2l ?\r\n\t\tY0(i) = n0;\r\n\t\tY1(i) = n1;\r\n\t}\r\n}\r\n\r\nvoid initializeW(MATRIX& W0, MATRIX& W1) {\r\n\tfor (int i = 0; i < D; ++i) {\t\t\r\n\t\tW0(i) = rand();\r\n\t\tW1(i) = rand();\r\n\t}\r\n}\r\n\r\nvoid genUVZmultTriplets(MATRIX& U0, MATRIX& U1, MATRIX& V0, MATRIX& V1, MATRIX& Z0, MATRIX& Z1) {\r\n\t\r\n\tunsigned long long int n, n0;\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tU0(i, j) = n0;\r\n\t\t\tU1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < D; i++) {\r\n\t\tfor (int j = 0; j < T; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tV0(i, j) = n0;\r\n\t\t\tV1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tZ0 = U0 * V0;\r\n\tZ1 = U1 * V1;\r\n}\r\n\r\nvoid genVZprimeMultTriplets(MATRIX& UB0, MATRIX& UB1, MATRIX& Vp0, MATRIX& Vp1, MATRIX& Zp0, MATRIX& Zp1) {\r\n\tMATRIX UBT0 = UB0.transpose();\r\n\tMATRIX UBT1 = UB1.transpose();\r\n\r\n\tunsigned long long int n, n0;\r\n\tfor (int i = 0; i < B_size; i++) {\r\n\t\tfor (int j = 0; j < T; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tVp0(i, j) = n0;\r\n\t\t\tVp1(i, j) = n - n0;\r\n\t\t}\r\n\t}\r\n\r\n\tZp0 = UBT0 * Vp0;\r\n\tZp1 = UBT1 * Vp1;\r\n\t/*cout << \"MATRIX UBT0:\\n\" << UBT0 << endl;\r\n\tcout << \"MATRIX UBT1:\\n\" << UBT1 << endl;*/\r\n}\r\n\r\nvoid reconstruct(MATRIX M0, MATRIX M1, MATRIX& M) {\tM = M0 + M1;}\r\n\r\nvoid maskMatrix(MATRIX Data, MATRIX Mask, MATRIX& Final) {\tFinal = Data - Mask;}\r\n\r\nset<int> createMiniBatch(set<int>& usedIndices) {\r\n\tset<int> minibatch;\r\n\tint num = 0;\r\n\t//srand(time(NULL));\r\n\twhile (minibatch.size() != B_size) {\r\n\t\tnum = (rand() % (N - 1 + 1)) + 1;\r\n\t\tif (usedIndices.count(num) == 0) {\r\n\t\t\tusedIndices.insert(num);\r\n\t\t\tminibatch.insert(num);\r\n\t\t}\r\n\t}\r\n\treturn minibatch;\r\n}\r\n\r\nvoid computeDifference(MATRIX& Dif, MATRIX Y_, MATRIX Y) {    Dif = Y_ - Y;}\r\n\r\n\r\nint reverse_int(int i){\r\n    unsigned char ch1, ch2, ch3, ch4;\r\n    ch1 = i & 255;\r\n    ch2 = (i >> 8) & 255;\r\n    ch3 = (i >> 16) & 255;\r\n    ch4 = (i >> 24) & 255;\r\n    return ((int) ch1 << 24) + ((int) ch2 << 16) + ((int) ch3 << 8) + ch4;\r\n}\r\n\r\nvoid read_MNIST_data(bool train, vector<vector<unsigned long long int>> &vec, int& number_of_images, int& number_of_features){\r\n    std::ifstream file;\r\n\tif (train == true)\r\n\t\tfile.open(\"/Users/ariad/Documents/train-images-idx3-ubyte\", std::ios::binary);\r\n\telse\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-images-idx3-ubyte\", std::ios::binary);\r\n    \r\n    if(!file){\r\n        std::cout<<\"Unable to open file\";\r\n        return;\r\n    }\r\n    if (file.is_open()){\r\n        int magic_number = 0;\r\n        int n_rows = 0;\r\n        int n_cols = 0;\r\n        file.read((char*) &magic_number, sizeof(magic_number));\r\n        magic_number = reverse_int(magic_number);\r\n        file.read((char*) &number_of_images, sizeof(number_of_images));\r\n        number_of_images = reverse_int(number_of_images);\r\n        if(train == true)\r\n            number_of_images = N;\r\n        file.read((char*) &n_rows, sizeof(n_rows));\r\n        n_rows = reverse_int(n_rows);\r\n        file.read((char*) &n_cols, sizeof(n_cols));\r\n        n_cols = reverse_int(n_cols);\r\n        number_of_features = n_rows * n_cols;\r\n        std::cout << \"Number of Images: \" << number_of_images << std::endl;\r\n        std::cout << \"Number of Features: \" << number_of_features << std::endl;\r\n        for(int i = 0; i < number_of_images; ++i){\r\n            std::vector<unsigned long long int> tp;\r\n            for(int r = 0; r < n_rows; ++r)\r\n                for(int c = 0; c < n_cols; ++c){\r\n                    unsigned char temp = 0;\r\n                    file.read((char*) &temp, sizeof(temp));\r\n                    tp.push_back(((unsigned long long int) temp));\r\n                }\r\n            vec.push_back(tp);\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid read_MNIST_labels(bool train, vector<unsigned long long int> &vec){\r\n    std::ifstream file;\r\n\tif (train == true) {\r\n\t\tfile.open(\"/Users/ariad/Documents/train-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n\telse {\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n    if(!file){\r\n        std::cout << \"Unable to open file\";\r\n        return;\r\n    }\r\n    if (file.is_open()){\r\n        int magic_number = 0;\r\n        int number_of_images = 0;\r\n        file.read((char*) &magic_number, sizeof(magic_number));\r\n        magic_number = reverse_int(magic_number);\r\n        file.read((char*) &number_of_images, sizeof(number_of_images));\r\n        number_of_images = reverse_int(number_of_images);\r\n\t\tcout << \"number of images inside MNIST LAbels: \" << number_of_images << endl;\r\n\r\n        if(train == true)\r\n            number_of_images = N;\r\n        for(int i = 0; i < number_of_images; ++i){\r\n            unsigned char temp = 0;\r\n            file.read((char*) &temp, sizeof(temp));\r\n\t\t\t//vec.push_back((unsigned long int) temp);\r\n\t\t\t\r\n            if((unsigned long long int) temp == 0)\r\n                vec.push_back((unsigned long long int) 0);\r\n            else\r\n                vec.push_back((unsigned long long int) 1);\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid read_MNIST_data_test(bool train, vector<vector<double>> &vec, int& number_of_images, int& number_of_features){\r\n    std::ifstream file;\r\n\tif (train == true)\r\n\t\tfile.open(\"/Users/ariad/Documents/train-images-idx3-ubyte\", std::ios::binary);\r\n\telse\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-images-idx3-ubyte\", std::ios::binary);\r\n    \r\n    if(!file){\r\n        std::cout<<\"Unable to open file\";\r\n        return;\r\n    }\r\n    if (file.is_open()){\r\n        int magic_number = 0;\r\n        int n_rows = 0;\r\n        int n_cols = 0;\r\n        file.read((char*) &magic_number, sizeof(magic_number));\r\n        magic_number = reverse_int(magic_number);\r\n        file.read((char*) &number_of_images, sizeof(number_of_images));\r\n        number_of_images = reverse_int(number_of_images);\r\n        if(train == true)\r\n            number_of_images = N;\r\n        file.read((char*) &n_rows, sizeof(n_rows));\r\n        n_rows = reverse_int(n_rows);\r\n        file.read((char*) &n_cols, sizeof(n_cols));\r\n        n_cols = reverse_int(n_cols);\r\n        number_of_features = n_rows * n_cols;\r\n        std::cout << \"Number of Images: \" << number_of_images << std::endl;\r\n        std::cout << \"Number of Features: \" << number_of_features << std::endl;\r\n        for(int i = 0; i < number_of_images; ++i){\r\n            std::vector<double> tp;\r\n            for(int r = 0; r < n_rows; ++r)\r\n                for(int c = 0; c < n_cols; ++c){\r\n                    unsigned char temp = 0;\r\n                    file.read((char*) &temp, sizeof(temp));\r\n                    tp.push_back(((double) temp));\r\n                }\r\n            vec.push_back(tp);\r\n        }\r\n    }\r\n}\r\n\r\nvoid read_MNIST_labels_test(bool train, vector<double> &vec){\r\n    std::ifstream file;\r\n\tif (train == true) {\r\n\t\tfile.open(\"/Users/ariad/Documents/train-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n\telse {\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n    if(!file){\r\n        std::cout << \"Unable to open file\";\r\n        return;\r\n    }\r\n    if (file.is_open()){\r\n        int magic_number = 0;\r\n        int number_of_images = 0;\r\n        file.read((char*) &magic_number, sizeof(magic_number));\r\n        magic_number = reverse_int(magic_number);\r\n        file.read((char*) &number_of_images, sizeof(number_of_images));\r\n        number_of_images = reverse_int(number_of_images);\r\n\t\tcout << \"number of images inside MNIST LAbels: \" << number_of_images << endl;\r\n\r\n        if(train == true)\r\n            number_of_images = N;\r\n        for(int i = 0; i < number_of_images; ++i){\r\n            unsigned char temp = 0;\r\n            file.read((char*) &temp, sizeof(temp));\r\n\t\t\t//vec.push_back((double) temp);\r\n\t\t\t\r\n            if((double) temp == 0)\r\n                vec.push_back((double) 0);\r\n            else\r\n                vec.push_back((double) 1);\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n\tModulus\r\n\tEpochs, testing accuracy\r\n*/", "meta": {"hexsha": "ea07a775107de32beda301035b9e16453546632e", "size": 20880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_stars_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T12:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:41:51.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_issues_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_issues_repo_licenses": ["MIT"], "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": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_forks_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:06:55.000Z", "avg_line_length": 29.4915254237, "max_line_length": 127, "alphanum_fraction": 0.5518678161, "num_tokens": 6884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7490872243177519, "lm_q1q2_score": 0.6521533013507571}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// accumulator::zscore.cpp                                                  //\n//                                                                          //\n//  (C) Copyright 2010 Erwann Rogard                                        //\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 <algorithm>\n#include <vector>\n#include <boost/ref.hpp>\n#include <boost/range.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/statistics/detail/accumulator/statistics/zscore.hpp>\n\nvoid example_accumulator_zscore(std::ostream& os)\n{\n\n\tos << \"-> example_accumulator_zscore\" << std::endl;\n\n\ttypedef double val_;\n    namespace stat = boost::statistics::detail;\n    typedef stat::accumulator::tag::zscore tag_z_;\n    \n    typedef boost::accumulators::accumulator_set<\n    \tval_,\n    \tboost::accumulators::stats<tag_z_>\n    > acc_;\n\n\ttypedef boost::normal_distribution<val_> r_;\n    typedef boost::mt19937 urng_;\n\ttypedef boost::variate_generator<urng_&,r_> vg_;\n\ttypedef std::vector<val_> vec_;\n\n\tconst val_ m = -1;\n    const val_ s = 2;\n\tr_ r(m,s);\n    urng_ urng;    \n\tvg_ vg(urng,r);\t\n    vec_ vec;\n    \n\tstd::generate_n(std::back_inserter(vec),10000,vg);\n    acc_ acc;\n    acc = std::for_each(\n    \tboost::begin(vec),\n        boost::end(vec),\n       \tacc\n    );\n    \n\t// should be close -1.96, 0, 1.96\n    val_ a = stat::accumulator::extract::zscore(acc,m-1.96 * s); \t\n    val_ b = stat::accumulator::extract::zscore(acc,m); \t\t\t\n    val_ c = stat::accumulator::extract::zscore(acc,m+1.96 * s); \t\n\tos << \"a = \" << a << std::endl;\n\tos << \"b = \" << b << std::endl;\n\tos << \"c = \" << c << std::endl;\n    \n    os << std::endl;\n    \n}\n", "meta": {"hexsha": "c3df32c77d952035da0bc5ce9935c2ef6ff09f28", "size": 2178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detail/accumulator/libs/statistics/detail/accumulator/example/zscore.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/accumulator/libs/statistics/detail/accumulator/example/zscore.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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": "detail/accumulator/libs/statistics/detail/accumulator/example/zscore.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "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.0, "max_line_length": 78, "alphanum_fraction": 0.54912764, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807406, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6521532890824044}}
{"text": "#include <igl/read_triangle_mesh.h>\n#include <igl/hessian_energy.h>\n#include <igl/massmatrix.h>\n#include <igl/cotmatrix.h>\n#include <igl/jet.h>\n#include <igl/edges.h>\n#include <igl/vertex_components.h>\n#include <igl/remove_unreferenced.h>\n#include <igl/opengl/glfw/Viewer.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCholesky>\n\n#include <iostream>\n#include <set>\n#include <limits>\n#include <stdlib.h>\n\n#include \"tutorial_shared_path.h\"\n\n#include <igl/isolines.h>\n\n\nint main(int argc, char * argv[])\n{\n    typedef Eigen::SparseMatrix<double> SparseMat;\n\n    //Read our mesh\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F, E;\n    if(!igl::read_triangle_mesh(\n        argc>1?argv[1]: TUTORIAL_SHARED_PATH \"/beetle.off\",V,F)) {\n        std::cout << \"Failed to load mesh.\" << std::endl;\n    }\n    igl::edges(F,E);\n\n    //Constructing an exact function to smooth\n    Eigen::VectorXd zexact = V.block(0,2,V.rows(),1).array()\n        + 0.5*V.block(0,1,V.rows(),1).array()\n        + V.block(0,1,V.rows(),1).array().pow(2)\n        + V.block(0,2,V.rows(),1).array().pow(3);\n\n    //Make the exact function noisy\n    srand(5);\n    const double s = 0.2*(zexact.maxCoeff() - zexact.minCoeff());\n    Eigen::VectorXd znoisy = zexact + s*Eigen::VectorXd::Random(zexact.size());\n\n    //Constructing the squared Laplacian and squared Hessian energy\n    SparseMat L, M;\n    igl::cotmatrix(V, F, L);\n    igl::massmatrix(V, F, igl::MASSMATRIX_TYPE_BARYCENTRIC, M);\n    Eigen::SimplicialLDLT<SparseMat> solver(M);\n    SparseMat MinvL = solver.solve(L);\n    SparseMat QL = L.transpose()*MinvL;\n    SparseMat QH;\n    igl::hessian_energy(V, F, QH);\n\n    //Solve to find Laplacian-smoothed and Hessian-smoothed solutions\n    const double al = 8e-4;\n    Eigen::SimplicialLDLT<SparseMat> lapSolver(al*QL + (1.-al)*M);\n    Eigen::VectorXd zl = lapSolver.solve(al*M*znoisy);\n    const double ah = 5e-6;\n    Eigen::SimplicialLDLT<SparseMat> hessSolver(ah*QH + (1.-ah)*M);\n    Eigen::VectorXd zh = hessSolver.solve(ah*M*znoisy);\n\n    //Viewer that shows all functions: zexact, znoisy, zl, zh\n    igl::opengl::glfw::Viewer viewer;\n    viewer.data().set_mesh(V,F);\n    viewer.data().show_lines = false;\n    viewer.callback_key_down =\n      [&](igl::opengl::glfw::Viewer & viewer, unsigned char key, int mod)->bool\n      {\n        //Graduate result to show isolines, then compute color matrix\n        const Eigen::VectorXd* z;\n        switch(key) {\n            case '1':\n                z = &zexact;\n                break;\n            case '2':\n                z = &znoisy;\n                break;\n            case '3':\n                z = &zl;\n                break;\n            case '4':\n                z = &zh;\n                break;\n            default:\n                return false;\n        }\n        Eigen::MatrixXd isoV;\n        Eigen::MatrixXi isoE;\n        if(key!='2')\n            igl::isolines(V, F, *z, 30, isoV, isoE);\n        viewer.data().set_edges(isoV,isoE,Eigen::RowVector3d(0,0,0));\n        Eigen::MatrixXd colors;\n        igl::jet(*z, true, colors);\n        viewer.data().set_colors(colors);\n        return true;\n    };\n    std::cout << R\"(Usage:\n1  Show original function\n2  Show noisy function\n3  Biharmonic smoothing (zero Neumann boundary)\n4  Biharmonic smoothing (natural Hessian boundary)\n\n)\";\n    viewer.launch();\n\n    return 0;\n}\n", "meta": {"hexsha": "2f863de590876526735492be17f7e1b1ac5c9648", "size": 3322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/712_DataSmoothing/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/712_DataSmoothing/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/tutorial/712_DataSmoothing/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["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.6607142857, "max_line_length": 79, "alphanum_fraction": 0.6020469597, "num_tokens": 956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6521532791756826}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2012-2015 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_GOLDBAR_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_GOLDBAR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate the conjugate golden ratio that is \\f$\\bar\\phi = \\frac{1-\\sqrt5}{2}\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Goldbar<T>();\n    @endcode\n\n    is similar for floating types to:\n\n    @code\n    T r = (1-sqrt(T(5)))/2;\n    @endcode\n\n    @return The Goldbar constant for the proper type\n  **/\n  template<typename T> T Goldbar();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant goldbar.\n\n      @return The Goldbar constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::goldbar_> goldbar = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/goldbar.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "f5db69207b5ed471fe4ecf59cce8782c0ddabd24", "size": 1386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/goldbar.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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/simd/constant/goldbar.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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/constant/goldbar.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "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": 24.75, "max_line_length": 100, "alphanum_fraction": 0.5952380952, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6521126793667772}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\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//[dimension\r\n//` Examine the number of coordinates making up the points in a linestring type\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian);\r\n\r\nint main()\r\n{\r\n    int dim = boost::geometry::dimension\r\n        <\r\n            boost::geometry::model::linestring\r\n                <\r\n                    boost::tuple<float, float, float>\r\n                >\r\n        >::value;\r\n    \r\n    std::cout << \"dimensions: \" << dim << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[dimension_output\r\n/*`\r\nOutput:\r\n[pre\r\ndimensions: 3\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "9c2cf7f15d21320184c3be6a5eef446e93442570", "size": 1058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/coordinate_dimension.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/geometry/doc/src/examples/core/coordinate_dimension.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/geometry/doc/src/examples/core/coordinate_dimension.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": 22.5106382979, "max_line_length": 80, "alphanum_fraction": 0.6332703214, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6520641464297209}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2018 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file cevrndcalculator.cpp */\n\n#include <ql/errors.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n\n#include <ql/methods/finitedifferences/utilities/cevrndcalculator.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\nnamespace QuantLib {\n\n    CEVRNDCalculator::CEVRNDCalculator(Real f0, Real alpha, Real beta)\n    : f0_(f0),\n      alpha_(alpha),\n      beta_(beta),\n      delta_((1.0-2.0*beta)/(1.0-beta)),\n      x0_(X(f0)) {\n        QL_REQUIRE(beta != 1.0, \"beta can not be one\");\n    }\n\n    Real CEVRNDCalculator::massAtZero(Time t) const {\n        if (delta_ < 2.0)\n            return 1.0-boost::math::gamma_p(-0.5*delta_+1.0,x0_/(2.0*t));\n        else\n            return 0.0;\n    }\n\n    Real CEVRNDCalculator::X(Real f) const {\n        return std::pow(f, 2.0*(1.0-beta_))/square<Real>()(alpha_*(1.0-beta_));\n    }\n\n    Real CEVRNDCalculator::invX(Real x) const {\n        return std::pow(x*square<Real>()(alpha_*(1.0-beta_)),\n                        1.0/(2.0*(1.0-beta_)));\n    }\n\n    Real CEVRNDCalculator::pdf(Real f, Time t) const {\n        const Real y = X(f);\n\n        if (delta_ < 2.0) {\n            return boost::math::pdf(\n                boost::math::non_central_chi_squared_distribution<Real>(\n                    4.0-delta_, y/t), x0_/t)/t * 2.0*(1.0-beta_)*y/f;\n        }\n        else {\n            return boost::math::pdf(\n                boost::math::non_central_chi_squared_distribution<Real>(\n                    delta_, x0_/t), y/t)/t * 2.0*(beta_-1.0)*y/f;\n        }\n    }\n\n    Real CEVRNDCalculator::cdf(Real f, Time t) const {\n        const Real y = X(f);\n\n        if (delta_ < 2.0)\n            return 1.0 - boost::math::cdf(\n                boost::math::non_central_chi_squared_distribution<Real>(\n                    2.0-delta_, y/t), x0_/t);\n        else\n            return 1.0 - boost::math::cdf(\n                boost::math::non_central_chi_squared_distribution<Real>(\n                    delta_, x0_/t), y/t);\n    }\n\n    Real CEVRNDCalculator::sankaranApprox(Real c, Time t, Real x) const {\n        const Real a = x0_/t;\n        const Real b = 2.0 - delta_;\n\n        c = std::max(c, -0.45*b);\n\n        const Real h = 1 - 2*(b+c)*(b+3*c)/(3*square<Real>()(b+2*c));\n        const Real p = (b+2*c)/square<Real>()(b+c);\n        const Real m = (h-1)*(1-3*h);\n\n        const Real u = (std::pow(a/(b+c), h) - (1 + h*p*(h-1-0.5*(2-h)*m*p)))/\n                (h*std::sqrt(2*p)*(1+0.5*m*p));\n\n        return u - x;\n    }\n\n    Real CEVRNDCalculator::invcdf(Real q, Time t) const {\n        if (delta_ < 2.0) {\n            if (f0_ < QL_EPSILON || q < massAtZero(t))\n                return 0.0;\n\n            const Real x = InverseCumulativeNormal()(1-q);\n\n            auto cdfApprox = [&](Real _c){ return sankaranApprox(_c, t, x); };\n\n            const Real y0 = X(f0_)/t;\n\n            try {\n                Brent brent;\n                brent.setMaxEvaluations(20);\n                const Real guess =\n                    invX(brent.solve(cdfApprox, 1e-8, y0, 0.02*y0) * t);\n\n                return InvCDFHelper(this, guess, 1e-8, 100).inverseCDF(q, t);\n            }\n            catch (...) {\n                return InvCDFHelper(this, f0_, 1e-8, 100).inverseCDF(q, t);\n            }\n        }\n        else {\n            const Real x = t * boost::math::quantile(\n                boost::math::non_central_chi_squared_distribution<Real>(\n                    delta_, x0_/t), 1-q);\n            return invX(x);\n        }\n    }\n}\n", "meta": {"hexsha": "a36078d8dcde1092eb0d76009ca6a66df1641861", "size": 4400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 32.8358208955, "max_line_length": 79, "alphanum_fraction": 0.5634090909, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6520441565020746}}
{"text": "#include <iostream>\n#include <fstream>\n#include \"spaND.h\"\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n#include \"mmio.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace spaND;\n\nint main(int argc, char* argv[]) {\n    assert(argc == 5);\n    string folder(argv[1]);\n    int nlevels = atoi(argv[2]);\n    double tol = atof(argv[3]);\n    int skip = atoi(argv[4]);\n    cout << \"Inputs folder \" << folder << \" nlevels = \" << nlevels << \" tol = \" << tol << \" skip = \" << skip << endl;\n    string file  = folder + \"/jac4.mm\";\n    string xfile = folder + \"/xCoords.mm\";\n    string yfile = folder + \"/yCoords.mm\";\n    cout << \"Reading from \" << file << \" \" << xfile << \" \" << yfile << endl;\n    SpMat A = mmio::sp_mmread<double,int>(file);\n    int N = A.rows();\n    cout << \"A has \" << N << \" rows\" << endl;\n    VectorXd xcoords = mmio::dense_mmread<double>(xfile);\n    VectorXd ycoords = mmio::dense_mmread<double>(yfile);\n    // Create X coordinate matrix\n    MatrixXd X(2, N);\n    assert(xcoords.size() == N/2);\n    assert(ycoords.size() == N/2);\n    for(int i = 0; i < N; i++) {\n        X(0,i) = xcoords(i/2);\n        X(1,i) = ycoords(i/2);\n    }\n    Tree t = Tree(nlevels);\n    t.set_tol(tol);\n    t.set_skip(skip);\n    t.set_use_geo(true);\n    t.set_Xcoo(&X);\n    // Run algo    \n    timer start = wctime();\n    t.partition(A);\n    // Rest\n    timer part = wctime();\n    t.assemble(A);\n    timer ass = wctime();\n    try {\n        t.factorize();\n    } catch (exception& ex) {\n        cout << ex.what();\n        exit(1);\n    }\n    timer end = wctime();\n    t.print_log();\n    cout << \"Timings:\" << endl << \"  Partition: \" << elapsed(start,part) << \" s.\" << endl << \"  Assembly: \" << elapsed(part,ass) << \" s.\" << endl << \"  Factorization: \" << elapsed(ass, end) << \" s.\" << endl;\n    // Use CG\n    VectorXd x = VectorXd::Zero(N);\n    VectorXd b = VectorXd::Random(N);\n    timer cg0 = wctime();\n    int iter = cg(A, b, x, t, 500, 1e-12, true);\n    timer cg1 = wctime();\n    cout << \"CG: #iterations: \" << iter << \", residual |Ax-b|/|b|: \" << (A*x-b).norm() / b.norm() << endl;\n    cout << \"  CG: \" << elapsed(cg0, cg1) << \" s.\" << endl;\n    return 0;\n}\n", "meta": {"hexsha": "e52c414f3f794e89d8af9d96ced10331b716bc19", "size": 2200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/icesheet.cpp", "max_stars_repo_name": "leopoldcambier/spaND_public", "max_stars_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T21:17:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:56:30.000Z", "max_issues_repo_path": "tests/icesheet.cpp", "max_issues_repo_name": "leopoldcambier/spaND_public", "max_issues_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/icesheet.cpp", "max_forks_repo_name": "leopoldcambier/spaND_public", "max_forks_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-23T12:04:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-23T12:04:28.000Z", "avg_line_length": 32.8358208955, "max_line_length": 207, "alphanum_fraction": 0.5422727273, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6520218106594667}}
{"text": "#include <iostream>\n#include <Eigen/dense>\n#include \"file_manage.h\"\n#include \"gaussian_mixture.h\"\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tMatrixXd features;\n\tVectorXd labels;\n\n\tread_csv(\"data/iris.csv\", features, labels, 150, 5);\n\t//read_csv(\"data/seeds.csv\", features, labels, 210, 8);\n\n\tGMM model(3);\n\tmodel.fit(features, 1);\n\n\treturn 0;\n}", "meta": {"hexsha": "e0041579a1028a7dcce02e6c8d912c5b60932777", "size": 360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "stnamjef/gaussian_mixture", "max_stars_repo_head_hexsha": "82a89624db1aba2293b9165d066568cdd3e227b0", "max_stars_repo_licenses": ["MIT"], "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": "stnamjef/gaussian_mixture", "max_issues_repo_head_hexsha": "82a89624db1aba2293b9165d066568cdd3e227b0", "max_issues_repo_licenses": ["MIT"], "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": "stnamjef/gaussian_mixture", "max_forks_repo_head_hexsha": "82a89624db1aba2293b9165d066568cdd3e227b0", "max_forks_repo_licenses": ["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.0, "max_line_length": 56, "alphanum_fraction": 0.7111111111, "num_tokens": 100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6520217881031523}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_layer.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n\n    int batch_size = 3;\n    int input_size = 3;\n    int output_size = 2;\n\n    MatrixXd X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd Y, dX;\n    MatrixXd W = MatrixXd::Zero(input_size, output_size);\n    VectorXd b = VectorXd::Zero(output_size);\n    MatrixXd dout = MatrixXd::Ones(batch_size, output_size);\n    X << 1, 2, 3,\n         4, 5, 6,\n         7, 8, 9;\n    W << 1, 2,\n         2, 3,\n         3, 4;\n    b << 1, 2;\n\n    MyDL::Affine affine(W, b);\n    Y = affine.forward(X);\n    cout << \"forward: \" << Y << endl;\n    dX = affine.backward(dout);\n    cout << \"backward: \" << dX << endl;\n\n    return 0;\n}", "meta": {"hexsha": "13442e7f69628effe9c70313d7b5f60a9dd9aff7", "size": 787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/affine.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch5/affine.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch5/affine.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.8611111111, "max_line_length": 60, "alphanum_fraction": 0.5679796696, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6519894836506834}}
{"text": "// Group B - Perpetual American Option\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-10-19\r\n//\r\n// Main.cpp\r\n//\r\n// We program the formula for pricing perptual American Options (part a). We test the data.\r\n// Again, we take the input of an array to compute prices for a varying parameter. We then \r\n// code a matrix pricer that allows us to vary two parameters. The structure of this project\r\n// mirrors the structure of group A. We have defined types for the option parameters in\r\n// Types.hpp. We have the struct in OptionData.hpp and we have our pricing functions in\r\n// OptionPricing.hpp. The perpetual American Option Class is in PerpetualAmericanOption.hpp\r\n// We have MeshArray.hpp to use the method for creating an array of parameter values.\r\n\r\n#include \"PerpetualAmericanOption.hpp\"\r\n#include \"MeshArray.hpp\"\r\n#include <boost/tuple/tuple_io.hpp>\r\n\r\nint main()\r\n{\t// 2 b)\r\n\t// We test our perpetual American option class. First we create the option and set the data.\r\n\tPerpetualAmericanOption Amer_Option;\r\n\tStrike_Price K = (Strike_Price)100.0;\r\n\tVolatility sig = (Volatility) 0.1;\r\n\trate r = (rate)0.1;\r\n\tcost_of_carry b = (cost_of_carry)0.02;\r\n\tcurr_stock_price S = (curr_stock_price)110;\r\n\tAmer_Option.SetOption(K,sig,r,b,S);\r\n\r\n\t// Now we print the call and put prices.\r\n\tcout << \"Perpetual American Option Call Price: \" << Amer_Option.CallPriceAmer() << endl;\r\n\tcout << \"Perpetual American Option Put Price: \" <<Amer_Option.PutPriceAmer() << endl;\r\n\t\r\n\tcout << endl;\r\n\t//============================================================================================== =\r\n\t// 2 c) We create a mesh array of current stock prices and determine the option prices.\r\n\tcurr_stock_price start = (curr_stock_price) 10.0;\r\n\tcurr_stock_price end = (curr_stock_price) 50.0;\r\n\tcurr_stock_price interval = (curr_stock_price) 1.0;\r\n\r\n\tvector<curr_stock_price> S_array = MeshArray(start, end, interval);\r\n\r\n\t// Create vector of Calls and puts\r\n\tvector<double> CallPrices = Amer_Option.CallPriceAmer(S_array);\r\n\tvector<double> PutPrices = Amer_Option.PutPriceAmer(S_array);\r\n\r\n\t\r\n\t// Print the result\r\n\tcout << \"S - value, Call, Put \" << endl;\r\n\tPrintArray(S_array, CallPrices, PutPrices);\r\n\r\n\t// Reset the Option\r\n\tAmer_Option.SetOption(K, sig, r, b, S);\r\n\tcout << endl;\r\n\t//============================================================================================== =\r\n\t// 2 d) We create a matrix of option parameters and output a matrix of option prices.\r\n\t// For the parameters, we use K and sig. We create two vectors.\r\n\tStrike_Price K_start = (Strike_Price)80.0;\r\n\tStrike_Price K_end = (Strike_Price)120.0;\r\n\tStrike_Price K_interval = (Strike_Price)1.0;\r\n\tvector<Strike_Price> K_array = MeshArray(K_start, K_end, K_interval);\r\n\r\n\tVolatility sig_start = (Volatility) 0.01;\r\n\tVolatility sig_end = (Volatility) 0.20;\r\n\tVolatility sig_interval = (Volatility)0.01;\r\n\tvector<Volatility> sig_array = MeshArray(sig_start, sig_end, sig_interval);\r\n\r\n\t// Create a Matrix to store the call prices and put prices.\r\n\ttypedef boost::tuple<double, double> CallPrice_PutPrice;\r\n\tconst int num_rows = 50;\r\n\tconst int num_cols = 50;\r\n\tCallPrice_PutPrice PriceMatrix[num_rows][num_cols]; // Price matrix stores call and put price when parameter I takes value x and parameter J takes value y.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   // In this example we use expiry time and volatility. \r\n\r\n\tcout << \"(Strike Price, Volatility, (Call Price Put Price))\" << endl;\r\n\r\n\tfor (int i = 0; i < K_array.size(); ++i)\r\n\t{\r\n\t\tAmer_Option.SetOption(K_array[i]);\r\n\r\n\t\tfor (int j = 0; j < sig_array.size(); ++j)\r\n\t\t{\r\n\t\t\tAmer_Option.SetOption(sig_array[j]);\r\n\t\t\tPriceMatrix[i][j] = CallPrice_PutPrice(Amer_Option.CallPriceAmer(), Amer_Option.PutPriceAmer());\r\n\r\n\t\t\tcout << \"(\" << K_array[i] << \", \" << sig_array[j] << \", \" << PriceMatrix[i][j] << \")\" << endl;\r\n\t\t}\r\n\t}\r\n\tcout << endl;\r\n\r\n\t// reset the option\r\n\tAmer_Option.SetOption(K, sig, r, b, S);\r\n\treturn 0;\r\n}", "meta": {"hexsha": "e0b12b4ba7f1d22d224b74ac2875543878602439", "size": 3900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Group B/Group B/Main.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "Group B/Group B/Main.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Group B/Group B/Main.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.625, "max_line_length": 157, "alphanum_fraction": 0.6664102564, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6519485337242289}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n*\n*   Tutorial: Calculation of the eigenvalue with largest modulus using the power iteration method\n*             (power-iter.cpp and power-iter.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n// include necessary system headers\n#include <iostream>\n\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n#define VIENNACL_WITH_UBLAS\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n\n#include \"viennacl/linalg/power_iter.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n// Some helper functions for this tutorial:\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <string>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n\n\nint main()\n{\n  typedef double     ScalarType;\n\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;\n\n  if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n\n  viennacl::compressed_matrix<double>  vcl_A(ublas_A.size1(), ublas_A.size2());\n  viennacl::copy(ublas_A, vcl_A);\n\n  viennacl::linalg::power_iter_tag ptag(1e-6);\n\n  std::cout << \"Starting computation of eigenvalue with largest modulus (might take about a minute)...\" << std::endl;\n  std::cout << \"Result of power iteration with ublas matrix (single-threaded): \" << viennacl::linalg::eig(ublas_A, ptag) << std::endl;\n  std::cout << \"Result of power iteration with ViennaCL (OpenCL accelerated): \" << viennacl::linalg::eig(vcl_A, ptag) << std::endl;\n\n}\n\n", "meta": {"hexsha": "3028ca75c3f67877ac13a8b7271600fcc1d78af0", "size": 2655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/power-iter.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "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/tutorial/power-iter.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "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/tutorial/power-iter.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["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.1875, "max_line_length": 134, "alphanum_fraction": 0.6433145009, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6519485315613961}}
{"text": "#include <algorithm>\r\n#include <Eigen/Dense>\r\n#include <opencv2/opencv.hpp>\r\n#include \"nv_core.h\"\r\n#include \"nv_ml.h\"\r\n#include \"nv_num.h\"\r\n\r\n// k-means++\r\nint nv_kmeans(nv_matrix_t *means_mat,  // k\r\n\t\t  nv_matrix_t *count_mat,  // k\r\n\t\t  nv_matrix_t *labels_mat, // data->m\r\n\t\t  const nv_matrix_t *data_mat,\r\n\t\t  const int k,\r\n\t\t  const int max_epoch)\r\n{\r\n\tcv::Mat means(means_mat->m, means_mat->n, CV_32F, means_mat->v);\r\n\tcv::Mat data(data_mat->m, data_mat->n, CV_32F, data_mat->v);\r\n\tcv::Mat labels(data_mat->m, 1, CV_32S);\r\n\r\n\tEigen::Map<Eigen::VectorXf> count(count_mat->v, count_mat->m);\r\n\tcount.setZero();\r\n\r\n\tcv::kmeans(data, k, labels, cv::TermCriteria(cv::TermCriteria::MAX_ITER, max_epoch, 0), 1, cv::KMEANS_PP_CENTERS, means);\r\n\r\n\tfor (int m = 0; m < data_mat->m; ++m) {\r\n\t\tNV_MAT_V(labels_mat, m, 0) = labels.at<int>(m, 0);\r\n\t\t++count(labels.at<int>(m, 0));\r\n\t}\r\n\treturn k;\r\n}\r\n\r\n", "meta": {"hexsha": "02d12d76a2a842df888b71a6e751cbe95d5cead4", "size": 895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nvxs/nv_ml/nv_kmeans.cpp", "max_stars_repo_name": "aliakseis/animeface-2009", "max_stars_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-14T15:21:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T09:49:35.000Z", "max_issues_repo_path": "nvxs/nv_ml/nv_kmeans.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_kmeans.cpp", "max_forks_repo_name": "aliakseis/animeface-2009", "max_forks_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T09:49:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T09:49:40.000Z", "avg_line_length": 27.96875, "max_line_length": 123, "alphanum_fraction": 0.6413407821, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6519464586250038}}
{"text": "#pragma once\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/register/box.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <cmath>\n#include <list>\n#include <tuple>\n\n#include \"geohash/math.hpp\"\n\nnamespace geohash {\n\n// Geographic point\nstruct Point {\n  double lng{};\n  double lat{};\n};\n\n// A box made of two describing points\nclass Box {\n public:\n  // Default constructor\n  Box() = default;\n\n  // Constructor taking the minimum corner point and the maximum corner point\n  Box(const Point& min_corner, const Point& max_corner)\n      : min_corner_(min_corner), max_corner_(max_corner) {}\n\n  // Returns the center of the box.\n  [[nodiscard]] inline constexpr auto center() const -> Point {\n    return {(min_corner_.lng + max_corner_.lng) * 0.5,\n            (min_corner_.lat + max_corner_.lat) * 0.5};\n  }\n\n  // Returns the delta of the box in latitude and longitude.\n  [[nodiscard]] inline auto delta(bool round) const\n      -> std::tuple<double, double> {\n    auto x = max_corner_.lng - min_corner_.lng;\n    auto y = max_corner_.lat - min_corner_.lat;\n    if (round) {\n      x = Box::max_decimal_power(x);\n      y = Box::max_decimal_power(y);\n    }\n    return std::make_tuple(x, y);\n  }\n\n  // Returns a point inside the box, making an effort to round to minimal\n  // precision.\n  [[nodiscard]] inline auto round() const -> Point {\n    double x;\n    double y;\n    std::tie(x, y) = delta(true);\n    return {std::ceil(min_corner_.lng / x) * x,\n            std::ceil(min_corner_.lat / y) * y};\n  }\n\n  // Returns the box, or the two boxes on either side of the dateline if the\n  // defined box wraps around the globe (i.e. the longitude of the min corner\n  // is greater than the longitude of the max corner.)\n  [[nodiscard]] auto split() const -> std::list<Box> {\n    // box wraps around the globe ?\n    if (min_corner_.lng > max_corner_.lng) {\n      return {Box({min_corner_.lng, min_corner_.lat}, {180, max_corner_.lat}),\n              Box({-180, min_corner_.lat}, {max_corner_.lng, max_corner_.lat})};\n    }\n    return {*this};\n  }\n\n  // Returns true if the geographic point is within the box\n  [[nodiscard]] auto contains(const Point& point) const -> bool {\n    // box wraps around the globe ?\n    if (min_corner_.lng > max_corner_.lng) {\n      for (const auto& item : split()) {\n        if (!item.contains(point)) {\n          return false;\n        }\n      }\n      return true;\n    }\n    return (min_corner_.lat <= point.lat && point.lat <= max_corner_.lat &&\n            min_corner_.lng <= point.lng && point.lng <= max_corner_.lng);\n  }\n\n  // Returns the minimum corner point\n  [[nodiscard]] auto min_corner() const -> const Point& { return min_corner_; }\n\n  // Returns the minimum corner point\n  [[nodiscard]] auto min_corner() -> Point& { return min_corner_; }\n\n  // Returns the maximum corner point\n  [[nodiscard]] auto max_corner() const -> const Point& { return max_corner_; }\n\n  // Returns the maximum corner point\n  [[nodiscard]] auto max_corner() -> Point& { return max_corner_; }\n\n private:\n  Point min_corner_{};\n  Point max_corner_{};\n\n  // Returns the maximum power of 10 from a number (x > 0)\n  static auto max_decimal_power(const double x) -> double {\n    auto m = static_cast<int32_t>(std::floor(std::log10(x)));\n    return power10(m);\n  }\n};\n\n}  // namespace geohash\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(\n    geohash::Point, double,\n    boost::geometry::cs::geographic<boost::geometry::degree>, lng, lat)\n\nBOOST_GEOMETRY_REGISTER_BOX(geohash::Box, geohash::Point, min_corner(),\n                            max_corner())\n\nnamespace geohash {\n\nusing Polygon = boost::geometry::model::polygon<Point>;\n\n}  // namespace geohash\n", "meta": {"hexsha": "743f875c0a6e1d1ae78636b098730eab7407a12f", "size": 3674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geohash/core/include/geohash/geometry.hpp", "max_stars_repo_name": "fbriol/pangeo-geohash", "max_stars_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_stars_repo_licenses": ["MIT"], "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/geohash/core/include/geohash/geometry.hpp", "max_issues_repo_name": "fbriol/pangeo-geohash", "max_issues_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_issues_repo_licenses": ["MIT"], "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/geohash/core/include/geohash/geometry.hpp", "max_forks_repo_name": "fbriol/pangeo-geohash", "max_forks_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_forks_repo_licenses": ["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.3636363636, "max_line_length": 80, "alphanum_fraction": 0.6551442569, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6519464569765024}}
{"text": "// Vec2.cpp\n#include \"Vec2.h\"\n\n#include <armadillo>\n\nnamespace ugps\n{\n    num_ug Vec2::length() const\n    {\n        return sqrt(length2());\n    }\n\n    num_ug Vec2::length2() const\n    {\n        return x*x + y*y;\n    }\n\n\n    arma::Col<num_ug> Vec2::col() const \n    {\n        arma::Col<num_ug> c = {x,y};\n        return c;\n    }\n\t\n    arma::Row<num_ug> Vec2::row() const \n    {\n        arma::Row<num_ug> r = {x,y};\n        return r;\n    }\n    \n    Vec2 Vec2::rotate(const num_ug& angle) const\n    {\n        return Vec2(\n                cos(angle)*x - sin(angle)*y,\n                sin(angle)*y + cos(angle)*x\n                );\n    }\n\n    num_ug Vec2::angle() const\n    {\n        return atan2(y,x);\n    }\n}\n", "meta": {"hexsha": "269e509cafaa47db0efde4c0a6de5ac2edc0eba0", "size": 706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Vec2.cpp", "max_stars_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_stars_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "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/Vec2.cpp", "max_issues_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_issues_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "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/Vec2.cpp", "max_forks_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_forks_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "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": 16.0454545455, "max_line_length": 48, "alphanum_fraction": 0.4645892351, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6519434106460197}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MATH_XGCD_HPP\n#define CRYPTO3_MATH_XGCD_HPP\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/math/tools/polynomial_gcd.hpp>\n#include <boost/integer/extended_euclidean.hpp>\n\n#include <nil/crypto3/math/polynomial/basic_operations.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace math {\n\n            /*!\n             * @brief Perform the standard Extended Euclidean Division algorithm.\n             * Input: Polynomial A, Polynomial B.\n             * Output: Polynomial G, Polynomial U, Polynomial V, such that G = (A * U) + (B * V).\n             */\n            template<typename Range1, typename Range2, typename Range3, typename Range4,\n                     typename Range5>\n            void extended_euclidean(const Range1 &a, const Range2 &b, Range3 &g, Range4 &u, Range5 &v) {\n\n                typedef\n                    typename std::iterator_traits<decltype(std::begin(std::declval<Range1>()))>::value_type value_type;\n\n                if (is_zero(b)) {\n                    g = a;\n                    u = std::vector<value_type>(1, value_type::one());\n                    v = std::vector<value_type>(1, value_type::zero());\n                    return;\n                }\n\n                std::vector<value_type> U(1, value_type::one());\n                std::vector<value_type> V1(1, value_type::zero());\n                std::vector<value_type> G(a);\n                std::vector<value_type> V3(b);\n\n                std::vector<value_type> Q(1, value_type::zero());\n                std::vector<value_type> R(1, value_type::zero());\n                std::vector<value_type> T(1, value_type::zero());\n\n                while (!is_zero(V3)) {\n                    division(Q, R, G, V3);\n                    multiplication(G, V1, Q);\n                    subtraction(T, U, G);\n\n                    U = V1;\n                    G = V3;\n                    V1 = T;\n                    V3 = R;\n                }\n\n                multiplication(V3, a, U);\n                subtraction(V3, G, V3);\n                division(V1, R, V3, b);\n\n                value_type lead_coeff = G.back().inversed();\n                std::transform(G.begin(), G.end(), G.begin(),\n                               std::bind(std::multiplies<value_type>(), lead_coeff, std::placeholders::_1));\n                std::transform(U.begin(), U.end(), U.begin(),\n                               std::bind(std::multiplies<value_type>(), lead_coeff, std::placeholders::_1));\n                std::transform(V1.begin(), V1.end(), V1.begin(),\n                               std::bind(std::multiplies<value_type>(), lead_coeff, std::placeholders::_1));\n\n                g = G;\n                u = U;\n                v = V1;\n            }\n        }    // namespace math\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // ALGEBRA_FFT_XGCD_HPP\n", "meta": {"hexsha": "2411e1e5fc4310557097ffe916108ef698b78ea7", "size": 4234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/polynomial/xgcd.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/polynomial/xgcd.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "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/nil/crypto3/math/polynomial/xgcd.hpp", "max_forks_repo_name": "NilFoundation/fft", "max_forks_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9207920792, "max_line_length": 119, "alphanum_fraction": 0.5529050543, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.651879831090975}}
{"text": "#include <acado_toolkit.hpp>\n#include <acado_gnuplot.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n#define pi 3.14159\n\nusing namespace std;\n\nstatic boost::random::mt19937 gen;\n\nint test(float bounds[8]);\nfloat rand_gen(float lim[2]);\n\nint test(float bounds[8]){\n\n  USING_NAMESPACE_ACADO\n\n  DifferentialState        q1,q2,qd1,qd2;   // the differential states\n  Control                  tau1,tau2;       // the control input u\n  Parameter                T;\n  DifferentialEquation     f( 0.0, 0.5 );\n\n  //  -------------------------------------\n  OCP ocp( 0.0, 0.5 );\n  \n  ocp.minimizeLagrangeTerm(tau1*tau1 + tau2*tau2);\n  // ocp.minimizeMayerTerm(T*T + tau1*tau1 + tau2*tau2);\n\n  f << dot(q1) == qd1;\n  f << dot(q2) == qd2;\n  f << dot(qd1) == -(48*tau1 - 48*tau2 + 24*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 18*qd1*qd1*sin(2*q2) - 72*tau2*cos(q2) + 48*qd1*qd2*sin(q2))/(36*cos(q2)*cos(q2) - 64);\n  f << dot(qd2) == (48*tau1 - 240*tau2 + 120*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 36*qd1*qd1*sin(2*q2) + 18*qd2*qd2*sin(2*q2) + 72*tau1*cos(q2) - 144*tau2*cos(q2) + 48*qd1*qd2*sin(q2) + 36*qd1*qd2*sin(2*q2))/(18*cos(2*q2) - 46);\n\n  ocp.subjectTo(f);\n  ocp.subjectTo(AT_START, q1 ==  bounds[0] );       \n\n  ocp.subjectTo(AT_START, q2 ==  bounds[1] );       \n\n  ocp.subjectTo(AT_START, qd1 ==  bounds[2] );\n  ocp.subjectTo(AT_START, qd2 ==  bounds[3] );\n\n  ocp.subjectTo(AT_END, q1 == bounds[4]);\n  ocp.subjectTo(AT_END, q2 == bounds[5]);\n  ocp.subjectTo(AT_END, qd1 == bounds[6]);\n  ocp.subjectTo(AT_END, qd2 == bounds[7]);\n\n  ocp.subjectTo(-400 <= tau1 <= 400);  // bounds on the control input u,\n  ocp.subjectTo(-400 <= tau2 <= 400);\n  //  -------------------------------------\n\n  // ---------PLOT FOR TESTING\n  // GnuplotWindow window;\n  // window.addSubplot(q1, \"q1\");\n  // window.addSubplot(q2, \"q2\");\n  // window.addSubplot(qd1, \"qd1\");\n  // window.addSubplot(qd2, \"qd2\");\n  // window.addSubplot(tau1, \"tau1\");\n  // window.addSubplot(tau2, \"tau2\");\n\n  OptimizationAlgorithm algorithm(ocp);     // the optimization algorithm\n  algorithm.set( DISCRETIZATION_TYPE , MULTIPLE_SHOOTING);\n  algorithm.set( INTEGRATOR_TYPE , INT_RK45);\n  algorithm.set( HESSIAN_APPROXIMATION   , BLOCK_BFGS_UPDATE);\n  algorithm.set( KKT_TOLERANCE   , 1e-4); \n  algorithm.set( ABSOLUTE_TOLERANCE, 1e-4);\n  algorithm.set( INTEGRATOR_TOLERANCE, 1e-4);\n  algorithm.set( MAX_NUM_ITERATIONS, 1000);\n  algorithm.set( MAX_NUM_INTEGRATOR_STEPS, 10000);\n\n  algorithm.set(PRINT_COPYRIGHT,BT_FALSE);\n  algorithm.set(PRINTLEVEL,LOW);\n  algorithm.set(PRINT_INTEGRATOR_PROFILE,BT_FALSE);\n  algorithm.set(PRINT_SCP_METHOD_PROFILE,BT_FALSE);\n  // algorithm << window;\n  algorithm.solve();                        // solves the problem.\n\n  algorithm.getDifferentialStates(\"states.txt\");\n  algorithm.getObjectiveValue(\"parameters.txt\");\n  algorithm.getControls(\"control.txt\");\n\n  clearAllStaticCounters();\n  return 0;\n}\n\nfloat rand_gen(float lim[2]) {\n    static boost::random::uniform_real_distribution<> dist(0, 1);\n    return lim[0] + dist(gen)*(lim[1] - lim[0]);\n}\n\nint main(int argc, char const *argv[])\n{\n  float q_lims[2] = {0.0,2*pi};\n  float qd_lims[2] = {-30.0,30.0};\n  float bounds[8] = {5.11906, 0.851226, 24.3475, 20.1005, 0.797881, 6.08757, 24.8026, -16.738};\n  // float bounds[8] = {rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims),rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims)};\n  cout << bounds[0] << \" \" << bounds[1] << \" \" << bounds[2] << \" \" << bounds[3] << \" \" << bounds[4] << \" \" << bounds[5] << \" \" << bounds[6] << \" \" << bounds[7] << endl;\n  bool success = test(bounds);\n  return 0;\n}\n", "meta": {"hexsha": "0894d8f07f99a665d50362773dc9a0fee4ba7e3b", "size": 3671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2link_direct/src/old/2link_final.cpp", "max_stars_repo_name": "DeepakParamkusam/learning-based-RRT", "max_stars_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T11:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-13T11:36:45.000Z", "max_issues_repo_path": "2link_direct/src/old/2link_final.cpp", "max_issues_repo_name": "DeepakParamkusam/learning-based-RRT", "max_issues_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2link_direct/src/old/2link_final.cpp", "max_forks_repo_name": "DeepakParamkusam/learning-based-RRT", "max_forks_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_forks_repo_licenses": ["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.3465346535, "max_line_length": 230, "alphanum_fraction": 0.6327976028, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.651879822111247}}
{"text": "#ifndef LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n#define LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n\n#include <queue>\n#include <sp_const.hpp>\n#include <Eigen/Dense>\n\nnamespace DynamicPlanning{\n    static int nChoosek(int n, int k){\n        if(k > n) return 0;\n        if(k * 2 > n) k = n-k;\n        if(k == 0) return 1;\n\n        int result = n;\n        for(int i = 2; i <= k; i++){\n            result *= (n-i+1);\n            result /= i;\n        }\n        return result;\n    }\n\n    static double getBernsteinBasis(int n, int i, double t_normalized){\n        return nChoosek(n, i) * pow(t_normalized, i) * pow(1-t_normalized, n - i);\n    }\n\n    static octomap::point3d getPointFromControlPoints(std::vector<octomap::point3d> control_points,\n                                                      double t_normalized){\n        octomap::point3d point;\n        double t = t_normalized;\n        if(t < 0 - SP_EPSILON || t > 1 + SP_EPSILON){\n            throw std::invalid_argument(\"[Polynomial] Input of getPointFromControlPoints is out of bound\");\n        }\n\n        int n_ctrl = (int)control_points.size() - 1;\n        double x = 0, y = 0, z = 0;\n        for(int i = 0; i < n_ctrl + 1; i++){\n            double b_i_n = getBernsteinBasis(n_ctrl, i, t_normalized);\n            x += control_points[i].x() * b_i_n;\n            y += control_points[i].y() * b_i_n;\n            z += control_points[i].z() * b_i_n;\n        }\n\n        point = octomap::point3d((float)x, (float)y, (float)z);\n        return point;\n    }\n\n    static double getPointFromControlPoints(std::vector<double> control_points, double t_normalized){\n        double t = t_normalized;\n        if(t < 0 - SP_EPSILON || t > 1 + SP_EPSILON){\n            throw std::invalid_argument(\"[Polynomial] Input of getPointFromControlPoints is out of bound\");\n        }\n\n        int n_ctrl = (int)control_points.size() - 1;\n        double x = 0;\n        for(int i = 0; i < n_ctrl + 1; i++){\n            double b_i_n = getBernsteinBasis(n_ctrl, i, t_normalized);\n            x += control_points[i] * b_i_n;\n        }\n\n        return x;\n    }\n\n    static dynamic_msgs::State getStateFromControlPoints(std::vector<std::vector<octomap::point3d>> control_points,\n                                                         double current_time, int M, int n, double dt){\n        dynamic_msgs::State state;\n        int m = static_cast<int>(current_time / dt);\n        if(m == M and current_time < M * dt + SP_EPSILON){\n            m = M - 1;\n        }\n        else if(m >= M){\n            throw std::invalid_argument(\"[Polynomial] Input of getOdom is out of bound\");\n        }\n\n        octomap::point3d position = getPointFromControlPoints(control_points[m], current_time/dt - m);\n        state.pose.position.x = position.x();\n        state.pose.position.y = position.y();\n        state.pose.position.z = position.z();\n\n        std::vector<octomap::point3d> velocity_points;\n        velocity_points.resize(n);\n        for(int i = 0; i < n; i++){\n            velocity_points[i] = (control_points[m][i+1] - control_points[m][i]) * n * pow(dt, -1);\n        }\n        octomap::point3d velocity = getPointFromControlPoints(velocity_points, current_time/dt - m);\n        state.velocity.linear.x = velocity.x();\n        state.velocity.linear.y = velocity.y();\n        state.velocity.linear.z = velocity.z();\n\n        std::vector<octomap::point3d> acceleration_points;\n        acceleration_points.resize(n-1);\n        for(int i = 0; i < n-1; i++){\n            acceleration_points[i] = (velocity_points[i+1] - velocity_points[i]) * (n-1) * pow(dt, -1);\n        }\n        octomap::point3d acceleration = getPointFromControlPoints(acceleration_points, current_time/dt - m);\n        state.acceleration.linear.x = acceleration.x();\n        state.acceleration.linear.y = acceleration.y();\n        state.acceleration.linear.z = acceleration.z();\n\n        std::vector<octomap::point3d> jerk_points;\n        jerk_points.resize(n-2);\n        for(int i = 0; i < n-2; i++){\n            jerk_points[i] = (acceleration_points[i+1] - acceleration_points[i]) * (n-2) * pow(dt, -1);\n        }\n        octomap::point3d jerk = getPointFromControlPoints(jerk_points, current_time/dt - m);\n\n        octomap::point3d thrust = acceleration + octomap::point3d(0, 0, 9.81); // add gravity\n\n        octomap::point3d z_body = thrust.normalized();\n        octomap::point3d x_world(1, 0, 0);\n        octomap::point3d y_body = (z_body.cross(x_world)).normalized();\n        octomap::point3d x_body = y_body.cross(z_body);\n\n        octomap::point3d jerk_orth_zbody = jerk - z_body * jerk.dot(z_body);\n        octomap::point3d h_w = jerk_orth_zbody * (1 / thrust.norm());\n        octomap::point3d omega(-h_w.dot(y_body), h_w.dot(x_body), 0); //TODO: yaw is 0\n        state.velocity.angular.x = omega.x();\n        state.velocity.angular.y = omega.y();\n        state.velocity.angular.z = omega.z();\n\n        return state;\n    }\n\n    static dynamic_msgs::State getStateFromControlPoints(std::vector<std::vector<octomap::point3d>> control_points,\n                                                         double current_time, int M, int n,\n                                                         std::vector<double> time_segments){\n        dynamic_msgs::State state;\n        int m = 0;\n        double t_normalized, segment_length, segment_start_time = 0;\n        bool is_time_end = false;\n        while(m < M and current_time > time_segments[m+1]){\n            segment_start_time = time_segments[m];\n            m++;\n        }\n        if(m == M){\n            m = M - 1;\n            segment_length = time_segments[m+1] - time_segments[m];\n            t_normalized = 1.0;\n            is_time_end = true;\n        }\n        else{\n            segment_length = time_segments[m+1] - time_segments[m];\n            t_normalized = (current_time - time_segments[m]) / segment_length;\n        }\n\n        octomap::point3d position = getPointFromControlPoints(control_points[m], t_normalized);\n        state.pose.position.x = position.x();\n        state.pose.position.y = position.y();\n        state.pose.position.z = position.z();\n\n        if(is_time_end){\n            return state;\n        }\n\n        std::vector<octomap::point3d> velocity_points;\n        velocity_points.resize(n);\n        for(int i = 0; i < n; i++){\n            velocity_points[i] = (control_points[m][i+1] - control_points[m][i]) * n * pow(segment_length, -1);\n        }\n        octomap::point3d velocity = getPointFromControlPoints(velocity_points, t_normalized);\n        state.velocity.linear.x = velocity.x();\n        state.velocity.linear.y = velocity.y();\n        state.velocity.linear.z = velocity.z();\n\n        std::vector<octomap::point3d> acceleration_points;\n        acceleration_points.resize(n-1);\n        for(int i = 0; i < n-1; i++){\n            acceleration_points[i] = (velocity_points[i+1] - velocity_points[i]) * (n-1) * pow(segment_length, -1);\n        }\n        octomap::point3d acceleration = getPointFromControlPoints(acceleration_points, t_normalized);\n        state.acceleration.linear.x = acceleration.x();\n        state.acceleration.linear.y = acceleration.y();\n        state.acceleration.linear.z = acceleration.z();\n\n        std::vector<octomap::point3d> jerk_points;\n        jerk_points.resize(n-1);\n        for(int i = 0; i < n-1; i++){\n            jerk_points[i] = (acceleration_points[i+1] - acceleration_points[i]) * (n-2) * pow(segment_length, -1);\n        }\n        octomap::point3d jerk = getPointFromControlPoints(jerk_points, t_normalized);\n\n        octomap::point3d thrust = acceleration + octomap::point3d(0, 0, 9.81); // add gravity\n\n        octomap::point3d z_body = thrust.normalized();\n        octomap::point3d x_world(1, 0, 0);\n        octomap::point3d y_body = (z_body.cross(x_world)).normalized();\n        octomap::point3d x_body = y_body.cross(z_body);\n\n        octomap::point3d jerk_orth_zbody = jerk - z_body * jerk.dot(z_body);\n        octomap::point3d h_w = jerk_orth_zbody * (1 / thrust.norm());\n        octomap::point3d omega(-h_w.dot(y_body), h_w.dot(x_body), 0); //TODO: yaw is 0\n        state.velocity.angular.x = omega.x();\n        state.velocity.angular.y = omega.y();\n        state.velocity.angular.z = omega.z();\n\n        return state;\n    }\n\n    static std::vector<octomap::point3d> bernsteinFitting(std::vector<octomap::point3d> target_points,\n                                                          std::vector<double> ts_normalized){\n        int n = (int)target_points.size() - 1;\n        Eigen::MatrixXd B = Eigen::MatrixXd(n+1, n+1);\n        for(int i = 0; i < n + 1; i++){\n            for(int j = 0; j < n + 1; j++){\n                B(i, j) = getBernsteinBasis(n, j, ts_normalized[i]);\n            }\n        }\n\n        Eigen::MatrixXd X = Eigen::MatrixXd(n+1, 3);\n        for(int i = 0; i < n + 1; i++){\n            X(i, 0) = target_points[i].x();\n            X(i, 1) = target_points[i].y();\n            X(i, 2) = target_points[i].z();\n        }\n\n        Eigen::MatrixXd C = B.inverse() * X;\n        std::vector<octomap::point3d> control_points;\n        control_points.resize(n+1);\n        for(int i = 0; i < n + 1; i++){\n            control_points[i] = octomap::point3d(C(i, 0), C(i, 1), C(i, 2));\n        }\n        return control_points;\n    }\n\n    static int coef_derivative(int n, int phi){\n        if(n < phi){\n            return 0;\n        }\n\n        int coef = 1;\n        for(int i = 0; i < phi; i++){\n            coef *= n - i;\n        }\n        return coef;\n    }\n\n    struct BisectionElement{\n        double c;\n        int k;\n        Eigen::VectorXd coef;\n    };\n\n    // return list of [a,b] includes one real root of polynomial which coefficient is coef\n    static std::vector<std::pair<double, double>> realRootIsolation(const Eigen::VectorXd& coef, int n) {\n        std::queue<BisectionElement> L;\n        L.push(BisectionElement{0, 0, coef});\n        std::vector<std::pair<double, double>> Isol;\n        int n_poly = 2 * n - 1;\n\n        while (not L.empty()) {\n            BisectionElement current_element = L.front();\n            L.pop();\n//                std::cout << \"current_coef: \" << std::endl << current_element.coef << std::endl;\n            if (current_element.coef(0) == 0) {\n                for (int i = 0; i < n_poly; i++) {\n                    current_element.coef(i) = current_element.coef(0, i + 1);\n                }\n                current_element.coef(n_poly) = 0;\n                n_poly--;\n                Isol.emplace_back(std::make_pair(current_element.c / pow(2, current_element.k),\n                                                 current_element.c / pow(2, current_element.k)));\n            }\n\n            Eigen::VectorXd coef_test = Eigen::VectorXd::Zero(n_poly + 1);\n            for (int i = 0; i < n_poly + 1; i++) {\n                for (int j = 0; j < n_poly + 1 - i; j++) {\n                    coef_test(j) += current_element.coef(i) * nChoosek(n_poly - i, j);\n                }\n            }\n//                std::cout << \"coef_test: \" << std::endl << coef_test << std::endl;\n            int var = 0;\n            for (int i = 0; i < n_poly; i++) {\n                if (coef_test(i) * coef_test(i + 1) < 0) {\n                    var++;\n                }\n            }\n            if (var == 1) {\n                Isol.emplace_back(std::make_pair(current_element.c / pow(2, current_element.k),\n                                                 (current_element.c + 1) / pow(2, current_element.k)));\n            }\n            if (var > 1) {\n                Eigen::VectorXd coef1 = current_element.coef;\n                for (int i = 0; i < n_poly + 1; i++) {\n                    coef1(i) *= pow(2, n_poly - i);\n                }\n//                    std::cout << \"coef1: \" << std::endl << coef1 << std::endl;\n                L.push(BisectionElement{2 * current_element.c, current_element.k + 1, coef1});\n\n                Eigen::VectorXd coef2 = Eigen::VectorXd::Zero(n_poly + 1);\n                for (int i = 0; i < n_poly + 1; i++) {\n                    for (int j = 0; j < i + 1; j++) {\n                        coef2(j) += current_element.coef(i) * pow(2, n_poly - i) * nChoosek(i, j);\n                    }\n                }\n//                    std::cout << \"coef2: \" << std::endl << coef2 << std::endl;\n                L.push(BisectionElement{2 * current_element.c + 1, current_element.k + 1, coef2});\n            }\n        }\n        return Isol;\n    }\n\n    static double evalPoly(const Eigen::VectorXd& coef, double t){\n        double ret = 0;\n        for(int i = 0; i < coef.size(); i++){\n            ret += coef(i) * pow(t, i);\n        }\n        return ret;\n    }\n\n    // pi_i = obstacle position, pi_j = agent_position\n    static double distanceBetweenPolys(const std::vector<octomap::point3d>& control_points_agent,\n                                       const std::vector<octomap::point3d>& control_points_obs,\n                                       const Eigen::MatrixXd& B,\n                                       double poly_root_tolerance,\n                                       octomap::point3d& closest_point) {\n        if(control_points_agent.size() != control_points_obs.size()){\n            throw std::invalid_argument(\"[Polynomial] degree of two polynomials are not same.\");\n        }\n\n        int n = (int)control_points_agent.size() - 1;\n        int dim = 3;\n\n        //get control points of relative trajectory\n        std::vector<octomap::point3d> control_points_rel;\n        control_points_rel.resize(n + 1);\n        for(int i = 0; i < n + 1; i++){\n            control_points_rel[i].x() = control_points_agent[i].x() - control_points_obs[i].x();\n            control_points_rel[i].y() = control_points_agent[i].y() - control_points_obs[i].y();\n            control_points_rel[i].z() = control_points_agent[i].z() - control_points_obs[i].z();\n        }\n\n        Eigen::MatrixXd control_points_rel_mtx = Eigen::MatrixXd::Zero(dim, n + 1);\n        for(int j = 0; j < n + 1; j++){\n            control_points_rel_mtx(0, j) = control_points_rel[j].x();\n            control_points_rel_mtx(1, j) = control_points_rel[j].y();\n            control_points_rel_mtx(2, j) = control_points_rel[j].z();\n        }\n\n        // convert to coef of standard basis\n        Eigen::MatrixXd coef = control_points_rel_mtx * B;\n\n        // get derivative of coef\n        Eigen::MatrixXd coef_derivative = Eigen::MatrixXd::Zero(dim, n + 1);\n        for(int j = 0; j < n; j++){\n            coef_derivative(0, j) = (j + 1) * coef(0, j + 1);\n            coef_derivative(1, j) = (j + 1) * coef(1, j + 1);\n            coef_derivative(2, j) = (j + 1) * coef(2, j + 1);\n        }\n\n        // coef dot coef_derivative\n        Eigen::VectorXd coef_g = Eigen::VectorXd::Zero(2 * n);\n        for(int j0 = 0; j0 < n + 1; j0++){\n            for(int j1 = 0; j1 < n; j1++){\n                for(int k = 0; k < dim; k++) {\n                    coef_g(j0 + j1) += coef(k, j0) * coef_derivative(k, j1);\n                }\n            }\n        }\n\n        // real root isolation\n        std::vector<std::pair<double, double>> Isol = realRootIsolation(coef_g, n);\n\n        // compute closest point by Newton method\n        bool isClosestPointInSection = false;\n        double a, b, m, g_m, t_cand, dist_cand;\n        double dist_closest = SP_INFINITY;\n        octomap::point3d p_cand;\n        for(auto section : Isol){\n            a = section.first;\n            b = section.second;\n            if(evalPoly(coef_g, a) < 0 and evalPoly(coef_g, b) > 0) {\n                while (true) {\n                    if (b - a < poly_root_tolerance) {\n                        t_cand = (a + b) / 2;\n                        break;\n                    }\n                    m = (a + b) / 2;\n                    g_m = evalPoly(coef_g, m);\n                    if (g_m == 0) {\n                        t_cand = m;\n                        break;\n                    } else if (g_m < 0) {\n                        a = m;\n                    } else {\n                        b = m;\n                    }\n                }\n                p_cand = getPointFromControlPoints(control_points_rel, t_cand);\n                dist_cand = p_cand.norm();\n                if(dist_cand < dist_closest){\n                    closest_point = p_cand;\n                    dist_closest = dist_cand;\n//                        t_normalized_closest = t_cand;\n                    isClosestPointInSection = true;\n                }\n            }\n        }\n        if(not isClosestPointInSection){\n            if(control_points_rel[0].norm() < control_points_rel[n].norm()){\n                closest_point = control_points_rel[0];\n//                    t_normalized_closest = 0;\n            }\n            else{\n                closest_point = control_points_rel[n];\n//                    t_normalized_closest = 1;\n            }\n        }\n\n        return closest_point.norm();\n//            // Exception handle for first segment\n//            if(m == 0 && p_closest.norm() < d[0] - SP_EPSILON_FLOAT){\n//                p_closest = control_points_rel[0];\n//            }\n    }\n\n    static void buildBernsteinBasis(int n, Eigen::MatrixXd& B, Eigen::MatrixXd& B_inv) {\n        B = Eigen::MatrixXd::Zero(n + 1, n + 1);\n        for(int i = 0; i < n + 1; i++){\n            for(int j = 0; j < n + 1; j++){\n                if(j >= i){\n                    B(i,j) = nChoosek(n, i) * nChoosek(n-i, n-j) * pow(-1, j-i);\n                }\n                else{\n                    B(i,j) = 0;\n                }\n            }\n        }\n        B_inv = B.inverse();\n    }\n\n    static std::vector<octomap::point3d> subdivisionBernsteinCurve(\n            const std::vector<octomap::point3d>& control_points, double a, double b,\n            const Eigen::MatrixXd& B,  const Eigen::MatrixXd& B_inv){\n        size_t n = control_points.size() - 1;\n        Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n        for(int i = 0; i < n + 1; i++){\n            for(int j = 0; j < i + 1; j++){\n                A(i, j) = nChoosek(i, j) * pow(a, j) * pow(b, i - j);\n            }\n        }\n\n        Eigen::MatrixXd c_tr = Eigen::MatrixXd::Zero(3, n + 1);\n        for(int k = 0; k < 3; k++){\n            for(int i = 0; i < n + 1; i++){\n                c_tr(k, i) = control_points[i](k);\n            }\n        }\n        c_tr = c_tr * B * A * B_inv;\n\n        std::vector<octomap::point3d> control_points_tr;\n        control_points_tr.resize(n + 1);\n        for(int i = 0; i < n + 1; i++){\n            control_points_tr[i] = octomap::point3d(c_tr(0, i), c_tr(1, i), c_tr(2, i));\n        }\n        return control_points_tr;\n    }\n}\n#endif //LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n", "meta": {"hexsha": "17085b7f40656da6f54ff3c75b2ade3d16981440", "size": 18622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polynomial.hpp", "max_stars_repo_name": "dabinkim-LGOM/lsc_planner", "max_stars_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T15:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:34:13.000Z", "max_issues_repo_path": "include/polynomial.hpp", "max_issues_repo_name": "dabinkim-LGOM/lsc_planner", "max_issues_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_issues_repo_licenses": ["MIT"], "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/polynomial.hpp", "max_forks_repo_name": "dabinkim-LGOM/lsc_planner", "max_forks_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T11:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T05:24:33.000Z", "avg_line_length": 40.6593886463, "max_line_length": 115, "alphanum_fraction": 0.5202448717, "num_tokens": 4800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6518798203856876}}
{"text": "/* test_student_t.cpp\n *\n * Copyright Steven Watanabe 2011\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 * $Id: test_student_t.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/student_t_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::student_t_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME student_t\n#define BOOST_MATH_DISTRIBUTION boost::math::students_t\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME n\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "09385257bb226b19c1d0000a466577b112f17bd0", "size": 848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_student_t.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_student_t.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "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": "libs/random/test/test_student_t.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "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": 33.92, "max_line_length": 75, "alphanum_fraction": 0.8054245283, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6517872812800461}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// Test code for a real operator.\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include \"blas/generic_vector.h\"\n#include \"inverters/generic_cg.h\"\n#include \"inverters/generic_ca_cg.h\"\n\n#include \"square_laplace.h\"\n\nusing namespace std; \n\n\n// Prepare vectors for various tests.\nvoid reset_vectors(complex<double>* rhs, complex<double>* lhs, complex<double>* check, int length)\n{\n  zero_vector(lhs, length*length);\n  zero_vector(rhs, length*length);\n  rhs[length/2+(length/2)*length] = 1.0; // set a point on rhs.\n  zero_vector(check, length*length);\n}\n\n\nint main(int argc, char** argv)\n{  \n    //double *lattice; // Holds the gauge field.\n  complex<double> *lhs, *rhs, *check; // For some Kinetic terms.\n  complex<double> *gauge_links; \n  double explicit_resid = 0.0;\n  double bnorm = 0.0;\n  inversion_info invif;\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n\n  // Basic information about the lattice.\n  int length = 32;\n  double m_sq = 0.01;\n  double inv_variance = 6.0; // inverse of variance for gaussian non-compact U(1) links.\n  \n  // Create a random compact U(1) link.\n  gauge_links = allocate_vector<complex<double>>(2*length*length);\n  \n  // Remark: fills real and imaginary with gaussian numbers.\n  gaussian(gauge_links, 2*length*length, generator, 1.0/inv_variance);\n  polar(gauge_links, 2*length*length); // ignores imag part to make compact link.\n  \n  \n  // Structure which gets passed to the function.\n  laplace_gauged_struct lapstr;\n  lapstr.length = length;\n  lapstr.m_sq = m_sq;\n  lapstr.gauge_links = gauge_links; \n  \n  // Parameters related to solve.\n  double tol = 1e-8;\n  int max_iter = 200;\n  //double minres_relaxation_param = 0.8;\n  //double richardson_relaxation_param = 0.2;\n  //int restart_freq = 64; // for restarted solves. \n  //int bicgstabl = 8; // L for, well, BiCGstab-L. \n  \n  // Some start-up.\n  int volume = length*length;\n  \n  //lattice = allocate_vector<double>(2*volume);  // Gauge field eventually.\n  \n  // Vectors. \n  lhs = allocate_vector<complex<double>>(volume);\n  rhs = allocate_vector<complex<double>>(volume);\n  check = allocate_vector<complex<double>>(volume);\n  \n  // Zero out vectors, set rhs point.\n  // zero_vector(lattice, 2*volume);\n  reset_vectors(rhs, lhs, check, length);\n  \n  // Get norm for rhs.\n  bnorm = sqrt(norm2sq(rhs, volume));\n\n  printf(\"Solving A [lhs] = [rhs] for lhs, using a point source. Single mass test: m^2 = %f.\\n\\n\", m_sq);\n\n  /****************\n  * NORMAL SOLVES *\n  ****************/\n  \n  // lhs = A^(-1) rhs\n  // Arguments:\n  // 1: lhs\n  // 2: rhs\n  // 3: size of vector\n  // 4: maximum iterations\n  // 5: residual\n  // 5a for gcr_restart: how often to restart.\n  // 5b for richardson, minres: overrelaxation parameter (can leave this out, assumes 1)\n  // 5c for richardson: how often to check the residual\n  // 6: function pointer\n  // 7: \"extra data\": \n  // 8: optional, verbosity information.\n\n  inversion_verbose_struct verb(VERB_DETAIL, \"Details: \");\n\n  /* CG */\n  reset_vectors(rhs, lhs, check, length);\n  invif = minv_vector_cg(lhs, rhs, volume, max_iter, tol, square_laplacian_gauged, &lapstr, &verb);\n  if (invif.success == true)\n  {\n    printf(\"Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n  }\n  else // failed, maybe.\n  {\n    printf(\"Potential error! Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n  }\n  printf(\"Computing [check] = A [lhs] as a confirmation.\\n\");\n  // Check and make sure we get the right answer.\n  square_laplacian_gauged(check, lhs, &lapstr);\n  explicit_resid = sqrt(diffnorm2sq(rhs, check, volume))/bnorm; // sqrt(|rhs - check|^2)/bnorm\n  printf(\"[check] should equal [rhs]. The residual is %15.20e.\\n\\n\", explicit_resid);\n  \n\n  /* CA-CG */\n  for (int ca_s = 2; ca_s <= 10; ca_s++)\n  {\n    reset_vectors(rhs, lhs, check, length);\n    invif = minv_vector_ca_cg(lhs, rhs, volume, max_iter, tol, ca_s, square_laplacian_gauged, &lapstr, &verb);\n    if (invif.success == true)\n    {\n      printf(\"Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    else // failed, maybe.\n    {\n      printf(\"Potential error! Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    printf(\"Computing [check] = A [lhs] as a confirmation.\\n\");\n    // Check and make sure we get the right answer.\n    square_laplacian_gauged(check, lhs, &lapstr);\n    explicit_resid = sqrt(diffnorm2sq(rhs, check, volume))/bnorm; // sqrt(|rhs - check|^2)/bnorm\n    printf(\"[check] should equal [rhs]. The residual is %15.20e.\\n\\n\", explicit_resid);\n  }\n  \n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  // Free the lattice.\n  //delete[] lattice;\n  deallocate_vector(&lhs);\n  deallocate_vector(&rhs);\n  deallocate_vector(&check);\n  deallocate_vector(&gauge_links); \n  return 0;\n}\n\n\n", "meta": {"hexsha": "d1975db915b09445f9e61452546977ca2362e007", "size": 5201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/n07_ca_cg/square_laplace_ca_cg.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "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/n07_ca_cg/square_laplace_ca_cg.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/n07_ca_cg/square_laplace_ca_cg.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["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.7134146341, "max_line_length": 154, "alphanum_fraction": 0.6683330129, "num_tokens": 1525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6517621670968525}}
{"text": "#include <algorithm>\n#include <chrono>\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <random>\n#include <string>\n#include <vector>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\n#include <mkl_cblas.h>\n\n/// helper functions\ntemplate <typename ForwardIt> void fill_random(ForwardIt begin, ForwardIt end) {\n\tstd::random_device rndDev;\n\tstd::mt19937 rndEng{rndDev()};\n\tusing T = typename std::iterator_traits<ForwardIt>::value_type;\n\tstd::uniform_real_distribution<T> dist{-1.0, 1.0};\n\n\tstd::generate(begin, end, [&] { return dist(rndEng); });\n}\n\ntemplate <typename T> auto timed(T&& f) {\n\tconst auto starttime = std::chrono::high_resolution_clock::now();\n\tf();\n\treturn std::chrono::duration<double>{\n\t    std::chrono::high_resolution_clock::now() - starttime}\n\t    .count();\n}\n\ntemplate <typename Map>[[noreturn]] void failInvalidArgs(const Map& modes) {\n\tstd::cerr << \"invalid args!\\nusage: prog \"\n\t          << boost::algorithm::join(\n\t                 modes | boost::adaptors::transformed(\n\t                             [](const auto& p) { return p.first; }),\n\t                 \"|\")\n\t          << \"\\n\";\n\tstd::exit(EXIT_FAILURE);\n}\n\n/// gemm implementations\ntemplate <typename T>\nvoid serialIkj(const T* a, const T* b, T* c, std::size_t aRows,\n               std::size_t aCols, std::size_t bCols) {\n\tfor (std::size_t i{0}; i < aRows; ++i) {\n\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate <typename T>\nvoid serialIjk(const T* a, const T* b, T* c, std::size_t aRows,\n               std::size_t aCols, std::size_t bCols) {\n\tfor (std::size_t i{0}; i < aRows; ++i) {\n\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate <typename T>\nvoid parallelGemm(const T* a, const T* b, T* c, std::size_t aRows,\n                  std::size_t aCols, std::size_t bCols) {\n// use std::for_each(std::execution::par, ... ) in\n// C++17 instead\n#pragma omp parallel for\n\tfor (std::size_t i = 0; i < aRows; ++i) {\n\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\n// float overload\nvoid blasGemm(const float* a, const float* b, float* c, std::size_t aRows,\n              std::size_t aCols, std::size_t bCols) {\n\tconst auto m = aRows;\n\tconst auto k = aCols;\n\tconst auto n = bCols;\n\tconst float alf = 1;\n\tconst float bet = 0;\n\n\tcblas_sgemm(CblasRowMajor, // CBLAS_LAYOUT layout,\n\t            CblasNoTrans,  // CBLAS_TRANSPOSE TransA,\n\t            CblasNoTrans,  // CBLAS_TRANSPOSE TransB,\n\t            m,             // const int M,\n\t            n,             // const int N,\n\t            k,             // const int K,\n\t            alf,           // const float alpha,\n\t            a,             // const float *A,\n\t            k,             // const int lda,\n\t            b,             // const float *B,\n\t            n,             // const int ldb,\n\t            bet,           // const float beta,\n\t            c,             // float *C,\n\t            n              // const int ldc\n\t            );\n}\n\n// double overload\nvoid blasGemm(const double* a, const double* b, double* c, std::size_t aRows,\n              std::size_t aCols, std::size_t bCols) {\n\tconst auto m = aRows;\n\tconst auto k = aCols;\n\tconst auto n = bCols;\n\tconst double alf = 1;\n\tconst double bet = 0;\n\n\tcblas_dgemm(CblasRowMajor, // CBLAS_LAYOUT layout,\n\t            CblasNoTrans,  // CBLAS_TRANSPOSE TransA,\n\t            CblasNoTrans,  // CBLAS_TRANSPOSE TransB,\n\t            m,             // const int M,\n\t            n,             // const int N,\n\t            k,             // const int K,\n\t            alf,           // const double alpha,\n\t            a,             // const double *A,\n\t            k,             // const int lda,\n\t            b,             // const double *B,\n\t            n,             // const int ldb,\n\t            bet,           // const double beta,\n\t            c,             // double *C,\n\t            n              // const int ldc\n\t            );\n}\n\nint main(int argc, char* argv[]) {\n\tusing Real = float;\n\tusing gemmFuncType = void(const Real*, const Real*, Real*, std::size_t,\n\t                          std::size_t, std::size_t);\n\tusing gemmFuncPrtType = void (*)(const Real*, const Real*, Real*,\n\t                                 std::size_t, std::size_t, std::size_t);\n\n\t// this map manages all implementations\n\tstd::map<std::string, std::function<gemmFuncType>> modes{\n\t    {\"serialikj\", &serialIkj<Real>},\n\t    {\"serialijk\", &serialIjk<Real>},\n\t    {\"parallel\", &parallelGemm<Real>},\n\t    {\"blas\", static_cast<gemmFuncPrtType>(&blasGemm)}};\n\n\t// validate cmd args and select gemm implementation\n\tif (argc != 2) { failInvalidArgs(modes); }\n\tconst std::string modeArg = argv[1];\n\tif (modes.count(modeArg) != 1) { failInvalidArgs(modes); }\n\tconst auto gemm = modes[modeArg];\n\n\t// benchmark sizes\n\tconst auto minSize = 2u;\n\tconst auto maxSize = 2048u;\n\tconst auto maxRepetitions = 2048u;\n\n\t// do measurements with increasing matrix dimensions and decreasing\n\t// repetitions to keep wall clock time short\n\tstd::size_t repetitions{};\n\tstd::size_t size{};\n\tfor (size = minSize, repetitions = maxRepetitions; size <= maxSize;\n\t     size *= 2, repetitions /= 2) {\n\n\t\t/// set up data\n\t\tconst auto aRows = size;\n\t\tconst auto aCols = size;\n\t\tconst auto bRows = size;\n\t\tconst auto bCols = size;\n\n\t\tstd::vector<Real> a(aRows * aCols); // m * k\n\t\tstd::vector<Real> b(bRows * bCols); // k * n\n\t\tstd::vector<Real> c(aRows * bCols); // m * n\n\n\t\tfill_random(std::begin(a), std::end(a));\n\t\tfill_random(std::begin(b), std::end(b));\n\n\t\t// create reference solution matrix using serialIkj\n\t\tstd::vector<Real> reference(c.size());\n\t\tserialIkj(a.data(), b.data(), reference.data(), aRows, aCols, bCols);\n\n\t\t/// warm up the caches\n\t\tgemm(a.data(), b.data(), c.data(), aRows, aCols, bCols);\n\n\t\t/// timed computations\n\t\tauto time = 0.0;\n\t\tfor (std::size_t r{0}; r < repetitions; ++r) {\n\t\t\tstd::fill(std::begin(c), std::end(c), 0);\n\t\t\ttime += timed([&]() {\n\t\t\t\tgemm(a.data(), b.data(), c.data(), aRows, aCols, bCols);\n\t\t\t});\n\n\t\t\t// validate the result c\n\t\t\tif (!std::equal(std::begin(c), std::end(c), std::begin(reference),\n\t\t\t                std::end(reference),\n\t\t\t                [](const Real& l, const Real& r) {\n\t\t\t\t                return std::abs(l - r) < 1.0e-3;\n\t\t\t\t            })) {\n\t\t\t\tstd::cerr << \"validation error!\\n\";\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t}\n\t\ttime /= repetitions; // get avg time per call\n\n\t\tstd::cout << size << \";\" << time << '\\n';\n\t}\n}", "meta": {"hexsha": "e68816e1057edbbb259ce1349537a8addd3d1d38", "size": 6771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gemm/mklblas/main.cpp", "max_stars_repo_name": "pengdada/dense_linear_algebra", "max_stars_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "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": "gemm/mklblas/main.cpp", "max_issues_repo_name": "pengdada/dense_linear_algebra", "max_issues_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "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": "gemm/mklblas/main.cpp", "max_forks_repo_name": "pengdada/dense_linear_algebra", "max_forks_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "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": 32.2428571429, "max_line_length": 80, "alphanum_fraction": 0.5499926156, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6517621562087963}}
{"text": "#include <libv/core/miscmath.hpp>\n#include <libv/lma/lma.hpp>\n#include <libv/graphic/viewer_context.hpp>\n#include <libv/geometry/rotation.hpp>\n\n#include <GL/gl.h>\n#include <boost/function.hpp>\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n\n  template<class T> using vector = std::vector<T,Eigen::aligned_allocator<T>>;\n  using namespace Eigen;\n  using namespace lma;\n\n  Vector3d on_sphere(double theta, double phi, double r)\n  {\n    return {r*std::cos(theta)*std::cos(phi),\n           r*std::cos(theta)*std::sin(phi),\n           r*std::sin(theta)};\n  }\n\n  auto draw_points = [](auto& points, auto& rotate)\n  {\n    v::viewer(0).layer(2).clear().pen_color(v::red).pen_width(3).point_style(v::Round).add_opengl([&]()\n    {\n      glBegin(GL_POINTS);\n      for(auto& p : points)\n        glVertex3dv((rotate*p).eval().data());\n      glEnd();\n    }).update();\n  };\n\n  auto draw_sphere = [](auto& sphere, auto& rotate)\n  {\n    v::viewer(0).layer(1).clear().pen_color(v::blue).pen_width(1).point_style(v::Round).add_opengl([&]()\n    {\n      for(double theta = -M_PI/2.0 ; theta < M_PI/2.0 ; theta+=0.1)\n      {\n        glBegin(GL_LINE_LOOP);\n        for(double phi = -M_PI ; phi < M_PI ; phi+=0.1)\n          glVertex3dv((rotate*on_sphere(theta,phi,sphere[3])).eval().data());\n        glEnd();\n      }\n\n      for(double phi = -M_PI ; phi < M_PI ; phi+=0.1)\n      {\n        glBegin(GL_LINE_STRIP);\n          for(double theta = -M_PI/2.0 ; theta < M_PI/2.0 ; theta+=0.1)\n         glVertex3dv((rotate*on_sphere(theta,phi,sphere[3])).eval().data());\n        glEnd();\n      }\n    }).update();\n  };\n\n  enum State { before, after0, after1, after2 };\n\n  auto draw_text = [](State state)\n  {\n    std::string str = \"\";\n    if (state == after0)\n      str = \"  Optimise Sphere\";\n    if (state == after1)\n      str = \"  Optimise Sphere + Points 3D\";\n    else if(state == after2)\n     str =\"  Optimise Sphere + Points 3D + Contrainte\";\n    v::viewer(0).layer(0).clear().pen_color(v::red).font_size(30).font_style(v::Bold).add_text(40,50,str).update();\n  };\n\n  void draw(Vector4d& sphere, vector<Vector3d>& points, State& state)\n  {\n    v::start_viewers();\n    v::set_interval(5);\n    Matrix3d rotate = Matrix3d::Identity();\n\n    for(;;)\n    {\n      v::apply_rotation(rotate,{0.0,0.0,0.001});\n      draw_text(state);\n      draw_sphere(sphere,rotate);\n      draw_points(points,rotate);\n      \n      v::tempo(5);\n    }\n  };\n\n\n//---------------------------------------------------------------------------------------------------------\n//---------------------------------------------------------------------------------------------------------\n\n  auto optimise = [](Vector4d& sphere, vector<Vector3d>& points, const vector<Vector3d>& refs, int mode)\n  {\n    \n    struct DistanceToSphere1\n    {\n      const Vector3d& point;\n      DistanceToSphere1(const Vector3d& point_):point(point_){}\n\n      bool operator()(const Vector4d& sphere, double& error) const\n      {\n        error = (sphere.head<3>()-point).norm() - sphere[3];\n        return true;\n      }\n    };\n\n    struct DistanceToSphere\n    {\n      bool operator()(const Vector4d& sphere, const Vector3d& point, double& error) const\n      {\n        error = (sphere.head<3>()-point).norm() - sphere[3];\n        return true;\n      }\n    };\n\n    struct DistanceTo3DPoint\n    {\n      const Vector3d& ref;\n      DistanceTo3DPoint(const Vector3d& ref_):ref(ref_){}\n\n      bool operator()(const Vector3d& point, double& error) const\n      {\n        error = (ref - point).norm();\n        return true;\n      }\n    };\n\n    Solver<DistanceToSphere1,DistanceToSphere,DistanceTo3DPoint> solver(1,50);\n\n    if (mode==0)\n    for(Vector3d& p : points)\n      solver.add(DistanceToSphere1(p),&sphere);\n\n    if (mode>0)\n    for(Vector3d& p : points)\n      solver.add(DistanceToSphere(),&sphere,&p);\n\n    if (mode==2)\n    for(size_t i = 0 ; i < refs.size() ; ++i)\n      solver.add(DistanceTo3DPoint(refs[i]),&points[i]);\n\n    solver.solve(DENSE_SCHUR,enable_verbose_output());\n  };\n\n//---------------------------------------------------------------------------------------------------------\n//---------------------------------------------------------------------------------------------------------\n\n\nint main()\n{\n  v::viewer(0).size(800,660);\n  Vector4d sphere;\n  sphere << 0,0,0,100;\n\n  vector<Vector3d> points,refs;\n\n  for(double theta = -M_PI/2.0 ; theta < M_PI/2.0 ; theta+=0.1)\n    for(double phi = -M_PI ; phi < M_PI ; phi+=0.1)\n      points.emplace_back(\n        on_sphere(theta,phi,sphere[3])\n        );\n\n  refs = points;\n\n  for(auto& p : points) p += Vector3d::Random()*50.0;\n\n  sphere << 0,0,0,50;\n\n  State state = before;\n  boost::thread th(boost::bind(draw,boost::ref(sphere),boost::ref(points),boost::ref(state)));\n\n\n\n  getchar();\n  optimise(sphere,points,refs,0);\n\n  state = after0;\n  getchar();\n  optimise(sphere,points,refs,1);\n  state = after1;\n  getchar();\n  optimise(sphere,points,refs,2);\n  state = after2;\n\n  v::wait_viewers();\n  th.interrupt();\n  th.join();\n\n  return 0;\n}", "meta": {"hexsha": "904e8e9adb984c0a5a74a3a085b9b0a62baf76d0", "size": 5006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/animate_sphere/src/main.cpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "examples/animate_sphere/src/main.cpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "examples/animate_sphere/src/main.cpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 26.6276595745, "max_line_length": 115, "alphanum_fraction": 0.5453455853, "num_tokens": 1372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6517463517953106}}
{"text": "#pragma once\n\n#include \"constants.hpp\"\n#include \"EcosWrapper.hpp\"\n#include <Eigen/Dense>\n\n\nclass model_simple_4th_order {\npublic:\n\n    static constexpr size_t n_states = 4;\n    static constexpr size_t n_inputs = 1;\n    static string get_name(){ return \"model_simple_4th_order\"; }\n\n    using StateVector   = Eigen::Matrix<double, n_states,        1>;\n    using ControlVector = Eigen::Matrix<double, n_inputs,        1>;\n    using StateMatrix   = Eigen::Matrix<double, n_states, n_states>;\n    using ControlMatrix = Eigen::Matrix<double, n_states, n_inputs>;\n\n    double total_time_guess() { return 3; }\n\n    void initialize(Eigen::Matrix<double, n_states, K> &X, Eigen::Matrix<double, n_inputs, K> &U);\n\n    StateVector                ode(const StateVector &x, const ControlVector &u);\n    StateMatrix     state_jacobian(const StateVector &x, const ControlVector &u);\n    ControlMatrix control_jacobian(const StateVector &x, const ControlVector &u);\n    \n    void add_application_constraints(optimization_problem::SecondOrderConeProgram &socp);\n    \n    StateVector get_random_state();\n    ControlVector get_random_input();\n\n};", "meta": {"hexsha": "a570de24934ad1bcb5561321c1d3cdc270cd60ef", "size": 1126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/model_simple_4th_order.hpp", "max_stars_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_stars_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T13:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T16:50:13.000Z", "max_issues_repo_path": "include/model_simple_4th_order.hpp", "max_issues_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_issues_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_issues_repo_licenses": ["MIT"], "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/model_simple_4th_order.hpp", "max_forks_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_forks_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T10:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T06:27:22.000Z", "avg_line_length": 34.1212121212, "max_line_length": 98, "alphanum_fraction": 0.7104795737, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6516767873373002}}
{"text": "#include \"dynet/nodes.h\"\n#include \"dynet/dynet.h\"\n#include \"dynet/training.h\"\n#include \"dynet/expr.h\"\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\nusing namespace dynet;\nusing namespace dynet::expr;\n\nint main(int argc, char** argv) {\n  dynet::initialize(argc, argv);\n\n  // parameters\n  const unsigned HIDDEN_SIZE = 8;\n  Model m;\n  SimpleSGDTrainer sgd(&m);\n  //MomentumSGDTrainer sgd(&m);\n\n  ComputationGraph cg;\n\n  Parameter p_W, p_b, p_V, p_a;\n  if (argc == 2) {\n    ifstream in(argv[1]);\n    boost::archive::text_iarchive ia(in);\n    ia >>  m >> p_W >> p_b >> p_V >> p_a;\n  }\n  else {\n    p_W = m.add_parameters({HIDDEN_SIZE, 2});\n    p_b = m.add_parameters({HIDDEN_SIZE});\n    p_V = m.add_parameters({1, HIDDEN_SIZE});\n    p_a = m.add_parameters({1});\n  }\n\n  Expression W = parameter(cg, p_W);\n  Expression b = parameter(cg, p_b);\n  Expression V = parameter(cg, p_V);\n  Expression a = parameter(cg, p_a);\n\n  vector<float> x_values(2);  // set x_values to change the inputs to the network\n  Expression x = input(cg, {2}, &x_values);\n  dynet::real y_value;  // set y_value to change the target output\n  Expression y = input(cg, &y_value);\n\n  Expression h = tanh(W*x + b);\n  Expression y_pred = logistic(V*h + a);\n  Expression loss_expr = binary_log_loss(y_pred, y);\n\n  cg.print_graphviz();\n\n  // train the parameters\n  for (unsigned iter = 0; iter < 2000; ++iter) {\n    double loss = 0;\n    for (unsigned mi = 0; mi < 4; ++mi) {\n      bool x1 = mi % 2;\n      bool x2 = (mi / 2) % 2;\n      x_values[0] = x1 ? 1 : 0;\n      x_values[1] = x2 ? 1 : 0;\n      y_value = (x1 != x2) ? 1 : 0;\n      loss += as_scalar(cg.forward(loss_expr));\n      cg.backward(loss_expr);\n      sgd.update(1.0);\n    }\n    sgd.update_epoch();\n    loss /= 4;\n    cerr << \"E = \" << loss << endl;\n  }\n\n  // Output the model and parameter objects\n  // to a cout.\n  boost::archive::text_oarchive oa(cout);\n  oa << m << p_W << p_b << p_V << p_a;\n}\n\n", "meta": {"hexsha": "a8a73b586af4e5f20a48314dc0df62ce40390a5b", "size": 2020, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/xor-xent.cc", "max_stars_repo_name": "slouvan/dynet", "max_stars_repo_head_hexsha": "9fab69665423249247fb8cc372f25353ebb226bf", "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": "examples/xor-xent.cc", "max_issues_repo_name": "slouvan/dynet", "max_issues_repo_head_hexsha": "9fab69665423249247fb8cc372f25353ebb226bf", "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": "examples/xor-xent.cc", "max_forks_repo_name": "slouvan/dynet", "max_forks_repo_head_hexsha": "9fab69665423249247fb8cc372f25353ebb226bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T23:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T23:36:57.000Z", "avg_line_length": 25.25, "max_line_length": 81, "alphanum_fraction": 0.6207920792, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6516767822325223}}
{"text": "#include <iostream>\n\n#include <NTL/ZZ_p.h>\n\n#include \"polynomial.hpp\"\n\nint main(int argc, char* argv[])\n{\n    (void)argc;\n    (void)argv;\n\n    NTL::ZZ p((long)17);\n    NTL::ZZ_p::init(p);\n    NTL::ZZ_p k(6);\n\n    std::cout << k << std::endl;\n    std::cout << k * 2 << std::endl;\n    std::cout << k * 3 << std::endl;\n    std::cout << k * 4 << std::endl;\n\n    unsigned int arity = 3;\n    unsigned int degree = 5;\n    unsigned int order = 7;\n\n    MultiVariatePolynomial poly(arity, degree, order);\n\n    NTL::ZZ_p value(5);\n    std::vector<unsigned int> monomial = { 0, 3, 1 };\n    poly.setElement(monomial, value);\n\n    poly.print();\n\n    std::cout << poly.to_string() << std::endl;\n    std::cout << poly.add(poly).to_string() << std::endl;\n    std::cout << (poly + poly).to_string() << std::endl;\n    std::cout << (poly - poly).to_string() << std::endl;\n\n    std::cout << poly.getMaxNbElements() << std::endl;\n\n    std::vector<NTL::ZZ_p> point = { NTL::ZZ_p(1), NTL::ZZ_p(1), NTL::ZZ_p(4) };\n    std::cout << poly.evaluate(point) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "ebdce3a06ccd40e8edf97929edd9c638f964c541", "size": 1059, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/polynomial/main.cc", "max_stars_repo_name": "pierreeliseeflory/PANDA", "max_stars_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "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/polynomial/main.cc", "max_issues_repo_name": "pierreeliseeflory/PANDA", "max_issues_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "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/polynomial/main.cc", "max_forks_repo_name": "pierreeliseeflory/PANDA", "max_forks_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "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.5333333333, "max_line_length": 80, "alphanum_fraction": 0.5646836638, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6516767720229667}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2010.\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// 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//[policy_ref_snip8\n\n#include <boost/math/distributions/negative_binomial.hpp>\nusing boost::math::negative_binomial_distribution;\n\nusing namespace boost::math::policies;\n\ntypedef negative_binomial_distribution<\n      double, \n      policy<discrete_quantile<integer_round_nearest> > \n   > dist_type;\n   \n// Lower quantile rounded (down) to nearest:\ndouble x = quantile(dist_type(20, 0.3), 0.05); // 27\n// Upper quantile rounded (down) to nearest:\ndouble y = quantile(complement(dist_type(20, 0.3), 0.05)); // 68\n\n//] //[/policy_ref_snip8]\n\n#include <iostream>\nusing std::cout; using std::endl;\n\nint main()\n{\n   cout << \"using policy<discrete_quantile<integer_round_nearest> \" << endl\n     << \"quantile(dist_type(20, 0.3), 0.05) = \" << x << endl\n     << \"quantile(complement(dist_type(20, 0.3), 0.05)) \" << y << endl;\n}\n\n/*\n\nOutput:\n\n   using policy<discrete_quantile<integer_round_nearest> \n  quantile(dist_type(20, 0.3), 0.05) = 27\n  quantile(complement(dist_type(20, 0.3), 0.05)) 68\n\n*/\n", "meta": {"hexsha": "abc48b9aeefaa19527b6ba196038ba7a9a9a4bdc", "size": 1383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/policy_ref_snip8.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/policy_ref_snip8.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/policy_ref_snip8.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": 28.8125, "max_line_length": 75, "alphanum_fraction": 0.7057122198, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6516767675187091}}
{"text": "//\n//  utils.hpp\n//  Jacobian\n//\n//  Created by David Freifeld\n//\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#include <functional>\n#include <Eigen/Dense>\n#include \"bpnn.hpp\"\n\nnamespace Jacobian {\nnamespace activations {\nfloat sigmoid(float x);\nfloat sigmoid_deriv(float x);\nfloat linear(float x);\nfloat linear_deriv(float x);\nfloat step(float x);\nfloat step_deriv(float x);\nfloat bipolar(float x);\nfloat bipolar_deriv(float x);\nfloat mytanh(float x);\nfloat tanh_deriv(float x);\nfloat lecun_tanh(float x);\nfloat lecun_tanh_deriv(float x);\nfloat cloglog(float x);\nfloat cloglog_deriv(float x);\nfloat softplus(float x);\nfloat softplus_deriv(float x);\nfloat inverse_logit(float x);\nfloat inverse_logit_deriv(float x);\nfloat hard_tanh(float x);\nfloat hard_tanh_deriv(float x);\nfloat bipolar_sigmoid(float x);\nfloat bipolar_sigmoid_deriv(float x);\nfloat leaky_relu(float x);\nfloat leaky_relu_deriv(float x);\nstd::function<float(float)> rectifier(float (*activation)(float));\n}\n\nnamespace optimizers {\nstd::function<void(Layer&, Eigen::MatrixXf, float)> momentum(float beta);\nstd::function<void(Layer&, Eigen::MatrixXf, float)> demon(float beta_init, int max_ep);\nstd::function<void(Layer&, Eigen::MatrixXf, float)> adam(float beta1, float beta2, float epsilon);\nstd::function<void(Layer&, Eigen::MatrixXf, float)> adamax(float beta1, float beta2, float epsilon);\n}\n\nnamespace decays {\nstd::function<void(float &)> step(float a_0, float k);\nstd::function<void(float &)> exponential(float a_0, float k);\nstd::function<void(float &)> fractional(float a_0, float k);\nstd::function<void(float &)> linear(int max_ep);\n}\n\nEigen::MatrixXf strassen_mul(Eigen::MatrixXf a, Eigen::MatrixXf b);\n\n}\n\n#endif /* MODULE_H */\n", "meta": {"hexsha": "ea13349ba73d064843bee2d715ec9855027f1953", "size": 1694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils.hpp", "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.hpp", "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.hpp", "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": 26.8888888889, "max_line_length": 100, "alphanum_fraction": 0.7497048406, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6516712165567895}}
{"text": "#include <cmath>\n#include <iostream>\n#include <vector>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"bateman.hpp\"\n\nusing Real_t = boost::multiprecision::cpp_dec_float_50;\nusing vec_t = std::vector<Real_t>;\nReal_t exp_cb(Real_t arg){\n    return boost::multiprecision::exp(arg);\n}\n\nint main(){\n   Real_t one = 1;\n   Real_t d = one/365;\n   Real_t h = d/24;\n   Real_t ln2 = boost::multiprecision::log(2*one);\n   vec_t lmbd {{ ln2/1.405e10, ln2/5.75, ln2/(6.25*h),\n       ln2/1.9116, ln2/(3.6319*d), ln2/(10.64*h), ln2/(60.55/60*h) }};\n   auto p = bateman::bateman_parent(lmbd, static_cast<Real_t>(100), exp_cb);\n   std::cout << std::setprecision(30);  // show 30 of our 50 digits\n   for (auto v : p)\n       std::cout << v << \" \";\n   std::cout << std::endl;\n   return 0;\n}\n", "meta": {"hexsha": "71f9db0765e0879a4c2317f46cb03cc526f88f8e", "size": 782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/multi.cpp", "max_stars_repo_name": "bjodah/batemaneq", "max_stars_repo_head_hexsha": "00ba061737151a5eb46bd2281a8351e5c5e7966c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T13:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-27T16:04:55.000Z", "max_issues_repo_path": "examples/multi.cpp", "max_issues_repo_name": "Rolleroo/batemaneq", "max_issues_repo_head_hexsha": "bd8c24d1f77ccb166b3210d81d9468f7789813ad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-08-27T22:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T06:42:15.000Z", "max_forks_repo_path": "examples/multi.cpp", "max_forks_repo_name": "Rolleroo/batemaneq", "max_forks_repo_head_hexsha": "bd8c24d1f77ccb166b3210d81d9468f7789813ad", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-27T16:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T08:15:21.000Z", "avg_line_length": 28.962962963, "max_line_length": 76, "alphanum_fraction": 0.6406649616, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.651630472820332}}
{"text": "#include <iostream>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <boost/multiprecision/cpp_int.hpp>\n\n#define KEY_BYTES_SIZE 32\n\nusing BigInt = boost::multiprecision::int1024_t;\n\nstruct Point {\n    int x;\n    BigInt y;\n\n    Point(int x, const BigInt& y) : x(x), y(y) {}\n\n    friend std::ostream& operator<<(std::ostream& stream, const Point& rhs);\n};\n\nstd::string format_to_hex(const BigInt& num) {\n    std::stringstream ss;\n    ss << std::hex << std::setfill('0') << std::setw(KEY_BYTES_SIZE * 2) << num;\n\n    return ss.str();\n}\n\nstd::ostream& operator<<(std::ostream& stream, const Point& rhs) {\n    stream << rhs.x << \" \" << format_to_hex(rhs.y);\n\n    return stream;\n}\n\ntemplate <typename T>\nT convert_from_hex(const std::string& hex_str) {\n    std::stringstream ss;\n    ss << std::hex << hex_str;\n\n    T v;\n    ss >> v;\n\n    return v;\n}\n\ntemplate <size_t bytes_count>\nstd::string generate_random_hex() {\n    std::stringstream ss;\n    ss << std::hex << std::setfill('0');\n\n    for (size_t i = 0; i < bytes_count; i++) {\n        ss << std::setw(2) << rand() % 256;\n    }\n\n    return ss.str();\n}\n\nBigInt PRIME = convert_from_hex<BigInt>(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43\");\n\nstd::vector<BigInt> generate_random_coefficients(uint32_t size) {\n    std::vector<BigInt> coefficients;\n    for (uint32_t i = 0; i < size; i++) {\n        BigInt random = convert_from_hex<BigInt>(generate_random_hex<KEY_BYTES_SIZE>());\n        coefficients.push_back(random % PRIME);\n    }\n\n    return coefficients;\n}\n\nBigInt calculate_polynomial(\n    std::vector<BigInt>& coefficients,\n    uint8_t argument\n) {\n    BigInt result = 0;\n    size_t coefficients_count = coefficients.size();\n    for (size_t i = 1; i <= coefficients_count; i++) {\n        result += coefficients[i - 1] * pow(BigInt(argument), coefficients_count - i);\n    }\n\n    return result % PRIME;\n}\n\nstd::vector<Point> split(\n    uint8_t shares_count, \n    uint8_t entry_threshold, \n    const BigInt& secret\n) {\n    std::vector<BigInt> coefficients = generate_random_coefficients(entry_threshold - 1);\n    coefficients.push_back(secret);\n\n    std::vector<Point> points;\n    for (uint8_t i = 1; i <= shares_count; i++) {\n        points.push_back(Point(i, calculate_polynomial(coefficients, i)));\n    }\n\n    return points;\n}\n\nBigInt recover(std::vector<Point>& shares) {\n    auto l = [shares](int x, size_t i) -> BigInt {\n        double result = 1;\n\n        for (size_t j = 0; j < shares.size(); j++) {\n            if (j != i) {\n                result *= (\n                    static_cast<double>(x) - \n                    static_cast<double>(shares[j].x)) / \n                    (static_cast<double>(shares[i].x) - \n                    static_cast<double>(shares[j].x)\n                );\n            }\n        }\n        \n        return BigInt(result);\n    };\n\n    BigInt result = 0;\n    for (size_t i = 0; i < shares.size(); i++) {\n        result += shares[i].y * l(0, i);\n    }\n\n    return result % PRIME;\n}\n\nint main(int args_count, char** args_value) {\n    srand(static_cast<unsigned int>(time(0)));\n\n    if (args_count < 2) {\n        return 1;\n    }\n\n    std::string first_argument(args_value[1]);\n\n    if (first_argument == \"recover\") {\n        int shares_count = 0;\n        std::cin >> shares_count;\n\n        std::vector<Point> shares;\n        for (int i = 0; i < shares_count; i++) {\n            int x = 0;\n            std::string y;\n\n            std::cin >> x >> y;\n            shares.push_back(Point(x, convert_from_hex<BigInt>(y)));\n        }\n\n        BigInt result = recover(shares);\n\n        std::cout << format_to_hex(result) << std::endl;\n    } else if (first_argument == \"split\") {\n        int shares_count = 0;\n        int entry_threshold = 0;\n        std::string string_secret;\n\n        std::cin >> shares_count >> entry_threshold >> string_secret;\n\n        if (shares_count < entry_threshold) {\n            std::cout << \"Shares count must be higher than entry threshold\" << std::endl;\n            return 1;\n        }\n\n        BigInt secret = convert_from_hex<BigInt>(string_secret);\n\n        if (secret > PRIME) {\n            std::cout << \"Your secret must be less than prime number\" << std::endl;\n            return 1;\n        }\n\n        auto shares = split(shares_count, entry_threshold, secret);\n\n        for (const auto& point : shares) {\n            std::cout << point << std::endl;\n        }\n    } else {\n        std::cout << \"Unknow arguments\" << std::endl;\n    }\n}", "meta": {"hexsha": "5b77ff23cf9f2c999a192ac09462765d449ac731", "size": 4499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "AleksMVP/shamir-secret", "max_stars_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T15:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T15:36:14.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "AleksMVP/shamir-secret", "max_issues_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_issues_repo_licenses": ["MIT"], "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": "AleksMVP/shamir-secret", "max_forks_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_forks_repo_licenses": ["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.5625, "max_line_length": 108, "alphanum_fraction": 0.5814625472, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6516153431170159}}
{"text": "/**\n * linalg.hpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents  are provided as  is,  with no express\n * or implied  warranties,  other  than those  that are  expressly stated  in the\n * License.\n *\n * Copyright \u00a9 2021 Gabriel Moreira. All rights reserved.\n */\n\n#ifndef LINALG_HPP\n#define LINALG_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/PardisoSupport>\n\n/* Linear algebra namespace */\nnamespace alg {\n\n\n/**\n * Converts two vectors i and j to matrix indices (in-place).\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param num_nodes (output) int - number of nodes.\n */\nvoid convertToIdx(Eigen::Ref<Eigen::VectorXi> ei,\n                  Eigen::Ref<Eigen::VectorXi> ej,\n                  int& num_nodes);\n\n\n/**\n * Builds sparse graph adjacency matrix.\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param num_edges (input) int - number of edges.\n * @param sym (input) bool - whether to make the matrix symmetric.\n * @param dst (output) Eigen::SparseMatrix<double> - output adjacency matrix.\n */\nvoid adjacency(const Eigen::Ref<Eigen::VectorXi> ei,\n               const Eigen::Ref<Eigen::VectorXi> ej,\n               int   num_edges,\n               bool  sym,\n               Eigen::SparseMatrix<double>& dst);\n\n\n/**\n * Builds sparse block matrix.\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param blocks (input) Eigen::MatrixXd - row block matrix containing contiguous blocks.\n * @param block_height (input) int - block height.\n * @param block_width (input) int - block width.\n * @param num_blocks (input) int - number of contiguous blocks.\n * @param sym (input) bool - whether to make the matrix symmetric.\n * @param dst (output) Eigen::SparseMatrix<double> - output adjacency matrix.\n */\nvoid sparseBlocks(const Eigen::Ref<Eigen::VectorXi> ei,\n                  const Eigen::Ref<Eigen::VectorXi> ej,\n                  const Eigen::Ref<Eigen::MatrixXd> blocks,\n                  int   block_height,\n                  int   block_width,\n                  int   num_blocks,\n                  bool  sym,\n                  Eigen::SparseMatrix<double>& dst);\n\n\n/**\n * Solves the orthogonal Procrustes problem in SO(3) (in-place).\n *\n * @param mat (input/output) Eigen::MatrixXd - 3x3 matrix\n */\nvoid orthoProcrustesSO3(Eigen::Ref<Eigen::Matrix3d> mat);\n\n\n/**\n * Solves the orthogonal Procrustes problem in O(3) (in-place).\n *\n * @param mat (input/output) Eigen::MatrixXd - 3x3 matrix.\n */\nvoid orthoProcrustesO3(Eigen::Ref<Eigen::Matrix3d> mat);\n\n\n/**\n * Finds the projection of a vector on a subpace spanned by the columns of a matrix.\n *\n * @param subspace_basis (input) Eigen::MatrixXd - Dense matrix whose columns span a subspace\n *        where we want to project the vector v.\n * @param idx (input) unsigned int - Sub-selects of the first idx columns of A only.\n * @param v (input) Eigen::VectorXd - Vector to project.\n * @return The component of the vector in the subspace spanned by the first\n *         idx columns of the input matrix A.\n */\nEigen::VectorXd projectionOnto(const Eigen::Ref<Eigen::MatrixXd> subspace_basis,\n                               unsigned int idx,\n                               const Eigen::Ref<Eigen::VectorXd> v);\n\n\n/**\n * Projects a vector onto a subpace spanned by the columns of a matrix (in-place)\n *\n * @param subspace_basis (input) Eigen::MatrixXd - Dense matrix whose columns span a subspace where we\n *        want to project the vector v.\n * @param idx (input) unsigned int - Sub-selects of the first idx columns of A only.\n * @param v (input/output) Eigen::VectorXd - Vector to project.\n */\nvoid projectOnto(const Eigen::Ref<Eigen::MatrixXd> subspace_basis,\n                 unsigned int idx,\n                 Eigen::Ref<Eigen::VectorXd> v);\n\n\n/**\n * Symmetric sparse solver via LDLT decomposition.\n *\n * Solves sparse system Ax = b via LDLt decomposition.\n *\n * @param solver (input) Eigen::PardisoLDLT<Sparse> - LDLt Intel PARDISO solver\n * @param mat (input) Eigen::MatrixXd - matrix to factorize.\n * @param rhs (input) Eigen::VectorXd - right hand side.\n * @param x (output) Eigen::VectorXd - solution of the system.\n */\nvoid sparseSolverLDL(Eigen::PardisoLDLT<Eigen::SparseMatrix<double>>* solver,\n                     const Eigen::SparseMatrix<double>& mat,\n                     const Eigen::Ref<Eigen::MatrixXd> rhs,\n                     Eigen::Ref<Eigen::MatrixXd> x);\n\n\n/**\n * Robust reorthogonalization. For an input matrix V and an input\n * vector r, tries to iteratively orthogonalize r against the j first columns\n * of V. This prevents numerical errors and ensures orthogonality. If, by any\n * chance, and after multiple iterations of subtracting projections, the vector\n * has a norm smaller than 1/sqrt(2) of its starting norm, it cannot be\n * reorthogonalized. This method then attempts to find another orthogonal vector\n * through random restarts. The flag stop is activated if everything fails.\n * (See G. W. Stewart 2001)\n *\n * @param V (input) Dense matrix of doubles whose columns contain orthogonal basis\n *        vectors\n * @param r (input/output) Vector to orthogonalize\n * @param residual_norm (output) Residual norm or r after it has been orthogonalized against the first j columns of V.\n * @param idx (input) Index specifying the number of columns of V used in the orthogonalization.\n * @param stop (output) Stop the algorithm flag. Indicates that it is impossible to find, to machine precision, a vector r orthogonal to the first j cols of V.\n */\nvoid reorthogonalize(const Eigen::Ref<Eigen::MatrixXd> V,\n                     Eigen::Ref<Eigen::VectorXd> r,\n                     double& residual_norm,\n                     unsigned int idx,\n                     int& stop);\n\n\n/**\n * Symmetric Krylov-Schur LDLt eigensolver.\n *\n * For a real sparse symmetric matrix A, this function computes k real eigenvalues\n * near a real target sigma using the Krylov-Schur method (G. W. Stewart 2001).\n *\n * @param solver (input) Eigen::PardisoLDLT<Sparse> - LDLt Intel PARDISO solver.\n * @param mat (input) Eigen::SparseMatrix<double> - sparse matrix to compute eigenvalues and eigenvectors.\n * @param eigenvalues (output) Eigen::VectorXd - k x 1 matrix to store the computed eigenvalues.\n * @param eigenvectors (output) Eigen::MatrixXd - n x k matrix to store normalized eigenvectors.\n * @param k (input) int - number of eigenvalues and eigenvectors to be computed.\n * @param sigma (input) double - spectral shift / eigenvalue target.\n*/\nvoid symKrylovSchurLDL(Eigen::PardisoLDLT<Eigen::SparseMatrix<double>>* solver,\n                       const Eigen::SparseMatrix<double>& mat,\n                       Eigen::Ref<Eigen::VectorXd> eigenvalues,\n                       Eigen::Ref<Eigen::MatrixXd> eigenvectors,\n                       unsigned int k,\n                       double sigma);\n\n};\n\n#endif /* LINALG_HPP */\n", "meta": {"hexsha": "641e8ad61483b2c9921c0f55fcdd9c5f7d8be944", "size": 7074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/linalg.hpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "include/linalg.hpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "include/linalg.hpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 38.6557377049, "max_line_length": 159, "alphanum_fraction": 0.6668080294, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6514483560276051}}
{"text": "#ifndef CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n#define CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n\n#include <cstddef> // size_t\n\n#include <Eigen/Dense>\n\nnamespace cppmath\n{\n    /**\n     * Implementation of Downhill Simplex or Nelder-Mead method for nonlinear optimization from 1998.\n     * J. Lagarias, J. Reeds, M. Wright, P. Wright,\n     * \"Convergence Properties of the Nelder-Mead Simplex Method in Low Dimensions,\"\n     * SIAM Journal of Optimization, 1998, 9, 112-147\n     *\n     * \\author cpieloth\n     * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n     */\n    template< size_t DIM >\n    class DownhillSimplexMethod\n    {\n    public:\n        typedef Eigen::Matrix< double, DIM, 1 > ParamsT; /**< Abbreviation for a vector of parameters. */\n\n        /**\n         * Enum to indicate how the optimization was converged.\n         */\n        enum Converged\n        {\n            CONVERGED_NO, /**< Optimization was not started. */\n            CONVERGED_EPSILON, /**< Optimization is smaller than epsilon/threshold. */\n            CONVERGED_ITERATIONS, /**< Maximum iterations was reached. */\n            CONVERGED_YES /**< Optimization is converged, but not specified how. */\n        };\n\n        DownhillSimplexMethod();\n        virtual ~DownhillSimplexMethod();\n\n        /**\n         * Implementation of the function to minimize.\n         *\n         * \\param x  n-dimensional parameter vector.\n         * \\return function value for vector x.\n         */\n        virtual double func( const ParamsT& x ) const = 0;\n\n        double getReflectionCoeff() const;\n\n        void setReflectionCoeff( double coeff );\n\n        double getContractionCoeff() const;\n\n        void setContractionCoeff( double coeff );\n\n        double getExpansionCoeff() const;\n\n        void setExpansionCoeff( double coeff );\n\n        double getShrinkageCoeff() const;\n\n        void setShrinkageCoeff( double coeff );\n\n        size_t getMaximumIterations() const;\n\n        void setMaximumIterations( size_t iterations );\n\n        double getEpsilon() const;\n\n        void setEpsilon( double eps );\n\n        double getInitialFactor() const;\n\n        void setInitialFactor( double factor );\n\n        size_t getResultIterations() const;\n\n        ParamsT getResultParams() const;\n\n        double getResultError() const;\n\n        /**\n         * Starts the optimization.\n         *\n         * \\param initial Initial start point.\n         * \\return Enum::Converged\n         */\n        Converged optimize( const ParamsT& initial );\n\n    protected:\n        /**\n         * Orders the parameters x and f(x) from min to max.\n         */\n        virtual void order();\n\n        /**\n         * Checks if the optimization has been converged.\n         *\n         * \\return Enum::Converged\n         */\n        virtual Converged converged() const;\n\n        /**\n         * Creates the initial parameter set and their function values.\n         *\n         * \\param initial Start parameter used to calculate initials.\n         */\n        virtual void createInitials( const ParamsT& initial );\n\n        double m_initFactor; /**< Factor to create the initial parameter set. */\n\n        ParamsT m_x[DIM + 1]; /**< Vector of all n+1 points. */\n        double m_f[DIM + 1]; /**< Stores the function values to reduce re-calculation. */\n\n        double m_epsilon; /**< Threshold or deviation for convergence. */\n        size_t m_maxIterations; /**< Maximum iterations until the algorithm is canceled. */\n        size_t m_iterations; /**< Iteration counter used for break condition. */\n\n        const size_t DIMENSION; /**< Constant for dimension. */\n        const size_t VALUES; /**< Constant for DIM+1. */\n\n    private:\n        enum Step\n        {\n            STEP_START, STEP_EXIT, STEP_REFLECTION, STEP_EXPANSION, STEP_CONTRACTION, STEP_SHRINKAGE\n        };\n\n        const size_t N; /**< Index n=DIM-1 */\n        const size_t N1; /**< Index n+1=DIM */\n\n        double m_refl; /**< Reflection coefficient. */\n        double m_contr; /**< Contraction coefficient. */\n        double m_exp; /**< Expansion coefficient. */\n        double m_shri; /**< Shrinkage coefficient. */\n\n        void centroid();\n        void accept( const ParamsT& x, double f );\n\n        Step reflection();\n        Step expansion();\n        Step contraction();\n        Step shrinkage();\n\n        ParamsT m_xo;\n        ParamsT m_xr;\n        double m_fr;\n    };\n} /* namespace cppmath */\n\n// Load the implementation\n#include \"DownhillSimplexMethod-impl.hpp\"\n\n#endif  // CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n", "meta": {"hexsha": "c559bef18842d96c329e71e0e6662f7ca361d976", "size": 4591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/optimization/DownhillSimplexMethod.hpp", "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/cppmath/optimization/DownhillSimplexMethod.hpp", "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/cppmath/optimization/DownhillSimplexMethod.hpp", "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": 30.0065359477, "max_line_length": 105, "alphanum_fraction": 0.6144630799, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6514483505784399}}
{"text": "#ifndef SM_MATH_HOMOGENEOUS_COORDINATES_HPP\n#define SM_MATH_HOMOGENEOUS_COORDINATES_HPP\n\n#include <Eigen/Core>\n\nnamespace sm {\nnamespace kinematics {\n\nEigen::Matrix<double, 4, 3> toHomogeneousJacobian(const Eigen::Vector3d& v);\nEigen::Vector4d toHomogeneous(const Eigen::Vector3d& v, Eigen::Matrix<double, 4, 3>* jacobian = NULL);\n\nEigen::Matrix<double, 3, 4> fromHomogeneousJacobian(const Eigen::Vector4d& v);\nEigen::Vector3d fromHomogeneous(const Eigen::Vector4d& v, Eigen::Matrix<double, 3, 4>* jacobian = NULL);\n\nEigen::MatrixXd toHomogeneousColumns(const Eigen::MatrixXd& M);\nEigen::MatrixXd fromHomogeneousColumns(const Eigen::MatrixXd& M);\n\ntemplate <int N>\nEigen::Matrix<double, N, 1> normalize(const Eigen::Matrix<double, N, 1>& v) {\n    return v / v.norm();\n}\n\ntemplate <int N>\nEigen::Matrix<double, N, 1> normalizeAndJacobian(const Eigen::Matrix<double, N, 1>& v,\n                                                 Eigen::Matrix<double, N, N>& outJacobian) {\n    double recip_s_vtv = 1.0 / v.norm();\n\n    outJacobian = (Eigen::Matrix<double, N, N>::Identity() * recip_s_vtv) -\n                  (recip_s_vtv * recip_s_vtv * recip_s_vtv) * v * v.transpose();\n\n    return v * recip_s_vtv;\n}\n\n/// \\brief to the matrix that implements \"plus\" for homogeneous coordinates.\n///        this operation has the same result as adding the corresponding Euclidean points.\nEigen::Matrix4d toHomogeneousPlus(const Eigen::Vector4d& ph);\n\n/// \\brief to the matrix that implements \"minus\" for homogeneous coordinates.\n///        this operation has the same result as adding the corresponding Euclidean points.\nEigen::Matrix4d toHomogeneousMinus(const Eigen::Vector4d& ph);\n\n}  // namespace kinematics\n}  // namespace sm\n\n#endif /* SM_MATH_HOMOGENEOUS_COORDINATES_HPP */\n", "meta": {"hexsha": "c7ebfcd409f2175ca1bc753054a96296802d073d", "size": 1761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/homogeneous_coordinates.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/homogeneous_coordinates.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/homogeneous_coordinates.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": 38.2826086957, "max_line_length": 104, "alphanum_fraction": 0.710959682, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6514483364714101}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <vector>\r\n#include <boost/format.hpp>\r\n#include \"logistic_regression.h\"\r\n#include \"utils.h\"\r\n#include <omp.h>\r\n#include <ctime>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nLogisticRegression::LogisticRegression() : max_iter(1000), alpha(0.01), lambda(0.0), tolerance(1e-7), seed(2018), use_batch(false) {}\r\n\r\nLogisticRegression::LogisticRegression(const int& max_iter, const double& alpha, const double& lambda, const double& tolerance, const int& seed, bool use_batch): max_iter(max_iter), alpha(alpha), lambda(lambda), tolerance(tolerance), seed(seed), use_batch(use_batch){}\r\n\r\nLogisticRegression::~LogisticRegression(){}\r\n\r\n\r\nvoid LogisticRegression::fit(const MatrixXd& X, const VectorXd& y, const int& batch_size, const int& early_stopping_round, double (*metric)(double* y, double* pred, int size)){\r\n\t// learn VectorXd W, consider reg, max_iter, tol\r\n\tsrand(seed);\r\n\tW = VectorXd::Random(X.cols()+1);   // the last column of weight represent bias\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new<<X, MatrixXd::Ones(X.rows(),1);\r\n\t// perform early stopping\r\n\tdouble best_acc = -1.0;\r\n\tdouble best_loss = -1.0;\r\n\tMatrixXd bestW = W;\r\n\tint become_worse_round = 0;\r\n\r\n\tif(use_batch){\r\n\t\tMatrixXd X_batch;\r\n\t\tVectorXd y_batch;\r\n\t\tMatrixXd X_new_batch;\r\n\t\tfor(int iter = 0; iter < max_iter; iter++){\r\n\t\t\t// index of this batch samples\r\n\t\t\tint start_idx = (batch_size*iter)%(static_cast<int>(X.rows()));\r\n\t\t\tint end_idx = min(start_idx+batch_size, static_cast<int>(X.rows()));\r\n\r\n\t\t\tX_batch = Utils::slice(X, start_idx, end_idx-1);\r\n\t\t\ty_batch = Utils::slice(y, start_idx, end_idx-1);\r\n\t\t\tX_new_batch = Utils::slice(X_new, start_idx, end_idx-1);\r\n\r\n\t\t\tVectorXd y_pred = predict_prob(X_batch);\r\n\t\t\tVectorXd E = y_pred - y_batch;\r\n\r\n\t\t\t// update W\r\n\t\t\tW -= (alpha * X_new_batch.transpose() * E + lambda * W);\r\n\t\t\t// calcalate the logloss and accuracy after this step\r\n\t\t\ty_pred = predict_prob(X_batch);\r\n\r\n\t\t\tdouble loss = Utils::crossEntropyLoss(y_batch, y_pred);\r\n\t\t\t//double acc = metric(y_batch, y_pred);\r\n\t\t\tdouble acc = metric(Utils::VectorXd_to_double_array(y_batch), Utils::VectorXd_to_double_array(y_pred), end_idx-start_idx);\r\n\t\t\tcout << boost::format(\"Iteration: %d, logloss:%.5f, accuracy:%.5f\") %iter %loss %acc << endl;\r\n\r\n\t\t\t// when loss < tolerance, break\r\n\t\t\tif(loss <= tolerance) break;\r\n\r\n\t\t\t// perform early stopping\r\n\t\t\tif(acc < best_acc){\r\n\t\t\t\tbecome_worse_round += 1;\r\n\t\t\t}else{\r\n\t\t\t\tbecome_worse_round = 0;\r\n\t\t\t\tbest_acc = acc;\r\n\t\t\t\tbestW = W;\r\n\t\t\t\tbest_loss = loss;\r\n\t\t\t}\r\n\t\t\tif(become_worse_round >= early_stopping_round){\r\n\t\t\t\tW = bestW;\r\n\t\t\t\tcout << boost::format(\"Early stopping in %d, the best iteration is: %d, logloss: %.5f, accuracy:%.5f\") %iter %(iter-early_stopping_round) %best_loss %best_acc << endl;\r\n\t\t\t\tcout << \"Early stopping.\" << endl;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tfor(int iter = 0; iter < max_iter; iter++){\r\n\t\t\t// index of this batch samples\r\n\r\n\t\t\tVectorXd y_pred = predict_prob(X);\r\n\t\t\tVectorXd E = y_pred - y;\r\n\r\n\t\t\t// update W\r\n\t\t\tW -= (alpha * X_new.transpose() * E + lambda * W);\r\n\t\t\t// calcalate the logloss and accuracy after this step\r\n\t\t\ty_pred = predict_prob(X);\r\n\r\n\t\t\tdouble loss = Utils::crossEntropyLoss(y, y_pred);\r\n\t\t\t//double acc = metric(y, y_pred);\r\n\t\t\tdouble acc = metric(Utils::VectorXd_to_double_array(y), Utils::VectorXd_to_double_array(y_pred), X.rows());\r\n\t\t\tcout << boost::format(\"Iteration: %d, logloss:%.5f, accuracy:%.5f\") %iter %loss %acc << endl;\r\n\r\n\t\t\t// when loss < tolerance, break\r\n\t\t\tif(loss <= tolerance) break;\r\n\r\n\t\t\t// perform early stopping\r\n\t\t\tif(acc < best_acc){\r\n\t\t\t\tbecome_worse_round += 1;\r\n\t\t\t}else{\r\n\t\t\t\tbecome_worse_round = 0;\r\n\t\t\t\tbest_acc = acc;\r\n\t\t\t\tbestW = W;\r\n\t\t\t\tbest_loss = loss;\r\n\t\t\t}\r\n\t\t\tif(become_worse_round >= early_stopping_round){\r\n\t\t\t\tW = bestW;\r\n\t\t\t\tcout << boost::format(\"Early stopping in %d, the best iteration is: %d, logloss: %.5f, accuracy:%.5f\") %iter %(iter-early_stopping_round) %best_loss %best_acc << endl;\r\n\t\t\t\tcout << \"Early stopping.\" << endl;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nVectorXd LogisticRegression::predict_prob(const MatrixXd& X){\r\n\t// predict the probability (of label 1) for given data X\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new << X, MatrixXd::Ones(X.rows(),1);\r\n\tint num_samples = X_new.rows();\r\n\tVectorXd y_pred_prob = VectorXd::Zero(num_samples);\r\n\t#pragma omp parallel for\r\n\tfor(int num = 0; num < num_samples; num++){\r\n\t\ty_pred_prob(num) = Utils::sigmoid(X_new.row(num).dot(W));\r\n\t}\r\n\treturn y_pred_prob;\r\n}\r\n\r\nVectorXi LogisticRegression::predict(const MatrixXd& X){\r\n\t// predict the label for given data X\r\n\tVectorXd y_pred_prob = predict_prob(X);\r\n\tVectorXi y_pred(y_pred_prob.size());\r\n\t#pragma omp parallel for\r\n\tfor(int num = 0; num < y_pred_prob.size(); num++){\r\n\t\ty_pred(num) = y_pred_prob(num)>0.5?1:0;\r\n\t}\r\n\treturn y_pred;\r\n}\r\n\r\nVectorXd LogisticRegression::getW(){\r\n\treturn W;\r\n}\r\n\r\nvoid LogisticRegression::saveWeights(const std::string& fpath){\r\n\t// save the model (save the weight)\r\n\tstd::ofstream ofile;\r\n\tofile.open(fpath.c_str());\r\n\tif (!ofile.is_open()){\r\n\t\tstd::cerr << \"Can not open the file when call LogisticRegression::saveWeights\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\t// W wirte into the file\r\n\tfor(int i = 0; i < W.size() - 1; i++){\r\n\t\tofile << W(i) << \" \";\r\n\t}\r\n\tofile << W(W.size()-1);\r\n\tofile.close();\r\n}\r\n\r\nvoid LogisticRegression::loadWeights(const std::string& fpath){\r\n\t// load the model (load the weight ) from filename\r\n\tstd::ifstream ifile;\r\n\tifile.open(fpath.c_str());\r\n\tif (!ifile.is_open()){\r\n\t\tstd::cerr << \"Can not open the file when call LogisticRegression::loadWeights\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\t// read the weights into vector<double>\r\n\tstd::string line;\r\n\tstd::vector<double> weights;\r\n\tgetline(ifile, line);   // only one line\r\n\tstd::stringstream ss(line);\r\n\tdouble tmp;\r\n\twhile(!ss.eof()){\r\n\t\tss >> tmp;\r\n\t\tweights.push_back(tmp);\r\n\t}\r\n\t// initialize VectorXd with std::vector\r\n\tW = VectorXd::Map(weights.data(), weights.size());\r\n\tifile.close();\r\n}\r\n", "meta": {"hexsha": "ef8d76a5da62777c161504adf740f624120a15e5", "size": 6043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/logistic_regression.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/logistic_regression.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/logistic_regression.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": 32.6648648649, "max_line_length": 269, "alphanum_fraction": 0.6577858679, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.651384773823843}}
{"text": "#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nclass Solver\n{\n    public:\n    Solver();\n    double power_iteration(const MatrixXd &A, const double epsilon,const int maxStep);\n    VectorXd iterative_refinement(const Ref<const MatrixXd> &A,const VectorXd &b, const double mu_ir, const double mu_rel, const double epsilon, const int max_iter);\n    VectorXd solveQP( MatrixXd P, const VectorXd &q, const VectorXd &warm_start , const double epsilon, const double mu_prox, const int max_iter, const bool adaptative_rho);\n    VectorXd dualFromPrimalQP(const MatrixXd &P,const VectorXd &q,const VectorXd &l, const double &epsilon);\n    VectorXd solveDerivativesQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l, const VectorXd &gamma, const VectorXd &grad_l, const double &epsilon);\n    //VectorXd prox_circle(VectorXd l, const VectorXd &l_n);\n    void prox_circle(VectorXd &l, const VectorXd &l_n);\n    VectorXd solveQCQP( MatrixXd P, const VectorXd &q, const VectorXd &l_n, const VectorXd &warm_start, const double epsilon, const double mu_prox, const int max_iter,const bool adaptative_rho);\n    VectorXd dualFromPrimalQCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l_n, const VectorXd &l, const double &epsilon);\n    VectorXd solveDerivativesQCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l_n, const VectorXd &l, const VectorXd &gamma, const VectorXd &grad_l, const double &epsilon);\n    std::tuple<MatrixXd,MatrixXd> getE12QCQP(const VectorXd &l_n, const VectorXd &mu, const VectorXd &gamma);\n\n    void prox_lorentz(VectorXd &l);\n    VectorXd solveLCQP( MatrixXd P, const VectorXd &q, const VectorXd &warm_start, const double epsilon, const double mu_prox, const int max_iter,const bool adaptative_rho);\n    VectorXd solveDerivativesLCQP(const MatrixXd &P, const VectorXd &q, const VectorXd &l, const VectorXd &grad_l, const double &epsilon);\n    \n    int test();\n\n    private:\n    int prob_id;\n};", "meta": {"hexsha": "6030caf998b9f6c62f44abf231c24a2086af0897", "size": 1949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/diffqcqp/Solver.hpp", "max_stars_repo_name": "mshalm/diffqcqp", "max_stars_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "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/diffqcqp/Solver.hpp", "max_issues_repo_name": "mshalm/diffqcqp", "max_issues_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "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/diffqcqp/Solver.hpp", "max_forks_repo_name": "mshalm/diffqcqp", "max_forks_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "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": 64.9666666667, "max_line_length": 194, "alphanum_fraction": 0.7573114418, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6513847624158039}}
{"text": "#include <iostream>\r\n#include <math.h>\r\n#include <stdio.h> \r\n#include <stdlib.h> \r\n#include <string.h> \r\n#include<vector> \r\n#include <complex.h>\r\n#include <algorithm>\r\n#include \"IIR_Butterworth.h\"\r\n\r\n//#define ARMA_DONT_USE_CXX11\r\n#define ARMA_DONT_USE_CXX11_MUTEX\r\n#include <armadillo>\r\n\r\n\r\n#define PI 3.141592653589793\r\n\r\n//Global variables\r\ndouble fs = 2;\r\ndouble u_f1;\r\ndouble u_f2;\r\ndouble Wn;\r\ndouble Bw;\r\n\r\nstd::vector<std::complex<double>> ptemp;\r\nstd::complex<double> complex_real(1.0, 0.0);\r\nstd::complex<double> complex_imag(0.0, 1.0);\r\nstd::vector<std::complex<double>> p;\r\n\r\nint temp_dim_arr_matr;\r\nstd::vector<std::vector<std::complex<double>> > a;\r\nstd::vector<std::complex<double>> b;\r\nstd::vector<std::complex<double>> c;\r\n\r\ndouble d[1];\r\ndouble t[1];\r\n\r\narma::cx_mat a_arma;\r\narma::cx_mat b_arma;\r\narma::cx_mat c_arma;\r\narma::cx_mat d_arma;\r\n\r\narma::cx_mat t1_arma;\r\narma::cx_mat t2_arma;\r\narma::cx_mat ad_arma;\r\narma::cx_mat bd_arma;\r\narma::cx_mat cd_arma;\r\narma::cx_mat dd_arma;\r\n\r\nstd::vector<double> num_filt;   //Vector where to temporarily save the numerator\r\nstd::vector<double> den_filt;   // Vector where to temporarily save the denumerator\r\nstd::vector<std::vector<double> > save_filt_coeff;  //Matrix where to save the numerator and denominator. First row is the numerator; second row is the denominator\r\n\r\nusing namespace IIR_B_F;\r\n\r\n//Step 1: get analog, pre - warped frequencies\r\nvoid IIR_Butterworth::freq_pre_wrapped(int type_filt, double Wnf_1, double Wnf_2)\r\n{\r\n\r\n    Bw = 0;\r\n\r\n    switch (type_filt)\r\n    {\r\n\r\n        //Band-pass\r\n    case 0:\r\n\r\n        u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n        u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n        break;\r\n\r\n        //Band-stop\r\n    case 1:\r\n\r\n        u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n        u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n\r\n        break;\r\n\r\n        //High-pass\r\n    case 2:\r\n\r\n        u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n\r\n        break;\r\n\r\n        //Low-pass\r\n    case 3:\r\n\r\n        u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n        break;\r\n\r\n    }\r\n}\r\n\r\n\r\n//Step 2: convert to low-pass prototype estimate\r\nvoid IIR_Butterworth::Wn_f1_Wn_f2(int type_filt, double u_f1, double u_f2)\r\n{\r\n\r\n    switch (type_filt)\r\n    {\r\n\r\n        //Band-pass\r\n    case 0:\r\n        Bw = u_f2 - u_f1;\r\n        Wn = sqrt(u_f1 * u_f2);\r\n\r\n        break;\r\n\r\n        //Band-stop\r\n    case 1:\r\n\r\n        Bw = u_f2 - u_f1;\r\n        Wn = sqrt(u_f1 * u_f2);\r\n\r\n        break;\r\n\r\n        //Low-pass\r\n    case 2:\r\n\r\n        Wn = u_f1;\r\n\r\n        break;\r\n\r\n        //High-pass\r\n    case 3:\r\n\r\n        Wn = u_f2;\r\n\r\n        break;\r\n\r\n    }\r\n}\r\n\r\n\r\n\r\n//Step 3: Get N - th order Butterworth analog lowpass prototype\r\nvoid IIR_Butterworth::buttap(int order_filt)\r\n{\r\n    double order_filt_exp = (double)order_filt;\r\n    int temp_length_vec = 0;\r\n    int kkk = 1;\r\n    do {\r\n\r\n        temp_length_vec++;\r\n        kkk += 2;\r\n\r\n    } while (kkk <= order_filt - 1);\r\n\r\n    //Initialize the vector \"ptemp\" \r\n    for (int i = 0; i < temp_length_vec; i++)\r\n    {\r\n\r\n        ptemp.push_back(0);\r\n\r\n    }\r\n    \r\n    int track_cell = 0;\r\n    for (double kk = 0; kk < (double)order_filt - 1; kk += 2)\r\n    {\r\n\r\n        ptemp.at(track_cell) = exp(complex_imag * ((PI * (kk + 1)) / (2 * order_filt_exp) + PI / 2));\r\n\r\n        track_cell++;\r\n\r\n    }\r\n\r\n    //Initialize the vector \"p\"\r\n    for (int i = 0; i < order_filt; i++)\r\n\r\n    {\r\n\r\n        p.push_back(0);\r\n\r\n    }\r\n\r\n   \r\n    double temp_rem = remainder(order_filt, 2);\r\n\r\n    if (temp_rem != 0)\r\n    {\r\n\r\n        for (int kk = 0; kk < order_filt; kk++)\r\n        {\r\n\r\n            if (kk < order_filt - 1)\r\n            {\r\n\r\n                p.at(kk) = complex_imag;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                p.at(kk) = -complex_real;\r\n\r\n            }\r\n\r\n\r\n        }\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        for (int kk = 0; kk < order_filt; kk++)\r\n        {\r\n\r\n            p.at(kk) = complex_imag;\r\n\r\n        }\r\n\r\n\r\n    }\r\n\r\n    if (order_filt > 1)\r\n    {\r\n        track_cell = 0;\r\n        for (int kk = 0; kk < temp_length_vec * 2; kk += 2)\r\n        {\r\n\r\n            p.at(kk) = ptemp.at(track_cell);\r\n            p.at(kk + 1) = conj(ptemp.at(track_cell));\r\n\r\n            track_cell++;\r\n\r\n        }\r\n    }\r\n\r\n}\r\n\r\n\r\n//Step 4: Transform to state-space\r\n//Intermidiate step: calculate the coefficients of the polynomial (based on Matlab code)\r\nstd::vector<std::complex<double>> IIR_Butterworth::poly(std::vector<std::complex<double>> temp_array_poly, int col_poly)\r\n{\r\n    std::vector<std::complex<double>> coeff_pol_f(col_poly + 1);\r\n    coeff_pol_f.at(0) = 1;\r\n\r\n    for (int ll = 0; ll < col_poly; ll++)\r\n    {\r\n\r\n        int yy = 0;\r\n\r\n        do\r\n        {\r\n\r\n            coeff_pol_f.at(ll + 1 - yy) = coeff_pol_f.at(ll + 1 - yy) - temp_array_poly.at(ll) * coeff_pol_f.at(ll - yy);\r\n            yy++;\r\n\r\n        } while (yy <= ll);\r\n\r\n    }\r\n\r\n    return coeff_pol_f;\r\n\r\n}\r\n\r\n//Calculate the factorial of the given number\r\nint IIR_Butterworth::factorial(int i)\r\n{\r\n\r\n    if (i <= 1) \r\n    {\r\n\r\n        return 1;\r\n\r\n    }\r\n\r\n    return i * factorial(i - 1);\r\n\r\n}\r\n\r\n\r\n\r\n//Method to calculate all the possible combinations. Code taken and slightly modified from: \r\n//http://rosettacode.org/wiki/Combinations#C.2B.2B\r\nstd::vector<std::vector<int> > IIR_Butterworth::combination_method(int N, int K, int comb_n)\r\n{\r\n    \r\n    int rows_f = 0;\r\n    \r\n    std::vector<std::vector<int> > matrix_comb_f;\r\n\r\n        std::vector<int> temp_v;\r\n\r\n        for (int ff = 0; ff < K; ff++)\r\n        {\r\n\r\n            temp_v.push_back(0);\r\n\r\n        }\r\n\r\n        for (int hh = 0; hh < comb_n; hh++)\r\n        {\r\n\r\n            matrix_comb_f.push_back(temp_v);\r\n\r\n        }\r\n\r\n    std::string bitmask(K, 1); // K leading 1's\r\n    bitmask.resize(N, 0); // N-K trailing 0's\r\n\r\n    int col_f;\r\n    do {\r\n\r\n        col_f = 0;\r\n\r\n        for (int i = 0; i < N; ++i) // [0..N-1] integers\r\n        {\r\n\r\n            if (bitmask[i])\r\n\r\n            {\r\n                \r\n               \r\n                matrix_comb_f[rows_f][col_f] = i;\r\n               \r\n                col_f++;\r\n\r\n            }\r\n        }\r\n        \r\n        rows_f++;\r\n\r\n    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\r\n\r\n    return matrix_comb_f;\r\n\r\n}\r\n\r\n\r\n\r\n//Intermidiate step: calculate the coefficients of the polynomial (Bernard Brooks' paper (2016))\r\nstd::vector<std::complex<double>> IIR_Butterworth::char_poly(arma::cx_mat temp_matr_poly, int row_col)\r\n{\r\n    \r\n    std::vector<std::complex<double>> coeff_pol_ff(row_col + 1);\r\n    arma::cx_mat temp_val = arma::zeros <arma::cx_mat>(1,1);\r\n    double num_det;\r\n    arma::cx_mat temp_matr = arma::zeros <arma::cx_mat>(row_col, row_col);\r\n    \r\n    std::vector<std::vector<int> > matrix_comb;\r\n\r\n    for (int kk = 0; kk < row_col + 1; kk++)\r\n\r\n    {\r\n\r\n        if (kk == 0)\r\n        {\r\n\r\n            coeff_pol_ff[row_col - kk] = pow(-1, row_col) * arma::det(temp_matr_poly);\r\n\r\n        }\r\n\r\n        else\r\n        {\r\n\r\n            temp_val(0, 0) = 0;\r\n\r\n\r\n            num_det = (double)factorial(row_col) / (double)(factorial(row_col - kk) * (double)factorial(kk));  //Calculate the number of combinations   \r\n\r\n\r\n        //Catching the situation where the denominator is zero. Assign the default value of 10^10 to the denominator\r\n            if (isnan(num_det))\r\n            {\r\n\r\n                for (int ff = 0; ff < row_col + 1; ff++)\r\n                {\r\n\r\n                    coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n                }\r\n\r\n                break;\r\n\r\n            }\r\n\r\n            if (num_det < 1)    //Handling the situation where numerical overflow generates a negative or zero value for the num_det because of the instability of the filter\r\n            {\r\n\r\n                for (int ff = 0; ff < row_col + 1; ff++)\r\n                {\r\n\r\n                    coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n                }\r\n\r\n                break;\r\n\r\n            }\r\n\r\n            std::vector<int> temp_v;\r\n\r\n            for (int ff = 0; ff < num_det; ff++)\r\n            {\r\n\r\n                temp_v.push_back(0);\r\n\r\n            }\r\n\r\n            for (int hh = 0; hh < num_det; hh++)\r\n            {\r\n\r\n                matrix_comb.push_back(temp_v);\r\n\r\n            }\r\n\r\n            if (num_det - (int)num_det == 0)\r\n            {\r\n                // Generate the combinations \r\n                matrix_comb = combination_method(row_col, kk, (int)num_det);\r\n\r\n                for (int mm = 0; mm < num_det; mm++)\r\n\r\n                {\r\n\r\n                    temp_matr = temp_matr_poly;\r\n\r\n                    for (int pp = 0; pp < row_col; pp++)\r\n                    {\r\n\r\n                        temp_matr(matrix_comb[mm][0], pp) = 0;\r\n                        temp_matr(pp, matrix_comb[mm][0]) = 0;\r\n                        temp_matr(matrix_comb[mm][0], matrix_comb[mm][0]) = -1;\r\n\r\n                    }\r\n\r\n                    for (int nn = 1; nn < kk; nn++)\r\n                    {\r\n\r\n                        for (int pp = 0; pp < row_col; pp++)\r\n                        {\r\n\r\n                            temp_matr(matrix_comb[mm][nn], pp) = 0;\r\n                            temp_matr(pp, matrix_comb[mm][nn]) = 0;\r\n                            temp_matr(matrix_comb[mm][nn], matrix_comb[mm][nn]) = -1;\r\n\r\n                        }\r\n\r\n                    }\r\n\r\n                    temp_val(0, 0) += det(temp_matr);\r\n\r\n                }\r\n\r\n                coeff_pol_ff[row_col - kk] = pow(-1, row_col) * temp_val(0, 0);\r\n\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                for (int ff = 0; ff < row_col + 1; ff++)\r\n                {\r\n\r\n                    coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n                }\r\n\r\n                break;\r\n\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    \r\n    return coeff_pol_ff;\r\n    \r\n}\r\n\r\n\r\n\r\n//Step 4: Transform to state-space\r\nvoid IIR_Butterworth::zp2ss(int order_filt)\r\n{\r\n\r\n    //Order the pairs of complex conjugate. The pairs with the smallest real part come first. Within pairs, the ones with the negative imaginary part comes first    \r\n    std::complex<double> temp_max;\r\n\r\n    //Using the selection sort algorithm to order based on the real part\r\n    double order_filt_d = (double)order_filt;\r\n    double temp_rem;\r\n    if (remainder(order_filt, 2) == 0)\r\n    {\r\n\r\n        temp_rem = order_filt_d;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        temp_rem = order_filt_d - 1;\r\n\r\n    }\r\n\r\n    int min_real;\r\n    for (int kk = 0; kk < temp_rem - 1; kk++)\r\n    {\r\n        min_real = kk;\r\n\r\n        for (int jj = kk + 1; jj < temp_rem; jj++)\r\n        {\r\n            if (real(p[jj]) < real(p[min_real]))\r\n            {\r\n\r\n                min_real = jj;\r\n\r\n                temp_max = p[kk];\r\n                p[kk] = p[min_real];\r\n                p[min_real] = temp_max;\r\n\r\n            }\r\n        }\r\n    }\r\n\r\n    //Using the selection sort algorithm to order the values based on the imaginary part\r\n    for (int kk = 0; kk < temp_rem - 1; kk += 2)\r\n    {\r\n        min_real = kk;\r\n\r\n\r\n        if (imag(p[kk]) > imag(p[kk + 1]))\r\n        {\r\n\r\n            min_real = kk + 1;\r\n\r\n            temp_max = p[kk];\r\n            p[kk] = p[min_real];\r\n            p[min_real] = temp_max;\r\n\r\n        }\r\n    }\r\n\r\n\r\n    // Initialize state - space matrices for running series\r\n    d[0] = 1;\r\n\r\n    int track_index = 1;\r\n\r\n    // Take care of any left over unmatched pole pairs.\r\n        // H(s) = 1 / (s ^ 2 + den(2)s + den(3))\r\n    std::vector<std::complex<double>> temp_poly_p;\r\n\r\n    double wn = 1;\r\n\r\n    if (order_filt > 1)\r\n    {\r\n\r\n        double b1[2] = { 1,0 };\r\n        double c1[2] = { 0,1 };\r\n        double d1 = 0;\r\n\r\n\r\n        temp_rem = remainder(order_filt, 2);\r\n        int order_filt_temp;\r\n        int dim_matr;\r\n        std::vector<std::vector<std::complex<double>> > temp_matrix_a;    //Temporary matrix where to save the coefficients at each interaction\r\n        int coeff_numb = 3;\r\n\r\n        if (temp_rem == 0)\r\n        {\r\n\r\n            order_filt_temp = order_filt;\r\n            dim_matr = order_filt_temp / 2;\r\n\r\n                std::vector<std::complex<double>> temp_v;\r\n\r\n                for (int ll = 0; ll < coeff_numb; ll++)\r\n                {\r\n\r\n                    temp_v.push_back(0);\r\n\r\n                }\r\n\r\n                for (int kk = 0; kk < dim_matr; kk++)\r\n                {\r\n\r\n                    temp_matrix_a.push_back(temp_v);\r\n                \r\n                }\r\n\r\n        }\r\n\r\n        else\r\n        {\r\n\r\n            order_filt_temp = order_filt - 1;\r\n            dim_matr = order_filt_temp / 2;\r\n\r\n                std::vector<std::complex<double>> temp_v;\r\n\r\n                for (int ll = 0; ll < coeff_numb; ll++)\r\n                {\r\n\r\n                    temp_v.push_back(0);\r\n\r\n                }\r\n\r\n                for (int kk = 0; kk < dim_matr; kk++)\r\n                {\r\n\r\n                    temp_matrix_a.push_back(temp_v);\r\n            \r\n                }\r\n\r\n        }\r\n\r\n        int track_cycles = 0;\r\n        int temp_val_pos_check;\r\n        int dim_poly_p = 2;\r\n        \r\n        for (int i = 0; i < dim_poly_p; i++)\r\n        {\r\n\r\n            temp_poly_p.push_back(0);\r\n\r\n        }\r\n\r\n        temp_dim_arr_matr = dim_poly_p + (order_filt % 2);\r\n\r\n        while (track_index < order_filt_temp)\r\n        {\r\n\r\n            for (int rr = track_index - 1; rr < track_index + 1; rr++)\r\n            {\r\n\r\n                temp_poly_p[rr - track_index + 1] = p[rr];\r\n\r\n            }\r\n\r\n            std::vector<std::complex<double>> coeff_pol(dim_poly_p + 1);\r\n\r\n            coeff_pol = poly(temp_poly_p, dim_poly_p);\r\n\r\n\r\n            for (int qq = 0; qq < coeff_numb; qq++)\r\n            {\r\n\r\n                temp_matrix_a[track_cycles][qq] = -real(coeff_pol[qq]);\r\n\r\n            }\r\n\r\n            //Update the state-space arrays/matrix\r\n            track_cycles += 1;\r\n\r\n                std::vector<std::complex<double>> temp_v;\r\n\r\n                for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n                {\r\n\r\n                    temp_v.push_back(0);\r\n\r\n                }\r\n\r\n                for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n                {\r\n\r\n                    a.push_back(temp_v);\r\n            \r\n                }\r\n\r\n            int track_index_coeff = 0;\r\n\r\n            if (remainder(order_filt, 2) == 0)\r\n            {\r\n                ///////////////////////////////////////////////////////////////////////////////////////////////\r\n                //Even number of poles\r\n                for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n                {\r\n\r\n                    for (int gg = 0; gg < temp_dim_arr_matr; gg++)\r\n\r\n                    {\r\n\r\n                        temp_val_pos_check = kk - gg;\r\n\r\n                        switch (temp_val_pos_check)\r\n                        {\r\n                        case 1:\r\n\r\n                            a[kk][gg] = 1;\r\n\r\n                            break;\r\n\r\n\r\n                        case 0:\r\n\r\n                            if ((remainder(kk + 1, 2) != 0) || (kk == 0))\r\n                            {\r\n\r\n                                a[kk][gg] = temp_matrix_a[track_index_coeff][1];\r\n\r\n                            }\r\n\r\n                            else\r\n                            {\r\n\r\n                                a[kk][gg] = 0;\r\n\r\n                            }\r\n\r\n                            break;\r\n\r\n                        case -1:\r\n\r\n                            if ((remainder(kk + 1, 2) != 0) || (kk == 0))\r\n                            {\r\n\r\n                                a[kk][gg] = temp_matrix_a[track_index_coeff][2];\r\n                                track_index_coeff++;\r\n\r\n                            }\r\n\r\n                            else\r\n                            {\r\n\r\n                                a[kk][gg] = 0;\r\n\r\n                            }\r\n                            break;\r\n\r\n                        default:\r\n\r\n                            a[kk][gg] = 0;\r\n\r\n                            break;\r\n\r\n\r\n                        }\r\n\r\n                    }\r\n\r\n                }\r\n                ///////////////////////////////////////////////////////////////////////////////////////////////\r\n            }\r\n\r\n            else\r\n            {\r\n                ///////////////////////////////////////////////////////////////////////////////////////////////\r\n                //Odd number of poles\r\n                for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n                {\r\n\r\n                    for (int gg = 0; gg < temp_dim_arr_matr; gg++)\r\n\r\n                    {\r\n\r\n                        temp_val_pos_check = kk - gg;\r\n\r\n                        switch (temp_val_pos_check)\r\n                        {\r\n                        case 1:\r\n\r\n                            a[kk][gg] = 1;\r\n\r\n                            break;\r\n\r\n\r\n                        case 0:\r\n\r\n                            if (kk == 0)\r\n                            {\r\n\r\n                                a[kk][gg] = -1;\r\n\r\n                            }\r\n\r\n                            else\r\n                            {\r\n\r\n                                if ((remainder(kk + 1, 2) == 0))\r\n                                {\r\n\r\n                                    a[kk][gg] = temp_matrix_a[track_index_coeff][1];\r\n\r\n                                }\r\n\r\n                                else\r\n                                {\r\n\r\n                                    a[kk][gg] = 0;\r\n\r\n                                }\r\n                            }\r\n\r\n                            break;\r\n\r\n                        case -1:\r\n\r\n                            if ((remainder(kk + 1, 2) == 0))\r\n                            {\r\n\r\n                                a[kk][gg] = temp_matrix_a[track_index_coeff][2];\r\n                                track_index_coeff++;\r\n\r\n                            }\r\n\r\n                            else\r\n                            {\r\n\r\n                                a[kk][gg] = 0;\r\n\r\n                            }\r\n                            break;\r\n\r\n                        default:\r\n\r\n                            a[kk][gg] = 0;\r\n\r\n                            break;\r\n\r\n\r\n                        }\r\n\r\n                    }\r\n\r\n                }\r\n\r\n            }\r\n             ///////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n             //Initialize the vectors \"b\" and \"c\"\r\n            for (int i = 0; i < temp_dim_arr_matr; i++)\r\n            {\r\n\r\n                b.push_back(0);\r\n                c.push_back(0);\r\n\r\n            }\r\n\r\n           \r\n            for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n            {\r\n\r\n                if (kk == 0)\r\n                {\r\n\r\n                    b[kk] = 1;\r\n\r\n                }\r\n\r\n                else\r\n                {\r\n\r\n                    b[kk] = 0;\r\n\r\n                }\r\n\r\n            }\r\n\r\n            for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n            {\r\n\r\n                if (kk == temp_dim_arr_matr - 1)\r\n                {\r\n\r\n                    c[kk] = 1;\r\n\r\n                }\r\n\r\n                else\r\n                {\r\n\r\n                    c[kk] = 0;\r\n\r\n                }\r\n\r\n            }\r\n\r\n            track_index += 2;\r\n\r\n            if (track_index < order_filt_temp)\r\n            {\r\n\r\n                //Clean up the matrix \"a\" and the arrays \"b\" and \"c\", so they can be re-initialized\r\n                a.erase(a.begin(), a.begin() + temp_dim_arr_matr);\r\n                b.erase(b.begin(), b.begin() + temp_dim_arr_matr);\r\n                c.erase(c.begin(), c.begin() + temp_dim_arr_matr);\r\n\r\n            }\r\n\r\n            dim_matr += 2;\r\n            temp_dim_arr_matr += 2;\r\n\r\n        }       \r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n\r\n        std::vector<std::complex<double>> temp_v;\r\n        temp_v.push_back(0);\r\n        a.push_back(temp_v);\r\n        a[0][0] = p[0];\r\n\r\n        b.push_back(1);\r\n        c.push_back(1);\r\n\r\n    }\r\n    \r\n    d[0] = 0;\r\n\r\n\r\n}\r\n\r\n\r\n//Extract the coefficients of the band pass filter\r\nstd::vector<std::vector<double> > IIR_Butterworth::lp2bp(double W_f1, double W_f2, int order_filt)\r\n{\r\n\r\n    //Check that the low cut-off frequency is higher than the low cut-off frequency\r\n    if (W_f2 <= W_f1)\r\n    {\r\n\r\n        throw new std::exception(\"The low cut-off frequency needs to be higher than the low cut-off frequency\");\r\n\r\n    }\r\n\r\n    //Check that the normalized frequencies are within the correct range of values\r\n    if ((W_f1 <= 0) || (W_f1 >= 1) || (W_f2 <= 0) || (W_f2 >= 1))\r\n    {\r\n\r\n        throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n    }\r\n\r\n    //Check that the order of the filter is > 0\r\n    if (order_filt <= 0)\r\n    {\r\n\r\n        throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n    }\r\n\r\n    //Clean up the global variables for a new analysis\r\n    if (save_filt_coeff.size() > 0)\r\n    {\r\n\r\n        save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n        ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n        p.erase(p.begin(), p.begin() + p.size());\r\n\r\n        a.erase(a.begin(), a.begin() + a.size());\r\n        b.erase(b.begin(), b.begin() + b.size());\r\n        c.erase(c.begin(), c.begin() + c.size());\r\n\r\n        num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n        den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n    }\r\n\r\n        std::vector<double> temp_v;\r\n\r\n        for (int ff = 0; ff < 2*order_filt + 1; ff++)\r\n        {\r\n\r\n            temp_v.push_back(0);\r\n\r\n        }\r\n\r\n        for (int hh = 0; hh < 2; hh++)\r\n        {\r\n\r\n            save_filt_coeff.push_back(temp_v);\r\n        \r\n        }\r\n\r\n    int type_filt = 0;\r\n\r\n    //Step 1: get analog, pre - warped frequencies\r\n    freq_pre_wrapped(type_filt, W_f1, W_f2); \r\n\r\n    \r\n    //Step 2: convert to low-pass prototype estimate\r\n    Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n    \r\n    //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n    buttap(order_filt);\r\n    \r\n    //Step 4: Transform to state-space\r\n    zp2ss(order_filt);\r\n\r\n    \r\n    if (order_filt > 1)\r\n    {\r\n\r\n        temp_dim_arr_matr -= 2;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        temp_dim_arr_matr = order_filt;\r\n\r\n    }\r\n\r\n    \r\n    //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n    a_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n    arma::cx_mat a_arma_p_eye = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    a_arma_p_eye = a_arma_p_eye.eye();\r\n    arma::cx_mat a_arma_n_eye = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    a_arma_n_eye = -a_arma_p_eye.eye();\r\n    b_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 1);\r\n    c_arma = arma::zeros <arma::cx_mat>(1, 2 * temp_dim_arr_matr);\r\n    d_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n\r\n    \r\n    double q = Wn / Bw;\r\n    for (int kk = 0; kk < 2 * temp_dim_arr_matr; kk++)\r\n    {\r\n        if (kk < temp_dim_arr_matr)\r\n        {\r\n\r\n            b_arma(kk, 0) = b[kk] * Wn / q;\r\n            c_arma(0, kk) = c[kk];\r\n\r\n        }\r\n\r\n        for (int ll = 0; ll < 2 * temp_dim_arr_matr; ll++)\r\n        {\r\n\r\n            if (kk < temp_dim_arr_matr)\r\n            {\r\n\r\n                if (ll < temp_dim_arr_matr)\r\n\r\n                {\r\n\r\n                    a_arma(kk, ll) = Wn * a[kk][ll] / q;\r\n\r\n                }\r\n\r\n                else\r\n                {\r\n\r\n                    a_arma(kk, ll) = Wn * a_arma_p_eye(kk, ll - temp_dim_arr_matr);\r\n\r\n                }\r\n            }\r\n\r\n            else\r\n            {\r\n                if (ll < temp_dim_arr_matr)\r\n                {\r\n\r\n                    a_arma(kk, ll) = Wn * a_arma_n_eye(kk - temp_dim_arr_matr, ll);\r\n\r\n                }\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    d_arma = d_arma;\r\n    \r\n\r\n    //Step 5: Use Bilinear transformation to find discrete equivalent\r\n    bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n    \r\n    //Step 6: Transform to zero-pole-gain and polynomial forms\r\n    zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n    return save_filt_coeff;\r\n\r\n}\r\n\r\n   \r\n//Extract the coefficients of the band stop filter\r\nstd::vector<std::vector<double> > IIR_Butterworth::lp2bs(double W_f1, double W_f2, int order_filt)\r\n{\r\n\r\n    //Check that the low cut-off frequency is higher than the low cut-off frequency\r\n    if (W_f2 <= W_f1)\r\n    {\r\n\r\n        throw new std::exception(\"The low cut-off frequency needs to be higher than the low cut-off frequency\");\r\n\r\n    }\r\n\r\n    //Check that the normalized frequencies are within the correct range of values\r\n    if ((W_f1 <= 0) || (W_f1 >= 1) || (W_f2 <= 0) || (W_f2 >= 1))\r\n    {\r\n\r\n        throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n    }\r\n\r\n    //Check that the order of the filter is > 0\r\n    if (order_filt <= 0)\r\n    {\r\n\r\n        throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n    }\r\n\r\n    //Clean up the global variables for a new analysis\r\n    if (save_filt_coeff.size() > 0)\r\n    {\r\n\r\n        save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n        ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n        p.erase(p.begin(), p.begin() + p.size());\r\n\r\n        a.erase(a.begin(), a.begin() + a.size());\r\n        b.erase(b.begin(), b.begin() + b.size());\r\n        c.erase(c.begin(), c.begin() + c.size());\r\n\r\n        num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n        den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n    }\r\n\r\n\r\n        std::vector<double> temp_v;\r\n\r\n        for (int ff = 0; ff < 2 * order_filt + 1; ff++)\r\n        {\r\n\r\n            temp_v.push_back(0);\r\n\r\n        }\r\n\r\n        for (int hh = 0; hh < 2; hh++)\r\n        {\r\n\r\n            save_filt_coeff.push_back(temp_v);\r\n\r\n        }\r\n\r\n    int type_filt = 1;\r\n\r\n    //Step 1: get analog, pre - warped frequencies\r\n    freq_pre_wrapped(type_filt, W_f1, W_f2);\r\n\r\n    //Step 2: convert to low-pass prototype estimate\r\n    Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n    //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n    buttap(order_filt);\r\n\r\n    //Step 4: Transform to state-space\r\n    zp2ss(order_filt);\r\n\r\n    if (order_filt > 1)\r\n    {\r\n\r\n        temp_dim_arr_matr -= 2;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        temp_dim_arr_matr = order_filt;\r\n\r\n    }\r\n\r\n    //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n    a_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n    arma::cx_mat a_arma_p_eye = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    a_arma_p_eye = a_arma_p_eye.eye();\r\n    arma::cx_mat a_arma_n_eye = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    a_arma_n_eye = -a_arma_p_eye.eye();\r\n    b_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 1);\r\n    c_arma = arma::zeros <arma::cx_mat>(1, 2 * temp_dim_arr_matr);\r\n    d_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n\r\n\r\n    arma::cx_mat a_arma_pinv = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    arma::cx_mat b_arma_temp = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, 1);\r\n    arma::cx_mat c_arma_temp = arma::zeros <arma::cx_mat>(1, temp_dim_arr_matr);\r\n\r\n    arma::cx_mat a_b_arma_temp = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, 1);\r\n    arma::cx_mat c_a_arma_temp = arma::zeros <arma::cx_mat>(1, temp_dim_arr_matr);\r\n\r\n    for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n    {\r\n        b_arma_temp(kk, 0) = b[kk];\r\n        c_arma_temp(0, kk) = c[kk];\r\n\r\n        for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n        {\r\n\r\n            a_arma_pinv(kk, ll) = a[kk][ll];\r\n\r\n        }\r\n\r\n    }\r\n\r\n    double q = Wn / Bw;\r\n\r\n    try\r\n    {\r\n\r\n        a_arma_pinv = (Wn / q) * arma::pinv(a_arma_pinv);\r\n\r\n    }\r\n\r\n    catch (std::runtime_error)\r\n    {\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n\r\n            for (int hh = 0; hh < 2 * order_filt + 1; hh++)\r\n            {\r\n\r\n                save_filt_coeff[kk][hh] = pow(10, 10);\r\n\r\n            }\r\n        \r\n\r\n        }\r\n        \r\n        return save_filt_coeff;\r\n\r\n    }\r\n\r\n\r\n    a_b_arma_temp = (Wn) * (a_arma_pinv * b_arma_temp) / q;\r\n    c_a_arma_temp = c_arma_temp * a_arma_pinv;\r\n\r\n    for (int kk = 0; kk < 2 * temp_dim_arr_matr; kk++)\r\n    {\r\n        if (kk < temp_dim_arr_matr)\r\n        {\r\n\r\n            b_arma(kk, 0) = -a_b_arma_temp(kk, 0);\r\n            c_arma(0, kk) = c_a_arma_temp(0, kk);\r\n\r\n        }\r\n\r\n        for (int ll = 0; ll < 2 * temp_dim_arr_matr; ll++)\r\n        {\r\n\r\n            if (kk < temp_dim_arr_matr)\r\n            {\r\n\r\n                if (ll < temp_dim_arr_matr)\r\n\r\n                {\r\n\r\n                    a_arma(kk, ll) = a_arma_pinv(kk, ll);\r\n\r\n                }\r\n\r\n                else\r\n                {\r\n\r\n                    a_arma(kk, ll) = Wn * a_arma_p_eye(kk, ll - temp_dim_arr_matr);\r\n\r\n                }\r\n            }\r\n\r\n            else\r\n            {\r\n                if (ll < temp_dim_arr_matr)\r\n                {\r\n\r\n                    a_arma(kk, ll) = Wn * a_arma_n_eye(kk - temp_dim_arr_matr, ll);\r\n\r\n                }\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n    d_arma = d[0] + c_a_arma_temp * b_arma_temp;\r\n\r\n    //Step 5: Use Bilinear transformation to find discrete equivalent\r\n    bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n    //Step 6: Transform to zero-pole-gain and polynomial forms\r\n    zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n    return save_filt_coeff;\r\n\r\n}\r\n\r\n//Extract the coefficients of the high pass filter\r\nstd::vector<std::vector<double> > IIR_Butterworth::lp2hp(double W_f2, int order_filt)\r\n{\r\n\r\n    //Check that the normalized frequencies are within the correct range of values\r\n    if ((W_f2 <= 0) || (W_f2 >= 1))\r\n    {\r\n\r\n        throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n    }\r\n\r\n    //Check that the order of the filter is > 0\r\n    if (order_filt <= 0)\r\n    {\r\n\r\n        throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n    }\r\n\r\n    //Clean up the global variables for a new analysis\r\n    if (save_filt_coeff.size() > 0)\r\n    {\r\n\r\n        save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n        ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n        p.erase(p.begin(), p.begin() + p.size());\r\n\r\n        a.erase(a.begin(), a.begin() + a.size());\r\n        b.erase(b.begin(), b.begin() + b.size());\r\n        c.erase(c.begin(), c.begin() + c.size());\r\n\r\n        num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n        den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n    }\r\n\r\n    std::vector<double> temp_v;\r\n\r\n    for (int ff = 0; ff < 2 * order_filt; ff++)\r\n    {\r\n\r\n        temp_v.push_back(0);\r\n\r\n    }\r\n\r\n    for (int hh = 0; hh < 2; hh++)\r\n    {\r\n\r\n        save_filt_coeff.push_back(temp_v);\r\n\r\n    }\r\n\r\n    int type_filt = 2;\r\n\r\n    //Step 1: get analog, pre - warped frequencies\r\n    freq_pre_wrapped(type_filt, W_f2, 0);\r\n\r\n    //Step 2: convert to low-pass prototype estimate\r\n    Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n    //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n    buttap(order_filt);\r\n\r\n    //Step 4: Transform to state-space\r\n    zp2ss(order_filt);\r\n\r\n    if (order_filt > 1)\r\n    {\r\n\r\n        temp_dim_arr_matr -= 2;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        temp_dim_arr_matr = order_filt;\r\n\r\n    }\r\n\r\n    //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n    a_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    b_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, 1);\r\n    c_arma = arma::zeros <arma::cx_mat>(1, temp_dim_arr_matr);\r\n    d_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n\r\n    for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n    {\r\n        b_arma(kk, 0) = b[kk];\r\n        c_arma(0, kk) = c[kk];\r\n\r\n        for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n        {\r\n\r\n            a_arma(kk, ll) = a[kk][ll];\r\n\r\n        }\r\n\r\n    }\r\n\r\n    try\r\n    {\r\n\r\n        d_arma = d_arma - (c_arma * arma::pinv(a_arma)) * b_arma;\r\n\r\n    }\r\n\r\n    catch (std::runtime_error)\r\n    {\r\n\r\n        for (int kk = 0; kk < 2; kk++)\r\n        {\r\n\r\n            for (int hh = 0; hh < order_filt + 1; hh++)\r\n            {\r\n\r\n                save_filt_coeff[kk][hh] = pow(10, 10);\r\n\r\n            }\r\n\r\n\r\n        }\r\n\r\n        return save_filt_coeff;\r\n\r\n    }\r\n\r\n    c_arma = c_arma * arma::pinv(a_arma);\r\n    b_arma = -Wn * arma::pinv(a_arma) * b_arma;\r\n    a_arma = Wn * arma::pinv(a_arma);\r\n\r\n\r\n    //Step 5: Use Bilinear transformation to find discrete equivalent\r\n    bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n    //Step 6: Transform to zero-pole-gain and polynomial forms\r\n    zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n    return save_filt_coeff;\r\n\r\n}\r\n\r\n\r\n//Extract the coefficients of the low pass filter\r\nstd::vector<std::vector<double> > IIR_Butterworth::lp2lp(double W_f1, int order_filt)\r\n{\r\n    //Check that the normalized frequencies are within the correct range of values\r\n    if ((W_f1 <= 0) || (W_f1 >= 1))\r\n    {\r\n\r\n        throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n    }\r\n\r\n    //Check that the order of the filter is > 0\r\n    if (order_filt <= 0)\r\n    {\r\n\r\n        throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n    }\r\n\r\n    //Clean up the global variables for a new analysis\r\n    if (save_filt_coeff.size() > 0)\r\n    {\r\n\r\n        save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n        ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n        p.erase(p.begin(), p.begin() + p.size());\r\n\r\n        a.erase(a.begin(), a.begin() + a.size());\r\n        b.erase(b.begin(), b.begin() + b.size());\r\n        c.erase(c.begin(), c.begin() + c.size());\r\n\r\n        num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n        den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n    }\r\n\r\n\r\n        std::vector<double> temp_v;\r\n\r\n        for (int ff = 0; ff < 2 * order_filt; ff++)\r\n        {\r\n\r\n            temp_v.push_back(0);\r\n\r\n        }\r\n\r\n        for (int hh = 0; hh < 2; hh++)\r\n        {\r\n\r\n            save_filt_coeff.push_back(temp_v);\r\n\r\n        }\r\n\r\n    int type_filt = 3;\r\n\r\n    //Step 1: get analog, pre - warped frequencies\r\n    freq_pre_wrapped(type_filt, 0, W_f1);\r\n\r\n    //Step 2: convert to low-pass prototype estimate\r\n    Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n    //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n    buttap(order_filt);\r\n\r\n    //Step 4: Transform to state-space\r\n    zp2ss(order_filt);\r\n\r\n    if (order_filt > 1)\r\n    {\r\n\r\n        temp_dim_arr_matr -= 2;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        temp_dim_arr_matr = order_filt;\r\n\r\n    }\r\n\r\n    //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n    a_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n    b_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, 1);\r\n    c_arma = arma::zeros <arma::cx_mat>(1, temp_dim_arr_matr);\r\n    d_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n\r\n    for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n    {\r\n        b_arma(kk, 0) = b[kk];\r\n        c_arma(0, kk) = c[kk];\r\n\r\n        for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n        {\r\n\r\n            a_arma(kk, ll) = a[kk][ll];\r\n\r\n        }\r\n\r\n    }\r\n\r\n    d_arma = d_arma;\r\n    c_arma = c_arma;\r\n    b_arma = Wn * b_arma;\r\n    a_arma = Wn * a_arma;\r\n\r\n\r\n    //Step 5: Use Bilinear transformation to find discrete equivalent\r\n    bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n    //Step 6: Transform to zero-pole-gain and polynomial forms\r\n    zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n    return save_filt_coeff;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n//Step 5: Use Bilinear transformation to find discrete equivalent\r\nvoid IIR_Butterworth::bilinear(arma::cx_mat a_arma_f, arma::cx_mat b_arma_f, arma::cx_mat c_arma_f, arma::cx_mat d_arma_f, double fs_f, int type_filt_f)\r\n{\r\n\r\n    double t_arma;\r\n    double r_arma;\r\n\r\n    if (type_filt_f > 1)\r\n    {\r\n        t1_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n        t2_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n        ad_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, temp_dim_arr_matr);\r\n        bd_arma = arma::zeros <arma::cx_mat>(temp_dim_arr_matr, 1);\r\n        cd_arma = arma::zeros <arma::cx_mat>(1, temp_dim_arr_matr);\r\n        dd_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        t1_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n        t2_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n        ad_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n        bd_arma = arma::zeros <arma::cx_mat>(2 * temp_dim_arr_matr, 1);\r\n        cd_arma = arma::zeros <arma::cx_mat>(1, 2 * temp_dim_arr_matr);\r\n        dd_arma = arma::zeros <arma::cx_mat>(1, 1);\r\n\r\n    }\r\n\r\n    try\r\n    {\r\n        t_arma = (1 / fs_f);\r\n        r_arma = sqrt(t_arma);\r\n        t1_arma = t1_arma.eye() + a_arma_f * t_arma * 0.5; //t1_arma.eye() \r\n        t2_arma = t2_arma.eye() - a_arma_f * t_arma * 0.5;\r\n        ad_arma = t1_arma * arma::pinv(t2_arma);\r\n        bd_arma = (t_arma / r_arma) * arma::solve(t2_arma, b_arma_f);\r\n        cd_arma = (r_arma * c_arma_f) * arma::pinv(t2_arma);\r\n        dd_arma = (c_arma_f * arma::pinv(t2_arma)) * b_arma_f * (t_arma / 2) + d_arma_f;\r\n    }\r\n\r\n    catch (std::runtime_error)\r\n    {\r\n\r\n\r\n\r\n    }\r\n}\r\n\r\n\r\n\r\n//Step 6: Transform to zero-pole-gain and polynomial forms\r\nvoid IIR_Butterworth::zero_pole_gain(arma::cx_mat a_arma_f, int type_filt_f, int order_filt_f, double Wn_f_f, double Bw_f)\r\n{\r\n\r\n    int dim_array;\r\n\r\n    if (type_filt_f > 1)\r\n    {\r\n\r\n        //Initialize the vectors \"num_filt\" and \"den_filt\"\r\n        for (int i = 0; i < order_filt_f + 1; i++)\r\n        {\r\n\r\n            num_filt.push_back(0);\r\n            den_filt.push_back(0);\r\n\r\n        }\r\n\r\n\r\n        dim_array = temp_dim_arr_matr;\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        //Initialize the vectors \"num_filt\" and \"den_filt\"\r\n        for (int i = 0; i < 2 * order_filt_f + 1; i++)\r\n        {\r\n\r\n            num_filt.push_back(0);\r\n            den_filt.push_back(0);\r\n\r\n        }\r\n\r\n\r\n        dim_array = 2 * temp_dim_arr_matr;\r\n\r\n    }\r\n\r\n    //Extract the coefficients of the denumerator\r\n    std::vector<std::complex<double>> coeff_pol(temp_dim_arr_matr + 1);\r\n\r\n    if (type_filt_f > 1)\r\n\r\n    {\r\n\r\n        coeff_pol = char_poly(a_arma_f, temp_dim_arr_matr);\r\n\r\n    }\r\n\r\n    else\r\n    {\r\n\r\n        coeff_pol = char_poly(a_arma_f, 2 * temp_dim_arr_matr);\r\n\r\n    }\r\n\r\n\r\n    for (int qq = 0; qq < dim_array + 1; qq++)\r\n    {\r\n\r\n        den_filt[qq] = real(coeff_pol[qq]);\r\n        save_filt_coeff[1][qq] = den_filt[qq];\r\n\r\n    }\r\n\r\n\r\n    //Extract the coefficients of the denominator\r\n    double w;\r\n    Wn = 2 * std::atan2(Wn, 4);\r\n    std::vector<std::complex<double>> r;\r\n\r\n    switch (type_filt_f)\r\n    {\r\n\r\n    case 0: // band-pass\r\n\r\n        for (int i = 0; i <= dim_array; i++)\r\n        {\r\n\r\n            r.push_back(0);\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < dim_array; kk++)\r\n        {\r\n\r\n            if (kk < temp_dim_arr_matr)\r\n            {\r\n\r\n                r[kk] = 1;\r\n\r\n            }\r\n\r\n            else\r\n            {\r\n\r\n                r[kk] = -1;\r\n\r\n            }\r\n\r\n        }\r\n\r\n        w = Wn;\r\n\r\n        break;\r\n\r\n    case 1: // band-stop\r\n\r\n        for (int i = 0; i <= dim_array; i++)\r\n        {\r\n\r\n            r.push_back(0);\r\n\r\n        }\r\n\r\n\r\n        for (int kk = 0; kk < dim_array; kk++)\r\n        {\r\n\r\n            r[kk] = exp(complex_imag * Wn * pow(-1, kk));\r\n\r\n        }\r\n        w = 0;\r\n\r\n        break;\r\n\r\n    case 2: //high-pass\r\n\r\n        for (int i = 0; i <= dim_array; i++)\r\n        {\r\n\r\n            r.push_back(0);\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < dim_array; kk++)\r\n        {\r\n\r\n            r[kk] = 1;\r\n\r\n        }\r\n\r\n        w = PI;\r\n        break;\r\n\r\n    case 3: // low-pass\r\n\r\n        for (int i = 0; i <= dim_array; i++)\r\n        {\r\n\r\n            r.push_back(0);\r\n\r\n        }\r\n\r\n        for (int kk = 0; kk < dim_array; kk++)\r\n        {\r\n\r\n            r[kk] = -1;\r\n\r\n        }\r\n        w = 0;\r\n        break;\r\n\r\n    default:\r\n        for (int i = 0; i <= dim_array; i++)\r\n        {\r\n\r\n            r.push_back(0);\r\n\r\n        }\r\n\r\n    }\r\n\r\n    std::vector<std::complex<double>> coeff_pol_num(dim_array + 1);\r\n\r\n    coeff_pol_num = poly(r, dim_array);\r\n\r\n    std::vector<std::complex<double>> kern(dim_array + 1);\r\n\r\n    for (int kk = 0; kk < dim_array + 1; kk++)\r\n    {\r\n\r\n        kern[kk] = exp(-complex_imag * w * double(kk));\r\n\r\n    }\r\n\r\n    std::complex<double> temp_sum_I;\r\n    std::complex<double> temp_sum_II;\r\n\r\n     for (int kk = 0; kk < dim_array + 1; kk++)\r\n    {\r\n\r\n        temp_sum_I = 0.0;\r\n        temp_sum_II = 0.0;\r\n\r\n        for (int hh = 0; hh < dim_array + 1; hh++)\r\n        {\r\n\r\n            temp_sum_I += kern[hh] * den_filt[hh];\r\n            temp_sum_II += kern[hh] * coeff_pol_num[hh];\r\n\r\n        }\r\n\r\n        num_filt[kk] = real(coeff_pol_num[kk] * temp_sum_I / temp_sum_II);\r\n        save_filt_coeff[0][kk] = num_filt[kk];\r\n\r\n    }\r\n\r\n}\r\n    //Check the stability of the filter\r\n    bool IIR_Butterworth::check_stability_iir(std::vector<std::vector<double> > coeff_filt)\r\n    {\r\n        bool stability_flag = true;\r\n\r\n        //Calculate the roots\r\n        arma::mat roots_den_matrix = arma::zeros(coeff_filt[1].size() - 1, coeff_filt[1].size() - 1);\r\n        for (int kk = 0; kk < coeff_filt[1].size() - 2; kk++)\r\n        {\r\n\r\n            roots_den_matrix(kk + 1, kk) = 1;\r\n\r\n        }\r\n\r\n         for (int kk = 0; kk < coeff_filt[1].size() - 1; kk++)\r\n        {\r\n\r\n            roots_den_matrix(0, kk) = -coeff_filt[1][kk + 1];\r\n\r\n        }\r\n        \r\n         \r\n        std::vector<double> magnitude_roots_den (coeff_filt[1].size() - 1);\r\n        arma::cx_vec roots_den;\r\n        arma::cx_mat eigvec;\r\n\r\n        arma::eig_gen(roots_den,eigvec, roots_den_matrix);\r\n        \r\n        for (int kk = 0; kk < coeff_filt[1].size() - 1; kk++)\r\n        {\r\n\r\n            magnitude_roots_den[kk] = abs(roots_den[kk]);\r\n\r\n            if (magnitude_roots_den[kk] >= 1)\r\n            {\r\n\r\n                stability_flag = false;\r\n                break;\r\n            }\r\n\r\n        }\r\n\r\n        return stability_flag;\r\n\r\n    }\r\n    \r\n//Filter the data by using the Direct-Form II Transpose, as explained in the Matlab documentation\r\nstd::vector<double> IIR_Butterworth::Filter_Data(std::vector<std::vector<double> > coeff_filt, std::vector<double> pre_filt_signal)\r\n{\r\n\r\n        std::vector<double> filt_signal(pre_filt_signal.size(), 0.0);\r\n\r\n        std::vector<std::vector<double>> w_val;\r\n        std::vector<double> temp_v;\r\n\r\n        for (int ff = 0; ff < pre_filt_signal.size(); ff++)\r\n        {\r\n\r\n                temp_v.push_back(0);\r\n\r\n        }\r\n\r\n        for (int hh = 0; hh < coeff_filt[0].size(); hh++)\r\n        {\r\n\r\n                w_val.push_back(temp_v);\r\n\r\n        }\r\n\r\n\r\n        //Convolution product to filter the data\r\n        for (int kk = 0; kk < pre_filt_signal.size(); kk++)\r\n        {\r\n\r\n                if (kk == 0)\r\n                {\r\n\r\n                        filt_signal[kk] = pre_filt_signal[kk] * coeff_filt[0][0];\r\n\r\n                        for (int ww = 1; ww < coeff_filt[0].size(); ww++)\r\n                        {\r\n\r\n                                w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n        }\r\n\r\n                }\r\n\r\n                else\r\n                {\r\n\r\n                        filt_signal[kk] = pre_filt_signal[kk] * coeff_filt[0][0] + w_val[0][kk - 1];\r\n\r\n                                for (int ww = 1; ww < coeff_filt[0].size(); ww++)\r\n                                {\r\n\r\n                                        w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] + w_val[ww][kk - 1] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n                                        if (ww == coeff_filt[0].size() - 1)\r\n                                        {\r\n\r\n                                                 w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n                                        }\r\n\r\n                                }\r\n\r\n                }\r\n\r\n        }\r\n\r\n\r\n        return filt_signal;\r\n\r\n}\r\n", "meta": {"hexsha": "811f9e432a924fcfd2910025e91bb5a8156fb88f", "size": 44955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IIR_Butterworth_H.cpp", "max_stars_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_stars_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IIR_Butterworth_H.cpp", "max_issues_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_issues_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IIR_Butterworth_H.cpp", "max_forks_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_forks_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_forks_repo_licenses": ["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.1726804124, "max_line_length": 174, "alphanum_fraction": 0.4678011345, "num_tokens": 11614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6513847465735467}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace arma;\n\nint\nmain()\n  {\n  std::cout << \"*** smoke test start\" << std::endl;\n  \n  uword N = 5;\n  \n  mat A = reshape(regspace(1, N*N), N, N);\n  \n  A.diag() += randu<vec>(N);\n  \n  mat B;\n  \n  bool status = expmat(B,A);\n  \n  A.print(\"A:\");\n  B.print(\"B:\");\n  \n  std::cout << ((status) ? \"*** smoke test okay\" : \"*** smoke test failed\") << std::endl;\n  \n  return (status) ? 0 : -1;\n  }\n", "meta": {"hexsha": "0fc83ea558fc5e66bb4c5466484bd930916c666d", "size": 437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/armadillo-10.1.2/tests1/smoke_test.cpp", "max_stars_repo_name": "hb407/libnome", "max_stars_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T20:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:58:36.000Z", "max_issues_repo_path": "external/armadillo-10.1.2/tests1/smoke_test.cpp", "max_issues_repo_name": "hb407/libnome", "max_issues_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-06T22:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T09:37:56.000Z", "max_forks_repo_path": "external/armadillo-10.1.2/tests1/smoke_test.cpp", "max_forks_repo_name": "hb407/libnome", "max_forks_repo_head_hexsha": "cf11c6e34e6d147e28bfc6f54dd3ca81d2443438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T16:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:28:31.000Z", "avg_line_length": 15.6071428571, "max_line_length": 89, "alphanum_fraction": 0.5194508009, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6513549687440247}}
{"text": "#include \"catch.hpp\"\n\n#include \"libirc/mathtools.h\"\n\n#include <cmath> // nextafter\n\n#ifdef HAVE_ARMA\n#include <armadillo>\nusing vec3 = arma::vec3;\nusing vec = arma::vec;\nusing mat = arma::mat;\ntemplate<typename T>\nusing Mat = arma::Mat<T>;\n#elif HAVE_EIGEN3\n#include <Eigen/Dense>\nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\ntemplate<typename T>\nusing Mat = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n#else\n#error\n#endif\n\nusing namespace irc;\n\nusing tools::constants::pi;\nusing namespace tools::math;\n\nTEST_CASE(\"pirange_rad produces angles in the interval (-pi,pi]\") {\n\n  const auto inclusive_angle = pi;\n  CAPTURE(inclusive_angle);\n\n  CHECK(pirange_rad(-pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(0) == 0);\n  CHECK(pirange_rad(pi) == Approx(inclusive_angle));\n  CHECK(std::nextafter(pi, 0) < pi);\n  CHECK(pirange_rad(std::nextafter(pi, 0)) == Approx(pi));\n  CHECK(pirange_rad(std::nextafter(pi, 2 * pi)) == Approx(-pi));\n  CHECK(pirange_rad(std::nextafter(-pi, -2 * pi)) == Approx(pi));\n  CHECK(pirange_rad(std::nextafter(-pi, 0)) == Approx(-pi));\n\n  CHECK(pirange_rad(2 * pi) == Approx(0));\n  CHECK(pirange_rad(4 * pi) == Approx(0));\n  CHECK(pirange_rad(6 * pi) == Approx(0));\n  CHECK(pirange_rad(8 * pi) == Approx(0));\n  CHECK(pirange_rad(1 * pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(3 * pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(5 * pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(-1 * pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(-3 * pi) == Approx(inclusive_angle));\n  CHECK(pirange_rad(-5 * pi) == Approx(inclusive_angle));\n\n  CHECK(pirange_rad(pi / 2.) == Approx(pi / 2.));\n  CHECK(pirange_rad(-pi / 2.) == Approx(-pi / 2.));\n  CHECK(pirange_rad(pi / 2. + pi) == Approx(-pi / 2.));\n  CHECK(pirange_rad(-pi / 2. - pi) == Approx(pi / 2.));\n}\n\nTEST_CASE(\"pirange_deg produces angles in the interval (-180,180]\") {\n\n  const auto inclusive_angle = 180.0;\n  CAPTURE(inclusive_angle);\n\n  CHECK(pirange_deg(-180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(0) == 0);\n  CHECK(pirange_deg(180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(std::nextafter(180, 0)) == Approx(180));\n  CHECK(pirange_deg(std::nextafter(180, 2 * 180)) == Approx(-180));\n  CHECK(pirange_deg(std::nextafter(-180, -2 * 180)) == Approx(180));\n  CHECK(pirange_deg(std::nextafter(-180, 0)) == Approx(-180));\n\n  CHECK(pirange_deg(2 * 180) == Approx(0));\n  CHECK(pirange_deg(4 * 180) == Approx(0));\n  CHECK(pirange_deg(6 * 180) == Approx(0));\n  CHECK(pirange_deg(8 * 180) == Approx(0));\n  CHECK(pirange_deg(1 * 180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(3 * 180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(5 * 180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(-1 * 180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(-3 * 180) == Approx(inclusive_angle));\n  CHECK(pirange_deg(-5 * 180) == Approx(inclusive_angle));\n\n  CHECK(pirange_deg(90) == Approx(90));\n  CHECK(pirange_deg(-90) == Approx(-90));\n  CHECK(pirange_deg(270) == Approx(-90));\n  CHECK(pirange_deg(-270) == Approx(90));\n}\n\nTEST_CASE(\"collinear vectors\") {\n\n  vec3 v1 = {1., 0., 0.};\n  vec3 v2 = {2., 0., 0.};\n  vec3 v3 = {-0.5, 0., 0.};\n  vec3 v4 = {1., 1., 1.};\n\n  CHECK(collinear(v1, v2));\n  CHECK(collinear(v1, v3));\n  CHECK(collinear(v2, v3));\n\n  CHECK(!collinear(v1, v4));\n  CHECK(!collinear(v2, v4));\n  CHECK(!collinear(v3, v4));\n}", "meta": {"hexsha": "d26597b6fadf08d586a01af36873bb76f88cf1be", "size": 3397, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/mathtools_test.cpp", "max_stars_repo_name": "francesco-bosia/irc", "max_stars_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T16:12:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:20:23.000Z", "max_issues_repo_path": "src/test/mathtools_test.cpp", "max_issues_repo_name": "francesco-bosia/irc", "max_issues_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T13:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T19:59:39.000Z", "max_forks_repo_path": "src/test/mathtools_test.cpp", "max_forks_repo_name": "francesco-bosia/irc", "max_forks_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T10:00:16.000Z", "avg_line_length": 32.3523809524, "max_line_length": 69, "alphanum_fraction": 0.6591109803, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6513549521939117}}
{"text": "\n// Copyright (C) 2006  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/matrix.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../stl_checked.h\"\n#include \"../array.h\"\n#include \"../rand.h\"\n\n#include \"tester.h\"\n#include <dlib/memory_manager_stateless.h>\n#include <dlib/array2d.h>\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    dlib::rand rnd;\n\n    logger dlog(\"test.matrix\");\n\n    template <typename type>\n    const matrix<type> rand_sp_banded(long n, long bw)\n    {\n        matrix<type> m = 10 * identity_matrix<type>(n);\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = row; col < min(m.nc(), row + bw); ++col)\n            {\n                type r = rnd.get_random_double();\n                m(row,col) += r;\n                m(col,row) += r; \n            }\n        }\n\n        return m;\n    }\n\n    void matrix_test (\n    )\n    /*!\n        ensures\n            - runs tests on the matrix stuff compliance with the specs\n    !*/\n    {        \n        typedef memory_manager_stateless<char>::kernel_2_2a MM;\n        print_spinner();\n\n\n        {\n            matrix<complex<double>,2,2,MM> m;\n            set_all_elements(m,complex<double>(1,2));\n            DLIB_TEST((conj(m) == uniform_matrix<complex<double>,2,2>(conj(m(0,0)))));\n            DLIB_TEST((real(m) == uniform_matrix<double,2,2>(1)));\n            DLIB_TEST((imag(m) == uniform_matrix<double,2,2>(2)));\n            DLIB_TEST_MSG((sum(abs(norm(m) - uniform_matrix<double,2,2>(5))) < 1e-10 ),norm(m));\n\n        }\n\n        {\n            matrix<double,5,5,MM,column_major_layout> m(5,5);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix(m))));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix(m))));\n\n            mi = pinv(m,1e-12); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix(m))));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix(m))));\n\n            m = diagm(diag(m));\n            mi = pinv(diagm(diag(m)),1e-12); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix(m))));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix(m))));\n\n            mi = pinv(m,0); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix(m))));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix(m))));\n\n            m = diagm(diag(m));\n            mi = pinv(diagm(diag(m)),0); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix(m))));\n            DLIB_TEST((equal(round_zeros(m*mi,0.000001) , identity_matrix(m))));\n        }\n        {\n            matrix<double,5,0,MM> m(5,5);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n        }\n\n        {\n            matrix<double,0,5,MM> m(5,5);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n        }\n\n\n        {\n            matrix<double> m(5,5);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,5>())));\n        }\n\n        {\n            matrix<double,5,2,MM,column_major_layout> m;\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,2>())));\n        }\n\n        {\n            matrix<double> m(5,2);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = pinv(m ); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,2>())));\n        }\n\n        {\n            matrix<double,5,2,MM,column_major_layout> m;\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = trans(pinv(trans(m) )); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,2>())));\n        }\n\n        {\n            matrix<double> m(5,2);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c; \n                }\n            }\n\n            m = cos(exp(m));\n\n\n            matrix<double> mi = trans(pinv(trans(m) )); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*m,0.000001) , identity_matrix<double,2>())));\n        }\n\n        {\n            matrix<long> a1(5,1);\n            matrix<long,0,0,MM,column_major_layout> a2(1,5);\n            matrix<long,5,1> b1(5,1);\n            matrix<long,1,5> b2(1,5);\n            matrix<long,0,1> c1(5,1);\n            matrix<long,1,0> c2(1,5);\n            matrix<long,0,1,MM,column_major_layout> d1(5,1);\n            matrix<long,1,0,MM> d2(1,5);\n\n            for (long i = 0; i < 5; ++i)\n            {\n                a1(i) = i;\n                a2(i) = i;\n                b1(i) = i;\n                b2(i) = i;\n                c1(i) = i;\n                c2(i) = i;\n                d1(i) = i;\n                d2(i) = i;\n            }\n\n            DLIB_TEST(a1 == trans(a2));\n            DLIB_TEST(a1 == trans(b2));\n            DLIB_TEST(a1 == trans(c2));\n            DLIB_TEST(a1 == trans(d2));\n\n            DLIB_TEST(a1 == b1);\n            DLIB_TEST(a1 == c1);\n            DLIB_TEST(a1 == d1);\n\n            DLIB_TEST(trans(a1) == c2);\n            DLIB_TEST(trans(b1) == c2);\n            DLIB_TEST(trans(c1) == c2);\n            DLIB_TEST(trans(d1) == c2);\n\n            DLIB_TEST(sum(a1) == 10);\n            DLIB_TEST(sum(a2) == 10);\n            DLIB_TEST(sum(b1) == 10);\n            DLIB_TEST(sum(b2) == 10);\n            DLIB_TEST(sum(c1) == 10);\n            DLIB_TEST(sum(c2) == 10);\n            DLIB_TEST(sum(d1) == 10);\n            DLIB_TEST(sum(d2) == 10);\n\n            const matrix<long> orig1 = a1;\n            const matrix<long> orig2 = a2;\n\n            ostringstream sout;\n            serialize(a1,sout);\n            serialize(a2,sout);\n            serialize(b1,sout);\n            serialize(b2,sout);\n            serialize(c1,sout);\n            serialize(c2,sout);\n            serialize(d1,sout);\n            serialize(d2,sout);\n\n            DLIB_TEST(a1 == orig1);\n            DLIB_TEST(a2 == orig2);\n            DLIB_TEST(b1 == orig1);\n            DLIB_TEST(b2 == orig2);\n            DLIB_TEST(c1 == orig1);\n            DLIB_TEST(c2 == orig2);\n            DLIB_TEST(d1 == orig1);\n            DLIB_TEST(d2 == orig2);\n\n            set_all_elements(a1,99);\n            set_all_elements(a2,99);\n            set_all_elements(b1,99);\n            set_all_elements(b2,99);\n            set_all_elements(c1,99);\n            set_all_elements(c2,99);\n            set_all_elements(d1,99);\n            set_all_elements(d2,99);\n\n            DLIB_TEST(a1 != orig1);\n            DLIB_TEST(a2 != orig2);\n            DLIB_TEST(b1 != orig1);\n            DLIB_TEST(b2 != orig2);\n            DLIB_TEST(c1 != orig1);\n            DLIB_TEST(c2 != orig2);\n            DLIB_TEST(d1 != orig1);\n            DLIB_TEST(d2 != orig2);\n\n            istringstream sin(sout.str());\n\n            deserialize(a1,sin);\n            deserialize(a2,sin);\n            deserialize(b1,sin);\n            deserialize(b2,sin);\n            deserialize(c1,sin);\n            deserialize(c2,sin);\n            deserialize(d1,sin);\n            deserialize(d2,sin);\n\n            DLIB_TEST(a1 == orig1);\n            DLIB_TEST(a2 == orig2);\n            DLIB_TEST(b1 == orig1);\n            DLIB_TEST(b2 == orig2);\n            DLIB_TEST(c1 == orig1);\n            DLIB_TEST(c2 == orig2);\n            DLIB_TEST(d1 == orig1);\n            DLIB_TEST(d2 == orig2);\n\n\n        }\n\n        {\n            matrix<double,1,0> a(5);\n            matrix<double,0,1> b(5);\n            matrix<double,1,5> c(5);\n            matrix<double,5,1> d(5);\n            DLIB_TEST(a.nr() == 1);\n            DLIB_TEST(a.nc() == 5);\n            DLIB_TEST(c.nr() == 1);\n            DLIB_TEST(c.nc() == 5);\n\n            DLIB_TEST(b.nc() == 1);\n            DLIB_TEST(b.nr() == 5);\n            DLIB_TEST(d.nc() == 1);\n            DLIB_TEST(d.nr() == 5);\n        }\n\n        {\n            matrix<double,1,0> a;\n            matrix<double,0,1> b;\n            matrix<double,1,5> c;\n            matrix<double,5,1> d;\n\n            a.set_size(5);\n            b.set_size(5);\n            c.set_size(5);\n            d.set_size(5);\n\n            DLIB_TEST(a.nr() == 1);\n            DLIB_TEST(a.nc() == 5);\n            DLIB_TEST(c.nr() == 1);\n            DLIB_TEST(c.nc() == 5);\n\n            DLIB_TEST(b.nc() == 1);\n            DLIB_TEST(b.nr() == 5);\n            DLIB_TEST(d.nc() == 1);\n            DLIB_TEST(d.nr() == 5);\n        }\n\n        {\n            matrix<double> a(1,5);\n            matrix<double> b(5,1);\n\n            set_all_elements(a,1);\n            set_all_elements(b,1);\n\n\n            a = a*b;\n\n            DLIB_TEST(a(0) == 5);\n        }\n\n        {\n            matrix<double,0,0,MM,column_major_layout> a(6,7);\n\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = r*a.nc() + c;\n                }\n            }\n\n\n\n            DLIB_TEST(rowm(a,1).nr() == 1);\n            DLIB_TEST(rowm(a,1).nc() == a.nc());\n            DLIB_TEST(colm(a,1).nr() == a.nr());\n            DLIB_TEST(colm(a,1).nc() == 1);\n\n            for (long c = 0; c < a.nc(); ++c)\n            {\n                DLIB_TEST( rowm(a,1)(c) == 1*a.nc() + c);\n            }\n\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                DLIB_TEST( colm(a,1)(r) == r*a.nc() + 1);\n            }\n\n            rectangle rect(2, 1, 3+2-1, 2+1-1);\n            DLIB_TEST(get_rect(a).contains(get_rect(a)));\n            DLIB_TEST(get_rect(a).contains(rect));\n            for (long r = 0; r < 2; ++r)\n            {\n                for (long c = 0; c < 3; ++c)\n                {\n                    DLIB_TEST(subm(a,1,2,2,3)(r,c) == (r+1)*a.nc() + c+2);\n                    DLIB_TEST(subm(a,1,2,2,3) == subm(a,rect));\n                    DLIB_TEST(subm_clipped(a,1,2,2,3) == subm(a,rect));\n                    DLIB_TEST(subm_clipped(a,1,2,2,3) == subm_clipped(a,rect));\n                }\n            }\n\n            DLIB_TEST(subm(a,rectangle()).nr() == 0);\n            DLIB_TEST(subm(a,rectangle()).nc() == 0);\n\n        }\n\n        {\n            array2d<double> a;\n            a.set_size(6,7);\n\n\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a[r][c] = r*a.nc() + c;\n                }\n            }\n\n\n\n            DLIB_TEST(rowm(mat(a),1).nr() == 1);\n            DLIB_TEST(rowm(mat(a),1).nc() == a.nc());\n            DLIB_TEST(colm(mat(a),1).nr() == a.nr());\n            DLIB_TEST(colm(mat(a),1).nc() == 1);\n\n            for (long c = 0; c < a.nc(); ++c)\n            {\n                DLIB_TEST( rowm(mat(a),1)(c) == 1*a.nc() + c);\n            }\n\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                DLIB_TEST( colm(mat(a),1)(r) == r*a.nc() + 1);\n            }\n\n            for (long r = 0; r < 2; ++r)\n            {\n                for (long c = 0; c < 3; ++c)\n                {\n                    DLIB_TEST(subm(mat(a),1,2,2,3)(r,c) == (r+1)*a.nc() + c+2);\n                }\n            }\n\n\n        }\n\n        {\n            array2d<double> m;\n            m.set_size(5,5);\n\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m[r][c] = r*c; \n                }\n            }\n\n\n            matrix<double> mi = pinv(cos(exp(mat(m))) ); \n            DLIB_TEST(mi.nr() == m.nc());\n            DLIB_TEST(mi.nc() == m.nr());\n            DLIB_TEST((equal(round_zeros(mi*cos(exp(mat(m))),0.000001) , identity_matrix<double,5>())));\n            DLIB_TEST((equal(round_zeros(cos(exp(mat(m)))*mi,0.000001) , identity_matrix<double,5>())));\n        }\n\n        {\n            matrix<long,5,5,MM,column_major_layout> m1, res;\n            matrix<long,2,2> m2;\n\n            set_all_elements(m1,0);\n\n\n            long res_vals[] = {\n                9, 9, 9, 9, 9,\n                0, 1, 1, 0, 0,\n                0, 1, 1, 0, 2,\n                0, 0, 2, 2, 2,\n                0, 0, 2, 2, 0\n            };\n\n            res = res_vals;\n\n            set_all_elements(m2, 1);\n            set_subm(m1, range(1,2), range(1,2)) = subm(m2,0,0,2,2);\n            set_all_elements(m2, 2);\n            set_subm(m1, 3,2,2,2) = m2;\n\n            set_colm(m1,4) = trans(rowm(m1,4));\n            set_rowm(m1,0) = 9;\n\n            DLIB_TEST_MSG(m1 == res, \"m1: \\n\" << m1 << \"\\nres: \\n\" << res);\n\n            set_subm(m1,0,0,5,5) = m1*m1;\n            DLIB_TEST_MSG(m1 == res*res, \"m1: \\n\" << m1 << \"\\nres*res: \\n\" << res*res);\n\n            m1 = res;\n            set_subm(m1,1,1,2,2) = subm(m1,0,0,2,2);\n\n            long res_vals2[] = {\n                9, 9, 9, 9, 9,\n                0, 9, 9, 0, 0,\n                0, 0, 1, 0, 2,\n                0, 0, 2, 2, 2,\n                0, 0, 2, 2, 0\n            };\n\n            res = res_vals2;\n            DLIB_TEST_MSG(m1 == res, \"m1: \\n\" << m1 << \"\\nres: \\n\" << res);\n\n\n        }\n\n        {\n            matrix<long,5,5> m1, res;\n            matrix<long,2,2> m2;\n\n            set_all_elements(m1,0);\n\n\n            long res_vals[] = {\n                9, 9, 9, 9, 9,\n                0, 1, 1, 0, 0,\n                0, 1, 1, 0, 2,\n                0, 0, 2, 2, 2,\n                0, 0, 2, 2, 0\n            };\n\n            res = res_vals;\n\n            set_all_elements(m2, 1);\n            set_subm(m1, rectangle(1,1,2,2)) = subm(m2,0,0,2,2);\n            set_all_elements(m2, 2);\n            set_subm(m1, 3,2,2,2) = m2;\n\n            set_colm(m1,4) = trans(rowm(m1,4));\n            set_rowm(m1,0) = 9;\n\n            DLIB_TEST_MSG(m1 == res, \"m1: \\n\" << m1 << \"\\nres: \\n\" << res);\n\n            set_subm(m1,0,0,5,5) = m1*m1;\n            DLIB_TEST_MSG(m1 == res*res, \"m1: \\n\" << m1 << \"\\nres*res: \\n\" << res*res);\n\n            m1 = res;\n            set_subm(m1,1,1,2,2) = subm(m1,0,0,2,2);\n\n            long res_vals2[] = {\n                9, 9, 9, 9, 9,\n                0, 9, 9, 0, 0,\n                0, 0, 1, 0, 2,\n                0, 0, 2, 2, 2,\n                0, 0, 2, 2, 0\n            };\n\n            res = res_vals2;\n            DLIB_TEST_MSG(m1 == res, \"m1: \\n\" << m1 << \"\\nres: \\n\" << res);\n\n\n        }\n\n        {\n            matrix<long,5,5> m1, res;\n            matrix<long,2,2> m2;\n\n            set_all_elements(m1,0);\n\n\n            long res_vals[] = {\n                9, 0, 3, 3, 0,\n                9, 2, 2, 2, 0,\n                9, 2, 2, 2, 0,\n                4, 4, 4, 4, 4,\n                9, 0, 3, 3, 0\n            };\n            long res_vals_c3[] = {\n                9, 0, 3, 0,\n                9, 2, 2, 0,\n                9, 2, 2, 0,\n                4, 4, 4, 4,\n                9, 0, 3, 0\n            };\n            long res_vals_r2[] = {\n                9, 0, 3, 3, 0,\n                9, 2, 2, 2, 0,\n                4, 4, 4, 4, 4,\n                9, 0, 3, 3, 0\n            };\n\n            matrix<long> temp;\n\n            res = res_vals;\n\n            temp = matrix<long,4,5>(res_vals_r2);\n            DLIB_TEST(remove_row<2>(res) == temp);\n            DLIB_TEST(remove_row<2>(res)(3,3) == 3);\n            DLIB_TEST(remove_row<2>(res).nr() == 4);\n            DLIB_TEST(remove_row<2>(res).nc() == 5);\n            DLIB_TEST(remove_row(res,2) == temp);\n            DLIB_TEST(remove_row(res,2)(3,3) == 3);\n            DLIB_TEST(remove_row(res,2).nr() == 4);\n            DLIB_TEST(remove_row(res,2).nc() == 5);\n\n            temp = matrix<long,5,5>(res_vals);\n            temp = remove_row(res,2);\n            DLIB_TEST((temp == matrix<long,4,5>(res_vals_r2)));\n            temp = matrix<long,5,5>(res_vals);\n            temp = remove_col(res,3);\n            DLIB_TEST((temp == matrix<long,5,4>(res_vals_c3)));\n\n            matrix<long,3,1> vect;\n            set_all_elements(vect,1);\n            temp = identity_matrix<long>(3);\n            temp = temp*vect;\n            DLIB_TEST(temp == vect);\n\n            temp = matrix<long,5,4>(res_vals_c3);\n            DLIB_TEST(remove_col(res,3) == temp);\n            DLIB_TEST(remove_col(res,3)(2,3) == 0);\n            DLIB_TEST(remove_col(res,3).nr() == 5);\n            DLIB_TEST(remove_col(res,3).nc() == 4);\n\n            set_all_elements(m2, 1);\n            set_subm(m1, rectangle(1,1,3,2)) = 2;\n            set_all_elements(m2, 2);\n            set_subm(m1, 3,2,2,2) = 3;\n\n            set_colm(m1,0) = 9;\n            set_rowm(m1,0) = rowm(m1,4);\n            set_rowm(m1,3) = 4;\n\n            DLIB_TEST_MSG(m1 == res, \"m1: \\n\" << m1 << \"\\nres: \\n\" << res);\n\n        }\n\n    }\n\n\n    void matrix_test2()\n    {\n        print_spinner();\n\n\n        {\n\n            const double stuff[] = { \n                1, 2, 3,\n                6, 3, 3, \n                7, 3, 9};\n\n            matrix<double,3,3> m(stuff);\n\n            // make m be symmetric\n            m = m*trans(m);\n\n            matrix<double> L = chol(m);\n            DLIB_TEST(equal(L*trans(L), m));\n\n            DLIB_TEST_MSG(equal(inv(m), inv_upper_triangular(trans(L))*inv_lower_triangular((L))), \"\");\n            DLIB_TEST(equal(round_zeros(inv_upper_triangular(trans(L))*trans(L),1e-10), identity_matrix<double>(3), 1e-10)); \n            DLIB_TEST(equal(round_zeros(inv_lower_triangular((L))*(L),1e-10) ,identity_matrix<double>(3),1e-10)); \n\n        }\n\n        {\n\n            const double stuff[] = { \n                1, 2, 3, 6, 3, 4,\n                6, 3, 3, 1, 2, 3,\n                7, 3, 9, 54.3, 5, 3,\n                -6, 3, -3, 1, 2, 3,\n                1, 2, 3, 5, -3, 3,\n                7, 3, -9, 54.3, 5, 3\n                };\n\n            matrix<double,6,6> m(stuff);\n\n            // make m be symmetric\n            m = m*trans(m);\n\n            matrix<double> L = chol(m);\n            DLIB_TEST_MSG(equal(L*trans(L), m, 1e-10), L*trans(L)-m);\n\n            DLIB_TEST_MSG(equal(inv(m), inv_upper_triangular(trans(L))*inv_lower_triangular((L))), \"\");\n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*inv_lower_triangular((L))), \"\"); \n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*trans(inv_upper_triangular(trans(L)))), \"\");\n            DLIB_TEST_MSG(equal(round_zeros(inv_upper_triangular(trans(L))*trans(L),1e-10) , identity_matrix<double>(6), 1e-10),\n                         round_zeros(inv_upper_triangular(trans(L))*trans(L),1e-10)); \n            DLIB_TEST_MSG(equal(round_zeros(inv_lower_triangular((L))*(L),1e-10) ,identity_matrix<double>(6), 1e-10),\n                         round_zeros(inv_lower_triangular((L))*(L),1e-10)); \n\n        }\n\n        {\n            // Test band chol\n            matrix<double> m = rand_sp_banded<double>(10, 3);\n\n            matrix<double> L = chol(m);\n            DLIB_TEST_MSG(equal(L*trans(L), m, 1e-10), L*trans(L)-m);   \n            DLIB_TEST_MSG(equal(inv(m), inv_upper_triangular(trans(L))*inv_lower_triangular((L))), \"\");\n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*inv_lower_triangular((L))), \"\"); \n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*trans(inv_upper_triangular(trans(L)))), \"\");\n        }\n\n        {\n            // Test band chol in column major layout\n            matrix<double,10,10,default_memory_manager,column_major_layout> m(rand_sp_banded<double>(10, 3));\n\n            matrix<double> L = chol(m);\n            DLIB_TEST_MSG(equal(L*trans(L), m, 1e-10), L*trans(L)-m);   \n            DLIB_TEST_MSG(equal(inv(m), inv_upper_triangular(trans(L))*inv_lower_triangular((L))), \"\");\n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*inv_lower_triangular((L))), \"\"); \n            DLIB_TEST_MSG(equal(inv(m), trans(inv_lower_triangular(L))*trans(inv_upper_triangular(trans(L)))), \"\");\n        }\n\n        {\n            matrix<int> m(3,4), m2;\n            m = 1,2,3,4,\n                4,5,6,6,\n                6,1,8,0;\n            m2 = m;\n            DLIB_TEST(round(m) == m2);\n            DLIB_TEST(round_zeros(m) == m2);\n\n            m2 = 0,2,3,4,\n                 4,5,6,6,\n                 6,0,8,0;\n\n            DLIB_TEST(round_zeros(m,2) == m2);\n        }\n\n\n        {\n\n            matrix<double,6,6> m(identity_matrix<double>(6)*4.5);\n\n            matrix<double> L = chol(m);\n            DLIB_TEST_MSG(equal(L*trans(L), m, 1e-10), L*trans(L)-m);\n\n            DLIB_TEST_MSG(equal(inv(m), inv_upper_triangular(trans(L))*inv_lower_triangular((L))), \"\"); \n            DLIB_TEST_MSG(equal(round_zeros(inv_upper_triangular(trans(L))*trans(L),1e-10) , identity_matrix<double>(6), 1e-10),\n                         round_zeros(inv_upper_triangular(trans(L))*trans(L),1e-10)); \n            DLIB_TEST_MSG(equal(round_zeros(inv_lower_triangular((L))*(L),1e-10) ,identity_matrix<double>(6), 1e-10),\n                         round_zeros(inv_lower_triangular((L))*(L),1e-10)); \n\n        }\n\n        {\n\n            matrix<double,6,6> m(identity_matrix<double>(6)*4.5);\n            m(1,4) = 2;\n\n            DLIB_TEST_MSG(dlib::equal(inv_upper_triangular(m), inv(m),1e-10), inv_upper_triangular(m)-inv(m));\n            DLIB_TEST_MSG(dlib::equal(inv_lower_triangular(trans(m)), inv(trans(m)),1e-10), inv_lower_triangular(trans(m))-inv(trans(m)));\n\n        }\n\n        {\n            matrix<double> a;\n            matrix<float> b;\n            matrix<int> i;\n            a.set_size(1000,10);\n            b.set_size(1000,10);\n            i.set_size(1000,10);\n            dlib::rand rnd;\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    a(r,c) = rnd.get_random_double();\n                    b(r,c) = rnd.get_random_float();\n                    i(r,c) = r+c*r;\n                }\n            }\n\n            // make sure the multiply optimizations aren't messing things up\n            DLIB_TEST(trans(i)*i == tmp(trans(i)*i));\n            DLIB_TEST_MSG(equal(trans(a)*a , tmp(trans(a)*a), 1e-11),max(abs(trans(a)*a - tmp(trans(a)*a))));\n            DLIB_TEST_MSG(equal(trans(b)*b , tmp(trans(b)*b), 1e-3f),max(abs(trans(b)*b - tmp(trans(b)*b))));\n        }\n\n        {\n            matrix<int,4> i(4,1);\n            i(0) = 1;\n            i(1) = 2;\n            i(2) = 3;\n            i(3) = 4;\n            matrix<int,4,4> m;\n            set_all_elements(m,0);\n            m(0,0) = 1;\n            m(1,1) = 2;\n            m(2,2) = 3;\n            m(3,3) = 4;\n\n            DLIB_TEST(diagm(i) == m);\n        }\n\n        {\n            matrix<int,1,4> i;\n            i(0) = 1;\n            i(1) = 2;\n            i(2) = 3;\n            i(3) = 4;\n            matrix<int,4,4> m;\n            set_all_elements(m,0);\n            m(0,0) = 1;\n            m(1,1) = 2;\n            m(2,2) = 3;\n            m(3,3) = 4;\n\n            DLIB_TEST(diagm(i) == m);\n        }\n\n        {\n            matrix<int> i(4,1);\n            i(0) = 1;\n            i(1) = 2;\n            i(2) = 3;\n            i(3) = 4;\n            matrix<int> m(4,4);\n            set_all_elements(m,0);\n            m(0,0) = 1;\n            m(1,1) = 2;\n            m(2,2) = 3;\n            m(3,3) = 4;\n\n            DLIB_TEST(diagm(i) == m);\n        }\n\n        {\n            matrix<int> i(1,4);\n            i(0) = 1;\n            i(1) = 2;\n            i(2) = 3;\n            i(3) = 4;\n            matrix<int> m(4,4);\n            set_all_elements(m,0);\n            m(0,0) = 1;\n            m(1,1) = 2;\n            m(2,2) = 3;\n            m(3,3) = 4;\n\n            DLIB_TEST(diagm(i) == m);\n        }\n\n        {\n            DLIB_TEST(range(0,5).nc() == 6);\n            DLIB_TEST(range(1,5).nc() == 5);\n            DLIB_TEST(range(0,5).nr() == 1);\n            DLIB_TEST(range(1,5).nr() == 1);\n            DLIB_TEST(trans(range(0,5)).nr() == 6);\n            DLIB_TEST(trans(range(1,5)).nr() == 5);\n            DLIB_TEST(trans(range(0,5)).nc() == 1);\n            DLIB_TEST(trans(range(1,5)).nc() == 1);\n\n            DLIB_TEST(range(0,2,5).nc() == 3);\n            DLIB_TEST(range(1,2,5).nc() == 3);\n            DLIB_TEST(range(0,2,5).nr() == 1);\n            DLIB_TEST(range(1,2,5).nr() == 1);\n            DLIB_TEST(trans(range(0,2,5)).nr() == 3);\n            DLIB_TEST(trans(range(1,2,5)).nr() == 3);\n            DLIB_TEST(trans(range(0,2,5)).nc() == 1);\n            DLIB_TEST(trans(range(1,2,5)).nc() == 1);\n\n            DLIB_TEST(range(0,3,6).nc() == 3);\n            DLIB_TEST(range(1,3,5).nc() == 2);\n            DLIB_TEST(range(0,3,5).nr() == 1);\n            DLIB_TEST(range(1,3,5).nr() == 1);\n            DLIB_TEST(trans(range(0,3,6)).nr() == 3);\n            DLIB_TEST(trans(range(1,3,5)).nr() == 2);\n            DLIB_TEST(trans(range(0,3,5)).nc() == 1);\n            DLIB_TEST(trans(range(1,3,5)).nc() == 1);\n\n            DLIB_TEST(range(1,9,5).nc() == 1);\n            DLIB_TEST(range(1,9,5).nr() == 1);\n\n            DLIB_TEST(range(0,0).nc() == 1);\n            DLIB_TEST(range(0,0).nr() == 1);\n\n            DLIB_TEST(range(1,1)(0) == 1);\n\n            DLIB_TEST(range(0,5)(0) == 0 && range(0,5)(1) == 1 && range(0,5)(5) == 5);\n            DLIB_TEST(range(1,2,5)(0) == 1 && range(1,2,5)(1) == 3 && range(1,2,5)(2) == 5);\n            DLIB_TEST((range<0,5>()(0) == 0 && range<0,5>()(1) == 1 && range<0,5>()(5) == 5));\n            DLIB_TEST((range<1,2,5>()(0) == 1 && range<1,2,5>()(1) == 3 && range<1,2,5>()(2) == 5));\n\n\n            DLIB_TEST((range<0,5>().nc() == 6));\n            DLIB_TEST((range<1,5>().nc() == 5));\n            DLIB_TEST((range<0,5>().nr() == 1));\n            DLIB_TEST((range<1,5>().nr() == 1));\n            DLIB_TEST((trans(range<0,5>()).nr() == 6));\n            DLIB_TEST((trans(range<1,5>()).nr() == 5));\n            DLIB_TEST((trans(range<0,5>()).nc() == 1));\n            DLIB_TEST((trans(range<1,5>()).nc() == 1));\n\n            DLIB_TEST((range<0,2,5>().nc() == 3));\n            DLIB_TEST((range<1,2,5>().nc() == 3));\n            DLIB_TEST((range<0,2,5>().nr() == 1));\n            DLIB_TEST((range<1,2,5>().nr() == 1));\n            DLIB_TEST((trans(range<0,2,5>()).nr() == 3));\n            DLIB_TEST((trans(range<1,2,5>()).nr() == 3));\n            DLIB_TEST((trans(range<0,2,5>()).nc() == 1));\n            DLIB_TEST((trans(range<1,2,5>()).nc() == 1));\n\n            DLIB_TEST((range<0,3,6>().nc() == 3));\n            DLIB_TEST((range<1,3,5>().nc() == 2));\n            DLIB_TEST((range<0,3,5>().nr() == 1));\n            DLIB_TEST((range<1,3,5>().nr() == 1));\n            DLIB_TEST((trans(range<0,3,6>()).nr() == 3));\n            DLIB_TEST((trans(range<1,3,5>()).nr() == 2));\n            DLIB_TEST((trans(range<0,3,5>()).nc() == 1));\n            DLIB_TEST((trans(range<1,3,5>()).nc() == 1));\n        }\n\n        {\n            DLIB_TEST(range(5,0).nc() == 6);\n            DLIB_TEST(range(5,1).nc() == 5);\n            DLIB_TEST(range(5,0).nr() == 1);\n            DLIB_TEST(range(5,1).nr() == 1);\n            DLIB_TEST(trans(range(5,0)).nr() == 6);\n            DLIB_TEST(trans(range(5,1)).nr() == 5);\n            DLIB_TEST(trans(range(5,0)).nc() == 1);\n            DLIB_TEST(trans(range(5,1)).nc() == 1);\n\n            DLIB_TEST(range(5,2,0).nc() == 3);\n            DLIB_TEST(range(5,2,1).nc() == 3);\n            DLIB_TEST(range(5,2,0).nr() == 1);\n            DLIB_TEST(range(5,2,1).nr() == 1);\n            DLIB_TEST(trans(range(5,2,0)).nr() == 3);\n            DLIB_TEST(trans(range(5,2,1)).nr() == 3);\n            DLIB_TEST(trans(range(5,2,0)).nc() == 1);\n            DLIB_TEST(trans(range(5,2,1)).nc() == 1);\n\n            DLIB_TEST(range(6,3,0).nc() == 3);\n            DLIB_TEST(range(5,3,1).nc() == 2);\n            DLIB_TEST(range(5,3,0).nr() == 1);\n            DLIB_TEST(range(5,3,1).nr() == 1);\n            DLIB_TEST(trans(range(6,3,0)).nr() == 3);\n            DLIB_TEST(trans(range(5,3,1)).nr() == 2);\n            DLIB_TEST(trans(range(5,3,0)).nc() == 1);\n            DLIB_TEST(trans(range(5,3,1)).nc() == 1);\n\n            DLIB_TEST(range(5,9,1).nc() == 1);\n            DLIB_TEST(range(5,9,1).nr() == 1);\n\n            DLIB_TEST(range(0,0).nc() == 1);\n            DLIB_TEST(range(0,0).nr() == 1);\n\n            DLIB_TEST(range(1,1)(0) == 1);\n\n            DLIB_TEST(range(5,0)(0) == 5 && range(5,0)(1) == 4 && range(5,0)(5) == 0);\n            DLIB_TEST(range(5,2,1)(0) == 5 && range(5,2,1)(1) == 3 && range(5,2,1)(2) == 1);\n            DLIB_TEST((range<5,0>()(0) == 5 && range<5,0>()(1) == 4 && range<5,0>()(5) == 0));\n            DLIB_TEST((range<5,2,1>()(0) == 5 && range<5,2,1>()(1) == 3 && range<5,2,1>()(2) == 1));\n\n\n            DLIB_TEST((range<5,0>().nc() == 6));\n            DLIB_TEST((range<5,1>().nc() == 5));\n            DLIB_TEST((range<5,0>().nr() == 1));\n            DLIB_TEST((range<5,1>().nr() == 1));\n            DLIB_TEST((trans(range<5,0>()).nr() == 6));\n            DLIB_TEST((trans(range<5,1>()).nr() == 5));\n            DLIB_TEST((trans(range<5,0>()).nc() == 1));\n            DLIB_TEST((trans(range<5,1>()).nc() == 1));\n\n            DLIB_TEST((range<5,2,0>().nc() == 3));\n            DLIB_TEST((range<5,2,1>().nc() == 3));\n            DLIB_TEST((range<5,2,0>().nr() == 1));\n            DLIB_TEST((range<5,2,1>().nr() == 1));\n            DLIB_TEST((trans(range<5,2,0>()).nr() == 3));\n            DLIB_TEST((trans(range<5,2,1>()).nr() == 3));\n            DLIB_TEST((trans(range<5,2,0>()).nc() == 1));\n            DLIB_TEST((trans(range<5,2,1>()).nc() == 1));\n\n            DLIB_TEST((range<6,3,0>().nc() == 3));\n            DLIB_TEST((range<5,3,1>().nc() == 2));\n            DLIB_TEST((range<5,3,0>().nr() == 1));\n            DLIB_TEST((range<5,3,1>().nr() == 1));\n            DLIB_TEST((trans(range<6,3,0>()).nr() == 3));\n            DLIB_TEST((trans(range<5,3,1>()).nr() == 2));\n            DLIB_TEST((trans(range<5,3,0>()).nc() == 1));\n            DLIB_TEST((trans(range<5,3,1>()).nc() == 1));\n        }\n\n        {\n            matrix<double> m(4,3);\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c;\n                }\n            }\n\n            DLIB_TEST(subm(m,range(0,3),range(0,0)) == colm(m,0));\n            DLIB_TEST(subm(m,range(0,3),range(1,1)) == colm(m,1));\n            DLIB_TEST(subm(m,range(0,3),range(2,2)) == colm(m,2));\n\n            DLIB_TEST(subm(m,range(0,0),range(0,2)) == rowm(m,0));\n            DLIB_TEST(subm(m,range(1,1),range(0,2)) == rowm(m,1));\n            DLIB_TEST(subm(m,range(2,2),range(0,2)) == rowm(m,2));\n            DLIB_TEST(subm(m,range(3,3),range(0,2)) == rowm(m,3));\n            DLIB_TEST(rowm(m,matrix<long>()).size()==0);\n            DLIB_TEST(colm(m,matrix<long>()).size()==0);\n\n            DLIB_TEST(subm(m,0,0,2,2) == subm(m,range(0,1),range(0,1)));\n            DLIB_TEST(subm(m,1,1,2,2) == subm(m,range(1,2),range(1,2)));\n\n            matrix<double,2,2> m2 = subm(m,range(0,2,2),range(0,2,2));\n\n            DLIB_TEST(m2(0,0) == m(0,0));\n            DLIB_TEST(m2(0,1) == m(0,2));\n            DLIB_TEST(m2(1,0) == m(2,0));\n            DLIB_TEST(m2(1,1) == m(2,2));\n\n\n        }\n        {\n            matrix<double,4,3> m(4,3);\n            for (long r = 0; r < m.nr(); ++r)\n            {\n                for (long c = 0; c < m.nc(); ++c)\n                {\n                    m(r,c) = r*c;\n                }\n            }\n\n            DLIB_TEST(subm(m,range<0,3>(),range<0,0>()) == colm(m,0));\n            DLIB_TEST(subm(m,range<0,3>(),range<1,1>()) == colm(m,1));\n            DLIB_TEST(subm(m,range<0,3>(),range<2,2>()) == colm(m,2));\n\n            DLIB_TEST(subm(m,range<0,0>(),range<0,2>()) == rowm(m,0));\n            DLIB_TEST(subm(m,range<1,1>(),range<0,2>()) == rowm(m,1));\n            DLIB_TEST(subm(m,range<2,2>(),range<0,2>()) == rowm(m,2));\n            DLIB_TEST(subm(m,range<3,3>(),range<0,2>()) == rowm(m,3));\n\n            DLIB_TEST(subm(m,0,0,2,2) == subm(m,range<0,1>(),range<0,1>()));\n            DLIB_TEST(subm(m,1,1,2,2) == subm(m,range<1,2>(),range<1,2>()));\n\n            matrix<double,2,2> m2 = subm(m,range<0,2,2>(),range<0,2,2>());\n\n            DLIB_TEST(m2(0,0) == m(0,0));\n            DLIB_TEST(m2(0,1) == m(0,2));\n            DLIB_TEST(m2(1,0) == m(2,0));\n            DLIB_TEST(m2(1,1) == m(2,2));\n\n\n        }\n\n        {\n            matrix<double> a = randm(3,4);\n            matrix<double> b = randm(3,4);\n\n            matrix<double> m1, m2;\n\n            m1 = max_pointwise(a,b);\n            m2 = min_pointwise(a,b);\n            DLIB_TEST(m1.nr() == a.nr());\n            DLIB_TEST(m1.nc() == a.nc());\n            DLIB_TEST(m2.nr() == a.nr());\n            DLIB_TEST(m2.nc() == a.nc());\n            for (long r = 0; r < a.nr(); ++r)\n            {\n                for (long c = 0; c < a.nc(); ++c)\n                {\n                    DLIB_TEST_MSG(m1(r,c) == std::max(a(r,c), b(r,c)), m1(r,c)  << \" : \" << a(r,c) << \" \" << b(r,c));\n                    DLIB_TEST(m2(r,c) == std::min(a(r,c), b(r,c)));\n                }\n            }\n        }\n\n        {\n            matrix<double,4,5> m;\n            set_subm(m, range(0,3), range(0,4)) = 4;\n            DLIB_TEST(min(m) == max(m) && min(m) == 4);\n\n            set_subm(m,range(1,1),range(0,4)) = 7;\n            DLIB_TEST((rowm(m,0) == uniform_matrix<double>(1,5, 4)));\n            DLIB_TEST((rowm(m,1) == uniform_matrix<double>(1,5, 7)));\n            DLIB_TEST((rowm(m,2) == uniform_matrix<double>(1,5, 4)));\n            DLIB_TEST((rowm(m,3) == uniform_matrix<double>(1,5, 4)));\n\n\n            set_subm(m, range(0,2,3), range(0,2,4)) = trans(subm(m,0,0,3,2));\n\n\n            DLIB_TEST(m(0,2) == 7);\n            DLIB_TEST(m(2,2) == 7);\n\n            DLIB_TEST(sum(m) == 7*5+ 7+7 +  4*(4*5 - 7));\n\n        }\n\n        {\n            matrix<double> mat(4,5);\n            DLIB_TEST((uniform_matrix<double>(4,5,1) == ones_matrix<double>(4,5)));\n            DLIB_TEST((uniform_matrix<double>(4,5,1) == ones_matrix(mat)));\n            DLIB_TEST((uniform_matrix<double>(4,5,0) == zeros_matrix<double>(4,5)));\n            DLIB_TEST((uniform_matrix<double>(4,5,0) == zeros_matrix(mat)));\n            DLIB_TEST((uniform_matrix<float>(4,5,1) == ones_matrix<float>(4,5)));\n            DLIB_TEST((uniform_matrix<float>(4,5,0) == zeros_matrix<float>(4,5)));\n            DLIB_TEST((uniform_matrix<complex<double> >(4,5,1) == ones_matrix<complex<double> >(4,5)));\n            DLIB_TEST((uniform_matrix<complex<double> >(4,5,0) == zeros_matrix<complex<double> >(4,5)));\n            DLIB_TEST((uniform_matrix<complex<float> >(4,5,1) == ones_matrix<complex<float> >(4,5)));\n            DLIB_TEST((uniform_matrix<complex<float> >(4,5,0) == zeros_matrix<complex<float> >(4,5)));\n            DLIB_TEST((complex_matrix(ones_matrix<double>(3,3), zeros_matrix<double>(3,3)) == complex_matrix(ones_matrix<double>(3,3))));\n            DLIB_TEST((pointwise_multiply(complex_matrix(ones_matrix<double>(3,3)), ones_matrix<double>(3,3)*2) ==\n                       complex_matrix(2*ones_matrix<double>(3,3))));\n            DLIB_TEST((pointwise_divide(complex_matrix(ones_matrix<double>(3,3)), ones_matrix<double>(3,3)) ==\n                       complex_matrix(ones_matrix<double>(3,3))));\n            DLIB_TEST((pointwise_divide(complex_matrix(zeros_matrix<double>(3,3)), ones_matrix<double>(3,3)) ==\n                       complex_matrix(zeros_matrix<double>(3,3))));\n        }\n\n        {\n            DLIB_TEST(( uniform_matrix<double>(303,303, 3)*identity_matrix<double>(303) == uniform_matrix<double,303,303>(3) ) );\n            DLIB_TEST(( uniform_matrix<double,303,303>(3)*identity_matrix<double,303>() == uniform_matrix<double,303,303>(3) ));\n        }\n\n        {\n            matrix<double> m(2,3);\n            m = 1,2,3,\n                5,6,7;\n\n            DLIB_TEST_MSG(m(0,0) == 1 && m(0,1) == 2 && m(0,2) == 3 &&\n                         m(1,0) == 5 && m(1,1) == 6 && m(1,2) == 7,\"\");\n\n            m = 4;\n            DLIB_TEST((m == uniform_matrix<double,2,3>(4)));\n\n            matrix<double,2,3> m2;\n            m2 = 1,2,3,\n                 5,6,7;\n            DLIB_TEST_MSG(m2(0,0) == 1 && m2(0,1) == 2 && m2(0,2) == 3 &&\n                         m2(1,0) == 5 && m2(1,1) == 6 && m2(1,2) == 7,\"\");\n\n            matrix<double,2,1> m3;\n            m3 = 1,\n                 5;\n            DLIB_TEST(m3(0) == 1 && m3(1) == 5 );\n\n            matrix<double,1,2> m4;\n            m4 = 1, 5;\n            DLIB_TEST(m3(0) == 1 && m3(1) == 5 );\n        }\n\n        {\n            matrix<double> m(4,1);\n            m = 3, 1, 5, 2;\n            DLIB_TEST(index_of_min(m) == 1);\n            DLIB_TEST(index_of_max(m) == 2);\n            DLIB_TEST(index_of_min(trans(m)) == 1);\n            DLIB_TEST(index_of_max(trans(m)) == 2);\n        }\n\n        {\n            matrix<double> m1(1,5), m2;\n\n            m1 = 3.0000,  3.7500,  4.5000,  5.2500,  6.0000; \n            m2 = linspace(3, 6, 5);\n\n            DLIB_TEST(equal(m1, m2));\n            \n            m1 = pow(10, m1);\n            m2 = logspace(3, 6, 5);\n\n            DLIB_TEST(equal(m1, m2));\n        }\n\n        {\n            matrix<long> m = cartesian_product(range(1,3), range(0,1));\n\n            matrix<long,2,1> c0, c1, c2, c3, c4, c5;\n            c0 = 1, 0;\n            c1 = 1, 1;\n            c2 = 2, 0;\n            c3 = 2, 1;\n            c4 = 3, 0;\n            c5 = 3, 1;\n\n            DLIB_TEST_MSG(colm(m,0) == c0, colm(m,0) << \"\\n\\n\" << c0);\n            DLIB_TEST(colm(m,1) == c1);\n            DLIB_TEST(colm(m,2) == c2);\n            DLIB_TEST(colm(m,3) == c3);\n            DLIB_TEST(colm(m,4) == c4);\n            DLIB_TEST(colm(m,5) == c5);\n        }\n\n\n        {\n            matrix<double> m(2,2), mr(2,2), mr_max(2,2);\n\n            m = 1, 2,\n                0, 4;\n\n            mr = 1, 1.0/2.0,\n                0,  1.0/4.0;\n\n            mr_max = 1, 1.0/2.0,\n                     std::numeric_limits<double>::max(),  1.0/4.0;\n\n            DLIB_TEST(equal(reciprocal(m), mr));\n            DLIB_TEST(equal(reciprocal_max(m), mr_max));\n\n        }\n\n        {\n            matrix<double> m1, m2;\n            m1.set_size(3,1);\n            m2.set_size(1,3);\n\n            m1 = 1,2,3;\n            m2 = 4,5,6;\n            DLIB_TEST(dot(m1, m2)               == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(m1, trans(m2))        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), m2)        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), trans(m2)) == 1*4 + 2*5 + 3*6);\n        }\n\n        {\n            matrix<double,3,1> m1, m2;\n            m1.set_size(3,1);\n            m2.set_size(3,1);\n\n            m1 = 1,2,3;\n            m2 = 4,5,6;\n            DLIB_TEST(dot(m1, m2)               == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(m1, trans(m2))        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), m2)        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), trans(m2)) == 1*4 + 2*5 + 3*6);\n        }\n        {\n            matrix<double,1,3> m1, m2;\n            m1.set_size(1,3);\n            m2.set_size(1,3);\n\n            m1 = 1,2,3;\n            m2 = 4,5,6;\n            DLIB_TEST(dot(m1, m2)               == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(m1, trans(m2))        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), m2)        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), trans(m2)) == 1*4 + 2*5 + 3*6);\n        }\n        {\n            matrix<double,1,3> m1;\n            matrix<double> m2;\n            m1.set_size(1,3);\n            m2.set_size(3,1);\n\n            m1 = 1,2,3;\n            m2 = 4,5,6;\n            DLIB_TEST(dot(m1, m2)               == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(m1, trans(m2))        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), m2)        == 1*4 + 2*5 + 3*6);\n            DLIB_TEST(dot(trans(m1), trans(m2)) == 1*4 + 2*5 + 3*6);\n        }\n\n        {\n            matrix<double> m1(3,3), m2(3,3);\n\n            m1 = 1;\n            m2 = 1;\n            m1 = m1*subm(m2,0,0,3,3);\n            DLIB_TEST(is_finite(m1));\n        }\n        {\n            matrix<double,3,1> m1;\n            matrix<double> m2(3,3);\n\n            m1 = 1;\n            m2 = 1;\n            m1 = subm(m2,0,0,3,3)*m1;\n        }\n\n        {\n            matrix<int> m(2,1);\n\n            m = 3,3;\n            m /= m(0);\n\n            DLIB_TEST(m(0) == 1);\n            DLIB_TEST(m(1) == 1);\n        }\n        {\n            matrix<int> m(2,1);\n\n            m = 3,3;\n            m *= m(0);\n\n            DLIB_TEST(m(0) == 9);\n            DLIB_TEST(m(1) == 9);\n        }\n        {\n            matrix<int> m(2,1);\n\n            m = 3,3;\n            m -= m(0);\n\n            DLIB_TEST(m(0) == 0);\n            DLIB_TEST(m(1) == 0);\n        }\n        {\n            matrix<int> m(2,1);\n\n            m = 3,3;\n            m += m(0);\n\n            DLIB_TEST(m(0) == 6);\n            DLIB_TEST(m(1) == 6);\n            DLIB_TEST(is_finite(m));\n        }\n\n\n        {\n            matrix<double> m(3,3);\n            m = 3;\n            m(1,1) = std::numeric_limits<double>::infinity();\n            DLIB_TEST(is_finite(m) == false);\n            m(1,1) = -std::numeric_limits<double>::infinity();\n            DLIB_TEST(is_finite(m) == false);\n            m(1,1) = 2;\n            DLIB_TEST(is_finite(m));\n        }\n\n        {\n            matrix<int> m(4,1), mm, mmm;\n\n            mmm = mm = (m = 1,2,3,4);\n            DLIB_TEST(m(0) == 1);\n            DLIB_TEST(m(1) == 2);\n            DLIB_TEST(m(2) == 3);\n            DLIB_TEST(m(3) == 4);\n            DLIB_TEST(mm == m);\n            DLIB_TEST(mmm == m);\n            DLIB_TEST(mm(0) == 1);\n            DLIB_TEST(mm(1) == 2);\n            DLIB_TEST(mm(2) == 3);\n            DLIB_TEST(mm(3) == 4);\n        }\n\n        {\n            const long n = 5;\n            matrix<double> m1, m2, m3, truth;\n            m1 = randm(n,n);\n            m2 = randm(n,n);\n\n            rectangle rect1(1,1,3,3);\n            rectangle rect2(2,1,4,3);\n\n            truth = subm(m1,rect1)*subm(m2,rect2);\n            m3 = mat(&m1(0,0)+6, 3,3, m1.nc()) * mat(&m2(0,0)+7, 3,3, m2.nc());\n\n            DLIB_TEST(max(abs(truth-m3)) < 1e-13);\n        }\n\n        {\n            const long n = 5;\n            matrix<double> m1, m2, m3, truth;\n            m1 = randm(n,n);\n            m2 = randm(n,n);\n            m3 = randm(n,n);\n\n\n            truth = m1*m2;\n            m3 = mat(&m1(0,0),n,n)*mat(&m2(0,0),n,n);\n            DLIB_TEST(max(abs(truth-m3)) < 1e-13);\n            m3 = 0;\n            set_ptrm(&m3(0,0),n,n) = mat(&m1(0,0),n,n)*mat(&m2(0,0),n,n);\n            DLIB_TEST(max(abs(truth-m3)) < 1e-13);\n            set_ptrm(&m3(0,0),n,n) = m1*m2;\n            DLIB_TEST(max(abs(truth-m3)) < 1e-13);\n\n            // now make sure it deals with aliasing correctly.\n            truth = m1*m2;\n            m1 = mat(&m1(0,0),n,n)*mat(&m2(0,0),n,n);\n            DLIB_TEST(max(abs(truth-m1)) < 1e-13);\n\n            m1 = randm(n,n);\n            truth = m1*m2;\n            set_ptrm(&m1(0,0),n,n) = mat(&m1(0,0),n,n)*mat(&m2(0,0),n,n);\n            DLIB_TEST(max(abs(truth-m1)) < 1e-13);\n\n            m1 = randm(n,n);\n            truth = m1*m2;\n            set_ptrm(&m1(0,0),n,n) = m1*m2;\n            DLIB_TEST(max(abs(truth-m1)) < 1e-13);\n\n            m1 = randm(n,n);\n            truth = m1+m1*m2;\n            set_ptrm(&m1(0,0),n,n) += m1*m2;\n            DLIB_TEST(max(abs(truth-m1)) < 1e-13);\n\n            m1 = randm(n,n);\n            truth = m1-m1*m2;\n            set_ptrm(&m1(0,0),n,n) -= m1*m2;\n            DLIB_TEST(max(abs(truth-m1)) < 1e-13);\n\n        }\n\n        {\n            matrix<double,3,3,default_memory_manager,column_major_layout> a(3,3);\n            matrix<double,3,3,default_memory_manager,column_major_layout> m = randm(3,3);\n            matrix<double,3,1,default_memory_manager,column_major_layout> b = randm(3,1);\n\n            a = 0;\n            set_colm(a,0) = m*b;\n            DLIB_TEST(colm(a,0) == m*b);\n            a = 0;\n            set_rowm(a,0) = trans(m*b);\n            DLIB_TEST(rowm(a,0) == trans(m*b));\n            DLIB_TEST(rowm(a,0) != m*b);\n        }\n        {\n            matrix<double,0,0,default_memory_manager,column_major_layout> a(3,3);\n            matrix<double,0,0,default_memory_manager,column_major_layout> m = randm(3,3);\n            matrix<double,0,0,default_memory_manager,column_major_layout> b = randm(3,1);\n\n            a = 0;\n            set_colm(a,0) = m*b;\n            DLIB_TEST(equal(colm(a,0) , m*b));\n            a = 0;\n            set_rowm(a,0) = trans(m*b);\n            DLIB_TEST(equal(rowm(a,0) , trans(m*b)));\n            DLIB_TEST(!equal(rowm(a,0) , m*b));\n        }\n        {\n            matrix<double> a(3,3);\n            matrix<double> m = randm(3,3);\n            matrix<double> b = randm(3,1);\n\n            a = 0;\n            set_colm(a,0) = m*b;\n            DLIB_TEST(equal(colm(a,0) , m*b));\n            a = 0;\n            set_rowm(a,0) = trans(m*b);\n            DLIB_TEST(equal(rowm(a,0) , trans(m*b)));\n            DLIB_TEST(!equal(rowm(a,0) , m*b));\n        }\n    }\n\n\n\n\n\n\n    class matrix_tester : public tester\n    {\n    public:\n        matrix_tester (\n        ) :\n            tester (\"test_matrix\",\n                    \"Runs tests on the matrix component.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            matrix_test();\n            matrix_test2();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "edc738aee747f0b33691963f69922ed83152cdcc", "size": 48528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/matrix.cpp", "max_stars_repo_name": "asm-jaime/facerec", "max_stars_repo_head_hexsha": "e5e101b9f478168ead179e6b08b5605ea7607da2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 243.0, "max_stars_repo_stars_event_min_datetime": "2017-02-28T08:52:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T16:54:48.000Z", "max_issues_repo_path": "dlib/test/matrix.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T20:39:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T11:38:14.000Z", "max_forks_repo_path": "dlib/test/matrix.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2017-04-05T15:39:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T13:49:08.000Z", "avg_line_length": 31.8007863696, "max_line_length": 138, "alphanum_fraction": 0.4200461589, "num_tokens": 15511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6513549417043805}}
{"text": "#ifndef MLT_UTILS_OPTIMIZERS_STOCHASTIC_GRADIENT_DESCENT_TRAINER_HPP\n#define MLT_UTILS_OPTIMIZERS_STOCHASTIC_GRADIENT_DESCENT_TRAINER_HPP\n\n#include <algorithm>\n#include <random>\n#include <tuple>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"../../defs.hpp\"\n#include \"../eigen.hpp\"\n#include \"gradient_descent_updates.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace optimizers {\n\tusing namespace eigen;\n\n    // Implementation of Stochastic Gradient Descent\n    // Parameters:\n    // - size_t batch_size: size of each batch when using mini-batches (set to 0 if using full batch gradient descent)\n    // - size_t epochs: number of epochs to run the descent steps through the training data    \n    // - double learning_rate: initial learning rate\n    // - double learning_rate_decay: learning_rate is multiplied by this after each epoch\n    // - UpdateMethod update_method: object implementing the update strategy to use\n\ttemplate <class UpdateMethod = RMSPropGradientDescentUpdate>\n    class StochasticGradientDescent {\n    public:\n\t\tStochasticGradientDescent(size_t batch_size = 1, size_t epochs = 1000, double learning_rate = 0.001, double learning_rate_decay = 0.99,\n\t\t\tconst UpdateMethod& update_method = UpdateMethod()) : _batch_size(batch_size), _epochs(epochs), _learning_rate(learning_rate), \n\t\t\t_current_learning_rate(learning_rate), _learning_rate_decay(learning_rate_decay), _update_method(update_method) {}\n\n        template <class Model, class Target>\n\t\tauto operator()(const Model& model, Features input, Target target, MatrixXdRef init, bool cold_start) {\n\t\t\tassert(input.cols() == target.cols());\n\n            if (cold_start) {\n                _current_learning_rate = _learning_rate;\n\t\t\t\t_update_method.restart();\n            }\n\n            auto iters_per_epoch = _batch_size > 0 && _batch_size <= input.cols() ? input.cols() / _batch_size : 1;\n\n\t\t\tMatrixXd params = init;\n\n\t\t\trandom_device rd;\n            default_random_engine generator(rd());\n\n            for (auto epoch = 0; epoch < _epochs; epoch++) {\n                for (auto iter = 0; iter < iters_per_epoch; iter++) {\n\t\t\t\t\tif (_batch_size > 0) {\n\t\t\t\t\t\tauto subset = tied_random_cols_subset(input, target, _batch_size, generator);\n\t\t\t\t\t\tauto input_batch = get<0>(subset);\n\t\t\t\t\t\tauto target_batch = get<1>(subset);\n\n\t\t\t\t\t\tparams += _update_method.step(_current_learning_rate, model.gradient(params, input_batch, target_batch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparams += _update_method.step(_current_learning_rate, model.gradient(params, input, target));\n\t\t\t\t\t}\n                }\n\n#ifdef MLT_VERBOSE\n\t\t\t\tif (epoch % 10 == 0) {\n\t\t\t\t\tauto loss = model.loss(params, input, target);\n\t\t\t\t\tMLT_LOG_LINE(\"[SGD]: Epoch \" << epoch + 1 << \"/\" << _epochs << \" Loss \" << loss);\n\t\t\t\t}\n#endif\n\n\t\t\t\t_current_learning_rate *= _learning_rate_decay;\n            }\n\n\t\t\treturn params;\n        }\n\n\tprotected:\n\t\tsize_t _batch_size;\n\t\tsize_t _epochs;\n\t\tdouble _learning_rate;\n\t\tdouble _current_learning_rate;\n\t\tdouble _learning_rate_decay;\n\t\tUpdateMethod _update_method;\n    };\n}\n}\n}\n#endif", "meta": {"hexsha": "61496aaa9658ed863f2b270af5aba1bb0630d2da", "size": 3033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/optimizers/stochastic_gradient_descent.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/stochastic_gradient_descent.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/stochastic_gradient_descent.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": 34.8620689655, "max_line_length": 137, "alphanum_fraction": 0.6983184965, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6513549372754316}}
{"text": "// Copyright (c) 2009-2016 Craig Henderson\n// https://github.com/cdmh/mapreduce\n\n#include <boost/config.hpp>\n#if defined(BOOST_MSVC)\n#   pragma warning(disable: 4127)\n\n// turn off checked iterators to avoid performance hit\n#   if !defined(__SGI_STL_PORT)  &&  !defined(_DEBUG)\n#       define _SECURE_SCL 0\n#       define _HAS_ITERATOR_DEBUGGING 0\n#   endif\n#endif\n\n#include \"../Thirdparty/mapreduce/include/mapreduce.hpp\"\n#include \"utils.cpp\"\n#include<chrono>\nusing namespace std;\nusing namespace std::chrono;\n\ndouble* I;\n// vector<vector<pair<int, double> > > H_Compact;/\nmap<int, vector<pair<int, double> > > H_Map;\nvector<int> activeIndices;\nvector<int> dangling_nodes;\ndouble alpha = 0.85;\nint activeNodeSize;\n\ntemplate<typename MapTask>\nclass datasource : mapreduce::detail::noncopyable{\npublic:\n    datasource(unsigned size_) : sequence_(0), size(size_){\n    }\n\n    bool const setup_key(typename MapTask::key_type &key){\n    \tint tempIndex = sequence_++;\n        key = activeIndices[tempIndex];\n        // return ((H_Compact[key].size() != 0) && (key < size));\n        // return key < size;\n        // return H_Map.find(key) != H_Map.end();\n        return tempIndex < activeNodeSize;\n    }\n\n    bool const get_data(typename MapTask::key_type const &key, typename MapTask::value_type &value){\n    \t// value.clear();\n    \tfor(int j=0;j<H_Map[key].size();j++){\n\t\t\tvalue.push_back(H_Map[key][j]);\n\t\t}\n\t\t// value = H_Map[key];\n\n\t\t// value.assign()\n        return true;\n    }\n\nprivate:\n    int sequence_;\n    int size;\n};\n\nstruct map_task : public mapreduce::map_task<int, vector<pair<int, double> > >{\n    template<typename Runtime>\n    void operator()(Runtime &runtime, key_type const &key, value_type const &value) const\n    {\n    \t// if(value.size() != 0){\n\t\ttypename Runtime::reduce_task_type::key_type const emit_key = key;\n    \truntime.emit_intermediate(emit_key, value);\t\n    \t// }\n    }\n};\n\nstruct reduce_task : public mapreduce::reduce_task<int, vector<pair<int, double> > >{\n    template<typename Runtime, typename It>\n    void operator()(Runtime &runtime, key_type const &key, It it, It ite) const\n    {\n\t\tdouble sum = 0;\n\t\tvector<pair<int, double> > results;\n\t\t\n\t\tfor(unsigned i=0;i<(*it).size();i++){\n\t\t\tsum += ((*it)[i].second)*(I[(*it)[i].first]);\n\t\t}\n\t\tsum *= alpha;\n\t\tif(sum != 0){\n\t\t\tresults.push_back(make_pair(0, sum));\n\t\t\truntime.emit(key, results);\n\t\t}\n\t\treturn;\n    }\n};\n\ntypedef mapreduce::job<map_task, reduce_task, mapreduce::null_combiner, datasource<map_task> > job;\n\nint main(int argc, char *argv[]){\n    mapreduce::specification spec;\n    \n    if(argc < 2){\n    \tcerr << \"Invalid Arguments!\" << endl;\n    \treturn 0;\n    }\n\n    string filename = \"../test/\" + (string)argv[1] + \".txt\";\n\n    if (argc > 2){\n        spec.map_tasks = max(1, atoi(argv[1]));\n    }\n\n    if(argc > 3){\n        spec.reduce_tasks = atoi(argv[2]);\n    }\n\n    else{\n        spec.reduce_tasks = max(1U, thread::hardware_concurrency());\n    }\n\n    // Datasource maybe from a file!\n    int size = getMatrixSize(filename);\n    int n = size;\n    cout << \"Matrix Size: \" << size << endl;\n\n    // H_Compact.resize(n);\n    // readCompactMatrixFile(filename, n, dangling_nodes, H_Compact);\n    readMapMatrixFile(filename, n, dangling_nodes, H_Map, activeIndices);\n    // printMap(H_Map);\n   \n    activeNodeSize = activeIndices.size();\n    cout <<\"\\nPageRank analysis MapReduce...\" << endl;\n    auto start = high_resolution_clock::now(); \n\n    double DI[n] = {0};\n    \n    for(int i=0;i<dangling_nodes.size();i++){\n    \tDI[dangling_nodes[i]] = 1.0/n;\n\t}\n\n\tdouble GI[n] = {0};\n\tI = (double*)malloc((size)*sizeof(double));\n\tmemset(I, 0, n*sizeof(double));\n\tI[0] = 1;\n\t\n\tbool converged = false;\n\tint index = 0;\n\t// return 0;\n\twhile(index < 100){\n\t\tdouble randomDanglingSum = 0;\n\t\t\n\t\tfor(int i=0;i<n;i++){\n\t\t\trandomDanglingSum += alpha*DI[i]*I[i] + ((1.0-alpha)/n)*I[i];\n\t\t}\n\n\t\tmemset(GI, 0, n*sizeof(double));\n\t\t\n\t\tjob::datasource_type datasource(size);\n\t\tjob job1(datasource, spec);\n\t    mapreduce::results result;\n\n\t\t// job1.run<mapreduce::schedule_policy::sequential<job> >(result);\n\t\tjob1.run<mapreduce::schedule_policy::cpu_parallel<job> >(result);\n\t\t\n\t\tfor(auto it=job1.begin_results(); it!=job1.end_results(); ++it){\n\t\t\tGI[it->first] = it->second[0].second;\n\t    }\n\t    \n\t\tfor(int i=0;i<n;i++){\n\t\t\tGI[i] += randomDanglingSum;\n\t\t}\n\n\t\tmemcpy(I, GI, n*sizeof(double));\n\t\t\n\t\tindex++;\n\t}\n\n\t// printMatrix(I, n);\n\tauto stop = high_resolution_clock::now();\n\tauto duration = duration_cast<microseconds>(stop - start);\n\tcout << \"Time taken by function: \" << (double)duration.count()/1000000 << \" seconds\" << endl; \n\twriteToFile((string)argv[1], 0, I, n);\n    return 0;\n}", "meta": {"hexsha": "051df89115fd098525267038a38ad5fd1eb3ba69", "size": 4657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pagerank_mapreduce.cpp", "max_stars_repo_name": "prateekstark/pagerank", "max_stars_repo_head_hexsha": "e86e06a1748a1e677ec4100f8d2e8c95a214f607", "max_stars_repo_licenses": ["MIT"], "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/pagerank_mapreduce.cpp", "max_issues_repo_name": "prateekstark/pagerank", "max_issues_repo_head_hexsha": "e86e06a1748a1e677ec4100f8d2e8c95a214f607", "max_issues_repo_licenses": ["MIT"], "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/pagerank_mapreduce.cpp", "max_forks_repo_name": "prateekstark/pagerank", "max_forks_repo_head_hexsha": "e86e06a1748a1e677ec4100f8d2e8c95a214f607", "max_forks_repo_licenses": ["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.3107344633, "max_line_length": 100, "alphanum_fraction": 0.6340992055, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6513549372754315}}
{"text": "//\n// $Id$\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 <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"pwiz/utility/misc/Std.hpp\"\n//#include <execinfo.h>\n\n#include \"pwiz/utility/misc/unit.hpp\"\n#include \"Types.hpp\"\n#include \"qr.hpp\"\n\nusing namespace boost::numeric::ublas;\nusing namespace pwiz::math;\nusing namespace pwiz::math::types;\nusing namespace pwiz::util;\n\n\nostream* os_ = 0;\nconst double epsilon = 1e-12;\n\n\ntemplate<class matrix_type>\nbool isUpperTriangular(const matrix_type& A, double eps)\n{\n    typedef typename matrix_type::size_type size_type;\n    bool upper = true;\n    \n    for (size_type i=1; i<A.size2() && upper; i++)\n    {\n        for (size_type j=0; j<i && upper; j++)\n        {\n            upper = fabs(A(i,j)) < eps;\n        }\n    }\n\n    return upper;\n}\n\n\nvoid testReflector()\n{\n    if (os_) *os_ << \"testReflector() begin\" << endl;\n\n    dmatrix F(3,3);\n    dvector x(3);\n\n    x(0) = 1;\n    x(1) = 1;\n    x(2) = 0;\n\n    Reflector(x, F);\n\n    dvector v = prod(F, x);\n\n    unit_assert_equal(fabs(v(0)), norm_2(x), epsilon);\n    unit_assert_equal(v(1), 0, epsilon);\n    unit_assert_equal(v(2), 0, epsilon);\n    \n    x(0) = -1;\n    x(1) = 1;\n    x(2) = 0;\n\n    if (os_) *os_ << \"testReflector() end\" << endl;\n}\n\nvoid testQR()\n{\n    if (os_) *os_ << \"testQR() begin\" << endl;\n    \n    dmatrix A(3,3);\n    dmatrix Q(3,3);\n    dmatrix R(3,3);\n\n    for (dmatrix::size_type i=0; i< A.size1(); i++)\n    {\n        for (dmatrix::size_type j=0; j<A.size2(); j++)\n        {\n            A(i,j) = ((i==j) || (j == 0));\n        }\n    }\n\n    try {\n        qr<dmatrix>(A, Q, R);\n\n        unit_assert(isUpperTriangular(R, epsilon));\n\n        dmatrix diff = (A - prod(Q, R));\n\n        unit_assert_equal(norm_1(diff), 0, epsilon);\n\n        identity_matrix<dmatrix::value_type> eye(Q.size1());\n        diff = prod(Q, herm(Q)) - eye;\n        \n        unit_assert_equal(norm_1(diff), 0, epsilon);        \n    }\n    catch (boost::numeric::ublas::bad_argument ba)\n    {\n        if (os_) *os_ << \"exception: \" << ba.what() << endl;\n    }\n    \n    if (os_) *os_ << \"testQR() end\" << endl;\n}\n\nvoid testRectangularQR()\n{\n    if (os_) *os_ << \"testRectangularQR() begin\" << endl;\n    \n    dmatrix A(5,3);\n    dmatrix Q;\n    dmatrix R;\n\n    for (dmatrix::size_type i=0; i< A.size1(); i++)\n    {\n        for (dmatrix::size_type j=0; j<A.size2(); j++)\n        {\n            A(i,j) = ((i==j) || (j == 0));\n        }\n    }\n\n    try {\n        qr<dmatrix>(A, Q, R);\n\n        unit_assert(isUpperTriangular(R, epsilon));\n\n        dmatrix diff = (A - prod(Q, R));\n\n        unit_assert_equal(norm_1(diff), 0, epsilon);\n\n        identity_matrix<dmatrix::value_type> eye(Q.size1());\n        diff = prod(Q, herm(Q)) - eye;\n        \n        unit_assert_equal(norm_1(diff), 0, epsilon);        \n    }\n    catch (boost::numeric::ublas::bad_argument ba)\n    {\n        if (os_) *os_ << \"exception: \" << ba.what() << endl;\n    }\n    \n    if (os_) *os_ << \"testRectangularQR() end\" << endl;\n}\n\nint main(int argc, char** argv)\n{\n    if (argc>1 && !strcmp(argv[1],\"-v\")) os_ = &cout;\n    if (os_) *os_ << \"qrTest\\n\";\n    testReflector();\n    testQR();\n    testRectangularQR();\n\n    return 0;\n}\n", "meta": {"hexsha": "8749a0124444c92816d58c0b82c3083a0553a125", "size": 3767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/qrTest.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/utility/math/qrTest.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/utility/math/qrTest.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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.4226190476, "max_line_length": 76, "alphanum_fraction": 0.5659676135, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6513549342451402}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestRotation3DZYX\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <cmath>\n#include \"minimath/rotation3d.hpp\"\n#include \"minimath/point3d.hpp\"\n#include \"Defines.h\"\n#include \"TestRotation3DUtils.h\"\n\nusing namespace minimath;\n\nBOOST_AUTO_TEST_SUITE(TestRotation3DZYX)\n\nnamespace\n{\n\n//\n// Check that a RotationZYX defined by angles phi, theta, psi has the same\n// effect on a point as individual Z, Y and X rotations.\n//\nbool testRotationZYX(const minimath::pointxyzd& point,\n                     double phi, \n                     double theta, \n                     double psi)\n{ \n  rotation3dzyx<double> rot1(phi, theta, psi);\n  pointxyzd ref = rotation3dx<double>(psi) *\n      ( rotation3dy<double>(theta) * (rotation3dz<double>(phi)*point) );\n  return rot1*point == ref;\n}\n\n} // namespace\n\nBOOST_AUTO_TEST_CASE(testInstantiation)\n{\n  rotation3dzyx<double> rot1, rot2;\n}\n\nBOOST_AUTO_TEST_CASE(testDefaultEquality)\n{\n  BOOST_CHECK(rotation3dzyx<double>() == rotation3dzyx<double>());\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  rotation3dzyx<double> rot1;\n  rotation3dzyx<double> rot2(rot1);\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  rotation3dzyx<double> rot1, rot2;\n  rot2 = rot1;\n  BOOST_CHECK(rot1 == rot2);\n}\n\nBOOST_AUTO_TEST_CASE(testNullRotation)\n{\n  rotation3dzyx<double> rot;\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45X)\n{\n  rotation3dzyx<double> rot(0, 0, PI/4.); // 45 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., cos45, cos45));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -cos45, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90X)\n{\n  rotation3dzyx<double> rot(0, 0, PI/2.); // 90 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180X)\n{\n  rotation3dzyx<double> rot(0, 0, PI); // 180 degree rotation about X\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Y)\n{\n  rotation3dzyx<double> rot(0, PI/4., 0); // 45 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0., -cos45));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(cos45, 0, cos45));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Y)\n{\n  rotation3dzyx<double> rot(0, PI/2., 0); // 90 degree rotation about X\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(1., 0., 0.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Y)\n{\n  rotation3dzyx<double> rot(0, PI, 0); // 180 degree rotation about X\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., -1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint45Z)\n{\n  rotation3dzyx<double> rot(PI/4., 0, 0); // 45 degree rotation about Z\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(cos45, cos45, 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(-cos45, cos45, 0));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0, 0, 1));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint90Z)\n{\n  rotation3dzyx<double> rot(PI/2., 0, 0); // 90 degree rotation about Z\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(0., 1., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testRotatePoint180Z)\n{\n  rotation3dzyx<double> rot(PI, 0, 0); // 180 degree rotation about Z\n\n  pointxyzd pTest = rot*p100;\n  BOOST_CHECK(pTest == pointxyzd(-1., 0., 0.));\n\n  pTest = rot*p010;\n  BOOST_CHECK(pTest == pointxyzd(0., -1., 0.));\n\n  pTest = rot*p001;\n  BOOST_CHECK(pTest == pointxyzd(0., 0., 1.));\n}\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DX)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(rotation3dzyx<double>(0, 0, PI/i) == rotation3dx<double>(PI/i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DY)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(rotation3dzyx<double>(0, PI/i, 0) == rotation3dy<double>(PI/i));\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(testAssignRotation3DZ)\n{\n  for (int i = 1; i < 9; ++i) {\n    BOOST_CHECK(rotation3dzyx<double>(PI/i, 0, 0) == rotation3dz<double>(PI/i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testZYXRotations)\n{\n  for (int i = 1; i < 9; ++i) {\n\n    const double angle = PI/i;\n\n    BOOST_CHECK(testRotationZYX(p100, angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p010, angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p001, angle, angle, angle)); \n\n    BOOST_CHECK(testRotationZYX(p100, -angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p010, angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p001, angle, angle, angle)); \n\n    BOOST_CHECK(testRotationZYX(p100, angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p010, -angle, angle, angle));\n    BOOST_CHECK(testRotationZYX(p001, angle, angle, angle)); \n\n    BOOST_CHECK(testRotationZYX(p100, angle, -angle, angle));\n    BOOST_CHECK(testRotationZYX(p010, angle, -angle, angle));\n    BOOST_CHECK(testRotationZYX(p001, angle, -angle, angle)); \n\n    BOOST_CHECK(testRotationZYX(p100, -angle, -angle, -angle));\n    BOOST_CHECK(testRotationZYX(p010, -angle, -angle, -angle));\n    BOOST_CHECK(testRotationZYX(p001, -angle, -angle, -angle)); \n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  BOOST_CHECK(TestUtils::testInverseRotation3DZYX<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInverseRotation3DZYX<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInverseRotation3DZYX<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  BOOST_CHECK(TestUtils::testInvertRotation3DZYX<rotation3dx<double> >());\n  BOOST_CHECK(TestUtils::testInvertRotation3DZYX<rotation3dy<double> >());\n  BOOST_CHECK(TestUtils::testInvertRotation3DZYX<rotation3dz<double> >());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "febed35d7ca6fe409bf6b00fe354b6a435d9c99d", "size": 6943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestRotation3DZYX.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestRotation3DZYX.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestRotation3DZYX.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 26.2992424242, "max_line_length": 80, "alphanum_fraction": 0.6893273801, "num_tokens": 2251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6513275248980713}}
{"text": "// Copyright Nick Thompson, 2017\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#include <iostream>\r\n#include <cmath>\r\n#include <boost/math/quadrature/tanh_sinh.hpp>\r\n#include <boost/math/quadrature/sinh_sinh.hpp>\r\n#include <boost/math/quadrature/exp_sinh.hpp>\r\n\r\nusing boost::math::quadrature::tanh_sinh;\r\nusing boost::math::quadrature::sinh_sinh;\r\nusing boost::math::quadrature::exp_sinh;\r\nusing boost::math::constants::pi;\r\nusing boost::math::constants::half_pi;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::root_pi;\r\nusing std::log;\r\nusing std::cos;\r\nusing std::cosh;\r\nusing std::exp;\r\nusing std::sqrt;\r\n\r\nint main()\r\n{\r\n    std::cout << std::setprecision(std::numeric_limits<double>::digits10);\r\n    double tol = sqrt(std::numeric_limits<double>::epsilon());\r\n    // For an integral over a finite domain, use tanh_sinh:\r\n    tanh_sinh<double> tanh_integrator(tol, 10);\r\n    auto f1 = [](double x) { return log(x)*log(1-x); };\r\n    double Q = tanh_integrator.integrate(f1, (double) 0, (double) 1);\r\n    double Q_expected = 2 - pi<double>()*pi<double>()*half<double>()*third<double>();\r\n\r\n    std::cout << \"tanh_sinh quadrature of log(x)log(1-x) gives \" << Q << std::endl;\r\n    std::cout << \"The exact integral is                        \" << Q_expected << std::endl;\r\n\r\n    // For an integral over the entire real line, use sinh-sinh quadrature:\r\n    sinh_sinh<double> sinh_integrator(tol, 10);\r\n    auto f2 = [](double t) { return cos(t)/cosh(t);};\r\n    Q = sinh_integrator.integrate(f2);\r\n    Q_expected = pi<double>()/cosh(half_pi<double>());\r\n    std::cout << \"sinh_sinh quadrature of cos(x)/cosh(x) gives \" << Q << std::endl;\r\n    std::cout << \"The exact integral is                        \" << Q_expected << std::endl;\r\n\r\n    // For half-infinite intervals, use exp-sinh.\r\n    // Endpoint singularities are handled well:\r\n    exp_sinh<double> exp_integrator(tol, 10);\r\n    auto f3 = [](double t) { return exp(-t)/sqrt(t); };\r\n    Q = exp_integrator.integrate(f3, 0, std::numeric_limits<double>::infinity());\r\n    Q_expected = root_pi<double>();\r\n    std::cout << \"exp_sinh quadrature of exp(-t)/sqrt(t) gives \" << Q << std::endl;\r\n    std::cout << \"The exact integral is                        \" << Q_expected << std::endl;\r\n\r\n\r\n\r\n}\r\n", "meta": {"hexsha": "fc3b161b1798dd7567f9b22ec990e49e13ae8b22", "size": 2455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/double_exponential.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/double_exponential.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/double_exponential.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": 40.9166666667, "max_line_length": 93, "alphanum_fraction": 0.6431771894, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.65132751453714}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 06.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"solve.h\"\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"mylinearfeelementmatrix.h\"\n#include \"mylinearloadvector.h\"\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solvePoissonBVP() {\n  // Convert the globally defined function f to a LehrFEM++ mesh function object\n  lf::mesh::utils::MeshFunctionGlobal mf_f{f};\n\n  // The basis expansion coefficient vector for the finite-element solution\n  Eigen::VectorXd solution = Eigen::VectorXd::Zero(1);\n\n  //====================\n  // Your code goes here\n  // that is to call solve() in order to compute the basis expansion coefficients of a solution \n  // of the Neumann boundary value problem\n  // make use of the LehrFEM++'s local PROVIDER types for element matrices for the bilinear form \n  //for the weak-laplacian\n  // and element vectors for the linear form \n  // initialize the lf::uscalfe::LinearFELocalLoadVector appropriately so that the right-hand side source function \n  // provided by the funtion f(Eigen::Vector2d x); \n\n  // define the element matrix and element vector builders and solve the system \n  lf::uscalfe::LinearFELaplaceElementMatrix elmat_builder; \n  lf::uscalfe::LinearFELocalLoadVector<double, decitype(mf_f)> elvec_builder(mf_f); \n  Eigen::VectorXd solve(elmat_builder, elvec_provider)\uff1b \n  //====================\n\n  return solution;\n}\n/* SAM_LISTING_END_2 */\n\nEigen::VectorXd solveNeumannEq() {\n  // Define the solution vector\n  Eigen::VectorXd solution;\n\n  //====================\n  // Your code goes here\n  //====================\n\n  return solution;\n}\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "8cdaa011270d489b0948459cdec5a9aea6dfee47", "size": 1798, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/solve.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/solve.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/solve.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4745762712, "max_line_length": 115, "alphanum_fraction": 0.7091212458, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6513275116249196}}
{"text": "#ifndef _INCLUDES_HPP_\n#define _INCLUDES_HPP_\n\n#define _USE_MATH_DEFINES\t\t// The get M_PI and similar constants from cmath\n\n#include <iostream>\t\t\t// For console I/O\n#include <fstream>\t\t\t// For file I/O\n#include <stdio.h>\t\t\t// For getchar\n#include <math.h>\t\t\t// Basic math functions\n#include <iomanip>\t\t\t// For setprecision\n#include <vector>\t\t\t// For stl vectors\n#include <string>\t\t\t// For stl strings\n#include <time.h>\t\t\t// For getting the time (e.g., and a RNG seed)\n#include <sstream>\t\t\t// Stringstream\n#include <stdarg.h>\t\t\t// For functions with different numbers of inputs\n#include <functional>\t\t// For passing functions\n#include <random>\t\t\t// For random numbers\n#include <thread>\t\t\t// For creating multiple threads\n#include <unistd.h>\t\t\t// To get the working directory\n#include <iterator>\t\t\t// Used by things like istream_iterator\n\n// For getting the current directory\n//#include <unistd.h>\n//#define GetCurrentDir getcwd\n\n#include <Eigen/Dense>\t\t\t// For matrix math\n#include <Eigen/SVD>\t\t\t// For writing our Moore-Penrose pseudo-inverse implementation\n#include <Eigen/Eigenvalues>\t\t// For getting eigenvalues\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\nusing namespace std;\nusing namespace Eigen;\n\n#include <IOStringUtils.hpp>\t\t\t\t// Basic file and string I/O functions\n#include <MathUtils.hpp>\t\t\t\t\t// Some useful math functions that aren't in other included libraries\n#include <MarsagliaGenerator.hpp>\n\n\n#endif\n", "meta": {"hexsha": "0848562396a4bbdbab07aed211e4a5a9499c909c", "size": 1422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gridworld/headers/Includes.hpp", "max_stars_repo_name": "LARG/regression-importance-sampling", "max_stars_repo_head_hexsha": "8cf2acf9313ab270c192fda29e1d5c1db68c2acc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-06-06T17:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T05:42:40.000Z", "max_issues_repo_path": "gridworld/headers/Includes.hpp", "max_issues_repo_name": "LARG/regression-importance-sampling", "max_issues_repo_head_hexsha": "8cf2acf9313ab270c192fda29e1d5c1db68c2acc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-21T16:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T13:53:48.000Z", "max_forks_repo_path": "gridworld/headers/Includes.hpp", "max_forks_repo_name": "LARG/regression-importance-sampling", "max_forks_repo_head_hexsha": "8cf2acf9313ab270c192fda29e1d5c1db68c2acc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T00:18:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T21:50:27.000Z", "avg_line_length": 34.6829268293, "max_line_length": 98, "alphanum_fraction": 0.729254571, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6513275041762083}}
{"text": "// Copyright 2015-2022 Tier IV, Inc. All rights reserved.\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#include <boost/lexical_cast.hpp>\n#include <random>\n#include <rclcpp/rclcpp.hpp>\n\nauto main(const int argc, char const * const * const argv) -> int\n{\n  rclcpp::init(argc, argv);\n\n  auto node = std::make_shared<rclcpp::Node>(\"uniform_distribution\");\n\n  auto number = [&]() {\n    auto engine = std::default_random_engine(std::random_device()());\n    switch (argc) {\n      case 3:\n        return std::uniform_real_distribution<double>(\n          boost::lexical_cast<double>(argv[1]), boost::lexical_cast<double>(argv[2]))(engine);\n      default:\n        return std::uniform_real_distribution<double>(0, 1)(engine);\n    }\n  };\n\n  std::cout << number() << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "bea47c0da1e5861e8d6c7354b7ebb2ee2a1f6aee", "size": 1305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openscenario/openscenario_interpreter_example/src/uniform_distribution.cpp", "max_stars_repo_name": "TakahiroNISHIOKA/scenario_simulator_v2", "max_stars_repo_head_hexsha": "949a46a64a26d17413c2586577e1f3a5ba41161e", "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": "openscenario/openscenario_interpreter_example/src/uniform_distribution.cpp", "max_issues_repo_name": "TakahiroNISHIOKA/scenario_simulator_v2", "max_issues_repo_head_hexsha": "949a46a64a26d17413c2586577e1f3a5ba41161e", "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": "openscenario/openscenario_interpreter_example/src/uniform_distribution.cpp", "max_forks_repo_name": "TakahiroNISHIOKA/scenario_simulator_v2", "max_forks_repo_head_hexsha": "949a46a64a26d17413c2586577e1f3a5ba41161e", "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": 32.625, "max_line_length": 94, "alphanum_fraction": 0.6950191571, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6513141975236911}}
{"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 of the empirical_kernel_map \r\n    from the dlib C++ Library.\r\n\r\n    This example program assumes you are familiar with some general elements of \r\n    the library.  In particular, you should have at least read the svm_ex.cpp \r\n    and matrix_ex.cpp examples.   \r\n\r\n\r\n    Most of the machine learning algorithms in dlib are some flavor of \"kernel machine\".\r\n    This means they are all simple linear algorithms that have been formulated such \r\n    that the only way they look at the data given by a user is via dot products between\r\n    the data samples.  These algorithms are made more useful via the application of the\r\n    so-called kernel trick.  This trick is to replace the dot product with a user \r\n    supplied function which takes two samples and returns a real number.  This function \r\n    is the kernel that is required by so many algorithms.  The most basic kernel is the \r\n    linear_kernel which is simply a normal dot product.  More interesting, however,\r\n    are kernels which first apply some nonlinear transformation to the user's data samples \r\n    and then compute a dot product.  In this way, a simple algorithm that finds a linear\r\n    plane to separate data (e.g. the SVM algorithm) can be made to solve complex \r\n    nonlinear learning problems.  \r\n    \r\n    An important element of the kernel trick is that these kernel functions perform \r\n    the nonlinear transformation implicitly.  That is, if you look at the implementations\r\n    of these kernel functions you won't see code that transforms two input vectors in \r\n    some way and then computes their dot products.  Instead you will see a simple function\r\n    that takes two input vectors and just computes a single real number via some simple\r\n    process.  You can basically think of this as an optimization.  Imagine that originally \r\n    we wrote out the entire procedure to perform the nonlinear transformation and then\r\n    compute the dot product but then noticed we could cancel a few terms here and there \r\n    and simplify the whole thing down into a more compact and easily evaluated form.\r\n    The result is a nice function that computes what we want but we no longer get to see\r\n    what those nonlinearly transformed input vectors are.  \r\n\r\n    The empirical_kernel_map is a tool that undoes this.  It allows you to obtain these \r\n    nonlinearly transformed vectors.  It does this by taking a set of data samples from \r\n    the user (referred to as basis samples), applying the nonlinear transformation to all \r\n    of them, and then constructing a set of orthonormal basis vectors which spans the space \r\n    occupied by those transformed input samples.  Then if we wish to obtain the nonlinear \r\n    version of any data sample we can simply project it onto this orthonormal basis and \r\n    we obtain a regular vector of real numbers which represents the nonlinearly transformed \r\n    version of the data sample.  The empirical_kernel_map has been formulated to use only \r\n    dot products between data samples so it is capable of performing this service for any \r\n    user supplied kernel function. \r\n    \r\n    The empirical_kernel_map is useful because it is often difficult to formulate an \r\n    algorithm in a way that uses only dot products.  So the empirical_kernel_map lets \r\n    us easily kernelize any algorithm we like by using this object during a preprocessing \r\n    step.  However, it should be noted that the algorithm is only practical when used \r\n    with at most a few thousand basis samples.  Fortunately, most datasets live in \r\n    subspaces that are relatively low dimensional.  So for these datasets, using the \r\n    empirical_kernel_map is practical assuming an appropriate set of basis samples can be \r\n    selected by the user.  To help with this dlib supplies the linearly_independent_subset_finder.  \r\n    I also often find that just picking a random subset of the data as a basis works well.\r\n\r\n\r\n\r\n    In what follows, we walk through the process of creating an empirical_kernel_map,\r\n    projecting data to obtain the nonlinearly transformed vectors, and then doing a \r\n    few interesting things with the data.\r\n*/\r\n\r\n\r\n\r\n\r\n#include <dlib/svm.h>\r\n#include <dlib/rand.h>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n// First let's make a typedef for the kind of samples we will be using. \r\ntypedef matrix<double, 0, 1> sample_type;\r\n\r\n// We will be using the radial_basis_kernel in this example program.\r\ntypedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid generate_concentric_circles (\r\n    std::vector<sample_type>& samples,\r\n    std::vector<double>& labels,\r\n    const int num_points\r\n);\r\n/*!\r\n    requires\r\n        - num_points > 0\r\n    ensures\r\n        - generates two circles centered at the point (0,0), one of radius 1 and\r\n          the other of radius 5.  These points are stored into samples.  labels will\r\n          tell you if a given samples is from the smaller circle (its label will be 1)\r\n          or from the larger circle (its label will be 2).\r\n        - each circle will be made up of num_points\r\n!*/\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid test_empirical_kernel_map (\r\n    const std::vector<sample_type>& samples,\r\n    const std::vector<double>& labels,\r\n    const empirical_kernel_map<kernel_type>& ekm\r\n);\r\n/*!\r\n    This function computes various interesting things with the empirical_kernel_map.  \r\n    See its implementation below for details.\r\n!*/\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    std::vector<sample_type> samples;\r\n    std::vector<double> labels;\r\n\r\n    // Declare an instance of the kernel we will be using.  \r\n    const kernel_type kern(0.1);\r\n\r\n    // create a dataset with two concentric circles.  There will be 100 points on each circle.\r\n    generate_concentric_circles(samples, labels, 100);\r\n\r\n    empirical_kernel_map<kernel_type> ekm;\r\n\r\n\r\n    // Here we create an empirical_kernel_map using all of our data samples as basis samples.  \r\n    cout << \"\\n\\nBuilding an empirical_kernel_map with \" << samples.size() << \" basis samples.\" << endl;\r\n    ekm.load(kern, samples);\r\n    cout << \"Test the empirical_kernel_map when loaded with every sample.\" << endl;\r\n    test_empirical_kernel_map(samples, labels, ekm);\r\n\r\n\r\n\r\n\r\n\r\n\r\n    // create a new dataset with two concentric circles.  There will be 1000 points on each circle.\r\n    generate_concentric_circles(samples, labels, 1000);\r\n    // Rather than use all 2000 samples as basis samples we are going to use the \r\n    // linearly_independent_subset_finder to pick out a good basis set.  The idea behind this \r\n    // object is to try and find the 40 or so samples that best spans the subspace containing all the \r\n    // data.  \r\n    linearly_independent_subset_finder<kernel_type> lisf(kern, 40);\r\n    // populate lisf with samples.  We have configured it to allow at most 40 samples but this function \r\n    // may determine that fewer samples are necessary to form a good basis.  In this example program\r\n    // it will select only 26.\r\n    fill_lisf(lisf, samples);\r\n\r\n    // Now reload the empirical_kernel_map but this time using only our small basis  \r\n    // selected using the linearly_independent_subset_finder.\r\n    cout << \"\\n\\nBuilding an empirical_kernel_map with \" << lisf.size() << \" basis samples.\" << endl;\r\n    ekm.load(lisf);\r\n    cout << \"Test the empirical_kernel_map when loaded with samples from the lisf object.\" << endl;\r\n    test_empirical_kernel_map(samples, labels, ekm);\r\n\r\n\r\n    cout << endl;\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid test_empirical_kernel_map (\r\n    const std::vector<sample_type>& samples,\r\n    const std::vector<double>& labels,\r\n    const empirical_kernel_map<kernel_type>& ekm\r\n)\r\n{\r\n\r\n    std::vector<sample_type> projected_samples;\r\n\r\n    // The first thing we do is compute the nonlinearly projected vectors using the \r\n    // empirical_kernel_map.  \r\n    for (unsigned long i = 0; i < samples.size(); ++i)\r\n    {\r\n        projected_samples.push_back(ekm.project(samples[i]));\r\n    }\r\n\r\n    // Note that a kernel matrix is just a matrix M such that M(i,j) == kernel(samples[i],samples[j]).\r\n    // So below we are computing the normal kernel matrix as given by the radial_basis_kernel and the\r\n    // input samples.  We also compute the kernel matrix for all the projected_samples as given by the \r\n    // linear_kernel.  Note that the linear_kernel just computes normal dot products.  So what we want to\r\n    // see is that the dot products between all the projected_samples samples are the same as the outputs\r\n    // of the kernel function for their respective untransformed input samples.  If they match then\r\n    // we know that the empirical_kernel_map is working properly.\r\n    const matrix<double> normal_kernel_matrix = kernel_matrix(ekm.get_kernel(), samples);\r\n    const matrix<double> new_kernel_matrix = kernel_matrix(linear_kernel<sample_type>(), projected_samples);\r\n\r\n    cout << \"Max kernel matrix error: \" << max(abs(normal_kernel_matrix - new_kernel_matrix)) << endl;\r\n    cout << \"Mean kernel matrix error: \" << mean(abs(normal_kernel_matrix - new_kernel_matrix)) << endl;\r\n    /*\r\n        Example outputs from these cout statements.\r\n        For the case where we use all samples as basis samples:\r\n            Max kernel matrix error: 7.32747e-15\r\n            Mean kernel matrix error: 7.47789e-16\r\n\r\n        For the case where we use only 26 samples as basis samples:\r\n            Max kernel matrix error: 0.000953573\r\n            Mean kernel matrix error: 2.26008e-05\r\n\r\n\r\n        Note that if we use enough basis samples we can perfectly span the space of input samples.\r\n        In that case we get errors that are essentially just rounding noise (Moreover, using all the \r\n        samples is always enough since they are always within their own span).  Once we start \r\n        to use fewer basis samples we may begin to get approximation error.  In the second case we \r\n        used 26 and we can see that the data doesn't really lay exactly in a 26 dimensional subspace.  \r\n        But it is pretty close.  \r\n    */\r\n\r\n\r\n\r\n    // Now let's do something more interesting.  The following loop finds the centroids\r\n    // of the two classes of data.\r\n    sample_type class1_center; \r\n    sample_type class2_center; \r\n    for (unsigned long i = 0; i < projected_samples.size(); ++i)\r\n    {\r\n        if (labels[i] == 1)\r\n            class1_center += projected_samples[i];\r\n        else\r\n            class2_center += projected_samples[i];\r\n    }\r\n\r\n    const int points_per_class = samples.size()/2;\r\n    class1_center /= points_per_class;\r\n    class2_center /= points_per_class;\r\n\r\n\r\n    // Now classify points by which center they are nearest.  Recall that the data\r\n    // is made up of two concentric circles.  Normally you can't separate two concentric\r\n    // circles by checking which points are nearest to each center since they have the same\r\n    // centers.  However, the kernel trick makes the data separable and the loop below will \r\n    // perfectly classify each data point.\r\n    for (unsigned long i = 0; i < projected_samples.size(); ++i)\r\n    {\r\n        double distance_to_class1 = length(projected_samples[i] - class1_center);\r\n        double distance_to_class2 = length(projected_samples[i] - class2_center);\r\n\r\n        bool predicted_as_class_1 = (distance_to_class1 < distance_to_class2);\r\n\r\n        // Now print a message for any misclassified points.\r\n        if (predicted_as_class_1 == true && labels[i] != 1)\r\n            cout << \"A point was misclassified\" << endl;\r\n\r\n        if (predicted_as_class_1 == false && labels[i] != 2)\r\n            cout << \"A point was misclassified\" << endl;\r\n    }\r\n\r\n\r\n\r\n    // Next, note that classifying a point based on its distance between two other \r\n    // points is the same thing as using the plane that lies between those two points \r\n    // as a decision boundary.  So let's compute that decision plane and use it to classify \r\n    // all the points.\r\n    \r\n    sample_type plane_normal_vector = class1_center - class2_center;\r\n    // The point right in the center of our two classes should be on the deciding plane, not\r\n    // on one side or the other.  This consideration brings us to the formula for the bias.\r\n    double bias = dot((class1_center+class2_center)/2, plane_normal_vector);\r\n\r\n    // Now classify points by which side of the plane they are on.\r\n    for (unsigned long i = 0; i < projected_samples.size(); ++i)\r\n    {\r\n        double side = dot(plane_normal_vector, projected_samples[i]) - bias;\r\n\r\n        bool predicted_as_class_1 = (side > 0);\r\n\r\n        // Now print a message for any misclassified points.\r\n        if (predicted_as_class_1 == true && labels[i] != 1)\r\n            cout << \"A point was misclassified\" << endl;\r\n\r\n        if (predicted_as_class_1 == false && labels[i] != 2)\r\n            cout << \"A point was misclassified\" << endl;\r\n    }\r\n\r\n\r\n    // It would be nice to convert this decision rule into a normal decision_function object and\r\n    // dispense with the empirical_kernel_map.  Happily, it is possible to do so.  Consider the\r\n    // following example code:\r\n    decision_function<kernel_type> dec_funct = ekm.convert_to_decision_function(plane_normal_vector);\r\n    // The dec_funct now computes dot products between plane_normal_vector and the projection\r\n    // of any sample point given to it.  All that remains is to account for the bias. \r\n    dec_funct.b = bias;\r\n\r\n    // now classify points by which side of the plane they are on.\r\n    for (unsigned long i = 0; i < samples.size(); ++i)\r\n    {\r\n        double side = dec_funct(samples[i]);\r\n\r\n        // And let's just check that the dec_funct really does compute the same thing as the previous equation.\r\n        double side_alternate_equation = dot(plane_normal_vector, projected_samples[i]) - bias;\r\n        if (abs(side-side_alternate_equation) > 1e-14)\r\n            cout << \"dec_funct error: \" << abs(side-side_alternate_equation) << endl;\r\n\r\n        bool predicted_as_class_1 = (side > 0);\r\n\r\n        // Now print a message for any misclassified points.\r\n        if (predicted_as_class_1 == true && labels[i] != 1)\r\n            cout << \"A point was misclassified\" << endl;\r\n\r\n        if (predicted_as_class_1 == false && labels[i] != 2)\r\n            cout << \"A point was misclassified\" << endl;\r\n    }\r\n\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nvoid generate_concentric_circles (\r\n    std::vector<sample_type>& samples,\r\n    std::vector<double>& labels,\r\n    const int num\r\n)\r\n{\r\n    sample_type m(2,1);\r\n    samples.clear();\r\n    labels.clear();\r\n\r\n    dlib::rand rnd;\r\n\r\n    // make some samples near the origin\r\n    double radius = 1.0;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        double sign = 1;\r\n        if (rnd.get_random_double() < 0.5)\r\n            sign = -1;\r\n        m(0) = 2*radius*rnd.get_random_double()-radius;\r\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\r\n\r\n        samples.push_back(m);\r\n        labels.push_back(1);\r\n    }\r\n\r\n    // make some samples in a circle around the origin but far away\r\n    radius = 5.0;\r\n    for (long i = 0; i < num; ++i)\r\n    {\r\n        double sign = 1;\r\n        if (rnd.get_random_double() < 0.5)\r\n            sign = -1;\r\n        m(0) = 2*radius*rnd.get_random_double()-radius;\r\n        m(1) = sign*sqrt(radius*radius - m(0)*m(0));\r\n\r\n        samples.push_back(m);\r\n        labels.push_back(2);\r\n    }\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n", "meta": {"hexsha": "a9c222a64a69a181e49dfa2988624169cacb7554", "size": 16100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/empirical_kernel_map_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/empirical_kernel_map_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/empirical_kernel_map_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": 45.2247191011, "max_line_length": 112, "alphanum_fraction": 0.6579503106, "num_tokens": 3505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6510818831964611}}
{"text": "\ufeff#include <CGAL/Delaunay_triangulation_2.h>\r\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\r\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\r\n\r\n#include <boost/chrono.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/pending/disjoint_sets.hpp>\r\n\r\n#include \"GraphDefs.h\"\r\n#include \"Timer.h\"\r\n#include \"GraphUtil.h\"\r\n#include \"GraphParse.h\"\r\n#include \"GraphGen.h\"\r\n\r\n#include <fstream>\r\n#include <string>\r\n\r\n#define SHOW_DEBUG false\r\n\r\nvoid printGraph(const char* title, VertexVector* vertices, EdgeVector* edges, bool printVertices = false) {\r\n\tstd::cout << std::endl << \"=== \" << title << std::endl;\r\n\r\n\tif (printVertices) {\r\n\t\t// Iterate through the vertices and print them out\r\n\t\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\t\tCGALPoint* v = (*vertices)[i];\r\n\t\t\tstd::cout << \"index: \" << i << \" (\" << v->x() << \", \" << v->y() << \")\" << std::endl;\r\n\t\t}\r\n\t}\r\n\r\n\t// Iterate through the edges and print them out\r\n\tstd::cout << std::endl << \"Edges: \" << std::endl;\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* e = (*edges)[i];\r\n\t\tCGALPoint* src = (*vertices)[e->u];\r\n\t\tCGALPoint* tar = (*vertices)[e->v];\r\n\t\t//std::cout << edgeWeightMap->at(e).weight << \" (\" << (*g)[src].pt << \") (\" << (*g)[tar].pt << \")\" << std::endl;\r\n\t\tstd::cout << e->weight << \" (\" << (*src) << \") (\" << (*tar) << \")\" << std::endl;\r\n\t}\r\n\r\n\tstd::cout << std::endl;\r\n}\r\n\r\nvoid printGDFGraph(const char* fileName, VertexVector* vertices, EdgeVector* edges) {\r\n\tstd::ofstream myfile;\r\n\tmyfile.open(fileName, std::ios::out | std::ios::in);\r\n\r\n\tmyfile << \"nodedef> name VARCHAR,label VARCHAR,width DOUBLE,height DOUBLE,x DOUBLE,y DOUBLE,color VARCHAR\" << std::endl;\r\n\r\n\t// Iterate through the vertices and print them out\r\n\tboost::unordered_map<CGALPoint*, VertexIndex> vertexHandles;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tCGALPoint* v = (*vertices)[i];\r\n\t\tmyfile << i << \",,10.0,10.0,\" << (*v).x() << \",\" << (*v).y() << \",'153,153,153'\" << std::endl;\r\n\t\tvertexHandles.emplace(v, i);\r\n\t}\r\n\r\n\tmyfile << \"edgedef> node1,node2,weight DOUBLE,directed BOOLEAN,color VARCHAR\" << std::endl;\r\n\r\n\t// Iterate through the edges and print them out\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* e = (*edges)[i];\r\n\t\tCGALPoint* src = (*vertices)[e->u];\r\n\t\tCGALPoint* tar = (*vertices)[e->v];\r\n\t\tVertexIndex srcInd = vertexHandles[src];\r\n\t\tVertexIndex tarInd = vertexHandles[tar];\r\n\t\t//EdgeWeight weight = sqrt(CGAL::squared_distance(*src, *tar));\r\n\t\tEdgeWeight weight = 1.0;\r\n\t\tmyfile << srcInd << \",\" << tarInd << \",\" << weight << \",false,'128,128,128'\" << std::endl;\r\n\t}\r\n\r\n\tmyfile.close();\r\n}\r\n\r\nCDT* computeCdt(VertexVector* vertices, EdgeVector* edges, boost::unordered_map<TriVertexHandle, VertexIndex>** handlesToIndex) {\r\n\tCDT* cdt = new CDT();\r\n\r\n\t(*handlesToIndex) = new boost::unordered_map<TriVertexHandle, VertexIndex>();\r\n\tboost::unordered_map<VertexIndex, TriVertexHandle> vertexHandles;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tCGALPoint* pt = (*vertices)[i];\r\n\t\tTriVertexHandle vHandle = cdt->insert(*pt);\r\n\t\tvertexHandles.emplace(i, vHandle);\r\n\t\t(*handlesToIndex)->emplace(vHandle, i);\r\n\t}\r\n\r\n\t// Insert constraint edges\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* edge = (*edges)[i];\r\n\t\tVertexIndex u = edge->u;\r\n\t\tVertexIndex v = edge->v;\r\n\t\tTriVertexHandle uH = vertexHandles[u];\r\n\t\tTriVertexHandle vH = vertexHandles[v];\r\n\t\tcdt->insert_constraint(uH, vH);\r\n\t}\r\n\r\n\tassert(cdt->is_valid());\r\n\r\n\treturn cdt;\r\n}\r\n\r\n// Given 3 colinear points, if the 2 furthest points are constrained, how is this delaunay triangulated?\r\n// It seems the outcome is implementation dependent. CGAL will split the constraint into 2 edges.\r\n// Other implementations might allow for overlapping, collinear edges. Either way, the current plan\r\n// is to assume that an input forest, F, with collinear edges will be replaced by smaller constraint edges.\r\nEdgeVector* newConstraintSetFromCdt(CDT* cdt, VertexVector* originalVertices) {\r\n\tEdgeVector* newEdgeVector = new EdgeVector();\r\n\r\n\tboost::unordered_map<CGALPoint, VertexIndex> vertexIndex;\r\n\tfor (int i = 0; i < originalVertices->size(); i++) {\r\n\t\tvertexIndex[*(*originalVertices)[i]] = i;\r\n\t}\r\n\r\n\t// Add edges to graph\r\n\tfor (CDT::Edge_iterator eit = cdt->edges_begin(); eit != cdt->edges_end(); ++eit) {\r\n\t\tCDT::Edge cgal_e = *eit;\r\n\r\n\t\tif (cdt->is_constrained(cgal_e)) {\r\n\t\t\t// Assumes point coord are unique\r\n\t\t\tCGALSegment segement = cdt->segment(cgal_e);\r\n\t\t\tCGALPoint cgal_u = segement.point(0);\r\n\t\t\tCGALPoint cgal_v = segement.point(1);\r\n\t\t\tVertexIndex u = vertexIndex[cgal_u];\r\n\t\t\tVertexIndex v = vertexIndex[cgal_v];\r\n\r\n\t\t\tSimpleEdge* edge = new SimpleEdge(u, v, 0);\r\n\t\t\tnewEdgeVector->push_back(edge);\r\n\t\t}\r\n\t}\r\n\treturn newEdgeVector;\r\n}\r\n\r\nTriVertexHandle OppositeOfEdge(TriVertexHandle ev0, TriVertexHandle ev1, TriFaceHandle f) {\r\n\tTriVertexHandle v0 = f->vertex(0);\r\n\tif (v0 != ev0 && v0 != ev1) {\r\n\t\treturn v0;\r\n\t}\r\n\r\n\tTriVertexHandle v1 = f->vertex(1);\r\n\tif (v1 != ev0 && v1 != ev1) {\r\n\t\treturn v1;\r\n\t}\r\n\r\n\tTriVertexHandle v2 = f->vertex(2);\r\n\tif (v2 != ev0 && v2 != ev1) {\r\n\t\treturn v2;\r\n\t}\r\n\r\n\tassert(false); // Unreachable\r\n\treturn NULL;\r\n}\r\n\r\nbool IsInsideCircle(CGALPoint* p, CGALPoint* q, CGALPoint* t) {\r\n\tif (SHOW_DEBUG) {\r\n\t\tstd::cout << \"(\" << (*p) << \") (\" << (*q) << \") (\" << (*t) << \")\" << std::endl;\r\n\t}\r\n\tCGALCircle c(*p, *q);\r\n\tCGAL::Bounded_side side = c.bounded_side(*t);\r\n\r\n\t// v is outside or on the circumcircle of f\r\n\treturn side == CGAL::Bounded_side::ON_BOUNDED_SIDE\r\n\t\t|| side == CGAL::Bounded_side::ON_BOUNDARY;\r\n}\r\n\r\nvoid computeNonLocallyGabriel(\r\n\tVertexVector* vertices,\r\n\tEdgeVector* edges,\r\n\tEdgeVector** NewEdges,\r\n\tEdgeVector** S_Edges) {\r\n\r\n\tboost::chrono::high_resolution_clock::time_point start;\r\n\tboost::chrono::high_resolution_clock::time_point end;\r\n\tboost::chrono::milliseconds duration(0);\r\n\tboost::chrono::milliseconds total(0);\r\n\r\n\t// Compute CDT(F)\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\tboost::unordered_map<TriVertexHandle, VertexIndex>* handlesToIndex;\r\n\tCDT* cdt = computeCdt(vertices, edges, &handlesToIndex);\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast<boost::chrono::milliseconds>(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"CDT(F)\", duration);\r\n\r\n\t// Replace F with NewF\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\t(*NewEdges) = newConstraintSetFromCdt(cdt, vertices);\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast<boost::chrono::milliseconds>(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"F -> NewF\", duration);\r\n\r\n\t// Compute Non-Locally Gabriel edges\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\tboost::unordered_set<TriEdge>* S = new boost::unordered_set<TriEdge>();\r\n\tTriVertexHandle infiniteVertex = cdt->infinite_vertex();\r\n\tint edgeCount = 0;\r\n\tfor (FiniteEdgeIter iter = cdt->finite_edges_begin(); iter != cdt->finite_edges_end(); ++iter) {\r\n\t\tedgeCount++;\r\n\r\n\t\t// typedef std::pair<Face_handle, int> Edge;\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\r\n\t\t// Edge shared by faces f0 and f1\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriFaceHandle f1 = e.first->neighbor(eIndex);\r\n\r\n\t\t// Vertex opposite of edge e in f0, f1\r\n\t\tTriVertexHandle opp0 = f0->vertex(eIndex);\r\n\r\n\t\t// Vertex of edge e\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tTriVertexHandle opp1 = OppositeOfEdge(e0, e1, f1);\r\n\r\n\t\tif (SHOW_DEBUG) {\r\n\t\t\t// Vertex endpoint v0, v1 of edge e for f0 (doesn't seem to be possible to identify the same edge for f1 in a similar way)\r\n\t\t\tstd::cout << eIndex << std::endl;\r\n\t\t\tstd::cout << \"(\" << *e0 << \") (\" << *e1 << \")\" << std::endl;\r\n\t\t\tstd::cout << \"(\" << *opp0 << \")\" << std::endl;\r\n\t\t}\r\n\r\n\t\tif (e0 != infiniteVertex && e1 != infiniteVertex) {\r\n\t\t\tCGALPoint p = e0->point();\r\n\t\t\tCGALPoint q = e1->point();\r\n\r\n\t\t\tbool addToConstraint = false;\r\n\r\n\t\t\tif (opp0 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp0->point();\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)) {\r\n\t\t\t\t\taddToConstraint = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (opp1 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp1->point();\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)) {\r\n\t\t\t\t\taddToConstraint = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (addToConstraint) {\r\n\t\t\t\tS->emplace(e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t(*S_Edges) = new EdgeVector();\r\n\tfor (boost::unordered_set<TriEdge>::iterator iter = S->begin(); iter != S->end(); ++iter) {\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t(*S_Edges)->push_back(new SimpleEdge(u, v, 0));\r\n\t}\r\n\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast<boost::chrono::milliseconds>(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"computeNonLocallyGabriel duration\", duration);\r\n\r\n\tprintDuration(\"Total\", total);\r\n\r\n\tdelete S;\r\n\tdelete cdt;\r\n\tdelete handlesToIndex;\r\n}\r\n\r\nvoid computeCgg(\r\n\tVertexVector* vertices,\r\n\tEdgeVector* edges,\r\n\tEdgeVector** NewEdges,\r\n\tEdgeVector** gabriel) {\r\n\r\n\tboost::unordered_set<SimpleEdge>* constraintEdgesSet = createSimpleEdgeSet(edges);\r\n\r\n\tboost::unordered_map<TriVertexHandle, VertexIndex>* handlesToIndex;\r\n\tCDT* cdt = computeCdt(vertices, edges, &handlesToIndex);\r\n\t(*NewEdges) = newConstraintSetFromCdt(cdt, vertices);\r\n\r\n\tboost::unordered_set<TriEdge>* S = new boost::unordered_set<TriEdge>();\r\n\r\n\tTriVertexHandle infiniteVertex = cdt->infinite_vertex();\r\n\tint edgeCount = 0;\r\n\r\n\tboost::chrono::high_resolution_clock::time_point startTotal = boost::chrono::high_resolution_clock::now();\r\n\r\n\tfor (FiniteEdgeIter iter = cdt->finite_edges_begin(); iter != cdt->finite_edges_end(); ++iter) {\r\n\t\tedgeCount++;\r\n\r\n\t\t// typedef std::pair<Face_handle, int> Edge;\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\r\n\t\t// Edge shared by faces f0 and f1\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriFaceHandle f1 = e.first->neighbor(eIndex);\r\n\r\n\t\t// Vertex opposite of edge e in f0\r\n\t\tTriVertexHandle opp0 = f0->vertex(eIndex);\r\n\r\n\t\t// Vertex of edge e\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tTriVertexHandle opp1 = OppositeOfEdge(e0, e1, f1);\r\n\r\n\t\tif (SHOW_DEBUG) {\r\n\t\t\t// Vertex endpoint v0, v1 of edge e for f0 (doesn't seem to be possible to identify the same edge for f1 in a similar way)\r\n\t\t\tstd::cout << eIndex << std::endl;\r\n\t\t\tstd::cout << \"(\" << *e0 << \") (\" << *e1 << \")\" << std::endl;\r\n\t\t\tstd::cout << \"(\" << *opp0 << \")\" << std::endl;\r\n\t\t}\r\n\r\n\t\tif (e0 != infiniteVertex && e1 != infiniteVertex) {\r\n\t\t\tCGALPoint p = e0->point();\r\n\t\t\tCGALPoint q = e1->point();\r\n\t\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t\tbool addToS = true;\r\n\r\n\t\t\tif (opp0 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp0->point();\r\n\t\t\t\t// Is not locally gabriel\r\n\t\t\t\t// Is not a constraint edge\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)\r\n\t\t\t\t\t&& (constraintEdgesSet->count(SimpleEdge(u, v, 0)) < 1)) {\r\n\t\t\t\t\taddToS = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (opp1 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp1->point();\r\n\t\t\t\t// Is not locally gabriel\r\n\t\t\t\t// Is not a constraint edge\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)\r\n\t\t\t\t\t&& (constraintEdgesSet->count(SimpleEdge(u, v, 0)) < 1)) {\r\n\t\t\t\t\taddToS = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (addToS) {\r\n\t\t\t\tS->emplace(e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t(*gabriel) = new EdgeVector();\r\n\tfor (boost::unordered_set<TriEdge>::iterator iter = S->begin(); iter != S->end(); ++iter) {\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t(*gabriel)->push_back(new SimpleEdge(u, v, 0));\r\n\t}\r\n\r\n\tboost::chrono::high_resolution_clock::time_point endTotal = boost::chrono::high_resolution_clock::now();\r\n\tboost::chrono::milliseconds total = (boost::chrono::duration_cast<boost::chrono::milliseconds>(endTotal - startTotal));\r\n\tprintDuration(\"computeCgg duration\", total);\r\n\r\n\tdelete S;\r\n\tdelete cdt;\r\n\tdelete handlesToIndex;\r\n\tdelete constraintEdgesSet;\r\n}\r\n\r\nEdgeVector* intersectInputSetWithConstraintSet(EdgeVector* inputSet, EdgeVector* constraintSet) {\r\n\tboost::unordered_set<SimpleEdge>* NewEdges_Hashset = new boost::unordered_set<SimpleEdge>();\r\n\tfor (int i = 0; i < inputSet->size(); i++) {\r\n\t\tSimpleEdge* e = (*inputSet)[i];\r\n\t\tNewEdges_Hashset->emplace((*e));\r\n\t}\r\n\r\n\tEdgeVector* intersect = new EdgeVector();\r\n\tfor (int i = 0; i < constraintSet->size(); i++) {\r\n\t\tSimpleEdge* se = (*constraintSet)[i];\r\n\t\tif (NewEdges_Hashset->count(*se) > 0) {\r\n\t\t\tintersect->push_back(new SimpleEdge(se->u, se->v, se->weight));\r\n\t\t}\r\n\t}\r\n\r\n\treturn intersect;\r\n}\r\n\r\nbool containsEdge(boost::unordered_set<SimpleEdge>* edgeSet, SimpleEdge* edge) {\r\n\tSimpleEdge se(edge->u, edge->v, 0);\r\n\treturn edgeSet->count(se) > 0;\r\n}\r\n\r\n// True if A a subgraph of B\r\nbool isSubgraph(VertexVector* vertices, EdgeVector* a, EdgeVector* b) {\r\n\tboost::unordered_set<SimpleEdge>* bEdgeSet = createSimpleEdgeSet(b);\r\n\r\n\t// Iterate through the edges\r\n\tfor (int i = 0; i < a->size(); i++) {\r\n\t\tSimpleEdge* edge = (*a)[i];\r\n\t\tif (!containsEdge(bEdgeSet, edge)) {\r\n\t\t\tCGALPoint* u = (*vertices)[edge->u];\r\n\t\t\tCGALPoint* v = (*vertices)[edge->v];\r\n\t\t\t//EdgeWeight weight = CGAL::squared_distance(*u, *v);\r\n\t\t\tCGAL::Lazy_exact_nt<CGAL::Gmpq> exactWeight = CGAL::squared_distance(*u, *v);\r\n\t\t\tEdgeWeight weight = CGAL::to_double(exactWeight);\r\n\t\t\tstd::cout << \"b contains edge not in a: \" << weight << \" (\" << *u << \") (\" << *v << \")\" << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nEdgeVector* convertCdtToGraph(VertexVector* vertices, CDT* cdt) {\r\n\tEdgeVector* edgeVec = new EdgeVector();\r\n\t// edgeVec->reserve(cdt->number_of_faces() * 3); // Upper bound on number of edges (typically too much)\r\n\r\n\t// Map CGALPoint -> VertexIndex\r\n\tboost::unordered_map<CGALPoint, VertexIndex> vertexIndex;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tvertexIndex[*(*vertices)[i]] = i;\r\n\t}\r\n\r\n\t// Add edges to graph\r\n\tfor (CDT::Edge_iterator eit = cdt->edges_begin(); eit != cdt->edges_end(); ++eit) {\r\n\t\tCDT::Edge cgal_e = *eit;\r\n\t\tCGALSegment segement = cdt->segment(cgal_e);\r\n\t\tCGALPoint cgal_u = segement.point(0);\r\n\t\tCGALPoint cgal_v = segement.point(1);\r\n\t\tVertexIndex u = vertexIndex[cgal_u];\r\n\t\tVertexIndex v = vertexIndex[cgal_v];\r\n\r\n\t\tSimpleEdge* edge = new SimpleEdge(u, v, 0);\r\n\t\tedgeVec->push_back(edge);\r\n\t}\r\n\r\n\treturn edgeVec;\r\n}\r\n\r\nbool isCdtSubgraph(VertexVector* vertices, EdgeVector* edgesF, EdgeVector* edgesS) {\r\n\tboost::unordered_map<TriVertexHandle, VertexIndex>* handlesToIndex;\r\n\tCDT* cdtS = computeCdt(vertices, edgesS, &handlesToIndex); // CDT of mimimum edge constraint\r\n\tEdgeVector* ev_cdtS = convertCdtToGraph(vertices, cdtS);\r\n\tbool res = isSubgraph(vertices, edgesF, ev_cdtS);\r\n\r\n\tdelete ev_cdtS;\r\n\tdelete cdtS;\r\n\tdelete handlesToIndex;\r\n\r\n\treturn res;\r\n}\r\n\r\nbool isCggSubgraph(VertexVector* vertices, EdgeVector* edgesF, EdgeVector* edgesS) {\r\n\tEdgeVector* newEdgesS;\r\n\tEdgeVector* gabriel_S;\r\n\tcomputeCgg(vertices, edgesS, &newEdgesS, &gabriel_S);\r\n\tbool res = isSubgraph(vertices, edgesF, gabriel_S);\r\n\r\n\tdelete gabriel_S;\r\n\tdelete newEdgesS;\r\n\r\n\treturn res;\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\tconst char* vertFile = (argc > 2) ? argv[1] : NULL;\r\n\tconst char* edgeFile = (argc > 2) ? argv[2] : NULL;\r\n\r\n\tVertexVector* vertices = NULL;\r\n\tEdgeVector* edges = NULL;\r\n\r\n\tif (vertFile == NULL || edgeFile == NULL) {\r\n\t\t// Random graph\r\n\t\t//createRandomCirclePlaneForest(1000, 1000, 100, &vertices, &edges);\r\n\t\t//createRandomMediumLengthPlaneForest(1000, 1000, 100, &vertices, &edges);\r\n\t\tcreateRandomNearTriangulation(1000, 1000, 100, &vertices, &edges);\r\n\t}\r\n\telse {\r\n\t\t// Load graph from file\r\n\t\t// e.g. D:\\g\\data\\HI.nodes D:\\g\\data\\HI.edges\r\n\t\tparseGraph(vertFile, edgeFile, &vertices, &edges);\r\n\t}\r\n\r\n\tif (SHOW_DEBUG) {\r\n\t\tprintGraph(\"Input\", vertices, edges, true);\r\n\t}\r\n\r\n\t// Compute CGG(V, E)\r\n\tEdgeVector* NewEdges;\r\n\tEdgeVector* cggS;\r\n\tcomputeNonLocallyGabriel(vertices, edges, &NewEdges, &cggS);\r\n\tEdgeVector* S = intersectInputSetWithConstraintSet(NewEdges, cggS);\r\n\t//std::cout << \"Edges in E: \" << NewEdges->size() << \" Edges in S: \" << S->size() << \" Ratio: \" << (double)((double)S->size() / (double)NewEdges->size()) << std::endl;\r\n\tstd::cout << S->size() << std::endl;\r\n\tstd::cout << (double)((double)S->size() / (double)NewEdges->size()) << std::endl;\r\n\tstd::cout << std::endl;\r\n\r\n\t//printGDFGraph(\"D:\\\\g\\\\results\\\\graph examples\\\\hi_gg_S.gdf\", vertices, S);\r\n\r\n\t// Other possible validatation\r\n\t// CGG \u2286 CDT\r\n\t// S \u2286 CDT\r\n\r\n\t// S \u2286 E\r\n\tif (!isSubgraph(vertices, S, NewEdges)) {\r\n\t\tstd::cout << \"Error: isSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t// F \u2286 CDT(V, S) (Note: CGG is contained in CDT)\r\n\tif (!isCdtSubgraph(vertices, NewEdges, S)) {\r\n\t\tstd::cout << \"Error: isCdtSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t// F \u2286 CGG(V, S), CGG is computed by running a CDT on S, followed by\r\n\t// a locally gabriel check on all edge from the CDT and eliminating edges\r\n\t// that are non-locally gabriel AND not a constraint edge\r\n\tif (!isCggSubgraph(vertices, NewEdges, S)) {\r\n\t\tstd::cout << \"Error: isCggSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t\t\r\n\tdeleteEdgeVector(S);\r\n\tdeleteEdgeVector(cggS);\r\n\tdeleteEdgeVector(NewEdges);\r\n\r\n\tdeleteEdgeVector(edges);\r\n\tdeleteVerticesVector(vertices);\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "0a3647665e0ec28c979143d2bd5f769aaf83aef9", "size": 17593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gabriel.cpp", "max_stars_repo_name": "eduong/cgal_gabriel", "max_stars_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "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/gabriel.cpp", "max_issues_repo_name": "eduong/cgal_gabriel", "max_issues_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "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/gabriel.cpp", "max_forks_repo_name": "eduong/cgal_gabriel", "max_forks_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "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.5194085028, "max_line_length": 169, "alphanum_fraction": 0.6467913375, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6510818792357697}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[overlaps\n//` Checks if two geometries overlap\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Checks if the two geometries overlaps or not. \n    bg::model::polygon<bg::model::d2::point_xy<double> > poly1;\n    bg::read_wkt(\"POLYGON((0 0,0 4,4 4,4 0,0 0))\", poly1);\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly2;\n    bg::read_wkt(\"POLYGON((2 2,2 6,6 7,6 1,2 2))\", poly2);\n    bool check_overlap = bg::overlaps(poly1, poly2);\n    if (check_overlap) {\n         std::cout << \"Overlaps: Yes\" << std::endl;\n    } else {\n        std::cout << \"Overlaps: No\" << std::endl;\n    }\n\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly3;\n    bg::read_wkt(\"POLYGON((-1 -1,-3 -4,-7 -7,-4 -3,-1 -1))\", poly3);\n    check_overlap = bg::overlaps(poly1, poly3);\n    if (check_overlap) {\n         std::cout << \"Overlaps: Yes\" << std::endl;\n    } else {\n        std::cout << \"Overlaps: No\" << std::endl;\n    }\n\n    return 0;\n}\n\n//]\n\n\n//[overlaps_output\n/*`\nOutput:\n[pre\nOverlaps: Yes\n\n[$img/algorithms/overlaps.png]\n\nOverlaps: No\n]\n*/\n//]\n", "meta": {"hexsha": "497d5e17e3f782978ef95ba9d291115410275ce7", "size": 1561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/overlaps.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/overlaps.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/overlaps.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 25.1774193548, "max_line_length": 79, "alphanum_fraction": 0.6367713004, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.8056321866478979, "lm_q1q2_score": 0.6510049524892103}}
{"text": "\n// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors.\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\n\n/**\n * @author Alexander Silva Barbosa <alexander.ti.ufv@gmail.com>\n * @date 2019\n * Particle Filter (Monte Carlo)\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <random>\n#include <chrono>\n#include <thread>\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate <typename dataType, int states, int inputs, int outputs, int outputSize>\nclass PF\n{\n    private:\n        typedef Matrix<dataType, states, 1> MatNx1;\n        typedef Matrix<dataType, inputs, 1> MatMx1;\n        typedef Matrix<dataType, outputs, 1> MatPx1;\n        typedef Matrix<dataType, states, states> MatNxN;\n\n    public:\n        typedef MatNx1 State;\n        typedef MatMx1 Input;\n        typedef MatPx1 Output;\n        typedef Input Control;\n        typedef Output Sensor;\n        typedef MatPx1 SensorStd;\n        typedef MatNx1 ResampleStd;\n\n        double eps;\n\n    private:\n        typedef void (*ModelFunction)(State &x, Input &u, double dt);\n        typedef void (*SensorFunction)(std::vector<Output> &y, State &x, double dt);\n\n        std::default_random_engine gen;\n        std::normal_distribution<double> distr{0.0, 1.0};\n        std::chrono::time_point<std::chrono::high_resolution_clock> start;\n\n        int N, NMax;\n        std::vector<State> W;\n        std::vector< std::vector<Output> > Y;\n        std::vector<double> w;\n        double wMax;\n\n        State minState, maxState, meanState;\n\n        State x;\n        ResampleStd Q;\n        SensorStd R;\n    \n        MatNxN resampleMatrix;\n        MatNx1 randX;\n\n        ModelFunction modelFn;\n        SensorFunction sensorFn;\n\n        void init()\n        {\n            modelFn = NULL;\n            sensorFn = NULL;\n\n            resampleMatrix = Q.asDiagonal();\n\n            N = NMax;\n            W.resize(N);\n            Y.resize(N);\n            w.resize(N);\n            meanState = (maxState - minState) / 2;\n            initW();\n\n            eps = 1e-10;\n\n            start = std::chrono::high_resolution_clock::now();\n        }\n    public:\n\n        PF(int N, State minState, State maxState) : NMax(N), minState(minState), maxState(maxState)\n        {\n            Q.setIdentity();\n            R.setIdentity();\n            x.setZero();\n            init();\n        }\n\n        PF(int N, State X, State minState, State maxState) : x(X), NMax(N), minState(minState), maxState(maxState)\n        {\n            Q.setIdentity();\n            R.setIdentity();\n            init();\n        }\n\n        PF(int N, State minState, State maxState, ResampleStd Q, SensorStd R) : Q(Q), R(R), NMax(N), minState(minState), maxState(maxState)\n        {\n            x.setZero();\n            init();\n        }\n\n        PF(int N, State X, State minState, State maxState, ResampleStd Q, SensorStd R) : x(X), Q(Q), R(R), NMax(N), minState(minState), maxState(maxState)\n        {\n            init();\n        }\n\n        virtual ~PF()\n        {\n\n        }\n\n        void seed()\n        {\n            unsigned int s = std::chrono::system_clock::now().time_since_epoch().count();\n            seed(s);\n        }\n\n        void seed(unsigned int s)\n        {\n            gen = std::default_random_engine(s);\n            srand (s);\n            std::srand(s);\n            initW();\n        }\n\n        State state()\n        {\n            MatNx1 x;\n            x.setZero();\n            return x;\n        }\n\n        Input input()\n        {\n            MatMx1 u;\n            u.setZero();\n            return u;\n        }\n\n        Output output()\n        {\n            MatPx1 y;\n            y.setZero();\n            return y;\n        }\n\n        SensorStd createR()\n        {\n            SensorStd R;\n            R.setZero();\n            return R;\n        }\n\n        void setR(SensorStd R)\n        {\n            this->R = R;\n        }\n\n        ResampleStd createQ()\n        {\n            ResampleStd Q;\n            Q.setZero();\n            return Q;\n        }\n\n        void setQ(ResampleStd Q)\n        {\n            this->Q = Q;\n            resampleMatrix = Q.asDiagonal();\n        }\n\n        double time()\n        {\n            auto end = std::chrono::high_resolution_clock::now();\n            std::chrono::duration<double> diff = end - start;\n            start = std::chrono::high_resolution_clock::now();\n            return diff.count();\n        }\n\n        double delay(double s)\n        {\n            double ellapsed = time();\n            double remain = s - ellapsed;\n            if(remain < 0)\n                return ellapsed;\n            std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9)));\n            ellapsed += time();\n            return ellapsed;\n        }\n\n        std::vector<State>& particles()\n        {\n            return W;\n        }\n\n        void setModel(ModelFunction fn)\n        {\n            modelFn = fn;\n        }\n\n        void setSensor(SensorFunction fn)\n        {\n            sensorFn = fn;\n        }\n\n        virtual void model(State &x, Input &u, double dt)\n        {\n\n        }\n\n        virtual void sensor(std::vector<Output> &z, State &x, double dt)\n        {\n\n        }\n\n        void simulate(State &x, std::vector<Output> &y, Input &u, double dt)\n        {\n            doModel(x, u, dt);\n\n            y.resize(outputSize);\n            doSensor(y, x, dt);\n        }\n\n        void run(State &xK, std::vector<Output> &y, Input &u, double dt)\n        {\n            y.resize(outputSize);\n\n            applyControl(u, dt);\n            sense(dt);\n            compare(y);\n            resample();\n            measure();\n\n            xK = x;\n        }\n\t\n\tvoid VaryN(float error, int Nmin, int Ni, float error_lim, int Nmax)\n\t{\n\t    int Np=0;\n\t    if(error>error_lim)\n\t    {\n\t    \tfloat l;\n\t    \n            \tl = round(error/error_lim);\n\t    \tint k = (int)l;\n                Np = Nmin + Ni*k;\n            \tif(Np > Nmax)\n\t\t{\n\t\t\tthis->N = Nmax;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->N = Np;\n\t\t}\n            }\n\t    else\n\t    {\n                Np = Nmin;\n\t\tthis->N = Np;\n            }\n\t  cout << this-> N << endl;\n\t}\n\n    private:\n        void initW()\n        {\n            for(int n = 0; n < N; n++)\n            {\n                W[n] = State::Random();\n                for (size_t i = 0; i < states; i++)\n                {\n                    W[n](i) = meanState(i) + W[n](i) * meanState(i);\n                }\n            }\n        }\n\n        void applyControl( Input &u, double dt)\n        {\n            for(int i = 0; i < N; i++)\n            {\n                doModel(W[i], u, dt);\n            }\n        }\n\n        void sense(double dt)\n        {\n            for(int i = 0; i < N; i++)\n            {\n                Y[i].resize(outputSize);\n                doSensor(Y[i], W[i], dt);\n            }\n        }\n\n        void compare(std::vector<Output> &y)\n        {\n            double sum = 0;\n            double lh = 0;\n            for(int i = 0; i < N; i++)\n            {\n                w[i] = 1.0;\n                for(int j = 0; j < outputSize; j++)\n                {\n                    lh = likelihood(y[j], Y[i][j]);\n                    w[i] *= lh;\n                }\n                sum += w[i];\n            }\n\n            wMax = 0;\n            for(int i = 0; i < N; i++)\n            {\n                w[i] /= sum;\n                if(w[i] > wMax)\n                    wMax = w[i];\n            }\n        }\n\n        double likelihood(Output y, Output z)\n        {\n            double lh = 0;\n            double df, sq, ex, pi2, m;\n\n            pi2 = sqrt(2 * 3.14159265358979);\n\n            for (size_t i = 0; i < outputs; i++)\n            {\n                if(R(i) == 0)\n                    continue;\n\n                m = 1.0 / ( R(i) * pi2 );\n\n                df = (z(i) - y(i)) / R(i);\n\n                sq = df*df;\n                ex = exp( -0.5 * sq );\n\n                lh += m * ex;\n            }\n\n            lh += eps;\n        }\n\n        void resample()\n        {\n            int index = rand() % N;\n            double F;\n            std::vector<State> nW(N);\n\n            for(int i = 0; i < N; i++)\n            {\n                F = 10 * wMax * ( ( rand() % 100 ) / 100.0);\n                while(F > w[index])\n                {\n                    F -= w[index];\n                    index = ( index + 1 ) % N;\n                }\n                randn(randX);\n                nW[i] = W[index] + resampleMatrix * randX;\n                for (size_t j = 0; j < outputs; j++)\n                {\n                    if(nW[i](j) < minState(j))\n                        nW[i](j) = maxState(j) - ( minState(j) - nW[i](j) );\n                    else if(nW[i](j) > maxState(j))\n                        nW[i](j) = minState(j) + ( nW[i](j) - maxState(j) );\n                }\n            }\n\n            W = nW;\n        }\n\n        void measure()\n        {\n            x.setZero();\n            for(int i = 0; i < N; i++)\n            {\n                x += W[i];\n            }\n            x /= N;\n        }\n\n        void doModel(State &x, Input &u, double dt)\n        {\n            if(modelFn != NULL)\n                modelFn(x, u, dt);\n            else\n                model(x, u, dt);\n        }\n\n        void doSensor(std::vector<Output> &z, State &x, double dt)\n        {\n            if(sensorFn != NULL)\n                sensorFn(z, x, dt);\n            else\n                sensor(z, x, dt);\n        }\n\n        template<class T>\n        void randn(T &mat)\n        {\n            for (size_t i = 0; i < mat.rows(); i++)\n            {\n                for (size_t j = 0; j < mat.cols(); j++)\n                {\n                    mat(i, j) = distr(gen);\n                }\n            }\n        }\n\n};\n", "meta": {"hexsha": "a3741a3d13e8a2058592972e82d3fa4c6553a2be", "size": 9702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bflib/PF.hpp", "max_stars_repo_name": "olggc/bflib", "max_stars_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T12:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T12:31:03.000Z", "max_issues_repo_path": "bflib/PF.hpp", "max_issues_repo_name": "viniciusreis21/bflib", "max_issues_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bflib/PF.hpp", "max_forks_repo_name": "viniciusreis21/bflib", "max_forks_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_forks_repo_licenses": ["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.2105263158, "max_line_length": 154, "alphanum_fraction": 0.4128014842, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6509621974679498}}
{"text": "// Arguments: Doubles, Doubles, Doubles\n#include <stan/math/prim/scal.hpp>\n#include <boost/utility/enable_if.hpp>\n\nusing stan::math::var;\nusing std::numeric_limits;\nusing std::vector;\n\nclass AgradDistributionsBeta : public AgradDistributionTest {\n public:\n  void valid_values(vector<vector<double> >& parameters,\n                    vector<double>& log_prob) {\n    vector<double> param(3);\n\n    param[0] = 0.4;  // y\n    param[1] = 0.5;  // alpha\n    param[2] = 0.5;  // beta\n    parameters.push_back(param);\n    log_prob.push_back(-0.4311717080293276382896);  // expected log_prob\n\n    param[0] = 0.5;  // y\n    param[1] = 2.0;  // alpha\n    param[2] = 5.0;  // beta\n    parameters.push_back(param);\n    log_prob.push_back(-0.06453852113757105324332);  // expected log_prob\n  }\n\n  void invalid_values(vector<size_t>& index, vector<double>& value) {\n    // y\n    index.push_back(0U);\n    value.push_back(-1.0);\n\n    index.push_back(0U);\n    value.push_back(2.0);\n\n    // alpha\n    index.push_back(1U);\n    value.push_back(0.0);\n\n    index.push_back(1U);\n    value.push_back(-1.0);\n\n    index.push_back(1U);\n    value.push_back(numeric_limits<double>::infinity());\n\n    index.push_back(1U);\n    value.push_back(-numeric_limits<double>::infinity());\n\n    // beta\n    index.push_back(2U);\n    value.push_back(0.0);\n\n    index.push_back(2U);\n    value.push_back(-1.0);\n\n    index.push_back(2U);\n    value.push_back(numeric_limits<double>::infinity());\n\n    index.push_back(2U);\n    value.push_back(-numeric_limits<double>::infinity());\n  }\n\n  template <typename T_y, typename T_scale1, typename T_scale2, typename T3,\n            typename T4, typename T5>\n  typename stan::return_type<T_y, T_scale1, T_scale2>::type log_prob(\n      const T_y& y, const T_scale1& alpha, const T_scale2& beta, const T3&,\n      const T4&, const T5&) {\n    return stan::math::beta_log(y, alpha, beta);\n  }\n\n  template <bool propto, typename T_y, typename T_scale1, typename T_scale2,\n            typename T3, typename T4, typename T5>\n  typename stan::return_type<T_y, T_scale1, T_scale2>::type log_prob(\n      const T_y& y, const T_scale1& alpha, const T_scale2& beta, const T3&,\n      const T4&, const T5&) {\n    return stan::math::beta_log<propto>(y, alpha, beta);\n  }\n\n  template <typename T_y, typename T_scale1, typename T_scale2, typename T3,\n            typename T4, typename T5>\n  typename stan::return_type<T_y, T_scale1, T_scale2, T3, T4, T5>::type\n  log_prob_function(const T_y& y, const T_scale1& alpha, const T_scale2& beta,\n                    const T3&, const T4&, const T5&) {\n    using stan::math::log1m;\n    using std::log;\n\n    return (alpha - 1.0) * log(y) + (beta - 1.0) * log1m(y)\n           + lgamma(alpha + beta) - lgamma(alpha) - lgamma(beta);\n  }\n};\n", "meta": {"hexsha": "edb124717b6afee52c225d5d91dc6debe0f9df0d", "size": 2752, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/prob/beta/beta_test.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/prob/beta/beta_test.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/prob/beta/beta_test.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2417582418, "max_line_length": 78, "alphanum_fraction": 0.648619186, "num_tokens": 825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6509551228072652}}
{"text": "#include <iostream>\n#include <Eigen/Lgsm>\n\n\nint main(int argc, char* argv [])\n{\n  Eigen::Vector3d pos(1, 0, 0);\n  Eigen::Displacementd H_1_0 = Eigen::Displacementd(pos);\n  Eigen::Displacementd H_2_1 = Eigen::Displacementd(pos);\n\n  Eigen::Vector3d axis(0, 0, 1);\n\n  Eigen::Twistd tw(Eigen::AngularVelocityd(axis), pos.cross(axis));\n\n  tw *=  1 * M_PI / 2.0;\n\n  // See Murray Lie Sastry page 50. \n  Eigen::Displacementd H_2_0 = tw.exp()  * H_1_0 * H_2_1;\n  //std::cout << \"twist : \" << tw.transpose() << std::endl;\n  std::cout << \"H_1_0 : \" << H_1_0 << std::endl;\n  std::cout << \"eTw \" << tw.exp() << std::endl;\n  //std::cout << \"H_2_1 : \" << H_2_1 << std::endl;\n  //std::cout << \"Brockett factor : \" << tw.exp()  * H_1_0 << std::endl;\n  std::cout << \"H_2_0 \" << H_2_0 << std::endl;\n  //std::cout <<  tw.exp()  * H_1_0 * H_2_1 << std::endl;\n  std::cout <<  tw.exp()  * H_1_0 << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "42aa061c11e2f7c437bfaec71816ad93eca3e09e", "size": 904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extra/testTwist.cpp", "max_stars_repo_name": "kayhman/lisphys", "max_stars_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-11T13:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T15:36:05.000Z", "max_issues_repo_path": "extra/testTwist.cpp", "max_issues_repo_name": "kayhman/lisphys", "max_issues_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-13T13:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-23T12:57:34.000Z", "max_forks_repo_path": "extra/testTwist.cpp", "max_forks_repo_name": "kayhman/lisphys", "max_forks_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T02:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T02:29:02.000Z", "avg_line_length": 30.1333333333, "max_line_length": 72, "alphanum_fraction": 0.578539823, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6509551193118266}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#include <iostream>\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE distributions test\n#include <boost/test/unit_test.hpp>\n\n#include <dpMM/sphere.hpp>\n#include <dpMM/clTGMMDataGpu.hpp>\n#include <dpMM/karcherMean.hpp>\n#include <dpMM/normalSphere.hpp>\n#include <dpMM/timer.hpp>\n\nusing std::cout;\nusing std::endl;\n\nBOOST_AUTO_TEST_CASE( sphere_test)\n{\n  cout<<\"----------------------- sphere ----------------------\"<<endl;\n  \n  boost::mt19937 rndGen(1);\n  Sphere<double> Sd(3);\n  \n  cout<<\"sampled point: \"<<Sd.sampleUnif(&rndGen).transpose()<<endl;\n\n  VectorXd a(3);\n  VectorXd b(3);\n  a << 0.0,0.0,1.0;\n  b << 0.0,0.0,1.0;\n  MatrixXd bRa = rotationFromAtoB<double>(a,b);\n  MatrixXd aRb = rotationFromAtoB<double>(b,a);\n  BOOST_CHECK((bRa.array() == aRb.transpose().array()).all());\n  BOOST_CHECK((bRa.array() == MatrixXd::Identity(3,3).array()).all());\n  \n  a << 0.0,0.0,1.0;\n  b << 0.0,1.0,0.0;\n  bRa = rotationFromAtoB<double>(a,b);\n  aRb = rotationFromAtoB<double>(b,a);\n  MatrixXd bRaSoll(3,3);\n  bRaSoll << 1.0,0.0,0.0,\n           0.0,0.0,1.0,\n           0.0,-1.0,0.0;\n  BOOST_CHECK((bRa.array() == aRb.transpose().array()).all());\n//  cout<<bRa<<endl;\n//  cout<<bRaSoll<<endl;\n  BOOST_CHECK(((bRa - bRaSoll).array() < 1e-6).all());\n\n  \n  VectorXd p = Sd.sampleUnif(&rndGen);\n  VectorXd q = Sd.sampleUnif(&rndGen);\n  cout<< \"q             : \" << q.transpose()<< endl;\n  cout<< \"q in TpS north: \" << Sd.Log_p_north(p,q).transpose()<< endl;\n  cout<< \"q (Log->Exp)  : \" << Sd.Exp_p(p,Sd.Log_p(p,q)).transpose()<< endl;\n\n  Sphere<double> Sd10(10);\n  p = Sd10.sampleUnif(&rndGen);\n  q = Sd10.sampleUnif(&rndGen);\n  cout<< \"x in TpS: \" << Sd10.Log_p_north(p,q).transpose()<< endl;\n  \n  uint32_t D = 3;\n  uint32_t K = 5;\n  uint32_t N = 20;\n  boost::shared_ptr<Matrix<double,Dynamic,Dynamic> > sq(\n      new Matrix<double,Dynamic,Dynamic>(D,N));\n  Matrix<double,Dynamic,Dynamic> xMu(D,N);\n  Matrix<double,Dynamic,Dynamic> x(D-1,N);\n  Matrix<double,Dynamic,Dynamic> p0s(D,K);\n  for (uint32_t k=0; k<K; ++k)\n     p0s.col(k) =  Sd.sampleUnif(&rndGen);\n  VectorXu z(N);\n  Matrix<double,Dynamic,Dynamic> mus = sampleClustersOnSphere<double>(*sq, z, K);\n\n  Matrix<double,Dynamic,Dynamic> muEst = karcherMeanMultiple(\n      p0s, *sq, xMu, z, K, 100); \n\n  cout<<\"muTrue=\"<<endl<<mus<<endl;\n  cout<<\"muEst =\"<<endl<<muEst<<endl;\n  cout<<\"muInit =\"<<endl<<p0s<<endl;\n\n  Sphere<double> S(D);\n  S.rotate_p2north(muEst,xMu, x, z, K);\n  \n  for(uint32_t i=0; i<N; ++i)\n    BOOST_CHECK(\n        (x.col(i) - S.Log_p_north(muEst.col(z(i)),sq->col(i))).norm() < 1e-6);\n  \n  p = VectorXd(3);\n  q = VectorXd(3);\n  p << 1,0,0;\n  q <<-1,0,0;\n  VectorXd qp = S.Log_p_single(p,q) ;\n  cout<<\"mapping \"<<q.transpose()<<\" to TpS at\"<<p.transpose()\n    <<endl<< qp.transpose() <<endl;\n  cout<<\"Exp ing it back down: \"<<S.Exp_p_single(p,qp).transpose()<<endl;\n \n}\n\ntypedef float myFlt;\n\nBOOST_AUTO_TEST_CASE( sphereGpu_test)\n{\n  cout<<\"----------------------- sphere Gpu ----------------------\"<<endl;\n  uint32_t D = 3;\n  uint32_t K = 6;\n  uint32_t N = 20;\n  boost::mt19937 rndGen(1112);\n  Sphere<myFlt> Sd(D);\n  \n  spVectorXu sz(new VectorXu(N));\n  sz->topRows(N/2) = VectorXu::Zero(N/2);\n  sz->bottomRows(N/2) = VectorXu::Ones(N/2);\n  boost::shared_ptr<Matrix<myFlt,Dynamic,Dynamic> > sq(\n      new Matrix<myFlt,Dynamic,Dynamic>(D,N));\n\n  Matrix<myFlt,Dynamic,Dynamic> mus = sampleClustersOnSphere<myFlt>(*sq, 2);\n//  for (uint32_t i=0; i<N; ++i) \n//  {\n//    sq->col(i) = Sd.sampleUnif(&rndGen);\n//    if(i<N/2)\n//      (*sz)(i) = 0;\n//    else\n//      (*sz)(i) = 1;\n//  }\n  Matrix<myFlt,Dynamic,Dynamic> ps(D,K);\n  for (uint32_t k=0; k<K; ++k)\n     ps.col(k) =  Sd.sampleUnif(&rndGen);\n//  ps.leftCols<2>() << 0.0,0.0,\n//        1.0,-1.0,\n//        0.0,0.0;\n  Matrix<myFlt,Dynamic,1> w(N/2);\n  w.setOnes(N/2);\n  cout<<\" karcher means on CPU\"<<endl;\n  cout<< karcherMeanWeighted<myFlt>(ps.col(0), sq->leftCols(N/2), w, 20) <<endl;\n  cout<< karcherMeanWeighted<myFlt>(ps.col(1), sq->rightCols(N/2), w, 20) <<endl;\n  \n//  assert(false);\n\n  ClTGMMDataGpu<myFlt> sphere(sq,sz,K);\n  //sphere.updateClusters(ps,z);\n  Matrix<myFlt,Dynamic,Dynamic> karcherMeans = sphere.karcherMeans(ps);\n  cout<< karcherMeans <<endl;\n  cout<< \"true centers\"<<endl << mus <<endl;\n  BOOST_CHECK(((karcherMeans.leftCols(2) - mus).array().abs() < 1e-2).all());\n  \n  Timer t;\n  Matrix<myFlt,Dynamic,Dynamic> x = sphere.Log_p_north(ps);\n  t.toctic(\"Log_p_north GPU\");\n  BOOST_CHECK(x.rows() == static_cast<myFlt>(D-1));\n  BOOST_CHECK(x.cols() == static_cast<myFlt>(N));\n\n  for(uint32_t i=0; i<N; ++i)\n  {\n    BOOST_CHECK(x.col(i).norm() < 3.141592653589793);\n    BOOST_CHECK(fabs(x.col(i).norm()\n          -acosf(ps.col((*sz)(i)).transpose()*sq->col(i)) ) < 1e-4); \n    myFlt err = fabs(x.col(i).norm() \n        -acosf(ps.col((*sz)(i)).transpose()*sq->col(i)));\n    if(err >= 1e-4)\n      cout<< err<<endl;\n  }\n\n  //cout<<x.transpose()<<endl;\n\n  Matrix<myFlt,Dynamic,Dynamic> xx(D-1,N);\n  t.tic();\n  xx.leftCols(N/2)  = Sd.Log_p_north(ps.col(0),sq->leftCols(N/2));\n  xx.rightCols(N/2) = Sd.Log_p_north(ps.col(1),sq->rightCols(N/2));\n  t.toctic(\"Log_p_north CPU\");\n  \n  //cout<< xx.transpose()<<endl;\n  BOOST_CHECK( ((x-xx).array().abs() < 1.0e-4).all());\n\n  cout<<\"sufficient statistics test --------------------\"<<endl;\n  sphere.relinearize(karcherMeans);\n  sphere.computeSufficientStatistics();\n  for (uint32_t k=0; k<K; ++k)\n    cout<<\"S_\"<<k<<endl<<sphere.S(k)<<endl;\n\n  cout<<\"pdf test --------------------------------------\"<<endl;\n \n  Matrix<myFlt,Dynamic,1> pi(K);\n  pi.setOnes(); pi /= K;\n  SamplerGpu<myFlt> sampler(N,K,&rndGen);\n  vector<Matrix<myFlt,Dynamic,Dynamic> > Sigmas(K);\n  for (uint32_t k=0; k<K; ++k)\n    if(sphere.counts()(k) > 0)\n      Sigmas[k] = sphere.S(k)/sphere.counts()(k);\n    else\n      Sigmas[k] = Matrix<myFlt,Dynamic,Dynamic>::Identity(D-1,D-1)*0.01;\n  Matrix<myFlt,Dynamic,1> logNormalizers(K);\n  for(uint32_t k=0; k<K; ++k)\n  {\n    NormalSphere<myFlt> normS(karcherMeans.col(k),Sigmas[k],&rndGen); \n    logNormalizers(k) = -0.5*normS.logDetSigma();\n  }\n\n  sphere.sampleGMMpdf(pi, Sigmas , logNormalizers, &sampler);\n  Matrix<myFlt,Dynamic,Dynamic> pdfs = sphere.pdfs();\n\n  for(uint32_t i=0; i<N; ++i)\n  {\n    Matrix<myFlt,Dynamic,1> logPdf(K);\n    for(uint32_t k=0; k<K; ++k)\n    {\n      NormalSphere<myFlt> normS(karcherMeans.col(k),Sigmas[k],&rndGen);\n      logPdf(k) = 0.5*(LOG_2PI*D+normS.logDetSigma()) + normS.logPdf(sq->col(i));; \n      //log(pi(k)) + normS.logPdf(sq->col(i));\n//      logPdf(k) = normS.normal_.; //log(pi(k)) + normS.logPdf(sq->col(i));\n    }\n    Matrix<myFlt,Dynamic,1> A = logPdf;\n    myFlt maxLog = logPdf.maxCoeff();\n    logPdf = logPdf.array() - log((logPdf.array() - maxLog).exp().matrix().sum())\n      - maxLog;\n//    cout<<pdfs(i,0)<<\" vs \"<< exp(logPdf(0))<<endl;\n    cout<<\"--------------------------------\"<<endl;\n    cout<<pdfs.row(i)<<endl;\n//    cout<<logPdf.array().exp().matrix().transpose()<<endl;\n//    cout<<\"-\"<<endl;\n//    cout<<(pdfs.row(i)-logPdf.array().exp().matrix().transpose())<<endl;\n//    cout<<\"log\"<<endl;\n//    cout<<logPdf.transpose()<<endl;\n\n//    cout<<pi.array().log().matrix().transpose()<<endl; // DONE: same!\n    cout<<(A.array()).matrix().transpose()<<endl;\n  }\n};\n\n", "meta": {"hexsha": "b7abd9aa1482acf858f5aadd17bc0d997f6808c9", "size": 7381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sphere.cpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "test/sphere.cpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "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/sphere.cpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 32.0913043478, "max_line_length": 83, "alphanum_fraction": 0.5921961794, "num_tokens": 2622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6508923941636218}}
{"text": "/**\n * @file IPCA.hpp\n * @brief Following the paper, \n * Juyang Weng, Yilu Zhang and Wey-Shiuan Hwang, \"Candid Covariance-free Incremental Principal Component Analysis\", TPAMI \n * @author Haoxiang Li\n * @version 1.1\n * @date 2015-01-11\n */\n#include <Eigen/Eigen>\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixXf;\n\n/**\n * @brief Candid convariance-free IPCA\n */\nclass CCIPCA {\npublic:\n\n    /**\n     * @brief Initialize CCIPCA\n     *\n     * @param dim_subspace number of eigen-vectors expected\n     * @param dim_data dimensionality of the data points (K)\n     * @param p_mean pre-computed data mean vector (D)\n     * @param p_init_pca pre-computed eigen-vectors (D -by- K)\n     * @param num_data_points number of data points used in pre-computation\n     */\n    CCIPCA(int dim_subspace, int dim_data, const float *p_mean, const float *p_init_pca, int num_data_points);\n\n    /**\n     * @brief Update the eigen-vectors given\n     */\n    void update(const float *pp);\n\n    /**\n     * @brief Obtain sorted (descending) eigen vectors && values\n     */\n    void sorted_eigen(RowMatrixXf& eigenvectors, Eigen::RowVectorXf& eigenvalues, int k) const; \n\nprivate:\n    int m_num_data_points;\n    RowMatrixXf m_eigenvecs;    \n    Eigen::RowVectorXf m_eigenvecs_norms;\n    Eigen::RowVectorXf m_mean; \n};\n", "meta": {"hexsha": "565ab5067cce335182b2df97ca440e876eedeb9d", "size": 1330, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IPCA.hpp", "max_stars_repo_name": "pppoe/IPCA", "max_stars_repo_head_hexsha": "1538cbc8ff89fd3d524a41de93268dcdc9469807", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-07-20T10:00:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T11:57:39.000Z", "max_issues_repo_path": "IPCA.hpp", "max_issues_repo_name": "pppoe/IPCA", "max_issues_repo_head_hexsha": "1538cbc8ff89fd3d524a41de93268dcdc9469807", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPCA.hpp", "max_forks_repo_name": "pppoe/IPCA", "max_forks_repo_head_hexsha": "1538cbc8ff89fd3d524a41de93268dcdc9469807", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T14:54:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-16T07:26:25.000Z", "avg_line_length": 28.9130434783, "max_line_length": 122, "alphanum_fraction": 0.6857142857, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6508923917154184}}
{"text": "#include <fastad>\n#include <benchmark/benchmark.h>\n\n#ifdef USE_ADEPT\n#include <adept_arrays.h>\n#endif\n\n// Finite-difference\n\nstatic inline double f_test1(const std::vector<double>& x)\n{\n    double sum = 0.;\n    for (size_t i = 0; i < x.size(); ++i) {\n        sum += x[i];\n    }\n\n    double w0 = x[0] * x[1] - x[2] * sin(x[0]);\n    double w1 = x[1] * w0 - cos(w0) + sum;\n    return w1 + exp(w1 - w0);\n}\n\nstatic void BM_test1_fd(benchmark::State& state)\n{\n    constexpr double h = 1e-10;\n    for (auto _ : state) {\n        std::vector<double> x(100);\n        for (size_t i = 0; i < x.size(); ++i) {\n            x[i] = i / 100.;\n        }\n        double f = f_test1(x);\n        for (size_t i = 0; i < x.size(); ++i) {\n            x[i] += h;\n            double f_h = f_test1(x);\n            double dfdx_i = (f_h - f) / h;\n            benchmark::DoNotOptimize(dfdx_i);\n            x[i] -= h;\n        }\n    }\n}\n\nBENCHMARK(BM_test1_fd);\n\n// FastAD\nstatic void BM_test1_fastad(benchmark::State& state)\n{\n    using namespace ad;\n    std::vector<Var<double>> x;\n    for (size_t i = 0; i < 100; ++i) {\n        x.emplace_back(i / 100.);\n    }\n    std::vector<Var<double>> w(3);\n    auto expr = ad::bind(\n                (w[0] = x[0] * x[1] - x[2] * sin(x[0]),\n                 w[1] = x[1] * w[0] - cos(w[0]) + \n                        ad::sum(x.begin(), x.end(), [](const auto& xi) {return xi;}),\n                 w[2] = w[1] + ad::exp(w[1] - w[0])) \n    );\n\n    for (auto _ : state) {\n        autodiff(expr);\n        benchmark::DoNotOptimize(expr);\n    }\n}\n\nBENCHMARK(BM_test1_fastad);\n\n#ifdef USE_ADEPT\n\n// Adept\nstatic void BM_test1_adept(benchmark::State& state)\n{\n    using namespace adept;\n    for (auto _ : state) {\n        Stack stack;\n        aVector x(100);\n        for (size_t i = 0; i < 100; ++i) {\n            x << i / 100.;\n        }\n        stack.new_recording();\n        aReal w_0 = x[0] * x[1] - x[2] * sin(x[0]);\n        aReal w_1 = x[1] * w_0 - cos(w_0) + sum(x);\n        aReal J = w_1 + exp(w_1 - w_0);\n        J.set_gradient(1.);\n        stack.reverse();\n        benchmark::ClobberMemory();\n    }\n}\n\nBENCHMARK(BM_test1_adept);\n\n#endif\n", "meta": {"hexsha": "162987f02689f44d17c0b2aac54e16b16ddde867", "size": 2144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/ad_benchmark.cpp", "max_stars_repo_name": "kilasuelika/FastAD", "max_stars_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-11-28T22:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T03:55:19.000Z", "max_issues_repo_path": "benchmark/ad_benchmark.cpp", "max_issues_repo_name": "kilasuelika/FastAD", "max_issues_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-28T20:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-30T00:14:39.000Z", "max_forks_repo_path": "benchmark/ad_benchmark.cpp", "max_forks_repo_name": "kilasuelika/FastAD", "max_forks_repo_head_hexsha": "dd070c608c18f5391f2ac68dca4f9db223a33eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-26T11:14:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T06:40:18.000Z", "avg_line_length": 23.3043478261, "max_line_length": 85, "alphanum_fraction": 0.4906716418, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6508923867629803}}
{"text": "\n#include <iostream>\n#include <chrono>\n#include <sstream>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n#include \"KinectFrame.h\"\n#include \"KinectSpecs.h\"\n#include \"ICP.h\"\n\ntypedef double Decimal;\n\n\n\n\n\nvoid compute_vertices(std::vector<Eigen::Matrix<Decimal, 4, 1>>& vertices, const KinectFrame& frame, Decimal fovy, Decimal aspect_ratio, Decimal near_plane, Decimal far_plane)\n{\n\tEigen::Matrix<Decimal, 3, 1> vert_uv, vert_u1v, vert_uv1;\n\n\tfor (int x = 0; x < frame.depth_width() - 1; ++x)\n\t{\n\t\tfor (int y = 0; y < frame.depth_height() - 1; ++y)\n\t\t{\n\t\t\tconst Decimal depth = frame.depth[y * frame.depth_width() + x];\n\n\t\t\tif (depth > 0.01)\n\t\t\t{\n\t\t\t\tvert_uv = window_coord_to_3d(Eigen::Matrix<Decimal, 2, 1>(x, y), depth, fovy, aspect_ratio, near_plane, far_plane, frame.depth_width(), frame.depth_height());\n\n\t\t\t\tint i = y * frame.depth_width() + x;\n\n#if 1\n\t\t\t\tvertices[i] = vert_uv.homogeneous();\n#else\n\n\t\t\t\tif (!vert_uv.isZero(0.0001))\n\t\t\t\t{\n\t\t\t\t\tvertices.push_back(vert_uv.homogeneous());\n\t\t\t\t}\n#endif\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n\n\n// Usage: ./Icp.exe ../../data/frame_0.knt ../../data/frame_1.knt 0 10 3\nint main(int argc, char **argv)\n{\n\n\tif (argc < 3)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"Missing parameters. Abort.\"\n\t\t\t<< std::endl\n\t\t\t<< \"Usage: ./Icp.exe <knt_frame> <knt_frame> <filter_width> <max_distance_threshold> \"\n\t\t\t<< \"Usage: ./Icp.exe ../../data/frame_1.knt ../../data/frame_1.knt 10 3\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\n\tTimer timer;\n\tconst std::string input_filename[] = { argv[1], argv[2] };\n\n\tconst int filter_width = (argc > 2) ? atoi(argv[3]) : 10;\n\tconst Decimal max_distance = (Decimal)((argc > 3) ? atof(argv[4]) : 100);\n\n\ttry\n\t{\n\t\ttimer.start();\n\t\tKinectFrame frame[2] =\n\t\t{\n\t\t\tKinectFrame(input_filename[0]),\n\t\t\tKinectFrame(input_filename[1])\n\t\t};\n\t\ttimer.print_interval(\"Importing frames          : \");\n\t\t\n\n\t\tif (frame[0].depth_width() != frame[1].depth_width() ||\n\t\t\tframe[0].depth_height() != frame[1].depth_height())\n\t\t{\n\t\t\tstd::cout\n\t\t\t\t<< \"Frame size doens not match: \" << std::endl\n\t\t\t\t<< frame[0].depth_width() << \", \" << frame[0].depth_height() << std::endl\n\t\t\t\t<< frame[1].depth_width() << \", \" << frame[1].depth_height() << std::endl\n\t\t\t\t<< std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tconst uint16_t width = frame[0].depth_width();\n\t\tconst uint16_t height = frame[0].depth_height();\n\t\tconst uint32_t pixel_count = width * height;\n\n\t\tDecimal fovy = KINECT_V2_FOVY;\n\t\tDecimal aspect_ratio = KINECT_V2_DEPTH_ASPECT_RATIO;\n\t\tDecimal near_plane = KINECT_V2_DEPTH_MIN;\n\t\tDecimal far_plane = KINECT_V2_DEPTH_MAX;\n\n\t\tif (width != 512)\t// it is not kinect version 2. It is version 1\n\t\t{\n\t\t\tfovy = KINECT_V1_FOVY;\n\t\t\taspect_ratio = KINECT_V1_ASPECT_RATIO;\n\t\t\tnear_plane = KINECT_V1_DEPTH_MIN;\n\t\t\tfar_plane = KINECT_V1_DEPTH_MAX;\n\t\t}\n\n\n\t\tstd::vector<Eigen::Matrix<Decimal, 4, 1>> vertices[2] = \n\t\t{\n\t\t\tstd::vector<Eigen::Matrix<Decimal, 4, 1>>(pixel_count, Eigen::Matrix<Decimal, 4, 1>(0, 0, 0, 0)), \n\t\t\tstd::vector<Eigen::Matrix<Decimal, 4, 1>>(pixel_count, Eigen::Matrix<Decimal, 4, 1>(0, 0, 0, 0))\n\t\t};\n\n\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\ttimer.start();\n\t\t\tcompute_vertices(vertices[i], frame[i], fovy, aspect_ratio, near_plane, far_plane);\n\t\t\ttimer.print_interval(\"Depth map back projection : \");\n\t\t}\n\n\t\n\n\t\tICP<Decimal> icp;\n\t\ticp.setInputCloud(vertices[0]);\n\t\ticp.setTargetCloud(vertices[1]);\n\n\n\t\tEigen::Matrix<Decimal, 4, 4> identity = Eigen::Matrix<Decimal, 4, 4>::Identity();\n\t\tEigen::Matrix<Decimal, 4, 4> rigidTransform = Eigen::Matrix<Decimal, 4, 4>::Identity();\n\t\tEigen::Matrix<Decimal, 3, 3> R;\n\t\tEigen::Matrix<Decimal, 3, 1> t;\n\t\n\t\tfor (int i = 0; i < 1; i++)\n\t\t{\n\n\t\t\ttimer.start();\n\t\t\tbool icp_success = icp.align_iteration(vertices[0], vertices[1], \n\t\t\t\tfilter_width, max_distance, width, height, \n\t\t\t\tR, t);\n\t\t\t\n\t\t\ttimer.print_interval(\"Computing icp             : \");\n\n\t\t\tif (icp_success)\n\t\t\t{\n\t\t\t\tstd::cout << \"Icp Success\" << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"Icp Failed\" << std::endl;\n\t\t\t}\n\n\t\t\tstd::cout \n\t\t\t\t<< std::fixed << std::endl\n\t\t\t\t<< R << std::endl << std::endl\n\t\t\t\t<< t.transpose() << std::endl << std::endl;\n\t\t}\n\n\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tstd::cerr << \"Error: \" << ex.what() << std::endl;\n\t}\n\n\n\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "32a661dc2f339898aa5f92553a593e477447b43f", "size": 4256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Icp_cpu.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/Icp_cpu.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "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/Icp_cpu.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 23.6444444444, "max_line_length": 175, "alphanum_fraction": 0.6278195489, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.650857230550537}}
{"text": "/* boost random/generate_canonical.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * See http://www.boost.org for most recent version including documentation.\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#ifndef BOOST_RANDOM_GENERATE_CANONICAL_HPP\r\n#define BOOST_RANDOM_GENERATE_CANONICAL_HPP\r\n\r\n#include <algorithm>\r\n#include <boost/assert.hpp>\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/type_traits/is_integral.hpp>\r\n#include <boost/mpl/bool.hpp>\r\n#include <boost/random/detail/signed_unsigned_tools.hpp>\r\n#include <boost/random/detail/generator_bits.hpp>\r\n\r\nnamespace boost {\r\nnamespace random {\r\n\r\nnamespace detail {\r\n\r\ntemplate<class RealType, std::size_t bits, class URNG>\r\nRealType generate_canonical_impl(URNG& g, boost::mpl::true_ /*is_integral*/)\r\n{\r\n    using std::pow;\r\n    typedef typename URNG::result_type base_result;\r\n    std::size_t digits = std::numeric_limits<RealType>::digits;\r\n    RealType R = RealType((g.max)()) - RealType((g.min)()) + 1;\r\n    RealType mult = R;\r\n    RealType limit =\r\n        pow(RealType(2),\r\n            RealType((std::min)(static_cast<std::size_t>(bits), digits)));\r\n    RealType S = RealType(detail::subtract<base_result>()(g(), (g.min)()));\r\n    while(mult < limit) {\r\n        RealType inc = RealType(detail::subtract<base_result>()(g(), (g.min)()));\r\n        S += inc * mult;\r\n        mult *= R;\r\n    }\r\n    return S / mult;\r\n}\r\n\r\ntemplate<class RealType, std::size_t bits, class URNG>\r\nRealType generate_canonical_impl(URNG& g, boost::mpl::false_ /*is_integral*/)\r\n{\r\n    using std::pow;\r\n    using std::floor;\r\n    BOOST_ASSERT((g.min)() == 0);\r\n    BOOST_ASSERT((g.max)() == 1);\r\n    std::size_t digits = std::numeric_limits<RealType>::digits;\r\n    std::size_t engine_bits = detail::generator_bits<URNG>::value();\r\n    std::size_t b = (std::min)(bits, digits);\r\n    RealType R = pow(RealType(2), RealType(engine_bits));\r\n    RealType mult = R;\r\n    RealType limit = pow(RealType(2), RealType(b));\r\n    RealType S = RealType(g() - (g.min)());\r\n    while(mult < limit) {\r\n        RealType inc(floor((RealType(g()) - RealType((g.min)())) * R));\r\n        S += inc * mult;\r\n        mult *= R;\r\n    }\r\n    return S / mult;\r\n}\r\n\r\n}\r\n\r\n/**\r\n * Returns a value uniformly distributed in the range [0, 1)\r\n * with at least @c bits random bits.\r\n */\r\ntemplate<class RealType, std::size_t bits, class URNG>\r\nRealType generate_canonical(URNG& g)\r\n{\r\n    RealType result = detail::generate_canonical_impl<RealType, bits>(\r\n        g, boost::is_integral<typename URNG::result_type>());\r\n    BOOST_ASSERT(result >= 0);\r\n    BOOST_ASSERT(result <= 1);\r\n    if(result == 1) {\r\n        result -= std::numeric_limits<RealType>::epsilon() / 2;\r\n        BOOST_ASSERT(result != 1);\r\n    }\r\n    return result;\r\n}\r\n\r\n} // namespace random\r\n} // namespace boost\r\n\r\n#endif // BOOST_RANDOM_GENERATE_CANONICAL_HPP\r\n", "meta": {"hexsha": "04af75549acac0c039952986af63c4dadafeeb26", "size": 3034, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/generate_canonical.hpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-08T02:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T02:16:44.000Z", "max_issues_repo_path": "include/boost/random/generate_canonical.hpp", "max_issues_repo_name": "Acidburn0zzz/PopcornTorrent-1", "max_issues_repo_head_hexsha": "c12a30ef9e971059dae5f7ce24a8c37fef83c0c4", "max_issues_repo_licenses": ["MIT"], "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/random/generate_canonical.hpp", "max_forks_repo_name": "Acidburn0zzz/PopcornTorrent-1", "max_forks_repo_head_hexsha": "c12a30ef9e971059dae5f7ce24a8c37fef83c0c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-09T17:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-09T17:04:14.000Z", "avg_line_length": 31.2783505155, "max_line_length": 82, "alphanum_fraction": 0.6453526697, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6508572210779265}}
{"text": "#include <string>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <CGAL/Aff_transformation_3.h>\r\n#include <CGAL/Cartesian.h>\r\n#include <CGAL/IO/STL_reader.h>\r\n#include <CGAL/Surface_mesh.h>\r\n#include <CGAL/Polygon_mesh_processing/intersection.h>\r\n#include <CGAL/Polygon_mesh_processing/transform.h>\r\n#include <ctime>\r\n#include <Eigen/Dense>\r\n\r\ntypedef CGAL::Simple_cartesian<double> K;\r\ntypedef CGAL::Surface_mesh<K::Point_3> Mesh;\r\n\r\nnamespace PMP = CGAL::Polygon_mesh_processing;\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  const char* filename1 = \"../meshes/BIG_SCREW.off\";\r\n  std::ifstream input1(filename1);\r\n  Mesh mesh1;\r\n  if (!input1 || !(input1 >> mesh1) || !CGAL::is_triangle_mesh(mesh1))\r\n  {\r\n    std::cerr << \"Not a valid input file.\" << std::endl;\r\n    return 1;\r\n  }\r\n\r\n  const char* filename2 = \"../meshes/fingertip_8faces.off\";\r\n  std::ifstream input2(filename2);\r\n  Mesh mesh2;\r\n  if (!input2 || !(input2 >> mesh2) || !CGAL::is_triangle_mesh(mesh2))\r\n  {\r\n    std::cerr << \"Not a valid input file.\" << std::endl;\r\n    return 1;\r\n  }\r\n\r\n  Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\r\n  for (int i = 0; i < 10; ++i) {\r\n    double begin = std::clock();\r\n    Eigen::Vector3d p;\r\n    p << 0, 2*i, 0;\r\n    K::Aff_transformation_3 transform_cgal(\r\n        R(0,0), R(0,1), R(0,2), p(0),\r\n        R(1,0), R(1,1), R(1,2), p(1),\r\n        R(2,0), R(2,1), R(2,2), p(2), 1);\r\n    // K::Aff_transformation_3 transform_cgal(CGAL::TRANSLATION, K::Vector_3(0,i*2,0));\r\n    PMP::transform (transform_cgal, mesh1);\r\n    bool intersecting = PMP::do_intersect (mesh1, mesh2);\r\n    std::cout << \"Computation Time: \" << (std::clock() - begin) / CLOCKS_PER_SEC << \" sec\" << std::endl;\r\n    std::cout << \"intersecting: \" << intersecting << std::endl;\r\n  }\r\n}\r\n", "meta": {"hexsha": "1ac23c5aae6fe33e17a3660dbf0eea6e1698dea7", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "yifan-hou/triangle-mesh-collision", "max_stars_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_stars_repo_licenses": ["MIT"], "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": "yifan-hou/triangle-mesh-collision", "max_issues_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_issues_repo_licenses": ["MIT"], "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": "yifan-hou/triangle-mesh-collision", "max_forks_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_forks_repo_licenses": ["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.5740740741, "max_line_length": 105, "alphanum_fraction": 0.6219442865, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.650856879370451}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>\n#include <pangolin/pangolin.h>\n\n\nusing namespace std;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../../images/left.png\";\nstring disparity_file = \"../../images/disparity.png\";\nboost::format fmt_others(\"../../images/%06d.png\");    // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n/// class for accumulator jacobians in parallel\nclass JacobianAccumulator {\npublic:\n    JacobianAccumulator(\n        const cv::Mat &img1_,\n        const cv::Mat &img2_,\n        const VecVector2d &px_ref_,\n        const vector<double> depth_ref_,    //FIXME: Use &?//FIXME: Use &?\n        Sophus::SE3d &T21_) :\n        img1(img1_), img2(img2_), px_ref(px_ref_), depth_ref(depth_ref_), T21(T21_) {\n        projection = VecVector2d(px_ref.size(), Eigen::Vector2d(0, 0));\n    }\n\n    /// accumulate jacobians in a range\n    void accumulate_jacobian(const cv::Range &range);\n\n    /// get hessian matrix\n    Matrix6d hessian() const { return H; }\n\n    /// get bias\n    Vector6d bias() const { return b; }\n\n    /// get total cost\n    double cost_func() const { return cost; }\n\n    /// get projected points\n    VecVector2d projected_points() const { return projection; }\n\n    /// reset h, b, cost to zero\n    void reset() {\n        H = Matrix6d::Zero();\n        b = Vector6d::Zero();\n        cost = 0;\n    }\n\nprivate:\n    const cv::Mat &img1;\n    const cv::Mat &img2;\n    const VecVector2d &px_ref;\n    const vector<double> depth_ref;  //FIXME: Use &?\n    Sophus::SE3d &T21;\n    VecVector2d projection; // projected points\n\n    std::mutex hessian_mutex;\n    Matrix6d H = Matrix6d::Zero();\n    Vector6d b = Vector6d::Zero();\n    double cost = 0;\n};\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21\n);\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21\n);\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n        (1 - xx) * (1 - yy) * data[0] +\n        xx * (1 - yy) * data[1] +\n        (1 - xx) * yy * data[img.step] +\n        xx * yy * data[img.step + 1]\n    );\n}\n\nint main(int argc, char **argv) {\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 2000;\n    int boarder = 20;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d T_cur_ref;\n\n    for (int i = 1; i < 6; i++) {  // 1~10\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n        // try single layer by uncomment this line\n        // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n        DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n    }\n    return 0;\n}\n\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,  //FIXME: Use &?\n    Sophus::SE3d &T21) {\n\n    const int iterations = 10;\n    double cost = 0, lastCost = 0;\n    auto t1 = chrono::steady_clock::now();\n    JacobianAccumulator jaco_accu(img1, img2, px_ref, depth_ref, T21);\n\n    for (int iter = 0; iter < iterations; iter++) {\n        jaco_accu.reset();\n        cv::parallel_for_(cv::Range(0, px_ref.size()),\n                          std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n        Matrix6d H = jaco_accu.hessian();\n        Vector6d b = jaco_accu.bias();\n\n        // solve update and put it into estimation\n        Vector6d update = H.ldlt().solve(b);;\n        T21 = Sophus::SE3d::exp(update) * T21;\n        cost = jaco_accu.cost_func();\n\n        if (std::isnan(update[0])) {\n            // sometimes occurred when we have a black or white patch and H is irreversible\n            cout << \"update is nan\" << endl;\n            break;\n        }\n        if (iter > 0 && cost > lastCost) {\n            cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n            break;\n        }\n        if (update.norm() < 1e-3) {\n            // converge\n            break;\n        }\n\n        lastCost = cost;\n        cout << \"iteration: \" << iter << \", cost: \" << cost << endl;\n    }\n\n    cout << \"T21 = \\n\" << T21.matrix() << endl;\n    auto t2 = chrono::steady_clock::now();\n    auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"direct method for single layer: \" << time_used.count() << endl;\n\n    // plot the projected pixels here\n    cv::Mat img2_show;\n    cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n    VecVector2d projection = jaco_accu.projected_points();\n    for (size_t i = 0; i < px_ref.size(); ++i) {\n        auto p_ref = px_ref[i];\n        auto p_cur = projection[i];\n        if (p_cur[0] > 0 && p_cur[1] > 0) {\n            cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]),\n                     cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"current\", img2_show);\n    cv::waitKey();\n}\n\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) {\n\n    // parameters\n    const int half_patch_size = 1;\n    int cnt_good = 0;\n    Matrix6d hessian = Matrix6d::Zero();\n    Vector6d bias = Vector6d::Zero();\n    double cost_tmp = 0;\n\n    for (size_t i = range.start; i < range.end; i++) {\n\n        // compute the projection in the second image\n        Eigen::Vector3d point_ref =\n            depth_ref[i] * Eigen::Vector3d((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);\n        Eigen::Vector3d point_cur = T21 * point_ref;\n        if (point_cur[2] < 0)   // depth invalid\n            continue;\n\n        float u = fx * point_cur[0] / point_cur[2] + cx, v = fy * point_cur[1] / point_cur[2] + cy;\n        if (u < half_patch_size || u > img2.cols - half_patch_size || v < half_patch_size ||\n            v > img2.rows - half_patch_size)\n            continue;\n\n        projection[i] = Eigen::Vector2d(u, v);\n        double X = point_cur[0], Y = point_cur[1], Z = point_cur[2],\n            Z2 = Z * Z, Z_inv = 1.0 / Z, Z2_inv = Z_inv * Z_inv;\n        cnt_good++;\n\n        // and compute error and jacobian\n        for (int x = -half_patch_size; x <= half_patch_size; x++)\n            for (int y = -half_patch_size; y <= half_patch_size; y++) {\n\n                double error = GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y) -\n                               GetPixelValue(img2, u + x, v + y);\n                Matrix26d J_pixel_xi;\n                Eigen::Vector2d J_img_pixel;\n\n                J_pixel_xi(0, 0) = fx * Z_inv;\n                J_pixel_xi(0, 1) = 0;\n                J_pixel_xi(0, 2) = -fx * X * Z2_inv;\n                J_pixel_xi(0, 3) = -fx * X * Y * Z2_inv;\n                J_pixel_xi(0, 4) = fx + fx * X * X * Z2_inv;\n                J_pixel_xi(0, 5) = -fx * Y * Z_inv;\n\n                J_pixel_xi(1, 0) = 0;\n                J_pixel_xi(1, 1) = fy * Z_inv;\n                J_pixel_xi(1, 2) = -fy * Y * Z2_inv;\n                J_pixel_xi(1, 3) = -fy - fy * Y * Y * Z2_inv;\n                J_pixel_xi(1, 4) = fy * X * Y * Z2_inv;\n                J_pixel_xi(1, 5) = fy * X * Z_inv;\n\n                J_img_pixel = Eigen::Vector2d(\n                    0.5 * (GetPixelValue(img2, u + 1 + x, v + y) - GetPixelValue(img2, u - 1 + x, v + y)),\n                    0.5 * (GetPixelValue(img2, u + x, v + 1 + y) - GetPixelValue(img2, u + x, v - 1 + y))\n                );\n\n                // total jacobian\n                Vector6d J = -1.0 * (J_img_pixel.transpose() * J_pixel_xi).transpose();\n\n                hessian += J * J.transpose();\n                bias += -error * J;\n                cost_tmp += error * error;\n            }\n    }\n\n    if (cnt_good) {\n        // set hessian, bias and cost\n        unique_lock<mutex> lck(hessian_mutex);\n        H += hessian;\n        b += bias;\n        cost += cost_tmp / cnt_good;\n    }\n}\n\nvoid DirectPoseEstimationMultiLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,  //FIXME: Use &?\n    Sophus::SE3d &T21) {\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    for (int i = 0; i < pyramids; i++) {\n        if (i == 0) {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        } else {\n            cv::Mat img1_pyr, img2_pyr;\n            cv::resize(pyr1[i - 1], img1_pyr,\n                       cv::Size(pyr1[i - 1].cols * pyramid_scale, pyr1[i - 1].rows * pyramid_scale));\n            cv::resize(pyr2[i - 1], img2_pyr,\n                       cv::Size(pyr2[i - 1].cols * pyramid_scale, pyr2[i - 1].rows * pyramid_scale));\n            pyr1.push_back(img1_pyr);\n            pyr2.push_back(img2_pyr);\n        }\n    }\n\n    double fxG = fx, fyG = fy, cxG = cx, cyG = cy;  // backup the old values\n    for (int level = pyramids - 1; level >= 0; level--) {\n        VecVector2d px_ref_pyr; // set the keypoints in this pyramid level\n        for (auto &px: px_ref) {\n            px_ref_pyr.push_back(scales[level] * px);\n        }\n\n        // scale fx, fy, cx, cy in different pyramid levels\n        fx = fxG * scales[level];\n        fy = fyG * scales[level];\n        cx = cxG * scales[level];\n        cy = cyG * scales[level];\n        DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);\n    }\n\n}\n", "meta": {"hexsha": "c8294f608ba52d9cde01d0d29dc15806e7081d8e", "size": 11302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_stars_repo_name": "nicolasrosa-forks/slambook2", "max_stars_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_issues_repo_name": "nicolasrosa-forks/slambook2", "max_issues_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_forks_repo_name": "nicolasrosa-forks/slambook2", "max_forks_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T14:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T14:55:53.000Z", "avg_line_length": 33.1436950147, "max_line_length": 115, "alphanum_fraction": 0.5652981773, "num_tokens": 3418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6508568698960397}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass WeightedStats\n{\npublic:\n  Eigen::ArrayXd process(Eigen::Ref<Eigen::ArrayXd> input,\n                         Eigen::Ref<Eigen::ArrayXd> weights, double low,\n                         double mid, double high)\n  {\n    using namespace Eigen;\n    using namespace std;\n    index   length = input.size();\n    ArrayXd out = ArrayXd::Zero(7);\n    double  mean = (weights * input).sum();\n    double  stdev = sqrt((weights * (input - mean).square()).sum());\n    double  skewness =\n        (weights * ((input - mean) / (stdev == 0 ? 1 : stdev)).cube()).sum();\n    double kurtosis =\n        (weights * ((input - mean) / (stdev == 0 ? 1 : stdev)).pow(4)).sum();\n    ArrayXd sorted = input;\n    ArrayXidx perm = ArrayXidx::LinSpaced(length, 0, length - 1);\n    std::sort(perm.data(), perm.data() + length,\n              [&](index i, index j) { return input(i) < input(j); });\n    index  level = 0;\n    double lowVal{input(perm(0))};\n    double midVal{input(perm(lrint(length - 1) / 2))};\n    double hiVal{input(perm(lrint(length - 1)))};\n    double acc = weights(perm(0)), prevAcc = 0;\n    for (index i = 1; i < length; i++)\n    {\n      acc += weights(perm(i));\n      if (level == 0 && acc >= low)\n      {\n        lowVal = abs(prevAcc - low) <= abs(acc - low) ? input(perm(i - 1))\n                                                      : input(perm(i));\n        level = 1;\n      }\n      if (level == 1 && acc >= mid)\n      {\n        midVal = abs(prevAcc - mid) < abs(acc - mid) ? input(perm(i - 1))\n                                                     : input(perm(i));\n        level = 2;\n      }\n      if (level == 2 && acc >= high)\n      {\n        hiVal = abs(prevAcc - high) < abs(acc - high) ? input(perm(i - 1))\n                                                      : input(perm(i));\n        break;\n      }\n      prevAcc = acc;\n    }\n    out << mean, stdev, skewness, kurtosis, lowVal, midVal, hiVal;\n    return out;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "b3e22f78591cbbbff1b8e6632e5e405ce5cdc4e6", "size": 2596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/WeightedStats.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/util/WeightedStats.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/util/WeightedStats.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": 33.2820512821, "max_line_length": 77, "alphanum_fraction": 0.5546995378, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6508568647512072}}
{"text": "#include <geom/aabb.h>\n#include <geom/matrix.h>\n#include <geom/primitives.h>\n#include <geom/properties.h>\n\n#include <Eigen/Dense>\n\ndouble SignedTriangleVolume6(double3 a, double3 b, double3 c) {\n    double z = a.z;\n    z += b.z;\n    z += c.z;\n    double s;\n    s = (a.y + b.y) * (a.x - b.x);\n    s += (b.y + c.y) * (b.x - c.x);\n    s += (c.y + a.y) * (c.x - a.x);\n    return s * z;\n}\n\ndouble SignedRingVolume6(cspan<double3> ring) {\n    double z = 0;\n    for (auto e : ring) z += e.z;\n    double s = 0;\n    for (auto e : Edges(ring)) s += (e.a.y + e.b.y) * (e.a.x - e.b.x);\n    return s * z;\n}\n\ndouble SignedVolume(const mesh3& mesh) {\n    double v = 0;\n    for (const triangle3& f : mesh) v += SignedTriangleVolume6(f.a, f.b, f.c);\n    return v / 6.0;\n}\n\ndouble SignedVolume(const xmesh3& mesh) {\n    double v = 0;\n    for (face f : mesh)\n        for (auto ring : f) v += SignedRingVolume6(ring);\n    return v / 6.0;\n}\n\n// TODO test with volume of cube (randomly rotated)\n\n// Center of mass of a valid polyhedron\ndouble3 CenterOfMass(const mesh3& mesh) {\n    double3 P = {0, 0, 0};\n    double V = 0;\n    for (const triangle3& f : mesh) {\n        double v = dot(f.a, cross(f.b, f.c));\n        P += (f.a + f.b + f.c) * v;\n        V += v;\n    }\n    return P / (V * 4);\n}\n\ndouble2 centroid(cspan<double2> poly) {\n    double2 P = {0, 0};\n    double2 V = 0;\n    for (auto i : range(poly.size())) {\n        double2 a = poly[i];\n        double2 b = poly[(i + 1) % poly.size()];\n        double v = a.x * b.y - a.y * b.x;\n        P += (a + b) * v;\n        V += v;\n    }\n    return P / (V * 3);\n}\n\ndouble2 CenterOfMass(const polygon2& poly) {\n    double2 P = {0, 0};\n    double2 V = 0;\n    for (auto [a, b] : Edges(poly)) {\n        double v = a.x * b.y - a.y * b.x;\n        P += (a + b) * v;\n        V += v;\n    }\n    return P / (V * 3);\n}\n\n// Moment of inertia of a valid polyhedron with Center of Mass = 0 and Density = 1\ndouble33 moment_of_inertia(const mesh3& mesh) {\n    constexpr double a = 1 / 60., b = 1 / 120.;\n    const double33 canonical = {{a, b, b}, {b, a, b}, {b, b, a}};\n    auto C = double33::make(0);  // covariance\n    for (const auto& f : mesh) {\n        double33 A;\n        // TODO setting rows or columns?\n        A.a = f[0];\n        A.b = f[1];\n        A.c = f[2];\n        C += transpose(A) * canonical * A * det(A);\n    }\n    return double33::make(trace(C)) - C;  // C -> I\n}\n\nbool is_aabb(const mesh3& mesh) {\n    aabb3 box(mesh);\n\n    // All vertices must be made from extreme coordinates\n    for (auto f : mesh)\n        for (double3 v : f)\n            if (v.x != box.min[0] && v.x != box.max[0] && v.y != box.min[1] && v.y != box.max[1] && v.z != box.min[2] &&\n                v.z != box.max[2])\n                return false;\n\n    // Every face must have one coordinate constant\n    for (auto f : mesh) {\n        bool xx = f.a.x == f.b.x && f.b.x == f.c.x;\n        bool yy = f.a.y == f.b.y && f.b.y == f.c.y;\n        bool zz = f.a.z == f.b.z && f.b.z == f.c.z;\n        if (!xx && !yy && !zz) return false;\n    }\n    return true;\n}\n\ndouble3 eigen_vector(cspan<double3> points) {\n    // compute mean\n    double3 m = {0, 0, 0};\n    for (auto p : points) m += p;\n    m /= points.size();\n\n    // compute matrix\n    double3 ss = {0, 0, 0};\n    double xy = 0, xz = 0, yz = 0;\n    for (auto p : points) {\n        p -= m;\n        ss += p * p;\n        xy += p.x * p.y;\n        xz += p.x * p.z;\n        yz += p.y * p.z;\n    }\n\n    Eigen::MatrixXd a = Eigen::MatrixXd::Zero(3, 3);\n    a(0, 0) = ss.x;\n    a(1, 1) = ss.y;\n    a(2, 2) = ss.z;\n    a(0, 1) = a(1, 0) = xy;\n    a(0, 2) = a(2, 0) = xz;\n    a(1, 2) = a(2, 1) = yz;\n\n    Eigen::EigenSolver<Eigen::MatrixXd> es(a, true);\n    auto values = es.eigenvalues();\n    int i = 0;\n    if (values(1).real() < values(i).real()) i = 1;\n    if (values(2).real() < values(i).real()) i = 2;\n\n    auto vectors = es.eigenvectors();\n    return {vectors(0, i).real(), vectors(1, i).real(), vectors(2, i).real()};\n}\n", "meta": {"hexsha": "620f678a6641a058e377268ba7808ffd92d66655", "size": 3958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "geom/properties.cc", "max_stars_repo_name": "tintor/sima", "max_stars_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-06T15:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-06T15:01:00.000Z", "max_issues_repo_path": "geom/properties.cc", "max_issues_repo_name": "tintor/sima", "max_issues_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "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": "geom/properties.cc", "max_forks_repo_name": "tintor/sima", "max_forks_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "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.7432432432, "max_line_length": 120, "alphanum_fraction": 0.4936836786, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6508270384469711}}
{"text": "//######################################################################\n//#   SDF_Fusion Module \n//#   \n//#   Copyright (C) 2020 Siemens AG\n//#   SPDX-License-Identifier: MIT\n//#   Author 2020: This module has been developed by \n//#                or under supervision of Slobodan Ilic\n//#######################################################################\n\n#include \"visualizer.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/video.hpp>\n\nusing namespace cv;\nusing namespace Eigen;\nusing namespace std;\n\nvector<Mat> transform_and_project(const vector<Mat>& points, const Mat& intrinsics, const Mat& pose)\n{\n\tvector<Mat> projected_2d_points(points.size());\n\ttransform(points.begin(), points.end(), projected_2d_points.begin(), [&pose, &intrinsics] (const auto &point)\n\t{\n\t\tMat transformed = pose * point;\n\t\tMat projected = intrinsics * transformed.rowRange(0, 3);\n\t\tprojected /= projected.at<float>(2);\n\t\treturn projected;\n\t});\n\n\treturn projected_2d_points;\n}\n\n\nvoid draw_origin_axis(Mat &colored_img, const Mat& intrinsics, const Mat& pose, float basis_length = 0.1) {\n\tvector<Mat> axes_endpoints;\n\taxes_endpoints.push_back((Mat_<float>(4, 1) << 0, 0, 0, 1));\n\taxes_endpoints.push_back((Mat_<float>(4, 1) << basis_length, 0, 0, 1));\n\taxes_endpoints.push_back((Mat_<float>(4, 1) << 0, basis_length, 0, 1));\n\taxes_endpoints.push_back((Mat_<float>(4, 1) << 0, 0, basis_length, 1));\n\n\t// transform cube into camera reference frame\n\n\tvector<Mat> p2d = transform_and_project(axes_endpoints, intrinsics, pose);\n\n\tPoint p0 = Point(p2d[0].at<float>(0), p2d[0].at<float>(1));\n\tPoint px = Point(p2d[1].at<float>(0), p2d[1].at<float>(1));\n\tPoint py = Point(p2d[2].at<float>(0), p2d[2].at<float>(1));\n\tPoint pz = Point(p2d[3].at<float>(0), p2d[3].at<float>(1));\n\n\tline(colored_img, p0, px, cv::Scalar(0, 0, 255), 1, 8);\n\tline(colored_img, p0, py, cv::Scalar(0, 255, 0), 1, 8);\n\tline(colored_img, p0, pz, cv::Scalar(255, 0, 0), 1, 8);\n\n\tcircle(colored_img, p0, 200 / 32.0, cv::Scalar(255, 255, 0), -1, 8);\n}\n\n\nvoid visualize_volume(const Mat &source_image, const Mat &intrinsics, const Mat &rotation, const Mat &translation, const Mat& llc, const Mat& upc)\n{\n\tMat image = source_image.clone();\n\t\n\tMat pose = Mat::eye(4, 4, CV_32F);\n\trotation.copyTo(pose.colRange(0, 3).rowRange(0, 3));\n\ttranslation.copyTo(pose.col(3).rowRange(0, 3));\n\n\tPoint3f llc_p(llc);\n\tPoint3f upc_p(upc);\n\n\t// Points in the world coordinates\n\tvector<Mat> volume_points;\n\tvolume_points.push_back((Mat_<float>(4, 1) << llc_p.x, llc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << llc_p.x, llc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << upc_p.x, llc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << upc_p.x, llc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << llc_p.x, upc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << llc_p.x, upc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << upc_p.x, upc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_<float>(4, 1) << upc_p.x, upc_p.y, llc_p.z, 1));\n\n\t// transform cube into camera reference frame\n\tvector<Mat> p2d = transform_and_project(volume_points, intrinsics, pose);\n\n\t// Draw cube\n\tScalar line_color = Scalar(148, 24, 248);\n\t// Generate edge points\n\tvector<pair<int, int>> edge_point_indices;\n\tedge_point_indices.push_back(make_pair(1, 5));\n\tedge_point_indices.push_back(make_pair(2, 6));\n\tedge_point_indices.push_back(make_pair(3, 7));\n\tedge_point_indices.push_back(make_pair(0, 4));\n\n\tedge_point_indices.push_back(make_pair(0, 1));\n\tedge_point_indices.push_back(make_pair(1, 2));\n\tedge_point_indices.push_back(make_pair(2, 3));\n\tedge_point_indices.push_back(make_pair(3, 0));\n\n\tedge_point_indices.push_back(make_pair(4, 7));\n\tedge_point_indices.push_back(make_pair(7, 6));\n\tedge_point_indices.push_back(make_pair(6, 5));\n\tedge_point_indices.push_back(make_pair(5, 4));\n\n\t// Draw edges\n\n\tfor (const auto &point_indices : edge_point_indices)\n\t{\n\t\tint p0_i = point_indices.first;\n\t\tPoint p0 = Point(p2d[p0_i].at<float>(0), p2d[p0_i].at<float>(1));\n\t\tint p1_i = point_indices.second;\n\t\tPoint p1 = Point(p2d[p1_i].at<float>(0), p2d[p1_i].at<float>(1));\n\t\tline(image, p0, p1, line_color, 1, 8);\n\t\t\n\t}\n\n\t// Draw circles\n\tfor (const auto& point : p2d)\n\t{\n\t\tPoint point_to_draw = Point(point.at<float>(0), point.at<float>(1));\n\t\tcircle(image, point_to_draw, 200 / 32.0, line_color, -1, 8);\n\t}\n\n\tdraw_origin_axis(image, intrinsics, pose);\n\n\tMat image_to_show;\n\n\t// resize if too big for showing\n\tif (image.cols > 800)\n\t{\n\t\tSize show_size = Size(image.cols / 2, image.rows / 2);\n\t\tresize(image, image_to_show, show_size);\n\t} else\n\t{\n\t\timage_to_show = image;\n\t}\n\t\n\t\n\timshow(\"image\", image_to_show);\n}\n\n\nvoid visualize_volume(const Mat& input_image, const Matrix3f& intrinsics, const Isometry3f& pose, const vector<float>& volume)\n{\n\tMat intrinsics_cv;\n\n\teigen2cv(intrinsics, intrinsics_cv);\n\n\tMat llc = (Mat_<float>(3, 1) << volume[0], volume[2], volume[4]);\n\tMat upc = (Mat_<float>(3, 1) << volume[1], volume[3], volume[5]);\n\n\tconst Matrix4f &pose_eigen = pose.matrix();\n\tMat pose_cv;\n\teigen2cv(pose_eigen, pose_cv);\n\n\tMat rotation = pose_cv(Range(0, 3), Range(0, 3));\n\tMat translation = pose_cv(Range(0, 3), Range(3, 4));\n\n\tvisualize_volume(input_image, intrinsics_cv, rotation, translation, llc, upc);\n}", "meta": {"hexsha": "3b6b820f95c7f0ce825e1ed561e158a549502342", "size": 5414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_stars_repo_name": "YyYyYong0331/homebrewdb", "max_stars_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T16:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:47:29.000Z", "max_issues_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_issues_repo_name": "YyYyYong0331/homebrewdb", "max_issues_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T07:28:52.000Z", "max_forks_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_forks_repo_name": "YyYyYong0331/homebrewdb", "max_forks_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T09:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T10:42:33.000Z", "avg_line_length": 34.0503144654, "max_line_length": 146, "alphanum_fraction": 0.6769486516, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.650827038446971}}
{"text": "#define BOOST_TEST_MODULE SparseLatticeMultTests\n\n\n\n#include \"DenseLattice.h\"\r\n#include \"SparseLattice.h\"\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\n\ntemplate<typename data_type>\nvoid multwork(size_t m1, size_t n1, size_t n2, size_t p){\n    typedef LibMIA::DenseLattice<data_type> denseType;\r\n    typedef LibMIA::SparseLattice<data_type> sparseType;\r\n\r\n    denseType DenseLat1(m1,n1,p);\n    denseType DenseLat2(n1,n2,p);\n    denseType DenseLat3;\r\n\r\n    sparseType SparseLat1(m1,n1,p);\n    sparseType SparseLat2(n1,n2,p);\n    sparseType SparseLat3;\n\n\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\r\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n//    std::cout << \"**************First LAT \" << std::endl;\r\n//    DenseLat1.print();\r\n//    SparseLat1.print();\r\n    SparseLat2=DenseLat2;\r\n//    std::cout << \"**************Second LAT \" << std::endl;\r\n//    DenseLat2.print();\r\n//    SparseLat2.print();\r\n    DenseLat3=DenseLat1*DenseLat2;\r\n//    std::cout << \"**************Result \" << std::endl;\r\n//    DenseLat3.print();\r\n    SparseLat3=SparseLat1*SparseLat2;\r\n//    SparseLat3.print();\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(SparseLat3,test_precision<data_type>()),std::string(\"Full Dimension Mult Test for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(1,n1,p);\n    DenseLat2=denseType(n1,1,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1*DenseLat2;\r\n    SparseLat3=SparseLat1*SparseLat2;\r\n\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(SparseLat3,test_precision<data_type>()),std::string(\"Repeated Inner Product Mult Test for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(m1,1,p);\n    DenseLat2=denseType(1,n2,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1*DenseLat2;\r\n    SparseLat3=SparseLat1*SparseLat2;\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(SparseLat3,test_precision<data_type>()),std::string(\"Repeated Outer Product Mult Test for \")+typeid(data_type).name());\r\n\r\n    DenseLat1=denseType(m1,n1,1);\n    DenseLat2=denseType(n1,n2,1);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1*DenseLat2;\r\n    SparseLat3=SparseLat1*SparseLat2;\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(SparseLat3,test_precision<data_type>()),std::string(\"No Depth Mult Test for \")+typeid(data_type).name());\r\n\r\n\r\n\r\n    DenseLat1=denseType(m1,1,p);\n    DenseLat2=denseType(1,1,p);\r\n    DenseLat1.randu(0,10);\r\n    DenseLat2.randu(0,10);\r\n\n    for(auto it=DenseLat1.data_begin();it<DenseLat1.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n    for(auto it=DenseLat2.data_begin();it<DenseLat2.data_end();++it)\r\n        if(*it<7)\r\n            *it=0;\r\n\r\n    SparseLat1=DenseLat1;\r\n    SparseLat2=DenseLat2;\r\n\r\n    DenseLat3=DenseLat1*DenseLat2;\r\n    SparseLat3=SparseLat1*SparseLat2;\r\n\r\n    BOOST_CHECK_MESSAGE(DenseLat3.fuzzy_equals(SparseLat3,test_precision<data_type>()),std::string(\"Outer product, one operand, test for \")+typeid(data_type).name());\r\n\r\n\r\n\n\n}\n\nBOOST_AUTO_TEST_CASE( SparseLatticeMultTests )\n{\n\n\n    //multwork<double>(5,5,5,1);\r\n    multwork<double>(20,20,20,20);\n    multwork<float>(20,20,20,20);\r\n    multwork<int>(20,20,20,20);\r\n    multwork<long>(20,20,20,20);\r\n\r\n    multwork<double>(40,20,20,20);\n    multwork<float>(40,20,20,20);\r\n    multwork<int>(40,20,20,20);\r\n    multwork<long>(40,20,20,20);\r\n\r\n    multwork<double>(20,20,40,20);\n    multwork<float>(20,20,40,20);\r\n    multwork<int>(20,20,40,20);\r\n    multwork<long>(20,20,40,20);\n\n\n\n}\r\n", "meta": {"hexsha": "75eba444c2dd45dddafe5f76a1619e4b4f834c47", "size": 4656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/SparseLattice/sparse_lattice_mult_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/SparseLattice/sparse_lattice_mult_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "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/tests/SparseLattice/sparse_lattice_mult_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 28.9192546584, "max_line_length": 167, "alphanum_fraction": 0.6408934708, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6508270234032015}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2019, Robert Bosch GmbH\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the Robert Bosch GmbH 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Leonard Bruns */\n\n#include \"ompl/base/samplers/deterministic/HaltonSequence.h\"\n#include \"ompl/util/Console.h\"\n#include <iostream>\n#include <cmath>\n#include <map>\n#include <boost/math/special_functions/prime.hpp>\n\nnamespace ompl\n{\n    namespace base\n    {\n        HaltonSequence1D::HaltonSequence1D() : i_(1), base_(2)\n        {\n        }\n\n        HaltonSequence1D::HaltonSequence1D(unsigned int base) : i_(1), base_(base)\n        {\n        }\n\n        void HaltonSequence1D::setBase(unsigned int base)\n        {\n            base_ = base;\n        }\n\n        double HaltonSequence1D::sample()\n        {\n            double f = 1, r = 0;\n            unsigned int i = i_;\n\n            while (i > 0)\n            {\n                f /= base_;\n                r += f * (i % base_);\n                i = std::floor(i / base_);\n            }\n\n            ++i_;\n            return r;\n        }\n\n        HaltonSequence::HaltonSequence(unsigned int dimensions)\n          : DeterministicSequence(dimensions), halton_sequences_1d_(dimensions)\n        {\n            setBasesToPrimes();\n        }\n\n        HaltonSequence::HaltonSequence(unsigned int dimensions, std::vector<unsigned int> bases)\n          : DeterministicSequence(dimensions), halton_sequences_1d_(dimensions)\n        {\n            if (bases.size() != dimensions)\n            {\n                OMPL_WARN(\"Number of bases does not match dimensions. Using first n primes instead.\");\n            }\n            else\n            {\n                int i = 0;\n                for (auto base : bases)\n                {\n                    halton_sequences_1d_[i].setBase(base);\n                    i++;\n                }\n            }\n        }\n\n        std::vector<double> HaltonSequence::sample()\n        {\n            std::vector<double> samples;\n            for (auto &seq : halton_sequences_1d_)\n            {\n                samples.push_back(seq.sample());\n            }\n            return samples;\n        }\n\n        void HaltonSequence::setBasesToPrimes()\n        {\n            // set the base of the halton sequences to the first n prime numbers, where n is dimensions\n            unsigned int current = 2;\n            for (unsigned int i = 0; i < dimensions_; i++)\n            {\n                current = boost::math::prime(i);\n                halton_sequences_1d_[i].setBase(current);\n            }\n        }\n    }  // namespace base\n}  // namespace ompl\n", "meta": {"hexsha": "2e54a9a27e6df32e1eecc8d3199d086cb09cf275", "size": 4221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_forks_repo_name": "ericpairet/ompl", "max_forks_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 34.3170731707, "max_line_length": 103, "alphanum_fraction": 0.5825633736, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6508270234032014}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <gauss/linalg.h>\n#include <Eigen/Eigenvalues>\n#include <gauss/internal/scopedHostPtr.h>\n#include <tuple>\n\naf::array gauss::linalg::eigvalsh(const af::array &m) {\n    auto mtype = m.type();\n\n    if (mtype == af::dtype::c32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cfloat>());\n        auto typed = (std::complex<float>*)matHost.get();\n        Eigen::MatrixXcf mat = Eigen::Map<Eigen::MatrixXcf>(typed, m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcf> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        return af::array(m.dims(0), solver.eigenvalues().data());\n    }\n    \n    if (mtype == af::dtype::c64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cdouble>());\n        auto typed = (std::complex<double>*)matHost.get();\n        Eigen::MatrixXcd mat = Eigen::Map<Eigen::MatrixXcd>(typed, m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        return af::array(m.dims(0), solver.eigenvalues().data());\n    }\n    \n    if (mtype == af::dtype::f64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<double>());\n        Eigen::MatrixXd mat = Eigen::Map<Eigen::MatrixXd>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        return af::array(m.dims(0), solver.eigenvalues().data());\n    } \n    \n    if (mtype == af::dtype::f32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<float>());\n        Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        return af::array(m.dims(0), solver.eigenvalues().data());\n    }\n    \n    if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n        return eigvalsh(m.as(af::dtype::f64));\n\n    return eigvalsh(m.as(af::dtype::f32));\n}\n\naf::array gauss::linalg::eigvals(const af::array &m) {\n    auto mtype = m.type();\n\n    if (mtype == af::dtype::c32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cfloat>());\n        auto typed = (std::complex<float>*)matHost.get();\n        Eigen::MatrixXcf mat = Eigen::Map<Eigen::MatrixXcf>(typed, m.dims(0), m.dims(1));\n        Eigen::ComplexEigenSolver<Eigen::MatrixXcf> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        auto eivals = solver.eigenvalues();\n        auto eivals_af = (af::af_cfloat*) eivals.data();\n        return af::array(m.dims(0), eivals_af);\n    }\n    \n    if (mtype == af::dtype::c64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cdouble>());\n        auto typed = (std::complex<double>*)matHost.get();\n        Eigen::MatrixXcd mat = Eigen::Map<Eigen::MatrixXcd>(typed, m.dims(0), m.dims(1));\n        Eigen::ComplexEigenSolver<Eigen::MatrixXcd> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n\n        auto eivals = solver.eigenvalues();\n        auto eivals_af = (af::af_cdouble*) eivals.data();\n        return af::array(m.dims(0), eivals_af);\n    }\n    \n    if (mtype == af::dtype::f64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<double>());\n        Eigen::MatrixXd mat = Eigen::Map<Eigen::MatrixXd>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::EigenSolver<Eigen::MatrixXd> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        auto eivals = solver.eigenvalues();\n        auto eivals_af = (af::af_cdouble*) eivals.data();\n        return af::array(m.dims(0), eivals_af);\n    } \n    \n    if (mtype == af::dtype::f32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<float>());\n        Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::EigenSolver<Eigen::MatrixXf> solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n        auto eivals = solver.eigenvalues();\n        auto eivals_af = (af::af_cfloat*) eivals.data();\n        return af::array(m.dims(0), eivals_af);\n    }\n    \n    if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n        return eigvals(m.as(af::dtype::f64));\n\n    return eigvals(m.as(af::dtype::f32));\n}\n\nstd::tuple<af::array, af::array> gauss::linalg::eig(const af::array &m) {\n\n    auto mtype = m.type();\n\n    if (mtype == af::dtype::c32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cfloat>());\n        auto typed = (std::complex<float>*)matHost.get();\n        Eigen::MatrixXcf mat = Eigen::Map<Eigen::MatrixXcf>(typed, m.dims(0), m.dims(1));\n        Eigen::ComplexEigenSolver<Eigen::MatrixXcf> solver(mat);\n        auto eivals = solver.eigenvalues();\n        auto eivect = solver.eigenvectors();\n        auto eivals_af = (af::af_cfloat*) eivals.data();\n        auto eivect_af = (af::af_cfloat*) eivect.data();\n        auto eigenValues = af::array(m.dims(0), eivals_af);\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);\n        return std::make_tuple(eigenValues, eigenVectors);\n    }\n    \n    if (mtype == af::dtype::c64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cdouble>());\n        auto typed = (std::complex<double>*)matHost.get();\n\n        Eigen::MatrixXcd mat = Eigen::Map<Eigen::MatrixXcd>(typed, m.dims(0), m.dims(1));\n        Eigen::ComplexEigenSolver<Eigen::MatrixXcd> solver(mat);\n\n        auto eivals = solver.eigenvalues();\n        auto eivect = solver.eigenvectors();\n        auto eivals_af = (af::af_cdouble*) eivals.data();\n        auto eivect_af = (af::af_cdouble*) eivect.data();\n        auto eigenValues = af::array(m.dims(0), eivals_af);\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);       \n        return std::make_tuple(eigenValues, eigenVectors); \n    }\n    \n    if (mtype == af::dtype::f64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<double>());\n        Eigen::MatrixXd mat = Eigen::Map<Eigen::MatrixXd>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::EigenSolver<Eigen::MatrixXd> solver(mat);\n        auto eivals = solver.eigenvalues();\n        auto eivect = solver.eigenvectors();\n        auto eivals_af = (af::af_cdouble*) eivals.data();\n        auto eivect_af = (af::af_cdouble*) eivect.data();\n        auto eigenValues = af::array(m.dims(0), eivals_af);\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);     \n        return std::make_tuple(eigenValues, eigenVectors);\n    } \n    \n    if (mtype == af::dtype::f32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<float>());\n        Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::EigenSolver<Eigen::MatrixXf> solver(mat);\n        auto eivals = solver.eigenvalues();\n        auto eivect = solver.eigenvectors();\n        auto eivals_af = (af::af_cfloat*) eivals.data();\n        auto eivect_af = (af::af_cfloat*) eivect.data();\n        auto eigenValues = af::array(m.dims(0), eivals_af);\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n        return std::make_tuple(eigenValues, eigenVectors);\n    }\n    \n    if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n        return eig(m.as(af::dtype::f64));\n\n    return eig(m.as(af::dtype::f32));\n}\n\n\nstd::tuple<af::array, af::array> gauss::linalg::eigh(const af::array &m) {\n\n    auto mtype = m.type();\n\n    if (mtype == af::dtype::c32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cfloat>());\n        auto typed = (std::complex<float>*)matHost.get();\n        Eigen::MatrixXcf mat = Eigen::Map<Eigen::MatrixXcf>(typed, m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcf> solver(mat);\n        auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n\n        auto eivect = solver.eigenvectors();\n        auto eivect_af = (af::af_cfloat*) eivect.data();\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);       \n\n        return std::make_tuple(eigenValues, eigenVectors); \n    }\n    \n    if (mtype == af::dtype::c64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<af::af_cdouble>());\n        auto typed = (std::complex<double>*)matHost.get();\n\n        Eigen::MatrixXcd mat = Eigen::Map<Eigen::MatrixXcd>(typed, m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXcd> solver(mat);\n\n        auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n\n        auto eivect = solver.eigenvectors();\n        auto eivect_af = (af::af_cdouble*) eivect.data();\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);       \n\n        return std::make_tuple(eigenValues, eigenVectors); \n    }\n    \n    if (mtype == af::dtype::f64) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<double>());\n        Eigen::MatrixXd mat = Eigen::Map<Eigen::MatrixXd>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(mat);\n        auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), solver.eigenvectors().data());     \n        return std::make_tuple(eigenValues, eigenVectors);\n    } \n    \n    if (mtype == af::dtype::f32) {\n        auto matHost = gauss::utils::makeScopedHostPtr(m.host<float>());\n        Eigen::MatrixXf mat = Eigen::Map<Eigen::MatrixXf>(matHost.get(), m.dims(0), m.dims(1));\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> solver(mat);\n\n        auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n        auto eigenVectors = af::array(m.dims(0), m.dims(1), solver.eigenvectors().data()); \n        return std::make_tuple(eigenValues, eigenVectors);\n    }\n    \n    if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n        return eigh(m.as(af::dtype::f64));\n\n    return eigh(m.as(af::dtype::f32));\n}\n\n\naf::array gauss::linalg::lls(const af::array &A, const af::array &b) {\n    af::array U;\n    af::array S;\n    af::array VT;\n\n    af::svd(U, S, VT, A);\n\n    S = af::diag(S, 0, false);\n\n    af::array S_dagger = (S != 0).as(S.type()) * af::inverse(S);\n\n    long missingRows = static_cast<long>(A.dims(1) - S.dims(0));\n    long missingColumns = static_cast<long>(A.dims(0) - S.dims(0));\n    af::array toPadRows = af::constant(0, missingRows, A.dims(0), A.type());\n    af::array toPadColumns = af::constant(0, A.dims(1), missingColumns, A.type());\n\n    S_dagger = af::join(0, S_dagger, toPadRows);\n    S_dagger = af::join(1, S_dagger, toPadColumns);\n\n    af::array V = af::transpose(VT);\n    af::array UT = af::transpose(U);\n    af::array x = af::matmul(V, S_dagger, UT, b);\n\n    return x;\n}\n\n\naf::array gauss::linalg::levinsonDurbin(af::array acv, int order) {\n    af::array result = af::constant(0, order + 1, acv.dims(1), acv.type());\n\n    for (int i = 0; i < acv.dims(1); i++) {\n        af::array phi = af::constant(0, order + 1, order + 1, acv.type());\n        af::array sig = af::constant(0, order + 1, acv.type());\n\n        phi(1, 1) = acv(1, i) / acv(0, i);\n        sig(1) = acv(0, i) - (phi(1, 1) * acv(1, i));\n\n        // First iteration, to avoid problems with negative sequences with 1 element\n        int k = 2;\n        if (k < (order + 1)) {\n            phi(k, k) = (acv(k, i) - af::dot(phi(af::seq(1, k - 1), k - 1), acv(af::seq(1, k - 1), i))) / sig(k - 1);\n            for (int j = 1; j < k; j++) {\n                phi(j, k) = phi(j, k - 1) - (phi(k, k) * phi(k - j, k - 1));\n            }\n            sig(k) = sig(k - 1) * (1.0 - phi(k, k) * phi(k, k));\n        }\n\n        // Second and subsequent iterations\n        for (int l = 3; l < (order + 1); l++) {\n            af::array aux = acv(af::seq(1, l - 1), i);\n            phi(l, l) = (acv(l, i) - af::dot(phi(af::seq(1, l - 1), l - 1),\n                                             aux(af::seq(static_cast<double>(aux.dims(0)) - 1, 0, -1)))) /\n                        sig(l - 1);\n            for (int j = 1; j < l; j++) {\n                phi(j, l) = phi(j, l - 1) - (phi(l, l) * phi(l - j, l - 1));\n            }\n            sig(l) = sig(l - 1) * (1.0 - phi(l, l) * phi(l, l));\n        }\n\n        af::array pac = af::diag(phi);\n        pac(0) = 1.0;\n        result(af::span, i) = pac;\n    }\n    return result;\n}", "meta": {"hexsha": "cb4124715ff19d74181140daec6a1585fd455ddf", "size": 12594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/linalg.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/linalg.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/linalg.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "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": 43.2783505155, "max_line_length": 117, "alphanum_fraction": 0.5909163094, "num_tokens": 3868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.650749825958808}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\nusing namespace std;\n\nvoid vector2transform(vector<double> &vec, Eigen::Matrix4d &t){\n    t(0,3) = vec[0];\n    t(1,3) = vec[1];\n    t(2,3) = vec[2];\n    Eigen::Quaterniond temp;\n    temp.w() = vec[3];\n    temp.x() = vec[4];\n    temp.y() = vec[5];\n    temp.z() = vec[6];\n    t.block(0,0,3,3) = temp.toRotationMatrix();\n}\n\nint main(){\n    string path_in = \"/home/chenchr/ttx.txt\";\n    fstream file_in(path_in, ios::in);\n    vector<vector<double> > all;\n    for(int i=0; i<10; ++i){\n        double x, y, z, qw, qx, qy, qz;\n        char temp;\n        file_in >> x >> temp >> y >> temp >> z >> temp >> qw >> temp >> qx >> temp >> qy >> temp >> qz;\n        all.push_back({x, y, z, qw, qx, qy, qz});\n    }\n    vector<Eigen::Matrix4d> all_T;\n    for(int i=0; i<10; ++i){\n        all_T.push_back(Eigen::Matrix4d::Identity());\n        vector2transform(all[i], all_T[i]);\n    }\n    for(int i=0; i<10; ++i){\n        cout << i << \": \" << endl;\n        for(int j=0; j<7; ++j)\n            cout << all[i][j] << \" \";\n        cout << endl;\n        cout << all_T[i] << endl;\n    }\n    return 0;\n}", "meta": {"hexsha": "09461dc999e60af2ec031278241413283128f8d4", "size": 1184, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc_cxx/vector2transform.cc", "max_stars_repo_name": "chenchr/PoseNet", "max_stars_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-09T03:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-10T00:13:56.000Z", "max_issues_repo_path": "misc_cxx/vector2transform.cc", "max_issues_repo_name": "chenchr/PoseNet", "max_issues_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_issues_repo_licenses": ["MIT"], "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_cxx/vector2transform.cc", "max_forks_repo_name": "chenchr/PoseNet", "max_forks_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 103, "alphanum_fraction": 0.5109797297, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6507219078576387}}
{"text": "//\n// Created by joshua on 9/6/17.\n//\n#include <mps/planner/util/Math.h>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\nvoid mps::planner::util::math::normalize_orientation(double& value) {\n    // from ompl::base::SO2StateSpace::enforceBounds\n    double v = fmod(value, 2.0 * boost::math::constants::pi<double>());\n    if (v < -boost::math::constants::pi<double>())\n        v += 2.0 * boost::math::constants::pi<double>();\n    else if (v >= boost::math::constants::pi<double>())\n        v -= 2.0 * boost::math::constants::pi<double>();\n    value = v;\n}\n\nvoid mps::planner::util::math::normalize_orientation(float& value) {\n    float v = fmod(value, 2.0f * boost::math::constants::pi<float>());\n    if (v < -boost::math::constants::pi<float>())\n        v += 2.0f * boost::math::constants::pi<float>();\n    else if (v >= boost::math::constants::pi<float>())\n        v -= 2.0f * boost::math::constants::pi<float>();\n    value = v;\n}\n\n/**\n * Returns the shortest direction from val_1 to val_2 assuming that both values\n * are angles in radian in [-pi, pi)\n * @param val_1\n * @param val_2\n * @return the smallest change in angle da such that val_1 + da = val_2 mod 2pi\n */\nfloat mps::planner::util::math::shortest_direction_so2(float val_1, float val_2) {\n    float value = val_2 - val_1;\n    if (std::abs(value) > boost::math::constants::pi<float>()) {\n        if (value > 0.0f) { // val_2 > val_1\n            value -= 2.0f * boost::math::constants::pi<float>();\n        } else {\n            value += 2.0f * boost::math::constants::pi<float>();\n        }\n    }\n    return value;\n}\n", "meta": {"hexsha": "5d9dd994808a87ee7a28e94f4eac4adc461b6f0e", "size": 1594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mps/planner/util/Math.cpp", "max_stars_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_stars_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "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/mps/planner/util/Math.cpp", "max_issues_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_issues_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "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/mps/planner/util/Math.cpp", "max_forks_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_forks_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T12:59:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-04T12:59:50.000Z", "avg_line_length": 35.4222222222, "max_line_length": 82, "alphanum_fraction": 0.6072772898, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.650721893443995}}
{"text": "#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\nusing namespace std;\n\nint main() {\n    mat A {{1.0, 2.0}, {3.0, 4.0}};\n    A.print(\"A:\");\n    mat B = A*A.i();\n    B.print(\"B:\");\n    mat C = eye<mat>(2, 2);\n    C.print(\"C:\");\n    cout << \"abs. sum: \" <<  accu(abs(B - C)) << endl;\n    return 0;\n}\n", "meta": {"hexsha": "d9cbc9fd78aadc36bb72c4e9c2dc7aa6b8719175", "size": 312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/inverse.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/Armadillo/inverse.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/Armadillo/inverse.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": 18.3529411765, "max_line_length": 54, "alphanum_fraction": 0.4967948718, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6507126356800703}}
{"text": "#include \"geo_calculator.h\"\n#include <Eigen/Sparse>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n#include <assert.h>\n\n#include \"cgal_predef.h\"\n\n\n//// CGAL \n// Compute OBB\n#include <CGAL/Polygon_2.h>\n#include <CGAL/min_quadrilateral_2.h>\n// convex hull\n#include <CGAL/convex_hull_2.h>\n// polyline simplification\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/Polyline_simplification_2/Squared_distance_cost.h>\n// curve reconstruction from unorganized point set\n#include <CGAL/Optimal_transportation_reconstruction_2.h>\n// random point generator\n#include <CGAL/point_generators_2.h>\n\ndouble CGeoCalculator::ComputeDistFromPoint2Plane(COpenMeshT::Point p, COpenMeshT::Point b, COpenMeshT::Point n)\n{\n\t// assert n is a unit vector\n\tassert((n.norm() - 1.0) < 10e-5);\n\n\tCOpenMeshT::Point v = p - b;\n\treturn innerProduct(v, n);\n}\n\ndouble CGeoCalculator::ComputeLinearity(std::vector<COpenMeshT::Point> p_list)\n{\n\tif (p_list.size() < 3)\n\t{\n\t\treturn 1.0;\n\t}\n\telse\n\t{\n\t\tstd::vector<std::vector<double>> eigenvectors;\n\t\tstd::vector<double> lambda;\n\t\tComputePCAwithSVD(p_list, eigenvectors, lambda);\n\t\t//ComputePCAwithEIG(p_list, eigenvectors, lambda);\n\t\treturn lambda[0] / (lambda[0] + lambda[1] + lambda[2]);\n\t}\n}\n\ndouble CGeoCalculator::ComputeLineLinearity(std::vector<COpenMeshT::Point> p_list, COpenMeshT::Point ctr, COpenMeshT::Point dir)\n{\n\tdouble sum_dev = 0.0;\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tdouble dev = (p_list[i] - ctr - innerProduct(p_list[i] - ctr, dir)*dir).norm();\n\t\tsum_dev += dev;\n\t}\n\tstd::cout << \"center = \" << ctr << std::endl;\n\tstd::cout << \"direction = \" << dir << std::endl;\n\tstd::cout << sum_dev <<\" \"<< p_list.size() << std::endl;\n\tsum_dev /= double(p_list.size());\n\treturn sum_dev;\n}\n\nvoid CGeoCalculator::FittingLineSegmentToPointSet(std::vector<COpenMeshT::Point> p_list, COpenMeshT::Point & pstart, COpenMeshT::Point & pend)\n{\n\t// base \n\tCOpenMeshT::Point base(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tbase += p_list[i];\n\t}\n\tbase = base / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tp_list[i] -= base;\n\t}\n\n\t// get line direction\n\tstd::vector<double> direction;\n\tComputePrincipalDirection(p_list, direction);\n\n\tstd::cout << \"line direction: \";\n\tstd::copy(direction.begin(), direction.end(), std::ostream_iterator<double>(std::cout, \" \"));\n\tstd::cout << std::endl;\n\n\t// project every point to direction and find the max and min parameters\n\tdouble max_t = 0, min_t = 0;\n\tCOpenMeshT::Point v(direction[0], direction[1], direction[2]);\n\tfor (int i = 0; i < p_list.size(); i++) {\n\t\tdouble t = innerProduct(v, p_list[i]);\n\t\tstd::cout << \"t = \" << t << std::endl;\n\t\tif (t > max_t)\n\t\t\tmax_t = t;\n\t\tif (t < min_t)\n\t\t\tmin_t = t;\n\t}\n\tstd::cout << \"min_t = \"<< min_t << \", max_t = \" << max_t << std::endl;\n\t// output\n\tpstart = base + v*min_t;\n\tpend = base + v*max_t;\n}\n\nvoid CGeoCalculator::FittingLineSegmentToPointSet(std::vector<COpenMeshT::Point> p_list, \n\tCOpenMeshT::Point base, COpenMeshT::Point dir, \n\tCOpenMeshT::Point & pstart, COpenMeshT::Point & pend)\n{\n\t// base \n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tp_list[i] -= base;\n\t}\n\t// project every point to direction and find the max and min parameters\n\tdouble max_t = 0, min_t = 0;\n\tfor (int i = 0; i < p_list.size(); i++) {\n\t\tdouble t = innerProduct(dir, p_list[i]);\n\t\tstd::cout << \"t = \" << t << std::endl;\n\t\tif (t > max_t)\n\t\t\tmax_t = t;\n\t\tif (t < min_t)\n\t\t\tmin_t = t;\n\t}\n\tstd::cout << \"min_t = \" << min_t << \", max_t = \" << max_t << std::endl;\n\t// output\n\tpstart = base + dir*min_t;\n\tpend = base + dir*max_t;\n}\n\nvoid CGeoCalculator::FittingPlaneToPointSet(std::vector<COpenMeshT::Point> p_list, std::vector<double>& transform)\n{\n\ttransform.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\n\t\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\t\n\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(P, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tV = svd.matrixV();\n\n\tEigen::Vector3d n = V.col(2);\n\tn.normalized();\n\ttransform.push_back(n[0]);\n\ttransform.push_back(n[1]);\n\ttransform.push_back(n[2]);\n}\n\nvoid CGeoCalculator::ComputePrincipalDirection(std::vector<COpenMeshT::Point> p_list, std::vector<double>& transform)\n{\n\ttransform.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(P, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tV = svd.matrixV();\n\n\t//std::cout << \"P = [\" << P << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\tEigen::Vector3d n = V.col(0);\n\tn.normalized();\n\ttransform.push_back(n[0]);\n\ttransform.push_back(n[1]);\n\ttransform.push_back(n[2]);\n}\n\nvoid CGeoCalculator::ComputePCAwithEIG(std::vector<COpenMeshT::Point> p_list, \n\tstd::vector<std::vector<double>>& eigenvectors, std::vector<double>& eigenvalues)\n{\n\teigenvectors.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\tEigen::MatrixXd S(Dim, Dim);\n\n\t// construct\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\n\tEigen::MatrixXd Pt = P.transpose();\n\tEigen::MatrixXd PtP = P.transpose() * P;\n\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver(PtP);\n\tS = eigen_solver.eigenvalues().asDiagonal();\n\tV = eigen_solver.eigenvectors();\n\n\t//std::cout << \"using ComputePCAwithEIG function\" << std::endl;\n\t//std::cout << \"S = [\" << S << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\t// make it in the descending order\n\tfor (int i = Dim; i > 0; i--)\n\t{\n\t\tstd::vector<double> tmp_vector;\n\t\tEigen::Vector3d n = V.col(i-1);\n\t\tn.normalized();\n\t\ttmp_vector.push_back(n[0]);\n\t\ttmp_vector.push_back(n[1]);\n\t\ttmp_vector.push_back(n[2]);\n\t\teigenvectors.push_back(tmp_vector);\n\t\teigenvalues.push_back(S(i-1, i-1));\n\t}\n}\n\nvoid CGeoCalculator::ComputePCAwithSVD(std::vector<COpenMeshT::Point> p_list, \n\tstd::vector<std::vector<double>>& eigenvectors, std::vector<double>& eigenvalues)\n{\n\teigenvectors.clear();\n\teigenvalues.clear();\n\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\tEigen::VectorXd S(Dim);\n\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\tEigen::MatrixXd CovP = P.transpose() * P;\n\tCovP = CovP / double(p_list.size());\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(CovP, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tV = svd.matrixV();\n\tS = svd.singularValues();\n\n\t//std::cout << \"using ComputePCAwithSVD function\" << std::endl;\n\t//std::cout << \"S = [\" << S << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tstd::vector<double> tmp_vector;\n\t\tEigen::Vector3d n = V.col(i);\n\t\tn.normalized();\n\t\ttmp_vector.push_back(n[0]);\n\t\ttmp_vector.push_back(n[1]);\n\t\ttmp_vector.push_back(n[2]);\n\t\teigenvectors.push_back(tmp_vector);\n\t\tdouble s = sqrt(S(i));\n\t\teigenvalues.push_back(s);\n\t}\n}\n\nvoid CGeoCalculator::ProjectPointToPlane(COpenMeshT::Point point, std::vector<double> plane, COpenMeshT::Point & projection)\n{\n\tdouble d = point[0] * plane[0] + point[1] * plane[1] + point[2] * plane[2] + plane[3];\n\tCOpenMeshT::Point v(plane[0] * d, plane[1] * d, plane[2] * d);\n\tprojection = point - v;\n}\n\ndouble CGeoCalculator::ComputeDistPointToLine(COpenMeshT::Point q, COpenMeshT::Point sp, COpenMeshT::Point tp)\n{\n\tCOpenMeshT::Point dir = tp - sp;\n\tdir /= dir.norm();\n\treturn (q - sp - innerProduct(q - sp, dir)*dir).norm();\n}\n\nvoid CGeoCalculator::givensTransform(double x, double y, std::vector<double>& g)\n{\n\tdouble absx = fabs(x);\n\tdouble c, s;\n\n\tif (absx == 0.0)\n\t{\n\t\tc = 0.0; s = 1.0;\n\t}\n\telse {\n\t\tdouble nrm = Eigen::Vector2d(x, y).norm();\n\t\tc = absx / nrm;\n\t\ts = x / absx*(y / nrm);\n\t}\n\tg.push_back(c);\n\tg.push_back(s);\n}\n\nvoid CGeoCalculator::computeOBB(const std::vector<COpenMeshT::Point> & pts, std::vector<double> & out_obb)\n{\n\ttypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ttypedef K::Point_2\t\t\t\t\t\t\t\tPoint_2;\n\ttypedef CGAL::Polygon_2<K>\t\t\t\t\t\tPolygon_2;\n\n\tstd::vector<Point_2> pointset;\n\tfor (int i = 0; i < pts.size(); i++)\n\t{\n\t\tpointset.push_back(Point_2(pts[i][1], pts[i][2]));\n\t}\n\n\tPolygon_2 ch, obb;\n\tCGAL::convex_hull_2(pointset.begin(), pointset.end(), std::back_inserter(ch));\n\tCGAL::min_rectangle_2(ch.vertices_begin(), ch.vertices_end(), std::back_inserter(obb));\n\tout_obb.clear();\n\tout_obb.push_back(obb.bbox().xmin());\n\tout_obb.push_back(obb.bbox().xmax());\n\tout_obb.push_back(obb.bbox().ymin());\n\tout_obb.push_back(obb.bbox().xmax());\n}\n\nstd::vector<double>  CGeoCalculator::getBernsteinBasis(int n, double step, Eigen::MatrixXd & Bmat)\n{\n\t// parameters\n\tstd::vector<double> t;\n\tdouble it = 0.0;\n\tt.push_back(it);\n\twhile (it < 1)\n\t{\n\t\tit += step;\n\t\tt.push_back(it);\n\t}\n\tif (fabs(t.back() - 1.0) > 0.00001)\n\t\tt.push_back(1.0);\n\n\t//for (int i = 0; i < t.size(); i++)\n\t//\tstd::cout << t[i] << std::endl;\n\n\tBmat.resize(t.size(), n);\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfor (int i = 0; i < t.size(); i++) {\n\t\t\tdouble c = CGeoCalculator::nchoosek(n - 1, j);\n\t\t\tBmat(i, j) = c*pow(t[i], j)*pow((1.0-t[i]), (n - 1 - j));\n\t\t}\n\t}\n\n\treturn t;\n}\n\nvoid CGeoCalculator::getBernsteinBasis(int n, std::vector<double> t, Eigen::MatrixXd & Bmat)\n{\n\tBmat.resize(t.size(), n);\n\tBmat.setZero();\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfor (int i = 0; i < t.size(); i++) {\n\t\t\tdouble c = CGeoCalculator::nchoosek(n - 1, j);\n\t\t\tBmat(i, j) = c*pow(t[i], j)*pow((1.0 - t[i]), (n - 1 - j));\n\t\t}\n\t}\n}\n\nvoid CGeoCalculator::getSampleFromBezier(\n\tEigen::MatrixXd & sample_pts, \n\tEigen::MatrixXd & ctrl_pts,\n\tdouble step)\n{\n\tint numCPs = ctrl_pts.rows();\n\tEigen::MatrixXd Bmat;\n\tgetBernsteinBasis(numCPs, step, Bmat);\n\tsample_pts = Bmat*ctrl_pts;\n}\n\nvoid CGeoCalculator::getEqualArcLengthSampleFromBezier(\n\tstd::vector<COpenMeshT::Point>& om_sample_pts, \n\tstd::vector<double>& tparas,\n\tconst std::vector<COpenMeshT::Point>& om_ctrl_pts, int Nsamples)\n{\n\tom_sample_pts.clear();\n\ttparas.clear();\n\n\tEigen::MatrixXd ctrl_pts;\n\tconvertOMptToEigenMat(om_ctrl_pts, ctrl_pts);\n\n\tint numCPs = ctrl_pts.rows();\n\tEigen::MatrixXd Bmat;\n\tdouble dt = 0.0001;\n\tstd::vector<double> ts;\n\tts = getBernsteinBasis(numCPs, dt, Bmat);\n\t// get total arc length\n\tEigen::MatrixXd dense_pts;\n\tdense_pts = Bmat*ctrl_pts;\n\tdouble total_length = 0.0;\n\tfor (int i = 1; i < dense_pts.rows(); i++)\n\t{\n\t\ttotal_length += (dense_pts.row(i) - dense_pts.row(i - 1)).norm();\n\t}\n\tdouble dD = total_length / double(Nsamples);\n\tdouble accum_length = 0.0;\n\tstd::vector<double> t_samples;\n\tt_samples.push_back(0);\n\tfor (int i = 1; i < dense_pts.rows(); i++)\n\t{\n\t\tif (accum_length > dD) {\n\t\t\t//std::cout << accum_length << \", \" << dD << std::endl;\n\t\t\tt_samples.push_back(ts[i]);\n\t\t\taccum_length = 0.0;\n\t\t}\n\t\telse {\n\t\t\taccum_length += (dense_pts.row(i) - dense_pts.row(i - 1)).norm();\n\t\t}\n\t}\n\tt_samples.push_back(1.0);\n\tgetBernsteinBasis(numCPs, t_samples, Bmat);\n\tEigen::MatrixXd sample_pts;\n\tsample_pts = Bmat*ctrl_pts;\n\n\t// convert sample_pts to om_pts;\n\tconvertEigenMatToOMpt(sample_pts, om_sample_pts);\n\ttparas = t_samples;\n}\n\ndouble CGeoCalculator::nchoosek(int n, int k)\n{\n\tif (k < 0 || k > n) {\n\t\tstd::cerr << \"Error: k should be less than n\" << std::endl;\n\t\treturn 0;\n\t}\n\tif (k == 0) {\n\t\treturn 1;\n\t}\n\treturn (n * nchoosek(n - 1, k - 1)) / k;\n}\n\nvoid CGeoCalculator::convertOMptToEigenMat(const std::vector<COpenMeshT::Point> om_pts, Eigen::MatrixXd & Mat)\n{\n\tstd::vector<double> om_pt_vec;\n\tfor (int i = 0; i < om_pts.size(); i++)\n\t{\n\t\tom_pt_vec.push_back(om_pts[i][0]);\n\t\tom_pt_vec.push_back(om_pts[i][1]);\n\t\tom_pt_vec.push_back(om_pts[i][2]);\n\t}\n\tMat = Eigen::Map<Eigen::MatrixXd, Eigen::Unaligned>\n\t\t(om_pt_vec.data(), 3, om_pt_vec.size() / 3);\n\tMat.transposeInPlace();\n}\n\nvoid CGeoCalculator::convertEigenMatToOMpt(const Eigen::MatrixXd & Mat, std::vector<COpenMeshT::Point>& om_pts)\n{\n\tom_pts.clear();\n\tfor (int i = 0; i < Mat.rows(); i++)\n\t{\n\t\tCOpenMeshT::Point pt(Mat(i, 0), Mat(i, 1), Mat(i, 2));\n\t\tom_pts.push_back(pt);\n\t}\n}\n\nvoid CGeoCalculator::pts_sorting_alg(std::vector<COpenMeshT::Point>& pts)\n{\n\t// use delaunay to compute the visibility graph\n\tdouble xCoord = pts[0][0];\n\tDelaunayT dt;\n\tfor (int i = 0; i < pts.size(); i++)\n\t{\n\t\tKPoint2 kp(pts[i][1], pts[i][2]);\n\t\tdt.insert(kp);\n\t}\n\n\tCOpenMeshT triMesh;\n\tstd::map<DelaunayT::Vertex_handle, COpenMeshT::VertexHandle> cgal_om_vh_map;\n\tstd::vector<std::vector<DelaunayT::Vertex_handle>> f_vhandles_cgal;\n\tfor (DelaunayT::Finite_faces_iterator fiter = dt.finite_faces_begin();\n\t\tfiter != dt.finite_faces_end(); ++fiter)\n\t{\n\t\tstd::vector<COpenMeshT::VertexHandle> vhandles;\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tDelaunayT::Vertex_handle vh_cgal = fiter->vertex(i);\n\t\t\tif (cgal_om_vh_map.find(vh_cgal) == cgal_om_vh_map.end()) {\n\t\t\t\tCOpenMeshT::VertexHandle vh_om =\n\t\t\t\t\ttriMesh.add_vertex(COpenMeshT::Point(0, vh_cgal->point().x(), vh_cgal->point().y()));\n\t\t\t\tcgal_om_vh_map[vh_cgal] = vh_om;\n\t\t\t\tvhandles.push_back(vh_om);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCOpenMeshT::VertexHandle vh_om = cgal_om_vh_map[vh_cgal];\n\t\t\t\tvhandles.push_back(vh_om);\n\t\t\t}\n\t\t}\n\t\ttriMesh.add_face(vhandles);\n\t}\n\n\tCOpenMeshT::VertexHandle seed_vh;\n\tfor (COpenMeshT::VertexIter viter = triMesh.vertices_begin(); viter != triMesh.vertices_end(); ++viter)\n\t{\n\t\tif (triMesh.is_boundary(*viter))\n\t\t{\n\t\t\tseed_vh = *viter;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::vector<COpenMeshT::VertexHandle> b_vertices;\n\tauto next_vh = seed_vh;\n\tdo {\n\t\tb_vertices.push_back(next_vh);\n\t\tfor (COpenMeshT::VertexOHalfedgeCCWIter voh_ccwiter = triMesh.voh_ccwbegin(next_vh);\n\t\t\tvoh_ccwiter != triMesh.voh_ccwend(next_vh); ++voh_ccwiter)\n\t\t{\n\t\t\tif (triMesh.is_boundary(*voh_ccwiter))\n\t\t\t{\n\t\t\t\tnext_vh = triMesh.to_vertex_handle(*voh_ccwiter);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} while (next_vh != seed_vh);\n\n\t// output\n\tpts.clear();\n\t//std::cout << b_vertices.size() << std::endl;\n\tfor (int i = 0; i < b_vertices.size(); i++)\n\t{\n\t\tCOpenMeshT::Point p = triMesh.point(b_vertices[i]);\n\t\tp[0] = xCoord;\n\t\tpts.push_back(p);\n\t\t//std::cout << p[1] << \" \" << p[2] << std::endl;\n\t}\n\n}\n\nvoid CGeoCalculator::simplify_polygon(std::vector<COpenMeshT::Point>& pts, double dT)\n{\n\tnamespace PS = CGAL::Polyline_simplification_2;\n\ttypedef PS::Stop_above_cost_threshold\t\tStop;\n\ttypedef PS::Squared_distance_cost\t\t\tCost;\n\n\tdouble xCoord = pts[0][0];\n\tKPolygon2 polygon;\n\tfor (int i = 0; i < pts.size(); i++)\n\t\tpolygon.push_back(KPoint2(pts[i][1], pts[i][2]));\n\n\tCost cost;\n\tpolygon = PS::simplify(polygon, cost, Stop(dT));\n\n\tpts.clear();\n\tfor (int i = 0; i < polygon.size(); i++) {\n\t\tpts.push_back(COpenMeshT::Point(xCoord, polygon[i].x(), polygon[i].y()));\n\t}\n}\n\nvoid CGeoCalculator::sample_polygon(std::vector<COpenMeshT::Point>& pts, double spacing, bool is_closed)\n{\n\tif (is_closed)\n\t\tpts.push_back(pts.front());\n\tstd::vector<COpenMeshT::Point> samples;\n\n\t// step size = ssz\n\tdouble alength = 0.0;\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\talength += (pts[i] - pts[i + 1]).norm();\n\t}\n\tdouble ssz = alength*spacing;\n\n\t// sample\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\tdouble t_alength = (pts[i] - pts[i + 1]).norm();\n\t\tint cnt = 0;\n\t\tdouble t = 0.0;\n\t\twhile (t < 1.0)\n\t\t{\n\t\t\tCOpenMeshT::Point pt = pts[i] + t * (pts[i + 1] - pts[i]);\n\t\t\tif ((pt - pts[i + 1]).norm() > ssz) {\n\t\t\t\tsamples.push_back(pt);\n\t\t\t}\n\t\t\tcnt++;\n\t\t\tt = double(cnt)*ssz / t_alength;\n\t\t}\n\t}\n\n\t//if (is_closed)\n\t//\tsamples.push_back(samples.front());\n\tpts = samples;\n}\n\nvoid CGeoCalculator::sample_polygon_parameters(std::vector<double> &tparas, \n\tconst std::vector<COpenMeshT::Point> pts, double spacing, bool is_closed)\n{\n\ttparas.clear();\n\tstd::vector<COpenMeshT::Point> in_pts;\n\tif (is_closed)\n\t\tin_pts.push_back(pts.front());\n\n\t// step size = ssz\n\tdouble alength = 0.0;\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\talength += (pts[i] - pts[i + 1]).norm();\n\t}\n\tdouble ssz = alength*spacing;\n\n\t// sample\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\tdouble t_alength = (pts[i] - pts[i + 1]).norm();\n\t\tint cnt = 0;\n\t\tdouble t = 0.0;\n\t\twhile (t < 1.0)\n\t\t{\n\t\t\tCOpenMeshT::Point pt = pts[i] + t * (pts[i + 1] - pts[i]);\n\t\t\tif ((pt - pts[i + 1]).norm() > ssz) {\n\t\t\t\ttparas.push_back(t);\n\t\t\t}\n\t\t\tcnt++;\n\t\t\tt = double(cnt)*ssz / t_alength;\n\t\t}\n\t}\n\t//tparas.push_back(1.0);\n}\n\nvoid CGeoCalculator::sample_polygon_with_parameters(std::vector<double> tparas,\n\tstd::vector<COpenMeshT::Point> cs_pts, std::vector<COpenMeshT::Point> &out_pts, bool is_closed)\n{\n\t//\n\tout_pts.clear();\n\tif (is_closed)\n\t\tcs_pts.push_back(cs_pts.front());\n\n\t// sample\n\tint pid = 0;\n\tfor (int i = 0; i < tparas.size(); i++)\n\t{\n\t\tdouble t = tparas[i];\n\t\tif (t == 0.0) pid++;\n\t\tCOpenMeshT::Point pt = cs_pts[pid-1] + t * (cs_pts[pid] - cs_pts[pid-1]);\n\t\tout_pts.push_back(pt);\n\t}\n}\n\nvoid CGeoCalculator::reconstruct_curve_from_pointset(std::vector<COpenMeshT::Point> &pts, float tolOMT)\n{\n\ttypedef CGAL::Optimal_transportation_reconstruction_2<K>    Otr_2;\n\tstd::vector<KPoint2> points;\n\tfor (int i = 0; i < pts.size(); i++)\n\t\tpoints.push_back(KPoint2(pts[i][1], pts[i][2]));\n\n\tstd::cout << \"init pts: \" << points.size() << std::endl;\n\tif (points.size() == 0)\n\t\treturn;\n\n\tstd::vector<double> obb;\n\tcomputeOBB(pts, obb);\n\tdouble dl = (std::max)((obb[1] - obb[0]) / 2.,\n\t\t(obb[3] - obb[2]) / 2.);\n\ttolOMT = dl*tolOMT;\n\tstd::cout << \"tolOMT: \" << tolOMT << std::endl;\n\tOtr_2 otr2(points);\n\t//otr2.set_random_sample_size(15);\n\t//otr2.set_relevance(0.3);\n\tstd::vector<KPoint2> ptss;\n\tstd::vector<std::size_t> isolated_vertices;\n\tstd::vector<std::pair<std::size_t, std::size_t> > edges;\n\tint cntIter = 0;\n\t//float tolOMT = 0.6;\n\totr2.run_under_wasserstein_tolerance(tolOMT);\n\n\totr2.indexed_output(\n\t\tstd::back_inserter(ptss),\n\t\tstd::back_inserter(isolated_vertices),\n\t\tstd::back_inserter(edges));\n\tstd::cout << \"(-------------List output---------- )\" << tolOMT << \" \" << cntIter << std::endl;\n\t// points\n\tstd::vector<KPoint2>::iterator pit;\n\tfor (pit = ptss.begin(); pit != ptss.end(); pit++)\n\t\tstd::cout << *pit << std::endl;\n\t// isolated vertices\n\tstd::vector<std::size_t>::iterator vit;\n\tfor (vit = isolated_vertices.begin(); vit != isolated_vertices.end(); vit++)\n\t\tstd::cout << \"1 \" << *vit << std::endl;\n\t// edges\n\tstd::vector<std::pair<std::size_t, std::size_t> >::iterator eit;\n\tfor (eit = edges.begin(); eit != edges.end(); eit++)\n\t\tstd::cout << \"2 \" << eit->first << \" \" << eit->second << std::endl;\n\n\t//KPoint2 orig(0.0, 0.0);\n\t//for (eit = edges.begin(); eit != edges.end(); eit++)\n\t//{\n\t//\tKVector2 v12 = ptss[eit->second] - ptss[eit->first];\n\t//\tKVector2 v01 = ptss[eit->first] - orig;\n\t//\tdouble a = v01.x*v12*\n\t//}\n\n\n\t\n\n}", "meta": {"hexsha": "40e719c3027214517f54d7f3362706b31c9bbd21", "size": 19454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeneralTools/geo_calculator.cpp", "max_stars_repo_name": "LeiYangJustin/LibSST", "max_stars_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeneralTools/geo_calculator.cpp", "max_issues_repo_name": "LeiYangJustin/LibSST", "max_issues_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeneralTools/geo_calculator.cpp", "max_forks_repo_name": "LeiYangJustin/LibSST", "max_forks_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_forks_repo_licenses": ["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.0947075209, "max_line_length": 142, "alphanum_fraction": 0.6388403413, "num_tokens": 6592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6507126349288745}}
{"text": "#include \"NewtonMethodEqNode.h\"\n#include <cmath>\n#include <Eigen/Dense>\n\nvoid NewtonEqNode::solve(EqNodePtr& root, EqNodePtr var)\n{\n\tEqNodePtr derivRoot;\n\tdouble x1, x2, f1, tol, df1, err;\n\tint kmax, k;\n\n\ttol = 1e-8;\n\tkmax = 100;\n\n\tx1 = var->getValue();\n\tf1 = root->getValue();\n\tdf1 = root->getDerValue(*var);\n\n\tfor (k = 0; k < kmax; k++) {\n\t\tx2 = x1 - f1 / df1;\n\t\terr = abs(x2 - x1);\n\n\t\tvar->v = x2;\n\t\tx1 = x2;\n\t\tif (err < tol)\n\t\t\treturn;\n\n\t\tf1 = root->getValue();\n\t\tdf1 = root->getDerValue(*var);\n\t}\n}\n\nvoid NewtonEqNode::NLASolve(const int& n, std::vector< EqNodePtr >& eqs,\n\tstd::vector < EqNodePtr >& vars, const double& tol)\n{\n\tint kmax, k;\n\tEigen::MatrixXd Jac(n, n);\n\tEigen::VectorXd F(n), x(n);\n\tEigen::VectorXd delta(n);\n\n\tkmax = 300;\n\tdouble err = 0;\n\n\tfor (const auto& var : vars)\n\t\tvar->correctValueInsideBoundaries();\n\n\tfor (k = 0; k < kmax; ++k) {\n\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tx[i] = vars[i]->v;\n\t\t\tF[i] = eqs[i]->getValue();\n\t\t\tfor (int j = 0; j < n; ++j)\n\t\t\t\tJac(i, j) = eqs[i]->getDerValue(*vars[j]);\n\t\t}\n\n\t\t// Solve linear system\n\t\tdelta = Jac.fullPivLu().solve(-F);\n\t\t// Update x values\n\t\tx = x + delta;\n\n\t\tfor (int i = 0; i < n; ++i) vars[i]->v = x[i];\n\n\t\t// criterion for stop\n\t\t// get max abs value of function\n\t\terr = 0.0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\terr = err < std::abs(F[i]) ? abs(F[i]) : err;\n\t\t\terr = err < std::abs(delta[i]) ? abs(delta[i]) : err;\n\t\t}\n\n\t\tif (err < tol) return;\n\n\t\tfor (auto& var : vars) var->correctValueInsideBoundaries();\n\t}\n}\n", "meta": {"hexsha": "5a1ff1dcb9dd949b426c6ed702c8c62ce10d4719", "size": 1490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_stars_repo_name": "marcusbfs/HydroModel", "max_stars_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_issues_repo_name": "marcusbfs/HydroModel", "max_issues_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_forks_repo_name": "marcusbfs/HydroModel", "max_forks_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_forks_repo_licenses": ["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.8666666667, "max_line_length": 72, "alphanum_fraction": 0.5657718121, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6507126329449053}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/componentwise_equal.hpp>\n#include <fcppt/math/matrix/inverse.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <limits>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_inverse\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tdouble,\n\t\t3,\n\t\t3\n\t>\n\tlarge_matrix_type;\n\n\tBOOST_CHECK((\n\t\tfcppt::math::matrix::componentwise_equal(\n\t\t\tfcppt::math::matrix::inverse(\n\t\t\t\tlarge_matrix_type(\n\t\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t\t0.,1.,2.\n\t\t\t\t\t),\n\t\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t\t1.,0.,3.\n\t\t\t\t\t),\n\t\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t\t4.,-3.,8.\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t),\n\t\t\tlarge_matrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t-9./2.,7.,-3./2.\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t-2.,4.,-1.\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t3./2.,-2.,1./2.\n\t\t\t\t)\n\t\t\t),\n\t\t\tstd::numeric_limits<\n\t\t\t\tdouble\n\t\t\t>::epsilon()\n\t\t)\n\t));\n}\n", "meta": {"hexsha": "e2610cf72b87bddd05120c9f5dc1f51cd7273a89", "size": 1442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/inverse.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/inverse.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/inverse.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8985507246, "max_line_length": 61, "alphanum_fraction": 0.6546463245, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029117, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6506593874405774}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <boost/numeric/odeint.hpp>\n#include \"helper_func.h\"\n#include \"LongDynamics.h\"\n#include \"EKF.h\"\n\nint main()\n{\n    // Define the dataset path\n    const std::string dataset_path{\"../data/aircraft_long_dynamics_dataset.txt\"};\n\n    // Load dataset\n    const int dataset_size = 1001;\n    Eigen::VectorXd elev_input(dataset_size);\n    Eigen::VectorXd throttle_input(dataset_size);\n    Eigen::VectorXd alpha_true(dataset_size);\n    Eigen::VectorXd alpha_measured(dataset_size);\n    Eigen::VectorXd pitch_rate_true(dataset_size);\n    Eigen::VectorXd pitch_rate_measured(dataset_size);\n    LoadDataSet(dataset_path, elev_input, throttle_input, alpha_true, \n                alpha_measured, pitch_rate_true, pitch_rate_measured);\n    \n    // Create a csv file to save output data\n    std::ofstream outputs_file;\n    std::string filename = \"outputs.csv\";\n    outputs_file.open(filename);\n    outputs_file << \"time\" << \",\" << \"true_alpha\" << \",\" << \"measured_alpha\" \n                << \",\" << \"estimated_alpha\" << \",\" << \"true_q\" << \",\" \n                << \"measured_q\" << \",\" << \"estimated_q\" << std::endl;\n    \n    // Define dynamic system parameters\n    int num_state = 4;\n    int num_input = 2;\n    int num_output = 2;\n    const double sample_time = 0.01;\n    Eigen::MatrixXd Q(num_state, num_state); // Process noise covariance matrix\n    Q << 0.0001, 0.0   , 0.0     , 0.0,\n         0.0   , 0.0001, 0.0     , 0.0,\n         0.0   , 0.0   , 0.000001, 0.0,\n         0.0   , 0.0   , 0.0     , 0.0;\n\n    Eigen::MatrixXd R(num_output, num_output); // Measurment noise covariance matrix\n    R << 0.00001, 0.0,\n         0.0    , 0.00001;\n\n    Eigen::MatrixXd P0(num_state, num_state); // Initial estimate error covariance matrix\n    P0 << 0.0001, 0.0   , 0.0     , 0.0,\n         0.0   , 0.0001, 0.0     , 0.0,\n         0.0   , 0.0   , 0.000001, 0.0,\n         0.0   , 0.0   , 0.0     , 0.0;\n\n    // Construct EKF object\n    EKF ekf(Q, R, P0, sample_time);\n\n    // Define integration class and a stepper integrator\n    state_type x(num_state);\n    LongDynamics long_dyn_object;\n    boost::numeric::odeint::runge_kutta4<state_type> rk4_stepper;\n\n    // Define vectors to hold the estimated outputs and the integrator predicted state\n    Eigen::VectorXd alpha_estimated(dataset_size);\n    Eigen::VectorXd pitch_rate_estimated(dataset_size);\n    Eigen::VectorXd predicted_state(num_state);\n\n    // Initialize the state\n    predicted_state << 74.9167 + 0.03,\n                       3.5330 + 0.03,\n                       0.0 +0.001,\n                       2.7 * PI / 180;\n\n    // Run the filter on the dataset of I/O\n    Eigen::VectorXd y(num_output);\n    Eigen::VectorXd u(num_input);\n    double t = 0.0;\n    std::cout << \"Processing dataset...\" << std::endl;\n    for (int i = 0; i < dataset_size; i++)\n    {\n        // Run EKF for one step\n        y << alpha_measured(i),\n             pitch_rate_measured(i);\n        u << elev_input(i),\n             throttle_input(i);\n        ekf.Update(y, u, predicted_state);\n        alpha_estimated(i) = ekf.GetEstimatedOutput()(0);\n        pitch_rate_estimated(i) = ekf.GetEstimatedOutput()(1);\n\n        // Save outputs to the csv file\n        outputs_file << sample_time * i << \",\" \n                     << alpha_true(i) * 180.0 / PI << \",\" \n                     << alpha_measured(i) * 180.0 / PI << \",\" \n                     << alpha_estimated(i) * 180.0 / PI << \",\" \n                     << pitch_rate_true(i) * 180.0 / PI << \",\" \n                     << pitch_rate_measured(i) * 180.0 / PI << \",\" \n                     << pitch_rate_estimated(i) * 180.0 / PI << std::endl;\n\n        // Pass the updated state back to the integrator\n        x[0] = ekf.GetState()(0);\n        x[1] = ekf.GetState()(1);\n        x[2] = ekf.GetState()(2);\n        x[3] = ekf.GetState()(3);\n        \n        // Run the integrator for one step and get the new state\n        t = sample_time * i;\n        rk4_stepper.do_step(long_dyn_object, x, t, sample_time);\n        predicted_state(0) = x[0];\n        predicted_state(1) = x[1];\n        predicted_state(2) = x[2];\n        predicted_state(3) = x[3];       \n    }\n    std::cout << \"Finished processing dataset\" << std::endl;\n\n    // Close the output csv file\n    outputs_file.close();\n\n    // Compute and print root mean square error for the estimated outputs (angle of attack and pitch rate)\n    std::cout << \"RMSE for the estimated AoA is: \" << ComputeRMSE(alpha_true, alpha_estimated) << std::endl;\n    std::cout << \"RMSE for the estimated pitch rate is: \" << ComputeRMSE(pitch_rate_true, pitch_rate_estimated) << std::endl;\n}", "meta": {"hexsha": "e79a33b1bb786deae4b94518f60844b12da0bf3f", "size": 4658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_stars_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T14:22:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T14:34:59.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_issues_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_issues_repo_licenses": ["MIT"], "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": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_forks_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T04:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T04:23:17.000Z", "avg_line_length": 38.4958677686, "max_line_length": 125, "alphanum_fraction": 0.5832975526, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6506593844089575}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXf A(MatrixXf::Random(5,3)), thinQ(MatrixXf::Identity(5,3)), Q;\nA.setRandom();\nHouseholderQR<MatrixXf> qr(A);\nQ = qr.householderQ();\nthinQ = qr.householderQ() * thinQ;\nstd::cout << \"The complete unitary matrix Q is:\\n\" << Q << \"\\n\\n\";\nstd::cout << \"The thin matrix Q is:\\n\" << thinQ << \"\\n\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "7fe79415069ca944571f012351ebe03972893d90", "size": 784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_HouseholderQR_householderQ.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_HouseholderQR_householderQ.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_HouseholderQR_householderQ.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 28.0, "max_line_length": 224, "alphanum_fraction": 0.6683673469, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6505976266590839}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\r\ntypedef math_types::vector_type                                vector_type;\r\ntypedef std::vector<double>                                    knot_container;\r\ntypedef std::vector<vector_type>                               point_container;\r\n\r\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_insert_knot);\r\n\r\nBOOST_AUTO_TEST_CASE(test_insert_knot)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 4\r\n  U.push_back(1.0);\r\n  U.push_back(2.0);\r\n  U.push_back(3.0);  // n = 6  => |P| = 7\r\n  U.push_back(4.0);\r\n  U.push_back(4.0);\r\n  U.push_back(4.0);  \r\n  U.push_back(4.0);  // m = 10  => |U| = 11\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n  vector_type p4(2);  p4(0) = 4.0; p4(1) = 0.0;\r\n  vector_type p5(2);  p5(0) = 5.0; p5(1) = 0.0;\r\n  vector_type p6(2);  p6(0) = 6.0; p6(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n  P.push_back(p4);\r\n  P.push_back(p5);\r\n  P.push_back(p6);\r\n\r\n  spline_type spline(4,U,P);\r\n\r\n  double const tolerance = 0.00001;\r\n  double const u = 2.5;\r\n\r\n  knot_container const & UU = spline.get_knot_container();\r\n  point_container const & PP = spline.get_control_container();\r\n\r\n  //--- Before insertion\r\n  BOOST_CHECK_CLOSE(UU[0], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[1], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[2], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[3], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[4], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[5], 2.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[6], 3.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[7], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[8], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[9], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UU[10], 4.0,  tolerance);\r\n  BOOST_CHECK( UU.size() == 11 );\r\n  BOOST_CHECK( PP.size() == 7 );\r\n\r\n  //--- After insertion\r\n  OpenTissue::spline::insert_knot(u,spline);\r\n\r\n  knot_container const & UUU = spline.get_knot_container();\r\n  point_container const & PPP = spline.get_control_container();\r\n\r\n  BOOST_CHECK_CLOSE(UUU[0], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[1], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[2], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[3], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[4], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[5], 2.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[6], 2.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[7], 3.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[8], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[9], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[10], 4.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(UUU[11], 4.0,  tolerance);\r\n\r\n  for(int i=0;i<8;++i)\r\n    BOOST_CHECK_CLOSE(PPP[i](1), 0.0,  tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(PPP[0](0), 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[1](0), 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[2](0), 2.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[3](0), 2.833333333333333,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[4](0), 3.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[5](0), 4.25,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[6](0), 5.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(PPP[7](0), 6.0,  tolerance);\r\n\r\n  BOOST_CHECK( UUU.size() == 12 );\r\n  BOOST_CHECK( PPP.size() == 8 );\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(test_bezier_curve_case)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  \r\n  U.push_back(0.0);   \r\n  U.push_back(1.0);\r\n  U.push_back(1.0);\r\n  U.push_back(1.0);  \r\n  U.push_back(1.0);  \r\n\r\n  // k = 4\r\n  // n = 3  => |P| = 4\r\n  // m = 7  => |U| = 8\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 1.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 1.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n\r\n  spline_type bezier(4,U,P);\r\n\r\n  double const tolerance = 10e-15;\r\n\r\n  // Now we have constructed the equivalent of a bezier curve\r\n  //\r\n  //   B(t) =     a t^3 +   b t^2 + c t + d\r\n  //   B'(t) =  3 a t^2 + 2 b t   + c \r\n  //\r\n  //   B(0) = p0  = d\r\n  //   B(1) = p3  = a + b + c + d\r\n  //   B'(0) = 3*(p1-p0) = c\r\n  //   B'(1) = 3*(p1-p0) = 3 a + 2 b + c\r\n  //\r\n  //  working out the equations one would get\r\n  vector_type a = -1*p0 + 3*p1 - 3*p2 + 1*p3;\r\n  vector_type b =  3*p0 - 6*p1 + 3*p2;\r\n  vector_type c = -3*p0 + 3*p1;\r\n  vector_type d =  1*p0;\r\n\r\n  double u = 0.5;\r\n\r\n  OpenTissue::spline::insert_knot(u,bezier);\r\n  OpenTissue::spline::insert_knot(u,bezier);\r\n  OpenTissue::spline::insert_knot(u,bezier);\r\n  OpenTissue::spline::insert_knot(u,bezier);\r\n\r\n  vector_type m0 = 0.5*(p1+p0);\r\n  vector_type m1 = 0.5*(p2+p1);\r\n  vector_type m2 = 0.5*(p3+p2);\r\n  vector_type n0 = 0.5*(m1+m0);\r\n  vector_type n1 = 0.5*(m2+m1);\r\n  vector_type q0 = 0.5*(n0+n1);\r\n\r\n  knot_container  const & newU = bezier.get_knot_container();\r\n  point_container const & newP = bezier.get_control_container();\r\n\r\n  BOOST_CHECK_CLOSE(newU[0], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[1], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[2], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[3], 0.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[4], 0.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[5], 0.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[6], 0.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[7], 0.5,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[8], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[9], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[10], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newU[11], 1.0,  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[0](0), p0(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[0](1), p0(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[1](0), m0(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[1](1), m0(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[2](0), n0(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[2](1), n0(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[3](0), q0(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[3](1), q0(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[4](0), q0(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[4](1), q0(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[5](0), n1(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[5](1), n1(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[6](0), m2(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[6](1), m2(1),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[7](0), p3(0),  tolerance);\r\n  BOOST_CHECK_CLOSE(newP[7](1), p3(1),  tolerance);\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "782bd0764555060ec809944e047730e0cb732696", "size": 7159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/insert_knot/src/unit_insert_knot.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/insert_knot/src/unit_insert_knot.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/insert_knot/src/unit_insert_knot.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.7688679245, "max_line_length": 84, "alphanum_fraction": 0.6289984635, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727026, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6505975893303818}}
{"text": "#ifndef ITERATOR_HPP\n#define ITERATOR_HPP\n\n#include <string>\n#include <Eigen/Dense>\n\n\ntemplate<typename T, int D>\nclass iterator {\npublic:\n\n    iterator()  {\n    }\n\n    uint dim() const {return D;}\n    uint num() const {return dataPtr.size();}\n\n    // insert a consecutive batch of vectors\n    void insertBatch(T *addr, uint n) {\n        for (uint i = 0; i < n; ++i) {\n            insert(addr + i * D, i);\n        }\n    }\n    // insert a single vector\n    void insert(T *addr, uint id) {\n        dataPtr.push_back(addr);\n        dataIdx.push_back(id);\n    }\n\n    T* addr(uint pos) const {\n        return dataPtr[pos];\n    }\n\n    const Eigen::Ref< const Eigen::Matrix< T, D, 1>> operator[](const uint i)  {\n        return get(i);\n    }\n    const Eigen::Ref< const Eigen::Matrix< T, D, 1>> get(const uint i)  {\n        return Eigen::Map<Eigen::Matrix<T, D, 1>>(dataPtr[i]);\n    }\n\n    const Eigen::Matrix< T, D, 1>  center() {\n        T *c = new T[D];\n        Eigen::Map<Eigen::Matrix<T, D, 1>> avgVector(c);\n        avgVector = Eigen::Matrix<T, D, 1>::Zero();\n\n        for (uint n = 0; n < num(); ++n) {\n            avgVector += get(n);\n        }\n\n        avgVector /= static_cast<T>(num());\n        return avgVector;\n\n    }\n\n    std::vector<T*> dataPtr;\n    std::vector<uint> dataIdx;\n\n\n};\n\n#endif", "meta": {"hexsha": "fa6502a49bac46b2593ef84a625a452a1398b344", "size": 1297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpu_version/iterator/iterator.hpp", "max_stars_repo_name": "takanokage/Product-Quantization-Tree", "max_stars_repo_head_hexsha": "2651ba871100ff4c0ccef42ba57e871fbc6181f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 98.0, "max_stars_repo_stars_event_min_datetime": "2016-07-18T07:38:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:28:01.000Z", "max_issues_repo_path": "cpu_version/iterator/iterator.hpp", "max_issues_repo_name": "takanokage/Product-Quantization-Tree", "max_issues_repo_head_hexsha": "2651ba871100ff4c0ccef42ba57e871fbc6181f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T08:43:36.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-02T14:39:41.000Z", "max_forks_repo_path": "cpu_version/iterator/iterator.hpp", "max_forks_repo_name": "takanokage/Product-Quantization-Tree", "max_forks_repo_head_hexsha": "2651ba871100ff4c0ccef42ba57e871fbc6181f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T13:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T14:34:46.000Z", "avg_line_length": 21.262295082, "max_line_length": 80, "alphanum_fraction": 0.5358519661, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7826624840223699, "lm_q1q2_score": 0.6505044955089243}}
{"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_FRANK_MATRIX_HPP\n#define ROKKO_UTILITY_FRANK_MATRIX_HPP\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/throw_exception.hpp>\n#include <rokko/config.h>\n#include <rokko/localized_matrix.hpp>\n#if defined(ROKKO_HAVE_PARALLEL_DENSE_SOLVER)\n# include <rokko/distributed_matrix.hpp>\n#endif\n\nnamespace rokko {\n\nclass frank_matrix {\npublic:\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate(rokko::localized_matrix<T, MATRIX_MAJOR>& mat) {\n    if (mat.rows() != mat.cols())\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n    int n = mat.rows();\n    for(int i = 0; i < n; ++i) {\n      for(int j = 0; j < n; ++j) {\n        mat(i,j) = n - std::max(i, j);\n      }\n    }\n  }\n\n#if defined(ROKKO_HAVE_PARALLEL_DENSE_SOLVER)\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate(rokko::distributed_matrix<T, MATRIX_MAJOR>& mat) {\n    if (mat.get_m_global() != mat.get_n_global())\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n    for(int local_i = 0; local_i < mat.get_m_local(); ++local_i) {\n      for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n        int global_i = mat.translate_l2g_row(local_i);\n        int global_j = mat.translate_l2g_col(local_j);\n        mat.set_local(local_i, local_j, mat.get_m_global() - std::max(global_i, global_j));\n      }\n    }\n  }\n  \n  // another (slower) implementation using set_global function\n  template<typename T, typename MATRIX_MAJOR>\n  static void generate_global(rokko::distributed_matrix<T, MATRIX_MAJOR>& mat) {\n    if (mat.m_global != mat.n_global)\n      BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n    for(int global_i=0; global_i<mat.m_global; ++global_i) {\n      for(int global_j=0; global_j<mat.n_global; ++global_j) {\n        mat.set_global(global_i, global_j, mat.m_global - std::max(global_i, global_j) );\n      }\n    }\n  }\n#endif\n  \n  // calculate k-th smallest eigenvalue of dim-dimensional Frank matrix (k=0...dim-1)\n  static double eigenvalue(int dim, int k) {\n    return 1 / (2 * (1 - std::cos(M_PI * (2 * k + 1) / (2 * dim + 1))));\n  }\n};\n    \n} // namespace rokko\n\n#endif // ROKKO_UTILITY_FRANK_MATRIX_HPP\n", "meta": {"hexsha": "a5764e0531aff837a4f824fe6d241577b9d8607e", "size": 2757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/utility/frank_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/frank_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/frank_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": 36.2763157895, "max_line_length": 99, "alphanum_fraction": 0.6543344215, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6505044697744432}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// EigSensitivity.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  First and second derivatives of symmetric 2x2 matrix eigenvalues.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  04/05/2019 10:32:17\n////////////////////////////////////////////////////////////////////////////////\n#ifndef EIGSENSITIVITY_HH\n#define EIGSENSITIVITY_HH\n\n#include <Eigen/Dense>\n#include <array>\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n\n// 2x2 case only for now, also can be sped up.\ntemplate<typename Real>\nstruct EigSensitivity {\n    using V2d  = Eigen::Matrix<Real, 2, 1>;\n    using M2d  = Eigen::Matrix<Real, 2, 2>;\n\n    EigSensitivity() { }\n\n    template<typename Derived>\n    EigSensitivity(const Eigen::MatrixBase<Derived> &A) { setMatrix(A); }\n\n    template<typename Derived>\n    void setMatrix(const Eigen::MatrixBase<Derived> &A) {\n        static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n\n        const Real a_minus_c = A(0, 0) - A(1, 1);\n        const Real b = A(0, 1);\n        if (std::abs(b - A(1, 0)) > 1e-15) throw std::runtime_error(\"Only symmetric matrices are supported\");\n        // d := descriminant of characteristic quadratic\n        const Real sqrt_d = std::sqrt(a_minus_c * a_minus_c + 4 * b * b);\n        m_Lambda << 0.5 * (A.trace() + sqrt_d),\n                    0.5 * (A.trace() - sqrt_d);\n\n        V2d q0(a_minus_c + sqrt_d, 2 * b);\n        q0.normalize();\n        m_Q.col(0) = q0;\n        m_Q.col(1) << -q0[1], q0[0];\n\n        if (sqrt_d < 1e-14) m_degenerate = true;\n        else                m_degenerate = false;\n    }\n\n    auto      q(size_t i) const { return m_Q.col(i); }\n    Real lambda(size_t i) const { return m_Lambda[i]; }\n\n    // Access Eigendecomposition\n    const M2d &     Q() const { return m_Q; }\n    const V2d &Lambda() const { return m_Lambda; }\n\n    V2d dLambda(const M2d &dA) const { return (m_Q.transpose() * dA * m_Q).diagonal(); }\n    M2d dLambda(size_t i) const { return q(i) * q(i).transpose(); }\n    Real dLambda(size_t i, const M2d &dA) const { return q(i).dot(dA * q(i)); }\n\n    // Only correct for symmetric dA_b!\n    V2d d2Lambda(const M2d &dA_a, const M2d &dA_b) const {\n        if (m_degenerate) return V2d(0.0, 0.0);\n        Real d2lambda_0 = (2.0 / (m_Lambda[0] - m_Lambda[1])) * (q(0).dot(dA_a * q(1))) * (q(0).dot(dA_b * q(1)));\n        return V2d(d2lambda_0, -d2lambda_0);\n    }\n\n    // Only correct for symmetric dA!\n    M2d delta_dLambda(size_t i, const M2d &dA) const {\n        if (m_degenerate) return M2d::Zero();\n        double sign = (i == 0) ? 1.0 : -1.0;\n        M2d result = ((sign * (2.0 / (m_Lambda[0] - m_Lambda[1])) * (q(0).dot(dA * q(1)))) * q(0)) * q(1).transpose();\n        symmetrize(result);\n        return result;\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    M2d m_Q;\n    V2d m_Lambda;\n\n    bool m_degenerate;\n};\n\n#endif /* end of include guard: EIGSENSITIVITY_HH */\n", "meta": {"hexsha": "38cbbebb9738672dd74e63e0a0e2dc3b0f919f89", "size": 3085, "ext": "hh", "lang": "C++", "max_stars_repo_path": "EigSensitivity.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "EigSensitivity.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigSensitivity.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 36.2941176471, "max_line_length": 124, "alphanum_fraction": 0.5559157212, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6504889194374132}}
{"text": "#ifndef SPLX_INTERNAL_BEZIER_H\n#define SPLX_INTERNAL_BEZIER_H\n#include <Eigen/Dense>\n#include <splx/types.hpp>\n#include <splx/internal/combinatorics.hpp>\n\nnamespace splx {\nnamespace internal {\nnamespace bezier {\n\n/*\n* given a bezier curve degree and max parameter, return row r so that\n* multiplying the row with control points gives the kth derivative\n* of the curve at u\n*\n* f^k(u) = \\sum_{i=0}^degree r(i) * p(i)\n* return r\n*/\ntemplate<typename T>\nRow<T> getBasisRow(unsigned int degree, T maxParameter, T u, unsigned int k) {\n    if(u < 0 || u > maxParameter) {\n    throw std::domain_error(\n        std::string(\"u is outside of the range [0, \")\n        + std::to_string(maxParameter)\n        + std::string(\"]\")\n    );\n    }\n\n    if(maxParameter == 0) {\n        Row<T> result(degree+1);\n        result.setZero();\n        if(k == 0 && degree >= 0) {\n            result(0) = 1.0;\n        }\n        return result;\n    }\n\n    Row<T> result(degree + 1);\n\n    T oneOverA = 1/maxParameter;\n    for(unsigned int i = 0; i <= degree; i++) {\n    T base = 0.0;\n    T mult = 1.0;\n    for(unsigned int j = 0; j+k <= degree; j++, mult *= u) {\n        if(j+k >= i) {\n        // base += pow(oneOverA, i) * this->comb(degree-i, j+k-i)\n        //       * pow(-oneOverA, j+k-i) * this->perm(j+k, k)\n        //       * mult;\n\n        base += splx::internal::comb(degree-i, j+k-i)\n            * splx::internal::pow(oneOverA, j+k) * splx::internal::perm(j+k, k)\n            * mult * ((j+k-i)%2 == 0 ? 1 : -1);\n        }\n    }\n    base *= splx::internal::comb(degree, i);\n    result(i) = base;\n    }\n    return result;\n}\n\n/*\n    Coefficient matrix for the k^th derivative bernstein base functions where each row r\n    contains coefficients where k^th derivative of i^th bernstein polynomial of degree d\n    can be expressed as r(0) + r(1)u + r(2)u^2 + ... + r(d)u^d\n*/\ntemplate<typename T>\nMatrix<T> bernsteinCoefficientMatrix(unsigned int degree, T maxParameter, unsigned int k) {\n    Matrix<T> bernsteinMtr(degree+1, degree+1);\n    bernsteinMtr.setZero();\n\n    if(maxParameter == 0) {\n        if(k == 0 && degree >= 0) {\n            bernsteinMtr(0, 0) = 1.0;\n        }\n        return bernsteinMtr;\n    }\n\n    unsigned int dcombi = 1;\n    for(Index i = 0; \n\n        i < degree+1; \n\n        dcombi *= (degree-i), \n        dcombi /= (i+1), \n        i++) {\n\n        unsigned int dminicombjmini = 1;\n        T min1 = 1;\n        T oneOverAPowj = splx::internal::pow(1/maxParameter, i);\n\n        for(Index j = i; \n\n            j < degree+1; \n\n            dminicombjmini *= (degree - j), \n            dminicombjmini/= (j+1-i), \n            j++, \n            min1 *= -1, \n            oneOverAPowj *= (1/maxParameter)) {\n\n            bernsteinMtr(i, j) = dcombi * dminicombjmini * min1 * oneOverAPowj;\n\n        }\n    }\n\n    Matrix<T> derivative(degree+1, degree+1);\n    derivative.setZero();\n\n    unsigned int jpermk = splx::internal::fac(k);\n    for(unsigned int j = k;\n        \n        j < degree+1;\n        \n        jpermk *= (j+1),\n        jpermk /= (j+1-k),\n        j++) {\n        derivative(j, j-k) = jpermk;\n    }\n\n    return bernsteinMtr * derivative;\n}\n\n} // namespace bezier\n} // namespace internal\n} // namespace splx\n\n#endif", "meta": {"hexsha": "7b6853012f1c0b4fed0d8198b133444577188cea", "size": 3207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/splx/internal/bezier.hpp", "max_stars_repo_name": "baskinburak/splx", "max_stars_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_stars_repo_licenses": ["MIT"], "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/splx/internal/bezier.hpp", "max_issues_repo_name": "baskinburak/splx", "max_issues_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T00:30:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T01:39:41.000Z", "max_forks_repo_path": "include/splx/internal/bezier.hpp", "max_forks_repo_name": "baskinburak/splx", "max_forks_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T08:17:37.000Z", "avg_line_length": 25.2519685039, "max_line_length": 91, "alphanum_fraction": 0.5447458684, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6504889148788876}}
{"text": "//test_ptf_mc_var.cpp\n\n//test portfolio VaR through MC simulation\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include<memory>\n\n#include <Eigen/Dense>\n\n#include \"compute_returns_eigen.h\"\n#include \"compute_var.h\"\n#include \"path.h\"\n#include \"mc_engine.h\"\n#include \"rng.h\"\n#include \"pca.h\"\n#include \"portfolio.h\"\n#include \"ptf_var.h\"\n\n#include <boost/math/special_functions/erf.hpp>\nusing boost::math::erfc_inv;\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)\n//https://www.gamedev.net/topic/444193-c-how-to-load-in-a-csv-file/\n{\n\tstd::string csvLine;\n\t// read every line from the stream\n\twhile( std::getline(input, csvLine) )\n\t{\n\t\tstd::istringstream csvStream(csvLine);\n\t\tstd::vector<std::string> csvColumn;\n\t\tstd::string csvElement;\n\t\t// read every element from the line that is seperated by commas\n\t\t// and put it into the vector or strings\n\t\twhile( std::getline(csvStream, csvElement, ',') )\n\t\t{\n\t\t\tcsvColumn.push_back(csvElement);\n\t\t}\n\t\toutput.push_back(csvColumn);\n\t}\n}\n\n\nint main()\n{\n\n    try{\n\n    // Read daily price history for crypto assets, in USD\n    //Date,EOS,DAPP\n    //2018-11-19,3.5,0.5\n    //2018-11-20,3.6,0.6 \n\n\tstd::fstream file(\"/home/gg/VaR/test/data.csv\", ios::in);\n\tif(!file.is_open())\n\t{\n\t\tstd::cout << \"File not found!\\n\";\n\t\treturn 1;\n\t}\n\t// typedef to save typing for the following object\n\ttypedef std::vector< std::vector<std::string> > csvVector;\n\tcsvVector csvData;\n\n\treadCSV(file, csvData);\n\n    //test\n    for(size_t i = 0;i < 5; ++i){\n        for(size_t j = 0;j < csvData[i].size();++j){\n            cout << csvData[i][j] << '\\t';\n\n        }\n\n        cout << endl;\n    }\n    cout << endl;\n\n    // Remove lines with missing values\n\n    size_t n(csvData.size() - 1);\n    size_t m(csvData[0].size() - 1);\n\n    Mat _prices;\n    _prices.resize(m,Vec(n));\n\n    for(size_t i = 1;i < n+1;++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-1] = 99999.;\n            }\n            else{\n                _prices[j-1][i-1] = std::stod(tmp);\n            }\n        }\n    }\n\n    std::vector<std::string> indexNames(csvData[0].size() - 1);\n\n    for(size_t i = 1;i < csvData[0].size();++i){\n        indexNames[i-1] = csvData[0][i];\n    }\n\n\t//Remove missing values to compute trailling returns\n    //Asynchornous time series. Shift to the next value\n    Mat prices;\n    prices.resize(m,Vec(0));\n\n    bool goodrow = true;\n    for(size_t j = 0;j < _prices[0].size();++j){\n        for(size_t i = 0;i < _prices.size();++i){\n            if((_prices[i][j] == 99999) || (_prices[i][j] == 0))\n                goodrow = false;\n        }\n        if (goodrow)\n            for(size_t i = 0;i < _prices.size();++i){\n                prices[i].push_back(_prices[i][j]);\n            }\n            goodrow = true;\n        }\n    unsigned int windowsize = prices[0].size()-2;\n    std::shared_ptr<ComputeReturn> cr(new ComputeReturn(prices,1,windowsize,true));\n\n    // create portfolio\n\tdouble a = double(1./m);\n\tstd::vector<double> weights{a,a}; //initialization. Equi-weighted asset for mere convenience\n\tPtf _ptf;\n\tfor(size_t i = 0;i < m;++i){\n        shared_ptr<Instrument> instrument(new DeltaOne());\n        auto p = std::make_pair(i,instrument);\n\t\t_ptf.push_back(p);\n\t}\n\tshared_ptr<Portfolio> ptf(new Portfolio(_ptf, weights, cr, false, 1.e+07));\n\n    HistoricalVaR model;\n\n    double alphatest = .95; // set alpha level, example 0.9 for 95% CVaR\n\n    // CVaRVarianceCovariance\n    // as currently used in VIGOR\n    double CVaRVarianceCovariance = -100.0 * std::log(1.0 + (((std::exp(-1.0*(std::pow(-1.0*std::sqrt(2.0)*erfc_inv(2.0*alphatest),2.0))/2.0)/(std::sqrt(2.0*M_PI)))/(1.0-alphatest)) * (ptf->getPtfSdev()/100)));\n    cout << \"CVaRVarianceCovariance: \" << CVaRVarianceCovariance << endl;\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": "a1d310089398aaafb229f44b05ce26a0f9bb1e74", "size": 4152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/CVaRVarianceCovariance.cpp", "max_stars_repo_name": "vigor-ish/VaR", "max_stars_repo_head_hexsha": "82e47d529415275fd673b611f1d6ffaff1296863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/CVaRVarianceCovariance.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": "test/CVaRVarianceCovariance.cpp", "max_forks_repo_name": "vigor-ish/VaR", "max_forks_repo_head_hexsha": "82e47d529415275fd673b611f1d6ffaff1296863", "max_forks_repo_licenses": ["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.1132075472, "max_line_length": 210, "alphanum_fraction": 0.5989884393, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6504889148788875}}
{"text": "/**\n * @file MathTools.hpp\n * @author John D. Jakeman\n * @date 31 October 2011\n * @brief Miscelaneous math functions.\n */\n\n#ifndef MATH_TOOLS_HPP\n#define MATH_TOOLS_HPP\n\n#include \"LinearAlgebra.hpp\"\n#include <algorithm>\n#include <functional>\n#include <ctime>\n#include <boost/functional/hash.hpp>\n#include <boost/unordered_set.hpp>\n\nnamespace Pecos {\n\n/**\n * \\brief Map a scalar index of a flat 1D array to the equivalent\n *        d-dimensional index\n *\n * Example:\n \\f[\n \\begin{bmatrix}\n 1 & 4 & 7\\\\\n 2 & 5 & 8\\\\\n 3 & 6 & 9\n \\end{bmatrix}\n \\rightarrow\n \\begin{bmatrix}\n 1,1 & 1,2 & 1,3\\\\\n 2,1 & 2,2 & 2,3\\\\\n 3,1 & 3,2 & 3,3\n \\end{bmatrix}\n \\f]\n *\n * @param sizes the number of elems in each dimension. For a 2D index\n * sizes = [numRows, numCols]\n * @param index the scalar index\n * @param num_elems the total number of elements in the d-dimensional matrix\n * @return result the d-dimensional index\n */\nvoid ind2sub( const IntVector &sizes, int index, int num_elems,\n\t      IntVector &result );\n\n/**\n * \\brief Map a d-dimensional index to the scalar index of the equivalent flat \n * 1D array\n * \n * Example:\n \\f[\n \\begin{bmatrix}\n 1,1 & 1,2 & 1,3\\\\\n 2,1 & 2,2 & 2,3\\\\\n 3,1 & 3,2 & 3,3\n \\end{bmatrix}\n \\rightarrow\n \\begin{bmatrix}\n 1 & 4 & 7\\\\\n 2 & 5 & 8\\\\\n 3 & 6 & 9\n \\end{bmatrix}\n \\f]\n *\n * @param sizes the number of elems in each dimension. For a 2D index\n * sizes = [numRows, numCols]\n * @param multi_index the d-dimensional index\n * @return scalar_index the scalar index of the flat array\n */\nint sub2ind( const IntVector &sizes, const IntVector &multi_index );\n\n/**\n * \\brief Compute the cartesian product of an arbitray number of sets. \n * \n * These sets can consist of numbers of be themselves sets of vectors\n * @param inputSets the sets to be used in the cartesian product\n * @param elem_size the size of the vectors within each set.\n * @return the cartesian product\n */\ntemplate<typename O, typename T>\nvoid cartesian_product( const std::vector< Teuchos::SerialDenseVector<O,T> > &input_sets, Teuchos::SerialDenseMatrix<O,T> &result, int elem_size )\n{\n#ifdef DEBUG\n  if ( input_sets.size() == 0 ) \n    {\n      throw(std::invalid_argument(\"CartesianProduct() there must be at least one input set\"));\n    }\n#endif\n  int num_elems = 1;\n  int num_sets = input_sets.size();\n  IntVector sizes;\n  sizes.resize( num_sets );\n  IntVector multi_index;\n  for ( int i = 0; i < num_sets; i++ )\n    {\n      sizes[i] = input_sets[i].length() / elem_size;\n      num_elems *= sizes[i];\n    }\n  result.reshape( num_sets*elem_size, num_elems );\n  for ( int i = 0; i < num_elems; i++ )\n    {\n      ind2sub( sizes, i, num_elems, multi_index );\n      for ( int j = 0; j < num_sets; j++ )\n\t{\n\t  for ( int k = 0; k < elem_size; k++ )\n\t    {\n\t      result( j*elem_size+k, i ) = \n\t\tinput_sets[j][multi_index[j]*elem_size+k];\n\t    }\n\t}\n    }\n};\n\n/**\n * \\brief Construct the outer product of an arbitray number of sets.\n *\n * Example: \n \\f[ \\{1,2\\}\\times\\{3,4\\}=\\{1\\times3, 2\\times3, 1\\times4, 2\\times4\\} = \n \\{3, 6, 4, 8\\} \\f]\n * @param input_sets \"Vector.hpp\" of sets to be used in the outer product\n * @return result the outer product\n */\ntemplate<typename O, typename T>\nvoid outer_product( const std::vector< Teuchos::SerialDenseVector<O,T> > &input_sets, Teuchos::SerialDenseVector<O,T> &result )\n{\n  int num_elems = 1;\n  int num_sets = input_sets.size();\n  IntVector sizes( num_sets, false );\n  for ( int i = 0; i < num_sets; i++ )\n    {\n      sizes[i] = input_sets[i].numRows();\n      num_elems *= sizes[i];\n    }\n  IntVector multi_index( num_sets, false );\n  result.sizeUninitialized( num_elems );\n  for ( int i = 0; i < num_elems; i++ )\n    {\n      result[i] = 1.0;\n      ind2sub( sizes, i, num_elems, multi_index );\n      for ( int j = 0; j < num_sets; j++ )\n\tresult[i] *= input_sets[j][multi_index[j]];\n    }\n}\n\n/**\n * \\brief Build a vector containing all integers in [m,n) seperated by incr\n *\n * E.g Range( 1, 10, 2 ) -> [1,3,5,7,9]\n */\ntemplate<typename O, typename T>\nvoid range( Teuchos::SerialDenseVector<O,T> &result, T m, T n, T incr = 1 )\n{\n  T i = m;\n  O j = 0;\n  O len = (O)( n - m ) / (O)incr;\n  if ( (O)( n - m ) % (O)incr != 0 ) len++;\n  result.sizeUninitialized( len );\n  while( i < n )\n    {\n      result[j] = i;\n      i += incr;\n      j++;\n    }\n};\n\n/** \n * \\brief Generate a vector whose n elements are equidistantly spaced in the\n * interval [a,b].\n *\n * @param [a,b] the range\n * @param n the number of times the interval [a,b] is divided\n * @return vec n numbers equidistant is [a,b]\n */\nvoid linspace( RealVector &result, Real a, Real b, int n );\n\n/**\n * \\brief Round a Real to the nearest integer.\n */\nReal round( Real r );\n\n/*\n * \\brief Function to allow for searching for maximum absolute \n * value (Real) in a containter\n *\n * @param a first value\n * @param b second value\n * @return true if a < b, false otherwise\n */\nbool abs_compare( Real a, Real b );\n\n/** \n * \\brief Return the nearest integer to x\n * @param x the value\n * return int the neartest integer to x\n */\nint nearest_integer( Real x );\n\n/**\n * \\brief Calulate n! \n *\n * @param n the factorial of interest\n * @return n!\n */\nReal factorial( int n );\n\n/**\n * \\brief Return the number of possible combinations of k elements that can be\n * chosen from n elements.\n *\n *\\f[ { n \\choose k} = \\frac{n!}{k!(n-k)!}\\f]\n * @param n number of elements\n * @param k the number of elements to be chosen. k<=n. \n * @return the total number of combinations.\n */\nint nchoosek( int n, int k );\n\n/**\n * \\brief Transform a point x in the interval [a,b] onto the interval [0,1] and\n * vice versa.\n *\n * @param x the value to be transformed\n * @param [a,b] the new/old interval\n * @param dir specifies whether to map to [a,b] or from [a,b]. That is \n * dir=0  returns [0,1] -> [a,b]\n * dir!=0 returns [a,b]  -> [0,1]\n * @return the rescaled value\n */\nReal rescale( Real x, Real a, Real b, int dir );\n\n/**\n * \\brief Transform a point x in the interval \n * \\f$[a_1,b_1] \\times \\cdots \\times [a_d,b_d] \\f$ onto \n * the hypercube interval \\f$[0,1]^d\\f$ and vice versa.\n *\n * @param x the value to be transformed\n * @param [a,b] the new/old interval\n * @param dir specifies whether to map to [a,b] or from [a,b]. That is \n * dir=0  returns [0,1] -> [a,b]\n * dir!=0 returns [a,b]  -> [0,1]\n * @return the rescaled value\n */\nvoid rescale( RealMatrix &x, const RealVector &domain, int dir );\n\n/**\n *\\brief transform points in domain_in to points in domain_out\n */\nvoid hypercube_map( RealMatrix &x, const RealVector &domain_in,  \n\t\t    const RealVector &domain_out,\n\t\t    RealMatrix &result );\n\n/**\n * \\brief Construct a d-dimensional mesh on a hyper-rectangle. The meshes are \n * equidistant with respect to each coordinate direction.\n *\n * @param num_pts_1d array specifying the number of meshpoints for each dimension\n * @param domain the min and max value of each dimension. \n *        That is \\f$ [a_1,b_1,...,a_d,b_d]\\f$\n * @return the multi-dimensional mesh coordinates. ( num_dims x num_pts ) array. \n * num_pts = num_pts_1d[0]*...*num_pts_1d[d-1]\n */\nvoid mesh_grid( const IntVector &num_pts_1d, \n\t\tconst RealVector &domain, \n\t\tRealMatrix &result );\n\n/**\n * Get all the multi-dimensional indices of a multi-dimensional polynomial\n * basis with a specified degree sum. A cleaner interface is provided by\n * GetMultiDimensionalPolynomial_indices()\n * @return B the multi-dimensional indices\n */\nvoid get_multi_dimensional_polynomial_subspace_indices( IntMatrix &B, \n\t\t\t\t\t\t\tint* elems, \n\t\t\t\t\t\t\tint len_elems, \n\t\t\t\t\t\t\tint* pos, \n\t\t\t\t\t\t\tint len_pos, \n\t\t\t\t\t\t\tint choices_made, \n\t\t\t\t\t\t\tint first_pos, \n\t\t\t\t\t\t\tint order, int &row );\n\n/**\n * \\brief Get all the multi-dimensional indices of a multi-dimensional polynomial\n * basis with a specified degree sum.\n *\n * @param num_dims the dimensionailty\n * @param degree the degree sum of the polynomial indices wanted\n * @return B the multi-dimensional polynomial_indices\n */\nvoid get_multi_dimensional_polynomial_indices( int num_dims, int degree, \n\t\t\t\t\t       IntMatrix &result );\n\n/**\n * \\brief Get the smallest degree of the total degree polynomial such that the\n * number of terms in the basis is larger than or equal to num_samples\n*/\nint get_total_degree_from_num_samples( int num_dims, int num_samples );\n\n/**\n * \\brief Get the multi-dimensional hypercube \\f$[a,b]^d\\f$\n *\n * @param num_dims the dimension of the computational domain.\n * @param \\f$[a,b]\\f$ the one-dimensional bounds of the hypercube.\n * @return result the multi-dimensional bounds of the hypercube.\n */\nvoid set_hypercube_domain( RealVector &result, int num_dims, Real a, Real b );\n\n/// Perturb the columns of a matrix\nvoid get_permutations( IntMatrix &permutations, \n\t\t       int M , int N, unsigned int seed );\n\nvoid compute_hyperbolic_level_subdim_indices( int num_dims, int level, \n\t\t\t\t\t      int num_active_dims, \n\t\t\t\t\t      Real p,\n\t\t\t\t\t      IntMatrix &result );\n\nvoid compute_hyperbolic_level_indices( int num_dims, int level, Real p, \n\t\t\t\t       IntMatrix &result );\n\nvoid compute_hyperbolic_indices( int num_dims, int level, Real p, \n\t\t\t\t IntMatrix &result );\n\n// weights ( num_dims x 1 ) vector with values in [0,1]\nvoid compute_anisotropic_hyperbolic_indices( int num_dims, int level, Real p, \n\t\t\t\t\t     RealVector &weights,\n\t\t\t\t\t     IntMatrix &result );\n\n// prepend \"mt_\" for MathTools to avoid name clash\nenum lp_norm\n  { \n    mt_l1_norm,\n    mt_l2_norm,\n    mt_linf_norm,\n  };\n\n/**\n * \\brief Return the index of the element of x with the minimum value.\n *\n *\\f[\n \\arg \\! \\min_i x_i\\quad i=1,\\ldots,n\n \\f] \n*/\n template<typename T>\nint argmin( int n, T* x )\n{\n  int amin( 0 );\n  T min = x[0];\n  for ( int i = 1; i < n; i++ )\n    {\n      if ( x[i] < min )\n\t{\n\t  min = x[i];\n\t  amin = i;\n\t}\n    }\n  return amin;\n};\n\n/**\n * \\brief Return the index of the element of x with the maximum value.\n *\n *\\f[\n \\arg \\! \\max_i x_i \\quad i=1,\\ldots,n\n \\f] \n*/\ntemplate<typename T>\nint argmax( int n, T* x )\n{\n  int amax( 0 );\n  T max = x[0];\n  for ( int i = 1; i < n; i++ )\n    {\n      if ( x[i] > max )\n\t{\n\t  max = x[i];\n\t  amax = i;\n\t}\n    }\n  return amax;\n};\n\ntemplate<typename T>\nint magnitude_argmax( int n, T* x )\n{\n  int amax( 0 );\n  T max = std::abs( x[0] );\n  for ( int i = 1; i < n; i++ )\n    {\n      Real abs_x = std::abs( x[i] );\n      if ( abs_x > max )\n\t{\n\t  max = abs_x;\n\t  amax = i;\n\t}\n    }\n  return amax;\n};\n\n/**\n * \\brief Return the sum of the elements in the array x. \n *\n *\\f[\n \\sum_{i=1}^N x_i\n \\f]\n*/\ntemplate<typename T>\nT sum( int n, T* x )\n{\n  T sum = x[0];\n  for ( int i = 1; i < n; i++ )\n    sum += x[i];\n  return sum;\n};\n\n/**\n * \\brief Return the sum of the elements in the vector x. \n *\n *\\f[\n \\sum_{i=1}^N x_i\n \\f]\n *\n * This will not return the same result as sum( int n, T* x ) if\n * the vector is a subvector of another vector. That is stride does not equal\n * the number of rows.\n */\ntemplate < typename O, typename T >\nT sum( Teuchos::SerialDenseVector<O,T> &v )\n{\n  T tmp = Teuchos::ScalarTraits<T>::zero();\n  for ( O i = 0; i < v.length(); i++ )\n    tmp += v[i];\n  return tmp;\n};\n\n/**\n * \\brief Return the mean of the array x. \n *\n * \\f[\n \\bar{x} = \\frac{1}{N}\\sum_{i=1}^N x_i\n \\f]\n*/\nReal mean( int n, Real *x );\n\n\n/**\n * \\brief Return the sample variance of the array x. \n *\n * \\f[\n \\sigma^2 = \\frac{1}{N-\\text{ddof}}\\sum_{i=1}^N ( x_i-\\bar{x} )^2\n \\f]\n * \n * \\param ddof Delta Degrees of Freedom (ddof).  \n * The divisor used in calculations is \\f$N - \\text{ddof}\\f$, \n * where \\$fN\\$f represents the number of elements.\n * By default ddof is one.\n */\nReal variance( int n, Real *x, int ddof = 1 );\n\n\n/**\n * \\brief Calculate one of several different types of \\f$\\ell_p\\f$ error norms\n * of a set of vectors. \n *\n * Each column of the reference_values matrix is considered \n * independently with the correpsonding column in the approximation_values.\n * The error between the each set of two columns tested is returned.\n * \\param reference_values a matrix containing the reference values\n * \\param approximate_values a matrix containig the approximate values\n * \\param active_columns specifies which set of columns to consider. If empty\n *        all columns are considered\n * \\pram normalise if true the error norms are normalised. The l_inf norm\n *                 is normalised by the half the range of the data in the \n *                 reference_values column. The L_2 norm is normalised by the\n *                 standard deviation of the data in the reference values column.\n */\nvoid lp_error( RealMatrix &reference_values, \n\t       RealMatrix &approximate_values,\n\t       std::vector<lp_norm> error_norms, RealMatrix &error, \n\t       IntVector &active_columns, bool normalise = false );\n\n/**\n *\\brief Construct a Latin Hyperube Design (LHD)\n */\nvoid latin_hypercube_design( int num_pts, int num_dims, RealMatrix &result, \n\t\t\t     int seed );\n\n\nvoid compute_next_combination( int num_dims, int level, IntVector &index, \n\t\t\t       bool &extend, int &h, int &t );\n\nvoid compute_combinations( int num_dims, int level, IntMatrix &result );\n\n\n/**\n * \\breif Return  the sign of x.\n *\n * \\return 1 if the corresponding element of x is greater than zero;\n * 0 if the corresponding element of X equals zero;\n *-1 if the corresponding element of X is less than zero\n */\ntemplate<typename T> \nint sgn( T x )\n{\n  return ( T(0) < x ) - ( x < T(0) );\n}\n\ntemplate<typename T> \nint num_non_zeros( T *data, int n )\n{\n  int num_non_zero_count( 0 );\n  for ( int i = 0; i < n; i++ )\n    {\n      if ( std::abs( data[i] ) > 0 ) \n\tnum_non_zero_count++;\n    }\n  return num_non_zero_count;\n}\n\n/**\n *\\brief return the median of a std::vector\n */\ntemplate<typename T>\ndouble median( std::vector<T> &v )\n{\n  size_t n = v.size();\n  typename std::vector<T>::iterator target = v.begin() + n / 2;\n  std::nth_element( v.begin(), target, v.end() );\n  if( n % 2 != 0 )\n    {\n      return (double)*target;\n    }\n  else\n    {\n      std::vector<Real>::iterator target_neighbour = \n\tstd::max_element( v.begin(), target );\n      return (double)( *target + *target_neighbour ) / 2.0;\n    }\n};\n\n/**\n *\\brief return the median of a RealVector.\n */\ntemplate<typename O, typename T>\ndouble median( Teuchos::SerialDenseVector<O,T> &v )\n{\n  std::vector<T> tmp( v.length() );\n  for ( int i = 0; i < v.length(); i++ )\n    tmp[i] = v[i];\n  return median( tmp );\n}\n\ntemplate<typename O, typename T>\ndouble pnorm( Teuchos::SerialDenseVector<O,T> &v, double p )\n{\n  double sum = 0.;\n  for ( O i = 0; i < v.length(); i++ )\n    {\n      sum += std::pow( std::abs( (double)v[i] ), p );\n    }\n  return std::pow( sum, 1./p );\n}\n\ntemplate<typename O, typename T>\nO num_nonzeros( Teuchos::SerialDenseVector<O,T> &v )\n{\n  O num_nonzeros = Teuchos::ScalarTraits<O>::zero();\n  for ( int d = 0; d < v.length(); d++ )\n    {\n      if ( v[d] != Teuchos::ScalarTraits<T>::zero() ) num_nonzeros++;\n    }\n  return num_nonzeros;\n}\n\ntemplate<typename O, typename T>\nvoid nonzero( Teuchos::SerialDenseVector<O,T> &v, \n\t      IntVector &result )\n{\n  int num_nonzeros = 0;\n  result.sizeUninitialized( v.length() );\n  for ( int d = 0; d < v.length(); d++ )\n    {\n      if ( v[d] != Teuchos::ScalarTraits<T>::zero() )  \n\t{\n\t  result[num_nonzeros] = d;\n\t  num_nonzeros++;\n\t}\n    }\n  // chop off unwanted memory\n  result.resize( num_nonzeros );\n}\n\nvoid lhs_indices( int num_dims, int num_pts, int duplication, int seed, \n\t\t  IntMatrix &result );\n\n/// Construct the improved distributed hypercube sample\nvoid ilhs( int num_dims, int num_pts, int duplication, int seed, \n\t   RealMatrix &result );\n\n/// Construct basic random hypercube sample\nvoid lhs( int num_dims, int num_pts, int seed, \n\t  RealMatrix &result );\n\ntemplate<typename T>\nclass index_sorter {\npublic:\n  index_sorter(const T &values){ values_ = values; }\n  bool operator()( int lhs, int rhs) const {\n    return values_[lhs] < values_[rhs];\n  }\nprivate:\n  T values_;\n};\n\ntemplate<typename T>\nclass magnitude_index_sorter {\npublic:\n  magnitude_index_sorter(const T &values){ values_ = values; }\n  bool operator()( int lhs, int rhs) const {\n    return std::abs( values_[lhs] ) > std::abs( values_[rhs] );\n  }\nprivate:\n  T values_;\n};\n\n// sorts in ascending order\ntemplate<typename O, typename T>\nvoid argsort( const Teuchos::SerialDenseVector<O,T> &values, \n\t      IntVector &result )\n{\n  std::vector<O> indices( values.length() );\n  for ( O i = 0; i < values.length(); i++ )\n    indices[i] = i;\n  \n  std::sort( indices.begin(), indices.end(), index_sorter< Teuchos::SerialDenseVector<O,T> >( values ) );\n\t     \n  result.sizeUninitialized( values.length() );\n  for ( O i = 0; i < values.length(); i++ )\n    result[i] = indices[i];\n}\n\ntemplate<typename O, typename T>\nvoid argsort( Teuchos::SerialDenseVector<O,T> &v,\n\t      Teuchos::SerialDenseVector<O,T> &result_0,\n\t      IntVector &result_1 )\n{\n  argsort( v, result_1 );\n  result_0.sizeUninitialized( v.length() );\n  for ( O i = 0; i < v.length(); i++ )\n    result_0[i] = v[result_1[i]];\n}\n\n// sorts in descending order absolute value of entries\ntemplate<typename O, typename T>\nvoid magnitude_argsort( const Teuchos::SerialDenseVector<O,T> &values, \n\t\t\tIntVector &result )\n{\n  std::vector<O> indices( values.length() );\n  for ( O i = 0; i < values.length(); i++ )\n    indices[i] = i;\n  \n  std::sort( indices.begin(), indices.end(), magnitude_index_sorter< Teuchos::SerialDenseVector<O,T> >( values ) );\n\t     \n  result.sizeUninitialized( values.length() );\n  for ( O i = 0; i < values.length(); i++ )\n    result[i] = indices[i];\n}\n\n/**\n * \\brief find the interval containing a target value. Assumes data is \n * in ascending order\n */\ntemplate<typename O, typename T>\nint binary_search( T target, Teuchos::SerialDenseVector<O,T> &data )\n{\n  O low = 0, high = data.length()-1, mid;\n  while ( low <= high )\n    {\n      mid = low + ( high - low ) / 2;\n      if ( target < data[mid] ) high = mid - 1;\n      else if ( target > data[mid] ) low = mid + 1;\n      else return mid;\n    }\n  if ( high < 0 ) return 0;\n  else if ( high < low ) return high;\n  else return low;\n}\n\nclass LinearInterpolant1D\n{\nprivate:\n  RealVector pts_, vals_;\n\npublic:\n  LinearInterpolant1D( RealVector &pts, RealVector &vals )\n  {\n    pts_ = pts; vals_ = vals;\n  };\n\n  ~LinearInterpolant1D(){};\n  \n  void interpolate( RealVector &pts, RealVector &result )\n  {\n    int num_pts = pts.length();\n    if ( result.length() != num_pts )\n      result.sizeUninitialized( num_pts );\n    for ( int i = 0; i < num_pts; i++ )\n      {\n\t// enforce constant interpolation when interpolation is outside the\n\t// range of pts_\n\tif ( pts[i] <= pts_[0] )\n\t  result[i] = vals_[0];\n\telse if ( pts[i] >= pts_[pts_.length()-1] )\n\t  result[i] = vals_[pts_.length()-1];\n\telse\n\t  {\n\t    // assumes binary search returns index of the closest point in pts_ \n\t    // to the left of pts[i]\n\t    int index = binary_search( pts[i], pts_ );\n\t    result[i] = vals_[index] + ( ( vals_[index+1] - vals_[index] ) / \n\t\t\t\t\t ( pts_[index+1] - pts_[index] ) ) \n\t      * ( pts[i] - pts_[index] );\n\t  }\n      }\n  };\n};\n\n/**\n * \\brief Reverse the contents of a vector. \n *\n * Useful for changing an ordered array to/from ascending/descending order\n */\ntemplate<typename O, typename T>\nvoid reverse( Teuchos::SerialDenseVector<O,T> &v )\n{\n  O n = v.length();\n  Teuchos::SerialDenseVector<O,T> tmp( v );\n  for ( O i = 0; i < n; i++ )\n    v[i] = tmp[n-i-1];\n}\n\ntemplate <typename O, typename T>\nstruct VectorEqual{\n  /*\n   * \\brief Determine if two vectors of doubles are equal\n   */\n  typedef Teuchos::SerialDenseVector<O,T> VectorType;\n  bool operator()( const VectorType &v1, const VectorType &v2 ) const{\n    if ( v1.length() != v2.length() )\n      return false;\n    else{\n      Real tol = std::numeric_limits<T>::epsilon();\n      Real dist = 0.;\n      for ( int i = 0; i < v1.length(); i++ )\n\tdist += ( v1[i]-v2[i] )*( v1[i]-v2[i] );\n      dist = std::sqrt( dist );\n      if ( dist > tol )\n\treturn false;\n    }\n    return true;\n  }\n};\n\ntemplate<typename VectorType >\nstruct VectorHash{\n  int operator()( const VectorType &v ) const{\n    return (int)boost::hash_range(v.values(), v.values() + v.length() );\n  }\n};\n\n/*\n * \\brief Get the columns in A that are not in B\n */\ntemplate <typename O, typename T>\nvoid set_difference_matrix_columns( const Teuchos::SerialDenseMatrix<O,T> &A,\n\t\t\t\t    const Teuchos::SerialDenseMatrix<O,T> &B,\n\t\t\t\t    IntVector &result ){\n  if ( B.numCols() == 0 ){\n    range( result, 0, A.numCols() );\n    return;\n  }\n\n  int num_rows = A.numRows(), num_cols = A.numCols();\n  if ( num_rows != B.numRows() ){\n    std::string msg = \"set_difference_matrix_columns: A and B are inconsistent\";\n    throw(std::runtime_error( msg ) );\n  }\n  typedef Teuchos::SerialDenseVector<O,T> VectorType;\n\n  // Hash columns of the matrix B\n  boost::unordered_set< VectorType,VectorHash<VectorType>,\n\t\t\tVectorEqual<O,T> > col_set;\n  for ( int i = 0; i < B.numCols(); i++ ){\n    VectorType col( Teuchos::View, const_cast<T*>(B[i]), num_rows );\n    col_set.insert( col );\n  }\n\n  // Find columns of A not in B\n  int num_result = 0;\n  typename boost::unordered_set< VectorType,VectorHash<VectorType>,\n\t\t\t\t VectorEqual<O,T> >::const_iterator it;\n  result.sizeUninitialized( num_cols );\n  for ( int i = 0; i < num_cols; i++ ){\n    VectorType col( Teuchos::View, const_cast<T*>(A[i]), num_rows );\n    it = col_set.find( col );\n    if ( it == col_set.end() ){\n      // Column is not in B\n      result[num_result] = i;\n      num_result++;\n    }\n  }\n  \n  // Remove unused memory\n  result.resize( num_result );\n}\n\ntemplate<typename MatrixType>\nvoid extract_submatrix_from_column_indices( const MatrixType &A,\n\t\t\t\t\t    const IntVector &column_indices,\n\t\t\t\t\t    MatrixType &submatrix ){\n  int num_rows = A.numRows(), num_indices = column_indices.length();\n  reshape( submatrix, num_rows, num_indices );\n\n  for ( int j = 0; j < num_indices; j++ )\n    for ( int i = 0; i < num_rows; i++ )\n      submatrix(i,j) = A(i,column_indices[j]);\n}\n\ntemplate<typename MatrixType>\nvoid copy_matrix( const MatrixType &source, MatrixType &dest, \n\t   int num_rows, int num_cols, int start_row=0, int start_col=0 ){\n\n  MatrixType source_subset( Teuchos::View, source, num_rows, num_cols, \n\t\t\t    start_row, start_col );\n  reshape( dest, num_rows, num_cols );\n  dest.assign( source_subset );\n}\n\ntemplate<typename VectorType>\nvoid copy_vector( const VectorType &source, VectorType &dest, \n\t   int num_rows, int start_row=0 ){\n  VectorType source_subset( Teuchos::View, source.values()+start_row, num_rows );\n  resize( dest, num_rows );\n  dest.assign( source_subset );\n}\n\ntemplate<typename MatrixType>\nvoid hstack( const MatrixType &source1, const MatrixType &source2,\n\t     MatrixType &dest ){\n  if ( ( source1.numRows() != source2.numRows() ) && \n       ( ( source1.numCols()!=0 ) && ( source2.numCols()!=0 ) ) )\n    throw( std::runtime_error(\"hstack: matrices are inconsistent\") );\n  int num_rows = source1.numRows() ? source1.numRows() : source2.numRows();\n  reshape( dest, num_rows, source1.numCols()+source2.numCols() );\n  int cntr = 0;\n  for ( int j = 0; j < source1.numCols(); j++, cntr++ )\n    for ( int i = 0; i < num_rows; i++ )\n      dest(i,cntr) = source1(i,j);\n  for ( int j = 0; j < source2.numCols(); j++, cntr++ )\n    for ( int i = 0; i < num_rows; i++ )\n      dest(i,cntr) = source2(i,j);\n}\n\n/**\n * Convert a static array to a \"Vector.hpp\" of vectors.\n * @param a array to be converted\n * @param n the number of vectors\n * @param m the size of each \"Vector.hpp\"\n * @return v the \"Vector.hpp\" of vectors\n */\ntemplate <typename O, typename T>\nvoid convert(T a[], int m, int n, std::vector< Teuchos::SerialDenseVector<O,T> > &v)\n{\n  v.resize( m );\n  for ( int i = 0; i < m; i++ )\n    {\n      Teuchos::SerialDenseVector<O,T> tmp( Teuchos::View, a + i * n, n );\n      v[i] = tmp;\n    }\n};\n\n/**\n * Convert a static array to a weakly ordered multiset of vectors.\n * Set allows for multiple keys with the same value.\n * @param a array to be converted\n * @param n the number of vectors\n * @param m the size of each \"Vector.hpp\"\n * @return s the set\n */\ntemplate <typename O, typename T>\nvoid convert(T a[], int m, int n, std::set< Teuchos::SerialDenseVector<O,T> > &s)\n{\n  for ( int i = 0; i < m; i++ )\n    {\n      Teuchos::SerialDenseVector<O,T> v( Teuchos::View, a+i*n, n );\n      s.insert( v );\n    }\n};\n\n/**\n * \\brief Convert a std::vector of vectors to a matrix\n *\n * Each element of the std::vector becomes a column of the matrix\n */\ntemplate <typename O, typename T>\nvoid convert( const std::vector< Teuchos::SerialDenseVector<O,T> > &V, \n\t      Teuchos::SerialDenseMatrix<O,T> &M )\n{\n  M.shapeUninitialized( V[0].length(), (int)V.size() );\n  for ( int i = 0; i < (int)V.size(); i++ )\n    {\n      for ( int j = 0; j < V[0].length(); j++ )\n\t{\n\t  M(j,i) = V[i][j];\n\t}\n    };\n};\n\n/**\n * Add a set of vectors together.\n * @param vectors set of vectors to be added\n * @param result the accumualted values\n */\ntemplate< typename T, typename Operator>\nvoid accumulate( const std::vector< std::vector<T> > &vectors, \n\t\t std::vector<T> &result, Operator op)\n{\n  if( !vectors.empty() )\n    {\n\t//invariant: all vectors are of the same size\n      result = vectors[0] ;\n      int N = result.size() ;\n      for( int i = 1 ; i < vectors.size() ; ++i )\n\t{\n\t  #ifdef DEBUG\n\t  if ( vectors[i].size() != N ) \n\t    {\n\t      throw(std::runtime_error(\"Accumulate() vectors must all have the same size\"));\n\t    }\n\t  #endif\n\t  std::transform( result.begin(), result.end(), vectors[i].begin(),\n\t\t\t  result.begin(), op );\n\t}\n    }\n  else\n    {\n      result.clear();\n    }\n};\n\n\ntemplate< typename T >\nbool is_nan_or_inf( T x )\n{\n  if ( x != x || \n       x >= std::numeric_limits<T>::infinity() || \n       x <= -std::numeric_limits<T>::infinity() || \n       x >= std::numeric_limits<T>::max() ||\n       x <= -std::numeric_limits<T>::max() )\n    return true;\n  return false;\n}\n\ntemplate <typename O, typename T>\nbool has_nan_or_inf( const Teuchos::SerialDenseMatrix<O,T> &matrix )\n{\n  for ( O j = 0 ; j < matrix.numCols(); j++ )\n    {\n      for ( O i = 0 ; i < matrix.numRows(); i++ )\n\t{\n\t  if ( is_nan_or_inf<T>( matrix(i,j ) ) )\n\t    {\n\t      disp( matrix(i,j) );\n\t      return true;\n\t    }\n\t}\n    }\n  return false;\n}\n\n\nvoid get_column_norms( RealMatrix &A, RealVector &result );\n\n\n}  // namespace Pecos\n\n#endif\n", "meta": {"hexsha": "82073893fdebf8f26ff38737fff3a12d6d6b0cd1", "size": 26152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_stars_repo_name": "seakers/ExtUtils", "max_stars_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "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": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_issues_repo_name": "seakers/ExtUtils", "max_issues_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "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": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_forks_repo_name": "seakers/ExtUtils", "max_forks_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:13:14.000Z", "avg_line_length": 26.4964539007, "max_line_length": 146, "alphanum_fraction": 0.6303150811, "num_tokens": 7671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6504521436570099}}
{"text": "#include <fstream>\n#include<boost/shared_ptr.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/partition_2.h>\n#include <CGAL/Partition_traits_2.h>\n#include<CGAL/create_straight_skeleton_2.h>\n#include<CGAL/create_offset_polygons_2.h>\n#include <CGAL/linear_least_squares_fitting_2.h>\n#include <CGAL/extremal_polygon_2.h>\n#include <CGAL/minkowski_sum_2.h>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QGraphicsLineItem>\n\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n#include <CGAL/Qt/PolygonGraphicsItem.h>\n#include <CGAL/Qt/PolygonWithHolesGraphicsItem.h>\n#include <CGAL/Qt/LineGraphicsItem.h>\n\n// the two base classes\n#include \"ui_Polygon_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Segment_2 Segment_2;\ntypedef K::Line_2 Line_2;\n\ntypedef CGAL::Polygon_2<K,std::list< Point_2 > > Polygon2; // it must be a list for the partition\ntypedef CGAL::Polygon_with_holes_2<K,std::list< Point_2 > > Polygon_with_holes_2;\n\ntypedef CGAL::Straight_skeleton_2<K> Ss ;\n\ntypedef boost::shared_ptr<Ss> SsPtr ;\n\ntypedef boost::shared_ptr<Polygon2> PolygonPtr ;\n\ntypedef std::vector<PolygonPtr> PolygonPtr_vector ;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Polygon_2\n{\n  Q_OBJECT\n\nprivate:\n\n  enum PartitionAlgorithm {YMonotone, ApproximateConvex, OptimalConvex} ;\n\n\n  CGAL::Qt::Converter<K> convert;\n  Polygon2 poly, kgon;\n  Polygon_with_holes_2 selfmink;\n  QGraphicsScene scene;\n\n  CGAL::Qt::PolygonGraphicsItem<Polygon2> * pgi;\n\n  CGAL::Qt::GraphicsViewPolylineInput<K> * pi;\n\n  CGAL::Qt::PolygonWithHolesGraphicsItem<Polygon_with_holes_2> * minkgi;\n\n  std::list<Polygon2> partitionPolygons;\n  std::list<CGAL::Qt::PolygonGraphicsItem<Polygon2>* >  partitionGraphicsItems;\n  std::list<QGraphicsLineItem* >  skeletonGraphicsItems;\n  std::list<QGraphicsLineItem* >  offsetGraphicsItems;\n  CGAL::Qt::LineGraphicsItem<K>* lgi;\n\n  CGAL::Qt::PolygonGraphicsItem<Polygon2> * kgongi;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void on_actionClear_triggered();\n\n  void on_actionLoadPolygon_triggered();\n  void on_actionSavePolygon_triggered();\n\n  void on_actionSelfMinkowskiSum_triggered();\n  void on_actionRecenter_triggered();\n  void on_actionMaximumAreaKGon_triggered();\n  void on_actionInnerSkeleton_triggered();\n  void on_actionOuterOffset_triggered();\n  void on_actionLinearLeastSquaresFitting_triggered();\n  void on_actionLinearLeastSquaresFittingOfSegments_triggered();\n  void on_actionCreateInputPolygon_toggled(bool);\n\n  void on_actionYMonotonePartition_triggered();\n  void on_actionApproximateConvexPartition_triggered();\n  void on_actionOptimalConvexPartition_triggered();\n  void partition(PartitionAlgorithm);\n\n  void clearPartition();\n  void clearMinkowski();\n  void clearSkeleton();\n  void clearOffset();\n  void clear();\n\n  virtual void open(QString);\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  minkgi = nullptr;\n  // Add a GraphicItem for the Polygon2\n  pgi = new CGAL::Qt::PolygonGraphicsItem<Polygon2>(&poly);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   pgi, SLOT(modelChanged()));\n\n  scene.addItem(pgi);\n\n  kgongi =  new CGAL::Qt::PolygonGraphicsItem<Polygon2>(&kgon);\n  kgongi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  kgongi->hide();\n  scene.addItem(kgongi);\n\n\n  lgi = new CGAL::Qt::LineGraphicsItem<K>();\n  lgi->setPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  lgi->hide();\n  scene.addItem(lgi);\n  assert(lgi->scene() == &scene);\n  // Setup input handlers. They get events before the scene gets them\n  pi = new CGAL::Qt::GraphicsViewPolylineInput<K>(this, &scene, 0, true);\n\n  this->actionCreateInputPolygon->setChecked(true);\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  //\n  // Manual handling of actions\n  //\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\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  // Uncomment the following line to get antialiasing by default.\n//   actionUse_Antialiasing->setChecked(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->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_Polygon_2.html\");\n  this->addAboutCGAL();\n  this->setupExportSVG(action_Export_SVG, graphicsView);\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n          this, SLOT(open(QString)));\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  this->actionCreateInputPolygon->setChecked(false);\n  std::list<Point_2> points;\n  if(CGAL::assign(points, o)){\n    if((points.size() == 1)&& poly.size()>0){\n\n    } else {\n      poly.clear();\n      if(points.front() == points.back()){\n        points.pop_back();\n      }\n      poly.insert(poly.vertices_begin(), points.begin(), points.end());\n    }\n    Q_EMIT( changed());\n  }\n}\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  poly.clear();\n  clear();\n  this->actionCreateInputPolygon->setChecked(true);\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPolygon_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Polygon File\"),\n                                                  \".\",\n                                                  tr( \"Polyline files (*.polygons.cgal);;\"\n                                                      \"WSL files (*.wsl);;\"\n                                                    #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                      \"WKT files (*.wkt *.WKT);;\"\n                                                    #endif\n                                                      \"All file (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\nvoid\nMainWindow::open(QString fileName)\n{\n  this->actionCreateInputPolygon->setChecked(false);\n  std::ifstream ifs(qPrintable(fileName));\n  poly.clear();\n  if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n  {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n    CGAL::Polygon_with_holes_2<K> P;\n    CGAL::read_polygon_WKT(ifs, P);\n    poly = Polygon2(P.outer_boundary().begin(),\n                    P.outer_boundary().end());\n#endif\n  }\n  else\n  {\n    ifs >> poly;\n  }\n  clear();\n\n  this->addToRecentFiles(fileName);\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionSavePolygon_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n                                                  tr(\"Save Polygon\"),\n                                                  \".\",\n                                                  tr( \"Polyline files (*.polygons.cgal);;\"\n                                                    #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                      \"WKT files (*.wkt *.WKT);;\"\n                                                    #endif\n                                                      \"All file (*)\"));\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      CGAL::Polygon_2<K> P(poly.begin(),\n                           poly.end());\n      CGAL::Polygon_with_holes_2<K> Pwh(P);\n      CGAL::write_polygon_WKT(ofs, Pwh);\n#endif\n    }\n    else\n      ofs << poly;\n  }\n}\n\n\nvoid\nMainWindow::on_actionCreateInputPolygon_toggled(bool checked)\n{\n  poly.clear();\n  clear();\n  if(checked){\n    scene.installEventFilter(pi);\n  } else {\n    scene.removeEventFilter(pi);\n  }\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(pgi->boundingRect());\n  this->graphicsView->fitInView(pgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\nvoid\nMainWindow::on_actionSelfMinkowskiSum_triggered()\n{\n  if(poly.size()>0){\n    if(! poly.is_simple()){\n      return;\n    }\n\n    selfmink = minkowski_sum_2 (poly, poly);\n\n    minkgi = new CGAL::Qt::PolygonWithHolesGraphicsItem<Polygon_with_holes_2>(&selfmink);\n\n    minkgi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    scene.addItem(minkgi);\n    minkgi->setEdgesPen(QPen(Qt::darkRed, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  }\n}\n\n\n\n\nvoid\nMainWindow::on_actionInnerSkeleton_triggered()\n{\n  if(poly.size()>0){\n    if(! poly.is_simple()){\n      return;\n    }\n    clear();\n    if(! poly.is_counterclockwise_oriented()){\n      poly.reverse_orientation();\n    }\n    SsPtr iss = CGAL::create_interior_straight_skeleton_2(poly.vertices_begin(), poly.vertices_end());\n\n    CGAL::Straight_skeleton_2<K> const& ss = *iss;\n\n    typedef Ss::Vertex_const_handle     Vertex_const_handle ;\n    typedef Ss::Halfedge_const_handle   Halfedge_const_handle ;\n    typedef Ss::Halfedge_const_iterator Halfedge_const_iterator ;\n\n    Halfedge_const_handle null_halfedge ;\n    Vertex_const_handle   null_vertex ;\n\n    for ( Halfedge_const_iterator i = ss.halfedges_begin(); i != ss.halfedges_end(); ++i )\n      {\n        if ( i->is_bisector() ){\n          Segment_2 s(i->opposite()->vertex()->point(), i->vertex()->point());\n          skeletonGraphicsItems.push_back(new QGraphicsLineItem(convert(s)));\n          scene.addItem(skeletonGraphicsItems.back());\n          skeletonGraphicsItems.back()->setPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n        }\n      }\n\n  }\n\n}\n\nvoid\nMainWindow::on_actionOuterOffset_triggered()\n{\n  if(poly.size()>0 && poly.is_simple())\n  {\n    clear();\n\n    if(! poly.is_counterclockwise_oriented())\n      poly.reverse_orientation();\n\n    double w = poly.bbox().xmax() - poly.bbox().xmin() ;\n    double h = poly.bbox().ymax() - poly.bbox().ymin() ;\n    double s = (std::max)(w,h);\n    double def_offset = s * 0.05 ;\n\n    bool ok;\n    const double off = QInputDialog::getDouble( this\n                                              , tr(\"Offset distance\")\n                                              , tr(\"Offset distance:\")\n                                              , def_offset\n                                              , 0.0\n                                              , s\n                                              , 2\n                                              , &ok\n                                              );\n    if ( ok )\n    {\n      PolygonPtr_vector lContours = create_exterior_skeleton_and_offset_polygons_2(off,poly) ;\n\n      PolygonPtr_vector::const_iterator frame ;\n\n      double max_area = 0.0 ;\n\n      for( PolygonPtr_vector::const_iterator cit = lContours.begin(); cit != lContours.end(); ++ cit )\n      {\n        double area = (*cit)->area();\n        if ( area > max_area )\n        {\n          max_area = area ;\n          frame = cit ;\n        }\n      }\n\n      for( PolygonPtr_vector::const_iterator cit = lContours.begin(); cit != lContours.end(); ++ cit )\n      {\n        if ( cit != frame )\n        {\n          Polygon2 const& lContour = **cit ;\n          lContour.area();\n          for ( Polygon2::Edge_const_iterator eit = lContour.edges_begin(); eit != lContour.edges_end(); ++ eit )\n          {\n            Segment_2 s(eit->source(), eit->target());\n            offsetGraphicsItems.push_back(new QGraphicsLineItem(convert(s)));\n            scene.addItem(offsetGraphicsItems.back());\n            offsetGraphicsItems.back()->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid\nMainWindow::on_actionMaximumAreaKGon_triggered()\n{\n  if( (poly.size()>2) && poly.is_convex()){\n    clear();\n\n    kgon.clear();\n    std::vector<Point_2> points(poly.vertices_begin(),\n                                poly.vertices_end());\n    CGAL::maximum_area_inscribed_k_gon_2(points.begin(),\n                                         points.end(),\n                                         3,\n                                         std::back_inserter(kgon));\n\n    kgongi->modelChanged();\n    kgongi->show();\n  } else {\n    std::cout << \"The polygon must be convex\" << std::endl;\n  }\n}\n\nvoid\nMainWindow::on_actionLinearLeastSquaresFitting_triggered()\n{\n  if(poly.size()>2){\n    clear();\n\n    Line_2 line;\n    CGAL::linear_least_squares_fitting_2(poly.vertices_begin(),\n                                         poly.vertices_end(),\n                                         line,\n                                         CGAL::Dimension_tag<0>());\n\n    lgi->setLine(line);\n    lgi->show();\n  }\n}\n\nvoid\nMainWindow::on_actionLinearLeastSquaresFittingOfSegments_triggered()\n{\n  if(poly.size()>2){\n    clear();\n\n    Line_2 line;\n    CGAL::linear_least_squares_fitting_2(poly.edges_begin(),\n                                         poly.edges_end(),\n                                         line,\n                                         CGAL::Dimension_tag<1>());\n\n\n    lgi->setLine(line);\n    lgi->show();\n  }\n}\n\nvoid\nMainWindow::on_actionYMonotonePartition_triggered()\n{\n  partition(YMonotone);\n}\n\n\nvoid\nMainWindow::on_actionOptimalConvexPartition_triggered()\n{\n  partition(OptimalConvex);\n}\n\n\nvoid\nMainWindow::on_actionApproximateConvexPartition_triggered()\n{\n  partition(ApproximateConvex);\n}\n\n\nvoid\nMainWindow::partition(PartitionAlgorithm pa)\n{\n  if(poly.size()>0){\n    clear();\n    if(! poly.is_counterclockwise_oriented()){\n      poly.reverse_orientation();\n    }\n    switch (pa) {\n    case YMonotone :\n      CGAL::y_monotone_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n      break;\n    case ApproximateConvex:\n      CGAL::approx_convex_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n      break;\n    default:\n      CGAL::optimal_convex_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n      break;\n    }\n    for(std::list<Polygon2>::iterator it = partitionPolygons.begin();\n        it != partitionPolygons.end();\n        ++it){\n      partitionGraphicsItems.push_back(new CGAL::Qt::PolygonGraphicsItem<Polygon2>(&(*it)));\n      scene.addItem(partitionGraphicsItems.back());\n      partitionGraphicsItems.back()->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n    }\n  }\n}\n\nvoid\nMainWindow::clearPartition()\n{\n  partitionPolygons.clear();\n  for(std::list<CGAL::Qt::PolygonGraphicsItem<Polygon2>* >::iterator it = partitionGraphicsItems.begin();\n      it != partitionGraphicsItems.end();\n      ++it){\n    scene.removeItem(*it);\n  }\n  partitionGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clearMinkowski()\n{\n  if(minkgi != nullptr){\n    scene.removeItem(minkgi);\n    delete minkgi;\n    minkgi = nullptr;\n  }\n}\n\nvoid\nMainWindow::clearSkeleton()\n{ for(std::list<QGraphicsLineItem* >::iterator it = skeletonGraphicsItems.begin();\n      it != skeletonGraphicsItems.end();\n      ++it){\n    scene.removeItem(*it);\n  }\n  skeletonGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clearOffset()\n{ for(std::list<QGraphicsLineItem* >::iterator it = offsetGraphicsItems.begin();\n      it != offsetGraphicsItems.end();\n      ++it){\n    scene.removeItem(*it);\n  }\n  offsetGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clear()\n{\n  clearPartition();\n  clearMinkowski();\n  clearSkeleton();\n  clearOffset();\n  lgi->hide();\n  kgongi->hide();\n}\n\n\n#include \"Polygon_2.moc\"\n#include <CGAL/Qt/resources.h>\n\nint main(int argc, char **argv)\n{\n  QApplication app(argc, argv);\n\n  app.setOrganizationDomain(\"geometryfactory.com\");\n  app.setOrganizationName(\"GeometryFactory\");\n  app.setApplicationName(\"Polygon_2 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  Q_INIT_RESOURCE(Polygon_2);\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n", "meta": {"hexsha": "98d66af08c5777a7774c188de29d0f0885bc717a", "size": 17034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_stars_repo_name": "mtola/cgal", "max_stars_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T23:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-08T23:06:26.000Z", "max_issues_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_issues_repo_name": "samrat2825/cgal-dev", "max_issues_repo_head_hexsha": "eab5df14e118deb20db7373717bac273f1775a92", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "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": 27.5185783522, "max_line_length": 127, "alphanum_fraction": 0.6251027357, "num_tokens": 4106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6504521316173905}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n\n//#define USE_ATLAS\n#include <OpenTissue/core/math/big/big_svd.h>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n\n\ntemplate< typename matrix_type,typename vector_type>\nvoid test(matrix_type const & A, vector_type  & x, vector_type const & b, vector_type const & y)\n{\n  using std::min;\n  using std::max;\n  \n  typedef typename matrix_type::value_type real_type;\n  typedef typename matrix_type::size_type  size_type;\n  \n  real_type const tol = boost::numeric_cast<real_type>(0.01);\n  \n  \n  \n  OpenTissue::math::big::svd(A,x,b);\n  \n  for(size_type i = 0; i < x.size();++i)\n    BOOST_CHECK_CLOSE( real_type( x(i) ), real_type( y(i) ), tol );\n  \n  {\n    matrix_type invA;\n    \n    OpenTissue::math::big::svd_invert(A,invA);\n    \n    size_type m = A.size1();\n    size_type n = A.size2();\n    matrix_type I;\n    I.resize(m,n,false);\n    ublas::noalias(I) = ublas::prod(A,invA);\n    \n    size_type K = min (m, n );\n    for(size_type i = 0; i < K;++i)\n      BOOST_CHECK_CLOSE( real_type( I(i,i) ), real_type( 1.0 ), tol );\n    \n    for(size_type i = 0; i < I.size1(); ++i)\n      for(size_type j = 0; j < I.size2(); ++j)\n        if(i!=j)\n          BOOST_CHECK( fabs( I(i,j) ) <  10e-10 );\n  }\n  \n}\n\n\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_svd);\n\n\nBOOST_AUTO_TEST_CASE(logic_and_valid_arguments_testing)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n  \n  {\n    matrix_type A;\n    vector_type x,b;\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    b.resize(4,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    x.resize(4,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    x.resize(4,false);\n    b.resize(4,false);\n    A(0,0) = A(1,1) = A(2,2) = A(3,3) = 1.0;\n    \n    BOOST_CHECK_NO_THROW( OpenTissue::math::big::svd(A,x,b) );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    x.resize(4,false);\n    b.resize(4,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    x.resize(3,false);\n    b.resize(4,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    x.resize(4,false);\n    b.resize(3,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n  {\n    matrix_type A;\n    vector_type x,b;\n    A.resize(4,4,false);\n    x.resize(3,false);\n    b.resize(3,false);\n    \n    BOOST_CHECK_THROW( OpenTissue::math::big::svd(A,x,b), std::invalid_argument );\n  }\n}\n\n\n\n\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  \n  typedef ublas::compressed_matrix<double> matrix_type;\n  typedef ublas::vector<double>            vector_type;\n  typedef vector_type::size_type           size_type;\n  \n  \n  \n  \n  for(size_type tst=0;tst<1000;++tst)\n  {\n    size_type N = 10;\n    \n    matrix_type A;\n    A.resize(N,N,false);\n    \n    vector_type x;\n    x.resize(N,false);\n    \n    vector_type b;\n    b.resize(N,false);\n    \n    vector_type y;\n    y.resize(N,false);\n    \n    matrix_type R;\n    R.resize(N,N,false);\n    \n    OpenTissue::math::Random<double> value(0.0,1.0);\n    for(size_t i=0;i<R.size1();++i)\n    { \n      b(i) = value();\n      x(i) = value();\n      y(i) = value();\n      for(size_t j=0;j<R.size2();++j)\n        R(i,j) = value();\n    }\n    ublas::noalias(A) = ublas::sparse_prod<matrix_type>( ublas::trans(R), R );\n    // forcing A to become PD matrix (it should be non-singular at all times)\n    for(size_t i=0;i<R.size1();++i)\n      A(i,i) += 0.5;\n    \n    ublas::noalias(b) = ublas::prod(A,x);\n    y.assign(x);\n    \n    x.clear();\n    test(A,x,b,y);\n  }\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f8e84f446f2b05de990400966efc3f8164685639", "size": 4853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/svd/src/unit_svd.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/big/svd/src/unit_svd.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/big/svd/src/unit_svd.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 23.2200956938, "max_line_length": 96, "alphanum_fraction": 0.6229136617, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6504521201378197}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 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#include <rokko/rokko.hpp>\n#include <rokko/lapack.h>\n#include <boost/lexical_cast.hpp>\n\ntypedef rokko::localized_vector<std::complex<double> > vector_t;\ntypedef rokko::localized_matrix<std::complex<double>, rokko::matrix_col_major> matrix_t;\n\nint main(int argc, char *argv[]) {\n  int info;\n  int m = 10;\n  int n = 6;\n  if (argc > 2) {\n    m = boost::lexical_cast<int>(argv[1]);\n    n = boost::lexical_cast<int>(argv[2]);\n  }\n  std::cout << \"m = \" << m << \"\\nn = \" << n << std::endl;\n  int k = std::min(m, n);\n\n  // generate random martix\n  matrix_t a = matrix_t::Random(m, n);\n  std::cout << \"Input random column vectors A:\\n\" << a << std::endl;\n\n  // orthonormalization\n  matrix_t mat = a;\n  vector_t tau(k);\n  info = LAPACKE_zgeqrf(LAPACK_COL_MAJOR, m, n, &mat(0, 0), m, &tau(0));\n  matrix_t r = mat;\n  for (int i = 0; i < m; ++i)\n    for (int j = 0; j < i; ++j)\n      r(i, j) = 0;\n  std::cout << \"Upper triangle matrix R:\\n\" << r << std::endl;\n  info = LAPACKE_zungqr(LAPACK_COL_MAJOR, m, k, k, &mat(0, 0), m, &tau(0));\n  matrix_t q(m, k);\n  for (int i = 0; i < m; ++i)\n    for (int j = 0; j < k; ++j)\n      q(i, j) = mat(i, j);\n  std::cout << \"Orthonormalized column vectors Q:\\n\" << q << std::endl;\n\n  // check orthonormality\n  matrix_t check = q.adjoint() * q;\n  std::cout << \"Check orthogonality:\\n\" << check << std::endl;\n  std::cout << \"Error: | I - Qt Q | = \" <<  (matrix_t::Identity(n, n) - check).norm() << std::endl;\n\n  // check decomposition\n  std::cout << \"Reconstruction of original matrix QR:\\n\" << q * r << std::endl;\n  std::cout << \"Error: | A - QR | = \" <<  (a - q * r).norm() << std::endl;\n}\n", "meta": {"hexsha": "6dcbce7a72e8e331e8b9c8205383a4ec8313afab", "size": 2078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/lapack/orthonormalization_c.cpp", "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": "example/cxx/lapack/orthonormalization_c.cpp", "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": "example/cxx/lapack/orthonormalization_c.cpp", "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": 35.2203389831, "max_line_length": 99, "alphanum_fraction": 0.5601539942, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6504521195777707}}
{"text": "#include <StatSim/Math.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n#include <cmath>\n#include <numbers>\n\nnamespace StatSim {\n\tdouble BinomialPMF(int tryCount, int occurCount, double probability) {\n\t\tconst auto numberOfCases = [](int n, int r) {\n\t\t\tif (n - r < r) {\n\t\t\t\tr = n - r;\n\t\t\t}\n\n\t\t\tboost::multiprecision::cpp_int result = 1;\n\t\t\tfor (int i = 0; i < r; ++i) {\n\t\t\t\tresult *= n - i;\n\t\t\t}\n\t\t\tfor (int i = 0; i < r; ++i) {\n\t\t\t\tresult /= i + 1;\n\t\t\t}\n\t\t\treturn result;\n\t\t}(tryCount, occurCount);\n\n\t\tconst boost::multiprecision::cpp_bin_float_100 probabilityEx(probability);\n\t\tconst auto occurProbability = boost::multiprecision::pow(probabilityEx, occurCount);\n\t\tconst auto notOccurProbability = boost::multiprecision::pow(1 - probabilityEx, tryCount - occurCount);\n\n\t\tconst auto result = static_cast<boost::multiprecision::cpp_bin_float_100>(numberOfCases) * occurProbability * notOccurProbability;\n\t\treturn static_cast<double>(result);\n\t}\n\tdouble NormalCDF(double value, double mean, double standardDeviation) {\n\t\treturn 0.5 * std::erfc((mean - value) / standardDeviation / std::numbers::sqrt2_v<double>);\n\t}\n}", "meta": {"hexsha": "4d6fdd0d95df36fd02e4c7bba65545158e0d31c2", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Math.cpp", "max_stars_repo_name": "kmc7468/StatSim", "max_stars_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "kmc7468/StatSim", "max_issues_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "kmc7468/StatSim", "max_forks_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 132, "alphanum_fraction": 0.7000856898, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6504080141684625}}
{"text": "#include<bits/stdc++.h>\r\n#include <boost/multiprecision/cpp_int.hpp> \r\n#define ll long long int\r\n#define watch(x) cout << (#x) << \" is \" << (x) << endl  //watch function print variable and value for debugging\r\n#define count_ones __builtin_popcountll                  // count_ones(9) is equal to 2 valid for ll also\r\n#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL);\r\n#define fo(i,n) for(ll i=0;i<n;i++)\r\nusing boost::multiprecision::cpp_int; \r\nusing namespace std;\r\n\r\n\r\ncpp_int boost_factorial(int num) \r\n{ \r\n    cpp_int fact = 1; \r\n    for (int i=num; i>1; --i)     \r\n        fact *= i; \r\n    return fact; \r\n} \r\n\r\n\r\nint main() {\r\n #ifndef ONLINE_JUDGE\r\n\t    freopen(\"input.txt\", \"r\", stdin);\r\n        freopen(\"output.txt\", \"w\", stdout);\r\n #endif\r\n       fast_io\r\n \r\n       ll t;\r\n       cin>>t;\r\n       while(t--)\r\n       {\r\n       \tll n;\r\n       \tcin>>n;\r\n       \tcout<<boost_factorial(n)<<\"\\n\";\r\n\r\n       }\r\n\r\n\r\n   return 0;\r\n }", "meta": {"hexsha": "e94cef75fd92b428d7eeedcd65c9e4e788b9e623", "size": 947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ_LIST/fctrl2(c++17).cpp", "max_stars_repo_name": "Nandini2901/Hacktoberfest-1", "max_stars_repo_head_hexsha": "ac5eff7c8678f3ce00041bdba20c63c416dac690", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 580.0, "max_stars_repo_stars_event_min_datetime": "2020-04-08T16:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:09:13.000Z", "max_issues_repo_path": "SPOJ_LIST/fctrl2(c++17).cpp", "max_issues_repo_name": "Nandini2901/Hacktoberfest-1", "max_issues_repo_head_hexsha": "ac5eff7c8678f3ce00041bdba20c63c416dac690", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T11:56:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T21:19:05.000Z", "max_forks_repo_path": "SPOJ_LIST/fctrl2(c++17).cpp", "max_forks_repo_name": "Nandini2901/Hacktoberfest-1", "max_forks_repo_head_hexsha": "ac5eff7c8678f3ce00041bdba20c63c416dac690", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2020-06-07T16:30:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T19:30:47.000Z", "avg_line_length": 23.675, "max_line_length": 112, "alphanum_fraction": 0.5575501584, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6503880953233281}}
{"text": "#include \"point_to_plane.h\"\n#include <Eigen/Dense>\n\nusing namespace probreg;\n\nPt2PlResult probreg::computeTwistForPointToPlane(const Matrix3X& model,\n                                                 const Matrix3X& target,\n                                                 const Matrix3X& target_normal,\n                                                 const Vector& weight) {\n    Matrix6 ata = Matrix6::Zero();\n    Vector6 atb = Vector6::Zero();\n    Float r_sum = 0.0;\n\n    for (auto k = 0; k < model.cols(); ++k){\n        const auto& vertex_k = model.col(k);\n        const auto& target_k = target.col(k);\n        const auto& normal_k = target_normal.col(k);\n        const auto& weight_k = weight[k];\n        const Float residual = normal_k.dot(target_k - vertex_k);\n        const Vector6 jac = (Vector6() << vertex_k.cross(normal_k), normal_k).finished();\n        ata += weight_k * jac * jac.transpose();\n        atb += weight_k * residual * jac;\n        r_sum += weight_k * weight_k * residual * residual;\n    }\n    return std::make_pair(ata.selfadjointView<Eigen::Upper>().ldlt().solve(atb), r_sum);\n}\n", "meta": {"hexsha": "f9a35946ca7c2634844b948a471617693e5dab64", "size": 1105, "ext": "cc", "lang": "C++", "max_stars_repo_path": "probreg/cc/point_to_plane.cc", "max_stars_repo_name": "KentaKawamata/probreg", "max_stars_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "probreg/cc/point_to_plane.cc", "max_issues_repo_name": "KentaKawamata/probreg", "max_issues_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_issues_repo_licenses": ["MIT"], "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/point_to_plane.cc", "max_forks_repo_name": "KentaKawamata/probreg", "max_forks_repo_head_hexsha": "ab29c01353f5ca490653172523d351cce26017c8", "max_forks_repo_licenses": ["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.9259259259, "max_line_length": 89, "alphanum_fraction": 0.5628959276, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6503851371182298}}
{"text": "#include<iostream>\n#include <math.h>\n#include <vector>\n#include <random>\n#include <iomanip>\n#include <Eigen/Core>\n#include <algorithm>\nusing namespace std;\n//\u9ad8\u65af\u5bc6\u5ea6\u51fd\u6570\nfloat gussian_fx(float x){\n    float weight=1/(sqrt(2*M_PI));\n    float exow=-pow(x,2)/2;\n    return (weight*exp(exow));\n};\n//\u6c42X<x \u7684\u6982\u7387\nfloat guassian_pb(float x, float u,float sigma2){\n    float detx=0.01;\n    float pb=0;\n    float MINX=-5;\n    while (MINX<=(x-u)/sqrt(sigma2)){\n        MINX+=detx;\n        pb+=detx*gussian_fx(MINX);\n    };\n    return pb;\n};\nfloat guassian_pb_from_data(vector<float >data,float x){\n    static int i=0,j=0;\n    while(i<data.size()){\n        if(data[i]<=x){i++;j++;}\n        else{i++;};\n    }\n    return float(j)/data.size();\n}\n//\u6700\u5927\u4f3c\u7136\u4f30\u8ba1\uff0c\u63a5\u53d7\u53c2\u6570\u4e3a\u5411\u91cf\uff0c\u8fd4\u56depair first\u4e3a\u5747\u503c\uff0csecond\u4e3a\u65b9\u5dee\npair<float,float> MaxLikelihood(vector<float > &xi){\n    float hatu=0; float hatsigma2=0;\n    for (int i = 0; i <xi.size() ; ++i) {\n        hatu+=xi[i];\n    }\n    for (int j = 0; j <xi.size() ; ++j) {\n        hatsigma2+=pow(xi[j]-(hatu/xi.size()),2);\n    }\n    pair<float ,float > us={hatu/xi.size(),hatsigma2/xi.size()};\n    return us;\n};\n\n//\u751f\u6210\u6b63\u6001\u5206\u5e03\uff0cmu\u5747\u503c\uff0csigma2\u65b9\u5dee\uff0c\u9ed8\u8ba4\u4e2a\u6570500\nvector<float >NormalGenerating(float mu,float sigma2,int length=500){\n    random_device rd;\n    std::mt19937 gen(rd());\n    uniform_real_distribution<float > ud(0.0,1.0);\n    int i=0;\n    vector<float > seed;\n    while(i<length) {\n        float x = ud(gen);\n        float y = ud(gen);\n        float temp;\n        if (i % 2) {\n            temp =cos(2 * M_PI * x) * sqrt(-2 * log(1 - y));\n        }\n        else{\n            temp=sin(2*M_PI*x)*sqrt(-2*log(1-y));\n        }\n        float ns=temp*sqrt(sigma2)+mu;\n        i++;\n        seed.push_back(ns);\n    }\n    return seed;\n}\n//\u751f\u6210\u6b63\u6001\u5206\u5e03\uff0cmu\u5747\u503c\uff0csigma2\u65b9\u5dee\uff0c\u9ed8\u8ba4\u4e2a\u6570500\nvector<float >NormalGenerating2(float mu,float sigma2,int length=500){\n    random_device rd;\n    std::mt19937 gen(rd());\n    normal_distribution<float > normal(mu,sqrt(sigma2));\n    vector<float >seed;\n    while(length--){\n        seed.push_back(normal(gen));\n    }\n    return seed;\n}\n\n//\u9700\u8981\u663e\u793a\u521d\u59cb\u5316\nstruct MultiNormal{\n    int length=500;\n    float u=0;\n    float sigma2=0;\n    vector<float> Gussiandata;\n    MultiNormal(vector<float> data){\n        u=MaxLikelihood(data).first;\n        sigma2=MaxLikelihood(data).second;\n        Gussiandata=data;\n    }\n};\n//\u6df7\u5408\u9ad8\u65af\u5206\u5e03\uff0c\u5c06\u591a\u4e2a\u6b63\u6001\u5206\u5e03\u76f8\u52a0\nvector<float>MultiNormalAdding(vector <MultiNormal> &kargs){\n    vector<float > reciver(500,0);\n    int k=kargs.size();\n    for (int loc = 0; loc <500 ; ++loc) {\n        int j=0;\n        while(j<k) {\n            reciver[loc]+=kargs[j].Gussiandata[loc];\n            j++;\n        }\n    }\n    return reciver;\n}\n//\u6df7\u5408\u9ad8\u65af\u5206\u5e03\uff0c\u5c06\u591a\u4e2a\u6b63\u6001\u5206\u5e03\u6df7\u5408\nvector<float>MultiNormalMerging(vector <MultiNormal> &kargs){\n    int k=kargs.size();\n    int Alllength=0;\n    int i=0;\n    while(i<k){\n        Alllength+=kargs[i].Gussiandata.size();\n        i++;\n    }\n    vector<float > reciver(Alllength,0);\n    int j=0;\n    int det=0;\n    while(j<k){\n        for (int l = 0; l <kargs[j].Gussiandata.size() ; ++l) {\n            int pos=j-1;\n            if(pos==-1)pos=0;\n            reciver[l+j*kargs[pos].Gussiandata.size()]=kargs[j].Gussiandata[l];\n        }\n        j++;\n    }\n    return reciver;\n}\n\n//\u751f\u6210\u7edf\u8ba1\u6570\u636e\nvector<vector<float >> CalNormalData(vector<float > &multgassian,int quration,int GMM=2){\n    vector<float > temp=multgassian;\n    sort(temp.begin(),temp.end());\n    float mindata=temp.front();\n    float maxdata=temp.back();\n    float middle=(mindata+maxdata)/2;\n    cout<<middle<<endl;\n    //cout<<temp.size()<<endl;\n    //for(auto &item:temp)cout<<item<<endl;\n    int qu=quration;//\u5206\u533a\u6570\n    float step=(maxdata-mindata)/qu;//\u5206\u533a\u6570;\n    vector<vector<float >> SortedHistData;\n    int i=0;\n    int pos=0;\n    while(i<qu){\n        vector<float> tempdata;\n        while(mindata+i*step<=temp[pos]&&temp[pos]<=mindata+(i+1)*step){\n            tempdata.push_back(temp[pos]);\n            pos++;\n        }\n        if(tempdata.size()==0) tempdata.push_back(0);//\u9632\u6b62\u8be5\u5206\u533a\u4e3a\u7a7a\n        SortedHistData.push_back(tempdata);\n        tempdata.clear();\n        i++;\n    }\n    Eigen::MatrixXf QKI(quration,GMM);\n    Eigen::MatrixXf SITA(GMM,2);//\u540c\u52170\u8868\u793amu 1\u8868\u793asigma2\n    SITA<<middle,middle,1,1;\n    vector<float> cof;\n    for (int i = 0; i <quration ; ++i) {\n        for (int j = 0; j <GMM ; ++j) { //\u6df7\u5408\u4e2a\u6570\n            QKI(i,j)=guassian_pb(SortedHistData[i].back(),SITA(j,0),SITA(j,1))\n                     -guassian_pb(SortedHistData[i].front(),SITA(j,0),SITA(j,1));\n        }\n    }\n    for (int k = 0; k <quration ; ++k) {\n        float temp=0;\n        for (int l = 0; l <GMM ; ++l) {\n            temp+=QKI(k,l);\n\n        }\n        cof.push_back(temp);\n    }\n    for (int m = 0; m <quration ; ++m) {\n        for (int n = 0; n <GMM ; ++n) {\n            if(!cof[m])QKI(m,n)=0;\n            else QKI(m,n)=QKI(m,n)/cof[m];\n        }\n\n    }\n    //cout<<QKI<<endl;\n\n\n\n    return SortedHistData;\n\n}\n\nint main(){\n    vector<float > seed1=NormalGenerating(0,2);\n    vector<float > seed2=NormalGenerating2(10,2);\n    //vector<float > seed3=NormalGenerating2(15,2);\n    MultiNormal No1(seed1);\n    MultiNormal No2(seed2);\n   // MultiNormal No3(seed3);\n    vector<MultiNormal> Multiseeds;\n    Multiseeds.push_back(No1);\n    Multiseeds.push_back(No2);\n    //Multiseeds.push_back(No3);\n    vector<float > merge=MultiNormalMerging(Multiseeds);\n    //for(auto &item:merge)cout<<item<<endl;\n    //cout<<\"the mixed guassian mean is u=\"<<MaxLikelihood(merge).first<<endl<<\"the mixed guassian variance is simga=\"<<MaxLikelihood(merge).second<<endl;\n//    for(auto &item:CalNormalData(merge,20)){\n//        for(auto &j:item){\n//            cout<<j<<\"  \"<<endl;\n//        }\n//        cout<<endl;\n//    }\n    CalNormalData(merge,20);\n    return 0;\n}", "meta": {"hexsha": "52e14cd4799bc06b36c101efe0c1186b20f38bb2", "size": 5694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Cessas/GMM", "max_stars_repo_head_hexsha": "7ee6ce0c228cc33bcd608e06d9423174e083a8fa", "max_stars_repo_licenses": ["MIT"], "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": "Cessas/GMM", "max_issues_repo_head_hexsha": "7ee6ce0c228cc33bcd608e06d9423174e083a8fa", "max_issues_repo_licenses": ["MIT"], "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": "Cessas/GMM", "max_forks_repo_head_hexsha": "7ee6ce0c228cc33bcd608e06d9423174e083a8fa", "max_forks_repo_licenses": ["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.9857819905, "max_line_length": 154, "alphanum_fraction": 0.5709518792, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6503073241552865}}
{"text": "#include <iostream>\n\n#include <boost/multiprecision/gmp.hpp>\n\n#include \"headers/euler.hpp\"\n\nconst int EXPANSIONS_BEGIN = 1;\nconst int EXPANSIONS_NUM = 1000;\n\ntypedef boost::multiprecision::mpz_int big_int;\ntypedef euler::fraction<big_int> fraction;\n\nfraction expandSqrt(int n, int depth = 0) {\n  if (depth == n) {\n    return fraction(1, 2);\n  }\n\n  fraction cd = expandSqrt(n, depth + 1);\n\n  big_int a = cd.denom + (depth ? 0 : cd.numer);\n  big_int b = depth ? (2 * cd.denom + cd.numer) : cd.denom;\n\n  return fraction(a, b);\n}\n\nint main(int argc, char** argv) {\n  int termsWithHigherDigitCountNumers = 0;\n\n  for (int i = EXPANSIONS_BEGIN; i <= EXPANSIONS_NUM; i++) {\n    fraction expandedTerm = expandSqrt(i);\n\n    if (euler::countDigits(expandedTerm.numer) > euler::countDigits(expandedTerm.denom)) {\n      termsWithHigherDigitCountNumers++;\n    }\n  }\n\n  std::cout << \"Total expansions between \" << EXPANSIONS_BEGIN << \" and \" << EXPANSIONS_NUM\n            << \" of sqrt(2) with higher counts of digits in numerator than denominator: \"\n            << termsWithHigherDigitCountNumers << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b75a620e2d5d526e693835ee7c0ae8d446fb1b5c", "size": 1111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "57.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": "57.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": "57.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": 25.8372093023, "max_line_length": 91, "alphanum_fraction": 0.6714671467, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6503000960557012}}
{"text": "#include <opencv2/opencv.hpp>\n#include <string>\n#include <chrono>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n\n\nstring file_1 = \"./LK1.png\";  // first image\nstring file_2 = \"./LK2.png\";  // second image\n\n\n\n\nclass OpticalFlowTracker{\npublic:\n    OpticalFlowTracker(const Mat &img1_,\n                       const Mat &img2_,\n                       const vector<KeyPoint> &kp1_,\n                       vector<KeyPoint> &kp2_,\n                       vector<bool> &success_,\n                       bool inverse_ = true,\n                       bool has_initial_ = false):\n                       img1(img1_), img2(img2_), kp1(kp1_), kp2(kp2_), success(success_), inverse(inverse_),\n                       has_initial(has_initial_) {}\n    \n    void calculateOpticalFlow(const Range &range);\n\nprivate:\n    const Mat &img1;\n    const Mat &img2;\n    const vector<KeyPoint> &kp1;\n    vector<KeyPoint> &kp2;\n    vector<bool> &success;\n    bool inverse = true;\n    bool has_initial = false;\n};\n\nvoid OpticalFlowMultiLevel(\n    const Mat &img1,\n    const Mat &img2,\n    const vector<KeyPoint> &kp1,\n    vector<KeyPoint> &kp2,\n    vector<bool> &success,\n    bool inverse = false\n);\n\n\nvoid OpticalFlowSingleLevel(\n    const Mat &img1,\n    const Mat &img2,\n    const vector<KeyPoint> &kp1,\n    vector<KeyPoint> &kp2,\n    vector<bool> &success,\n    bool inverse = false, bool has_initial = false);\n\n\n\n\n\ninline float GetPixelValue(const Mat &img, double x, double y){\n    if (x < 0) x = 0;\n    else if (x > img.cols - 1) x = img.cols - 1;\n    if (y < 0) y = 0;\n    else if (y > img.rows - 1) y = img.rows - 1;\n\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    float pixelValue = (1-xx)*(1-yy)*data[0] + (xx)*(1-yy)*data[1] \n                        + (1-xx)*(yy)*data[img.step] + (xx)*(yy)*data[img.step+1];\n    return pixelValue;\n}\n\n\n\n\n\n\n\nint main(int argc, char **argv){\n    cv::Mat img_1 = cv::imread(file_1, 0);\n    cv::Mat img_2 = cv::imread(file_2, 0);\n\n    // \u4eceimg1\u4e2d\u63d0\u53d6\u7279\u5f81\u70b9\uff0c\u4f7f\u7528GFTT\u7279\u5f81\n    vector<KeyPoint> kp_1;\n    Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20);\n    detector->detect(img_1, kp_1);\n\n\n    // OpenCV LK\u5149\u6d41\n    vector<Point2f> pts_1, pts_2;\n    for (auto &kp:kp_1){\n        pts_1.push_back(kp.pt);\n    }\n    vector<uchar> status;\n    vector<float> error;\n    cv::calcOpticalFlowPyrLK(img_1, img_2, pts_1, pts_2, status, error);\n    // \u753b\u56fe\uff1aBy OpenCV LK\u5149\u6d41\n    Mat img_2_CV;\n    cv::cvtColor(img_2,img_2_CV, CV_GRAY2BGR);\n    for (int i=0; i<pts_2.size(); i++){\n        if (status[i]){\n            cv::circle(img_2_CV, pts_2[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img_2_CV, pts_1[i], pts_2[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"By OpenCV\", img_2_CV);\n\n\n    // \u5355\u5c42LK\u5149\u6d41\n    vector<KeyPoint> kp_2_single;\n    vector<bool> success_single;\n    OpticalFlowSingleLevel(img_1, img_2, kp_1, kp_2_single, success_single);\n    // \u753b\u56fe\uff1a\u5355\u5c42LK\u5149\u6d41\n    Mat img_2_single;\n    cv::cvtColor(img_2,img_2_single, CV_GRAY2BGR);\n    for (int i=0; i<kp_2_single.size(); i++){\n        if (success_single[i]){\n            cv::circle(img_2_single, kp_2_single[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img_2_single, kp_1[i].pt, kp_2_single[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"By single\", img_2_single);\n\n    // \u53cd\u5411\u5355\u5c42LK\u5149\u6d41\n    vector<KeyPoint> kp_2_single_inverse;\n    vector<bool> success_single_inverse;\n    OpticalFlowSingleLevel(img_1, img_2, kp_1, kp_2_single_inverse, success_single_inverse, true);\n    // \u753b\u56fe\uff1a\u5355\u5c42LK\u5149\u6d41\n    Mat img_2_single_inverse;\n    cv::cvtColor(img_2,img_2_single_inverse, CV_GRAY2BGR);\n    for (int i=0; i<kp_2_single_inverse.size(); i++){\n        if (success_single_inverse[i]){\n            cv::circle(img_2_single_inverse, kp_2_single_inverse[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img_2_single_inverse, kp_1[i].pt, kp_2_single_inverse[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"By single_inverse\", img_2_single_inverse);\n\n\n    // \u591a\u5c42LK\u5149\u6d41\n    vector<KeyPoint> kp_2_multi;\n    vector<bool> success_multi;\n    OpticalFlowMultiLevel(img_1, img_2, kp_1, kp_2_multi, success_multi, true);\n    // OpticalFLowMultiLevel(img_1, img_2, kp_1, kp_2_multi, success_multi, true);\n    // \u753b\u56fe\uff1a\u591a\u5c42LK\u5149\u6d41\n    Mat img_2_multi;\n    cv::cvtColor(img_2,img_2_multi, CV_GRAY2BGR);\n    for (int i=0; i<kp_2_multi.size(); i++){\n        if (success_multi[i]){\n            cv::circle(img_2_multi, kp_2_multi[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img_2_multi, kp_1[i].pt, kp_2_multi[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"By multi\", img_2_multi);\n\n\n    \n\n\n\n\n\n\n\n\n    cv::waitKey(0);\n    return 0;\n}\n\n\n\n\n\n\n\n\nvoid OpticalFlowSingleLevel(\n    const Mat &img1,\n    const Mat &img2,\n    const vector<KeyPoint> &kp1,\n    vector<KeyPoint> &kp2,\n    vector<bool> &success,\n    bool inverse, bool has_initial){\n    \n    kp2.resize(kp1.size());\n    success.resize(kp1.size());\n    OpticalFlowTracker tracker(img1, img2, kp1, kp2, success, inverse, has_initial);\n    parallel_for_(Range(0, kp1.size()), \n        std::bind(&OpticalFlowTracker::calculateOpticalFlow, &tracker, placeholders::_1));\n}\n\n\nvoid OpticalFlowMultiLevel(\n    const Mat &img1,\n    const Mat &img2,\n    const vector<KeyPoint> &kp1,\n    vector<KeyPoint> &kp2,\n    vector<bool> &success,\n    bool inverse) {\n\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    vector<Mat> pyr1, pyr2;\n    for (int i = 0; i < pyramids; i++){\n        if(i==0){\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        }\n        else{\n            Mat img1_ptr, img2_ptr;\n            cv::resize(pyr1[i-1], img1_ptr, Size(), pyramid_scale, pyramid_scale);\n            cv::resize(pyr2[i-1], img2_ptr, Size(), pyramid_scale, pyramid_scale);\n            pyr1.push_back(img1_ptr);\n            pyr2.push_back(img2_ptr);\n        }\n    }\n\n    vector<KeyPoint> kp1_ptr, kp2_ptr;\n    for (auto &kp: kp1){\n        auto kp_top = kp;\n        kp_top.pt *= (pow(pyramid_scale, pyramids - 1));\n        kp1_ptr.push_back(kp_top);\n        kp2_ptr.push_back(kp_top);\n    }\n\n    for(int level = pyramids - 1; level >= 0; level--){\n        success.clear();\n        OpticalFlowSingleLevel(pyr1[level], pyr2[level], kp1_ptr, kp2_ptr, success, inverse, true);\n\n        if (level > 0){\n            for (auto &kp:kp1_ptr){\n                kp.pt /= pyramid_scale; \n            }\n            for (auto &kp:kp2_ptr){\n                kp.pt /= pyramid_scale; \n            }\n        }\n    }\n\n    for(auto &kp: kp2_ptr){\n        kp2.push_back(kp);\n    }\n}\n\n\n\n\n\n\n\n\n// void OpticalFlowTracker::calculateOpticalFlow(const Range &range){\n//     int half_patch_size = 4;\n//     int iterations = 10;\n//     for(size_t i = range.start; i < range.end; i++){\n//         auto kp = kp1[i];\n//         double dx = 0, dy = 0;\n//         if (has_initial){\n//             dx = kp2[i].pt.x - kp.pt.x;\n//             dy = kp2[i].pt.y - kp.pt.y;\n//         }\n\n//         double cost = 0, lastCost = 0;\n//         bool succ = true;\n\n//         // Gauss-Newton iterations\n//         Eigen::Matrix2d H = Eigen::Matrix2d::Zero();\n//         Eigen::Vector2d b = Eigen::Vector2d::Zero();\n//         Eigen::Vector2d J;\n\n//         for (int iter = 0; iter < iterations; iter++){\n\n//             cost = 0;\n//             if (inverse == false){\n//                 H = Eigen::Matrix2d::Zero();\n//                 b = Eigen::Vector2d::Zero();\n//             }\n//             else{\n//                 b = Eigen::Vector2d::Zero();\n//             }\n\n//             for (int x = -half_patch_size; x < half_patch_size; x++){\n//                 for (int y = -half_patch_size; y < half_patch_size; y++) {\n//                     double error = GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y) -\n//                                    GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);;  // Jacobian\n//                     if (inverse == false) {\n//                         J = -1.0 * Eigen::Vector2d(\n//                             0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -\n//                                    GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),\n//                             0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -\n//                                    GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1))\n//                         );\n//                     } else if (iter == 0) {\n//                         // in inverse mode, J keeps same for all iterations\n//                         // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n//                         J = -1.0 * Eigen::Vector2d(\n//                             0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -\n//                                    GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),\n//                             0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -\n//                                    GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1))\n//                         );\n//                     }\n//                     // compute H, b and set cost;\n//                     b += -error * J;\n//                     cost += error * error;\n//                     if (inverse == false || iter == 0) {\n//                         // also update H\n//                         H += J * J.transpose();\n//                     }\n//                 }\n//             }\n\n\n//             Eigen::Vector2d update = H.ldlt().solve(b);\n\n//             if (std::isnan(update[0])) {\n//                 // sometimes occurred when we have a black or white patch and H is irreversible\n//                 cout << \"update is nan\" << endl;\n//                 succ = false;\n//                 break;\n//             }\n\n//             if (iter > 0 && cost > lastCost) {\n//                 break;\n//             }\n\n//             // update dx, dy\n//             dx += update[0];\n//             dy += update[1];\n//             lastCost = cost;\n//             succ = true;\n\n//             if (update.norm() < 1e-2) {\n//                 // converge\n//                 break;\n//             }\n//         }\n\n//         success[i] = succ;\n\n//         // set kp2\n//         kp2[i].pt = kp.pt + Point2f(dx, dy);\n//     }\n// }\n\n\nvoid OpticalFlowTracker::calculateOpticalFlow(const Range &range) {\n    // parameters\n    int half_patch_size = 4;\n    int iterations = 10;\n    for (size_t i = range.start; i < range.end; i++) {\n        auto kp = kp1[i];\n        double dx = 0, dy = 0; // dx,dy need to be estimated\n        if (has_initial) {\n            dx = kp2[i].pt.x - kp.pt.x;\n            dy = kp2[i].pt.y - kp.pt.y;\n        }\n\n        double cost = 0, lastCost = 0;\n        bool succ = true; // indicate if this point succeeded\n\n        // Gauss-Newton iterations\n        Eigen::Matrix2d H = Eigen::Matrix2d::Zero();    // hessian\n        Eigen::Vector2d b = Eigen::Vector2d::Zero();    // bias\n        Eigen::Vector2d J;  // jacobian\n        for (int iter = 0; iter < iterations; iter++) {\n            if (inverse == false) {\n                H = Eigen::Matrix2d::Zero();\n                b = Eigen::Vector2d::Zero();\n            } else {\n                // only reset b\n                b = Eigen::Vector2d::Zero();\n            }\n\n            cost = 0;\n\n            // compute cost and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)\n                for (int y = -half_patch_size; y < half_patch_size; y++) {\n                    double error = GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y) -\n                                   GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);;  // Jacobian\n                    if (inverse == false) {\n                        J = -1.0 * Eigen::Vector2d(\n                            0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -\n                                   GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),\n                            0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -\n                                   GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1))\n                        );\n                    } else if (iter == 0) {\n                        // in inverse mode, J keeps same for all iterations\n                        // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n                        J = -1.0 * Eigen::Vector2d(\n                            0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -\n                                   GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),\n                            0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -\n                                   GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1))\n                        );\n                    }\n                    // compute H, b and set cost;\n                    b += -error * J;\n                    cost += error * error;\n                    if (inverse == false || iter == 0) {\n                        // also update H\n                        H += J * J.transpose();\n                    }\n                }\n\n            // compute update\n            Eigen::Vector2d update = H.ldlt().solve(b);\n\n            if (std::isnan(update[0])) {\n                // sometimes occurred when we have a black or white patch and H is irreversible\n                cout << \"update is nan\" << endl;\n                succ = false;\n                break;\n            }\n\n            if (iter > 0 && cost > lastCost) {\n                break;\n            }\n\n            // update dx, dy\n            dx += update[0];\n            dy += update[1];\n            lastCost = cost;\n            succ = true;\n\n            if (update.norm() < 1e-2) {\n                // converge\n                break;\n            }\n        }\n\n        success[i] = succ;\n\n        // set kp2\n        kp2[i].pt = kp.pt + Point2f(dx, dy);\n    }\n}", "meta": {"hexsha": "80cb4fd90b892e76dd2c9ba5126a8f216707d2c8", "size": 14124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch8/optical_flow.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/ch8/optical_flow.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/ch8/optical_flow.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": 31.7393258427, "max_line_length": 123, "alphanum_fraction": 0.4819456245, "num_tokens": 4007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.6502622770685279}}
{"text": "/**\n * @file\n * @brief  NPDE UnstableBVP. Solution of source-free heat equation and\n * computation of H1 seminorms on different triangular meshes and refinement\n * levels\n * @author Julien Gacon, Ralf Hiptmair, Am\u00e9lie Loher\n * @date   March 2019\n * @copyright MIT License\n */\n#include \"unstablebvp.h\"\n// General includes\n#include <fstream>\n#include <iomanip>\n#include <memory>\n// Math includes\n#include <cmath>\n// Eigen\n#include <Eigen/Core>\n// Lehrfempp\n#include <lf/mesh/mesh.h>\n#include <lf/refinement/refinement.h>\n\nint main() {\n  // Define the number of refinement levels we want for our mesh\n  const int reflevels = 7;\n\n  // Do the computations for all three possible mesh locations:\n  // Above x2 = 0 (top), intersecting it (center), or below it (bottom)\n  // Store the data in a Eigen Matrix for nice display later on\n  Eigen::MatrixXd h1_seminorms(reflevels + 1, 3), h1_diffs(reflevels + 1, 3);\n\n  // 0 for top (-> first column), 1 for center, 2 for bottom\n  int type_idx = 0;\n  for (auto mesh_type : {\"top\", \"center\", \"bottom\"}) {\n    // Get a hierachy of refined meshes\n    std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n        UnstableBVP::createMeshHierarchy(reflevels, mesh_type);\n    lf::refinement::MeshHierarchy &multi_mesh{*multi_mesh_p};\n\n    // Number of levels\n    const int L = multi_mesh.NumLevels();\n\n    // Computing the difference u_L - u_k, k=0...L-1 is hard, since we would\n    // the functions are defined on different meshes.\n    // To avoid this caveat we can approximate using the triangle inequality:\n    // abs(norm(u_L) - norm(u_k)) <= norm(u_L - u_k)\n    // This should also display the right convergence properties.\n\n    // H1 seminorm of most refined solution (level L-1)\n    double h1_uL =\n        UnstableBVP::solveTemperatureDistribution(multi_mesh.getMesh(L - 1));\n\n    // Store H1 seminorms and the difference of the seminorms to uL\n    h1_seminorms(reflevels, type_idx) = h1_uL;\n    h1_diffs(reflevels, type_idx) = 0;\n\n    // Compute H1 seminorm for all levels 0..L-2\n    for (int level = 0; level < L - 1; ++level) {\n      // Get the mesh pointer\n      std::shared_ptr<const lf::mesh::Mesh> mesh_p = multi_mesh.getMesh(level);\n\n      // Get the seminorm\n      double h1 = UnstableBVP::solveTemperatureDistribution(mesh_p);\n\n      // Store\n      h1_seminorms(level, type_idx) = h1;\n      h1_diffs(level, type_idx) = std::abs(h1_uL - h1);\n    }\n    ++type_idx;\n  }\n\n  // Print to terminal\n  std::cout << std::left << std::setfill('-');\n  std::cout << std::setw(39) << \"#  -- Above x2 = 0 \" << std::setw(30)\n            << \"|-- Intersecting x2 = 0 \" << std::setw(30)\n            << \"|-- Below x2 = 0 \"\n            << \"\\n\"\n            << std::right << std::setfill(' ');\n  std::cout << \"#\" << std::setw(8) << \"Level\" << std::setw(10) << \"|u_k|\"\n            << std::setw(20) << \"||u_L| - |u_k||\" << std::setw(10) << \"|u_k|\"\n            << std::setw(20) << \"||u_L| - |u_k||\" << std::setw(10) << \"|u_k|\"\n            << std::setw(20) << \"||u_L| - |u_k||\"\n            << \"\\n\";\n\n  for (int l = 0; l < reflevels; ++l) {\n    std::cout << std::setw(9) << l << std::setw(10) << h1_seminorms(l, 0)\n              << std::setw(20) << h1_diffs(l, 0) << std::setw(10)\n              << h1_seminorms(l, 1) << std::setw(20) << h1_diffs(l, 1)\n              << std::setw(10) << h1_seminorms(l, 2) << std::setw(20)\n              << h1_diffs(l, 2) << \"\\n\";\n  }\n  std::cout << std::setw(9) << reflevels << std::setw(10)\n            << h1_seminorms(reflevels, 0) << std::setw(20) << 0 << std::setw(10)\n            << h1_seminorms(reflevels, 1) << std::setw(20) << 0 << std::setw(10)\n            << h1_seminorms(reflevels, 2) << std::setw(20) << 0 << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "b1cc1c3d11a71c156609cfa6cdb918c7bc2c825b", "size": 3704, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.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": 37.4141414141, "max_line_length": 80, "alphanum_fraction": 0.593412527, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6502622770685278}}
{"text": "#include \"my_pearce_not_recursive.cpp\"\n#include \"include_and_types.cpp\"\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n\nusing namespace boost;\n\nint main(int, char*[])\n{\n    /*This is an example of how to modify this code for describing a graph \"by hand\" without using graphml parser and\n    stdin*/\n    /*typedef std::pair<int, int> Edge;\n\n    const int num_nodes = 8;\n\n    enum nodes { A, B, C, D, E, F, G, H, I, L, M, N};\n    char name[] = \"ABCDEFGHILMN\";\n\n    Edge edge_array[] = { Edge(A, B),\n                          Edge(B, C), Edge(B, H),\n                          Edge(C, D), Edge(C, G),\n                          Edge(D, E),\n                          Edge(E, F), Edge(E, C),\n                          Edge(G, F), Edge(G, D),\n                          Edge(H, A), Edge(H, G),\n                          Edge(I, L),\n                          Edge(M, N), Edge(N, M)\n    };\n    \n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n    Graph g(edge_array, edge_array + num_arcs, num_nodes);*/\n\n    //Reading graph from stdin\n    Graph g;\n    dynamic_properties dp;\n    read_graphml(std::cin, g, dp);\n\n    //Graph printing\n    std::cout << \"A directed graph:\" << std::endl;\n    print_graph(g, get(vertex_index,g));\n    std::cout << std::endl;\n\n    //Instantiation of the PearceNR class object\n    PearceNR <typeBool, typeInt> pearcenr(&g);\n    std::vector<int>* rindex = pearcenr.pearce_not_recursive_scc();\n\n    //Results printing\n    IndexMap index=get(vertex_index,g);\n    for (int i = 0; i != num_vertices(g); ++i){\n        std::cout << index[i] << \" -> \" << (*rindex)[i] << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "463496332da2e58e8cdc39e3bee620a26d1516cd", "size": 1715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_pearce_not_recursive.cpp", "max_stars_repo_name": "phisco/advance_algorithms_project", "max_stars_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T13:46:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-28T16:42:31.000Z", "max_issues_repo_path": "main_pearce_not_recursive.cpp", "max_issues_repo_name": "phisco/advance_algorithms_project", "max_issues_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_issues_repo_licenses": ["MIT"], "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_pearce_not_recursive.cpp", "max_forks_repo_name": "phisco/advance_algorithms_project", "max_forks_repo_head_hexsha": "2961959cf6036ed4c85d479dd14389315df55ee1", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 117, "alphanum_fraction": 0.5516034985, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6502622700878359}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef META_MATH_IS_POWER_OF_2_INCLUDE\n#define META_MATH_IS_POWER_OF_2_INCLUDE\n\n#include <boost/numeric/meta_math/least_significant_one_bit.hpp>\n\nnamespace meta_math {\n\ntemplate <unsigned long X>\nstruct is_power_of_2\n{\n    static const bool value= X == least_significant_one_bit<X>::value;\n};\n\n} // namespace meta_math\n\n#endif // META_MATH_IS_POWER_OF_2_INCLUDE\n", "meta": {"hexsha": "e629a6d30f0401f18702b2f22c41719b8ab7693f", "size": 807, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/meta_math/is_power_of_2.hpp", "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": "lib/mtl4/boost/numeric/meta_math/is_power_of_2.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "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": "lib/mtl4/boost/numeric/meta_math/is_power_of_2.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "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": 27.8275862069, "max_line_length": 94, "alphanum_fraction": 0.750929368, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927012, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6501593571279181}}
{"text": "#include <iostream>\n#include <cmath>\n#include <vector>\n#include <chrono>\n#include <memory>\n#include <random>\n#include <boost/range/irange.hpp>\n#include <Eigen/Dense>\n#include \"GPs.h\"\n\n// Include CppOptLib files\n#include \"./include/cppoptlib/meta.h\"\n#include \"./include/cppoptlib/boundedproblem.h\"\n#include \"./include/cppoptlib/solver/lbfgsbsolver.h\"\n\n// Retrieve aliases from GP namescope\nusing Matrix = GP::Matrix;\nusing Vector = GP::Vector;\n\n\n// Compute pairwise distance between lists of points\nvoid GP::pdist(Matrix & Dv, Matrix & X1, Matrix & X2)\n{\n  auto n = static_cast<int>(X1.rows());\n  int k = 0;\n  auto entryCount = static_cast<int>( (n*(n-1))/2);\n  Dv.resize(entryCount, 1);\n  for ( auto i : boost::irange(0,n-1) )\n    {      \n      for ( auto j : boost::irange(i+1,n) )\n          Dv(k++) = (static_cast<Vector>(X1.row(i) - X2.row(j))).squaredNorm();\n    }\n}\n\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareForm(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n\n  D.resize(n,n);\n\n  int k = 0;\n  for ( auto i : boost::irange(0,n-1) )\n    {\n      for ( auto j : boost::irange(i+1,n) )\n        D(i,j) = D(j,i) = Dv(k++,0);\n    }\n\n  D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n\n\n// Compute covariance matrix (and gradients) from a vector of squared pairwise distances Dv\nstd::vector<Matrix> GP::RBF::computeCov(Matrix & K, Matrix & Dv, Vector & params, double jitter, bool evalGrad)\n{\n  auto n = static_cast<int>(K.rows());\n  int lengthIndex;\n  if ( params.size() > paramCount )\n    {\n      Kv.noalias() = ( (-0.5 / std::pow(params(1),2)) * Dv ).array().exp().matrix();\n      squareForm(K, Kv, n, 1.0 + params(0) + jitter);\n      lengthIndex = 1;\n    }\n  else\n    {\n      Kv.noalias() = ( (-0.5 / std::pow(params(0),2)) * Dv ).array().exp().matrix();\n      squareForm(K, Kv, n, 1.0 + noiseLevel + jitter);\n      lengthIndex = 0;\n    }\n\n  // Compute gradient list if \"evalGrad=true\"\n  std::vector<Matrix> gradList;\n  if ( evalGrad )\n    {\n      dK_iv.noalias() = 1/std::pow(params(lengthIndex),2) * ( Dv.array() * Kv.array() ).matrix();\n      squareForm(dK_i, dK_iv, n); // Note: diagVal = 0.0\n      gradList.push_back(dK_i);\n    }\n\n  return gradList;\n  \n};\n\n\n// Compute cross covariance between two input vectors using kernel parameters params\nvoid GP::RBF::computeCrossCov(Matrix & K, Matrix & X1, Matrix & X2, Vector & params)\n{\n  // Get prediction count\n  auto m = static_cast<int>(X2.rows());\n\n   // Define lambda function to create unary operator (by clamping kernelParams argument)      \n  auto lambda = [=,&params](double d)->double { return evalDistKernel(d, params, 0); };\n  for ( auto j : boost::irange(0,m) )\n    {\n      K.col(j) = ((X1.rowwise() - X2.row(j)).rowwise().squaredNorm()).unaryExpr(lambda);          \n    }\n  \n};\n\n\n// Precompute distance matrix to avoid repeated calculations during optimization procedure\nvoid GP::GaussianProcess::computeDistMat()\n{\n  pdist(distMatrix, obsX, obsX);\n}\n\n\n// Evaluate NLML for specified kernel hyperparameters p\ndouble GP::GaussianProcess::evalNLML(const Vector & p, Vector & g, bool evalGrad)\n{\n  // Get matrix input observation count\n  auto n = static_cast<int>(obsX.rows());\n\n  // ASSUME OPTIMIZATION OVER LOG VALUES\n  auto params = static_cast<Vector>(p);\n  params = params.array().exp().matrix();\n\n  // Compute covariance matrix and store Cholesky factor\n  K.resize(n,n);\n  //time start = high_resolution_clock::now();\n  auto gradList = (*kernel).computeCov(K, distMatrix, params, jitter, evalGrad);\n  //time end = high_resolution_clock::now();\n  //time_computecov += getTime(start, end);\n\n  //start = high_resolution_clock::now();\n  cholesky = K.llt();\n  //end = high_resolution_clock::now();\n  //time_cholesky_llt += getTime(start, end);\n\n  // Store alpha for DNLML calculation\n  _alpha.noalias() = cholesky.solve(obsY);\n\n  // Compute NLML value\n  //start = high_resolution_clock::now();\n  double NLML_value = 0.5*(obsY.transpose()*_alpha)(0);\n  NLML_value += static_cast<Matrix>(cholesky.matrixL()).diagonal().array().log().sum();\n  NLML_value += 0.5*n*std::log(2*PI);\n  //end = high_resolution_clock::now();\n  //time_NLML += getTime(start, end);\n\n\n  if ( evalGrad )\n    {\n\n      //\n      // Precompute the multiplicative term in derivative expressions\n      //\n      // [ THIS APPEARS TO BE A COMPUTATIONAL BOTTLE-NECK ]\n      //\n\n      //start = high_resolution_clock::now();\n      // Direct evaluation of inverse matrix\n      term.noalias() = cholesky.solve(Matrix::Identity(n,n)) - _alpha*_alpha.transpose();\n\n\n      /*\n      //\n      //          ---  PARALLEL IMPLEMENTATION  ---\n      //\n      //  [ Typically much slower; possibly not thread-safe... ]\n      //\n      term.resize(n,n);\n      //Matrix ei = Eigen::MatrixXd::Zero(n,1);\n      int i = 0;\n      //#pragma omp parallel for private(i) shared(cholesky, term, n)\n#pragma omp parallel for private(i) shared(cholesky, _alpha, term, n)\n      for ( i=0 ; i<n ; i++ )\n        {\n          Matrix ei = Eigen::MatrixXd::Zero(n,1);\n          ei(i) = 1.0;\n          //term.col(i) = cholesky.solve(ei);\n          term.col(i) = cholesky.solve(ei);\n          term.col(i) -= _alpha(i)*_alpha;\n        }\n      */\n\n      \n      //term.noalias() -= _alpha*_alpha.transpose();\n      //end = high_resolution_clock::now();\n      //time_term += getTime(start, end);\n\n      \n      //start = high_resolution_clock::now();      \n      // Compute gradient for noise term if 'fixedNoise=false'\n      int index = 0;\n      if (!fixedNoise)\n        {\n          // Specify gradient of white noise kernel\n          g(index++) = 0.5 * (term * params(0)).trace() ;\n        }\n\n      // Compute gradients with respect to kernel hyperparameters\n      for (auto dK_i = gradList.begin(); dK_i != gradList.end(); ++dK_i) \n        {\n          // Compute trace of full matrix\n          g(index++) = 0.5 * (term * (*dK_i) ).trace() ;\n        }\n      //end = high_resolution_clock::now();\n      //time_grad += getTime(start, end);\n\n    }\n\n  return NLML_value;\n  \n}\n\n\n// Define simplified interface for evaluating NLML without gradient calculation\ndouble GP::GaussianProcess::evalNLML(const Vector & p)\n{\n  Vector nullGrad(0);\n  return evalNLML(p,nullGrad,false);\n}\n\n\n// Define function for uniform sampling\nMatrix GP::sampleUnif(double a, double b, int N, int dim)\n{\n  //return (b-a)*(Eigen::MatrixXd::Random(N,1) * 0.5 + 0.5*Eigen::MatrixXd::Ones(N,1)) + a*Eigen::MatrixXd::Ones(N,1);\n  return (b-a)*(Eigen::MatrixXd::Random(N,dim) * 0.5 + 0.5*Eigen::MatrixXd::Ones(N,dim) ) + a*Eigen::MatrixXd::Ones(N,dim);\n}\n\n\n// Define function for uniform sampling [Vectors]\nVector GP::sampleUnifVector(Vector lbs, Vector ubs)\n{\n  auto n = static_cast<int>(lbs.rows());\n\n  Vector sampleVector = ((ubs-lbs).array()*( 0.5*Eigen::MatrixXd::Random(n,1) + 0.5*Eigen::MatrixXd::Ones(n,1) ).array()).matrix() + (lbs.array()*Eigen::MatrixXd::Ones(n,1).array()).matrix();\n  \n  return sampleVector;\n}\n\n// Define function for sampling from standard normal distribution\nMatrix GP::sampleNormal(int N)\n{\n  // Note: Boost random is currently throwing deprecated header warnings...\n  //boost::random::mt19937 rng;\n  //boost::random::normal_distribution<> normalDist;\n  std::default_random_engine rng;\n  std::normal_distribution<double> normalDist(0.0,1.0);\n  Matrix sampleVals(N,1);\n  for ( auto i : boost::irange(0,N) )\n    sampleVals(i) = normalDist(rng);\n  return sampleVals;\n}\n\n\n// Generate equally spaced points on an interval or square region\nMatrix GP::linspace(double a, double b, int N, int dim)\n{\n\n  Matrix linspaceVals;\n  if ( dim == 1 )\n    {\n      linspaceVals.resize(N,1);\n      linspaceVals = Eigen::Array<double, Eigen::Dynamic, 1>::LinSpaced(N, a, b);\n    }\n  else if ( dim == 2 )\n    {\n      linspaceVals.resize(N*N,2);\n      Matrix linspaceVals1D = Eigen::Array<double, Eigen::Dynamic, 1>::LinSpaced(N, a, b);\n      int k = 0;\n      for ( auto i : boost::irange(0,N) )\n        {\n          for ( auto j : boost::irange(0,N) )\n            {\n              linspaceVals(k,0) = linspaceVals1D(i);\n              linspaceVals(k,1) = linspaceVals1D(j);\n              k++;\n            }\n        }\n    }\n  else\n      std::cout << \"[*] GP::linspace has not been implemented for dim > 2\\n\";\n  \n  return linspaceVals;\n}\n\n\n// Define utility function for formatting hyperparameter bounds\nvoid GP::GaussianProcess::parseBounds(Vector & lbs, Vector & ubs, int augParamCount)\n{\n  lbs.resize(augParamCount);\n  ubs.resize(augParamCount);\n\n  double defaultLowerBound = 0.00001;\n  double defaultUpperBound = 10.0;\n  \n  if ( fixedBounds )\n    {\n      // Check if bounds for noise parameter were provided\n      if ( lowerBounds.size() < augParamCount )\n        {\n          // Set noise bounds to defaults\n          lbs(0) = std::log( defaultLowerBound );\n          ubs(0) = std::log( defaultUpperBound );\n\n          // Convert specified bounds to log-scale\n          for ( auto bi : boost::irange(1,augParamCount) )\n            {\n              lbs(bi) = std::log(lowerBounds(bi-1));\n              ubs(bi) = std::log(upperBounds(bi-1));\n            }\n        }\n      else\n        {\n          // Convert specified bounds to log-scale\n          lbs = (lowerBounds.array().log()).matrix();\n          ubs = (upperBounds.array().log()).matrix();\n        }\n    }\n  else\n    {\n      // Set noise and hyperparameter bounds to defaults\n      lbs = ( defaultLowerBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n      ubs = ( defaultUpperBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n    }\n\n  /*\n  std::cout << \"Bounds:\\n\";\n  std::cout << lbs.array().exp().matrix().transpose() << std::endl;\n  std::cout << ubs.array().exp().matrix().transpose() << std::endl;\n  std::cout << \"\\nLog Bounds:\\n\";\n  std::cout << lbs.transpose() << std::endl;\n  std::cout << ubs.transpose() << std::endl << std::endl;\n  */\n\n}\n\n\n// Fit model hyperparameters\nvoid GP::GaussianProcess::fitModel()\n{\n\n  // Get combined parameter/noise vector size\n  paramCount = (*kernel).getParamCount();\n  augParamCount = (fixedNoise) ? static_cast<int>(paramCount) : static_cast<int>(paramCount) + 1 ;\n\n  // Pass noise level to kernel when 'fixedNoise=true'\n  if ( fixedNoise )\n    (*kernel).setNoise(noiseLevel);\n  \n  // Precompute distance matrix\n  computeDistMat();\n\n  // Declare vector for storing gradient calculations\n  Vector g(augParamCount);\n\n  // Initialize gradient vector size\n  cppOptLibgrad.resize(augParamCount);\n\n  // Convert hyperparameter bounds to log-scale\n  Vector lbs, ubs;\n  parseBounds(lbs, ubs, augParamCount);\n\n  Vector optParams = Eigen::MatrixXd::Zero(augParamCount,1);\n  \n  this->setLowerBound(lbs);\n  this->setUpperBound(ubs);\n  cppoptlib::LbfgsbSolver<GaussianProcess> solver;\n\n  // Specify stopping criteria\n  cppoptlib::Criteria<double> crit = cppoptlib::Criteria<double>::defaults();\n  //crit.iterations = 5000;\n  //crit.gradNorm = 10.0;   //!< Minimum norm of gradient vector\n  //crit.xDelta = 0;      //!< Minimum change in parameter vector\n  //crit.fDelta = 0;      //!< Minimum change in cost function\n  //crit.condition = 0;\n  solver.setStopCriteria(crit);\n\n  solver.minimize(*this, optParams);\n\n  // ASSUME OPTIMIZATION OVER LOG VALUES\n  optParams = optParams.array().exp().matrix();\n\n\n  //start = high_resolution_clock::now();\n  ///* [ This is included in the SciKit Learn model.fit() call as well ]\n\n  // Recompute covariance and Cholesky factor\n  auto nullGradList = (*kernel).computeCov(K, distMatrix, optParams);\n  cholesky = K.llt();\n  _alpha.noalias() = cholesky.solve(obsY);\n  \n  //*/\n  //end = high_resolution_clock::now();\n  //time_final_chol += getTime(start, end);\n  \n  \n  // Assign tuned parameters to model\n  if (!fixedNoise)\n    {\n      noiseLevel = static_cast<double>((optParams.head(1))[0]);\n      optParams = static_cast<Vector>(optParams.tail(augParamCount - 1));\n    }\n  \n  (*kernel).setParams(optParams);\n\n\n  // DISPLAY TIMING INFORMATION\n  /*\n  std::cout << \"\\n\\n Time Diagnostics |\\n\";\n  std::cout << \"------------------\\n\";\n  std::cout << \"computeCov():\\t  \" << time_computecov  << std::endl;\n  std::cout << \"cholesky.llt():\\t  \" << time_cholesky_llt  << std::endl;\n  std::cout << \"NLML:\\t  \\t  \" << time_NLML  << std::endl;\n  std::cout << \"Grad term:\\t  \" << time_term  << std::endl;\n  std::cout << \"Gradient:\\t  \" << time_grad  << std::endl;\n  std::cout << \"\\n\" << std::endl;\n  std::cout << \"paramSearch:\\t  \" << time_paramsearch  << std::endl;\n  std::cout << \"Minimize:\\t  \" << time_minimize  << std::endl;\n  std::cout << \"Final Cholesky:\\t  \" << time_final_chol  << std::endl;\n  */\n  \n};\n\n// Compute predicted values\nvoid GP::GaussianProcess::predict()\n{\n  // Get matrix input observation count\n  auto n = static_cast<int>(obsX.rows());\n  auto m = static_cast<int>(predX.rows());\n  \n  // Get optimized kernel hyperparameters\n  Vector params = (*kernel).getParams();\n\n  // Compute cross covariance for test points\n  Matrix kstar;\n  kstar.resize(n,m);\n  (*kernel).computeCrossCov(kstar, obsX, predX, params);\n\n  // Compute covariance matrix for test points\n  Matrix kstarmat;\n  kstarmat.resize(m,m);\n  (*kernel).computeCrossCov(kstarmat, predX, predX, params);\n\n  // Possible redundant calculations; should simplify...\n  Matrix cholMat(cholesky.matrixL());\n  //Matrix alpha = cholesky.solve(obsY);\n  Matrix v = kstar;\n  cholMat.triangularView<Eigen::Lower>().solveInPlace(v);\n\n  // Set predictive means/variances and compute negative log marginal likelihood\n  //predMean = kstar.transpose() * alpha;\n  predMean = kstar.transpose() * _alpha;\n  predCov = kstarmat - v.transpose() * v;\n\n}\n\n\n// Draw sample paths from posterior distribution\nMatrix GP::GaussianProcess::getSamples(int count)\n{\n  // Get number of target points\n  auto n = static_cast<int>(predX.rows());\n  \n  // Construct simple random generator engine from a time-based seed\n  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  std::default_random_engine generator (seed);\n  std::normal_distribution<double> normal (0.0,1.0);\n\n  // Assign i.i.d. random normal values to uVals\n  Matrix uVals(n,count);\n  for (auto i : boost::irange(0,n))\n    {\n      for (auto j : boost::irange(0,count))\n          uVals(i,j) = normal(generator);\n    }\n\n  // Compute Cholesky factor L\n  Matrix L = ( predCov + (noiseLevel+jitter)*Matrix::Identity(static_cast<int>(predCov.cols()), static_cast<int>(predCov.cols())) ).llt().matrixL();\n\n  // Draw samples using the formula:  y = m + L*u\n  Matrix samples = predMean.replicate(1,count) + L*uVals;\n  \n  return samples;\n}\n\n\n// Evaluate NLML [public interface]\ndouble GP::GaussianProcess::computeNLML(const Vector & p, double noise)\n{\n  // Compute log-hyperparameters\n  Vector logparams(augParamCount);\n\n  if ( !fixedNoise )\n    {\n      logparams(0) = std::log(noise);\n      for ( auto i : boost::irange(1,augParamCount) )\n        logparams(i) = std::log(p(i-1));\n    }\n  else\n    {\n      logparams = logparams.array().log().matrix();\n    }\n\n  // Evaluate NLML using log-hyperparameters\n  return evalNLML(logparams);\n}\n\n// Evaluate NLML with default noise level [public interface]\ndouble GP::GaussianProcess::computeNLML(const Vector & p)\n{\n  return computeNLML(p, noiseLevel);\n}\n\n// Evaluate NLML with default noise level [public interface]\ndouble GP::GaussianProcess::computeNLML()\n{\n  auto params = (*kernel).getParams();\n  return computeNLML(params, noiseLevel);\n}\n\n\n// Define function for retrieving time from chrono\nfloat GP::getTime(std::chrono::high_resolution_clock::time_point start, std::chrono::high_resolution_clock::time_point end)\n{\n  return static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>( end - start ).count() / 1000000.0);\n};\n\n\n// Define kernel function for RBF\ndouble GP::RBF::evalKernel(Matrix & x, Matrix & y, Vector & params, int n)\n{\n  switch (n)\n    {\n    case 0: return std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n    case 1: return (x-y).squaredNorm() / std::pow(params(0),3) * std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n    default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n    }\n};\n\n// Define distance kernel function for RBF\n//\n// REVISION:  Optimize w.r.t. theta = log(l) for stability  ==>   / l^2  instead of  / l^3\n//\ndouble GP::RBF::evalDistKernel(double d, Vector & params, int n)\n{\n  switch (n)\n    {\n    case 0: return std::exp( -d / (2.0*std::pow(params(0),2)));\n    case 1: return d / std::pow(params(0),2) * std::exp( -d / (2.0*std::pow(params(0),2)));\n    default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n    }\n};\n\n\n\n\n/*\n// POTENTIAL PARALLEL IMPLEMENTATION OF SQUARE FORM; SPEED-UP APPEARS NEGLIGIBLE\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareFormParallel(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n\n  D.resize(n,n);\n  int i;\n  int j;\n#pragma omp parallel for private(i,j) shared(D,Dv,n)\n  for ( i = 0 ; i<n-1; i++ )\n    {\n      for ( j = i+1 ; j<n ; j++ )\n        {\n          D(i,j) = D(j,i) = Dv( static_cast<int>(i*n - (i*(i+1))/2 + j - i -1) ,0);\n        }\n    }\n  D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n*/\n\n\n\n\n//\n//   ORIGINAL MINIMIZATION IMPLEMENTATION USING RASMUSSEN'S CODE\n//\n\n//\n//    NOTE:\n//\n//    Remember to include \"utils/minimize.h\" and derive the\n//   'GaussianProcess' class from the 'GradientObj' class:\n//\n//    i.e.  class GaussianProcess : public minimize::GradientObj\n//\n\n/*\nvoid minimize(...)\n{\n\n\n  //\n  // Specify the parameters for the minimization algorithm\n  //\n  \n  //   HIGH ACCURACY SETTINGS   //\n  // max of MAX function evaluations per line search\n  //int MAX = 30;\n  // max number of line searches = length\n  //int length = 20;\n  // don't reevaluate within INT of the limit of the current bracket\n  //double INT = 0.00001;\n  // SIG is a constant controlling the Wolfe-Powell conditions\n  //double SIG = 0.9;\n  // extrapolate maximum EXT times the current step-size\n  //double EXT = 5.0;\n\n  //  EFFICIENT SETTINGS  //\n\n\n  int MAX = 15;\n  int length = 10;\n  double INT = 0.00001;\n  double SIG = 0.9;\n  double EXT = 5.0;\n\n  // Define number of exploratory NLML evaluations for specifying\n  // a reasonable initial value for the optimization algorithm\n  int initParamSearchCount = 30;\n    \n  // Define restart count for optimizer\n  int restartCount = 0;\n  \n  // Convert hyperparameter bounds to log-scale\n  Vector lbs, ubs;\n  parseBounds(lbs, ubs, augParamCount);\n\n  // Declare variables to store optimization loop results\n  double currentVal;\n  double optVal = 1e9;\n  Vector theta(augParamCount);\n  Vector optParams(augParamCount);\n\n  //time start = high_resolution_clock::now();\n  // First explore hyperparameter space to get a reasonable initializer for optimization\n  for ( auto i : boost::irange(0,initParamSearchCount) )\n    {\n      if ( i == 0 )\n          theta = Eigen::MatrixXd::Zero(augParamCount,1);\n      else\n          theta = sampleUnifVector(lbs, ubs);\n\n      // Compute current NLML and store parameters if optimal\n      currentVal = evalNLML(theta);\n      if ( currentVal < optVal )\n        {\n          optVal = currentVal;\n          optParams = theta;\n        }\n      //std::cout << \"Theta Search:  \" << theta.transpose() << \"  [ NLML = \" << currentVal << \" ]\"<< std::endl;\n    }\n  //time end = high_resolution_clock::now();\n  //time_paramsearch += getTime(start, end);\n\n\n  // NOTE: THIS NEEDS TO BE RE-WRITTEN TO USE THE PRELIMINARY PARAMETER SEARCH RESULTS\n  // Evaluate optimizer with various different initializations\n  for ( auto i : boost::irange(0,restartCount) )\n    {\n      // Avoid compiler warning for unused variable\n      //(void)i;\n\n      if ( i == 0 )\n        {\n          // Set initial guess (should make this user specifiable...)\n          theta = Eigen::MatrixXd::Zero(augParamCount,1);\n        }\n      else\n        {\n          // Sample initial hyperparameter vector\n          theta = sampleUnifVector(lbs, ubs);\n        }\n\n      // Optimize hyperparameters\n      minimize::cg_minimize(theta, this, g, length, SIG, EXT, INT, MAX);\n      \n      // Compute current NLML and store parameters if optimal\n      currentVal = evalNLML(theta);\n      if ( currentVal < optVal )\n        {\n          optVal = currentVal;\n          optParams = theta;\n        }\n    }\n\n  // Perform one last optimization starting from best parameters so far\n  if ( ( initParamSearchCount == 0 ) && ( restartCount == 0 ) )\n    optParams = sampleUnifVector(lbs, ubs);\n  //std::cout << \"\\n[*] FINAL - Initial Values (log):  \" << optParams.transpose() << std::endl;\n  //std::cout << \"[*] FINAL - Initial Values (std):  \" << optParams.transpose().array().exp().matrix() << std::endl;\n  //start = high_resolution_clock::now();\n  minimize::cg_minimize(optParams, this, g, length, SIG, EXT, INT, MAX);\n  //end = high_resolution_clock::now();\n  //time_minimize += getTime(start, end);\n\n}\n*/\n", "meta": {"hexsha": "51ff66542e3ddb6825a771d947cdd17b22525d6b", "size": 20789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 29.7836676218, "max_line_length": 191, "alphanum_fraction": 0.6318726249, "num_tokens": 5804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6501593467674481}}
{"text": "#include <iostream>\n#include <random>\n#include <Eigen/Geometry>\n\n#include \"GeometryDerivatives.h\"\n#include \"MeshConnectivity.h\"\n\nEigen::Matrix3d crossMatrix(Eigen::Vector3d v)\n{\n    Eigen::Matrix3d ret;\n    ret << 0, -v[2], v[1],\n        v[2], 0, -v[0],\n        -v[1], v[0], 0;\n    return ret;\n}\n\nEigen::Matrix2d adjugate(Eigen::Matrix2d M)\n{\n    Eigen::Matrix2d ret;\n    ret << M(1, 1), -M(0, 1), -M(1, 0), M(0, 0);\n    return ret;\n}\n\ndouble angle(const Eigen::Vector3d& v, const Eigen::Vector3d& w, const Eigen::Vector3d& axis,\n    Eigen::Matrix<double, 1, 9>* derivative, // v, w, a\n    Eigen::Matrix<double, 9, 9>* hessian\n)\n{\n    double theta = 2.0 * atan2((v.cross(w).dot(axis) / axis.norm()), v.dot(w) + v.norm() * w.norm());\n\n    if (derivative)\n    {\n        derivative->segment<3>(0) = -axis.cross(v) / v.squaredNorm() / axis.norm();\n        derivative->segment<3>(3) = axis.cross(w) / w.squaredNorm() / axis.norm();\n        derivative->segment<3>(6).setZero();\n    }\n    if (hessian)\n    {\n        hessian->setZero();\n        hessian->block<3, 3>(0, 0) += 2.0 * (axis.cross(v)) * v.transpose() / v.squaredNorm() / v.squaredNorm() / axis.norm();\n        hessian->block<3, 3>(3, 3) += -2.0 * (axis.cross(w)) * w.transpose() / w.squaredNorm() / w.squaredNorm() / axis.norm();\n        hessian->block<3, 3>(0, 0) += -crossMatrix(axis) / v.squaredNorm() / axis.norm();\n        hessian->block<3, 3>(3, 3) += crossMatrix(axis) / w.squaredNorm() / axis.norm();\n\n        Eigen::Matrix3d dahat = (Eigen::Matrix3d::Identity() / axis.norm() - axis * axis.transpose() / axis.norm() / axis.norm() / axis.norm());\n\n        hessian->block<3, 3>(0, 6) += crossMatrix(v) * dahat / v.squaredNorm();\n        hessian->block<3, 3>(3, 6) += -crossMatrix(w) * dahat / w.squaredNorm();\n    }\n\n    return theta;\n}\n\nEigen::Vector3d faceNormal(const MeshConnectivity &mesh,\n    const Eigen::MatrixXd &curPos,\n    int face, int startidx,\n    Eigen::Matrix<double, 3, 9> *derivative,\n    std::vector<Eigen::Matrix<double, 9, 9> > *hessian)\n{\n    if (derivative)\n        derivative->setZero();\n\n    if (hessian)\n    {\n        hessian->resize(3);\n        for (int i = 0; i < 3; i++) (*hessian)[i].setZero();\n    }\n\n    int v0 = startidx % 3;\n    int v1 = (startidx + 1) % 3;\n    int v2 = (startidx + 2) % 3;\n    Eigen::Vector3d qi0 = curPos.row(mesh.faceVertex(face, v0)).transpose();\n    Eigen::Vector3d qi1 = curPos.row(mesh.faceVertex(face, v1)).transpose();\n    Eigen::Vector3d qi2 = curPos.row(mesh.faceVertex(face, v2)).transpose();\n    Eigen::Vector3d n = (qi1 - qi0).cross(qi2 - qi0);\n\n    if (derivative)\n    {\n        derivative->block<3, 3>(0, 0) += crossMatrix(qi2 - qi1);\n        derivative->block<3, 3>(0, 3) += crossMatrix(qi0 - qi2);\n        derivative->block<3, 3>(0, 6) += crossMatrix(qi1 - qi0);\n    }\n\n    if (hessian)\n    {\n        for (int j = 0; j < 3; j++)\n        {\n            Eigen::Vector3d ej(0, 0, 0);\n            ej[j] = 1.0;\n            Eigen::Matrix3d ejc = crossMatrix(ej);\n            (*hessian)[j].block<3, 3>(0, 3) -= ejc;\n            (*hessian)[j].block<3, 3>(0, 6) += ejc;\n            (*hessian)[j].block<3, 3>(3, 6) -= ejc;\n            (*hessian)[j].block<3, 3>(3, 0) += ejc;\n            (*hessian)[j].block<3, 3>(6, 0) -= ejc;\n            (*hessian)[j].block<3, 3>(6, 3) += ejc;\n        }\n    }\n\n    return n;\n}\n\ndouble triangleAltitude(const MeshConnectivity &mesh,\n    const Eigen::MatrixXd &curPos,\n    int face,\n    int edgeidx,\n    Eigen::Matrix<double, 1, 9> *derivative,\n    Eigen::Matrix<double, 9, 9> *hessian)\n{\n    if (derivative)\n        derivative->setZero();\n    if (hessian)\n        hessian->setZero();\n\n    Eigen::Matrix<double, 3, 9> nderiv;\n    std::vector<Eigen::Matrix<double, 9, 9> > nhess;\n    Eigen::Vector3d n = faceNormal(mesh, curPos, face, edgeidx, (derivative || hessian ? &nderiv : NULL), hessian ? &nhess : NULL);\n\n    int v2 = (edgeidx + 2) % 3;\n    int v1 = (edgeidx + 1) % 3;\n    Eigen::Vector3d q2 = curPos.row(mesh.faceVertex(face, v2)).transpose();\n    Eigen::Vector3d q1 = curPos.row(mesh.faceVertex(face, v1)).transpose();\n\n    Eigen::Vector3d e = q2 - q1;\n    double nnorm = n.norm();\n    double enorm = e.norm();\n    double h = nnorm / enorm;\n\n    if (derivative)\n    {\n        for (int i = 0; i < 3; i++)\n        {\n            *derivative += nderiv.row(i) * n[i] / nnorm / enorm;\n        }\n        derivative->block(0, 6, 1, 3) += -nnorm / enorm / enorm / enorm * e.transpose();\n        derivative->block(0, 3, 1, 3) += nnorm / enorm / enorm / enorm * e.transpose();\n    }\n\n    if (hessian)\n    {\n        for (int i = 0; i < 3; i++)\n        {\n            *hessian += nhess[i] * n[i] / nnorm / enorm;\n        }\n\n        Eigen::Matrix3d idMat = Eigen::Matrix3d::Identity();\n\n        Eigen::Matrix3d P = idMat / nnorm - n*n.transpose() / nnorm / nnorm / nnorm;\n        *hessian += nderiv.transpose() * P * nderiv / enorm;\n        hessian->block<3, 9>(6, 0) += -e * n.transpose() * nderiv / nnorm / enorm / enorm / enorm;\n        hessian->block<3, 9>(3, 0) += e * n.transpose() * nderiv / nnorm / enorm / enorm / enorm;\n        hessian->block<9, 3>(0, 6) += -nderiv.transpose() * n * e.transpose() / nnorm / enorm / enorm / enorm;\n        hessian->block<9, 3>(0, 3) += nderiv.transpose() * n * e.transpose() / nnorm / enorm / enorm / enorm;\n        hessian->block<3, 3>(6, 6) += -nnorm / enorm / enorm / enorm * idMat;\n        hessian->block<3, 3>(6, 3) += nnorm / enorm / enorm / enorm * idMat;\n        hessian->block<3, 3>(3, 6) += nnorm / enorm / enorm / enorm * idMat;\n        hessian->block<3, 3>(3, 3) += -nnorm / enorm / enorm / enorm * idMat;\n\n        Eigen::Matrix3d outer = e*e.transpose() * 3.0 * nnorm / enorm / enorm / enorm / enorm / enorm;\n        hessian->block(6, 6, 3, 3) += outer;\n        hessian->block(6, 3, 3, 3) += -outer;\n        hessian->block(3, 6, 3, 3) += -outer;\n        hessian->block(3, 3, 3, 3) += outer;\n    }\n\n    return h;\n}\n\nEigen::Matrix2d firstFundamentalForm(\n    const MeshConnectivity &mesh,\n    const Eigen::MatrixXd &curPos,\n    int face,\n    Eigen::Matrix<double, 4, 9> *derivative, // F(face, i)\n    std::vector <Eigen::Matrix<double, 9, 9> > *hessian)\n{\n    Eigen::Vector3d q0 = curPos.row(mesh.faceVertex(face, 0));\n    Eigen::Vector3d q1 = curPos.row(mesh.faceVertex(face, 1));\n    Eigen::Vector3d q2 = curPos.row(mesh.faceVertex(face, 2));\n    Eigen::Matrix2d result;\n    result << (q1 - q0).dot(q1 - q0), (q1 - q0).dot(q2 - q0),\n        (q2 - q0).dot(q1 - q0), (q2 - q0).dot(q2 - q0);\n\n    if (derivative)\n    {\n        derivative->setZero();\n        derivative->block<1, 3>(0, 3) += 2.0 * (q1 - q0).transpose();\n        derivative->block<1, 3>(0, 0) -= 2.0 * (q1 - q0).transpose();\n        derivative->block<1, 3>(1, 6) += (q1 - q0).transpose();\n        derivative->block<1, 3>(1, 3) += (q2 - q0).transpose();\n        derivative->block<1, 3>(1, 0) += -(q1 - q0).transpose() - (q2 - q0).transpose();\n        derivative->block<1, 3>(2, 6) += (q1 - q0).transpose();\n        derivative->block<1, 3>(2, 3) += (q2 - q0).transpose();\n        derivative->block<1, 3>(2, 0) += -(q1 - q0).transpose() - (q2 - q0).transpose();\n        derivative->block<1, 3>(3, 6) += 2.0 * (q2 - q0).transpose();\n        derivative->block<1, 3>(3, 0) -= 2.0 * (q2 - q0).transpose();\n    }\n\n    if (hessian)\n    {\n        hessian->resize(4);\n        for (int i = 0; i < 4; i++)\n        {\n            (*hessian)[i].setZero();\n        }\n        Eigen::Matrix3d I = Eigen::Matrix3d::Identity();\n        (*hessian)[0].block<3, 3>(0, 0) += 2.0*I;\n        (*hessian)[0].block<3, 3>(3, 3) += 2.0*I;\n        (*hessian)[0].block<3, 3>(0, 3) -= 2.0*I;\n        (*hessian)[0].block<3, 3>(3, 0) -= 2.0*I;\n\n        (*hessian)[1].block<3, 3>(3, 6) += I;\n        (*hessian)[1].block<3, 3>(6, 3) += I;\n        (*hessian)[1].block<3, 3>(0, 3) -= I;\n        (*hessian)[1].block<3, 3>(0, 6) -= I;\n        (*hessian)[1].block<3, 3>(3, 0) -= I;\n        (*hessian)[1].block<3, 3>(6, 0) -= I;\n        (*hessian)[1].block<3, 3>(0, 0) += 2.0*I;\n\n        (*hessian)[2].block<3, 3>(3, 6) += I;\n        (*hessian)[2].block<3, 3>(6, 3) += I;\n        (*hessian)[2].block<3, 3>(0, 3) -= I;\n        (*hessian)[2].block<3, 3>(0, 6) -= I;\n        (*hessian)[2].block<3, 3>(3, 0) -= I;\n        (*hessian)[2].block<3, 3>(6, 0) -= I;\n        (*hessian)[2].block<3, 3>(0, 0) += 2.0*I;\n\n        (*hessian)[3].block<3, 3>(0, 0) += 2.0*I;\n        (*hessian)[3].block<3, 3>(6, 6) += 2.0*I;\n        (*hessian)[3].block<3, 3>(0, 6) -= 2.0*I;\n        (*hessian)[3].block<3, 3>(6, 0) -= 2.0*I;\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "9b05a7ba10777b01147525d8db02c6b54a0c2e1c", "size": 8554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeometryDerivatives.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeometryDerivatives.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeometryDerivatives.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["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.4, "max_line_length": 144, "alphanum_fraction": 0.5234977788, "num_tokens": 3158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6500470427213318}}
{"text": "/**\n * @file LossTests.cpp\n *\n * @breif Tests for our loss functions\n *\n * @date 1/06/17\n * @author Ben Caine\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE LossTests\n\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include \"loss/CrossEntropy.h\"\n#include \"loss/HuberLoss.h\"\n#include \"loss/MeanSquaredError.h\"\n\nBOOST_AUTO_TEST_CASE(test_cross_entropy_loss) {\n    // TODO: Really just checking compilation right now. Need to use TF/Pytorch/Numpy to generate test cases\n    nn::CrossEntropyLoss<float, 2> lossFunction;\n\n    int batchSize = 4;\n    int numClasses = 3;\n    Eigen::Tensor<float, 2> predictions(batchSize, numClasses);\n    predictions.setValues({\n                          {0.1, 0.7, 0.2},\n                          {0.9, 0.0, 0.1},\n                          {0.0, 0.0, 1.0},\n                          {0.3, 0.4, 0.3}\n                          });\n\n    Eigen::Tensor<float, 2> labels(batchSize, numClasses);\n    labels.setValues({\n                             {0, 1, 0},\n                             {1, 0, 0},\n                             {1, 0, 0},\n                             {0, 1, 0}\n                     });\n\n    auto loss = lossFunction.loss(predictions, labels);\n    auto accuracy = lossFunction.accuracy(predictions, labels);\n    auto backwardsResult = lossFunction.backward(predictions, labels);\n    BOOST_REQUIRE_MESSAGE(accuracy == 0.75, \"Accuracy was not correct\");\n}\n\nBOOST_AUTO_TEST_CASE(test_mse_loss) {\n    nn::MeanSquaredError<float, 2> lossFunction;\n\n    const int batchSize = 4;\n\n    Eigen::Tensor<float, 2> predictions(batchSize, 1);\n    predictions.setValues({{2}, {3}, {4}, {5}});\n\n    Eigen::Tensor<float, 2> labels(batchSize, 1);\n    labels.setValues({{2}, {1}, {3}, {0}});\n\n    // Expected squared error of each should be:\n    // 0^2 + 2^2 + 1^2 + 5^2 = 0 + 4 + 1 + 25 = 30 / 4 = 7.5\n\n    auto loss = lossFunction.loss(predictions, labels);\n    BOOST_REQUIRE_MESSAGE(loss == 7.5, \"Loss not what was expected\");\n\n    auto backwardsResult = lossFunction.backward(predictions, labels);\n    std::array<float, batchSize> expectedBackwardsResults = {0, 2, 1, 5};\n\n    for (int ii = 0; ii < batchSize; ++ii) {\n        BOOST_REQUIRE_CLOSE(backwardsResult(ii, 0), expectedBackwardsResults[ii], 1e-3);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(test_huber_loss) {\n    float threshold = 1.5;\n    nn::HuberLoss<float, 2> lossFunction(threshold);\n\n    const int batchSize = 4;\n    Eigen::Tensor<float, 2> predictions(batchSize, 1);\n    predictions.setValues({{2}, {3}, {4}, {5}});\n\n    Eigen::Tensor<float, 2> labels(batchSize, 1);\n    labels.setValues({{2}, {1}, {3}, {0}});\n\n    // Expected absolute error:\n    // [0, 2, 1, 5]\n    // If our thresh is 1.5, then two terms are squared loss and two are absolute\n    // So, we expect:\n    // 0.5 * 0^2 + (1.5 * 2 - 0.5 * 1.5^2) + 0.5 * 1^2 + (1.5 * 5 - 0.5 * 1.5^2)\n    // Which is:\n    // [0, 1.875, 0.5, 6.375] = 8.75 / 4 = 2.1875\n\n    auto loss = lossFunction.loss(predictions, labels);\n    BOOST_REQUIRE_CLOSE(loss, 2.1875, 1e-3);\n\n    auto backwardsResult = lossFunction.backward(predictions, labels);\n\n\n    std::array<float, batchSize> expectedBackwardsResults = {0, threshold, 1, threshold};\n\n    for (int ii = 0; ii < batchSize; ++ii) {\n        BOOST_REQUIRE_CLOSE(backwardsResult(ii, 0), expectedBackwardsResults[ii], 1e-3);\n    }\n}", "meta": {"hexsha": "1170307bc046b8b2404b4007964ccf2a02300fad", "size": 3320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/LossTests.cpp", "max_stars_repo_name": "bcaine/nn_cpp", "max_stars_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T03:52:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T14:32:49.000Z", "max_issues_repo_path": "tests/LossTests.cpp", "max_issues_repo_name": "bcaine/nn_cpp", "max_issues_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-10T09:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-10T09:32:21.000Z", "max_forks_repo_path": "tests/LossTests.cpp", "max_forks_repo_name": "bcaine/nn_cpp", "max_forks_repo_head_hexsha": "447ffa49f591e1c1c6dad0a1ab8b4f72411385b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T04:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T09:42:35.000Z", "avg_line_length": 32.5490196078, "max_line_length": 108, "alphanum_fraction": 0.5942771084, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6500118528416018}}
{"text": "//  (C) Copyright Matt Borland 2022.\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 <cmath>\n#include <iterator>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n#include <initializer_list>\n#include <boost/math/special_functions/logaddexp.hpp>\n\nnamespace boost { namespace math {\n\n// https://nhigham.com/2021/01/05/what-is-the-log-sum-exp-function/\n// See equation (#)\ntemplate <typename ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type>\nReal logsumexp(ForwardIterator first, ForwardIterator last)\n{\n    using std::exp;\n    using std::log1p;\n    \n    const auto elem = std::max_element(first, last);\n    const Real max_val = *elem;\n\n    Real arg = 0;\n    while (first != last)\n    {\n        if (first != elem) \n        {\n            arg += exp(*first - max_val);\n        }\n\n        ++first;\n    }\n\n    return max_val + log1p(arg);\n}\n\ntemplate <typename Container, typename Real = typename Container::value_type>\ninline Real logsumexp(const Container& c)\n{\n    return logsumexp(std::begin(c), std::end(c));\n}\n\ntemplate <typename... Args, typename Real = typename std::common_type<Args...>::type, \n          typename std::enable_if<std::is_floating_point<Real>::value, bool>::type = true>\ninline Real logsumexp(Args&& ...args)\n{\n    std::initializer_list<Real> list {std::forward<Args>(args)...};\n    \n    if(list.size() == 2)\n    {\n        return logaddexp(*list.begin(), *std::next(list.begin()));\n    }\n    return logsumexp(list.begin(), list.end());\n}\n\n}} // Namespace boost::math\n", "meta": {"hexsha": "8aa1d4bffd83a07cae820f7cfa6a0ae7032cc535", "size": 1693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/logsumexp.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/logsumexp.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/logsumexp.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "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.7540983607, "max_line_length": 111, "alphanum_fraction": 0.6650915535, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6500118465123896}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved\uff1aCC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      \u7248\u6743\u90e8\u5206\u6240\u6709\uff0c\u9075\u5faaCC(creativecommons.org)BY-NC-SA\u534f\u8bae\u6388\u6743\u65b9\u5f0f\u4f7f\u7528\n *\n * Filename                : \n * Description             : \u89c6\u89c9SLAM\u5341\u56db\u8bb2/ch3/useGeometry/eigenGeometry.cpp \u5b66\u4e60\u8bb0\u5f55\n\t\t\t\t\t\t\t\t\u77e9\u9635\u5e93                    \n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4FOCUS\u56e2\u961f\n * Modification History\t   : ver1.0, 2018.03.26, William Yu\n                            \n=================================================================================*/\n/// Include Files\n#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n// Eigen \u51e0\u4f55\u6a21\u5757\n#include <Eigen/Geometry>\nusing namespace std;\n\n\n/// Global Variables\n\n\n\n/// Function Definitions\n\n\n/**\n * @function main\n * @author William Yu\n * @brief Eigen\u51e0\u4f55\u6a21\u5757\u7684\u4f7f\u7528\u65b9\u6cd5\n * @param  None\n * @retval None\n */\nint main ( int argc, char** argv )\n{\n    //---------------------------------------------------------------------------\n    //  \u65cb\u8f6c\u5e73\u79fb\u8868\u793a\n    //----------------------------------------------------------------\n    // Eigen/Geometry \u51e0\u4f55\u6a21\u5757\u63d0\u4f9b\u4e86\u5404\u79cd\u65cb\u8f6c\u548c\u5e73\u79fb\u7684\u8868\u793a\n    // 3D \u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u4f7f\u7528 Matrix3d \u6216 Matrix3f\n    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    // \u65cb\u8f6c\u5411\u91cf\u4f7f\u7528 AngleAxis, \u5b83\u5e95\u5c42\u4e0d\u76f4\u63a5\u662fMatrix\uff0c\u4f46\u8fd0\u7b97\u53ef\u4ee5\u5f53\u4f5c\u77e9\u9635\uff08\u56e0\u4e3a\u91cd\u8f7d\u4e86\u8fd0\u7b97\u7b26\uff09\n    Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) );     //\u6cbf Z \u8f74\u65cb\u8f6c 45 \u5ea6\n    cout .precision(3);\n    cout<<\"rotation matrix =\\n\"<<rotation_vector.matrix() <<endl;                //\u7528matrix()\u8f6c\u6362\u6210\u77e9\u9635\n    // \u4e5f\u53ef\u4ee5\u76f4\u63a5\u8d4b\u503c\n    rotation_matrix = rotation_vector.toRotationMatrix();\n    // \u7528 AngleAxis \u53ef\u4ee5\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Eigen::Vector3d v ( 1,0,0 );\n    Eigen::Vector3d v_rotated = rotation_vector * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n    // \u6216\u8005\u7528\u65cb\u8f6c\u77e9\u9635\n    v_rotated = rotation_matrix * v;\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n\n\n    //---------------------------------------------------------------------------\n    //  \u6b27\u62c9\u89d2\n    //----------------------------------------------------------------\n    //-- \u53ef\u4ee5\u5c06\u65cb\u8f6c\u77e9\u9635\u76f4\u63a5\u8f6c\u6362\u6210\u6b27\u62c9\u89d2\n    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles ( 2,1,0 ); // ZYX\u987a\u5e8f\uff0c\u5373roll pitch yaw\u987a\u5e8f\n    cout<<\"yaw pitch roll = \"<<euler_angles.transpose()<<endl;\n\n    // \u6b27\u6c0f\u53d8\u6362\u77e9\u9635\u4f7f\u7528 Eigen::Isometry\n    Eigen::Isometry3d T=Eigen::Isometry3d::Identity();                // \u867d\u7136\u79f0\u4e3a3d\uff0c\u5b9e\u8d28\u4e0a\u662f4\uff0a4\u7684\u77e9\u9635\n    T.rotate ( rotation_vector );                                     // \u6309\u7167rotation_vector\u8fdb\u884c\u65cb\u8f6c\n    T.pretranslate ( Eigen::Vector3d ( 1,3,4 ) );                     // \u628a\u5e73\u79fb\u5411\u91cf\u8bbe\u6210(1,3,4)\n    cout << \"Transform matrix = \\n\" << T.matrix() <<endl;\n\n    // \u7528\u53d8\u6362\u77e9\u9635\u8fdb\u884c\u5750\u6807\u53d8\u6362\n    Eigen::Vector3d v_transformed = T*v;                              // \u76f8\u5f53\u4e8eR*v+t\n    cout<<\"v tranformed = \"<<v_transformed.transpose()<<endl;\n\n    // \u5bf9\u4e8e\u4eff\u5c04\u548c\u5c04\u5f71\u53d8\u6362\uff0c\u4f7f\u7528 Eigen::Affine3d \u548c Eigen::Projective3d \u5373\u53ef\uff0c\u7565\n\n\n\n    //---------------------------------------------------------------------------\n    //  \u56db\u5143\u6570\n    //----------------------------------------------------------------\n    // \u53ef\u4ee5\u76f4\u63a5\u628aAngleAxis\u8d4b\u503c\u7ed9\u56db\u5143\u6570\uff0c\u53cd\u4e4b\u4ea6\u7136\n    Eigen::Quaterniond q = Eigen::Quaterniond ( rotation_vector );\n    cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;   // \u8bf7\u6ce8\u610fcoeffs\u7684\u987a\u5e8f\u662f(x,y,z,w),w\u4e3a\u5b9e\u90e8\uff0c\u524d\u4e09\u8005\u4e3a\u865a\u90e8\n    // \u4e5f\u53ef\u4ee5\u628a\u65cb\u8f6c\u77e9\u9635\u8d4b\u7ed9\u5b83\n    q = Eigen::Quaterniond ( rotation_matrix );\n    cout<<\"quaternion = \\n\"<<q.coeffs() <<endl;\n    // \u4f7f\u7528\u56db\u5143\u6570\u65cb\u8f6c\u4e00\u4e2a\u5411\u91cf\uff0c\u4f7f\u7528\u91cd\u8f7d\u7684\u4e58\u6cd5\u5373\u53ef\n    v_rotated = q*v; // \u6ce8\u610f\u6570\u5b66\u4e0a\u662fqvq^{-1}\n    cout<<\"(1,0,0) after rotation = \"<<v_rotated.transpose()<<endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "c92e15e6011444b62e2084bf8b7b9f2ce6012528", "size": 3642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useGeometry/eigenGeometry_test.cpp", "max_stars_repo_name": "HustRobot/VSLAM", "max_stars_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useGeometry/eigenGeometry_test.cpp", "max_issues_repo_name": "HustRobot/VSLAM", "max_issues_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useGeometry/eigenGeometry_test.cpp", "max_forks_repo_name": "HustRobot/VSLAM", "max_forks_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 36.7878787879, "max_line_length": 100, "alphanum_fraction": 0.4945085118, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6500118390651188}}
